text
stringlengths 7
3.69M
|
|---|
define(['./hello_world_2'], function(){
console.log('Hello, world!');
});
|
let CassetteChecker = require('./CassetteChecker');
let ErrorHandler = require('./ErrorHandler');
const maxCassettes = 4;
const cassetteCapacity = 2000;
class Program{
constructor(order){
this.order = order;
this.cassettes = [];
this.orderChecker();
}
orderChecker() {
this.errorHandler = new ErrorHandler(this.order);
if(this.errorHandler.isValid === true){
this.cassetteValidator();
this.cassetteChecker = new CassetteChecker(this.cassettes,this.errorHandler, this.numberOfCassettes, cassetteCapacity);
} else {
console.log(this.errorHandler.errorMessage);
};
};
cassetteValidator() {
if(this.order[0][0] == 'cassettes'){
this.numberOfCassettes = this.order[0][1];
this.cassettes = this.order.slice(1,5);
} else {
this.numberOfCassettes = maxCassettes;
this.cassettes = this.order;
};
};
}
module.exports = Program;
|
// content of index.js
const http = require('http')
const port = 3112
const sleep = require('system-sleep');
const fs = require('fs');
const version = process.env.version;
const requestHandler = (request, response) => {
console.log(request.url)
if (fs.existsSync('/var/tmp/sleep')) {
console.log('Found file');
sleep(15000);
}
response.end('Hello Node.js test Server, version: ' + version );
}
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err);
}
console.log(`server is listening on ${port}`);
})
|
import Web3 from 'web3';
async function loadProvider() {
const mnemonic = 'silly funny task remove diamond maximum rack awesome sting chalk recycle also social banner verify';
const { HDWalletProvider } = (await import('@catalyst-net-js/truffle-provider'));
return new HDWalletProvider(mnemonic, 'http://localhost:5005/api/eth/request');
}
async function loadTxLib() {
return import('@catalyst-net-js/tx');
}
const RandExp = require('randexp');
const { numberToHex, toWei, bytesToHex } = Web3.utils;
// export async function sendTransaction(to, value, gasPrice, gasLimit) {
// const provider = (await loadProvider());
// const web3 = new Web3(provider);
// const address = provider.getAddress(0);
// console.log(address);
// await web3.eth.sendTransaction({
// from: address,
// to: to,
// value: numberToHex(toWei(value.toString(), 'ether')),
// gasPrice: numberToHex(toWei(gasPrice.toString(), 'gwei')),
// gasLimit: numberToHex(gasLimit),
// data: '0x0',
// }, function(error, hash){
// if(error) console.error(error);
// console.log('Hash: ', hash);
// return hash;
// });
// }
const web3 = new Web3('http://localhost:5005/api/eth/request');
function broadcastTransaction(raw) {
return new Promise((resolve, reject) => {
web3.eth.sendSignedTransaction(raw, function (error, hash) {
if (error)
reject(error);
console.log('Hash: ', hash);
return resolve(hash);
});
});
}
async function constructTransaction(nonce, gasPrice, gasLimit, to, value) {
const { Transaction } = (await loadTxLib());
const tx = new Transaction({
nonce: `0x${parseInt(nonce, 16)}`,
gasPrice: numberToHex(toWei(gasPrice.toString(), 'gwei')),
gasLimit: numberToHex(gasLimit),
to: to,
value: numberToHex(toWei(value.toString(), 'ether')),
data: '0x0',
});
return tx;
}
export async function sendRawTransaction(to, value, gasPrice, gasLimit) {
const provider = (await loadProvider());
const address = provider.getAddress(0);
const nonce = await web3.eth.getTransactionCount(address);
// Construct transaction
const tx = await constructTransaction(nonce, gasPrice, gasLimit, to, value);
await tx.sign(provider.wallets[address].getPrivateKey());
const raw = bytesToHex(tx.serialize());
// broadcast transaction
return broadcastTransaction(raw);
}
export async function spamTransactions(transactionsNo) {
const provider = (await loadProvider());
const address = provider.getAddress(0);
const nonce = await web3.eth.getTransactionCount(address);
// const accounts = web3.eth.getAccounts(console.log);
let transactions = [];
for (let i = 0; i < transactionsNo; i++) {
let to = new RandExp("^0x[0-9a-fA-F]{40}$").gen(); //'0x91470b2c2ab22f6eccf7b347138a43c781b8b831'
// console.log(to);
const tx = await constructTransaction(
nonce + i,
(3 + 4 * Math.random()).toFixed(2),
(21005 + 3000 * Math.random()).toFixed(0),
to,
(0.05 + 0.1 * Math.random()).toString()
);
await tx.sign(provider.wallets[address].getPrivateKey());
transactions.push(broadcastTransaction(bytesToHex(tx.serialize())));
}
return transactions;
}
|
const remote = require('electron').remote;
const React = require('react');
const PropTypes = require('prop-types');
const classNames = require('classnames');
const ChatActions = require('../../actions/chat-actions.js');
const Constants = require('../../constants');
class FriendsListItem extends React.Component {
_getOnlineStateClassName() {
if(this.props.user.relationshipEnum === Constants.SteamEnums.EFriendRelationship.IgnoredFriend) {
return 'blocked-border';
}
if(this.props.user.inGame) {
return 'in-game-border';
}
switch (this.props.user.stateEnum) {
case 0:
return 'offline-border';
default:
return 'online-border';
}
}
_getRelationshipStateClassName() {
return `relationship-${ this.props.user.relationshipEnum}`;
}
_onDoubleClick(event) {
event.preventDefault();
if(this.props.user.relationshipEnum === Constants.SteamEnums.EFriendRelationship.Friend) {
ChatActions.openChat(this.props.user);
}
}
_onContextMenu(event) {
event.preventDefault();
const menu = require('../../ui/menus/friends-menu.js')(this.props.user);
menu.popup(remote.getCurrentWindow());
}
render() {
const classNameItem = classNames('list-group-item', this._getRelationshipStateClassName(), this._getOnlineStateClassName());
const classNameAvatar = classNames('img-circle', 'media-object', 'pull-left', this._getOnlineStateClassName());
return (
<li className={classNameItem} onDoubleClick={(e) => this._onDoubleClick(e)} onContextMenu={(e) => this._onContextMenu(e)}>
<img className={classNameAvatar} src={this.props.user.avatar} width="32" height="32" />
<div className="media-body">
<strong>{this.props.user.username}</strong>
<p>{this.props.user.state}</p>
</div>
</li>
);
}
};
FriendsListItem.propTypes = {
user: PropTypes.object.isRequired
};
module.exports = FriendsListItem;
|
const qs = document.querySelector.bind(document);
const copied = document.querySelector('#copied');
const delay = ms => new Promise(res => setTimeout(res, ms));
function ifEmpty(input, fb) {
return input ? `${input}` : fb;
}
function doReplace() {
const device_name = qs('#device_name').value;
const device_codename = qs('#device_codename').value;
const name = qs('#name').value;
const bugs = ifEmpty(qs('#bugs').value, 'You tell me');
const donate_url = ifEmpty(qs('#donate_url').value, 'https://t.me/EvolutionX/');
const xda_url = qs('#xda_url').value;
const kernel_source_url = qs('#kernel_source_url').value;
qs('#output').value =
template.replace(/##DEVICE_NAME##/g, device_name)
.replace(/##DEVICE_CODENAME##/g, device_codename)
.replace(/##NAME##/g, name)
.replace(/##BUGS##/g, bugs)
.replace(/##DONATE_URL##/g, donate_url)
.replace(/##XDA_URL##/g, xda_url)
.replace(/##KERNEL_SOURCE_URL##/g, kernel_source_url)
.replace(/--/g, '\n')
}
qs('#form').addEventListener('submit', (event) => {
event.preventDefault();
doReplace();
copied.style.opacity = 1;
document.getElementById('output').select();
document.execCommand('copy');
document.getElementById('copied').innerHTML = 'Copied';
delay(2000).then(() => {
copied.style.opacity = 0;
});
});
|
import { useState, useEffect } from 'react'
import { axios_instance } from '../index'
import {subjects} from './Subjects'
import {Link} from 'react-router-dom';
const UserTableListing = (props) => {
const [hours, setHours] = useState([]);
const getHours = async (username) => {
const res = await axios_instance.get(`/user/${username}/tutoring_history?hours=true`)
return res.data;
}
useEffect(() => {
if (props.username) {
getHours(props.username)
.then((res) => {
const hoursFormatted = [];
for(const subject in res){
hoursFormatted.push(<div>{subject} : {res[subject]}</div>)
}
return hoursFormatted;
})
.then((res)=>{
setHours(res);
})
}
else {
console.log("NO USER FOUND")
}
}, [])
return (
<tr className="userListing">
<td>{props.full_name}</td>
<td><Link to={`/user/${props.username}`}>{props.username}</Link></td>
<td>{props.email}</td>
<td>{props.us_phone_number}</td>
<td>{props.roles}</td>
<td>{props.tutor_subjects && props.tutor_subjects.length !== 0 ? props.tutor_subjects.join(", ") : "N/A"}</td>
<td>{props.tutor_subjects && props.problem_subjects.length !== 0 ? props.problem_subjects : "N/A"}</td>
<td>{hours}</td>
</tr>
);
}
export default UserTableListing;
|
import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom';
import { useContext } from 'react';
import AuthContext from '../contexts/AuthContext';
import NewsList from './NewsList';
import NewsView from './NewsView';
import Page404 from './Page404';
import Welcome from './Welcome';
export default function RouteWrapper() {
const { token } = useContext(AuthContext);
return (
<Router>
<div className="page">
{token &&
<Switch>
<Route exact path="/">
<Redirect to="/news" />
</Route>
<Route exact path="/news" component={NewsList} />
<Route exact path="/news/:id" component={NewsView} />
<Route component={Page404} />
</Switch>
}
{!token &&
<Switch>
<Route exact path="/" component={Welcome} />
<Route>
<Redirect to="/" />
</Route>
</Switch>
}
</div>
</Router>
);
}
|
/*
Date Typer
Navigation in time space by typing, dragging and scrolling.
Author
H. R. Baer
hbaer@ethz.ch
Version 1
11.09.2015
*/
+function(global) {
"use strict";
// D A T E T Y P E R
var dateTyper = function(selector, dateFormatter) {
// HTML text input element selector for the date.
var dateTyperInput = document.querySelector(selector);
// The function that formats a date.
dateFormatter = dateFormatter || function(date) { return date.toString(); };
// Regular expression used to split a date string.
var separator = /[\.\-\/:,\s]+/g;
// Object holding the results of the learned date format.
var memory = { index: [], pos: [], months: [] };
// Number of pixels for one unit.
var pixelsPerUnit = 5;
// The updated date.
var upDate;
// The selected field index.
var currentField = 0;
// Make sure Array's find and findIndex methods are available
if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function(cb) {
for (var i = 0; i < this.length; ++i) {
if (cb(this[i], i, this)) {
return i;
}
}
return -1;
}
}
if (!Array.prototype.find) {
Array.prototype.find = function(cb) {
return this[this.findIndex(cb)];
}
}
// Splits a date string into its components.
function splitDate(dateString) {
return dateString.split(separator);
}
// Returns the field for a given name.
function findFieldByName(name) {
return memory.index.find(function(field) { return field.name === name; });
}
// Returns the field for the given index.
function findFieldByIndex(index) {
return memory.index.find(function(field) { return field.index === index; });
}
// Analyzes a date string and stores the current date values.
function analyzeDate(dateString) {
var fields = splitDate(dateString);
memory.index.forEach(function(v) {
switch (v.name) {
case 'month':
var value = fields[v.index]
if (+value) {
v.value = +value - 1;
}
else {
var month = memory.months.find(function(m) { return m.name.match(new RegExp('^' + value, 'i')); });
if (month) {
v.value = month.value;
}
}
break;
default:
v.value = +fields[v.index];
break;
}
})
}
// Recreates the date string from the current date values.
function updateDate() {
upDate = new Date(0);
memory.pos.forEach(function(v) {
v.update(upDate, v.value);
});
upDate = isNaN(upDate.valueOf()) ? new Date() : upDate;
dateTyperInput.value = dateFormatter(upDate);
}
// L E A R N
// Empirically learns the fields of a date string.
function learn() {
// Creates an array of the components of a date string.
function createTestFields(year, month, day, hour, min, sec) {
return splitDate(dateFormatter(new Date(year, month, day, hour, min, sec)));
}
// Determine the fields of the date
var testValues1 = [2001, 1, 1, 10, 34, 56];
var testValues2 = [2001, 1, 1, 11, 34, 56];
var testValues3 = [2001, 2, 1, 10, 34, 56];
// Array resonsible for the proper handling of date components.
var fields = [
{ name: 'year' , pos: 0, update: function(date, value) { date.setFullYear(value); } },
{ name: 'min' , pos: 4, update: function(date, value) { date.setMinutes(value); } },
{ name: 'sec' , pos: 5, update: function(date, value) { date.setSeconds(value); } },
{ name: 'day' , pos: 2, update: function(date, value) { date.setDate(value); } },
{ name: 'hour' , pos: 3, update: function(date, value) { date.setHours(value); } },
{ name: 'month', pos: 1, update: function(date, value) { date.setMonth(value); } }
];
// Three test date strings used to determine the components of the date string.
function testFields(tv1, tv2, tv3) {
var tf1 = createTestFields.apply(null, tv1);
var tf2 = createTestFields.apply(null, tv2);
var tf3 = createTestFields.apply(null, tv3);
var t1 = function(field) { return tf1.findIndex(function(v) { return !field.index && tv1[field.pos] === +v }) };
var t2 = function(field) { return tf1.findIndex(function(v, i) { return !field.index && tf2[i] - v == 1}) };
var t3 = function(field) { return tf1.findIndex(function(v, i) { return !field.index && tf3[i] != v }) };
return function(fields) {
fields.forEach(function(field) {
switch (field.name) {
case 'hour':
field.index = t2(field);
break;
case 'month':
field.index = t3(field);
break;
default:
field.index = t1(field);
break;
}
if (field.index >= 0) {
memory.index.push(field);
memory.pos.push(field);
}
});
}
}
// Actually determines the date components and creates two arrays:
// one by ascending indices and one by ascending positions.
var test = testFields(testValues1, testValues2, testValues3);
test(fields);
memory.index.sort(function(a, b) {
return a.index - b.index;
});
memory.pos.sort(function(a, b) {
return a.pos - b.pos;
});
// Extract the names of the months.
var monthField = findFieldByName('month');
if (monthField) {
var monthIndex = monthField.index;
for (var month = 0; month < 12; month += 1) {
testValues1[1] = month;
var testFields = createTestFields.apply(null, testValues1);
memory.months.push({ name: testFields[monthIndex], value: month })
}
}
}
learn();
// Dispatches a change event.
function dispatchChangeEvent(value) {
var evt = new CustomEvent('change', {
detail: {
valueAsDate: value,
valueAsNumber: value.valueOf()
}
});
dateTyperInput.dispatchEvent(evt);
}
// Initial date: uses either HTML's data attribute or the current date.
var date = dateTyperInput.dataset.date ? new Date(+dateTyperInput.dataset.date) : new Date();
dateTyperInput.value = dateFormatter(date);
dateTyperInput.spellcheck = false;
// Shows the specified selection.
function showSelection(field, start, end) {
field.setSelectionRange(start, end);
}
// Selects the currently active date component.
function selectField(input) {
createFieldSpans(input);
var numFields = memory.index.length;
currentField = (currentField + numFields) % numFields;
var span = memory.index[currentField];
showSelection(input, span.from, span.to);
}
// Creates spans for each date component.
function createFieldSpans(input) {
var match, from = 0, to, spans = [];
var i = 0;
while ((match = separator.exec(input.value)) != null) {
to = match.index;
spans.push([from, to]);
from = to + match[0].length;
i += 1;
}
spans.push([from, input.value.length]);
memory.index.forEach(function(v, i) {
v.from = spans[v.index][0];
v.to = spans[v.index][1];
})
}
// Selects field from current cursor position
function choseDateComponent(input) {
var start = input.selectionStart;
createFieldSpans(input);
memory.index.forEach(function(v, i) {
if (v.from <= start && start <= v.to + 1) {
showSelection(input, v.from, v.to);
currentField = i;
}
});
}
// Increases or decreases the selected date component.
function changeDateComponent(input, value) {
analyzeDate(input.value);
var field = memory.index[currentField];
field.value += value;
updateDate();
selectField(input);
dispatchChangeEvent(upDate);
}
// Move the date component selection.
function moveDateComponent(input, value) {
currentField += value;
selectField(input);
}
// EVENT HANDLING
// Handles key-down events.
dateTyperInput.addEventListener('keydown', function(evt) {
var text = this.value, start = this.selectionStart, end = this.selectionEnd;
var selectedText = text.substring(start, end);
var key = evt.keyCode || evt.which;
switch(key) {
// Moves selection to next field on the right.
case 39:
case 190:
moveDateComponent(this, +1);
evt.preventDefault();
break;
// Moves selection to next field on the left.
case 37:
case 188:
moveDateComponent(this, -1);
evt.preventDefault();
break;
// Increases the selected date component value.
case 40:
changeDateComponent(this, +1);
evt.preventDefault();
break;
// Decreases the selected date component value.
case 38:
changeDateComponent(this, -1);
evt.preventDefault();
break;
// Updates on pressing enter.
case 13:
analyzeDate(this.value);
updateDate();
dispatchChangeEvent(upDate);
selectField(this);
evt.preventDefault();
break;
}
});
var lastPos, dragEnabled = false;
// Shows date selection on mouse up
dateTyperInput.addEventListener('mouseup', function(evt) {
choseDateComponent(this);
evt.preventDefault();
});
// Changes the date component by wheel action.
dateTyperInput.addEventListener('wheel', function(evt) {
var delta = evt.deltaX | evt.deltaY;
changeDateComponent(this, -delta / Math.abs(delta));
evt.preventDefault();
});
dateTyperInput.addEventListener("touchstart", function(evt) {
var touch = event.touches[0];
lastPos = { x: touch.screenX, y: touch.screenY };
selectField(this);
});
dateTyperInput.addEventListener("touchend", function(evt) {
setTimeout(function() {
choseDateComponent(dateTyperInput);
}, 100);
});
dateTyperInput.addEventListener("touchmove", function(evt) {
var touch = event.touches[0];
var dy = ((touch.screenY - lastPos.y) / pixelsPerUnit) | 0;
if (dy != 0) {
changeDateComponent(this, dy);
lastPos.y = touch.screenY;
}
evt.preventDefault();
});
// Initializes drag and drop.
dateTyperInput.addEventListener('dragstart', function(evt) {
lastPos = { x: evt.screenX, y: evt.screenY };
dragEnabled = true;
});
// Changes date component when dragging a field.
dateTyperInput.addEventListener('drag', function(evt) {
if (dragEnabled && evt.screenX != 0 && evt.screenY != 0) {
var dy = ((evt.screenY - lastPos.y) / pixelsPerUnit) | 0;
if (dy != 0) {
changeDateComponent(this, dy);
lastPos.y = evt.screenY;
}
}
evt.preventDefault();
});
// Disables drop action
dateTyperInput.addEventListener('drop', function(evt) {
evt.preventDefault();
});
return {
domElement: dateTyperInput,
setDate: function(date) {
dateTyperInput.value = dateFormatter(upDate = date);
},
getDate: function() {
return upDate;
}
};
}
global.dateTyper = dateTyper;
}(window);
|
/*
* Copyright 2014 Jive Software
*
* 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.
*/
/**
overrides jive-sdk/routes/oauth.js to do something useful,
like storing access token for the viewer
*/
var url = require('url');
var util = require('util');
var jive = require('jive-sdk');
var mustache = require('mustache');
var sdkInstance = require('jive-sdk/jive-sdk-service/routes/oauth');
var myOauth = Object.create(sdkInstance);
var libDir = process.cwd() + "/lib/";
var placeStore = require( libDir + "github4jive/placeStore");
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// public
module.exports = myOauth;
myOauth.fetchOAuth2Conf = function() {
jive.logger.debug("fetchOAuth2Conf ...");
return jive.service.options['github']['oauth2'];
};
myOauth.oauth2SuccessCallback = function( state, originServerAccessTokenResponse, callback ) {
jive.logger.debug("oauth2SuccessCallback ...");
jive.logger.debug('State', state);
jive.logger.debug('GitHub Response: ', originServerAccessTokenResponse['entity']);
var placeRef = state.context.place;
var tokenID = jive.util.guid();
var tokenRaw = originServerAccessTokenResponse['entity']['body'].toString();
var tokenParams = tokenRaw.split('&');
var token = {};
tokenParams.forEach(function (p) {
if (p.indexOf('access_token') == 0) {
token['access_token'] = decodeURIComponent(p.split("=")[1]);
}
if (p.indexOf('scope') == 0) {
token['scope'] = decodeURIComponent(p.split("=")[1]);
}
if (p.indexOf('token_type') == 0) {
token['token_type'] = decodeURIComponent(p.split("=")[1]);
}
});
var toStore = {"github": {
userID : state['viewerID'],
tokenID : tokenID,
token: token
}};
placeStore.save( placeRef, toStore).then( function() {
callback({'ticket': tokenID });
});
};
myOauth.getTokenStore = function() {
return placeStore;
};
|
/**
* Created by Tomasz Jodko on 2016-06-07.
*/
app.controller('PriorityController', ['$scope', '$rootScope', 'priorityFactory', '$location', function ($scope, $rootScope, priorityFactory, $location) {
$scope.saveNewPriority = function () {
$scope.newPriority.id = 0;
priorityFactory.savePriority($scope.newPriority, function (resp) {
console.log(resp);
$scope.priorities.push(resp);
$('#newPriorityType').val('');
$('#newPriorityTimeUnit').val('');
$scope.newPriority.ilosc = 1;
$("#success-alert").show();
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").hide();
});
});
};
$scope.deselect = function(){
$scope.selectedPriority.isSelected = false;
};
$scope.savePriority = function () {
priorityFactory.savePriority($scope.selectedPriority, function (resp) {
console.log(resp);
$("#success-alert2").show();
$("#success-alert2").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert2").hide();
});
});
};
$scope.deletePriority = function () {
var id = $scope.selectedPriority.id;
priorityFactory.deletePriority(id);
var index = $scope.priorities.indexOf($scope.selectedPriority);
$scope.priorities.splice(index, 1);
};
// fired when table rows are selected
$scope.$watch('displayedCollection', function (row) {
// get selected row
var selectedCount = 0;
row.filter(function (r) {
if (r.isSelected) {
console.log(r);
$scope.selectedPriority = r;
selectedCount++;
}
});
if (selectedCount > 0) {
$('#selectedPriorityForm').collapse("show")
} else {
$('#selectedPriorityForm').collapse("hide")
}
}, true);
priorityFactory.getPriorities(function (resp) {
$scope.priorities = resp;
console.log(resp);
});
if (!$rootScope.authenticated || $rootScope.adminWew === false) {
$location.path('/'); //redirect user to home.
}
}]);
|
const ELTCoin = artifacts.require('./ELTCoin.sol');
module.exports = deployer => {
deployer.deploy(ELTCoin);
};
|
import axios from "axios";
const actions = {
login({ commit }, data) {
return new Promise((resolve, reject) => {
axios
.post(
"https://backend-front-test.dev.echo-company.ru/api/auth/login",
data
)
.then(response => {
const token = response.data.token;
const success = response.data.success;
commit("authSuccess", { token, success });
resolve(response);
})
.catch(error => reject(error.response));
});
},
registration({ commit }, data) {
return new Promise((resolve, reject) => {
axios
.post(
"https://backend-front-test.dev.echo-company.ru/api/user/registration",
data
)
.then(response => {
const token = response.data.token;
const success = response.data.success;
commit("authSuccess", { token, success });
resolve(response);
})
.catch(error => reject(error.response));
});
},
forgotPasswordStart(context, data) {
return new Promise((resolve, reject) => {
axios
.post(
"https://backend-front-test.dev.echo-company.ru/api/user/forgot-start",
data
)
.then(response => {
resolve(response);
})
.catch(error => reject(error.response));
});
},
forgotPasswordEnd({ commit }, data) {
return new Promise((resolve, reject) => {
axios
.post(
"https://backend-front-test.dev.echo-company.ru/api/user/forgot-end",
data
)
.then(response => {
const token = response.data.token;
const success = response.data.success;
commit("authSuccess", { token, success });
resolve(response.data);
})
.catch(error => reject(error.response));
});
}
};
export default actions;
|
function main( input ) {
var opt = 1;
while ( input > 0) {
opt = opt * input;
input --;
}
//Enter your code here
process.stdout.write(opt);
}
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input;
});
process.stdin.on("end", function () {
main(stdin_input);
});
|
import React, { useState } from "react";
import { useAlert } from "react-alert";
import api from "../../services/api";
import { setSession } from "../../services/auth";
import "./styles.css";
export default function Login(props) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const alert = useAlert();
async function handleSignIn(e) {
e.preventDefault();
try {
const response = await api.post("login", { email, password });
await setSession(response.data._id);
props.history.push("/dash");
} catch (error) {
alert.error("Usuário ou senha ivalida!!");
}
}
return (
<div id="container">
<form onSubmit={handleSignIn}>
<input
type="email"
onChange={e => setEmail(e.target.value)}
required
value={email}
className="txt"
placeholder="Digite seu E-mail"
/>
<input
type="password"
required
onChange={e => setPassword(e.target.value)}
value={password}
className="txt"
placeholder="Digite sua Senha"
/>
<input type="submit" className="btn" />
</form>
</div>
);
}
|
import React from 'react';
import './header.scss'
import logo from '../../image/logo.png'
function HeaderTitle () {
return (
<div className="header-title">
<img src={logo} alt="logo"/>
</div>
)
}
export default HeaderTitle
|
const menu = {
_courses: {
appetizers: [],
mains: [],
desserts: []
},
get appetizers() {
return this._courses.appetizers;
},
get mains() {
return this._courses.mains;
},
get desserts() {
return this._courses.desserts;
},
set appetizers(appetizersIn) {
this._courses.appetizers = appetizersIn;
},
set mains(mainsIn) {
this._courses.mains = mainsIn;
},
set desserts(dessertsIn) {
this._courses.desserts = dessertsIn;
},
get courses(){
return this._courses;
},
addDishToCourse(course, name, price) {
const dish = {
name,
price
};
this._courses[course].push(dish);
},
getRandomDishFromCourse(courseName) {
const dishes = this._courses[courseName];
const randomIndex = Math.floor(Math.random() * dishes.length);
return dishes[randomIndex];
},
generateRandomMeal() {
const appetizer = this.getRandomDishFromCourse('appetizers');
const main = this.getRandomDishFromCourse('mains');
const dessert = this.getRandomDishFromCourse('desserts');
let totalPrice = appetizer.price + main.price + dessert.price;
return `Your meal is ${appetizer.name}, ${main.name} and ${dessert.name} The price is ${totalPrice}.`;
}
};
menu.addDishToCourse('appetizers', 'Caesar Salad', 4.25);
menu.addDishToCourse('appetizers', 'Greek Salad', 3.55);
menu.addDishToCourse('appetizers', 'Hallumi Salad', 4.25);
menu.addDishToCourse('mains', 'Lamb', 8.72);
menu.addDishToCourse('mains', 'Salmon', 13.6);
menu.addDishToCourse('mains', 'Chopped Pork on grill', 13.6);
menu.addDishToCourse('desserts', 'Chocolate Triffle', 6.25);
menu.addDishToCourse('desserts', 'Tiramisu', 3.25);
menu.addDishToCourse('desserts', 'Eclairs', 4.35);
let meal = menu.generateRandomMeal();
console.log(meal);
|
/**
* Created by gullumbroso on 30/04/2016.
*/
angular.module('DealersApp')
.factory('Dialogs', ['$rootScope', '$mdDialog', '$mdMedia', 'Translations', function DialogsFactory($rootScope, $mdDialog, $mdMedia, Translations) {
var service = {};
var customFullscreen = $mdMedia('xs');
service.showSignUpViewerDialog = showSignUpViewerDialog;
service.showSignInDialog = showSignInDialog;
service.confirmDialog = confirmDialog;
service.showAlertDialog = showAlertDialog;
service.showLoadingDialog = showLoadingDialog;
service.hideDialog = hideDialog;
return service;
function showSignUpViewerDialog(ev, email) {
return $mdDialog.show({
controller: 'SignInDialogController',
templateUrl: 'app/components/views/sign-in/sign-up-viewer-dialog.view.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: customFullscreen, // Only for -xs, -sm breakpoints.
locals: {tab: null, isViewer: null, email: email}
})
}
/**
* Presents the sign in dialog (sign up and log in) and returns the promise.
* @param ev - The event that triggered the function.
* @param tabIndex - the index of the selected option (sign up is 0, log in is 1).
* @param isViewer - true if triggered the sign up for viewers.
* @return {Promise} - the promise that will run if process finished successfully.
*/
function showSignInDialog(ev, tabIndex, isViewer) {
return $mdDialog.show({
controller: 'SignInDialogController',
templateUrl: 'app/components/views/sign-in/sign-in-dialog.view.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: customFullscreen,
locals: {tab: tabIndex, isViewer: isViewer, email: null}
});
}
/**
* Returns the confirm dialog object of type confirm (doesn't show it).
*
* @param title - the title of the alert dialog.
* @param content - the content of the alert dialog.
* @param confirm - the confirm button title.
* @param ev - the event that triggered the alert.
* @return {mdDialog} - the confirm dialog object.
*/
function confirmDialog(title, content, confirm, ev) {
return $mdDialog.confirm(ev)
.parent(angular.element(document.body))
.clickOutsideToClose(false)
.title(title)
.textContent(content)
.ariaLabel('Confirm Dialog')
.ok(confirm)
.cancel(Translations.general.cancel)
.targetEvent(ev);
}
/**
* Presents the alert dialog.
* @param title - the title of the alert dialog.
* @param content - the content of the alert dialog.
* @param ev - the event that triggered the alert.
*/
function showAlertDialog(title, content, ev) {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.clickOutsideToClose(true)
.title(title)
.textContent(content)
.ariaLabel('Alert Dialog')
.ok(Translations.general.gotIt)
.targetEvent(ev)
);
}
/**
* Presents the loading dialog.
* @param message - the message to present in the loading dialog.
* @param ev - the event that triggered the loading.
*/
function showLoadingDialog(message, ev) {
$mdDialog.show({
templateUrl: 'app/components/views/loading-dialog.view.html',
parent: angular.element(document.body),
targetEvent: ev,
controller: 'LoadingDialogController',
locals: {message: message},
escapeToClose: false
});
}
/**
* Hides the dialog.
* @param ev - the event that triggered the hiding.
*/
function hideDialog(ev) {
$mdDialog.hide();
}
}]);
|
const { Pagination } = require('@limit0/mongoose-graphql-pagination');
module.exports = function paginablePlugin(schema) {
// eslint-disable-next-line no-param-reassign
schema.statics.paginate = function paginate({ criteria, pagination, sort } = {}) {
return new Pagination(this, { criteria, pagination, sort });
};
};
|
import React from 'react'
import { View, Button } from 'react-native'
export default function Home(props) {
return (
<View style={{ flex: 1, justifyContent: 'space-around', alignItems: 'center' }}>
<Button title="Satu" onPress={() => { props.navigation.navigate('Satu') }} />
<Button title="Dua" onPress={() => { props.navigation.navigate('Dua') }} />
<Button title="Tiga" onPress={() => { props.navigation.navigate('Tiga') }} />
<Button title="Empat" onPress={() => { props.navigation.navigate('Empat') }} />
<Button title="Lima" onPress={() => { props.navigation.navigate('Lima') }} />
</View>
)
}
|
export const generateRandomDataSet = (opts = {}) => {
const {
count,
max,
min,
useWholeNumbers
} = opts;
const dataSet = [];
const generateRandomNumber = () => Math.random() * (max - min) + min;
const roundNumber = num => Math.round(num);
for (let i = 0; i < count; i++) {
const entry = {
x: i,
y: useWholeNumbers
? roundNumber(generateRandomNumber())
: generateRandomNumber()
};
dataSet.push(entry);
}
return dataSet;
};
export default generateRandomDataSet;
|
var pattern_2flags_8c =
[
[ "lookup_tag", "pattern_2flags_8c.html#ad74affc6a3ff7fa89a1bb4953f3c7006", null ],
[ "lookup_op", "pattern_2flags_8c.html#aa38a5696bc6986833d624995a8beb23f", null ],
[ "Flags", "pattern_2flags_8c.html#a669a98acfe6bfc0997fc263c94eab77b", null ]
];
|
/**
* Created by Makeev Evgeny on 17.08.18.
*/
//import app from './server';
const app = require('./server');
console.log('IN MEADOWLARK', module.parent);
app.listen(app.get('port'), () => console.log(`running express in http://localhost:${app.get('port')} press CTRL+C to quit`));
|
import React, { useEffect, useContext } from "react";
import Feed from "./Feed";
import FeedsContext from "../../context/feed/feedsContext";
const Feeds = () => {
//useContext
const feedsContext = useContext(FeedsContext);
useEffect(() => {
feedsContext.getFeeds();
}, []);
const renderFeeds = (feeds) => {
if (feeds.length === 0) {
return <div>No Feed</div>;
} else {
return feeds
.slice(0)
.reverse()
.map((feed) => {
return (
<Feed
username={feed.firstName + " " + feed.lastName}
message={feed.message}
likes={feed.likes}
unlikes={feed.unlikes}
childComments={feed.childComments}
key={feed.postID}
postID={feed.postID}
courseName={feed.courseName}
/>
);
});
}
};
return <div>{renderFeeds(feedsContext.feeds)}</div>;
};
export default Feeds;
|
/*
* Copyright 2013-2014 Riskified.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0.html
*
* or in the "license" file accompanying this file. This file 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.
*/
// A Riskified API v2 sample usage.
// Configure your shop settings and the riskified environment you work
// against.
var riskifiedBaseUrl = "https://sandbox.riskified.com";
var authToken = "AUTH_TOKEN";
var shopDomain = "my.shop.domain";
var request = require("request");
var crypto = require("crypto");
var _ = require("lodash");
var order = require("./sample_order.json");
/*
* createHmac:
*
* Creates verification hash from the supplied auth_token
* and data.
*/
function createHmac(token, data) {
return crypto.createHmac('sha256', token).update(data).digest('hex');
}
/*
* generateRequest:
*
* Generates object that matches the input for the 'request'
* library.
*/
function generateRequest(path, order) {
var orderString = JSON.stringify({'order': order});
verificationHash = createHmac(authToken, orderString);
return {
url: riskifiedBaseUrl + path,
body: orderString,
headers: {
"Content-Type": "application/json; charset=utf-8",
"ACCEPT": "application/vnd.riskified.com; version=2",
"X_RISKIFIED_SHOP_DOMAIN": shopDomain,
"X_RISKIFIED_HMAC_SHA256": verificationHash
},
method: 'POST'
};
}
/*
* Partially applied funciton to generate create-order request. The
* same could be created for the other API actions.
*/
var generateCreateOrderRequest = _.partial(generateRequest, "/api/create");
// Create the order
var createOrderRequest = generateCreateOrderRequest(order);
request(createOrderRequest, function(err, res) {
if (err) {
return console.error(err);
}
var body = JSON.parse(res.body);
if (res.statusCode === 200) {
if (body.warnings) {
console.log("WARNINGS:");
body.warnings.forEach(function(msg) {
console.log("* " + msg);
});
}
console.log(body.order);
} else {
console.log("ERROR:");
console.log("* " + body.error.message);
}
});
|
import React from "react"
import { connect } from "react-redux";
import Item from "../Movies/Item"
import Translate from "../../components/Translate/Index"
import dynamic from 'next/dynamic'
import Link from "../../components/Link"
const Carousel = dynamic(() => import("../Slider/Index"), {
ssr: false,
loading: () => <div className="shimmer-elem">
<div className="heading shimmer"></div>
<div className="grid">
<div className="item shimmer"></div>
<div className="item shimmer"></div>
<div className="item shimmer"></div>
<div className="item shimmer"></div>
<div className="item shimmer"></div>
</div>
</div>
});
class CarouselMovies extends React.Component {
constructor(props) {
super(props)
let propsData = {...props}
this.state = {
movies: propsData.movies,
key: 1,
type:"movie",
language:propsData.i18n.language,
}
this.slider = null
}
static getDerivedStateFromProps(nextProps, prevState) {
if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){
return null;
}
if(prevState.localUpdate){
return {...prevState,localUpdate:false}
} else if (nextProps.movies != prevState.movies || nextProps.i18n.language != prevState.language) {
return { movies: nextProps.movies,language:nextProps.i18n.language }
} else{
return null
}
}
componentDidMount(){
this.props.socket.on('movieDeleted', data => {
let id = data.movie_id
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const movies = [...this.state.movies]
movies.splice(itemIndex, 1);
this.setState({localUpdate:true, movies: movies })
}
})
this.props.socket.on('ratedItem', data => {
let id = data.itemId
let type = data.itemType
let Statustype = data.type
let rating = data.rating
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1 && type == this.state.type + "s") {
const items = [...this.state.movies]
const changedItem = {...items[itemIndex]}
changedItem.rating = rating
items[itemIndex] = changedItem
this.setState({localUpdate:true, movies: items })
}
});
this.props.socket.on('unwatchlaterMovies', data => {
let id = data.itemId
let ownerId = data.ownerId
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const items = [...this.state.movies]
const changedItem = {...items[itemIndex]}
if (this.props.pageInfoData && this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.watchlater_id = null
}
items[itemIndex] = changedItem
this.setState({localUpdate:true, movies: items })
}
});
this.props.socket.on('watchlaterMovies', data => {
let id = data.itemId
let ownerId = data.ownerId
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const items = [...this.state.movies]
const changedItem = {...items[itemIndex]}
if (this.props.pageInfoData && this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.watchlater_id = 1
}
items[itemIndex] = changedItem
this.setState({localUpdate:true, movies: items })
}
});
this.props.socket.on('unfavouriteItem', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (type == this.state.type + "s") {
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const movies = [...this.state.movies]
const changedItem = {...movies[itemIndex]}
changedItem.favourite_count = changedItem.favourite_count - 1
if (this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.favourite_id = null
}
movies[itemIndex] = changedItem
this.setState({localUpdate:true, movies: movies })
}
}
});
this.props.socket.on('favouriteItem', data => {
let id = data.itemId
let type = data.itemType
let ownerId = data.ownerId
if (type == this.state.type + "s") {
const itemIndex = this.getItemIndex(id)
if (itemIndex > -1) {
const movies = [...this.state.movies]
const changedItem = {...movies[itemIndex]}
changedItem.favourite_count = changedItem.favourite_count + 1
if (this.props.pageInfoData.loggedInUserDetails && this.props.pageInfoData.loggedInUserDetails.user_id == ownerId) {
changedItem.favourite_id = 1
}
movies[itemIndex] = changedItem
this.setState({localUpdate:true, movies: movies })
}
}
});
this.props.socket.on('likeDislike', data => {
let itemId = data.itemId
let itemType = data.itemType
let ownerId = data.ownerId
let removeLike = data.removeLike
let removeDislike = data.removeDislike
let insertLike = data.insertLike
let insertDislike = data.insertDislike
if (itemType == this.state.type + "s") {
const itemIndex = this.getItemIndex(itemId)
if (itemIndex > -1) {
const movies = [...this.state.movies]
const changedItem = {...movies[itemIndex]};
let loggedInUserDetails = {}
if (this.props.pageInfoData && this.props.pageInfoData.loggedInUserDetails) {
loggedInUserDetails = this.props.pageInfoData.loggedInUserDetails
}
if (removeLike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = null
changedItem['like_count'] = parseInt(changedItem['like_count']) - 1
}
if (removeDislike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = null
changedItem['dislike_count'] = parseInt(changedItem['dislike_count']) - 1
}
if (insertLike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = "like"
changedItem['like_count'] = parseInt(changedItem['like_count']) + 1
}
if (insertDislike) {
if (loggedInUserDetails.user_id == ownerId)
changedItem['like_dislike'] = "dislike"
changedItem['dislike_count'] = parseInt(changedItem['dislike_count']) + 1
}
movies[itemIndex] = changedItem
this.setState({localUpdate:true, movies: movies })
}
}
});
}
getItemIndex(item_id) {
const movies = [...this.state.movies];
const itemIndex = movies.findIndex(p => p["movie_id"] == item_id);
return itemIndex;
}
render() {
if (!this.state.movies || !this.state.movies.length) {
return null
}
const content = this.state.movies.map(result => {
return <div key={result.movie_id}><Item {...this.props} {...result} movie={result} /></div>
})
return (
<div className="VideoRoWrap">
<div className="container">
<div className="row">
<div className="col-md-12">
<div className="titleWrap">
{
this.props.pageInfoData.themeType == 2 && this.props.seemore ?
<Link href={`/${this.props.headerType == "Series" ? "series" : "movies"}?${this.props.type ? "type" : "sort"}=${this.props.type ? this.props.type : this.props.sort}`}>
<a className="link">
<span className="title">
<React.Fragment>
{
this.props.headerTitle ?
this.props.headerTitle :
null
}
{Translate(this.props,this.props.title)}
</React.Fragment>
</span>
</a>
</Link>
:
<span className="title">
<React.Fragment>
{
this.props.headerTitle ?
this.props.headerTitle :
null
}
{Translate(this.props, this.props.title ? this.props.title : `Popular ${this.props.headerType}`)}
</React.Fragment>
</span>
}
{
this.props.seemore && this.state.movies.length > 8 ?
this.props.headerType == "Series" ?
<Link href={`/series?${this.props.type ? "type" : "sort"}=${this.props.type ? this.props.type : this.props.sort}`}>
<a className="seemore_link">
{Translate(this.props, "See more")}
</a>
</Link>
:
<Link href={`/movies?${this.props.type ? "type" : "sort"}=${this.props.type ? this.props.type : this.props.sort}`}>
<a className="seemore_link">
{Translate(this.props, "See more")}
</a>
</Link>
: null
}
</div>
</div>
</div>
<div className="row">
<div className="col-md-12">
{
<Carousel {...this.props} carouselType="movie" items={content} itemAt1024={4} itemAt1200={4} itemAt900={3} itemAt600={2} itemAt480={1} >
{content}
</Carousel>
}
</div>
</div>
</div>
</div>
)
}
}
const mapStateToProps = state => {
return {
pageInfoData: state.general.pageInfoData
};
};
export default connect(mapStateToProps, null, null)(CarouselMovies)
|
const LocalStrategy = require('passport-local').Strategy;
const Admin = require('../models/admin');
const bcrypt = require('bcrypt');
const serializeUser = (user, done) => {
done(null, user._id);
}
const deserializeUser = (id, done) => {
Admin.findById(id, (err, user) => {
done(err, user);
});
}
const signupStrategy = new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, (req, username, password, done) => {
const confirmPassword = req.body.confirm_password;
const phone = req.body.phone;
const address = req.body.address;
const fullname = req.body.fullname;
const email = req.body.email;
if (username && password && confirmPassword && email && phone && address && fullname) {
let data = {
username,
password,
confirmPassword,
phone,
address,
fullname,
email
}
if (password != confirmPassword) {
return done(null, false, req.flash('message', 'pass'), req.flash('data', data));
}
Admin.findOne({ 'uasername': username }, (err, user) => {
if (user) {
return done(null, false, req.flash('message', 'uasername'), req.flash('data', data));
}
const newAdmin = new Admin({
username: username,
password: password,
email: email,
phone: phone,
address: address,
fullname: fullname
});
newAdmin.save(err => {
if (err) {
console.log('err', err);
return done(null, false, req.flash('message', 'save'));
} else {
return done(null, newAdmin);
}
});
});
} else {
return done(null, false, req.flash('message', 'disfull'));
}
});
const loginStrategy = new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true,
}, (req, username, password, done) => {
try {
Admin.findOne({ 'username': username }, (err, user) => {
if (err) {
done(err);
}
if (!user) {
console.log('Admin not found username', username);
return done(null, false, req.flash('message', 'username'));
}
bcrypt.compare(password, user.password, (err, result) => {
if (err || result == false) {
return done(null, false, req.flash('message', 'password'));
}
return done(null, user);
});
});
} catch (e) {
console.log(e.message());
}
});
module.exports = {
serializeUser,
deserializeUser,
signupStrategy,
loginStrategy
}
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2016-11-04.
*/
'use strict';
// services
const LKE = require('../../../../services');
const Access = LKE.getAccess();
const Application = LKE.getApplication();
const Utils = LKE.getUtils();
// locals
const api = require('../../api');
/**
* @apiDefine ReturnApplication
*
* @apiSuccess {number} id ID of the application
* @apiSuccess {string} name Name of the application
* @apiSuccess {string} apiKey Generated key (32 hexadecimal characters)
* @apiSuccess {boolean} enabled Whether the application is enabled
* @apiSuccess {string[]} rights Enabled actions for the application
* @apiSuccess {type:group[]} groups Groups the application can act on behalf of
* @apiSuccess {string[]} createdAt Creation date in ISO-8601 format
* @apiSuccess {string[]} updatedAt Last update date in ISO-8601 format
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "id": 1,
* "enabled": true,
* "apiKey": "76554081e5b0a2d7852deec4990ebc58",
* "name": "test_app",
* "rights": [
* "visualization.create",
* "visualization.edit",
* "visualization.read",
* "visualization.delete"
* ],
* "groups": [
* {
* "id": 3,
* "name": "read and edit",
* "builtin": true,
* "sourceKey": "584f2569"
* }
* ],
* "createdAt": "2017-01-24T11:16:03.445Z",
* "updatedAt": "2017-01-24T11:16:03.445Z"
* }
*/
/**
* @apiDefine ReturnApplications
*
* @apiSuccess {object[]} applications Applications
* @apiSuccess {number} applications.id ID of the application
* @apiSuccess {string} applications.name Name of the application
* @apiSuccess {string} applications.apiKey Generated key (32 hexadecimal characters)
* @apiSuccess {boolean} applications.enabled Whether the application is enabled
* @apiSuccess {string[]} applications.rights Enabled actions for the application
* @apiSuccess {type:group[]} applications.groups Groups the application can act on behalf of
* @apiSuccess {string[]} applications.createdAt Creation date in ISO-8601 format
* @apiSuccess {string[]} applications.updatedAt Last update date in ISO-8601 format
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "id": 1,
* "enabled": true,
* "apiKey": "e3fadcbd39ddb21fe8ecb206dadff36d",
* "name": "test_app",
* "rights": [
* "visualization.create",
* "visualization.edit",
* "visualization.read",
* "visualization.delete"
* ],
* "groups": [
* {
* "id": 3,
* "name": "read and edit",
* "builtin": true,
* "sourceKey": "584f2569"
* }
* ],
* "createdAt": "2017-01-24T11:14:51.337Z",
* "updatedAt": "2017-01-24T11:31:13.769Z"
* },
* {
* "id": 2,
* "enabled": true,
* "apiKey": "738c9f3b66aad7218c69843a78905ccd",
* "name": "test_app_2",
* "rights": [
* "visualization.read"
* ],
* "groups": [
* {
* "id": 2,
* "name": "read",
* "builtin": true,
* "sourceKey": "584f2569"
* }
* ],
* "createdAt": "2017-01-24T11:16:02.417Z",
* "updatedAt": "2017-01-24T11:16:02.417Z"
* }
* ]
*/
module.exports = function(app) {
app.all('/api/admin/applications*', api.proxy(req => Access.hasAction(req, 'admin.app')));
// ------------------------------------------------------------------------------------------
// Applications
// ------------------------------------------------------------------------------------------
/**
* @api {get} /api/admin/applications Get all the applications
* @apiName GetApplications
* @apiGroup Applications
* @apiPermission action:admin.app
* @apiVersion 1.0.0
*
* @apiDescription Get all the API applications.
*
* @apiUse ReturnApplications
*/
app.get('/api/admin/applications', api.respond(() => {
return Application.getApplications();
}));
/**
* @api {post} /api/admin/applications Create an application
* @apiName CreateApplication
* @apiGroup Applications
* @apiPermission action:admin.app
* @apiVersion 1.0.0
*
* @apiDescription Add a new API application.
*
* @apiParam {string} name Name of the application
* @apiParam {boolean} [enabled=true] Whether the application is enabled
* @apiParam {number[]} groups IDs of the groups the application can act on behalf of
* @apiParam {string[]="visualization.read", "visualization.create", "visualization.edit", "visualization.delete", "visualization.list", "visualizationFolder.create", "visualizationFolder.edit", "visualizationFolder.delete", "visualizationShare.read", "visualizationShare.create", "visualizationShare.delete", "sandbox", "widget.read", "widget.create", "widget.edit", "widget.delete", "graphItem.read", "graphItem.create", "graphItem.edit", "graphItem.delete", "graphItem.search", "savedGraphQuery.read", "savedGraphQuery.create", "savedGraphQuery.edit", "savedGraphQuery.delete", "graph.rawRead", "graph.rawWrite", "graph.shortestPath", "alert.read", "alert.doAction", "schema"} rights Enabled actions for the application
*
* @apiUse ReturnApplication
*/
app.post('/api/admin/applications', api.respond(req => {
return Application.createApplication({
name: req.body.name,
enabled: req.body.enabled,
groups: req.body.groups,
rights: req.body.rights
});
}, 201));
/**
* @api {patch} /api/admin/applications/:id Update an application
* @apiName UpdateApplication
* @apiGroup Applications
* @apiPermission action:admin.app
* @apiVersion 1.0.0
*
* @apiDescription Update an API application.
*
* @apiParam {string} [name] Name of the application
* @apiParam {boolean} [enabled=true] Whether the application is enabled
* @apiParam {number[]} [groups] IDs of the groups the application can act on behalf of
* @apiParam {string[]="visualization.read", "visualization.create", "visualization.edit", "visualization.delete", "visualization.list", "visualizationFolder.create", "visualizationFolder.edit", "visualizationFolder.delete", "visualizationShare.read", "visualizationShare.create", "visualizationShare.delete", "sandbox", "widget.read", "widget.create", "widget.edit", "widget.delete", "graphItem.read", "graphItem.create", "graphItem.edit", "graphItem.delete", "graphItem.search", "savedGraphQuery.read", "savedGraphQuery.create", "savedGraphQuery.edit", "savedGraphQuery.delete", "graph.rawRead", "graph.rawWrite", "graph.shortestPath", "alert.read", "alert.doAction", "schema"} [rights] Enabled actions for the application
*
* @apiUse ReturnApplication
*/
app.patch('/api/admin/applications/:id', api.respond(req => {
return Application.updateApplication({
id: Utils.tryParsePosInt(req.params.id, 'id'),
name: req.body.name,
enabled: req.body.enabled,
groups: req.body.groups,
rights: req.body.rights
});
}, 200));
};
|
import {Box} from "@material-ui/core";
import {useEffect, useState} from "react";
import Configurable from "../Configurable";
import IfBlockConfigurator from "./IfBlockConfigurator";
import ComponentRender from "../ComponentRender";
import {StyledIfBlock} from "./IfBlock.style";
import Select from "~/components/atoms/Select/Select";
import {useRecoilState} from "recoil";
import {updateComponentState} from "~/components/organisms/PageEditor/componentAtoms";
const IfBlock = function ({...props}) {
const [conditionGroup, setConditionGroup] = useState(props.component.data.selectedCondition);
const [updateComponent, setUpdateComponent] = useRecoilState(updateComponentState);
useEffect(() => {
handleSave();
}, [conditionGroup]);
useEffect(() => {
setConditionGroup(props.component.data.selectedCondition);
}, [props.component.data.selectedCondition]);
const handleSave = async () => {
if (conditionGroup != props.component.data.selectedCondition) {
const newComponent = JSON.parse(JSON.stringify(props.component));
newComponent.data.selectedCondition = conditionGroup;
setUpdateComponent(newComponent);
}
};
if (props.liveMode == false) {
return (
<StyledIfBlock liveMode={props.liveMode}>
<Configurable setWidth={900} preview={false} component={props.component} title="Conditioneel blok" configurator={<IfBlockConfigurator />}>
<div className="ifblock-header">
<Select
label="Conditie groep"
onChange={(e) => setConditionGroup(e.target.value)}
value={conditionGroup}
name="conditionGroup"
items={props.component.data.data.map((condition, i) => {
return {label: i + 1 + "/" + props.component.data.data.length + ": " + condition.label, value: i};
})}
/>
</div>
<Component conditionGroup={conditionGroup} {...props} />
</Configurable>
</StyledIfBlock>
);
} else {
return <Component {...props} />;
}
};
const Component = function ({component, conditionGroup, ...props}) {
const data = component.data;
if (props.liveMode == false) {
return <ComponentRender parent={component} component={component.data.data[conditionGroup].children} />;
} else {
var children = null;
data.data.forEach((conditionGroup) => {
if (children == null) {
conditionGroup.conditions.forEach((orCondition) => {
if (children == null) {
var valid = true;
orCondition.forEach((condition) => {
valid = validateCondition(condition);
});
if (valid) children = conditionGroup.children;
}
});
}
});
if (children == null) return <></>;
return (
<>
<ComponentRender parent={component} component={children} />
</>
);
}
};
const validateCondition = function (condition) {
var value = condition.variable;
if (/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/.test(value)) value = Number(value);
var compareValue = condition.value;
if (/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/.test(compareValue)) compareValue = Number(compareValue);
switch (condition.condition) {
case "==":
return value == compareValue;
case "!=":
return value != compareValue;
case ">":
return value > compareValue;
case ">=":
return value >= compareValue;
case "<":
return value < compareValue;
case "<=":
return value <= compareValue;
}
};
export default IfBlock;
|
console.log("my bot app");
var TelegramBot = require('node-telegram-bot-api');
var tg;
function create() {
var token = "351310686:AAFnSsMRKdWg2xHZjef2CcYSUvGEkVBvRPk";
tg = new TelegramBot(token, {
polling: true
});
tg.on('message', onMessage);
tg.on('callback_query', onCallbackQuery);
}
function onCallbackQuery(callbackQuery) {
console.log('callbackQuery:', callbackQuery);
}
function onMessage(message) {
console.log('message:', message);
if (message.text && message.text.toLowerCase() == 'ping') {
tg.sendMessage(message.chat.id, '<pre>член</pre>', {
parse_mode:'HTML'
});
return;
}
//
if (message.text && message.text.toLowerCase() == '/start') {
sendStartMessage(message);
return;
}
}
function sendStartMessage(message) {
var text = 'Чего желаете? ';
//
var SetButton = {
text:"Установить напоминалку",
callback_data:'SetCmd'
}
//
var ClearButton = {
text:"Очистить все напоминалки",
callback_data:'ClearCmd'
}
//
var ShowButton = {
text:"Показать все напоминалки",
callback_data:'ShowCmd'
}
//
var options = {};
options.reply_markup = {};
options.reply_markup.inline_keyboard = [];
options.reply_markup.inline_keyboard.push([SetButton]);
options.reply_markup.inline_keyboard.push([ClearButton]);
options.reply_markup.inline_keyboard.push([ShowButton]);
tg.sendMessage(message.chat.id, text, options);
}
var notes = [];
var rem = 0;
function onCallbackQuery(callbackQuery)
{
console.log('callbackQuery:', callbackQuery);
if (callbackQuery.data == 'SetCmd')
{
var flag = 0;
tg.sendMessage(callbackQuery.message.chat.id,'Введите напоминание и время в формате ЧЧ:ММ');
tg.onText(/(.+) (.+)/, function (msg, match)
{
if (flag != 1)
{
var userId = msg.from.id
var textt = match[1];
var time = match[2];
var timeNow = new Date().getHours()+ ':' + new Date().getMinutes();
notes.push({'uid':userId, 'time':time, 'textt':textt, 'timeNow':timeNow});
rem = rem + 1;
var helpText = "Напоминание установлено!";
tg.sendMessage(callbackQuery.message.chat.id,helpText);
flag = 1;
}
});
} //end Function Set
setInterval(function()
{
for (var i=0; i<notes.length; i++)
{
var curDate = new Date().getHours()+ ':' + new Date().getMinutes();
if (notes [i]['time'] == curDate)
{
tg.sendMessage(notes[i]['uid'],'Напоминалка - установлена в '+ notes[i]['timeNow'] +'\r\n' + notes[i]['textt'] );
notes.splice(i,4); //удаление 1 элемента с индекса i
}
}
},100);
tg.answerCallbackQuery(callbackQuery.id);
if (callbackQuery.data == 'ClearCmd')
{
for(var i=0;i<100;i++)
{
notes.splice(i,4);
}
tg.sendMessage(callbackQuery.message.chat.id,'Удалено ' + rem + ' напоминаний');
tg.sendMessage(callbackQuery.message.chat.id,'Очищено!');
rem = 0;
}
if (callbackQuery.data == 'ShowCmd')
{
tg.sendMessage('Установлено:');
if (rem == 0)
{
tg.sendMessage(callbackQuery.message.chat.id,'Напоминаний нет');
}
else
{
for (i=0; i<notes.length; i++)
{
tg.sendMessage(notes[i]['uid'],'Напоминание ' + '- установлено в '+ notes[i]['timeNow'] +'\r\n' + notes[i]['textt'] +'\r\n' +'time: ' + notes [i]['time']);
}
}
}
};
create();
|
(function () {
// ## Core Constructor
// The Doctape core module consists of a platform-independent
// DoctapeCore-class which holds the configuration and performs
// the OAuth procedures.
var DoctapeCore = this['DoctapeCore'] = function () {
this.options = {
authPt: {
protocol: 'https',
host: 'my.doctape.com',
port: null,
base: '/oauth2'
},
resourcePt: {
protocol: 'https',
host: 'api.doctape.com',
port: null,
base: '/v1'
},
scope: [],
client_id: null,
client_secret: null
};
this._token = {
type: null,
timeout: null,
timestamp: null,
access: null,
refresh: null
};
// This library factors the platform-dependent back-end including
// functions like http-request or getting an access token
// into "environments". The following object has to be filled by
// the environment.
this.env = {
emit: null,
subscribe: null,
unsubscribe: null,
req: null
};
};
// ## Getter / Setter Functions
var setToken = DoctapeCore.prototype.setToken = function (obj) {
this._token.type = obj.token_type;
this._token.timeout = obj.expires_in;
this._token.timestamp = obj.timestamp || (new Date()).getTime();
this._token.access = obj.access_token;
this._token.refresh = obj.refresh_token;
};
var token = DoctapeCore.prototype.token = function () {
return {
token_type: this._token.type,
expires_in: this._token.timeout,
timestamp: this._token.timestamp,
access_token: this._token.access,
refresh_token: this._token.refresh
};
};
var setAuthPt = DoctapeCore.prototype.setAuthPt = function (url) {
var parts = url.match(/([a-z]+):\/\/([^:]+):?([0-9]+)?(\/.*)/);
this.options.authPt.protocol = parts[1] || null;
this.options.authPt.host = parts[2] || null;
this.options.authPt.port = parseInt(parts[3], 10) || null;
this.options.authPt.base = parts[4] || null;
};
var authBase = DoctapeCore.prototype.authBase = function () {
return this.options.authPt.protocol + '://' + this.options.authPt.host +
(this.options.authPt.port ? ':' + this.options.authPt.port : '');
};
var authPath = DoctapeCore.prototype.authPath = function (redirect, type) {
var uri = redirect || 'urn:ietf:wg:oauth:2.0:oob';
return this.options.authPt.base +
'?' + 'response_type=' + (type || 'code') +
'&' + 'client_id=' + encodeURIComponent(this.options.client_id) +
'&' + 'scope=' + encodeURIComponent(this.options.scope.join(' ')) +
'&' + 'redirect_uri=' + uri;
};
var setResourcePt = DoctapeCore.prototype.setResourcePt = function (url) {
var parts = url.match(/([a-z]+):\/\/([^:]+):?([0-9]+)?(\/.*)/);
this.options.resourcePt.protocol = parts[1] || null;
this.options.resourcePt.host = parts[2] || null;
this.options.resourcePt.port = parseInt(parts[3], 10) || null;
this.options.resourcePt.base = parts[4] || null;
};
var resourcePt = DoctapeCore.prototype.resourcePt = function () {
return this.options.resourcePt.protocol + '://' + this.options.resourcePt.host +
(this.options.resourcePt.port ? ':' + this.options.resourcePt.port : '') +
this.options.resourcePt.base;
};
// ## Core Functions
// Not for direct use.
/**
* Perform a standard POST-request to the auth point with raw form post data.
*
* @param {string} path
* @param {Object} data
* @param {function (Object, Object=)} cb
*/
var postAuth = function (path, data, cb) {
var lines = [];
var field;
for (field in data) {
lines.push(field + '=' + encodeURIComponent(data[field]));
}
this.env.req({
method: 'POST',
protocol: this.options.authPt.protocol,
host: this.options.authPt.host,
port: this.options.authPt.port,
path: this.options.authPt.base + path,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
postData: lines.join('&')
}, cb);
};
// ## OAuth functions
// These functions will authorize the client on a doctape
// API server.
/**
* Perform an authorized GET-request using an access-token.
*
* @param {string} endpoint
* @param {function (Object, Object=)} cb
*/
var getResource = DoctapeCore.prototype.getResource = function (endpoint, cb) {
var self = this;
withValidAccessToken.call(this, function (token) {
self.env.req({
method: 'GET',
protocol: self.options.resourcePt.protocol,
host: self.options.resourcePt.host,
port: self.options.resourcePt.port,
path: self.options.resourcePt.base + endpoint,
headers: {'Authorization': 'Bearer ' + token}
}, cb);
});
};
/**
* Perform an authorized POST-request using an access-token.
*
* @param {string} endpoint
* @param {Object} data
* @param {function (Object, Object=)} cb
*/
var postResource = DoctapeCore.prototype.postResource = function (endpoint, data, cb) {
var self = this;
withValidAccessToken.call(this, function (token) {
self.env.req({
method: 'POST',
protocol: self.options.resourcePt.protocol,
host: self.options.resourcePt.host,
port: self.options.resourcePt.port,
path: self.options.resourcePt.base + endpoint,
headers: {'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json; charset=UTF-8'},
postData: JSON.stringify(data)
}, cb);
});
};
/**
* Perform an authorized DELETE-request using an access-token.
*
* @param {string} endpoint
* @param {function (Object, Object=)} cb
*/
var deleteResource = DoctapeCore.prototype.deleteResource = function (endpoint, cb) {
var self = this;
withValidAccessToken.call(this, function (token) {
self.env.req({
method: 'DELETE',
protocol: self.options.resourcePt.protocol,
host: self.options.resourcePt.host,
port: self.options.resourcePt.port,
path: self.options.resourcePt.base + endpoint,
headers: {'Authorization': 'Bearer ' + token}
}, cb);
});
};
/**
* Try to get a valid access token, or throw.
*/
var getValidAccessToken = DoctapeCore.prototype.getValidAccessToken = function () {
if (this._token.access && this._token.timestamp + this._token.timeout * 1000 > (new Date()).getTime()) {
return this._token.access;
} else {
throw new Error('Access Token Expired');
}
};
/**
* Ensure a valid access token, then continue.
*
* @param {function (?string)} fn
*/
var withValidAccessToken = DoctapeCore.prototype.withValidAccessToken = function (fn) {
if (this._token.access && this._token.timestamp + this._token.timeout * 1000 > (new Date()).getTime()) {
return fn(this._token.access);
} else {
var self = this;
var on_refresh = function () {
withValidAccessToken.call(self, fn);
unsubscribe.call(self, 'auth.refresh', on_refresh);
};
subscribe.call(this, 'auth.refresh', on_refresh);
refresh.call(this);
}
};
/**
* Private helper function for registering a new token.
* @param {string} error_msg
*/
var mkTokenRegistry = function (error_msg) {
var self = this;
return function (err, resp) {
self._lock_refresh = undefined;
if (!err) {
var auth = JSON.parse(resp);
if (!auth.error) {
setToken.call(self, auth);
return emit.call(self, 'auth.refresh', token.call(self));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(auth.error));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(err));
};
};
/**
* Exchange an authorization code for an access token and a
* refresh token.
*
* @param {string} code
*/
var exchange = DoctapeCore.prototype.exchange = function (code) {
if (this._lock_refresh === undefined) {
this._lock_refresh = true;
postAuth.call(this, '/token',
{ code: code,
client_id: this.options.client_id,
client_secret: this.options.client_secret,
redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',
grant_type: 'authorization_code' },
mkTokenRegistry.call(this, 'error exchanging token'));
}
};
/**
* Get a new access token by using the already-received refresh
* token.
*/
var refresh = DoctapeCore.prototype.refresh = function () {
if (this._lock_refresh === undefined) {
this._lock_refresh = true;
postAuth.call(this, '/token',
{ refresh_token: this._token.refresh,
client_id: this.options.client_id,
client_secret: this.options.client_secret,
grant_type: 'refresh_token' },
mkTokenRegistry.call(this, 'error refreshing token'));
}
};
// ## Misc functions
/**
* Emit an event.
*/
var emit = DoctapeCore.prototype.emit = function (ev, data) {
this.env.emit(ev, data);
};
/**
* Subscribe to a specific event.
*/
var subscribe = DoctapeCore.prototype.subscribe = function (ev, fn) {
this.env.subscribe(ev, fn);
};
/*
* Unsubscribe from a specific event.
*/
var unsubscribe = DoctapeCore.prototype.unsubscribe = function (ev, fn) {
this.env.unsubscribe(ev, fn);
};
}).call(this);
|
import axios from 'axios';
import {
URL_API,
RM_ALL_FLIGHTS,
ADD_FLIGHTS,
} from "./../../config/types";
export const searchFlights = (
{
from,
to,
outboundDate,
inboundDate,
cabin,
adults,
children,
infants
}) => {
return async (dispatch)=>{
dispatch({type: RM_ALL_FLIGHTS});
const postData = {
tripType: "RT",
from: from, //origem
to: to, //destino
outboundDate: outboundDate,//"2019-12-22", //data de partida
inboundDate: inboundDate,// "2019-12-28", //data de volta
cabin: cabin, //classe econômica (EC) ou executiva (EX)
adults: adults, //adultos
children: children, //crianças
infants: infants //bebês
}
axios.post(`${URL_API }/search?time=${Date.now()}`, postData)
.then(res => {
for(let i=0; i<res.data.airlines.length; i++){
axios.get(`${URL_API }/search/${res.data.id}/flights?airline=${res.data.airlines[i].label}`)
.then(res2 => {
dispatch({type: ADD_FLIGHTS, newValue: res2.data});
})
}
})
};}
|
import React, { useState, useEffect } from 'react';
import styles from './aulasfrequencias.module.css'
import { Radio } from 'semantic-ui-react';
import Button from '@material-ui/core/Button'
import { Upload, message } from 'antd';
import { Input, Label, Col, Row } from 'reactstrap';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import 'antd/dist/antd.css';
import MaskedInput from 'react-text-mask'
import Select from 'react-select';
import { withRouter, Link } from 'react-router-dom'
import api from '../../../service/api'
import moment from 'moment'
const initialState = {
nome: '',
modalidade: '',
dataInicio: '',
dataFinal: '',
rua: '',
bairro: '',
complemento: '',
cep: '',
estado: '',
cidade: '',
atletas: [],
editItem: false,
}
const CadastroAulasFreq = (props) => {
const [state, setState] = useState(
{
nome: '',
modalidades: [],
modalidade: '',
dataInicio: '',
dataFinal: '',
rua: '',
bairro: '',
complemento: '',
cep: '',
estado: '',
cidade: '',
atletas: [],
atletasAula: [],
editItem: false,
loading: false,
}
)
useEffect(() => {
refreshList()
}, [props])
function handleSave() {
const arrayAux = []
state.atletasAula.map((item) => {
return arrayAux.push({
atletaId: item.atletaId
})
})
api.post('api/aula', {
nome: state.nome,
rua: state.rua,
bairro: state.bairro,
cep: state.cep,
estado: state.estado,
cidade: state.cidade,
dataInicial: moment(state.dataInicio).format(),
dataFinal: moment(state.dataFinal).format(),
modalidadeId: state.modalidade,
atletas: arrayAux
})
.then((response) => {
message.success('Sucesso ao gravar Aula')
props.history.push({
pathname: '/AulasFrequencias'
})
})
.catch((error) => {
message.warning('Erro ao gravar Aula')
})
}
async function refreshList() {
const arrayAux = []
const arrayAtletas = []
const arrayModalidade = []
await api.get('api/modalidade').then(async (response) => { await response.data.map((item) => { arrayModalidade.push({ value: item.id, label: item.nome }) }) })
await api.get('api/atleta').then(async (response) => { await response.data.map(async (item) => { arrayAux.push({ value: item.id, label: item.nome }) }) })
if (props.location.state) {
const arrayAuxLocation = []
arrayAux.filter(item1 => {
props.location.state.atletas.filter(item2 => {
if (item1.value === item2.atletaId) {
arrayAuxLocation.push({
value: item2.atletaId,
label: item1.label,
})
}
else {
arrayAtletas.push({
value: item2.atletaId,
label: item1.label,
})
}
})
})
await setState({
nome: props.location.state.nome,
modalidades: arrayModalidade,
modalidade: props.location.state.modalidadeId,
dataInicio: props.location.state.dataInicial,
dataFinal: props.location.state.dataFinal,
rua: props.location.state.rua,
bairro: props.location.state.bairro,
cep: props.location.state.cep,
estado: props.location.state.estado,
cidade: props.location.state.cidade,
atletas: arrayAtletas,
atletasAula: arrayAuxLocation,
editItem: true
})
} else {
setState({ ...state, modalidades: arrayModalidade, atletas: arrayAux })
}
}
function handleEdit() {
const arrayAux = []
if (props.location.state) {
state.atletasAula.map((item) => {
return arrayAux.push({
atletaId: item.atletaId
})
})
api.post('api/aula', {
id: props.location.state.id,
nome: state.nome,
rua: state.rua,
bairro: state.bairro,
cep: state.cep,
estado: state.estado,
cidade: state.cidade,
dataInicial: moment(state.dataInicio).format(),
dataFinal: moment(state.dataFinal).format(),
modalidadeId: state.modalidade,
atletas: arrayAux
})
.then((response) => {
message.success('Sucesso ao editar Aula')
props.history.push({
pathname: '/AulasFrequencias'
})
})
.catch((error) => {
message.warning('Erro ao editar Aula')
})
}
}
function handleChange(event) {
const value = event.target.type === "checkbox" ? event.target.checked : event.target.value;
setState({
...state,
[event.target.name]: value
});
}
function DesMask(e, nome) {
switch (nome) {
case 'cep':
let cep = e.target.value
cep = cep.replace('-', "")
setState({ ...state, cep: cep })
break;
default:
break;
}
}
function setAtletas(event, option) {
if (event !== null) {
event.map((item) => {
if (option.action === "select-option") {
setState({
...state,
atletasAula:
[
...state.atletasAula,
{
atletaId: item.value,
label: item.label,
}
]
})
}
if (option.action === "remove-value") {
const data = state.atletasAula.filter(opt => opt.value !== option.removedValue.value)
if (state.atletasAula.length > 1) {
setState({
...state,
atletasAula:
[
...data
]
})
}
}
})
}
if (event === null) {
const arrayAux = []
setState({
...state,
atletasAula: arrayAux
})
}
}
return (
<div className={styles.container}>
<div className={styles.title}>
Novo Cadastro
</div>
<Row style={{ margin: '0px 0px 0px 28px' }}>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Turma</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="text"
name="nome"
value={state.nome}
onChange={event => handleChange(event)}
/>
</div>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Data Inicio</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="datetime-local"
step="1800"
name="dataInicio"
value={state.dataInicio}
onChange={event => handleChange(event)}
/>
</div>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Data Final</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="datetime-local"
step="1800"
name="dataFinal"
value={state.dataFinal}
onChange={event => handleChange(event)}
/>
</div>
</Row>
<hr className={styles.hr} />
<Row style={{ margin: '0px 0px 0px 28px' }}>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>CEP</label>
<MaskedInput
mask={[/\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/]}
type="text"
name='cep'
className={`form-control ${styles.inputs}`}
keepCharPositions='true'
value={state.cep}
onChange={e => DesMask(e, 'cep')} />
</div>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Cidade</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="text"
name="cidade"
value={state.cidade}
onChange={event => handleChange(event)}
/>
</div>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Estado</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="text"
name="estado"
value={state.estado}
onChange={event => handleChange(event)}
/>
</div>
</Row>
<hr className={styles.hr} />
<Row style={{ margin: '0px 0px 0px 28px' }}>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Endereço</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="text"
name="rua"
value={state.rua}
onChange={event => handleChange(event)}
/>
</div>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Bairro</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="text"
name="bairro"
value={state.bairro}
onChange={event => handleChange(event)}
/>
</div>
<div className={styles.card_inputs} style={{ width: '30%' }}>
<label>Complemento</label>
<Input
className={styles.inputs}
style={{ width: '100%' }}
type="text"
name="complemento"
value={state.complemento}
onChange={event => handleChange(event)}
/>
</div>
</Row>
<hr className={styles.hr} />
<Row style={{ margin: '0px 0px 0px 28px' }}>
<div className={styles.card_inputs} style={{ width: '46.1%' }}>
<label>Atletas</label>
<Select
isMulti
name="atletas"
options={state.atletas}
value={state.atletasAula}
onChange={(event, options) => setAtletas(event, options)}
className="basic-multi-select"
classNamePrefix="select"
/>
</div>
<div className={styles.card_inputs} style={{ width: '46.1%' }}>
<label>Modalidade</label>
<Select
name="modalidade"
options={state.modalidades}
value={state.modalidades.filter(option => option.value === state.modalidade)}
onChange={event => setState({ ...state, modalidade: event.value })}
className="basic-multi-select"
classNamePrefix="select"
/>
</div>
</Row>
<Row style={{ margin: '20px 48px 0px 0px', display: 'flex', justifyContent: 'flex-end' }}>
{state.editItem ?
<Button variant="contained" onClick={() => handleEdit()} style={{ textTransform: 'capitalize', backgroundColor: '#fc9643' }} className={styles.btn_salvar} color="primary">
Editar
</Button>
:
<Button variant="contained" onClick={() => handleSave()} style={{ textTransform: 'capitalize', backgroundColor: '#fc9643' }} className={styles.btn_salvar} color="primary">
Salvar
</Button>
}
<Link to='/AulasFrequencias'>
<Button variant="contained" onClick={() => setState({ ...initialState })} style={{ textTransform: 'capitalize', backgroundColor: '#959C9C' }} className={styles.btn_salvar} color="primary">
Cancelar
</Button>
</Link>
</Row>
</div>
)
}
export default withRouter(CadastroAulasFreq);
|
import React, {Component} from 'react';
import './style.scss';
import 'react-datepicker/dist/react-datepicker.css'
import Loading from '../Loading'
import moment from 'moment'
import {addMission} from '../../AC'
import {connect} from 'react-redux'
import DatePicker from 'react-datepicker'
class AddMission extends Component {
constructor(props) {
super(props);
this.state = {
agent: '',
country: '',
address: '',
startDate: '',
date: ''
}
}
render() {
const {isLoading} = this.props;
return (
<form onSubmit = {this.handleSubmit}>
<div className="form-row">
<div className="form-group col-md-4">
<label htmlFor="agent" className="">Agent ID</label>
<input id="agent" value = {this.state.agent} className='form-control' onChange = {this.handleChange('agent')} />
</div>
<div className="form-group col-md-4">
<label htmlFor="country" className="">Country</label>
<input id="country" value = {this.state.country} className='form-control' onChange = {this.handleChange('country')} />
</div>
<div className="form-group col-md-4">
<label htmlFor="date" className="">Date</label>
<div>
<DatePicker
selected={this.state.startDate}
onChange={this.handleChangeDate}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
dateFormat="MMMM d, yyyy h:mm aa"
timeCaption="time"
className="form-control container-fluid"
/>
</div>
</div>
</div>
<div className="form-row">
<div className="form-group col-md-12">
<label htmlFor="address" className="">Address</label>
<input id="address" value = {this.state.address} className='form-control' onChange = {this.handleChange('address')} />
</div>
</div>
<div className="form-row">
<div className="form-group col-md-6">
<input disabled={this.setDisabled()} className='btn btn-primary' type = "submit" value = "Add Mission"/>
</div>
</div>
{isLoading ? <Loading/> : null}
</form>
)
}
handleSubmit = ev => {
ev.preventDefault();
const {addMission} = this.props;
let dataSend = {
agent: this.state.agent,
country: this.state.country,
address: this.state.address,
date: this.state.date
};
addMission(dataSend);
this.setState({
agent: '',
country: '',
address: '',
startDate: '',
date: ''
})
};
setDisabled = () => {
return (this.state.agent.length === 0 || this.state.country.length === 0 || this.state.address.length === 0 || !this.state.date) ? 'disabled' : null
};
handleChangeDate = (date) => {
this.setState({
startDate: date,
date: moment(date).format('MMM D, YYYY, h:mm:ss A')
});
};
handleChange = type => ev => {
let {value} = ev.target;
this.setState({
[type]: value
});
};
}
export default connect((state) =>({
isLoading: state.missions.loading
}), {addMission})(AddMission)
|
import React from "react";
import "./ChangePin.css";
const ChangePin = () => {
return(
<div>
<h4>Change Transaction Pin</h4>
<p>To Change Transaction pin, type in your current pin</p>
<form className="setForm">
<input type="text" name="currentpin" placeholder="Current Pin" required/>
<input type="text" name="newpin" placeholder="New Pin" required/>
</form>
<button className="setBtn">Save Changes</button>
</div>
);
};
export default ChangePin;
|
import React from "react";
import "../../assets/css/styles.css";
// reactstrap components
import { Container, Row, Col } from "reactstrap";
let img1 = "https://cdn2.hubspot.net/hubfs/1951013/Parallax/SkyBG.png";
let img2 = "https://cdn2.hubspot.net/hubfs/1951013/Parallax/Clouds1.png";
let img3 = "https://cdn2.hubspot.net/hubfs/1951013/Parallax/Clouds2.png";
let img4 = "https://cdn2.hubspot.net/hubfs/1951013/Parallax/Clouds3.png";
let img5 = "https://cdn2.hubspot.net/hubfs/1951013/Parallax/Moon.png";
let img6 = "https://cdn2.hubspot.net/hubfs/1951013/Parallax/Hill.png";
class Header extends React.Component {
render() {
return (
<div className="landing-page-container" id="home-section">
<img
src={require("../../assets/img/astronaut.png")}
alt=""
className="astronaut"
/>
<div className="landing-page-main">
<div className="parallax-container">
<div style={{ background: `url(${img1})` }}></div>
<div style={{ background: `url(${img2})` }}></div>
<div style={{ background: `url(${img3})` }}></div>
<div style={{ background: `url(${img4})` }}></div>
<div style={{ background: `url(${img5})` }} id="top-circle"></div>
<div style={{ background: `url(${img6})` }}></div>
<img
className="object_astronaut"
src={require("../../assets/img/homeassets/astronaut.svg")}
width="100px"
style={{ top: "20%", right: "10%", position: "absolute" }}
/>
<div className="glowing_stars">
<div className="star" />
<div className="star" />
<div className="star" />
<div className="star" />
<div className="star" />
</div>
<div className="earth-moon">
<img
className="object_earth"
src={require("../../assets/img/homeassets/earth.svg")}
width="100px"
/>
</div>
<div>
<img
className="object_rocket"
src={require("../../assets/img/homeassets/rocket.svg")}
width="40px"
/>
</div>
</div>
</div>
<div className="page-header header-filter bg">
<Container>
<Row className="justify-content-between align-items-center">
<Col className="mb-5 mb-lg-0 content-center brand" lg="5">
<h1 className="text-white font-weight-light h1-seo ">
Celesta 2020
</h1>
<br/>
<p className="text-white mt-4">
Celesta is the annual Techno-Management Fest of IIT Patna. To
promote technical and managerial enthusiasm amongst young and
bright minds of our nation and to provide a platform to
transform their innovative ideas into a meaningful reality.
</p>
</Col>
</Row>
</Container>
</div>
</div>
);
}
}
export default Header;
|
import React, { useState } from 'react';
import { connect, useDispatch } from 'react-redux';
import { addNewTask } from '../../../redux/actions';
import { asyncPostData } from '../../../redux/asyncActions';
const InputTask = (props) => {
const dispatch = useDispatch();
const [state, setState] = useState('');
const pressEnter = (e) => {
if (e.key === 'Enter') {
console.log(state)
props.add(state)
dispatch(asyncPostData());
setState('');
}
}
return (
<div className="input-task">
<input type="text" placeholder="Напишите вашу задачу..." className="form-control" value={state} onChange={(e) => setState(e.target.value)} onKeyPress={pressEnter}></input>
</div>
)
}
const mapDispatchToProps = (dispatch, data) => {
return {
add: (data) => dispatch(addNewTask(data))
}
}
export default connect(null, mapDispatchToProps)(InputTask);
|
export { NoTransactions } from './no-transactions';
|
/*
File: sessionstorage.js
Purpose: Contains methods that allow the browser to store some important details about a user's
session in order to allow the other methods to run. This data includes username, userID, and user
index. These values help us update, access, and change the database in the backend to keep our data
a little bit more secure.
*/
function remember(name, ind, uid) {
sessionStorage.setItem('user', name);
sessionStorage.setItem('ind', ind);
sessionStorage.setItem('uid', uid);/*
sessionStorage.user = name;
sessionStorage.userIndex = ind;
sessionStorage.uid = uid;*/
}
function forget() {
sessionStorage.user = "blank";
sessionStorage.userIndex = "blank";
sessionStorage.uid = "blank";
}
function savePieChartData(data){
sessionStorage.setItem('data', data);
}
|
console.log("This should log without refreshing")
import pageLoad from './modules/pageContent';
pageLoad();
import populateMenu from './modules/menu';
import populateAbout from './modules/about';
import populateContact from './modules/contact';
import populateHours from './modules/hours';
// import "../src/style.css"
// populateMenu(['one','two'])
let main = document.querySelector('#main');
let aboutButton = document.querySelector('#aboutButton');
let menuButton = document.querySelector('#menuButton');
let contactButton = document.querySelector('#contactButton');
let hoursButton = document.querySelector('#hoursButton');
let div = populateAbout();
main.appendChild(div)
document.addEventListener('click', function(e) {
aboutButton.className = 'navButton';
menuButton.className = 'navButton';
contactButton.className = 'navButton';
hoursButton.className = 'navButton';
if (e.target.id === 'aboutButton') {
aboutButton.classList.add('navButtonActive')
main.innerHTML = ''
let div = populateAbout();
main.appendChild(div)
} else if (e.target.id === 'menuButton') {
menuButton.classList.add('navButtonActive')
main.innerHTML = ''
let div = populateMenu();
main.appendChild(div)
} else if (e.target.id === 'contactButton') {
contactButton.classList.add('navButtonActive')
main.innerHTML = '';
let div = populateContact();
main.appendChild(div);
} else if (e.target.id === 'hoursButton') {
hoursButton.classList.add('navButtonActive')
main.innerHTML = '';
let div = populateHours();
main.appendChild(div);
}
});
|
// https://docs.cypress.io/api/introduction/api.html
describe('Home page', () => {
beforeEach(function visitRootPage() {
cy.visit('/')
})
it('All navigation should be visible', () => {
cy.get('[data-cy=play]').contains('Spill turnering').should('be.visible')
cy.get('[data-cy=create-tournament]').contains('Opprett turnering').should('be.visible')
cy.get('[data-cy=login-adminID]').contains('Logg på med adminID').should('be.visible')
cy.get('[data-cy=help]').contains('Hjelp').should('be.visible')
cy.get('[data-cy=about]').contains('Om Sjakkarena').should('be.visible')
cy.get('[data-cy=chess-clock]').contains('Sjakkur').should('be.visible')
})
it('Play navigates to enter-tourney', () => {
cy.get('[data-cy=play]').click()
cy.location('pathname').should('eq', '/enter-tourney')
cy.wait(500)
})
it('Create-tournament navigates to tournament-creation', () => {
cy.get('[data-cy=create-tournament]').click()
cy.location('pathname').should('eq', '/tournament-creation')
cy.wait(500)
})
it('Login-adminID navigates to enter-AID', () => {
cy.get('[data-cy=login-adminID]').click()
cy.location('pathname').should('eq', '/enter-AID')
cy.wait(500)
})
it('Help in footer opens new tab', () => {
cy.get('a[href="/help"]').should('have.attr', 'target', '_blank')
})
it('About in footer opens new tab', () => {
cy.get('a[href="/about"]').should('have.attr', 'target', '_blank')
})
it('Chess-clock in footer opens new tab', () => {
cy.get('a[href="/chess-clock"]').should('have.attr', 'target', '_blank')
})
})
|
const assert = require('assert');
const { PG_CONNECTION } = process.env;
assert(PG_CONNECTION, 'PG_CONNECTION must be provided');
module.exports = {
client: 'pg',
connection: PG_CONNECTION,
};
|
// Created by razvan on 4/9/2017.
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from '../reducers';
import thunk from 'redux-thunk';
/* eslint-disable no-underscore-dangle */
const store = createStore(rootReducer,
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
/* eslint-enable */
export default store;
|
function onRequest(request, response, modules) {
var sender = JSON.parse(request.body.sender);
var project = JSON.parse(request.body.project);
var target = JSON.parse(request.body.target);
var joinerList = JSON.parse(request.body.joinerList);
var channels = JSON.parse(request.body.channels);
var privacy = parseInt(request.body.privacy, 10);
var installationId = request.body.installationId;
var db = modules.oData;
var bat = modules.oBatch;
var push = modules.oPush;
var result = {
"setProject": null,
"setJoinList": null,
"setTarget": null,
"setItemList": null,
"subscribeChannel": null,
"pushMessageToSubject": null
};
project.sender = {
"__type": "Pointer",
"className": "Subject",
"objectId": sender.objectId
};
db.insert({
"table": "Project",
"data": project
}, function (err, data) {
result.setProject = JSON.parse(data);
project.objectId = result.setProject.objectId;
project.createdAt = result.setProject.createdAt;
project.updatedAt = result.setProject.updatedAt;
var joinListForBatch = [];
joinListForBatch[0] = {
"method": "POST",
"path": "/1/classes/Join",
"body": {
"project": {
"__type": "Pointer",
"className": "Project",
"objectId": project.objectId
},
"joiner": {
"__type": "Pointer",
"className": "Subject",
"objectId": sender.objectId
},
"role": 0,
"privacy": privacy
}
};
for (var i = 1; i < joinerList.length + 1; i++) {
joinListForBatch[i] = {
"method": "POST",
"path": "/1/classes/Join",
"body": {
"project": {
"__type": "Pointer",
"className": "Project",
"objectId": project.objectId
},
"joiner": {
"__type": "Pointer",
"className": "Subject",
"objectId": joinerList[i - 1].objectId
},
"role": 2,
"privacy": 0
}
};
}
bat.exec({
"data": {
"requests": joinListForBatch
}
}, function (err, data) {
var joinListResult = JSON.parse(data);
result.setJoinList = joinListResult;
target.project = {
"__type": "Pointer",
"className": "Project",
"objectId": project.objectId
};
target.sender = {
"__type": "Pointer",
"className": "Join",
"objectId": joinListResult[0].success.objectId
};
db.insert({
"table": "ProjectItem",
"data": target
}, function (err, data) {
result.setTarget = JSON.parse(data);
target.objectId = result.setTarget.objectId;
var itemListForBatch = [];
for (var i = 0; i < joinerList.length; i++) {
itemListForBatch[i] = {
"method": "POST",
"path": "/1/classes/ProjectItem",
"body": {
"project": {
"__type": "Pointer",
"className": "Project",
"objectId": project.objectId
},
"sender": {
"__type": "Pointer",
"className": "Join",
"objectId": joinListResult[i + 1].success.objectId
},
"parent": {
"__type": "Pointer",
"className": "ProjectItem",
"objectId": target.objectId
},
"content": "",
"option": 3,
"type": 1,
}
};
}
bat.exec({
"data": {
"requests": itemListForBatch
}
}, function (err, data) {
result.setItemList = JSON.parse(data);
push.update({
"objectId": installationId,
"data": {
"channels": {
"__op": "AddUnique",
"objects": [project.objectId]
}
}
}, function (err, data) {
result.subscribeChannel = JSON.parse(data);
project.sender = sender;
var newData = {
"dataType": "Project",
"dataOption": "set",
"dataChannels": project.objectId,
"data": project
};
push.send({
"data": {
"channels": channels,
"data": newData
}
}, function (err, data) {
result.pushMessageToSubject = JSON.parse(data);
response.send(result);
});
});
});
});
});
});
}
|
var mongoose = require('mongoose'),
uuid = require('node-uuid'),
Schema = mongoose.Schema;
var crypto = require('crypto');
var User = new Schema({
email: { type: String, required: true },
password: { type: String, required: true, set: encryptPassword},
salt : { type:String, default: uuid.v1},
level: { type: Number, default:0 }
});
User.methods.isValidPassword = function(passwordString) {
return this.password === hash(passwordString, this.salt);
};
function hash(password, salt) {
return crypto.createHmac('sha256', salt).update(password).digest('hex');
}
function encryptPassword(password) {
return hash(password, this.salt);
}
module.exports = mongoose.model('User', User);
|
goog.provide('annotorious.Popup');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.dom.query');
goog.require('goog.style');
/**
* A popup bubble widget to show annotation details.
* @param {Object} annotator reference to the annotator
* @constructor
*/
annotorious.Popup = function(annotator) {
this.element = goog.soy.renderAsElement(annotorious.templates.popup);
/** @private **/
this._annotator = annotator;
/** @private **/
this._currentAnnotation;
/** @private **/
this._text = goog.dom.query('.annotorious-popup-text', this.element)[0];
/** @private **/
this._buttons = goog.dom.query('.annotorious-popup-buttons', this.element)[0];
/** @private **/
this._popupHideTimer;
/** @private **/
this._buttonHideTimer;
/** @private **/
this._cancelHide = false;
/** @private **/
this._extraFields = [];
var btnEdit = goog.dom.query('.annotorious-popup-button-edit', this._buttons)[0];
var btnDelete = goog.dom.query('.annotorious-popup-button-delete', this._buttons)[0];
var self = this;
goog.events.listen(btnEdit, goog.events.EventType.MOUSEOVER, function(event) {
goog.dom.classes.add(btnEdit, 'annotorious-popup-button-active');
});
goog.events.listen(btnEdit, goog.events.EventType.MOUSEOUT, function() {
goog.dom.classes.remove(btnEdit, 'annotorious-popup-button-active');
});
goog.events.listen(btnEdit, goog.events.EventType.CLICK, function(event) {
goog.style.setOpacity(self.element, 0);
goog.style.setStyle(self.element, 'pointer-events', 'none');
annotator.editAnnotation(self._currentAnnotation);
});
goog.events.listen(btnDelete, goog.events.EventType.MOUSEOVER, function(event) {
goog.dom.classes.add(btnDelete, 'annotorious-popup-button-active');
});
goog.events.listen(btnDelete, goog.events.EventType.MOUSEOUT, function() {
goog.dom.classes.remove(btnDelete, 'annotorious-popup-button-active');
});
goog.events.listen(btnDelete, goog.events.EventType.CLICK, function(event) {
var cancelEvent = annotator.fireEvent(annotorious.events.EventType.BEFORE_ANNOTATION_REMOVED, self._currentAnnotation);
if (!cancelEvent) {
goog.style.setOpacity(self.element, 0);
goog.style.setStyle(self.element, 'pointer-events', 'none');
annotator.removeAnnotation(self._currentAnnotation);
annotator.fireEvent(annotorious.events.EventType.ANNOTATION_REMOVED, self._currentAnnotation);
}
});
if (annotorious.events.ui.hasMouse) {
goog.events.listen(this.element, goog.events.EventType.MOUSEOVER, function(event) {
window.clearTimeout(self._buttonHideTimer);
if (goog.style.getStyle(self._buttons, 'opacity') < 0.9)
goog.style.setOpacity(self._buttons, 0.9);
self.clearHideTimer();
});
goog.events.listen(this.element, goog.events.EventType.MOUSEOUT, function(event) {
goog.style.setOpacity(self._buttons, 0);
self.startHideTimer();
});
annotator.addHandler(annotorious.events.EventType.MOUSE_OUT_OF_ANNOTATABLE_ITEM, function(event) {
self.startHideTimer();
});
}
goog.style.setOpacity(this._buttons, 0);
goog.style.setOpacity(this.element, 0);
goog.style.setStyle(this.element, 'pointer-events', 'none');
goog.dom.appendChild(annotator.element, this.element);
}
/**
* Adds a field to the popup GUI widget. A field can be either an (HTML) string, or
* a function that takes an Annotation as argument and returns an (HTML) string or
* a DOM element.
* @param {string | Function} field the field
*/
annotorious.Popup.prototype.addField = function(field) {
var fieldEl = goog.dom.createDom('div', 'annotorious-popup-field');
if (goog.isString(field)) {
fieldEl.innerHTML = field;
} else if (goog.isFunction(field)) {
this._extraFields.push({el: fieldEl, fn: field});
} else if (goog.dom.isElement(field)) {
goog.dom.appendChild(fieldEl, field);
}
goog.dom.appendChild(this.element, fieldEl);
}
/**
* Start the popup hide timer.
*/
annotorious.Popup.prototype.startHideTimer = function() {
this._cancelHide = false;
if (!this._popupHideTimer) {
var self = this;
this._popupHideTimer = window.setTimeout(function() {
self._annotator.fireEvent(annotorious.events.EventType.BEFORE_POPUP_HIDE, self);
if (!self._cancelHide) {
goog.style.setOpacity(self.element, 0.0);
goog.style.setStyle(self.element, 'pointer-events', 'none');
goog.style.setOpacity(self._buttons, 0.9);
delete self._popupHideTimer;
}
}, 150);
}
}
/**
* Clear the popup hide timer.
*/
annotorious.Popup.prototype.clearHideTimer = function() {
this._cancelHide = true;
if (this._popupHideTimer) {
window.clearTimeout(this._popupHideTimer);
delete this._popupHideTimer;
}
}
/**
* Show the popup, loaded with the specified annotation, at the specified coordinates.
* @param {annotorious.Annotation} annotation the annotation
* @param {annotorious.shape.geom.Point} xy the viewport coordinate
*/
annotorious.Popup.prototype.show = function(annotation, xy) {
this.clearHideTimer();
if (xy)
this.setPosition(xy);
if (annotation)
this.setAnnotation(annotation);
if (this._buttonHideTimer)
window.clearTimeout(this._buttonHideTimer);
goog.style.setOpacity(this._buttons, 0.9);
if (annotorious.events.ui.hasMouse) {
var self = this;
this._buttonHideTimer = window.setTimeout(function() {
goog.style.setOpacity(self._buttons, 0);
}, 1000);
}
goog.style.setOpacity(this.element, 0.9);
goog.style.setStyle(this.element, 'pointer-events', 'auto');
this._annotator.fireEvent(annotorious.events.EventType.POPUP_SHOWN, this._currentAnnotation);
}
/**
* Set the position of the popup.
* @param {annotorious.shape.geom.Point} xy the viewport coordinate
*/
annotorious.Popup.prototype.setPosition = function(xy) {
goog.style.setPosition(this.element, new goog.math.Coordinate(xy.x, xy.y));
}
/**
* Set the annotation for the popup.
* @param {annotorious.Annotation} annotation the annotation
*/
annotorious.Popup.prototype.setAnnotation = function(annotation) {
this._currentAnnotation = annotation;
if (annotation.text)
this._text.innerHTML = annotation.text.replace(/\n/g, '<br/>');
else
this._text.innerHTML = '<span class="annotorious-popup-empty">No comment</span>';
if (('editable' in annotation) && annotation.editable == false)
goog.style.showElement(this._buttons, false);
else
goog.style.showElement(this._buttons, true);
// Update extra fields (if any)
goog.array.forEach(this._extraFields, function(field) {
var f = field.fn(annotation);
if (goog.isString(f)) {
field.el.innerHTML = f;
} else if (goog.dom.isElement(f)) {
goog.dom.removeChildren(field.el);
goog.dom.appendChild(field.el, f);
}
});
}
/** API exports **/
annotorious.Popup.prototype['addField'] = annotorious.Popup.prototype.addField;
|
var Marionette = require('backbone.marionette')
, Layout = require('./layout.js')
module.exports = Marionette.Controller.extend({
initialize: function(options){
console.log('test');
},
dashboard: function() {
this.layout = new Layout;
},
test: function() {
}
});
|
! function() {
function e() {
document.body.removeAttribute("unresolved")
}
window.WebComponents ? addEventListener("WebComponentsReady", e) : "interactive" === document.readyState || "complete" === document.readyState ? e() : addEventListener("DOMContentLoaded", e)
}(), window.Polymer = {
Settings: function() {
var e = window.Polymer || {};
if (!e.noUrlSettings)
for (var t, r = location.search.slice(1).split("&"), i = 0; i < r.length && (t = r[i]); i++) t = t.split("="), t[0] && (e[t[0]] = t[1] || !0);
return e.wantShadow = "shadow" === e.dom, e.hasShadow = Boolean(Element.prototype.createShadowRoot), e.nativeShadow = e.hasShadow && !window.ShadowDOMPolyfill, e.useShadow = e.wantShadow && e.hasShadow, e.hasNativeImports = Boolean("import" in document.createElement("link")), e.useNativeImports = e.hasNativeImports, e.useNativeCustomElements = !window.CustomElements || window.CustomElements.useNative, e.useNativeShadow = e.useShadow && e.nativeShadow, e.usePolyfillProto = !e.useNativeCustomElements && !Object.__proto__, e.hasNativeCSSProperties = !navigator.userAgent.match(/AppleWebKit\/601|Edge\/15/) && window.CSS && CSS.supports && CSS.supports("box-shadow", "0 0 0 var(--foo)"), e.useNativeCSSProperties = e.hasNativeCSSProperties && e.lazyRegister && e.useNativeCSSProperties, e.isIE = navigator.userAgent.match("Trident"), e.passiveTouchGestures = e.passiveTouchGestures || !1, e
}()
},
function() {
var e = window.Polymer;
window.Polymer = function(e) {
"function" == typeof e && (e = e.prototype), e || (e = {}), e = t(e);
var r = e === e.constructor.prototype ? e.constructor : null,
i = {
prototype: e
};
e.extends && (i.extends = e.extends), Polymer.telemetry._registrate(e);
var s = document.registerElement(e.is, i);
return r || s
};
var t = function(e) {
var t = Polymer.Base;
return e.extends && (t = Polymer.Base._getExtendedPrototype(e.extends)), e = Polymer.Base.chainObject(e, t), e.registerCallback(), e
};
if (e)
for (var r in e) Polymer[r] = e[r];
Polymer.Class = function(e) {
return e.factoryImpl || (e.factoryImpl = function() {}), t(e).constructor
}
}(), Polymer.telemetry = {
registrations: [],
_regLog: function(e) {
console.log("[" + e.is + "]: registered")
},
_registrate: function(e) {
this.registrations.push(e), Polymer.log && this._regLog(e)
},
dumpRegistrations: function() {
this.registrations.forEach(this._regLog)
}
}, Object.defineProperty(window, "currentImport", {
enumerable: !0,
configurable: !0,
get: function() {
return (document._currentScript || document.currentScript || {}).ownerDocument
}
}), Polymer.RenderStatus = {
_ready: !1,
_callbacks: [],
whenReady: function(e) {
this._ready ? e() : this._callbacks.push(e)
},
_makeReady: function() {
this._ready = !0;
for (var e = 0; e < this._callbacks.length; e++) this._callbacks[e]();
this._callbacks = []
},
_catchFirstRender: function() {
requestAnimationFrame(function() {
Polymer.RenderStatus._makeReady()
})
},
_afterNextRenderQueue: [],
_waitingNextRender: !1,
afterNextRender: function(e, t, r) {
this._watchNextRender(), this._afterNextRenderQueue.push([e, t, r])
},
hasRendered: function() {
return this._ready
},
_watchNextRender: function() {
if (!this._waitingNextRender) {
this._waitingNextRender = !0;
var e = function() {
Polymer.RenderStatus._flushNextRender()
};
this._ready ? requestAnimationFrame(e) : this.whenReady(e)
}
},
_flushNextRender: function() {
var e = this;
setTimeout(function() {
e._flushRenderCallbacks(e._afterNextRenderQueue), e._afterNextRenderQueue = [], e._waitingNextRender = !1
})
},
_flushRenderCallbacks: function(e) {
for (var t, r = 0; r < e.length; r++) t = e[r], t[1].apply(t[0], t[2] || Polymer.nar)
}
}, window.HTMLImports ? HTMLImports.whenReady(function() {
Polymer.RenderStatus._catchFirstRender()
}) : Polymer.RenderStatus._catchFirstRender(), Polymer.ImportStatus = Polymer.RenderStatus, Polymer.ImportStatus.whenLoaded = Polymer.ImportStatus.whenReady,
function() {
"use strict";
var e = Polymer.Settings;
Polymer.Base = {
__isPolymerInstance__: !0,
_addFeature: function(e) {
this.mixin(this, e)
},
registerCallback: function() {
if ("max" === e.lazyRegister) this.beforeRegister && this.beforeRegister();
else {
this._desugarBehaviors();
for (var t, r = 0; r < this.behaviors.length; r++) t = this.behaviors[r], t.beforeRegister && t.beforeRegister.call(this);
this.beforeRegister && this.beforeRegister()
}
this._registerFeatures(), e.lazyRegister || this.ensureRegisterFinished()
},
createdCallback: function() {
if (e.disableUpgradeEnabled) {
if (this.hasAttribute("disable-upgrade")) return this._propertySetter = t, this._configValue = null, void(this.__data__ = {});
this.__hasInitialized = !0
}
this.__initialize()
},
__initialize: function() {
this.__hasRegisterFinished || this._ensureRegisterFinished(this.__proto__), Polymer.telemetry.instanceCount++, this.root = this;
for (var e, t = 0; t < this.behaviors.length; t++) e = this.behaviors[t], e.created && e.created.call(this);
this.created && this.created(), this._initFeatures()
},
ensureRegisterFinished: function() {
this._ensureRegisterFinished(this)
},
_ensureRegisterFinished: function(t) {
if (t.__hasRegisterFinished !== t.is || !t.is) {
if ("max" === e.lazyRegister) {
t._desugarBehaviors();
for (var r, i = 0; i < t.behaviors.length; i++) r = t.behaviors[i], r.beforeRegister && r.beforeRegister.call(t)
}
t.__hasRegisterFinished = t.is, t._finishRegisterFeatures && t._finishRegisterFeatures();
for (var s, o = 0; o < t.behaviors.length; o++) s = t.behaviors[o], s.registered && s.registered.call(t);
t.registered && t.registered(), e.usePolyfillProto && t !== this && t.extend(this, t)
}
},
attachedCallback: function() {
var e = this;
Polymer.RenderStatus.whenReady(function() {
e.isAttached = !0;
for (var t, r = 0; r < e.behaviors.length; r++) t = e.behaviors[r], t.attached && t.attached.call(e);
e.attached && e.attached()
})
},
detachedCallback: function() {
var e = this;
Polymer.RenderStatus.whenReady(function() {
e.isAttached = !1;
for (var t, r = 0; r < e.behaviors.length; r++) t = e.behaviors[r], t.detached && t.detached.call(e);
e.detached && e.detached()
})
},
attributeChangedCallback: function(e, t, r) {
this._attributeChangedImpl(e);
for (var i, s = 0; s < this.behaviors.length; s++) i = this.behaviors[s], i.attributeChanged && i.attributeChanged.call(this, e, t, r);
this.attributeChanged && this.attributeChanged(e, t, r)
},
_attributeChangedImpl: function(e) {
this._setAttributeToProperty(this, e)
},
extend: function(e, t) {
if (e && t)
for (var r, i = Object.getOwnPropertyNames(t), s = 0; s < i.length && (r = i[s]); s++) this.copyOwnProperty(r, t, e);
return e || t
},
mixin: function(e, t) {
for (var r in t) e[r] = t[r];
return e
},
copyOwnProperty: function(e, t, r) {
var i = Object.getOwnPropertyDescriptor(t, e);
i && Object.defineProperty(r, e, i)
},
_logger: function(e, t) {
switch (1 === t.length && Array.isArray(t[0]) && (t = t[0]), e) {
case "log":
case "warn":
case "error":
console[e].apply(console, t)
}
},
_log: function() {
var e = Array.prototype.slice.call(arguments, 0);
this._logger("log", e)
},
_warn: function() {
var e = Array.prototype.slice.call(arguments, 0);
this._logger("warn", e)
},
_error: function() {
var e = Array.prototype.slice.call(arguments, 0);
this._logger("error", e)
},
_logf: function() {
return this._logPrefix.concat(this.is).concat(Array.prototype.slice.call(arguments, 0))
}
}, Polymer.Base._logPrefix = function() {
var e = window.chrome && !/edge/i.test(navigator.userAgent) || /firefox/i.test(navigator.userAgent);
return e ? ["%c[%s::%s]:", "font-weight: bold; background-color:#EEEE00;"] : ["[%s::%s]:"]
}(), Polymer.Base.chainObject = function(e, t) {
return e && t && e !== t && (Object.__proto__ || (e = Polymer.Base.extend(Object.create(t), e)), e.__proto__ = t), e
}, Polymer.Base = Polymer.Base.chainObject(Polymer.Base, HTMLElement.prototype), Polymer.BaseDescriptors = {};
var t;
if (e.disableUpgradeEnabled) {
t = function(e, t) {
this.__data__[e] = t
};
var r = Polymer.Base.attributeChangedCallback;
Polymer.Base.attributeChangedCallback = function(e, t, i) {
this.__hasInitialized || "disable-upgrade" !== e || (this.__hasInitialized = !0, this._propertySetter = Polymer.Bind._modelApi._propertySetter, this._configValue = Polymer.Base._configValue, this.__initialize()), r.call(this, e, t, i)
}
}
window.CustomElements ? Polymer.instanceof = CustomElements.instanceof : Polymer.instanceof = function(e, t) {
return e instanceof t
}, Polymer.isInstance = function(e) {
return Boolean(e && e.__isPolymerInstance__)
}, Polymer.telemetry.instanceCount = 0
}(),
function() {
function e() {
if (o)
for (var e, t = document._currentScript || document.currentScript, r = t && t.ownerDocument || document, i = r.querySelectorAll("dom-module"), s = i.length - 1; s >= 0 && (e = i[s]); s--) {
if (e.__upgraded__) return;
CustomElements.upgrade(e)
}
}
var t = {},
r = {},
i = function(e) {
return t[e] || r[e.toLowerCase()]
},
s = function() {
return document.createElement("dom-module")
};
s.prototype = Object.create(HTMLElement.prototype), Polymer.Base.mixin(s.prototype, {
createdCallback: function() {
this.register()
},
register: function(e) {
e = e || this.id || this.getAttribute("name") || this.getAttribute("is"), e && (this.id = e, t[e] = this, r[e.toLowerCase()] = this)
},
import: function(t, r) {
if (t) {
var s = i(t);
return s || (e(), s = i(t)), s && r && (s = s.querySelector(r)), s
}
}
}), Object.defineProperty(s.prototype, "constructor", {
value: s,
configurable: !0,
writable: !0
});
var o = window.CustomElements && !CustomElements.useNative;
document.registerElement("dom-module", s)
}(), Polymer.Base._addFeature({
_prepIs: function() {
if (!this.is) {
var e = (document._currentScript || document.currentScript).parentNode;
if ("dom-module" === e.localName) {
var t = e.id || e.getAttribute("name") || e.getAttribute("is");
this.is = t
}
}
this.is && (this.is = this.is.toLowerCase())
}
}), Polymer.Base._addFeature({
behaviors: [],
_desugarBehaviors: function() {
this.behaviors.length && (this.behaviors = this._desugarSomeBehaviors(this.behaviors))
},
_desugarSomeBehaviors: function(e) {
var t = [];
e = this._flattenBehaviorsList(e);
for (var r = e.length - 1; r >= 0; r--) {
var i = e[r];
t.indexOf(i) === -1 && (this._mixinBehavior(i), t.unshift(i))
}
return t
},
_flattenBehaviorsList: function(e) {
for (var t = [], r = 0; r < e.length; r++) {
var i = e[r];
i instanceof Array ? t = t.concat(this._flattenBehaviorsList(i)) : i ? t.push(i) : this._warn(this._logf("_flattenBehaviorsList", "behavior is null, check for missing or 404 import"))
}
return t
},
_mixinBehavior: function(e) {
for (var t, r = Object.getOwnPropertyNames(e), i = e._noAccessors, s = 0; s < r.length && (t = r[s]); s++) Polymer.Base._behaviorProperties[t] || this.hasOwnProperty(t) || (i ? this[t] = e[t] : this.copyOwnProperty(t, e, this))
},
_prepBehaviors: function() {
this._prepFlattenedBehaviors(this.behaviors)
},
_prepFlattenedBehaviors: function(e) {
for (var t = 0, r = e.length; t < r; t++) this._prepBehavior(e[t]);
this._prepBehavior(this)
},
_marshalBehaviors: function() {
for (var e = 0; e < this.behaviors.length; e++) this._marshalBehavior(this.behaviors[e]);
this._marshalBehavior(this)
}
}), Polymer.Base._behaviorProperties = {
hostAttributes: !0,
beforeRegister: !0,
registered: !0,
properties: !0,
observers: !0,
listeners: !0,
created: !0,
attached: !0,
detached: !0,
attributeChanged: !0,
ready: !0,
_noAccessors: !0
}, Polymer.Base._addFeature({
_getExtendedPrototype: function(e) {
return this._getExtendedNativePrototype(e)
},
_nativePrototypes: {},
_getExtendedNativePrototype: function(e) {
var t = this._nativePrototypes[e];
if (!t) {
t = Object.create(this.getNativePrototype(e));
for (var r, i = Object.getOwnPropertyNames(Polymer.Base), s = 0; s < i.length && (r = i[s]); s++) Polymer.BaseDescriptors[r] || (t[r] = Polymer.Base[r]);
Object.defineProperties(t, Polymer.BaseDescriptors), this._nativePrototypes[e] = t
}
return t
},
getNativePrototype: function(e) {
return Object.getPrototypeOf(document.createElement(e))
}
}), Polymer.Base._addFeature({
_prepConstructor: function() {
this._factoryArgs = this.extends ? [this.extends, this.is] : [this.is];
var e = function() {
return this._factory(arguments)
};
this.hasOwnProperty("extends") && (e.extends = this.extends), Object.defineProperty(this, "constructor", {
value: e,
writable: !0,
configurable: !0
}), e.prototype = this
},
_factory: function(e) {
var t = document.createElement.apply(document, this._factoryArgs);
return this.factoryImpl && this.factoryImpl.apply(t, e), t
}
}), Polymer.nob = Object.create(null), Polymer.Base._addFeature({
getPropertyInfo: function(e) {
var t = this._getPropertyInfo(e, this.properties);
if (!t)
for (var r = 0; r < this.behaviors.length; r++)
if (t = this._getPropertyInfo(e, this.behaviors[r].properties)) return t;
return t || Polymer.nob
},
_getPropertyInfo: function(e, t) {
var r = t && t[e];
return "function" == typeof r && (r = t[e] = {
type: r
}), r && (r.defined = !0), r
},
_prepPropertyInfo: function() {
this._propertyInfo = {};
for (var e = 0; e < this.behaviors.length; e++) this._addPropertyInfo(this._propertyInfo, this.behaviors[e].properties);
this._addPropertyInfo(this._propertyInfo, this.properties), this._addPropertyInfo(this._propertyInfo, this._propertyEffects)
},
_addPropertyInfo: function(e, t) {
if (t) {
var r, i;
for (var s in t) r = e[s], i = t[s], ("_" !== s[0] || i.readOnly) && (e[s] ? (r.type || (r.type = i.type), r.readOnly || (r.readOnly = i.readOnly)) : e[s] = {
type: "function" == typeof i ? i : i.type,
readOnly: i.readOnly,
attribute: Polymer.CaseMap.camelToDashCase(s)
})
}
}
}),
function() {
var e = {
configurable: !0,
writable: !0,
enumerable: !0,
value: {}
};
Polymer.BaseDescriptors.properties = e, Object.defineProperty(Polymer.Base, "properties", e)
}(), Polymer.CaseMap = {
_caseMap: {},
_rx: {
dashToCamel: /-[a-z]/g,
camelToDash: /([A-Z])/g
},
dashToCamelCase: function(e) {
return this._caseMap[e] || (this._caseMap[e] = e.indexOf("-") < 0 ? e : e.replace(this._rx.dashToCamel, function(e) {
return e[1].toUpperCase()
}))
},
camelToDashCase: function(e) {
return this._caseMap[e] || (this._caseMap[e] = e.replace(this._rx.camelToDash, "-$1").toLowerCase())
}
}, Polymer.Base._addFeature({
_addHostAttributes: function(e) {
this._aggregatedAttributes || (this._aggregatedAttributes = {}), e && this.mixin(this._aggregatedAttributes, e)
},
_marshalHostAttributes: function() {
this._aggregatedAttributes && this._applyAttributes(this, this._aggregatedAttributes)
},
_applyAttributes: function(e, t) {
for (var r in t)
if (!this.hasAttribute(r) && "class" !== r) {
var i = t[r];
this.serializeValueToAttribute(i, r, this)
}
},
_marshalAttributes: function() {
this._takeAttributesToModel(this)
},
_takeAttributesToModel: function(e) {
if (this.hasAttributes())
for (var t in this._propertyInfo) {
var r = this._propertyInfo[t];
this.hasAttribute(r.attribute) && this._setAttributeToProperty(e, r.attribute, t, r)
}
},
_setAttributeToProperty: function(e, t, r, i) {
if (!this._serializing && (r = r || Polymer.CaseMap.dashToCamelCase(t), i = i || this._propertyInfo && this._propertyInfo[r], i && !i.readOnly)) {
var s = this.getAttribute(t);
e[r] = this.deserialize(s, i.type)
}
},
_serializing: !1,
reflectPropertyToAttribute: function(e, t, r) {
this._serializing = !0, r = void 0 === r ? this[e] : r, this.serializeValueToAttribute(r, t || Polymer.CaseMap.camelToDashCase(e)), this._serializing = !1
},
serializeValueToAttribute: function(e, t, r) {
var i = this.serialize(e);
r = r || this, void 0 === i ? r.removeAttribute(t) : r.setAttribute(t, i)
},
deserialize: function(e, t) {
switch (t) {
case Number:
e = Number(e);
break;
case Boolean:
e = null != e;
break;
case Object:
try {
e = JSON.parse(e)
} catch (e) {}
break;
case Array:
try {
e = JSON.parse(e)
} catch (t) {
e = null, console.warn("Polymer::Attributes: couldn`t decode Array as JSON")
}
break;
case Date:
e = new Date(e);
break;
case String:
}
return e
},
serialize: function(e) {
switch (typeof e) {
case "boolean":
return e ? "" : void 0;
case "object":
if (e instanceof Date) return e.toString();
if (e) try {
return JSON.stringify(e)
} catch (e) {
return ""
}
default: return null != e ? e : void 0
}
}
}), Polymer.version = "1.11.2", Polymer.Base._addFeature({
_registerFeatures: function() {
this._prepIs(), this._prepBehaviors(), this._prepConstructor(), this._prepPropertyInfo()
},
_prepBehavior: function(e) {
this._addHostAttributes(e.hostAttributes)
},
_marshalBehavior: function(e) {},
_initFeatures: function() {
this._marshalHostAttributes(), this._marshalBehaviors()
}
});
|
import models from "./../../models/index.js";
export const resolvers = {
Query: {
getTraceability: async (_, { user }, { license }) => {
//! add security layers
return await models.Traceability.findById(user);
},
getAllTracers: async () => {
//! Add security layer
return await models.Traceability.find();
},
},
Mutation: {
startTraceability: async (_, { user, exposed }, { license }) => {
//! Add security layer
const traceability = await models.Traceability.findOneAndUpdate(
{ _id: user },
{
active: true,
$push: {
exposedUsers: exposed,
},
}
);
return traceability;
},
},
};
|
const mongoose = require("mongoose");
const validator = require("validator");
const bcryptjs = require("bcryptjs");
const jwt = require("jsonwebtoken");
const Task = require("../models/task");
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: [true, "Name is required."],
},
email: {
type: String,
unique: true,required:[true, "Please enter email."],
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("Email is invalid.");
}
},
},
password: {
type: String,
minlength: 6,
trim: true,
required:[true, "Please enter password."],
validate(value) {
if (value === "password") {
throw new Error("Password cant be password.");
}
},
},
role: {
type: String,
enum: ["admin", "user"],
default: "user"
},
tokens: [
{
token: {
type: String,
required: true,
},
},
],
isIndian: {
type: Boolean,
default: true,
},
},
{
timestamps: true,
}
);
//methods declared on static are available on the Model itself
userSchema.statics.findUserByLoginPassword = async (email, password) => {
const user = await User.findOne({ email });
if (!user) {
throw new Error("No user found!");
}
const isMatch = await bcryptjs.compare(password, user.password);
if (!isMatch) {
throw new Error("Unable to login!");
}
return user;
};
userSchema.virtual("tasks", {
ref: "Task",
localField: "_id",
foreignField: "creator",
});
userSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject();
delete userObject.password;
delete userObject.tokens;
return userObject;
};
//instance methods work on individual instance of Model/documents
userSchema.methods.getAuthToken = async function () {
const user = this;
const token = jwt.sign({ _id: user._id.toString() }, "nishitjwt");
user.tokens = user.tokens.concat({ token });
await user.save();
return token;
};
//pre methods here is called before user is saved in the database
userSchema.pre("save", async function (next) {
const user = this;
if (user.isModified("password")) {
user.password = await bcryptjs.hash(user.password, 8);
}
next();
});
userSchema.pre("remove", async function (next) {
const user = this;
const task = await Task.deleteMany({ creator: user._id });
next();
});
const User = mongoose.model("User", userSchema);
module.exports = User;
|
import { makeStyles } from '@material-ui/core/styles'
export default makeStyles((theme) => ({
media: {
height: '5rem',
paddingTop: '56.25%',
backgroundColor: 'rgba(0, 0, 0, 0.5)',
backgroundBlendMode: 'darken'
},
border: {
border: 'solid'
},
fullHeightCard: {
height: '80%'
},
card: {
display: 'flex',
flexDirection: 'column',
borderRadius: '12px',
boxShadow: '2px 2px 5px #a2a2a2',
width: '20%',
height: '100%',
minHeight: '300px',
margin: '21px 26px',
position: 'relative',
[theme.breakpoints.down('md')]: {
width: '100%',
margin: 0,
marginBottom: '25px'
}
},
content: {
overflowY: 'scroll',
height: '75px',
'&::-webkit-scrollbar': {
// display: 'none'
width: '3px'
},
'&::-webkit-scrollbar-thumb': {
background: 'gray',
borderRadius: '20px'
},
'&::-webkit-scrollbar-thumb:hover': {
background: '#b30000'
}
},
overlay: {
position: 'absolute',
top: '20px',
left: '20px',
color: 'white'
},
overlay2: {
position: 'absolute',
top: '20px',
right: '20px',
color: 'white',
zIndex: '100'
},
grid: {
display: 'flex'
},
details: {
display: 'flex',
margin: '20px',
flexWrap: 'wrap'
},
title: {
padding: '0 16px',
fontWeight: '500',
fontSize: '20px'
},
cardActions: {
padding: '0 16px 8px 16px',
display: 'flex',
justifyContent: 'space-between',
position: 'relative',
bottom: 0
},
likeTxt: {
color: '#F8485E'
},
likePost: {
padding: 5,
color: '#F8485E',
'&:hover': {
backgroundColor: '#f7cad0'
}
},
cardButton: {
display: 'block',
textAlign: 'initial'
}
}))
|
var searchData=
[
['range_2eh',['Range.h',['../Range_8h.html',1,'']]],
['ray_2eh',['Ray.h',['../nanovdb_2nanovdb_2util_2Ray_8h.html',1,'']]],
['ray_2eh',['Ray.h',['../openvdb_2openvdb_2math_2Ray_8h.html',1,'']]],
['rayintersector_2eh',['RayIntersector.h',['../RayIntersector_8h.html',1,'']]],
['raytracer_2eh',['RayTracer.h',['../RayTracer_8h.html',1,'']]],
['reduce_2eh',['Reduce.h',['../Reduce_8h.html',1,'']]],
['rootnode_2eh',['RootNode.h',['../RootNode_8h.html',1,'']]]
];
|
import React from "react";
export const Background = (props) => {
let weatherDesc = props.desc[0] && props.desc[0].main;
const phase = () => {
let hour = new Date().getHours();
return hour > 5 && hour < 19 ? "d" : "n";
};
const images = {
cloud1: {
imgSrc: "./PNGImages/cloud1.png",
desc: "cloud1",
},
cloud2: {
imgSrc: "./PNGImages/cloud2.png",
desc: "cloud2",
},
light: {
imgSrc: "./PNGImages/light.png",
desc: "light",
},
rain: {
imgSrc: "./PNGImages/rain.png",
desc: "rain",
},
mist: {
imgSrc: "./PNGImages/mist.png",
desc: "mist",
},
stars: {
imgSrc: "./PNGImages/stars.png",
desc: "stars",
},
};
const weatherObject = {
Thunderstorm: [images.cloud1, images.cloud2, images.light, images.rain],
Drizzle: [images.cloud2, images.rain],
Rain: [images.cloud1, images.rain],
Clouds: [images.cloud1, images.cloud2, images.stars],
Mist: [images.stars, images.mist],
Fog: [images.stars, images.mist],
Clear: [images.stars],
Snow: [images.stars, images.cloud2, "Winter"],
};
const background = {
d: {
bg: "daySky",
imgSrc: "./PNGImages/sun.png",
imgAlt: "Sun",
},
n: {
bg: "nightSky",
imgSrc: "./PNGImages/moon.png",
imgAlt: "Moon",
},
};
let currentBackground = background[phase()];
let weather = weatherObject[weatherDesc];
return (
<div className={`${currentBackground.bg} ${weatherDesc + phase()}`}>
{weather &&
weather.map((Weather, index) => {
if (phase() === "d" && Weather.desc === "stars") return null;
else if (Weather === "Winter") {
return <Winter key={`background${index}`} />;
} else
return (
<div
key={`background${index}`}
className={"background"}
style={{
background: `url(${require(`${Weather.imgSrc}`)}) repeat top center`,
}}
/>
);
})}
<img
className={"foreground"}
src={require(`${currentBackground.imgSrc}`)}
alt={currentBackground.imgAlt}
/>
</div>
);
};
export const Winter = () => {
let element = [];
for (let i = 0; i < 83; i++) element.push(<i key={`WinterSnow${i}`}></i>);
return <div className={`snowflakes`}>{element}</div>;
};
|
function setStep(state) {
state.steps += 1;
}
function restoreSteps(state) {
state.steps = 0;
}
module.exports = {
setStep,
restoreSteps,
};
|
import ReactDOM from "react-dom";
jest.mock('react-dom')
require('../../index')
test('Renders the application', () => {
expect(ReactDOM.render).toBeCalled()
})
|
import React from 'react';
function App() {
const [course, setCourse] = React.useState("");
const [courseList, setCourseList] = React.useState([]);
const addCourse = () => {
setCourseList([...courseList, course]);
setCourse("");
};
const deleteAll = () => setCourseList([])
const deleteItem = (index) => {
const newArray = [...courseList];
newArray.splice(index, 1);
setCourseList(newArray);
}
const inputTextHandler = e => setCourse(e.target.value)
return (
<div>
<Title color="red">Course List</Title>
<TextInput placeholder="Enter a course" value={course} onChange={inputTextHandler}/>
<Button onClick={addCourse} disabled={!course}>Add Course</Button>
<ul>
{courseList.map((item, index) => (
<ListItem item={item} index={index} deleteItem={deleteItem}/>
))}
</ul>
{
courseList.length > 0 &&
<Button onClick={deleteAll}>Delete All</Button>
}
</div>
);
}
function Button(props) {
let buttonStyle ={
color: ''
}
return (
<button style={buttonStyle} onClick= {props.onClick} disabled={props.disabled}>{props.children}</button>
)
}
function Title({children, color}) {
return (
<h1 style={{color}}>{children}</h1>
)
}
function TextInput({placeholder,value, onChange}) {
return (
<input
type="text"
placeholder={placeholder}
value={value}
onChange={onChange}
/>
)
}
function ListItem({item, index, deleteItem}) {
function deleteHandler() {
deleteItem(index)
}
return (
<li>
{item}
<span onClick={deleteHandler}> ❌</span>
</li>
)
}
export default App;
|
var express = require('express');
var mdAutenticacion = require('../middlewares/autenticacion');
var app = express();
var Publicacion = require('../models/publicacion');
// ==========================================
// Obtener todos los publicaciones
// ==========================================
app.get('/', (req, res, next) => {
var desde = req.query.desde || 0;
desde = Number(desde);
Publicacion.find({})
.skip(desde)
.limit(5)
.populate('usuario', 'nombre email')
.exec(
(err, publicaciones) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error cargando publicacion',
errors: err
});
}
Publicacion.count({}, (err, conteo) => {
res.status(200).json({
ok: true,
publicaciones: publicaciones,
total: conteo
});
})
});
});
// ==========================================
// Obtener Publicacion por ID
// ==========================================
app.get('/:id', (req, res) => {
var id = req.params.id;
Publicacion.findById(id)
.populate('usuario', 'nombre img email')
.exec((err, publicacion) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error al buscar publicacion',
errors: err
});
}
if (!publicacion) {
return res.status(400).json({
ok: false,
mensaje: 'El publicacion con el id ' + id + 'no existe',
errors: { message: 'No existe un publicacion con ese ID' }
});
}
res.status(200).json({
ok: true,
publicacion: publicacion
});
})
})
// ==========================================
// Actualizar Publicacion
// ==========================================
app.put('/:id', mdAutenticacion.verificaToken, (req, res) => {
var id = req.params.id;
var body = req.body;
Publicacion.findById(id, (err, publicacion) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error al buscar publicacion',
errors: err
});
}
if (!publicacion) {
return res.status(400).json({
ok: false,
mensaje: 'El publicacion con el id ' + id + ' no existe',
errors: { message: 'No existe un publicacion con ese ID' }
});
}
publicacion.nombre = body.nombre;
publicacion.usuario = req.usuario._id;
publicacion.save((err, publicacionGuardado) => {
if (err) {
return res.status(400).json({
ok: false,
mensaje: 'Error al actualizar publicacion',
errors: err
});
}
res.status(200).json({
ok: true,
publicacion: publicacionGuardado
});
});
});
});
// ==========================================
// Crear un nuevo publicacion
// ==========================================
app.post('/', mdAutenticacion.verificaToken, (req, res) => {
var body = req.body;
var publicacion = new Publicacion({
nombre: body.nombre,
usuario: req.usuario._id
});
publicacion.save((err, publicacionGuardado) => {
if (err) {
return res.status(400).json({
ok: false,
mensaje: 'Error al crear publicacion',
errors: err
});
}
res.status(201).json({
ok: true,
publicacion: publicacionGuardado
});
});
});
// ============================================
// Borrar un publicacion por el id
// ============================================
app.delete('/:id', mdAutenticacion.verificaToken, (req, res) => {
var id = req.params.id;
Publicacion.findByIdAndRemove(id, (err, publicacionBorrado) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error borrar publicacion',
errors: err
});
}
if (!publicacionBorrado) {
return res.status(400).json({
ok: false,
mensaje: 'No existe un publicacion con ese id',
errors: { message: 'No existe un publicacion con ese id' }
});
}
res.status(200).json({
ok: true,
publicacion: publicacionBorrado
});
});
});
module.exports = app;
|
/* eslint-disable camelcase */
import React, { useState, useEffect, useContext } from 'react';
import axios from 'axios';
import styled from 'styled-components';
import { toast } from 'react-toastify';
import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core';
import Theme, { Title, Container } from '../assets/styles/Theme';
import UserContext from '../assets/UserContext';
import Select from '../assets/styles/Select';
const ComponentContainer = styled(Container)`
border-radius: 0px;
`;
const ImageAvatar = styled.img`
clip-path: ellipse(50% 50%);
object-fit: cover;
width: 10rem;
height: 10rem;
`;
const ProfileContainer = styled(Container)``;
const ProfileTitle = styled.h2`
font-size: 1.2rem;
`;
const ProfileText = styled.p`
font-size: 0.9rem;
`;
// const AddCommunityButton = styled(Button)`
// width: 40%;
// margin-left: 1rem;
// `;
const Community = styled.div`
background-color: ${Theme.fiverrGreenLight};
padding: 0.5rem;
margin-bottom: 0.5rem;
font-size: 0.9rem;
border-radius: 6px;
width: 40%;
text-align: center;
vertical-align: middle;
`;
const AddCommunityContainer = styled(Container)`
justify-content: space-around;
flex-wrap: wrap;
width: 100%;
`;
const useStyles = makeStyles((theme) => ({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
title: {
paddingLeft: '6px',
},
button: {
margin: theme.spacing(1.5),
backgroundColor: '#1dbf73',
color: 'white',
'&:hover': {
backgroundColor: '#d0f7e6',
color: 'black',
},
},
}));
export default function UserProfile() {
const { userInfo, loadingInfo, setNewChange, newChange } =
useContext(UserContext);
const [userCounter, setUserCounter] = useState(0);
const [loadingCounter, setLoadingCounter] = useState(true);
const [userCommunities, setUserCommunities] = useState([]);
const [loadingCommunity, setLoadingCommunity] = useState(true);
const [communityList, setCommunityList] = useState([]);
const [loadingList, setLoadingList] = useState(true);
const [selectedCommunity, setSelectedCommunity] = useState('');
const [newCommunity, setNewCommunity] = useState(false);
const userId = !loadingInfo && userInfo.user_id;
const getUserCounter = async () => {
try {
const dataCounter = await axios.get(
`http://localhost:8000/api/post/${userId}`
);
setUserCounter(dataCounter.data[0]);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
} finally {
setLoadingCounter(false);
}
};
const getUserCommunities = async () => {
try {
const dataCommunity = await axios.get(
`http://localhost:8000/api/user/community/${userId}`
);
setUserCommunities(dataCommunity.data);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
} finally {
setLoadingCommunity(false);
}
};
const getCommunityList = async () => {
try {
const dataList = await axios.get(`http://localhost:8000/api/community`);
setCommunityList(dataList.data);
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
} finally {
setLoadingList(false);
}
};
useEffect(() => {
getUserCounter();
getUserCommunities();
getCommunityList();
}, [newCommunity, userInfo, newChange]);
const { firstname, job, user_picture } = !loadingInfo && userInfo;
const { count } = !loadingCounter && userCounter;
const newCommunityName =
!loadingList && selectedCommunity !== '' && selectedCommunity;
const newCommunityId =
!loadingList &&
selectedCommunity !== '' &&
communityList.filter(
(community) => community.community_name === newCommunityName
)[0].id;
const postNewCommunity = async () => {
try {
await axios.post('http://localhost:8000/api/community', {
user_id: userId,
community_id: newCommunityId,
});
setNewCommunity(true);
setNewChange(!newChange);
toast.success('Community correctly added');
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
toast.error(`${error.message}`);
} finally {
setNewCommunity(false);
}
};
const classes = useStyles();
return (
!loadingInfo &&
!loadingCounter &&
!loadingCommunity &&
!loadingList && (
<ComponentContainer flex column aiCenter jcCenter>
<Title>Hello, {firstname} !</Title>
<ImageAvatar src={user_picture} />
<ProfileContainer flex column aiCenter jcCenter>
<ProfileTitle>{job}</ProfileTitle>
<ProfileText>Contributions : {count}</ProfileText>
</ProfileContainer>
<AddCommunityContainer flex row>
{userCommunities.map((community) => (
<Community key={community.id}>{community.community_name}</Community>
))}
</AddCommunityContainer>
<Container flex row>
<Select
value={selectedCommunity}
onChange={(e) => setSelectedCommunity(e.target.value)}
>
<option>-- Select community --</option>
{communityList.map((community) => (
<option key={community.id}>{community.community_name}</option>
))}
</Select>
<Button
variant="contained"
size="small"
className={classes.button}
onClick={selectedCommunity !== '' && postNewCommunity}
>
Add
</Button>
</Container>
</ComponentContainer>
)
);
}
|
import React, {Component} from 'react';
import {StyleSheet, Text, View, Button, StatusBar, TouchableHighlight, Linking} from 'react-native';
import { setNotificationData, getNotificationData } from '../Data';
import { HandleNotification } from '../PushController';
import { Slider } from 'react-native-elements';
import Switch from 'react-native-switch-pro';
import { Divider } from 'react-native-elements';
class Settings extends Component {
constructor(props){
super(props)
this.state = {
value: 30,
onOff: null
}
}
async componentDidMount(){
info = await getNotificationData()
if(info == 0){
this.setState({
onOff: false
})
}
else {
this.setState({
onOff: true,
value: info
})
}
}
setTime(swtch){
this.setState({ onOff: swtch })
console.log("state.onOff"+this.state.onOff)
console.log("swtch"+swtch)
//alert(this.state.value+String(swtch))
if(swtch){
this.bildirimAyarla(this.state.value)
}
else{
this.bildirimAyarla(0)
}
}
bildirimAyarla(number){
setNotificationData(number)
HandleNotification()
}
render() {
return (
<View style={{ flex:1 }}>
<StatusBar
backgroundColor="white"
barStyle="dark-content"
/>
<View style={{ margin:20 }}>
<View style={{ flexDirection:'row' }}>
<View style={{ flex:6 }}>
<Text style={{ fontSize: 26, fontWeight:'bold' }}>Notifications</Text>
</View>
<View style={{ flex: 2, justifyContent:'center', alignItems:'center' }}>
<Switch
backgroundActive='#4d94ff'
value={this.state.onOff}
onSyncPress={(value) => this.setTime(value)}
/>
</View>
</View>
<Divider style={{ height: 1 ,backgroundColor: '#cccccc', marginRight:10 }} />
<View style={{ marginTop:10 }}>
<Text style={{ fontSize: 16, fontWeight:'bold' }}>Notification per minute:</Text>
</View>
<View style={{ flexDirection:'row' }}>
<View style={{ flex:6, alignItems: 'stretch', justifyContent: 'center' }}>
<Slider
disabled={false}
maximumValue={180}
minimumValue={30}
step={30}
onSlidingComplete={() => this.setTime(this.state.onOff)}
thumbTintColor='#4d94ff'
value={this.state.value}
onValueChange={value => this.setState({ value })}
/>
</View>
<View style={{ flex: 2, borderColor:'#cccccc', borderRadius:20, borderWidth: 1, justifyContent:'center', alignItems:'center' }}>
<Text style={{ fontSize:28, fontWeight:'bold' }}>{this.state.value}</Text>
</View>
</View>
</View>
<Divider style={{ height: 1 ,backgroundColor: '#cccccc', marginHorizontal:10 }} />
<View style={{ margin:20 }}>
<View style={{ flexDirection:'row' }}>
<View style={{ flex:6 }}>
<Text style={{ fontSize: 26, fontWeight:'bold' }}>FeedBack</Text>
</View>
<View style={{ flex: 2, justifyContent:'center', alignItems:'center' }}>
</View>
</View>
<Divider style={{ height: 1 ,backgroundColor: '#cccccc', marginRight:10 }} />
<View style={{ marginTop:10 }}>
<Text style={{ fontSize: 16, fontWeight:'bold' }}>Please let us know if you have an issue or cool idea about Memo app.</Text>
</View>
<View style={{ flexDirection:'row' }}>
<Text style={{ fontSize:17, fontWeight:'bold', alignSelf:'center'}}>Email: </Text>
<Text onPress={() => Linking.openURL('mailto:trihay@outlook.com.tr')} style={{ fontSize:16, color: 'blue'}}> trihay@outlook.com.tr</Text>
</View>
</View>
</View>
);
}
}
export default Settings;
|
import React, { Component, PropTypes } from 'react'
import CSSModules from 'react-css-modules'
import styles from './list-group.scss'
class ListGroup extends Component {
render() {
return (
<ul styleName="list-group">
{this.props.children}
</ul>
)
}
}
export default CSSModules(ListGroup, styles)
|
//Youtube variables
var tag = document.getElementById("youtube-script");//document.createElement('script');
//tag.src = "https://www.youtube.com/iframe_api";
var ytid;
var youtubeUrl;
var player;
var endInterval;
var isPlaying = false;
//Youtube player parameters
var controls, loop, autoplay, volume, startTime, endTime, cfs, hfs;
var stopPlayTimer;
var loops = 0;
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
BannerFlow.addEventListener(BannerFlow.INIT, function(){
if(BannerFlow.imageGeneratorMode)document.getElementById("player").style.display = "none";
});
BannerFlow.addEventListener(BannerFlow.TEXT_CHANGED, function(){
if(BannerFlow.editorMode)document.getElementById("no-value").style.display = "table-cell";
if(cfs == false)document.getElementById("overlay").style.display = "none";
youtubeUrl = BannerFlow.getText().toString();
setParams();
});
BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, setParams)
function setParams(){
autoplay = BannerFlow.settings.autoplay;
loop = (BannerFlow.settings.loop == true) ? 1 : 0 ;
controls = (BannerFlow.settings.controls == true) ? 1 : 0;
startTime = (BannerFlow.settings.startTime == 0) ? null : BannerFlow.settings.startTime;
endTime = (BannerFlow.settings.endTime == 0) ? null : BannerFlow.settings.endTime;
if(BannerFlow.settings.volume >= 0)volume = BannerFlow.settings.volume; if(BannerFlow.settings.volume >= 100) volume = 100;
cfs = BannerFlow.settings.cfs;
hfs = BannerFlow.settings.hfs;
hideOnMobile = BannerFlow.settings.hideOnMobile;
autoplay = (getParameterByName('autoplay') == "false") ? (autoplay = 0) : autoplay;
controls = (getParameterByName('controls') == "false") ? (controls = 0) : controls;
loop = (getParameterByName('loop') == "false") ? (loop = 0) : loop;
startTime = (getParameterByName('start') !== null|undefined) ? parseInt(getParameterByName('start')) : parseInt(startTime);
endTime = (getParameterByName('end') !== null|undefined) ? parseInt(getParameterByName('end')) : parseInt(endTime);
volume = (getParameterByName('volume') !== null|undefined) ? parseInt(getParameterByName('volume')) : volume;
cfs = (getParameterByName('cfs') == "true") ? (cfs = true) : cfs;
hfs = (getParameterByName('hfs') == "true") ? (hfs = true) : hfs;
if(BannerFlow.editorMode) {
volume = 0;
if(BannerFlow.editorMode) {
onYouTubeIframeAPIReady();
}
}
updateVideo();
}
function updateVideo(){
if(BannerFlow.editorMode) document.getElementById("no-value").style.display = "table-cell";
if(youtubeUrl && (youtubeUrl.indexOf("//") != -1 || youtubeUrl.indexOf("www") != -1)) {
document.getElementById("player").style.opacity = 1;
if(youtubeUrl.indexOf("youtu.be") != -1){
ytid = youtubeUrl.split("/");
ytid = ytid[ytid.length - 1];
ytid = ytid.split(/[\&?\s]/)[0];
}
else{
if(youtubeUrl.indexOf("v=") != -1){
ytid = youtubeUrl.split("v=")[1];
ytid = ytid.split(/[\&?\s]/)[0];
}
}
if(controls) document.getElementById("overlay").style.display = "none";
//onPlayerReady(event);
}
else {
document.getElementById("player").style.opacity = 0;
document.getElementById("no-value").innerHTML = "<strong>Youtube player</strong>Double-click and enter a Youtube URL.";
if(youtubeUrl)
onError();
}
if(isMobile || BannerFlow.imageGeneratorMode){
if(hideOnMobile)
document.getElementsByTagName("BODY")[0].style.display = "none";
else
document.getElementsByTagName("BODY")[0].innerHTML = '<img src="http://img.youtube.com/vi/'+ytid+'/maxresdefault.jpg" style="width:100%"/>';
}
}
//Initiates and Loads the YouTube API for Iframes
function onYouTubeIframeAPIReady(e) {
if(!YT) return;
if(player) {
try {
player.removeEventListener('onReady', onPlayerReady)
player.removeEventListener('onError', onError)
player.removeEventListener('onStateChange', onStateChange)
player.destroy();
player = null;
} catch (e) {}
}
//if(!player) {
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: ytid,
playerVars: {'modestbranding':1,'showinfo':0,'controls':controls,'html5': 1,'rel': 0,'iv_load_policy':3},
events: {
'onReady': onPlayerReady,
'onError': onError,
'onStateChange': onStateChange
}
});
//}
}
function onError(){
document.getElementById("no-value").innerHTML = "<strong>Youtube player</strong>Please enter a valid Youtube URL.";
document.getElementById("player").style.opacity = 0;
}
//Loads and starts the video
function onPlayerReady(event) {
if(!player) return;
//player = event.target;
//player.setLoop(loop ? true : false);
if(player.setVolume)
player.setVolume(cfs ? 0 : volume);
if(ytid) {
if(autoplay)
player.loadVideoById({'videoId': ytid});
else
player.cueVideoById({'videoId': ytid});
}
if(!isPlaying)
player.pauseVideo();
}
BannerFlow.addEventListener(BannerFlow.START_ANIMATION, function(){
isPlaying = true;
if(player) {
player.seekTo(startTime);
if(autoplay)
player.playVideo();
else
player.pauseVideo();
}
});
//Animation in banner ended
BannerFlow.addEventListener(BannerFlow.END_ANIMATION, function(){
isPlaying = false;
if(player)
player.pauseVideo();
});
//Player state changed
function onStateChange(event){
if(!player) return;
var state = event.data;
//var time, rate, remainingTime;
if(state == 0) { //Ended
loops++
if(loop) {
player.seekTo(startTime);
}
}
if(state == -1 && loops > 0)player.seekTo(startTime); //Unstarted
if(state == 1){ //Playing
if(!endTime) endTime = event.target.B.duration;
if(endInterval) clearInterval(endInterval)
endInterval = setInterval(function(){
var time = player.getCurrentTime();
if (time > endTime) {
//rate = player.getPlaybackRate();
//remainingTime = (startTime - time) / rate;
if(loop)
player.seekTo(startTime)
else
player.pauseVideo();
}
}, 300);
}
if(loops == 0)
player.setVolume(cfs ? 0 : volume);
return event;
}
//Get query-parameters
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(BannerFlow.getText().replace(/&/g, '&'));
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var vol = false, playing = false;
//Sound on click
document.getElementById("overlay").onclick = function (){
if(cfs){
vol = !vol;
if(player) {
player.setVolume(vol ? volume : 0)
}
}
}
|
import React, { Component } from 'react';
import {
Form, Input, Tooltip,Button, Icon
} from 'antd';
import { HttpUtils } from '../../Service/HttpUtils';
import './uploadDress.css';
class ChangePassword extends Component {
state = {
confirmDirty: false,
msg: '',
correct: false,
loader: false,
showMsg: false
};
handleConfirmBlur = (e) => {
const value = e.target.value;
this.setState({ confirmDirty: this.state.confirmDirty || !!value });
}
compareToFirstPassword = (rule, value, callback) => {
const form = this.props.form;
if (value && value !== form.getFieldValue('newPassword')) {
callback('Two passwords that you enter is inconsistent!');
} else {
callback();
}
}
comparePasword = async(e) => {
if(!this.state.loader){
let obj = {
email: this.props.user,
password: e.target.value
},
res = await HttpUtils.post('comparepassword', obj);
if(!res.Match){
this.setState({msg: res.msg, correct: false});
}else {
this.setState({msg: '', correct: true});
}
}
}
changePassword = async(e) => {
this.setState({loader: true})
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
this.changePasswordApi(values);
}
});
}
changePasswordApi = async(values) => {
let obj = {
currentPassword: values.currentPassword,
newPassword: values.newPassword,
email: this.props.user
},
res = await HttpUtils.post('changePassword', obj)
if(res && res.code === 200){
this.setState({ showMsg : true });
setTimeout(() => {
document.getElementById("changePassword").click();
this.props.form.resetFields();
this.setState({ loader: false, correct: false, showMsg: false })
}, 4000);
}
}
render(){
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0,
},
sm: {
span: 16,
offset: 8,
},
},
};
const { getFieldDecorator } = this.props.form;
return(
<div>
{/*<!-- Trigger the modal with a button -->*/}
<button type="button" data-toggle="modal" data-target="#changePassword" className="btn btn_change_password">Change Password</button>
{/*<!-- Modal -->*/}
<div id="changePassword" className="modal fade" role="dialog" style={{marginTop:'5%'}}>
<div className="modal-dialog">
{/*<!-- Modal content-->*/}
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" style={{color:'rgb(203, 157, 108)'}}>×</button>
<h4 className="modal-title form_password_head">Change Password</h4>
</div>
<div className="modal-body">
<Form onSubmit={this.comparePasword}>
<div className="row" style={{margin:'0px'}}>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<label className="input_form_Profile">
Current Password
</label>
</div>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<Form.Item>
{getFieldDecorator('currentPassword', {
rules: [{
required: true, message: 'Please input your current password!',
}, {
validator: this.validateToNextPassword,
}],
})(
<Input type="password" className="reset_password" onBlur={(e) => this.comparePasword(e)}/>
)}
</Form.Item>
{!!this.state.msg && <span>{this.state.msg}</span>}
</div>
<div className="col-md-3 col-sm-3 col-12">
{this.state.correct && <Icon
type="check-circle" theme="twoTone"
twoToneColor="#52c41a" style={{float: 'right'}}/>}
</div>
</div>
<div className="row" style={{margin:'0px'}}>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<label className="input_form_Profile">
New Password
</label>
</div>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<Form.Item>
{getFieldDecorator('newPassword', {
rules: [{
required: true, message: 'Please input your password!',
}, {
validator: this.validateToNextPassword,
}],
})(
<Input type="password" className="reset_password" />
)}
</Form.Item>
</div>
</div>
<div className="row" style={{margin:'0px'}}>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<label className="input_form_Profile">
Confirm Password
</label>
</div>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<Form.Item>
{getFieldDecorator('confirm', {
rules: [{
required: true, message: 'Please confirm your password!',
}, {
validator: this.compareToFirstPassword,
}],
})(
<Input type="password" className="reset_password" onBlur={this.handleConfirmBlur} />
)}
</Form.Item>
</div>
</div>
<div className="row" style={{margin:'0px'}}>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<button
type="submit"
name=""
className="button btn_reset_password"
value=""
onClick={this.changePassword}>
Reset Password</button>
</div>
</div>
<div className="row" style={{margin:'0px'}}>
<div className="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<button
type="submit"
name=""
className="button btn_cancel_password"
value=""
onClick={this.changePassword}>
Cancel</button>
</div>
</div>
{this.state.showMsg && <div className="row" style={{textAlign: 'center', marginTop: '10px'}}>
Your password has been changed!!!
</div>}
</Form>
</div>
</div>
</div>
</div>
</div>
)
}
}
const WrappedNormalchangepasswordForm = Form.create()(ChangePassword);
export default WrappedNormalchangepasswordForm;
|
import { memo } from 'react';
import { Box } from '@rebass/grid';
import PropTypes from 'prop-types';
import Outer from './style';
import { convertTimeStampToDate } from '../../utils';
const Flight = ({ data }) => {
if (!data) return null;
return (
<Outer alignItems="center">
<Box width={1 / 4}>{data.route}</Box>
<Box width={1 / 4}>{convertTimeStampToDate(data.departure)}</Box>
<Box width={1 / 4}>{convertTimeStampToDate(data.arrival)}</Box>
<Box width={1 / 4}>{data.type}</Box>
</Outer>
);
};
Flight.propTypes = {
data: PropTypes.object.isRequired,
};
export default memo(Flight);
|
const mogoose = require('mongoose')
if (process.argv.length < 3) {
console.log('give password as argument');
process.exit(1)
}
const password = process.argv[2]
const url = `mongodb+srv://fullstack:${password}@cluster0-88lk9.mongodb.net/phonebook-app?retryWrites=true&w=majority`
mogoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true})
const contactSchema = new mogoose.Schema({
name: String,
number: String,
})
const Contact = mogoose.model('Contact', contactSchema)
if (process.argv.length == 3) {
// get all data
console.log('phonebook:')
Contact.find({}).then(result => {
result.forEach(contact => {
console.log(`${contact.name} ${contact.number}`)
mogoose.connection.close()
})
})
} else if (process.argv.length == 5) {
// create new object save to database
const contact = new Contact({
name: process.argv[3],
number: process.argv[4]
})
contact.save().then(response => {
// console.log(response)
console.log(`add ${response.name} number ${response.number} to phonebook`)
mogoose.connection.close()
})
}
|
$(document).ready(() => {
var navScrollPos = $("nav").offset().top;
$('.options').hide();
$('.options').sticky({ topSpacing: 0 });
$('.button').on('click', event => {
if (($("html, body").scrollTop() + 200) < navScrollPos) {
$("html, body").animate({ scrollTop: $('#arrow').offset().top + 1 }, 1000);
$(event.currentTarget).addClass('rotate');
} else if ($("html, body").scrollTop() >= (navScrollPos - 200)) {
$("html, body").animate({ scrollTop: $('.sec1').offset().top }, 1000);
$(event.currentTarget).removeClass('rotate');
}
});
$(window).scroll(function() {
if (($(document).scrollTop() + 200) < navScrollPos) {
$('.button').removeClass('rotate');
$('nav').removeClass('black',800);
$('.options').fadeOut('fast');
$('#toTop').fadeOut('slow');
} else if ($(document).scrollTop() >= (navScrollPos - 200)) {
$('.button').addClass('rotate');
$('nav').addClass('black',800);
$('.options').fadeIn('fast');
$('#toTop').fadeIn('slow');
};
});
$('.options').on('sticky-start', () => {
$('.options').addClass('black');
$('.options').on('mouseenter', () => {
$('.options').addClass('active',300);
});
$('.options').on('mouseleave', () => {
$('.options').removeClass('active',100);
});
});
$('.options').on('sticky-end', () => {
$('.options').removeClass('black');
$('.options').removeClass('active');
});
$('.options').on('click', () => {
$('#email').trigger();
});
$('#toTop').on('mouseenter', event => {
$(event.currentTarget).addClass('active', 500);
});
$('#toTop').on('mouseleave', event => {
$(event.currentTarget).removeClass('active', 500);
});
$('#toTop').on('click', () => {
$("html, body").animate({ scrollTop: $('.sec1').offset().top }, 1000);
});
$('li').on('click', function () {
$(this).siblings().removeClass('active');
$(this).addClass('active');
});
$('#media').click(function () {
$('#loadableContent').load("ajax/media.html", function () {
$('#mediaContainer').fadeIn(2500);
});
});
$('#resume').click(function () {
$('#loadableContent').load("ajax/resume.html", function () {
$('#resumeContainer').fadeIn(2500);
});
});
$('#comp_sci').click(function () {
$('#loadableContent').load("ajax/comp_sci.html", function () {
$('#comp_sciContainer').fadeIn(2500);
});
});
$('#photo').click(function () {
$('#loadableContent').load("ajax/photo.html", function () {
$('#photoContainer').fadeIn(2500);
});
});
$('#video').click(function () {
$('#loadableContent').load("ajax/video.html", function () {
$('#videoContainer').fadeIn(2500);
});
});
$('#graphics').click(function () {
$('#loadableContent').load("ajax/graphics.html", function () {
$('#graphicsContainer').fadeIn(2500);
});
});
var date = new Date();
$('#copyright').html("©" + date.getFullYear());
$('#randSent').html(randStr());
(function theLoop (i) {
setTimeout(function () {
$('#randSent').html(randStr());
if (--i) { // If i > 0, keep going
theLoop(i); // Call the loop again, and pass it the current value of i
}
}, 4500);
})(10);
$('#footerHome').click(function () {
console.log("I've been clicked!");
window.location.href = 'blog.html';
});
// $('.dynamic-photo').fadeTo('slow', 0.3, function () {
// $(this).css('background-image', 'url("imgs/LukeZwickerPlaneRide-3.jpg")');
// }).delay(5000).fadeTo('slow', 1);
});
function randStr() {
var num = Math.floor(Math.random() * 6);
var str = "hello_world";
switch (num) {
case 0:
str = "reconstructing the matrix";
break;
case 1:
str = "be prepared for awesomeness";
break;
case 2:
str = "environment fabrication in progress";
break;
case 3:
str = "making something";
break;
case 4:
str = "gathering materials";
break;
case 5:
str = "where am i?";
break;
default:
str = "hello_world";
}
return str;
}
|
import extrasOne from "../assets/extras1.png";
import extrasTwo from "../assets/extras2.png";
import extrasThree from "../assets/extras3.png";
import extrasFour from "../assets/extras4.png";
const extras = [
{
img: extrasOne,
title: "Red Stripe Beer",
subtitle: "4pk",
price: "10",
vip: false,
features: [
"Select From Medium or Large Bouquet",
"Presented Inside the Vehicle",
"Presented on Inbound Journey",
],
},
{
img: extrasTwo,
title: "Champagne",
subtitle: "4pk",
price: "10",
vip: false,
features: [
"Select From Medium or Large Bouquet",
"Presented Inside the Vehicle",
"Presented on Inbound Journey",
],
},
{
img: extrasThree,
title: "Flowers",
subtitle: "1 Bouquet",
price: "10",
vip: false,
features: [
"Select From Medium or Large Bouquet",
"Presented Inside the Vehicle",
"Presented on Inbound Journey",
],
},
{
img: extrasFour,
title: "VIP Pass",
subtitle: "Club & Airport",
price: "10",
vip: true,
features: [
"Select From Medium or Large Bouquet",
"Presented Inside the Vehicle",
"Presented on Inbound Journey",
],
},
];
export default extras;
|
/**
* Authors: Diego Ceresuela, Luis Jesús Pellicer, Raúl Piracés.
* Date: 16-05-2016
* Name file: tweets.js
* Description: Provides functions to interact with Twitter API and Tweet resource.
*/
(function () {
var OAuth = require('./OAuth');
var mongoose = require('mongoose');
var Twitter = mongoose.model('twitter');
var User = mongoose.model('users');
var passport = require('passport');
var request = require('request');
var atob = require('atob');
/**
* Function for posting a new tweet using OAuth, user token and secret.
* It needs an initial OAuth object with the twitter application consumer
* key and secret.
* @param user is the local user object (from database).
* @param body is the body of the request made.
* @param callback is the callback object, containing response of Twitter.
*/
function makeTweet(user, body, callback) {
OAuth.initTwitterOauth(function(oa)
{
oa.post(
"https://api.twitter.com/1.1/statuses/update.json"
, user.token
, user.secret
// Tweet content
, {
"status": body.status
//"in_reply_to_status_id": body.in_reply_to_status_id,
//"lat": body.lat,
//"long": body.long,
//"place_id": body.place_id
}
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Gets an unique tweet from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param params are the params of the request.
* @param callback is the callback object, containing the resultant tweet data.
*/
function getTweet(user, params, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.get(
"https://api.twitter.com/1.1/statuses/show.json?" +
"id=" + params.id
, user.token
, user.secret
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Retweet an unique tweet from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param params are the params of the request.
* @param callback is the callback object, containing the resultant tweet
* data (and retweet data).
*/
function makeRetweet(user, params, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.post(
"https://api.twitter.com/1.1/statuses/retweet/" + params.id + ".json"
, user.token
, user.secret
// Content
, {
"id": params.id
}
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Unretweets an unique tweet from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param params are the params of the request.
* @param callback is the callback object, containing the resultant tweet
* data (and unretweet data).
*/
function makeUnretweet(user, params, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.post(
"https://api.twitter.com/1.1/statuses/unretweet/"
+ params.id + ".json"
, user.token
, user.secret
// Content
, {
"id": params.id
}
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Favorite/like an unique tweet from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param params are the params of the request.
* @param callback is the callback object, containing the resultant
* tweet data (and favorite data).
*/
function makeFavorite(user, params, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.post(
"https://api.twitter.com/1.1/favorites/create.json"
, user.token
, user.secret
// Content
, {
"id": params.id
}
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Unfavorite/dislike an unique tweet from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param params are the params of the request.
* @param callback is the callback object, containing the resultant
* tweet data (and unfavorite data).
*/
function makeUnfavorite(user, params, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.post(
"https://api.twitter.com/1.1/favorites/destroy.json"
, user.token
, user.secret
// Content
, {
"id": params.id
}
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Gets user info from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param id is the id of the twitter user.
* @param callback is the callback object, containing the resultant
* user data (statistics info).
*/
function getUserInfo(user, id, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.get(
"https://api.twitter.com/1.1/users/show.json?id=" + id
, user.token
, user.secret
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Increments the local saved number of tweets by num.
* @param user is the local user object.
* @param id is the twitter id user.
* @param num_app is the number to add to the local total tweets statistic.
*/
function updateStatistics(user, id, num_app){
getUserInfo(user, id, function(result){
Twitter.findOneAndUpdate({user: user.user},
{$set: {statuses_count: result.statuses_count},
$inc: { tweet_app: num_app }}, function(err, doc){
Twitter.find({user:user.user}, function(err,docs){
var totalTwitter = 0;
var totalApp = 0;
for(var doc in docs){
totalTwitter = totalTwitter + docs[doc].statuses_count;
totalApp = totalApp + docs[doc].tweet_app;
}
User.findOneAndUpdate({email: user.user},
{$set: {tweet_total: totalTwitter, tweet_app: totalApp}},
function(){});
});
});
});
}
/**
* Converts a JWT in request to a JSON Object.
* @param req is the request containing the JWT.
* @param callback is the object callback, a user from database.
* @constructor constructor.
*/
function getUserFromJWT(req, callback){
var payload = req.headers.authorization.split('.')[1];
payload = atob(payload);
payload = JSON.parse(payload);
Twitter.findOne({user: payload.email, in_use: true}, function(err, doc){
if(err) {
callback(err);
} else {
callback(doc);
}
});
}
/**
* Gets own tweets from Twitter.
* Requires user authentication.
* @param user is the twitter user.
* @param callback is the object callback, a user from database.
*/
function getOwnTweets(user, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.get(
"https://api.twitter.com/1.1/statuses/user_timeline.json?count=200"
, user.token,user.secret,
function(error, data, response){
if(error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
)});
}
/**
* Gets all tweets from Twitter account.
* Requires user authentication
* @param user is the local user object.
* @param callback is the object callback, a user from database.
*/
function getAccountTweets(user,callback){
OAuth.initTwitterOauth(function(oa)
{
oa.get(
"https://api.twitter.com/1.1/statuses/home_timeline.json?count=200"
, user.token,user.secret,
function(error, data, response){
if(error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
)});
}
/**
* Delete tweet in Twitter
* Requires user authentication.
* @param user is the local user object.
* @param id is the unique tweet id.
* @param callback is the object callback, a user from database.
*/
function deleteTweet(user, id, callback) {
OAuth.initTwitterOauth(function (oa) {
oa.post(
"https://api.twitter.com/1.1/statuses/destroy/" + id + ".json"
, user.token
, user.secret
// Content
, {
"id": id
},
function (error, data, response) {
if (error) {
callback(error);
} else {
callback(JSON.parse(data));
}
}
)
});
}
/**
* Gets user info from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param query is the query to find tweets.
* @param callback is the callback object, containing the resultant
* user data (searched tweets).
*/
function searchTweets(user, query, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.get(
"https://api.twitter.com/1.1/search/tweets.json?q=" + query
, user.token
, user.secret
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Search mentions of specific user from Twitter by unique id.
* Requires user authentication.
* @param user is the local user.
* @param callback is the callback object, containing the resultant mentions
* data (searched mention tweets).
*/
function searchMentions(user, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.get(
"https://api.twitter.com/1.1/statuses/mentions_timeline.json"
, user.token
, user.secret
, function (error, data, response) {
if (error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
);
});
}
/**
* Gets followers list from Twitter.
* Requires user authentication.
* @param user is the twitter user.
* @param callback is the object callback, a user from database.
*/
function getFollowersList(user, callback){
OAuth.initTwitterOauth(function(oa)
{
oa.get(
"https://api.twitter.com/1.1/followers/list.json?" +
"count=200&screen_name=" + user.screen_name
, user.token,user.secret,
function(error, data, response){
if(error){
callback(error);
} else {
callback(JSON.parse(data));
}
}
)});
}
exports.makeTweet = makeTweet;
exports.getTweet = getTweet;
exports.makeRetweet = makeRetweet;
exports.makeUnretweet = makeUnretweet;
exports.makeFavorite = makeFavorite;
exports.makeUnfavorite = makeUnfavorite;
exports.getUserInfo = getUserInfo;
exports.updateStatistics = updateStatistics;
exports.getUserFromJWT = getUserFromJWT;
exports.getOwnTweets = getOwnTweets;
exports.getAccountTweets = getAccountTweets;
exports.deleteTweet = deleteTweet;
exports.searchTweets = searchTweets;
exports.searchMentions = searchMentions;
exports.getFollowersList = getFollowersList;
})();
|
import React from "react";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import HomeSharpIcon from "@material-ui/icons/HomeSharp";
import images from "../photos";
const useStyles = makeStyles({
root: {
maxWidth: "90%",
height: "100%",
"@media (min-width:330px)": {
display: "flex",
},
},
media: {
height: 300,
maxHeight: "40%",
minWidth: "35%",
},
});
export default function AnimalCard({
id,
name,
age,
weight,
gender,
breed,
blurb,
foster,
picture_link,
alt_text,
}) {
const classes = useStyles();
return (
<Card
className={classes.root}
variant="outlined"
style={{ marginBottom: "1rem", marginLeft: "auto", marginRight: "auto " }}
>
<CardMedia
className={classes.media}
image={images[picture_link]}
title={alt_text}
/>
<CardContent>
<Typography
data-testid={`animalcard-1`}
gutterBottom
variant="h5"
component="h2"
>
{name}{" "}
</Typography>
<Typography gutterBottom variant="h6" component="h5">
{foster ? (
<div>
<HomeSharpIcon />
Foster Home Needed
</div>
) : null}
<span>•</span> {breed}, {age}, {weight}, {gender}
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
{blurb}
</Typography>
</CardContent>
</Card>
);
}
|
import React, { useEffect, useState } from 'react';
import {
Container,
EmptyStateMsg,
EmptyStateMsgContainer,
PlaceholderImg,
ResultMovieNameLink,
ResultMovieYear,
ResultMovieCard,
} from './Movies.style';
const Movies = ({ movies }) => {
const [moviesCard, setMoviesCard] = useState([]);
useEffect(() => {
const moviesList = [];
if (!moviesCard.length && movies && movies.length) {
debugger
movies.forEach(movie => {
const imdbURL = "https://www.imdb.com/title/"+movie.movie.ids.imdb;
debugger
moviesList.push(
<ResultMovieCard>
{/* <PlaceholderImg src={MoviePlaceholderImg}/> */}
<ResultMovieNameLink href={imdbURL} target="_blank">
{movie.movie.title}
</ResultMovieNameLink>
<ResultMovieYear>
Year: {movie.movie.year}
</ResultMovieYear>
</ResultMovieCard>
)
});
}
setMoviesCard(moviesList);
}, [movies]);
return (
<Container>
{moviesCard}
</Container>
)
}
export default Movies;
|
$(document).ready(function() {
//Login
$("#go").click(function() {
var user = $("#user").val();
var pass = $("#pass").val();
$("#error").html("");
login(user,pass);
});
//Register
$("#register").click(function() {
var reguser = $("#reguser").val();
var regpass = $("#regpass").val();
var regname = $("#regname").val();
if(reguser.length == 0) {
$("#err").html("Please Enter A Username");
}
else if(regpass.length == 0) {
$("#err").html("Please Enter A Password");
}
else if(reguser.length > 19) {
$("#err").html("Please Enter A Shorter Username");
}
else if(regname.length == 0) {
$("#err").html("Please Enter A Name");
}
else {
reg(reguser,regpass,regname);
}
});
//Nav-bar click
$(".change").click(function() {
if(sessionStorage.login!= undefined) {
pauseWorker();
if(this.id == "profile") {
$.when(template(this.id)).done(function() {
prof(sessionStorage.login,sessionStorage.login);
unpauseWorker(sessionStorage.login,sessionStorage.login);
});
}
else if(this.id == "friends") {
$.when(template(this.id)).done(function() {
friends();
});
}
else if(this.id == "logout") {
$.when(template(this.id)).done(function() {
logout();
stopFriendsOnline();
});
}
}
});
$("#home").click(function() {
if(sessionStorage.login == undefined) {
location.reload();
}
});
//Post
$("#sendpost").live('click', function() {
//send post
var username = $("#username").html();
var post = $("#post").val();
$.ajax({
url: "http://localhost:8888/post?user="+sessionStorage.login
+"&target="+username+"&text="+post,
dataType: "json"
});
//Remove text
$("#post").val("");
});
//Friend in Friends click
$(".friendlisted").live('click', function() {
var id = this.id;
$.when(template("profile")).done(function() {
prof(sessionStorage.login,id);
unpauseWorker(sessionStorage.login,id);
});
});
//Search on "Enter" key
$("#search").keydown(function(e) {
if (e.keyCode == 13) {
var query = $("#search").val();
$.when(template("search")).done(function() {
search(query);
$("#search").val("");
stopWorker();
});
}
});
//Search-result click
$(".searchResult").live('click', function() {
var id = this.id;
$.when(template("profile")).done(function() {
prof(sessionStorage.login,id);
unpauseWorker(sessionStorage.login,id);
});
});
//Add friend
$("#friendadd").live('click', function() {
var username = $("#username").html();
$.ajax({
url: "http://localhost:8888/add?user="+sessionStorage.login
+"&target="+username,
dataType: "json",
success: function(data, err) {
updateProf = true; //Force update -worker
}
});
$("#friendadd").attr("disabled", "disabled");
$("#friendadd span").text("Already Friends");
});
}); //End document ready
function template(thisid) {
return $.ajax({
url: "http://localhost:8888/content?template="+thisid,
success : function(data,err) {
$("#content").html(data);
}
});
}
//Profile ajax-call, not used by worker
function prof(userprof, profile) {
return $.ajax({
url: "http://localhost:8888/profile?user="+userprof+"&target="+profile,
dataType : "json",
success : showProfile
});
}
//Friends ajax-call
function friends() {
return $.ajax({
url: "http://localhost:8888/friends?user="+sessionStorage.login,
dataType : "json",
success : showFriends
});
}
//Search ajax-call
function search(query) {
$.ajax({
url: "http://localhost:8888/search?q="+query,
dataType: "json",
success: showSearch
});
}
//Login ajax-call
function log(user,pass) {
return $.ajax({
url: "http://localhost:8888/login?user="+user+"&pw="+pass,
success : function(data,err) {
if (data == "1") {
sessionStorage.login = user;
chatClient(user); //Login to chat
}
else if (data == "0") {
$("#error").html("Wrong Password or Username");
}
else {
$("#error").html("Database Error")
}
}
});
}
function login(user,pass) {
$.when(log(user, pass)).done(function(){
if (sessionStorage.login != undefined) {
$.when(template("profile")).done(function() {
//Start the workers
startFriendsOnline(user);
startWorker(sessionStorage.login, sessionStorage.login);
$("#chatOk").html(" <i class=\"icon-ok-circle\"></i>");
});
}
});
}
//Logoff ajax-call
function logout() {
return $.ajax({
url: "http://localhost:8888/logoff?user="+sessionStorage.login,
success : function(data,err) {
sessionStorage.clear();
}
});
}
//Used by non-worker
function showProfile(data,err) {
if(data["username"] == sessionStorage.login || data["friends"] == true) {
$("#note").html(""); //remove the help text
$("#friendadd").attr('disabled','disabled') //disable the friend button
$('#friendadd span').text('Already Friends');
$.map(data["posts"], function(post){
var member = $(document.createElement("div"))
.attr("class", "posts")
.append("<pre>"+post["post"]+"</pre>")
.append("<p class=\"postname\">"+"- "+post["user"]+"</p>")
$("#oldposts").prepend(member);
});
}
else {
$("#friendadd").removeAttr("disabled") // Enable friendadd again
$('#friendadd span').text('Add Friend');
}
$("#username").html(data["username"]);
$("#name").html(data["name"]);
}
function showFriends(data,err) {
for(var i = 0; i < data.length; i++) {
//Add friend-element
var flist = $(document.createElement("div"))
.attr("class", "friendlisted")
.attr("id", data[i]["user"])
.append("<pre>" + data[i]["name"] + "</pre>")
$("#friendlist").append(flist);
}
}
function showSearch(data,err) {
for(var i=0; i < data.length; i++) {
//Add result-element
var slist = $(document.createElement("div"))
.attr("class", "searchResult")
.attr("id", data[i]["user"])
.append("<pre>" + data[i]["name"] + "</pre>")
$("#searchlist").append(slist);
}
}
//Register ajax-call
function reg(user,pass,name) {
$.ajax({
url: "http://localhost:8888/register?user="+user+"&pw="+pass+"&name="+name,
success : function(data,err) {
$("#err").html(data);
if(data == "Congratulations! Your account has been successfully registred.") {
$("#Regdrop").modal("hide")
}
}
});
}
function showOnlineFriends(data) {
//Reload online friends
$('#of').html("");
$('#amountOnline span').text('Online Friends: ' + data.length);
for(var i = 0; i < data.length; i++) {
var flist = $(document.createElement("li"))
.attr("class", "noGroup")
.attr("id", "online" + data[i]["user"])
.attr("onClick", "addToChat(" + data[i]["user"] + ")")
.append("<a tabindex=\"-1\" href=\"#\">" + data[i]["user"] + "</a>")
$("#of").append(flist);
}
}
/************************
* Workers
************************/
var friendsOnline;
function startFriendsOnline(user) {
if(typeof(Worker)!=="undefined") {
if(typeof(worker)=="undefined") {
friendsOnline = new Worker('friendsOnline.js');
}
friendsOnline.onmessage = function(event) {
var data = jQuery.parseJSON(event.data);
showOnlineFriends(data);
}
friendsOnline.postMessage(user);
}
}
function stopFriendsOnline() {
friendsOnline.terminate();
}
var worker;
var updateProf = true; //Force update
function startWorker(user,target) {
if(typeof(Worker)!=="undefined") {
if(typeof(worker)=="undefined") {
worker = new Worker('worker.js');
}
worker.onmessage = function(event) {
var data = jQuery.parseJSON(event.data);
var newPosts = data["posts"].length - $("#oldposts").children().length;
//Any update required?
if (newPosts > 0 || updateProf) {
//Check if friends
if(data["username"] == sessionStorage.login || data["friends"] == true) {
$("#note").html(""); //remove the help text
$("#friendadd").attr('disabled','disabled') //disable the friend button
$('#friendadd span').text('Already Friends');
}
else {
$("#friendadd").removeAttr("disabled") // Enable friendadd again
$('#friendadd span').text('Add Friend');
}
updateProf = false;
//Add posts
for(var i=data["posts"].length - newPosts; i < data["posts"].length; i++) {
var post = data["posts"][i];
var member = $(document.createElement("div"))
.attr("class", "posts")
.append("<pre>"+post["post"]+"</pre>")
.append("<p class=\"postname\">"+"- "+post["user"]+"</p>")
$("#oldposts").prepend(member);
};
}
$("#username").html(data["username"]);
$("#name").html(data["name"]);
};
//First postMessage is to let worker know what variable to set
worker.postMessage("user");
worker.postMessage(user);
worker.postMessage("target");
worker.postMessage(target);
}
else
{
alert("Sorry, your browser does not support Web Workers!");
}
}
function pauseWorker() {
//First postMessage is to let worker know what variable to set
worker.postMessage("pause");
worker.postMessage("1");
}
function unpauseWorker(user,target) {
//First postMessage is to let worker know what variable to set
worker.postMessage("user");
worker.postMessage(user);
worker.postMessage("target");
worker.postMessage(target);
worker.postMessage("pause");
worker.postMessage("0");
}
function stopWorker()
{
worker.terminate();
}
|
import { combineReducers } from 'redux'
import productReducer from './products/productReducer'
const reducers = combineReducers({
products: productReducer
})
export default reducers
|
import Node from './node';
import * as types from './types';
export default class Container extends Node {
constructor (opts) {
super(opts);
if (!this.nodes) {
this.nodes = [];
}
}
append (selector) {
selector.parent = this;
this.nodes.push(selector);
return this;
}
prepend (selector) {
selector.parent = this;
this.nodes.unshift(selector);
return this;
}
at (index) {
return this.nodes[index];
}
index (child) {
if (typeof child === 'number') {
return child;
}
return this.nodes.indexOf(child);
}
get first () {
return this.at(0);
}
get last () {
return this.at(this.length - 1);
}
get length () {
return this.nodes.length;
}
removeChild (child) {
child = this.index(child);
this.at(child).parent = undefined;
this.nodes.splice(child, 1);
let index;
for ( let id in this.indexes ) {
index = this.indexes[id];
if ( index >= child ) {
this.indexes[id] = index - 1;
}
}
return this;
}
removeAll () {
for (let node of this.nodes) {
node.parent = undefined;
}
this.nodes = [];
return this;
}
empty () {
return this.removeAll();
}
insertAfter (oldNode, newNode) {
newNode.parent = this;
let oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex + 1, 0, newNode);
newNode.parent = this;
let index;
for ( let id in this.indexes ) {
index = this.indexes[id];
if ( oldIndex <= index ) {
this.indexes[id] = index + 1;
}
}
return this;
}
insertBefore (oldNode, newNode) {
newNode.parent = this;
let oldIndex = this.index(oldNode);
this.nodes.splice(oldIndex, 0, newNode);
newNode.parent = this;
let index;
for ( let id in this.indexes ) {
index = this.indexes[id];
if ( index <= oldIndex ) {
this.indexes[id] = index + 1;
}
}
return this;
}
each (callback) {
if (!this.lastEach) {
this.lastEach = 0;
}
if (!this.indexes) {
this.indexes = {};
}
this.lastEach ++;
let id = this.lastEach;
this.indexes[id] = 0;
if (!this.length) {
return undefined;
}
let index, result;
while (this.indexes[id] < this.length) {
index = this.indexes[id];
result = callback(this.at(index), index);
if (result === false) {
break;
}
this.indexes[id] += 1;
}
delete this.indexes[id];
if (result === false) {
return false;
}
}
walk (callback) {
return this.each((node, i) => {
let result = callback(node, i);
if (result !== false && node.length) {
result = node.walk(callback);
}
if (result === false) {
return false;
}
});
}
walkAttributes (callback) {
return this.walk((selector) => {
if (selector.type === types.ATTRIBUTE) {
return callback.call(this, selector);
}
});
}
walkClasses (callback) {
return this.walk((selector) => {
if (selector.type === types.CLASS) {
return callback.call(this, selector);
}
});
}
walkCombinators (callback) {
return this.walk((selector) => {
if (selector.type === types.COMBINATOR) {
return callback.call(this, selector);
}
});
}
walkComments (callback) {
return this.walk((selector) => {
if (selector.type === types.COMMENT) {
return callback.call(this, selector);
}
});
}
walkIds (callback) {
return this.walk((selector) => {
if (selector.type === types.ID) {
return callback.call(this, selector);
}
});
}
walkNesting (callback) {
return this.walk(selector => {
if (selector.type === types.NESTING) {
return callback.call(this, selector);
}
});
}
walkPseudos (callback) {
return this.walk((selector) => {
if (selector.type === types.PSEUDO) {
return callback.call(this, selector);
}
});
}
walkTags (callback) {
return this.walk((selector) => {
if (selector.type === types.TAG) {
return callback.call(this, selector);
}
});
}
walkUniversals (callback) {
return this.walk((selector) => {
if (selector.type === types.UNIVERSAL) {
return callback.call(this, selector);
}
});
}
split (callback) {
let current = [];
return this.reduce((memo, node, index) => {
let split = callback.call(this, node);
current.push(node);
if (split) {
memo.push(current);
current = [];
} else if (index === this.length - 1) {
memo.push(current);
}
return memo;
}, []);
}
map (callback) {
return this.nodes.map(callback);
}
reduce (callback, memo) {
return this.nodes.reduce(callback, memo);
}
every (callback) {
return this.nodes.every(callback);
}
some (callback) {
return this.nodes.some(callback);
}
filter (callback) {
return this.nodes.filter(callback);
}
sort (callback) {
return this.nodes.sort(callback);
}
toString () {
return this.map(String).join('');
}
}
|
;(function(){
//设置foot下的当前时间
var nowtime=new Date();
var nowyear=nowtime.getFullYear();
$(".nowtime").html(nowyear);
//地址切换
$(".address_list li").mouseover(function(){
$(".address_list li").removeClass("active");
$(this).addClass("active");
$(".dizhi_box").hide();
$(".dizhi_box").eq($(this).index()).show();
})
//右侧悬浮窗
$(".cha").click(function(){
$(".rightFixed").animate({
right:-150
},200,function(){
$(".yousuo").animate({
right:0
},200)
})
})
$(".yousuo").click(function(){
$(".yousuo").animate({
right:-52
},200,function(){
$(".rightFixed").animate({
right:7
},200)
})
})
//返回顶部
$(".totop").click(function(){
$("body").animate({
scrollTop:0
},500);
$("html").animate({
scrollTop:0
},500);
});
})();
|
const mongoose = require('mongoose')
const shortid = require('shortid')
const Response = require('../lib/generateResponseLib')
const util = require('../lib/utilityLib')
const bcryptLib = require('../lib/bcryptLib')
const Mailer = require('../lib/sendMailLib')
const logger = require('../lib/loggerLib')
const time = require('../lib/timeLib')
const JWT = require('../lib/tokenLib')
//Importing the models here
const UserModel = mongoose.model('User')
const AuthModel = mongoose.model('Auth')
/**
* function for sign-up.
*/
let signup = (req, res) => {
let validateUserInput = () => {
return new Promise((resolve, reject) => {
console.log(req.body)
if (util.isObjectEmpty(req.body)) {
let apiResponse = Response.generate(true, 'Signup Failed!! One or More Parameters were missing.', 400, null);
res.send(apiResponse);
reject(apiResponse);
}
else if (util.isEmailValid(req.body.email)) {
if (!util.isPasswordValid(req.body.password)) {
let apiResponse = Response.generate(true, 'Signup Failed!! Invalid Password.', 400, null);
res.send(apiResponse);
reject(apiResponse);
}
else
resolve(req);
}
else {
let apiResponse = Response.generate(true, 'Signup Failed!! Invalid Email address.', 400, null);
res.send(apiResponse);
reject(apiResponse);
}
})
}
let createUserAccount = () => {
return new Promise((resolve, reject) => {
UserModel.findOne({ email: req.body.email }, (err, document) => {
if (err) {
logger.error('Error occurred at database.', 'userProfileController: createUserAccount()', 10);
let apiResponse = Response.generate(true, 'Failed to create User account!! Some internal error occurred.', 500, err);
res.send(apiResponse);
reject(apiResponse);
}
else if (!util.isEmpty(document)) {
let apiResponse = Response.generate(true, 'Signup Failed!! User already exists with this Email.', 403, null);
res.send(apiResponse);
reject(apiResponse);
}
else {
let newUser = new UserModel({
userId: shortid.generate(),
firstName: req.body.firstName,
lastName: req.body.lastName,
countryCode: req.body.countryCode,
mobileNumber: req.body.mobile,
email: req.body.email,
password: bcryptLib.hashPassword(req.body.password),
createdOn: time.now()
}) // end new User model
newUser.save((error, userAccount) => {
if (error) {
logger.error('Error occurred at database.', 'userProfileController: createUserAccount()', 10);
let apiResponse = Response.generate(true, 'Failed to create User account!! Some internal error occurred.', 500, err);
res.send(apiResponse);
reject(apiResponse);
} else {
let userAccountObj = userAccount.toObject();
delete userAccountObj.password;
delete userAccountObj.__v;
delete userAccountObj._id;
let apiResponse = Response.generate(false, 'Signup Successful!!', 200, userAccountObj);
res.send(apiResponse);
resolve(userAccountObj);
}
}) // saved new User in database
}
})
})
}
validateUserInput().then(createUserAccount)
.then((resolve) => {
logger.info('New User Account Created.', 'userProfileController: createUserAccount()', 10);
logger.info(resolve, 'Resolve from createUserAccount()', 5)
})
.catch((err) => {
logger.error(err, 'userProfileController: createUserAccount()', 10);
})
} // end signup()
/**
* function for login.
*/
let login = (req, res) => {
let validateLogin = () => {
return new Promise((resolve, reject) => {
if (util.isObjectEmpty(req.body)) {
let apiResponse = Response.generate(true, 'Login Failed!! One or More Parameters were missing.', 400, null);
res.send(apiResponse);
reject(apiResponse);
}
else {
UserModel.findOne({ email: req.body.email }, (err, userDetails) => {
if (err) {
logger.error('Error occurred while retrieving from database.', 'userProfileController: validateLogin()', 10);
let apiResponse = Response.generate(true, 'Failed to retrieve User details!! Some internal error occurred.', 500, err);
res.send(apiResponse);
reject(apiResponse);
} else if (util.isEmpty(userDetails)) {
logger.error("No User Found", "userProfileController: validateLogin()", 7);
let apiResponse = Response.generate(true, 'The email or password you entered was incorrect. Please try again. ', 404, null);
res.send(apiResponse);
reject(apiResponse);
} else {
console.log(userDetails);
bcryptLib.comparePassword(req.body.password, userDetails.password, (error, isMatched) => {
if (error) {
logger.error("Error occurred while comparing password", "userProfileController: validateLogin()", 10);
let apiResponse = Response.generate(true, 'Login Failed !! Some error occurred. Please try again or later. ', 500, null);
res.send(apiResponse);
reject(apiResponse);
}
else if (isMatched) {
let userDetailsObj = userDetails.toObject();
delete userDetailsObj.password;
delete userDetailsObj.__v;
delete userDetailsObj._id;
delete userDetailsObj.createdOn;
logger.info("Login validation successful.", "userProfileController: validateLogin()", 10);
// let apiResponse = Response.generate(false, 'Login Successful!!', 200, userDetailsObj);
// res.send(apiResponse);
resolve(userDetailsObj);
}
else {
logger.info("Invalid Login !!", "userProfileController: validateLogin()", 10);
let apiResponse = Response.generate(true, 'The email or password you entered was incorrect. Please try again. ', 404, null);
res.send(apiResponse);
reject(apiResponse);
}
})
}
})
}
})
}
let generateToken = (userDetails) => {
console.log("generate token");
return new Promise((resolve, reject) => {
JWT.generateToken(userDetails, (err, tokenDetails) => {
if (err) {
console.log(err)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null);
reject(apiResponse)
} else {
tokenDetails.userId = userDetails.userId;
tokenDetails.userDetails = userDetails;
resolve(tokenDetails)
}
})
})
} // END generateToken()
let saveToken = (tokenDetails) => {
console.log("save token");
return new Promise((resolve, reject) => {
AuthModel.findOne({ userId: tokenDetails.userId }, (err, retrievedTokenDetails) => {
if (err) {
logger.error(err.message, 'userProfileController: saveToken()', 10)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
}
else if (util.isEmpty(retrievedTokenDetails)) {
let newAuthToken = new AuthModel({
userId: tokenDetails.userId,
authToken: tokenDetails.token,
tokenSecret: tokenDetails.tokenSecret,
tokenGenerationTime: time.now()
})
newAuthToken.save((err, newTokenDetails) => {
if (err) {
console.log(err)
logger.error(err.message, 'userProfileController: saveToken()', 10)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else {
let responseBody = {
authToken: newTokenDetails.authToken,
userDetails: tokenDetails.userDetails
}
resolve(responseBody)
}
})
}
else {
retrievedTokenDetails.authToken = tokenDetails.token
retrievedTokenDetails.tokenSecret = tokenDetails.tokenSecret
retrievedTokenDetails.tokenGenerationTime = time.now()
retrievedTokenDetails.save((err, newTokenDetails) => {
if (err) {
console.log(err)
logger.error(err.message, 'userProfileController: saveToken()', 10)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else {
let responseBody = {
authToken: newTokenDetails.authToken,
userDetails: tokenDetails.userDetails
};
resolve(responseBody)
}
})
}
})
})
} // END saveToken()
validateLogin()
.then(generateToken)
.then(saveToken)
.then((resolve) => {
let apiResponse = Response.generate(false, 'Login Successful', 200, resolve);
res.status(200)
res.send(apiResponse)
})
.catch((err) => {
console.log("Errorhandler:");
console.log(err);
res.status(err.status);
})
} // end login()
/**
* function for Password Reset Mail.
*/
let forgotPassword = (req, res) => {
// function for generating a AUTHTOKEN
let generateToken = (userDetails) => {
console.log("generate token");
return new Promise((resolve, reject) => {
JWT.generateToken(userDetails, (err, tokenDetails) => {
if (err) {
console.log(err)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null);
reject(apiResponse)
} else {
tokenDetails.userId = userDetails.userId;
tokenDetails.userDetails = userDetails;
resolve(tokenDetails)
}
})
})
} // END generateToken()
// function for saving the AUTHTOKEN
let saveToken = (tokenDetails) => {
console.log("save token");
return new Promise((resolve, reject) => {
AuthModel.findOne({ userId: tokenDetails.userId }, (err, retrievedTokenDetails) => {
if (err) {
logger.error(err.message, 'userProfileController: saveToken()', 10)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
}
else if (util.isEmpty(retrievedTokenDetails)) {
let newAuthToken = new AuthModel({
userId: tokenDetails.userId,
authToken: tokenDetails.token,
tokenSecret: tokenDetails.tokenSecret,
tokenGenerationTime: time.now()
})
newAuthToken.save((err, newTokenDetails) => {
if (err) {
console.log(err)
logger.error(err.message, 'userProfileController: saveToken()', 10)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else {
let responseBody = {
authToken: newTokenDetails.authToken,
userDetails: tokenDetails.userDetails
}
resolve(responseBody)
}
})
}
else {
retrievedTokenDetails.authToken = tokenDetails.token
retrievedTokenDetails.tokenSecret = tokenDetails.tokenSecret
retrievedTokenDetails.tokenGenerationTime = time.now()
retrievedTokenDetails.save((err, newTokenDetails) => {
if (err) {
console.log(err)
logger.error(err.message, 'userProfileController: saveToken()', 10)
let apiResponse = Response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else {
let responseBody = {
authToken: newTokenDetails.authToken,
userDetails: tokenDetails.userDetails
};
resolve(responseBody)
}
})
}
})
})
} // END saveToken()
// function for sending Email - SendEmail()
let SendEmail = (emailOptions) => {
let MailerResponse = Mailer.SendMail(emailOptions);
MailerResponse.then((resolve) => { // Mail sent successfully
let successResponse = Response.generate(false, 'Password Reset mail sent', 200, resolve);
res.send(successResponse);
console.log("----resolve value----")
console.log(resolve);
}, (reject) => {
console.log('Reason of rejection:- ' + reject);
if (reject.code === 'EAUTH') { // Invalid login from the Admin using NodeMailer
let errorResponse = Response.generate(true, 'Error occurred while sending email', 'EAUTH', reject);
res.send(errorResponse);
}
else if (reject.code === 'EENVELOPE') { // No recipients defined(Invalid Email Address)
let errorResponse = Response.generate(true, 'Invalid Email address', 'EENVELOPE', reject);
res.send(errorResponse);
}
}).catch((err) => console.log("Errorhandler caught: " + err))
} // end SendEmail()
if (!util.isEmailValid(req.body.email)) {
let apiResponse = Response.generate(true, 'Invalid Email address!!', 404, null);
res.send(apiResponse);
return;
}
UserModel.findOne({ email: req.body.email }, (err, userDetails) => {
if (err) {
console.log(err);
let apiResponse = Response.generate(true, 'Some internal error occurred!!', 500, err);
res.send(apiResponse);
} else if (util.isEmpty(userDetails)) {
console.log("No User with this Email Found")
let apiResponse = Response.generate(true, "No account associated with that Email exists.", 404, null);
res.send(apiResponse);
} else {
console.log(userDetails);
generateToken(userDetails).then(saveToken)
.then((responseBody) => {
let emailOptions = {
emailAddress: req.body.email,
subject: "Reset Your Password",
text: "ToDo List Web Application",
html: `<div style="background-color:#17a2b8; color:white; padding:5px; border:solid 2px green; width:50%; text-align:center; margin-left:auto; margin-right:auto;">
<h1 style="text-align:center;">Reset your password</h1>
<p> It looks like you’ve forgotten your password. Don’t worry, you can reset your
password by clicking the button below.</p>
<span style="background-color: indianred; border: none; padding: 10px 25px;
text-align: center; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 5px; ">
<a style="text-decoration:none; color:white;" href="http://nishant-kumar.com/reset-password/${userDetails.userId}/${responseBody.authToken}" target="_blank">Reset Password</a></span>
</div>`
};
SendEmail(emailOptions);
})
.catch((err) => {
console.log("Errorhandler:");
console.log(err);
res.status(err.status);
})
}
})
}
/**
* function for Password Reset.
*/
let resetPassword = (req, res) => {
if (!req.body.password || !req.params.userId || !req.params.authToken) {
let apiResponse = Response.generate(true, 'One or More Parameters are missing!!', 400, null);
res.send(apiResponse);
return;
}
if (!util.isPasswordValid(req.body.password)) {
let apiResponse = Response.generate(true, 'Invalid Password!!', 400, null);
res.send(apiResponse);
return;
}
AuthModel.findOne({ userId: req.params.userId, authToken: req.params.authToken }, (err, result) => {
if (err) {
console.log(err);
let apiResponse = Response.generate(true, 'Some internal error occurred!!', 500, err);
res.send(apiResponse);
}
else if (util.isEmpty(result)) {
console.log("Invalid Authorization Token or Token Expired.")
let apiResponse = Response.generate(true, "Invalid Authorization Token or Token Expired.", 404, null);
res.send(apiResponse);
}
else {
let hashPassword = bcryptLib.hashPassword(req.body.password);
UserModel.findOneAndUpdate({ userId: req.params.userId }, { password: hashPassword }, (err, details) => {
console.log(req.params.userId)
if (err) {
console.log(err);
let apiResponse = Response.generate(true, 'Some internal error occurred!!', 500, err);
res.send(apiResponse);
} else if (util.isEmpty(details)) {
console.log("No User with this userId Found")
let apiResponse = Response.generate(true, "No User Found.", 404, null);
res.send(apiResponse);
} else {
console.log(details);
let apiResponse = Response.generate(false, 'Password Reset Successful!!', 200, details);
res.send(apiResponse);
}
})
}
})
} // END resetPassword()
/**
* function to logout user.
* auth params: userId.
*/
let logout = (req, res) => {
AuthModel.findOneAndRemove({ userId: req.user.userId }, (err, result) => {
if (err) {
console.log(err)
logger.error(err.message, 'userProfileController: logout', 10)
let apiResponse = Response.generate(true, `error occurred: ${err.message}`, 500, null)
res.send(apiResponse)
} else if (util.isEmpty(result)) {
let apiResponse = Response.generate(true, 'Already Logged Out or Invalid UserId', 404, null)
res.send(apiResponse)
} else {
let apiResponse = Response.generate(false, 'Logged Out Successfully', 200, null)
res.send(apiResponse)
}
})
} // end of the logout function.
module.exports = {
signup: signup,
login: login,
logout: logout,
forgotPassword: forgotPassword,
resetPassword: resetPassword
}
|
function Element (value) {
this.value = value
this.next = null
}
function LinkedList (head = null) {
this._length = 0
this.head = head
}
LinkedList.prototype.getLength = function () {
let counter = 0
let current = this.head
while (current !== null) {
current = current.next
counter++
}
this._length = counter
}
LinkedList.prototype.traverse = function () {
let current = this.head
while (current !== null) {
console.log(current.value)
current = current.next
}
}
LinkedList.prototype.append = function (newElement) {
let current = this.head
if (this.head) {
while (current.next) {
current = current.next
}
current.next = newElement
} else {
this.head = newElement
}
}
LinkedList.prototype.getElementOnPosition = function (position) {
let counter = 1
let current = this.head
if (position < 1) {
return null
}
while (current && counter <= position) {
if (counter === position) {
return current.value
}
current = current.next
counter++
}
}
LinkedList.prototype.insertElementAtPosition = function (newElement, position) {
let counter = 1
let current = this.head
if (position < 1) {
return console.log('invalid position provided')
} else if (position > 1) {
while (current && counter < position) {
if (counter === position - 1) {
newElement.next = current.next
current.next = newElement
}
current = current.next
counter++
}
} else {
newElement.next = this.head
this.head = newElement
}
}
LinkedList.prototype.deleteElement = function (value) {
let current = this.head
let previous = null
while (current.value !== value && current.next) {
previous = current
current = current.next
}
if (current.value === value) {
if (previous) {
previous.next = current.next
} else {
this.head = current.next
}
} else {
return console.log('element to be deleted not found')
}
}
const e1 = new Element(1)
const e2 = new Element(2)
const e3 = new Element(3)
const e4 = new Element(4)
const e12 = new Element(12)
let myObj = new LinkedList(e1)
myObj.append(e2)
myObj.append(e3)
myObj.append(e4)
// myObj.getLength()
// console.log(myObj._length)
myObj.insertElementAtPosition(e12, 2)
// myObj.traverse()
// console.log(myObj.getElementOnPosition(5))
myObj.deleteElement(10)
myObj.traverse()
|
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Paging.module.scss'
const getFriendlyNumber = (x) => isNaN(x) ? '?' : x
const Paging = (props) => {
const {
count,
total,
page,
onNextPage,
onPrevPage,
hasNext,
hasPrev,
} = props
const itemTotal = getFriendlyNumber(total)
const pageTotal = getFriendlyNumber(Math.ceil(total / 10))
return (
<div className={styles.root}>
<div className={styles.info}>
{count} of {itemTotal} items
</div>
<div>
page {page} of {pageTotal}
<div className={styles.buttons}>
<button disabled={!hasPrev} onClick={onPrevPage}>
<span className="fas fa-chevron-left" />
</button>
<button disabled={!hasNext} onClick={onNextPage}>
<span className="fas fa-chevron-right" />
</button>
</div>
</div>
</div>
)
}
Paging.propTypes = {
count: PropTypes.number.isRequired,
hasNext: PropTypes.bool,
hasPrev: PropTypes.bool,
onNextPage: PropTypes.func.isRequired,
onPrevPage: PropTypes.func.isRequired,
page: PropTypes.number,
total: PropTypes.number,
}
export default Paging
|
/*
* @lc app=leetcode id=121 lang=javascript
*
* [121] Best Time to Buy and Sell Stock
*/
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
if (!prices.length) {
return 0;
}
let min = prices[0];
let max = prices[0];
let result = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] < min) {
max = min = prices[i];
} else if (prices[i] > max) {
max = prices[i];
const diff = max - min;
if (result < diff) {
result = diff;
}
}
}
return result;
};
|
import { parseJSON } from "jquery";
import { EMAIL } from "../constants/auth";
import { PASSWORD_FORMAT_MESSAGE } from "../constants/messages";
import {
BID_REGEX,
CITY_REGEX,
EMAIL_REGEX,
PASSWORD_REGEX,
PHONE_NUMBER_REGEX,
STREET_REGEX,
ZIP_CODE_REGEX,
} from "../constants/regex";
class ValidationService {
validateFormat(text, regex) {
const re = regex;
return re.test(String(text).toLowerCase());
}
validateEmailFormat(email) {
if (email !== "" && this.validateFormat(email, EMAIL_REGEX) === false) {
return false;
}
return true;
}
validatePasswordFormat(password) {
if (
password !== "" &&
this.validateFormat(password, PASSWORD_REGEX) === false
) {
return false;
}
return true;
}
validatePhoneFormat(phoneNumber) {
if (
phoneNumber !== "" &&
this.validateFormat(phoneNumber, PHONE_NUMBER_REGEX) === false
) {
return false;
}
return true;
}
validateCityFormat = (city) => {
if (city !== "" && this.validateFormat(city, CITY_REGEX) == false) {
return false;
}
return true;
};
validateZipCodeFormat = (zipCode) => {
if (
zipCode !== "" &&
this.validateFormat(zipCode, ZIP_CODE_REGEX) == false
) {
return false;
}
return true;
};
validateStreetFormat = (street) => {
if (street !== "" && this.validateFormat(street, STREET_REGEX) == false) {
return false;
}
return true;
};
validateProductNameFormat = (productName) => {
if (productName !== "" && productName.length > 60) {
return false;
}
return true;
};
validateDescriptionFormat = (description) => {
if (description !== "" && description.length > 700) {
return false;
}
return true;
};
validateStartPriceFormat = (startPrice) => {
if (
startPrice !== "" &&
this.validateFormat(startPrice, BID_REGEX) == false
) {
return false;
}
return true;
};
validateStartDate = (startDate) => {
return startDate !== "";
};
validateRequiredFiled = (text) => {
return text !== "";
};
}
export default ValidationService;
|
/*
* batchUploadByCategorySpecificAttributesController.js
*
* Copyright (c) 2017 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* Controller to support the page that allows users to download or upload excel template.
*
* @author vn70529
* @since 2.12
*/
(function () {
angular.module('productMaintenanceUiApp').controller('BatchUploadByCategorySpecificAttributesController', batchUploadByCategorySpecificAttributesController);
batchUploadByCategorySpecificAttributesController.$inject = ['$scope', 'urlBase', '$uibModal', 'BatchUploadResultsFactory', 'BatchUploadApi'];
/**
* Constructs for batchUploadByCategorySpecificAttributes controller.
*
* @param urlBase The base URL to use to contact the backend.
* @param $uibModal uibmodal service to show modal.
*/
function batchUploadByCategorySpecificAttributesController($scope, urlBase, $uibModal, batchUploadResultsFactory,batchUploadApi) {
var self = this;
/**
* Holds the id of wine template.
*
* @type {number}
*/
self.WINE_TEMPLATE_ID = 5;
/**
* Holds download template url.
*
* @type {string}
*/
self.generateTemplateURL = urlBase + '/pm/categorySpecific/generateTemplate/';
/**
* The list of allowed upload file types. It separates by comma.
*
* @type {string}
*/
self.allowedUploadFileTypes = ".xls, .xlsx";
/**
* Default option for default selected excel type.
*
* @type {{id: string, description: string}}
*/
self.optionDefault = {id: "", description: "-- Select --"};
/**
* Initial the detault selected excel type.
*
* @type {{id: string, description: string}}
*/
self.selectedExcelType = self.optionDefault;
/**
* The list of excel types.
*
* @type {Array}
*/
self.excelTypeOptions = [];
/**
* Holds the file needs to upload.
*/
self.fileUpload;
/**
* Initialize the controller.
*/
self.init = function () {
self.loadExcelTypeOptions();
}
/**
* Load the list of excel type options from server.
*/
self.loadExcelTypeOptions = function () {
self.excelTypeOptions[0] = {id: "1", description: "Apparel"};
self.excelTypeOptions[1] = {id: "2", description: "Kitchenware"};
self.excelTypeOptions[2] = {id: "3", description: "Large and Small Appliances"};
self.excelTypeOptions[3] = {id: "4", description: "Softlines"};
self.excelTypeOptions[4] = {id: "5", description: "Wine"};
}
/**
* Set selected excel type by default value if selected excel type is null.
*
* @param excelType selected excel type.
*/
self.excelTypeChanged = function (excelType) {
if (excelType == null) {
self.selectedExcelType = self.optionDefault
}
}
/**
* Check the enable or disable status for the button on form.
* If selected excel type is null or default value then return true for disable status.
*
* @returns {boolean} if it is true then disabled status or enabled status.
*/
self.isDisabledButton = function () {
return self.selectedExcelType == null || self.selectedExcelType.id == '' || $scope.isWaitingForResponse == true;
}
/**
* This action is used to generate template that selected from excel type option.
*/
self.generateTemplateAction = function () {
return self.generateTemplateURL + self.selectedExcelType.id;
}
/**
* Call service to upload excel file.
*/
self.doUpload = function (event, data) {
/**
* Prepare data form for upload.
*/
if(!$scope.isWaitingForResponse) {
$scope.isWaitingForResponse = true;
var formData = new FormData();
formData.append('name', data.description);
formData.append('file', self.fileUpload);
formData.append('fileType',self.selectedExcelType.id);
/**
* Execute uploading.
*/
return batchUploadApi.uploadCategorySpecific(formData, self.doUploadSuccessCallback, self.doUploadSuccessError);
}
}
/**
* Callback for upload is success.
*
* @param response
*/
self.doUploadSuccessCallback = function (response) {
self.selectedExcelType = self.optionDefault
$scope.isWaitingForResponse = false;
$("#fileUpload").val(null);
self.fileUpload = null;
$("#excelFileName").val(null);
batchUploadResultsFactory.showResultsModal(response.transactionId);
}
/**
* Callback for upload is error.
* @param response
*/
self.doUploadSuccessError = function (response) {
$scope.isWaitingForResponse = false;
if(response.data){
self.error = response.data.message;
}
$("#fileUpload").val(null);
self.fileUpload = null;
$("#excelFileName").val(null);
}
/**
* Listen ok button event on confirmation upload file.
* If the user agree with uploading template, then they will click on ok button to upload.
*/
$scope.$on("okButtonClicked", self.doUpload);
}
})();
|
var namespace = namespace || {};
namespace.InventoryModule = function(options){
var leftColumnContainer = options.leftColumnContainer || null;
var midColumnContainer = options.midColumnContainer || null
var rightColumnContainer = options.rightColumnContainer || null;
var callback = options.callback;
var webServiceAddress = options.webServiceAddress || "http://localhost/GG/web-services/products/"; //THIS IS REQUIRED!
var consoleArr = ["NES", "Super Nintendo", "Nintendo 64", "Gamecube", "Wii", "Wii U", "Nintendo Switch", "GameBoy", "GameBoy Color", "GameBoy Advance",
"Nintendo DS", "Nintendo 3DS", "Playstation", "Playstation 2", "Playstation 3", "Playstation 4", "PSP", "Playstation Vita",
"Xbox", "Xbox 360", "Xbox One", "Sega Genesis", "Sega Saturn", "Sega Dreamcast", "Sega Game Gear", "Atari 2600", "Atari 400", "Atari 5200", "Atari 7800", "Atari Lynx", "Atari ST" ];
//var header;
//var footer;
var productTableListContainer;
//left column search vars
var consoleSelectBox;
var txtSearchProduct;
var btnSearchByProdName;
var txtSearchUpc;
var btnSearchByUpc;
//left column link list
var consoleList;
//mid column table/list
var productTable;
//right column text fields
var txtProductId;
var txtUpc;
var txtConsole;
var txtItem;
var txtLoosePrice;
var txtCibPrice;
var txtGsTradeValue;
var txtGsPrice;
var txtQuantity;
var selProductList;
var txtTradeInCreditValue;
var txtTradeInCashValue;
var selectedProducts = [];
//right column buttons
var btnAddToList;
var btnClearForm;
var btnRemoveSelected;
var btnClearAll;
var btnTradeIn;
var btnSale;
var btnAddOneToTradeInValue;
var btnAddFiveToTradeInValue;
var btnSubtractOneFromTradeInValue;
var btnSubtractFiveFromTradeInValue;
//running total variables
var totalTradeInCreditValue = 0;
var totalTradeInCashValue = 0;
//item value variables
var itemTradeInCreditValue = 0;
var itemTradeInCashValue = 0;
initialize();
function initialize(){
leftColumnContainer.innerHTML = "";
midColumnContainer.innerHTML = "";
rightColumnContainer.innerHTML = "";
var leftColumnContainerTemplate = `
<div id="search-container">
<p>Search for item:</p><br>
<p>Search by name:</p>` +
createConsoleSelectBox(consoleArr) +
`<input type="text" id="txtSearchProduct" placeholder="Enter product name"><br>
<input id="btnSearchByProdName" type="button" value="Search"><br>
<p>Searby by UPC:</p>
<input type="text" id="txtSearchUpc" placeholder="Enter UPC">
<input id="btnSearchByUpc" type="button" value="Search">
</div>
<div id="list-container">
<p>Filter:</p>` +
createConsoleList(consoleArr) +
`</div>`;
var midColumnContainerTemplate = `
<div id="product-table-list">
<p style="text-align:right;">Search for a product to see results</p>
<table id="product-table">
</table>
</div>`;
var rightColumnContainerTemplate = `
<div class="info">
<table class="info-pane">
<form>
<tr>
<td><label for="productId" hidden="true">Product ID:</label></td>
<td><input type="text" name="productId" id="txtProductId" placeholder="Product ID" readonly="true" hidden="true"></td>
</tr>
<tr>
<td><label for="upc">UPC:</label></td>
<td><input type="text" name="upc" id="txtUpc" placeholder="UPC" readonly="true"></td>
</tr>
<tr>
<td><label for="console">Console:</label></td>
<td><input type="text" name="console" id="txtConsole" placeholder="Console" readonly="true"></td>
</tr>
<tr>
<td><label for="item">Item:</label></td>
<td><input type="text" name="item" id="txtItem" placeholder="Item" readonly="true"></td>
</tr>
<tr>
<td><label for="loosePrice">Loose Price:</label></td>
<td><input type="text" name="loosePrice" id="txtLoosePrice" placeholder="Loose Price" readonly="true"></td>
</tr>
<tr>
<td><label for="cibPrice">CIB Price:</label></td>
<td><input type="text" name="citPrice" id="txtCibPrice" placeholder="CIB Price" readonly="true"></td>
</tr>
<tr>
<td><label for="gsTradeValue">Gamestop Trade Value:</label></td>
<td><input type="text" name="gsTradeValue" id="txtGsTradeValue" placeholder="Gamestop Value" readonly="true"></td>
</tr>
<tr>
<td><label for="gsPrice">Gamestop Price:</label></td>
<td><input type="text" name="gsPrice" id="txtGsPrice" placeholder="Gamestop Price" readonly="true"></td>
</tr>
<tr>
<td><label for="quantity">Quantity in stock:</label></td>
<td><input type="text" name="quantity" id="txtQuantity" readonly="true"></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Add" id="btnAddToList">
<input type="button" value="Clear" id="btnClearForm">
</td>
</tr>
<tr>
<td colspan="2">
<select id="selProductList" size=15 name="item-list" style="width:500px; height:200px;">
</select>
</td>
</tr>
<tr>
<td>
<input type="button" value="Remove Selected" id="btnRemoveSelected">
<input type="button" value="Clear All" id="btnClearAll">
</td>
<td>
<input type="button" value="Trade-In" id="btnTradeIn">
<input type="button" value="Sale" id="btnSale">
</td>
</tr>
<tr>
<td><label for="item-trade-in-credit-value">Item Trade-In Credit Value:</label></td>
<td><input type="text" name="item-trade-in-credit-value" id="txtItemTradeInCreditValue" readonly="true"></td>
</tr>
<tr>
<td><label for="item-trade-in-cash-value">Item Trade-In Cash Value:</label></td>
<td><input type="text" name="item-trade-in-cash-value" id="txtItemTradeInCashValue" readonly="true"></td>
</tr>
<tr>
<td><label for="trade-in-credit-value">Total Trade-In Credit Value:</label></td>
<td><input type="text" name="trade-in-credit-value" id="txtTradeInCreditValue" readonly="true"></td>
</tr>
<tr>
<td><label for="trade-in-cash-value">Total Trade-In Cash Value:</label></td>
<td><input type="text" name="trade-in-cash-value" id="txtTradeInCashValue" readonly="true"></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Add 1$" id="btnAddOneToTradeInValue">
<input type="button" value="Subtract 1$" id="btnSubtractOneFromTradeInValue">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Add 5$" id="btnAddFiveToTradeInValue">
<input type="button" value="Subtract 5$" id="btnSubtractFiveFromTradeInValue">
</td>
</tr>
</form>
</table>
</div>`;
//inject HTML
leftColumnContainer.innerHTML = leftColumnContainerTemplate;
midColumnContainer.innerHTML = midColumnContainerTemplate;
rightColumnContainer.innerHTML = rightColumnContainerTemplate;
footer = document.querySelector("#footer");
footer.innerHTML=`Gaming Generations ©2020`;
productTableListContainer = document.getElementById("product-table-list");
//search by product name
consoleSelectBox = leftColumnContainer.querySelector("#consoleSelectBox");
txtSearchProduct = leftColumnContainer.querySelector("#txtSearchProduct");
btnSearchByProdName = leftColumnContainer.querySelector("#btnSearchByProdName").onclick = searchByProductName;
//search by upc
txtSearchUpc = leftColumnContainer.querySelector("#txtSearchUpc");
btnSearchByUpc = leftColumnContainer.querySelector("#btnSearchByUpc").onclick = searchByUpc;
//console link list
consoleList = leftColumnContainer.querySelector("#consoleList").onclick = getProductsByConsoleName;
//mid column product table
productTable = midColumnContainer.querySelector("#product-table");
//right column text fields
txtProductId = rightColumnContainer.querySelector("#txtProductId");
txtUpc = rightColumnContainer.querySelector("#txtUpc");
txtConsole = rightColumnContainer.querySelector("#txtConsole");
txtItem = rightColumnContainer.querySelector("#txtItem");
txtLoosePrice = rightColumnContainer.querySelector("#txtLoosePrice");
txtCibPrice = rightColumnContainer.querySelector("#txtCibPrice");
txtGsTradeValue = rightColumnContainer.querySelector("#txtGsTradeValue");
txtGsPrice = rightColumnContainer.querySelector("#txtGsPrice");
txtQuantity = rightColumnContainer.querySelector("#txtQuantity");
selProductList = rightColumnContainer.querySelector("#selProductList");
txtTradeInCreditValue = rightColumnContainer.querySelector("#txtTradeInCreditValue");
txtTradeInCashValue = rightColumnContainer.querySelector("#txtTradeInCashValue");
txtItemTradeInCreditValue = rightColumnContainer.querySelector("#txtItemTradeInCreditValue");
txtItemTradeInCashValue = rightColumnContainer.querySelector("#txtItemTradeInCashValue");
//right column buttons
btnAddToList = rightColumnContainer.querySelector("#btnAddToList").onclick = addProductForTransaction;
btnClearForm = rightColumnContainer.querySelector("#btnClearForm").onclick = clearProductInfoTextBoxes;
btnRemoveSelected = rightColumnContainer.querySelector("#btnRemoveSelected").onclick = removeSelectedClick;
btnClearAll = rightColumnContainer.querySelector("#btnClearAll").onclick = function(){
selectedProducts.length = 0;
refreshSelectedProducts();
calculateTradeInValue(selectedProducts);
};
btnTradeIn = rightColumnContainer.querySelector("#btnTradeIn").onclick = tradeInQuantityUpdate;
btnSale = rightColumnContainer.querySelector("#btnSale").onclick = saleQuantityUpdate;
btnAddOneToTradeInValue = rightColumnContainer.querySelector("#btnAddOneToTradeInValue");
btnAddFiveToTradeInValue = rightColumnContainer.querySelector("#btnAddFiveToTradeInValue");
btnSubtractOneFromTradeInValue = rightColumnContainer.querySelector("#btnSubtractOneFromTradeInValue");
btnSubtractFiveFromTradeInValue = rightColumnContainer.querySelector("#btnSubtractFiveFromTradeInValue");
//event handlers
productTable.addEventListener("click", selectProductInList);
selProductList.addEventListener("change", populateProductFormFromSelectBox);
txtSearchProduct.addEventListener("keyup", function(event){
if(event.keyCode == 13){
event.preventDefault();
leftColumnContainer.querySelector("#btnSearchByProdName").click();
}
});
txtSearchUpc.addEventListener("keyup", function(event){
if(event.keyCode == 13){
event.preventDefault();
leftColumnContainer.querySelector("#btnSearchByUpc").click();
}
});
btnAddOneToTradeInValue.addEventListener("click", function(event){
addOneToTradeInValue(totalTradeInCreditValue, totalTradeInCashValue);
});
btnAddFiveToTradeInValue.addEventListener("click", function(event){
addFiveToTradeInValue(totalTradeInCreditValue, totalTradeInCashValue);
});
btnSubtractOneFromTradeInValue.addEventListener("click", function(event){
removeOneFromTradeInValue(totalTradeInCreditValue, totalTradeInCashValue);
});
btnSubtractFiveFromTradeInValue.addEventListener("click", function(event){
removeFiveFromTradeInValue(totalTradeInCreditValue, totalTradeInCashValue);
});
}
function generateProductList(products){
productTableListContainer.innerHTML =`<h4>PRODUCTS</h4>`;
var html = `<tr>
<th>Console</th>
<th>Product</th>
</tr>`;
if(Array.isArray(products)){
for(var x = 0; x < products.length; x++){
html += `<tr class="product-table-row" productId="${products[x].productId}">
<td class="product-table-cell">
${products[x].consoleName}
</td>
<td class="product-table-cell">
${products[x].productName}
</td>
</tr>`;
}
}else{
html += `<tr class="product-table-row" productId="${products.productId}">
<td class="product-table-cell">
${products.consoleName}
</td>
<td class="product-table-cell">
${products.productName}
</td>
</tr>`;
}
productTable.innerHTML = html;
productTableListContainer.appendChild(productTable);
return productTable;
}
function selectProductInList(evt){
var target = evt.target
if(target.classList.contains("product-table-cell")){
var selectedProductId = target.closest("tr").getAttribute("productId");
}
namespace.ajax.send({
url: webServiceAddress + selectedProductId,
method: "GET",
callback: function(response){
//console.log(response);
var product = JSON.parse(response);
populateProductForm(product);
}
});
}
function populateProductForm(product){
txtProductId.value = product.productId;
txtUpc.value = product.upc;
txtConsole.value = product.consoleName;
txtItem.value = product.productName;
txtLoosePrice.value = Math.floor(product.loosePrice).toFixed(2);
txtCibPrice.value = Math.floor(product.cibPrice).toFixed(2);
txtGsTradeValue.value = Math.floor(product.gamestopTradePrice).toFixed(2);
txtGsPrice.value = Math.floor(product.gamestopPrice).toFixed(2);
txtQuantity.value = product.quantity;
}
function createProductFromForm(){
var product = {
productId: txtProductId.value,
productName: txtItem.value,
consoleName: txtConsole.value,
loosePrice: txtLoosePrice.value,
cibPrice: txtCibPrice.value,
gamestopTradePrice: txtGsTradeValue.value,
gamestopPrice: txtGsPrice.value,
upc: txtUpc.value,
quantity: txtQuantity.value
};
return product;
}
function getAllProducts(){
namespace.ajax.send({
url: webServiceAddress,
method: "GET",
callback: function(response){
//console.log(response);
var products = JSON.parse(response);
generateProductList(products);
}
});
}
function tradeInQuantityUpdate(){
if(selectedProducts.length > 0){
if(confirm("Are you sure you want to finalize this trade-in?")){
selectedProducts.forEach((p)=>{
p.quantity++;
namespace.ajax.send({
url: webServiceAddress + p.productId,
method: "PUT",
headers: {"Content-Type": "application/json", "Accept": "application/json"},
requestBody: JSON.stringify(p),
callback: function(response){
console.log(response);
}
});
selectedProducts.length = 0;
refreshSelectedProducts();
});
}
}else{
alert("Please add product(s) to the transaction list.")
}
}
function saleQuantityUpdate(){
if(selectedProducts.length > 0){
if(confirm("Are you sure you want to finalize this sale?")){
selectedProducts.forEach((p)=>{
p.quantity = p.quantity - 1;
namespace.ajax.send({
url: webServiceAddress + p.productId,
method: "PUT",
headers: {"Content-Type": "application/json", "Accept": "application/json"},
requestBody: JSON.stringify(p),
callback: function(response){
console.log(response);
}
});
selectedProducts.length = 0;
refreshSelectedProducts();
});
}
}else{
alert("Please add product(s) to the transaction list.")
}
}
function getProductsByConsoleName(evt){
var target = evt.target
if(target.classList.contains("list-anchor")){
var vgConsole = target.closest("a").getAttribute("selectedConsole");
}
namespace.ajax.send({
url: webServiceAddress + vgConsole,
method: "GET",
callback: function(response){
//console.log(response);
var products = JSON.parse(response);
generateProductList(products);
}
});
}
function getProductsByProductName(product, vgConsole){
namespace.ajax.send({
url: webServiceAddress + vgConsole + "/" + product,
method: "GET",
callback: function(response){
var products = JSON.parse(response);
generateProductList(products);
},
errorCallback: function(response){
if(response.status == 404){
alert("Search yielded zero results.");
}
}
});
}
function getProductByUpc(upc){
namespace.ajax.send({
url: webServiceAddress + upc,
method: "GET",
callback: function(response){
console.log(response);
var product = JSON.parse(response);
generateProductList(product);
}
});
}
function searchByProductName(){
if(validateSearchProductName()){
var consoleName = consoleSelectBox.value;
var productName = txtSearchProduct.value;
getProductsByProductName(productName, consoleName);
clearSearchTextBoxes();
}
}
function searchByUpc(){
if(validateSearchUpc()){
var upc = txtSearchUpc.value;
getProductByUpc(upc);
clearSearchTextBoxes();
}
}
function createConsoleSelectBox(arr){
var selectBox = document.createElement("select");
selectBox.setAttribute("id", "consoleSelectBox");
var opt0 = document.createElement("option");
opt0.value = "-1";
opt0.text = "Select console:"
selectBox.add(opt0, null);
arr.forEach((c) =>{
var option = document.createElement("option");
option.value = c.toLowerCase();
option.text = c;
selectBox.add(option);
});
return selectBox.outerHTML;
};
function createConsoleList(arr){
var ul = document.createElement("ul");
arr.forEach((c)=>{
var li = document.createElement("li");
li.innerHTML=`<a class='list-anchor' selectedConsole="${c}">` + c + `</a>`;
ul.appendChild(li);
});
ul.setAttribute("id", "consoleList");
return ul.outerHTML;
}
function clearSearchTextBoxes(){
consoleSelectBox.selectedIndex = 0;
txtSearchProduct.value = "";
txtSearchUpc.value = "";
}
function clearProductInfoTextBoxes(){
txtProductId.value="";
txtUpc.value="";
txtConsole.value="";
txtItem.value="";
txtLoosePrice.value="";
txtCibPrice.value="";
txtGsTradeValue.value="";
txtGsPrice.value="";
txtQuantity.value="";
}
function refreshSelectedProducts(){
selProductList.innerHTML = "";
selectedProducts.forEach((p)=>{
selProductList.innerHTML += `<option value="${p.productId}">${p.productName} - ${p.consoleName}</option>`
});
}
function addProductForTransaction(){
if(txtProductId.value == ""){
alert("Please select a product to add to the pending transaction list.")
}else{
var product = createProductFromForm();
selectedProducts.push(product);
clearProductInfoTextBoxes();
refreshSelectedProducts();
calculateTradeInValue(selectedProducts);
txtItemTradeInCreditValue.value = "";
txtItemTradeInCashValue.value = "";
}
}
function removeSelectedProduct(productId){
for(var i = 0; i < selectedProducts.length; i++){
if(productId == selectedProducts[i].productId){
selectedProducts.splice(i, 1);
}
}
refreshSelectedProducts();
calculateTradeInValue(selectedProducts);
}
function removeSelectedClick(){
if(selProductList.selectedIndex != -1){
var id = selProductList.value;
removeSelectedProduct(id);
txtItemTradeInCreditValue.value = "";
txtItemTradeInCashValue.value = "";
}else{
alert("Please select a product from the pending transaction list.")
}
}
function validateSearchProductName(){
if(consoleSelectBox.value == -1){
alert("Please select a console.");
return false;
}
if(txtSearchProduct.value == ""){
alert("Please enter a product.");
return false;
}
return true;
}
function validateSearchUpc(){
var regExp = /^[0-9]{12}$/;
if(txtSearchUpc.value == ""){
alert("Please enter a UPC.");
return false;
}
if(!regExp.test(txtSearchUpc.value)){
alert("Please enter a valid UPC (12 numerical digits).");
return false;
}
return true;
}
function populateProductFormFromSelectBox(){
for(var i = 0; i < selectedProducts.length; i++){
if(selectedProducts[i].productId == selProductList.value){
populateProductForm(selectedProducts[i]);
calculateTradeInValue(selectedProducts);
}
}
}
function addOneToTradeInValue(baseValueCredit, baseValueCash){
//var holdValue = baseValue;
txtTradeInCreditValue.value = (parseFloat(txtTradeInCreditValue.value) + (1)).toFixed(2);
txtTradeInCashValue.value = (parseFloat(txtTradeInCashValue.value) + (1)).toFixed(2);
}
function addFiveToTradeInValue(baseValueCredit, baseValueCash){
//var holdValue = baseValue;
txtTradeInCreditValue.value = (parseFloat(txtTradeInCreditValue.value) + (5)).toFixed(2);
txtTradeInCashValue.value = (parseFloat(txtTradeInCashValue.value) + (5)).toFixed(2);
}
function removeOneFromTradeInValue(baseValueCredit, baseValueCash){
//var holdValue = baseValue;
txtTradeInCreditValue.value = (parseFloat(txtTradeInCreditValue.value) - (1)).toFixed(2);
txtTradeInCashValue.value = (parseFloat(txtTradeInCashValue.value) - (1)).toFixed(2);
}
function removeFiveFromTradeInValue(baseValueCredit, baseValueCash){
//var holdValue = baseValue;
txtTradeInCreditValue.value = (parseFloat(txtTradeInCreditValue.value) - (5)).toFixed(2);
txtTradeInCashValue.value = (parseFloat(txtTradeInCashValue.value) - (5)).toFixed(2);
}
//TODO: Talk to jake and find out how we want to do this.
function calculateTradeInValue(products){
totalTradeInCreditValue = 0;
totalTradeInCashValue = 0;
itemTradeInCreditValue;
itemTradeInCashValue;
for(var i = 0; i < products.length; i++){
var p = products[i];
var consoleInName = p.productName.toLowerCase().includes("console");
var systemInName = p.productName.toLowerCase().includes("system");
if(!consoleInName && !systemInName){
//GAME PRICING
if(p.consoleName.toLowerCase() == "nes" || p.consoleName.toLowerCase() == "super nintendo" || p.consoleName.toLowerCase() == "nintendo 64"
|| p.consoleName.toLowerCase() == "sega saturn" || p.consoleName.toLowerCase().includes("atari")){
totalTradeInCreditValue += Math.floor(p.loosePrice * 0.4);
totalTradeInCashValue += Math.floor(p.loosePrice * 0.3);
if(Math.floor(p.loosePrice * 4) < 1){
totalTradeInCreditValue += 0.1;
}
if(selProductList.value == p.productId){
itemTradeInCreditValue = Math.floor(p.loosePrice * 0.4);
itemTradeInCashValue = Math.floor(p.loosePrice * 0.3);
if(itemTradeInCreditValue < 1){
itemTradeInCreditValue = 0.1;
}
}
}
if(p.consoleName.toLowerCase() == "gamecube" || p.consoleName.toLowerCase() == "playstation" || p.consoleName.toLowerCase() == "playstation 2"
|| p.consoleName.toLowerCase() == "playstation 3" || p.consoleName.toLowerCase() == "psp" || p.consoleName.toLowerCase() == "playstation vita"
|| p.consoleName.toLowerCase() == "gameboy" || p.consoleName.toLowerCase() == "gameboy advance" || p.consoleName.toLowerCase() == "gameboy color"
|| p.consoleName.toLowerCase() == "sega game gear" || p.consoleName.toLowerCase() == "sega genesis" || p.consoleName.toLowerCase() == "xbox"
|| p.consoleName.toLowerCase() == "xbox 360" || p.consoleName.toLowerCase() == "nintendo ds" || p.consoleName.toLowerCase() == "sega dreamcast"
|| p.consoleName.toLowerCase() == "wii"){
totalTradeInCreditValue += Math.floor(p.loosePrice * 0.25);
totalTradeInCashValue += Math.floor(p.loosePrice * 0.1);
if(Math.floor(p.loosePrice * 0.25) < 1){
totalTradeInCreditValue += 0.1;
}
if(selProductList.value == p.productId){
itemTradeInCreditValue = Math.floor(p.loosePrice * 0.25);
itemTradeInCashValue = Math.floor(p.loosePrice * 0.1);
if(itemTradeInCreditValue < 1){
itemTradeInCreditValue = 0.1;
}
}
}
if(p.consoleName.toLowerCase() == "xbox one" || p.consoleName.toLowerCase() == "playstation 4" || p.consoleName.toLowerCase() == "wii u"
|| p.consoleName.toLowerCase() == "nintendo switch" || p.consoleName.toLowerCase() == "nintendo 3ds"){
totalTradeInCreditValue += Math.floor(p.loosePrice * 0.5);
totalTradeInCashValue += Math.floor(p.loosePrice * 0.3);
if(Math.floor(p.loosePrice * 0.5) < 1){
totalTradeInCreditValue += 0.1;
}
if(selProductList.value == p.productId){
itemTradeInCreditValue = Math.floor(p.loosePrice * 0.5);
itemTradeInCashValue = Math.floor(p.loosePrice * 0.3);
if(itemTradeInCreditValue < 1){
itemTradeInCreditValue = 0.1;
}
}
}
}else if(p.productName.toLowerCase().includes("console") || p.productName.toLowerCase().includes("system")){
//SYSTEM PRICING
if(p.consoleName.toLowerCase() == "nes" || p.consoleName.toLowerCase() == "super nintendo" || p.consoleName.toLowerCase() == "nintendo 64"
|| p.consoleName.toLowerCase() == "sega saturn" || p.consoleName.toLowerCase().includes("atari") || p.consoleName.toLowerCase() == "xbox one"
|| p.consoleName.toLowerCase() == "playstation 4" || p.consoleName.toLowerCase() == "wii u" || p.consoleName.toLowerCase() == "nintendo switch"
|| p.consoleName.toLowerCase() == "nintendo 3ds" ){
totalTradeInCreditValue += Math.floor(p.loosePrice * 0.5);
totalTradeInCashValue += Math.floor(p.loosePrice * 0.4);
if(selProductList.value == p.productId){
itemTradeInCreditValue = Math.floor(p.loosePrice * 0.5);
itemTradeInCashValue = Math.floor(p.loosePrice * 0.4);
}
}
if(p.consoleName.toLowerCase() == "gamecube" || p.consoleName.toLowerCase() == "playstation" || p.consoleName.toLowerCase() == "playstation 2"
|| p.consoleName.toLowerCase() == "playstation 3" || p.consoleName.toLowerCase() == "psp" || p.consoleName.toLowerCase() == "playstation vita"
|| p.consoleName.toLowerCase() == "gameboy" || p.consoleName.toLowerCase() == "gameboy advance" || p.consoleName.toLowerCase() == "gameboy color"
|| p.consoleName.toLowerCase() == "sega game gear" || p.consoleName.toLowerCase() == "sega genesis" || p.consoleName.toLowerCase() == "xbox"
|| p.consoleName.toLowerCase() == "xbox 360" || p.consoleName.toLowerCase() == "nintendo ds" || p.consoleName.toLowerCase() == "sega dreamcast"
|| p.consoleName.toLowerCase() == "wii"){
totalTradeInCreditValue += Math.floor(p.loosePrice * 0.3);
totalTradeInCashValue += Math.floor(p.loosePrice * 0.2);
if(selProductList.value == p.productId){
itemTradeInCreditValue = Math.floor(p.loosePrice * 0.3);
itemTradeInCashValue = Math.floor(p.loosePrice * 0.2);
}
}
}else{
totalTradeInCreditValue += Math.floor(p.loosePrice * 0.4);
totalTradeInCashValue += Math.floor(p.loosePrice * 0.3);
if(selProductList.value == p.productId){
itemTradeInCreditValue = Math.floor(p.loosePrice * 0.4);
itemTradeInCashValue = Math.floor(p.loosePrice * 0.3);
}
}
}
txtTradeInCreditValue.value = totalTradeInCreditValue.toFixed(2);
txtTradeInCashValue.value = totalTradeInCashValue.toFixed(2);
txtItemTradeInCreditValue.value = itemTradeInCreditValue.toFixed(2);
txtItemTradeInCashValue.value = itemTradeInCashValue.toFixed(2);
}
};
|
/**
Template Name: Upbond
Chartist chart
*/
var chart = new Chartist.Line("#chart-with-area", {
labels: ["Mars"],
series: [
[75]
]
}, { low: 0, showArea: !0, plugins: [Chartist.plugins.tooltip()] });
|
//recursive fibonnaci (O(2^N )) time complexity O(N) space complexity
const fib = (n) => {
if (n <= 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
};
// console.log(fib(6)); //8
// console.log(fib(7)); //13
// console.log(fib(8)); //21
//using dynamic programing with memoization O(N) time and space complexity
const fibDP = (n, table = {}) => {
//creates a new object table at the initial call
if (n in table) return table[n];
if (n <= 2) return 1;
table[n] = fibDP(n - 1, table) + fibDP(n - 2, table); //pass in table so you can keep the same object storing the values
return table[n];
};
// console.log(fibDP(6));
// console.log(fibDP(50));
//Using tabulation
const fibTB = (n) => {
const table = Array(n + 1).fill(0);
table[1] = 1;
for (let i = 2; i < n + 1; i++) {
table[i] = table[i - 1] + table[i - 2];
}
return table[n];
};
console.log(fibTB(6));
console.log(fibTB(50));
|
let QRCode = require('qrcode');
const handler = {
async exec({ m, args, MessageMedia, client, messageFrom, dbid }) {
if (args.length < 1) {
m.reply('Mana teksnya!1!1')
} else {
QRCode.toDataURL(args.join` `, (err, url) => {
if (err) {
m.reply(err)
} else {
let media = new MessageMedia('image/png', url.split('base64,')[1], '');
m.reply(media)
}
})
}
},
tag: 'Tools',
commands: ['', 'code'].map(v => 'qr' + v),
help: ['', 'code'].map(v => 'qr' + v + ' <Teks>')
}
module.exports = handler
|
var assert = require('assert');
var ObjectDisp = require('../objectDisp.js');
var disp = new ObjectDisp({
'counter': require('../counter.js'),
':inv': require('../inv.js'),
'directory': require('../directory.js'),
'echo': { init: function() {},
_default: function(ctx, p, u) { return p; } },
'query': { init: function() {},
relayPatch: function(ctx, p, u) { return ctx.query(p.self, p.patch.query); } },
});
var scenario = require('./scenario.js');
describe('Directory', function(){
describe('_create', function(){
it('should construct a new object if the _path if of size 1 and the entry does not exist', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['child1'], content: {_type: 'counter'}},
]));
it('should report a conflict if the child already exist', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['child1'], content: {_type: 'counter'}},
{_type: '_create', _path: ['child1'], content: {_type: 'counter'}},
{conflict: 1},
]));
it('should create sub-directories if they do not exist', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['foo', 'bar'], content: {_type: 'counter'}},
{_type: '_create', _path: ['foo', 'baz'], content: {_type: 'counter'}},
{_type: 'add', _path: ['foo', 'bar'], amount: 3},
{_type: 'add', _path: ['foo', 'baz'], amount: 4},
{_type: 'get', _path: ['foo', 'bar']},
function(v) { assert.equal(v, 3); },
{_type: 'get', _path: ['foo', 'baz']},
function(v) { assert.equal(v, 4); },
]));
});
describe('_default', function(){
it('should propagate patches to the relevant child', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['child1'], content: {_type: 'counter'}},
{_type: '_create', _path: ['child2'], content: {_type: 'counter'}},
{_type: 'add', _path: ['child1'], amount: 3},
{_type: 'get', _path: ['child1']},
function(v) { assert.equal(v, 3); },
{_type: 'get', _path: ['child2']},
function(v) { assert.equal(v, 0); },
]));
it('should conflict when the child does not exist', scenario(disp, [
{_type: 'directory'},
{_type: 'get', _path: ['child1']},
{conflict: 1},
]));
it('should propagate unhandled patches directed at the directory itself to the .@ child, if exists', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['.@'], content: {_type: 'echo'}},
{_type: 'foo', _path: [], bar: 2},
function(v) { assert.equal(v._type, 'relayPatch');
assert.deepEqual(v.patch, {_type: 'foo', _path: [], bar: 2}); },
]));
it('should provide the directori\'s version ID', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['foo', 'bar', '.@'], content: {_type: 'query'}},
{_type: '_create', _path: ['foo', 'bar', 'baz'], content: {_type: 'counter'}},
{_type: 'foo', _path: ['foo', 'bar'], query: {_type: 'get', _path: ['foo', 'bar', 'baz']}},
function(v) { assert.equal(v, 0); },
]));
});
describe('count', function(){
it('should return a count of the number of immediate children of a directory', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['child1'], content: {_type: 'counter'}},
{_type: '_create', _path: ['child2'], content: {_type: 'counter'}},
{_type: 'count', _path: []},
function(c) { assert.equal(c, 2); },
]));
it('should be propagated to a child if the path so indicates', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['child1'], content: {_type: 'counter'}},
{_type: 'count', _path: ['child1']},
{error: 'Patch method count is not defined in class counter'},
]));
});
describe('_get_id', function(){
var x;
it('should return the version ID of the referenced object', scenario(disp, [
{_type: 'directory'},
{_type: '_create', _path: ['a', 'b1', 'c1'], content: {_type: 'counter'}},
{_type: '_create', _path: ['a', 'b1', 'c2'], content: {_type: 'counter'}},
{_type: '_create', _path: ['a', 'b2', 'c1'], content: {_type: 'counter'}},
{_type: '_create', _path: ['a', 'b2', 'c2'], content: {_type: 'counter'}},
{_type: 'add', _path: ['a', 'b1', 'c1'], amount: 1},
{_type: 'add', _path: ['a', 'b1', 'c2'], amount: 2},
{_type: 'add', _path: ['a', 'b2', 'c1'], amount: 2},
{_type: 'add', _path: ['a', 'b2', 'c2'], amount: 1},
{_type: '_get_id', _path: ['a', 'b1', 'c1']},
function(y) { x = y; },
{_type: '_get_id', _path: ['a', 'b2', 'c2']},
function(y) { assert.equal(y.$, x.$); },
{_type: '_get_id', _path: ['a', 'b1', 'c2']},
function(y) { x = y; },
{_type: '_get_id', _path: ['a', 'b2', 'c1']},
function(y) { assert.equal(y.$, x.$); },
]));
});
});
|
/*
1. Register: Save new staff's details, save new staff's role
2. Login: Check whether the staff exists in database, verify password, generate an access token and refresh token, return to user
*/
const jwt = require("jsonwebtoken");
const {TokenExpiredError, JsonWebTokenError} = jwt;
const db = require("../models");
const User = db.user;
const CustomError = require("../utils/custom-error");
const logger = require("../utils/logger")(__filename);
const {asyncHandler} = require("../utils/error-handler");
const {validatePassword} = require("../utils/validate");
const {register, login} = require("../services/auth.service");
const {updateOne, findOne} = require("../services/user.service");
const {secret, jwtExpiration, jwtRefreshExpiration} = require("../config/auth.config");
module.exports = {
register: async (req, res) => {
const author = req.url.includes("admin") ? "Admin" : "User";
logger.audit(`${author}: Registering new user`);
await verifyNewUser(req.body.id);
const {id, name, password} = req.body;
// Validate request before passing to database
// check user ID
if (!id) throw new CustomError(400, "Error: User ID cannot be empty for registration");
// check user name
if (!name) throw new CustomError(400, "Error: User name cannot be empty for registration");
// check password format
if (!validatePassword(password)) throw new CustomError(400, "Error: Password should be in alphanumeric format");
const user = {
id: id,
name: name,
password: password,
};
await register(user, req.body.roles);
res.status(200).send({message: "User was registered successfully"});
},
login: async (req, res) => {
const {id, password} = req.body;
logger.audit(`User ${id} is logging in`)
// check user ID
if (!id) throw new CustomError(400, "Error: User ID cannot be empty for authentication");
// check user password
if (!password) throw new CustomError(400, "Error: User password cannot be empty for authentication");
const {statusCode, body} = await login(id, password);
res.status(statusCode).send({body});
},
logout: async (req, res) => {
const {id} = req.body;
logger.audit(`User ${id} is logging out`);
await updateOne(id, {refreshToken: ""});
logger.audit("User's refresh token is being removed from database successfully");
logger.audit(`User ${id} logged out successfully`);
res.status(200).send({message: `User ${id} logged out successfully`});
},
refreshToken: (req, res) => {
return jwt.verify(req.body.refreshToken, secret, async (err, decoded) => {
if (err instanceof TokenExpiredError) throw new CustomError(401, "Error: Refresh token was expired");
if (err instanceof JsonWebTokenError) throw new CustomError(401, "Error: Invalid refresh token");
const {id, roles, refreshToken} = await findOne(decoded.id);
if (refreshToken !== req.body.refreshToken)
throw new CustomError(401, "Error: Invalid refresh token");
// generate new access token with user's ID and user's roles
const newToken = jwt.sign({id: id, roles: roles}, secret, {
expiresIn: jwtExpiration
});
// generate new refresh token with user's ID
const newRefreshToken = jwt.sign({id: id}, secret, {
expiresIn: jwtRefreshExpiration
});
logger.audit(`New access token and refresh token are generated successfully`);
await updateOne(id, {refreshToken: newRefreshToken});
logger.audit(`New refresh token is updated to database successfully`);
res.status(200).send({accessToken: newToken, refreshToken: newRefreshToken});
});
}
};
async function verifyNewUser(id) {
logger.audit("Verifying new user");
// check duplicate username
const user = await User.findByPk(id);
if (user) throw new CustomError(400, "Error: User ID is already in used");
}
|
module.exports = {
hello(req, res) {
var roomName = 'FunRoom';
sails.sockets.join(req, roomName, function(err) {
if (err) {
return res.serverError(err);
}
sails.sockets.broadcast(roomName, 'foo', { greeting: 'Hola!' });
// return res.json({
// message: 'Subscribed to a fun room called '+roomName+'!'
// });
});
// return res.ok({
// sessionId: req.sessionID
// });
}
};
|
import React, { useState } from 'react';
import styles from './index.module.scss';
import { Input, Button } from '@alifd/next';
function TextEdit(props) {
const { value, onOk, disabled=false } = props;
const [inputValue, setInputValue] = useState(value);
const [editStatus, setEditStatus] = useState(false);
function inputChange(val) {
setInputValue(val)
}
function cancel() {
setInputValue(value)
setEditStatus(false)
}
function ok() {
if(onOk)onOk(
inputValue,
{
success: () => {
setEditStatus(false);
},
error: () => {
setEditStatus(true);
setInputValue(value);
}
}
)
}
return editStatus ? (
<div className={styles.edit}>
<Input value={inputValue} onChange={(val)=> inputChange(val)} />
<p>
<Button type="primary" size="small" onClick={()=> ok()}>确定</Button>
<Button type="normal" size="small" onClick={()=> cancel()}>取消</Button>
</p>
</div>
) : (
<div className={styles.unedit}>
<span style={{marginRight: '10px'}}>{inputValue}</span>
<Button
type="normal"
text={true}
size="small"
onClick={()=>setEditStatus(true)}
disabled={disabled}
>修改</Button>
</div>
)
}
export default TextEdit;
|
const {Players} = require("./players");
class Room{
constructor(roomName){
this.name = roomName;
this.players = new Players();
this.host = false;
this.onGame = false;
this.drawer;
this.currentWord;
this.wordPool = [];
this.hasNotAnswer = [];
this.hasNotDraw = [];
this.time;
}
updateHost(player){
if (player) {
this.host = player;
return player;
}else{
return false;
}
}
searchPlayerById(id){
let player = this.players.getPlayerById(id);
if (player==null) {
return false;
}else{
return player;
}
}
removePlayer(id){
let player = this.players.removePlayer(id);
return player;
}
randomTurn(){
let turn = Math.round(Math.random()*(this.hasNotDraw.length-1));
this.drawer = this.hasNotDraw[turn];
this.hasNotDraw = this.hasNotDraw.filter((player)=> player != this.drawer);
return this.drawer;
}
randomWord(){
let randomWords = [];
for (let i = 0; i < 3; i++) {
let random = Math.round(Math.random()*(this.wordPool.length-1));
random = this.wordPool[random];
// console.log(random);
// console.log(this.wordPool)
this.wordPool = this.wordPool.filter((word)=>word!=random)
randomWords.push(random);
}
return randomWords;
}
startTimer(time) {
this.time = time;
setInterval(()=>{
this.time -= 1000;
if (time<=0) {
clearInterval();
this.time = 0;
}
},1000)
}
scoreCalculate(){
let score;
score = this.time/1000;
return score;
}
getTop3(){
let Top3 = new Players();
let rank = new Players();
rank.players = this.players.players;
// console.log(rank)
let count = 0
for (let i = 0; i < 3; i++) {
let max = 0;
let idTopPlayer;
let topPlayer;
rank.players.forEach((player)=>{
if (player.score>max) {
max = player.score;
idTopPlayer = player.id
}
})
topPlayer = this.searchPlayerById(idTopPlayer);
if (topPlayer) {
Top3.addPlayer(topPlayer.id,topPlayer.name,topPlayer.score);
}
rank.players = rank.players.filter((player)=>player.id!==topPlayer.id);
}
if (Top3.players.length <3) {
for (let i = 0; i < 3; i++) {
if (Top3.players[i]==null) {
Top3.addPlayer(count++,"None")
}
}
}
return Top3;
}
}
class Rooms{
constructor() {
this.rooms = []
}
addRoom(roomName){
let newRoom = new Room(roomName)
this.rooms.push(newRoom);
}
searchRoom(roomName){
let searchingRoom = false;
this.rooms.forEach(room => {
if (room.name == roomName) {
searchingRoom = room;
}
});
return searchingRoom;
}
searchPlayerById(id){
let searchingPlayer;
this.rooms.forEach((room)=>{
let player = room.searchPlayerById(id)
if (player) {
searchingPlayer = player;
}
})
if (searchingPlayer==null) {
return false;
}
else{
return searchingPlayer;
}
}
removePlayer(id){
let removedPlayer;
this.rooms.forEach((room)=>{
let player = room.removePlayer(id)
if (player) {
removedPlayer = player;
}
})
return removedPlayer;
}
memberOfRoom(id){
let searchingRoom;
let room = this.rooms.forEach((room)=>{
let player = room.searchPlayerById(id)
if (player) {
searchingRoom = room;
}
})
if (searchingRoom==null) {
return false;
}
else{
return searchingRoom;
}
}
removeRoom(roomName){
let room = this.searchRoom(roomName);
this.rooms = this.rooms.filter((room)=>room.name!=roomName)
return room;
}
checkEmptyRoom(){
for (let i = 0; i < this.rooms.length; i++) {
const room = array[i];
if (room.members.length==0) {
for (let j = i; j < this.rooms.length-1; j++) {
this.rooms[j] = this.rooms[j+1]
}
}
}
}
}
module.exports = {Rooms}
|
const userRouter = require('express').Router()
const User = require('../models/user')
const bcrypt = require('bcrypt')
userRouter.post('/', async (request, response) => {
const newUser = request.body
// check existence of fields
if (!(newUser.name && newUser.username && newUser.password)) {
response.status(400).json('Invalid user info')
return
}
// check length of fields
if (!(newUser.username.length >= 3 && newUser.password.length >= 3)) {
response.status(400).json('username and/or password are too short')
return
}
// check uniqueness of username
const dup = await User.findOne({username: newUser.username});
if (dup) {
response.status(400).json('duplicated username')
return
}
const saltRounds = 10
newUser.password = await bcrypt.hash(newUser.password, saltRounds) // encrypt the password
const user = new User(newUser)
const res = await user.save() // save to MongoDB database
if (res) {
response.json(res)
} else {
response.status(400)
}
})
userRouter.get('/', async (request, response) => {
const users = await User.find({}).populate('blogs')
if (users) {
response.json(users)
} else {
response.status(400).end()
}
})
module.exports = userRouter
|
import axios from "axios";
import { AllTypes } from "./types";
//API LINKS
const apiLinks = {
featured: "https://api.spotify.com/v1/browse/featured-playlists",
latest: "https://api.spotify.com/v1/browse/new-releases",
genres: "https://api.spotify.com/v1/browse/categories?country=IN&locale=in_IN"
};
//GENRES
export const fetchGenresSuccess = (genres) => {
return {
type: AllTypes.FETCH_GENRES_SUCCESS,
payload: genres,
};
};
export const fetchGenresError = (error) => {
return {
type: AllTypes.FETCH_GENRES_ERROR,
payload: error,
};
};
export const fetchGenres = (token) => async (dispatch) => {
dispatch({
type: AllTypes.FETCH_ASYNC_START,
});
try {
const res = await axios.get(apiLinks["genres"], {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
});
dispatch(fetchGenresSuccess(res.data.categories.items));
} catch (error) {
dispatch(fetchGenresError(error));
}
};
//NEW RELEASES
export const fetchNewReleasesSuccess = (newReleases) => {
return {
type: "FETCH_NEW_RELEASES_SUCCESS",
payload: newReleases,
};
};
export const fetchNewReleasesError = (error) => {
return {
type: "FETCH_NEW_RELEASES_ERROR",
payload: error,
};
};
export const fetchNewRelease = (token) => async (dispatch) => {
dispatch({
type: AllTypes.FETCH_ASYNC_START,
});
try {
const res = await axios.get(apiLinks["latest"], {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
});
dispatch(fetchNewReleasesSuccess(res.data.albums.items));
} catch (error) {
dispatch(fetchNewReleasesError(error));
}
};
//FEATURED
export const fetchFeaturedSuccess = (featured) => {
return {
type: "FETCH_FEATURED_SUCCESS",
payload: featured,
};
};
export const fetchFeaturedError = (error) => {
return {
type: "FETCH_FEATURED_ERROR",
payload: error
};
};
export const fetchFeatured = (token) => async (dispatch) => {
dispatch({
type: AllTypes.FETCH_ASYNC_START,
});
try {
const res = await axios.get(apiLinks["featured"], {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
});
dispatch(fetchFeaturedSuccess(res.data.playlists.items));
} catch (error) {
dispatch(fetchFeaturedError(error));
}
};
|
const container = document.getElementById('js-postCover');
const caption = document.getElementById('js-postCover-caption');
const image = document.getElementById('js-postCover-img');
const loader = document.getElementById('js-postCover-loader');
function imageLoaded() {
container.classList.add('js-is-loaded');
caption.classList.add('js-is-loaded');
const event = new CustomEvent('cover-loaded', { bubbles: true });
setTimeout(() => {
container.dispatchEvent(event);
});
}
if (!image.complete || !image.naturalWidth) {
loader.style.display = 'block';
image.style.visibility = 'hidden';
image.style.opacity = 0;
image.onload = function () {
if (image.complete) {
loader.style.display = 'none';
image.style.visibility = 'visible';
setTimeout(() => {
image.style.opacity = 1;
imageLoaded();
}, 100);
}
};
} else {
// we retrieved it from cache
imageLoaded();
}
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
const intersectingEvent = new CustomEvent('post-cover-intersecting', {
bubbles: true,
detail: { isIntersecting: entry.isIntersecting },
});
container.dispatchEvent(intersectingEvent);
});
});
observer.observe(container);
|
// pages/login/index.js
Page({
handleGetUserInfo(e){
const {userInfo}=e.detail;
wx.setStorageSync("userInfo", userInfo);
wx.navigateBack({
delta: 1
});
if(!wx.getStorageSync('openid')){
wx.navigateTo({
url: '../../pages/auth/index',
success: (result)=>{
}
});
}
}
})
|
QUnit.test( "Object: 1", function( assert ) {
var a = 2, b = 4;
var old = {
'a':a,
'b':b
};
assert.deepEqual(old, {a:2, b:4});
var new_ = {
a,
b
};
assert.deepEqual(new_, {a:2, b:4});
});
QUnit.test( "Object: 2", function( assert ) {
var old = {
'x': function(){},
'w': function(){}
};
assert.equal(typeof old.w, 'function')
var new_ = {
x(){},
w(){}
};
assert.equal(typeof new_.w, 'function')
});
QUnit.todo( "Object: 3", function( assert ) {
var o = {
*foo(){}
};
});
QUnit.test( "Object: 4", function( assert ) {
var o = {
__id: 10,
cont_get_test: 0,
__test2: 'test attribute',
get id(){
return this.__id++;
},
set id(v){
this.__id = v;
},
get test2(){
this.cont_get_test++;
return this.__test2;
}
};
assert.equal(o.test2, 'test attribute');
assert.equal(o.cont_get_test, 1);
assert.equal(o.id, 10);
assert.equal(o.id, 11);
o.id=1;
assert.equal(o.id, 1);
assert.equal(o.id, 2);
});
QUnit.test( "Object: 4", function( assert ) {
var prefix = 'user_';
var o = {
bas: function () {
},
[prefix + 'bar']: function () {
},
[prefix + 'baz']: function () {
}
};
assert.equal(typeof o.user_bar, 'function')
});
|
import ApiConfigList from './base_api.json';
import request from '@/configs/reqreset';
const ApiMap = {};
ApiConfigList.forEach(element => {
const { name, method, path } = element;
if (name && method && path) {
ApiMap[name] = (params) => request({
method,
url: path,
params
});
}
});
export default ApiMap;
|
const ColorPalette = {
primary: '#222d62',
secondary: '#346CAF',
light: '#FDFFFC',
accent: '#A9E5BB',
black: '#000000',
formBackground: '#dfffef',
textInput: '#222d62',
white: '#FFF'
}
export default ColorPalette
|
jest.dontMock("../gamestate")
let GameState = require("../gamestate")
describe("GameState", function() {
it("can be created", function() {
let state = new GameState({name: "bob"})
})
it("can be serialized", function() {
let state = new GameState({name: "bob"})
let data = JSON.stringify(state)
expect(data).toEqual('{"name":"bob","_started":false,"players":[{"name":"bob","hand":[],"board":[],"trash":[],"life":30,"mana":0,"maxMana":0},{"name":"waiting...","hand":[],"board":[],"trash":[],"life":30,"mana":0,"maxMana":0}],"winner":null,"godMode":false,"history":[]}')
})
it("can be deserialized", function() {
let state = new GameState({name: "bob"})
let data = JSON.stringify(state)
let state2 = new GameState(JSON.parse(data))
expect(state2.name).toEqual(state.name)
expect(state2._started).toEqual(state._started)
expect(state2.winner).toEqual(state.winner)
})
it("has accessible players via playerForName", function() {
let state = new GameState({name: "bob"})
expect(state.playerForName("bob").name).toEqual("bob")
})
it("retains card function across reserialization", function() {
let state = new GameState({name: "bob"})
state.startGame(["bob", "eve"], 123)
state.makeMove({op: "refreshCards"})
state.makeMove({op: "refreshCards"})
let data = JSON.stringify(state)
let state2 = new GameState(JSON.parse(data))
expect(state2.name).toEqual(state.name)
expect(state2._started).toEqual(state._started)
expect(state2.winner).toEqual(state.winner)
})
it("can be consistently serialized with displayString", function() {
let state = new GameState({name: "yorp"})
state.startGame(["yorp", "blorp"], 1212)
let data = JSON.stringify(state)
let state2 = new GameState(JSON.parse(data))
expect(state.displayString()).toEqual(state2.displayString())
})
it("kill moves creature from board to trash", function() {
let state = new GameState({name: "bob"})
state.startGame(["bob", "eve"], 123)
// draw the simplest permanent
state.draw({"name":"bob"}, {"cost":0, "permanent": true})
expect(state.current().hand.length).toEqual(1)
// play last card drawn
state.selectCard(0, "hand", "bob")
state.selectCard(0, "hand", "bob")
expect(state.current().board.length).toEqual(1)
// go to next turn
state.makeMove({op: "refreshCards"})
// get a card that implements kill
state.draw({"name":"eve"}, {"kill":true, "cost":0})
// play last card drawn
state.selectCard(0, "hand", "eve")
state.selectCard(0, "hand", "eve")
// permanent leaves board and goes to trash
expect(state.opponent().board.length).toEqual(0)
expect(state.opponent().trash.length).toEqual(1)
})
it("direct damage kills appropriate sized creature", function() {
let state = new GameState({name: "bob"})
state.startGame(["bob", "eve"], 123)
// draw the simplest 2/2
state.draw({"name":"bob"},
{"cost":0, "permanent": true, "attack": 2, "defense": 2})
// play last card drawn
state.selectCard(0, "hand", "bob")
state.selectCard(0, "hand", "bob")
// go to next turn
state.makeMove({op: "refreshCards"})
// get a card that implements direct damage
state.draw({"name":"eve"}, {"damage":2, "cost":0})
// play last card drawn
state.selectCard(0, "hand", "eve")
state.selectCard(0, "opponentBoard", "eve")
// permanent leaves board and goes to trash
// bob
expect(state.current().board.length).toEqual(0)
expect(state.current().trash.length).toEqual(1)
// eve
expect(state.opponent().board.length).toEqual(0)
expect(state.opponent().trash.length).toEqual(1)
})
it("two creatures die when colliding", function() {
let state = new GameState({name: "bob"})
state.startGame(["bob", "eve"], 123)
// draw the simplest 2/2
state.draw({"name":"bob"},
{"cost":0, "permanent": true, "attack": 2, "defense": 2})
// play last card drawn
state.selectCard(0, "hand", "bob")
state.selectCard(0, "hand", "bob")
// draw the simplest 2/2
state.draw({"name":"eve"},
{"cost":0, "permanent": true, "attack": 2, "defense": 2})
// play last card drawn
state.selectCard(0, "hand", "eve")
state.selectCard(0, "hand", "eve")
// go to next turn
state.makeMove({op: "refreshCards"})
state.selectCard(0, "board", "eve")
state.selectCard(0, "opponentBoard", "eve")
// both permanents leave board and go to trash
expect(state.current().board.length).toEqual(0)
expect(state.current().trash.length).toEqual(1)
expect(state.opponent().board.length).toEqual(0)
expect(state.opponent().trash.length).toEqual(1)
})
})
|
'use strict';
angular.module('crm')
.controller('billingReportCtrl', function ($scope, $window, ReportsSetup, ChartInit, $rootScope,
DataStorage, GlobalVars, DataProcessing, $q, ScrollService, ModalService, $filter) {
var defaultFrom = DataProcessing.toDateFormat(moment().subtract(7, 'd'));
var defaultTo = DataProcessing.toDateFormat(moment());
$scope.options = {}
$scope.options.fromDateOptions = {
label: $filter('translate')('common.from'),
id: 304,
inline: true
};
$scope.options.toDateOptions = {
label: $filter('translate')('common.to'),
id: 305,
inline: true
};
$scope.options.groupBySelectOptions = [
{"id":1,"name":$rootScope.translate('services.reports.reportssetup.offer'), "sName":"offer"},
{"id":2,"name":$rootScope.translate('services.reports.reportssetup.affiliate'), "sName":"affiliate"},
{"id":3,"name":$rootScope.translate('services.reports.reportssetup.sub-affiliate'), "sName":"subaffiliate"},
{"id":4,"name":$rootScope.translate('services.reports.reportssetup.product'), "sName":"product"},
//{"id":5,"name":$rootScope.translate('services.reports.reportssetup.day'), "sName":"day"},
]
$scope.value = {
fromDateValue: $scope.options.defaultFrom || defaultFrom,
toDateValue: $scope.options.defaultTo || defaultTo,
signupFlag: false
};
$scope.clientsModel = [];
$scope.clientsData = GlobalVars.commonObject().Clients;
$scope.clientsSettings = {
enableSearch: true,
scrollableHeight: '165px',
scrollable: true,
idProp: 'ClientID',
displayProp: 'CompanyName',
selectName: $filter('translate')('common.clients')
};
$scope.$watchCollection( "clientsModel",
function(clients) {
$scope.sitesData = DataProcessing.newMakeSites(clients, $scope.clientsData) || $scope.sitesData;
$scope.sitesModel = DataProcessing.checkAvailableSites($scope.sitesModel, clients, $scope.clientsData)
}
);
$scope.sitesModel = [];
$scope.$watchCollection( "sitesModel",
function( newValue, oldValue ) {
if ($scope.sitesModel.length && $scope.sitesModel[0].SiteID === 0) {
$scope.sitesModel.shift();
}
$scope.value.sitesModel = $scope.sitesModel;
}
);
$scope.sitesData = [{
"SiteID": 0,
"Name": $filter('translate')('common.no-clients-selected'),
disabled: true
}];
$scope.sitesSettings = {
idProp: 'SiteID',
displayProp: 'Name',
enableSearch: true,
scrollableHeight: '165px',
scrollable: true,
searchPlaceholder: 'Type site name here or select from list.',
selectName: $filter('translate')('common.sites')
};
$scope.portletHeaderOptions2 = {
title: $rootScope.translate('reports.billingreport.billingreport.controller.billing-charts')
};
$scope.portletHeaderOptions3 = {
title: $rootScope.translate('reports.billingreport.billingreport.controller.billing-details')
};
ReportsSetup.commonOptions2($scope);
$scope.dataReady = false;
$scope.keysHeader = {}
var tableFiltersGetDataPromise = function () {
var cd = angular.copy($scope.value)
var dateFrom = cd && cd.fromDateValue
? DataProcessing.stringToDate(cd.fromDateValue)
: defaultFrom;
var dateTo = cd && cd.toDateValue
? DataProcessing.stringToDate(cd.toDateValue)
: defaultTo;
var searchObj = {
SiteIDs: cd && cd.sitesModel ? cd.sitesModel.map(function (item) {
return item.id;
}) : [],
DateFrom: DataProcessing.dateToServer(dateFrom),
DateTo: DataProcessing.dateToServer(dateTo),
ReportBy: $scope.value.groupBySelectValue,
OnlySignupsInRange: cd.signupFlag
};
var actionPromise = DataStorage.reportsAnyApi('billing').post(searchObj).$promise;
return actionPromise;
};
$scope.search = function () {
$scope.searching = true;
$scope.dataReady = false;
var deferred = $q.defer();
GlobalVars.setLoadingRequestStatus(true)
var actionPromise = tableFiltersGetDataPromise();
actionPromise.then(function (data) {
$scope.searching = false;
deferred.resolve();
GlobalVars.setLoadingRequestStatus(false)
if (data.Status) {
$scope.tableObj = [];
$scope.tableObjSafe = [];
$scope.keysHeader = {}
$scope.dataReady = 'No';
} else {
var sData = data.BillingReport;
if (sData.Grid.length) {
var percent = sData.ActiveSignupsPercentage;
$scope.donutchartOptions.chartData = [
// First obj is a black line
{ label: '', data: percent, color: "#383D42" },
{ label: '', data: 100 - percent, color: "rgba(255, 255, 255, 0)" }
];
$scope.donutchartOptions.percents = percent;
if (!sData.SignupTrends || !sData.SignupTrends.length) {
$scope.haveSignupData = false;
} else {
$scope.dottedLinechartOptions1.chartData = sData.SignupTrends.map(function (item) {
return [item.DateEntered * 1000, item.ID];
}).sort(ReportsSetup.compareDates);
$scope.haveSignupData = true;
}
if (!sData.ApprovalTrends || !sData.ApprovalTrends.length) {
$scope.haveApprovalData = false;
} else {
$scope.dottedLinechartOptions2.chartData = sData.ApprovalTrends.map(function (item) {
return [item.DateEntered * 1000, item.ID];
}).sort(ReportsSetup.compareDates);
$scope.haveApprovalData = true;
}
$scope.tableObj = sData.Grid;
$scope.tableObjSafe = sData.Grid;
if (sData.Grid && sData.Grid.length){
_.each(Object.keys(sData.Grid[0]), function(key){
$scope.keysHeader[key] = ReportsSetup.unCamelCase(key).replace('Dollars', '$')
})
}
if (sData.GridTotal){
$scope.gridTotal = sData.GridTotal
}
$scope.dataReady = true;
} else {
$scope.keysHeader = {}
$scope.tableObj = [];
$scope.tableObjSafe = [];
$scope.dataReady = 'No';
}
}
ScrollService.scrollTo('bottom');
}
);
return deferred.promise;
};
$scope.showSummaryDetails = function (query) {
var cd = angular.copy($scope.value)
query.SiteIDs = cd.sitesModel.map(function (item) { return item.id; });
query.GridType = cd.groupBySelectValue;
query.SignupFlag = cd.signupFlag;
query.DateFrom = cd.fromDateValue
? DataProcessing.dateToServer(DataProcessing.stringToDate(cd.fromDateValue), $scope.selectedTimezone)
: DataProcessing.dateToServer(DataProcessing.stringToDate(cd.fromDateValue), $scope.selectedTimezone)
query.DateTo = cd.toDateValue
? DataProcessing.dateToServer(DataProcessing.stringToDate(cd.toDateValue), $scope.selectedTimezone)
: DataProcessing.dateToServer(DataProcessing.stringToDate(cd.toDateValue), $scope.selectedTimezone)
var title = query.Column.split(/(?=[A-Z])/).join(' ').toUpperCase();
ModalService.showModal({
templateUrl: "components/modals/REPORTS/summaryDetails.html",
controller: "summaryDetailsCtrl",
windowClass: 'big-modal',
inputs: {
data: {
modalTitle: title.toLowerCase()=='recurringattempts' ? 'RECURRING ATTEMPTS' : title,
query: query,
method: 'billing'
}
}
}).then(function (modal) {
//it's a bootstrap element, use 'modal' to show it
modal.element.modal();
modal.close.then(function (result) {
if (result === 'false') return false;
return false;
});
});
};
var percent = 70;
$scope.donutchartOptions = {
tooltipLabel: $rootScope.translate('reports.billingreport.billingreport.controller.active-signups'),
percents: percent,
squareDonut: true,
color: 'black',
amountLabelStyles: {
top: '110px',
},
tooltipLabelStyles:{
top: '177px',
},
//chartData: [],
chartData: [
// First obj is a black line
{ label: '', data: percent, color: "#383D42" },
{ label: '', data: 100 - percent, color: "rgba(255, 255, 255, 0)" }
],
chartID: 15
};
$scope.dottedLinechartOptions1 = {
height: 290,
tooltipLabel: 'SIGNUPS',
chartID: 2,
chartData: [],
bottomBlock: false,
leftBlockDisabled: true
};
$scope.dottedLinechartOptions2 = {
height: 290,
tooltipLabel: 'APPROVALS',
chartID: 3,
chartData: [],
blackGrey: true,
bottomBlock: false,
leftBlockDisabled: true
};
});
|
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import DownArrow from '../Resources/DownArrow'
export default class CategoryDropdown extends Component {
constructor(props) {
super(props)
this.dropdown = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);
}
renderDropdownRequest = () => {
// allows them to request new sub genre at the bottom of the dropdown
return (
<React.Fragment>
<a className='dropdown_suggest' href='https://forms.gle/1gnaDbqZLeQmGxoRA' target='blank'>
<p className='dropdown_menu_item dropdown_menu_item-suggest'>Suggest a new genre</p>
</a>
</React.Fragment>
)
}
renderDropdownOptions = () => {
return (
this.props.subGenres.map((subGenre, index) => {
return (
<React.Fragment key={index}>
<p className='dropdown_menu_item' onClick={() => this.props.changeCategoryHandler(index)}>{subGenre}</p>
<div className='dropdown_menu_line'></div>
{index === this.props.subGenres.length - 1 && this.renderDropdownRequest(index)}
</React.Fragment>
)
})
)
}
renderDropdownMenu = () => {
return (
<div className='dropdown_menu'>
{this.renderDropdownOptions()}
</div>
)
}
componentDidMount() {
document.addEventListener('click', this.handleClickOutside, true);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside, true);
}
handleClickOutside = event => {
const domNode = ReactDOM.findDOMNode(this);
if ((!domNode || !domNode.contains(event.target)) && this.props.menuOpen) {
this.props.toggleMenuHandler()
}
}
render() {
return (
<div ref={this.dropdown} className='dropdown'>
<div className='dropdown_input' onClick={() => this.props.toggleMenuHandler()}>
<p className='dropdown_selected'>{this.props.subGenres[this.props.genreIndex]}</p>
<div className={`dropdown_arrow ${this.props.menuOpen ? 'dropdown_arrow_open' : 'dropdown_arrow_closed'}`}>
<DownArrow />
</div>
</div>
{this.props.menuOpen && this.renderDropdownMenu()}
</div>
)
}
}
|
var spawn = require('child_process').spawn;
var exec = require('child_process').exec;
/*
The new process will get the same enviromental variables as the current
process, but the PORT is different.
*/
var options = process.env;
options.PORT = 3005;
var procSysProcess;
function run(cb) {
procSysProcess = spawn('node',['.'],options);
procSysProcess.stdout.on('data', function (data) {
var dataString = data.toString();
// The keyword on output indecates procurement system is running
if (dataString && dataString.indexOf('listening') !== -1){
cb();
}
});
}
function resetDatabase(cb) {
exec('npm run reset-database', cb);
}
function halt() {
procSysProcess.kill();
}
module.exports = {
run: run,
halt: halt,
resetDatabase: resetDatabase,
};
|
"use strict";
const express = require("express");
const mdAuth = require("./../middlewares/authenticated");
const categoryController = require("./../controllers/category-controller");
const api = express.Router();
api.post(
"/saveCategory", [mdAuth.ensureAuth, mdAuth.ensureAuthAdmin],
categoryController.saveCategory
);
api.get(
"/getCategories", [mdAuth.ensureAuth, mdAuth.ensureAuthAdmin],
categoryController.getCategories
);
api.get(
"/createDefaultCategory", [mdAuth.ensureAuth, mdAuth.ensureAuthAdmin],
categoryController.createDefaultCategory
);
api.put(
"/updateCategory/:idC", [mdAuth.ensureAuth, mdAuth.ensureAuthAdmin],
categoryController.updateCategory
);
api.delete(
"/deleteCategory/:idC", [mdAuth.ensureAuth, mdAuth.ensureAuthAdmin],
categoryController.deleteCategory
);
module.exports = api;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.