text stringlengths 7 3.69M |
|---|
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import { Paper } from '../../Components/Paper';
import './home-view.scss';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import AddIcon from '@material-ui/icons/Add';
import Icon from '@material-ui/core/Icon';
import DeleteIcon from '@material-ui/icons/Delete';
import NavigationIcon from '@material-ui/icons/Navigation';
import { withRouter, Redirect } from 'react-router-dom';
export default class homePage extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.state = {
artist: "",
date: '',
ready: 0,
}};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
console.log('hi')
};
onSubmit = e => {
if(this.state.artist == '' || this.state.date == '') {
return
}
else {
this.setState({
ready: 1,
})
}
e.preventDefault();
}
render() {
const { classes } = this.props;
return (
<div className='main-container'>
<div className="main">
<div className='welcome'>
<div className='homemessage'> <message1 style={{fontSize:'40px'}}>Tokyo Music Search</message1> <br/> <message2 style={{fontSize:'25px'}}> Type in the name of an artist to see if they are performing in Tokyo.</message2> </div>
</div>
<div className='search'>
<div className="searchbar">
<form autoComplete="off">
<FormControl style={{height: '80px'}}>
<InputLabel htmlFor="month-simple">Month</InputLabel>
<Select
name='date'
value={this.state.date}
onChange={this.handleChange}
inputProps={{
name: 'date',
id: 'date-simple',
}}
>
<MenuItem value={0}>
<em>None</em>
</MenuItem>
<MenuItem value={'01'}>JAN</MenuItem>
<MenuItem value={'02'}>FEB</MenuItem>
<MenuItem value={'03'}>MAR</MenuItem>
<MenuItem value={'04'}>APR</MenuItem>
<MenuItem value={'05'}>MAY</MenuItem>
<MenuItem value={'06'}>JUN</MenuItem>
<MenuItem value={'07'}>JUL</MenuItem>
<MenuItem value={'08'}>AUG</MenuItem>
<MenuItem value={'09'}>SEP</MenuItem>
<MenuItem value={'10'}>OCT</MenuItem>
<MenuItem value={'11'}>NOV</MenuItem>
<MenuItem value={'12'}>DEC</MenuItem>
</Select>
</FormControl>
<TextField
name='artist'
id="with-placeholder"
label="Name of Artist"
placeholder="Utada Hikaru..."
onChange={this.handleChange}
style={{marginLeft: '50px', fontSize: '90px', width: '400px' }}
/>
<Button type='submit' onClick={this.onSubmit} variant="fab" color="secondary" aria-label="edit" >
<Icon>search_icon</Icon>
</Button>
</form>
</div>
</div>
</div>
{ this.state.ready > 0 && <Redirect to={{
pathname: '/results',
state: { artist: this.state.artist, date: this.state.date} }}/> }
</div>
)
}
} |
var winston = require('winston');
var Crawler = require('../../crawler.js').Crawler;
describe('Crawler._crawlPage method', function () {
'use strict';
var crawler;
var pageInfo;
var finishCallback;
beforeEach(function () {
crawler = new Crawler();
pageInfo = {
page: {
url: 'http://www.google.com',
type: 'text/html'
}
};
finishCallback = jasmine.createSpy('finishCallback');
spyOn(crawler, '_request');
spyOn(crawler, '_onResponse');
});
it('logs errors', function () {
spyOn(winston, 'error');
crawler._request.andCallFake(function (params, callback) {
callback(new Error('error message'));
});
crawler._crawlPage(pageInfo, finishCallback);
expect(winston.error).toHaveBeenCalledWith('Failed on: ' + pageInfo.page.url);
expect(winston.error).toHaveBeenCalledWith('error message');
});
describe('request', function () {
beforeEach(function () {
crawler.strictSSL = false;
crawler.timeout = 1000;
crawler.acceptCookies = true;
pageInfo.page.isExternal = true;
crawler.auth = { username: 'user', password: 'pass' };
crawler._crawlPage(pageInfo, function () {});
});
it('uses the pageInfo.page.url for the url', function () {
expect(crawler._request.calls[0].args[0].url).toBe('http://www.google.com');
});
it('uses the crawler.timeout for the timeout', function () {
expect(crawler._request.calls[0].args[0].timeout).toBe(1000);
});
it('uses the crawler.strictSSL for the strictSSL', function () {
expect(crawler._request.calls[0].args[0].strictSSL).toBe(false);
});
it('passes the pageInfo.page.isExternal property to the request', function () {
expect(crawler._request.calls[0].args[0].isExternal).toBe(true);
});
it('passes the crawler.auth property to the request', function () {
expect(crawler._request.calls[0].args[0].auth).toBe(crawler.auth);
});
it('executes _onResponse function in response callback', function () {
// Execute the callback
crawler._request.calls[0].args[1](null, 'arg2', 'arg3');
expect(crawler._onResponse).toHaveBeenCalledWith(pageInfo, null, 'arg2', 'arg3', jasmine.any(Function));
});
});
});
|
var hours = 1;
var minutes = 0;
var seconds = 0;
function showTime() {
var shown_hours = " ";
var shown_minutes = " ";
var shown_seconds = " ";
if (hours == 0) {
shown_hours = "00";
} else if (hours < 10 && hours.toString()[0] != "0") {
shown_hours = "0" + hours;
} else {
shown_hours = hours.toString();
}
if (minutes == 0) {
shown_minutes = "00";
} else if (minutes < 10 && minutes.toString()[0] != "0") {
shown_minutes = "0" + minutes;
} else {
shown_minutes = minutes.toString();
}
if (seconds == 0) {
shown_seconds = "00";
}
else if (seconds < 10 && seconds.toString()[0] != "0") {
shown_seconds = "0" + seconds;
} else {
shown_seconds = seconds.toString();
}
var time = shown_hours + ":" + shown_minutes + ":" + shown_seconds;
document.getElementById("clockDisplay").innerText = time;
}
function startCountdown() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
var spacebarToggle = false;
var redLedOn = false;
document.body.onkeyup = function(e) {
if (e.keyCode == 32) { //32 is keyCode for spacebar
spacebarToggle = !spacebarToggle; //start, pause, or resume the countdown
} else if (e.keyCode == 13) {
redLedOn = !redLedOn;
socket.emit("toggleLED", redLedOn);
}
}
var countdown = setInterval(function() {
if (spacebarToggle) {
if (seconds > 0) {
--seconds;
} else if (seconds == 0 && minutes > 0) {
seconds = 59;
--minutes;
} else if (seconds == 0 && minutes == 0 && hours > 0) {
seconds = 59;
minutes = 59;
--hours;
}
showTime();
}
}, 1000);
}
|
exports.emailTemplate = name => {
return `
<div>
<h1 style="display: block; margin: 0 auto; margin-top: 30px;font-size: 20px; text-align: center;font-family: Helvetica; color: rgb(80, 80, 90); font-weight: lighter;">Hey ${ name }!! We are so stoked you signed up to Course Camp! Course Camp is a great website to learn a skill, or teach others to learn a skill.
At Course Camp you can create highly interactive courses that will ensure success for the student.
You can add quizzes, picture quizzes, matching games, coding challenges, coding projects, and crunch challenges to
every video in every section. The possibilities are endless! </h1>
<a href="https://teamcoursecamp.com" style="color: white; text-decoration: none;">
<button style="display: block; cursor: pointer; margin: 0 auto; padding: 1rem; margin-top: 40px; border: none; font-size: 17px; font-family: Arial; font-weight: lighter; letter-spacing: .5px; color: white; border-radius: 6px; background: #9881B1">
Course Camp
</button>
</a>
</div>
`;
}; |
const Router = require('express')
const router = new Router()
const EmployeController = require('../controllers/employeController')
router.get('/', EmployeController.all)
module.exports = router |
const Clock = ({format}) => format ? format : <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">기록없음</span>;
const Duration = ({format}) => format ? <span className="px-2 inline-flex leading-5 text-xs text-gray-500">{format}</span> : '';
const Attendance = ({date, clockIn, clockOut, duration, bg, note}) => {
return (
<div className={`${bg} px-4 py-5 sm:grid sm:grid-cols-3 sm:gap-4 sm:px-6`}>
<dt className="text-sm leading-5 font-medium text-gray-500">
{date}
</dt>
<dd className="mt-1 text-sm leading-5 text-gray-900 sm:mt-0 sm:col-span-2">
<Clock format={clockIn}/> - <Clock format={clockOut}/> <Duration format={duration}/>
<p className="pt-1 text-xs text-gray-500">{note}</p>
</dd>
</div>
);
};
const Attendances = ({attendances}) => {
return attendances.map(({attendance_id, format, note}, i) => {
return (
<Attendance
key={attendance_id}
bg={i % 2 === 0 ? 'bg-gray-100' : 'bg-white'}
note={note}
{...format} />
);
});
}
export default Attendances;
|
/**
* Created by elie.
*/
/**
/**
* Generates one stacked histogram with auto-update and its legend inside the svg parameter which will have two of them.
* @param div {Object} D3 encapsulated parent div element.
* @param svg {Object} D3 encapsulated parent svg element, direct child of div parameter, which contains svgChild.
* @param svgChild {Object} D3 encapsulated svg element, child of the svg parameter, contains one graph.
* @param numSvg {Number} Used to differentiate the different graphs from top to bottom.
* @param divLegend {Object} D3 selection of the div which contains the legend's table of the two graphs.
* @param mydiv {String} The parent div id.
*/
function createChildSvgCurrent(div, svg, svgChild, numSvg, divLegend, mydiv){
var maxHeight = svg.margin.top/2 + svg.margin.zero/4 + svg.heightGraph;
svgChild.divtable = divLegend.append("div").classed("borderTable diagram",true).style("top", svg.margin.zero/2 + "px")
.style("position","relative");
svgChild.table = svgChild.divtable.append("table").classed("diagram font2 tableLegend", true).style("width", svg.tableWidth + "px")
.style("max-height", maxHeight + "px");
svgChild.values.sort(sortValuesCurrent);
var totalSumValues = [];
var x = 0;
var sum = 0;
var i = 0;
while (x < svg.xMax) {
while (i < svgChild.values.length && svgChild.values[i].x == x) {
sum += svgChild.values[i].height;
svgChild.values[i].y = sum;
i++;
}
totalSumValues.push(sum);
sum = 0;
x++;
}
svgChild.total = Math.max(1, d3.max(totalSumValues));
svgChild.x = d3.scaleLinear().range([0,svg.width]).domain([-0.625, svg.xMax - 0.375]);
svgChild.y = d3.scaleLinear().range([svg.heightGraph,0]).domain([0,svgChild.total * 1.1]);
svgChild.chartBackground = svgChild.append("g");
svgChild.backgroundRect = svgChild.chartBackground.append("rect").attr("y",0).attr("x",0).attr("height",svg.heightGraph)
.attr("width",svg.width).attr("fill",numSvg === 0?"#fff":"#e6e6e6");
svgChild.text = svgChild.chartBackground.append("text").classed("bckgr-txt", true)
.style("fill",numSvg === 0?"#e6e6e6":"#fff")
.text(numSvg === 0?"Ingress":"Egress");
svgChild.text.attr("transform", "translate(" + (svg.width / 2) + "," + (svg.heightGraph/8 +
parseFloat(getComputedStyle(svgChild.text.node()).fontSize)) + ")");
//Here, the grid, after the text
svgChild.grid = svgChild.chartBackground.append("g").classed("grid", true);
svgChild.newX = d3.scaleLinear().range(svgChild.x.range()).domain(svgChild.x.domain());
svgChild.newY = d3.scaleLinear().range(svgChild.y.range()).domain(svgChild.y.domain());
svgChild.chart = svgChild.append("g");
svgChild.selec = svgChild.append("g").append("rect").attr("class", "rectSelec");
var dataWidth = 0.75*(svgChild.newX(svgChild.newX.domain()[0] + 1) - svgChild.newX.range()[0]);
svgChild.selection = svgChild.chart.selectAll(".data")
.data(svgChild.values)
.enter().append("rect")
.classed("data", true)
.attr("fill", function (d) {
return svg.colorMap.get(d.item);
})
.attr("stroke", "#000000")
.attr("x",function(d){return svgChild.newX(d.x - 0.375);})
.attr("y", function(d){return svgChild.newY(d.y);})
.attr("height", function(d){return svg.heightGraph - svgChild.newY(d.height);})
.attr("width", dataWidth);
svgChild.trSelec = svgChild.table.selectAll("tr").data(svgChild.sumArray).enter().append("tr");
var blink = blinkCreate(svg.colorMap);
svgChild.activeItem = null;
function activationElems(d) {
if (svg.popup.pieChart !== null) {
return;
}
svgChild.activeItem = d.item;
function testitem(data) {
return d.item == data.item;
}
svgChild.trSelec.filter(testitem).classed("outlined", true);
svgChild.selection.filter(testitem).each(blink);
}
function activationElemsAutoScroll(d) {
if (svg.popup.pieChart !== null) {
return;
}
svgChild.activeItem = d.item;
function testitem(data) {
return d.item == data.item;
}
var elem = svgChild.trSelec.filter(testitem).classed("outlined", true);
scrollToElementTableTransition(elem,svgChild.table);
svgChild.selection.filter(testitem).each(blink);
}
function activationElemsAutoScrollPopup(d) {
svgChild.activeItem = d.item;
function testitem(data) {
return d.item == data.item;
}
var elem = svgChild.trSelec.filter(testitem).classed("outlined", true);
scrollToElementTableTransition(elem,svgChild.table);
}
function deactivationElems() {
if (svgChild.activeItem == null || svg.popup.pieChart !== null) {
return;
}
function testitem(data) {
return data.item == svgChild.activeItem;
}
svgChild.trSelec.filter(testitem).classed("outlined", false);
svgChild.selection.filter(testitem).interrupt().attr("stroke", "#000000").attr("fill", svg.colorMap.get(svgChild.activeItem));
svgChild.activeItem = null;
}
svgChild.deactivationElems = deactivationElems;
svgChild.activationElemsAutoScrollPopup = activationElemsAutoScrollPopup;
svgChild.activationElemsAutoScroll = activationElemsAutoScroll;
svgChild.activationElems = activationElems;
svgChild.selection.on("mouseover", activationElemsAutoScroll).on("mouseout", deactivationElems);
svgChild.axisx = svg.append("g")
.attr("class", "axisGraph")
.attr('transform', 'translate(' + [svg.margin.left, svg.margin.top + svg.heightGraph + numSvg * (svg.heightGraph + svg.margin.zero) - 0.5] + ")");
svgChild.axisx.call(d3.axisBottom(svgChild.x));
svgChild.step = svg.step;
svgChild.timeMin = svg.timeMin;
legendAxisX(svgChild);
yAxe2HistoCreation(svg, svgChild, numSvg);
optionalAxes2HistoCreation(svg,svgChild,numSvg);
gridHisto2Graph(svg, svgChild);
/*
addPopup2Histo(selection,div,svg, svgChild, numSvg, function(data){
desactivationElems();
activationElemsAutoScrollPopup(data);},
desactivationElems);
*/
//Legend creation
//(not svgChild, ok)
tableLegendTitle(svg,svgChild.trSelec);
svgChild.trSelec.append("td").append("div").classed("lgd", true).style("background-color", function (d) {
return svg.colorMap.get(d.item);
});
svgChild.trSelec.append("td").text(function (d) {
return d.display;
});
svgChild.trSelec.on("mouseover", activationElems).on("mouseout", deactivationElems);
svgChild.divtable.style("margin-bottom",maxHeight - parseInt(svgChild.table.style("height"),10) + "px");
addZoom2Histo(svg, svgChild, update2HistoStack);
hideShowValuesCurrent2Histo(svg, svgChild);
/*
addPopup2Histo(selection, div, svg , svgChild, numSvg, function(data){
desactivationElems();
activationElemsAutoScrollPopup(data);},
desactivationElems)
*/
}
/**
*
* @param svg
* @param svgChild
*/
function hideShowValuesCurrent2Histo(svg, svgChild){
var duration = 800;
svgChild.hiddenValues = [];
svgChild.mapPercentDisplay = new Map();
svgChild.trSelec.each(function(d){
svgChild.mapPercentDisplay.set(d.item,{percentDisplay:1});
});
svgChild.onClick = function(d){
var clickedRow = d3.select(this);
var index = svgChild.hiddenValues.indexOf(d.item);
if(index === -1){
//hide the data
svgChild.hiddenValues.push(d.item);
clickedRow.classed("strikedRow",true);
}else{
//show the data
svgChild.hiddenValues.splice(index,1);
clickedRow.classed("strikedRow",false);
}
createTransitionSimpleCurrent2Histo(svg,svgChild, duration);
};
svgChild.onContextMenu = function(d){
d3.event.preventDefault();
var clickedRow = d3.select(this);
var index = svgChild.hiddenValues.indexOf(d.item);
if ((index !== -1) || (svgChild.trSelec.size() - 1 !== svgChild.hiddenValues.length )) {
//Hide all data except this one
svgChild.hiddenValues = [];
svgChild.mapPercentDisplay.forEach(function(value, key){
svgChild.hiddenValues.push(key);
});
svgChild.hiddenValues.splice(svgChild.hiddenValues.indexOf(d.item), 1);
svgChild.trSelec.classed("strikedRow",true);
clickedRow.classed("strikedRow",false);
}else{
//index === -1 && hiddenValues.length == trSelec.size() -1
// ->show all data.
svgChild.hiddenValues = [];
svgChild.trSelec.classed("strikedRow", false);
}
createTransitionSimpleCurrent2Histo(svg,svgChild, duration);
};
svgChild.trSelec.on("click", svgChild.onClick).on("contextmenu",svgChild.onContextMenu);
}
/**
*
* @param svg
* @param svgChild
* @param duration
*/
function createTransitionSimpleCurrent2Histo(svg, svgChild, duration){
svgChild.interrupt("hideshow");
svgChild.transition("hideshow").duration(duration)
.tween("",function(){
var arrayUpdate = [];
svgChild.mapPercentDisplay.forEach(function(value, key){
var coef = (svgChild.hiddenValues.indexOf(key) === -1?1:0) - value.percentDisplay;
if(coef !== 0){
arrayUpdate.push([value,value.percentDisplay,coef]);
}
});
return function(t){
arrayUpdate.forEach(function(elem){
elem[0].percentDisplay = elem[1] + t * elem[2];
});
transitionRefreshSimpleCurrent2Histo(svg, svgChild);
}
})
.on("end",function(){
svgChild.mapPercentDisplay.forEach(function(value, key){
value.percentDisplay = (svgChild.hiddenValues.indexOf(key) === -1?1:0);
});
transitionRefreshSimpleCurrent2Histo(svg,svgChild);
});
}
function transitionRefreshSimpleCurrent2Histo(svg, svgChild){
var i, currentX;
var sum, elemValues, currentPercent;
var mapDisplay = svgChild.mapPercentDisplay;
var valuesSortAlphabet = svgChild.valuesSCAlphabetSort;
var valuesUsualSort = svgChild.values;
var valuesLength = valuesUsualSort.length;
var totalSum = [], currentItem = null;
//height actualization
for (i = 0; i < valuesLength; i++) {
elemValues = valuesSortAlphabet[i];
if (elemValues.item !== currentItem) {
currentItem = elemValues.item;
currentPercent = mapDisplay.get(currentItem).percentDisplay;
}
elemValues.height = elemValues.heightRef * currentPercent;
}
currentX = null;
sum = 0;
for (i = 0; i < valuesLength; i++) {
elemValues = valuesUsualSort[i];
if (currentX !== elemValues.x) {
currentX = elemValues.x;
totalSum.push(sum);
sum = 0;
}
sum += elemValues.height;
elemValues.y = sum;
}
totalSum.push(sum);
svgChild.total = Math.max(1,d3.max(totalSum));
updateScales2HistoCurrent(svg,svgChild);
update2HistoStack(svg, svgChild);
}
function updateScales2HistoCurrent(svg, svgChild){
var actTranslate1 = -svgChild.transform.y/(svgChild.scaley*svgChild.transform.k);
svgChild.y.domain([0,svgChild.total*1.1]);
svgChild.newY.domain([svgChild.y.invert(actTranslate1 + svg.heightGraph/(svgChild.transform.k*svgChild.scaley)), svgChild.y.invert(actTranslate1)]);
}
function onAutoUpdate(svg, svgChild, valuesNew, gapMinute, sumMapUpdate){
valuesNew.sort(sortValuesCurrent);
var totalUpdate = [];
var x = 60;
var xMax = 60 + gapMinute;
var sum = 0;
var i = 0;
while (x < xMax) {
while (i < valuesNew.length && valuesNew[i].x === x) {
sum += valuesNew[i].height;
valuesNew[i].y = sum;
i++;
}
totalUpdate.push(sum);
sum = 0;
x++;
}
svgChild.total = Math.max(svgChild.total,d3.max(totalUpdate));
removeValuesOnUpdate(svg,svgChild.values,sumMapUpdate,gapMinute);
sumMapUpdate.forEach(function(value,key){
if(!svg.sumMap.has(key)){
svg.sumMap.set(key,{sum:value.sum, display:value.display})
}
});
svgChild.selection = svgChild.chart.selectAll(".data");
svgChild.values = svgChild.selection.data();
svgChild.values = svgChild.values.concat(valuesNew);
svgChild.selection = svgChild.chart.selectAll(".data")
.data(svgChild.values);
var selecEnter = svgChild.selection.enter()
.append("rect")
.classed("data", true)
.attr("fill", function (d) {
return svg.colorMap.get(d.item);
})
.attr("stroke", "#000000");
svgChild.selection = selecEnter.merge(svgChild.selection);
svgChild.values.sort(sortValuesCurrent);
svgChild.valuesSCAlphabetSort = svgChild.values.concat();
svgChild.valuesSCAlphabetSort.sort(sortAlphabetItemOnly);
selecEnter.on("mouseover", svgChild.activationElemsAutoScroll).on("mouseout", svgChild.deactivationElems);
svgChild.selecEnter = selecEnter;
updateScales2HistoCurrent(svg, svgChild);
}
/**
*
* @param svg
* @param svgChild
* @param sumMapUpdate
*/
function onEndAutoUpdate(svg,svgChild, sumMapUpdate){
createTooltipHistoCurrent(svg,svgChild.selecEnter,svg.sumMap);
var maxTotal = 1;
svgChild.chart.selectAll(".data").each(function(d){
d.x = Math.round(d.x);
if(d.x < 0){
this.remove();
}else{
maxTotal = Math.max(maxTotal,d.y);
}
});
svgChild.total = maxTotal;
svgChild.selection = svgChild.chart.selectAll(".data");
svgChild.values = svgChild.selection.data();
svgChild.values.sort(sortValuesCurrent);
svgChild.valuesSCAlphabetSort = svgChild.values.concat();
svgChild.valuesSCAlphabetSort.sort(sortAlphabetItemOnly);
updateSumArray(svgChild.sumArray, sumMapUpdate,svgChild.hiddenValues,svgChild.mapPercentDisplay);
svgChild.sumArray.sort(sortAlphabet);
svgChild.trSelec = svgChild.table.selectAll("tr").data(svgChild.sumArray);
svgChild.trSelec.classed("strikedRow",function(d){return svgChild.hiddenValues.indexOf(d.item) !== -1; });
svgChild.trSelec.select("div").style("background-color", function (d) {
return svg.colorMap.get(d.item);
});
svgChild.trSelec.select("td:nth-of-type(2)").text(function (d) {
return d.display;
});
var trselecEnter = svgChild.trSelec.enter().append("tr")
.classed("strikedRow",function(d){return svgChild.hiddenValues.indexOf(d.item) !== -1; });
trselecEnter.append("td").append("div").classed("lgd", true).style("background-color", function (d) {
return svg.colorMap.get(d.item);
});
trselecEnter.append("td").text(function (d) {
return d.display;
});
trselecEnter.on("click",svgChild.onClick).on("contextmenu", svgChild.onContextMenu);
svgChild.trSelec.exit().remove();
svgChild.trSelec = svgChild.table.selectAll("tr");
svgChild.trSelec.on("mouseover",svgChild.activationElems).on("mouseout", svgChild.deactivationElems);
tableLegendTitle(svg, svgChild.trSelec);
updateScales2HistoCurrent(svg, svgChild);
update2HistoStack(svg, svgChild);
} |
import React from 'react';
import styled from 'styled-components';
const MainBox = styled.div`
width: 100vw;
height: 100vh;
margin: 0;
padding-top: 5rem;
`
const PageHeader = styled.p`
border: 1px solid red;
`
const AboutPage =()=> {
return(
<MainBox>
<PageHeader>About Us</PageHeader>
</MainBox>
)
};
export default AboutPage; |
// NOTE: change repo.name to repo.folderName in the cloc command to test the error state
//////////// IMPORTS ////////////
const { exec } = require('child_process'),
Promise = require('bluebird'),
config = require('@config'),
Log = require('@log');
//////////// PRIVATE ////////////
function convertRepoToClocFile(ctrl) {
return new Promise((resolve, reject) => {
Log(2, '5. Converting Repo To Cloc File');
let cd = 'cd ' + config.paths.repos + ctrl.folderName + '; ',
cloc = 'cloc ' + ctrl.repo.name +
' --csv --by-file ' +
`--ignored=${config.cloc.ignoredFile} ` +
`--report-file=${config.cloc.dataFile}`;
ctrl.resp.update('\n>> ' + cd + cloc);
let proc = exec(cd + cloc, (err) => {
if (err)
reject(new Error(err));
else
resolve(ctrl);
});
proc.stdout.on('data', ctrl.resp.update);
proc.stderr.on('data', ctrl.resp.update);
});
}
//////////// EXPORTS ////////////
module.exports = convertRepoToClocFile;
|
/**
* Module
*
* Description
*/
(function(){
var app = angular.module('app.liga');
app.factory('ligaResource', ['', function(){
return function name(){};
}])
})(); |
const View = () => {
var is_loading = false;
var current_level = 0;
var view_data = {};
setInterval(onUpdate, 1000);
function onUpdate(key) {
if(current_level === 0 && !is_loading){
init();
}
}
const get = key => {
return new Promise(function (resolve, reject) {
chrome.storage.local.get(key, function (obj) {
if (Array.isArray(key)) {
resolve(obj);
} else if(key === null){
resolve(obj);
} else {
var val = obj[key];
resolve(val);
}
});
})
}
const getTotalRequests = data => {
var c = 0;
for (var tld in data) {
var obj = data[tld];
c += obj['count'];
}
return c;
}
const drawDomainView = (all_data, data, level) => {
var total = getTotalRequests(data);
var el = document.getElementById('base');
var divs = [];
var eids = [];
for (var k = 0; k < all_data.length; k++) {
var d = all_data[k];
var percent = d['count'] / total;
var rpercent = d['count'] / (1.2 * all_data[0]['count']);
var fcolor, color;
if (percent > 0.2) {
fcolor = 'black';
color = "#FA6767";
} else if (percent > 0.1) {
color = '#ffe26c';
fcolor = 'black';
} else if (percent > 0.05) {
color = '#00cc00';
fcolor = 'black';
} else {
color = 'rgb(34, 126, 121)';
fcolor = 'black';
}
var name = d['name'];
var eid = 'tld_' + name;
eids.push(eid);
var right = 400 * (1.0 - rpercent);
var style = 'background-color:' + color + ';color:' + fcolor + ';right:' + right + 'px;' + 'margin-top:5px;' + 'border-radius:5px';
var html = "<div class='domain' id='" + eid + "'>";
percent *= 100;
name = name + ' (' + d['count'] + ')';
html += "<div class='domain-name' style='" + style + "'> " + name + "</div>";
html += "<div class='domain-amount'>" + percent.toFixed(2) + "%</div>";
html += '</div>';
divs.push(html);
}
var html = '<p> Below is a list of domains. Click any of them to get more information.</p>';
if(divs.length > 0){
if(level !== 0){
html += "<button id='backButton'>Back</button>";
}else{
html += "<button id='clearButton'>Clear</button>";
html += "<button style= float:right id='downloadButton'>Download</button>";
}
html += divs.join('');
}else{
html += "<p>Processing data...</p>"
}
el.innerHTML = html;
return eids;
}
const onClickDomain = level => {
return async function (e){
try{
var target = e.target;
if(!target.id){
target = target.parentNode;
}
var id = target.id;
if(id.indexOf('tld_') !== -1){
id = id.replace('tld_', '');
var obj = await get(id);
var info = JSON.parse(obj);
var children = info['children'];
if(children.length == 0){
await addRequestView(info,id, level + 1);
}else{
await addInitView(children, level + 1);
}
}
}catch(err){
throw err;
}
}
}
const addRequestView = async (info, top_name, level) => {
try{
current_level = level;
var sv = [];
var values = info['values'];
for(var n = 0; n < values.length; n++){
sv.push(values[n].toString());
}
var requests = await get(sv);
var divs = [];
var rdiv = '<h2>' + top_name + '</h2>';
rdiv += "<ul>";
for(var r = values.length - 1; r >= 0; r--){
var val = values[r].toString();
if(requests.hasOwnProperty(val)){
var request = requests[val];
if(!request){
continue;
}
var timestamp = false;
var keys = Object.keys(request);
if(keys.length === 0){
continue;
}
rdiv += '<li>';
var div = '<ul>';
for(var key in request){
var idiv = '<li>';
idiv += "<div class='title'>"+ key +"</div>"
var data = request[key];
for(var k = 0; k < data.length; k++){
var d = JSON.parse(data[k]);
if(!timestamp){
var ts = new Date(d['timeStamp']);
rdiv += "<div class='title'>Web Request on " + ts.toLocaleString() +"</div>"
timestamp = true;
}
var keys = Object.keys(d).sort();
idiv += '<ul>'
for(var n = 0; n < keys.length; n++){
var key = keys[n];
var id = d[key];
if(Array.isArray(id)){
idiv += "<li><span class='name'>" + key + "</span><ul>";
for(var p = 0; p < id.length; p++){
var iid = id[p];
if(typeof iid === 'string'){
idiv += '<li>' + id[p] + '</li>';
}else{
if(iid.hasOwnProperty('name') && iid.hasOwnProperty('value')){
idiv += "<li><span class='name'>" + iid['name'] + " : </span><span>" + iid['value'] + "</span></li>";
}
}
}
idiv += "</ul></li>";
}else if(typeof id === 'object'){
}else{
idiv += "<li><span class='name'>" + key + " : </span><span>" + id + "</span></li>";
}
}
idiv += '</ul>'
}
idiv += "</li>";
div += idiv;
}
div += '</ul>';
rdiv += div;
rdiv += '</li>';
}
}
rdiv += '</ul>';
divs.push(rdiv);
var el = document.getElementById('base');
if(el){
var html = '<p> Below is the list of 200 requests</p>';
html += "<button id='backButton'>Back</button>";
html += divs.join('');
el.innerHTML = html;
}
var el = document.getElementById('backButton');
if(el){
el.addEventListener('click', onBackButton(level));
}
}catch(err){
chrome.extension.getBackgroundPage().console.log(err);
}
}
const onBackButton = level => {
return async function(e){
try{
var obj = view_data[level - 1];
_addInitViewToDOM(obj.all_data, obj.data, level -1);
}catch(err){
throw err;
}
}
}
const onClearButton = () => {
chrome.storage.local.clear();
}
const _getDownloadName = () => {
var d = new Date();
return d.toISOString();
}
const onDownloadButton = async () => {
try{
var data = await get(null);
chrome.extension.getBackgroundPage().console.log(data)
var download_name = _getDownloadName() + '.json';
var download_data =JSON.stringify(data, null, 2);
var anchor = document.createElement('a');
var dataBlob = new Blob([download_data], {type: "application/json"});
var data_url = window.URL.createObjectURL(dataBlob);
anchor.setAttribute('href', data_url);
anchor.setAttribute('download', download_name);
anchor.click();
}catch(err){
chrome.extension.getBackgroundPage().console.log(JSON.stringify(err));
throw err;
}
}
const addInitView = async (tlds, level) => {
try {
current_level = level;
var all_data = [];
var data = {};
var info = await get(tlds);
for (var k = 0; k < tlds.length; k++) {
var tld = tlds[k];
var val = info[tld];
if(val){
var d = JSON.parse(val);
d['name'] = tld;
data[tld] = d;
all_data.push(d);
}
}
all_data.sort( (a, b) =>
b['count'] - a['count']
);
view_data[level] = {'all_data':all_data, 'data':data};
_addInitViewToDOM(all_data, data, level);
} catch (err) {
chrome.extension.getBackgroundPage().console.log(JSON.stringify(err));
throw err;
}
}
const _addInitViewToDOM = (all_data, data, level) => {
var eids = drawDomainView(all_data, data, level);
for(var k = 0; k < eids.length; k++){
var eid = eids[k];
var el = document.getElementById(eid);
if(el){
el.addEventListener('click', onClickDomain(level));
}
}
var el = document.getElementById('backButton');
if(el){
el.addEventListener('click', onBackButton(level));
}
el = document.getElementById('clearButton');
if(el){
el.addEventListener('click', onClearButton);
}
el = document.getElementById('downloadButton');
if(el){
el.addEventListener('click', onDownloadButton);
}
}
const init = async () => {
try {
is_loading = true;
var tld_data = await get('tlds');
var tlds = [];
if(tld_data){
tlds = JSON.parse(tld_data);
}
await addInitView(tlds, 0);
is_loading = false;
} catch (err) {
chrome.extension.getBackgroundPage().console.log(err);
throw err;
}
}
return {
init: init
}
}
View()
document.addEventListener('DOMContentLoaded', View.init); |
/**
* Copyright 2015 Google 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.
*/
templatesLoader.register('FormAjax', '/src/custom-form-ajax/snippets/form-ajax.html');
templatesLoader.register('FormAjaxHtml5', '/src/custom-form-ajax/snippets/form-ajax-html5.html');
describe('CustomFormAjax', function () {
var defTout = 250;
it('should be globally available', function () {
expect(CustomFormAjax).to.be.a('function');
});
it('should upgrade successfully', function () {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
componentHandler.upgradeElements(el);
var form = el.querySelector('.custom-js-form-ajax');
expect(form.getAttribute('data-upgraded')).to.be.equal(',CustomFormAjax');
componentHandler.downgradeElementRecursive(el);
expect(form.getAttribute('data-upgraded')).to.be.equal('');
el.remove();
});
it('should emit pre-submit event', function () {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
componentHandler.upgradeElements(el);
var form = el.querySelector('.custom-js-form-ajax');
var bt = el.querySelector('button');
var cherry = window.cherry;
var preSubmmitted = false;
cherry.once(form, 'pre-submit', function () {
preSubmmitted = true;
});
bt.click();
expect(preSubmmitted).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
});
it('should emit post-submit event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
componentHandler.upgradeElements(el);
var form = el.querySelector('.custom-js-form-ajax');
var bt = el.querySelector('button');
var cherry = window.cherry;
var postSubmmitted = false;
cherry.once(form, 'post-submit', function () {
postSubmmitted = true;
});
bt.click();
expect(postSubmmitted).to.be.equal(false);
setTimeout(function() {
expect(postSubmmitted).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit validation-success event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
componentHandler.upgradeElements(el);
var form = el.querySelector('.custom-js-form-ajax');
var bt = el.querySelector('button');
var cherry = window.cherry;
var postSubmmitted = false;
cherry.once(form, 'validation-success', function () {
postSubmmitted = true;
});
bt.click();
expect(postSubmmitted).to.be.equal(false);
setTimeout(function() {
expect(postSubmmitted).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit validation-fail event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-form_failure.json');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var cherry = window.cherry;
var postSubmmitted = false;
cherry.once(form, 'validation-fail', function () {
postSubmmitted = true;
});
bt.click();
expect(postSubmmitted).to.be.equal(false);
setTimeout(function() {
expect(postSubmmitted).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit success events in right order', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
var form = el.querySelector('.custom-js-form-ajax');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var cherry = window.cherry;
var events = [];
cherry.once(form, 'pre-submit', function(ev) {
events.push(ev.type);
});
cherry.once(form, 'post-submit', function(ev) {
events.push(ev.type);
});
cherry.once(form, 'validation-success', function(ev) {
events.push(ev.type);
});
bt.click();
setTimeout(function() {
expect(events).to.be.eql(['pre-submit', 'post-submit', 'validation-success']);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit failure events in right order', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-form_failure.json');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var cherry = window.cherry;
var events = [];
cherry.once(form, 'pre-submit', function(ev) {
events.push(ev.type);
});
cherry.once(form, 'post-submit', function(ev) {
events.push(ev.type);
});
cherry.once(form, 'validation-fail', function(ev) {
events.push(ev.type);
});
bt.click();
setTimeout(function() {
expect(events).to.be.eql(['pre-submit', 'post-submit', 'validation-fail']);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should display form failure error', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-form_failure.json');
var text = el.querySelector('.custom-form__errorfailure');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
bt.click();
setTimeout(function() {
expect(text.innerHTML).to.be.equal('Something went wrong');
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should display field failure errors', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-field_errors.json');
var errfields = el.querySelectorAll('.mdl-textfield__error');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
bt.click();
setTimeout(function() {
for( var i = 0; i < errfields.length; i++) {
expect(errfields[i].innerHTML).to.be.equal('Anyway its wrong for the demo!');
expect(errfields[i].parentNode.classList.contains('is-invalid')).to.be.equal(true);
}
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should disable buttons while processing the form', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjax');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-field_errors.json');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
expect(bt.getAttribute('disabled')).to.be.equal(null);
bt.click();
expect(bt.getAttribute('disabled')).to.be.equal('disabled');
setTimeout(function() {
expect(bt.getAttribute('disabled')).to.be.equal(null);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should handle html5 buttons', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-field_errors.json');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
expect(bt.getAttribute('disabled')).to.be.equal(null);
bt.click();
expect(bt.getAttribute('disabled')).to.be.equal('disabled');
setTimeout(function() {
expect(bt.getAttribute('disabled')).to.be.equal(null);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should update submit options for the clicked html5 button', function () {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-field_errors.json');
var bt = el.querySelector('button');
bt.setAttribute('formmethod', 'GET');
bt.setAttribute('formaction', '/somewhere');
bt.setAttribute('formenctype', 'encoded');
componentHandler.upgradeElements(el);
var options = form['CustomFormAjax'].getSubmitOptions(bt);
expect(options.method).to.be.equal('GET');
expect(options.url).to.be.equal('/somewhere');
expect(options.headers['content-type']).to.be.equal('encoded');
componentHandler.downgradeElementRecursive(el);
el.remove();
});
it('should emit pre-notify event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var div = document.createElement('div');
div.id = 'prenotifier';
el.appendChild(div);
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('pre-notify', '#'+div.id);
form.setAttribute('pre-notify-message', 'message');
form.setAttribute('pre-notify-action', 'action');
form.setAttribute('pre-notify-timeout', '1500');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var notified = false;
var ts = Date.now();
div.addEventListener('notify', function(ev) {
var notification = ev.notification;
notified = true;
expect(notification.targetElement).to.be.equal(form);
expect(notification.inputElement).to.be.equal(bt);
expect(notification.sourceEvent).to.be.equal('pre-submit');
expect(notification.notificationType).to.be.equal('info');
expect(notification.message).to.be.equal('message');
expect(notification.actionText).to.be.equal('action');
expect(notification.timeout).to.be.equal(1500);
})
bt.click();
setTimeout(function() {
expect(notified).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit post-notify success event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var div = document.createElement('div');
div.id = 'prenotifier';
el.appendChild(div);
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('post-notify', '#'+div.id);
form.setAttribute('post-notify-success', 'message');
form.setAttribute('post-notify-action', 'action');
form.setAttribute('post-notify-success-timeout', '1500');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var notified = false;
var ts = Date.now();
div.addEventListener('notify', function(ev) {
var notification = ev.notification;
notified = true;
expect(notification.targetElement).to.be.equal(form);
expect(notification.inputElement).to.be.equal(bt);
expect(notification.sourceEvent).to.be.equal('post-submit');
expect(notification.notificationType).to.be.equal('success');
expect(notification.message).to.be.equal('message');
expect(notification.actionText).to.be.equal('action');
expect(notification.timeout).to.be.equal(1500);
})
bt.click();
setTimeout(function() {
expect(notified).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit post-notify field errors event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var div = document.createElement('div');
div.id = 'prenotifier';
el.appendChild(div);
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-field_errors.json');
form.setAttribute('post-notify', '#'+div.id);
form.setAttribute('post-notify-failure', 'message');
form.setAttribute('post-notify-action', 'action');
form.setAttribute('post-notify-failure-timeout', '1500');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var notified = false;
var ts = Date.now();
div.addEventListener('notify', function(ev) {
var notification = ev.notification;
notified = true;
expect(notification.targetElement).to.be.equal(form);
expect(notification.inputElement).to.be.equal(bt);
expect(notification.sourceEvent).to.be.equal('post-submit');
expect(notification.notificationType).to.be.equal('warn');
expect(notification.message).to.be.equal('message');
expect(notification.actionText).to.be.equal('action');
expect(notification.timeout).to.be.equal(1500);
})
bt.click();
setTimeout(function() {
expect(notified).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit post-notify form failure event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var div = document.createElement('div');
div.id = 'prenotifier';
el.appendChild(div);
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', 'ajax/form-ajax-form_failure.json');
form.setAttribute('post-notify', '#'+div.id);
form.setAttribute('post-notify-failure', 'message');
form.setAttribute('post-notify-action', 'action');
form.setAttribute('post-notify-failure-timeout', '1500');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var notified = false;
var ts = Date.now();
div.addEventListener('notify', function(ev) {
var notification = ev.notification;
notified = true;
expect(notification.targetElement).to.be.equal(form);
expect(notification.inputElement).to.be.equal(bt);
expect(notification.sourceEvent).to.be.equal('post-submit');
expect(notification.notificationType).to.be.equal('severe');
expect(notification.message).to.be.equal('Something went wrong');
expect(notification.actionText).to.be.equal('action');
expect(notification.timeout).to.be.equal(1500);
})
bt.click();
setTimeout(function() {
expect(notified).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit post-notify crtical event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var div = document.createElement('div');
div.id = 'prenotifier';
el.appendChild(div);
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', '/nop');
form.setAttribute('post-notify', '#'+div.id);
form.setAttribute('post-notify-failure', 'message');
form.setAttribute('post-notify-critical', 'critical message');
form.setAttribute('post-notify-action', 'action');
form.setAttribute('post-notify-failure-timeout', '1500');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var notified = false;
var ts = Date.now();
div.addEventListener('notify', function(ev) {
var notification = ev.notification;
notified = true;
expect(notification.targetElement).to.be.equal(form);
expect(notification.inputElement).to.be.equal(bt);
expect(notification.sourceEvent).to.be.equal('post-submit');
expect(notification.notificationType).to.be.equal('critical');
expect(notification.message).to.be.equal('critical message');
expect(notification.actionText).to.be.equal('action');
expect(notification.timeout).to.be.equal(1500);
})
bt.click();
setTimeout(function() {
expect(notified).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it('should emit post-submit crtical event', function (done) {
var el = document.createElement('div');
document.body.appendChild(el);
el.innerHTML = templatesLoader.get('FormAjaxHtml5');
var form = el.querySelector('.custom-js-form-ajax');
form.setAttribute('action', '/nop');
var bt = el.querySelector('button');
componentHandler.upgradeElements(el);
var critical = false;
form.addEventListener('post-submit', function(ev) {
critical = ev.CriticalFailure;
})
bt.click();
setTimeout(function() {
expect(critical).to.be.equal(true);
componentHandler.downgradeElementRecursive(el);
el.remove();
done();
}, defTout);
});
it.skip('should grab form values', function () {
// ensure getSubmitData works well
});
});
|
/*
* productUPCGeneratorApi.js
*
* Copyright (c) 2017 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* API to support display product updates task details.
*
* @author vn86116
* @since 2.15.0
*/
(function () {
angular.module('productMaintenanceUiApp').factory('CaseUPCGeneratorApi', caseUPCGeneratorApi);
caseUPCGeneratorApi.$inject = ['urlBase', '$resource'];
/**
* Constructs the API to call the backend functions related to task summary.
*
* @param urlBase The Base URL for the back-end.
* @param $resource Angular $resource factory used to create the API.
* @returns {*}
*/
function caseUPCGeneratorApi(urlBase, $resource) {
return $resource(null, null, {
getUpcGenerateForCaseUpc: {
method: 'GET',
url: urlBase + '/pm/utilities/caseUPCGenerator/getUpcGenerateForCaseUpc',
isArray: false
}
});
}
})();
|
import { expect } from 'chai'
import { call, put, select } from 'redux-saga/effects'
import { clearOnDemand, insertIdsToTheFeed } from '../../src/reducers/ui/updates-feed'
import { findPlaceToInsertIds, moveOnDemandToTheFeed } from '../../src/sagas/move-on-demand-evidences-to-the-feed'
import * as updatesFeedSelector from '../../src/selectors/ui/updates-feed'
import * as evidencesSelector from '../../src/selectors/entities/evidences'
describe('sagas / move-on-demand-evidences-to-the-feed', () => {
it('should move on demand ids to the feed', () => {
const gen = moveOnDemandToTheFeed()
const sortBy = ['when', 'estimation']
const ids = [2, 4, 6]
const indexes = ['id-1', 'id-2', 'id-3']
expect(gen.next().value).to.be.deep.equal(
call(findPlaceToInsertIds, sortBy)
)
expect(gen.next({ ids, indexes }).value).to.be.deep.equal(
put(insertIdsToTheFeed({
indexes, ids
}))
)
expect(gen.next().value).to.be.deep.equal(
put(clearOnDemand())
)
})
it('should find place to insert ids', () => {
const ids = ['2', '4', '6']
const sortedIds = ['1', '3', '5', '7']
const byIds = {
'1': { value: 7000 },
'2': { value: 6000 },
'3': { value: 5000 },
'4': { value: 4000 },
'5': { value: 3000 },
'6': { value: 2000 },
'7': { value: 1000 }
}
const gen = findPlaceToInsertIds(['value'])
expect(gen.next().value).to.be.deep.equal(
select(updatesFeedSelector.getOnDemand))
expect(gen.next(ids).value).to.be.deep.equal(
select(updatesFeedSelector.getSortedIds))
expect(gen.next(sortedIds).value).to.be.deep.equal(
select(evidencesSelector.getEvidencesById))
const res = gen.next(byIds)
expect(res).to.have.property('done').to.be.true
expect(res).to.have.property('value').to.be.deep.equal({
ids: ['2', '4', '6'],
indexes: [1, 2, 3]
})
})
it('should find place to insert (even for messed) ids', () => {
const ids = ['4', '2', '6']
const sortedIds = ['1', '3', '5', '7']
const byIds = {
'1': { value: 7000 },
'2': { value: 6000 },
'3': { value: 5000 },
'4': { value: 4000 },
'5': { value: 3000 },
'6': { value: 2000 },
'7': { value: 1000 }
}
const gen = findPlaceToInsertIds(['value'])
expect(gen.next().value).to.be.deep.equal(
select(updatesFeedSelector.getOnDemand))
expect(gen.next(ids).value).to.be.deep.equal(
select(updatesFeedSelector.getSortedIds))
expect(gen.next(sortedIds).value).to.be.deep.equal(
select(evidencesSelector.getEvidencesById))
const res = gen.next(byIds)
expect(res).to.have.property('done').to.be.true
expect(res).to.have.property('value').to.be.deep.equal({
ids: ['2', '4', '6'],
indexes: [1, 2, 3]
})
})
})
|
// Properties file for the server instance
module.exports = {
ping: { "health": "OK" },
port: 5000,
instantClientDir : process.env.NODE_ORACLEDB_ICPATH || "/Users/sriksure/Downloads/instantclient_19_8"
};
|
import { handleResponse, handleError } from "./apiUtils";
// const baseUrl = process.env.API_URL + "/courses/";
// get courses from the mockdatabase
export function getProduct(baseUrl) {
return fetch(baseUrl)
.then(handleResponse)
.catch(handleError);
}
// get product by id from the database
export function getProductById(baseUrl) {
return fetch(baseUrl)
.then(handleResponse)
.catch(handleError);
}
// a dual purpose route for editing and creating courses
export function saveProduct(baseUrl, product) {
return fetch(baseUrl + (product.id || ""), {
method: product.id ? "PUT" : "POST", // POST for create, PUT to update when id already exists.
headers: { "content-type": "application/json" },
body: JSON.stringify(product)
})
.then(handleResponse)
.catch(handleError);
}
// delete a course from the mockDatabase
export function deleteProduct(baseUrl, productId) {
return fetch(baseUrl + productId, { method: "DELETE" })
.then(handleResponse)
.catch(handleError);
}
|
function mostrar()
{
var contador = 0;
var tipoDeProducto;
var jabonCantidad=0;
var barbijoCantidad=0;
var alcoholCantidad=0;
var cantidadDeUnidades;
var fabricante;
var precioMaximoJabon;
var primeraVez;
var cantidadJabon=0;
var cantidadUnidadesJabonMaximo;
var cantidadJabonesFabricanteMaximo;
var cantidadesMaximas = 0;
var promedioCompra;
var contadorCompraJabones = 0;
var contadorCompraBarjijo = 0;
var contadorCompraAlcohol = 0;
while (contador <5){
contador++;
do{
tipoDeProducto = prompt ("Ingrese tipo de producto");
}while (tipoDeProducto != "jabon" &&
tipoDeProducto != "acohol" && tipoDeProducto != "barbijo");
do{
precio= prompt ("ingrese precio");
precio= parseInt(precio);
}while(precio <100 || precio>300 || isNaN (precio));
do{
cantidadDeUnidades = prompt ("ingrese cantidad unidades");
cantidadDeUnidades = parseInt(cantidadDeUnidades);
}while (cantidadDeUnidades < 1 || cantidadDeUnidades > 100 || isNaN(cantidadDeUnidades));
do{
marca = prompt("Ingrese marca");
}while (marca == false);
do{
fabricante = prompt ("ingrese fabricante");
}while (fabricante == false);
if(tipoDeProducto == "jabon"){
cantidadJabon++;
if (cantidadJabon == 1){
precioMaximoJabon = precio;
cantidadUnidadesJabonMaximo = cantidadJabon;
cantidadJabonesFabricanteMaximo = fabricante;
}else{
if (precio > precioMaximoJabon){
precioMaximoJabon = precio;
cantidadUnidadesJabonMaximo = cantidadJabon;
cantidadJabonesFabricanteMaximo = fabricante;
}
}
}
switch (tipoDeProducto){
case "acohol":
alcoholCantidad += cantidadDeUnidades;
contadorCompraAlcohol++;
break;
case "barbijo":
barbijoCantidad += cantidadDeUnidades;
contadorCompraBarjijo++;
break;
case "jabon":
jabonCantidad += cantidadDeUnidades;
contadorCompraJabones++;
break;
}
if(alcoholCantidad > barbijoCantidad && alcoholCantidad > jabonCantidad){
alert (" Alcohol es mayor");
} else if (barbijoCantidad > jabonCantidad){
alert ("barbijo es mayor");
}else{
alert ("jabon es mayor");
}
}// fin del while principal
} |
export default {
small: 0,
medium: 640,
large: 1024,
xlarge: 1200,
xxlarge: 1440,
xxxlarge: 1800,
};
|
/*
Task 8. Write a JavaScript program to compute the sum of the two given integers. If the two values are same, then returns triple their sum.
Sample Input: 12,5 Sample Input: 8,8
Output : 17 Output : 48 */
var num1 = 8;
var num2 = 8;
if(num1 === num2){
console.log((num1 + num2) * 3);
}else{
console.log(num1 + num2);
}
|
import tw from 'tailwind-styled-components'
/** */
export const StyledInfoSpacer = tw.div`
h-px
bg-gray-400
my-4
` |
$(function() {
$("#login").bind("ajax:success", function(event, xhr, settings){
toastr["success"]("Все ок");
Turbolinks.visit(window.location);
});
$("#create_user, #create_rest").bind("ajax:success", function(event, xhr, settings){
toastr["success"]("Все ок");
Turbolinks.visit("/users/profile");
});
}); |
// ==UserScript==
// @name SPIEGEL Remove AdBlock Warning
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://addons.mozilla.org/en-US/firefox/addon/tampermonkey/
// @include http://www.spiegel.de*
// @include https://www.spiegel.de*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// ==UserScript==a
var homeAnchor = document.getElementsByTagName('body')[0];
//observer.observe(homeAnchor, config);
homeAnchor.removeChild(document.getElementsByClassName('ua-default')[0]);
})();
|
conn = new Mongo();
db = conn.getDB("sci")
//var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/;
db.tweets.find().forEach(function(element) {
var dStr = element.created_at;
dStr.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/,"$1 $2 $4 $3 UTC");
var d = new Date(dStr);
print(d); // Just to make sure it's still working...
element.created_at = d;
db.tweets.save(element);
})
print(db.tweets.find({},{created_at:1}).limit(10).forEach(function(f) { print (f.created_at instanceof Date) } ));
cursor = db.tweets.find().sort({created_at:1}).limit(5);
while (cursor.hasNext()) {
printjson(cursor.next());
} |
class PlayerList extends React.Component {
state = {
players: []
}
findAllPlayers = () =>
findAllPlayers()
.then(players => this.setState({players}))
componentDidMount = () =>
this.findAllPlayers()
createPlayer = () =>
createPlayer()
.then(this.findAllPlayers)
deletePlayer = (id) =>
deletePlayer(id)
.then(this.findAllPlayers)
render() {
return(
<div>
<h1>Player List</h1>
<table>
<tbody>
{
this.state.players.map(player =>
<tr>
<td>
Name: {player.player_name};
</td>
<td>
Team ID: {player.team_id};
</td>
<td>
Manager ID: {player.manager_id};
</td>
<td>
Age: {player.age};
</td>
<td>
Height: {player.height};
</td>
<td>
Player Salary: {player.player_payment};
</td>
<td>
Player Bank: {player.player_bank};
</td>
<td>
Player Statistic: {player.statistic};
</td>
</tr>
)
}
</tbody>
</table>
<br/> <br/>
<a href="/home-fan.html">
Home
</a>
</div>
)
}
}
ReactDOM.render(
<PlayerList/>, document.getElementById("root"))
|
module.exports = function(grunt) {
var mapUrlToBowerComponents = function(req, res, next) {
url_parts = req.url.split('/');
if (url_parts.length > 2 && url_parts[1] != 'bower_components') {
req.url = '/bower_components' + req.url;
}
return next();
};
grunt.initConfig({
connect: {
server: {
options: {
open: true,
keepalive: true,
middleware: function(connect, options, middlewares) {
middlewares.unshift(mapUrlToBowerComponents);
return middlewares;
}
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default', ['connect']);
};
|
import test from "tape"
import { upsertWith } from "./upsert"
test("upsertWith", t => {
t.deepEquals(
upsertWith({ id: 2 }, { id: 2, foo: "bar" })([{}]),
[{}, { id: 2, foo: "bar" }],
"Add if doesnt exist"
)
t.deepEquals(
upsertWith(
{ id: 2 },
{ id: 2, title: source => `${source} ipsum`, foo: "bar" }
)([{ id: 2, title: "lorem" }]),
[{ id: 2, title: "lorem ipsum", foo: "bar" }],
"Update value if exists"
)
t.deepEquals(
upsertWith(
{ id: 1 },
{ id: 1, title: source => `${source} ipsum` }
)([{ id: 2 }]),
[{ id: 2 }, { id: 1, title: "undefined ipsum" }],
"Update value if exists"
)
t.end()
})
|
// Scrivi un programma che stampi i numeri da 1 a 100, ma per i multipli di 3 stampi “Fizz” al posto del numero e per i multipli di 5 stampi Buzz.
// Per i numeri che sono sia multipli di 3 che di 5 stampi FizzBuzz.
//scrivere un ciclo che stampa i numeri da 1 a 100
//inserire all interno del ciclo la condizione: i = numeroDaAnalizzare --> se numeroDaAnalizzare % 3 == 0 allora console.log("fizz");
var numeroDaAnalizzare;
for (var i = 1; i <= 100; i++) {
numeroDaAnalizzare = i;
if (numeroDaAnalizzare % 3 == 0 && numeroDaAnalizzare % 5 == 0) {
console.log("FizzBuzz");
} else if (numeroDaAnalizzare % 3 == 0) {
console.log("Fizz");
} else if (numeroDaAnalizzare % 5 == 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
|
import {
recoveryChangePassword,
recoveryPassword
} from "../../services/RecoveryService";
export default {
Mutation: {
recoveryChangePassword: (_, {token, newPassword}, {user, req}) => {
return recoveryChangePassword(token, newPassword, req)
},
recoveryByEmail: (_, {email}) => {
return recoveryPassword(email)
},
}
}
|
'use strict'
const tap = require('tap')
const Api = require('../../api')
tap.test('commandDirectory > supports no arg (directory of caller)', async t => {
const result = await Api.get({ name: 'test' })
.commandDirectory()
.help()
.outputSettings({ maxWidth: 50 })
.parse('--help')
t.equal(result.code, 0)
t.equal(result.errors.length, 0)
t.equal(result.output, [
'Usage: test <command> <args> [options]',
'',
'Commands:',
' random [max=1] [min=0] Get pseudo-random number',
'',
'Options:',
' --help Show help [commands: help] [boolean]'
].join('\n'))
})
tap.test('commandDirectory > supports opts only', async t => {
const result = await Api.get({ name: 'test' })
.commandDirectory({ extensions: ['.cjs'] })
.help()
.outputSettings({ maxWidth: 50 })
.parse('--help')
t.equal(result.code, 0)
t.equal(result.errors.length, 0)
t.equal(result.output, [
'Usage: test <command> [options]',
'',
'Commands:',
' module A module with cjs file extension',
'',
'Options:',
' --help Show help [commands: help] [boolean]'
].join('\n'))
})
|
import fmoney from '@/utils/fmoney';
import { paginat } from '@/utils/pagination';
import { Badge, Card, Col, Modal, Row, Table, message } from 'antd';
import axios from 'axios';
import React, { Component } from 'react';
import SearchBox from './SearchBox';
//交易状态
const statusMap = {
'支付失败': 'error',
'待支付': 'warning',
'支付成功': 'success',
'退款成功': 'success',
'退款失败': 'error',
'退款中': 'processing',
'部分退款': 'success'
};
class TradeBlotter extends Component {
_isMounted = false
state = {
loading: true, //表格是否加载中
data: [],
total: 0, //总数
current: 1, //当前页数
pageSize: 10, //每页数量
visible: false,
selectedRowKeys: [], //当前有哪些行被选中, 这里只保存key
selectedRows: [], //选中行的具体信息
item: {},
searchParams: {}, //查询参数
}
componentDidMount() {
this._isMounted = true
// this.title = document.title
// document.title = '订单查询-明细'
const id = this.props.params.id
if (id) {
this.getPageList(10, 1, { merchantId: id })
} else {
this.getPageList()
}
}
componentDidUpdate() {
this.setTableScrollAuto()
}
componentWillUnmount() {
this._isMounted = false
// document.title = this.title
}
setTableScrollAuto() {
}
/**
*
* @param {Number} limit 每页条数默认10条
* @param {Number} offset 第几页,如果当前页数超过可分页的最后一页按最后一页算默认第1页
* @param {Object} params 其他参数
*/
getPageList(limit = this.state.pageSize, offset = this.state.current, params) {
if (!this.state.loading) {
this.setState({ loading: true })
}
axios.get('/back/tradeBlotter/page', {
params: {
limit,
offset,
...params
}
}
).then(({ data }) => {
data.rows.forEach((item, index) => {
item.key = `${index}`
})
this._isMounted && this.setState({
total: data.total,
data: data.rows,
current: offset,
loading: false,
})
}).catch(err => console.log(err))
}
//增加按钮
addHandle = () => {
this.setState({
visible: true
})
}
/**
* 点击删除按钮, 弹出一个确认对话框
* 注意区分单条删除和批量删除
* @param e
*/
onClickDelete = (e) => {
e.preventDefault();
Modal.confirm({
title: this.state.selectedRowKeys.length > 1 ? '确认批量删除' : '确认删除',
// 这里注意要用箭头函数, 否则this不生效
onOk: () => {
axios.all(this.state.selectedRows.map((item) => {
return axios.delete(`/back/passway/remove/${item.id}`)
})).then(axios.spread((acct, perms) => {
console.log(acct, perms)
if (!acct.data.rel) {
message.error('删除失败')
return
}
message.success('删除成功')
this.handleDelete();
}))
},
});
}
/**
* 发送http请求,删除数据,更新表格
* @param keys:Array 选中行的key
*/
handleDelete(keys = this.state.selectedRowKeys) {
let data = this.state.data.slice()
for (let i = 0, len = data.length; i < len; i++) {
for (let j = 0; j < keys.length; j++) {
if (data[i] && data[i].key === keys[j]) {
data.splice(i, 1);
i--;
}
}
}
this.setState({
data: data,
selectedRowKeys: []
})
}
/**
* 模态框提交按钮
* @param values
*/
handleOk = (values) => {
console.log('Received values of form: ', values);
axios.post('/back/passway/passway', values)
.then(({ data }) => {
message.success('添加成功!')
if (data.rel) {
let newData = this.state.data.slice()
newData.push({
key: values.passwayName,
passwayName: values.passwayName,
})
this.setState({
data: newData
})
}
})
this.setState({
visible: false,
});
// 清空表单
this.refs.addModal.resetFields()
}
/**
* 模态框取消按钮
*/
handleCancel = () => {
this.setState({
visible: false,
});
}
/**
* 处理表格的选择事件
*
* @param selectedRowKeys
*/
onTableSelectChange = (selectedRowKeys, selectedRows) => {
this.setState({ selectedRowKeys, selectedRows });
};
/**
* 下拉按钮组件
*/
handleMenuClick = (record, e) => {
if (e.key === '1') {
//详细按钮
this.setState({
item: record,
visible: true,
})
} else if (e.key === '2') {
//更新按钮
this.setState({
item: record,
visible: true,
})
//this.handleOk(record)
}
}
/**
* 页码改变的回调,参数是改变后的页码及每页条数
* @param page 改变后的页码
* @param pageSize 改变页的条数
*/
pageChange = (page, pageSize) => {
this.setState({
pageSize: pageSize,
current: page
})
this.getPageList(pageSize, page, this.state.searchParams)
}
/**
* pageSize 变化的回调
* @param current 当前页码
* @param pageSize 改变后每页条数
*/
onShowSizeChange = (current, pageSize) => {
this.setState({
pageSize: pageSize,
current: current
})
this.getPageList(pageSize, current, this.state.searchParams)
}
/**
* 查询功能
* @param values
*/
search = (values) => {
this.setState({
searchParams: values
})
this.getPageList(this.state.pageSize, 1, values)
}
render() {
const pagination = paginat(this, (pageSize, current, searchParams) => {
this.getPageList(pageSize, current, searchParams)
})
return (
<div className="templateClass">
<Card
bordered={false}
bodyStyle={{ backgroundColor: "#f8f8f8", marginRight: 32 }}
noHovering
>
<SearchBox loading={this.state.loading} search={this.search} />
</Card>
<Card
bordered={false}
noHovering bodyStyle={{ paddingLeft: 0 }}
>
<Row>
<Col>
<Table
scroll={{ x: true }}
loading={this.state.loading}
columns={columns}
dataSource={this.state.data}
pagination={pagination}
/>
</Col>
</Row>
</Card>
</div>
)
}
}
export default TradeBlotter
//表格表头信息
const columns = [
{
title: "交易发起时间",
dataIndex: "tradedt",
}, {
title: "商户名称",
dataIndex: "merchantName",
// className: 'table_text_center',
// width: 180,
// render: (text, record, index) => {
// return <div title={text} style={{ maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: 'default' }} >
// {text}
// </div>
// }
}, {
title: "通道",
dataIndex: "passwayId",
// className: 'table_text_center',
}, {
title: "交易状态",
dataIndex: "stateName",
// className: 'table_text_center',
render: (text, record) => (
// console.log(text, record) status={statusMap[text]}
<Badge status={statusMap[text]} text={text} />
)
}, {
title: "交易金额",
dataIndex: "sum",
className: 'table_text_right',
render: (text) => {
return fmoney(text)
}
}, {
title: "退款金额",
dataIndex: "refundsum",
className: 'table_text_right',
render: (text) => {
return fmoney(text)
}
}, {
title: "订单号",
dataIndex: "orders",
}, {
title: "退款订单号",
dataIndex: "refundorders",
// className: 'table_text_center',
// width: 260
}, {
title: "设备终端",
dataIndex: "terminalName",
}, {
title: "二维码值",
dataIndex: "qrNo",
// className: 'table_text_center',
}, {
title: '二维码名',
dataIndex: 'qrName',
}, {
title: "交易确认时间",
dataIndex: "tradecfdt",
},
{
title: "支付方式",
dataIndex: "paySceneName",
},
// {
// title: "交易类型",
// dadaIndex: "typeName",
// className: 'table_text_center',
// },
// {
// title: "手续费",
// dataIndex: "fee",
// className: 'table_text_center',
// },
// {
// title: "设备品类",
// dataIndex: "deviceName",
// className: 'table_text_center',
// },
{
title: "钱包方订单号",
dataIndex: "tradeNo",
}, {
title: "费率",
dataIndex: "rate",
// className: 'table_text_center',
},
{
title: "备注",
dataIndex: "remark",
}
]
|
const net = require('net');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function Client(username) {
var address = '';
var port = '';
this.username = username;
this.socket = null;
this.send = function (message) {
this.socket.write(username + ': ' + message);
}
this.receive = function (message) {
console.log(new Date().toLocaleTimeString() + ' ' + message.toLocaleString());
}
this.init = function (server) {
this.socket = net.connect({ port: server.port, host: server.host }, () => {
console.log('Successfully connected to ' + server.host + ' at port ' + this.socket.localPort);
});
this.socket.on('data', this.receive);
}
}
const NETWORK_CREDENTIALS = {
host: '151.251.11.225',
port: 9000
};
(function () {
var client = null;
rl.question('username: ', (answer) => {
client = new Client(answer);
client.init(NETWORK_CREDENTIALS);
});
rl.setPrompt('>');
rl.on('line', (line) => {
client.send(line);
rl.prompt();
});
}()); |
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import {
Button,
CardStack,
Density,
Surface,
Intent,
Input,
ListItem,
List,
Spinner,
InputGroup
} from "amino-ui";
import useSWR from "swr";
import { AppHeader } from "../Layout/AppHeader";
import { Card } from "../Layout/Card";
import { fetcher } from "../../utils/fetcher";
import { LoadingLayout } from "../Layout/LoadingLayout";
import { ResponsiveContainer } from "../Layout/ResponsiveContainer";
import { toaster } from "evergreen-ui";
import { useDispatch } from "react-redux";
import { push } from "connected-react-router";
import { Back } from "../Layout/Back";
import { CategoryEdit } from "./CategoryEdit";
export const DivisionDetail = () => {
const { id, division_id } = useParams();
const dispatch = useDispatch();
const goto = url => dispatch(push(url));
const { data: division } = useSWR(
`${process.env.REACT_APP_API_URL}/events/${id}/divisions/${division_id}`,
fetcher
);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [savingDetails, setSavingDetails] = useState(false);
const [editCategory, setEditCategory] = useState(false);
const [category, setCategory] = useState(true);
useEffect(() => {
if (division && division.division) {
setName(division.division.name || "");
setDescription(division.division.description || "");
}
}, [division]);
const saveDivisionDetails = async () => {
setSavingDetails(true);
try {
if (division_id !== "new") {
const response = await fetcher(
`${process.env.REACT_APP_API_URL}/events/${id}/divisions/${division_id}`,
{
method: "PATCH",
body: JSON.stringify({
name,
description
})
}
);
if (response) {
toaster.success("Division details updated successfully");
} else {
toaster.danger("Couldn't update division details");
}
} else {
const response = await fetcher(
`${process.env.REACT_APP_API_URL}/events/${id}/divisions`,
{
method: "POST",
body: JSON.stringify({
name,
description,
event_id: id
})
}
);
if (response) {
toaster.success("Division created successfully");
goto(`/events/${id}/divisions/${response.division.id}`);
} else {
toaster.danger("Couldn't create division");
}
}
} catch (e) {
toaster.danger("Couldn't create division");
}
setSavingDetails(false);
};
if (!division)
return (
<LoadingLayout>
<Spinner />
</LoadingLayout>
);
return (
<>
<AppHeader />
<ResponsiveContainer>
<Back label="Event admin" url={`/events/${id}/admin`} />
<CardStack>
<Card
cardTitle="Division info"
actions={
<Button
disabled={savingDetails || !division}
saving={savingDetails}
intent={Intent.Primary}
onClick={() => saveDivisionDetails()}
>
Save details
</Button>
}
>
<InputGroup>
<Input
label="Name"
value={name}
onChange={e => setName(e.target.value)}
/>
<Input
label="Description"
value={description}
onChange={e => setDescription(e.target.value)}
/>
</InputGroup>
</Card>
{division_id !== "new" ? (
<Card
cardTitle="Categories"
actions={
<Button
onClick={() => {
setCategory(null);
setEditCategory(true);
}}
>
Create category
</Button>
}
></Card>
) : null}
</CardStack>
</ResponsiveContainer>
<CategoryEdit
open={editCategory}
onClose={() => setEditCategory(false)}
category_id={category}
divisionId={division_id}
id={id}
/>
</>
);
};
|
import React, { Component } from 'react';
import './css/message.css';
export default class Message extends Component {
constructor(option){
super(option);
this.state = {
height:'2rem',
marginTop:0,
imgTop:0,
hasImg:false
}
}
render() {
let {role,text,fullWidth,date} = this.props;
return (
<div className={'message-C ' + role} ref='message-C' style={{height:this.state.height,marginTop
:this.state.marginTop,width:fullWidth?'99%':'96%'}}>
<h1></h1>
{date && <h2>{date}</h2>}
<div className='role'><img style={{marginTop: this.state.imgTop}} src={'./assets/images/'+role+'.jpg'}/></div>
<div className={'text '+ (this.state.hasImg?'notext':'')}>{text}</div>
</div>
);
}
componentDidMount(){
let {obserable} = this.props;
let messageC = this.refs['message-C'];
setTimeout(()=>{
messageC.style.opacity=1;
},1);
if(messageC.querySelector('.pic')){
messageC.querySelector('.pic').onload = ()=>{
this.setState({
height:messageC.querySelector('.pic').height+30,
marginTop:'.5rem',
imgTop:0,
hasImg:true
},()=>{
obserable.trigger({type:'refresh'});
});
}
}
}
}
Message.defaultProps = {
}
|
import CONSTANTS from '@/utils/interfaces/constants';
const REDUCER_KEY = 'Cadence';
const API_PATH = 'mam/cadence';
const DATES_PATH = 'mam';
export const RESULT_KEY = {
LOAD: 'load',
RPM: 'rpm',
TIME: 'time'
};
export const LABELS = {
[RESULT_KEY.RPM]: 'Скорость, об/мин',
[RESULT_KEY.TIME]: 'Время, мс'
};
export default CONSTANTS(REDUCER_KEY, API_PATH, null, DATES_PATH);
|
import React, { useState } from 'react'
import { StyleSheet, View } from 'react-native'
import SegmentedControlTab from 'react-native-segmented-control-tab'
const ContainerSegment = ({ values, onPress }) => {
const [ selectedIndex, setValue ] = useState(0)
return (
<View style={styles.container}>
<SegmentedControlTab
values={ values }
onTabPress={ index => {
setValue(index)
onPress(index)
} }
selectedIndex={ selectedIndex }
/>
</View>
)
}
const styles = StyleSheet.create({
container: {
width: '100%',
padding: 10,
justifyContent: 'center',
alignItems: 'center',
}
})
export default ContainerSegment |
/**
* Angular module for /customers
*/
angular.module('customerApp', ['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'customers/kunderegister',
controller: 'kunderegisterCtrl'
})
.when('/nykunde', {
templateUrl: 'customers/newcustomer',
controller: 'addNewCustomerCtrl'
})
.when('/nykunde/:id', {
templateUrl: 'customers/newcustomer',
controller: 'editCustomerCtrl'
})
.when('/ordreoversikt', {
templateUrl: 'customers/ordreoversikt',
controller: 'ordreoversiktCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.factory('CustomerService', ['$http', '$q', function($http, $q) {
var getAllCustomersUrl = "/customers/getAllCustomers";
var allCustomers = [];
var fetchCustomers = function(cb) {
$http({method: "GET", url: getAllCustomersUrl}).
success(function(data, status) {
allCustomers = data.allCustomers;
return cb(allCustomers);
}).
error(function(data, status) {
return cb(data || "Request failed");
});
};
return {
getAllCustomers: function (cb) {
if(allCustomers.length > 0) {
return cb(allCustomers);
} else {
var deferred = $q.defer();
fetchCustomers(function(data) {
deferred.resolve(data);
});
deferred.promise.then(function(res) {
return cb(res);
});
}
}
};
}])
.filter('tel', function () {
return function (tel) {
if(tel !== null) {
var s = tel.toString();
return s.slice(0,3) + " " + s.slice(3,5) + " " + s.slice(5,8);
}
}
})
.controller('menuCtrl', ['$scope', '$location', function($scope, $location){
$scope.isActive = function(route) {
return route === $location.path();
}
}])
.controller('kunderegisterCtrl', ['$scope', 'CustomerService', function($scope, CustomerService){
CustomerService.getAllCustomers(function(res) {
$scope.allCustomers = res;
});
$scope.orderByVariable = "name";
}])
.controller('addNewCustomerCtrl', ['$scope', '$http', function($scope, $http){
$scope.userForm = {};
$scope.addedPerson = "";
$scope.removeAddedPerson = function() {
$scope.addedPerson = "";
};
$scope.submitNewCustomer = function(isValid) {
if(isValid) {
// Submitting
$http.post("/customers/create", $scope.userForm).success(function(newcustomer, status){
console.log("success", newcustomer, status);
$scope.addedPerson = newcustomer.name;
$scope.userForm = {};
$scope.newUserForm.$setPristine(true)
}).error(function(data, status){
console.log("error", data, status);
});
}
};
}])
.controller('editCustomerCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
var id = $routeParams.id;
$http.get("/customers/getCustomer?id=" + id).success(function(customer, status){
$scope.userForm = customer;
console.log($scope.userForm);
}).error(function(data, status){
console.log("error", data, status);
});
$scope.removeAddedPerson = function() {
$scope.addedPerson = "";
};
$scope.submitNewCustomer = function(isValid) {
if(isValid) {
// Submitting
$http.post("/customers/updateCustomer", $scope.userForm).success(function(newcustomer, status){
console.log("success", newcustomer, status);
window.location.replace("/customers");
}).error(function(data, status){
console.log("error", data, status);
});
}
};
}])
.controller('ordreoversiktCtrl', ['$scope', 'filterFilter', 'CustomerService', function($scope, filterFilter, CustomerService){
$scope.filterSecondLevel = function (orders) {
var filteredOrders = filterFilter(orders, $scope.orderSok);
if(filteredOrders.length > 0 ){
return filteredOrders;
} else {
return orders;
}
};
$scope.totalPrice = function(customer) {
var totPrice = 0;
angular.forEach(customer.orders, function(order) {
angular.forEach(order.tickets, function(ticket) {
totPrice += ticket.price;
});
});
return totPrice;
};
$scope.viewOrder = function(order) {
console.log("View order: ", order);
};
CustomerService.getAllCustomers(function(res) {
angular.forEach(res, function(customer) {
customer.totaltickets = 0;
customer.totalprice = 0;
angular.forEach(customer.orders, function(order) {
customer.totaltickets += order.tickets.length;
customer.totalprice += order.totalprice;
});
});
// Have orders only
$scope.allCustomers = res.filter(function(customer){
return customer.orders.length > 0;
});
});
}]); |
$(document).ready(function() {
$("#zoom_01").elevateZoom();
}) |
'use strict';
var Error = require('../Error');
var request = require('request');
function WiaResourceOrganisations(wia) {
this.me = function(cb) {
request.get(wia.getApiUrl() + "organisations/me", {
auth: {
bearer: wia.getApiField('accessToken')
},
json: true,
headers: wia.getHeaders()
}, function (error, response, body) {
if (cb) {
if (error) return cb(error, null);
if (response.statusCode == 200 || response.statusCode == 201)
cb(null, body);
else
cb(new Error.WiaRequestException(response.statusCode, body || ""), null);
}
});
}
}
module.exports = WiaResourceOrganisations;
|
const hoursHand = document.querySelector('.clock-h')
const minutesHand = document.querySelector('.clock-m')
const secondsHand = document.querySelector('.clock-s')
const dateblock = document.querySelector('.day')
function clock() {
let now = new Date()
let h = now.getHours()
let m = now.getMinutes()
let s = now.getSeconds()
let sAngle = s * 6
let mAngle = m * 6 +s*0.1
let hAngle = h*30 + m*.5
secondsHand.style.transform = `rotate(${sAngle}deg)`
minutesHand.style.transform = `rotate(${mAngle}deg)`
hoursHand.style.transform = `rotate(${hAngle}deg)`
setTimeout(clock,500)
}
function day() {
let now = new Date()
let mth = now.getMonth()
let d = now.getDate()
let year = ['jan',
'feb',
'mar',
'apr',
'may',
'jun',
'jul',
'aug',
'sep',
'oct',
'nov',
'dec',]
// 1способ
// Находим день
// if (d < 10) { d = '0' +d}
// Находим месяц
// mth++
// if (mth < 10) { mth = '0'+mth}
// dateblock.textContent = ` ${d} . ${mth} `
// 2способ
// mth = (++mth < 10) ? '0' + mth : mth
// d = (d < 10) ? '0' +d : d
// dateblock.textContent = ` ${d} . ${mth} `
// 3 способ
// dateblock.textContent = ` ${(d < 10) ? '0' +d : d} . ${mth = (++mth < 10) ? '0' + mth : mth} `
// console.log(d, mth)
// 4 способ
console.log(d, mth, year[mth])
// mth = year[mth]
dateblock.textContent = `${(d < 10) ? '0' + d : d} ${year[mth]}`
setTimeout(day, 1000)
}
day()
clock()
|
/* data actions */
export const FETCH_FEED_COMPANY = 'FETCH_FEED_COMPANY'
export const UPDATE_FEED_DATA = 'UPDATE_FEED_DATA'
export const FETCH_COMPANY_DATA = 'FETCH_COMPANY_DATA'
export const UPDATE_COMPANY_DATA = 'UPDATE_COMPANY_DATA'
export const SORT_COMPANY_DATA = 'SORT_COMPANY_DATA'
export const FETCH_COMPANY = 'FETCH_COMPANY'
export const FETCH_PRODUCT_DATA = 'FETCH_PRODUCT_DATA'
export const UPDATE_PRODUCT_DATA = 'UPDATE_PRODUCT_DATA'
export const FETCH_PRODUCT = 'FETCH_PRODUCT'
//Filter Actions
export const FILTER_FEED_SEARCH = 'FILTER_FEED_SEARCH'
export const FILTER_FEED_DROPDOWN = 'FILTER_FEED_DROPDOWN'
export const FILTER_FEED_DATE = 'FILTER_FEED_DATE'
export const CLEAR_FEED_DROPDOWN = 'CLEAR_FEED_DROPDOWN'
export const FILTER_COMPANY_NAME = 'FILTER_COMPANY_NAME'
export const FILTER_COMPANY_DESCRIPTION = 'FILTER_COMPANY_DESCRIPTION'
export const FILTER_COMPANY_DROPDOWNOPTIONS = 'FILTER_COMPANY_DROPDOWNOPTIONS'
export const FILL_COMPANY_COLUMN = 'FILL_COMPANY_COLUMN'
export const FILTER_COMPANY_SLIDERS = 'FILTER_COMPANY_SLIDERS'
export const CLEAR_COMPANY_DROPDOWNOPTIONS = 'CLEAR_COMPANY_DROPDOWNOPTIONS'
export const CLEAR_COMPANY_SLIDERS = 'CLEAR_COMPANY_SLIDERS'
export const CLEAR_COMPANY_ALL = 'CLEAR_COMPANY_ALL'
export const CHANGE_RANK_WEIGHTS = 'CHANGE_RANK_WEIGHTS'
export const FILTER_PRODUCT_NAME = 'FILTER_PRODUCT_NAME'
export const FILTER_PRODUCT_DROPDOWNOPTIONS = 'FILTER_PRODUCT_DROPDOWNOPTIONS'
export const FILL_PRODUCT_COLUMN = 'FILL_PRODUCT_COLUMN'
export const CLEAR_PRODUCT_DROPDOWNOPTIONS = 'CLEAR_PRODUCT_DROPDOWNOPTIONS'
export const CLEAR_PRODUCT_ALL = 'CLEAR_PRODUCT_ALL'
/* pagination actions */
export const CHANGE_PAGE_NUMBER = 'CHANGE_PAGE_NUMBER'
export const CHANGE_LAST_PAGE_NUMBER = 'CHANGE_LAST_PAGE_NUMBER'
|
//获取客户列表
export const GET_USERLIST ="GET_USERLIST";
//修改其中一条数据
export const MODEL_INFO='MODEL_INFO'
//伤处其中一条数据
export const REMOVE_INFO='REMOVE_INFO'
|
import axios from "axios";
const baseUrl = "https://restcountries.eu/rest/v2/all"
const getAll = () => {
const request = axios.get(baseUrl).then((response) => {
return response.data
})
return request
}
const countriesService = { getAll }
export default countriesService |
// Copyright (c) 2021 Visiosto oy
// Licensed under the MIT License
export default {
cvGradesShow: 'Näytä arvosanojen erittely',
cvGradesHide: 'Piilota',
};
|
$.ajax({
url: 'https://api.github.com/repos/MalikSteam/account_public/commits',
beforeSend: function (xhr) {
xhr.setRequestHeader ("Accept: application/vnd.github.v3+json");
},
dataType: 'jsonp',
success: function(data){
console.log(data.data[0].sha);
$.ajax({
url: 'https://api.github.com/repos/MalikSteam/account_public/commits/'+data.data[0].sha,
dataType: 'jsonp',
success: function(data){
console.log(data.data.files[0].patch);
$( ".commit_0" ).append( "<h4>" +data.data.files[0].filename+ '</h4><pre style="font-size:66%;"><xmp>' + data.data.files[0].patch + '</xmp><pre>' );
}
});
$.ajax({
url: 'https://api.github.com/repos/MalikSteam/account_public/commits/'+data.data[0].parents[0].sha,
dataType: 'jsonp',
success: function(data){
console.log(data.data.files[0].patch);
$( ".commit_1" ).append( "<h4>" +data.data.files[0].filename+ '</h4><pre style="font-size:66%;"><xmp>' + data.data.files[0].patch + '</xmp><pre>' );
}
});
}
}); |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { hbs } from 'ember-cli-htmlbars';
import Component from '@ember/component';
import { register } from 'ember-register-helper/helpers/register';
module('Integration | Helper | register', function(hooks) {
setupRenderingTest(hooks);
test('it registers the class', async function(assert) {
let TestComponent = Component.extend();
let name = register(this.owner, TestComponent);
let resolvedClass = this.owner.resolveRegistration(`component:${name}`);
assert.strictEqual(
resolvedClass,
TestComponent,
'component class is registered and resolved correctly'
);
});
test('it memoizes the registration name', async function(assert) {
let TestComponent = Component.extend();
let name1 = register(this.owner, TestComponent);
let name2 = register(this.owner, TestComponent);
assert.strictEqual(name1, name2, 'two invocations return the same name');
});
test('it returns null when passed something nullish', async function(assert) {
assert.strictEqual(register(this.owner, null), null, 'returns null when passed null');
assert.strictEqual(register(this.owner, undefined), null, 'returns null when passed undefined');
});
// The next test is executed twice to ensure that the registration cache doesn't leak between tests.
let TestComponent = Component.extend({
layout: hbs`test`,
});
for (let i = 0; i < 2; i++) {
test(`The registration cache is properly scoped to an owner (${i +
1}/2)`, async function(assert) {
this.set('testComponentClass', TestComponent);
await this.render(hbs`{{component (register this.testComponentClass)}}`);
assert.dom().hasText('test');
});
}
test('it returns the same string when passed a string', async function(assert) {
assert.strictEqual(
register(this.owner, 'my-component'),
'my-component',
'returns the same string when passed a string'
);
});
});
|
document.addEventListener('DOMContentLoaded', function() {
object_id = '';
$(document).on("click", ".fc-time-grid-event", function() {
object_id = $('#object_id_calendar').val();
//object_id = document.getElementById('object_id_calendar').value;
});
$(".upload").upload({
action: "../php/handler.php",
label: '',
maxQueue: '1',
postData: {
id: object_id
},
}).on("start", Start).on("filestart", fileStart).on("fileprogress", fileProgress).on("filecomplete", fileComplete).on("fileerror", fileError);
function Start (e, files) {
$("#res").text('');
console.log('Start');
for(var i = 0; i < files.length; i++) {
var html ='<li class=loading-str data-index="' + files[i].index + '"><span class="file">' + files[i].name + '</span><progress value="0" max="100"></progress><span class="loading"></span></li>';
$("#res").append(html);
}
}
function fileStart (e, file) {
console.log('File Start');
$("#res").find('li[data-index='+file.index+']').find('.loading').text('0%');
}
function fileProgress (e, file, percent) {
console.log('File Progress');
$("#res")
.find('li[data-index='+file.index+']')
.find('progress').attr('value', percent)
.next().text(percent + '%');
}
function fileComplete (e, file, response) {
if(response == '' || response.toLowerCase() == 'error') {
$("#res").find('li[data-index='+file.index+']').addClass('upload_error').find('.loading').text('Ошибка загрузки');
}
else{
$("#res").find('li[data-index='+file.index+']').remove();
Request();
}
}
function fileError (e, file) {
$("#res").find('li[data-index='+file.index+']').addClass('upload_error').find('.loading').text('Файл не поддерживается');
}
});
|
module.exports = {
extends: 'airbnb',
parser: 'babel-eslint',
env: {
jest: true
},
rules: {
'no-use-before-define': 'off',
'react/jsx-filename-extension': 'off',
'react/prop-types': 'off',
'comma-dangle': 'off',
'import/prefer-default-export': 'off',
'no-console': 'off',
'global-require': 'off',
'no-return-assign': 'off',
'linebreak-style': 'off',
'no-return-await': 'off',
'object-curly-newline': 'off',
'react/jsx-one-expression-per-line': 'off',
'arrow-parens': 'off'
},
globals: {
fetch: false
}
};
|
$(document).ready(function(){
$("#tweets").change(function(e) {
var selected = $(this).val();
if(selected === '--')
{
return ;
}
else
{
$.ajax({
method: 'POST',
url: 'test.php',
dataType: 'json',
data: {
selected: selected,
},
success: function(msg) {
$("#displaytweets").html(msg.tweets);
}
});
}
});
}); |
import CurrencyService from "../Services/Currency.service";
export default class User {
constructor(budget, selectedItems) {
this.budget = budget;
this.selectedItems = selectedItems;
}
selectedItemsMinPrice(items) {
return this.selectedItems.map((itemID) => items.find((item) => item.id === itemID)).reduce((sum, each) => sum + each.lowPrice, 0);
}
selectedItemsMaxPrice(items) {
return this.selectedItems.map((itemID) => items.find((item) => item.id === itemID)).reduce((sum, each) => sum + each.highPrice, 0);
}
prettySelectedItemsPriceRange(items) {
return `${CurrencyService.convertToDollars(this.selectedItemsMinPrice(items))} - ${CurrencyService.convertToDollars(this.selectedItemsMaxPrice(items))}`;
}
}
|
import React from "react";
import ReactDOM from "react-dom";
import { applyMiddleware, createStore } from "redux";
import { MuiThemeProvider } from '@material-ui/core/styles';
import { Provider } from "react-redux";
import ReduxThunk from "redux-thunk"; // no
import { Router } from "react-router-dom";
import reducers from "./reducers";
import theme from "./config/theme";
import history from "./config/history";
import axiosConfig from "./config/axios";
import App from "./components/App/index";
const reduxDevTools = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__();
const store = createStore(reducers, reduxDevTools, applyMiddleware(ReduxThunk));
axiosConfig.store = store;
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<MuiThemeProvider theme={theme}>
<App />
</MuiThemeProvider>
</Router>
</Provider>,
document.querySelector("#root"),
);
|
/**
* Layout component that queries for data
* with Gatsby's useStaticQuery component
*
* See: https://www.gatsbyjs.com/docs/use-static-query/
*/
import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Header from "./header"
// import Footer from "./footer"
import "./layout.css"
// import "./menu.js"
import { Link } from "gatsby"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
nama
}
}
}
`)
return (
<>
<Header siteTitle={data.site.siteMetadata?.nama || `Title`} />
<div
style={{
// marginTop: 0,
margin: `0 auto`,
maxWidth: 960,
padding: `0 1.0875rem 1.45rem`,
paddingTop: "0",
// background:'grey',
}}
>
<nav
style={{
maxWidth: "auto",
// textAlign: "center",
// alignItems: 'center',
// alignContent: "center",
// background: "grey",
marginTop: "0",
paddingTop: "0",
justifyContent: "space-evenly",
}}
>
<ul
style={{
listStyle: "none",
padding: "auto",
color: "black",
display: "flex",
justifyContent: "space-evenly",
textDecoration: "none",
textDecorationLine: "none",
fontStyle: "bold",
// background: "red",
}}
>
{/* <li
style={{
fontStyle: "bold",
}}
>
<Link
style={{
textDecoration: "none",
fontStyle: "bold",
}}
to="/blog"
>
Blog
</Link>
</li> */}
<li>
<Link style={{ textDecoration: "none" }} to="/contact">
Contact
</Link>
</li>
<li>
<Link style={{ textDecoration: "none" }} to="/about">
About
</Link>
</li>
</ul>
</nav>
<main>{children}</main>
<footer
style={{
marginTop: `2rem`,
}}
>
© {new Date().getFullYear()}, Created by
{` `}
<a href="#" style={{ textDecoration: `none` }}>
{data.site.siteMetadata.nama}
</a>
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
function stxAjax(vUrl, vCallBack, vIsPost)
{
if (window.ActiveXObject)
{
this.objXmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest)
{
this.objXmlHttpReq = new XMLHttpRequest();
}
this.url = vUrl;
this.isPost = vIsPost;
this.callBack = vCallBack;
vUrl = null;
vIsPost = null;
vCallBack = null;
}
stxAjax.prototype = {
getUrl: function ()
{
return this.url;
},
getCallBack: function ()
{
return this.callBack;
},
setUrl: function(vUrl)
{
if(vUrl)
{
this.url = vUrl;
}
vUrl = null;
},
setCallBack: function(vCallBack)
{
if(vCallBack)
{
this.callBack = vCallBack;
}
vCallBack == null;
},
setPost: function()
{
this.isPost = true;
},
executeAnSync: function(isXMLOut,vParam)
{
var vGetPost = "GET";
if(this.isPost)
{
vGetPost = "POST";
}
if(!this.url || this.url == '')
{
alert("AjaxError:Url is null or Empty");
return;
}
if(!this.callBack || this.callBack == '')
{
alert("AjaxError:CallBack Function is null or Empty");
return;
}
var vXmlHttpReq = this.objXmlHttpReq;
var vCallBack = this.callBack;
vXmlHttpReq.open(vGetPost, this.url, true);
vXmlHttpReq.onreadystatechange = function() {
if(vXmlHttpReq.readyState == 4)
{
if(vXmlHttpReq.status == 200)
{
var vReturn = vXmlHttpReq.responseText;
if(isXMLOut)
{
vReturn = vReturn.replace(/(^\s*)|(\s*$)/g, "");
vReturn = fnParseXmlFromText(vReturn)
} else {
vReturn = vReturn.replace(/(^\s*)|(\s*$)/g, "");
}
eval(vCallBack+"(vReturn,vParam)");
vGetPost = null;
vCallBack = null;
vXmlHttpReq = null;
vReturn = null;
} else if(vXmlHttpReq.status == 204) {
} else {
alert('Ajax Error'+vXmlHttpReq.status)
vGetPost = null;
vCallBack = null;
vXmlHttpReq = null;
}
}
}
vXmlHttpReq.send(null);
},
executeSync: function(isXMLOut,vParam)
{
try{
if(!this.url || this.url == '')
{
alert("AjaxError:Url is null or Empty");
return;
}
var vGetPost = "GET";
var vXmlHttpReq = this.objXmlHttpReq;
if(this.isPost)
{
vGetPost = "POST";
}
vXmlHttpReq.open(vGetPost, this.url, false);
if(this.isPost)
{
vXmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
vXmlHttpReq.send(vParam);
if(isXMLOut)
{
return fnParseXmlFromText(this.trim(vXmlHttpReq.responseText))
} else {
return this.trim(vXmlHttpReq.responseText);
}
} catch(e) {
alert(e);
} finally {
vGetPost = null;
isXMLOut = null;
vXmlHttpReq = null;
}
},
trim: function(vText)
{
return vText.replace(/(^\s*)|(\s*$)/g, "");
},
parseXML: function(vText)
{
var vReturnDoc = new ActiveXObject("Msxml2.DOMDocument");
vReturnDoc.loadXML(vText);
return vReturnDoc;
}
}
function fnParseXmlFromText(vText)
{
try{
var vReturnDoc = new ActiveXObject("Msxml2.DOMDocument");
vReturnDoc.loadXML(vText);
return vReturnDoc;
} finally {
vReturnDoc = null;
vText = null;
}
}
function fnGetformParam(oForm)
{
try{
var vParam = "";
var elForm;
for(var index=0;index<oForm.elements.length;index++)
{
elForm = oForm.elements[index];
switch(elForm.type)
{
case 'text':
vParam += elForm.name + '=' + elForm.value + '&'
break;
case 'hidden':
vParam += elForm.name + '=' + elForm.value + '&'
break;
case 'password':
case 'textarea':
case 'select-one':
vParam += elForm.name + '=' + elForm.value + '&'
break;
case 'radio':
if(elForm.checked) {
vParam += elForm.name + '=' + elForm.value + '&'
}
break;
case 'checkbox':
break;
}
}
return vParam;
} finally {
oForm = null;
vParam = null;
elForm = null;
}
}
String.prototype.encodeURI = function()
{
return encodeURIComponent(this);
}
|
import React, { useState } from 'react';
import useForm from 'react-hook-form';
import { Link, Redirect } from "react-router-dom";
import { usernameLoginConfig, passwordConfig } from '../../utils/userValidationRules';
import authReducer, { login } from "../../utils/authAdministration";
import './styles.css';
import routes from "../../utils/routes";
import { Button } from "react-bootstrap";
const Login = (props) => {
const { register, handleSubmit, /* watch, */ errors } = useForm();
const [isToLogin, setIsToLogin] = useState(false);
const [loginErrorMsg, setLoginErrorMsg] = useState(null);
const locationState = props.location.state;
const locationStateHasMsg = locationState && locationState.authMsg;
const hasLoginErrorMsg = loginErrorMsg;
const _login = () => isToLogin ? <Redirect to={{
pathname: routes.home
}} /> : null;
const onSubmit = data => {
const loginAction = login(data);
authReducer(loginAction);
if (loginAction.user.exists) setIsToLogin(true);
else setLoginErrorMsg("Username or password invalid");
};
return (
<div className="container">
<div className="Login">
{_login()}
<form onSubmit={handleSubmit(onSubmit)}>
<h2 className="title">Login Form</h2>
{hasLoginErrorMsg && /* Access denied error */
<div className="alert alert-danger">{loginErrorMsg}</div>
}
{!hasLoginErrorMsg && locationStateHasMsg && /* Access denied error */
<div className="alert alert-danger">{locationState.authMsg}</div>
}
<div className="input-container"> {/* Username input */}
{/*<i className="fa fa-user icon"></i>*/}
<i className="i-username icon"></i>
<input className="input-field" type="text" name="username"
placeholder="Who are you?" ref={register(usernameLoginConfig)}
defaultValue={locationState && locationState.userData ?
locationState.userData.username : ""}
autoFocus={hasLoginErrorMsg} />
</div>
{errors.username && /* Username error */
<div className="alert alert-danger">{errors.username.message}</div>
}
<div className="input-container"> {/* Password input */}
{/*<i className="fa fa-key icon"></i>*/}
<i className="i-password fa fa-key icon"></i>
<input className="input-field" type="password" name="password"
placeholder="What's your password?" ref={register(passwordConfig)}
autoFocus={!hasLoginErrorMsg && locationStateHasMsg} />
</div>
{errors.password && /* Password error */
<div className="alert alert-danger">{errors.password.message}</div>
}
<div className="btns-login d-flex justify-content-around">
<Link to={routes.index}>
<Button variant="light">Come back</Button>
</Link>
<Button variant="primary" type="submit" >Explore</Button>
</div>
<div>
<Link to={routes.register}>
<Button variant="secondary" size="sm">
Let me introduce myself
</Button>
</Link>
</div>
</form>
</div>
</div>
);
};
export default Login;
|
import RegionScreen from '@screens/userScreens/regions';
import PokemonScreen from '@screens/userScreens/pokemon';
import PokemonDetailsScreen from '@screens/userScreens/pokemonDetails';
import TeamScreen from '@screens/userScreens/teams';
import TeamDetailsScreen from '@screens/userScreens/teamDetails';
import TeamTokenScreen from '@screens/userScreens/teamToken';
const userScreens = {
Region: RegionScreen,
Pokemon: PokemonScreen,
PokemonDetails: PokemonDetailsScreen,
Team: TeamScreen,
TeamDetails: TeamDetailsScreen,
TeamToken: TeamTokenScreen,
};
export default userScreens;
|
var i=document.cookie;
var read='http://localhost:8010/history?userID='+i;
var API_URL = {
READ: read
};
console.log(API_URL.READ);
window.Eye = {
getRow: function(history) {
return `<tr>
<td style="width:100px">${history.date}</td>
<td style="width:100px">${history.result}</td>
</tr>`;
},
load: function () {
$.ajax({
url: API_URL.READ,
method: "GET"
}).done(function (histories) {
console.info('done:', histories);
Eye.display(histories);
})
},
display: function(histories) {
window.histories = histories;
var rows = '';
histories.forEach(history => rows += Eye.getRow(history));
$('#performance tbody').html(rows);
}
};
console.info('loading histories');
console.log("cookie = "+document.cookie);
Eye.load(); |
import moment from 'moment';
const convertISOString = ({
hour, minute, second
}) => (
moment
.duration(second, 'seconds')
.add(minute, 'minutes')
.add(hour, 'hours')
.toISOString()
)
export default convertISOString
|
const init_auto_comlete=function (){
const Input=(function(){
function Input(select_el,controll,delault_v){
this.select_el=select_el;
this.controll=controll;
this.delault_v=delault_v;
this.input;
this.values;
this.Tr;
this.Html;
}
Input.prototype.init_focus=function(){
this.select_el.addEventListener('focus',this.activInput.bind(this));
}
Input.prototype.cls_click=function(){
this.select_el.addEventListener('click',function(){
this.value="";
});
}
Input.prototype.activInput=function(e){
if(this.input==e.target)return;//cls mullti call
this.input=e.target;
e.target.addEventListener('keyup',this.getValue.bind(this));
}
Input.prototype.cls_tr_go=function(e){
if(!this.Tr)return;
else{
this.Tr.tab_refere();
}
}
Input.prototype.set_Html=function(Html){
this.Html=Html;
}
Input.prototype.getValue=function(e){
this.controll.fetch_value(this.values=e.target.value);
//ajax.execute({v:this.value});
}
Input.prototype.setValue=function(value_target){
if(typeof value_target =='string'){
return this.input.value=value_target;
}else {
this.input.value='';
}
};
return Input;
})();
const Controll=(function(){
function Controll(obj_array,html,char_len){
this.obj_array=obj_array;
this.html=html;
this.char_len=char_len;
this.string;
}
Controll.prototype.switch_=function(){
if(Array.isArray(this.obj_array)){
const serch_array=this.Serch_array();
}else{
this.search_obj()
}
}
Controll.prototype.search_obj=function(){
let array_result=[];
let label_result=[];
let reg_exp=new RegExp(this.string,"gi");
for(let i in this.obj_array.ona){
if(reg_exp.exec(this.obj_array.ona[i].name)){
array_result.push(this.obj_array.ona[i].name);
label_result.push(this.obj_array.ona[i].nr_g);
}
}
this.send_array(array_result,label_result);
}
Controll.prototype.fetch_value=function(string){
this.string=string;
this.switch_();
}
Controll.prototype.Serch_array=function(){
let array_result=this.obj_array.filter(function(v){
if(this.string.length>=this.char_len){
let reg_exp=new RegExp(this.string,"gi");
return reg_exp.exec(v);
}else{return}
}.bind(this));
this.send_array(array_result,null);
}
Controll.prototype.send_array=function(array,label_result){
this.html.dowland(array,label_result);
}
return Controll;
})();
const Create_html=(function(){
function Get_ele(id){
this.wraper=id;
this.list;
this.Inp;
this.result_value;
this.nr_row;
this.Column;
}
Get_ele.prototype.select_el=function(wraper){
this.wraper=document.querySelector('#wrap_'+this.nr_row);
}
Get_ele.prototype.dowland=function(array,label_result){
this.behavior_list(array,label_result);
}
Get_ele.prototype.behavior_list=function(array,label_result){
if(array.length){
if(this.list){
this.list.remove();
this.create(array,label_result);
}else if(!this.list){
this.create(array,label_result);
}else return;
}else if(!array.length)
if(this.list){
this.list.remove()
}
else if(!this.list)return;
}
Get_ele.prototype.create=function(array,label_result){
let ul=document.createElement('ul');
array.map(function(v,i){
let li=document.createElement('li');
li.textContent=(v);
ul.appendChild(li);
})
this.list=ul;
this.show();
};
Get_ele.prototype.show=function(){
this.wraper.appendChild(this.list);
this.Events_list();
}
Get_ele.prototype.Events_list=function(){
this.list.addEventListener('click',this.mouseClick.bind(this));
this.list.addEventListener('mouseover',this.mouseOver.bind(this));
this.list.addEventListener('mouseleave',this.mouseLeave.bind(this));
}
Get_ele.prototype.removeEvent=function(e){
this.list.removeEventListener('mouseover',this.mouseOver);
this.list.removeEventListener('click',this.mouseClick);
this.list.removeEventListener('mouseleave',this.mouseLeave);
}
Get_ele.prototype.get_obj_inp=function(Input){
this.Inp=Input;
}
Get_ele.prototype.getCol=function(Column){
if(!Column)return;
this.Column=Column;
}
Get_ele.prototype.mouseClick=function(e){
this.fixt_value(e);
this.removeEvent();
this.clear_list();
this.refresh();
this.column(e)
}
Get_ele.prototype.mouseOver=function(e){this.fixt_value(e)}
Get_ele.prototype.mouseLeave=function(){this.Inp.setValue(this.Inp.values);this.removeEvent();this.clear_list();
}
Get_ele.prototype.fixt_value=function(e){
if(e.target.matches('li'))this.result_value=this.Inp.setValue(e.target.textContent);
}
Get_ele.prototype.column=function(e){
this.Column.search_val(e);
}
Get_ele.prototype.refresh=function(){
this.Column.remove_tr();
}
Get_ele.prototype.clear_list=function(){
this.list.remove();
}
return Get_ele
})();
const Column=(function(){
function Column(tbody){
console.log()
this.columns=tbody.querySelectorAll('tr>td:nth-child(9n+2)');
this.tr=tbody.querySelectorAll('tr');
this.beack=document.querySelector('#disp_block');
}
Column.prototype.column=function(){
let arr_valu=[];
for(td of this.columns){
arr_valu.push(td.textContent);
}
return arr_valu;
}
Column.prototype.search_val=function(e){
Array.prototype.map.call(this.columns,(v,i)=>{
if(v.textContent!==e.target.textContent)this.tr[i+1].style.display="none";
else{return}
})
}
Column.prototype.init_back=function(){
this.beack.addEventListener('click',this.remove_tr.bind(this))
}
Column.prototype.remove_tr=function(){
for(tr of this.tr){
tr.style.display="table-row";
}
}
return Column;
})();
let column=new Column(document.querySelectorAll('#window_all>table>tbody')[0]);
let html=new Create_html(document.querySelector('#tab'));
let controll=new Controll(column.column(),html,1);
let inp=new Input(document.querySelectorAll('#tab>input')[0],controll,'pierwszy');
html.getCol(column);
html.get_obj_inp(inp);
inp.init_focus();
inp.cls_click();
column.init_back();
}
|
import React from 'react';
import { View, Text, StyleSheet, ActivityIndicator, ScrollView } from 'react-native';
import { Image, Button } from 'react-native-elements';
import BootstrapStyleSheet from 'react-native-bootstrap-styles';
import Tts from 'react-native-tts';
import Icon from 'react-native-vector-icons/FontAwesome';
import UrlGlobal from '../providers/Global';
const bootstrapStyleSheet = new BootstrapStyleSheet();
const { s, c } = bootstrapStyleSheet;
class DetalleDocente extends React.Component {
generarVoz(texto) {
Tts.speak(texto);
}
render() {
const { params } = this.props.route
return (
<ScrollView>
<View style={styles.container}>
<Image source={{ uri: UrlGlobal.urlArchivos+params.foto }} style={styles.imageDocente} PlaceholderContent={<ActivityIndicator />} />
<View style={styles.containerBody}>
<Button
title=" Escuchar"
type="outline"
icon={
<Icon
name="volume-up"
size={15}
color="#2196F3" />
}
onPress={() => {
let docente = params.nombres + " docente de la carrera de ingeniería en sistemas de información ";
let formacion = " Su formación académica es : " + params.formacion_academica;
let experiencia = "Se desempeño : " + params.experiencia_laboral;
this.generarVoz(docente + formacion + experiencia) }
}
/>
<Text style={styles.textEmail}>{params.email}</Text>
<Text style={[s.fontWeightBold, styles.titulo]}>Formación académica</Text>
<Text style={styles.textFormacion}>{params.formacion_academica}</Text>
<Text style={[s.fontWeightBold, styles.titulo]}>Experiencia laboral</Text>
<Text style={styles.textFormacion}>{params.experiencia_laboral}</Text>
</View>
</View>
</ScrollView>
);
}
}
export default DetalleDocente;
const styles = StyleSheet.create({
container: {
padding: 20
},
imageDocente: {
height: 250,
width: 'auto',
},
textEmail: {
fontSize: 17,
marginTop:5
},
containerBody: {
backgroundColor: '#fff',
marginTop: 15,
padding: 10
},
titulo: {
fontSize: 17,
marginTop: 20,
color: '#49494E'
},
textFormacion: {
fontSize: 15,
textAlign: 'justify',
}
})
|
import React from "react";
const Country = ({ country, setQuery }) => (
<div>
<h2>{country.name}</h2>
<p>capital {country.capital}</p>
<p>population {country.population}</p>
<h3>languages</h3>
<ul>
{country.languages.map(l => <li key={l.iso639_1}>{l.name}</li>)}
</ul>
<img src={country.flag} height="120" alt={`flag of ${country.name}`}/>
<br />
</div>
)
export default Country |
import { css } from 'styled-components';
import fonts from './fonts';
const common = css`
margin: 0;
padding: 0;
`;
const display = css`
font-size: 6rem;
line-height: 6.5rem;
font-weight: 700;
text-transform: uppercase;
${common}
font-family: ${fonts.saira};
`;
const h2 = css`
font-size: 3.5rem;
line-height: 4rem;
font-weight: 700;
text-transform: uppercase;
${common}
font-family: ${fonts.saira};
`;
const h3 = css`
font-size: 1.75rem;
line-height: 2rem;
font-weight: 700;
text-transform: uppercase;
${common}
font-family: ${fonts.saira};
`;
const lead = css`
font-size: 1.35rem;
line-height: 1.5rem;
font-weight: 500;
text-transform: uppercase;
${common}
font-family: ${fonts.saira};
`;
const regular = css`
font-size: 1rem;
line-height: 1.5rem;
font-weight: 400;
${common}
font-family: ${fonts.openSans};
`;
export default {
display,
h2,
h3,
lead,
regular,
};
|
'use strict';
const url = require('url');
const querystring = require('querystring');
const expressionsToMatch = [{
regex: /devEnv=(dev\d*|staging|qa\d*)/,
onMatch: (match) => ({ devMode: true, devEnv: match[1] })
}, {
regex: /releaseChannel=(beta|prod)/,
onMatch: (match) => ({ releaseChannel: match[1] })
}, {
regex: /openDevToolsOnStart/,
onMatch: () => ({ openDevToolsOnStart: true })
}, {
regex: /notReallyWindows10/,
onMatch: () => ({ pretendNotReallyWindows10: true })
}, {
regex: /magic-login/,
onMatch: parseMagicLoginUrl
}, {
regex: /\?(feature_.*=1)|(pri=\d*)/,
onMatch: (match, theUrl) => ({
webappParams: querystring.parse(theUrl.query)
})
}];
/**
* Parses a slack: protocol URL looking for certain items.
*
* @param {String} protoUrl The URL to parse
*
* @returns An {Object} that may contain any of the following keys:
*
* devMode - True if running in developer mode, which exposes devTools
* devEnv - The dev environment we are pointed at, e.g., 'dev13'
* releaseChannel - The release channel we are using, 'beta' or 'prod'
* magicLogin - An object with magic login details: the teamId and token
* openDevToolsOnStart - True to open devTools on app start
* pretendNotReallyWindows10 - True to act like older versions of Windows
* webappParams - An object with query parameters to forward to the webapp
*/
function parseProtocolUrl(protoUrl) {
protoUrl = protoUrl || '';
const theUrl = url.parse(protoUrl);
if (theUrl.protocol !== 'slack:') return {};
return expressionsToMatch.reduce((result, { regex, onMatch }) => {
const match = protoUrl.match(regex);
if (match) result = Object.assign(result, onMatch(match, theUrl));
return result;
}, {});
}
function parseMagicLoginUrl(match, theUrl) {
const teamId = theUrl.host.toUpperCase();
const pathComponents = theUrl.path.split('/');
if (teamId.match(/T[A-Z0-9]{8}/) &&
pathComponents.length === 3 &&
pathComponents[1].match(/magic-login/)) {
const magicLogin = {
teamId: teamId,
token: pathComponents[2]
};
return { magicLogin };
}
}
module.exports = { parseProtocolUrl };
|
function Renderer_Parcometro() {
};
Renderer_Parcometro.prototype.reset = function(container) {
if (container == undefined) {
container = containerParcometro;
}
container.empty();
};
Renderer_Parcometro.prototype.render = function(add, data, container) {
if (add) {
var li = $("#" + data['id']);
if (li.length == 0) {
li = $('<tr></tr>').addClass('elements');
li.attr('id', data['id']);
var span = $('<span></span>');
span.text(data['code']);
var action = $('<a></a>');
action.append($('<img></img>').attr('src', 'imgs/details.ico'))
.attr('alt', 'dettagli').attr('title', 'dettagli');
action.attr('href', '#');
action.click(function() {
map.setCenter(new google.maps.LatLng(data['geometry']['lat'],
data['geometry']['lng']), zoomToLevel);
parcometriGeo[data['id']].setMap(map);
google.maps.event.trigger(parcometriGeo[data['id']], 'click');
});
li.append($('<td></td>').attr('width', '16px').append(
$('<div></div>')
.attr('title', aree[data['areaId']]['name'])
.addClass('color-div').css('background-color',
'#' + aree[data['areaId']]['color'])));
li.append($('<td></td>').attr('width', '80%').append(span));
if (data['status'] == 'INACTIVE') {
li.append($('<td></td>').attr('width', '16px').append(
$('<img></img>').attr('src', 'imgs/status-off.ico')
.attr('alt', 'non attivo').attr('title',
'non attivo')));
} else {
li
.append($('<td></td>').attr('width', '16px').append(
$('<img></img>').attr('src',
'imgs/status-on.ico').attr('alt',
'attivo').attr('title', 'attivo')));
}
li.append($('<td></td>').attr('width', '10%').append(action));
if (container == undefined) {
container = containerParcometro;
}
container.append(li);
} else {
li.children('td:first').children('div').attr('title',
aree[data['areaId']]['name']).addClass('color-div').css(
'background-color', '#' + aree[data['areaId']]['color']);
if (data['status'] == 'INACTIVE') {
li.children('td:first').next().next().children('img').attr(
'src', 'imgs/status-off.ico').attr('alt', 'non attivo')
.attr('title', 'non attivo');
} else {
li.children('td:first').next().next().children('img').attr(
'src', 'imgs/status-on.ico').attr('alt', 'attivo')
.attr('title', 'attivo');
}
li.children('td:first').next().children('span').text(data['code']);
}
} else {
var li = $("#" + data);
li.remove();
}
$("tr.elements:even").css("background-color", "#6eb4e9");
$("tr.elements:odd").css("background-color", "#add6f5");
};
// RENDER SAMPLE
// <li id="#id"><span>Parcometro 1<a href="">dettagli</a></span>
// </li>
Renderer_Parcometro.prototype.updateGeo = function(marker, data) {
marker.setMap(null);
data['color'] = aree[data['areaId']]['color'];
rendererParcometro.renderGeo(false, data, false);
};
Renderer_Parcometro.prototype.renderGeo = function(modeEdit, data, open) {
var width =16;
var height = 26;
var position = new google.maps.LatLng(((data != null) ? data['geometry']['lat'] : lat),
((data != null) ? data['geometry']['lng'] : lng));
var marker = new google.maps.Marker({
icon: {
url: baseUrl+'/rest/marker/'+company+'/parcometro/'+((data['color'] != null) ? data['color'] : defaultMarkerColor),
ancor: new google.maps.Point(width / 2, height)
},
position: position,
draggable: modeEdit,
map: map
});
if (data['id'] != null) {
parcometriGeo[data['id']] = marker;
} else {
tempGeo[tempIndex] = marker;
data['tempId'] = tempIndex;
tempIndex++;
}
if (modeEdit) {
google.maps.event.addListener(marker, 'dragstart', function() {
if (infowindow) {
infowindow.close();
}
});
}
google.maps.event.addListener(marker, 'click', function() {
rendererParcometro.popup(modeEdit, (data['id'] != null) ? parcometri[data['id']] : data, marker);
});
if (modeEdit) {
google.maps.event.addListener(marker, "dragend", function() {
var info;
if (data['id'] != null) {
info = parcometri[data['id']];
} else {
info = data;
}
info['geometry']['lat'] = marker.position.lat();
info['geometry']['lng'] = marker.position.lng();
google.maps.event.trigger(marker, 'click');
});
}
if (open) {
google.maps.event.trigger(marker, 'click');
}
};
Renderer_Parcometro.prototype.updatePopup = function(modeEdit, data) {
if (!!infowindow) {
rendererParcometro.popup(modeEdit, data, infowindow.getPosition());
}
};
Renderer_Parcometro.prototype.popup = function(modeEdit, data, marker) {
var renderPopup = function(modeEdit, data) {
var popup = '';
if (modeEdit) {
var areeCombo = '<select name="parcometro_area">';
areeCombo += '<option value=""></option>';
$
.each(
aree,
function(key, value) {
areeCombo += '<option value="'
+ this['id']
+ '"'
+ ((data['areaId'] != undefined && data['areaId'] == this['id']) ? ' selected="selected"'
: '') + '>' + this['name']
+ '</option>';
});
areeCombo += '</select>';
var status = '<select name="parcometro_status">';
status += '<option value=""></option>';
$
.each(
parcometroStatus,
function(key, value) {
status += '<option value="'
+ key
+ '"'
+ ((data['status'] != undefined && data['status'] == key) ? ' selected="selected"'
: '') + '>' + value + '</option>';
});
status += ' </select>';
popup = '<div style="width:200px;">'
+ parcometroLabels['code']+' <label id="parcometro_code_msg" class="errorMsg"></label> <input name="parcometro_code" type="text" value="'
+ ((data['code'] != undefined) ? data['code'] : "")
+ '"/>'
+ '<br/>'
+ 'Posizione<br/>'
+ data['geometry']['lat']
+ ','
+ data['geometry']['lng']
+ '<br/>'
+ parcometroLabels['note']
+ ' <label id="parcometro_note_msg" class="errorMsg"></label><textarea class="note" name="parcometro_note" >'
+ ((data['note'] != undefined) ? data['note'] : "")
+ '</textarea>'
+ parcometroLabels['status']
+ ' <label id="parcometro_status_msg" class="errorMsg"></label>'
+ status + parcometroLabels['areaId']
+ ' <label id="parcometro_area_msg" class="errorMsg"></label>'
+ areeCombo
+ '<input name="parcometro_id" type="hidden" value="'
+ ((data['id'] != undefined) ? data['id'] : "") + '"/>'
+ '<input name="parcometro_tempId" type="hidden" value="'
+ ((data['tempId'] != undefined) ? data['tempId'] : "") + '"/>'
+ '<input name="parcometro_areaId" type="hidden" value="'
+ ((data['areaId'] != undefined) ? data['areaId'] : "") + '"/>'
+ '<input name="parcometro_coord" type="hidden" value="'
+ data['geometry']['lat'] + ',' + data['geometry']['lng']
+ '"/>'
+ '<hr/><a href="#" onclick="saveParcometro();">Salva</a>'
+ ' <a href="#" onclick="removeParcometro();">Elimina</a>'
+ '</div>';
} else {
popup = '<div style="width:200px;">'
+ '<p class="title-popup">'+parcometroLabels['code']+'</p>'
+ data['code']
+ '<p class="title-popup">Posizione</p>'
+ data['geometry']['lat']
+ ','
+ data['geometry']['lng']
+ '<br/>'
+ (data['note'] ? '<p class="title-popup">'
+ parcometroLabels['note'] + '</p>'
+ data['note'].replace(/\n/g, '<br/>') : '')
+ '<br/><br/>'
+ rendererArea.renderPopupDetails(aree[data['areaId']])
+ '</div><input name="parcometro_id" type="hidden" value="'
+ ((data['id'] != undefined) ? data['id'] : "")
+ '"/>'
+ '<hr/><a href="#" onclick="editParcometro();">Modifica</a>'
+ '</div>';
}
return popup;
};
if (!!infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow(
{
content: renderPopup(modeEdit, data)
});
infowindow.open(map, marker);
}; |
var core = new Core({ debug: true });
/**
*
*
*/
function initApp() {
core.installModules(function () {
//you script here
console.debug("Scripts loaded");
utils.load();
});
}
document.addEventListener('DOMContentLoaded', initApp);
|
import React, { useEffect } from "react";
import { connect } from "react-redux";
import Sidebar from "../../components/Sidebar/Sidebar";
import { StyledDashboard } from "./Dashboard.styled";
import { Switch, Route } from "react-router-dom";
import UserProfile from "../../components/UserProfile/UserProfile";
function Dashboard(props) {
let { history, user, match } = props;
useEffect(() => {
if (!user) {
history.push("/");
}
}, [history, user]);
return (
<StyledDashboard>
<div className="sidebar-container">
<Sidebar />
</div>
<div className="user-panel">
<Switch>
<Route exact path={`${match.path}`} component={UserProfile} />
</Switch>
</div>
</StyledDashboard>
);
}
let mapStateToProps = (state) => {
return {
user: state.authState.user,
};
};
export default connect(mapStateToProps)(Dashboard);
|
function emptyObj (obj) {
return Object.entries(obj)
.every(([, val]) => val === '')
}
module.exports = (invoice) => {
const unicodeMinus = '\u2212'
// Recipient newline
const recipientAddressTooLong = Object
.values(invoice.to.address)
.join()
.length > 50
const rnl = recipientAddressTooLong ? '\\\\' : ''
let discountValue = ''
if (invoice.discount) {
discountValue = invoice.discount.type === 'fixed'
? `${invoice.discount.value} €`
: invoice.discount.type === 'proportionate'
? `${invoice.discount.value * 100} \\%`
: `ERROR: ${invoice.discount.type} is no valid discount type`
}
/* eslint-disable indent */
return `
---
title: \\vspace{-5ex} Invoice
---
-------------- --------------
Invoice ID: **${invoice.id}**
Issuing Date: **${invoice.issuingDate
.toISOString()
.substr(0, 10)}**
Delivery Date: **${invoice.deliveryDate
.toISOString()
.substr(0, 10)}**
-----------------------------
\\begin{multicols}{2}
\\subsection{Invoice Recipient}
${invoice.to.name} \\\\
${invoice.to.organization ? `${invoice.to.organization}\\\\` : '\\'}
${invoice.to.address.country ? `${invoice.to.address.country},` : ''}
${invoice.to.address.city && invoice.to.address.zip
? `${invoice.to.address.city} ${invoice.to.address.zip}, ${rnl}`
: ''
}
${invoice.to.address.street} ${invoice.to.address.number} ${
invoice.to.address.addition
? `/ ${invoice.to.address.addition.replace('#', '\\#')}`
// TODO: Escape all special LaTeX characters
: ''
} ${emptyObj(invoice.to.address) ? '' : '\\\\'}
${invoice.to.vatin ? 'Tax ID Number: ' + invoice.to.vatin : ''}
\\columnbreak
\\subsection{Biller}
${invoice.from.name}
${Array.isArray(invoice.from.emails)
? `([${invoice.from.emails[0]}](mailto:${invoice.from.emails[0]}))`
: ''
} \\\\
${invoice.from.job ? `${invoice.from.job}\\\\` : '\\'}
${invoice.from.address.country},
${invoice.from.address.city} ${invoice.from.address.zip},
${invoice.from.address.street} ${invoice.from.address.number}\
${invoice.from.address.flat
? '/' + invoice.from.address.flat
: ''
} \\\\
${invoice.from.vatin ? 'Tax ID Number: ' + invoice.from.vatin : ''}
\\end{multicols}
## Items
${invoice.taskTable}
\\begin{flushright}
${invoice.totalDuration
? `Total working time: ${invoice.totalDuration} min`
: ''
}
${invoice.discount || invoice.vat
? `Subtotal:\\qquad${invoice.subTotal.toFixed(2)} €\n\n`
: ''
}
${invoice.discount
? `Discount of ${discountValue}
${invoice.discount.reason
? `(${invoice.discount.reason}):\\qquad`
: ''
} ${unicodeMinus}${invoice.discount.amount.toFixed(2)} €`
: ''
}
${invoice.vat
? `VAT of ${invoice.vat * 100} \\%:\\qquad` +
`${invoice.tax.toFixed(2)} €`
: invoice.vatid && !invoice.vatid.startsWith('DE')
? 'Reverse Charge'
: ''
}
\\textbf{Total amount:\\qquad${invoice.total.toFixed(2)}}
${'\\textbf{€}' /* TODO: Also underline € sign */}
\\end{flushright}
${invoice.from.smallBusiness
? 'The amount is without tax as this is a small business.'
: ''
}
Please transfer the money onto following bank account due to
**${invoice.dueDate
.toISOString()
.substr(0, 10)
}**:
--------- ---------------------
Owner: **${invoice.from.name}**
IBAN: **${invoice.from.iban}**
-------------------------------
Thank you for the good cooperation!
`
}
|
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
width: 0, // 浏览器宽度
height: 0, // 浏览器高度
stories: [], // 新闻内容数组
ids: [], // 新闻id数组
id: '' // 当前新闻详情的id
},
getters: {
collectText: state => {
return state.isCollect ? '取消收藏' : '收藏';
}
},
mutations: {
// 初始化浏览器尺寸
}
});
|
import React, { useContext } from 'react';
import {
Button,
Image,
Spinner
} from 'react-bootstrap';
import AuthContext from './../../contexts/AuthContext';
function NavbarProfile() {
const {
isProfileLoading,
profile,
logout
} = useContext(AuthContext);
const handleLogoutClick = () => logout();
return (
<div>
{isProfileLoading && (
<Spinner
animation="grow"
role="status"
size="sm"
>
<span className="sr-only">Загрузка...</span>
</Spinner>
)}
{!isProfileLoading && profile && (
<>
<span className="mr-2">{profile.name}</span>
<Image
className="mr-2"
roundedCircle
src={profile.avatar}
/>
<Button
variant="outline-danger"
onClick={handleLogoutClick}
>
Logout
</Button>
</>
)}
</div>
);
}
export default NavbarProfile;
|
"use strict";
angular.module("GolfClub").controller("InfoCtrl", ["$scope", "$location", function ($scope, $location) {
var params = $location.search();
$scope.lt.page = $location.path();
$scope.reservationData = [];
$scope.resourcesData = [];
$scope.info = {
loadingData: true,
currentDate: new Date(params.startDate),
date: GolfClub.getDateForView(params)
};
$scope.club = null;
$scope.position = { at: 'bottom', offset: '-116 175', of: '.green-button' };
GolfClub.stores.clubs
.byKey(parseInt(params.clubId), { expand: ["City", "Reservations"] })
.done(function (data) {
data.Price = Globalize.formatCurrency(parseInt(data.Price), "USD", { maximumFractionDigits: 0 });
$scope.club = data;
GolfClub.getDataForScheduler($scope, [data], params.startDate);
$scope.info.loadingData = false;
$(".responsive-info").dxResponsiveBox("instance").repaint();
$scope.$apply();
});
}]);
|
import UtilQS from 'qs';
import UtilDom from './utils/util_dom.js';
import UtilUrl from './utils/util_url.js';
import UtilRecurse from './utils/util_recurse.js';
import UtilFilter from './utils/util_filter.js';
import UtilCrypto from './utils/util_crypto.js';
import UtilStorage from './utils/util_storage.js';
import UtilDebouncer from './utils/util_debounce.js';
import UtilComm from './utils/util_comm.js';
import UtilBlade from './utils/util_blade.js';
export default {
UtilQS,
UtilDom,
UtilUrl,
UtilRecurse,
UtilFilter,
UtilCrypto,
UtilStorage,
UtilDebouncer,
UtilComm,
UtilBlade,
};
|
(function(root, $) {
if (!$) {
alert("jQuery未加载");
return;
}
var dm = root.dm = function() {}; //向全局对象添加dm属性
if (!root.Object.create)
dm.create = function(o) {
var F = function() {};
F.prototype = o;
return new F();
};
else
dm.create = root.Object.create; //对象生成器
(function() {
dm.klass = function(Parent, props) {
var Child, i;
var F;
Child = function() {
/*Child函数内必须手动调用构造函数*/
if (Child.prototype.hasOwnProperty("__construct")) {
Child.prototype.__construct.apply(this, arguments);
} else {
if (Child.superKlass && Child.superKlass.hasOwnProperty("__construct")) {
Child.superKlass.__construct.apply(this, arguments);
//Child.superKlass指向parent的原型
}
}
};
//构造函数内判断__construct
Parent = Parent || Object;
if (Parent !== Object) {
if (typeof Parent == "object") {
F = function() {};
F.prototype = Parent;
Child.prototype = new F();
Child.superKlass = Parent;
} else if (typeof Parent == "function") {
F = function() {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.superKlass = Parent.prototype;
}
}
// 继承
Child.prototype.constructor = Child;
// 将props中的属性放到Child原形中
for (i in props) {
if (props.hasOwnProperty(i))
Child.prototype[i] = props[i];
}
return Child;
};
dm.klass.extend = function(currentClass, ex) {
var toString = Object.prototype.toString;
var proto = currentClass.prototype,
p;
if (toString.call(ex) == "[object Object]")
for (p in ex) {
if (ex.hasOwnProperty(p))
proto[p] = ex[p];
}
if (typeof ex == "function") {
var _p = ex.prototype;
for (p in _p) {
proto[p] = _p[p];
}
}
};
})();
(function() {
/*
*/
var e = dm.event = {};
e.create = function() {
return new EventsHandler(); //内置一个dom无关事件处理
};
function EventsHandler() {
this._callbacks = {}; //事件表
}
var ep = EventsHandler.prototype;
ep.on = function(event, callback) {
/*
@param string event 事件名称,如果要以命名空间形式,分隔符为:
例如a:b:c
@param function callback 事件触发后的回调函数*/
(this._callbacks[event] || (this._callbacks[event] = [])).push(callback);
return this;
}; //注册一个事件
ep.emit = function() {
/*
@param string arguments[0] 事件名称,如果要以命名空间形式,分隔符为:
例如a:b:c
@param function arguments[0]... 传入事件处理函数的参数*/
var args = Array.prototype.slice.call(arguments, 0),
ev = args.shift();
var list;
if (!(list = this._callbacks[ev])) return this;
for (var i = 0, j = list.length; i < j; i++)
list[i].apply(null, args);
return this;
}; //触发一个事件
ep.off = function(events) {
var c = this._callbacks;
if (!events) {
for (var p in c)
delete c[p];
return this;
} //删除所有事件
if (Object.prototype.toString.call(events) == "[object Array]")
for (var i = 0, j = events.length; i < j; i++) {
delete c[events[i]];
} //移除列表中指定事件
if (typeof events == "string")
delete c[events];
return this;
}; //移除一个事件
})(); //Events类
(function() {
dm.SandBox = function() {
/*
* 参数至少包含一个factory函数,
* 且factory至少包含一个参数用于导出,放在最后面*/
var args = Array.prototype.slice.call(arguments, 0),
callback,
length = args.length;
if (length == 1) {
//此时是有factory参数为一个无参匿名函数
callback = args.pop();
return callback.call(null);
} else if (length == 2 && (Object.prototype.toString.call(args[0]) == "[object Array]")) {
callback = args.pop();
return callback.apply(null, args[0]);
} else {
callback = args.pop();
return callback.apply(null, args);
}
};
})(); //沙箱类
var r = {
addRouter: function(name, factory) {
/*
* @param String name 路由名称
* @param Function factory 路由函数;
该函数需要形参context:对当前this的引用
* @return Object this 返回当前对象;
* */
var routerStore = this.routerStore;
var SandBox = dm.SandBox;
var args = Array.prototype.slice.call(arguments, 0);
var i, j, currentList;
if (args.length == 1 && (Object.prototype.toString.call(args[0]) == "[object Object]")) {
for (var p in args[0]) {
routerStore[p] = SandBox(this, args[0][p]);
}
return this;
} //
if (args.length == 2) {
routerStore[name] = SandBox(this, factory);
return this;
}
}, //
removeRouter: function() {
var p, routerStore = this.routerStore,
tmp;
if (arguments.length == 0) {
for (p in routerStore)
delete routerStore[p];
return this;
} //没有参数时删除所有ROUTER
var args = Array.prototype.slice.call(arguments),
length = args.length;
if ((Object.prototype.toString.call(args[0]) == "[object Array]"))
tmp = args[0];
if (length >= 1 && (typeof args[0] == "string"))
tmp = args;
for (var i = 0, j = tmp.length; i < j; i++)
delete routerStore[tmp[i]];
return this;
} //父ROUTER,需要被view,controller,model继承
};
(function() {
var Controller = dm.klass(r, {
__construct: function(config) {
/*
* @param Object config 配置,
* 格式:{[optional,Object]domStore,[optional,Object]events}*/
var configEv;
this.domStore = config ? (config.domStore ? config.domStore : {}) : {};
this.routerStore = {}; //存放router名与内部沙箱导出对象映射
var ev = this.events = dm.event.create();
if (config)
if (config.events) {
configEv = config.events;
for (var p in configEv)
ev.on(p, configEv[p]);
}
},
addDom: function() {
var args = Array.prototype.slice.call(arguments, 0);
var p;
if ((args.length == 1) && (typeof args[0] == "object")) {
for (p in args[0])
this.domStore[p] = args[0][p];
}
if (args.length == 2)
this.domStore[args[0]] = args[1];
return this;
},
removeDom: function() {
var args = Array.prototype.slice.call(arguments, 0),
d = this.domStore;
if (arguments.length == 0) {
for (var p in d)
delete d[p];
return this;
}
var i, j, tmp;
if ((Object.prototype.toString.call(args[0]) == "[object Array]")) {
tmp = args[0];
for (i = 0, j = tmp.length; i < j; i++)
delete d[tmp[i]];
}
if (args.length >= 1 && (typeof args[0] == "string")) {
for (i = 0, j = args.length; i < j; i++)
delete d[args[i]];
}
return this;
},
addEvent: function() {
var args = Array.prototype.slice.call(arguments, 0);
var p, ev = this.events;
if (args.length == 1 && (typeof args[0] == "object"))
for (p in args[0])
ev.on(p, args[0][p]);
if (args.length == 2) {
if ((typeof args[0] == 'string') && (typeof args[1] == "function"))
ev.on(args[0], args[1]);
}
return this;
},
removeEvent: function() {
if (arguments.length == 0) {
this.events.off();
return this;
}
var args = Array.prototype.slice.call(arguments, 0),
length = args.length;
var ev = this.events;
if (length == 1 && (Object.prototype.toString.call(args[0]) == "[object Array]")) {
ev.off(args[0]);
return this;
}
if (length == 1 && (typeof args[0] == 'string')) {
ev.off(args[0]);
return this;
}
if (length > 1) {
ev.off(args);
return this;
}
}
});
dm.Controller = Controller;
})(); //Controller类
(function() {
/*
* model要使用事件之前必须与至少一个控制器绑定*/
var Model = dm.klass(r, {
__construct: function(request) {
/*
* @param Object request 请求函数存储{funcName:'',func:function(){}}*/
this.events = undefined;
this.record = {};
this.routerStore = {}; //提供路由存储
this.requestStore = request || {};
},
addRecord: function() {
var args = Array.prototype.slice.call(arguments, 0),
length = args.length;
var record = this.record;
if (length == 1 && (Object.prototype.toString.call(args[0]) == "[object Object]")) {
for (var p in args[0])
record[p] = args[0][p];
return this;
}
if (length == 2 && (typeof args[0] == "string")) {
record[args[0]] = args[1];
return this;
}
},
removeRecord: function() {
var p, record = this.record,
args, length, i, j;
if (arguments.length == 0) {
for (p in record)
delete record[p];
return this;
}
args = Array.prototype.slice.call(arguments, 0);
length = args.length;
if (length == 1 && (Object.prototype.toString.call(args[0]) == "[object Array]")) {
for (i = 0, j = args[0].length; i < j; i++)
delete record[args[0][i]];
return this;
}
for (i = 0, j = args.length; i < j; i++)
delete record[args[i]];
return this;
},
fetchData: function(options) {
/*options:{reqWay:"get/post",reqUrl:"url",
reqData:"data",
reqDone:function(){},
reqFail:function(){},
reqAlways:function(){}
}*/
var way = eval("$." + options.reqWay.toLowerCase()),
req;
req = options.reqData !== undefined ? way(options.reqUrl, options.reqData) : way(options.reqUrl);
//req=way(options.reqUrl,options.reqData);
req.
done(options.reqDone || function() {}).
fail(options.reqFail || function() {}).
always(options.reqAlways || function() {});
},
addRequest: function() {
var args = Array.prototype.slice.call(arguments, 0);
var requestStore = this.requestStore;
if (args.length == 1 && (Object.prototype.toString.call(args[0]) == "[object Object]")) {
for (var p in args[0])
requestStore[p] = args[0][p];
return this;
}
if (args.length == 2 && (typeof args[0] == "string")) {
requestStore[args[0]] = args[1];
return this;
}
},
removeRequest: function() {
var requestStore = this.requestStore;
var args, length, tmp;
if (arguments.length == 0) {
for (var p in requestStore)
delete requestStore[p];
return this;
}
args = Array.prototype.slice.call(arguments, 0);
length = args.length;
if ((Object.prototype.toString.call(args[0]) == "[object Array]")) {
tmp = args[0];
}
if (length >= 1 && (typeof args[0] == "string"))
tmp = args;
for (var i = 0, j = tmp.length; i < j; i++) {
delete requestStore[tmp[i]];
}
return this;
},
useRequest: function(name) {
/*@param必须提供name*/
var args = Array.prototype.slice.call(arguments, 0);
args.shift();
this.requestStore[name].apply(this, args);
return this;
}
});
dm.Model = Model;
})(); //Model类
(function() {
var View = dm.klass(r, {
__construct: function() {
/*
* @param render Object 渲染器 格式:{name:'',}*/
this.routerStore = {};
this.renderStore = {};
this.events = undefined; //使用事件之前绑定一个控制器
},
addRender: function() {
/*
* 1、@param Array [{name:string,render:function(selector,data){}}...]
* 2、@param string 渲染器名称
* @param function 函数名*/
var args = Array.prototype.slice.call(arguments, 0);
var renderStore = this.renderStore;
var t;
if (Object.prototype.toString.call(args[0]) == "[object Object]") {
t=args[0];
for(var p in t){
if(t.hasOwnProperty(p)){
renderStore[p]=t[p];
}
}
return this;
}
if (args.length == 2) {
renderStore[args[0]] = args[1];
return this;
}
},
removeRender: function() {
var args, length;
var renderStore = this.renderStore;
var tmp;
if (arguments.length == 0) {
for (var p in renderStore)
delete renderStore[p];
return this;
}
args = Array.prototype.slice.call(arguments, 0);
length = args.length;
if (Object.prototype.toString.call(args[0]) == "[object Array]")
tmp = args[0];
if (length >= 1 && (typeof args[0] == "string"))
tmp = args;
for (var i = 0, j = tmp.length; i < j; i++)
delete renderStore[tmp[i]];
return this;
},
useRender: function(name) {
/*
* @param String name 必须提供的渲染器的名称
* */
var args = Array.prototype.slice.call(arguments, 0),
length;
args.shift(); //去除第一个参数
length = args.length;
if (length == 1 && (typeof args[0] == "object")) {
this.renderStore[name].call(this, args[0].selector, args[0].data);
} //第二个参数为对象,包含selector与data两个属性
if (length == 2) {
this.renderStore[name].call(this, args[0], args[1]);
} //第二个参数为selector,第三个参数为data
return this;
}
});
dm.View = View;
})(); //view类
(function() {
dm.connect = function(controller, vom) {
/*@param[must] object controller 必须提供的参数
*@param[must] object vom view or model 必须提供的参数
*@param[optional] array 事件列表,支持以命名空间形式
* e.g: a:b:c or a:*(用来选择命名空间下所有事件)
*/
/*
当参数只有controller 和 vom 时为默认绑定整个事件表,
当指定第三个参数为数组或传入3个以上的字符串列表作为参数时,
绑定列表指定的事件
*/
var args, t, length;
var i, j;
if (arguments.length < 2)
return false;
if (arguments.length > 2) {
args = Array.prototype.slice.call(arguments, 0);
args.splice(0, 2);
// length = args.length;
if ((Object.prototype.toString.call(args[0]) == "[object Array]"))
t = args[0];
else if (typeof args[0] == "string")
t = args; //判断事件列表类型为多个字符串参数
if (t[0] == "*")
return _bindAllEvents(controller, vom) ? this : false;
//绑定所有事件
else
return _bindPartialEvents(controller, vom, t) ? this : false; //绑定部分事件
} //判断事件列表类型为数组
if (arguments.length == 2)
_bindAllEvents(controller, vom);
};
function _bindAllEvents(controller, vom) {
vom.events = controller.events;
return true;
} //绑定controller所有事件
function _bindPartialEvents(controller, vom, evList) {
var e, c_e;
if (evList) {
if (!vom.events)
e = vom.events = dm.event.create();
else
e = vom.events;
c_e = controller.events._callbacks;
for (var i = 0, j = evList.length; i < j; i++) {
if (c_e.hasOwnProperty(evList[i]))
e._callbacks[evList[i]] = c_e[evList[i]];
}
return true;
}
return false;
}
})(); //绑定函数,用于绑定视图与控制器,模型与控制器
(function() {
var libs = dm.libs = {};
dm.registLib = function() {
if (arguments.length == 0)
return false;
var args = Array.prototype.slice.call(arguments, 0);
if (args.length == 1 && (Object.prototype.toString.call(args[0]) == "[object Object]")) {
for (var p in args[0])
libs[p] = args[0][p];
}
if (args.length == 2 && (typeof args[0] == "string")) {
libs[args[0]] = args[1];
}
};
dm.removeLib = function() {
var args = Array.prototype.slice.call(arguments, 0);
var t;
if (Object.prototype.toString.call(args[0]) == "[object Array]") {
t = args[0];
}
if (typeof args[0] == "string") {
t = args;
}
for (var i = 0, j = args.length; i < j; i++) {
if (libs[t[i]])
delete libs[t[i]];
}
};
dm.useLib = function(name) {
/*@param string name 库的名字*/
return libs[name] ? libs[name] : root.undefined;
}
})(); //
})(window, $); //基于导入全局变量 |
const express = require('express');
const router = express.Router();
const bcrypt = require("bcryptjs")
const mongoose = require('mongoose');
const Register = require('../models/register');
const jwt = require('jsonwebtoken');
//Authdata
const Authdata = async (req, res, next) => {
try {
const token = req.cookies.fit;
const verifydata = jwt.verify(token, process.env.secretkey);
const userdata = await Register.findOne({ _id: verifydata._id, "tokens.token": token });
if (!userdata) {
res.status(400).send('Not Authorized');
}
req.userdata = { Userid: userdata.Userid };
next();
} catch (err) {
res.status(400).send('Not Authorized')
}
}
router.post('/feedback', (req, res) => {
res.status(200).redirect('/');
})
//Login and Logout activity
router.post('/register', async (req, res) => {
try {
userid = req.body.userid;
email = req.body.email;
password = req.body.password;
cpassword = req.body.cpassword;
if (userid == "" || email == "" || password == "" || userid.length<5
|| email.length>40 || password!=cpassword || password.length<8) {
res.status(400).send('UnSuccessful');
}
const registerbodybuilder = new Register({
Userid: userid,
Emailid: email,
Password: password
})
// Hashing of password using middle ware means in between two process
const registered = await registerbodybuilder.save();
res.status(200).send('successfully Registered');
} catch (error) {
res.status(400).send('UnSuccessful');
}
})
router.post('/signin', async (req, res) => {
try {
const userid = req.body.userid;
const password = req.body.password;
if (userid == "" || password == "") {
res.status(400).send('UnSuccessful');
}
const infouserid = await Register.findOne({ Userid: userid });
const ismatch = await bcrypt.compare(password, infouserid.Password);
const token = await infouserid.generateAuthToken();
res.cookie('fit', token, {
expires: new Date(Date.now() + 31536000),
httpOnly: true
});
if (ismatch) {
res.status(200).send('Successful');
}
else {
res.status(400).send('UnSuccessful');
}
} catch (e) {
res.status(400).send('UnSuccessful');
}
})
router.get('/signout', async (req, res) => {
try {
const token = req.cookies.fit;
const verifyuser = jwt.verify(token, process.env.secretkey);
const user = await Register.findOne({ _id: verifyuser._id });
res.clearCookie('fit', { path: '/' });
user.tokens = user.tokens.filter((currentcookie) => {
return currentcookie.token != token
})
await user.save();
res.status(200).redirect('/')
} catch (e) {
res.status(400).redirect('/')
}
})
router.get('/Auth', Authdata, (req, res) => {
res.status(200).send(req.userdata);
})
module.exports = router; |
import { RECEIVE_USER_DATA, RECEIVE_DASHBOARDUSER_DATA, RECEIVE_ALLUSER_DATA } from "../actions";
export default (state = {}, { type, data }) => {
switch (type) {
case RECEIVE_USER_DATA:
return {
...state,
userData: data,
}
case RECEIVE_DASHBOARDUSER_DATA:
return {
...state,
userDashbord: data,
}
case RECEIVE_ALLUSER_DATA:
return {
...state,
userList: data,
}
default:
return state;
}
}; |
Package.describe({
summary: "Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript."
});
Package.on_use(function (api, where) {
api.add_files('async/lib/async.js', 'server');
});
|
/* @flow */
/* **********************************************************
* File: utils/dataStreams/textFiles.js
*
* Brief: Opening, reading, and manipulating text files.
*
* Authors: Craig Cheney
*
* 2017.10.25 CC - Document created
*
********************************************************* */
/* Save a text file with optional extension */
export function saveTextFile(
filePath: string, targetData: string, extension?: string = '.txt'
): boolean {
/* Ensure that the correct extension is written */
let fileWithExtension = filePath;
if (!fileWithExtension.endsWith(extension)) {
fileWithExtension += extension;
}
// jetpack.write(filePath, )
}
/* [] - END OF FILE */
|
function getFilterParams(filter = {}) {
return {
date: filter.date || null,
status: filter.status || null,
teachersIds: filter.teachersIds || null,
studentsCount: filter.studentsCount || null,
page: filter.page || 1,
lessonPerPage: filter.lessonPerPage || 5,
}
}
module.exports = {
getFilterParams,
} |
'use strict';
angular.module('myangularApp.util', []);
|
const applicationInfo = require('../_application.json');
const path = require('path');
const logger = require(__loggerPath);
const express = require('express');
const router = express.Router();
const fs = require('fs');
const PageHelper = require('../../../components/helpers/PageHelper');
const BaseCarHelper = require('../helpers/BaseCarHelper');
const FileHelper = require('../../File/helpers/FileHelper');
router.get('/list', function(req, res) {
PageHelper.getPageWithLayout(req, res, "basic", `${__rootPath}/applications/BaseCar/views/BaseCarListView.ejs`);
});
router.get('/data/list', async function(req, res) {
let list;
try {
list = await BaseCarHelper.getBaseCarList(req.query);
for(var i=0;i<list.length;i++) {
var data = list[i];
var file = (await FileHelper.getFileList({useType: 'BASECAR', useVal: data.basecarKey, fileDesc: 'thumbnail'}))[0];
if(file != null) { data.thumbnail = FileHelper.getImageDownloadUrl(file.fileKey); }
}
} catch(e) {
logger.error(e);
res.json({result: false});
throw e;
}
res.json(list);
});
module.exports = router;
|
import { stringify } from 'querystring';
import { router } from 'umi';
import { getPageQuery } from '@/utils/utils';
export const HOST = 'http://www.qinguanghui.com'
// export const HOST = ''
// export const HOST = 'http://localhost:7001'
/**
* 检查是否具有权限
* 返回值: 没有权限返回空, 有权限,返回应该添加的 header 值
*/
export const authHeader = () => {
let token = localStorage.getItem('token')
if (token) {
return {
headers: {
'Authorization': `Bearer ${token}`
}
}
} else {
return {}
}
} |
import tw from 'tailwind-styled-components'
export const NavigationItemLiner = tw.div`
flex
px-2
py-2
hover:bg-gray-200
items-center
rounded
cursor:pointer
`
|
import React, {
forwardRef,
useState,
useRef,
useImperativeMethods,
} from 'react'
import PropTypes from 'prop-types'
const CheckBox = forwardRef(({ name, label, checked: isChecked }, ref) => {
const [value, setValue] = useState(isChecked)
const handleChange = e => {
setValue(e.target.checked)
}
const inputRef = useRef()
useImperativeMethods(ref, () => ({
getValue: () => inputRef.current.checked,
}))
return (
<div className="form-row_container">
<label>
{label || ''}
<input
ref={inputRef}
onChange={handleChange}
name={name}
type="checkbox"
checked={value}
/>
</label>
</div>
)
})
CheckBox.propTypes = {
label: PropTypes.string,
name: PropTypes.string,
checked: PropTypes.bool,
}
CheckBox.defaultProps = {
label: 'label',
name: 'checkbox',
checked: false,
}
CheckBox.displayName = 'ReactFormElements(CheckBox)'
export default CheckBox
|
import React from "react";
function Buy() {
return (
<div>
<h1 className="buy">Buy</h1>
</div>
);
}
export default Buy;
|
Toolbar = React.createClass({
propTypes: { //validators for this component
logo: React.PropTypes.string.isRequired,
logged: React.PropTypes.bool.isRequired
},
getInitialState() {
return {
notifications : 0
};
},
render() {
if (this.props.logged) {
return (
<header>
<div className="logo">{this.props.logo}</div>
<div className="notifications" onClick={this.showNotifications}><span>{this.state.notifications}</span> Notifications</div>
<Button text="Logout" onClick={this.handleLogout}/>
</header>
);
}
return (
<header>
<div className="logo">{this.props.logo}</div>
<Button text="Login" onClick={this.handleOnLogin}/>
</header>
);
},
handleOnLogin() {
FlowRouter.go("/login");
},
handleLogout() {
Meteor.logout(function(err){
if (err) {
throw new Meteor.Error("Logout failed");
} else {
FlowRouter.go('/');
};
});
},
showNotifications (){
FlowRouter.go('/notifications');
}
});
|
import React from 'react'
import { Icon } from '../icon'
import './assets/footer.css'
const WEBSITE_AUTHOR = process.env.REACT_APP_WEBSITE_AUTHOR
const YEAR = new Date().getFullYear()
const SOCIAL_NETWORKS = [
{ name: 'github', link: 'https://github.com/raulmoyareyes' },
{ name: 'linkedin', link: 'https://www.linkedin.com/in/raulmoyareyes/' },
{ name: 'twitter', link: 'https://twitter.com/raulmoyareyes' },
]
export const Footer = () => (
<div className="footer">
<div className="footer__content">
<span>Copyright © { YEAR } - { WEBSITE_AUTHOR }</span>
{ SOCIAL_NETWORKS.map((network, index) => (
<a key={ index } href={ network.link } target="_blank" rel="noopener noreferrer">
<Icon name={ network.name }/>
</a>
))}
</div>
</div>
) |
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import VuePageTitle from 'vue-page-title'
Vue.config.productionTip = false;
Vue.use(VuePageTitle, {suffix: ' - Demo'});
// Original title mixin does not allow for reactivity nor switching routes with same component.
/* const pageTitleUpdateMixin = {
updated() {
const {title} = this.$options;
if (title !== undefined) {
this.$title = typeof (title) === 'function' ? title.call(this, this) : title;
}
}
};
Vue.mixin(pageTitleUpdateMixin); */
new Vue({
router,
render: h => h(App)
}).$mount('#app')
|
/**
* Created by ZXW on 2017/11/13.
*/
var adminidbefore = $("#adminid").val().trim();
$('#baocun').on("click", function () {
var adminid = $("#adminid").val().trim();
var roleid = $("#roleid").val().trim();
var adminlogin = $("#adminlogin").val().trim();
var adminpsw = $("#adminpsw").val().trim();
var admincondition = $("#admincondition").val().trim();
$.ajax({
type: "POST",
url: "updateeditstaff.do",
data:{"adminid":adminid,"roleid":roleid,"adminlogin":adminlogin,"adminpsw":adminpsw,
"admincondition":admincondition,"adminidbefore":adminidbefore},
dataType: "json",
success:function (data){
if (data) {
$('form').submit();
alert("修改成功!");
window.location = "person.html";
}
}
})
});
|
import React from 'react';
import CollectionItem from '../../components/collection-item/collection-item.component';
import {connect} from 'react-redux';
import './category.styles.scss';
const CategoryPage = ({match,collections}) => {
//const filtered = collections.find(item=>item.routeName===match.params.categoryId);
const filtered = collections[match.params.categoryId];
const {title, items} = filtered;
return (<div className='collection-page'>
<h2 className='title'>{title}</h2>
<div className='items'>
{
items.map(item=> (
<CollectionItem className='collection-item' key={item.id} item={item}/>
))
}
</div>
</div>)
};
const mapStateToProps = ({shop : {collections}}) => ({
collections
});
export default connect(mapStateToProps)(CategoryPage); |
/**
* @module FilmClass
*/
/*
* Class Film
* ----------
* Pour la gestion d'un film, principalement lorsqu'il est édité
*
* NOTES
* -----
* :: La toute première définition se trouve dans required.
*/
// // On l'étend avec les méthodes et propriétés partagées
// $.extend(Film.prototype, ObjetClass.prototype)
// // On l'étend avec les propriétés complexes partagées
// Object.defineProperties(Film.prototype, ObjetClass_defined_properties)
/**
* @class Film
* @constructor
*/
$.extend(Film.prototype,{
/*
* Construit et retourne la balise à insérer dans une fiche
* avec les options +options+
*
* @param options {Hash} des options.
* Ces options sont celles disponibles dans FILM.OPTIONS et
* sont insérées si elles existent en 3e paramètre de la
* balise. Elles permettront de composer le titre affiché
*
*/
balise:function(options)
{
if(undefined == options) options = {}
var bal = "[film:"+this.id+"|"
if(options.titrefr === false) bal += this.titre
else bal += (this.titre_fr || this.titre)
// Les options choisies
var opts = L(options).select(function(opt, value){ return value == true }).join(' ')
if(opts != "") bal += "|" + opts
bal += "]"
return bal
},
/*
* Formate la balise film (cf. `balise' ci-dessus) en respectant
* les options +options+
*
* @param opts {Array} Les options d'affichage du titre du film.
* Cf. ci-dessus
* @param skip_missing Si TRUE, on passe les données manquantes qui nécessiteraient
* le chargement complet du film. Cela est utile lorsqu'on
* passe en revue toutes les balises pour les formater, comme
* après l'édition d'un champ de saisie.
* Cependant, ces films sont mis en attente et chargés dès
* que possible (cf. FILMS.need_loading)
*/
formate:function(opts, skip_loading)
{
if(undefined == opts) opts = []
else if ('string' == typeof opts) opts = opts.split(' ')
// Il faut passer le {Array} des options en {Hash} (convenient)
var options = {} ;
L(opts).each(function(opt){ options[opt] = true})
if(undefined == skip_loading) skip_loading = false
// Les options à passer si le film n'est pas chargé et qu'il faut
// passer son chargement.
if(!this.loaded)
{
var missing_data = ['auteurs']
var memorized = false
for(var i in missing_data)
{
if(options[missing_data[i]]) // p.e. options['auteurs']
{
/*
* Dans le cas où le chargement doit être passé, si des données
* optionnelles sont à afficher, on mémorise qu'il faudra charger
* ce film à la première occasion.
*
*/
if(skip_loading)
{
// On mémorise que le film devra être chargé dès que
// possible
if(memorized == false)
{
FILMS.need_loading.push(this.id)
memorized = true
}
}
/*
* Dans le cas où il ne faut pas sauter le chargement, il faut
* regarder si des données optionnelles sont requises en fonction
* des options (par exemple les auteurs) et lancer le chargement
* du film le cas échéant.
*
*/
else
{
// Le chargement du film est nécessaire
this.load($.proxy(this.formate, this, options))
return null
}
}
}
}
var t
/*
* Le titre
*
* Sauf indication contraire, c'est toujours le titre français qui
* est utilisé comme titre principal.
* Le titre original n'est affiché que lorsque :
* - le titre français n'existe pas
* - le titre original est demandé en option, mais pas le titre français
*/
if(options.titreor && !options.titrefr) t = this.titre
else t = options.titrefr ? (this.titre_fr || this.titre) : this.titre
var inpar = []
if(options.titrefr && options.titreor && this.titre_fr) inpar.push(this.titre)
if(options.annee && this.annee) inpar.push(this.annee)
if(options.auteurs && this.auteurs) inpar.push(this.auteurs_as_patronyme)
if(inpar.length)
{
t += " ("+inpar.join(', ')+")"
}
// Dans un lien ou un span
var bal = options.nolink ? '<span' : '<a onmouseover="FILMS.show_apercu(this, \''+this.id+'\')"' ;
t = bal + ' class="lk lk_film">' + t
t += options.nolink ? '</span>' : '</a>'
return t
}
})
Object.defineProperties(Film.prototype,{
/* ---------------------------------------------------------------------
*
* DATA
*
--------------------------------------------------------------------- */
"titre":{
get:function(){return this._titre},
set:function(titre){
this._titre = titre
}
},
"titre_fr":{
get:function(){return this._titre_fr},
set:function(titre){
this._titre_fr = titre
}
},
"annee":{
get:function(){return this._annee || null },
set:function(annee){
if(annee) this._annee = parseInt(annee, 10)
}
},
/*
* Retourne les "data mini", c'est-à-dire les données qu'on trouve
* dans FILMS.DATA (mais ici, l'objet est construit)
*
* NOTES
* -----
* = Cette méthode n'est utile (pour le moment) qu'à la création
* d'un nouveau film.
*
*/
"data_mini":{
get:function(){
return {
id : this.id,
titre : this.titre,
titre_fr : this.titre_fr,
annee : (this.annee || null),
let : this.let
}
}
},
/* ---------------------------------------------------------------------
*
* MÉTHODES D'AFFICHAGE
*
--------------------------------------------------------------------- */
/*
* Retourne les auteurs comme une string de patronymes
*
*/
"auteurs_as_patronyme":{
get:function(){
if(!this.auteurs) return ""
var str = [], auteur ;
for(var i=0, len=this.auteurs.length; i<len; ++i)
{
auteur = this.auteurs[i]
// TODO: Plus tard,auteur sera une class Person et
// répondra à la méthode `patronyme'
str.push(auteur.prenom + " " + auteur.nom)
}
return str.join(', ')
}
},
/*
* Retourne le code HTML de l'aperçu de l'item
*
* NOTES
* -----
* = Ce code sera placé dans un div.apercu
*/
"html_apercu":{
get:function(){
return '<div id="'+this.id_apercu+'" class="apercu">'+
'<div class="mainprop"></div>' +
'<div class="resume"></div>' +
'</div>'
}
},
/*
* Actualise l'affichage de l'aperçu de l'item
*
*/
"update_apercu":{
get:function(){
if(this.apercu.length == 0) return
this.apercu.find('.mainprop').html(this.titre)
this.apercu.find('.resume').html(this.resume.formate())
}
}
}) |
let nav = document.querySelector('.navbar');
document.addEventListener('scroll', () => {
if (scrollY > 50 ) {
if (!nav.classList.contains('over')){
nav.classList.add('over')
}
} else {
nav.classList.remove('over')
}
}) |
import 'rxjs';
import { combineEpics } from 'redux-observable';
import { api } from '../services';
import * as actions from '../actions';
import * as membershipActions from '../actions/membership.action';
/**
* add to member
* @param action$
* @param store
* @returns {any|*|Observable}
*/
const getAllMembership = (action$) => {
return action$
.ofType(actions.GET_ALL_MEMBERSHIPS)
.switchMap(() =>{
return api.getAllMembership().map(membershipActions.receiveAllMembership);
});
};
const addMembership = (action$) => {
return action$
.ofType(actions.ADD_MEMBERSHIPS)
.switchMap((action) => api.addMembership(action.payload).map(membershipActions.receiveMembership));
};
const membershipEpics = combineEpics(
getAllMembership,
addMembership
);
export default membershipEpics; |
var mutt__menu_8h =
[
[ "Menu", "structMenu.html", "structMenu" ],
[ "REDRAW_NO_FLAGS", "mutt__menu_8h.html#a1f96f27f798ffa90d7b8a37c5f5d963a", null ],
[ "REDRAW_INDEX", "mutt__menu_8h.html#a17ef6a49291da65aac4163281062c9bf", null ],
[ "REDRAW_MOTION", "mutt__menu_8h.html#a2cbe5a56bfd89f5bc04d61a756b2d053", null ],
[ "REDRAW_MOTION_RESYNC", "mutt__menu_8h.html#a3540f3fb484029dfd504f2fe7f216c44", null ],
[ "REDRAW_CURRENT", "mutt__menu_8h.html#a3496434eacf006a8f10feeddd42f96f1", null ],
[ "REDRAW_STATUS", "mutt__menu_8h.html#a8a2fa08531cc0e55b095c555a79eadaa", null ],
[ "REDRAW_FULL", "mutt__menu_8h.html#a716ec76c9c77fe08876a80a7859bde2c", null ],
[ "REDRAW_BODY", "mutt__menu_8h.html#ac9ef629d8b77ec35f04f52fae487e306", null ],
[ "REDRAW_FLOW", "mutt__menu_8h.html#af2bef4a166f1cc649eb20d8f5954a405", null ],
[ "MuttRedrawFlags", "mutt__menu_8h.html#a7bd0809997971e28d300dfa17c0873f0", null ],
[ "menu_bottom_page", "mutt__menu_8h.html#a1ea4024b7eb12da80b949dd73cd7ece0", null ],
[ "menu_check_recenter", "mutt__menu_8h.html#a71465e725b041bc3175323d0210f69ca", null ],
[ "menu_current_bottom", "mutt__menu_8h.html#a9ace9a1b119fadd8955eab21208d68f6", null ],
[ "menu_current_middle", "mutt__menu_8h.html#af77c14dc829023bf8cab50824fcedb59", null ],
[ "menu_current_top", "mutt__menu_8h.html#a5fbd07c9ba05297dbb9c6b6da1d310e3", null ],
[ "menu_first_entry", "mutt__menu_8h.html#af9704a95c8ca0fa4683cca09abe2752d", null ],
[ "menu_half_down", "mutt__menu_8h.html#aedacdfa878d8a022d35749b03a4cecc7", null ],
[ "menu_half_up", "mutt__menu_8h.html#adf218323f3027edcec7c22491bea6f30", null ],
[ "menu_last_entry", "mutt__menu_8h.html#ae4d6d408703cf768a355a532359b7ac2", null ],
[ "menu_middle_page", "mutt__menu_8h.html#a863635769352a439bee04af26a9ce38b", null ],
[ "menu_next_line", "mutt__menu_8h.html#a9ebb3222efc82f4a55858911278a3016", null ],
[ "menu_next_page", "mutt__menu_8h.html#a9b13c608a3b0bfd22b1961b83169097c", null ],
[ "menu_prev_line", "mutt__menu_8h.html#a7e1b88289b77111db8bdc14abc304981", null ],
[ "menu_prev_page", "mutt__menu_8h.html#a4ba92e31cdc5ba96e4851554ff820066", null ],
[ "menu_redraw_current", "mutt__menu_8h.html#a2367fdbd574e0b041ed3382121696602", null ],
[ "menu_redraw_full", "mutt__menu_8h.html#a7416efe55303324c07e1515bec5697d2", null ],
[ "menu_redraw_index", "mutt__menu_8h.html#a39b631a566b12a37364e82049e708dfa", null ],
[ "menu_redraw_motion", "mutt__menu_8h.html#adb45718706531be131e704b8af873338", null ],
[ "menu_redraw_status", "mutt__menu_8h.html#a3581b1d404de8b9d6e4000d20fd316b2", null ],
[ "menu_redraw", "mutt__menu_8h.html#a3da31793ff9ae935dccab75ae653a064", null ],
[ "menu_top_page", "mutt__menu_8h.html#a15266916f9c0c962638f83d74f27df9f", null ],
[ "mutt_menu_add_dialog_row", "mutt__menu_8h.html#afdbd824f10162d5fb74d76596392ff66", null ],
[ "mutt_menu_current_redraw", "mutt__menu_8h.html#a37b5dcb140bd203a9f32e02d25137fb4", null ],
[ "mutt_menu_free", "mutt__menu_8h.html#ac462ae742dd183b457372c0488fedd1b", null ],
[ "mutt_menu_init", "mutt__menu_8h.html#ac922f9566dd84d77196ccb637f35fce5", null ],
[ "mutt_menu_loop", "mutt__menu_8h.html#a2a7161a4171307d15f2362f5d55dfdb1", null ],
[ "mutt_menu_new", "mutt__menu_8h.html#a8034d82776d0c709ed9d9521fd09948e", null ],
[ "mutt_menu_pop_current", "mutt__menu_8h.html#acbb5c8e0e047ca06629a7e8ee967d890", null ],
[ "mutt_menu_push_current", "mutt__menu_8h.html#a04f3d31793e49bd9c718fd184ce3d575", null ],
[ "mutt_menu_set_current_redraw_full", "mutt__menu_8h.html#adea2310d0ce202d0e2e3170b434c0ecc", null ],
[ "mutt_menu_set_current_redraw", "mutt__menu_8h.html#a7236a590554190cf9e0093fedc86dd60", null ],
[ "mutt_menu_set_redraw_full", "mutt__menu_8h.html#a4dc047ee6f471343beb7ba148301d1b5", null ],
[ "mutt_menu_set_redraw", "mutt__menu_8h.html#a9aa1df273a2fd3ac9e4af57a1a1831d2", null ],
[ "mutt_menu_color_observer", "mutt__menu_8h.html#abb778418fe915f8e5f0fae1d9cc7f7aa", null ],
[ "mutt_menu_config_observer", "mutt__menu_8h.html#a2eeb9294bb635065c7240df12d5402d5", null ],
[ "C_MenuContext", "mutt__menu_8h.html#a2ddf1f72232d3ee71b8fede3e0a32d35", null ],
[ "C_MenuMoveOff", "mutt__menu_8h.html#a850109819abacb7b69160d471e2f4c2b", null ],
[ "C_MenuScroll", "mutt__menu_8h.html#a02d0b21b8fca47b22153da27d5f3ffcf", null ]
]; |
(function () {
'use strict';
/**
* @ngdoc object
* @name 0502pfingsten.controller:C0502pfingstenCtrl
*
* @description
*
*/
angular
.module('0502pfingsten')
.controller('C0502pfingstenCtrl', C0502pfingstenCtrl);
function C0502pfingstenCtrl() {
var vm = this;
vm.ctrlName = 'C0502pfingstenCtrl';
}
}());
|
const webpack = require('@dolittle/vanir-webpack/backend');
module.exports = (env, argv) => {
return webpack(env, argv, config => { });
};
|
import useSWR from "swr";
import { useParams } from "react-router-dom";
const baseUrl =
"https://2q2woep105.execute-api.eu-west-1.amazonaws.com/napptilus/oompa-loompas/{id}";
export default function useGetSingleOompaResult() {
const { id } = useParams();
const url = baseUrl.replace(/{id}/, parseInt(id));
const { data, error } = useSWR(url);
return { data, error };
}
|
'use strict';
angular.module('newApp').controller('mdl.mobileweb.controller.recordprogress',
['$rootScope', '$scope', 'mdl.mobileweb.service.dashboard', 'mdl.mobileweb.service.recordprogress', 'mdl.mobileweb.service.login', 'toaster', 'mdl.mobileweb.service.json', '$http', 'modalService', '$location',
function ($rootScope, $scope, dashboardService, recordprogressService, loginService, toaster, jsonService, $http, modalService, $location) {
var vm = this;
vm.pollingStationList = [];
vm.electionlist = [];
vm.electionId;
vm.periodProgress = {};
vm.periodProgress.ballotPappersIssued = "";
vm.periodProgress.postalPackRecieved = "";
vm.periodProgress.postalPacksCollected = "";
vm.bpNames = {}
vm.progressSummery = [];
vm.progressSummery.ballotpapers = "0";
vm.progressSummery.postalpacks = "0";
vm.periodProgress.ballotPappersSpoiled = "0";
vm.progressSummery.postalpackscollected = "0";
vm.org_state = [];
vm.buttonDisabled = false;
vm.fieldDisabled = false;
vm.stationstatus = false;
vm.polling_Station_Election = [];
vm.postalPacksTotalCollected = 0;
vm.BPA_identifier = "0";
var ballotTotalArray = new Array(vm.progressSummery.length);
var ballotIssuedFullTotal = 0;
var tenderedTotalArray = new Array(vm.progressSummery.length);
var tenderedIssuedFullTotal = 0;
vm.popup_topic = "Name of Person Uplifting";
vm.popup_user = "";
vm.collect_packs_electionid = 0;
vm.collect_packs_stationid = 0;
vm.postalPacksOnloadSet = new Array(vm.progressSummery.length);
var progressSummeryArray = new Array(vm.progressSummery.length);
vm.stationstatuscheck = function (stationId) {
dashboardService.getpollingstationclosedstatus(stationId, function (response) {
var res = response.result.entry;
if (res.response == "success") {
if ((res.open_status == 1) && (res.closed_status == 0)) {
// toaster.pop("info","can do record progress");
vm.stationstatus = true;
}
else if (res.open_status == 0) {
vm.stationstatus = false;
toaster.pop("info", "Station Not Opened!", "Cannot do record progress to unopened stations.");
}
else if (res.closed_status == 1) {
vm.stationstatus = false;
toaster.pop("error", "Station Closed!", "Cannot do record progress to closed stations.");
}
else {
vm.stationstatus = false;
toaster.pop("error", "Error!", "Please try again later.");
}
}
else {
toaster.pop("error", "Error!", "Try again later");
}
});
}
vm.getStationList = function () {
dashboardService.getPollingStations(function (response) {
var resp = response.result.entry;
if (jsonService.whatIsIt(resp) == "Object") {
vm.pollingStationList[0] = resp;
vm.getEList(vm.pollingStationList[0].id)
}
else if (jsonService.whatIsIt(resp) == "Array") {
vm.pollingStationList = resp;
vm.getEList(vm.pollingStationList[0].id)
}
vm.stationstatuscheck(vm.pollingStationList[0].id);
})
};
vm.getStationList();
vm.getEList = function (stationid) {
dashboardService.getEllectionList(stationid, function (response) {
var res = response.result.entry;
if (jsonService.whatIsIt(res) == "Object") {
vm.electionlist[0] = res;
}
else if (jsonService.whatIsIt(res) == "Array") {
vm.electionlist = res;
}
vm.getBPNames(vm.electionlist[0].electionid);
vm.getProgress(vm.electionlist[0].electionid, stationid);
vm.showCloseButton(vm.electionlist[0].electionid, stationid);
vm.checkElection(vm.electionlist[0].electionid, stationid);
})
};
vm.checkElectionClosed = 0;
vm.checkElection = function (eid, stationid, callback) {
$rootScope.cui_blocker(true);//UI blocker started
dashboardService.getElectionStatus(eid, stationid, function (response) {
vm.checkElectionClosed = response.result.entry.electionstatus;
vm.electionstatus = response.result.entry;
$rootScope.cui_blocker(false);//UI blocker close
if (callback)
callback();
});
}
vm.getBPNames = function (eid) {
$rootScope.cui_blocker(true);//UI blocker started
dashboardService.getBPNames(eid, function (response) {
vm.bpNames = response.result.entry;
$rootScope.cui_blocker(false);//UI blocker close
});
}
vm.tenderedShow = false;
vm.mainballowStats = true;
vm.tenderedControl = function (action) {
if (action) {
vm.mainballowStats = false;
vm.tenderedShow = true;
}
else {
vm.mainballowStats = true;
vm.tenderedShow = false;
}
}
vm.stationcheck = function (stationid, eid) {
vm.electionlist = [];
vm.getEList(stationid);
vm.recordProgress = [];
vm.periodProgress = {};
vm.periodProgress.ballotPappersIssued = "";
vm.periodProgress.ballotPappersSpoiled = "";
vm.periodProgress.postalPackRecieved = "";
vm.periodProgress.postalPacksCollected = "";
vm.progressSummery = [];
vm.progressSummery.ballotpapers = "0";
vm.progressSummery.postalpacks = "0";
vm.progressSummery.postalpackscollected = "0";
vm.stationstatuscheck(stationid);
}
vm.saveTimeSlot = function (electionId, stationId, data, toastEnable, successCallback) {
$rootScope.cui_blocker(true);//UI blocker started
recordprogressService.updateProgress(electionId, stationId, data, function (response) {
if (response.response && response.response === 'sucess') {
if (toastEnable) {
toaster.pop("success", "Data saved Successfully", "");
}
if (successCallback) {
successCallback();
}
} else if (toastEnable && response.response != 'invalid ballot paper count') {
toaster.pop("error", "Ballot Paper Count is Invalid!", "Please try again later.");
}
$rootScope.cui_blocker();
});
}
vm.validateValue = function (val) { // Validate for positive valid number
if (!isNaN(val) && val >= 0)
return true;
else
return false;
}
vm.save = function (stationId, updateObj, tendred, successCallback) {
var ballotPaperSaved = (parseInt(vm.ballotIssuedTotal(), 10)) - (parseInt(vm.spoiltBallotsTotal(), 10));
var tenderdBallotPaperSaved = (parseInt(vm.tendredballotIssuedTotal(), 10)) - (parseInt(vm.tendredspoiltBallotsTotal(), 10));
angular.copy(vm.progressSummery, vm.org_state);
var isValidInput = true;
var validateToastMsg = "";
if (vm.electionstatus.ballotturnout < parseInt(vm.ballotIssuedTotal(), 10)) {
isValidInput = false;
validateToastMsg = "Your ballot paper count (" + parseInt(vm.ballotIssuedTotal(), 10) + ") is greater than total ballot turnout (" + vm.electionstatus.ballotturnout + "). Please correct.";
}
else if (vm.electionstatus.tendturnout < parseInt(vm.tendredballotIssuedTotal(), 10)) {
isValidInput = false;
validateToastMsg = "Your Tendered ballot paper count (" + parseInt(vm.tendredballotIssuedTotal(), 10) + ") is greater than total ballot turnout (" + vm.electionstatus.tendturnout + "). Please correct.";
}
if (vm.BPA_identifier == "1") {
if ((parseInt(vm.ballotIssuedTotal(), 10)) < 0) {
toaster.pop("error", "Ballot Paper Issued should be greater than " + vm.polling_Station_Election.ballotstart + " and smaller than " + vm.polling_Station_Election.ballotend + "!", "");
} else if ((parseInt(vm.ballotIssuedTotal(), 10)) > (vm.polling_Station_Election.ballotend - vm.polling_Station_Election.ballotstart)) {
toaster.pop("error", "Ballot Paper Issued should be greater than " + vm.polling_Station_Election.ballotstart + " and smaller than " + vm.polling_Station_Election.ballotend + "!", "");
} else if ((parseInt(vm.tendredballotIssuedTotal(), 10)) < 0) {
toaster.pop("error", "Tendered Paper Issued should be smaller than " + vm.polling_Station_Election.tenderstart + " and smaller than " + vm.polling_Station_Election.tenderend + "!", "");
} else if ((parseInt(vm.tendredballotIssuedTotal(), 10)) > (vm.polling_Station_Election.tenderend - vm.polling_Station_Election.tenderstart)) {
toaster.pop("error", "Tendered Paper Issued should be smaller than " + vm.polling_Station_Election.tenderstart + " and smaller than " + vm.polling_Station_Election.tenderend + "!", "");
} else if ((ballotPaperSaved >= 0) && (tenderdBallotPaperSaved >= 0) && isValidInput) {
var hasError = false;
var progressData = [];
angular.forEach(updateObj, function (value, key) {
var toastMsg = ''; //Validate Input
if (!vm.checkPassingValidValues(updateObj, value.ballotpapers, key)) {
toastMsg = "You have enterd invalid values, Check them again! ";
} else if (!vm.checkPassingValidValues2(updateObj, value.tenballotpapers, key)) {
toastMsg = "You have enterd invalid values, Check them again! ";
}
else if (!vm.validateValue(value.ballotpapers))
toastMsg = "Ballot Papers ";
else if (!vm.validateValue(value.postalpacks))
toastMsg = "Postalpacks ";
else if (!vm.validateValue(value.postalpackscollected))
toastMsg = "Postalpacks collected ";
else if (!vm.validateValue(value.spoiltballots))
toastMsg = "Spolit Ballots ";
else if (!vm.validateValue(value.tenballotpapers))
toastMsg = "Tendered ballot papers ";
else if (!vm.validateValue(value.tenspoiltballots))
toastMsg = "Tendered Spoilt ballots ";
if (toastMsg.length > 0) {
hasError = true;
toaster.pop("error", toastMsg + " - Invalid record with a minus value is not saved, please correct. Rest of the records Saved successfully", "");
}
else {
vm.saveObj = {};
vm.saveObj.ballotPapers = vm.checkAssigningValues(value, key, updateObj);
vm.saveObj.postalPacks = value.postalpacks;
vm.saveObj.postalPacksCollected = value.postalpackscollected;
vm.saveObj.spoiltBallots = value.spoiltballots;
vm.saveObj.tenBallotPapers = vm.checkAssigningValues2(value, key, updateObj);
vm.saveObj.tenSpoiltBallots = value.tenspoiltballots;
vm.saveObj.ballotPapers2 = value.ballotpapers2//vm.checkAssigningValues(value, key, updateObj);
vm.saveObj.postalPacks2 = value.postalpacks2;
vm.saveObj.postalPacksCollected2 = value.postalpackscollected2;
vm.saveObj.spoiltBallots2 = value.spoiltballots2;
vm.saveObj.tenBallotPapers2 = value.tenballotpapers2; //vm.checkAssigningValues2(value, key, updateObj);
vm.saveObj.tenSpoiltBallots2 = value.tenspoiltballots2;
vm.saveObj.updateTime = value.time.split('-')[0].split(':')[0];
progressData.push(vm.saveObj);
}
});
vm.saveTimeSlot(vm.electionId, stationId, progressData, false, successCallback);
if (!hasError)
toaster.pop("success", "Data saved Successfully", "");
if (tendred)
vm.tenderedControl(false);
} else {
if (!isValidInput)
toaster.pop("error", validateToastMsg, "");
else
toaster.pop("error", "Ballot Paper Issued should be larger than Spoilt Ballot Papers!", "");
}
} else if (vm.BPA_identifier == "0") {
if ((ballotPaperSaved >= 0) && (tenderdBallotPaperSaved >= 0) && isValidInput) {
var hasError = false;
var progressData = [];
angular.forEach(updateObj, function (value, key) {
vm.saveObj = {};
var toastMsg = ''; //Validate Input
if (!vm.validateValue(value.ballotpapers))
toastMsg = "Ballot Papers ";
else if (!vm.validateValue(value.postalpacks))
toastMsg = "Postalpacks ";
else if (!vm.validateValue(value.postalpackscollected))
toastMsg = "Postalpacks collected ";
else if (!vm.validateValue(value.spoiltballots))
toastMsg = "Spolit Ballots ";
else if (!vm.validateValue(value.tenballotpapers))
toastMsg = "Tendered ballot papers ";
else if (!vm.validateValue(value.tenspoiltballots))
toastMsg = "Tendered Spoilt ballots ";
if (toastMsg.length > 0) {
hasError = true;
toaster.pop("error", toastMsg + " - Invalid record with a minus value is not saved, please correct. Rest of the records Saved successfully", "");
}
else {
vm.saveObj.ballotPapers = value.ballotpapers;
vm.saveObj.postalPacks = value.postalpacks;
vm.saveObj.postalPacksCollected = value.postalpackscollected;
vm.saveObj.spoiltBallots = value.spoiltballots;
vm.saveObj.tenBallotPapers = value.tenballotpapers;
vm.saveObj.tenSpoiltBallots = value.tenspoiltballots;
vm.saveObj.updateTime = value.time.split('-')[0].split(':')[0];
vm.saveObj.ballotPapers2 = value.ballotpapers2
vm.saveObj.postalPacks2 = value.postalpacks2;
vm.saveObj.postalPacksCollected2 = value.postalpackscollected2;
vm.saveObj.spoiltBallots2 = value.spoiltballots2;
vm.saveObj.tenBallotPapers2 = value.tenballotpapers2;
vm.saveObj.tenSpoiltBallots2 = value.tenspoiltballots2;
progressData.push(vm.saveObj);
}
});
vm.saveTimeSlot(vm.electionId, stationId, progressData, false, successCallback);
if (!hasError)
toaster.pop("success", "Data saved Successfully", "");
if (tendred)
vm.tenderedControl(false);
} else {
if (!isValidInput)
toaster.pop("error", validateToastMsg, "");
else
toaster.pop("error", "Ballot Paper Issued should be larger than Spoilt Ballot Papers!", "");
}
}
};
vm.getProgressSummary = [];
vm.getProgress = function (electionid, stationId) {
vm.electionId = electionid;
var getProgressApiCall = function () {
recordprogressService.getProgress(electionid, stationId, function (response) {
var isAllSucess = "1";
for (var row in response.results) {
if (row.response != "success" && row.ballotpapers != null) {
isAllSucess = "0";
break;
}
}
if (isAllSucess == "1") {
//alert("");
vm.progressSummery = response.results;
//if user navigate to another page wthout saving data
angular.copy(vm.progressSummery, vm.org_state);
//vm.templateModal2.eid = electionid;
//vm.templateModal2.sid = stationId;
if (vm.BPA_identifier == "0") {
for (var i = 0; i < vm.progressSummery.length; i++) {
var ballotpapersrecievedTotal = vm.progressSummery[i];
if (ballotpapersrecievedTotal.ballotpapers != null) {
vm.progressSummery[i].ballotpapers = parseInt(ballotpapersrecievedTotal.ballotpapers, 10);
}
if (ballotpapersrecievedTotal.tenballotpapers != null) {
vm.progressSummery[i].tenballotpapers = parseInt(ballotpapersrecievedTotal.tenballotpapers, 10);
}
}
} else if (vm.BPA_identifier == "1") {
var cumilativeBallotCount = 0;
var balotPaperStart = -1;
balotPaperStart = parseInt(vm.polling_Station_Election.ballotstart);
var cumilativeTenderdCount = 0;
var tenderdStart = -1;
tenderdStart = parseInt(vm.polling_Station_Election.tenderstart);
if (balotPaperStart == -1 || tenderdStart == -1) {
toaster.pop("error", "Data loading error!", "");
} else {
for (var i = 0; i < response.results.length; i++) {
var row = response.results[i];
var val = 0;
var val2 = 0;
//if balotpapers issued in this hour
if (row.ballotpapers != 0) {
val = cumilativeBallotCount + balotPaperStart + row.ballotpapers;
}
if (row.tenballotpapers != 0) {
val2 = cumilativeTenderdCount + tenderdStart + row.tenballotpapers;
}
cumilativeBallotCount = cumilativeBallotCount + row.ballotpapers;
cumilativeTenderdCount = cumilativeTenderdCount + row.tenballotpapers;
vm.progressSummery[i].ballotpapers = val;
vm.progressSummery[i].tenballotpapers = val2;
}
}
}
}
else {
toaster.pop("error", "Data loading error!", "");
}
vm.postalPacksTotalCollected = vm.postalPacksTotalOnload();
});
vm.showCloseButton(electionid, stationId);
}
vm.getElectionByID(electionid, function () {
vm.getPollingStationElectionDetails(electionid, stationId, function () {
vm.checkElection(electionid, stationId, function () {
getProgressApiCall();
});
});
});
}
vm.ballotIssuedTotal = function () {
var total = 0;
if (vm.BPA_identifier == "0") {
for (var i = 0; i < vm.progressSummery.length; i++) {
var ballotTotal = vm.progressSummery[i];
if (ballotTotal.ballotpapers != null)
total += parseInt(ballotTotal.ballotpapers, 10);
}
} else if (vm.BPA_identifier == "1") {
for (var i = 0; i < vm.progressSummery.length; i++) {
var ballotTotal = vm.progressSummery[i];
ballotTotalArray[i] = ballotTotal.ballotpapers;
}
if (Math.max.apply(Math, ballotTotalArray) > 0) {
total = (Math.max.apply(Math, ballotTotalArray) - vm.polling_Station_Election.ballotstart) + 1;
ballotIssuedFullTotal = total;
} else {
total = 0;
ballotIssuedFullTotal = total;
}
}
return total;
}
vm.tendredballotIssuedTotal = function () {
var total = 0;
if (vm.BPA_identifier == "0") {
for (var i = 0; i < vm.progressSummery.length; i++) {
var ballotTotal = vm.progressSummery[i];
if (ballotTotal.tenballotpapers != null)
total += parseInt(ballotTotal.tenballotpapers, 10);
}
} else if (vm.BPA_identifier == "1") {
for (var i = 0; i < vm.progressSummery.length; i++) {
var ballotTotal = vm.progressSummery[i];
tenderedTotalArray[i] = ballotTotal.tenballotpapers;
}
if (Math.max.apply(Math, tenderedTotalArray) > 0) {
total = (Math.max.apply(Math, tenderedTotalArray) - vm.polling_Station_Election.tenderstart) + 1;
} else {
total = 0;
}
}
return total;
}
vm.spoiltBallotsTotal = function () {
var total2 = 0;
for (var i = 0; i < vm.progressSummery.length; i++) {
var spoiltTotal = vm.progressSummery[i];
if (spoiltTotal.spoiltballots != null)
total2 += parseInt(spoiltTotal.spoiltballots, 10);
}
return total2;
}
vm.tendredspoiltBallotsTotal = function () {
var total2 = 0;
for (var i = 0; i < vm.progressSummery.length; i++) {
var spoiltTotal = vm.progressSummery[i];
if (spoiltTotal.tenspoiltballots != null)
total2 += parseInt(spoiltTotal.tenspoiltballots, 10);
}
return total2;
}
vm.postalPacksTotal = function () {
var total3 = 0;
for (var i = 0; i < vm.progressSummery.length; i++) {
var postalTotal = vm.progressSummery[i];
if (postalTotal.postalpacks != null)
total3 += parseInt(postalTotal.postalpacks, 10);
}
return total3;
}
//vm.postalPacksOnloadSet = vm.progressSummery;
vm.postalPacksTotalOnload = function () {
var total4 = 0;
for (var i = 0; i < vm.progressSummery.length; i++) {
var postalTotalOnload = vm.progressSummery[i];
//vm.postalPacksOnloadSet[i] = vm.progressSummery[i].postalpackscollected;
if (postalTotalOnload.postalpackscollected != null)
total4 += parseInt(postalTotalOnload.postalpackscollected, 10);
}
return total4;
}
vm.showCloseButton = function (electionid, stationId) {
recordprogressService.showCloseButton(electionid, stationId, function (response) {
if (response.result.entry.response == "success") {
vm.buttonshowDetails = response.result.entry.buttonshow;
} else {
toaster.pop("error", "Error!", "Try again later");
}
});
}
$scope.rec_electionid = '';
$scope.rec_stationId = '';
$scope.callConfirmation = function (electionid, stationId) {
$scope.templateModal.body = "Did you save all data before you close this election?"
$scope.templateModal.save = function () { $scope.closeStation(); };
if (vm.postalPacksTotalOnload() !== vm.postalPacksTotal())
toaster.pop("error", "Collect all postal packs.", "Please collect last updated postal packs.");
else {
$scope.rec_electionid = electionid;
$scope.rec_stationId = stationId;
modalService.load('rec_progress');
}
};
$scope.closeStation = function () {
if ($scope.rec_electionid.length > 0 && $scope.rec_stationId.length > 0) {
recordprogressService.closeStation($scope.rec_electionid, $scope.rec_stationId, function (response) {
if (response.result.entry.response == "success") {
vm.closeStationDetails = response.result.entry;
//vm.buttonDisabled = true;
//vm.fieldDisabled = true;
vm.checkElectionClosed = 1;
toaster.pop("success", "Election closed successfully", "");
vm.onRouteChangeOff();
modalService.close('rec_progress');
} else {
toaster.pop("error", "Error!", "Try again later");
}
});
}
}
vm.postalPackCollected = function (electionid, stationId) {
if ((isNaN(vm.postalPacksTotal())) || (vm.postalPacksTotal() < 0)) {
toaster.pop("error", "Enter a valid value for Postal Packs!", "");
} else {
if (vm.postalPacksTotalOnload() === vm.postalPacksTotal()) {
toaster.pop("success", "Collected Postal Packs are same as Total Postal Packs!", "No need to save it.");
} else {
//setTimeout(vm.save(stationId,vm.progressSummery,false), 3000);
vm.save(stationId, vm.progressSummery, false, function () { vm.assignPerson(electionid, stationId); })
/*vm.getElectionByID(vm.collect_packs_electionid,function(){
vm.getPollingStationElectionDetails(vm.collect_packs_electionid, vm.collect_packs_stationid, function(){
vm.checkElection(vm.collect_packs_electionid,vm.collect_packs_stationid, function(){
getProgressApiCall();
});
});
});*/
}
}
}
//modalcolouredfooter
vm.template2 = "views/closestation/popup_collect_packs.html";
vm.templateModal2 = {
id: "rec_progress2",
body: "Did you save all data before you close this election?",
closeCaption: "No",
saveCaption: "Yes",
};
vm.assignPerson = function (electionid, stationId) {
vm.templateModal2.eid = electionid;
vm.templateModal2.sid = stationId;
vm.templateModal2.save = function () {
vm.collectingPostalPacks(electionid, stationId);
modalService.close('rec_progress2');
},
vm.templateModal2.close = function () { modalService.close('rec_progress2'); };
modalService.load('rec_progress2');
};
vm.collectingPostalPacks = function (electionid, stationId) {
//setTimeout(vm.save(stationId,vm.progressSummery,false), 3000);
recordprogressService.postalPackCollected(electionid, stationId, function (response) {
if (response.result.entry.response == "success") {
vm.postalPackDetails = response.result.entry;
if (vm.postalPacksTotal() == 0) {
$rootScope.cui_blocker(true);//UI blocker started
angular.forEach(vm.progressSummery, function (value, key) {
vm.saveObj2 = {};
vm.saveObj2.updatetime = value.time.split('-')[0].split(':')[0];
vm.saveObj2.uplifting_person_name = vm.popup_user;
vm.saveObj2.postalpackscollected = value.postalpackscollected;
if (value.postalpackscollected != 0) {
vm.postalPackCollected_V2(vm.electionId, stationId, vm.saveObj2.uplifting_person_name, vm.saveObj2.updatetime);
} else {
vm.saveObj2.uplifting_person_name = "";
vm.postalPackCollected_V2(vm.electionId, stationId, vm.saveObj2.uplifting_person_name, vm.saveObj2.updatetime);
}
});
toaster.pop("success", "Postal Packs are Collected!", "There are no packs to Collect!");
//alert("***");
//vm.getProgress(electionid, stationId);
//setTimeout(vm.getProgress(electionid, stationId), 30000);
//setTimeout($scope.$apply(vm.getProgress(electionid, stationId)), 30000);
//vm.getProgress(electionid, stationId);
//alert("---");
$rootScope.cui_blocker(false);//UI blocker close
} else {
$rootScope.cui_blocker(true);//UI blocker started
angular.forEach(vm.progressSummery, function (value, key) {
vm.saveObj2 = {};
vm.saveObj2.updatetime = value.time.split('-')[0].split(':')[0];
vm.saveObj2.uplifting_person_name = vm.popup_user;
vm.saveObj2.postalpackscollected = value.postalpackscollected;
if (value.postalpackscollected != 0) {
vm.postalPackCollected_V2(vm.electionId, stationId, vm.saveObj2.uplifting_person_name, vm.saveObj2.updatetime);
} else {
vm.saveObj2.uplifting_person_name = "";
vm.postalPackCollected_V2(vm.electionId, stationId, vm.saveObj2.uplifting_person_name, vm.saveObj2.updatetime);
}
});
toaster.pop("success", "Postal Packs are Collected", "");
//alert("&&&");
//vm.getProgress(electionid, stationId);
//setTimeout(vm.getProgress(electionid, stationId), 30000);
//setTimeout($scope.$apply(vm.getProgress(electionid, stationId)), 30000);
//alert("%%%");
$rootScope.cui_blocker(false);//UI blocker close
}
} else {
toaster.pop("error", "Error!", "Try again later");
}
/*vm.getElectionByID(electionid,function(){
vm.getPollingStationElectionDetails(electionid, stationId, function(){
vm.checkElection(electionid, stationId, function(){
getProgressApiCall();
});
});
});*/
});
/*angular.forEach(vm.progressSummery, function(value, key) {
vm.saveObj2 = {};
vm.saveObj2.updatetime=value.time.split('-')[0].split(':')[0];
vm.saveObj2.uplifting_person_name = vm.popup_user;
vm.saveObj2.postalpackscollected = value.postalpackscollected;
if (value.postalpackscollected != 0) {
vm.postalPackCollected_V2(vm.electionId,stationId,vm.saveObj2.uplifting_person_name, vm.saveObj2.updatetime);
} else {
vm.saveObj2.uplifting_person_name = "";
vm.postalPackCollected_V2(vm.electionId,stationId,vm.saveObj2.uplifting_person_name, vm.saveObj2.updatetime);
}
});*/
};
vm.postalPackCollected_V2 = function (electionid, stationId, assigned_person_name, update_time) {
recordprogressService.postalPackCollected_V2(electionid, stationId, assigned_person_name, update_time, function (response) {
if (response.result.entry.response == "success") {
vm.postalPackDetails2 = response.result.entry;
vm.getProgress(electionid, stationId);
/*if (vm.postalPacksTotal() == 0) {
//toaster.pop("success","Postal Packs are Already Collected","");
vm.getProgress(electionid, stationId);
} else {
//toaster.pop("success","Postal Packs are Assigned to "+assigned_person_name,"");
vm.getProgress(electionid, stationId);
}*/
} else {
toaster.pop("error", "Error!", "Try again later");
}
});
};
vm.getPassingPostalPackValues = function (value, key, postalpackscollected) {
if (vm.postalPacksOnloadSet[key].postalpackscollected == postalpackscollected) {
return false;
} else {
return true;
}
}
vm.getElectionByID = function (election_Id, callback) {
recordprogressService.getElectionByID(function (response) {
vm.oneOfElections = response.result.entry;
vm.BPA_identifier = vm.oneOfElections.BPA_identifier;
if (callback)
callback();
}, election_Id)
};
vm.getPollingStationElectionDetails = function (electionid, pollingstationid, callback) {
recordprogressService.getPollingStationElectionDetails(function (response) {
vm.polling_Station_Election = response.result.entry;
if (callback)
callback();
}, electionid, pollingstationid)
};
vm.checkNumberValidity = function (ballotpaperscount, key1) {
var count = 0;
var largestValue = 0;
var last_element = 0;
var passing_value_index = 0;
passing_value_index = ballotTotalArray.indexOf(ballotpaperscount);
if (ballotTotalArray[passing_value_index + 1] == 0) {
if ((ballotpaperscount < ballotTotalArray[passing_value_index - 1])) {
$scope.templateModal.body = "Are you sure you want to update this value?"
$scope.templateModal.save = function () {
vm.updatingCells(ballotpaperscount, ballotTotalArray, key1);
modalService.close('rec_progress');
};
modalService.load('rec_progress');
} else {
//$scope.templateModal.body = "";
$scope.templateModal.body = "Did you save all data before you close this election?"
$scope.templateModal.save = function () { $scope.closeStation(); };
}
} else if (ballotTotalArray[passing_value_index + 1] > 0) {
if ((ballotpaperscount < ballotTotalArray[passing_value_index - 1]) || (ballotpaperscount > ballotTotalArray[passing_value_index + 1])) {
$scope.templateModal.body = "Are you sure you want to update this value?"
$scope.templateModal.save = function () {
vm.updatingCells2(ballotpaperscount, ballotTotalArray, key1);
modalService.close('rec_progress');
};
modalService.load('rec_progress');
} else {
//$scope.templateModal.body = "";
$scope.templateModal.body = "Did you save all data before you close this election?"
$scope.templateModal.save = function () { $scope.closeStation(); };
}
}
};
vm.checkNumberValidity2 = function (tenderedpaperscount, key1) {
var count = 0;
var largestValue = 0;
var last_element = 0;
var passing_value_index = 0;
passing_value_index = tenderedTotalArray.indexOf(tenderedpaperscount);
if (tenderedTotalArray[passing_value_index + 1] == 0) {
if ((tenderedpaperscount < tenderedTotalArray[passing_value_index - 1])) {
$scope.templateModal.body = "Are you sure you want to update this value?"
$scope.templateModal.save = function () {
vm.updatingCells3(tenderedpaperscount, tenderedTotalArray, key1);
modalService.close('rec_progress');
};
modalService.load('rec_progress');
} else {
//$scope.templateModal.body = ""
$scope.templateModal.body = "Did you save all data before you close this election?"
$scope.templateModal.save = function () { $scope.closeStation(); };
}
} else if (tenderedTotalArray[passing_value_index + 1] > 0) {
if ((tenderedpaperscount < tenderedTotalArray[passing_value_index - 1]) || (tenderedpaperscount > tenderedTotalArray[passing_value_index + 1])) {
$scope.templateModal.body = "Are you sure you want to update this value?"
$scope.templateModal.save = function () {
vm.updatingCells4(tenderedpaperscount, tenderedTotalArray, key1);
modalService.close('rec_progress');
};
modalService.load('rec_progress');
} else {
//$scope.templateModal.body = "";
$scope.templateModal.body = "Did you save all data before you close this election?"
$scope.templateModal.save = function () { $scope.closeStation(); };
}
}
};
//modalcolouredfooter
$scope.template = "views/templatemodal/modalcolouredfooter.html";
$scope.templateModal = {
id: "rec_progress",
header: "Confirmation",
body: "Did you save all data before you close this election?",
closeCaption: "No",
saveCaption: "Yes",
save: function () {
$scope.closeStation();
},
close: function () { modalService.close('rec_progress'); }
};
vm.onRouteChangeOff = $scope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {
if (!angular.equals(vm.org_state, vm.progressSummery)) {
vm.newUrl = newUrl;
event.preventDefault();
$scope.templateModal.body = "You have unsaved data before navigating to another page. Are you sure you want to leave this page?"
$scope.templateModal.save = function () {
vm.onRouteChangeOff();
$location.path($location.url(vm.newUrl).hash()); //Go to page
modalService.close('rec_progress');
};
modalService.load('rec_progress');
}
else {
$scope.templateModal.body = "Did you save all data before you close this election?"
$scope.templateModal.save = function () { $scope.closeStation(); };
}
});
vm.updatingCells = function (ballotpaperscount, ballotTotalArray, key1) {
var passing_value_index = 0;
passing_value_index = ballotTotalArray.indexOf(ballotpaperscount);
for (var i = 0; i < key1; i++) {
if (vm.progressSummery[i].ballotpapers > ballotpaperscount) {
vm.progressSummery[i].ballotpapers = 0;
}
}
};
vm.updatingCells2 = function (ballotpaperscount, ballotTotalArray, key1) {
var passing_value_index = 0;
passing_value_index = ballotTotalArray.indexOf(ballotpaperscount);
for (var i = 0; i < key1; i++) {
if (vm.progressSummery[i].ballotpapers > ballotpaperscount) {
vm.progressSummery[i].ballotpapers = 0;
}
}
/*if(ballotTotalArray[key1+1]<ballotpaperscount) {
vm.progressSummery[key1+1].ballotpapers = 0;
}*/
for (var i = (key1 + 1) ; i < vm.progressSummery.length; i++) {
vm.progressSummery[i].ballotpapers = 0;
}
};
vm.updatingCells3 = function (tenderedpaperscount, tenderedTotalArray, key1) {
var passing_value_index = 0;
passing_value_index = tenderedTotalArray.indexOf(tenderedpaperscount);
for (var i = 0; i < key1; i++) {
if (vm.progressSummery[i].tenballotpapers > tenderedpaperscount) {
vm.progressSummery[i].tenballotpapers = 0;
}
}
};
vm.updatingCells4 = function (tenderedpaperscount, tenderedTotalArray, key1) {
var passing_value_index = 0;
passing_value_index = tenderedTotalArray.indexOf(tenderedpaperscount);
for (var i = 0; i < key1; i++) {
if (vm.progressSummery[i].tenballotpapers > tenderedpaperscount) {
vm.progressSummery[i].tenballotpapers = 0;
}
}
if (tenderedTotalArray[key1 + 1] < tenderedpaperscount) {
vm.progressSummery[key1 + 1].tenballotpapers = 0;
}
};
vm.checkAssigningValues = function (value, key, updateObj) {
if (key > 0) {
var prevValue = parseInt(updateObj[key - 1].ballotpapers);
if (prevValue > 0) {
var diffBallotPapers = parseInt(value.ballotpapers) - parseInt(updateObj[key - 1].ballotpapers);
if (diffBallotPapers > 0) {
return diffBallotPapers;
} else {
return 0;
}
} else {
var ballotOtherSet = [];
var count3 = 0;
var lastValue = 0;
for (var i = 0; i < key; i++) {
if (parseInt(updateObj[i].ballotpapers) > 0) {
ballotOtherSet[count3] = parseInt(updateObj[i].ballotpapers);
count3++;
}
}
if (ballotOtherSet.length > 0) {
lastValue = parseInt(ballotOtherSet[count3 - 1]);
}
if (parseInt(value.ballotpapers) > 0) {
if (lastValue > 0) {
var checkPositiveValue = (parseInt(value.ballotpapers) - parseInt(lastValue));
if (checkPositiveValue > 0) {
return checkPositiveValue;
}
} else {
var diffBallotPapers2 = parseInt(value.ballotpapers) - parseInt(vm.polling_Station_Election.ballotstart);
if (diffBallotPapers2 > 0) {
return diffBallotPapers2;
}
}
} else {
if (parseInt(value.ballotpapers) == 0) {
return 0;
}
}
}
} else {
if (parseInt(value.ballotpapers) > 0) {
var checkPositiveValue = (parseInt(value.ballotpapers) - parseInt(vm.polling_Station_Election.ballotstart));
if (checkPositiveValue > 0) {
return checkPositiveValue;
}
} else {
if (parseInt(value.ballotpapers) == 0) {
return 0;
}
}
}
}
vm.checkAssigningValues2 = function (value, key, updateObj) {
if (key > 0) {
var prevValue = parseInt(updateObj[key - 1].tenballotpapers);
if (prevValue > 0) {
var diffBallotPapers = parseInt(value.tenballotpapers) - parseInt(updateObj[key - 1].tenballotpapers);
if (diffBallotPapers > 0) {
return diffBallotPapers;
} else {
return 0;
}
} else {
var ballotOtherSet = [];
var count3 = 0;
var lastValue = 0;
for (var i = 0; i < key; i++) {
if (parseInt(updateObj[i].tenballotpapers) > 0) {
ballotOtherSet[count3] = parseInt(updateObj[i].tenballotpapers);
count3++;
}
}
if (ballotOtherSet.length > 0) {
lastValue = ballotOtherSet[count3 - 1];
}
if (parseInt(value.tenballotpapers) > 0) {
if (lastValue > 0) {
var checkPositiveValue = (parseInt(value.tenballotpapers) - parseInt(lastValue));
if (checkPositiveValue > 0) {
return checkPositiveValue;
}
} else {
var diffBallotPapers2 = parseInt(value.tenballotpapers) - parseInt(vm.polling_Station_Election.tenderstart);
if (diffBallotPapers2 > 0) {
return diffBallotPapers2;
}
}
} else {
if (parseInt(value.tenballotpapers) == 0) {
return 0;
}
}
}
} else {
if (parseInt(value.tenballotpapers) > 0) {
var checkPositiveValue = (parseInt(value.tenballotpapers) - parseInt(vm.polling_Station_Election.tenderstart));
if (checkPositiveValue > 0) {
return checkPositiveValue;
}
} else {
if (parseInt(value.tenballotpapers) == 0) {
return 0;
}
}
}
}
vm.checkPassingValidValues = function (updateObj, ballotpapers, key) {
if (key > 0) {
var prevValue = parseInt(updateObj[key - 1].ballotpapers);
if (prevValue > 0) {
if (parseInt(ballotpapers) > 0) {
var diffBallotPapers = parseInt(ballotpapers) - parseInt(updateObj[key - 1].ballotpapers);
if (diffBallotPapers < 0) {
return false;
} else if (diffBallotPapers > 0) {
return true;
} else {
return false;
}
} else if (parseInt(ballotpapers) < 0) {
return false;
} else {
return true;
}
} else {
var ballotOtherSet = [];
var count3 = 0;
var lastValue = 0;
for (var i = 0; i < key; i++) {
if (parseInt(updateObj[i].ballotpapers) > 0) {
ballotOtherSet[count3] = parseInt(updateObj[i].ballotpapers);
count3++;
}
}
if (ballotOtherSet.length > 0) {
lastValue = parseInt(ballotOtherSet[count3 - 1]);
}
if (parseInt(ballotpapers) > 0) {
if (lastValue > 0) {
var checkPositiveValue = (parseInt(ballotpapers) - parseInt(lastValue));
if (checkPositiveValue < 0) {
return false;
} else {
return true;
}
} else {
var diffBallotPapers2 = parseInt(ballotpapers) - parseInt(vm.polling_Station_Election.ballotstart);
if (diffBallotPapers2 < 0) {
return false;
} else {
return true;
}
}
} else if (parseInt(ballotpapers) < 0) {
return false;
} else {
return true;
}
}
} else {
if (parseInt(ballotpapers) > 0) {
var checkPositiveValue = (parseInt(ballotpapers) - parseInt(vm.polling_Station_Election.ballotstart));
if (checkPositiveValue < 0) {
return false;
} else {
return true;
}
} else if (parseInt(ballotpapers) < 0) {
return false;
} else {
return true;
}
}
}
vm.checkPassingValidValues2 = function (updateObj, tenballotpapers, key) {
if (key > 0) {
var prevValue = parseInt(updateObj[key - 1].tenballotpapers);
if (prevValue > 0) {
if (parseInt(tenballotpapers) > 0) {
var diffBallotPapers = parseInt(tenballotpapers) - parseInt(updateObj[key - 1].tenballotpapers);
if (diffBallotPapers < 0) {
return false;
} else if (diffBallotPapers > 0) {
return true;
} else {
return false;
}
} else if (parseInt(tenballotpapers) < 0) {
return false;
} else {
return true;
}
} else {
var ballotOtherSet = [];
var count3 = 0;
var lastValue = 0;
for (var i = 0; i < key; i++) {
if (parseInt(updateObj[i].tenballotpapers) > 0) {
ballotOtherSet[count3] = parseInt(updateObj[i].tenballotpapers);
count3++;
}
}
if (ballotOtherSet.length > 0) {
lastValue = parseInt(ballotOtherSet[count3 - 1]);
}
if (parseInt(tenballotpapers) > 0) {
if (lastValue > 0) {
var checkPositiveValue = (parseInt(tenballotpapers) - parseInt(lastValue));
if (checkPositiveValue < 0) {
return false;
} else {
return true;
}
} else {
var diffBallotPapers2 = parseInt(tenballotpapers) - parseInt(vm.polling_Station_Election.tenderstart);
if (diffBallotPapers2 < 0) {
return false;
} else {
return true;
}
}
} else if (parseInt(tenballotpapers) < 0) {
return false;
} else {
return true;
}
}
} else {
if (parseInt(tenballotpapers) > 0) {
var checkPositiveValue = (parseInt(tenballotpapers) - parseInt(vm.polling_Station_Election.tenderstart));
if (checkPositiveValue < 0) {
return false;
} else {
return true;
}
} else if (parseInt(tenballotpapers) < 0) {
return false;
} else {
return true;
}
}
}
}])
.directive('focusctrl', function ($timeout, $parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind("focus", function (e) {
if (element.val() == 0) element.val('');
})
element.bind("blur", function (e) {
if (element.val() == '') { element.val(0); }
});
}
}
});
|
export const fetchCandidates = (data) => {
return{
type: 'ADD_CANDIDATES',
payload: data
}
} |
import axios from 'axios'
/* Given an upper limit, returns an object with the median and error
If error occurs, median will be null and error will contain a message.
If successful, median will be an array of numbers, and error will be null
*/
export function getMedianPrime(limit) {
return axios.get(`/api/median-prime?limit=${limit}`).then(response => response.data.medianPrime)
}
|
$(document).ready(function() {
$('.scrollbars').ClassyScroll();
});
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 75) {
$(".clearHeader").addClass("darkHeader");
} else {
$(".clearHeader").removeClass("darkHeader");
}
});
function toggler(divId) {
$("#" + divId).toggle();
}
$(document).ready(function() {
$(".menu-icon").on("click", function() {
$("nav ul").toggleClass("showing");
});
});
// Scrolling Effect
$(window).on("scroll", function() {
if($(window).scrollTop()) {
$('nav').addClass('black');
}
else {
$('nav').removeClass('black');
}
})
// optional
$('#blogCarousel').carousel({
interval: 5000
});
$(document).ready(function() {
$('.owl-carousel').owlCarousel({
loop: true,
margin: 10,
responsiveClass: true,
responsive: {
0: {
items: 1,
nav: true
},
600: {
items: 3,
nav: false
},
1000: {
items: 5,
nav: true,
loop: false,
margin: 20
}
}
})
})
window.onload = function() {
document.getElementById('button').onclick = function() {
document.getElementById('modalOverlay').style.display = 'none'
};
};
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
$( '#topheader .navbar-nav a' ).on( 'click', function () {
$( '#topheader .navbar-nav' ).find( 'li.active' ).removeClass( 'active' );
$( this ).parent( 'li' ).addClass( 'active' );
});
$(document).ready(function ()
{
$("#new-colplaint").click(function()
{
$("#new-colplaint-show:hidden").show('slow');
$("#exisiting-cmplaint-show").hide();
$("#show-me-three").hide();
});
$("#new-colplaint").click(function()
{
if($('new-colplaint').prop('checked')===false)
{
$('#new-colplaint-show').hide();
}
});
$("#existing-colplaint").click(function()
{
$("#exisiting-cmplaint-show:hidden").show('slow');
$("#new-colplaint-show").hide();
$("#show-me-three-ad").hide();
});
$("#existing-colplaint").click(function()
{
if($('see-me-two-ad').prop('checked')===false)
{
$('#exisiting-cmplaint-show').hide();
}
});
$("#look-me-ad").click(function()
{
$("#show-me-three-ad:hidden").show('slow');
$("#new-colplaint-show").hide();
$("#exisiting-cmplaint-show").hide();
});
$("#look-me-ad").click(function()
{
if($('see-me-three-ad').prop('checked')===false)
{
$('#show-me-three-ad').hide();
}
});
});
$(document).ready(function ()
{
$("#watch-me").click(function()
{
$("#show-me:hidden").show('slow');
$("#show-me-two").hide();
$("#show-me-three").hide();
});
$("#watch-me").click(function()
{
if($('watch-me').prop('checked')===false)
{
$('#show-me').hide();
}
});
$("#see-me").click(function()
{
$("#show-me-two:hidden").show('slow');
$("#show-me").hide();
$("#show-me-three").hide();
});
$("#see-me").click(function()
{
if($('see-me-two').prop('checked')===false)
{
$('#show-me-two').hide();
}
});
$("#look-me").click(function()
{
$("#show-me-three:hidden").show('slow');
$("#show-me").hide();
$("#show-me-two").hide();
});
$("#look-me").click(function()
{
if($('see-me-three').prop('checked')===false)
{
$('#show-me-three').hide();
}
});
});
$(document).ready(function ()
{
$("#watch-me-ad").click(function()
{
$("#show-me-ad:hidden").show('slow');
$("#show-me-two-ad").hide();
$("#show-me-three").hide();
});
$("#watch-me-ad").click(function()
{
if($('watch-me-ad').prop('checked')===false)
{
$('#show-me-ad').hide();
}
});
$("#see-me-ad").click(function()
{
$("#show-me-two-ad:hidden").show('slow');
$("#show-me-ad").hide();
$("#show-me-three-ad").hide();
});
$("#see-me-ad").click(function()
{
if($('see-me-two-ad').prop('checked')===false)
{
$('#show-me-two-ad').hide();
}
});
$("#look-me-ad").click(function()
{
$("#show-me-three-ad:hidden").show('slow');
$("#show-me-ad").hide();
$("#show-me-two-ad").hide();
});
$("#look-me-ad").click(function()
{
if($('see-me-three-ad').prop('checked')===false)
{
$('#show-me-three-ad').hide();
}
});
});
var x, i, j, selElmnt, a, b, c;
/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
selElmnt = x[i].getElementsByTagName("select")[0];
/*for each element, create a new DIV that will act as the selected item:*/
a = document.createElement("DIV");
a.setAttribute("class", "select-selected");
a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
x[i].appendChild(a);
/*for each element, create a new DIV that will contain the option list:*/
b = document.createElement("DIV");
b.setAttribute("class", "select-items select-hide");
for (j = 1; j < selElmnt.length; j++) {
/*for each option in the original select element,
create a new DIV that will act as an option item:*/
c = document.createElement("DIV");
c.innerHTML = selElmnt.options[j].innerHTML;
c.addEventListener("click", function(e) {
/*when an item is clicked, update the original select box,
and the selected item:*/
var y, i, k, s, h;
s = this.parentNode.parentNode.getElementsByTagName("select")[0];
h = this.parentNode.previousSibling;
for (i = 0; i < s.length; i++) {
if (s.options[i].innerHTML == this.innerHTML) {
s.selectedIndex = i;
h.innerHTML = this.innerHTML;
y = this.parentNode.getElementsByClassName("same-as-selected");
for (k = 0; k < y.length; k++) {
y[k].removeAttribute("class");
}
this.setAttribute("class", "same-as-selected");
break;
}
}
h.click();
});
b.appendChild(c);
}
x[i].appendChild(b);
a.addEventListener("click", function(e) {
/*when the select box is clicked, close any other select boxes,
and open/close the current select box:*/
e.stopPropagation();
closeAllSelect(this);
this.nextSibling.classList.toggle("select-hide");
this.classList.toggle("select-arrow-active");
});
}
function closeAllSelect(elmnt) {
/*a function that will close all select boxes in the document,
except the current select box:*/
var x, y, i, arrNo = [];
x = document.getElementsByClassName("select-items");
y = document.getElementsByClassName("select-selected");
for (i = 0; i < y.length; i++) {
if (elmnt == y[i]) {
arrNo.push(i)
} else {
y[i].classList.remove("select-arrow-active");
}
}
for (i = 0; i < x.length; i++) {
if (arrNo.indexOf(i)) {
x[i].classList.add("select-hide");
}
}
}
/*if the user clicks anywhere outside the select box,
then close all select boxes:*/
document.addEventListener("click", closeAllSelect);
|
let restaurant1 = {
name: "Paesano",
totalSeats: 10,
numberOfCustomers: 8,
address: {
city: "Glasgow",
area: "center",
},
menu: ["pizza", "calzone", "salad"],
};
let restaurant2 = {
name: "Ubiquitous Chip",
totalSeats: 20,
numberOfCustomers: 10,
address: {
city: "Glasgow",
area: "west",
},
menu: ["salad", "chocolate cake", "roast lamb"],
};
let restaurant3 = {
name: "Monkeyz",
totalSeats: 15,
numberOfCustomers: 8,
address: {
city: "Glasgow",
area: "center",
},
menu: ["stew", "chocolate cake", "panini"],
};
let restaurants = [restaurant1, restaurant2, restaurant3];
/*
DO NOT EDIT ANYTHING ABOVE THIS LINE
WRITE YOUR CODE BELOW
*/
let restaurantFinderApplication = {
applicationName: "Restaurant Finder",
applicationVersion: "1.0",
restaurants: restaurants,
findAvailableRestaurants: function (numberOfPeople) {
// 1. Complete this method findAvailableRestaurants which takes a number of people in parameter
// and returns all the restaurant names which have the required number of seats available at the moment.
},
findRestaurantServingDish: function (dishName) {
// 2. Complete this method findRestaurantServingDish which takes a dish name in parameter
// and returns all the restaurant names serving this dish.
},
countNumberOfRestaurantsInArea: function (area) {
// 3. Complete this method countNumberOfRestaurantsInArea which takes an area of Glasgow in parameter (center, west),
// and returns the number of restaurants in this area.
},
};
/*
DO NOT EDIT ANYTHING BELOW THIS LINE
*/
let restaurantsAvailableFor5People = restaurantFinderApplication.findAvailableRestaurants(
5
);
console.log(
`Find available restaurants for 5 people: Expected result: Ubiquitous Chip,Monkeyz, actual result: ${restaurantsAvailableFor5People}`
);
let restaurantsServingSalad = restaurantFinderApplication.findRestaurantServingDish(
"salad"
);
console.log(
`Find restaurants serving salad: Expected result: Paesano,Ubiquitous Chip, actual result: ${restaurantsServingSalad}`
);
let numberOfRestaurantsInCityCentre = restaurantFinderApplication.countNumberOfRestaurantsInArea(
"center"
);
console.log(
`Number of restaurants in city centre: Expected result: 2, actual result: ${numberOfRestaurantsInCityCentre}`
); |
// https://github.com/jigish/slate/wiki
// https://github.com/jigish/dotfiles/blob/master/slate.js
S.cfga({
"keyboardLayout": "qwerty",
"nudgePercentOf": "windowSize",
"resizePercentOf": "windowSize",
"focusCheckWidthMax": 3000,
"undoOps": ""
});
var monitorMac = "1920x1200";
var monitorTID = "1920x1080";
// Operations
var lapSkype = S.op("corner", {
"screen": monitorMac,
"direction": "top-left",
"width": "screenSizeX/3",
"height": "screenSizeY"
});
var lapMain = lapSkype.dup({"direction": "top-right",
"width": "2*screenSizeX/3"});
var lapMaximize = lapSkype.dup({"direction": "top-left",
"width": "screenSizeX"});
var lapFocusSublime = S.op("focus", {
// only one of these is required. if both are specified it will use app.
"app" : "Sublime Text 2"
});
// common layout hashes
var lapMainHash = {
"operations" : [lapMain],
"ignore-fail" : true,
"repeat" : true
};
var skypeHash = {
"operations" : [lapSkype, lapMain],
"ignore-fail" : true,
"title-order" : ["Contacts"],
"repeat-last" : true
};
var oneMonitorLayout = S.lay("oneMonitor", {
"Sublime Text 2" : lapMainHash,
"iTerm" : lapMainHash,
"Terminal" : lapMainHash,
"Google Chrome" : lapMainHash,
"Xcode" : lapMainHash,
"GitX" : lapMainHash,
"Firefox" : lapMainHash,
"Safari" : lapMainHash,
});
S.def([monitorMac], oneMonitorLayout);
var oneMonitor = S.op("layout", {"name": oneMonitorLayout});
var twoMonitor = S.op("layout", {"name": oneMonitorLayout});
var universalLayout = function() {
S.log("SCREEN COUNT: " + S.screenCount());
if (S.screenCount() === 2) {
twoMonitor.run();
} else if (S.screenCount() === 1) {
oneMonitor.run();
} else {
S.log("WTF! more than two monitors?");
}
};
S.bnda({
"space:ctrl,cmd" : universalLayout,
"left:ctrl,cmd" : lapSkype,
"right:ctrl,cmd" : lapMain,
"s:ctrl,cmd": lapFocusSublime,
"=:ctrl,cmd" : lapMaximize,
});
S.log("[SLATE] -------------- Finished Loading Config --------------");
|
/*fetch all team name**/
const Team = require('../models/Team');
const Player = require('../models/Player');
const Coach = require('../models/Coach');
// const Executive = require('../models/Executive');
exports.getIndex = (req, res, next) => {
console.log("This is a message")
Team.fetchAll()
.then(([rows, fieldData]) => {
res.render('Team/Index', {
teams: rows,
pageTitle: 'Shop',
path: '/'
});
})
.catch(err => console.log(err));
};
exports.getTeammname = (req, res, next) => {
Team.fetchAll()
.then(([rows, fieldData]) => {
res.render('Team/Team', {
teams: rows,
pageTitle: 'All Team',
path: '/Team'
});
})
.catch(err => console.log(err));
};
exports.getTeammname2 = (req, res, next) => {
Team.fetchAll()
.then(([rows, fieldData]) => {
res.render('Team/Coach', {
teams: rows,
pageTitle: 'Team_list',
path: '/Coach'
});
})
.catch(err => console.log(err));
};
exports.findplayerGivenTeam = (req, res, next) => {
const Team = req.params.Team;
console.log("This is a message")
Player.findplayerGivenTeam(Team)
.then(([rows, fieldData]) => {
res.render('Team/Team_detail', {
players: rows,
playerID:rows.PID,
pageTitle: 'Team_Info',
path: '/Team'
});
})
};
exports.findCoachGivenTeam = (req, res, next) => {
const Team = req.params.Team;
console.log("This is a Coach")
Coach.findCoachGivenTeam(Team)
.then(([rows, fieldData]) => {
res.render('Team/Coach_detail', {
coach: rows[0],
pageTitle: 'Team_info',
path: '/Coach'
});
})
.catch(err => console.log(err));
};
exports.findExecutiveGivenTeam = (req, res, next) => {
const Team = req.params.Team;
console.log("This is a message")
Executive.findExecutiveGivenTeam(Team)
.then(([rows, fieldData]) => {
res.render('Team/Team', {
teams: rows,
pageTitle: 'All Team',
path: '/Team'
});
})
.catch(err => console.log(err));
};
exports.findStatisticsGivenTeam = (req, res, next) => {
const Team = req.params.Team;
console.log("This is a message")
Team.findStatisticsGivenTeam(Team)
.then(([rows, fieldData]) => {
res.render('Team/Team', {
teams: rows,
pageTitle: 'All Team',
path: '/Team'
});
})
.catch(err => console.log(err));
};
exports.findTeamGivenLocation = (req, res, next) => {
const State = req.params.State;
console.log("This is a State")
console.log(State)
Team.findTeamGivenLocation(State)
.then(([rows, fieldData]) => {
console.log(State)
res.render('Team/Team_Info', {
teams: rows,
pageTitle: 'Find Team by Location',
path: '/Team'
});
})
.catch(err => console.log(err));
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.