text
stringlengths 7
3.69M
|
|---|
console.log("#S clothTab.js!!!!!!");
function openModal(id) {
console.log("#S openModal(): ", id);
var url = "/viewClothDetail";
var clothId = id;
showLoader();
$.get(url, function(result) {
$('body').append(result);
$("#myModal").modal();
$.ajax({
type: "GET",
contentType: "application/json",
dataType: 'json',
url: "/api/getClothById?clothId="+clothId,
timeout: 100000,
success: function(data) {
console.log("#S sucess in getClothById: ", data);
populateModal(data);
hideLoader();
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error");
alert(xhr.status);
alert(thrownError);
hideLoader();
}
});
// var greeting = {
// id: 10,
// message: "hello world"
// }
// $.ajax({
// type: "POST",
// contentType: "application/json",
// dataType: 'json',
// data: JSON.stringify(greeting),
// url: "/api/letTest",
// timeout: 100000,
// success: function(data) {
// console.log("#S sucess in getClothById: ", data);
// $("#testId").html(data);
// },
// error: function (xhr, ajaxOptions, thrownError) {
// console.log("error");
// alert(xhr.status);
// alert(thrownError);
// },
// complete: function(data) {
// console.log("final data: ", data);
// //A function to be called when the request finishes
// // (after success and error callbacks are executed).
// hideLoader();
// }
// });
});
}
function populateModal(cloth) {
console.log("#S populateModal: ", cloth);
var clothId = cloth.clothId;
var active = cloth.active;
var clothGroup = cloth.clothGroup;
var clothType = cloth.clothType;
var color = cloth.color;
var madeByYear = cloth.madeByYear;
var model = cloth.model;
var price = cloth.price;
var size = cloth.size;
var brand = cloth.clothBrand;
$('#testId').html(clothId);
$('#clothModel').html(model);
$('#clothType').html(clothType);
$('#clothGroup').html(clothGroup);
$('#clothBrand').html(brand);
$('#clothPrice').html(price);
$('#clothColor').html(color);
$('#clothSize').html(size);
}
|
var socket;
var map;
var layer;
var player;
var enemies;
var cursors;
var platforms;
var collector = false;
var height = 560;
var width = 1008;
var game = new Phaser.Game(
width, height,
Phaser.AUTO,
'phaser',
{ preload: preload, create: create, update: update }
);
$(window).resize(
function() {
window.resizeGame();
}
);
function resizeGame () {
var height = window.innerHeight;
var width = window.innerWidth;
game.width = width;
game.height = height;
game.stage.bounds.width = width;
game.stage.bounds.height = height;
if (game.renderType === 1) {
game.renderer.resize(width, height);
Phaser.Canvas.setSmoothingEnabled(game.context, false);
}
}
function preload() {
game.load.tilemap('world', 'assets/tilemaps/maps/world_map.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tiles', 'assets/tilemaps/tiles/world_tiles.png');
game.load.spritesheet('character', 'assets/dude.png', 32, 48);
game.load.spritesheet('enemy', 'assets/dude.png', 32, 48);
}
function create() {
socket = io.connect();
game.physics.startSystem(Phaser.Physics.ARCADE);
game.stage.backgroundColor = '#787878';
createMap();
createPlayer();
}
function createMap() {
map = game.add.tilemap('world');
map.addTilesetImage('world_tileset', 'tiles');
map.setCollisionBetween(466, 466, true, 'world_layer');
map.setCollisionBetween(335, 335, true, 'world_layer');
map.setTileIndexCallback(179, collectBox, this);
map.setTileIndexCallback(178, depositBox, this);
layer = map.createLayer('world_layer');
layer.resizeWorld();
}
function createPlayer() {
// creating a new player
console.log('createPlayer()');
player = game.add.sprite(32, game.world.height - 150, 'character');
player.anchor.set(0.5);
game.physics.enable(player);
player.body.gravity.y = 900;
player.body.collideWorldBounds = true;
player.animations.add('left', [0,1,2,3], 10, true);
player.animations.add('right', [5,6,7,8], 10, true);
player.scale.setTo(.6,.6);
enemies = [];
player.bringToTop();
cursors = game.input.keyboard.createCursorKeys();
setEventHandlers();
}
var setEventHandlers = function() {
socket.on('connect', onSocketConnected);
socket.on('disconnect', onSocketDisconnect);
socket.on('new player', onNewPlayer);
socket.on('move player', onMovePlayer);
socket.on('remove player', onRemovePlayer);
}
function onSocketConnected() {
console.log('Connected to socket server');
enemies.forEach( function(enemy) {
enemy.player.kill();
});
enemies = [];
socket.emit('new player', {x: player.x, y: player.y});
}
function onSocketDisconnect() {
console.log('Disconnected from socket server');
}
function onNewPlayer( data ) {
console.log('public New player connected : ', data.id);
var dupe = playerById(data.id);
if (dupe) {
console.log('Duplicate player!');
return;
}
enemies.push(new RemotePlayer(data.id, game, player, data.x, data.y));
}
function onMovePlayer( data ) {
var movePlayer = playerById(data.id);
if (!movePlayer) {
console.log('onMovePlayer Player not Found: ', data.id);
return;
}
movePlayer.player.x = data.x;
movePlayer.player.y = data.y;
}
function onRemovePlayer( data ) {
var removePlayer = playerById(data.id);
if (!removePlayer) {
console.log('herhehre not found : ', data.id);
return;
}
removePlayer.player.kill();
enemies.splice(enemies.indexOf(removePlayer), 1);
}
function collectBox(sprite, tile) {
if (!collector && tile.index !== -1) {
tile.alpha = 0.2;
tile.index = 0;
layer.dirty = true;
collector = true;
}
return false;
}
function depositBox(sprite, tile) {
if (collector && tile.index !== -1) {
tile.alpha = 0.2;
tile.index = -1;
layer.dirty = true;
collector = false;
}
return false;
}
function update() {
for (var i = 0; i < enemies.length; i++) {
if (enemies[i].alive) {
enemies[i].update();
game.physics.arcade.collide(player, enemies[i].player);
}
}
var hitPlatform = game.physics.arcade.collide(player, layer);
player.body.velocity.x = 0;
if (cursors.right.isDown) {
player.body.velocity.x = 150;
player.animations.play('right');
} else if (cursors.left.isDown) {
player.body.velocity.x = -150;
player.animations.play('left');
} else if (cursors.down.isDown) {
player.body.velocity.y = 150;
} else {
player.animations.stop();
player.frame = 4;
}
// Jump Mechanics
if (cursors.up.isDown && hitPlatform && player.body.blocked.down) {
player.body.velocity.y = -380;
}
socket.emit('move player', {id: player.id , x: player.x, y: player.y});
}
// Find player by ID
function playerById ( id ) {
for (var i = 0; i < enemies.length; i++) {
if (enemies[i].player.name === id) {
return enemies[i]
}
}
return false
}
|
OC.L10N.register(
"settings",
{
"No user supplied" : "Nijedan korisnik nije dostavljen",
"Authentication error" : "Grešna autentifikacije",
"Wrong admin recovery password. Please check the password and try again." : "Pogrešna admin lozinka za povratak. Molim provjerite lozinku i pokušajte ponovno.",
"Unable to change password" : "Promjena lozinke nije moguća",
"Couldn't send reset email. Please contact your administrator." : "Slanje emaila resetovanja nije moguće. Molim kontaktirajte administratora.",
"Group already exists." : "Grupa već postoji.",
"Unable to add group." : "Nemoguće dodati grupu.",
"Unable to delete group." : "Nemoguće izbrisati grupu.",
"Saved" : "Spremljeno",
"test email settings" : "testiraj postavke e-pošte",
"Email sent" : "E-pošta je poslana",
"You need to set your user email before being able to send test emails." : "Prije nego li ste u mogućnosti slati testnu email trebate postaviti svoj korisnički email.",
"Your %s account was created" : "Vaš %s račun je kreiran",
"Invalid mail address" : "Nevažeća adresa e-pošte",
"Unable to create user." : "Nemoguće kreirati korisnika",
"Unable to delete user." : "Nemoguće izbrisati korisnika",
"Forbidden" : "Zabranjeno",
"Invalid user" : "Nevažeči korisnik",
"Unable to change mail address" : "Nemoguće je izmjeniti adresu e-pošte",
"Your full name has been changed." : "Vaše puno ime je promijenjeno.",
"Unable to change full name" : "Puno ime nije moguće promijeniti",
"Create" : "Kreiraj",
"Delete" : "Izbriši",
"Share" : "Dijeli",
"Language changed" : "Jezik je promijenjen",
"Invalid request" : "Neispravan zahtjev",
"Admins can't remove themself from the admin group" : "Administratori ne mogu sami sebe ukloniti iz admin grupe",
"Couldn't remove app." : "Nije moguće ukloniti aplikaciju.",
"All" : "Sve",
"Enabled" : "Aktivirano",
"Not enabled" : "Nije aktivirano",
"Please wait...." : "Molim pričekajte...",
"Error while disabling app" : "Greška pri onemogućavanju aplikacije",
"Disable" : "Onemogući",
"Enable" : "Omogući",
"Error while enabling app" : "Greška pri omogućavanju aplikacije",
"Updating...." : "Ažuriranje...",
"Error while updating app" : "Greška pri ažuriranju aplikacije",
"Updated" : "Ažurirano",
"Uninstalling ...." : "Deinstaliranje....",
"Error while uninstalling app" : "Greška pri deinstaliranju aplikacije",
"Uninstall" : "Deinstaliraj",
"Valid until {date}" : "Validno do {date}",
"Sending..." : "Slanje...",
"Select a profile picture" : "Odaberi sliku profila",
"Very weak password" : "Veoma slaba lozinka",
"Weak password" : "Slaba lozinka",
"So-so password" : "Tu-i-tamo lozinka",
"Good password" : "Dobra lozinka",
"Strong password" : "Jaka lozinka",
"Groups" : "Grupe",
"Unable to delete {objName}" : "Nije moguće izbrisati {objName}",
"A valid group name must be provided" : "Nužno je navesti valjani naziv grupe",
"deleted {groupName}" : "izbrisana {groupName}",
"undo" : "poništi",
"never" : "nikad",
"deleted {userName}" : "izbrisan {userName}",
"add group" : "dodaj grupu",
"no group" : "nema grupe",
"A valid username must be provided" : "Nužno je navesti valjano korisničko ime",
"A valid password must be provided" : "Nužno je navesti valjanu lozinku",
"A valid email must be provided" : "Nužno je navesti valjanu adresu e-pošte",
"Cheers!" : "Cheers!",
"Language" : "Jezik",
"Documentation:" : "Dokumentacija:",
"This app cannot be installed because the following dependencies are not fulfilled:" : "Ova aplikacija se ne može instalirati zbog slijedećih neispunjenih ovisnosti:",
"Enable only for specific groups" : "Omogućite samo za specifične grupe",
"Uninstall App" : "Deinstaliraj aplikaciju",
"Cron" : "Cron",
"Cron was not executed yet!" : "Cron još nije izvršen!",
"Execute one task with each page loaded" : "Izvrši jedan zadatak sa svakom učitanom stranicom",
"cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php je registrovan na webcron usluzi da poziva cron.php svakih 15 minuta preko http.",
"Use system's cron service to call the cron.php file every 15 minutes." : "Koristite cron uslugu sustava za pozivanje cron.php datoteke svakih 15 minuta.",
"Common Name" : "Opće Ime",
"Valid until" : "Validno do",
"Issued By" : "Izdano od",
"Valid until %s" : "Validno do %s",
"Sharing" : "Dijeljenje",
"Allow apps to use the Share API" : "Dozvoli aplikacijama korištenje Share API",
"Allow users to share via link" : "Dozvoli korisnicima dijeljenje putem veze",
"Allow public uploads" : "Dozvoli javno učitavanje",
"Set default expiration date" : "Postavite zadani datum isteka",
"Expire after " : "Istek nakon",
"days" : "dana",
"Allow users to send mail notification for shared files" : "Dozvoli korisnicima slanje notifikacijske e-pošte za podijeljene datoteke",
"Allow resharing" : "Dopustite ponovno dijeljenje",
"Restrict users to only share with users in their groups" : "Ograniči korisnike na međusobno dijeljenje resursa samo s korisnicima unutar svoje grupe",
"Allow users to send mail notification for shared files to other users" : "Dozvoli korisnicima slanje notifikacijske e-pošte za podijeljene datoteke ka ostalim korisnicima",
"Exclude groups from sharing" : "Isključite grupe iz dijeljenja",
"These groups will still be able to receive shares, but not to initiate them." : "Ove će grupe i dalje moći primati dijeljene resurse, ali ne i inicirati ih",
"None" : "Ništa",
"Save" : "Spremi",
"Everything (fatal issues, errors, warnings, info, debug)" : "Sve (fatalni problemi, greške, upozorenja, info, ispravljanje pogrešaka)",
"Info, warnings, errors and fatal issues" : "Informacije, upozorenja, greške i fatalni problemi",
"Warnings, errors and fatal issues" : "Upozorenja, greške i fatalni problemi",
"Errors and fatal issues" : "Greške i fatalni problemi",
"Fatal issues only" : "Samo fatalni problemi",
"Log" : "Zapisnik",
"Login" : "Prijava",
"Plain" : "Čisti tekst",
"NT LAN Manager" : "NT LAN menedžer",
"This is used for sending out notifications." : "Ovo se koristi za slanje notifikacija.",
"Send mode" : "Način rada za slanje",
"Encryption" : "Šifriranje",
"From address" : "S adrese",
"mail" : "pošta",
"Authentication method" : "Metoda autentifikacije",
"Authentication required" : "Potrebna autentifikacija",
"Server address" : "Adresa servera",
"Port" : "Priključak",
"Credentials" : "Vjerodajnice",
"SMTP Username" : "SMTP Korisničko ime",
"SMTP Password" : "SMPT Lozinka",
"Store credentials" : "Spremi vjerodajnice",
"Test email settings" : "Postavke za testnu e-poštu",
"Send email" : "Pošalji e-poštu",
"The Read-Only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Samo-čitajuća konfiguracija je podešena. Ovo spriječava postavljanje neke konfiguracije putem web-sučelja. Nadalje, datoteka mora biti omogućena ručnu izmjenu pri svakom ažuriranju.",
"PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "PHP je očigledno postavljen da se skine inline doc blokova. To će nekoliko osnovnih aplikacija učiniti nedostupnim.",
"This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Uzrok tome je vjerojatno neki ubrzivač predmemorisanja kao što je Zend OPcache ili eAccelerator.",
"The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "PHP modul 'fileinfo' nedostaje. Strogo vam preporučjem da taj modul omogućite kako biste dobili najbolje rezultate u detekciji mime vrste.",
"System locale can not be set to a one which supports UTF-8." : "Regionalnu šemu sustava nemoguće je postaviti na neku koja podržava UTF-8.",
"This means that there might be problems with certain characters in file names." : "To znači da se mogu javiti problemi s određenim znakovima u nazivu datoteke.",
"We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Strogo se preporučuje instaliranje zahtjevnih paketa na vašem sistemu koji podržavaju jednu od slijedećih regionalnih šemi: %s.",
"Get the apps to sync your files" : "Koristite aplikacije za sinhronizaciju svojih datoteka",
"Desktop client" : "Desktop klijent",
"Android app" : "Android aplikacija",
"iOS app" : "iOS aplikacija",
"Show First Run Wizard again" : "Opet pokažite First Run Wizard",
"Add" : "Dodaj",
"Profile picture" : "Slika profila",
"Upload new" : "Učitaj novu",
"Remove image" : "Ukloni sliku",
"Cancel" : "Odustani",
"Email" : "E-pošta",
"Your email address" : "Vaša adresa e-pošte",
"Password" : "Lozinka",
"Unable to change your password" : "Vašu lozinku nije moguće promijeniti",
"Current password" : "Trenutna lozinka",
"New password" : "Nova lozinka",
"Change password" : "Promijeni lozinku",
"Help translate" : "Pomozi prevesti",
"Name" : "Ime",
"Username" : "Korisničko ime",
"Version" : "Verzija",
"New Password" : "Nova Lozinka",
"Personal" : "Osobno",
"Admin" : "Admin",
"Settings" : "Postavke",
"Show storage location" : "Prikaži mjesto pohrane",
"Show last log in" : "Prikaži zadnju prijavu",
"Show user backend" : "Prikaži korisničku pozadinu (backend)",
"Show email address" : "Prikaži adresu e-pošte",
"E-Mail" : "E-pošta",
"Admin Recovery Password" : "Admin lozinka za oporavak",
"Enter the recovery password in order to recover the users files during password change" : "Unesite lozinku za oporavak da biste oporavili korisničke datoteke tokom promjene lozinke",
"Add Group" : "Dodaj Grupu",
"Group" : "Grupa",
"Everyone" : "Svi",
"Admins" : "Administratori",
"Default Quota" : "Zadana kvota",
"Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Molim unesite kvotu za spremanje (npr: \"512 MB\" ili \"12 GB\")",
"Unlimited" : "Neograničeno",
"Other" : "Ostali",
"Full Name" : "Puno ime",
"Group Admin for" : "Grupa Admin za",
"Quota" : "Kvota",
"Storage Location" : "Mjesto za spremanje",
"User Backend" : "Korisnička Pozadina (Backend)",
"Last Login" : "Zadnja prijava",
"change full name" : "promijeni puno ime",
"set new password" : "postavi novu lozinku",
"change email address" : "promjeni adresu e-pošte",
"Default" : "Zadano"
},
"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);");
|
import React from 'react';
import Card from '../Card/Card.js';
import PropTypes from 'prop-types';
import './CardContainer.css';
const CardContainer = ({ repo, addCompareCard, removeCompareCard }) => {
const cardList = repo.map((district, index) => {
const title = Object.keys(district)[0];
const listOfData = Object.values(district)[0];
return (
<Card
title={ title }
listOfData={ listOfData }
addCompareCard={ addCompareCard }
removeCompareCard={ removeCompareCard }
selected={ district.selected }
key={ `Card${index}` }
/>
);
});
return (
<div className="card-container">
{ cardList }
</div>
);
};
CardContainer.propTypes = {
repo: PropTypes.arrayOf(PropTypes.object).isRequired,
addCompareCard: PropTypes.func.isRequired,
removeCompareCard: PropTypes.func.isRequired
};
export default CardContainer;
|
'use strict';
const Card = require('./card');
class Deck {
constructor() {
const suits = ['D', 'S', 'H', 'C'];
const ranks = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'];
this.deck = [];
for (let i = 0; i < suits.length; i++) {
for (let j = 0; j < ranks.length; j++) {
var card = new Card(ranks[j], suits[i]);
this.deck.push(card);
}
}
}
}
module.exports = Deck;
|
import axios from 'axios'
// import utils from '@/utils/utils';
const TIME_OUT = 50000 // 请求超时时间
// const LOADING_START = 600; // loading开始时间
// const LOADING_END = 30000; // 动画结束时间
let requestInstanceStack = new Map() // 请球拦截栈
let responseInstanceStack = new Map() // 响应拦截栈
let cancelFetch = new Map() // 取消请求的拦截栈
// let start_timer = null;
// let over_timer = null;
let customAxios = axios.create({
/**
* 开发环境:/android-task/ 本地代理到测试环境
* 正式环境:https://micro.api.wps.com/android-task/
*/
baseURL: '/server',
timeout: TIME_OUT, // 默认请求超时时间
// 设置请求头格式:用自定义的覆盖 axios 自带的 'Content-Type': 'application/x-www-form-urlencoded'
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Authorization: '' // 权限鉴别字段默认为空
},
withCredentials: true, // 请求凭证
// 使用自定义的验签头
auth: {
username: '',
password: ''
},
// params: {
// platform: 'PC2019'
// },
responseType: 'json' // 默认的相应数据格式
})
/** 添加请求拦截器,eg: 做一些初始化的参数过滤和验证等等 */
let _requestInstance = customAxios.interceptors.request.use(
config => {
/** 根据实际业务写逻辑 */
return config
},
error => {
return Promise.reject(error)
}
)
/** 响应拦截 eg: 做一些数据过滤以及权限限制的处理 */
let _responseInstance = customAxios.interceptors.response.use(
res => {
/** 根据实际业务写逻辑 */
return res
},
error => {
return Promise.reject(error)
}
)
/** 开始请求接口 */
// function startLoading() {
// start_timer = setTimeout(() => {
// // 弹出loading框
// }, LOADING_START);
// over_timer = setTimeout(() => {
// // 超时后的弹框内容,待定
// }, LOADING_END);
// }
/** 请求接口结束 */
// function endLoading() {
// clearTimeout(start_timer);
// clearTimeout(over_timer);
// start_timer = null;
// over_timer = null;
// }
/** 启用拦截 */
function setInterceptorsStack (interfaceKey) {
requestInstanceStack.set(interfaceKey, _requestInstance)
responseInstanceStack.set(interfaceKey, _responseInstance)
}
/** 删除拦截和改拦截实例 */
function deleteInterceptors (interfaceKey) {
// 清除拦截栈
requestInstanceStack.delete(interfaceKey)
responseInstanceStack.delete(interfaceKey)
cancelFetch.delete(interfaceKey)
// 移除拦截
customAxios.interceptors.request.eject(requestInstanceStack.get(interfaceKey))
customAxios.interceptors.response.eject(responseInstanceStack.get(interfaceKey))
}
// 对 get 请求简易封装
export function getFetch ({
url = '',
params = {},
interfaceKey = '',
cancel = false // 判断是否中断请求的参数
// isLoading = true,
} = {}) {
if (cancel) {
cancelFetch.get(interfaceKey)()
deleteInterceptors(interfaceKey) // 删除拦截器以及其实例
return
}
setInterceptorsStack(interfaceKey) // 请求拦截
/** 这里使用 promise 进行就建议包装是为了更友好的将数据的处理暴露在业务层 */
return new Promise((resolve, reject) => {
// isLoading && startLoading(); // 展示loading
customAxios({
method: 'get',
url: url,
params: params,
cancelToken:
(!cancel &&
axios.CancelToken(function executor (c) {
// executor 函数接收一个 cancel 函数作为参数
cancelFetch.set(interfaceKey, c)
})) ||
''
})
.then(response => {
// endLoading(); // 隐藏loading
deleteInterceptors(interfaceKey) // 删除拦截器以及其实例
if (response.status === 200) {
/** 这里也可以通过制定的成功的毁掉函数来返回数据 */
return resolve(response.data)
} else {
/**
* 这里的数据处理请根据实际业务来操作
* 比如指定跳转到某页面
*/
}
})
.catch(error => {
console.log(`请求当前的接口为 ${url} 错误信息为 ${error}`)
/**
* 这里可以配置一些关于操作失败的提示信息:比如获取数据失败等等
* 或者失败的毁掉函数
*/
reject(error)
})
})
}
// 对 post 请求简易封装
export function postFetch ({
url = '',
params = {},
interfaceKey = '',
cancel = false
// isLoading = true,
} = {}) {
if (cancel) {
deleteInterceptors(interfaceKey) // 删除拦截器以及其实例
return cancelFetch.get(interfaceKey)()
}
setInterceptorsStack(interfaceKey) // 开启请求拦截
/** 这里使用 promise 进行就建议包装是为了更友好的将数据的处理暴露在业务层 */
return new Promise((resolve, reject) => {
// isLoading && startLoading(); // 展示loading
/** 配置请求是否加载动画 */
customAxios({
method: 'post',
url: url,
data: params,
cancelToken:
(!cancel &&
axios.CancelToken(function executor (c) {
// executor 函数接收一个 cancel 函数作为参数
cancelFetch.set(interfaceKey, c)
})) ||
''
})
.then(response => {
// endLoading();
deleteInterceptors(interfaceKey) // 删除拦截器以及其实例
if (response.status === 200) {
return resolve(response.data)
} else {
/**
* 这里的数据处理请根据实际业务来操作
* 比如指定跳转到某页面
*/
}
})
.catch(error => {
/**
* 这里可以配置一些关于操作失败的提示信息:比如获取数据失败等等
* reject 方法的参数会传到外部的catch方法,建议关于提示信息统一封装在这里处理,不要放到业务层
*/
console.log(`请求当前的接口为 ${url} 错误信息为 ${error}`)
reject(error)
})
})
}
|
import React from 'react';
import ToyCard from './ToyCard'
class ToyContainer extends React.Component{
render(){
let toys = this.props.toys.map(toys => <ToyCard toys={toys} likes={toys.likes} donateGoodWillClick={this.props.donateGoodWillClick} likeClickHandler={this.props.likeClickHandler}/>)
return(
<div id="toy-collection">
{toys}
</div>
);}
}
export default ToyContainer;
|
import React, {
Component,
} from 'react'
import PropTypes from 'prop-types';
import {
View,
} from 'react-native'
export default class AndroidFloatSectionHeader extends Component {
static propTypes = {
...View.propTypes,
floatSectionHeaderWidth: PropTypes.number.isRequired,
renderChildren: PropTypes.func.isRequired,
}
constructor (props) {
super(props)
this.state = {
sectionID: '',
hidden: true,
}
}
render () {
return (
<View
{...this.props}
style={{position: 'absolute', top: 0, left: 0, width: this.props.floatSectionHeaderWidth,
opacity: !this.state.hidden ? 1 : 0, }}>
{this.props.renderChildren(this.state.sectionID)}
</View>
)
}
setSectionID = (sectionID) => {
this.setState({
sectionID,
})
}
}
|
"use strict";
function PageNavigation(classDefinitions, isTouch) {
// Prototype variables
if (! classDefinitions) {
classDefinitions = {};
}
classDefinitions.hidden = classDefinitions.hidden || "hidden";
classDefinitions.page = classDefinitions.page || "vubn-page";
classDefinitions.startpage = classDefinitions.startpage || "vubn-startpage";
classDefinitions.pagecontainer = classDefinitions.pagecontainer || "vubn-pagecontainer";
classDefinitions.navigationlink = classDefinitions.navigationlink || "vubn-navigate-link";
classDefinitions.animIn = classDefinitions.animIn || "vubn-page-anim-in";
classDefinitions.animOut = classDefinitions.animOut || "vubn-page-anim-out";
isTouch = (isTouch === undefined) ? false : isTouch;
this.pages = null;
this.classes = classDefinitions;
this.animator = null;
this.pagecontainer = null;
this.currentPage = null;
this.useAnimations = vubn.useAnimations;
this.pageOpenEventer = null;
this.pageLeaveEventer = null;
// Prototype functions
this.navigatelinkOnClick = function (event) {
// Get the target for every link (minus the '#' at the beginning)
let link = event.currentTarget.getAttribute("href");
if (!link || link === "") {
link = event.currentTarget.getAttribute("data-href");
}
link = link.substring(1, link.length);
// Already on the correct page -> do nothing, also no leave or enter events
if (this.currentPage.getAttribute("id") === link) {
return;
}
let foundPage = false;
for (let i = 0; i < this.pages.length; i++) {
if (this.pages[i].getAttribute("id") === link) {
this.hidePreviousPage();
this.showPage(this.pages[i]);
foundPage = true;
break;
}
}
if (! foundPage) {
throw new Error("The page " + link + " could not be found.");
}
};
this.hidePreviousPage = function () {
this.hidePage(this.currentPage);
};
this.hideAllPages = function () {
this.pages.forEach((page, index) => {
page.classList.add(this.classes.hidden);
});
};
this.showStartPage = function () {
for (let i = 0; i < this.pages.length; i++) {
if (this.pages[i].classList.contains(this.classes.startpage)) {
this.showPage(this.pages[i]);
break;
}
}
};
this.hidePage = function (pageDomObject) {
let pageid = pageDomObject.getAttribute("id");
this.pageLeaveEventer.fire(pageid);
this.animator.setObject(pageDomObject).hide();
}
this.showPage = function (pageDomObject) {
let pageid = pageDomObject.getAttribute("id");
this.pageOpenEventer.fire(pageid);
this.currentPage = pageDomObject;
this.animator.setObject(pageDomObject).show();
this.pagecontainer.scrollTop = 0;
};
// Initialisation
this.init = function () {
return new Promise((resolve, reject) => {
// Prepare the animators
this.animator = new Animator(classDefinitions.animIn, classDefinitions.animOut, this.classes.hidden, true, false, this.useAnimations);
// Prepare the eventer
this.pageOpenEventer = new Eventer();
this.pageLeaveEventer = new Eventer();
// Get the pages and turn into array
this.pages = document.getElementsByClassName(this.classes.page);
this.pages = [].slice.call(this.pages);
this.pagecontainer = document.getElementById(this.classes.pagecontainer);
this.hideAllPages();
// Now that the correct page only is displayed, show the container
this.pagecontainer.classList.remove(this.classes.hidden);
this.showStartPage();
// Collect all the navigation links
let pagelinks = document.getElementsByClassName(this.classes.navigationlink);
let me = this;
// Use eventlisteners on every navigation link to make navigation work
let eventType = (isTouch) ? "touchend" : "click";
for (let i = 0; i < pagelinks.length; i++) {
pagelinks[i].addEventListener(eventType, (event) => {
event.stopPropagation();
me.navigatelinkOnClick(event);
});
}
resolve();
});
};
// Optional constructor code
}
|
/**
* Created by Navit
*/
/**
* Please use appLogger for logging in this file try to abstain from console
* levels of logging:
* - TRACE - ‘blue’
* - DEBUG - ‘cyan’
* - INFO - ‘green’
* - WARN - ‘yellow’
* - ERROR - ‘red’
* - FATAL - ‘magenta’
*/
var Service = require("../../services");
var UniversalFunctions = require("../../utils/universalFunctions");
var async = require("async");
var TokenManager = require("../../lib/tokenManager");
var CodeGenerator = require("../../lib/codeGenerator");
var ERROR = UniversalFunctions.CONFIG.APP_CONSTANTS.STATUS_MSG.ERROR;
var _ = require("underscore");
var Config = require("../../config");
var createProgram = function (userData, payloadData, callback) {
var programData, customerData;
async.series([
function (cb) {
var query = {
_id: userData._id
};
var options = { lean: true };
Service.AdminService.getAdmin(query, {}, options, function (err, data) {
if (err) {
cb(err);
} else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
customerData = (data && data[0]) || null;
if (customerData.isBlocked) cb(ERROR.ACCOUNT_BLOCKED);
else cb();
}
}
});
},
function (cb) {
Service.ProgramService.createProgram(payloadData, function (err, data) {
if (err) cb(err)
else {
programData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { programData: programData })
})
}
var getPrograms = function (userData, callback) {
var customerData, programData;
async.series([
function (cb) {
var query = {
_id: userData._id
};
var options = { lean: true };
Service.AdminService.getAdmin(query, {}, options, function (err, data) {
if (err) {
cb(err);
} else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
customerData = (data && data[0]) || null;
if (customerData.isBlocked) cb(ERROR.ACCOUNT_BLOCKED);
else cb();
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({}, {}, {}, function (err, data) {
if (err) cb(err)
else {
programData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { programData: programData })
})
}
var blockUnblockProgram = function (userData, payloadData, callback) {
var userFound
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.programId
}
var dataToUpdate = {
$set: {
isActive: payloadData.isActive
}
}
Service.ProgramService.updateProgram(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var updateProgram = function (userData, payloadData, callback) {
var userFound, programData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var dataToUpdate
if (payloadData.hasOwnProperty("programImage") && (payloadData.programImage != null && payloadData.programImage != undefined)) {
dataToUpdate = {
title: payloadData.title,
description: payloadData.description,
programImage: payloadData.programImage,
updatedAt: new Date().toISOString()
}
}
else {
dataToUpdate = {
title: payloadData.title,
description: payloadData.description,
updatedAt: new Date().toISOString()
}
}
Service.ProgramService.updateProgram({ _id: payloadData.programId }, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
programData = data && data[0] || null;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { programData: programData })
})
}
var createModule = function (userData, payloadData, callback) {
var userFound, moduleData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var moduleCreate = {
programId: payloadData.programId,
title: payloadData.title,
description: payloadData.description
}
if (payloadData.hasOwnProperty("moduleImage") && (payloadData.moduleImage != null || payloadData.moduleImage != undefined)) {
moduleCreate.moduleImage = payloadData.moduleImage
}
Service.ModuleService.createModule(moduleCreate, function (err, data) {
if (err) cb(err)
else {
moduleData = data;
cb()
}
})
},
function (cb) {
if (payloadData.hasOwnProperty("content") && payloadData.content.length != 0) {
if (payloadData.content) {
var taskInParallel = [];
for (var key in payloadData.content) {
(function (key) {
taskInParallel.push((function (key) {
return function (embeddedCB) {
//TODO
var dataToUpdate = {
$addToSet: {
content: {
type: payloadData.content[key].type,
content: payloadData.content[key].content,
position: payloadData.content[key].position
}
}
}
var criteria = {
_id: moduleData._id
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) embeddedCB(err)
else {
if (payloadData.content[key].hasOwnProperty("misc") && payloadData.content[key].misc.length != 0) {
addMiscToModuleContent(moduleData, payloadData.content[key].misc, data.content[key], function (err, data) {
if (err) embeddedCB(err)
else embeddedCB()
})
}
else embeddedCB()
}
})
}
})(key))
}(key));
}
async.series(taskInParallel, function (err, result) {
cb(null);
});
}
}
else cb()
},
function (cb) {
Service.ModuleService.getModule({ _id: moduleData._id }, {}, {}, function (err, data) {
if (err) cb(err)
else {
moduleData = data && data[0] || null;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { moduleData: moduleData })
})
}
var addMiscToModuleContent = function (moduleData, miscData, contentData, callback) {
async.series([
function (cb) {
var taskInParallel = [];
for (var key in miscData) {
(function (key) {
taskInParallel.push((function (key) {
return function (embeddedCB) {
//TODO
var criteria = {
_id: moduleData._id,
"content._id": contentData._id
}
var dataToUpdate = {
$addToSet: {
"content.$.misc": {
key: miscData[key].key,
content: miscData[key].content,
subText: miscData[key].subText,
redirect: miscData[key].redirect
}
}
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) embeddedCB(err)
else embeddedCB()
})
}
})(key))
}(key));
}
async.series(taskInParallel, function (err, result) {
cb(null);
});
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var getModules = function (userData, payloadData, callback) {
var userFound, moduleData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ programId: payloadData.programId }, {
id: 1,
programId: 1,
title: 1,
description: 1,
moduleImage: 1,
createdAt: 1,
isActive: 1,
}, {}, function (err, data) {
if (err) cb(err)
else {
moduleData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { moduleData: moduleData })
})
}
var blockUnblockModule = function (userData, payloadData, callback) {
var userFound;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.moduleId
}
var dataToUpdate = {
$set: {
isActive: payloadData.isActive
}
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var getSpecificModule = function (userData, payloadData, callback) {
var userFound, moduleData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
moduleData = data && data[0] || null;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { moduleData: moduleData })
})
}
var updateModule = function (userData, payloadData, callback) {
var userFound, moduleData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else cb()
}
})
},
function (cb) {
var dataToUpdate
if (payloadData.hasOwnProperty("moduleImage") && (payloadData.moduleImage != null && payloadData.moduleImage != undefined)) {
dataToUpdate = {
title: payloadData.title,
description: payloadData.description,
moduleImage: payloadData.moduleImage,
updatedAt: new Date().toISOString()
}
}
else {
dataToUpdate = {
title: payloadData.title,
description: payloadData.description,
updatedAt: new Date().toISOString()
}
}
Service.ModuleService.updateModule({ _id: payloadData.moduleId }, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
moduleData = data && data[0] || null;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { moduleData: moduleData })
})
}
var updateModuleContent = function (userData, payloadData, callback) {
var userFound, moduleData, moduleDataFinal;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
moduleData = data && data[0] || null;
cb()
}
}
})
},
function (cb) {
Service.ModuleService.updateModule({ _id: payloadData.moduleId }, { $unset: { content: 1 } }, {}, function (err, data) {
if (err) cb(err)
else cb()
})
},
function (cb) {
if (payloadData.content) {
var taskInParallel = [];
for (var key in payloadData.content) {
(function (key) {
taskInParallel.push((function (key) {
return function (embeddedCB) {
//TODO
var dataToUpdate = {
$addToSet: {
content: {
type: payloadData.content[key].type,
content: payloadData.content[key].content,
position: payloadData.content[key].position
}
}
}
var criteria = {
_id: moduleData._id
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) embeddedCB(err)
else {
if (payloadData.content[key].hasOwnProperty("misc") && payloadData.content[key].misc.length != 0) {
addMiscToModuleContent(moduleData, payloadData.content[key].misc, data.content[key], function (err, data) {
if (err) embeddedCB(err)
else embeddedCB()
})
}
else embeddedCB()
}
})
}
})(key))
}(key));
}
async.series(taskInParallel, function (err, result) {
cb(null);
});
}
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
moduleDataFinal = data && data[0] || null;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { moduleData: moduleDataFinal })
})
}
var createTimeTable = function (userData, payloadData, callback) {
var userFound, timeTableData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
var dataToSave = {
moduleId: payloadData.moduleId,
title: payloadData.title
}
if (payloadData.hasOwnProperty("description") && payloadData.description != null && payloadData.description != undefined && payloadData.description != "") {
dataToSave.description = payloadData.description
}
Service.TimeTableService.createTimeTable(dataToSave, function (err, data) {
if (err) cb(err)
else {
timeTableData = data;
cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.moduleId
}
var dataToUpdate = {
$addToSet: {
timetable: timeTableData._id
}
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { timeTableData: timeTableData })
})
}
var getTimeTable = function (userData, payloadData, callback) {
var userFound, timeTableData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.TimeTableService.getTimeTable({ moduleId: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
timeTableData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { timeTableData: timeTableData })
})
}
var blockUnblockTimeTable = function (userData, payloadData, callback) {
var userFound
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.TimeTableService.getTimeTable({ _id: payloadData.timeTableId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.TIMETABLE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.timeTableId
}
var dataToUpdate = {
$set: {
isActive: payloadData.isActive
}
}
Service.TimeTableService.updateTimeTable(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var updateTimeTable = function (userData, payloadData, callback) {
var userFound
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.TimeTableService.getTimeTable({ _id: payloadData.timeTableId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.TIMETABLE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.timeTableId
}
var dataToUpdate
if (payloadData.hasOwnProperty("description") && payloadData.description != null && payloadData.description != undefined && payloadData.description != "") {
dataToUpdate = {
$set: {
title: payloadData.title,
description: payloadData.description
}
}
}
else {
dataToUpdate = {
$set: {
title: payloadData.title
}
}
}
Service.TimeTableService.updateTimeTable(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var createActivities = function (userData, payloadData, callback) {
var userFound, activitiesData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
var dataToSave = {
moduleId: payloadData.moduleId,
title: payloadData.title
}
if (payloadData.hasOwnProperty("description") && payloadData.description != null && payloadData.description != undefined && payloadData.description != "") {
dataToSave.description = payloadData.description
}
Service.ActivitiesService.createActivities(dataToSave, function (err, data) {
if (err) cb(err)
else {
activitiesData = data;
cb()
}
})
},
function (cb) {
if (payloadData.hasOwnProperty("content") && payloadData.content.length != 0) {
if (payloadData.content) {
var taskInParallel = [];
for (var key in payloadData.content) {
(function (key) {
taskInParallel.push((function (key) {
return function (embeddedCB) {
//TODO
var dataToUpdate = {
$addToSet: {
content: {
type: payloadData.content[key].type,
content: payloadData.content[key].content,
position: payloadData.content[key].position
}
}
}
var criteria = {
_id: activitiesData._id
}
Service.ActivitiesService.updateActivities(criteria, dataToUpdate, {}, function (err, data) {
if (err) embeddedCB(err)
else {
if (payloadData.content[key].hasOwnProperty("misc") && payloadData.content[key].misc.length != 0) {
addMiscToActivityContent(activitiesData, payloadData.content[key].misc, data.content[key], function (err, data) {
if (err) embeddedCB(err)
else embeddedCB()
})
}
else embeddedCB()
}
})
}
})(key))
}(key));
}
async.series(taskInParallel, function (err, result) {
cb(null);
});
}
}
else cb()
},
function (cb) {
var criteria = {
_id: payloadData.moduleId
}
var dataToUpdate = {
$addToSet: {
activities: activitiesData._id
}
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
},
function (cb) {
var criteria = {
_id: activitiesData._id
}
Service.ActivitiesService.getActivities(criteria, {}, {}, function (err, data) {
if (err) cb(err)
else {
activitiesData = data && data[0] || null
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { activitiesData: activitiesData })
})
}
var addMiscToActivityContent = function (activitiesData, miscData, contentData, callback) {
async.series([
function (cb) {
var taskInParallel = [];
for (var key in miscData) {
(function (key) {
taskInParallel.push((function (key) {
return function (embeddedCB) {
//TODO
var criteria = {
_id: activitiesData._id,
"content._id": contentData._id
}
var dataToUpdate = {
$addToSet: {
"content.$.misc": {
key: miscData[key].key,
content: miscData[key].content,
subText: miscData[key].subText,
redirect: miscData[key].redirect
}
}
}
Service.ActivitiesService.updateActivities(criteria, dataToUpdate, {}, function (err, data) {
if (err) embeddedCB(err)
else embeddedCB()
})
}
})(key))
}(key));
}
async.series(taskInParallel, function (err, result) {
cb(null);
});
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var getActivities = function (userData, payloadData, callback) {
var userFound, activitiesData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.ActivitiesService.getActivities({ moduleId: payloadData.moduleId }, { title: 1, description: 1, id: 1 }, {}, function (err, data) {
if (err) cb(err)
else {
activitiesData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { activitiesData: activitiesData })
})
}
var getSpecificActivities = function (userData, payloadData, callback) {
var userFound, activitiesData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.ActivitiesService.getActivities({ _id: payloadData.activityId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.ACTIVITY_NOT_FOUND)
else {
activitiesData = data && data[0] || null;
cb()
}
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { activitiesData: activitiesData })
})
}
var blockUnblockActivity = function (userData, payloadData, callback) {
var userFound;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.ActivitiesService.getActivities({ _id: payloadData.activityId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.ACTIVITY_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.activityId
}
var dataToUpdate = {
$set: {
isActive: payloadData.isActive
}
}
Service.ActivitiesService.updateActivities(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var updateActivity = function (userData, payloadData, callback) {
var userFound;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.ActivitiesService.getActivities({ _id: payloadData.activityId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.ACTIVITY_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.activityId
}
var dataToUpdate = {
$set: {
title: payloadData.title
}
}
if (payloadData.hasOwnProperty("description") && payloadData.description != null && payloadData.description != undefined && payloadData.description != "") {
dataToUpdate.description = payloadData.description
}
Service.ActivitiesService.updateActivities(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var updateActivityContent = function (userData, payloadData, callback) {
var userFound, activityData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.ActivitiesService.getActivities({ _id: payloadData.activityId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.ACTIVITY_NOT_FOUND)
else {
activityData = data && data[0] || null;
cb()
}
}
})
},
function (cb) {
Service.ActivitiesService.updateActivities({ _id: activityData._id }, { $unset: { content: 1 } }, {}, function (err, data) {
if (err) cb(err)
else cb()
})
},
function (cb) {
if (payloadData.content) {
var taskInParallel = [];
for (var key in payloadData.content) {
(function (key) {
taskInParallel.push((function (key) {
return function (embeddedCB) {
//TODO
var dataToUpdate = {
$addToSet: {
content: {
type: payloadData.content[key].type,
content: payloadData.content[key].content,
position: payloadData.content[key].position
}
}
}
var criteria = {
_id: activityData._id
}
Service.ActivitiesService.updateActivities(criteria, dataToUpdate, {}, function (err, data) {
if (err) embeddedCB(err)
else {
if (payloadData.content[key].hasOwnProperty("misc") && payloadData.content[key].misc.length != 0) {
addMiscToActivityContent(activityData, payloadData.content[key].misc, data.content[key], function (err, data) {
if (err) embeddedCB(err)
else embeddedCB()
})
}
else embeddedCB()
}
})
}
})(key))
}(key));
}
async.series(taskInParallel, function (err, result) {
cb(null);
});
}
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
moduleDataFinal = data && data[0] || null;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var createGoals = function (userData, payloadData, callback) {
var userFound, goalsData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
var dataToSave = {
moduleId: payloadData.moduleId,
text: payloadData.text
}
if (payloadData.hasOwnProperty("color") && payloadData.color != null && payloadData.color != undefined && payloadData.color != "") {
dataToSave.color = payloadData.color
}
if (payloadData.hasOwnProperty("image") && payloadData.image != null && payloadData.image != undefined && payloadData.image != "") {
dataToSave.image = payloadData.image
}
Service.GoalsService.createGoals(dataToSave, function (err, data) {
if (err) cb(err)
else {
goalsData = data;
cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.moduleId
}
var dataToUpdate = {
$addToSet: {
goals: goalsData._id
}
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { goalsData: goalsData })
})
}
var getGoals = function (userData, payloadData, callback) {
var userFound, goalsData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.GoalsService.getGoals({ moduleId: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
goalsData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { goalsData: goalsData })
})
}
var blockUnblockGoals = function (userData, payloadData, callback) {
var userFound
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.GoalsService.getGoals({ _id: payloadData.goalId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.GOAL_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.goalId
}
var dataToUpdate = {
$set: {
isActive: payloadData.isActive
}
}
Service.GoalsService.updateGoals(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var updateGoals = function (userData, payloadData, callback) {
var userFound, goalsData;
var multiUpdate = false;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.GoalsService.getGoals({ _id: payloadData.goalId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.GOAL_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.goalId
}
var dataToUpdate
if (payloadData.hasOwnProperty("color") && payloadData.color != null && payloadData.color != undefined && payloadData.color != "") {
multiUpdate = true;
dataToUpdate = {
$set: {
text: payloadData.text,
color: payloadData.color
}
}
}
if (payloadData.hasOwnProperty("image") && payloadData.image != null && payloadData.image != undefined && payloadData.image != "") {
multiUpdate = true;
dataToUpdate = {
$set: {
text: payloadData.text,
image: payloadData.image
}
}
}
if (payloadData.hasOwnProperty("color") && payloadData.color != null && payloadData.color != undefined && payloadData.color != "" && payloadData.hasOwnProperty("image") && payloadData.image != null && payloadData.image != undefined && payloadData.image != "") {
multiUpdate = true;
dataToUpdate = {
$set: {
text: payloadData.text,
color: payloadData.color,
image: payloadData.image
}
}
}
if (!multiUpdate) {
dataToUpdate = {
$set: {
text: payloadData.text
}
}
}
Service.GoalsService.updateGoals(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else {
goalsData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { goalsData: goalsData })
})
}
var createQuiz = function (userData, payloadData, callback) {
var userFound, quizData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
var dataToSave = {
moduleId: payloadData.moduleId,
title: payloadData.title
}
if (payloadData.hasOwnProperty("description") && payloadData.description != null && payloadData.description != undefined && payloadData.description != "") {
dataToSave.description = payloadData.description
}
Service.QuizService.createQuiz(dataToSave, function (err, data) {
if (err) cb(err)
else {
quizData = data;
cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.moduleId
}
var dataToUpdate = {
$addToSet: {
quizes: quizData._id
}
}
Service.ModuleService.updateModule(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { quizData: quizData })
})
}
var getQuiz = function (userData, payloadData, callback) {
var userFound, quizData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.QuizService.getQuiz({ moduleId: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
quizData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { quizData: quizData })
})
}
var blockUnblockQuiz = function (userData, payloadData, callback) {
var userFound
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function (cb) {
Service.QuizService.getQuiz({ _id: payloadData.quizId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.QUIZ_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.quizId
}
var dataToUpdate = {
$set: {
isActive: payloadData.isActive
}
}
Service.QuizService.updateQuiz(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
var createQuestion = function (userData, payloadData, callback) {
var userFound, questionData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function(cb){
Service.QuizService.getQuiz({_id: payloadData.quizId},{},{},function(err,data){
if(err) cb(err)
else {
if(data.length == 0) cb(ERROR.QUIZ_NOT_FOUND)
else cb()
}
})
},
function(cb){
Service.QuizService.getQuiz({_id: payloadData.quizId,moduleId: payloadData.moduleId},{},{},function(err,data){
if(err) cb(err)
else {
if(data.length == 0) cb(ERROR.MODULE_QUIZ_MISMATCH)
else cb()
}
})
},
function (cb) {
var dataToSave = {
quizId: payloadData.quizId,
question: payloadData.question,
questionType: payloadData.questionType,
answerId: payloadData.answerId,
}
Service.QuestionService.createQuestion(dataToSave, function (err, data) {
if (err) cb(err)
else {
questionData = data;
cb()
}
})
},
function (cb) {
var taskInParallel = [];
for (var key in payloadData.options) {
(function (key) {
taskInParallel.push((function (key) {
return function (embeddedCB) {
//TODO
var dataToUpdate = {
$addToSet: {
options: payloadData.options[key]
}
}
var criteria = {
_id: questionData._id
}
Service.QuestionService.updateQuestion(criteria, dataToUpdate, {}, function (err, data) {
if (err) embeddedCB(err)
else embeddedCB()
})
}
})(key))
}(key));
}
async.series(taskInParallel, function (err, result) {
cb(null);
});
},
function (cb) {
var criteria = {
_id: payloadData.quizId
}
var dataToUpdate = {
$addToSet: {
question: questionData._id
}
}
Service.QuizService.updateQuiz(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
},
function (cb) {
var criteria = {
_id: questionData._id
}
Service.QuestionService.getQuestion(criteria, {}, {}, function (err, data) {
if (err) cb(err)
else {
questionData = data && data[0] || null;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { questionData: questionData })
})
}
var getQuestion = function (userData, payloadData, callback) {
var userFound, questionData;
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function(cb){
Service.QuizService.getQuiz({_id: payloadData.quizId},{},{},function(err,data){
if(err) cb(err)
else {
if(data.length == 0) cb(ERROR.QUIZ_NOT_FOUND)
else cb()
}
})
},
function(cb){
Service.QuizService.getQuiz({_id: payloadData.quizId,moduleId: payloadData.moduleId},{},{},function(err,data){
if(err) cb(err)
else {
if(data.length == 0) cb(ERROR.MODULE_QUIZ_MISMATCH)
else cb()
}
})
},
function (cb) {
Service.QuestionService.getQuestion({ quizId: payloadData.quizId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
questionData = data;
cb()
}
})
}
], function (err, result) {
if (err) callback(err)
else callback(null, { questionData: questionData })
})
}
var blockUnblockQuestion = function (userData, payloadData, callback) {
var userFound
async.series([
function (cb) {
var criteria = {
_id: userData._id
};
Service.AdminService.getAdmin(criteria, { password: 0 }, {}, function (err, data) {
if (err) cb(err);
else {
if (data.length == 0) cb(ERROR.INCORRECT_ACCESSTOKEN);
else {
userFound = (data && data[0]) || null;
if (userFound.isBlocked == true) cb(ERROR.ACCOUNT_BLOCKED)
else cb()
}
}
});
},
function (cb) {
Service.ProgramService.getProgram({ _id: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.MODULE_NOT_FOUND)
else cb()
}
})
},
function (cb) {
Service.ModuleService.getModule({ _id: payloadData.moduleId, programId: payloadData.programId }, {}, {}, function (err, data) {
if (err) cb(err)
else {
if (data.length == 0) cb(ERROR.PROGRAM_MODULE_MISMATCH)
else {
cb()
}
}
})
},
function(cb){
Service.QuizService.getQuiz({_id: payloadData.quizId},{},{},function(err,data){
if(err) cb(err)
else {
if(data.length == 0) cb(ERROR.QUIZ_NOT_FOUND)
else cb()
}
})
},
function(cb){
Service.QuizService.getQuiz({_id: payloadData.quizId,moduleId: payloadData.moduleId},{},{},function(err,data){
if(err) cb(err)
else {
if(data.length == 0) cb(ERROR.MODULE_QUIZ_MISMATCH)
else cb()
}
})
},
function(cb){
Service.QuestionService.getQuestion({_id: payloadData.questionId},{},{},function(err,data){
if(err) cb(err)
else {
if(data.length == 0) cb(ERROR.QUESTION_NOT_FOUND)
else cb()
}
})
},
function (cb) {
var criteria = {
_id: payloadData.questionId
}
var dataToUpdate = {
$set: {
isActive: payloadData.isActive
}
}
Service.QuestionService.updateQuestion(criteria, dataToUpdate, {}, function (err, data) {
if (err) cb(err)
else cb()
})
}
], function (err, result) {
if (err) callback(err)
else callback(null)
})
}
module.exports = {
createProgram: createProgram,
getPrograms: getPrograms,
blockUnblockProgram: blockUnblockProgram,
updateProgram: updateProgram,
createModule: createModule,
getModules: getModules,
blockUnblockModule: blockUnblockModule,
getSpecificModule: getSpecificModule,
updateModule: updateModule,
updateModuleContent: updateModuleContent,
createTimeTable: createTimeTable,
getTimeTable: getTimeTable,
blockUnblockTimeTable: blockUnblockTimeTable,
updateTimeTable: updateTimeTable,
createActivities: createActivities,
getActivities: getActivities,
getSpecificActivities: getSpecificActivities,
blockUnblockActivity: blockUnblockActivity,
updateActivity: updateActivity,
updateActivityContent: updateActivityContent,
createGoals: createGoals,
getGoals: getGoals,
blockUnblockGoals: blockUnblockGoals,
updateGoals: updateGoals,
createQuiz: createQuiz,
getQuiz: getQuiz,
blockUnblockQuiz: blockUnblockQuiz,
createQuestion: createQuestion,
getQuestion: getQuestion,
blockUnblockQuestion: blockUnblockQuestion
};
|
import React from 'react';
import { describe, add } from '@sparkpost/libby-react';
import { Autorenew, Search } from '@sparkpost/matchbox-icons';
import { TextField, Button, Tooltip, Stack, Select } from '@sparkpost/matchbox';
describe('TextField', () => {
add('basic usage', () => <TextField id="id" label="Name" placeholder="Leslie Knope" />);
add('error', () => <TextField id="id" error="You forgot an ID!" label="Template ID" />);
add('required and error in label', () => (
<TextField id="id" error="You forgot an ID!" label="Template ID" errorInLabel required />
));
add('optional', () => <TextField id="id" label="Template ID" optional />);
add('help text and error', () => (
<TextField
id="id"
error="You forgot an ID!"
label="Template ID"
helpText={
<>
A unique ID for your <a>template</a>.
</>
}
/>
));
add('hidden label', () => <TextField id="id" labelHidden label="Template ID" />);
add('disabled', () => <TextField id="id" label="Template ID" value="template-12" disabled />);
add('text alignment', () => (
<Stack>
<TextField id="id" label="Right" value={500} align="right" suffix="emails" />
<TextField id="id" label="Centered" value="What a weird input" align="center" />
</Stack>
));
add('connected with buttons', () => (
<TextField
id="id"
label="Button"
value="Button Value"
connectLeft={
<Button color="blue" outline>
+ Add
</Button>
}
connectRight={
<Button color="red" outline>
Delete
</Button>
}
/>
));
add('connected with components', () => (
<TextField
id="id"
label="Date Range"
value="July 21, 2017 - July 28, 2017"
connectLeft={
<Tooltip content="Hey">
<Button outline>Injection Time</Button>
</Tooltip>
}
connectRight={<Select options={['Last Week', 'Last 24 Hours']} />}
/>
));
add('prefix and suffix', () => (
<TextField id="id" prefix="$" suffix={<Autorenew />} suffixClassname="test" />
));
add('connected with suffix', () => (
<TextField
id="id"
label="Date Range"
value="July 21, 2017 - July 28, 2017"
connectLeft={<Select options={['Last Week', 'Last 24 Hours']} />}
suffix={<Search />}
/>
));
add('multiline', () => <TextField id="id" label="Message" rows="5" multiline />);
add('works with system props', () => (
<>
<TextField
id="id"
label="Name"
placeholder="Leslie Knope"
my={['200', '400', null, '700']}
maxWidth="800px"
/>
<TextField
id="id"
label="Email"
placeholder="leslie.knope@pawnee.in.gov"
mx={['200', '400', null, '700']}
/>
</>
));
});
|
// example data format
// tournament and bettingGround
const initialState = {
};
export default function tournamentReducer(state = initalState, action) {
switch(action.type) {
default:
return state;
};
};
|
const fs = require('fs');
// global functions that can be imported if needed
module.exports.isEmptyObject = (obj) => {
return !Object.keys(obj).length;
};
// logWrapper function in which to wrap all global.logWrapper messages. Found idea here: https://stackoverflow.com/questions/32025766/listen-for-message-written-to-console-node-js
module.exports.logWrapper = (message) => {
console.log(message);
let cleanerMessage = message + "\n";
fs.appendFile("log.txt", cleanerMessage, function(err) {
// If the code experiences any errors it will log the error to the console.
if (err) {
return console.log(err);
}
});
};
|
import PostDetails from "../PostDetails";
import PostExcerpt from "../PostExcerpt";
import PostPreviewTitle from "../PostPreviewTitle";
export default function PostPreview({ post }) {
return (
<div className="flex flex-col my-4 space-y-3">
<PostPreviewTitle slug={post.slug} title={post.title} />
<PostDetails author={post.author} date={post.date} />
<PostExcerpt excerpt={post.excerpt} />
</div>
);
}
|
import firebase from "firebase/app";
import "firebase/auth";
// import "firebase/database";
import "firebase/firestore";
import firebaseConfig from "./firebase-config.json";
firebase.initializeApp(firebaseConfig);
// firebase.firestore().settings({ timestampsInSnapshots: true });
export const auth = firebase.auth();
// export const database = firebase.database();
export default firebase;
|
APP.controller('sidebarController', function sidebarController($scope, ngProgressFactory, $location, $window) {
$scope.progressbar = ngProgressFactory.createInstance();
var ngProgressChannel = $scope.$bus().channel('ngProgressChannel')
$scope.loading = true;
ngProgressChannel.subscribe('ngProgressChannelStart', function (value) {
$scope.progressbar.start();
});
ngProgressChannel.subscribe('ngProgressChannelComplete', function (value) {
$scope.progressbar.complete();
});
$scope.toggle = false;
$scope.buy = function () {
//$location.path('buy');
$window.location.href = '/buy'
}
var query = null;
var routeInfo = $location.absUrl().split(/[\s/]+/);
var entireRoute = null;
if (routeInfo && routeInfo.length >= 3) {
query = routeInfo[2];
entireRoute = "/" + routeInfo[2];
}
if (routeInfo.length == 4) {
entireRoute = entireRoute + "/" + routeInfo[3];
}
if (query) {
// expand that segment.. may be no change is required
_.each($('.title.parent'), function (element) {
if ($(element).find('a').attr("href") == "/" + query) {
//$(element).slideToggle("slow");
}
else {
$(element).find("div:first").slideToggle("slow");
}
})
//$("a[href$='buy']").slideToggle("fast");
}
else {
//collapse all child menu
$('.list-group-item.child').slideToggle("fast");
}
//$('#buy').click(function (event) {
// var target = $(event.target);
// if (target.is('span')) {
// // do ajax request
// event.stopPropagation();
// event.preventDefault();
// }
//});
$scope.toggleMenu = function (event) {
$scope.toggle = !$scope.toggle;
$(event.target.parentElement).find("div").slideToggle("slow");
//$(event.target.parentElement).find("div").toggle($scope.toggle);
//do all the animations here
//but using $.get, you will get more animation effect
//I guess
$('#content').load($(this).find('a').attr('href'));
}
//$(".title").click(function () {
// $scope.toggle = !$scope.toggle;
// $(this).find("div").slideToggle("slow");
// //do all the animations here
// //but using $.get, you will get more animation effect
// //I guess
// $('#content').load($(this).find('a').attr('href'));
//// return false;
//});
//similarly for inner link
$(".title a a").click(
function () {
$('#content').load($(this).attr('href'));
return true;
});
if (entireRoute) {
//$('#accordion').find("a:contains('" + query + "')").parent().parent().addClass("open").find('.submenu').css({ display: "block" });
_.each($("*[data-link]"), function (e) {
if ($(e).attr('href') == entireRoute) {
var elem = $(e).parent().parent();
if (routeInfo.length == 4) {
elem = elem.parent();
}
elem.addClass("open").find('.submenu').css({ display: "block" });
}
})
}
$scope.loading = false;
ngProgressChannel.publish('ngProgressChannelStart');
ngProgressChannel.publish('ngProgressChannelComplete');
});
$(function () {
var Accordion = function (el, multiple) {
this.el = el || {};
this.multiple = multiple || false;
// Variables privadas
var links = this.el.find('.link');
// Evento
links.on('click', { el: this.el, multiple: this.multiple }, this.dropdown)
}
Accordion.prototype.dropdown = function (e) {
var $el = e.data.el;
$this = $(this),
$next = $this.next();
$next.slideToggle();
$this.parent().toggleClass('open');
if (!e.data.multiple) {
$el.find('.submenu').not($next).slideUp().parent().removeClass('open');
};
}
var accordion = new Accordion($('#accordion'), false);
});
|
import React from "react";
import {
StyleSheet,
View,
Image,
TouchableOpacity,
Dimensions,
TouchableWithoutFeedback,
Animated,
Text,
BackHandler
} from "react-native";
import Store from "../store";
import { Icon } from "react-native-elements";
import Tutorial from "../Tutorial/Tutorial";
const { width, height } = Dimensions.get("window");
export default class OpenBox extends React.Component {
constructor(props) {
super(props);
this.state = {
tutorial: false
};
this._handlePressIn = this._handlePressIn.bind(this);
this._handlePressOut = this._handlePressOut.bind(this);
}
_handlePressIn() {
Animated.spring(this.animatedValue, {
toValue: 0.5
}).start();
}
_handlePressOut() {
Animated.spring(this.animatedValue, {
toValue: 1,
friction: 3,
tension: 40
}).start();
}
_handleBackPress = () => {
BackHandler.exitApp();
return true;
};
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerTitle: (
<View style={{ alignItems: "center", flex: 1 }}>
<Text style={{ fontFamily: "Goyang", fontSize: 17, color: "white" }}>
고양이들을 만나러 갈고양?
</Text>
</View>
),
headerStyle: {
backgroundColor: "#f4da6c",
height: height * 0.07
},
headerTitleStyle: {
fontWeight: "bold",
fontSize: 17
},
headerLeft: (
<TouchableOpacity onPress={() => params.toggleTutorial()}>
<Icon
name="help-circle"
type="material-community"
color="white"
size={22}
iconStyle={{
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10
}}
/>
</TouchableOpacity>
),
headerRightContainerStyle: { marginRight: 5 },
headerRight: (
<Store.Consumer>
{store => {
return (
<TouchableOpacity
onPress={() => params.openProfile(store.socket)}
>
<Icon
name="cat"
type="material-community"
color="white"
size={28}
iconStyle={{
paddingRight: 10,
paddingLeft: 10,
paddingTop: 10,
paddingBottom: 10
}}
/>
</TouchableOpacity>
);
}}
</Store.Consumer>
)
};
};
componentDidMount() {
this.props.navigation.setParams({ openProfile: this._openProfile });
BackHandler.addEventListener("hardwareBackPress", this._handleBackPress);
this.props.navigation.setParams({ toggleTutorial: this._toggleTutorial });
}
componentWillMount() {
this.animatedValue = new Animated.Value(1);
}
componentWillUnmount() {
clearTimeout(this.timeoutHandler);
BackHandler.removeEventListener("hardwareBackPress", this._handleBackPress);
}
render() {
const animatedStyle = {
transform: [{ scale: this.animatedValue }]
};
return (
<View style={styles.container}>
{this.state.tutorial ? (
<Tutorial
tutorial={this.state.tutorial}
toggleTutorial={this._toggleTutorial}
/>
) : null}
<Text style={styles.text}>상자속에 고양이들이 있을 것 같다옹</Text>
<Store.Consumer>
{store => {
return (
<TouchableWithoutFeedback
onPressIn={this._handlePressIn}
// onPressOut={}
onPressOut={() => {
this._handlePressOut();
setTimeout(() => {
this._findRoom(store.socket);
}, 500);
}}
>
<Animated.View style={animatedStyle}>
<Image
style={{ width: 250, height: 250 }}
source={require("../../assets/img/openBox.gif")}
/>
</Animated.View>
</TouchableWithoutFeedback>
);
}}
</Store.Consumer>
</View>
);
}
_findRoom = async socket => {
// const { latitude, longitude } = this.state;
try {
// await socket.emit("findRoom", { latitude, longitude });
await this.props.navigation.navigate("LoadingScreen");
} catch (err) {
console.log(err);
}
};
_openProfile = async socket => {
try {
await socket.emit("info");
await this.props.navigation.navigate("ProfileScreen");
} catch (err) {
console.log(err);
}
};
_toggleTutorial = e => {
if (e) {
this.setState({ tutorial: false });
} else {
this.setState({ tutorial: true });
}
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#FCFCFC",
alignItems: "center",
justifyContent: "center"
},
text: {
fontFamily: "Goyang",
fontSize: 20
}
});
|
const setDocuments = (documents, state) => {
return {
...state,
documents: documents,
};
};
const sendingRequest = (state) => {
return {
...state,
loading: true,
};
};
const requestFinished = (state) => {
return {
...state,
loading: false,
};
};
const addDocument = (document, state) => {
const newDocuments = [...state.documents, document];
return {
...state,
documents: newDocuments,
};
};
const setCurrentInfo = (info, state) => {
return {
...state,
currentInfo: info,
};
};
const addComment = (comment, state) => {
let new_comments = [...state.currentComments,comment];
return {
...state,
currentComments: new_comments,
};
};
const setSimilarDocuments = (similarDocuments, state) => {
return {
...state,
currentSimilarDocuments: similarDocuments,
};
};
const setCurrentComments = (comments, state) => {
return {
...state,
currentComments: comments,
};
}
const setCurrentURL = (url, state) => {
return{
...state,
currentURL: url,
}
}
const reducer = (state, action) => {
switch (action.type) {
case "SET_DOCUMENTS":
return setDocuments(action.payload, state);
case "SENDING_REQUEST":
return sendingRequest(state);
case "REQUEST_FINISHED":
return requestFinished(state);
case "ADD_DOCUMENT":
return addDocument(action.payload, state);
case "SET_CURRENT_INFO":
return setCurrentInfo(action.payload, state);
case "ADD_COMMENT":
return addComment(action.payload, state);
case "SET_SIMILAR_DOCUMENTS":
return setSimilarDocuments(action.payload, state);
case "SET_CURRENT_COMMENTS":
return setCurrentComments(action.payload, state);
case "SET_CURRENT_URL":
return setCurrentURL(action.payload, state);
default:
return state;
}
};
export default reducer;
|
import React, {Component} from 'react'
import cn from 'classnames'
import Carousel from '../../../carousel'
import Mobile from '../../../mobile'
import styles from './styles.styl'
class Body extends Component {
render() {
return (
<div
className={cn(
styles['header-area'],
styles['overlay'],
styles['full-height'],
styles['v-center'],
styles['header-content']
)}
id="home-page"
>
<div className="container">
<div className={cn(styles['v-center'], styles['text-white'], 'row')}>
<div className="col-xs-12 col-md-7 header-text">
<h2>It’s all about Promoting your Business</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero ex inventore vel error quibusdam
animi fugiat, doloribus dolores consectetur nulla deleniti sint blanditiis quod debitis quis vitae
officiis tempora numquam.
</p>
</div>
<div className="hidden-xs hidden-sm col-md-5 text-right">
<Carousel>
<Mobile imageSrc="https://colorlib.com/etc/colid/images/screen-1.jpg" key={1}/>
<Mobile imageSrc="https://colorlib.com/etc/colid/images/screen-2.jpg" key={2}/>
<Mobile imageSrc="https://colorlib.com/etc/colid/images/screen-3.jpg" key={3}/>
<Mobile imageSrc="https://colorlib.com/etc/colid/images/screen-4.jpg" key={4}/>
</Carousel>
</div>
</div>
</div>
</div>
)
}
}
export default Body
|
const questionDescription = JSON.stringify({
document: {
nodes: [
{
object: 'block',
type: 'paragraph',
nodes: [
{
object: 'text',
leaves: [
{
text: 'Default question for testing?',
},
],
},
],
},
],
},
});
const optionADesc = JSON.stringify({
document: {
nodes: [
{
object: 'block',
type: 'paragraph',
nodes: [
{
object: 'text',
leaves: [
{
text: 'Option A',
},
],
},
],
},
],
},
});
const optionBDesc = JSON.stringify({
document: {
nodes: [
{
object: 'block',
type: 'paragraph',
nodes: [
{
object: 'text',
leaves: [
{
text: 'Option B',
},
],
},
],
},
],
},
});
const optionCDesc = JSON.stringify({
document: {
nodes: [
{
object: 'block',
type: 'paragraph',
nodes: [
{
object: 'text',
leaves: [
{
text: 'Option C',
},
],
},
],
},
],
},
});
const optionDDesc = JSON.stringify({
document: {
nodes: [
{
object: 'block',
type: 'paragraph',
nodes: [
{
object: 'text',
leaves: [
{
text: 'Option D',
},
],
},
],
},
],
},
});
export const defaultQuestion = {
id:1,
subject:1,
chapter:1,
desc:questionDescription,
type:1,
optionA:optionADesc,
optionB:optionBDesc,
optionC:optionCDesc,
optionD:optionDDesc,
tags:[{name:'',value:''}]
};
|
/* ADD FUNCTION
function add(x,y){
console.log(x+y);
}
add(4,5)
*/
function work(job){
switch(job){
case 'teacher':
console.log("he is a teacher");
break;
case 'doctor':
console.log("he is a doctor");
break;
default:
console.log("error")
}
}
work("doctor")
|
import { tools } from "./../../../tools/index.js";
import { UserInputError } from "apollo-server";
import models from "../../models/index.js";
import obj from "lodash";
export const resolvers = {
Query: {
getAppointments: async () => {
return await models.Appointments.find();
},
getAppointment: async (_, { id }, { license }) => {
return await models.Appointments.findById(id);
},
},
Mutation: {
addAppointment: async (_, { patient }, { license }) => {
// await tools.auth.authorize(license, ["Admin", "User"]);
const getPatient = await models.Users.findById({
_id: patient,
});
if (!obj.isEmpty(getPatient)) {
const newAppointments = await models.Appointments({
request: Date.now(),
patient: getPatient._id,
status: "pending",
files: [],
});
if (await newAppointments.save()) {
await models.MedicalRecord.findOneAndUpdate(
{ patient: newAppointments.patient },
{ $push: { appointments: [newAppointments._id] } }
);
return newAppointments;
}
// if (!obj.isEmpty(getDoctor)) {
// // let fileList = [];
// // files.map((file) => {
// // fileList.push(file["file"]);
// // });
// }
}
},
appointmentAddFile: async (_, { file, ctx }) => {
const upload = await tools.fileHandler.uploadFile(file, ctx);
if (!obj.isEmpty(upload)) {
const newUpload = new models.Files({
type: upload.type,
filename: upload.filename,
mimeType: upload.mimetype,
path: upload.path,
});
if (await newUpload.save()) {
await models.Appointment.findOneAndUpdate(
{ _id: ctx.id },
{ $push: { files: [newUpload._id] } }
);
return newUpload;
}
}
},
appointmentResolution: async (
_,
{ id, doctor, status, modality, place, date },
{ license }
) => {
// await tools.auth.authorize(license, ["Admin"]);
const getDoctor = await models.Users.findById(doctor);
// console.log(getDoctor);
if (!obj.isEmpty(getDoctor)) {
const resolution = await models.Appointments.findOneAndUpdate(
{ _id: id },
{
doctor: getDoctor._id,
date,
status,
modality,
place,
}
);
if (!obj.isEmpty(resolution)) {
await models.Notifications.findOneAndUpdate(
{ user: resolution.patient },
{
$push: {
notifications: {
date: Date.now(),
title: "Appointment info",
message: "The status of your appointment has changed.",
type: "common",
target: `/Appointment/${resolution._id}`,
},
},
}
);
return resolution;
}
}
throw new UserInputError("Doctor is not found");
},
appointmentRemoveFile: async (_, { id, file }) => {
// tools.fileHandler.deleteDirs(patient);
// TODO: Make remove file method for filehandler
console.log("remove file method");
const appointment = await models.Appointments.findOneAndUpdate(
{ _id: id },
{ $pull: { files: file } }
);
},
},
Appointment: {
patient: async ({ patient }) => {
return await models.Users.findById({
_id: patient,
});
},
doctor: async ({ doctor }) => {
return await models.Users.findById({
_id: doctor ? doctor : "00aa00000aaa0000000a000a",
});
},
files: async ({ files }) => {
return await models.Files.find({
_id: { $in: files },
});
},
},
};
|
function emailInfo(sender, recipient, subject, booleanCheck, date, message){
this.sender = sender,
this.recipient = recipient,
this.subject = subject,
this.booleanCheck = booleanCheck,
this.date = date;
this.message = message;
}
var NDate = new Date(2020, 00, 02);
var selectorDate = null; //beginning of date range
var endDate = null; //end of date range
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var emails = [
new emailInfo("aaa@example.com", ["zzz@example.com"], "[HR-888] Notice of official announcement.", false, new Date(2020, 0, 3, 0, 22), "1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("bbb.bbb@example.com", ["yyy@example.com"], "[Web:333]\"Web Contact\"", false, new Date(2020, 0, 3, 0, 10) ," 2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("ccc@example.com", ["xxx.xxx@example.com", "xwz.xyz@example.com"], "Happy New Year! Greetings for the New Year", true, new Date(2020, 0, 3, 0, 0), "3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("ddd.ddd@example.com", ["vvv.vvv@example.com", "vzz.vzz@example.com"], "[HR-887(Revised: Office Expansion Project Team)] Notice of offer to be received by the president of the Company on December 23, 2020", false, new Date("January 1, 2020"), "4 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("eee@example.com", ["sss@example.com", "rrr.rrr@example.com", "ttt.ttt@example.com"], "[Github] Logout page", false, new Date("January 1, 2020"), "5 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("fff.ffff@example.com", ["qqq.qqq@example.com"], "[dev] Postfix 3.1.12 / 3.2.9 / 3.3.4 / 3.4.5", false, new Date("January 1, 2020"), "6 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("ggg@example.com", ["ppp.qqq@example.com"], "Re: [Github] Brush-up on loading animation", false, new Date("January 1, 2020"), "7 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("hhh.hhh@example.com ", ["ooo.ooo@example.com"], "Workplace Summary for sample, Inc.: Jun 2 - Jun 9", true, new Date("January 1, 2020"), "8 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("iii@example.com", ["nnn@example.com"], "I love you", true, new Date("December 31, 2019"), "9 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
new emailInfo("Pablo-Diego@example.com", ["Pablo-Diego-Jose-Francisco@example.com"], "[info:888] ABC EQUIPMENT COMPANY", false, new Date("December 31, 2019"), "10 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Facilisi cras fermentum odio eu feugiat. Consectetur adipiscing elit duis tristique sollicitudin nibh. Gravida rutrum quisque non tellus orci ac auctor. Neque viverra justo nec ultrices dui sapien eget mi. Netus et malesuada fames ac. Ac turpis egestas maecenas pharetra convallis posuere morbi leo urna. Urna et pharetra pharetra massa massa ultricies. "),
];
//this funciton goes through the email object see if the selected dates match any of the dates in the emails array object.
function checkMail(){
var chosenDate = document.getElementById('chosenDate');
var split1 = chosenDate.value.split("-"); //get the dates specified and split them to the start and end date.
selectorDate = new Date(split1[0]);
endDate = new Date(split1[1]);
endDate.setHours(endDate.getHours() + 23);
endDate.setMinutes(endDate.getMinutes() + 59);
endDate.setSeconds(endDate.getSeconds() + 59);
var main_logo = document.getElementById('main_logo')
main_logo.setAttribute('style', 'display:none;');
var resultsFiltered = document.getElementById('filterType'); //get the id to show the filtering options.
var emailList = document.getElementById('emails'); //get the id to show the found emails
//variables set which will hold strings of content.
var stringlead;
var arrayOfRecipients = "";
var emaildetails = "";
//button used to read selected emails.
var email_chosen_ = "";
//if the user selects to have the older emails show up first the boolean will be set to false.
var dateBoolean = true;
emailCount = document.getElementById('numberOfEmails');
emailCounter = 0; //counter for emails that showed up on the list.
stringlead ="";
for(i =0; i < emails.length; i++){
if(emails[i].date >= selectorDate && emails[i].date <= endDate){
emailCounter++;
var CDate = emails[i].date;
email_chosen_ += 'email_chosen_' + (emailCounter -1); //assign a unique id to all the rows of emails.
stringlead+= '<div id = "'+ email_chosen_+'"data-email-id ="' + i + '" class = \'col-xs-12 contents1 mailsread1\'><div data-email-id = "' + i + '" class = "email-open-button"></div> <svg class = \'spMail\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 11.35144 26.35693\'><defs><style>.a{fill:#666;}</style></defs><title>icon_mail_sp</title><path class=\'a\' d=\'M0,0V7.20007H11.35144V0ZM9.90466.80005,5.67542,4.34863,1.44617.80005ZM.80005,6.4V1.30225L5.41858,5.17773a.39868.39868,0,0,0,.51367,0l4.61914-3.876V6.4Z\'/><path class=\'a\' d=\'M3.54952,13.76637a.36946.36946,0,0,0,0,.52093l2.13177,2.14285L7.82044,14.291a.36945.36945,0,0,0-.52093-.52093L6.05075,15.01513v-2.7963a.36946.36946,0,0,0-.73892,0v2.80738L4.06307,13.77745A.36946.36946,0,0,0,3.54952,13.76637Z\'/><path class=\'a\' d=\'M5.67566,22.35693a1.5,1.5,0,1,1-1.5,1.5,1.50164,1.50164,0,0,1,1.5-1.5m0-1a2.5,2.5,0,1,0,2.5,2.5,2.5,2.5,0,0,0-2.5-2.5Z\'/></svg>';
var elements = document.getElementsByClassName("mailsread1");
stringlead+= "<p class = \'svgSenderMatch\'>" + emails[i].sender + "</p>";
//if there is more than one recipient. go through them all and add them to a string.
if(emails[i].recipient.length > 1){
for(k = 0; k < emails[i].recipient.length; k++){
if(k == (emails[i].recipient.length - 1)){
arrayOfRecipients+=emails[i].recipient[k];
}
else{
arrayOfRecipients+= emails[i].recipient[k] + ",";
}
}
stringlead+= "<div class = \'svgRecipientMatchDiv\'><p class = \'svgRecipientMatch\'>" + arrayOfRecipients + "</p><p class = \'recipientCounter\'> +" + (emails[i].recipient.length -1) + "</p></div>";
arrayOfRecipients = "";
}
else{
stringlead+= "<div class = \'svgRecipientMatchDiv\'><p class = \'svgRecipientMatch\'>" + emails[i].recipient + "</p></div>";
}
//add subject to stringlead if an icon clip is included. If the boolean value is true in the email object. Than include a clip in the email list.
if(emails[i].booleanCheck){
stringlead+= "<div class = \'subjectLine\'><p class = \'subject\'>" + emails[i].subject + "</p><svg class = \'iconClip\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 13.93083 15\'><defs><style>.a{fill:#666;}</style></defs><title>icon_clip</title><path class=\'a\' d=\'M6.799,3.6254A2.30522,2.30522,0,1,0,3.56718,6.85622l4.304,4.304a.5222.5222,0,0,0,.7385-.7385l-4.304-4.304c-.53586-.53586-.87743-1.33808-.23084-1.98466.64553-.64659,1.4488-.304,1.98466.23189L11.032,9.3364c1.90632,1.90841,2.38159,2.78793,1.24615,3.92441-1.149,1.148-2.367.86385-4.20121-.96935L2.367,6.57941C1.1741,5.38653.33845,3.43842,1.90633,1.87159c1.86141-1.86141,3.98708-.03134,4.59293.57555l5.11038,5.11142a.5222.5222,0,0,0,.7385-.7385L7.23776,1.70864C5.18625-.34288,2.86-.56223,1.16678,1.13308c-1.711,1.71-1.5261,4.196.4617,6.18484l5.711,5.711C7.96726,13.6567,9.31161,15,10.85756,15a3.01214,3.01214,0,0,0,2.16014-1.00173c2.07554-2.07658.15564-3.99857-1.24616-5.40141Z\'/></svg></div>";
}
else{
stringlead+= "<div class = \'subjectLine\'><p class = \'subject\'>" + emails[i].subject + "</p></div>";
}
//if statement that decides the outputed format depending on the date that is in the email object array.
if(CDate.getFullYear() == '2019'){
stringlead+= "<p class = \'time\'>" + CDate.getFullYear() + "/" +(CDate.getMonth() + 1) + "/" + CDate.getDate() + "</p>";
}
else if(CDate.getFullYear() > '2019' && CDate < NDate){
stringlead+= "<p class = \'time\'> " + monthNames[CDate.getMonth()] + " " + CDate.getDate() + "</p>";
}
else{
stringlead+= "<p class = \'time\'>" + CDate.getHours() + ":" + CDate.getMinutes() + "</p>";
}
stringlead +="<svg class = \'sideArrow\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 2.9882 6\'><defs><style>.a{fill:#666;}</style></defs><title>icon_arrow02</title><path class=\'a\' d=\'M2.9882,3.00782a.29009.29009,0,0,1-.07319.19286L.51262,5.90234a.29054.29054,0,0,1-.43456-.38577l2.23114-2.509L.07806.48856A.29045.29045,0,0,1,.50284.09233l.00978.011L2.91512,2.8152A.28942.28942,0,0,1,2.9882,3.00782Z\'/></svg></div>";
email_chosen_ = "";
stringlead+= '<p id="email-body-' + i + '" class="mail-subject" style="display: none;" data-is-open="0">' + emails[i].message + '</p>';
}
//reset content back so that it can display a new batch if desired.
else{
stringlead+="";
}
}
//if string lead has some content, add the filtering on top. display the button. and reset the email counter to 0.
if(stringlead != ""){
resultsFiltered.className = "searchActive";
emaildetails+= "<p class = \'from\'> From<svg id = \'adjustFrom\' class = \'iconArrowFrom\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 8 5\'><defs><style>.a{fill:#333;}</style></defs><title>icon_arrow01</title><polygon class=\'a\' points=\'8 5 3.993 0 0 5 8 5\'/></svg></span> </p>";
emaildetails += "<p class = \'toPerson\'> to </p>";
emaildetails += "<p class = \'subjectMessage\'> Subject </p>";
emaildetails +="<span class = \'dateOfMessage\'> Date <svg id = \'adjustDate\' class = \'iconArrowDate\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 8 5\'><defs><style>.a{fill:#333;}</style></defs><title>icon_arrow01</title><polygon class=\'a\' points=\'8 5 3.993 0 0 5 8 5\'/></svg></span>";
resultsFiltered.innerHTML = emaildetails;
emailCount.innerHTML = emailCounter;
emailCounter = 0;
}
//else, if no content, show the main logo. hide the button.
else{
main_logo.setAttribute('style', 'display:flex;');
resultsFiltered.className = "searchResults";
emailCount.innerHTML = 0;
}
//in the end, Show whatever has been done.
emailList.innerHTML = stringlead;
var myFunction = function(e)
{ console.log("My function is being run");
var attribute = e.target.getAttribute("data-email-id");
var element = document.getElementById('email-body-' + attribute);
console.log(attribute);
console.log(element);
if (element.getAttribute('data-is-open') === '0')
{
element.setAttribute('style', 'display: block;');
element.setAttribute('data-is-open', '1');
}
else
{
element.setAttribute('style', 'display: none;');
element.setAttribute('data-is-open', '0');
}
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
//this function sorts the date and name if desired.
function sortDate(){
dateBoolean = !dateBoolean;
//if the boolean value is true, show the email list how it originally was.
// logic is the same as above.
if(dateBoolean){
stringlead = "";
for(i =0; i < emails.length; i++){
if(emails[i].date >= selectorDate && emails[i].date <= endDate){
emailCounter++;
var CDate = emails[i].date;
email_chosen_ += 'email_chosen_' + (emailCounter -1);
stringlead+= '<div id = "'+ email_chosen_+'"data-email-id ="' + i + '" class = \'col-xs-12 contents1 mailsread1\'><div data-email-id = "' + i + '" class = "email-open-button"></div> <svg class = \'spMail\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 11.35144 26.35693\'><defs><style>.a{fill:#666;}</style></defs><title>icon_mail_sp</title><path class=\'a\' d=\'M0,0V7.20007H11.35144V0ZM9.90466.80005,5.67542,4.34863,1.44617.80005ZM.80005,6.4V1.30225L5.41858,5.17773a.39868.39868,0,0,0,.51367,0l4.61914-3.876V6.4Z\'/><path class=\'a\' d=\'M3.54952,13.76637a.36946.36946,0,0,0,0,.52093l2.13177,2.14285L7.82044,14.291a.36945.36945,0,0,0-.52093-.52093L6.05075,15.01513v-2.7963a.36946.36946,0,0,0-.73892,0v2.80738L4.06307,13.77745A.36946.36946,0,0,0,3.54952,13.76637Z\'/><path class=\'a\' d=\'M5.67566,22.35693a1.5,1.5,0,1,1-1.5,1.5,1.50164,1.50164,0,0,1,1.5-1.5m0-1a2.5,2.5,0,1,0,2.5,2.5,2.5,2.5,0,0,0-2.5-2.5Z\'/></svg>';
stringlead+= "<p class = \'svgSenderMatch\'>" + emails[i].sender + "</p>";
if(emails[i].recipient.length > 1){
for(k = 0; k < emails[i].recipient.length; k++){
if(k == (emails[i].recipient.length - 1)){
arrayOfRecipients+=emails[i].recipient[k];
}
else{
arrayOfRecipients+= emails[i].recipient[k] + ",";
}
}
stringlead+= "<div class = \'svgRecipientMatchDiv\'><p class = \'svgRecipientMatch\'>" + arrayOfRecipients + "</p><p class = \'recipientCounter\'> +" + (emails[i].recipient.length -1) + "</p></div>";
arrayOfRecipients = "";
}
else{
stringlead+= "<div class = \'svgRecipientMatchDiv\'><p class = \'svgRecipientMatch\'>" + emails[i].recipient + "</p></div>";
}
if(emails[i].booleanCheck){
stringlead+= "<div class = \'subjectLine\'><p class = \'subject\'>" + emails[i].subject + "</p><svg class = \'iconClip\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 13.93083 15\'><defs><style>.a{fill:#666;}</style></defs><title>icon_clip</title><path class=\'a\' d=\'M6.799,3.6254A2.30522,2.30522,0,1,0,3.56718,6.85622l4.304,4.304a.5222.5222,0,0,0,.7385-.7385l-4.304-4.304c-.53586-.53586-.87743-1.33808-.23084-1.98466.64553-.64659,1.4488-.304,1.98466.23189L11.032,9.3364c1.90632,1.90841,2.38159,2.78793,1.24615,3.92441-1.149,1.148-2.367.86385-4.20121-.96935L2.367,6.57941C1.1741,5.38653.33845,3.43842,1.90633,1.87159c1.86141-1.86141,3.98708-.03134,4.59293.57555l5.11038,5.11142a.5222.5222,0,0,0,.7385-.7385L7.23776,1.70864C5.18625-.34288,2.86-.56223,1.16678,1.13308c-1.711,1.71-1.5261,4.196.4617,6.18484l5.711,5.711C7.96726,13.6567,9.31161,15,10.85756,15a3.01214,3.01214,0,0,0,2.16014-1.00173c2.07554-2.07658.15564-3.99857-1.24616-5.40141Z\'/></svg></div>";
}
else{
stringlead+= "<div class = \'subjectLine\'><p class = \'subject\'>" + emails[i].subject + "</p></div>";
}
if(CDate.getFullYear() == '2019'){
stringlead+= "<p class = \'time\'>" + CDate.getFullYear() + "/" +(CDate.getMonth() + 1) + "/" + CDate.getDate() + "</p>";
}
else if(CDate.getFullYear() > '2019' && CDate < NDate){
stringlead+= "<p class = \'time\'> " + monthNames[CDate.getMonth()] + " " + CDate.getDate() + "</p>";
}
else{
stringlead+= "<p class = \'time\'>" + CDate.getHours() + ":" + CDate.getMinutes() + "</p>";
}
stringlead +="<svg class = \'sideArrow\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 2.9882 6\'><defs><style>.a{fill:#666;}</style></defs><title>icon_arrow02</title><path class=\'a\' d=\'M2.9882,3.00782a.29009.29009,0,0,1-.07319.19286L.51262,5.90234a.29054.29054,0,0,1-.43456-.38577l2.23114-2.509L.07806.48856A.29045.29045,0,0,1,.50284.09233l.00978.011L2.91512,2.8152A.28942.28942,0,0,1,2.9882,3.00782Z\'/></svg></div>";
email_chosen_ = "";
stringlead+= '<p id="email-body-' + i + '" class="mail-subject" style="display: none;" data-is-open="0">' + emails[i].message + '</p>';
}
else{
stringlead+="";
}
}
emailList.innerHTML = stringlead;
emailCounter = 0;
}
//else excute this else statement.
//LOGIC IS THE Same but will ouput a different result.
else{
stringlead = "";
for(i = 9; i >= 0; i--){
if(emails[i].date >= selectorDate && emails[i].date <= endDate){
emailCounter++;
var CDate = emails[i].date;
email_chosen_ += 'email_chosen_' + (i);
stringlead+= '<div id = "'+ email_chosen_+'"data-email-id ="' + i + '" class = \'col-xs-12 contents1 mailsread1\'><div data-email-id = "' + i + '" class = "email-open-button"></div> <svg class = \'spMail\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 11.35144 26.35693\'><defs><style>.a{fill:#666;}</style></defs><title>icon_mail_sp</title><path class=\'a\' d=\'M0,0V7.20007H11.35144V0ZM9.90466.80005,5.67542,4.34863,1.44617.80005ZM.80005,6.4V1.30225L5.41858,5.17773a.39868.39868,0,0,0,.51367,0l4.61914-3.876V6.4Z\'/><path class=\'a\' d=\'M3.54952,13.76637a.36946.36946,0,0,0,0,.52093l2.13177,2.14285L7.82044,14.291a.36945.36945,0,0,0-.52093-.52093L6.05075,15.01513v-2.7963a.36946.36946,0,0,0-.73892,0v2.80738L4.06307,13.77745A.36946.36946,0,0,0,3.54952,13.76637Z\'/><path class=\'a\' d=\'M5.67566,22.35693a1.5,1.5,0,1,1-1.5,1.5,1.50164,1.50164,0,0,1,1.5-1.5m0-1a2.5,2.5,0,1,0,2.5,2.5,2.5,2.5,0,0,0-2.5-2.5Z\'/></svg>';
stringlead+= "<p class = \'svgSenderMatch\'>" + emails[i].sender + "</p>";
if(emails[i].recipient.length > 1){
for(k = 0; k < emails[i].recipient.length; k++){
if(k == (emails[i].recipient.length - 1)){
arrayOfRecipients+=emails[i].recipient[k];
}
else{
arrayOfRecipients+= emails[i].recipient[k] + ",";
}
}
stringlead+= "<div class = \'svgRecipientMatchDiv\'><p class = \'svgRecipientMatch\'>" + arrayOfRecipients + "</p><p class = \'recipientCounter\'> +" + (emails[i].recipient.length -1) + "</p></div>";
arrayOfRecipients = "";
}
else{
stringlead+= "<div class = \'svgRecipientMatchDiv\'><p class = \'svgRecipientMatch\'>" + emails[i].recipient + "</p></div>";
}
if(emails[i].booleanCheck){
stringlead+= "<div class = \'subjectLine\'><p class = \'subject\'>" + emails[i].subject + "</p><svg class = \'iconClip\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 13.93083 15\'><defs><style>.a{fill:#666;}</style></defs><title>icon_clip</title><path class=\'a\' d=\'M6.799,3.6254A2.30522,2.30522,0,1,0,3.56718,6.85622l4.304,4.304a.5222.5222,0,0,0,.7385-.7385l-4.304-4.304c-.53586-.53586-.87743-1.33808-.23084-1.98466.64553-.64659,1.4488-.304,1.98466.23189L11.032,9.3364c1.90632,1.90841,2.38159,2.78793,1.24615,3.92441-1.149,1.148-2.367.86385-4.20121-.96935L2.367,6.57941C1.1741,5.38653.33845,3.43842,1.90633,1.87159c1.86141-1.86141,3.98708-.03134,4.59293.57555l5.11038,5.11142a.5222.5222,0,0,0,.7385-.7385L7.23776,1.70864C5.18625-.34288,2.86-.56223,1.16678,1.13308c-1.711,1.71-1.5261,4.196.4617,6.18484l5.711,5.711C7.96726,13.6567,9.31161,15,10.85756,15a3.01214,3.01214,0,0,0,2.16014-1.00173c2.07554-2.07658.15564-3.99857-1.24616-5.40141Z\'/></svg></div>";
}
else{
stringlead+= "<div class = \'subjectLine\'><p class = \'subject\'>" + emails[i].subject + "</p></div>";
}
if(CDate.getFullYear() == '2019'){
stringlead+= "<p class = \'time\'>" + CDate.getFullYear() + "/" +(CDate.getMonth() + 1) + "/" + CDate.getDate() + "</p>";
}
else if(CDate.getFullYear() > '2019' && CDate < NDate){
stringlead+= "<p class = \'time\'>Jan " + CDate.getDate() + "</p>";
}
else{
stringlead+= "<p class = \'time\'>" + CDate.getHours() + ":" + CDate.getMinutes() + "</p>";
}
stringlead +="<svg class = \'sideArrow\' xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 2.9882 6\'><defs><style>.a{fill:#666;}</style></defs><title>icon_arrow02</title><path class=\'a\' d=\'M2.9882,3.00782a.29009.29009,0,0,1-.07319.19286L.51262,5.90234a.29054.29054,0,0,1-.43456-.38577l2.23114-2.509L.07806.48856A.29045.29045,0,0,1,.50284.09233l.00978.011L2.91512,2.8152A.28942.28942,0,0,1,2.9882,3.00782Z\'/></svg></div>";
email_chosen_ = "";
stringlead+= '<p id="email-body-' + i + '" class="mail-subject" style="display: none;" data-is-open="0">' + emails[i].message + '</p>';
}
else{
stringlead+="";
}
}
emailList.innerHTML = stringlead;
emailCounter =0;
}
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
}//end of sort date function
//add event listeners so when the user clicks on a arrow, it sorts the emails.
var dateSort = document.getElementById('adjustDate');
var fromSort = document.getElementById('adjustFrom');
dateSort.addEventListener('click', sortDate, false);
fromSort.addEventListener('click', sortDate, false);
};
//JQuery is used to get the date range picker.
$(function(){
$('.form-control').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('.form-control[name="dateChosen"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
});
$('.form-control[name="dateChosen"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
var form = document.getElementById('submitButton');
form.addEventListener('click', checkMail, false);
|
import React, { Component } from "react";
class CommentDeleter extends Component {
render() {
return (
<div>
<button
onClick={() => {
this.props.delete(this.props.commentId);
}}
>
Delete
</button>
</div>
);
}
}
export default CommentDeleter;
|
import { useQuery } from 'react-query';
import api from '../services/api';
const getPost = async (id) => {
const { data } = await api.get(`posts/${id}`);
return data;
};
export default function usePost(id) {
return useQuery(['post', id], () => getPost(id));
}
|
///////////////app版本管理/////////////
$(function(){
$('#dg').datagrid({
onLoadSuccess: function(data){
if (data.total == 0 && data.ERROR == 'No Login!') {
//relogin();
var user_id = localStorage.getItem('user_id');
var user_pwd = localStorage.getItem('user_pwd');
if(user_id==''||!user_id||user_pwd==''||!user_pwd){
$.messager.alert('信息提示', '登录超时,请重新登录!', 'error');
relogin();
}
else{
$.post('loginAction!login1.zk',{user_id:user_id,user_pwd:user_pwd},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
}
},'json').complete(function(){
$('#dg').datagrid('reload');
});
}
}
},
onLoadError : function() {
alert('出错啦');
}
});
});
//页面初始化
function initPage() {
//刷新表格数据
$('#dg').datagrid('reload');
//清空相关参数
$("#txt_oa").val('');
$("#txt_ob").val('');
$("#txt_oc").val('');
$("#oplatform").val('');
}
//验证URL
function checkUrl(str) {
var strRegex = '^((https|http|ftp|itms)?://)'
+ '?(([0-9a-zA-Z_!~*\'().&=+$%-]+: )?[0-9a-zA-Z_!~*\'().&=+$%-]+@)?' //ftp的user@
+ '(([0-9]{1,3}.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184
+ '|' // 允许IP和DOMAIN(域名)
+ '([0-9a-zA-Z_!~*\'()-]+.)*' // 域名- www.
+ '([0-9a-zA-Z-]{0,62}.)?([0-9a-z])*.' // 二级域名
+ '[a-z]{2,6})' // first level domain- .com or .museum
+ '(:[0-9]{1,4})?' // 端口- :80
+ '((/?)|' // a slash isn't required if there is no file name
+ '(/[0-9a-zA-Z_!~*\'().;?:@&=+$,%#-]+)+/?)$';
var regex = new RegExp(strRegex);
return regex.test(str);
}
//新增版本
function newVersion() {
var oa = $.trim($("#txt_oa").val());
var ob = $.trim($("#txt_ob").val());
var oc = $.trim($("#txt_oc").val());
var oplatform = $.trim($("#oplatform").val());
var a = $.trim($("#txt_a").val());
var b = $.trim($("#txt_b").val());
var c = $.trim($("#txt_c").val());
var platform = $.trim($("#sl_platform").val());
var url = $.trim($("#txt_url").val());
var note = $.trim($("#tf_note").val());
if (isEmpty(a)) {
alert('版本号不能为空!');
return;
}
if (isEmpty(b)) {
alert('版本号不能为空!');
return;
}
if (isEmpty(c)) {
alert('版本号不能为空!');
return;
}
if (equals(platform, '选择平台')) {
alert('请选择平台!');
return;
}
if (isEmpty(url)) {
alert('下载链接不能为空!');
return;
}
if(!checkUrl(url)){
alert('请填写正确的下载链接!');
return;
}
if (isEmpty(note)) {
alert('版本更新说明不能为空!');
return;
}
var postData = {
a : a,
b : b,
c : c,
platform : platform,
url : url,
note : note,
module : 'add'
};
var msg = "成功添加新版本!";
if (!isEmpty(oa) && !isEmpty(ob) && !isEmpty(oc) && !isEmpty(oplatform)) {
msg = "成功更新版本信息!";
postData = {
a : a,
b : b,
c : c,
oa : oa,
ob : ob,
oc : oc,
oplatform : oplatform,
platform : platform,
url : url,
note : note,
module : 'update'
};
}
$.post("versionAction!saveOrUpdate.zk", postData, function(data) {
if (data.STATUS) {
if(data.ERROR&&data.ERROR=='No Login!'){
//alert('登陆超时,请重新登录!');
//location.replace('index.html');
var user_id = localStorage.getItem('user_id');
var user_pwd = localStorage.getItem('user_pwd');
if(user_id==''||!user_id||user_pwd==''||!user_pwd){
$.messager.alert('信息提示', '登录超时,请重新登录!', 'error');
location.replace('index.html');
}
else{
$.post('loginAction!login1.zk',{user_id:user_id,user_pwd:user_pwd},function(data){
},'json').complete(function(){
$.post("versionAction!saveOrUpdate.zk", postData, function(data) {
},'json');
});
}
}else{
$('#dlg').dialog('close');
initPage();
showTip(msg);
}
} else {
alert(data.INFO);
}
}, 'json');
}
function equals(v, n) {
return (v == n);
}
function isEmpty(v) {
return (v == null || v == '');
}
//初始化更新操作
function initUpdate() {
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('setTitle','填写App版本信息');
//原始版本号
$("#txt_oa").val(row.a);
$("#txt_ob").val(row.b);
$("#txt_oc").val(row.c);
$("#oplatform").val(row.platform);
$("#txt_a").val(row.a);
$("#txt_b").val(row.b);
$("#txt_c").val(row.c);
$("#sl_platform").val(row.platform);
$("#txt_url").val(row.downloadUrl);
$("#tf_note").val(row.releaseNote);
}else{
$.messager.alert('错误','请先选择一个版本!','error');
}
}
//删除版本
function del() {
var row = $('#dg').datagrid('getSelected');
if(row){
if (confirm('确定删除该版本吗?')) {
$.getJSON("versionAction!delete.zk", {
a : row.a,
b : row.b,
c : row.c,
platform : row.platform
}, function(data) {
if (data.STATUS) {
if(data.ERROR&&data.ERROR=='No Login!'){
alert('登陆超时,请重新登录!');
location.replace('index.html');
}else{
initPage();
showTip("成功删除了一条版本信息!");
}
} else {
alert(data.INFO);
}
});
}
}else{
$.messager.alert('错误','请先选择一个版本!','error');
}
}
//格式化时间
function formatDate(value){
var d = new Date(value);
return d.format("yyyy-MM-dd hh:mm:ss");
}
//格式化版本信息
function formatVersion(a,row) {
var a = a;
var b = row.b;
var c = row.c;
var p = row.platform ;
var platform = 'IOS系统';
var img = 'wttp_huo_2';
if (p == 'a') {
platform = 'Android系统';
}
var str = "["+platform+"]<span>版本"+a+"."+b+"."+c+"</span></a>";
return str;
}
function newAppVersion(){
//clear form
$("#txt_oa").val('');
$("#txt_ob").val('');
$("#txt_oc").val('');
$("#oplatform").val('');
$("#txt_a").val('');
$("#txt_b").val('');
$("#txt_c").val('');
$("#txt_url").val('');
$("#tf_note").val('');
$('#dlg').dialog('open').dialog('setTitle','填写App版本信息');
}
|
import ChatList from "../components/ChatList";
import ChatArea from "../components/ChatArea";
import UserChatInformation from "../components/UserChatInformation";
import styles from "../styles/Chat.module.scss";
export default function Chat () {
return (
<div className={styles.chatBody}>
<ChatList/>
<ChatArea />
<UserChatInformation/>
</div>
)
}
|
module.exports = require('./relation.factory');
|
import React from "react";
import { Icon } from "semantic-ui-react";
function Header() {
return (
<div className="ui stackable grid margin-no">
<div className="middle aligned column padding-vs-vertical" style={{ width: 104 }}>
<img
className="ui medium circular image"
src="/assets/images/WhatsApp Image 2021-03-05 at 10.00.19.jpeg"
alt=""
width="50px"
/>
</div>
<div className="thirteen wide column padding-vs-vertical">
<p className="text-size-large text-weight-medium margin-five-bottom">Sailab Basak</p>
{/* <p className="margin-no">React | React Native | EmberJs Developer</p> */}
<p className="margin-five-bottom">
<span>
<a
href="mailto:sailabbasak1998@gmail.com"
className="margin-ten-right text-color-red disableOnPrint"
target="black"
>
<Icon name="mail outline" />
sailabbasak1998@gmail.com
</a>
</span>
<span>
<a
href="tel:07662914308"
className="margin-ten-right text-color-green disableOnPrint"
target="black"
>
<Icon name="phone" />
+91-7662914308
</a>
</span>
<span>
<Icon name="map marker alternate" />
<span className="margin-ten-right">Guwahati, Assam, 781040</span>
</span>
</p>
<p>
<span>
<a href="https://www.linkedin.com/in/sailab-basak-a6a201183/" target="blank">
<Icon name="linkedin" />
<span className="margin-ten-right">sailab-basak-a6a201183</span>
</a>
<a href="https://github.com/Sailab12345" target="blank">
<Icon name="github" />
<span className="margin-ten-right">Sailab12345</span>
</a>
</span>
</p>
</div>
</div>
);
}
export default Header;
|
atom.declare("Game.Part", App.Element,
{
configure: function()
{
this.localPosition = this.settings.get("localPosition");
this.parent = this.settings.get("parent");
this.angle = this.settings.get("angle");
this.quads = this.settings.get("quads");
this.killed = false;
this.shape = new Rectangle({
center: this.localPosition,
size: SizeZero
});
},
doDamage: function(damage)
{
if (this.killed)
return;
this.HP -= damage;
if (this.HP <= 0)
this.kill();
},
kill: function()
{
this.killed = true;
this.destroy();
Controller.sound.play("part_explosion", this.parent.shape.center);
if (this.deadTexture != null)
{
this.textureMain = this.deadTexture;
this.parent.partExplosion(this);
this.parent.doDamage(0);
}
else
this.parent.killPart(this);
this.parent.redraw();
},
updateFunc: function(time)
{
},
drawFunc: function(ctx)
{
if (this.textureMain != null)
{
ctx.drawImage({
image: this.textureMain,
center: this.localPosition,
angle: this.angle
});
}
}
});
|
'use strict';
import ArrayItem from './ArrayItem'
const ComponentsWithProps = (props) => {
const values = props.arrayProp.map((item) => <li key={item}>{item}</li>);
//print an object
const objectPropsDisplay = [];
for(let[k,v] of Object.entries(props.objProp)) {
objectPropsDisplay.push(<li key={k}> value: {v}</li>)
}
return (
<>
<p>Hi there, the value of string is: {props.stringProp}</p>
<p>Hi there, the value of function is: {props.func()}</p>
{
props.arrayProp.map((item, i) => (
<ArrayItem key={i} item={item} />
))
}
<p>{objectPropsDisplay}</p>
</>
)
}
export default ComponentsWithProps;
|
var obj = module.exports = function(){
this.count = 0;
};
obj.prototype.touch = function(){
this.count++;
};
|
import React from 'react';
import './index.scss';
import Agenda from '../../Components/Agenda';
import Points from '../../Components/Points';
import Schedule from '../../Components/Schedule';
const Home = () => (
<main className="Home">
<section className="Home__wp">
<div className="Home__wp__grid">
<Agenda />
<Points />
<Schedule />
</div>
</section>
</main>
);
export default Home;
|
//Potion for the player
// with name, and health it heals ah
function Potion (name, healing){
this.name = name;
this.healing = healing;
//is it responsability of the potion eliminate itself from the list or not
this.consume = function(character){
character.health += this.healing;
}
console.log(this);
}
|
import profileReducer, { addPostActionCreator, deletePost } from "./profile-reducer";
let state = {
postData: [
{id: 1, message: 'Hi, how are u', likesCount: 15},
{id: 2, message: 'I am trololo', likesCount: 2},
{id: 3, message: 'azaza', likesCount: 101}
]}
test('length of posts should be incremented', () => {
//1. test data
let action = addPostActionCreator("it-kamasutra.com")
//2.action
let newState = profileReducer(state, action)
//3.expectation
expect (newState.postData.length).toBe(4)
});
test('message of new post should be correct', () => {
//1. test data
let action = addPostActionCreator("it-kamasutra.com")
//2.action
let newState = profileReducer(state, action)
//3.expectation
expect (newState.postData[3].message).toBe("it-kamasutra.com")
});
test(`after deleting length should't be decrement if id is incorrect`, () => {
//1. test data
let action = deletePost(1000)
//2.action
let newState = profileReducer(state, action)
//3.expectation
expect (newState.postData.length).toBe(3)
});
|
const showdown = require('showdown')
// var babel = require("babel-core");
module.exports = function(content,map) {
this.cacheable && this.cacheable()
/*
1. content -> html
2. html -> jsx
3. jsx -> js
*/
const converter = new showdown.Converter()
converter.setOption('tables', true)
content = converter.makeHtml(content)
// this.value = content;
/*
import React,{Component} from 'react'
export default class extends Component{
render(){
return (
content
)
}
}
``
*/
// { => {'{'} } => {'}'}
/*
[
{tag:'div':child:[{tag:'sds'},'sdadasd']}
]
*/
// const contentData = JSON.stringify(htmlParse(content))
// React.createElement('', props, children)
content = `
import React,{Component} from 'react'
import ReactHtmlParser from 'react-html-parser'
export default class extends Component{
render(){
return (
<div>
{ ReactHtmlParser(${JSON.stringify(content)}) }
</div>
)
}
}
`
//
// return JSON.stringify(content)
this.callback(null, content,map);
}
module.exports.seperable = true;
|
{
const DOC = document;
const WIN = window;
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
DOC.getElementsByClassName('parallax-front').classList.add('front-page-bg__phone');
DOC.getElementsByClassName('parallax-front').classList.add('parallax-front__disable');
}
else {
const parallaxFrontContainer = DOC.getElementById('parallax-front');
const layers = parallaxFrontContainer.children;
const moveLayers = e => {
const initialX = WIN.innerWidth / 2 - e.pageX;
const initialY = WIN.innerHeight / 2 - e.pageY;
Array.from(layers).forEach((layer, i) => {
const divider = i / 100;
const posX = initialX * divider;
const posY = initialY * divider;
layer.style.transform = `translate(${posX}px, ${posY}px)`;
});
};
WIN.addEventListener('mousemove', moveLayers);
}
}
|
const prod1 = {}
// {} representa um objeto
// pode-se criar um objeto dentro do outro
prod1.nome = 'Iphone 11'
prod1.preco = 4999.90
prod1['Desconto Legal'] = 0.40
// não entendi os []
console.log(prod1)
const prod2 = {
nome: 'Camisa polo',
preco: 79.90 }
console.log(prod2)
/*obj: {
blabla: 1,
obj:{
blabla: 2
}
}*/
/* é possivel ter um objeto dentro de outro objeto
nomear com o mesmo nome, desde que seja dentro do mesmo obj
JSON - SEUS ATRIBUTOS SÃO DELIMITADOS POR ASPAS DUPLAS " "
não é um objeto, é um formato textual para troca de dados entre sistemas
'{ "nome": "Suellen", "preco": 2700.00 }' */
|
function booking(mode)
{
if(mode)
{
if (document.getElementById("name").value=="")
document.getElementById("status_booking").innerHTML = "Заполните поле Имя.";
else if (document.getElementById("firstName").value=="")
document.getElementById("status_booking").innerHTML = "Заполните поле Фамилия.";
else if (document.getElementById("email1").value=="")
document.getElementById("status_booking").innerHTML = "Заполните поле e-mail 1.";
else if (document.getElementById("email2").value=="")
document.getElementById("status_booking").innerHTML = "Заполните поле e-mail 2.";
else if (document.getElementById("pass1").value=="")
document.getElementById("status_booking").innerHTML = "Заполните поле Пароль 1.";
else if (document.getElementById("pass2").value=="")
document.getElementById("status_booking").innerHTML = "Заполните поле Пароль 2.";
else if (document.getElementById("pass1").value!==document.getElementById("pass2").value)
document.getElementById("status_booking").innerHTML = "Поля Пароль 1 и Пароль 2 должны быть одинаковы.";
else if (document.getElementById("email1").value!==document.getElementById("email2").value)
document.getElementById("status_booking").innerHTML = "Поля email 1 и email 2 должны быть одинаковы.";
else
sendData({
url:'modules/booking.php',
statbox:'status',
method:'POST',
data:
{
begin: document.getElementById("beginDate").value,
end: document.getElementById("endDate").value,
name: document.getElementById("name").value,
firstName: document.getElementById("firstName").value,
email: document.getElementById("email1").value,
password: document.getElementById("pass1").value,
contact: document.getElementById("contact").value,
id_object: document.getElementById("id_object").value
},
success:function(data){document.getElementById('booking').innerHTML=data; }
});
}
else
{
sendData({
url:'modules/booking.php',
statbox:'status',
method:'POST',
data:
{
begin: document.getElementById("beginDate").value,
end: document.getElementById("endDate").value,
id_object: document.getElementById("id_object").value
},
success:function(data){document.getElementById('booking').innerHTML=data; }
});
}
}
|
let table = [];
let mult1 = [];
let mult2 = [];
let mult3 = [];
let mult4 = [];
let mult5 = [];
let mult6 = [];
let mult7 = [];
let mult8 = [];
let mult9 = [];
for(let i = 1; i < 10; i++) {
for(let j = 1; j < 10; j++) {
if(i == 1) {
mult1.push(i * j);
} else if(i == 2) {
mult2.push(i * j);
} else if(i == 3) {
mult3.push(i * j);
} else if(i == 4) {
mult4.push(i * j);
} else if(i == 5) {
mult5.push(i * j);
} else if(i == 6) {
mult6.push(i * j);
} else if(i == 7) {
mult7.push(i * j);
} else if(i == 8) {
mult8.push(i * j);
} else {
mult9.push(i * j);
}
};
};
table.push(mult1, mult2, mult3, mult4, mult5, mult6, mult7, mult8, mult9);
console.log(table);
|
import _extends from "@babel/runtime/helpers/esm/extends";
import { isDefined } from "../../../../core/utils/type";
import domAdapter from "../../../../core/dom_adapter";
import { normalizeEnum } from "../../../../viz/core/utils";
var KEY_FONT_SIZE = "font-size";
var DEFAULT_FONT_SIZE = 12;
var SHARPING_CORRECTION = 0.5;
export var getNextDefsSvgId = (() => {
var numDefsSvgElements = 1;
return () => "DevExpress_".concat(numDefsSvgElements++);
})();
export var getFuncIri = (id, pathModified) => id !== null ? "url(".concat(pathModified ? window.location.href.split("#")[0] : "", "#").concat(id, ")") : id;
export var extend = (target, source) => {
target = _extends({}, target, source);
return target;
};
function buildSegments(points, buildSimpleSegment, close) {
var i;
var ii;
var list = [];
if (Array.isArray(points[0])) {
for (i = 0, ii = points.length; i < ii; ++i) {
buildSimpleSegment(points[i], close, list);
}
} else {
buildSimpleSegment(points, close, list);
}
return list;
}
function buildSimpleLineSegment(points, close, list) {
var i = 0;
var k0 = list.length;
var k = k0;
var ii = (points || []).length;
if (ii) {
if (points[0].x !== undefined) {
var arrPoints = points;
for (; i < ii;) {
list[k++] = ["L", arrPoints[i].x, arrPoints[i++].y];
}
} else {
var _arrPoints = points;
for (; i < ii;) {
list[k++] = ["L", _arrPoints[i++], _arrPoints[i++]];
}
}
list[k0][0] = "M";
} else {
list[k] = ["M", 0, 0];
}
close && list.push(["Z"]);
return list;
}
function buildSimpleCurveSegment(points, close, list) {
var i;
var k = list.length;
var ii = (points || []).length;
if (ii) {
if (points[0] !== undefined) {
var arrPoints = points;
list[k++] = ["M", arrPoints[0].x, arrPoints[0].y];
for (i = 1; i < ii;) {
list[k++] = ["C", arrPoints[i].x, arrPoints[i++].y, arrPoints[i].x, arrPoints[i++].y, arrPoints[i].x, arrPoints[i++].y];
}
} else {
var _arrPoints2 = points;
list[k++] = ["M", _arrPoints2[0], _arrPoints2[1]];
for (i = 2; i < ii;) {
list[k++] = ["C", _arrPoints2[i++], _arrPoints2[i++], _arrPoints2[i++], _arrPoints2[i++], _arrPoints2[i++], _arrPoints2[i++]];
}
}
} else {
list[k] = ["M", 0, 0];
}
close && list.push(["Z"]);
return list;
}
function buildLineSegments(points, close) {
return buildSegments(points, buildSimpleLineSegment, close);
}
function buildCurveSegments(points, close) {
return buildSegments(points, buildSimpleCurveSegment, close);
}
export var buildPathSegments = (points, type) => {
var list = [["M", 0, 0]];
if (type === "line") {
list = buildLineSegments(points, false);
} else if (type === "area") {
list = buildLineSegments(points, true);
} else if (type === "bezier") {
list = buildCurveSegments(points, false);
} else if (type === "bezierarea") {
list = buildCurveSegments(points, true);
}
return list;
};
export var combinePathParam = segments => {
var d = [];
var ii = segments.length;
var segment;
for (var i = 0; i < ii; ++i) {
segment = segments[i];
for (var j = 0, jj = segment.length; j < jj; ++j) {
d.push(segment[j]);
}
}
return d.join(" ");
};
function prepareConstSegment(constSeg, type) {
var x = constSeg[constSeg.length - 2];
var y = constSeg[constSeg.length - 1];
if (type === "line" || type === "area") {
constSeg[0] = "L";
} else if (type === "bezier" || type === "bezierarea") {
constSeg[0] = "C";
constSeg[1] = x;
constSeg[3] = x;
constSeg[5] = x;
constSeg[2] = y;
constSeg[4] = y;
constSeg[6] = y;
}
}
function makeEqualLineSegments(short, long, type) {
var constSeg = [...short[short.length - 1]];
var i = short.length;
prepareConstSegment(constSeg, type);
for (; i < long.length; i++) {
short[i] = [...constSeg];
}
}
function makeEqualAreaSegments(short, long, type) {
var i;
var head;
var shortLength = short.length;
var longLength = long.length;
var constsSeg1;
var constsSeg2;
if ((shortLength - 1) % 2 === 0 && (longLength - 1) % 2 === 0) {
i = (shortLength - 1) / 2 - 1;
head = short.slice(0, i + 1);
constsSeg1 = [...head[head.length - 1]];
constsSeg2 = [...short.slice(i + 1)[0]];
prepareConstSegment(constsSeg1, type);
prepareConstSegment(constsSeg2, type);
for (var j = i; j < (longLength - 1) / 2 - 1; j++) {
short.splice(j + 1, 0, constsSeg1);
short.splice(j + 3, 0, constsSeg2);
}
}
}
export var compensateSegments = (oldSegments, newSegments, type) => {
var oldLength = oldSegments.length;
var newLength = newSegments.length;
var originalNewSegments = [];
var makeEqualSegments = type.indexOf("area") !== -1 ? makeEqualAreaSegments : makeEqualLineSegments;
if (oldLength === 0) {
for (var i = 0; i < newLength; i++) {
oldSegments.push([...newSegments[i]]);
}
} else if (oldLength < newLength) {
makeEqualSegments(oldSegments, newSegments, type);
} else if (oldLength > newLength) {
originalNewSegments = [...newSegments];
makeEqualSegments(newSegments, oldSegments, type);
}
return originalNewSegments;
};
export var getElementBBox = element => {
var bBox = new SVGRect(0, 0, 0, 0);
if (element !== undefined) {
bBox = element.getBBox();
} else if (element !== undefined) {
var el = element;
bBox = new SVGRect(0, 0, el.offsetWidth, el.offsetHeight);
}
return bBox;
};
function maxLengthFontSize(fontSize1, fontSize2) {
var height1 = fontSize1 || DEFAULT_FONT_SIZE;
var height2 = fontSize2 || DEFAULT_FONT_SIZE;
return height1 > height2 ? height1 : height2;
}
function orderHtmlTree(list, line, node, parentStyle, parentClassName) {
var style;
var realStyle = node.style;
if (isDefined(node.wholeText)) {
list.push({
value: node.wholeText,
style: parentStyle,
className: parentClassName,
line,
height: parseFloat(parentStyle.fontSize) || 0
});
} else if (node.tagName === "BR") {
++line;
} else if (domAdapter.isElementNode(node)) {
style = extend(style = {}, parentStyle);
switch (node.tagName) {
case "B":
case "STRONG":
style.fontWeight = "bold";
break;
case "I":
case "EM":
style.fontStyle = "italic";
break;
case "U":
style.textDecoration = "underline";
break;
default:
break;
}
realStyle.color && (style.fill = realStyle.color);
realStyle.fontSize && (style.fontSize = realStyle.fontSize);
realStyle.fontStyle && (style.fontStyle = realStyle.fontStyle);
realStyle.fontWeight && (style.fontWeight = realStyle.fontWeight);
realStyle.textDecoration && (style.textDecoration = realStyle.textDecoration);
for (var i = 0, nodes = node.childNodes, ii = nodes.length; i < ii; ++i) {
line = orderHtmlTree(list, line, nodes[i], style, node.className || parentClassName);
}
}
return line;
}
function adjustLineHeights(items) {
var currentItem = items[0];
var item;
for (var i = 1, ii = items.length; i < ii; ++i) {
item = items[i];
if (item.line === currentItem.line) {
currentItem.height = maxLengthFontSize(currentItem.height, item.height);
currentItem.inherits = currentItem.inherits || item.height === 0;
item.height = NaN;
} else {
currentItem = item;
}
}
}
export var removeExtraAttrs = html => {
var findTagAttrs = /(?:(<[a-z0-9]+\s*))([\s\S]*?)(>|\/>)/gi;
var findStyleAndClassAttrs = /(style|class)\s*=\s*(["'])(?:(?!\2).)*\2\s?/gi;
return html.replace(findTagAttrs, (_, p1, p2, p3) => {
var _p;
p2 = (((_p = p2) === null || _p === void 0 ? void 0 : _p.match(findStyleAndClassAttrs)) || []).map(str => str).join(" ");
return p1 + p2 + p3;
});
};
export var parseHTML = text => {
var items = [];
var div = domAdapter.createElement("div");
div.innerHTML = text.replace(/\r/g, "").replace(/\n/g, "<br/>");
orderHtmlTree(items, 0, div, {}, "");
adjustLineHeights(items);
return items;
};
export var parseMultiline = text => {
var texts = text.replace(/\r/g, "").split(/\n/g);
var items = [];
for (var i = 0; i < texts.length; i++) {
items.push({
value: texts[i].trim(),
height: 0,
line: i
});
}
return items;
};
export var getTextWidth = text => {
var {
tspan,
value
} = text;
return value.length && tspan ? tspan.getSubStringLength(0, value.length) : 0;
};
export var setTextNodeAttribute = (item, name, value) => {
var _item$tspan, _item$stroke;
(_item$tspan = item.tspan) === null || _item$tspan === void 0 ? void 0 : _item$tspan.setAttribute(name, value);
(_item$stroke = item.stroke) === null || _item$stroke === void 0 ? void 0 : _item$stroke.setAttribute(name, value);
};
export var getItemLineHeight = (item, defaultValue) => item.inherits ? maxLengthFontSize(item.height, defaultValue) : item.height || defaultValue;
export var getLineHeight = styles => styles && !isNaN(parseFloat(styles[KEY_FONT_SIZE])) ? parseFloat(styles[KEY_FONT_SIZE]) : DEFAULT_FONT_SIZE;
export var textsAreEqual = (newItems, renderedItems) => {
if (!renderedItems || renderedItems.length !== newItems.length) return false;
return renderedItems.every((item, index) => item.value === newItems[index].value);
};
export var convertAlignmentToAnchor = function convertAlignmentToAnchor(value) {
var rtl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return value ? {
left: rtl ? "end" : "start",
center: "middle",
right: rtl ? "start" : "end"
}[value] : undefined;
};
function getTransformation(props, x, y) {
var {
rotate,
rotateX,
rotateY,
scaleX,
scaleY,
sharp,
sharpDirection,
strokeWidth,
translateX,
translateY
} = props;
var transformations = [];
var transDir = sharpDirection === "backward" ? -1 : 1;
var strokeOdd = (strokeWidth || 0) % 2;
var correctionX = strokeOdd && (sharp === "h" || sharp === true) ? SHARPING_CORRECTION * transDir : 0;
var correctionY = strokeOdd && (sharp === "v" || sharp === true) ? SHARPING_CORRECTION * transDir : 0;
if (translateX || translateY || correctionX || correctionY) {
transformations.push("translate(".concat((translateX || 0) + correctionX, ",").concat((translateY || 0) + correctionY, ")"));
}
if (rotate) {
transformations.push("rotate(".concat(rotate, ",").concat(rotateX || x || 0, ",").concat(rotateY || y || 0, ")"));
}
var scaleXDefined = isDefined(scaleX);
var scaleYDefined = isDefined(scaleY);
if (scaleXDefined || scaleYDefined) {
transformations.push("scale(".concat(scaleXDefined ? scaleX : 1, ",").concat(scaleYDefined ? scaleY : 1, ")"));
}
return transformations.length ? transformations.join(" ") : undefined;
}
function getDashStyle(props) {
var {
dashStyle,
strokeWidth
} = props;
if (!dashStyle || dashStyle === "none" || dashStyle === "solid") {
return undefined;
}
var sw = strokeWidth || 1;
var value = normalizeEnum(dashStyle);
var dashArray = [];
dashArray = value.replace(/longdash/g, "8,3,").replace(/dash/g, "4,3,").replace(/dot/g, "1,3,").replace(/,$/, "").split(",");
var i = dashArray.length;
while (i--) {
dashArray[i] = parseInt(dashArray[i], 10) * sw;
}
return dashArray.join(",");
}
export var getGraphicExtraProps = (props, x, y) => ({
transform: getTransformation(props, x, y),
"stroke-dasharray": getDashStyle(props)
});
|
import React from 'react';
import PropTypes from 'prop-types';
const Debug = ({label, data}) => (<div style={{padding: '2rem', border: '1px solid red', margin: '2rem'}}>
<small>{label}</small>
<code>
<pre style={{fontSize: '0.75rem'}}>
{JSON.stringify(data, null, ' ')}
</pre>
</code>
</div>);
Debug.propTypes = {
label: PropTypes.string,
data: PropTypes.any // eslint-disable-line react/forbid-prop-types
};
export default Debug;
|
import React, { Component } from 'react';
import './App.css';
import Article from './components/Article'
import axios from 'axios';
class App extends Component {
constructor(){
super()
this.state = {
articles: []
}
// this.getData = this.getData.bind(this)
}
componentWillMount(){
axios.get('https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=9618a7c6df4946c0b5ba0da63ea1448a')
.then(response => {
// console.log(response.data.articles)
this.setState({
articles: response.data.articles
})
})
}
render() {
console.log(this.state.articles)
var news = this.state.articles.map((article) => {
return (
<Article title={article.title} subtitle={article.description} imageUrl={article.urlToImage} url={article.url}/>
)
})
return (
<div className="App">
{news}
<h1>Hello</h1>
</div>
);
}
}
export default App;
|
//need to sort out the cloning ids problem
//TODO : remove renderBibleLookUp
var renderBibleLookUp = function (aBible, book, chapter, verse)
{
aBible = new Hash(aBible);
if ($('bookReading').options.length < 2)
{
$('bookReading').empty();
aBible.each(function(aChapters, sBook)
{
var myEl = new Element('option', {'value':sBook, 'text':sBook});
$('bookReading').adopt(myEl);
});
}
$('bookReading').set('value', book);
/*
$('chapterReading').empty();
var oChapter = new Hash(aBible[book]);
oChapter.each(function(aPages, iChapter)
{
var myEl = new Element('option', {'value':iChapter, 'text':iChapter});
$('chapterReading').adopt(myEl);
});
$('chapterReading').set('value', chapter);
$('verseReading').empty();
var oPages = new Hash(aBible[book][chapter]);
var aPageKeys = oPages.getKeys();
for(var i = 1 ; i < aPageKeys[aPageKeys.length - 1]; i++)
{
var myEl = new Element('option', {'value':i, 'text':i});
$('verseReading').adopt(myEl);
}
$('verseReading').set('value', verse);
*/
};
//GUI stuff
var editSetSong = function(eLi)
{
var xmlnode = eLi.retrieve('xmlnode');
var sPath = xmlnode.getAttribute('path');
if (sPath === null)
{
sPath = '';
}
var sName = xmlnode.getAttribute('name');
var sFile = sPath+sName;
//oSongEditFetchRequest.send({data:{church:CONST_CHOOSEN_CHURCH, type:'song', file:sFile}});
oSongEditFetchRequest.send({data:{church:CONST_CHOOSEN_CHURCH, file:sFile}});
};
var editSetSlide = function(eLi)
{
var xmlnode = eLi.retrieve('xmlnode');
oPanelSliders.show('editSetSlide');
var myBodys = xmlnode.getElements('body');
var aText = [];
myBodys.each(function(item, index){
var nextText = item.get('text');
if(nextText.trim().length)
{
aText[aText.length] = nextText;
}
});
var sText = aText.join("\n---\n");
if(sText.match('\\[\\[verse\\]\\]'))
{
readingLookup();
}
if(sText.match('\\[\\[songs\\]\\]'))
{
oPanelSliders.show('chooseSong');
return;
}
if(sText.match('\\[\\[notices\\]\\]'))
{
noticesLookup();
}
if(sText.match('\\[\\[youtube\\]\\]'))
{
YouTubeLookup();
}
if(sText.match('\\[\\[video\\]\\]'))
{
VideoLookup();
}
if(sText.match('\\[\\[dvdclip\\]\\]'))
{
DVDClipLookup();
}
if(sText.match('\\[\\[presentation\\]\\]'))
{
PresentationLookup();
}
$('bodySetSlide').set('value', sText);
$('notesSetSlide').set('value', xmlnode.getElement('notes').get('text'));
$('titleSetSlide').set('value', xmlnode.getElement('title').get('text'));
$('nameSetSlide').set('value', xmlnode.getAttribute('name'));
};
var editSetItem = function(eLi)
{
var sCurrLiID = eLi.parentNode.retrieve('sCurrLiID');
if (eLi.getAttribute('id') !== sCurrLiID)
{
var eCurrEl = $(sCurrLiID);
if(eCurrEl)
{
eCurrEl.removeClass('highlight');
}
eLi.addClass('highlight');
var sType = eLi.retrieve('xmlnode').getAttribute('type');
if(sType == 'song')
{
editSetSong(eLi);
}
if(sType == 'custom' || sType == 'external')
{
editSetSlide(eLi);
}
}
//sCurrLiID = eLi.getAttribute('id');
eLi.parentNode.store('sCurrLiID', eLi.getAttribute('id'));
};
//This code initalizes the sortable list.
var oSlideGroups = new Sortables('.slidegroups', {
handle: '.drag-handle',
//This will constrain the list items to the list.
constrain: true,
//We'll get to see a nice cloned element when we drag.
clone: true,
snap:0,
//This function will happen when the user 'drops' an item in a new place.
onStart: function(eLi){editSetItem(eLi);}
});
//This is the code that makes the text input add list items to the <ul>,
//which we then make sortable.
var addListItem = function (sListID, val, xNode, sType){
var oList = $(sListID);
var i = $(sListID).childNodes.length + 1 ;
var li = new Element('li', {id: 'item-'+i, text:val});
//This handle element will serve as the point where the user 'picks up'
//the draggable element.
var handle = new Element('div', {id:'handle-'+i, 'class':'drag-handle list_'+sType});
handle.inject(li, 'top');
//Set the value of the form to '', since we've added its value to the <li>.
//Add the <li> to our list.
var sCurrLiID = oList.retrieve('sCurrLiID');
if(sCurrLiID)
{
li.inject(sCurrLiID, 'after');
}
else
{
li.inject(sListID, 'bottom');
}
li.store('xmlnode', xNode.clone(true));
//Do a fancy effect on the <li>.
li.highlight();
li.addEvent('click', function(e){editSetItem(this);});
//We have to add the list item to our Sortable object so it's sortable.
oSlideGroups.addItems(li);
return li;
};
$('btnSetSave').addEvent('click', function(e){
e.stop();
saveSet();
});
$('selectNewSetSlide').addEvent('change', function(e) {
var sSelectedType = this.get('value');
if(sSelectedType == "Video")
{
$("btnUploadFile").fade("in");
swfUploadFile.setOptions({
url: 'upload.php?type=video&'
//typeFilter: {
// 'Images (*.mov, *.mp4, *.avi)': '*.mov; *.jpeg; *.mp4; *.avi'
//},
});
}
else if(sSelectedType == "Presentation")
{
$("btnUploadFile").fade("in");
swfUploadFile.setOptions({
url: 'upload.php?type=presentation&'
//typeFilter: {
// 'Images (*.mov, *.mp4, *.avi)': '*.mov; *.jpeg; *.mp4; *.avi'
//},
});
}
else
{
$("btnUploadFile").fade("out");
}
});
$('selectSetChooser').addEvent('change', function(e) {
e.stop();
if(dirtyCheckStop())
{
return false;
}
//Get the value of the text input.
var sFile = this.get('value');
//The code here will execute if the input is empty.
if (!sFile || sFile == 'null') {
$('slidegroups').empty();
}
oSetFetchRequest.send({data:{church:CONST_CHOOSEN_CHURCH, file:sFile}});
});
$('btnSetDownload').addEvent('click', function(e) {
e.stop();
//Get the value of the text input.
var sFile = $('selectSetChooser').get('value');
//The code here will execute if the input is empty.
var sURL = 'fetch.php?type=set&file='+sFile; //Would prefer to use the XHR fuctions but can't work ouit how to use it to calculate the URL
window.location = sURL;
});
$('btnSetPrint').addEvent('click', function(e) {
e.stop();
//Get the value of the text input.
var sFile = $('selectSetChooser').get('value');
//The code here will execute if the input is empty.
var sURL = 'print.php?type=set&file='+sFile; //Would prefer to use the XHR fuctions but can't work ouit how to use it to calculate the URL
//Sexy.iframe(sURL);
window.location = sURL;
});
$('btnSongsPrint').addEvent('click', function(e) {
e.stop();
//Get the value of the text input.
var sFile = $('selectSetChooser').get('value');
//The code here will execute if the input is empty.
var sURL = 'printhtml.php?type=set&file='+sFile; //Would prefer to use the XHR fuctions but can't work ouit how to use it to calculate the URL
//console.log("sURL =", sURL);
window.open(sURL);
return false;
});
$('textChooseSong').addEvent('change', function(e) {
e.stop();
//Get the value of the text input.
var val = this.get('value');
oSongListFetchRequest.send({data:{church:CONST_CHOOSEN_CHURCH, q:val}});
});
$('btnChooseSong').addEvent('click', function(e) {
e.stop();
var sFile = $('selectChooseSong').get('value');
var iSelectedIndex = $('selectChooseSong').selectedIndex;
var eOption = $('selectChooseSong').options[iSelectedIndex];
var sName = eOption.get('text');
if (sFile)
{
sPath = sFile;
sPath = sPath.replace(sName, '');
var newSong = new Element('slide_group', {type: 'song', path:sPath, name:sName});
var newLi = addListItem('slidegroups', sName, newSong, 'song');
//oPanelSliders.show('none');
editSetItem(newLi);
setDirty();
}
});
$('btnChooseSongSearch').addEvent('click', function(e) {
e.stop();
var val = $('textChooseSong').get('value');
var sType = $('selectChooseSongSearchType').get('value');
oSongListFetchRequest.send({data:{church:CONST_CHOOSEN_CHURCH, q:val, s:sType}});
});
$('btnDeleteSetItem').addEvent('click', function(e) {
e.stop();
//var li = $(sCurrLiID);
var li = $($('slidegroups').retrieve('sCurrLiID'));
oSlideGroups.removeItems(li).destroy();
});
$('selectChooseSong').addEvent('change', function(e) {
e.stop();
var sFile = this.get('value');
if (!sFile || sFile == 'null') {
$('displayChooseSong').empty();
}
//oSongPreviewFetchRequest.send({data:{church:CONST_CHOOSEN_CHURCH, type:'song', file:sFile}});
oSongPreviewFetchRequest.send({data:{church:CONST_CHOOSEN_CHURCH, file:sFile}});
//$('selectSetChooser').empty();
});
$('btnNewSong').addEvent('click', function(e) {
e.stop();
oPanelSliders.show('chooseSong');
});
$('btnNewSetSlide').addEvent('click', function(e){
e.stop();
var sName = '';
var sNewSlideType = $('selectNewSetSlide').get('value');
var newSG = aBlankNodes[sNewSlideType].clone(true);
if (sNewSlideType == 'Blank')
{
sName = prompt('Name For New Slides');
if(sName === null)
{
return;
}
newSG.setAttribute('name', sName);
}
else
{
sName = newSG.getAttribute('name');
}
var li = addListItem('slidegroups', sName, newSG, 'custom');
editSetItem(li);
setDirty();
});
$('btnSaveSetSlide').addEvent('click', function(e) {
e.stop();
saveSetSlide();
});
$('btnSetNew').addEvent('click', function(e) {
e.stop();
if(dirtyCheckStop())
{
return false;
}
Sexy.prompt('<h1>Name For New Set.</h1>', getDefaultSetName(), { onComplete:
function(returnvalue) {
if(returnvalue)
{
oSetNewRequest.send({'data':{name:returnvalue}});
}
}
});
});
var showThinking = function(bShow)
{
if (bShow === null)
{
bShow = true;
}
if (bShow)
{
iThinking ++;
}
else
{
iThinking --;
}
if (iThinking > 0)
{
$('mainbody').getElements('body,div,select,input,textarea').addClass('thinking');
}
else
{
$('mainbody').getElements('body,div,select,input,textarea').removeClass('thinking');
}
};
|
/**
* UserController
*
* @description :: Server-side logic for managing Users
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
view_login : function(req, res) {
return res.view('user/login');
},
view_profile : function(req, res) {
return res.view('user/profile');
},
view_people : function(req, res) {
return res.view('user/people');
},
// Pega todos os usuarios
api_get: function(req, res) {
if (req.query.query) {
var query = {
or : [
{ name : { contains : req.query.query } },
{ email : { contains : req.query.query } }
]
};
} else {
var query = { };
}
User
.find(query)
.populate('following')
.populate('followers')
.exec(function(err, users) {
if (err || !users) {
console.log(err);
return res.status(400).json({});
}
return res.json(users)
});
},
// Cria um novo usuario
api_create: function(req, res) {
var user = {
name: req.body.name,
username: req.body.username,
email: req.body.email,
password: req.body.password
};
User
.create(user)
.exec(function(err, user) {
if (err || !user) {
console.log(err);
return res.status(400).json({});
}
return res.json(user)
});
},
// Procura por um usuario
api_find_by_id: function(req, res) {
User
.findOne({ id : req.params.id })
.exec(function(err, user) {
if (err || !user) {
console.log(err);
return res.status(404).json({});
}
return res.json(user)
});
},
// Altera um usuario
api_edit: function(req, res) {
var _user;
User
.findOne({ email : req.body.email, password : req.body.password })
.then(function(user) {
if (!user) {
return res.status(401).json({});
} else {
if (req.body.name) user.name = req.body.name;
if (req.body.username) user.username = req.body.username;
if (req.body.email) user.email = req.body.email;
if (req.body.description) user.description = req.body.description;
if (req.body.birthday) user.birthday = req.body.birthday;
if (req.body.picture) user.picture = req.body.picture;
if (req.body.password) user.password = req.body.password;
_user = user;
return user.save();
}
})
.then(function() {
return res.json(_user);
})
.catch(function(err) {
console.log(err);
return res.status(401).json({});
});
},
// Segue um usuario
api_follow: function(req, res) {
var _user;
User
.findOne({ id : req.params.uid })
.then(function(user) {
if (!user) {
return res.status(401).json({});
} else {
user.following.add(req.params.fid);
_user = user;
return user.save();
}
})
.then(function() {
return res.json(_user);
})
.catch(function(err) {
return res.status(401).json({});
});
},
// Segue um usuario
api_unfollow: function(req, res) {
var _user;
User
.findOne({ id : req.params.uid })
.then(function(user) {
if (!user) {
return res.status(401).json({});
} else {
user.following.remove(req.params.fid);
_user = user;
return user.save();
}
})
.then(function() {
return res.json(_user);
})
.catch(function(err) {
return res.status(401).json({});
});
},
// Remove um usuario
api_delete: function(req, res) {
var _user;
User
.destroy({ email : req.body.email, password : req.body.password })
.then(function() {
return res.json({});
})
.catch(function(err) {
console.log(err);
return res.status(401).json({});
});
},
// Faz login do usuario
api_login: function(req, res) {
User
.findOne({ email : req.body.email, password : req.body.password })
.exec(function(err, user) {
if (err || !user) {
console.log(err);
return res.status(401).json({});
}
return res.json(user);
});
},
// Importa dados de usuarios
api_import: function(req, res) {
var users = JSON.parse(req.body.users);
}
};
|
const db = require("../database/config.js");
const Data_Sensor = require("../models/data_sensor");
const List_Alat = require("../models/list_alat");
const Report = require("../models/report");
List_Alat.hasMany(Data_Sensor, {
as: "Data_Sensor2",
foreignKey: "listAlatId",
});
Data_Sensor.belongsTo(List_Alat, {
as: "List_Alat2",
foreignKey: "listAlatId",
});
List_Alat.hasMany(Report, { as: "Report2", foreignKey: "listAlatId" });
Report.belongsTo(List_Alat, { as: "List_Alat2", foreignKey: "listAlatId" });
async function ConvertToWeekly() {
const ID = await Report.findAll({
attributes: [[db.fn("DISTINCT", db.col("listAlatId")), "id"]],
raw: true,
});
for (let i = 0; i < ID.length; i++) {
const data = await Report.findAll({
where: {
listAlatId: ID[i].id,
},
raw: true,
});
// console.log(data);
let data_daily = data.filter((x) => x.tag == "daily");
// console.log("Panjang data_daily:", data_daily.length);
// console.log("data_daily:", data_daily);
if (data_daily.length == 7) {
console.log(data_daily);
await Report.destroy({
where: {
tag: "daily",
listAlatId: ID[i].id,
},
raw: true,
});
let report_weekly = {
temp_avg: avg(data_daily, "temp_avg"),
temp_min: min(data_daily, "temp_min"),
temp_max: max(data_daily, "temp_max"),
ppg_avg: avg(data_daily, "ppg_avg"),
ppg_min: min(data_daily, "ppg_min"),
ppg_max: max(data_daily, "ppg_max"),
ekg_avg: avg(data_daily, "ekg_avg"),
ekg_min: min(data_daily, "ekg_min"),
ekg_max: max(data_daily, "ekg_max"),
nivac_avg: avg(data_daily, "nivac_avg"),
nivac_min: min(data_daily, "nivac_min"),
nivac_max: max(data_daily, "nivac_max"),
tag: "weekly",
listAlatId: ID[i].id,
};
await Report.create(report_weekly);
}
// console.log("data dengan tag daily:", data_daily);
}
}
module.exports = ConvertToWeekly;
function min(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
// console.log(baru);
let min = Math.min.apply(Math, baru);
return min;
}
function max(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
// console.log(baru);
let max = Math.max.apply(Math, baru);
return max;
}
function avg(object, property) {
let baru = object.map((x) => {
// console.log(x[property]);
let temp = {
[property]: x[property],
};
return temp[property];
});
let sum = baru.reduce((total, value) => {
return total + value;
});
const count = baru.length;
let result = sum / count;
return Number(result.toFixed(2));
}
|
import {Random} from 'mockjs'
let employeeList = [];
for(let j = 0 ; j < 100; j++){
employeeList.push({
id:Random.increment(),
name: Random.cname(),
phone: Random.float(),
state: Random.float(0,1,0,0),
education: Random.ctitle(3, 5),
idCard: Random.id(),
sex: Random.float(0,1,0,0)
})
}
export {
employeeList
}
|
import React, { useContext } from "react";
import Settings from './context/settingsContext.js';
import ToDo from './components/todo/todo.js';
import Header from './components/header.js';
import 'normalize.css';
import '@blueprintjs/core/lib/css/blueprint.css'
import '@blueprintjs/icons/lib/css/blueprint-icons.css'
import SettingForm from './components/SettingForm.js';
import LoginForm from './components/login/login';
import { LoginContext } from './context/loginContext';
import { If, Else, Then } from "react-if";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Signup from "./components/login/signup.js";
export default function App(props) {
const context = useContext(LoginContext);
return (
<Router>
<Switch>
<If condition={context.loggedIn == true}>
{console.log(context)}
<Then>
<Settings>
<Route exact path="/">
<Header />
<ToDo />
</Route>
<Route path="/form">
<Header />
<SettingForm />
</Route>
</Settings>
</Then>
<Else>
<Route exact path="/">
<LoginForm />
</Route>
<Route path="/signup">
<Signup />
</Route>
</Else>
</If>
</Switch>
</Router>
);
}
|
import React from 'react'
const PreloadedWithDelay = () => (
<div className="PreloadedWithDelay">
<h1>Hello, PreloadedWithDelay!</h1>
</div>
)
export default PreloadedWithDelay
|
class NesefComponents{
constructor() {
console.log('constructor')
this.el = {}
// ************ BOTOES E LINKS *******************
this.el.btnShowAboutNesef = document.getElementById('btn-show-nesef')
this.el.btnShowLines = document.getElementById('btn-lines')
this.el.btnShowEvents = document.getElementById('bt-show-events')
// ############ ELEMENTOS BLOCOS DIV NESEF #############
this.el.jumbo = document.getElementById('jumbo')
this.el.logo = document.getElementsByClassName('imglogo')[0]
this.el.events = document.getElementById('nesef-events')
this.el.aboutNesef = document.getElementById('about-nesef')
this.el.lines = document.getElementById('research-lines')
this.elementsPrototype()
this.initEvents()
}
initEvents(){
console.log('initEvents')
this.el.btnShowEvents.addEventListener('click', e => {
this.el.events.show()
this.el.jumbo.hide()
this.el.logo.hide()
this.el.aboutNesef.hide()
this.el.lines.hide()
})
this.el.btnShowAboutNesef.addEventListener('click', e => {
if (this.el.aboutNesef.style.display === 'block'){
this.el.jumbo.show()
this.el.logo.show()
this.el.aboutNesef.hide()
this.el.lines.hide()
this.el.events.hide()
} else{
this.el.aboutNesef.show()
this.el.jumbo.hide()
this.el.logo.hide()
this.el.lines.hide()
this.el.events.hide();
}
})
this.el.btnShowLines.addEventListener('click', e => {
this.el.lines.show()
this.el.jumbo.hide()
this.el.logo.hide()
this.el.aboutNesef.hide()
this.el.events.hide();
})
}
elementsPrototype() {
Element.prototype.hide = function () {
this.style.display = 'none'
return this
}
Element.prototype.show = function () {
this.style.display = 'block'
return this
}
Element.prototype.toggle = function () {
this.style.display = (this.style.display === 'none') ? 'block' : 'none'
return this
}
Element.prototype.on = function (events, fn) {
events.split(' ').forEach(event => {
this.el.addEventListener(event, fn)
//(exemplo para digitar no console) app.el.btnNewContact.on('click mouseover dblclick', (event) => {console.log('evento do botão newContact >>> ', event.type)})
})
return this
}
}
}
window.nesefApp = new NesefComponents()
|
var $cegla="rgb(255, 102, 0)";
var $biezacy="rgb(255, 204, 102)";
$(document).ready(function() {
$('a').on( "click", function(){
$text=$(this).text();
$params="option="+$(this).attr('id');
// $params+="&NIP="+$('input[name=NIP]').val();
// $params+="&NAZWA="+$('input[name=NAZWA]').val().replace('&',' and ');
$(this).load("save.php",$params,function(){
$(this).text($text);
});
return true;
});
/*
$('a[href=#obsluga]').on( "click", function(){
scroll(0,0);
return false;
});
$('#myModal').on('shown.bs.modal', function () {
$('#iframeKontrahenci').focus();
});
$('input[name=NIP]')
.on( "focus", function(){szukanie=true;$('#uwaga').hide();})
.on( "blur", function(){szukanie=false;$('#uwaga').show();});
$('input[name=NAZWA]')
.on( "focus", function(){szukanie=true;$('#uwaga').hide();})
.on( "blur", function(){szukanie=false;$('#uwaga').show();});
$('select[name=magazyn]')
.on( "focus", function(){szukanie=true;$('#uwaga').hide();})
.on( "blur", function(){szukanie=false;$('#uwaga').show();});
*/
Menu(menu);
SubMenu(option);
});
function Menu($litera)
{
$("th a").parent().css("background-color","");
$("#"+$litera).focus().parent().css("background-color",$cegla);
SubMenu("a");
}
function SubMenu($litera)
{
//wszystkim cells, które mają kolor $biezacy, zgaś kolor
$("td").filter(function(){
return ($(this).css("background-color")==$biezacy);
}).css("background-color","");
//znajdź komórkę nagłówkową (th), która ma kolor $cegla i dla tego menu (np.: 1) zaznacz opcję $litera (np.: 1a), a komórce nadal kolor $biezacy
$("#"
+$("th").filter(function(){
return ($(this).css("background-color")==$cegla);
}).text()[0]+$litera).focus().parent().css("background-color",$biezacy);
}
function Prawo()
{
if($('a:focus').closest('div.table-responsive').parent().next('div').find('div.table-responsive th a').length>0)
{
$("th a").parent().css("background-color","");
$('a:focus').parent().css("background-color","").closest('div.table-responsive').parent().next('div').find('div.table-responsive th a').first().focus().parent().css("background-color",$cegla);
$('a:focus').closest('tr').next('tr').find('td a').focus().parent().css("background-color",$biezacy);
}
}
function Lewo()
{
if($('a:focus').closest('div.table-responsive').parent().prev('div').find('div.table-responsive th a').length>0)
{
$("th a").parent().css("background-color","");
$('a:focus').parent().css("background-color","").closest('div.table-responsive').parent().prev('div').find('div.table-responsive th a').first().focus().parent().css("background-color",$cegla);
$('a:focus').closest('table').find('tr').last().find('td a').focus().parent().css("background-color",$biezacy);
}
}
function Prev()
{
if($('a:focus').closest('tr').prev('tr').find('td a').length>0)
{
$('td').css("background-color","");
$('td a:focus').parent().css("background-color","").closest('tr').prev('tr').find('td a').focus().parent().css("background-color",$biezacy);
}
else if($('a:focus').closest('div.table-responsive').prev('div.table-responsive').find('td a').length>0)
{
$('td').css("background-color","");
$("th a").parent().css("background-color","");
$('a:focus').closest('div.table-responsive').prev('div.table-responsive').find('th a').first().parent().css("background-color",$cegla);
$('a:focus').closest('div.table-responsive').prev('div.table-responsive').find('td a').last().focus().parent().css("background-color",$biezacy);
}
else
{
Lewo();
}
}
function Next()
{
if($('a:focus').closest('tr').next('tr').find('td a').length>0)
{
$('td').css("background-color","");
$('a:focus').closest('tr').next('tr').find('td a').focus().parent().css("background-color",$biezacy);
}
else if($('a:focus').closest('div.table-responsive').next('div.table-responsive').find('td a').length>0)
{
$('td').css("background-color","");
$("th a").parent().css("background-color","");
$('a:focus').closest('div.table-responsive').next('div.table-responsive').find('th a').first().parent().css("background-color",$cegla);
$('a:focus').closest('div.table-responsive').next('div.table-responsive').find('td a').first().focus().parent().css("background-color",$biezacy);
}
else
{
Prawo();
}
}
function RedON($this,$title)
{
$this.attr("title","<font style='font-size:14pt'>"+$title+"</font>");
$this.tooltip({placement: "right", html: true}).tooltip("show");
$this.css("font-weight", "bold").css("color", "white").css("background-color", "red");
}
function RedOFF($this)
{
if ($this.css("background-color")=="rgb(255, 0, 0)")
{
$this.attr("title","");
$this.tooltip("destroy");
$this.parent().prev().css("font-weight", "").css("color", "");
$this.css("font-weight", "").css("color", "").css("background-color", "");
}
}
function RegulaZlamana($name,$title)
{
$this=$("input[name="+$name+"]");
RedON($this,$title);
}
function RegulaOK($name)
{
$this=$("input[name="+$name+"]");
RedOFF($this);
}
function GetKontrahentByNIP($name,$validType)
{
$value=$("input[name="+$name+"]").val();
$params="val="+$value+"&validType="+$validType;
$("input[name="+$name+"]").load("valid.php",$params,function(){
$wynik=$(this).text();
if ($wynik.substr(0,3)=="nie") {
RegulaZlamana($name,$wynik);
}
else
{
RegulaOK($name);
if($wynik!="")
{
var arr=$wynik.split(",");
$("input[name=NIP]").val(arr[0]);
$("input[name=NAZWA]").val(arr[1]);
if(arr[2]>1)
{
$('#myModal').modal('show');
$('#iframeKontrahenci').attr( 'src', function ( i, val ) { return val; });
}
}
}
});
}
function GetKontrahentByNAZWA($name,$validType)
{
$value=$("input[name="+$name+"]").val();
$params="val="+$value+"&validType="+$validType;
$("input[name="+$name+"]").load("valid.php",$params,function(){
$wynik=$(this).text();
if ($wynik.substr(0,3)=="nie") {
RegulaZlamana($name,$wynik);
}
else
{
RegulaOK($name);
if($wynik!="")
{
var arr=$wynik.split(",");
$("input[name=NIP]").val(arr[0]);
$("input[name=NAZWA]").val(arr[1]);
if(arr[2]>1)
{
$('#myModal').modal('show');
$('#iframeKontrahenci').attr( 'src', function ( i, val ) { return val; });
}
}
}
});
}
function valid($name,$validType)
{
if($validType=='NIP') {GetKontrahentByNIP($name,$validType);}
if($validType=='NAZWA') {GetKontrahentByNAZWA($name,$validType);}
return true;
}
|
function charCount(str) {
let obj = {}
for (let char of str) {
char = char.toLowerCase()
if (/[a-z0-9]/.test(char)) {
obj[char] = ++obj[char] || 1
}
}
return obj
}
console.log(charCount('aaa')) //{a:3}
console.log(charCount('Hi hello!')) //{h:2, i:1, e:1, l:2, o:1}
|
/**
* Created by Adam on 2016-04-05.
*/
(function (){
"use strict";
angular.module('blog')
.controller('OtherBloggersController', OtherBloggersController);
function OtherBloggersController($http,$scope, $routeParams, $log, $timeout,$location){
var obc = this;
obc.getUsers = function(){
$http.get("api/blogs/users") .then(function(response) {
obc.users = response.data;
}, function (reason){
//$location.url('/404');
});
};
obc.getUsers();
}
})();
|
import React from 'react';
import { mount } from 'enzyme';
import withHistoryActions from './withHistoryActions';
const mockedAction = jest.fn();
jest.mock('react-redux', () => ({
connect: () => Component => props => (
<Component
historyPush={(...args) => mockedAction('historyPush', ...args)}
historyPop={(...args) => mockedAction('historyPop', ...args)}
historyReplace={(...args) => mockedAction('historyReplace', ...args)}
{...props}
/>
),
}));
describe('connectors/withHistoryActions', () => {
// eslint-disable-next-line react/prop-types, require-jsdoc
const TestedComponent = props => <div>Other prop: {props.foo}</div>;
const ConnectedComponent = withHistoryActions(TestedComponent);
let component;
let props;
beforeEach(() => {
jest.clearAllMocks();
});
it('should render component with specified props', () => {
component = mount(<ConnectedComponent foo="bar" />);
props = component.find('TestedComponent').props();
expect(typeof props.historyPop).toBe('function');
expect(typeof props.historyPush).toBe('function');
expect(typeof props.historyReplace).toBe('function');
expect(props.foo).toBe('bar');
expect(mockedAction).not.toHaveBeenCalled();
});
describe('Actions', () => {
const actions = ['historyPush', 'historyPop', 'historyReplace'];
actions.forEach((action) => {
it(`should call ${action}`, () => {
const pathname = 'PATHNAME';
if (action === 'historyPop') {
props[action]();
expect(mockedAction).toHaveBeenCalledWith(action);
return;
}
props[action](pathname);
expect(mockedAction).toHaveBeenCalledWith(action, {
pathname,
});
});
it(`should call ${action} with options`, () => {
const pathname = 'PATHNAME';
const options = {
state: {},
};
if (action === 'historyPop') {
props[action]();
expect(mockedAction).toHaveBeenCalledWith(action);
return;
}
props[action](pathname, options);
expect(mockedAction).toHaveBeenCalledWith(action, {
pathname,
...options,
});
});
});
});
});
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as formActions from '../actions/form';
import HostSignup from '../components/HostSignup';
import Header from './Header';
import AudienceSignup from '../components/AudienceSignup';
import './Signup.css';
class Signup extends Component {
render() {
const {signupType, isFormValid} = this.props;
return (
<div>
<Header />
<div className="container">
<div className="innerContainer">
<h1 className="signupHeader">Sign up</h1>
<form className="signupTypeSelect">
<label htmlFor="host">(Performer)</label>
<input
className="radioSelect"
type="radio"
name="signupType"
value="host"
checked={signupType === 'host'}
onChange={event => this.onChange(event)}
/>
<label htmlFor="audience">Audience</label>
<input
className="radioSelect"
type="radio"
name="signupType"
value="audience"
onChange={event => this.onChange(event)}
/>
</form>
{signupType && signupType === 'host' && <HostSignup />}
{signupType && signupType === 'audience' && <AudienceSignup />}
</div>
</div>
</div>
);
}
onChange(event) {
this.props.actions.setSignupType(event.target.value);
}
}
function mapStateToProps(state, props) {
return {
signupType: state.form.get('signupType'),
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(formActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Signup);
|
var searchInsert = function(nums, target) {
let mid = Math.floor((nums.length / 2));
let mid_num = nums[mid];
if (nums.length <= 2) {
if (target <= nums[0]) {
return 0;
} else if (target <= nums[1]) {
return 1;
} else {
return nums.length;
}
}
if (mid_num === target) {
return mid
}
if (target < mid_num) {
return searchInsert(nums.slice(0, mid), target)
} else if (target > mid_num) {
return mid + searchInsert(nums.slice(mid), target)
}
};
console.log(searchInsert([1,3,5,7,9], 1))
|
import React from 'react';
import PropTypes from 'prop-types';
const SearchForm = ({ onChange }) => {
return (
<div className="row">
<div className="col-4">
<form action="" onSubmit={e => e.preventDefault()}>
<input onChange={onChange} type="text" className="form-control" placeholder="Search..." />
</form>
</div>
</div>
);
};
SearchForm.propTypes = {
onChange: PropTypes.func.isRequired
};
export default SearchForm;
|
var chai = require('chai');
var expect = chai.expect;
var React = require('react');
var sd = require('../skin-deep');
var $ = React.createElement;
describe("skin-deep", function() {
it("should render a ReactElement", function() {
var tree = sd.shallowRender($('h1', { title: "blah" }, "Heading!"));
var vdom = tree.getRenderOutput();
expect(vdom).to.have.property('type', 'h1');
expect(vdom.props).to.have.property('title', 'blah');
expect(vdom.props).to.have.property('children', 'Heading!');
});
it("should render a React Component", function() {
var Component = React.createClass({
render: function() {
return $('h1', { title: "blah" }, "Heading!");
}
});
var tree = sd.shallowRender($(Component));
var vdom = tree.getRenderOutput();
expect(vdom).to.have.property('type', 'h1');
expect(vdom.props).to.have.property('title', 'blah');
expect(vdom.props).to.have.property('children', 'Heading!');
});
it("should render function returning a ReactElement tree", function() {
var tree = sd.shallowRender(function() {
return $('h1', { title: "blah" }, "Heading!");
});
var vdom = tree.getRenderOutput();
expect(vdom).to.have.property('type', 'h1');
expect(vdom.props).to.have.property('title', 'blah');
expect(vdom.props).to.have.property('children', 'Heading!');
});
it("should render function building a component", function() {
var Component = React.createClass({
render: function() {
return $('h1', { title: "blah" }, "Heading!");
}
});
var tree = sd.shallowRender(function() {
return $(Component);
});
var vdom = tree.getRenderOutput();
expect(vdom).to.have.property('type', 'h1');
expect(vdom.props).to.have.property('title', 'blah');
expect(vdom.props).to.have.property('children', 'Heading!');
});
it("should render components with context using function", function() {
var Component = React.createClass({
contextTypes: { title: React.PropTypes.string },
render: function() {
return $('h1', { title: "blah" }, this.context.title);
}
});
var tree = sd.shallowRender(function() {
return $(Component);
}, { title: "Heading!" });
var vdom = tree.getRenderOutput();
expect(vdom).to.have.property('type', 'h1');
expect(vdom.props).to.have.property('title', 'blah');
expect(vdom.props).to.have.property('children', 'Heading!');
});
describe("findNode", function() {
var tree = sd.shallowRender(
$('div', {},
$('div', {className: "abc"}, "ABC"),
$('div', {id: "def"}, "DEF"),
$('object', {}, "objection!")
)
);
it("should find a node in tree by className", function() {
var abc = tree.findNode(".abc");
expect(abc).to.have.property('type', 'div');
expect(abc.props).to.have.property('children', 'ABC');
});
it("should find a node in tree by id", function() {
var abc = tree.findNode("#def");
expect(abc).to.have.property('type', 'div');
expect(abc.props).to.have.property('children', 'DEF');
});
it("should find a node in tree by tagname", function() {
var abc = tree.findNode("object");
expect(abc).to.have.property('type', 'object');
expect(abc.props).to.have.property('children', 'objection!');
});
it("should return false when node not found", function() {
expect(tree.findNode(".def")).to.eql(false);
expect(tree.findNode("#abc")).to.eql(false);
});
it("should throw on invalid selector", function() {
expect(function() {
tree.findNode(";huh?");
}).to.throw(/invalid/i);
});
});
describe("fillField", function() {
var tree;
var Component = React.createClass({
getInitialState: function() {
return { "username": "" };
},
getNickname: function() {
return React.findDOMNode(this.refs.nickname).value;
},
render: function() {
return $('form', {},
$('input', {
type: "text", id: "username",
value: this.state.username, onChange: function(event) {
this.setState({"username": event.target.value});
}.bind(this)
}),
$('input', {
type: "text", ref: "nickname", className: "nickname"
})
);
}
});
beforeEach(function() {
tree = sd.shallowRender($(Component));
});
it("should set value of controlled text field", function() {
expect(tree.findNode("#username").props)
.to.have.property("value", "");
tree.fillField("#username", "glenjamin");
expect(tree.findNode("#username").props)
.to.have.property("value", "glenjamin");
});
it.skip("should set value of uncontrolled text field", function() {
// Can this be done?
});
it("should throw if field not found", function() {
expect(function() {
tree.fillField("#losername", "not-glenjamin");
}).to.throw(/unknown/i);
});
});
describe("toString", function() {
it("should give HTML", function() {
var tree = sd.shallowRender($('h1', { title: "blah" }, "Heading!"));
expect('' + tree).to.eql('<h1 title="blah">Heading!</h1>');
});
});
});
|
import React from 'react';
import StarRatingComponent from 'react-star-rating-component';
export default React.createClass({
getInitialState: function(){
return ({
rating: 1;
})
},
onStarClick: function(name, value) {
this.setState({rating: value});
},
render: function() {
const { rating } = this.state;
return (
<div>
<h2>Rating from state: {rating}</h2>
<StarRatingComponent
name="rate1"
starCount={10}
value={rating}
onStarClick={this.onStarClick.bind(this)}
/>
</div>
);
}
})
|
import React from 'react';
import BlogListItem from './BlogListItem';
import { List } from '@material-ui/core';
const BlogList = ({ user, blogs, handleLike, handleDelete }) => (
<div>
<List>
{blogs && blogs.map((b) => (
<BlogListItem user={user} blog={b} key={b.title} handleLike={handleLike} handleDelete={handleDelete} />
))}
</List>
</div>
);
export default BlogList;
|
angular.module('AdSales').controller('NewSlsInvceStatusController', function ($scope, $location, locationParser, SlsInvceStatusResource ) {
$scope.disabled = false;
$scope.$location = $location;
$scope.slsInvceStatus = $scope.slsInvceStatus || {};
$scope.save = function() {
var successCallback = function(data,responseHeaders){
var id = locationParser(responseHeaders);
$location.path('/SlsInvceStatuss/edit/' + id);
$scope.displayError = false;
};
var errorCallback = function() {
$scope.displayError = true;
};
SlsInvceStatusResource.save($scope.slsInvceStatus, successCallback, errorCallback);
};
$scope.cancel = function() {
$location.path("/SlsInvceStatuss");
};
});
|
import api from 'api/api';
import store from 'store';
api.new('https://evening-citadel-85778.herokuapp.com/');
// api.new('http://10.68.0.45:8000/');
export function login(user, pass) {
return api.login(user, pass);
}
export function logout() {
return api.logout();
}
export function getUsers() {
return api.get('users/users/');
}
export function addNewUser(user, pass, cb){
return api.post('users/', {username:user, password:pass}).then(function(){
api.login(user, pass).then(function(){
cb();
}).catch(function(err){
console.log(err);
});
}).catch(function(err){
console.log(err);
});
}
export function getRandomFact(){
return api.get("randomfact/").then(function(resp){
store.dispatch({
type: 'GET_RANDOMFACT',
randomFact: resp.data.results
})
// console.log('Random Fact', resp.data.results);
})
}
export function getWhiskey(id){
return api.get("whiskey/" + id + "/").then(function(resp){
store.dispatch({
type: 'GET_WHISKEYITEM',
whiskeyItem: resp.data,
comparables: resp.data.comparables,
tags: resp.data.tags,
reviews: resp.data.reviews
})
})
}
export function postNewReview(obj){
// console.log('******ID To Post', obj.whiskey);
return api.post('review/', obj).then(function(resp){
getWhiskey(obj.whiskey)
});
}
var a = "";
var b = "";
var c = "";
export function getAllResults(obj){
// console.log('Object being sent:', obj);
if(obj.tag.length > 0){
if(obj.region.length > 0 || obj.price.length > 0){
a = "tags="+ obj.tag;
}
else if(obj.region.length === 0 && obj.price.length === 0){
a = "tags=" + obj.tag;
}
else {
a = "&tags=" + obj.tag;
}
}
else {
a = "";
}
if(obj.region.length > 0){
if(obj.tag.length === 0 && obj.price.length === 0){
b = "region="+ obj.region;
}
else {
b = "®ion=" + obj.region;
}
}
else {
b = "";
}
if(obj.price.length > 0){
if(obj.tag.length === 0 && obj.region.length === 0){
c = "price="+ obj.price;
}
else {
c = "&price=" + obj.price;
}
}
else {
c = "";
}
// console.log("In the getAllResults function: shoot/?" + a + b + c);
return api.get("shoot/?" + a + b + c).then(function(resp){
store.dispatch({
type: 'GET_LIKETAGS',
likes: a + b + c
})
// console.log('Likes:', a+b+c);
if(a === "" && b === "" && c === ""){
store.dispatch({
type: 'GET_TAGSEARCH',
tagSearch: [],
itemCount: 0,
containerInfo: []
})
store.dispatch({
type: 'CHANGE_SHOWMOREBUTTON',
showMoreButton: false
})
} else {
store.dispatch({
type: 'GET_TAGSEARCH',
tagSearch: resp.data.results,
itemCount: resp.data.count,
containerInfo: resp.data.results
})
if(resp.data.count >= 12) {
store.dispatch({
type: 'CHANGE_SHOWMOREBUTTON',
showMoreButton: true
})
}
else {
store.dispatch({
type: 'CHANGE_SHOWMOREBUTTON',
showMoreButton: false
})
}
}
})
}
export function getTagSearch(str){
// console.log("shoot/?tags=" + str);
return api.get("shoot/?" + str).then(function(resp){
store.dispatch({
type: 'GET_TAGSEARCH',
tagSearch: resp.data.results,
itemCount: resp.data.count,
containerInfo: resp.data.results
})
if(resp.data.count >= 12) {
store.dispatch({
type: 'CHANGE_SHOWMOREBUTTON',
showMoreButton: true
})} else {
store.dispatch({
type: 'CHANGE_SHOWMOREBUTTON',
showMoreButton: false
})
}
// console.log('After the call:', resp.data.results.length);
// console.log("tagCount:", resp.data.count);
})
}
export function getMore(num, str){
// console.log("shoot/?tags=" + str);
return api.get("shoot/?page=" + num + "&" + str).then(function(resp){
store.dispatch({
type: 'GET_MORE',
tagSearch: resp.data.results,
containerInfo: resp.data.results
})
// console.log('After the more call:', resp.data.results);
})
}
export function getGeneralSearch(str){
return api.get("searchbox/?terms=" + str).then(function(resp){
store.dispatch({
type: 'GET_TAGSEARCH',
tagSearch: resp.data,
// itemCount: resp.data.count,
containerInfo: resp.data
})
if(resp.data.length >= 12) {
store.dispatch({
type: 'CHANGE_SHOWMOREBUTTON',
showMoreButton: true
})} else {
store.dispatch({
type: 'CHANGE_SHOWMOREBUTTON',
showMoreButton: false
})
}
// console.log("tagSearch:", resp.data);
})
}
export function postSavedSearch(obj){
return api.post('tagsearch/', obj);
}
export function changeFavorite(obj){
return api.put('changeliked/', obj).then(function(resp){
getLikes();
});
}
export function getMyLikes() {
return api.get('likedwhiskey/').then(function(resp){
store.dispatch({
type: 'GET_LIKES',
likedwhiskey: resp.data.results
})
// console.log('My Likes:', resp.data.results)
})
};
export function getLikes() {
return api.get('likedwhiskey/').then(function(resp){
store.dispatch({
type: 'GET_LIKES',
likedwhiskey: resp.data.results,
containerInfo: resp.data.results
})
// console.log('Likes:', resp.data.results.length)
})
};
export function getSearches() {
return api.get('usersearches/').then(function(resp){
store.dispatch({
type: 'GET_SEARCHES',
usersearches: resp.data.results
})
// console.log('Searches:', resp.data)
})
};
export function deleteUserSearchBox(id){
return api.delete("tagsearch/" + id + "/").then(function(resp){
getSearches();
});
}
export function getSpecificItem(id){
return api.get('whiskey/' + id + '/').then(function(resp){
store.dispatch({
type: 'GET_ITEM',
list: resp.data
})
})
}
export function getSpecificItem(id){
return api.get('whiskey/' + id + '/').then(function(resp){
store.dispatch({
type: 'GET_ITEM',
list: resp.data
})
})
}
|
'use strict';
var config = require('config');
var shield = require('bookshelf-shield');
var shieldConfig = config.get('shieldConfig');
function shieldsUp(server) {
var models = {
Study: server.plugins.bookshelf.model('Study'),
Scan: server.plugins.bookshelf.model('Scan')
};
return shield({
models: models,
config: shieldConfig,
acl: server.plugins.relations
});
}
module.exports = shieldsUp;
|
class Character {
constructor(sprite, position) {
this.sprite = sprite;
this.position = position;
// this.image = imageSource;
// this.x = positionX;
// this.y = ((positionY - variationY)-imgHeight);
// this.width = imgWidth;
// this.height = imgHeight;
// this.dx = 0;
// this.dy = 0;
// this.dw = dWidth;
// this.dh = dHeight;
// this.countSprites = countSprites;
// this.dPosition = 0;
this.isOutScreen = false;
}
display() {
image(
this.sprite.image,
this.position.x, this.position.y,
this.sprite.width, this.sprite.height,
this.sprite.dx, this.sprite.dy,
this.sprite.dw, this.sprite.dh
);
}
animate() {
this.sprite.next();
// this.dPosition++;
// this.dx += this.dw;
// if(this.dPosition >= this.countSprites) {
// this.dx = 0;
// this.dy = 0;
// this.dPosition = 0;
// }
// else if (this.dx >= (this.LIMIT_WIDTH)) {
// this.dx = 0;
// this.dy += this.dh;
// if (this.dy > (this.LIMIT_HEIGHT)) {
// this.dx = 0;
// this.dy = 0;
// this.dPosition = 0;
// }
// }
}
}
|
var ProDevFactory = angular.module("ProDevFactory", ['ui.bootstrap']);
ProDevFactory.value('$calenderSelectedDate', { value: new Date() })
|
import React from 'react';
const Highlights = () => {
return (
<React.Fragment>
<h1>Highlights</h1>
</React.Fragment>
);
}
export default Highlights;
|
import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import NavigationItems from './NavigationItems';
import NavigationItem from './NavigationItem/NavigationItem';
import { wrap } from 'module';
configure({ adapter: new Adapter() });
describe('<NavigationItets />', () => {
let warpper;
beforeEach(() => {
warpper = shallow(<NavigationItems />);
})
it('should show two Navigation if is not Authintecated', () => {
expect(warpper.find(NavigationItem)).toHaveLength(2);
});
it('should show two Navigation if is Authintecated', () => {
warpper.setProps({ isAuth: true })
expect(warpper.find(NavigationItem)).toHaveLength(3);
});
it('should be there when is Authenticated', () => {
warpper.setProps({ isAuth: true });
expect(warpper.contains(<NavigationItem link="/logout">Logout</NavigationItem>)).toEqual(true);
})
});
|
const http = require('http');
const PORT = 5000;
const ip = 'localhost';
const server = http.createServer((request, response) => {
// const { method, url } = request;
let headers = defaultCorsHeader;
if(request.method === 'OPTIONS'){
response.writeHead(200, headers);
response.end();
}
if(request.method === 'POST'){
let body = [];
request
.on("data", chunk => {
body.push(chunk);
console.log(chunk);
})
.on("end", () => {
console.log(data);
body = Buffer.concat(body).toString();
response.writeHead(200, headers);
if(request.url === '/upper'){
response.end(body.toUpperCase());
// console.log(body);
}else if(request.url === '/lower'){
response.end(body.toLowerCase());
// console.log(body);
}
})
}else{
response.writeHead(404, headers);
response.end();
}
console.log(
`http request method is ${request.method}, url is ${request.url}`
);
// response.writeHead(200, headers);
// response.end('hello mini-server sprints');
});
server.listen(PORT, ip, () => {
console.log(`http server listen on ${ip}:${PORT}`);
});
const defaultCorsHeader = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
'access-control-allow-headers': 'content-type, accept',
'access-control-max-age': 10
};
|
/**
* @file san-xui/x/forms/ComboForm.js
* @author leeight
*/
import _ from 'lodash';
import {DataTypes, defineComponent} from 'san';
import {create} from '../components/util';
import {asInput} from '../components/asInput';
import Button from '../components/Button';
import {asForm} from './asForm';
import StaticItem from './StaticItem';
const cx = create('ui-combo');
/* eslint-disable */
const template = `<div class="{{mainClass}}" style="{{mainStyle}}">
<template s-if="!preview">
<div s-if="multiple">
<div class="${cx('item')}" s-for="v, i in formData">
<ui-form form-data="{=v=}" />
<ui-button icon="minus" on-click="removeElement(i)" />
</div>
<ui-button s-if="btnVisible" icon="plus" on-click="addElement" />
</div>
<div class="${cx('item')}" s-else>
<ui-form form-data="{=formData=}" />
</div>
</template>
<template s-else>
<slot name="preview">
<table width="100%" cellpadding="0" cellspacing="0">
<tbody>
<template s-if="multiple">
<tr s-for="item in value">
<td s-for="col in previewCols">
<ui-static
mapper="{{col.mapper}}"
datasource="{{col.datasource}}"
value="{{item[col.name]}}"/>
</td>
</tr>
</template>
<template s-else>
<tr>
<td s-for="col in previewCols">
<ui-static
mapper="{{col.mapper}}"
datasource="{{col.datasource}}"
formData="{{formData[col.name]}}"/>
</td>
</tr>
</template>
</tbody>
</table>
</slot>
</template>
</div>`;
/* eslint-enable */
const ComboForm = defineComponent({
template,
dataTypes: {
/**
* 是否预览状态
* @default false
*/
preview: DataTypes.bool,
/**
* 预览时显示的数据项。如果没有配置,会默认使用的controls变量的 name datasource 参数。
* 如果自定义preview slot, 该参数可做扩展。
* @default null
*/
previewCols: DataTypes.array,
/**
* 是否支持添加多项目
* @default false
*/
multiple: DataTypes.bool,
/**
* 单行模式
* @default true
*/
inline: DataTypes.bool,
/**
* 可以输入的数据项
*/
controls: DataTypes.array,
/**
* 最多的数量
* @default Infinity
*/
max: DataTypes.number,
/**
* 最少的数量
* @default 0
*/
min: DataTypes.number,
/**
* ComboForm 输入的内容
* @bindx
*/
value: DataTypes.any
},
computed: {
mainClass() {
const klass = cx.mainClass(this);
const inline = this.data.get('inline');
if (inline) {
klass.push(cx('inline'));
klass.push(cx('x-inline'));
}
return klass;
},
mainStyle() {
return cx.mainStyle(this);
},
btnVisible() {
const formData = this.data.get('formData');
const max = this.data.get('max');
const min = this.data.get('min');
const size = formData && formData.length;
return size >= min && size < max;
}
},
initData() {
return {
preview: false,
min: 0,
max: Infinity,
multiple: false,
inline: true,
value: null,
previewCols: null,
controls: []
};
},
inited() {
let {controls, multiple, value, previewCols} = this.data.get();
if (multiple) {
if (!_.isArray(value)) {
this.data.set('value', []);
}
}
else {
if (!_.isPlainObject(value)) {
this.data.set('value', {});
}
}
if (!previewCols) {
this.data.set('previewCols', _.map(controls, item => _.pick(item, ['name', 'datasource'])));
}
const Component = asForm({controls});
this.components = {
'ui-button': Button,
'ui-static': StaticItem,
'ui-form': Component
};
this.data.set('formData', _.cloneDeep(this.data.get('value')));
// 此改动是处理combo类型为数组时, 控件没有填写值时,value值为[{}],
this.watch('formData', formData => {
const value = _.isArray(formData) ? _.reject(formData, _.isEmpty) : formData;
this.data.set('value', value);
this.fire('change', {value});
});
},
attached() {
// TODO(leeight) 子表单的验证逻辑
// TODO(chenbo09) combo目前有二重校验(1, 3)。可增加一个行校验(待出现实际需求时,目前暂无)。
// 理想的校验如下:改动combo中组件的值(包括新增和删除), 依次触发触发3, 2 ,1层级的校验,每层校验会使用下级校验的结果,比如1,2
// 的校验 是 自身 + 下级校验的组合。
// 行校验具体实现:通过diff当前的 value 和 formData,找到被改动的记录index。
// 执行自己的validateForm方法并ref到具体的form查看其校验结果,综合后显示error在form行的下一行。
// 1. combo顶层的校验。value是整个combo的值
// 2. combo行校验。仅仅在multiple模式下有效 value值是整个数组中的某一个对象,也就是combo中的子form。
// 3. 组件级自身校验,这个在controls中为每个组件配置即可,value是控件值。
// 目前的问题:
// 1. combo在顶层并没有机制去调用下层的校验。必须到修改了combo中的具体组件值时才能监听到事件,开始校验。
// 2. 在combo顶层的rules可以自定义较为复杂的校验,只是只有一个提示的地方。上述方案是否有必要?
},
addElement() {
this.data.push('formData', {});
},
removeElement(i) {
this.data.removeAt('formData', i);
}
});
export default asInput(ComboForm);
|
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableOpacity
} from 'react-native';
export default class BuninessNav extends Component {
render() {
return (
<View style={styles.container}>
<TouchableOpacity activeOpacity={0.5}>
<Image source={require("../../images/icon_shop_local.png")} style={styles.iconStyle} />
</TouchableOpacity>
<Text style={styles.txtStyle}>{this.props.txt}</Text>
<TouchableOpacity activeOpacity={0.5}>
<Image source={require("../../images/icon_shop_search.png")} style={styles.iconStyle} />
</TouchableOpacity>
</View>
);
}
}
var styles = StyleSheet.create({
container:{
height:44,
// backgroundColor:"#fd4b1f",
flexDirection:"row",
justifyContent:"space-between",
alignItems:"center",
},
txtStyle:{
fontSize:20,
color:"#282828",
},
iconStyle:{
width:30,
height:30,
marginLeft:15,
marginRight:15,
}
});
module.exports = BuninessNav;
|
import React from 'react';
import './Nav.scss';
import {Link as LinkRoute} from 'react-router-dom';
import { HashLink as Link } from 'react-router-hash-link';
export default function Nav() {
return (
<>
<div className="header-login">
<LinkRoute className="link-item" to='/logowanie'>Zaloguj</LinkRoute>
<LinkRoute className='link-item link-reg' to='/rejestracja'>Załóż konto</LinkRoute>
</div>
<nav className="nav-header">
<ul>
<li><Link to ="/#start" className="nav-link">Start</Link></li>
<li><Link to ="/#what-is-about" className="nav-link">O co chodzi?</Link></li>
<li><Link to ="/#about-us" className="nav-link">O nas</Link></li>
<li><Link to ="/#who-get-help" className="nav-link">Fundacje i organizacje</Link></li>
<li><Link to ="/#contact-us" className="nav-link">Kontakt</Link></li>
</ul>
</nav>
</>
)
}
|
const test = require('tape');
const orderBy = require('./orderBy.js');
test('Testing orderBy', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof orderBy === 'function', 'orderBy is a Function');
const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }];
t.deepEqual(orderBy(users, ['name', 'age'], ['asc', 'desc']), [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}], "Returns a sorted array of objects ordered by properties and orders.");
t.deepEqual(orderBy(users, ['name', 'age']), [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}], "Returns a sorted array of objects ordered by properties and orders.");
//t.deepEqual(orderBy(args..), 'Expected');
//t.equal(orderBy(args..), 'Expected');
//t.false(orderBy(args..), 'Expected');
//t.throws(orderBy(args..), 'Expected');
t.end();
});
|
function jpage (data, callback) {
console.log('jpage');
var indexPage = data.index,
totalPages = data.total,
paginationNumbers = 0,
jpageResponse = [];
console.log(indexPage, totalPages);
function paginationObj (start, end) {
var pagination = [];
if (start > 10) {
pagination.push({
value: indexPage - 1,
label: '<<'
});
}
for (var i = start; i <= end; i++) {
var v = i;
indexPage == i && (v = '#');
pagination.push({
value: v,
label: i
});
}
if (end < totalPages) {
pagination.push({
value: end + 1,
label: '>>'
});
}
return pagination;
}
if (totalPages < 10 ) {
jpageResponse = paginationObj(paginationNumbers+1, totalPages);
callback(jpageResponse);
return;
}
var numberIndexPage = Math.floor(indexPage/10), numberTotalPages = Math.floor(totalPages/10);
if ( numberIndexPage != numberTotalPages ) {
if (indexPage%10 == 0) {
paginationNumbers = (numberIndexPage-1) * 10;
jpageResponse = paginationObj(paginationNumbers+1, paginationNumbers+10);
} else {
paginationNumbers = (numberIndexPage) * 10;
jpageResponse = paginationObj(paginationNumbers+1, paginationNumbers+10);
}
} else {
if (indexPage%10 == 0) {
paginationNumbers = (numberIndexPage-1) * 10;
jpageResponse = paginationObj(paginationNumbers+1, paginationNumbers+10);
} else {
var modSobrante = totalPages%10;
jpageResponse = paginationObj(((numberIndexPage*10 )+1), (modSobrante+(numberIndexPage*10)));
}
}
callback(jpageResponse);
}
|
import React from 'react';
import { Container, Table, Header, Input, Message } from 'semantic-ui-react';
import swal from 'sweetalert';
import TreatmentLogItem from '../components/TreatmentLogItem';
import TreatmentLogPlan from '../components/TreatmentLogPlan';
/** Renders a table containing all of the Notification documents. Use <NotificationItem> to render each row. */
class TreatmentLog extends React.Component {
submitID() {
swal('Success', 'This should populate the treatment table with the patient current treatment and the log table with the list of the days they have taken the treatment for the patient associated with the inputted patient ID.', 'success');
}
// Render the page once subscriptions have been received.
render() {
return (
<Container>
<Header as="h2" textAlign="center">Treatment Log</Header>
<Message>
<Message.Header>Note for Prototype Purposes</Message.Header>
<p>
{/* eslint-disable-next-line max-len */}
This page is supposed to auto-populate data when the submit button is pressed and a valid patient ID is entered. Since the back-end is not implemented yet, pressing submit will populate an example log of a patient. Please press the submit button once to show the example treatment plan and example log of a patient.
</p>
</Message>
<Input action={{ icon: 'search', onClick: () => this.submitID() }} placeholder='Enter Patient ID' />
<Header as="h3" textAlign="center">Patient Treatment Plan</Header>
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Start Date</Table.HeaderCell>
<Table.HeaderCell>End Date</Table.HeaderCell>
<Table.HeaderCell>Frequency</Table.HeaderCell>
<Table.HeaderCell>Instructions</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<TreatmentLogPlan/>
</Table.Body>
</Table>
<Header as="h3" textAlign="center">Patient Log</Header>
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Date</Table.HeaderCell>
<Table.HeaderCell>Treatment Taken</Table.HeaderCell>
</Table.Row>
</Table.Header>
<TreatmentLogItem/>
</Table>
</Container>
);
}
}
// withTracker connects Meteor data to React components. https://guide.meteor.com/react.html#using-withTracker
export default TreatmentLog;
|
/*
* @Author: xr
* @Date: 2021-03-20 12:22:32
* @LastEditors: xr
* @LastEditTime: 2021-03-20 22:08:15
* @version: v1.0.0
* @Descripttion: 功能说明
* @FilePath: \ui\src\libs\store\index.js
*/
import { useStore, mapState, mapActions } from 'vuex'
export const myMapStates = (...args) => {
const store = useStore();
const states = mapState(...args);
for (let j in states) {
states[j] = states[j].bind({ $store: store })();
}
return states;
}
export const myMapActions = (...args) => {
const store = useStore();
const actions = mapActions(...args);
for (let j in actions) {
actions[j] = actions[j].bind({ $store: store });
}
return actions;
}
|
$(document).ready(function() {
$('#accpengajuan').DataTable();
} );
|
// copy from ember-cli
(function() {
/* global define, Ember */
define('ember', [], function() {
"use strict";
require('ember-metal');
require('ember-runtime');
require('ember-handlebars-compiler');
require('ember-handlebars');
require('ember-views');
require('ember-routing');
require('ember-application');
require('ember-extension-support');
// ensure that the global exports have occurred for above
// required packages
requireModule('ember-metal');
requireModule('ember-runtime');
requireModule('ember-handlebars');
requireModule('ember-views');
requireModule('ember-routing');
requireModule('ember-application');
requireModule('ember-extension-support');
// do this to ensure that Ember.Test is defined properly on the global
// if it is present.
if (Ember.__loader.registry['ember-testing']) {
requireModule('ember-testing');
}
return {
'default': Ember
};
});
})();
|
import { HttpStatusCode } from "solid-start/server";
import { A } from "solid-start";
import ErrorMessage from "~/components/ErrorMessage";
export default () => (
<>
<HttpStatusCode code={404} />
<ErrorMessage
message={
<>
404 Page Not Found
<br />
<A href="/">Go Back to the Home Page</A>
</>
}
/>
</>
);
|
'use strict';
var React = require('react-native');
var {StyleSheet} = React;
var colors = StyleSheet.create({
white: {
color: '#fff',
},
blue: {
color: '#09c',
},
grey: {
color: '#ccc',
},
});
module.exports = colors;
|
import React from 'react'
import ProjectsContext from '../contexts/ProjectsContext'
import { Player } from 'video-react';
import './ArchiveList.scss'
export default class ArchiveList extends React.Component {
static contextType = ProjectsContext
state = {
previewAsset: null
}
componentDidMount() {
window.scrollTo(0, 0)
}
updatePreview = (e) => {
e.preventDefault()
let previewAsset = this.context.archiveProjects.filter(proj => proj.title === e.currentTarget.dataset.id)
previewAsset = previewAsset[0]
this.setState({
previewAsset
},
() => {
console.log(this.state.previewAsset.cover.fields.file.url);
})
}
clearPreview = (e) => {
this.setState({
previewAsset: null
})
}
render() {
let archiveList = []
if (this.context.archiveProjects) {
archiveList = this.context.archiveProjects.map(proj => {
let technologyList = proj.technology.map(tech => {
return (
<li className='stack' key={tech}>{tech}</li>
)
})
return (
<tr className='archive-table-project' key={proj.title} onMouseEnter={this.updatePreview} onMouseLeave={this.clearPreview} data-id={proj.title}>
<td>
<a href={proj.url} target={'_blank'} rel={'noreferrer noopener'}>
<ul className='tech-stack'>
{technologyList}
</ul>
</a>
</td>
<td>
<a href={proj.url} target={'_blank'} rel={'noreferrer noopener'}>
{proj.title}
</a>
</td>
<td>
<a href={proj.url} target={'_blank'} rel={'noreferrer noopener'}>
{proj.year}
</a>
</td>
</tr>
)
})
}
let previewAsset
if (this.state.previewAsset) {
if (this.state.previewAsset.cover.fields.file.contentType === 'image/jpeg' || this.state.previewAsset.cover.fields.file.contentType === 'image/png' || this.state.previewAsset.cover.fields.file.contentType === 'image/gif') {
previewAsset = (<img src={`https:${this.state.previewAsset.cover.fields.file.url}`} className={'preview-img'} alt={'Project Preview'}/>)
} else {
previewAsset = (
<Player
playsInline
muted={true}
loop={true}
autoPlay={true}
className={'preview-video'}
src={this.state.previewAsset.cover.fields.file.url}
/>
)
}
}
return (
<main className='archive-list'>
<h2>Archive</h2>
<div id={'preview'}>
{this.state.previewAsset
? (
<>
{previewAsset}
</>
)
: ''}
</div>
<table className='archive-table'>
<thead>
<tr className='archive-table-title'>
<th className='tech-header'>Technology</th>
<th className='client-header'>Client</th>
<th className='year-header'>Year</th>
</tr>
</thead>
<tbody>
{archiveList}
</tbody>
</table>
</main>
)
}
}
|
import React from 'react';
import {
Text,
ListView,
TouchableHighlight,
} from 'react-native';
import {
PComponent,
} from 'rnplus';
import {
STYLE_ITEM,
STYLE_SCROLL_VIEW,
} from './styles.js';
class List extends PComponent {
styles = {
list: STYLE_SCROLL_VIEW,
};
render() {
return (
<ListView
class="list"
contentContainerStyle={{ paddingBottom: 20 }}
dataSource={this.props.dataSource}
renderRow={item => (<ListItem item={item} onPressContext={this} />)}
/>
);
}
}
class ListItem extends PComponent {
constructor(props) {
super(props);
let className = 'item list-item';
if (props.item.gap) {
className += ' item-gap';
}
this.className = className;
this.onPress = props.item.onPress.bind(this.props.onPressContext);
}
styles = {
item: STYLE_ITEM,
'list-item': {
justifyContent: 'center',
},
'item-gap': {
marginTop: 20,
},
};
render() {
const item = this.props.item;
return (
<TouchableHighlight
class={this.className}
underlayColor="#D9D9D9"
onPress={this.onPress}
>
<Text
style={{
color: 'black',
}}
>
{item.text}
</Text>
</TouchableHighlight>
);
}
}
export default List;
|
/* eslint-disable no-alert */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-nested-ternary */
import React, { useState } from 'react';
import {
Container,
Row,
Col,
DropdownButton,
Dropdown,
Button,
Modal,
Alert,
} from 'react-bootstrap';
const ShoppingCart = ({
styleSkus,
productName,
styleName,
originalPrice,
salePrice,
}) => {
const [cart, setCart] = useState({});
const [selectedSize, setSelectedSize] = useState(null);
const [selectedQuantity, setSelectedQuantity] = useState(0);
const [qtyIdx, setQtyIdx] = useState(0);
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
let inStock = true;
for (const sku in styleSkus) {
if (styleSkus[sku] > 0 in styleSkus || sku === 'null') {
inStock = false;
}
}
const clickedAndSelectSku = (size, quantity) => {
setSelectedSize(size);
setSelectedQuantity(quantity);
};
const availableQuantity = selectedQuantity >= 15 ? 15 : selectedQuantity;
const quantityList = [];
for (let i = 0; i < availableQuantity; i += 1) {
quantityList.push(i + 1);
}
const selectSizeTitle = () => selectedSize || (inStock ? 'SELECT SIZE' : 'OUT OF STOCK');
const selectQuantityTitle = () => (quantityList.length === 0
? '-'
: !qtyIdx
? 1
: qtyIdx > quantityList.length
? quantityList[quantityList.length - 1]
: qtyIdx < quantityList.length
? qtyIdx
: qtyIdx);
const displayedPrice = salePrice === '0' ? originalPrice : salePrice;
const cartItem = {
product: productName,
style: styleName,
price: displayedPrice,
size: selectedSize,
quantity: qtyIdx,
};
const handleQuantitySelect = (eKey) => {
setQtyIdx(quantityList[eKey]);
if (qtyIdx === undefined) {
cartItem.quantity = 1;
}
};
if (cartItem.quantity === undefined || cartItem.quantity === 0) {
cartItem.quantity = 1;
}
// if (cartItem) {
// console.log('cartItem: ', cartItem);
// }
const handleSelectSize = () => React.Children.toArray(
Object.entries(styleSkus).map(
(size, quantity) => quantity > 0 && (
<Dropdown.Item
onClick={() => clickedAndSelectSku(size[0], quantity)}
>
{size[0]}
</Dropdown.Item>
),
),
);
const handleSelectQuantity = () => quantityList.map((quantity, i) => (
<Dropdown.Item eventKey={i} onSelect={handleQuantitySelect}>
{quantity}
</Dropdown.Item>
));
const handleShoppingCart = () => {
if (!cartItem.size) {
return alert('Please select a size');
}
setCart(cartItem);
return handleShow();
};
// if (Object.entries(cart).length > 0) {
// console.log('cart: ', cart);
// }
return (
<Container className="shopping-cart-container">
<Row>
<Col md={4}>
<DropdownButton
bsPrefix="cart-select-size"
id="dropdown-basic-button dropdown-chevron"
title={selectSizeTitle()}
>
{handleSelectSize()}
</DropdownButton>
</Col>
<Col md={2}>
<DropdownButton
bsPrefix="cart-select-quantity"
id="dropdown-basic-button"
title={selectQuantityTitle()}
>
{handleSelectQuantity()}
</DropdownButton>
</Col>
</Row>
<Row>
<Col xs={6}>
<Button
bsPrefix="shopping-cart-btn"
variant="primary"
onClick={() => handleShoppingCart()}
>
<span>ADD TO BAG</span>
</Button>
<Modal
show={show}
onHide={handleClose}
backdrop="static"
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
keyboard={false}
>
<Modal.Header closeButton>
<Modal.Title>Shopping Cart</Modal.Title>
</Modal.Header>
<Modal.Body>
{`Product: ${cartItem.product}, Style: ${cartItem.style}, Size: ${cartItem.size}, QTY: ${cartItem.quantity}, Total: ${cartItem.price}, `}
</Modal.Body>
<Modal.Footer>
<Button
bsPrefix="shopping-cart-modal-cancel"
variant="secondary"
onClick={handleClose}
>
CANCEL
</Button>
<Button
variant="primary"
bsPrefix="shopping-cart-modal-add"
onClick={handleClose}
>
ADD
</Button>
</Modal.Footer>
</Modal>
</Col>
</Row>
</Container>
);
};
export default ShoppingCart;
|
import axios from 'axios'
import AuthService from '@/services/auth.service'
class ApiService {
constructor () {
let service = axios.create({})
service.interceptors.request.use((config) => {
if (!config.headers.hasOwnProperty('token')) {
return AuthService.requestToken().then((data) => {
config.headers.common['token'] = data.token
AuthService.saveToken(data.token)
return Promise.resolve(config)
})
} else {
return Promise.resolve(config)
}
})
// Retry if token expired
service.interceptors.response.use(null, (error) => {
if (error.config && error.response && error.response.status === 401) {
return AuthService.refreshToken().then((data) => {
error.config.headers.token = data.token
AuthService.saveToken(data.token)
return service.request(error.config)
})
}
})
this.service = service
}
get (path) {
return this.service.get(path)
}
}
export default new ApiService()
|
import React, { Component } from "react";
import axios from "axios";
export default class CreateJob extends Component {
constructor(props) {
super(props);
this.state = {
jobs: [],
flag: false,
searchedJobs: [],
apiLoaded: false,
jobTitle: ["Software Engineer", "Computer Science", "Architecture", "DJ"],
location: [
"New York",
"New Jersey",
"Conneticut",
"Virginia",
"Orlando",
"LA",
"Texas"
],
formData: {
jobTitle: null,
location: null,
jobDescription: null,
jobRequirement: null,
salary: null,
jobId: null
},
isClicked: false,
recruiterId: null
};
}
handleChange = event => {
let value = event.target.value;
let name = event.target.name;
this.setState(prevState => ({
formData: {
...prevState.formData,
[name]: value
}
}));
};
submitJob = async e => {
e.preventDefault();
try {
axios.post(`http://localhost:3001/jobs/${this.state.recruiterId}`, {
jobTitle: this.state.formData.jobTitle,
jobId: this.state.formData.jobId,
jobDescription: this.state.formData.jobDescription,
jobRequirements: this.state.formData.jobRequirements,
location: this.state.formData.location,
salary: this.state.formData.salary
});
} catch (e) {
console.error(e);
}
};
componentDidMount = e => {
this.setState({
recruiterId: this.props.currentUser.id
});
};
render() {
return (
<div>
<h1>Create Job</h1>
<form onSubmit={e => this.submitJob(e)} className="jobCreateForm">
<select
className="jobTitle"
onChange={this.handleChange}
name="jobTitle"
type="text"
placeholder="Job Title"
defaultValue="Job Title"
>
<option disabled>Job Title</option>
{this.state.jobTitle.map(job => (
<>
<option value={job}>{job}</option>
</>
))}
</select>
<input
type="textarea"
name="jobId"
value={this.state.text}
onChange={this.handleChange}
placeholder="Job ID"
id="jobId"
required
/>
<input
type="textarea"
name="jobDescription"
value={this.state.text}
onChange={this.handleChange}
placeholder="Job Description"
id="jobDescription"
required
/>
<input
type="textarea"
name="jobRequirements"
value={this.state.text}
onChange={this.handleChange}
placeholder="Job Requirements"
id="jobRequirement"
required
/>
<select
className="location"
name="location"
type="text"
placeholder="location"
defaultValue="City"
>
<option disabled>City</option>
{this.state.location.map(city => (
<>
<option>{city}</option>
</>
))}
</select>
<input
type="textarea"
name="salary"
value={this.state.text}
onChange={this.handleChange}
placeholder="Salary"
id="jobSalary"
required
/>
<input type="submit" id="jobSubmit" />
</form>
</div>
);
}
}
|
const express = require('express');
const http = require('http');
const io = require('socket.io');
const path = require('path');
var serialPort = require("serialport");
if (process.argv.length != 3) {
//console.log("usage: \"node app.js <serial_port>\"");
console.log("usage: "+ process.argv[2]);
process.exit(0);
}
const config = {
port: 3000
};
const app = express();
const httpServer = http.createServer(app);
const socketsOptions = {
serveClient: false
};
const socketsServer = io(httpServer, socketsOptions);
const webRoot = path.resolve(__dirname, '../client/build');
app.use("/", express.static(webRoot));
//initialize serial connection with a single byte parser
const ByteLength = serialPort.parsers.ByteLength;
var serialConnection = new serialPort(process.argv[2], {
baudRate: 9600
});
const parser = serialConnection.pipe(new ByteLength({length: 8}));
serialConnection.open(function () {
console.log('open');
serialConnection.on('data', function(data) {
var buff = new Buffer(data);
console.log('data received: ' + buff.toString('utf8'));
socketsServer.emit('event', buff.toString('utf8'));
});
});
//error handling
serialConnection.on("error", function () {
console.error("Can't establish serial connection with " + process.argv[2]);
process.exit(1);
});
/*
let num = 0;
const sendMessage = () => {
socketsServer.emit('event', 'button 1 clicked')
}
*/
httpServer.listen(config.port, () => console.log(`Server listening on port ${config.port}`));
//sendMessage();
/* how to let the clients know of an event
const theEvent = {};
socketsServer.emit('event', theEvent);
*/
|
window.onload = function () {
showAvailableSurveys();
showLogoutAndProfile();
getUser();
showUnavailableSurveys();
};
var json;
function showAvailableSurveys() {
var xhr = new XMLHttpRequest();
var token = $.cookie("token");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var surveyIds = xhr.responseText.substring(1, xhr.responseText.length - 1);
surveyIds = surveyIds.split(',').map(x => +x);
if (surveyIds[0] !== 0) {
var html = "<div class=\"main-panel border rounded p-4\">";
for (var i in surveyIds) {
getTitleAndDescription(surveyIds[i]);
var topic = json.topic;
var description = json.description;
html += "<div class=\"card mr-2 mb-2\" style=\"width: 18.2rem; float: left;\">\n" +
" <div class=\"card-body\">\n" +
" <h5 class=\"card-title\">" + topic + "</h5>\n" +
" <p class=\"card-text\">" + description + "</p>\n" +
" <button class=\"btn btn-dark\" onclick='goToSurvey(" + surveyIds[i] + ")'>Open survey</button>\n" +
" </div>\n" +
"</div>";
}
html += "</div>";
$("body").append(html);
}
}
};
xhr.open('GET', 'http://localhost:8080/con_us_su/' + token, false);
xhr.send(null);
}
function goToSurvey(id) {
sessionStorage.setItem('surveyId', id);
window.setTimeout(function () {
location.href = "surveyPage.html";
},);
}
function getTitleAndDescription(id) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
json = JSON.parse(xhr.responseText);
}
};
xhr.open('GET', 'http://localhost:8080/survey/' + id, false);
xhr.send(null);
}
var user;
function getUser() {
var token = $.cookie("token");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
user = JSON.parse(xhr.responseText);
$("#email-profile").text(user["email"]);
if (user["group"] === "admin") {
$(".right-panel").append(`<button type=\"button\" class=\"adm-menu btn btn-outline-secondary\" onclick=\"redirectToAdminPanel()\">Admin Panel</button>
<button type=\"button\" class=\"res-menu btn btn-outline-secondary btn-block mt-1\" onclick=\"redirectToAdminPanel()\">Admin Panel</button>`);
}
}
};
xhr.open('GET', 'http://localhost:8080/users/' + token, false);
xhr.send(null);
}
function redirectToAdminPanel() {
window.setTimeout(function () {
location.href = "admin.html";
},);
}
function showUnavailableSurveys() {
var xhr = new XMLHttpRequest();
var token = $.cookie("token");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var surveyIds = xhr.responseText.substring(1, xhr.responseText.length - 1);
surveyIds = surveyIds.split(',').map(x => +x);
if (surveyIds[0] !== 0) {
var html = "<div class=\"main-panel border rounded p-4\">";
for (var i in surveyIds) {
getTitleAndDescription(surveyIds[i]);
var topic = json.topic;
var description = json.description;
html += "<div class=\"card mr-2 mb-2 text-muted\" style=\"width: 18.2rem; float: left;\">\n" +
" <div class=\"card-body\">\n" +
" <h5 class=\"card-title\">" + topic + "</h5>\n" +
" <p class=\"card-text\">" + description + "</p>\n" +
" <button class=\"btn btn-dark\" onclick='goToSurvey(" + surveyIds[i] + ")' disabled>Answered</button>\n" +
" </div>\n" +
"</div>";
}
html += "</div>";
$("body").append(html);
}
}
};
xhr.open('GET', 'http://localhost:8080/answered/' + token, false);
xhr.send(null);
}
function redirectToAnswersWithKey() {
sessionStorage.setItem('key', $("#key").val());
window.setTimeout(function () {
location.href = "answers.html";
});
}
|
import React, { useState } from 'react';
import axios from 'axios';
import Loader from "react-loader-spinner";
export default function Weather(props) {
let [temperature, setTemperature] = useState(null);
function handleResponse(response) {
setTemperature(response.data.main.temp);
}
if (temperature) {
return <h4>The temperature in {props.city} is {Math.round(temperature)}°C</h4>
} else {
let apiKey = "735adde991f0a3263e9a14037efe90bf";
let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${props.city}&appid=${apiKey}a&units=metric`;
axios.get(apiUrl).then(handleResponse);
return (
<Loader
type="Puff"
color="#00BFFF"
height={100}
width={100}
timeout={3000}
/>
);
}
}
|
'use strict';
angular.module('instangularApp', [])
.config(function ($routeProvider) {
$routeProvider
.when('/', { templateUrl: 'views/partials/phone-list.html', controller:'MainCtrl'})
.when('/about', { templateUrl: 'views/partials/about.html' })
.when('/phone/:phoneId', { templateUrl: 'views/partials/phone-detail.html', controller: 'PhoneDetailCtrl' })
.when('/login', { templateUrl: 'views/login.html', controller: 'PhoneDetailCtrl' })
//.otherwise({
//redirectTo: '/'
//});
});
|
'use strict'
/** @typedef { import('./types').CliArguments } CliArguments */
const meow = require('meow')
const pkg = require('../package.json')
const DEFAULT_CONFIG = 'config'
const DEFAULT_MINUTES = 10
const DEFAULT_PERCENT_FIRING = 0
const ENV_CONFIG_NAME = `${pkg.name.toUpperCase().replace(/-/g, '_')}_CONFIG`
const ENV_MINUTES_NAME = `${pkg.name.toUpperCase().replace(/-/g, '_')}_MINUTES`
const ENV_PERCENT_FIRING_NAME = `${pkg.name.toUpperCase().replace(/-/g, '_')}_ACTIONS`
const ENV_CONFIG = process.env[ENV_CONFIG_NAME]
const ENV_MINUTES = parseInt(process.env[ENV_MINUTES_NAME], 10) || undefined
const ENV_PERCENT_FIRING = parseInt(process.env[ENV_PERCENT_FIRING_NAME], 10) || undefined
const help = getHelp()
module.exports = {
parseArgs,
help,
}
/** @type { () => CliArguments } */
function parseArgs() {
const { input, flags } = meow({
pkg,
help,
flags: {
config: { alias: 'C', type: 'string' },
template: { alias: 'T', type: 'string' },
minutes: { alias: 'M', type: 'number' },
percentFiring: { type: 'number' },
}
})
const config = flags.config || ENV_CONFIG || DEFAULT_CONFIG
const template = flags.template || null
const minutes = flags.minutes || ENV_MINUTES || DEFAULT_MINUTES
const percentFiring = flags.percentFiring || ENV_PERCENT_FIRING || DEFAULT_PERCENT_FIRING
const [command, ...commandArgs] = input
return {
command,
commandArgs,
config,
template,
minutes,
percentFiring,
}
}
function getHelp () {
return`
${pkg.name}: ${pkg.description}
v${pkg.version}
usage: ${pkg.name} <options> <cmd> <arguments>
options:
-C --config use the specified ecctl config in $HOME/.ecctl/[name].json (default: ${DEFAULT_CONFIG})
-T --template deployment template to use (use lst command to list; default: unknown)
-M --minutes override the number of minutes to run the test (default: ${DEFAULT_MINUTES})
--percentFiring use to specify the percentages of alerts firing actions (default: ${DEFAULT_PERCENT_FIRING})
commands:
run <scenarioId> run scenario with specified id
ls list suites
lsv list suites verbosely
lsd list existing deployments, by name and id
lst list existing templates, by description and id
rmd <name> delete existing deployments match the specified name
rmdall delete all existing deployments
env print settings given options and env vars
You may also use the following environment variables as the value of the
respective config options:
- ${ENV_CONFIG_NAME}
- ${ENV_MINUTES_NAME}
`.trim()
}
|
const svg = d3.select('svg');
svg.style('background-color', 'red');
svg.style('box-shadow', '10px 10px 3px lightgray');
|
require('./config-bench-factory')('heavydeps')
|
// Запрос за данными
request.get('/index/json', function(error, JSON) {
// JSON => BEMJSON ( Database Data => View data)
BEMTREE
.apply(JSON)
.then(function(BEMJSON) {
// View data => Browser code (HTML)
var html = BEMHTML.apply(BEMJSON);
response.send(html);
});
});
|
var todoList= (function(){
var values = [];
return {
Item: function (title) {
this.title = title;
this.date = new Date();
this.asText = function () {
return title + ", " + this.date;
}
},
add: function (item) {
values.push(item);
},
asText: function () {
var content = "";
for (var i = 0; i < values.length; i++) {
content += values[i].asText() + "<br/>";
}
return content;
}
}
})();
(function() {
window.document.getElementById("add").addEventListener("click", function () {
todoList.add(new todoList.Item(window.document.getElementById("title").value));
window.document.getElementById("items").innerHTML = todoList.asText();
}, false);
})();
var item1 = new todoList.Item("hoge");
var item2 = new todoList.Item("fuga");
todoList.add(item1);
todoList.add(item2);
window.document.getElementById("items").innerHTML = todoList.asText();
|
'use strict';
var browseServices = angular.module('browseServices', ['ngResource']);
browseServices.factory('Users', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
return $resource('http://:url/users/:id/:query.:format', {url: API_SERVER, format: 'json'}, {
query: {method: 'GET', params: {}, isArray: true}
});
}]);
browseServices.factory('Courses', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
return $resource('http://:url/courses/:id/:query.:format', {url: API_SERVER, format: 'json'}, {
query: {method:'GET', params:{}, isArray: false}
});
}]);
browseServices.factory('Universities', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
return $resource('http://:url/universities/:id/:query.:format', {url: API_SERVER, format: 'json'}, {
query: {method:'GET', params:{}, isArray: true}
});
}]);
browseServices.factory('Lectures', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
return $resource('http://:url/lectures/:id/:query.:format', {url: API_SERVER, format: 'json'}, {
query: {method:'GET', params:{}, isArray:true}
});
}]);
browseServices.factory('Visits', ['$resource', 'API_SERVER', function($resource, API_SERVER){
return $resource('http://:url/visits/:query', {url: API_SERVER, format: 'json'},{
save: {method: 'POST', params: {}}
});
}]);
browseServices.factory('Subjects', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
return $resource('http://:url/subjects/:id/:query.:format', {url: API_SERVER, format: 'json'}, {
query: {method:'GET', params:{}, isArray:true}
});
}]);
browseServices.factory('Subject', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
return $resource('http://:url/subjects/:id/:query.:format', {url: API_SERVER, format: 'json'}, {
query: {method:'GET', params:{}, isArray:false}
});
}]);
// browseServices.factory('Universities', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
// return $resource('http://:url/:service/:id/:query.:format', {url: API_SERVER, service: '', format: 'json'}, {
// query: {method:'GET', params:{service: 'universities'}, isArray:true}
// });
// }]);
// browseServices.factory('Courses', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
// return $resource('http://:url/:service/:id/:query.:format', {url: API_SERVER, service: '', format: 'json'}, {
// query: {method:'GET', params:{query: 'courses'}, isArray:false}
// });
// }]);
// browseServices.factory('CourseInfo', ['$resource', 'API_SERVER', function($resource, API_SERVER){
// return $resource('http://:url/:service/:id/:query.:format', {url:API_SERVER, service: ''},{
// query: {method: 'GET', params: {service: 'course_info', id: '@id'}, isArray:false}
// });
// }]);
// browseServices.factory('Parts', ['$resource', 'API_SERVER', function($resource, API_SERVER){
// return $resource('http://:url/:service/:id/parts', {url:API_SERVER, service: ''},{
// get: {method: 'GET', params: {}, isArray:true}
// });
// }]);
// browseServices.factory('MyCourses', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
// return $resource('http://:url/:service/:course_id/:query.:format', {url: API_SERVER, format: 'json'}, {
// query: {method: 'GET', params: {service: 'user_visited_courses'}, isArray: true}
// });
// }]);
// browseServices.factory('VisitedPart', ['$resource', 'API_SERVER', function($resource, API_SERVER){
// return $resource('http://:url/:service/:lecture_id/:part_id/:query', {url: API_SERVER, service: ''},{
// save: {method: 'POST', params: {service: 'save_part_visit'}}
// });
// }]);
// browseServices.factory('UserMbaEnrollment', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
// return $resource('http://:url/:service/:name/:query.:format', {url: API_SERVER, format: 'json'}, {
// get: {method: 'GET', params: {service: 'enrollment_program_data', name: '@name'}, isArray: false}
// });
// }]);
// browseServices.factory('CourseProgress', ['$resource', 'API_SERVER', function($resource, API_SERVER) {
// return $resource('http://:url/:service/:course_id/:query.:format', {url: API_SERVER, format: 'json'}, {
// get: {method: 'GET', params: {service: 'course_progress', course_id: '@course_id'}, isArray:false}
// });
// }]);
|
const express = require('express')
const bodyParser = require('body-parser')
const server = express()
server.use(bodyParser.json())
server.use(bodyParser.urlencoded({ extended: true }))
server.get('/', (req, res) => {
res.send('<h1>Home</h1>')
})
server.get('/contato', (req, res) => {
res.send(`
<h1>Contato</h1>
<form action="/contato" method="POST">
<label>E_Mail</label>
<input type="email" name="email" id="email">
<label>Mensagem</label>
<textarea name="mensagem" id="mensagem"></textarea>
<input type="submit" value="Enviar">
</form>
`)
})
server.post('/contato', (req,res) => {
res.send({
'E_Mail':req.body.email,
'Mensagem':req.body.mensagem
})
})
server.get('/pessoa', (req,res) => {
res.send(`
<form action="/pessoa" method="POST">
<h1>Pessoa</h1>
<label>Nome</label>
<textarea name="nome" id="nome"></textarea>
<label>E-Mail</label>
<input type="email" name="email" id="email">
<label>Telefone</label>
<textarea name="numero" id="numero"></textarea>
<input type="submit" value="Enviar">
</form>
`)
server.post('/pessoa', (req,res) => {
res.send(
`<h1>Pessoa ${req.body.nome} Casastrada com sucesso</h1>`
)
})
})
server.listen(3000, () => {
console.log('Servidor rodando em http://localhost:3000')
console.log('Para encerrar a aplicação: CTRL+C')
})
|
import React from 'react';
import PropTypes from 'prop-types';
import { Card, CardText, CardBody, CardTitle, CardSubtitle } from 'reactstrap';
import Spinner from '../../common/Spinner';
import Button from '../../common/Button';
const MembershipCard = ({ isMember, imageUrl, toggleModal, title, subtitle, body, loading }) => {
return (
<div className="col-5">
<Card>
{loading ? (
<CardBody style={{ minHeight: '200px' }}>
<Spinner style={{ marginLeft: '36%', top: '33%' }} />
</CardBody>
) : (
<React.Fragment>
<img className="card-img-top" src={imageUrl} alt="Card cap" />
<CardBody>
<CardTitle style={{ fontSize: '1.5em' }}>{title}</CardTitle>
<hr />
<CardSubtitle style={{ fontSize: '1.3em' }}>{subtitle}</CardSubtitle>
<hr />
<CardText style={{ color: 'black' }}>{body}</CardText>
{!isMember && (
<React.Fragment>
<hr />
<Button title="Get Membership" classes="btn btn-primary" onClick={toggleModal} />
</React.Fragment>
)}
</CardBody>
</React.Fragment>
)}
</Card>
</div>
);
};
MembershipCard.propTypes = {
isMember: PropTypes.bool.isRequired,
loading: PropTypes.bool.isRequired,
imageUrl: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
subtitle: PropTypes.string.isRequired,
body: PropTypes.string.isRequired,
toggleModal: PropTypes.func.isRequired
};
export default MembershipCard;
|
/*******************************************************************************************************
sertal.ch user management twitter-bootstrap and Live HTML template for the following features
- controller file for 'users' template views
Date: 15-June-2013
Author:
********************************************************************************************************/
Meteor.subscribe("allusers");
Template.usersinfo.recorddisplay = function() {
return Session.get("recorddisplays");
}
Template.usersinfo.currentuser = function() {
return Meteor.users.findOne({
_id: Session.get("currentuser")
});
}
Template.usersinfo.externalIds = function() {
if (Session.get("currentuser"))
return Meteor.users.findOne({
_id: Session.get("currentuser")
}).externalIds;
}
Template.usersinfo.groupperm = function() {
if (Groups.findOne({
_id: this.group
}))
return true;
return false;
}
Template.usersinfo.created = function() {
Session.set("errorMessage", null);
}
Template.usersinfo.currentusermail = function() {
if (Session.get("currentuser")) {
return Meteor.users.findOne({
_id: Session.get("currentuser")
}).emails[0].address;
}
}
Template.usersinfo.events({
"click #cancel": function() {
Session.set("recordContext", "usersdevices");
},
"click #register": function(event, template) {
$("#grouptree").jstree("save_opened");
var username = template.find("#username").value.toLowerCase();
var userdes = template.find("#userdes").value.trim();
var email = template.find("#email").value.toLowerCase();
var password = template.find("#password").value;
var password = template.find("#password").value;
var lang = template.find("#lang").value;
var groups = Session.get("customlist");
var conflicts;
var externalIds = getExternalIds();
if (externalIds != "error") {
conflicts = externalIds.conflicts;
externalIds = externalIds.externalIds;
}
if (!userdes) {
userdes = email;
}
if (username.length && (username.indexOf('@') === -1) && email.length && groups.length && password.length && externalIds != "error") {
createuser({
username: username,
email: email,
groups: groups,
password: password,
userdes: userdes,
lang: lang,
externalIds: externalIds,
conflicts: conflicts,
tenant: Session.get("currenttenant")
});
} else {
var loc = Session.get("currentLanguage");
if (!username.length) {
Session.set('errorMessage', labels["userName"][loc] + labels["empty"][loc]);
} else if (!(username.indexOf('@') === -1)) {
Session.set('errorMessage', labels["userName"][loc] + labels["userNameValidation"][loc]);
} else if (!email.length) {
Session.set('errorMessage', labels["email"][loc] + " " + labels["empty"][loc]);
} else if (!groups.length) {
Session.set('errorMessage', labels["group"][loc] + " " + labels["empty"][loc])
} else if (password.length < 6) {
Session.set('errorMessage', labels["password"][loc] + labels["passwordValidation"][loc])
} else if (externalIds == "error")
Session.set('errorMessage', labels["uniqueExIdsError"][loc]);
}
},
"click #edit": function() {
Session.set("recorddisplays", false);
var groups = Meteor.users.findOne({
_id: Session.get("currentuser")
}).groups;
for (var i = 0; i < groups.length; i++) {
if (!Groups.findOne({
_id: groups[i].group
})) {
groups.splice(i, 1)
}
}
Session.set("customlist", groups);
var exs = Meteor.users.findOne({
_id: Session.get("currentuser")
}).externalIds;
if (!exs)
exs = []
Session.set("externalIds", exs);
},
"click #update": function(event, template) {
$("#grouptree").jstree("save_opened");
var username = template.find("#username").value.toLowerCase();
var userdes = template.find("#userdes").value;
var email = template.find("#email").value.toLowerCase();
var password = template.find("#password").value;
var lang = template.find("#lang").value;
var groups = Session.get("customlist");
var oldgroups = Meteor.users.findOne({
_id: Session.get("currentuser")
});
var conflicts;
var externalIds = getExternalIds();
if (!userdes) {
userdes = email;
}
for (var i = 0; i < oldgroups.length; i++) {
if (!Groups.findOne({
_id: oldgroups[i].group
})) {
groups.push({
group: oldgroups[i].group
});
}
}
if (username.length && (username.indexOf('@') === -1) && email.length && groups.length && externalIds != "error") {
Meteor.call('updateuser', {
userid: Session.get("currentuser"),
username: username,
userdes: userdes,
externalIds: externalIds,
email: email,
password: password,
language: lang,
groups: groups,
tenant: Session.get("currenttenant")
}, function(error, res) {
if (!error) {
if (res && res.error) {
Session.set("errorMessage", labels[res.reason][Session.get("currentLanguage")]);
} else {
Session.set("recorddisplays", true);
Session.set("errorMessage", "");
}
} else {
Session.set("errorMessage", error.reason)
}
});
} else {
loc = Session.get('currentLanguage');
if (!username.length) {
Session.set('errorMessage', labels["userName"][loc] + labels["empty"][loc]);
} else if (!(username.indexOf('@') === -1)) {
Session.set('errorMessage', labels["group"][loc] + " " + labels["empty"][loc]);
Session.set("customlist", Meteor.users.findOne({
_id: Session.get("currentuser")
}).groups)
} else if (!email.length) {
Session.set('errorMessage', labels["email"][loc] + " " + labels["empty"][loc]);
} else if (!groups.length) {
Session.set('errorMessage', labels["group"][loc] + " " + labels["empty"][loc]);
} else if (externalIds == "error") {
Session.set('errorMessage', labels["uniqueExIdsError"][loc]);
}
}
},
"click #delete": function() {
Meteor.call("deleteuser", {
uid: Session.get("currentuser"),
tenant: Session.get("currenttenant")
}, function(error) {
if (!error) {
Session.set("recordContext", "usersdevices");
} else {
alert(error);
}
});
},
"click #addExternalIds": function(ev, tem) {
$("#externalSystems tbody ").append('<tr class="externalIds"><td><input type="text" class="systemName" /></td><td><input type="text" class="externalId" /></td><td> <a href="#"> <img src="/minus.png" height="20" width="20" class="remove" /></a></td></tr>');
},
"click .remove": function(ev, tem) {
$(ev.target).parent().parent().parent().remove();
}
})
createuser = function(options) {
var username = options.username;
var email = options.email;
if (!username && !email)
throw new Meteor.Error(400, "Need to set a username or email");
if (options.password) {
if (options.srp)
throw new Meteor.Error(400, "Don't pass both password and srp in options");
options.srp = SRP.generateVerifier(options.password);
}
var user = {
services: {}
};
user.userdes = options.userdes;
user.language = options.lang;
user.externalIds = options.externalIds;
user.groups = options.groups
if (options.srp)
user.services.password = {
srp: options.srp
};
if (username)
user.username = username;
if (email)
user.emails = [{
address: email,
verified: false
}];
Meteor.call('createuser', options, user, function(error, user) {
if (!error) {
Session.set("currentuser", user);
Session.set("recorddisplays", true);
} else Session.set("errorMessage", error.reason);
});
};
var temp = [];
Template.groupslist.helpers({
groups: function() {
try {
var groups = Groups.find({
tenant: Session.get("currenttenant"),
parent: ""
}, {
sort: {
groupname: 1
}
}).fetch();
if (Session.get("currentuser"))
_.each(groups, function(group) {
if (_.find(group.users, function(ele) {
return ele.user == Session.get("currentuser")
})) {
group["checked"] = "checked";
}
})
return groups;
} catch (err) {}
},
groupChilds: function() {
var groups = Groups.find({
tenant: Session.get("currenttenant"),
parent: this._id
}, {
sort: {
groupname: 1
}
}).fetch();
var childGroups = "";
var checked = "";
temp = []
var open;
for (var i = 0; i < groups.length; i++) {
if (_.find(groups[i].users, function(ele) {
return ele.user == Session.get("currentuser")
})) {
checked = "checked";
} else
checked = "";
childGroups += '<li><input id="' + groups[i]._id + '" type="checkbox" class="userGroup" ' + checked + ' /><img src="group.png" alt="" height="15" width="15" /><a>' + groups[i].groupname + '</a><ul>';
childGroups += getChilds(groups[i]._id);
childGroups += "</ul></li>";
}
return childGroups;
}
});
var getExternalIds = function() {
var exs = [];
var breakfun = false
var index;
var conflicts = [];
var exunique = Tenants.findOne({
_id: Session.get("currenttenant")
}).exIdUnique;
try {
$("#externalSystems tbody tr").each(function(index, ele) {
obj = {};
$(ele).find("input").each(function(ind1, ele1) {
obj[$(ele1).attr("class")] = $(ele1).val().trim();
});
if (_.find(exs, function(ele) {
return ele.systemName == obj.systemName && ele.externalId == obj.externalId
})) {
//no code
} else {
if (obj.systemName && obj.externalId)
exs[index] = obj;
}
});
var groups = Groups.find({
tenant: Session.get("currenttenant")
}).fetch();
groups = _.pluck(groups, "_id");
var user;
for (var i = 0; i < exs.length; i++) {
user = Meteor.users.find({
_id: {
$ne: Session.get("currentuser")
},
"groups.group": {
$in: groups
},
externalIds: {
$elemMatch: exs[i]
}
}, {
fields: {
_id: 1
}
}).fetch();
if (user.length) {
if (exunique) {
return "error";
break;
}
}
}
return exs;
} catch (err) {
console.log(err)
}
}
var getChilds = function(id) {
var groups = Groups.find({
tenant: Session.get("currenttenant"),
parent: id
}).fetch();
var childGroups = "";
var checked = ""
var open;
for (var i = 0; i < groups.length; i++) {
if (_.find(groups[i].users, function(ele) {
return ele.user == Session.get("currentuser")
})) {
open = id;
checked = "checked";
} else
checked = "";
childGroups += '<li><input id="' + groups[i]._id + '" type="checkbox" class="userGroup" ' + checked + '/> <img src="group.png" alt="" height="15" width="15" /><a>' + groups[i].groupname + '</a><ul>';
childGroups += getChilds(groups[i]._id);
childGroups += "</ul></li>";
}
if (open)
temp.push(open);
return childGroups;
}
Template.groupslist.rendered = function() {
$(function() {
$("#userGrouptree").jstree({
"core": {
"initially_open": temp
},
"ui": {
"select_limit": 0
},
"themes": {
"theme": "default",
"dots": true,
"icons": false
},
"plugins": ["themes", "html_data", "ui"]
})
})
}
Template.groupslist.events({
"change #groupslist": function(event) {
if (event.target.value) {
var customlist = Session.get("customlist");
customlist.push({
group: event.target.value
});
Session.set("customlist", customlist);
event.target.value = "";
}
},
"click .delgroup": function(event) {
var groups = Session.get("customlist");
for (var i = 0; i < groups.length; i++) {
if (groups[i].group == this.group) {
groups.splice(i, 1);
}
}
Session.set("customlist", groups);
},
"click .userGroup": function(ev, tem) {
var id = ev.target.id;
var groups = Session.get("customlist");
groups = _.reject(groups, function(ele) {
console.log(ele.group + ":" + id);
return ele.group == id
});
if ($(ev.target).attr("checked"))
groups.push({
group: id
});
Session.set("customlist", groups)
}
})
Handlebars.registerHelper('groupnamebyid', function() {
var grp = Groups.findOne({
_id: this.group
});
var str = grp.groupname;
var ten = Tenants.findOne({
_id: grp.tenant
})
str += "(" + ten.tname + ")"
return new Handlebars.SafeString(str);
});
Handlebars.registerHelper('langOptions', function(language) {
var str = "";
var langcodes = ['en', 'de', 'fr', 'it'];
var langs = ['English', 'German', 'French', 'Italian'];
for (var i = 0; i < langcodes.length; i++) {
if (langcodes[i] != language) {
str += "<option value='" + langcodes[i] + "'>" + langs[i] + "</option>";
} else {
str += "<option value='" + langcodes[i] + "' selected='selected'>" + langs[i] + "</option>";
}
}
return new Handlebars.SafeString(str);
});
|
let pictureButton = document.querySelector("#picture")
let apiKey = "DIhfuwgrEZQzwxenOdDsfVfVHQL01UMn7U0FP5ms"
pictureButton.addEventListener("click", () => {
getApiData()
})
async function getApiData() {
let response = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&camera=fhaz&api_key=${apiKey}`);
let responseOne = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&camera=rhaz&api_key=${apiKey}`);
let responseTwo = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&camera=mast&api_key=${apiKey}`);
let responseThree = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&camera=navcam&api_key=${apiKey}`);
let data = await response.json()
let dataOne = await responseOne.json()
let dataTwo = await responseTwo.json()
let dataThree = await responseThree.json()
const datas = [data, dataOne, dataTwo, dataThree];
displayApiData(datas);
}
function displayApiData(datas) {
const rover = document.querySelector(".rover");
datas.forEach((data) => {
rover.innerHTML += `
<div>
<p>${data.photos[0].camera.full_name}</p>
<img src="${data.photos[0].img_src}">
</div>
`;
});
}
|
import { Col, Row } from 'Components/UI-Library'
import React from 'react'
import './index.less'
import usePayment from './Payment.Hook'
import PaymentForm from './PaymentForm.Component'
const Payment = () => {
usePayment()
return (
<Row justify="center" className="payment-wrapper">
<Col xs={24} xl={16}>
<PaymentForm />
</Col>
</Row>
)
}
export default Payment
|
''.endsWith || (String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
});
(function ($) {
/**
*
* @param options = {
* appendTo,
* html,
* js,
* css,
* dependencies: [
* http://.../a.css,
* http://.../jquery.js
* ]
* }
*/
$.fn.loadWidget = function (options) {
if (options.html && options.appendTo) {
$(options.appendTo).html(options.html);
}
var depJSs = [];
var depCSSs = [];
if (options.dependencies) {
$.each(options.dependencies, function (i, dep) {
if (dep.endsWith('.js')) {
depJSs.push(dep);
} else if (dep.endsWith('.css')) {
depCSSs.push(dep);
}
});
}
var doc = document;
var head = doc.getElementsByTagName('head')[0];
if (options.css) {
addCssText(options.css);
}
function addCssText(cssText) {
try { // IE
doc.createStyleSheet().cssText = cssText;
} catch (e) { //Firefox, Opera, Safari, Chrome
var style = doc.createElement("style");
style.type = "text/css";
style.textContent = cssText;
head.appendChild(style);
}
}
$.each(depCSSs, function (i, css) {
var css = doc.createElement('link');
css.type = 'text/css';
css.rel = 'stylesheet';
css.href = css;
head.appendChild(css);
});
var JSs = $.map(depJSs, function (js) {
return {data: js, tyep: 'url'};
});
if (options.js) {
JSs.push({
data: options.js,
type: 'text'
});
}
addScripts(JSs)
function addScripts(scripts) {
if (scripts.length == 0) return;
var t = scripts.shift();
var script = doc.createElement("script");
script.type = "text/javascript";
if (t.type == 'url') script.src = t.data;
else if (t.type == 'text') script.text = t.data;
document.body.appendChild(script);
script.onload = script.onreadystatechange = function () {
addScripts(scripts);
}
}
};
})(jQuery);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.