text
stringlengths
7
3.69M
ON_DAED["3D"].NuvemMolecular = function (scene) { var o = new THREE.Object3D(); var particulas = []; var numParticulas = 1000; var countVisible = numParticulas; var escalaSol = 0.225; var tamanhoSol = 90; var estrela = new THREE.Object3D(); var sol = ON_DAED['3D'].criarSol(estrela); sol.scale.multiplyScalar(escalaSol); estrela.visible = false; o.add(estrela); var esferaBranca = new THREE.Mesh(new THREE.SphereGeometry(escalaSol * tamanhoSol, 64, 32), new THREE.MeshBasicMaterial({ color: 0xFFFFFF })); esferaBranca.scale.z = esferaBranca.scale.y = esferaBranca.scale.x = 1 / numParticulas; o.add(esferaBranca); function initParticula(p) { var hAngle = Math.random() * Math.PI * 2; var vAngle = Math.random() * Math.PI * 2; var r = 5 + 55 * Math.random(); p.it = 0; p.r = r; p.hAngle = hAngle; p.vAngle = vAngle; p.position.copy(MathHelper.sphericalToCartesian(r, hAngle, vAngle)); var scale = Math.random() * 2.5; p.scale.set(scale, scale, 1); p.material.color.setHex(0x999999 + 0x111111 * parseInt(6 * Math.random())); p.ciclo = true; } function start() { estrela.visible = false; esferaBranca.visible = true; estrela.scale.z = estrela.scale.y = estrela.scale.x = esferaBranca.scale.z = esferaBranca.scale.y = esferaBranca.scale.x = 1 / particulas.length; countVisible = particulas.length; for (var i = 0; i < particulas.length; i++) { initParticula(particulas[i]); } } var velocidadeUniao = 80; for (var i = 0; i < numParticulas; i++) { var material = new THREE.SpriteMaterial({ map: THREE.ImageUtils.loadTexture("lib/on-daed-js/imgs/texturas/nuvem-molecular/particula.png") }); var p = new THREE.Sprite(material); particulas.push(p); initParticula(p); var semOperacao = 0; var maxSemOperacao = 38000; ON_DAED['3D'].register(o, p, function () { if (o.visible) { if (this.ciclo) { this.it++; var r = this.r - this.r * (this.it / velocidadeUniao); this.position.copy(MathHelper.sphericalToCartesian(r, this.hAngle, this.vAngle)); if (r <= 5) { this.material.color.setHex(0xFFFFFF); this.ciclo = false; countVisible--; var esfera; if(countVisible > (numParticulas / 2)) { esfera = esferaBranca; estrela.visible = false; esferaBranca.visible = true; } else { esfera = estrela; estrela.visible = true; esferaBranca.visible = false; } esfera.scale.z = esfera.scale.y = esfera.scale.x = ((particulas.length - countVisible) / particulas.length); } } else if (countVisible === 0 && semOperacao++ === maxSemOperacao) { semOperacao = 0; start(); } } }); } scene.add(o); return o; };
module.exports = { projects: [ { title: "Punctually", subtitle: "a schedule generator app demo", image: "/assets/projects/punctually.jpg", technologies: ["NextJS", "Sass"], url: "https://punctually.vercel.app", }, { title: "Styled", subtitle: "a full stack ecommerce site", image: "/assets/projects/styled.jpg", technologies: [ "NextJS", "Styled-Components", "Framer Motion", "Strapi", "Auth0", "Stripe", ], url: "https://mikepodo-styled.vercel.app/", }, { title: "Twitterclone", subtitle: "a semi-functioning clone of Twitter", image: "/assets/projects/twitter.jpg", technologies: [ "React", "Sass", "Framer Motion", "Firebase Cloud Firestore", ], url: "https://twitterclone.mikepodo.net", }, { title: "Portfolio v2", subtitle: "v2 of mikepodo.net", image: "/assets/projects/portfolio2.jpg", technologies: ["React", "Styled-Components", "Framer Motion"], url: "https://mikepodo.netlify.app", }, { title: "Ignite", subtitle: "a site utilizing an API to display categorized games", image: "/assets/projects/ignite.jpg", technologies: [ "React", "React-Router", "Styled-Components", "Framer Motion", "Redux", "Axios", ], url: "https://mikepodo-ignite.netlify.app/", }, { title: "Capture", subtitle: "a template website for any general business", image: "/assets/projects/capture.jpg", technologies: [ "React", "React-Router", "Styled-Components", "Framer Motion", ], url: "https://mikepodo-capture.netlify.app/", }, { title: "Waves", subtitle: "a React media player", image: "/assets/projects/waves.jpg", technologies: ["React", "Sass"], url: "https://mikepodo-waves.netlify.app/", }, { title: "Coolors", subtitle: "a color-picking toolkit for web developers", image: "/assets/projects/coolors.jpg", technologies: ["JavaScript", "HTML", "Sass"], url: "https://mikepodo-coolors.netlify.app/", }, { title: "Beatmaker", subtitle: "a musical drum beat site", image: "/assets/projects/beatmaker.jpg", technologies: ["JavaScript", "HTML", "Sass"], url: "https://mikepodo-beatmaker.netlify.app/", }, { title: "Todo List", subtitle: "a beginner programmer's todo list application", image: "/assets/projects/todolist.jpg", technologies: ["JavaScript", "HTML", "Sass"], url: "https://mikepodo-todolist.netlify.app/", }, { title: "Portfolio v1", subtitle: "v1 of mikepodo.net", image: "/assets/projects/portfolio1.jpg", technologies: ["HTML", "Sass"], url: "https://mikepodo-portfolio.netlify.app/", }, { title: "BMI Calculator", subtitle: "a calculator used to find one's body mass index", image: "/assets/projects/bmi.jpg", technologies: ["JavaScript", "HTML", "Sass"], url: "https://mikepodo-bmi-calculator.netlify.app/", }, ], };
import React from 'react' import { StyleSheet } from 'quantum' import { connect, hover as hoverState } from 'bypass/ui/state' import { Tooltip } from '../../tooltip' import Content from './Content' const styles = StyleSheet.create({ self: { height: '100%', display: 'flex', alignItems: 'center', fontSize: '12px', background: '#ffffff', padding: '2px 7px', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, oddRow: { background: '#eceff1', }, selected: { background: '#e5e19a', }, 'justify=center': { justifyContent: 'center', }, 'justify=end': { justifyContent: 'flex-end', }, strong: { fontWeight: 'bold', }, }) const Cell = ({ children, oddRow, justify, strong, selected, tooltip, hover, onMouseEnter, onMouseLeave }) => ( <div className={styles({ oddRow, justify, selected, strong })} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} > <Content> {children} </Content> {tooltip && hover ? ( <Tooltip align='top' offset='10px 0'> {tooltip} </Tooltip> ) : null} </div> ) export default connect([hoverState], Cell)
var pop_8c = [ [ "HC_FNAME", "pop_8c.html#a33dd225b4dd2d3c29644e01b60cf4723", null ], [ "HC_FEXT", "pop_8c.html#ab0029aa20b987416bdcd51e73e7091b5", null ], [ "cache_id", "pop_8c.html#a371c7306913dedd360a4b5c7d3e8ffa7", null ], [ "pop_adata_free", "pop_8c.html#a25c7eb318029948e41fa95b8158434ef", null ], [ "pop_adata_new", "pop_8c.html#a984d3035a11a9d2befecf9d99a2d1d71", null ], [ "pop_edata_free", "pop_8c.html#a193efd9405a7f4875480f473a42bf25b", null ], [ "pop_edata_new", "pop_8c.html#a0312c710e9128c2b2312941e54f135d0", null ], [ "fetch_message", "pop_8c.html#a3cc06c4686cd79cfa3177fca6a868fa2", null ], [ "pop_read_header", "pop_8c.html#ac8590e3bcca739faf5b19884475fa008", null ], [ "fetch_uidl", "pop_8c.html#ac2b98a8e580cfbd41e57db2b4132ea59", null ], [ "msg_cache_check", "pop_8c.html#a3bf9c44e730e2d242d09c2b0662c3a30", null ], [ "pop_hcache_namer", "pop_8c.html#a38f44bd1528545c8c77a842e2a9f7e0d", null ], [ "pop_hcache_open", "pop_8c.html#a3956320a3812ac0af7796e4b99d4c3e6", null ], [ "pop_fetch_headers", "pop_8c.html#aed296290f911b6522df2dd97ce554f65", null ], [ "pop_clear_cache", "pop_8c.html#a306deeb158f76bd338f04b1a5494d6a9", null ], [ "pop_fetch_mail", "pop_8c.html#ae41e43ca791955eb76c5709db39a21d7", null ], [ "pop_ac_find", "pop_8c.html#a5c088533a3c9fff2f12c32e4e037295a", null ], [ "pop_ac_add", "pop_8c.html#af00be472994755930e72b18eb1976f60", null ], [ "pop_mbox_open", "pop_8c.html#acdba1ee37ea546f48016d1cf3f7f512b", null ], [ "pop_mbox_check", "pop_8c.html#acc854b150d5fc2fbe01af6dea1ba61c4", null ], [ "pop_mbox_sync", "pop_8c.html#aebf6ed4e14773a95fe83caa0b79f2445", null ], [ "pop_mbox_close", "pop_8c.html#aebc7b81fdfa8c397574ab3a243534ec6", null ], [ "pop_msg_open", "pop_8c.html#ac2445888a612c0679bf9b71e529f5846", null ], [ "pop_msg_close", "pop_8c.html#a7401b6da959be8294880ff7df8c611a8", null ], [ "pop_msg_save_hcache", "pop_8c.html#abcd55f0bb3f983b76ecbdc34253f1c05", null ], [ "pop_path_probe", "pop_8c.html#a5b33b7c070124e656f1a4e8c67c039ad", null ], [ "pop_path_canon", "pop_8c.html#a15f51348ae6a47437dcd21d7aca945b9", null ], [ "pop_path_pretty", "pop_8c.html#a47c10790f7a2d4bac15a9a82a90e1f04", null ], [ "pop_path_parent", "pop_8c.html#a0c80b09a7ac17ad83cf6b5d647cde95c", null ], [ "MxPopOps", "pop_8c.html#aec53cbb4297fe9b475784600a3957dc7", null ] ];
ddp_conn = DDP.connect("http://localhost:3000") ddp_conn.subscribe("data"); Data = new Meteor.Collection("data", { connection: ddp_conn}); Meteor.publish("data", function() { //Uncomment to trigger Bug 1, sorting isn't too relevant to DDP but it is needed to use 'limit' //return Data.find({}, {sort: {number: -1}, limit: 3}); return Data.find({}); });
var germany = document.getElementById('germany') var france = document.getElementById('france') var spain = document.getElementById('spain') window.onscroll = function(event){ window.requestAnimationFrame(onScroll) console.log(event) // console.log('hi') } window.onload = function(){ setTimeout(function(){ germany.style.opacity = 1 animateIn(germany) },500) setTimeout(function(){ france.style.opacity = 1 animateIn(france) },800) setTimeout(function(){ spain.style.opacity = 1 animateIn(spain) },1200) } function onScroll() { var scrollPosition = window.pageYOffset germany.style.opacity = scrollPosition/100 // console.log('im scrolling') } function animateIn(elem){ elem.style.opacity = 1 elem.style.transform = 'translateX(10px)' }
module.exports = '0.0.0.0'
$(document).ready(function(){ // $("#main-nav-container").load("nav.html"); // Proper way to load the htmls with jquery load method - from tuts+ // $(".page-links").on('click', function( e ) { // var href = $(this).attr('href'); // $('.content-row').load(href + ' .content-container'); // e.preventDefault(); // /* Act on the event */ // }); });
/** * 두 날짜 차이 비교 */ exports.DateDiff = { Second: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/1000); }, Minute: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/1000/60); }, Day: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/(24*3600*1000)); }, Weeks: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/(24*3600*1000*7)); }, Month: function(d1, d2) { var d1Y = d1.getFullYear(); var d2Y = d2.getFullYear(); var d1M = d1.getMonth(); var d2M = d2.getMonth(); return (d2M+12*d2Y)-(d1M+12*d1Y); }, Year: function(d1, d2) { var t = d2.getFullYear() - d1.getFullYear(); return t; } }; /** * 오늘기준 +/- (년/월/일) 날짜 가져오기 */ exports.DateAdd = { Day: function(v) { var today = new Date(); return new Date(today.getFullYear(), today.getMonth(), today.getDate() + v); }, Month: function(v) { var today = new Date(); return new Date(today.getFullYear(), today.getMonth() + v, today.getDate()); }, Year: function(v) { var today = new Date(); return new Date(today.getFullYear() + v, today.getMonth(), today.getDate()); }, Hour: function(v) { var today = new Date(); return new Date(today.getFullYear(), today.getMonth(), today.getDate(), today.getHours() + v, today.getMinutes(), today.getSeconds()); }, Minute: function(v) { var today = new Date(); return new Date(today.getFullYear(), today.getMonth(), today.getDate(), today.getHours(), today.getMinutes() + v, today.getSeconds()); }, Second: function(v) { var today = new Date(); return new Date(today.getFullYear(), today.getMonth(), today.getDate(), today.getHours(), today.getMinutes(), today.getSeconds() + v); } }; /** * 임의 날짜 +/- (년/월/일) 날짜 가져오기 */ exports.DateAddCustom = { Day: function(d, v) { return new Date(d.getFullYear(), d.getMonth(), d.getDate() + v); }, Month: function(d, v) { return new Date(d.getFullYear(), d.getMonth() + v, d.getDate()); }, Year: function(d, v) { return new Date(d.getFullYear() + v, d.getMonth(), d.getDate()); }, Hour: function(d, v) { return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + v, d.getMinutes(), d.getSeconds()); }, Minute: function(d, v) { return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes() + v, d.getSeconds()); }, Second: function(d, v) { return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds() + v); } }; /** * 문자열을 날짜형식으로 변경 */ exports.Str2Date = function(s) { var year = 0, month = 0, day = 0; var hour = 0, minute = 0, second = 0; if (s.indexOf(" ") > -1) { var items = s.split(" "); if (isDate(s) == false) { return null; } var arrDay = items[0].split("-"); year = parseInt(arrDay[0]); month = parseInt(arrDay[1].replace(/^0(\d)/g,"$1")); day = parseInt(arrDay[2].replace(/^0(\d)/g,"$1")); if (items[1].split(":").length == 3) { var arrTime = items[1].split(":"); hour = parseInt(arrTime[0]); minute = parseInt(arrTime[1]); second = parseInt(arrTime[2]); } else { return null; } } else { if (isDate(s) == false) { return null; } var arrDay = s.split("-"); year = parseInt(arrDay[0]); month = parseInt(arrDay[1].replace(/^0(\d)/g,"$1")); day = parseInt(arrDay[2].replace(/^0(\d)/g,"$1")); } return new Date(year, month - 1, day, hour, minute, second); }; /* * 문자열 날짜형식 여부 확인 */ function isDate(s) { var valid = false; if (s.search(/\d{4}-([1-9]|0[1-9]|1[0-2])-([1-9]|[0-3][0-9])/) == 0) { var arrDay = s.split("-"); var year = parseInt(arrDay[0]); var month = parseInt(arrDay[1].replace(/^0(\d)/g,"$1")); var day = parseInt(arrDay[2].replace(/^0(\d)/g,"$1")); var d = new Date(year, month - 1, day); if (d.getMonth() == month - 1 && d.getDate() == day) valid = true ; } return valid; } /** * 날짜를 yyyy-MM-dd 형식으로 출력 */ exports.PrtDate = function(d) { var prtString = d.getFullYear().toString() + "-"; var month = d.getMonth() + 1; var day = d.getDate(); if (month < 10) { prtString += "0" + month.toString(); } else { prtString += month.toString(); } prtString += "-"; if (day < 10) { prtString += "0" + day.toString(); } else { prtString += day.toString(); } return prtString; }; /** * 날짜를 yyyyMMdd 형식으로 출력 * @param d * @returns */ exports.PrtDateNoDash = function(d) { var prtString = d.getFullYear().toString(); var month = d.getMonth() + 1; var day = d.getDate(); if (month < 10) { prtString += "0" + month.toString(); } else { prtString += month.toString(); } if (day < 10) { prtString += "0" + day.toString(); } else { prtString += day.toString(); } return prtString; }; /** * 날짜를 yyyyMMddHHmmss 형식으로 출력 * @param d * @returns */ exports.PrtDateTimeNoDash = function(d) { var prtString = d.getFullYear().toString(); var month = d.getMonth() + 1; var day = d.getDate(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); if (month < 10) { prtString += "0" + month.toString(); } else { prtString += "" + month.toString(); } if (day < 10) { prtString += "0" + day.toString(); } else { prtString += "" + day.toString(); } if (hours < 10) { prtString += "0" + hours.toString(); } else { prtString += "" + hours.toString(); } if (minutes < 10) { prtString += "0" + minutes.toString(); } else { prtString += "" + minutes.toString(); } if (seconds < 10) { prtString += "0" + seconds.toString(); } else { prtString += "" + seconds.toString(); } return prtString; }; /** * 날짜를 yyyy-MM-dd hh:mm:ss 형식으로 출력 */ exports.PrtDateTime = function(d) { var prtString = d.getFullYear().toString(); var month = d.getMonth() + 1; var day = d.getDate(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); if (month < 10) { prtString += "-0" + month.toString(); } else { prtString += "-" + month.toString(); } if (day < 10) { prtString += "-0" + day.toString(); } else { prtString += "-" + day.toString(); } if (hours < 10) { prtString += " 0" + hours.toString(); } else { prtString += " " + hours.toString(); } if (minutes < 10) { prtString += ":0" + minutes.toString(); } else { prtString += ":" + minutes.toString(); } if (seconds < 10) { prtString += ":0" + seconds.toString(); } else { prtString += ":" + seconds.toString(); } return prtString; }; /** * 날짜를 hh:mm:ss 형식으로 출력 */ exports.PrtTime = function(d) { var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var prtString = ""; if (hours < 10) { prtString += "0" + hours.toString(); } else { prtString += "" + hours.toString(); } if (minutes < 10) { prtString += ":0" + minutes.toString(); } else { prtString += ":" + minutes.toString(); } if (seconds < 10) { prtString += ":0" + seconds.toString(); } else { prtString += ":" + seconds.toString(); } return prtString; }; /** * 날짜를 hhmmss 형식으로 출력 */ exports.PrtTimeNoDash = function(d) { var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var prtString = ""; if (hours < 10) { prtString += "0" + hours.toString(); } else { prtString += "" + hours.toString(); } if (minutes < 10) { prtString += "0" + minutes.toString(); } else { prtString += "" + minutes.toString(); } if (seconds < 10) { prtString += "0" + seconds.toString(); } else { prtString += "" + seconds.toString(); } return prtString; }; /** * 해당월의 마지막일을 가져오기 */ exports.GetMonthLastDay = function(y, m) { if (y + "-" + m + "1".isDate() == false) return 0; y = parseInt(y); m = parseInt(m); var monthLastDay = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); //각 달별 마지막날 저장 var currentLastDay = monthLastDay[m - 1]; //윤년계산 if (m == 2) { if ((y % 400) == 0) currentLastDay = 29; else if (((y % 4) == 0) && ((y % 100) > 0)) currentLastDay = 29; } return currentLastDay; }; /** * 초단위로 시간단위 환산 * return : {h:시, m:분, s:초, d:일, dh:일기준 시} */ exports.secondsToTime = function(secs) { var hours = Math.floor(secs / (60 * 60)); var divisor4minutes = secs % (60 * 60); var minutes = Math.floor(divisor4minutes / 60); if (minutes < 10) minutes = "0" + minutes; var divisor4seconds = divisor4minutes % 60; var seconds = Math.floor(divisor4seconds); if (seconds < 10) seconds = "0" + seconds; var days = Math.floor(hours / 24); var daysHour = hours % 24; if (daysHour < 10) daysHour = "0" + daysHour; var obj = { h: hours, m: minutes, s: seconds, d: days, dh: daysHour }; return obj; };
var findKthPositive = function(arr, k) { let missing = []; let i=1; while(missing.length<k){ if(arr.indexOf(i)===-1){ missing.push(i) } i++ } return missing[k-1] };
import { StatusBar } from 'expo-status-bar'; import React, { useState, useEffect } from 'react'; import { StyleSheet, Text, View,ScrollView,Dimensions, FlatList,Modal} from 'react-native'; import Header from '../header' import { Entypo,Octicons,FontAwesome,MaterialCommunityIcons } from '@expo/vector-icons'; import CardC from '../card' import { Chip,Searchbar,Button,ActivityIndicator, Colors } from 'react-native-paper'; import Constant from 'expo-constants' import { Video } from 'expo-av' import VideoPlayer from 'expo-video-player' import {WebView} from 'react-native-webview' export default function Player({route}){ console.log(route) const link ='https://www.youtube.com/embed/'+route.params.id+'/' console.log(link) return( // <View style={{flex:0.5}}> // <VideoPlayer // videoProps={{ // shouldPlay: true, // resizeMode: Video.RESIZE_MODE_CONTAIN, // source: { // uri:'http://techslides.com/demos/sample-videos/small.webm' // }, // }} // inFullscreen={true} // /> // </View> <View style={{ height: 300,marginTop:150 }}> <WebView javaScriptEnabled={true} domStorageEnabled={true} source={{uri: link }} /> </View> ) }
var cfg = require("../../utils/cfg.js"); var config = require("../../utils/config.js"); var regeneratorRuntime = require("../../utils/runtime.js"); var event = require("../../utils/event.js"); var app = getApp(); Component({ options: { addGlobalClass: true, }, data: { projects: [], nodata: '', showSkeleton: true }, attached: function () { // wx.newWx.showLoading({title:'数据正在请求中'}) // .then(wx.newWx.hideLoading) // this.switchPage([this.getProjects(),this.getTasks()]) var pages = getCurrentPages() var page = pages[pages.length - 1].route switch (page) { case "pages/index/index": this.getProjects() break; case "pagesA/my_task/index": this.getTasks() break; } this.setData({ nodata: app.language('validator.nodata') }) }, methods: { switchPage: function ([a, b]) { var pages = getCurrentPages() var page = pages[pages.length - 1].route switch (page) { case "pages/index/index": return a break; case "pagesA/my_task/index": return b break; } }, viewProject: function (e) { let id = e.currentTarget.dataset.id; // this.switchPage([wx.navigateTo({ // url: '../../pagesA/task_detail/index?taskid=' + id, // }), wx.navigateTo({ // url: '../../pagesA/task_revises/index?taskid=' + id, // })]) var pages = getCurrentPages() var page = pages[pages.length - 1].route switch (page) { case "pages/index/index": wx.navigateTo({ url: '../../pagesA/task_detail/index?taskid=' + id, }) break; return; case "pagesA/my_task/index": wx.navigateTo({ url: '../../pagesA/task_revises/index?taskid=' + id, }) break; } }, filterSopType: function (tasklist) { var tmp = [] for (var k in tasklist) { if (tasklist[k].sopType.indexOf("COLLECT") != -1 || tasklist[k].sopType.indexOf("TEXTTRANS") != -1) { tmp.push(tasklist[k]) } } return tmp }, async Projects(tempurl) { // wx.getStorage({ // key: 'projects', // success: res=> { // console.log(res,'resresres') // this.setData({ // projects: res.data // }) // } // }) cfg.wxPromise(wx.request)({ url: tempurl, header: app.globalData.header, }) .then(res => { if (res.statusCode === 200) { if ((res.data.projects.length === 0) || (res.data.projects === null)) { cfg.titleToast(app.language('validator.nodata')) } // this.switchPage([this.setData({ // projects: this.filterSopType(res.data.projects) // }), this.setData({ // projects: res.data.projects // })]) var pages = getCurrentPages() var page = pages[pages.length - 1].route switch (page) { case "pages/index/index": this.setData({ projects: this.filterSopType(res.data.projects) }); break; default: this.setData({ projects: res.data.projects }); break; } wx.setStorage({ key: "projects", data: this.data.projects, }) } else { cfg.titleToast(app.language('validator.loadingfature')) } }) }, getProjects () { let url = cfg.getAPIURL() + "/api/projects" this.Projects(url) }, getTasks () { let url = cfg.getAPIURL() + "/api/projects?username=true" this.Projects(url) } } })
import { createAction } from 'redux-actions'; export const GET_TAGS = "GET_TAGS"; export const BUILD_CLOUD = "BUILD_CLOUD"; const getTagsAction = createAction(GET_TAGS); const buildCloudAction = createAction(BUILD_CLOUD); export { getTagsAction, buildCloudAction };
import {combineReducers, createStore} from 'redux'; import Watcher, { ADD_EVENT, CHANGE_EVENT, UNLINK_EVENT, ADD_DIR_EVENT, UNLINK_DIR_EVENT, ERROR_EVENT, READY_EVENT, RAW_EVENT, } from './services/watcher' import File, { addFile, removeFile, updateFile, } from './models/file'; import path from 'path'; import React from 'react'; import {Provider} from 'react-redux'; import App from './containers/App'; /** * Initialize the application. * @param {String} selector CSS selector for the application's root element. */ export default function(selector) { const cwd = process.cwd(); const DATA_DIR = `${cwd}/data`; const FILES_DIR = `${DATA_DIR}/files`; // Initialize the data store. const store = createStore(combineReducers({ files: File })); // Initialize the filesystem watcher. const watcher = new Watcher(FILES_DIR); function getRelativePath(absolutePath) { return path.relative(cwd, absolutePath); } watcher.on(ADD_EVENT, function(absolutePath, stat) { const relativePath = getRelativePath(absolutePath); store.dispatch(addFile(relativePath, stat)); }); watcher.on(ADD_DIR_EVENT, function(absolutePath, stat) { const relativePath = getRelativePath(absolutePath); store.dispatch(addFile(relativePath, stat)); }); watcher.on(UNLINK_EVENT, function(absolutePath) { const relativePath = getRelativePath(absolutePath); store.dispatch(removeFile(relativePath)); }); watcher.on(UNLINK_DIR_EVENT, function(absolutePath) { const relativePath = getRelativePath(absolutePath); store.dispatch(removeFile(relativePath)); }); watcher.on(RAW_EVENT, function(event, absolutePath, stats) { if (event === CHANGE_EVENT) { const relativePath = getRelativePath(absolutePath); store.dispatch(updateFile(relativePath, stats.curr)); } }); // Initialize the view. React.render( <Provider store={store}>{() => <App />}</Provider>, document.querySelector(selector) ); };
$(function(){ $('.login-btn button').click(function(event) { window.location.href='index.html'; }); })
({ onFocus : function(component, event, helper){ var forOpen = component.find("searchRes"); $A.util.addClass(forOpen, "slds-is-open"); $A.util.removeClass(forOpen, "slds-is-close"); var getInputkeyWord = ''; helper.searchHelper(component, event, helper, getInputkeyWord); }, keyPressController : function(component, event, helper) { var getInputkeyWord = component.get("v.searchKeyWord"); if (getInputkeyWord.length > 0 ){ var forOpen = component.find("searchRes"); $A.util.addClass(forOpen, "slds-is-open"); $A.util.removeClass(forOpen, "slds-is-close"); helper.searchHelper(component, event, helper, getInputkeyWord); } else { component.set("v.listOfSearchRecords", null ); var forclose = component.find("searchRes"); $A.util.addClass(forclose, "slds-is-close"); $A.util.removeClass(forclose, "slds-is-open"); } }, handleComponentEvent : function(component, event, helper) { var selectedObjectGetFromEvent = event.getParam("recordByEvent"); component.set("v.selectedRecord", selectedObjectGetFromEvent); var forclose = component.find("searchRes"); $A.util.addClass(forclose, "slds-is-close"); $A.util.removeClass(forclose, "slds-is-open"); helper.clearSearch(component); } })
var a; function showHideAdd () { if (a == 1) { document.getElementById ("inputAdd").style.visibility = "visible"; return a = 0; } else { document.getElementById ("inputAdd").style.visibility = "hidden"; return a = 1; } } var b; function showHideRemove() { if (b == 1) { document.getElementById("removeStocksFieldset").style.visibility = "visible"; return b = 0; } else { document.getElementById("removeStocksFieldset").style.visibility = "hidden"; return b = 1; } }
var gulp = require('gulp'), gutil = require('gulp-util'), sass = require('gulp-sass'), concat = require('gulp-concat'), connect = require('gulp-connect'); gulp.task('sass', function () { gulp.src('./scss/*.scss') .pipe(sass({errLogToConsole: true})) .pipe(gulp.dest('./css/tmp/')) }); gulp.task('concat', function(){ gulp.src('./css/tmp/*.css') .pipe(concat('style.css')) .pipe(gulp.dest('./css/')); }); gulp.task('reload', function (){ gulp.src('./index.html') //optimize! .pipe(connect.reload()); }); gulp.task('webserver', function (){ connect.server({ livereload: true }); }); gulp.task('watch', function(){ gulp.watch('./scss/*.scss', ['sass', 'concat', 'reload']); gulp.watch('./index.html', ['reload']); }); gulp.task('default', ['sass', 'concat', 'webserver', 'watch']);
import React, { Component, PropTypes } from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Snackbar } from 'material-ui'; import { Navbar } from 'containers'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as SettingActionCreators from 'actions/settings'; import * as ScheduleActionCreators from 'actions/schedule'; class Main extends Component { constructor() { super(); this.handleCloseSnackbar = this.handleCloseSnackbar.bind(this); this.addOfflineEventListeners = this.addOfflineEventListeners.bind(this); this.state = { snackbar: { isOpen: false, message: '' } }; } componentDidMount() { const { actions, needsDefaultSchedule } = this.props; this.addOfflineEventListeners(); if (needsDefaultSchedule) { actions.fetchAndCacheDefaultSchedule(); } else { actions.loadCachedDefaultSchedule(); } } componentWillReceiveProps(newProps) { const { isOffline, alertMessage } = newProps; if (this.props.isOffline !== isOffline) { this.setState({ snackbar: { isOpen: true, message: alertMessage } }); } } componentWillUnmount() { window.removeEventListener('online', (e) => e); window.removeEventListener('offline', (e) => e); } addOfflineEventListeners() { const { actions } = this.props; window.addEventListener('online', () => { const message = 'The browser is back online! Hurray 🎉🎉🎉!'; actions.setOfflineMode(false, message); }, true); window.addEventListener('offline', () => { const message = `The application is offline, but our offline worker 🐝🐝🐝s will load a default schedule for you!`; actions.setOfflineMode(true, message); }, true); } handleCloseSnackbar() { this.setState({ snackbar: { isOpen: false, message: '' } }); } render() { const { snackbar } = this.state; return ( <div className="main"> <MuiThemeProvider> <Navbar> {React.cloneElement(this.props.children, this.props)} <Snackbar open={snackbar.isOpen} message={snackbar.message} autoHideDuration={4000} action="Okay" onActionTouchTap={this.handleCloseSnackbar} onRequestClose={this.handleCloseSnackbar} /> </Navbar> </MuiThemeProvider> </div> ); } } Main.propTypes = { isOffline: PropTypes.bool.isRequired, children: PropTypes.element.isRequired, actions: PropTypes.object.isRequired, alertMessage: PropTypes.string.isRequired, needsDefaultSchedule: PropTypes.bool.isRequired }; const mapStateToProps = (state) => ({ isOffline: state.settings.offlineMode, alertMessage: state.settings.alertMessage, needsDefaultSchedule: !state.schedule.defaultSchedule.hasLoaded }); const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators( Object.assign({}, SettingActionCreators, ScheduleActionCreators ), dispatch) }); export default connect( mapStateToProps, mapDispatchToProps )(Main);
import SendEmail from '../component/SendEmail/SendEmail' const Email = () => ( <div className="main-div"> <h2>Send email to one's, who refered the shop</h2> <SendEmail /> <style>{` .main-div { display: flex; justify-content: center; align-items: center; flex-direction: column; margin-top: 50px } `}</style> </div> ) export default Email;
const request = require('request') //Return the run as user ID to be used in the bot deployment API const bot = (crURL, token, botName, callback) => { const url = crURL + '/v2/repository/workspaces/public/files/list' request({ url : url, method :"POST", headers : { "content-type": "application/json", "X-Authorization": token }, body: { //json body to filter based on bot name provided 'sort':[ { 'field':'name', 'direction':'asc' } ], 'filter':{ 'operator': 'eq', 'field': 'name', 'value': botName }, 'fields':[], 'page':{ 'length':5, 'offset':0 } }, json: true }, (e, r, body)=>{ if(e){ callback('Connection with control room failed. Please try again.', undefined) } else if (r.body.message){ callback(body.message, undefined) } else if (body.list.length===0) { callback('Bot name not found. Please try again.', undefined) } else { callback(undefined, { botId: r.body.list[0].id }) } }) } module.exports = bot
import React, { Component } from "react"; import { Redirect } from "react-router-dom"; import axios from "axios"; import { CloudinaryContext, Image } from "cloudinary-react"; import Navbar from "./Navbar"; import Title from "./Title"; class Photos extends Component { constructor(props) { super(props); this.state = { albumTitle: "", albumDesc: "", photos: [], render: true, width: "300" }; this.getPhotos = this.getPhotos.bind(this); this.handleUploadWidget = this.handleUploadWidget.bind(this); this.handleLogout = this.handleLogout.bind(this); } componentDidMount() { this.getPhotos(); } getPhotos() { let id = this.props.match.params.albumid; axios.get(`/album/${id}`).then(response => { console.log(response); if (response.status === 200) { this.setState({ albumTitle: response.data.album.title, albumDesc: response.data.album.description, photos: response.data.photos }); } }); } handleUploadWidget(event) { event.preventDefault(); window.cloudinary.openUploadWidget( { cloud_name: "pixo", upload_preset: "zupqatkm", folder: `${this.props.match.params.userId}/${ this.props.match.params.albumid }` }, (error, result) => { console.log(result); let newFiles = []; for (let i in result) { newFiles.push({ path: result[i].public_id, name: result[i].original_filename }); } axios .post("/photos", { albumId: this.props.match.params.albumid, files: newFiles }) .then(response => { console.log(response); this.getPhotos(); }); } ); } handleLogout(event) { event.preventDefault(); axios.get("/logout").then(response => { this.setState({ loggedIn: false }); }); } render() { if (this.state.loggedIn === false) { return <Redirect to="/" />; } let photos = this.state.photos.map((photo, i) => { return ( <div key={i}> <Image publicId={photo.path} width={this.state.width} /> <p className="image desc"> {photo.name} </p> </div> ); }); return ( <div> <Navbar home={true} photos={true} handlerFn={this.handleUploadWidget} userId={this.props.match.params.userId} logoutFn={this.handleLogout} /> <Title text={this.state.albumTitle} /> <Title text={this.state.albumDesc} /> <CloudinaryContext className="grid" cloudName="pixo"> {photos} </CloudinaryContext> </div> ); } } export default Photos;
18 gid=1329781531 17 uid=183816338 20 ctime=1441138964 20 atime=1441138971 23 SCHILY.dev=16777221 23 SCHILY.ino=32546048 18 SCHILY.nlink=1
// import axios from 'axios'; export const finance = () => true;
import React from 'react' const Person = ({ person, handleDeletePerson }) => ( <tr> <td>{person && person.name}</td> <td>{person && person.number}</td> <td>{person && <button onClick={(e) => handleDeletePerson(e, person._id)}>delete</button> }</td> </tr> ) export default Person
require('../../connections'); const { graphql, setup, teardown } = require('./utils'); const { CursorType } = require('@limit0/graphql-custom-types'); const PlacementRepo = require('../../../src/repositories/placement'); const PublisherRepo = require('../../../src/repositories/publisher'); const createPublisher = async () => { const results = await PublisherRepo.seed(); return results.one(); }; const createPlacement = async () => { const results = await PlacementRepo.seed(); return results.one(); }; const createPlacements = async (count) => { const results = await PlacementRepo.seed({ count }); return results.all(); }; describe('graph/resolvers/placement', function() { before(async function() { await setup(); await PlacementRepo.remove(); }); after(async function() { await teardown(); await PlacementRepo.remove(); }); describe('Query', function() { describe('placement', function() { let placement; before(async function() { placement = await createPlacement(); }); const query = ` query Placement($input: ModelIdInput!) { placement(input: $input) { id name createdAt updatedAt publisher { id name } } } `; it('should reject when no user is logged-in.', async function() { const id = '507f1f77bcf86cd799439011'; const input = { id }; const variables = { input }; await expect(graphql({ query, variables, key: 'placement', loggedIn: false })).to.be.rejectedWith(Error, /you must be logged-in/i); }); it('should reject if no record was found.', async function() { const id = '507f1f77bcf86cd799439011'; const input = { id }; const variables = { input }; await expect(graphql({ query, variables, key: 'placement', loggedIn: true })).to.be.rejectedWith(Error, `No placement record found for ID ${id}.`); }); it('should return the requested placement.', async function() { const id = placement.id; const input = { id }; const variables = { input }; const promise = graphql({ query, variables, key: 'placement', loggedIn: true }); await expect(promise).to.eventually.be.an('object').with.property('id', id); const data = await promise; expect(data).to.have.all.keys('id', 'name', 'createdAt', 'updatedAt', 'publisher'); }); }); describe('allPlacements', function() { let placements; before(async function() { await PlacementRepo.remove(); placements = await createPlacements(10); }); after(async function() { await PlacementRepo.remove(); }); const query = ` query AllPlacements($pagination: PaginationInput, $sort: PlacementSortInput) { allPlacements(pagination: $pagination, sort: $sort) { totalCount edges { node { id name } cursor } pageInfo { hasNextPage endCursor } } } `; it('should reject when no user is logged-in.', async function() { await expect(graphql({ query, key: 'allPlacements', loggedIn: false })).to.be.rejectedWith(Error, /you must be logged-in/i); }); it('should return five placements out of ten.', async function() { const pagination = { first: 5 }; const variables = { pagination }; const promise = graphql({ query, key: 'allPlacements', variables, loggedIn: true }); await expect(promise).to.eventually.be.an('object'); const data = await promise; expect(data.totalCount).to.equal(10); expect(data.edges.length).to.equal(5); expect(data.pageInfo.hasNextPage).to.be.true; expect(data.pageInfo.endCursor).to.be.a('string'); const last = data.edges.pop(); expect(data.pageInfo.endCursor).to.equal(last.cursor); }); it('should not have a next page when limited by more than the total.', async function() { const pagination = { first: 50 }; const variables = { pagination }; const promise = graphql({ query, key: 'allPlacements', variables, loggedIn: true }); await expect(promise).to.eventually.be.an('object'); const data = await promise; expect(data.totalCount).to.equal(10); expect(data.edges.length).to.equal(10); expect(data.pageInfo.hasNextPage).to.be.false; }); it('should return an error when an after cursor is requested that does not exist.', async function() { const { id } = PlacementRepo.generate(1, { publisherId: () => '1234' }).one(); const after = CursorType.serialize(id); const pagination = { first: 5, after }; const variables = { pagination }; const promise = graphql({ query, key: 'allPlacements', variables, loggedIn: true }); await expect(promise).to.be.rejectedWith(Error, `No record found for ID '${id}'`); }); }); // describe('searchPlacements', function() { // let placements, model; // before(async function() { // await PlacementRepo.remove(); // placements = await createPlacements(10); // model = placements[0]; // }); // after(async function() { // await PlacementRepo.remove(); // }); // const field = 'name'; // const query = ` // query SearchPlacements($pagination: PaginationInput, $search: PlacementSearchInput!) { // searchPlacements(pagination: $pagination, search: $search) { // totalCount // edges { // node { // id // name // } // cursor // } // pageInfo { // hasNextPage // endCursor // } // } // } // `; // it('should reject when no user is logged-in.', async function() { // const pagination = { first: 5 }; // const search = { typeahead: { field, term: 'John' }} // const variables = { pagination, search }; // await expect(graphql({ query, variables, key: 'searchPlacements', loggedIn: false })).to.be.rejectedWith(Error, /you must be logged-in/i); // }); // it('should return at most 5 results.', async function() { // const pagination = { first: 5 }; // const search = { typeahead: { field, term: 'John' }} // const variables = { pagination, search }; // const promise = graphql({ query, key: 'searchPlacements', variables, loggedIn: true }); // await expect(promise).to.eventually.be.an('object'); // const data = await promise; // expect(data.totalCount).to.be.at.most(10); // expect(data.edges.length).to.be.at.most(5); // }); // it('should return an error when an after cursor is requested that does not exist.', async function() { // const after = CursorType.serialize(PlacementRepo.generate(1, { publisherId: () => '1234' }).one().id); // const pagination = { first: 5, after }; // const search = { typeahead: { field, term: 'John' }} // const variables = { pagination, search }; // const promise = graphql({ query, key: 'searchPlacements', variables, loggedIn: true }); // await expect(promise).to.be.rejectedWith(Error, `No record found for cursor '${after}'.`); // }); // it('should reject if field is not specified.', async function() { // const pagination = { first: 5 }; // const search = { typeahead: { term: 'John' }} // const variables = { pagination, search }; // await expect(graphql({ query, variables, key: 'searchPlacements', loggedIn: true })).to.be.rejectedWith(Error, /Field value\.typeahead\.field of required type PlacementTypeAheadField! was not provided/i); // }); // it('should always return an array', async function() { // const pagination = { first: 5 }; // const search = { typeahead: { field, term: 'this should never be found unless someone is dumb' }} // const variables = { pagination, search }; // const promise = graphql({ query, variables, key: 'searchPlacements', loggedIn: true }) // const data = await expect(promise).to.eventually.be.an('object'); // expect(data.edges).to.be.an('array') // }); // it('should return the expected model', async function() { // const { id, name } = model; // const pagination = { first: 5 }; // const search = { typeahead: { field, term: name }} // const variables = { pagination, search }; // const promise = graphql({ query, variables, key: 'searchPlacements', loggedIn: true }) // const data = await expect(promise).to.eventually.be.an('object'); // expect(data.edges).to.be.an('array') // expect(data.edges[0].node).to.deep.include({ id, name }); // }); // it('should allow partial searches', async function() { // const { id, name } = model; // const term = name.substr(0, 3); // const pagination = { first: 5 }; // const search = { typeahead: { field, term }} // const variables = { pagination, search }; // const promise = graphql({ query, variables, key: 'searchPlacements', loggedIn: true }) // const data = await expect(promise).to.eventually.be.an('object'); // expect(data.edges).to.be.an('array') // expect(data.edges[0].node).to.deep.include({ id, name }); // }); // it('should allow case-insensitive searches', async function() { // const { id, name } = model; // const term = name.toUpperCase(); // const pagination = { first: 5 }; // const search = { typeahead: { field, term }} // const variables = { pagination, search }; // const promise = graphql({ query, variables, key: 'searchPlacements', loggedIn: true }) // const data = await expect(promise).to.eventually.be.an('object'); // expect(data.edges).to.be.an('array') // expect(data.edges[0].node).to.deep.include({ id, name }); // }); // }); }); describe('Mutation', function() { describe('createPlacement', function() { let publisher; before(async function() { publisher = await createPublisher(); }); after(async function() { await PublisherRepo.remove(); }); const query = ` mutation CreatePlacement($input: CreatePlacementInput!) { createPlacement(input: $input) { id name publisher { id name } createdAt updatedAt } } `; it('should reject when no user is logged-in.', async function() { const payload = { name: 'Test Placement', publisherId: publisher.id, }; const input = { payload }; const variables = { input }; await expect(graphql({ query, variables, key: 'createPlacement', loggedIn: false })).to.be.rejectedWith(Error, /you must be logged-in/i); }); it('should create the placement.', async function() { const payload = { name: 'Test Placement', publisherId: publisher.id, }; const input = { payload }; const variables = { input }; const promise = graphql({ query, variables, key: 'createPlacement', loggedIn: true }); await expect(promise).to.eventually.be.an('object').with.property('id'); const data = await promise; await expect(PlacementRepo.findById(data.id)).to.eventually.be.an('object').with.property('name', payload.name); }); }); describe('updatePlacement', function() { let placement; let publisher; before(async function() { placement = await createPlacement(); publisher = await createPublisher(); }); const query = ` mutation UpdatePlacement($input: UpdatePlacementInput!) { updatePlacement(input: $input) { id name publisher { id name } createdAt updatedAt } } `; it('should reject when no user is logged-in.', async function() { const payload = { name: 'Updated Placement Name', publisherId: publisher.id, }; const id = '507f1f77bcf86cd799439011' const input = { id, payload }; const variables = { input }; await expect(graphql({ query, variables, key: 'updatePlacement', loggedIn: false })).to.be.rejectedWith(Error, /you must be logged-in/i); }); it('should reject when the placement record is not found.', async function() { const payload = { name: 'Updated Placement Name', publisherId: publisher.id, }; const id = '507f1f77bcf86cd799439011' const input = { id, payload }; const variables = { input }; await expect(graphql({ query, variables, key: 'updatePlacement', loggedIn: true })).to.be.rejectedWith(Error, `Unable to update placement: no record was found for ID '${id}'`); }); it('should update the placement.', async function() { const payload = { name: 'Updated Placement Name', publisherId: publisher.id, }; const id = placement.id; const input = { id, payload }; const variables = { input }; const promise = graphql({ query, variables, key: 'updatePlacement', loggedIn: true }); await expect(promise).to.eventually.be.an('object').with.property('id'); const data = await promise; expect(data.name).to.equal(payload.name); expect(data.publisher.id).to.equal(payload.publisherId); await expect(PlacementRepo.findById(data.id)).to.eventually.be.an('object').with.property('name', payload.name); }); }); }); });
import React from 'react' import PropTypes from 'prop-types' // redux import { bindActionCreators } from 'redux' import { connect } from 'react-redux' // module import { ActionCreators as AppActions } from '../../modules/app/actions' import { ActionCreators as ClientActions } from '../../modules/clients/actions' import ClientSelectors from '../../modules/clients/selectors' import ClientFormSelectors from '../../modules/clients/client-form-selectors' import { getLocale } from '../../modules/app/selectors' // components import {createTranslate} from '../../locales/translate' import { FormError } from '../components/forms/FormError' import makeStandardToolbar from '../components/behavioral/StandardListToolbar' import {ConfirmButton} from '../components/controls/SemanticControls' import {SmartTable, Column, renderLinkToDetail} from '../components/SmartTable' import {Pagination} from '../components/Pagination' const labelNamespace = 'clients' const StandardToolbar = makeStandardToolbar(ClientActions, ClientSelectors, labelNamespace, 'clients') const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators(ClientActions, dispatch), appActions: bindActionCreators(AppActions, dispatch) } } class ListClientsPage extends React.PureComponent { constructor (props) { super(props) this.message = createTranslate(labelNamespace, this) this.handleDelete = this.handleDelete.bind(this) } componentWillMount () { this.props.actions.clearSelectedItems() this.props.actions.setEditedEntity(null) this.props.actions.fetchList(this.props.urlParams) this.props.actions.fetchClientForm() } componentWillReceiveProps (nextProps) { if (nextProps.urlParams !== this.props.urlParams) { this.props.actions.fetchList(nextProps.urlParams) } } handleDelete () { const selectedItemIds = this.props.selectedItemIds const count = selectedItemIds.length const actions = this.props.actions const appActions = this.props.appActions actions.deleteEntities(selectedItemIds, ids => { actions.clearSelectedItems() appActions.notify('common.delete', 'common.deleted', {count}) }) } render () { const {formError, locale} = this.props return ( <div> <StandardToolbar location={this.props.location}> {this.props.isDisplayingArchived === false && <a className="btn btn-secondary" href="/api/reports/client-list">{this.message('export', 'common')}</a> } {this.props.isDisplayingArchived && <ConfirmButton locale={locale} onClick={this.handleDelete} disabled={this.props.isListDeleteEnabled}> {this.message('delete', 'common')} </ConfirmButton> } </StandardToolbar> <FormError error={formError} locale={locale} /> <SmartTable rows={this.props.entities} selectable selectedItemIds={this.props.selectedItemIds} onRowSelected={this.props.actions.toggleSelectedItem} location={this.props.location} clientTypesById={this.props.clientTypesById} > <Column name="lastName" label={this.message('lastName')} renderer={renderLinkToDetail} /> <Column name="firstName" label={this.message('firstName')} renderer={renderLinkToDetail} /> <Column name="clientType" label={this.message('clientType')} /> </SmartTable> {this.props.totalPages > 1 && <div className="ui centered grid"> <div className="center aligned column"> <Pagination location={this.props.location} totalPages={this.props.totalPages} /> </div> </div> } </div> ) } } const mapStateToProps = (state, props) => { return { urlParams: ClientSelectors.getUrlParams(state, props), entities: ClientSelectors.getEntitiesPage(state), totalPages: ClientSelectors.getTotalPages(state, props), listFilters: ClientSelectors.getFilters(state, props), isDisplayingArchived: ClientSelectors.isListDisplayingArchived(state, props), selectedItemIds: ClientSelectors.getSelectedItemIds(state), locale: getLocale(state), clientTypesById: ClientFormSelectors.getClientTypeOptions(state), formError: ClientSelectors.getSubmitError(state), isDeleteEnabled: ClientSelectors.isListDeleteEnabled(state) } } ListClientsPage.propTypes = { urlParams: PropTypes.object.isRequired, entities: PropTypes.array.isRequired, totalPages: PropTypes.number.isRequired, listFilters: PropTypes.object.isRequired, isDisplayingArchived: PropTypes.bool.isRequired, selectedItemIds: PropTypes.array.isRequired, locale: PropTypes.string.isRequired, location: PropTypes.object.isRequired, formError: PropTypes.any } const ConnectedListClientsPage = connect(mapStateToProps, mapDispatchToProps)(ListClientsPage) export default ConnectedListClientsPage
// This file is loading model //var vertexPositionBuffer; var vertexNormalBuffer; var vertexTextureCoordBuffer; var vertexIndexBuffer; var vertexColorBuffer; var model; function handleLoadedCornellbox(modelData) { console.log("LoadModel"); /*vertexNormalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexNormalBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.normals), gl.STATIC_DRAW); vertexNormalBuffer.itemSize = 3; vertexNormalBuffer.numItems = modelData.normals.length / vertexNormalBuffer.itemSize; vertexTextureCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexTextureCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.uvs), gl.STATIC_DRAW); vertexTextureCoordBuffer.itemSize = 2; vertexTextureCoordBuffer.numItems = modelData.uvs.length / vertexTextureCoordBuffer.itemSize; */ model = modelData; // position : vertex vertexArray = modelData.vertices; bbox = new Boundingbox(); bbox.calculateBBox(vertexArray); var vbuffer = new nbuffer(); vbuffer.create("testModelVertexBuffer", vertexArray, 3); bufferList.push(vbuffer); /*vertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); //gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.vertices), gl.STATIC_DRAW); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexArray), gl.STATIC_DRAW); vertexPositionBuffer.itemSize = 3; vertexPositionBuffer.numItems = modelData.vertices.length / vertexPositionBuffer.itemSize;*/ // face : index vertexIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, vertexIndexBuffer); /*modelData.faces = modelData.faces.map(function(v) { return v - 1; });*/ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(modelData.faces), gl.STATIC_DRAW); vertexIndexBuffer.itemSize = 1; vertexIndexBuffer.numItems = modelData.faces.length; // color vertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.colors), gl.STATIC_DRAW); vertexColorBuffer.itemSize = 4; vertexColorBuffer.numItems = modelData.colors.length / vertexColorBuffer.itemSize; // normal vertexNormalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexNormalBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(modelData.normals), gl.STATIC_DRAW); vertexNormalBuffer.itemSize = 3; vertexNormalBuffer.numItems = modelData.normals.length / vertexNormalBuffer.itemSize; // texture coordinate var scaleTexCoord = modelData.uvs; for( var i = 0; i < scaleTexCoord.length; i++ ) { scaleTexCoord[i] *= 8; } vertexTextureCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexTextureCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(scaleTexCoord), gl.STATIC_DRAW); vertexTextureCoordBuffer.itemSize = 2; vertexTextureCoordBuffer.numItems = modelData.uvs.length / vertexTextureCoordBuffer.itemSize; } function loadCornellbox(callback) { //function loadCornellbox() { var request = new XMLHttpRequest(); request.open("GET", "obj/cornellbox2.js"); request.onreadystatechange = function() { if (request.readyState == 4) { handleLoadedCornellbox(JSON.parse(request.responseText)); // wait for succeed to load model file, go to next function callback(); } } request.send(); }
'use strict'; const passport = require("passport"); const jwt = require('jsonwebtoken'); const User = require('../models/user'); const config = require('../utils/config'); class AuthRoutes{ constructor(app){ this.app = app; } routes(){ // Register via username and password this.app.post('/register', function (req, res, next) { var credentials = {'firstName': req.body.firstName, 'lastName': req.body.lastName, 'userName': req.body.userName, 'email': req.body.email, 'password': req.body.password }; if (!credentials.userName || !credentials.password || !credentials.firstName || !credentials.lastName || !credentials.email) { res.json({ success: false, message: 'Please fill the required fields.' }); } else { // Check if the username already exists for non-social account User.findOne({ 'userName': new RegExp('^' + req.body.userName + '$', 'i'), 'socialId': null }, function (err, user) { if (err) throw err; if (user) { res.json({ success: false, message: 'Username already exists, try to login.' }); } else { User.create(credentials, function (err, newUser) { if (err) throw err; let token = generateToken(newUser); res.json({ success: true, message: 'Your account has been created.', token: 'bearer ' + token, userId: newUser.id, userName: newUser.userName}); }); } }); } }); this.app.post('/login', function (req, res) { User.findOne({ userName: req.body.userName }, function (err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'User not found.' }) } else { user.validatePassword(req.body.password, function (err, isMatch) { if (isMatch && !err) { let token = generateToken(user); res.json({ success: true, token: 'bearer ' + token, userId: user.id, userName: user.userName }); } else { res.json({ success: false, message: 'Authentication faild.' }) }; }); }; }); }); } routesConfig(){ this.routes(); } } function generateToken(user){ return jwt.sign(user.toJSON(), config.jwt.secret, { expiresIn: config.jwt.expiresIn }); } function isAuthenticated(type) { return passport.authenticate(type, { session: false }); } module.exports = AuthRoutes;
import firebase from '@/api/firebase' import axios from '@/api/axios' /* * Firebase Authentication * */ const login = credentials => { return firebase .auth() .signInWithEmailAndPassword(credentials.email, credentials.password) .then(response => response.user) } const register = credentials => { return firebase .auth() .createUserWithEmailAndPassword(credentials.email, credentials.password) .then(response => response.user) } const logout = () => { return firebase.auth().signOut() } /* * Firebase RealTime Database * */ const insertUser = (userId, userData) => { return firebase .database() .ref(`/users/${userId}`) .set(userData) } const selectUser = userId => { return firebase.database().ref(`/users/${userId}`) } const updateAppSettings = (userId, data) => { return firebase .database() .ref(`/users/${userId}`) .update(data) } /* * Axios: Third-Party Api * */ const getCurrencies = () => { return axios .get('https://openexchangerates.org/api/currencies.json') .then(r => Object.entries(r.data).map(c => ({id: c[0], name: c[1]}))) } export default { login, register, logout, insertUser, selectUser, updateAppSettings, getCurrencies }
// latest.js var Api = require('../../utils/api.js'); Page({ data: { groupList: [], activeHoverIndex: undefined }, getCartInfo: function (callback) { var callback = callback; var that = this; getApp().doRequest({ url: getApp().config.host + '/cart_item_list', method: 'GET', header: { "Content-Type": "application/x-www-form-urlencoded", "token": getApp().globalData.userInfo.token }, success: function (res) { that.setData({ groupList: res.data.data }) }, complete: function () { if (callback) { callback(); } } }); }, refresh: function() { this.getCartInfo(); }, onLoad: function (options) { console.log(options); wx.showNavigationBarLoading(); this.getCartInfo(function() { wx.hideNavigationBarLoading(); }); }, onPullDownRefresh: function () { console.log("下拉刷新"); var that = this; wx.stopPullDownRefresh(); that.getCartInfo(function () { wx.stopPullDownRefresh({ complete: function (res) { console.log(res, new Date()) } }) }) }, stopPullDownRefresh: function () { }, touchStartElement: function (e) { console.log("start", e); var id = e.currentTarget.id; this.setData({ activeHoverIndex: id }) }, touchEndElement: function (e) { console.log("end", e); var that = this; setTimeout(function () { that.setData({ //warnning undefined==""=="0"==0 activeHoverIndex: "none" }) }, 500) }, touchMoveElement: function (e) { console.log("move", e); this.setData({ activeHoverIndex: "none" }) }, goOrderPreview: function(e) { var url = '../orderPreview/orderPreview?book_user_id=' + e.currentTarget.dataset.userid; console.log(e, "goOrderPreview", url) wx.redirectTo({ url: url }) }, goCartBookList: function (e) { var bookIds = e.currentTarget.dataset.books; var url = '../chooseBookList/chooseBookList?edit=1&user_book_ids=' + bookIds; console.log(e, "goCartBookList", url) wx.redirectTo({ url: url }) } })
import React from 'react'; import styled from 'styled-components'; const CardBody = styled.div` background-color: #fff; border-bottom: 1px solid rgba(0, 0, 0, 0.15); width: 100%; margin-top: 2rem; `; const CardTitle = styled.h2` color: #c1c1c1; font-size: 2rem; font-weight: '800'; margin-left: 2rem; `; const CardContent = styled.p` color: #c1c1c1; font-size: 1.4rem; font-weight: '300'; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; `; const CardAuthor = styled.h3` color: #c1c1c1; font-size: 1.4rem; font-weight: '800'; `; const Holder = styled.div` justify-content: space-between; align-items: center; display: flex; flex-direction: row; `; const Button = styled.div` align-self: center; position: relative; letter-spacing: 0.025em; font-size: 1.3rem; line-height: 1.5; padding: 0.3rem 2.5rem; box-shadow: 0 0.5rem 1.5rem rgba($color: #000000, $alpha: 0.15); margin: 1rem 0 0 0; cursor: pointer; transition: all 0.3s ease-in-out; color: #a1a1a1; &:active { transform: translate(0, 2px); outline: none; box-shadow: 0 0.3rem 1rem rgba($color: #000000, $alpha: 0.15); } `; const Card = ({ feed }) => { return ( <CardBody> <CardTitle>{feed.title}</CardTitle> <CardContent>{feed.content}</CardContent> <Holder> <CardAuthor> by: {`${feed.writer.surname} ${feed.writer.firstname}`} </CardAuthor> <Button>Learn more</Button> </Holder> </CardBody> ); }; export default Card;
import React, { Component } from 'react'; import axios from '../../axios-emails'; import { Parallax } from 'react-spring'; class Form extends Component { state={ name: '', lastname: '', email: '', sended: false, } handleUserInput = (e) => { const name = e.target.name; const value = e.target.value; this.setState({[name]: value}, ()=>{ console.log(this.state.email,'<<<email') console.log(this.state.name,'<<<<nombre') console.log(this.state.lastname,'<<<<apellido') }); console.log(this.state.email,'<<<email') console.log(this.state.name,'<<<<pass') } send = (e) => { e.preventDefault(); const data = { email : this.state.email, name: this.state.name, lastName: this.state.lastname } axios.post('/emails.json', data) .then((response)=>{ console.log(response); this.setState({ sended:true }) }) .catch(err => console.log(err)); } render(){ return( <div> <form className="form-group" onSubmit={this.send}> <div className="card person-card card-shadow"> <div className="card-body"> <h2 id="who_message" className="card-title" style={{textAlign:'center'}}>Informame</h2> {this.state.sended ? <div className="container d-flex flex-column align-items-center justify-content-center" style={{textAlign:'center'}}> <h1 >GRACIAS</h1> </div> : <div className="row"> <div className="form-group col-md-2"> <input id="first_name" type="text" className="form-control" placeholder="Nombre" onChange={this.handleUserInput} value={this.state.name} name='name'/> <div id="first_name_feedback" className="invalid-feedback"> </div> </div> <div className="form-group col-md-5"> <input id="last_name" type="text" className="form-control" placeholder="Apellido" value={this.state.lastname} onChange={this.handleUserInput} name='lastname' /> <div id="last_name_feedback" className="invalid-feedback"> </div> </div> <div className="form-group col-md-5"> <input id="email" type="email" className="form-control" placeholder="Tu Correo" onChange={this.handleUserInput} value={this.state.email} name='email'/> <div id="email_feedback" className="invalid-feedback"> </div> </div> </div> } </div> </div> <div > <button type="submit" className="btn btn-primary btn-lg btn-block btnstyle">{this.state.sended ? 'Nos pondremos en contacto' : 'Enviar'}</button> </div> </form> </div> ) } } export default Form;
const { emailService, organizationService, issueService } = require('../services'); module.exports = async function (job) { const { orgId, issueId } = job.data; const org = await organizationService.getOrganizationById(orgId); if (!org) { return Promise.reject( new Error(`Error sending email for issue: ${issueId}, organization with id: ${orgId} does not exists`) ); } const issue = await issueService.getIssueById(issueId, orgId); if (!issue) { return Promise.reject(new Error(`Error sending email, issue with id: ${issueId} does not exists`)); } const { users } = org; const text = `Issue created: Id:${issue._id}, Title: ${issue.title}, Description: ${issue.description}, Severity: ${ issue.severity }, Developer: ${issue.developer || 'Not assigned'}, Status: ${issue.status}`; const subject = `Issue created (${org.name})`; // eslint-disable-next-line no-restricted-syntax for await (const email of users) { try { await emailService.sendEmail(email, subject, text); } catch (e) { return Promise.reject(new Error(`error sending email, ${e.message}`)); } } return Promise.resolve(); };
'use strict'; const pkg = require( '../package' ); const Config = require( '../utils/config' )( pkg.name ).current; const Session = require( '../models/v0/session' ); const jwt = require( 'jsonwebtoken' ); module.exports = { express: express }; function express() { return function ( req, res, next ) { req.ip_address = proxy( req.header( 'via' ), req.header( 'x-forwarded-for' ) ) || req.connection.remoteAddress; // We require that the cookie-parser middleware is registered before this middleware if ( !req.cookies ) { return next( { code: 500, type: 'configuration', err: new Error( 'Missing middleware: cookie-parser.' ) } ); } handle( req, res, next ); }; } function handle( req, res, next ) { delete req.session; // Note: Only accept token in cookie for GET requests to prevent CSRF attacks const auth = get( req.headers.authorization ) || ( req.method === 'GET' ? get( 'Bearer ' + req.cookies.access_token ) : null ) || get( 'Bearer ' + req.query.access_token ); // TODO: Fix that auth.value is get to undefined if it doesn't exist if ( !auth || auth.type !== 'bearer' || !auth.value || auth.value === 'undefined' ) { res.clearCookie( 'access_token', { secure: false } ); res.clearCookie( 'access_token', { secure: true } ); return next(); } // Ensure valid jwt jwt.verify( auth.value, Config().session.secret, function ( err, token ) { if ( err ) { res.clearCookie( 'access_token', { secure: false } ); res.clearCookie( 'access_token', { secure: true } ); return next( { code: 401, domain: 'user', operation: 'session.jwt.validate', type: 'authentication', reason: err, err: new Error( 'Invalid token.' ) } ); } // Ensure valid session Session.get( token.session, function ( err, result ) { if ( err ) { res.clearCookie( 'access_token', { secure: false } ); res.clearCookie( 'access_token', { secure: true } ); return next( { code: 401, domain: 'user', operation: 'session.get', type: 'authentication', reason: err, err: new Error( 'Invalid session.' ) } ); } req.session = result.session; next(); } ); } ); } function proxy( via, xff ) { if ( via === '1.1 google' ) { return ( xff || '' ).split( ',' )[ 0 ]; } } function get( authorization ) { const parts = ( authorization || '' ).split( ' ' ); if ( parts[ 0 ] && parts[ 1 ] ) { return { type: parts[ 0 ].toLowerCase() || '', value: parts[ 1 ] || '' }; } }
module.exports = class ApiFeatures { constructor(mongooseQuery, queryString) { this.mongooseQuery = mongooseQuery; this.queryString = queryString; } filter() { let queryObj = { ...this.queryString }; let excludedArrays = ["sort", "limit", "page", "fields"]; for (let key in queryObj) { if (excludedArrays.includes(key)) { delete queryObj[key]; } } //2-Advanced Filtering let queryString = JSON.stringify(queryObj); queryString = queryString.replace( /\b(gte|gt|lt|lte)\b/g, (match) => `$${match}` ); queryString = JSON.parse(queryString); this.mongooseQuery = this.mongooseQuery.find(queryString); //this is the first One so we save this as the "this.mongooseQuery" return this; //because we want to change } sort() { if (this.queryString.sort) { let sort = this.queryString.sort.split(",").join(" "); this.mongooseQuery = this.mongooseQuery.sort(sort); //because these methods returns new Query and updated version we assign then } else { this.mongooseQuery = this.mongooseQuery.sort("-createdAt"); } return this; } fieldLimiting() { if (this.queryString.fields) { let fields = this.queryString.fields.split(",").join(" "); this.mongooseQuery = this.mongooseQuery.select(fields); } else { this.mongooseQuery = this.mongooseQuery.select("-__v"); } return this; } paginate() { let page = this.queryString.page * 1 || 1; let limit = this.queryString.limit * 1 || 10; let skip = (page - 1) * limit; this.mongooseQuery = this.mongooseQuery.skip(skip).limit(limit); return this; } };
(function () { 'use strict'; var app = angular .module('controllersModule') .controller('EditCatController', CatCtrl); CatCtrl.$inject = ['$location', '$window', '$rootScope', '$scope', '$timeout', '$modal', '$log', 'FlashService', 'CatSrvc']; function CatCtrl($location, $window, $rootScope, $scope, $timeout, $modal, $log, FlashService, CatSrvc) { var vm = this; vm.category = null; vm.save = save; vm.reset = reset; loadCategory(); function loadCategory() { CatSrvc.getOne($routeParams.catId).then(function(category) { vm.category = category; }); } function save() { if (CatSrvc) CatSrvc.update(vm.category) .then(function() { $timeout(function(){ loadCategory(); }, 300); }) } function reset() { loadCategory(); } //loadCategories(); } })();
Ext.define('dlmsprint2a.view.Main', { extend: 'Ext.container.Container', requires:[ 'Ext.tab.Panel', 'Ext.layout.container.Border' ], xtype: 'app-main', layout: { type: 'border' }, items: [{ region : 'north', xtype : 'toolbar', items : [{ text : 'Add', iconCls : 'add', },'-',{ text : 'Save', iconCls : 'save', },{ text : 'Refresh', iconCls : 'refresh', },{ xtype : 'tbspacer', width : 98, },{ text : 'Exports', name : 'exportsbtn', iconCls : 'export', enableToggle : true, pressed : true, },{ text : 'Editor', name : 'editorbtn', iconCls : 'pencil', enableToggle : true, },{ text : 'Accounts', name : 'accountsbtn', iconCls : 'account', enableToggle : true, },{ text : 'Uploads', name : 'uploadsbtn', iconCls : 'lists', enableToggle : true, /* },'-',{ text : '199,834 uploaded in 22 files', iconCls : 'lists', iconAlign : 'right', },'-',{ text : '=>&nbsp;&nbsp; 199,384 exported in 22 lists', text : '199,384 exported in 22 lists', iconCls : 'lists', iconAlign : 'right', */ }], },{ region : 'west', xtype : 'filtergrid', //flex : 1, //hidden : true, width : 1011, },{ region : 'center', xtype : 'panel', //hidden : true, name : 'mainpanel', layout : 'card', activeItem: 3, items : [{ xtype : 'accountgrid', },{ xtype : 'uploadgrid', width : 528, },{ xtype : 'rulegrid', margin : '5 5 5 5', },{ html : '', border : false, }] }] });
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "e00917d94d8ad51d0fb1", "url": "/css/app.a59bd7b2.css" }, { "revision": "4992f01c4a52c1fc0c29", "url": "/css/chunk-vendors.3446c5ff.css" }, { "revision": "6acc66a317d8a1dc54b54cecee3ba2e1", "url": "/img/colorscale.png" }, { "revision": "bdad90647b43ffc58ba0e6285c2a333d", "url": "/img/colorscale1.png" }, { "revision": "ab93b5356f3c953703112f6b019e93af", "url": "/img/colorscale2.png" }, { "revision": "da1e8503e46fce245501731ea259f912", "url": "/img/graph.PNG" }, { "revision": "649260fbf532497e994b63d30e9f2258", "url": "/img/left.png" }, { "revision": "b8860cefae40e3e1f873c647bfef784e", "url": "/img/logo.png" }, { "revision": "e47eab661979cd62ef0c7d956d51cc51", "url": "/img/logo_white.png" }, { "revision": "0dd2f073c6bccde9baf2a8f738077c25", "url": "/img/marker.png" }, { "revision": "275e5ae274764f558c745539e3c419f2", "url": "/img/newcolorscale.png" }, { "revision": "87be748211989030415a2b171c652402", "url": "/img/north.png" }, { "revision": "3a84996c9765c8a32aba60f94869b9f5", "url": "/img/right.png" }, { "revision": "f1a7813443cebd8c6f2d2e90bb1af040", "url": "/img/socialshare.PNG" }, { "revision": "d7cc9752e19ab540296d3e1db3de8006", "url": "/img/south.png" }, { "revision": "3bfb1b21f5fc47d4899c894c70203fad", "url": "/index.html" }, { "revision": "e00917d94d8ad51d0fb1", "url": "/js/app.e2375c73.js" }, { "revision": "4992f01c4a52c1fc0c29", "url": "/js/chunk-vendors.981ecee9.js" }, { "revision": "d05a8e631733b0979abe53e42468d608", "url": "/json/PollutionBurdenByCouncilDistrict.json" }, { "revision": "5f1a8d92a0e70ea9086fc50d49b25af3", "url": "/manifest.json" }, { "revision": "f95cbfdb8887060463fd70b13ec7ed6b", "url": "/package.json" }, { "revision": "735ab4f94fbcd57074377afca324c813", "url": "/robots.txt" }, { "revision": "752320090b5e20ec43f20f95dc873333", "url": "/server.js" }, { "revision": "bbc18268bbf1a5ab365e6ed89b245bb2", "url": "/web.config" } ]);
// server.js // where your node app starts // init project var express = require('express'); var app = express(); var mongo = require('mongodb'); var mongoose = require('mongoose'); var port =process.env.PORT || 3000 let bodyParser = require('body-parser') let multer = require('multer') var apiRoutes = require('./routes/api.js'); let path = require('path') require('dotenv').config() var cors = require('cors'); app.use(cors({optionSuccessStatus: 200})); app.use(express.static(path.join(__dirname, 'public'))); app.use((req,res,next)=>{ next() }) app.get('/', function (req, res) { res.sendFile(__dirname + '/views/home.html'); }); app.use(express.static(path.join(__dirname, 'build'))); app.get('/drummachine', function (req, res) { res.sendFile(__dirname+'/build/index.html'); }); app.get('/randomquotemachine', (req, res, next) =>{ res.sendFile(__dirname + '/views/randomquotemachine.html') }) app.use(express.static(path.join(__dirname, 'buildMarkdown-Previever'))); app.get('/markdownpreviever',(req,res)=>{ res.sendFile(__dirname+'/buildMarkdown-Previever/index.html'); }) app.get('/api/shorturl/new', (req, res, next) =>{ res.sendFile(__dirname + '/views/urlshortner.html') }) app.get('/api/exercise/add', (req, res, next) =>{ res.sendFile(__dirname + '/views/exercisetracker.html') }) app.get('/api/filemetadata', (req, res, next) =>{ res.sendFile(__dirname + '/views/filemetadata.html') }) app.get('/api/timestamp/:date_string', function (req, res){ let resultArray={} var input = req.params.date_string; if(input.includes('-')){ resultArray['unix'] = new Date(input).getTime(); resultArray['utc'] = new Date(input).toUTCString() }else { input = parseInt(input) resultArray['unix'] = new Date(input).getTime(); resultArray['utc'] = new Date(input).toUTCString() } if(!resultArray['unix'] || !resultArray['utc']){ res.json({"error" : "Invalid Date" }) } res.json(resultArray) }) let url = process.env.MONGODB_URI mongoose.connect(url, { useNewUrlParser : true, useUnifiedTopology: true }); let urlSchema = new mongoose.Schema({ original_url: {type: String, required: true}, short_url: Number, }) let Url = mongoose.model('Url', urlSchema) let responseObj = {} app.post('/api/shorturl/new', bodyParser.urlencoded( { extended: false} ), (req, res) => { let inputUrl = req.body['url'] responseObj['original_url']= inputUrl let inputShort = 1; Url.findOne({}) .sort({short_url: 'desc'}) .exec((err, result) =>{ if(!err && result != undefined){ inputShort = result.short_url + 1; } if (!err){ Url.findOneAndUpdate( {original_url: inputUrl}, {original_url: inputUrl, short_url: inputShort }, {new: true, upsert: true}, (err, savedUrl)=>{ if(!err){ responseObj['short_url'] = savedUrl.short_url; res.json(responseObj) } } ) } }) }) app.get('/api/shorturl/:input',(req, res) =>{ let input = req.params.input Url.findOne({short_url: input}, (err, result) => { if(!err && result != undefined){ res.redirect(result.original_url) }else{ res.json('{error: url not found}') } }) } ) let exercisesSesionsSchema = new mongoose.Schema({ description: {type: String, required: true}, duration: {type: Number, required: true}, date: String }) let userSchema = new mongoose.Schema({ username: {type: String, required: true}, log: [exercisesSesionsSchema] }) let Sessions = mongoose.model('Sessions', exercisesSesionsSchema) let User = mongoose.model('User', userSchema) app.post('/api/exercise/new-user', bodyParser.urlencoded( { extended: false} ), (req, res) => { let inputUser = req.body['username'] let newUser = new User({username: inputUser}) newUser.save((err, savedUser) =>{ if(err){ console.log(err) } else{ let responseObj = {} responseObj['username'] = savedUser.username responseObj['_id'] = savedUser.id res.json(responseObj) }} ) }) app.get('/api/exercise/users', (req,res) =>{ User.find({}, (err, arrOfUsers) => { if(!err){ res.json(arrOfUsers) } }) }) app.post('/api/exercise/add', bodyParser.urlencoded( { extended: false} ), (req, res) => { let body = req.body; let newSession = new Sessions({ description: body.description, duration: parseInt(body.duration), date: body.date }) if(newSession.date == ''){ newSession.date = new Date().toISOString().substring(0, 10) } User.findByIdAndUpdate( req.body.userId, {$push : {log: newSession}}, {new: true}, (err, updatedUser) => { if(err){ console.log('user not found') } if(!err){ let responseObject = {} responseObject['username'] = updatedUser.username responseObject['_id'] = updatedUser.id responseObject['description'] = newSession.description responseObject['duration'] = newSession.duration responseObject['date'] = new Date(newSession.date).toDateString() res.json(responseObject) } } ) }) app.get('/api/exercise/log', (req, res) =>{ User.findById(req.query.userId, (err, result) => { let responseObject = result responseObject['count'] = result.log.length if(req.query.from || req.query.to){ let fromDate = new Date(0); let toDate = new Date(); if(req.query.to){ toDate = new Date(req.query.to) } if(req.query.from){ fromDate = new Date(req.query.from) } fromDate = fromDate.getTime() toDate = toDate.getTime() console.log(toDate, fromDate) responseObject.log= responseObject.log.filter((session) =>{ let sessionDate = new Date(session.date).getTime() if(sessionDate >= fromDate && sessionDate <= toDate){ return sessionDate }}) } if(req.query.limit){ responseObject.log = responseObject.log.slice(0, req.query.limit) } res.json(responseObject) }) }) let dataInformationSchema = new mongoose.Schema({ name: {type: String, required: true}, type: String, size: Number }) let dataInformation = mongoose.model('dataInformation', dataInformationSchema) app.post('/api/fileanalyse', multer().single('upfile'), (req, res) =>{ let data = req.file let newData = new dataInformation({ name: data.originalname,type: data.mimetype,size: data.size}) newData.save((err, savedData) =>{ if(err){ console.log(err) }else{ console.log(savedData); let responseObject = {} responseObject['name'] = savedData.name; responseObject['type'] = savedData.type; responseObject['size'] = savedData.size res.json(responseObject) } }) }) app.route('/api/convert') .get(function (req, res) { res.sendFile(__dirname + '/views/metricconverter.html'); }); //metric converter routes apiRoutes(app); // listen for requests :) var listener = app.listen(port, function () { console.log('Your app is listening on port ' + listener.address().port); });
/** * This is where all the logic for the Special Attribute Component * @author s753601 * @version 2.12.0 */ (function () { angular.module('productMaintenanceUiApp').component('productSpecialAttribute', { // isolated scope binding bindings: { productMaster: '<' }, scope: '=', // Inline template which is binded to message variable in the component controller templateUrl: 'src/productDetails/product/specialAttribute.html', // The controller that handles our component logic controller: ProductSpecialAttributeController }); ProductSpecialAttributeController.$inject = ['productApi', 'UserApi','$rootScope', 'ProductDetailAuditModal', 'ProductSearchService', '$filter']; /** * Product shelf attributes component's controller definition. * @constructor */ function ProductSpecialAttributeController(productApi, userApi, $rootScope, ProductDetailAuditModal, productSearchService, $filter) { /** * The constant for pharmacy tab. * @type {string} */ var pharmacyTab= "pharmacy"; /** * The constant for tobacco tab. * @type {string} */ var tobaccoTab = "tobacco"; /** * The constant for code date tab. * @type {string} */ var codeDateTab = "codeDate"; /** * The constant for shipping and handling tab. * @type {string} */ var shippingHandlingTab = "shippingHandling"; /** * The constant for rating/restrictions tab. * @type {string} */ var ratingRestrictionsTab = "rating/restrictions"; /** All CRUD operation controls of Case pack Import page goes here */ var self = this; /** * Constant for the pharmacy tab. * @type {string} */ var pharmacy = "pharmacy"; /** * Constant for the code Date tab. * @type {string} */ var codeDate = "codeDate"; /** * Constant for the rating or restrictions tab. * @type {string} */ var ratingOrRestrictions = "rating/restrictions"; /** * Constant for the rating or restrictions tab. * @type {string} */ var tobacco = "tobacco"; var shippingHandling = "shippingHandling"; var MISSING_TOBACCO_PRODUCT_TYPE = "Missing Tobacco Product Type"; /** * Determines which tab is currently selected. * @type {null} */ self.currentTab = pharmacyTab; /** * Error message * @type {null} */ self.error=null; /** * Success message * @type {null} */ self.success=null; /** * Flag to display spinner while loading data * @type {boolean} */ self.isLoading = false; /** * These flags are whichever component is currently being loaded in. * @type {boolean} */ self.isLoadingPharmacy=false; self.isLoadingRestriction=false; self.isLoadingRestrictionGroups=false; self.isLoadingShippingRestriction=false; /** * Array to hold all of the drug schedule types * @type {Array} */ self.drugSchedule=[]; /** * The complete set of restrictions * @type {Array} */ self.restrictions=[]; /** * The filtered set of restrictions based on the selected restriction group * @type {Array} */ self.restrictionFilter=[]; /** * The currently selected restriction * @type {null} */ self.restriction=null; /** * The set of restriction types * @type {Array} */ self.restrictionGroups = []; /** * The currently selected restriction type * @type {null} */ self.restrictionGroup=null; /** * The current set of values available to the pharmacy * @type {null} */ self.currentRx=null; /** * The original set of values available to the pharmacy * @type {null} */ self.originalRx=null; /** * Determines which tab is currently selected. * @type {null} */ self.currentTab = pharmacy; /** * The types of tobacco products available * @type {Array} */ self.tobaccoProductTypes=[]; /** * This is the original tobacco product if there is one * @type {null} */ self.originalTobaccoProduct=null; /** * This is the current tobacco product * @type {null} */ self.currentTobaccoProduct=null; /** * This is the default class code for tobacco products this is check to see if the new tobacco product is * part of the tobacco commodity class * @type {number} */ self.tobaccoDefault=62; /** * This is the default class code for pharmacy products this is check to see if the new pharmacy product is * part of the pharmacy commodity class * @type {number} */ self.pharmacyDefault=[32, 34, 68, 69]; /** * The current list of restrictions on the product * @type {null} */ self.currentRestrictions=null; /** * The original list of restrictions on a product * @type {null} */ self.originalRestrictions=null; /** * The currently selected restriction group to possibly add to the product * @type {null} */ self.restrictionGroup=null; /** * The currently selected restriction to possibly add to the product * @type {null} */ self.restriction=null; /** * A list of indexes to delete from the product's restrictions list * @type {Array} */ self.deleteList=[]; /** * This flag is set for when all of the checkboxes in the table are checked. * @type {boolean} */ self.allChecked=false; /** * Hold the data for all shipping restrictions available. * * @type {Array} */ self.allShippingRestrictionsList = []; /** * Keep track of all shipping restrictions that have been checked in UI. * * @type {boolean} */ self.allShippingRestrictionChecked = false; /** * Keep track of all shipping methods checked in the UI. * * @type {boolean} */ self.allShippingMethodChecked = false; /** * Keep track of all state warnings checked in the UI. * * @type {boolean} */ self.allStateWarningsChecked = false; /** * Holds current products shipping restrictions. * * @type {null} */ self.productShippingRestrictions = null; /** * Modified returned shipping restrictions. * * @type {Array} */ self.returnProductShippingRestrictions = []; /** * Modified returned shipping methods. * * @type {Array} */ self.returnShippingMethods = []; /** * Modified retunre state warnings. * * @type {Array} */ self.returnStateWarnings = []; /** * RegExp check number is decimal type (#####.####), and max value is 99999.9999 * @type {{}} */ self.regexDecimal = new RegExp("^[0-9]{1,5}\.?([0-9]{1,4})?$"); const NO_CHANGE_DETECTED_MSG = "No changes detected."; /** * Whenever the view is initialized. */ this.$onInit =function () { productApi.getTobaccoType(self.loadTobaccoType, self.fetchError); self.disableReturnToList = productSearchService.getDisableReturnToList(); }; /** * Whenever the current page makes a change. */ this.$onChanges = function () { self.isLoading=true; self.success = null; self.isLoadingPharmacy=true; self.isLoadingRestriction=true; self.isLoadingShippingRestriction=true; self.isLoadingRestrictionGroups=true; self.currentRx=null; self.originalRx=null; self.originalCodeDate=null; self.currentCodeDate = null; self.currentTobaccoProduct=null; self.originalTobaccoProduct=null; self.originalRestrictions=null; self.currentRestrictions=null; self.originalShipping=null; self.currentShipping=null; self.loadApiCallData(); }; /** * Loads all of the api calls that are fetching for data. */ self.loadApiCallData = function() { productApi.getDrugSchedule(self.loadPharmacyData, self.fetchError); productApi.getRestrictionGroups(self.loadRestrictionGroup, self.fetchError); productApi.getRestrictions(self.loadRestriction, self.fetchError); productApi.getProductShippingRestrictions({prodId: self.productMaster.prodId} , self.loadProductShippingRestrictions, self.fetchError); productApi.getAllShippingRestrictions(self.loadShippingRestrictions, self.fetchError); productApi.getSalesRestrictionsBySubCommodity({subcomcd: self.productMaster.subCommodityCode} , self.loadSalesRestrictionsBySubCommodity, self.fetchError); productApi.getShippingMethodExceptions({prodId: self.productMaster.prodId}, self.loadShippingMethodExceptions, self.fetchError); productApi.getAllShippingMethodExceptions(self.loadAllShippingMethodRestrictions, self.fetchError); productApi.getStateWarnings({prodId: self.productMaster.prodId}, self.loadProductStateWarnings, self.fetchError); productApi.getAllStateWarnings(self.loadAllStateWarnings, self.fetchError); productApi.getStateWarningBySubcommodity({subcomcd: self.productMaster.subCommodityCode} , self.loadStateWarningBySubcommodity, self.fetchError); self.createCurrentShipping(); self.createCurrentCodeDate(); self.createCurrentTobaccoProduct(); self.createCurrentRestrictions(); }; /** * Component ngOnDestroy lifecycle hook. Called just before Angular destroys the directive/component. */ this.$onDestroy = function () { }; /** * This method is called when the UI successfully gets All the State Warnings. * * @param results */ self.loadAllStateWarnings = function (results) { self.allStateWarnings = results; }; /** * This method is called when the UI successfully gets Product State Warnings. * * @param results */ self.loadProductStateWarnings = function (results) { self.productStateWarnings = results; }; /** * This method is called when the UI successfully gets Product Shipping Restrictions. * * @param results */ self.loadProductShippingRestrictions = function (results) { self.productShippingRestrictions = results; }; /** * This method is called when the UI successfully get sales restrictions by sub commodity. * * @param results */ self.loadSalesRestrictionsBySubCommodity = function (results) { self.listSalesRestrictionsBySubCommodity = results; }; /** * This method is called when the UI successfully get state warning by sub commodity. * * @param results */ self.loadStateWarningBySubcommodity = function (results) { self.listStateWarningBySubcommodity = results; }; /** * This method is called when the UI successfully gets Shipping Method Exceptions. * * @param results */ self.loadShippingMethodExceptions = function (results) { self.shippingMethodExceptions = results; }; /** * This method is called when the UI successfully gets the tobacco product type code table * @param results */ self.loadTobaccoType=function (results) { self.tobaccoProductTypes=results; }; self.updateLoadingStatus=function () { self.isLoading=(self.isLoadingPharmacy || self.isLoadingRestrictionGroups || self.isLoadingRestriction); }; /** * After updating the database get the latest ItemMaster * @param results */ self.loadPharmacyData = function (results) { self.isLoading=false; self.isLoadingPharmacy=false; self.drugSchedule = []; if(results != null) { angular.forEach(results, function(item){ if(self.isNullOrEmptyOrBlank(item.description) == false){ if(item.description.trim() === 'DEFAULT'){ item.description = "--Select--"; } item.description = item.description.trim() item.id = item.id.trim(); self.drugSchedule.push(item); } }); } self.currentRx = {}; self.currentRx.id = self.productMaster.prodId; self.currentRx.sellingUnits = self.productMaster.sellingUnits; if(self.productMaster.goodsProduct !== null){ self.currentRx.goodsProduct = { pseDisplay: self.productMaster.goodsProduct.psedisplay, pseTypeCode: self.productMaster.goodsProduct.pseTypeCode.trim() || null, rxProductFlag: self.productMaster.goodsProduct.rxProductFlag, medicaidCode: self.productMaster.goodsProduct.rxProductFlag?self.productMaster.goodsProduct.medicaidCode.trim() || null : "", medicaidDisplay: self.productMaster.goodsProduct.medicaidDisplay }; if(self.productMaster.goodsProduct.rxProduct !== null || undefined){ self.currentRx.goodsProduct.rxProduct = { drugScheduleTypeCode: self.productMaster.goodsProduct.rxProduct.drugScheduleTypeCode.trim() || null, drugScheduleDisplay: self.productMaster.goodsProduct.rxProduct.drugScheduleType.description.trim() || null, ndc: self.productMaster.goodsProduct.rxProduct.ndc.trim() || null }; } else { self.currentRx.goodsProduct.rxProduct = {}; } }else{ self.currentRx.goodsProduct = null; } self.originalRx = angular.copy(self.currentRx); self.updateLoadingStatus(); }; /** * Loads the restriction group. * @param results */ self.loadRestrictionGroup = function (results) { self.restrictionGroups=results; self.isLoadingRestrictionGroups= false; self.updateLoadingStatus(); }; self.loadAllShippingMethodRestrictions = function (results) { self.allShippingMethodRestrictions = results; }; self.loadShippingRestrictions = function (results) { self.allShippingRestrictions = results; self.isLoadingShippingRestriction = false; self.updateLoadingStatus(); }; /** * Loads the restriction. * @param results */ self.loadRestriction = function (results) { self.restrictions=results; self.isLoadingRestriction= false; self.updateLoadingStatus(); }; /** * Fetches the error from the back end. * * @param error */ self.fetchError = function(error) { self.isLoading = false; if(error && error.data) { self.isLoading = false; if (error.data.message) { self.setError(error.data.message); } else { self.setError(error.data.error); } } else { self.setError("An unknown error occurred."); } }; /** * Sets the controller's error message. * * @param error The error message. */ self.setError = function(error) { self.error = error; }; /** * This sorts the rating types. * @param index */ self.ratingTypeSelected = function (index) { self.restrictionFilter = []; if(self.restrictionGroup != null) { angular.forEach(self.restrictions, function (key, value) { if (angular.equals(key.restrictionGroupCode, self.restrictionGroup)){ self.restrictionFilter.push(key); } }); } }; /** * Checks to see if there were any changes made. * @returns {boolean} */ self.isDifference = function(tab) { if (tab === pharmacy) { if(angular.toJson(self.originalRx) !== angular.toJson(self.currentRx)){ $rootScope.contentChangedFlag = true; return true; } else{ $rootScope.contentChangedFlag = false; return false; } } else if(tab === codeDate) { if(angular.toJson(self.originalCodeDate) !== angular.toJson(self.currentCodeDate)){ $rootScope.contentChangedFlag = true; return true; } else{ $rootScope.contentChangedFlag = false; return false; } } else if(tab === tobacco) { if(angular.toJson(self.originalTobaccoProduct) !== angular.toJson(self.currentTobaccoProduct)){ $rootScope.contentChangedFlag = true; return true; } else{ $rootScope.contentChangedFlag = false; return false; } } else if(tab === ratingOrRestrictions) { if(angular.toJson(self.originalRestrictions) !== angular.toJson(self.currentRestrictions)){ $rootScope.contentChangedFlag = true; return true; } else{ $rootScope.contentChangedFlag = false; return false; } } else if(tab === shippingHandling) { if(angular.toJson(self.originalShipping) !== angular.toJson(self.currentShipping)){ $rootScope.contentChangedFlag = true; return true; } else{ $rootScope.contentChangedFlag = false; return false; } } }; /** * Resets all of the values back to the original. */ self.reset = function(tab) { self.success = null; self.error = null; if(tab === pharmacy) { self.currentRx = angular.copy(self.originalRx); } else if(tab === codeDate) { self.currentCodeDate = angular.copy(self.originalCodeDate); self.resetAllCss(); } else if(tab === tobacco) { self.currentTobaccoProduct = angular.copy(self.originalTobaccoProduct); }else if(tab === ratingOrRestrictions) { self.currentRestrictions = angular.copy(self.originalRestrictions); }else if(tab === shippingHandling) { self.currentShipping = angular.copy(self.originalShipping); } }; /** * Saves any changes to the rx product. */ self.saveChanges = function(tab) { self.isLoading = true; self.success = null; self.error = null; if(tab === pharmacy) { // This will check for any changes and saves the changes to a temporary RX object to send to the back end. // If it hasn't been changed then the field will be null. var tempRx = self.getProductMasterChanges(self.originalRx, self.currentRx); tempRx.prodId = self.currentRx.id; if (self.checkCurrentPharmacy(tempRx)){ productApi.savePharmacyChanges(tempRx, self.reloadSavedData, self.fetchError); }else{ self.isLoading = false; } } if(tab === codeDate) { // This will check for any changes and saves the changes to a temporary code date object to send to the // back end. If it hasn't been changed then it will be null in the back end. self.error = null; var tempCodeDate = self.getProductMasterChanges(self.originalCodeDate, self.currentCodeDate); tempCodeDate.prodId = self.currentCodeDate.prodId; if (self.currentCodeDate.goodsProduct !== null && self.currentCodeDate.goodsProduct.codeDate){ if (self.checkCurrentCodeDate(self.currentCodeDate)){ productApi.saveCodeDateChanges(tempCodeDate, self.reloadSavedData, self.fetchError); }else { self.isLoading = false; } }else { productApi.saveCodeDateChanges(tempCodeDate, self.reloadSavedData, self.fetchError); } } if(tab === shippingHandling) { var tempShippingHandling = self.getProductMasterChanges(self.originalShipping, self.currentShipping); tempShippingHandling.prodId = self.currentShipping.prodId; productApi.updateShippingHandlingChanges(tempShippingHandling, self.reloadSavedData, self.fetchError); } if(tab === tobacco) { // This will check for any changes and saves the changes to a temporary code date object to send to the // back end. If it hasn't been changed then it will be null in the back end. var tempTobacco = self.getProductMasterChanges(self.originalTobaccoProduct, self.currentTobaccoProduct); tempTobacco.prodId = self.currentTobaccoProduct.prodId; if(tempTobacco.goodsProduct !== null && (tempTobacco.goodsProduct.tobaccoProduct === undefined || angular.equals("", tempTobacco.goodsProduct.tobaccoProduct.tobaccoProductTypeCode))){ self.error = MISSING_TOBACCO_PRODUCT_TYPE; self.isLoading=false; } else { productApi.saveTobaccoChanges(tempTobacco, self.reloadSavedData, self.fetchError); } } if(tab === ratingOrRestrictions){ var ratingChanges = self.getRestrictionDifference(); productApi.saveRatingRestrictionsChanges(ratingChanges, self.reloadSavedData, self.fetchError); } }; /** * This recursively traverses through an object that may contain lists or other objects inside of it. This will * check each field inside of each object or list to determine whether or not that field has changed. If it has changed, * it saves it to a temporary and then the temporary will be returned. * * @param original * @param current * @returns {{}} */ self.getProductMasterChanges = function(original, current) { var temp = {}; for (var key in current) { if (!current.hasOwnProperty(key)) continue; if(angular.toJson(current[key]) !== angular.toJson(original[key])) { // It is in a list. This will look through a list of things to check whether any of them have // changed. if(self.isInt(key)) { if(!Array.isArray(temp)) { temp = []; } temp[key] = self.getProductMasterChanges(original[key], current[key]); temp[key].upc = current[key].upc; } else if(key !== "sellingUnits" && key !== "goodsProduct" && key !== "rxProduct") { // If the object is not a sellingUnit, goodsProduct or an rxProduct object and it has been changed // then save it into the temporary from the current. temp[key] = current[key]; } else if(key === "sellingUnits" || key === "goodsProduct" || key === "rxProduct") { // If it is a sellingUnits List, goodsProduct object or an rxProduct. Go inside and check each // object to check and see if any of it has changed. temp[key] = self.getProductMasterChanges(original[key], current[key]); } } } return temp; }; /** * Whether or not the value is an integer. This determines whether or not it is in a key. * @param value * @returns {boolean} */ self.isInt = function(value) { var x = parseFloat(value); return !isNaN(value) && (x | 0) === x; }; /** * This reloads any changes that might have happened. * @param results */ self.reloadSavedData = function(results) { // On an update, copy everything from the updated product master // and put it into the current product master. for(var i in results.data) { self.productMaster[i] = results.data[i]; } self.success = results.message; self.loadApiCallData(); }; /** * Determines which tab you are currently on. * @param tab */ self.chooseTab = function(tab) { self.reset(self.currentTab); self.currentTab = tab; }; /** * Creates a current Code Date. */ self.createCurrentCodeDate = function() { if (self.productMaster.goodsProduct !== null && self.productMaster.goodsProduct.codeDate){ self.currentCodeDate = { prodId: self.productMaster.prodId, goodsProduct: { prodId: self.productMaster.goodsProduct.prodId, codeDate: self.productMaster.goodsProduct.codeDate, maxShelfLifeDays: self.productMaster.goodsProduct.maxShelfLifeDays, inboundSpecificationDays: self.productMaster.goodsProduct.inboundSpecificationDays, warehouseReactionDays: self.productMaster.goodsProduct.warehouseReactionDays, guaranteeToStoreDays: self.productMaster.goodsProduct.guaranteeToStoreDays, sendCodeDate: self.productMaster.goodsProduct.sendCodeDate } }; }else { self.currentCodeDate = {}; self.currentCodeDate.prodId = self.productMaster.prodId; if(self.productMaster.goodsProduct !== null){ self.currentCodeDate.goodsProduct = { prodId: self.productMaster.goodsProduct.prodId, codeDate: self.productMaster.goodsProduct.codeDate, maxShelfLifeDays: null, inboundSpecificationDays: null, warehouseReactionDays: null, guaranteeToStoreDays: null, sendCodeDate: null }; }else{ self.currentCodeDate.goodsProduct = null; } } self.originalCodeDate = angular.copy(self.currentCodeDate); }; /** * Create object to hold the current shipping data. * */ self.createCurrentShipping = function () { self.currentShipping = {}; self.currentShipping.prodId = self.productMaster.prodId; if(self.productMaster.goodsProduct !== null){ self.currentShipping.goodsProduct = { prodId: self.productMaster.goodsProduct.prodId, fragile: self.productMaster.goodsProduct.fragile, hazardType: self.productMaster.goodsProduct.hazardType, ormd: self.productMaster.goodsProduct.ormd, shipByItself: self.productMaster.goodsProduct.shipByItself }; }else{ self.currentShipping.goodsProduct = null; } self.originalShipping = angular.copy(self.currentShipping); }; /** * This method creates the current tobacco product if the product is already a tobacco product */ self.createCurrentTobaccoProduct = function () { if(self.productMaster.goodsProduct !== null && self.productMaster.goodsProduct.tobaccoProductSwitch){ var params = { prodId: self.productMaster.prodId }; productApi.getTobaccoProduct(params, function(results) { self.currentTobaccoProduct = { prodId: results.goodsProduct.prodId, goodsProduct: { prodId: results.goodsProduct.prodId, tobaccoProductSwitch: results.goodsProduct.tobaccoProductSwitch, tobaccoProduct: { prodId: results.goodsProduct.prodId, tobaccoProductTypeCode: results.tobaccoProductType.tobaccoProductTypeCode, tobaccoProductType: results.tobaccoProductType } } }; self.originalTobaccoProduct = angular.copy(self.currentTobaccoProduct); }, self.fetchError); } else { self.currentTobaccoProduct = {}; self.currentTobaccoProduct.prodId = self.productMaster.prodId; if(self.productMaster.goodsProduct !== null){ self.currentTobaccoProduct.goodsProduct = { prodId: self.productMaster.goodsProduct.prodId, tobaccoProductSwitch: self.productMaster.goodsProduct.tobaccoProductSwitch, tobaccoProduct: { prodId: self.productMaster.goodsProduct.prodId, tobaccoProductTypeCode: null, tobaccoProductType: null } }; }else{ self.currentTobaccoProduct.goodsProduct = null; } } self.originalTobaccoProduct = angular.copy(self.currentTobaccoProduct); }; /** * This function will either set the default tobacco product type when sent to true or null the value when set to * false * @param flag */ self.changeTobaccoProduct= function (flag) { if(self.currentTobaccoProduct.goodsProduct !== null){ if(flag){ self.currentTobaccoProduct.goodsProduct.tobaccoProduct.tobaccoProductTypeCode=""; } else { self.currentTobaccoProduct.goodsProduct.tobaccoProduct.tobaccoProductTypeCode=null; } } }; /** * This method is used to check if the current product is part of the tobacco commodity class * @param differentThanDefault * @returns {*} */ self.differentThanDefault=function (differentThanDefault) { if(self.currentTobaccoProduct !== null && self.currentTobaccoProduct.goodsProduct !== null){ if(self.currentTobaccoProduct.goodsProduct.tobaccoProductSwitch){ return (self.currentTobaccoProduct.goodsProduct.tobaccoProductSwitch && self.productMaster.classCode !== differentThanDefault); } } return false; }; /** * This method is used to check if the current product is part of the pharmacy commodity class * @returns {*} */ self.differentProductDefault=function () { if(self.currentRx !== null && self.currentRx.goodsProduct !== null && self.currentRx.goodsProduct.rxProductFlag === true && self.pharmacyDefault.indexOf(self.productMaster.classCode)){ return true; } return false; }; /** * This method is used to check if the current shipping restriction is different with default shipping restriction. */ self.differentThanDefaultByShippingRestriction=function () { var currentSalesRestrictionList = self.getCurrentSalesRestrictionList(self.productShippingRestrictions); if(currentSalesRestrictionList && (currentSalesRestrictionList.length > 0) && self.listSalesRestrictionsBySubCommodity){ var diffArray = this.getDifferenceBetweenTwoArrays(currentSalesRestrictionList, self.listSalesRestrictionsBySubCommodity); if(diffArray != null && diffArray.length > 0){ return true; } } return false; }; /** * This method is used to check if the current state warning is different with default state warning. */ self.differentThanDefaultByStateWarning=function () { var currentStateWarningList = self.getCurrentStateWarningList(self.productStateWarnings); if(currentStateWarningList && (currentStateWarningList.length > 0) && self.listStateWarningBySubcommodity){ var diffArray = this.getDifferenceBetweenTwoArrays(currentStateWarningList, self.listStateWarningBySubcommodity); if(diffArray != null && diffArray.length > 0){ return true; } } return false; }; /** * Get the list of current shipping restriction. */ self.getCurrentSalesRestrictionList=function (listData) { var returnList = []; if(listData){ angular.forEach(listData, function(item){ returnList.push(item.restriction.restrictionCode.trim()); }); } return returnList; }; /** * Get the list of current state warning. */ self.getCurrentStateWarningList=function (listData) { var returnList = []; if(listData){ angular.forEach(listData, function(item){ returnList.push(item.productStateWarning.key.warningCode.trim()); }); } return returnList; }; /** * Get difference between two arrays. */ self.getDifferenceBetweenTwoArrays=function (a1, a2) { return a1.concat(a2).filter(function(val, index, arr){ return arr.indexOf(val) === arr.lastIndexOf(val); }); }; /** * This method creates the current list of (non shipping) restrictions on the product */ self.createCurrentRestrictions = function () { var filteredRestrictions=self.removeStateRestrictions(); self.currentRestrictions = { prodId: self.productMaster.prodId, restrictions: filteredRestrictions }; self.originalRestrictions = angular.copy(self.currentRestrictions); }; /** * Method will remove any shipping restrictions from the products current restrictions list * @returns {Array} */ self.removeStateRestrictions = function () { var nonShippingRestrictions = []; angular.forEach(self.productMaster.restrictions, function(restriction){ if(!angular.equals("9", restriction.restriction.restrictionGroupCode)){ nonShippingRestrictions.push(restriction) } }); return nonShippingRestrictions; }; /** * This method will create a new restriction to add to the current products restrictions list */ self.addRestriction=function(){ var selectedRestriction=self.restrictionFilter[document.getElementById("restrictionSelect").selectedIndex]; var newRestriction={ key:{ prodId: self.productMaster.prodId, restrictionCode: self.restrictionGroup }, restriction: { sellingRestriction:{ restrictionGroupCode:selectedRestriction.sellingRestriction.restrictionGroupCode, restrictionAbbreviation:selectedRestriction.sellingRestriction.restrictionAbbreviation, restrictionDescription:selectedRestriction.sellingRestriction.restrictionDescription }, dateTimeRestriction: selectedRestriction.dateTimeRestriction, minimumRestrictedAge: selectedRestriction.minimumRestrictedAge, restrictedQuantity: selectedRestriction.restrictedQuantity, restrictionAbbreviation: selectedRestriction.restrictionAbbreviation, restrictionCode: selectedRestriction.restrictionCode, restrictionGroupCode: selectedRestriction.restrictionGroupCode, shippingRestriction: selectedRestriction.shippingRestriction, restrictionDescription: selectedRestriction.restrictionDescription } }; self.currentRestrictions.restrictions.push(newRestriction); }; /** * This method will insure that you do not add any duplicate restrictions * @returns {boolean} */ self.validAdd=function () { var returnValue = false; if(self.currentRestrictions.restrictions.length>0){ for(var index = 0; index<self.currentRestrictions.restrictions.length; index++) { if(angular.equals(self.currentRestrictions.restrictions[index].restriction.restrictionGroupCode.toString().trim(), self.restrictionGroup.toString().trim())){ returnValue = true; break; } } } return returnValue; }; /** * Gets all the changes in the restrictions list * @param index */ self.getRestrictionDifference = function () { var arrayIndex; var restrictionChanges = { prodId: self.productMaster.prodId, restrictionsAdded: [], restrictionsRemoved: [] }; angular.forEach(self.currentRestrictions.restrictions, function (restriction) { var foundBanner = false; if (self.originalRestrictions.restrictions.length > 0) { for (arrayIndex = 0; arrayIndex < self.originalRestrictions.restrictions.length; arrayIndex++) { if (angular.equals(restriction.key, self.originalRestrictions.restrictions[arrayIndex].key)) { foundBanner = true; break; } } } if (!foundBanner) { restrictionChanges.restrictionsAdded.push(restriction); } }); angular.forEach(self.originalRestrictions.restrictions, function (restriction) { var foundBanner = false; if (self.currentRestrictions.restrictions !== null){ if (self.currentRestrictions.restrictions.length > 0) { for (arrayIndex = 0; arrayIndex < self.currentRestrictions.restrictions.length; arrayIndex++) { if (angular.equals(restriction.key, self.currentRestrictions.restrictions[arrayIndex].key)) { foundBanner = true; break; } } } } if (!foundBanner) { restrictionChanges.restrictionsRemoved.push(restriction) } }); return restrictionChanges; }; /** * Whenever one of the check boxes is checked this method will update a list of what indexes need to be deleted * @param index */ self.updateDeleteList = function (index) { if(self.deleteList.indexOf(index)<0){ self.deleteList.push(index); } else { self.allChecked = false; var iterator = self.deleteList.length; while (iterator--) { if (index === self.deleteList[iterator]) { self.deleteList.splice(iterator, 1); } } } }; /** * API call to update selling restrictions for special attributes. * */ self.getSellingRestrictionsForUpdate = function () { self.error = ''; self.success = ''; self.initCheckAllSellingRestrictions(); var sellingRestrictions = angular.copy(self.allShippingRestrictions); for(var index = 0; index < self.productShippingRestrictions.length; index++) { for(var innerIndex = 0; innerIndex < sellingRestrictions.length; innerIndex++) { if(sellingRestrictions[innerIndex].restrictionCode === self.productShippingRestrictions[index].restriction.restrictionCode) { sellingRestrictions[innerIndex].isChecked = true; break; } } } self.currentShippingRestrictions = angular.copy(sellingRestrictions); }; self.initCheckAllSellingRestrictions = function () { self.allShippingRestrictionChecked = self.productShippingRestrictions.length === self.allShippingRestrictions.length; }; /** * API call to update shipping method exceptions for special attributes. * */ self.getShippingMethodExceptionsForUpdate = function () { self.error = ''; self.success = ''; self.initCheckAllShippingMethodExceptions(); self.originalShippingMethodExceptions = angular.copy(self.allShippingMethodRestrictions); for(var index = 0; index<self.shippingMethodExceptions.length; index++) { for(var innerIndex = 0; innerIndex<self.originalShippingMethodExceptions.length; innerIndex++) { if(self.originalShippingMethodExceptions[innerIndex].customShippingMethod === self.shippingMethodExceptions[index].customShippingMethod.customShippingMethod) { self.originalShippingMethodExceptions[innerIndex].isChecked = true; break; } } } self.currentShippingMethodExceptions = angular.copy(self.originalShippingMethodExceptions); }; self.initCheckAllShippingMethodExceptions = function () { self.allShippingMethodChecked = self.shippingMethodExceptions.length === self.allShippingMethodRestrictions.length; }; /** * API call to update state warning for special attributes. * */ self.getStateWarningsForUpdate = function () { self.error = ''; self.success = ''; self.initCheckAllStateWarnings(); self.originalStateWarnings = angular.copy(self.allStateWarnings); for(var index = 0; index<self.productStateWarnings.length; index++) { for(var innerIndex = 0; innerIndex<self.originalStateWarnings.length; innerIndex++) { if(self.originalStateWarnings[innerIndex].key.stateCode === self.productStateWarnings[index].key.stateCode) { self.originalStateWarnings[innerIndex].isChecked = true; break; } } } self.currentStateWarnings = angular.copy(self.originalStateWarnings); }; self.initCheckAllStateWarnings = function () { self.allStateWarningsChecked = self.productStateWarnings.length === self.allStateWarnings.length; }; self.resetCheckAllRestrictions = function () { var currentShippingRestrictions = angular.copy(self.currentShippingRestrictions); var count = 0; for(var i = 0; i < currentShippingRestrictions.length; i++) { if(currentShippingRestrictions[i].isChecked === true) { count++; } } self.allShippingRestrictionChecked = self.allShippingRestrictions.length === count; }; self.resetCheckAllShippingMethod = function () { var currentShippingMethodExceptions = angular.copy(self.currentShippingMethodExceptions); var count = 0; for(var i = 0; i < currentShippingMethodExceptions.length; i++) { if(currentShippingMethodExceptions[i].isChecked === true) { count++; } } self.allShippingMethodChecked = self.allShippingMethodRestrictions.length === count; }; self.resetCheckAllStateWarnings = function () { var currentStateWarnings = angular.copy(self.currentStateWarnings); var count = 0; for(var i = 0; i < currentStateWarnings.length; i++) { if(currentStateWarnings[i].isChecked === true) { count++; } } self.allStateWarningsChecked = self.allStateWarnings.length === count; }; /** * This method will check all rows */ self.checkAllRows= function () { self.deleteList=[]; $("#restrictionsTable tr td:nth-child(1) input[type=checkbox]").prop("checked", self.allChecked); if(self.allChecked){ if(self.currentRestrictions.restrictions !== null){ for(var index=0; index<self.currentRestrictions.restrictions.length; index++){ self.deleteList.push(index); } } } }; /** * API call to update shipping restrictions for special attributes. * */ self.updateShippingRestrictions = function () { self.isLoading = true; self.error = ''; self.success = ''; var productRestrictionUpdates = {}; productRestrictionUpdates.prodId = angular.copy(self.productMaster.prodId); productRestrictionUpdates.productRestrictions = []; var productRestrictionUpdate; for(var innerIndex = 0; innerIndex<self.allShippingRestrictions.length; innerIndex++) { if (self.currentShippingRestrictions[innerIndex].isChecked) { productRestrictionUpdate = {}; productRestrictionUpdate.key = {}; productRestrictionUpdate.key.restrictionCode = self.currentShippingRestrictions[innerIndex].restrictionCode; productRestrictionUpdate.key.prodId = self.productMaster.prodId; productRestrictionUpdates.productRestrictions.push(productRestrictionUpdate); } } var shippingRestrictionsBeforeChange = []; var shippingRestrictionsAfterChange = []; angular.forEach(self.productShippingRestrictions, function(shippingRestrictions) { shippingRestrictionsBeforeChange.push(shippingRestrictions.key.restrictionCode.trim()) }); angular.forEach(productRestrictionUpdates.productRestrictions, function(productRestrictionUpdate) { shippingRestrictionsAfterChange.push(productRestrictionUpdate.key.restrictionCode.trim()); }); shippingRestrictionsBeforeChange.sort(); shippingRestrictionsAfterChange.sort(); if (JSON.stringify(shippingRestrictionsBeforeChange) !== JSON.stringify(shippingRestrictionsAfterChange)) { productApi.updateShippingRestrictionList(productRestrictionUpdates, self.reloadSavedData, self.fetchError); } else { self.error = NO_CHANGE_DETECTED_MSG; self.isLoading = false; } }; /** * API call to update shipping methods for special attributes. * */ self.updateShippingMethodExceptions = function () { self.isLoading = true; self.error = ''; self.success = ''; var shippingMethods = {}; shippingMethods.prodId = angular.copy(self.productMaster.prodId); shippingMethods.customShippingMethods = []; var customShippingMethod; for(var innerIndex = 0; innerIndex<self.allShippingMethodRestrictions.length; innerIndex++) { if(self.currentShippingMethodExceptions[innerIndex].isChecked) { customShippingMethod = {}; customShippingMethod.customShippingAbbriviation = self.currentShippingMethodExceptions[innerIndex].customShippingAbbriviation; customShippingMethod.customShippingMethod = self.currentShippingMethodExceptions[innerIndex].customShippingMethod; customShippingMethod.customShippingMethodDescription = self.currentShippingMethodExceptions[innerIndex].customShippingMethodDescription; shippingMethods.customShippingMethods.push(customShippingMethod); } } var shippingMethodsBeforeChange = []; var shippingMethodsAfterChange = []; angular.forEach(shippingMethods.customShippingMethods, function(shippingMethod) { shippingMethodsBeforeChange.push(shippingMethod.customShippingMethod.trim()) }); angular.forEach(self.shippingMethodExceptions, function(shippingMethod) { shippingMethodsAfterChange.push(shippingMethod.customShippingMethod.customShippingMethod.trim()) }); shippingMethodsBeforeChange.sort(); shippingMethodsAfterChange.sort(); if (JSON.stringify(shippingMethodsBeforeChange) !== JSON.stringify(shippingMethodsAfterChange)) { productApi.updateShippingMethods(shippingMethods, self.reloadSavedData, self.fetchError); } else { self.error = NO_CHANGE_DETECTED_MSG; self.isLoading = false; } }; /** * API call to update state warnings for special attributes. * */ self.updateStateWarnings = function () { self.isLoading = true; self.error = ''; self.success = ''; var productStateWarnings = {}; productStateWarnings.prodId = angular.copy(self.productMaster.prodId); productStateWarnings.productStateWarnings = []; var stateWarning; for(var innerIndex = 0; innerIndex<self.allStateWarnings.length; innerIndex++) { if(self.currentStateWarnings[innerIndex].isChecked) { stateWarning = {}; stateWarning.key = {}; stateWarning.key.stateCode = self.currentStateWarnings[innerIndex].key.stateCode; stateWarning.key.warningCode = self.currentStateWarnings[innerIndex].key.warningCode; stateWarning.abbreviation = self.currentStateWarnings[innerIndex].abbreviation; stateWarning.description = self.currentStateWarnings[innerIndex].description; productStateWarnings.productStateWarnings.push(stateWarning); } } var stateWarningsBeforeChange = []; var stateWarningsAfterChange = []; angular.forEach(self.productStateWarnings, function(stateWarning) { stateWarningsBeforeChange.push(stateWarning.productStateWarning.key.warningCode.trim()) }); angular.forEach(productStateWarnings.productStateWarnings, function(stateWarning) { stateWarningsAfterChange.push(stateWarning.key.warningCode.trim()) }); stateWarningsBeforeChange.sort(); stateWarningsAfterChange.sort(); if (JSON.stringify(stateWarningsBeforeChange) !== JSON.stringify(stateWarningsAfterChange)) { productApi.updateProductStateWarnings(productStateWarnings, self.reloadSavedData, self.fetchError); } else { self.error = NO_CHANGE_DETECTED_MSG; self.isLoading = false; } }; /** * This method will check all rows for shipping restrictions. */ self.checkAllShippingRestrictionRows= function () { var isChecked = self.allShippingRestrictionChecked === true; var allShippingRestrictionsWithCheck = angular.copy(self.allShippingRestrictions); for(var i = 0; i < allShippingRestrictionsWithCheck.length; i++) { allShippingRestrictionsWithCheck[i].isChecked = isChecked; }; self.currentShippingRestrictions = angular.copy(allShippingRestrictionsWithCheck); }; /** * This method will check all rows for shipping methods. */ self.checkAllShippingMethodRows= function () { var isChecked = self.allShippingMethodChecked === true; var allShippingMethodsWithCheck = angular.copy(self.allShippingMethodRestrictions); for(var i = 0; i < allShippingMethodsWithCheck.length; i++) { allShippingMethodsWithCheck[i].isChecked = isChecked; }; self.currentShippingMethodExceptions = angular.copy(allShippingMethodsWithCheck); }; /** * This method will check all rows for state warnings. */ self.checkAllStateWarningsRows = function () { var isChecked = self.allStateWarningsChecked === true; var allStateWarningsWithCheck = angular.copy(self.allStateWarnings); for(var i = 0; i < allStateWarningsWithCheck.length; i++) { allStateWarningsWithCheck[i].isChecked = isChecked; }; self.currentStateWarnings = angular.copy(allStateWarningsWithCheck); }; /** * This method will remove the selected restrictions */ self.deleteRestrictions = function () { self.allChecked=false; $("#restrictionsTable tr td:nth-child(1) input[type=checkbox]").prop("checked", false); for(var index = 0; index<self.deleteList.length; index++){ self.currentRestrictions.restrictions[self.deleteList[index]].toDelete=true; } for(var index = self.currentRestrictions.restrictions.length -1; index >=0; index--){ if(self.currentRestrictions.restrictions[index].toDelete){ self.currentRestrictions.restrictions.splice(index, 1); } } if(self.currentRestrictions.restrictions.length === 0){ self.currentRestrictions.restrictions = []; } self.deleteList=[]; }; /** * Show audit folder icon * @return - boolean to show icon */ self.showAuditFolder = function () { return true; } /** * Show audit information modal */ self.showSpecialAttributesAuditInfo = function () { if (angular.equals(self.currentTab, pharmacyTab)) { self.showPharmacyAuditInfo(); } else if (angular.equals(self.currentTab, tobaccoTab)) { self.showTobaccoAuditInfo(); } else if (angular.equals(self.currentTab, codeDateTab)) { self.showCodeDateAuditInfo(); } else if (angular.equals(self.currentTab, shippingHandlingTab)) { self.showShippingHandlingAuditInfo(); } else if (angular.equals(self.currentTab, ratingRestrictionsTab)) { self.showRatingRestrictionsAuditInfo(); } } /** * Show code date information modal */ self.showCodeDateAuditInfo = function () { self.codeDateAuditInfo = productApi.getCodeDateAudits; var title ="Code Date"; var parameters = {'prodId' :self.productMaster.prodId}; ProductDetailAuditModal.open(self.codeDateAuditInfo, parameters, title); } /** * Show shipping handling information modal */ self.showShippingHandlingAuditInfo = function () { self.shippingHandlingAuditInfo = productApi.getShippingHandlingAudits; var title ="Shipping and Handling"; var parameters = {'prodId' :self.productMaster.prodId}; ProductDetailAuditModal.open(self.shippingHandlingAuditInfo, parameters, title); } /** * Show pharmacy audit information modal */ self.showPharmacyAuditInfo = function () { self.pharmacyAuditInfo = productApi.getPharmacyAudits; var title ="Pharmacy"; var parameters = {'prodId' :self.productMaster.prodId}; ProductDetailAuditModal.open(self.pharmacyAuditInfo, parameters, title); } /** * Show tobacco audit information modal */ self.showTobaccoAuditInfo = function () { self.tobaccoAuditInfo = productApi.getTobaccoAudits; var title ="Tobacco"; var parameters = {'prodId' :self.productMaster.prodId}; ProductDetailAuditModal.open(self.tobaccoAuditInfo, parameters, title); } /** * Show rating/restriction audit information modal */ self.showRatingRestrictionsAuditInfo = function () { self.ratingRestrictionsAuditInfo = productApi.getRatingRestrictionsAudits; var title ="Rating/Restrictions"; var parameters = {'prodId' :self.productMaster.prodId}; ProductDetailAuditModal.open(self.ratingRestrictionsAuditInfo, parameters, title); } /** * handle when click on return to list button */ self.returnToList = function(){ $rootScope.$broadcast('returnToListEvent'); }; /** * Returns the added date, or null value if date doesn't exist. */ self.getAddedDate = function() { if(self.productMaster.createdDateTime === null || angular.isUndefined(self.productMaster.createdDateTime)) { return '01/01/1901 00:00'; } else if (parseInt(self.productMaster.createdDateTime.substring(0, 4)) < 1900) { return '01/01/0001 00:00'; } else { return $filter('date')(self.productMaster.createdDateTime, 'MM/dd/yyyy HH:mm'); } }; /** * Returns createUser or '' if not present. */ self.getCreateUser = function() { if(self.productMaster.displayCreatedName === null || self.productMaster.displayCreatedName.trim().length == 0) { return ''; } return self.productMaster.displayCreatedName; }; /** * Check current code date. * * @param currentCodeDate current code date. * @returns {boolean} result check. */ self.checkCurrentCodeDate = function (currentCodeDate) { self.resetAllCss(); var messageContent = ''; if (currentCodeDate.goodsProduct !== null) { if (self.isNullOrEmpty(currentCodeDate.goodsProduct.maxShelfLifeDays)) { messageContent += '<li>Max Shelf Life Days must be entered.</li>'; $('#maxSelf').attr('title', 'Max Shelf Life Days must be entered.'); $('#maxSelf').addClass('ng-touched ng-invalid'); }else if (currentCodeDate.goodsProduct.maxShelfLifeDays > 3650 || currentCodeDate.goodsProduct.maxShelfLifeDays === 0) { messageContent += '<li>Max Shelf Life Days must be greater than 0 and less than or equal to 3650.</li>'; $('#maxSelf').attr('title', 'Max Shelf Life Days must be greater than 0 and less than or equal to 3650.'); $('#maxSelf').addClass('ng-touched ng-invalid'); } if (self.isNullOrEmpty(currentCodeDate.goodsProduct.inboundSpecificationDays)) { messageContent += '<li>Inbound Specification Days must be entered.</li>'; $('#inboundSpecification').attr('title', 'Inbound Specification Days must be entered.'); $('#inboundSpecification').addClass('ng-touched ng-invalid'); }else if (!self.isNullOrEmpty(currentCodeDate.goodsProduct.maxShelfLifeDays) && (currentCodeDate.goodsProduct.inboundSpecificationDays >= currentCodeDate.goodsProduct.maxShelfLifeDays || currentCodeDate.goodsProduct.inboundSpecificationDays === 0)) { messageContent += '<li>Inbound Specification Days must be greater than 0 and less than Max Shelf Life Days.</li>'; $('#inboundSpecification').attr('title', 'Inbound Specification Days must be greater than 0 and less than Max Shelf Life Days.'); $('#inboundSpecification').addClass('ng-touched ng-invalid'); } if (self.isNullOrEmpty(currentCodeDate.goodsProduct.warehouseReactionDays)) { messageContent += '<li>Warehouse Reaction Days must be entered.</li>'; $('#warehouseReaction').attr('title', 'Warehouse Reaction Days must be entered.'); $('#warehouseReaction').addClass('ng-touched ng-invalid'); }else if(!self.isNullOrEmpty(currentCodeDate.goodsProduct.inboundSpecificationDays) && (currentCodeDate.goodsProduct.warehouseReactionDays >= currentCodeDate.goodsProduct.inboundSpecificationDays || currentCodeDate.goodsProduct.warehouseReactionDays === 0)){ messageContent += '<li>Warehouse Reaction Days must be greater than 0 and less than Inbound Specification Days.</li>'; $('#warehouseReaction').attr('title', 'Warehouse Reaction Days must be greater than 0 and less than Inbound Specification Days.'); $('#warehouseReaction').addClass('ng-touched ng-invalid'); } if (self.isNullOrEmpty(currentCodeDate.goodsProduct.guaranteeToStoreDays)) { messageContent += '<li>Guarantee To Store Days must be entered.</li>'; $('#guaranteeToStore').attr('title', 'Guarantee To Store Days must be entered.'); $('#guaranteeToStore').addClass('ng-touched ng-invalid'); }else if (!self.isNullOrEmpty(currentCodeDate.goodsProduct.warehouseReactionDays) && (currentCodeDate.goodsProduct.guaranteeToStoreDays >= currentCodeDate.goodsProduct.warehouseReactionDays || currentCodeDate.goodsProduct.guaranteeToStoreDays === 0)){ messageContent += '<li>Guarantee To Store Days must be greater than 0 and less than Warehouse Reaction Days.</li>' $('#guaranteeToStore').attr('title', 'Guarantee To Store Days must be greater than 0 and less than Warehouse Reaction Days.'); $('#guaranteeToStore').addClass('ng-touched ng-invalid'); } } if (messageContent !== '') { self.error = "Product Special Attribute:" + messageContent; return false; } return true; }; /** * Check object null or empty * * @param object * @returns {boolean} true if Object is null/ false or equals blank, otherwise return false. */ self.isNullOrEmpty = function (object) { return object === null || object === ""; }; /** * Check object null or empty * * @param object * @returns {boolean} true if Object is null/ false or equals blank, otherwise return false. */ self.isNullOrEmptyOrBlank = function (object) { return object === null || object === undefined || object.trim() === ""; }; /** * Reset all html. */ self.resetAllCss = function () { $('#maxSelf').attr('title', ''); $('#maxSelf').removeClass('ng-touched ng-invalid'); $('#inboundSpecification').attr('title', ''); $('#inboundSpecification').removeClass('ng-touched ng-invalid'); $('#warehouseReaction').attr('title', ''); $('#warehouseReaction').removeClass('ng-touched ng-invalid'); $('#guaranteeToStore').attr('title', ''); $('#guaranteeToStore').removeClass('ng-touched ng-invalid'); }; /** * Handle current code date when check or uncheck code date check box. * @param value */ self.currentCodeDateHandle = function (value) { if (self.currentCodeDate.goodsProduct !== null){ if (value === false){ self.resetAllCss(); self.currentCodeDate.goodsProduct.codeDate = false; self.currentCodeDate.goodsProduct.guaranteeToStoreDays = null; self.currentCodeDate.goodsProduct.maxShelfLifeDays = null; self.currentCodeDate.goodsProduct.inboundSpecificationDays = null; self.currentCodeDate.goodsProduct.warehouseReactionDays = null; self.currentCodeDate.goodsProduct.sendCodeDate = false; }else { self.currentCodeDate.goodsProduct.codeDate = true; self.currentCodeDate.goodsProduct.guaranteeToStoreDays = self.originalCodeDate.goodsProduct.guaranteeToStoreDays; self.currentCodeDate.goodsProduct.maxShelfLifeDays = self.originalCodeDate.goodsProduct.maxShelfLifeDays; self.currentCodeDate.goodsProduct.inboundSpecificationDays = self.originalCodeDate.goodsProduct.inboundSpecificationDays; self.currentCodeDate.goodsProduct.warehouseReactionDays = self.originalCodeDate.goodsProduct.warehouseReactionDays; self.currentCodeDate.goodsProduct.sendCodeDate = self.originalCodeDate.goodsProduct.sendCodeDate; } } }; /** * Clear value for medicail code, nd, drug schedule type code */ self.uncheckablePharmacySw = function () { if (self.currentRx.goodsProduct !== null){ if(self.currentRx.goodsProduct.rxProductFlag == false){ self.currentRx.goodsProduct.rxProduct.drugScheduleTypeCode = ""; self.currentRx.goodsProduct.medicaidCode = ""; self.currentRx.goodsProduct.rxProduct.ndc = ""; } } }; /** * PSE Type Code changed handle. Set all pse gram weight to zero when PSE type code has been set to NO PSE. */ self.pseTypeCodeChanged = function () { if (self.currentRx.goodsProduct !== null){ if(self.currentRx.goodsProduct.pseTypeCode === 'N'){ angular.forEach(self.currentRx.sellingUnits, function(item) { item.pseGramWeight = 0; }); } } }; /** * Check current pharmacy. * * @param currentCodeDate current pharmacy date. * @returns {boolean} result check. */ self.checkCurrentPharmacy = function (currentRx) { var messageContent = ''; if(currentRx.goodsProduct != null && currentRx.goodsProduct != undefined){ if(currentRx.goodsProduct.rxProductFlag === true) { if (currentRx.goodsProduct.rxProduct == null || currentRx.goodsProduct.rxProduct == undefined){ messageContent += '<li>Please select a Drug Schedulle.</li>'; messageContent += '<li>Please select a Medicaid.</li>'; }else{ if(self.isNullOrEmptyOrBlank(currentRx.goodsProduct.rxProduct.drugScheduleTypeCode)) { messageContent += '<li>Please select a Drug Schedulle.</li>'; } if (self.isNullOrEmptyOrBlank(currentRx.goodsProduct.medicaidCode)) { messageContent += '<li>Please select a Medicaid.</li>'; } } }else if(self.currentRx.goodsProduct !== null && self.currentRx.goodsProduct.rxProductFlag === true){ if (currentRx.goodsProduct.rxProduct != null && currentRx.goodsProduct.rxProduct != undefined && currentRx.goodsProduct.rxProduct.drugScheduleTypeCode != undefined && self.isNullOrEmptyOrBlank(currentRx.goodsProduct.rxProduct.drugScheduleTypeCode)) { messageContent += '<li>Please select a Drug Schedulle.</li>'; } if (currentRx.goodsProduct.medicaidCode != undefined && self.isNullOrEmptyOrBlank(currentRx.goodsProduct.medicaidCode)) { messageContent += '<li>Please select a Medicaid.</li>'; } } } if(currentRx.sellingUnits != null && currentRx.sellingUnits != undefined){ if (currentRx.goodsProduct != null && currentRx.goodsProduct != undefined) { if(self.isNullOrEmptyOrBlank(currentRx.goodsProduct.pseTypeCode)){ messageContent += '<li>Please select a PSE value.</li>'; } }else if(self.isNullOrEmptyOrBlank(self.currentRx.goodsProduct.pseTypeCode)){ messageContent += '<li>Please select a PSE value.</li>'; } if(self.currentRx.goodsProduct !== null && self.currentRx.goodsProduct.pseTypeCode != 'N') { angular.forEach(currentRx.sellingUnits, function (item) { if ((item.pseGramWeight && !self.regexDecimal.test(item.pseGramWeight)) || (item.pseGramWeight == 0)) { if (messageContent.indexOf("PSE Grams value must be number (#####.####), greater 0 and less than or equal to 99999.9999") == -1) { messageContent += '<li>PSE Grams value must be number (#####.####), greater 0 and less than or equal to 99999.9999.</li>'; } } }); } }else{ if (currentRx.goodsProduct != null && currentRx.goodsProduct != undefined && currentRx.goodsProduct.pseTypeCode != null && currentRx.goodsProduct.pseTypeCode != undefined) { if (self.isNullOrEmptyOrBlank(currentRx.goodsProduct.pseTypeCode)) { messageContent += '<li>Please select a PSE value.</li>'; } if(self.currentRx.sellingUnits != null && self.currentRx.sellingUnits != undefined && self.currentRx.goodsProduct != null && self.currentRx.goodsProduct != undefined && self.currentRx.goodsProduct.pseTypeCode != 'N'){ angular.forEach(self.currentRx.sellingUnits, function(item){ if((item.pseGramWeight && !self.regexDecimal.test(item.pseGramWeight)) ||(item.pseGramWeight == 0)){ if(messageContent.indexOf("PSE Grams value must be number (#####.####), greater 0 and less than or equal to 99999.9999") == -1){ messageContent+= '<li>PSE Grams value must be number (#####.####), greater 0 and less than or equal to 99999.9999.</li>'; } } }); } } } if (messageContent !== '') { self.error = "Product Special Attribute:" + messageContent; return false; } return true; }; } })();
var helper = require('./testcafeHtmlHelper.js'); module.exports = function htmlContent(reportObject) { return ` <!DOCTYPE html> <html> <head> <title>My Account Test Report</title> <link rel="stylesheet" href="./testcafeReport.css"> </head> <body> <table class="reportSummary"> <thead> <tr> <th>User Agent</th> <th><button class="filterBtn" id="total">Total</button></th> <th><button class="filterBtn" id="passed">Passed</button></th> <th><button class="filterBtn" id="failed">Failed</button></th> <th><button class="filterBtn" id="skipped">Skipped</button></th> <th>Execution Time</th> </tr> </thead> <tbody> <tr> <td>${reportObject.userAgents}</td> <td>${reportObject.total}</td> <td>${reportObject.passed}</td> <td>${reportObject.total - reportObject.passed}</td> <td>${reportObject.skipped}</td> <td>${((Date.parse(reportObject.endTime) - Date.parse(reportObject.startTime)) / 60000).toFixed(2)} minutes</td> </tr> </tbody> </table> <table class="legendTable"> <tr> <td>Fixtures: ${symbols.fixtures}</td> <td>Tests: ${symbols.tests}</td> <td>Browser Logs: ${symbols.browserLogs}</td> <td>Http Requests: ${symbols.httpRequests}</td> <td>Test Info: ${symbols.testInfo}</td> </tr> </table> ${expandAndCollapseButtons} ${helper.flushFixtures(reportObject.fixtures)} ${expandAndCollapseButtons} <!-- The Modal --> <div id="myModal" class="modal"> <!-- The Close Button --> <span class="close">&times;</span> <!-- Modal Content (The Image) --> <img class="modal-content" id="img01"> <!-- Modal Caption (Image Text) --> <div id="caption"></div> </div> <script type="text/javascript"> var acc = document.getElementsByClassName("accordian"); var failed = document.getElementsByName("fixture-Failed"); var expandAll = document.getElementsByName("expand"); var collapseAll = document.getElementsByName("collapse"); var failedFixtures = document.getElementsByName("expand-fixtures-Failed"); var filterFail = document.getElementById("failed") var filterPassed = document.getElementById("passed") var filterSkipped = document.getElementById("skipped") var filterTotal = document.getElementById("total"); var trs = document.getElementsByClassName("result-rows"); var failedTrs= document.getElementsByClassName("failed-testrows"); // Click on Individual accordian to expand and collapse for (var i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function () { this.classList.toggle("active"); var panel = this.nextElementSibling; var testRow = this.nextElementSibling.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; testRow.style.display = "none"; } else { panel.style.display = "block"; testRow.style.display = "table"; } }); } // Click on Expand All Buttons to expand all the accordians for (var i = 0; i < expandAll.length; i++) { expandAll[i].addEventListener("click", function () { for (var j = 0; j < acc.length; j++) { acc[j].nextElementSibling.style.display = "block"; acc[j].nextElementSibling.nextElementSibling.style.display = "table"; } for (var k = 0; k < trs.length; k++) { trs[k].style.display = "table-row"; } }); } // Click on Collapse All Buttons to collapse all the accordians for (var i = 0; i < collapseAll.length; i++) { collapseAll[i].addEventListener("click", function () { for (var j = 0; j < acc.length; j++) { acc[j].nextElementSibling.style.display = "none"; acc[j].nextElementSibling.nextElementSibling.style.display = "none"; } for (var k = 0; k < trs.length; k++) { trs[k].style.display = "none"; } }); } // Click on Expand Failed Fixturesbutton to expand only the failed fixtures for (var i = 0; i < failedFixtures.length; i++) { failedFixtures[i].addEventListener("click", function () { for (var j = 0; j < acc.length; j++) { if(failed[j]){ failed[j].nextElementSibling.style.display = "block"; failed[j].nextElementSibling.nextElementSibling.style.display = "table"; } } for (var k = 0; k < failedTrs.length; k++) { failedTrs[k].style.display = "table-row"; } }); } // Show only Failed Fixtures and Hide the rest filterFail.addEventListener("click", function () { for (var i = 0; i < acc.length; i++) { changeDisplay(acc[i],"fixture-Failed"); } }); // Show only Passed Fixtures and Hide the rest filterPassed.addEventListener("click", function() { for(var i = 0; i < acc.length; i++) { changeDisplay(acc[i],"fixture-Passed"); } }); // Show only Skipped Fixtures and Hide the rest filterSkipped.addEventListener("click", function() { for(var i = 0; i < acc.length; i++) { changeDisplay(acc[i],"fixture-Skipped"); } }); // Clear all Filters filterTotal.addEventListener("click", function() { for(var i = 0; i < acc.length; i++) { acc[i].style.display="block" ; } }); function changeDisplay(element,fixtureType){ if(element.getAttribute("name")==fixtureType ) { element.style.display="block" ; } else{ element.style.display="none"; } } //Adding event handler against each header rows for accordian functionality var tbodies = document.getElementsByClassName("test-tbody"); for (i = 0; i < tbodies.length; i++) { var tbody= tbodies[i]; var id=tbody.id; var thead=tbody.children[0]; thead.addEventListener("click", function(event){ var targetElement = event.target || event.srcElement; }); } // Get the modal var modal = document.getElementById("myModal"); // Get the image and insert it inside the modal - use its "alt" text as a caption var body = document.getElementsByTagName("body") var imgs = body[0].querySelectorAll("img"); var modalImg = document.getElementById("img01"); for (i = 0; i < imgs.length-1; i++) { var img=imgs[i]; img.onclick = function(){ modal.style.display = "block"; modalImg.src = this.src; } } // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } </script> </body> </html> `; }; const expandAndCollapseButtons = ` <button class="toggle-all" name="expand">EXPAND ALL</button> <button class="toggle-all" name="collapse">COLLAPSE ALL</button> <button class="toggle-all" name="expand-fixtures-Failed">EXPAND FAILED FIXTURES</button> `; const symbols = { fixtures: '&#128301;', tests: '&#127776;', browserLogs: '&#128187;', httpRequests: '&#128376;', testInfo: '&#128712;', greenTick: '&#9989;', redCross: '&#10060;', slashChar: '&#92;' };
var mongoose = require('mongoose'); var q = require('q'); var bcrypt = require('bcryptjs'); mongoose.connect('mongodb://conde:1234@ds013290.mlab.com:13290/mydatabase', function(err) { if (err) { throw err; } else { console.log('Connected to database'); } }); var UserSchema = mongoose.Schema({ username: { type: String, index: true }, name: { type: String }, email: { type: String }, password: { type:String } }); UserSchema.pre('save', function(next) { var user = this; bcrypt.genSalt(10, function(err, salt) { if (err) { return next(err); } if (!user.isModified('password')) return next(); bcrypt.hash(user.password, salt, function(err, hash) { if (err) { return next(err); } user.password = hash; next(); }); }); }); var User = module.exports = mongoose.model('User', UserSchema); User.createUser = function(newUser) { var deferred = q.defer(); newUser.save(function(err, newUser) { if(err) { deferred.reject(err); } else { deferred.resolve(newUser); } }); return deferred.promise; }
function prepareSlideShow(){ if(!yc.isCompatible()) return false; if(!yc.$("alltabs")) return false; if(!yc.$("preview")) return false; var preview=yc.$("preview"); preview.style.position="absolute"; preview.style.left="0px"; preview.style.top="0px"; var list=yc.$("alltabs"); var links=list.getElementsByTagName("a"); // for(var i=0;i<links.length;i++){ // links[i].index=i+1; // yc.addEvent(links[i],"mouseover",function(){ // //yc.moveElement("preview",this.index*(-100),0,10); // console.log(this.index*(-100)); // }); // } for(var i=0;i<links.length;i++){ (function(index){ yc.addEvent(links[index],"mouseover",function(){ yc.moveElement("preview",(index+1)*(-100),0,10); }); })(i); } } yc.addLoadEvent(prepareSlideShow);
import React, { Component } from 'react' import SliderPort from './SliderPort'; class PortfolioSection extends Component { render() { return ( <div className="portfolio-section"> <h3>Get To Know Us a Little Better!</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eu eratiuy lacus, vel congue mauris. Fusce velitaria justo, faucibus eu.</p> <SliderPort /> </div> ) } } export default PortfolioSection;
#! /usr/local/bin/jjs // わかりません function pipe () { var pb = new java.lang.ProcessBuilder var args = [] for each (var arg in arguments) { args.push(arg) } pb.command(['/bin/sh','-c',args.join("|")]) var p = pb.start() var br = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream())) var str var result = [] while((str = br.readLine()) != null) { result.push(str) } return result.join("\n") } print(pipe('cat pipeTest.txt', 'grep -v a', 'sort'))
import '../../../../scripts/common/app' import View from './index.vue' new Vue({ el: '#app', components: { }, render:function(h){ const v = h(View); return v } })
import { TESTAPPID, APPID } from './constants' import storage from './storage-lite' import session from './session-lite' import router from '../router' import Tools from './tools' import api from '@/api/login' import Bridge from '@/utils/bridge' const AUTH_DATA = 'authData' export default { name: 'auth', isWx: (/MicroMessenger/i).test(window.navigator.userAgent.toLowerCase()), /** * * @return {[type]} [description] */ getAuthData () { return storage.get(AUTH_DATA) }, /** * isLoggedIn * @return {Boolean} [description] */ isLoggedIn () { return this.checkToken() //if (Tools.isApp && session.get('appAccountId') == 0) return false }, /** * 微信授权 * @return {[type]} [description] */ wxLogin () { const appid = location.hostname.startsWith('h5test') ? TESTAPPID : APPID // const appid = APPID storage.set('HQBSREDIRECT', location.href) const url = encodeURIComponent(`${location.origin}/wxauth`) window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect` }, /** * 登录 * @return {[type]} [description] */ login (redirectUrl) { // if (Tools.isApp && session.get('appAccountId') == 0) { // window.location.href = 'ggj://redirect/typeCommon/{"type":6}' // return false // } //if (!this.isLoggedIn()) { if (this.isWx) { this.wxLogin() } else if (Tools.isApp) { Bridge.appLogin(redirectUrl,res=>{ if(res == 'success'){ // window.location.href = redirectUrl || '/' }else{ Tools.toast('登录失败,请稍后重试') } }) //window.location.href = 'ggj://redirect/typeCommon/{"type":6}' } else { window.location.href = '/login?redirect_url=' + encodeURIComponent(redirectUrl) || '' } //} }, loginByCode (code) { const _accountId = session.get('accountId') || 0 let data = { code: code, referrerId: _accountId } api.wxLogin(data).then((res) => { const _redirect = storage.get('HQBSREDIRECT') const _r = res storage.remove('HQBSREDIRECT') if (_r.status === 1) { storage.set('authData', _r.data) //router.replace({ path: _redirect }) location.href = _redirect } else { router.push({path: '/'}) // if (_r.codeMsg) { // const _c = _r.codeMsg // if (_c.code === 3090320002) { // storage.set('authData', _r.data) // // 绑定手机号 // router.push( // { // path: '/login/bound?redirect_url=' + _redirect // } // ) // } else if (_c.code === 3090320003) { // storage.set('authData', _r.data) // // 绑定推荐人 // router.push( // { // path: '/login/introducer?redirect_url=' + _redirect // } // ) // } // } } }) }, /* * 判断token是否失效 * _expiredTime <= 5 获取新的token * 新token失效后 后端会返回跳转登录的错误代码 */ checkToken () { if (Tools.getCookie('_ggj_aid_')) { // const _currentTime = new Date().getTime() // const _expiredTime = storage.get('authData').expired // const _val = _expiredTime - _currentTime // if (_val > 300000) { // return 1// 有效 // } else { // return 0// 失效或即将失效 重新获取token // } return true }else{ return false } }, // getNewToken () { // let conf = new Config() // conf.data = { // refreshToken: storage.get('authData').refreshToken // } // conf.url = '/auth/refreshToken' // new Request(conf).POST().then((res) => { // console.log(res) // storage.set('authData', res.data) // window.location.reload() // }) // }, getAppToken (obj) { // let conf = new Config() // conf.url = '/auth/loginByApp' let data = { accountId: obj.accountId, sign: obj.sign, version: obj.version, os: obj.os } api.loginApp(data).POST().then((res) => { storage.set('authData', res.data) // window.location.reload() }) } }
import React, {useState, useEffect, useRef} from 'react'; import Results from '../Results/Results'; import TopButton from '../TopButton/TopButton'; import {FaSearch} from 'react-icons/fa'; import '../global.css'; import * as styles from './searchBar.module.css'; const Search = (props) => { const [searchTerm, setSearchTerm] = useState(''); const [submitted, setSubmitted] = useState(false); const handleChange = (e) => { setSearchTerm(e.target.value); submitted && setSubmitted(false); }; const handleSubmit = (e) => { e.preventDefault(); // Force the search alert to show if there are no search results: setSubmitted(true); }; // Listen for page scroll and show the back-to-top button: const [showTop, setShowTop] = useState(false); const searchBar = useRef(null); useEffect(() => { const watchScroll = () => { searchBar.current.getBoundingClientRect().top < 0 && setShowTop(true); searchBar.current.getBoundingClientRect().top >= 0 && setShowTop(false); }; window.addEventListener('scroll', watchScroll, false); return () => window.removeEventListener('scroll', watchScroll); }); return ( <> <section className={styles.search}> <form className={`${styles.searchBar} box`} onSubmit={handleSubmit} ref={searchBar} > <fieldset> <legend> {`We invite you to acknowledge your favourite directors by nominating their movies in the search results below.`} <br /> Please select 5 movies. </legend> <input name="search-text" className={styles.searchTextField} placeholder="Search for the movie to nominate" value={searchTerm} onChange={handleChange} type="search" style={{fontSize: '1em'}} /> <button className={styles.searchButton} value="Submit" > <FaSearch /> </button> </fieldset> </form> </section> {searchTerm.length > 0 && <> <Results searchTerm={searchTerm} submitted={submitted} nominatedList={props.nominatedList} nominate={props.nominate} /> {showTop && <TopButton />} </> } </> ); }; export default Search;
var m = require('mithril'); var icons = ( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-_=+[{]};:'" + '"' + "|,<.>/?" ).split(''); var rand = ( min, max ) => min + Math.floor( Math.random() * ( max - min ) ); var sample = ( arr, n = 1 ) => { if ( n === 1 ) return arr[ rand( 0, arr.length ) ]; var sample = arr.map( x => x ); for ( var i = 0; i < n; i++ ) { var r = rand( i, arr.length - 1 ); var temp = sample[ i ]; sample[ i ] = sample[ r ]; sample[ r ] = temp; } return sample.slice( 0, n ); } var padNumber = n => String( n ).padStart( 2, '0' ); var formatTime = date => padNumber( date.getHours() ) + ':' + padNumber( date.getMinutes() ); module.exports = { oninit: ({ state }) => { state.icons = sample( icons, 5 ); var update = () => { var icon = sample( icons.filter( i => !state.icons.includes( i ) )); // do { // icon = char(); // } while ( state.icons.includes( icon ) ); state.icons[ rand( 0, state.icons.length ) ] = icon; m.redraw(); state.timer = setTimeout( update, rand( 1000, 3000 ) ); } update(); }, onremove: ({ state }) => clearTimeout( state.timer ), view: ({ attrs: { battery = 0 }, state: { icons } }) => { var color = battery < .25 ? 'red' : ( battery < 1 ? 'yellow' : 'green' ); return m( '.status-bar', // m('span.status-bar__item', 'Just an Idea'), // m('span.status-bar__item.status-bar__item--icons', icons.map( i => m('span.status-bar__icon', i )) ), m('span.status-bar__item', { style: { color } }, Math.round( battery * 100 ), '%' ), // m('span.status-bar__item', formatTime( new Date() ) ) ) } }
'use strict'; const path = require('path'); //export plugin registration function exports.register = (server, options, next) => { const clientDistPath = path.join(__dirname, '../../../dist/client/dist'); server.route({ path: '/client/{param*}', method: 'GET', config: { auth: false, cors: true, description: 'Returns client source code', notes: 'Add filename (e.g. client.js)', handler: { directory: { path: clientDistPath, listing: true } }, plugins: { 'hapi-swagger': { nickname: 'get' } }, tags: ['client'], } }); next(); }; exports.register.attributes = { name: 'client-source' };
const BrowserWaits = require('../../../support/customWaits'); const exuiErrorMessage = require('../common/exuiErrorMessage'); class DescribeExclusionPage { constructor() { this.container = $('exui-describe-exclusion'); this.headerCaption = this.container.$('h1 span'); this.header = this.container.$('h1'); this.textArea = this.container.$('#exclusion-description'); } async isDisplayed() { try { await BrowserWaits.waitForElement(this.container); return true; } catch (err) { return false; } } async getHeaderCaption() { return await this.headerCaption.getText(); } async getHeaderText() { return await this.header.getText(); } async enterExclusionDescription(description){ await this.textArea.clear(); await this.textArea.sendKeys(description); } } module.exports = new DescribeExclusionPage();
/** * @author Bruce * created on 2018.06.08 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.emergency') .controller('fireAlertPageCtrl', fireAlertPageCtrl); /** @ngInject */ function fireAlertPageCtrl($scope, $filter, editableOptions, editableThemes, $uibModal, baProgressModal) { $scope.fireAlertData = [{ id: 1, num: 'SY001fa', date: '2018-02-02', dept: '动火车间', person: 'Bruce', duty: '张三', stus: '0', locked: false }, ]; // 火警的实体类 class FireAlertData { // 构造函数 constructor(id, num, date, dept, person, duty, stus, locked, ) { this.id = id; this.num = num; this.date = date; this.dept = dept; this.person = person; this.duty = duty; this.stus = stus; this.locked = locked; } } // 将报警信息实例化 var getFireAlert = function (msg) { msg.map((v, i) => { // id let id = i+1; // 生成一个新的编号num let num = 'SY' + Date.now().toString(36).substr(3); // 当前时间 let date = moment().format('YYYY-MM-DD'); // 部门 let dept = v.addr; // 报警人 let person = 'Bruce'; // 值长 let duty = '管理员'; // 状态,初始状态为0 let stus = '0'; // 是否归档 let locked = false; let obj_fireAlert = new FireAlertData(id, num, date, dept, person, duty, stus, locked); $scope.fireAlertData.push(obj_fireAlert); }); }; getFireAlert(msgCenter.msg); // 指派状态 $scope.stus = [{ value: 0, text: '未指派' }, { value: 1, text: '火警安全员' }, { value: 2, text: '安全部主任' }, { value: 3, text: '厂长办公室' }, { value: 4, text: '系统管理员' }, { id: 2, num:'GY009fa', date: '2018-02-02', dept: '动火车间', person: 'Bruce', duty:'张三', stus: '未分配' } ]; } })();
var maxPathSum = function(root) { let localmax = -Infinity function dfs(node) { if (!node) {return 0} let leftmax = Math.max(0, dfs(node.left)) let rightmax = Math.max(0, dfs(node.right)) localmax = Math.max(localmax, leftmax + rightmax + node.val) return Math.max(leftmax, rightmax) + node.val } dfs(root) return localmax };
'use strict'; var makeComposition = require('./composition').makeComposition; var regex = /(.*?)(\s+?)(extends\s+?)((?:.|\n)*?){(?:(?:.|\n)*?)}/g; module.exports = function extractExtends(css, hashed) { var found, matches = []; while (found = regex.exec(css)) { matches.unshift(found); } function extractCompositions(acc, match) { var extendee = getClassName(match[1]); var keyword = match[3]; var extended = match[4]; // remove from output css var index = match.index + match[1].length + match[2].length; var len = keyword.length + extended.length; acc.css = acc.css.slice(0, index) + acc.css.slice(index + len); var extendedClasses = splitter(extended); extendedClasses.forEach(function(className) { if (!acc.compositions[extendee]) { acc.compositions[extendee] = {}; } if (!acc.compositions[className]) { acc.compositions[className] = {}; } acc.compositions[extendee][className] = acc.compositions[className]; }); return acc; } var res = matches.reduce(extractCompositions, { css: css, compositions: {} }); var extensions = Object.keys(res.compositions) .reduce(function(acc, key) { var val = res.compositions[key]; var extended = getClassChain(val); if (extended.length) { var allClasses = [key].concat(extended); var unscoped = allClasses.map(function(name) { return hashed[name] ? hashed[name] : name; }); acc[key] = makeComposition(allClasses, unscoped); } return acc; }, {}); return { css: res.css, extensions: extensions }; }; function splitter(match) { return match.split(',').map(getClassName); } function getClassName(str) { var trimmed = str.trim(); return trimmed[0] === '.' ? trimmed.substr(1) : trimmed; } function getClassChain(obj) { var visited = {}, acc = []; function traverse(obj) { return Object.keys(obj).forEach(function(key) { if (!visited[key]) { visited[key] = true; acc.push(key); traverse(obj[key]); } }); } traverse(obj); return acc; }
import Immutable from 'immutable'; import ActionTypes from '../redux-actions/ActionTypes'; const initialState = Immutable.Map({ branchStatePage: false }); export default function dismissedBetaNotifications(state = initialState, action) { switch (action.type) { case ActionTypes.DISMISS_BRANCH_STATE_PAGE_BETA_NOTIFICATION: return state.set('branchStatePage', true); default: return state; } }
//a for loop and display the numbers from 1 to 100, 2 by 2 for(var x=0;x<=100;x+=2){ document.write("Line"+ x + "</br>"); }
/* * imageInfoComponent.js * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * Selling Unit -> Image Info component. * * @author s753601 * @since 2.13.0 */ (function () { angular.module('productMaintenanceUiApp').component('imageInfo', { // isolated scope binding bindings: { sellingUnit: '<', productMaster: '<' }, // Inline template which is binded to message variable in the component controller templateUrl: 'src/productDetails/productSellingUnits/imageInfo.html', // The controller that handles our component logic controller: ImageInfoController }); angular.module('productMaintenanceUiApp').directive('customNavigate', function ($templateCache, $compile, $timeout) { return { restrict: 'A', scope: true, link: function (scope, element, attr) { var template = $templateCache.get(attr.templatePagination); $timeout(function () { // angular.element( document.querySelector( '#paging' ) ).remove(); angular.element(document.querySelector('#customPaging')).append($compile(template.replace('hidden', ''))(scope)); }, 1000); } } }); ImageInfoController.$inject = ['productSellingUnitsApi', 'customHierarchyService', '$state', '$rootScope', 'appConstants', 'imageInfoService', 'PermissionsService', 'ProductSearchService', 'DownloadImageService', 'ngTableParams', '$scope']; /** * UPC Info component's controller definition. * @constructor * @param productSellingUnitsApi * @param customHierarchyService * @param $state * @param $rootScope * @param appConstants * @param imageInfoService * @param permissionsService * @param productSearchService * @param downloadImageService * @param ngTableParams * @param $scope * @constructor */ function ImageInfoController(productSellingUnitsApi, customHierarchyService, $state, $rootScope, appConstants, imageInfoService, permissionsService, productSearchService, downloadImageService, ngTableParams, $scope) { var self = this; /** * When attempting to make an invalid upload request these messages will tell you what the cause of the error is * @type {string} */ var INVALID_FILE_UPLOAD = "Attempting to upload an invalid file type"; var MISSING_OR_INVALID_FILE = "Missing or Invalid file type cannot upload"; var MISSING_IMAGE_SOURCE = "Missing Image Source"; var MISSING_IMAGE_CATEGORY = "Missing Image Category"; var IMAGE_UPLOAD_FAIL_TO_LAUNCH = "Failed to upload Image because of the following error(s)\n "; var MISSING_DESTINATION_FOR_UPLOAD = "Missing Destination Domain"; var MISSING_DESTINATION_DOMAIN = "Destination Domain is mandatory"; var APPROVED_STATUS_CODE = "A"; var STATUS_FOR_REVIEW = 'S'; var STATUS_REJECTED = 'R'; var PRIMARY_PRIORITY = "P"; var PRIMARY_ALTERNATE = 'A'; var PRIMARY_NOT_APPLICABLE = 'NA'; var CATEGORY_SWATCHES = 'SWAT'; var MISSING_PRIMARY_STRING = "Alternate Images cannot be \" Active Online\" without a Primary Image that is \"Active\"."; /** * Validation messages */ const ONLY_ONE_PRIMARY_FOR_PRODUCT = "Only image can be Primary for a product."; const IMG_ACTIVE_ONLINE_IN_ALTERNATE = 'Alternate Images cannot be "Active Online" without a Primary Image that is "Active Online".'; const IMG_STATUS_CHANGE_TO_REVIEW = 'An image in "Approved" or "Rejected" status cannot be moved to "For Review" Status.'; const IMG_ACTIVE_ONLINE_IN_CATEGORY_SWATCH = 'Swatch images cannot be "Active Online" without a Primary image that is "Active Online".'; const IMG_PRIMARY_REJECTED = "An image in 'Rejected' status cannot be set as 'Primary'."; const IMG_PRIMARY_FOR_REVIEW_ACTONLINE = 'An image in "For review" status can not be made "Active Online".'; const IMG_STATUS_REJECTED = 'An image in "Rejected" status cannot be made "Active Online".'; const IMG_ACTIVE_ONLINE_IS_NONE_CATEGORY_OR_PRIMARY_ALTERNATE = 'An image cannot be "Active Online" without the "Image Category" or the "Primary/Alternate" defined.'; const MESSAGE_NO_DATA_CHANGE = "There are no changes on this page to be saved. Please make any changes to update."; /** * Boolean for if images are present * @type {boolean} */ self.imageInfo = false; /** * List of Approved Images * @type {Array} */ self.approvedImageInfo = []; /** * List of Active Online Images * @type {Array} */ self.activeOnlineImages = []; /** * List of Pending and Rejected Images * @type {Array} */ self.submittedImages = []; /** * List of URIs to be sent to webservice for image retrieval * @type {Array} */ self.imageURIs = []; /** * Flag for indicating that the front end is still waiting on data from the backend */ self.isWaitingForResponse = false; /** * Success message to be displayed */ self.success = null; /** * Error message to be displayed */ self.error = null; /** * Whenever the user attempts a change that is not valid this message will be displayed * @type {null} */ self.invalidChange = null; /** * List of categories for the dropdown */ self.categories = []; /** * List of statuses for the dropdown */ self.statuses = []; /** * List of destinations for the dropdown \ */ self.destinations = []; /** * List of priorities for the dropdown */ self.priorities = []; /** * List of iamge sources for a dropdown * @type {{}} */ self.sources = {}; /** * Flag for displaying rejected images. */ self.showRejected = false; /** * String for the show rejected button */ self.showRejectedDisplay = "Show Rejected"; /** * String for the show all button */ self.showAllDisplay = "Show All"; /** * Image category for new image candidate * @type {string} */ self.uploadImageCategory = ""; /** * Arrays of original data used for comparison and for data reset * @type {Array} */ self.originalImages = []; self.originalActiveImages = []; self.originalSubmittedImage = []; /** * These flags are used to tell the component what part of the updated it is still waiting on * @type {boolean} */ self.waitingForAddingDestintions = false; self.waitingForRemovingDestinations = false; self.waitingForDataUpdates = false; /** * A list of changes that need to be made to the upc's image info. * @type {Array} */ self.destinationUpdates = []; /** * Image source for new image candidate * @type {string} */ self.uploadImageSource = ""; /** * List of destinations for new image candidate * @type {{}} */ self.uploadImageDestinations = {}; /** * Byte[] for new image candidate * @type {string} */ self.uploadImageImage = ""; /** * Current image loading. * @type {string} */ self.imageBytes = ''; /** * Current image format. * @type {string} */ self.imageFormat = ''; /** * This flag states if the current file is of a valid file type * @type {boolean} */ self.invalidFileType = false; /** * List of valid file types * @type {[string,string,string,string,string]} */ self.validFileTypes = ["jpg", "jpeg", "png"]; /** * This object handles all of the image editing functionality * @type {null} */ self.cropper = null; /** * This variable keeps track of the number of degrees the image has been spinned * @type {number} */ self.currentAngle = 0; /** * This variable keeps track how if the x axis has been flipped * @type {number} */ self.scaleX = 1; /** * This variable keeps track if the y axis has been flipped * @type {number} */ self.scaleY = 1; /** * This variable holds the data for the new cropped image * @type {null} */ self.editedImage = null; /** * This variable is used to send the new cropped image to the backend. * @type {null} */ self.imageToEditData = null; /** * Flag stating if the image information is missing a destination domain * @type {boolean} */ self.missingDestination = false; /** * A list of selected images to possibly be copied to an hierarchy * @type {Array} */ self.selectedImages = []; /** * Flag for if all the images are selected * @type {boolean} */ self.selectAllImages = false; /** * A flag to state if either a single or all entities in the default path need to be copied * @type {null} */ self.hierarchyLevels = null; /** * The default hierarchy path for a product * @type {Array} */ self.hierarchyPath = []; /** * The string used to display the default path of a product * @type {null} */ self.hierarchyString = null; /** * The list of upcs attached to a product and used to get all of the images attached to the product * @type {Array} */ self.upcs = []; /** * Flag stating if there is a default hierarchy path available. * @type {boolean} */ self.isDisableHierarchy = false; /** * This flag is set to true when the images status is in an illegal state * @type {boolean} */ self.invalidStatus = false; /** * This string is set when the images status is in an illegal state * @type {string} */ self.invalidStatusString = ""; /** * Check if it is the first time to load images or not. * * @type {boolean} */ self.isFisrtLoad = true; /** * The default page number. * * @type {number} */ self.PAGE = 1; /** * Total element in page * @type {number} */ self.PAGE_SIZE = 10; /** * The ngTable object that will be waiting for data while the report is being refreshed. * * @type {object} */ self.defer = null; /** * The parameters passed from the ngTable when it is asking for data. * * @type {object} */ self.dataResolvingParams = null; /** * The total number of pages in the report. * * @type {null} */ self.totalPages = null; /** * The total records in the report. * * @type {null} */ self.totalRecordCount = null; /** * The flag for show/hide rejected images. * @type {boolean} */ self.isShowRejected = false; /** * Check if it is search with count or not. * * @type {boolean} */ self.includeCount = false; /** * The flag check for show/hide navigation confirm popup. * @type {boolean} */ self.isShowingNavigationConfirmPopup = false; /** * Total images of selling unit UPC. * @type {number} */ self.totalImages = 0; /** * Total approved images of selling unit UPC. * @type {number} */ self.totalApprovedImages = 0; /** * Total need approving images of selling unit UPC. * @type {number} */ self.totalNeedingApprovingImages = 0; /** * Set value margin top css of object. * @type {string} */ self.marginTop = "0px"; /** * Function getActiveOnlineImages has called. * @type {boolean} */ self.getActiveOnlineImagesHasCalled = false; /** * Current productId. * @type {null} */ self.currentProductId = null; /** * Initialize some default values . * @type {string} */ const EMPTY = ""; const SHOW_ALL = "Show All"; const HIDE_ALL = "Hide All"; const HIDE_REJECTED = "Hide Rejected"; const SHOW_REJECTED = "Show Rejected"; /** * Component ngOnInit lifecycle hook. This lifecycle is executed every time the component is initialized * (or re-initialized). */ this.$onInit = function () { self.disableReturnToList = productSearchService.getDisableReturnToList(); self.imageInfo = false; productSellingUnitsApi.getImageCategories(self.loadImageCategories, self.handleError); productSellingUnitsApi.getImageStatuses(self.loadImageStatuses, self.handleError); productSellingUnitsApi.getImageDestinations(self.loadDestinations, self.handleError); productSellingUnitsApi.getImagePriorities(self.loadPriorities, self.handleError); productSellingUnitsApi.getImageSources(self.loadImageSources, self.handleError); self.cropper = window.Cropper; var image = document.getElementById('imageToEdit'); self.cropper = new Cropper(image, { minContainerWidth: 1000, minContainerHeight: 750 }); }; /** * Component will reload the vendor data whenever the item is changed in casepack. */ this.$onChanges = function () { self.isAllButtonClicked = undefined; self.error = null; self.success = null; self.invalidChange = null; self.resetCountImages(); if (self.productMaster !== null && self.productMaster !== undefined) { self.isWaitingForResponse = true; self.imageInfo = false; self.upcs = []; angular.forEach(self.productMaster.sellingUnits, function (sellingUnit) { self.upcs.push(sellingUnit.upc); }); if(!self.getActiveOnlineImagesHasCalled || self.currentProductId === self.productMaster.prodId){ self.getActiveOnlineImages(); } else { self.getActiveOnlineImagesHasCalled = false; } } }; /** * Reset variables count image */ self.resetCountImages = function () { self.totalImages = 0; self.totalApprovedImages = 0; self.totalNeedingApprovingImages = 0; }; /** * Load image sources that response from api. * @param results the list of image sources. */ self.loadImageSources = function (results) { self.sources = results; }; /** * Load image categories that response from api. * @param results the list of image categories. */ self.loadImageCategories = function (results) { self.categories = results; }; /** * Load image statuses that response from api. * @param results the list of image status. */ self.loadImageStatuses = function (results) { angular.forEach(results, function (status) { if (status.id !== '') { self.statuses.push(status); } }); }; /** * Load destination that response from api. * @param results the list of destinations. */ self.loadDestinations = function (results) { self.destinations = results; self.uploadImageDestinations = results; }; /** * Load priorities that response from api. * @param results the list of Priorities. */ self.loadPriorities = function (results) { self.priorities = results; }; /** * Build ng table for Active Online Images */ self.getActiveOnlineImages = function () { self.getActiveOnlineImagesHasCalled = true; self.isWaitingForResponse = true; self.currentProductId = self.productMaster.prodId; productSellingUnitsApi.getActiveOnlineImages({ upcs: self.upcs }, self.loadActiveOnlineImageTable, self.handleError); }; /** * Load active online image that response from api. * @param results the list of active online image info. */ self.loadActiveOnlineImageTable = function (results) { self.activeOnlineImages = results.data; self.originalActiveImages = angular.copy(self.activeOnlineImages); self.buildActiveOnlineImageTable(); self.loadActiveOnlineImages(); //Count images follow image status in active online. for(var index in results.data){ if(results.data[index].imageStatus.id === APPROVED_STATUS_CODE){ self.totalApprovedImages++; } if(results.data[index].imageStatus.id === STATUS_REJECTED || results.data[index].imageStatus.id === STATUS_FOR_REVIEW){ self.totalNeedingApprovingImages++; } } var upcs = []; upcs.push(self.sellingUnit.upc); var params = { upcs : upcs }; //Get submitted images of upc with all image status. productSellingUnitsApi.getCountSubmittedImages(params, self.countImages, self.handleError); }; /** * Count images follow image status in submitted images. * @param results the list submitted image info. */ self.countImages = function (results) { self.totalApprovedImages += results.approved; self.totalNeedingApprovingImages += results.needApproved; self.totalImages = self.totalApprovedImages + self.totalNeedingApprovingImages; if(self.isNavigateToNewPage){ self.isNavigateToNewPage = false; self.buildSubmittedImageTable(self.nextPage); }else{ self.buildSubmittedImageTable(null); } }; /** * Build ng table for active online image. */ self.buildActiveOnlineImageTable = function () { self.activeOnlineImageTable = new ngTableParams({ page: 1, count: self.activeOnlineImages.length }, { counts: [], orderBy: 'imagePriorityCode', data: self.activeOnlineImages }); }; /** * Build ng table for Submitted Images * @param page the page index. if it is, then get default page. */ self.buildSubmittedImageTable = function (page) { self.isWaitingForResponse = true; self.firstSearch=true; self.submittedImageTable = new ngTableParams( { page: page == null ? self.PAGE : page, count: self.PAGE_SIZE }, { counts: [], /** * Called by ngTable to load data. * * @param $defer The object that will be waiting for data. * @param params The parameters from the table helping the function determine what data to get. */ getData: function ($defer, params) { self.isWaitingForResponse = true; // Save off these parameters as they are needed by the callback when data comes back from // the back-end. self.defer = $defer; self.dataResolvingParams = params; // If it is first time to search, then it search with count, otherwise it doesn't include count. if (self.firstSearch) { self.includeCount = true; self.firstSearch = false; } else { self.includeCount = false; } // Issue calls to the backend to get the data. if(self.isAllButtonClicked){ if(angular.equals(self.showAllDisplay , HIDE_ALL)){ self.isShowRejected = true; self.showRejectedDisplay = HIDE_REJECTED; self.getSubmittedImagePage(params.page() - 1); }else{ self.isShowRejected = false; self.showRejectedDisplay = SHOW_REJECTED; self.resetSubmittedImageToNullObject(); } }else if(self.isAllButtonClicked === false){ if(angular.equals(self.showRejectedDisplay , HIDE_REJECTED)) { if (_.pluck(_.filter(self.originalSubmittedImage, function(o){ return o.imageStatus.id === STATUS_FOR_REVIEW;})).length >0 || _.pluck(_.filter(self.originalSubmittedImage, function(o){ return o.imageStatus.id === APPROVED_STATUS_CODE;})).length >0 || (self.originalSubmittedImage.length > 0 && !angular.equals(self.showAllDisplay , SHOW_ALL))){ self.isShowAllImages = true; self.showAllDisplay = HIDE_ALL; self.getSubmittedImagePage(params.page() - 1); }else{ self.getRejectedImagePage(params.page() - 1); } }else{ if (_.pluck(_.filter(self.originalSubmittedImage, function(o){ return o.imageStatus.id === STATUS_FOR_REVIEW;})).length === 0 && _.pluck(_.filter(self.originalSubmittedImage, function(o){ return o.imageStatus.id === APPROVED_STATUS_CODE;})).length === 0 && !angular.equals(self.showAllDisplay , HIDE_ALL)){ self.isShowAllImages = false; self.showAllDisplay = SHOW_ALL; self.resetSubmittedImageToNullObject(); }else{ self.isShowRejected = false; self.showRejectedDisplay = SHOW_REJECTED; self.getSubmittedImagePage(params.page() - 1); } } }else{ self.getSubmittedImagePage(params.page() - 1); } } } ); }; /** * This function to reset submittedImages to null object. */ self.resetSubmittedImageToNullObject = function (){ self.isWaitingForResponse = false; self.dataResolvingParams.data = []; self.submittedImages = []; self.originalSubmittedImage = angular.copy(self.submittedImages); self.defer.resolve(self.submittedImages); }; /** * Get the rejected image by page. * @param page the page index. */ self.getRejectedImagePage = function (page) { var upcs = []; upcs.push(self.sellingUnit.upc); var params = { upcs : upcs, page: page, pageSize: self.PAGE_SIZE, includeCounts: self.includeCount }; productSellingUnitsApi.getRejectedImages(params, self.loadSubmittedImageTable, self.handleError); }; /** * Get the submitted image by page. * @param page the page index. */ self.getSubmittedImagePage = function (page) { var upcs = []; upcs.push(self.sellingUnit.upc); var params = { upcs : upcs, isShowRejected: self.isShowRejected, page: page, pageSize: self.PAGE_SIZE, includeCounts: self.includeCount }; productSellingUnitsApi.getSubmittedImages(params, self.loadSubmittedImageTable, self.handleError); }; /** * Load submitted image into the table. * @param results the list of submitted image. */ self.loadSubmittedImageTable = function (results) { self.error = null; if (results.data.complete) { self.totalRecordCount = results.data.recordCount; self.totalPages = results.data.pageCount; self.dataResolvingParams.total(self.totalRecordCount); } if (results.data.data.length === 0) { self.dataResolvingParams.data = []; self.submittedImages = []; self.originalSubmittedImage = angular.copy(self.submittedImages); self.defer.resolve(self.submittedImages); self.error = self.NO_RECORDS_FOUND; } else { self.submittedImages = results.data.data; self.originalSubmittedImage = angular.copy(self.submittedImages); self.defer.resolve(self.submittedImages); angular.forEach(self.submittedImages, function (image) { image.selected = false; image.useImageData = false; image.imagePriorityCode = self.trimData(image.imagePriorityCode); image.imageStatusCode = self.trimData(image.imageStatusCode); }); self.loadSubmittedImages(); } if(self.totalPages>1){ self.marginTop = "20px"; }else { self.marginTop = "0px"; } self.isWaitingForResponse = false; }; /** * Switch the image between active online and submitted. * If it is submitted then move it to online and else move it to submitted. * @param image the image info. */ self.switchImageBetweenActiveOnlineAndSubmitted = function (image) { if (image.activeOnline) { self.submittedImages.splice(self.submittedImages.indexOf(image), 1); self.activeOnlineImages.push(angular.copy(image)); } else { self.activeOnlineImages.splice(self.activeOnlineImages.indexOf(image), 1); self.submittedImages.push(angular.copy(image)); } self.buildActiveOnlineImageTable(); }; /** * Get all active online image data from api. */ self.loadActiveOnlineImages = function () { angular.forEach(self.activeOnlineImages, function (image) { if (image !== undefined && image !== null) { self.getSingleImage(image); } }) }; /** * Get all active online image data from api. */ self.loadSubmittedImages = function () { angular.forEach(self.submittedImages, function (image) { if (image !== undefined && image !== null) { self.getSingleImage(image); } }) }; /** * This method makes a call to get all of the images for the image info individually * @param image the image. */ self.getSingleImage = function (image) { productSellingUnitsApi.getImages(image.imageURI, function (results) { var imageData = EMPTY; var useImageData = false; if (image.imageFormat.indexOf("TIF") != -1) { image.useImageData = false; } else if (results.data.length !== 0) { imageData = "data:image/jpg;base64," + results.data; useImageData = true; } else { useImageData = false; } image.imagePriorityCode = self.trimData(image.imagePriorityCode); image.imageStatusCode = self.trimData(image.imageStatusCode); image.image = imageData; image.useImageData = useImageData; for (var originalIndex = 0; originalIndex < self.originalActiveImages.length; originalIndex++) { if (image.key.id === self.originalActiveImages[originalIndex].key.id && image.key.sequenceNumber === self.originalActiveImages[originalIndex].key.sequenceNumber) { self.originalActiveImages[originalIndex] = angular.copy(image); break; } } for (originalIndex = 0; originalIndex < self.originalSubmittedImage.length; originalIndex++) { if (image.key.id === self.originalSubmittedImage[originalIndex].key.id && image.key.sequenceNumber === self.originalSubmittedImage[originalIndex].key.sequenceNumber) { self.originalSubmittedImage[originalIndex] = angular.copy(image); break; } } }); }; /** * Handle the error from the back end. * @param error the error. */ self.handleError = function (error) { self.setDisplayNameForShowOrHideRejectedButton(); self.setDisplayNameForShowOrHideAllButton(); self.isWaitingForResponse = false; if (error && error.data) { self.isWaitingForResponse = false; if (error.data.message) { self.setError(error.data.message); } else { self.setError(error.data.error); } } else { self.setError("An unknown error occurred."); } }; /** * Sets the controller's error message. * @param error The error message. */ self.setError = function (error) { self.error = error; }; /** * Sends the user to the custom hierarchy for that image * @param entityId */ self.navigateToCustomHierarchy = function (entityId) { imageInfoService.setEntityId(entityId); customHierarchyService.setEntityId(entityId); $state.go(appConstants.CUSTOM_HIERARCHY_ADMIN); }; /** * This method converts the list of destinations into a more readable form * @param destinations the list of destinations * @returns {string} a human readable list of destinations */ self.getDestinations = function (destinations) { var string = EMPTY; if (destinations.length > 0) { string = destinations[0].description; for (var index = 1; index < destinations.length; index++) { string += ", " + destinations[index].description; } } return string; }; /** * This method checks to make sure all required information is present to create a new image record * @returns {boolean} true it is valid or false it's invalid. */ self.isValidImageForUpload = function () { var invalidUpload = false; var invalidComponents = IMAGE_UPLOAD_FAIL_TO_LAUNCH; if (angular.equals(self.uploadImageCategory, EMPTY)) { invalidComponents = invalidComponents + MISSING_IMAGE_CATEGORY; invalidUpload = true; } if (angular.equals(self.uploadImageSource, EMPTY)) { if (invalidUpload) { invalidComponents = invalidComponents + "\n "; } invalidComponents = invalidComponents + MISSING_IMAGE_SOURCE; invalidUpload = true; } if (self.uploadImageDestinations.length === 0) { if (invalidUpload) { invalidComponents = invalidComponents + "\n "; } invalidComponents = invalidComponents + MISSING_DESTINATION_FOR_UPLOAD; invalidUpload = true; } if (self.invalidFileType) { if (invalidUpload) { invalidComponents = invalidComponents + "\n "; } invalidComponents = invalidComponents + MISSING_OR_INVALID_FILE; invalidUpload = true; } if (invalidUpload) { alert(invalidComponents); return false; } return true; }; /** * After successfully uploading an image resets the fields */ self.resetUploadFields = function () { document.getElementById("uploadImageData").value = null; self.uploadImageCategory = EMPTY; self.uploadImageSource = EMPTY; self.uploadImageDestinations = self.destinations; self.uploadImageImage = EMPTY; }; /** * This method will check if the upload request is valid and then make a call to the api to upload the image * This method will also close the modal */ self.uploadImage = function () { self.error = null; self.success = null; if (self.isValidImageForUpload()) { $('.modal').modal('hide'); var uploadImage = { upc: self.sellingUnit.upc, imageCategoryCode: self.uploadImageCategory, imageSourceCode: self.uploadImageSource, destinationList: self.uploadImageDestinations, imageData: self.uploadImageImage, imageName: self.uploadImageName }; productSellingUnitsApi.uploadImage(uploadImage, self.uploadImageResult, self.handleError); self.isWaitingForResponse = true; } }; /** * On successful upload reset the view * @param results */ self.uploadImageResult = function (results) { self.resetCountImages(); self.success = 'Image "' + self.uploadImageName + '" is uploaded successfully and associated with the UPC "' + self.sellingUnit.upc + '"'; self.resetUploadFields(); self.getActiveOnlineImages(); }; /** * Initializes the modal and sets the onchange for the file input to check the file type */ self.initModal = function () { var uploadImageData = document.getElementById("uploadImageData"); var invalidSpan = document.getElementById("invalidSpan"); var imageTypeCode = EMPTY; self.invalidFileType = true; uploadImageData.addEventListener('change', function (e) { self.uploadImageName = EMPTY; var imageData = uploadImageData.files[0]; imageTypeCode = imageData.type.split('/').pop(); if (self.validFileTypes.includes(imageTypeCode.toLowerCase())) { invalidSpan.style.display = 'none'; self.uploadImageName = imageData.name; self.invalidFileType = false; var reader = new FileReader(); reader.onloadend = function () { self.uploadImageImage = reader.result.split(',').pop(); }; reader.readAsDataURL(imageData); } else { self.invalidFileType = true; invalidSpan.style.display = 'block'; alert(INVALID_FILE_UPLOAD); } }); }; /** * This method resets all of the image info data to its original value */ self.resetImageInfo = function () { self.selectedImages = []; self.error = null; self.success = null; self.invalidStatusString = ''; self.activeOnlineImages = angular.copy(self.originalActiveImages); self.submittedImages = angular.copy(self.originalSubmittedImage); self.buildActiveOnlineImageTable(); }; /** * This method will take determine the changes to be made then send the changes to the backend for updating */ self.saveImageInfo = function () { self.isWaitingForResponse = true; self.error = EMPTY; self.success = null; self.missingDestination = false; self.invalidStatus = false; var allImagesOrigin = self.originalActiveImages.concat(self.originalSubmittedImage); var allImages = self.activeOnlineImages.concat(self.submittedImages); var imageChanges = self.getChangedImageInfoList(allImages, allImagesOrigin); if (imageChanges.length !== 0) { if (self.missingDestination) { self.error = MISSING_DESTINATION_DOMAIN; self.isWaitingForResponse = false; if (self.isChangeShowRejected) { self.isChangeShowRejected = false; self.setDisplayNameForShowOrHideAllButton(); self.setDisplayNameForShowOrHideRejectedButton(); } } else if (self.invalidStatus || self.isActiveOnlineAndPrimaryNotExists(allImages) || !self.isValidImageInfo(allImages)) { self.error = self.invalidStatusString; self.isWaitingForResponse = false; if (self.isChangeShowRejected) { self.isChangeShowRejected = false; self.setDisplayNameForShowOrHideAllButton(); self.setDisplayNameForShowOrHideRejectedButton(); } } else { if (imageChanges.length > 0) { self.waitingForDataUpdates = true; productSellingUnitsApi.updateImageInfo({upcs: self.upcs}, imageChanges, self.saveImageInfoResult, self.handleError); } } } else { self.error = MESSAGE_NO_DATA_CHANGE; self.isWaitingForResponse = false; } }; /** * This method catches the success result for save image info and copy image info. * @param results the success result. */ self.saveImageInfoResult = function (results) { self.resetCountImages(); if (results.message !== null) { self.success = results.message; } self.getActiveOnlineImages(); }; /** * Check the primary priority on the list of active online images and submitted images that is not exists * then return true or if it is existing then return false. * @returns {boolean} true if it is not exists, otherwise return false. */ self.isActiveOnlineAndPrimaryNotExists = function (images) { var isExisting = false; var flagCheck = false; angular.forEach(images, function (image) { if (image.activeOnline && self.trimData(image.imagePriorityCode) === PRIMARY_PRIORITY) { isExisting = true; } }); if (!isExisting) { angular.forEach(images, function (image) { if (image.activeOnline) { if (self.trimData(image.imagePriorityCode) === PRIMARY_ALTERNATE) { self.invalidStatusString = IMG_ACTIVE_ONLINE_IN_ALTERNATE; flagCheck = true; } else if (self.trimData(image.imageCategoryCode) === CATEGORY_SWATCHES) { self.invalidStatusString = IMG_ACTIVE_ONLINE_IN_CATEGORY_SWATCH; flagCheck = true; } } }); } return flagCheck; }; /** * Validation images before save. * @param images * @returns {boolean} */ self.isValidImageInfo = function (images) { var flagCheck = true; var originalImages = self.originalActiveImages.concat(self.originalSubmittedImage); angular.forEach(images, function (image) { if (image.imageStatusCode === STATUS_FOR_REVIEW) { angular.forEach(originalImages, function (originalImage) { if (originalImage.key.sequenceNumber === image.key.sequenceNumber && self.trimData(originalImage.imageStatusCode) !== STATUS_FOR_REVIEW) { self.invalidStatusString = IMG_STATUS_CHANGE_TO_REVIEW; flagCheck = false; } }); } else if (self.trimData(image.imageStatusCode) === STATUS_REJECTED && self.trimData(image.imagePriorityCode) === PRIMARY_PRIORITY) { self.invalidStatusString = IMG_PRIMARY_REJECTED; flagCheck = false; } if (image.activeOnline) { if (self.trimData(image.imageStatusCode) === STATUS_FOR_REVIEW) { self.invalidStatusString = IMG_PRIMARY_FOR_REVIEW_ACTONLINE; flagCheck = false; } if (self.trimData(image.imageStatusCode) === STATUS_REJECTED) { self.invalidStatusString = IMG_STATUS_REJECTED; flagCheck = false; } if (self.trimData(image.imagePriorityCode) === PRIMARY_NOT_APPLICABLE && self.trimData(image.imageCategoryCode) !== CATEGORY_SWATCHES) { self.invalidStatusString = IMG_ACTIVE_ONLINE_IS_NONE_CATEGORY_OR_PRIMARY_ALTERNATE; flagCheck = false; } } }); return flagCheck; }; /** * Get the list of changed image info current image info list. * @param currentImageInfoList the list of current image info. * @param originalImageInfoList the of original image info. * @returns {Array} the list of changed image info. */ self.getChangedImageInfoList = function (currentImageInfoList, originalImageInfoList) { self.destinationUpdates = []; var changedImageInfoList = []; var isChanged = false; for (var index = 0; index < currentImageInfoList.length; index++) { var currentImage = { key: { id: currentImageInfoList[index].key.id, sequenceNumber: currentImageInfoList[index].key.sequenceNumber, }, productScanImageBannerList: [] }; isChanged = false; for (var originalIndex = 0; originalIndex < originalImageInfoList.length; originalIndex++) { if (currentImageInfoList[index].key.id === originalImageInfoList[originalIndex].key.id && currentImageInfoList[index].key.sequenceNumber === originalImageInfoList[originalIndex].key.sequenceNumber) { if (!angular.equals(self.trimData(currentImageInfoList[index].altTag), self.trimData(originalImageInfoList[originalIndex].altTag))) { currentImage.altTag = currentImageInfoList[index].altTag; isChanged = true; } if (!angular.equals(self.trimData(currentImageInfoList[index].imageCategoryCode), self.trimData(originalImageInfoList[originalIndex].imageCategoryCode))) { currentImage.imageCategoryCode = currentImageInfoList[index].imageCategoryCode; isChanged = true; } if (!angular.equals(self.trimData(currentImageInfoList[index].imagePriorityCode), self.trimData(originalImageInfoList[originalIndex].imagePriorityCode))) { currentImage.imagePriorityCode = currentImageInfoList[index].imagePriorityCode; isChanged = true; } if (!angular.equals(currentImageInfoList[index].destinations, originalImageInfoList[originalIndex].destinations)) { currentImage.destinationChanges = self.getChangedDestination(currentImageInfoList[index], originalImageInfoList[originalIndex]) isChanged = true; } if (!angular.equals(currentImageInfoList[index].activeOnline, originalImageInfoList[originalIndex].activeOnline)) { currentImage.activeOnline = currentImageInfoList[index].activeOnline; isChanged = true; } if (!angular.equals(self.trimData(currentImageInfoList[index].imageStatusCode), self.trimData(originalImageInfoList[originalIndex].imageStatusCode))) { currentImage.imageStatusCode = currentImageInfoList[index].imageStatusCode; isChanged = true; } if (isChanged) { changedImageInfoList.push(currentImage); if (!angular.equals(currentImageInfoList[index].imageStatusCode.trim(), STATUS_REJECTED) && currentImageInfoList[index].destinations.length === 0) { self.missingDestination = true; } } break; } } } return changedImageInfoList; }; /** * Trim data string, if data string is null or undefined then return empty. * @param dataString the data string needs to trim. * @returns {string} the data string was trimmed. */ self.trimData = function (dataString) { return (dataString == null || dataString == undefined) ? '' : dataString.trim(); } /** * Gets changed destination of image info. * @param image the image info * @param originalImageInfo the original image info. * @returns {{upc: *, sequenceNumber: (Document.sequenceNumber|*), activeSwitch: (string|boolean), destinationsAdded: Array, destinationsRemoved: Array}} */ self.getChangedDestination = function (imageInfo, originalImageInfo) { var arrayIndex; var changedDestination = { upc: imageInfo.key.id, sequenceNumber: imageInfo.key.sequenceNumber, activeSwitch: imageInfo.activeSwitch, destinationsAdded: [], destinationsRemoved: [] }; angular.forEach(imageInfo.destinations, function (destination) { var originalDestinations = originalImageInfo.destinations; var foundBanner = false; if (originalDestinations.length > 0) { for (arrayIndex = 0; arrayIndex < originalDestinations.length; arrayIndex++) { if (angular.equals(destination.id, originalDestinations[arrayIndex].id)) { foundBanner = true; break; } } } if (!foundBanner) { changedDestination.destinationsAdded.push(destination.id); } }); angular.forEach(originalImageInfo.destinations, function (destination) { var newDestinations = imageInfo.destinations; var foundBanner = false; if (newDestinations.length > 0) { for (arrayIndex = 0; arrayIndex < newDestinations.length; arrayIndex++) { if (angular.equals(destination.id, newDestinations[arrayIndex].id)) { foundBanner = true; break; } } } if (!foundBanner) { changedDestination.destinationsRemoved.push(destination.id) } }); self.destinationUpdates.push(changedDestination); return changedDestination; }; /** * Updates the cropper to a new image * @param imageData */ self.setImageToEdit = function (imageData) { self.imageToEditData = imageData; var modal = document.getElementById("editImageModalDialog"); modal.style.width = EMPTY + 1030 + "px"; self.cropper.replace(imageData.image); }; /** * Show full image for view. * @param image */ self.showFullImage = function (image) { self.imageBytes = image.image; self.imageFormat = self.trimData(image.imageFormat); if (self.imageBytes !== '') { $('#imagePopup').modal({backdrop: 'static', keyboard: true}); } }; /** * Spin the editing image * @param degrees */ self.spinCropper = function (degrees) { self.currentAngle += degrees; self.cropper.rotateTo(self.currentAngle); }; /** * Set the movement mode to crop(create new crop box or move it) on the editing image */ self.cropMode = function () { self.cropper.setDragMode("crop"); }; /** * Set the movement mode to move (move image or crop box) on the editing image */ self.moveMode = function () { self.cropper.setDragMode("move"); }; /** * Zoom into the editing image */ self.zoomIn = function () { self.cropper.zoom(0.1); }; /** * Zoom out of editing image */ self.zoomOut = function () { self.cropper.zoom(-0.1); }; /** * Flip image on its X axis */ self.flipImageX = function () { self.scaleX = self.scaleX * -1; self.cropper.scale(self.scaleX, self.scaleY); }; /** * Flip image on its Y axis */ self.flipImageY = function () { self.scaleY = self.scaleY * -1; self.cropper.scale(self.scaleX, self.scaleY); }; /** * preview the proposed changes to the image */ self.previewCroppedImage = function () { self.editedImage = self.cropper.getCroppedCanvas().toDataURL(); var preview = document.getElementById("previewImage"); var previewModal = document.getElementById("previewImageModalDialog"); previewModal.style.width = "1000px"; preview.src = self.editedImage; }; /** *Save new cropped image and send it to the backend to update the database */ self.saveImage = function () { $('.modal').modal('hide'); self.uploadImageName = EMPTY + self.imageToEditData.key.id + "." + self.imageToEditData.imageType.imageFormat + EMPTY; var uploadImage = { upc: self.imageToEditData.key.id, imageCategoryCode: self.imageToEditData.imageCategoryCode, imageSourceCode: self.imageToEditData.imageSource.id, imageData: self.editedImage.split(',').pop(), imageName: self.uploadImageName }; productSellingUnitsApi.uploadImage(uploadImage, self.uploadImageResult, self.handleError); self.isWaitingForResponse = true; }; /** * This method will check the category of an image and if it is set to 'Swatches' it will automatically * set the priority of the image to Not Applicable * @param image */ self.checkCategory = function (image) { if (angular.equals(image.imageCategoryCode, "SWAT")) { image.imagePriorityCode = 'NA' } }; /** * This method will update the selectedImages list * @param image the image to be added or removed * @param selected whether to add(true) or remove (false) the image */ self.updateSelectedImage = function (image, selected) { if (selected) { self.selectedImages.push(angular.copy(image)); } else { var index = self.selectedImages.length; while (index--) { if (angular.equals(image.id, self.selectedImages[index].id)) { if (angular.equals(image.sequenceNumber, self.selectedImages[index].sequenceNumber)) { self.selectedImages.splice(index, 1); } } } } }; /** * This method will add or remove all of the images from the selected images list */ self.selectAll = function () { self.selectedImages = []; angular.forEach(self.activeOnlineImages, function (image) { image.selected = self.selectAllImages; if (self.selectAllImages) { self.updateSelectedImage(image, image.selected); } }); angular.forEach(self.submittedImages, function (image) { image.selected = self.selectAllImages; if (self.selectAllImages) { self.updateSelectedImage(image, image.selected); } }); }; /** * This method is called to initialize the copy to hierarchy modal */ self.copyToHierarchyModalInit = function () { if (permissionsService.getPermissions('CP_IMG_01', 'EDIT')) { var params = { prodId: self.productMaster.prodId, }; productSellingUnitsApi.copyToHierarchyPath(params, function (results) { self.hierarchyPath = results.data; if (self.hierarchyPath.length > 0) { self.hierarchyString = "Nominate image for the hierarchy " + self.hierarchyPath[self.hierarchyPath.length - 1].displayText; for (var index = self.hierarchyPath.length - 2; index >= 0; index--) { self.hierarchyString = self.hierarchyString + "→" + self.hierarchyPath[index].displayText; } self.hierarchyString = self.hierarchyString + " at the level:"; self.isDisableHierarchy = false; } else { self.isDisableHierarchy = true; } }, self.handleError); } }; /** * Check for disable or enable Copy to Hierarchy button. * @returns {boolean} */ self.isDisableCopyToHierarchyButton = function () { return (!self.selectedImages.length > 0); }; /** * This method will validate that all of the images to be copied to the customer hierarchy are valid * @returns {boolean} true it is valid or of invalid. */ self.isValidHierarchy = function () { if (self.selectedImages.length === 0) { return false; } var isValid = true; angular.forEach(self.selectedImages, function (hierarchyCandidate) { if (!angular.equals(hierarchyCandidate.imageStatusCode, APPROVED_STATUS_CODE)) { isValid = false; } }); return isValid; }; /** * This method will copy an image's information to the customer hierarchy */ self.copyToHierarchy = function () { $('.modal').modal('hide'); var path; if (angular.equals(self.hierarchyLevels, "single")) { path = [ self.hierarchyPath[0] ]; } else { path = self.hierarchyPath; } angular.forEach(self.selectedImages, function (image) { image.imageData = null; image.image = null; }); var copyToHierarchyRequest = { imageInfo: self.selectedImages, genericEntities: path, upcs: self.upcs }; self.isWaitingForResponse = true; productSellingUnitsApi.copyToHierarchy(copyToHierarchyRequest, self.saveImageInfoResult, self.handleError); self.selectedImages = []; angular.forEach(self.activeOnlineImages, function (images) { images.selected = false; }); angular.forEach(self.submittedImages, function (images) { images.selected = false; }); }; /** * This method is used to determine what image to display * @param imageInfo * @returns {boolean} true if imageInfo is still waiting for image from api false if the api has returned image info */ self.isImageUndefined = function (imageInfo) { return typeof imageInfo['image'] === 'undefined'; }; /** * handle when click on return to list button */ self.returnToList = function () { $rootScope.$broadcast('returnToListEvent'); }; /** * Download current image. */ self.downloadImage = function (imageBytes, imageFormat) { if (imageBytes !== '') { downloadImageService.download(imageBytes, imageFormat); } }; /** * This method is used to determine if there is a change to save * @returns {boolean} */ self.detectChange = function () { var allOriginalImages = self.originalActiveImages.concat(self.originalSubmittedImage); var allCurrentImages = self.activeOnlineImages.concat(self.submittedImages); var imageChanges = self.getChangedImageInfoList(allCurrentImages, allOriginalImages); if (imageChanges.length > 0) { $rootScope.contentChangedFlag = true; return true; } $rootScope.contentChangedFlag = false; return false; }; /** * This method will be called when user click on Show/Hide rejected images. * If there is any change on image info then a confirm popup will display. */ self.onShowOrHideRejectedImage = function () { self.isAllButtonClicked = false; if (self.detectChange()) { self.isShowingNavigationConfirmPopup = false; $('#confirmationShowHideReject').modal({backdrop: 'static', keyboard: true}); } else { self.setDisplayNameForShowOrHideRejectedButton(); self.buildSubmittedImageTable(null); } }; /** * This method will be called when user click on Show/Hide all images. * If there is any change on image info then a confirm popup will display. */ self.onShowOrHideALlImage = function () { self.isAllButtonClicked = true; if (self.detectChange()) { self.isShowingNavigationConfirmPopup = false; $('#confirmationShowHideReject').modal({backdrop: 'static', keyboard: true}); } else { self.setDisplayNameForShowOrHideAllButton(); self.buildSubmittedImageTable(null); } }; /** * This method will call when user click on Yes button of save confirm popup. * When switch between show rejected image and hide rejected image. If there is any change on it, * then a confirm popup ask save changed data with Yes/No buttons. */ self.onYesConfirmedButtonClicked = function () { if(self.isShowingNavigationConfirmPopup){ // Case 1: On navigation confirm popup. $('#confirmationShowHideReject').modal("hide"); self.isNavigateToNewPage = true; }else{ // Case 2: On Show or hide rejected confirm popup. self.setDisplayNameForShowOrHideAllButton(); self.setDisplayNameForShowOrHideRejectedButton(); self.isChangeShowRejected = true; } self.saveImageInfo(); }; /** * This method with remove all messages. */ self.resetAllMessage = function(){ self.error = null; self.success = null; self.invalidStatusString = ''; }; /** * This method will call when user click on No button of save confirm popup. * When switch between show rejected image and hide rejected image. If there is any change on it, * then a confirm popup ask save changed data with Yes/No buttons. */ self.onNoConfirmedButtonClicked = function () { self.resetAllMessage(); self.resetCountImages(); if(self.isShowingNavigationConfirmPopup){ // Case 1: On navigation confirm popup. $('#confirmationShowHideReject').modal("hide"); self.isNavigateToNewPage = true; self.getActiveOnlineImages(); }else{ // Case 2: On Show or hide rejected confirm popup. self.setDisplayNameForShowOrHideAllButton(); self.setDisplayNameForShowOrHideRejectedButton(); self.buildSubmittedImageTable(null); self.getActiveOnlineImages(); } }; /** * Set display name for button show/hide rejected button. */ self.setDisplayNameForShowOrHideRejectedButton = function () { self.isShowRejected = !self.isShowRejected; if (self.isShowRejected) { self.showRejectedDisplay = HIDE_REJECTED; } else { self.showRejectedDisplay = SHOW_REJECTED; } }; /** * Set display name for button show/hide all button. */ self.setDisplayNameForShowOrHideAllButton = function () { self.isShowAllImages = !self.isShowAllImages; if (self.isShowAllImages) { self.showAllDisplay = HIDE_ALL; } else { self.showAllDisplay = SHOW_ALL; } }; /** * Handle event navigating on UI */ $scope.selectPage = function (params, page) { if (self.submittedImageTable.page() == page) { return false; } if (self.detectChange()) { self.nextPage = page; self.isShowingNavigationConfirmPopup = true; $('#confirmationShowHideReject').modal({backdrop: 'static', keyboard: true}); } else { self.success = null; self.error = null; self.submittedImageTable.page(page); } }; } } )();
import React, { useState } from "react"; import { useHistory } from "react-router"; import axios from "axios"; import MarkEmailReadIcon from '@mui/icons-material/MarkEmailRead'; import SecurityIcon from '@mui/icons-material/Security'; import AddReactionTwoToneIcon from '@mui/icons-material/AddReactionTwoTone'; import CheckCircleIcon from '@mui/icons-material/CheckCircle'; import { Nav } from "../../Components/Navbar/Nav"; import ErrorSnackbar from "../../Alert/Error"; import CustomizedSnackbars from "../../Alert/SuccessSnackbar"; import useForm from "../../hooks/Validationhook"; import validate from "../../hooks/validate"; const SignIn = (props) => { const [open, setOpen] = React.useState(false); const [notification, setnotification] = React.useState(false); const { inputs, handleInputChange } = useForm({}); const [errors, setErrors] = useState({}); const history = useHistory(); const handleClose = (reason, event) => { if (reason === "clickaway") { return; } setOpen(false); setnotification(false); }; const handleSubmit = (event) => { event.preventDefault(); const validationErrors = validate(inputs); const noErrors = Object.keys(validationErrors).length === 0; console.log("error", noErrors); setErrors(validationErrors); try { if (noErrors) { axios .post("http://localhost:3000/api/login", { ...inputs }) .then((res) => { const {token, role} = res.data; localStorage.setItem('token', JSON.stringify({token, role})); if(role === 'admin') { history.push('/admin/dashboard') return setOpen(true); } history.push('/dashboard') ; setOpen(true) }); } setnotification(true) } catch (error) { console.log("Problem submitting New Post", errors); setnotification(true) } console.log(inputs); }; const head = { borderRadius: "10px", background: "linear-gradient(#444 , #999 , #333)", width: "100%", height: "calc(100vh - 58px)", display: "flex", flexdirection: "column", alignitems: "center", justifyContent: "center" } const formhead = { display: "flex", flexDirection: 'column', alignItems: "center", marginRight: "calc(var(--bs-gutter-x) * 0.5)", margintop: "30px", width: "50%" } return ( <> <Nav/> <div className="form" style={head} onSubmit={(e) => { handleSubmit(e); }} > <form className="row g-3 p-4" style={formhead}> <CustomizedSnackbars handlerclose={handleClose} open={open} setOpen={setOpen} /> <ErrorSnackbar handlerclose={handleClose} notification={notification} setnotification={setnotification} /> <hr /> <h1 className="text-center"> <AddReactionTwoToneIcon className="text-center icons mx-3" /> Login - Form </h1> <hr /> <div className="col-5"> <label htmlFor="inputAddress" className="form-label"> <MarkEmailReadIcon /> Email: </label> <input className="form-control" id="inputAddress" placeholder="Enter Your Email Address" type="email" name="email" required={true} value={inputs.email} onChange={handleInputChange} /> </div> <div className="col-5"> <label htmlFor="inputZip" className="form-label"> <SecurityIcon /> Password </label> <input placeholder="Enter Password " className="form-control" id="inputCity" type="password" name="password" required={true} value={inputs.password} onChange={handleInputChange} /> </div> <div className=" my-5 text-center"> <button className="btn btn-info"><CheckCircleIcon /> Sign In</button> </div> </form> </div> </> ); }; export default SignIn;
import Gulp from 'gulp'; import istanbul from 'gulp-istanbul'; import mocha from 'gulp-mocha'; import {instrumenterConfig} from '@kpdecker/linoleum/src/cover'; import plumber from '@kpdecker/linoleum/src/plumber'; import {SOURCE_FILES, COVERAGE_TARGET, MOCHA_TIMEOUT, testFiles} from '@kpdecker/linoleum/config'; function coverSourceFiles() { return Gulp.src(SOURCE_FILES) .pipe(plumber()) .pipe(istanbul(instrumenterConfig())); } // This task hierarchy is to hack around // https://github.com/sindresorhus/gulp-mocha/issues/112 Gulp.task('cover:mocha:pre', function() { return coverSourceFiles() .pipe(istanbul.hookRequire({extensions: ['.js', '.jsx']})); }); Gulp.task('cover:mocha:run', ['cover:mocha:pre'], function() { return Gulp.src(testFiles()) .pipe(plumber()) .pipe(mocha({timeout: MOCHA_TIMEOUT || 2000})); }); Gulp.task('cover:mocha', ['cover:mocha:run'], function() { return Gulp.src(testFiles()) .pipe(istanbul.writeReports({ dir: COVERAGE_TARGET, reporters: [ 'json' ], reportOpts: { dir: `${COVERAGE_TARGET}/mocha` } })); });
// ROOMS : Let user create rooms // SOCIALIZING : var app = { //this function makes a new chat application for us init : function(){ //the new app will need to wait until the rest of the page is loaded $(document).ready(function() { // first thing: see previous messages & refresh every 3 seconds setInterval(app.fetch,3000); //this powers the event listener for the text submission app.handleSubmit(); //this listener enables send to be clicked $('#send').on('click', function(){ var obj = { username: String(window.location.search.slice(10)), text: $('#message').val(), roomname: $('#roomoptions').className }; console.log(obj); // console.log(sms); app.send(obj); }); //this listener enables clearMessages to be clicked $('#clear').on('click', function(){ app.clearMessages(); }); app.addRoom(); }); }, send : function(message){ $.ajax({ //Reformat this type: "POST", url: "https://api.parse.com/1/classes/chatterbox", //data needs to include message text, username, date, and roomname data: JSON.stringify(message), contentType: 'application/json', success: function (data) { console.log(data); console.log('chatterbox: Message sent'); }, error: function (data) { // See: https://developer.mozilla.org/en-US/docs/Web/API/console.error console.error('chatterbox: Failed to send message'); } }) }, //This function retrieves and parses the data from our server //Some of the data is malicious, so we have a regular expression check in place to remove scripts. fetch : function(){ $.ajax({ type: "GET", url: "https://api.parse.com/1/classes/chatterbox", success: function(data){ // when obtaining the data, run each to process each data point. _.each(data.results, function(value){ //if (value.roomname === ) if (value.username === undefined || value.username === "" || value.username === null){ value.username = 'anonymous'; } value.text = (app.checkUp(value.text)) ? "Don't even try to hack us" : value.text value.username = (app.checkUp(value.username)) ? "Badguy" : value.username; //add each cleaned piece of data to the chat client. var usr = value.username; $("#chats").append('<label class='+ usr +' onclick="app.addFriend.call(this)">'+usr.toUpperCase() +'</label>'); $("#chats").append("<p>"+ value.text+"</p>"); }) } }) console.log('I AM FETCHING !'); }, //this function will clear messages clearMessages : function(){ $('#chats').empty(); }, addMessage : function(message){ var obj = { username: String(window.location.search.slice(10)+":"), text: message, roomname:"s" }; //We need to reformat the addMessage to collection username, message, and roomname. //Currently, it only collects a message. //We have access to the username from the String(window.location.search.slice(10)) //We need to build out the roomname variable. $("#localinfo").append("<label>"+obj.username.toUpperCase()+"</label>"+"<p>"+ obj.text+"</p>"); }, addRoom : function(){ $('#newroom').on('click',function(){ var roomInputName = $("#roomSelect").val(); if (roomInputName === "") { alert('You cannot add an empty room name'); } else { $("#roomoptions").append('<option class="'+ roomInputName +'">'+roomInputName +'</option>'); } }); }, addFriend : function(string){ app.myFriendList[this.className] = true; var tryIt = "$('."+ this.className+"')"; var evalTryIt = eval(tryIt).css("color","red"); //tryIt.style.color = "red"; console.log(evalTryIt); // .style.color = "red"; // console.log(app.myFriendList); }, handleSubmit : function(){ var btn = $("#send") btn.on('click',function(){ var msm = $('#message').val(); app.addMessage(msm) //console.log(msm); }) }, checkUp : function(text) { if (text === undefined || text === null) { return false; } return text.match(/[-[\]{}\$()*+;,\\^$|#\s]/g, "\\$&"); } }; app.init(); app.server = "https://api.parse.com/1/classes/chatterbox"; app.myFriendList = {};
import { combineReducers, createStore, compose, applyMiddleware } from 'redux'; import {createLogger} from 'redux-logger'; import photos from './containers/Photos/reducer'; var finalCreateStore = compose( applyMiddleware( createLogger({ collapsed: true }) ), !!window.devToolsExtension ? window.devToolsExtension() : f => f )(createStore); var store = finalCreateStore(combineReducers({ photos })); export default store;
import React from 'react' import styles from './styles.module.scss' export const GUITAR = 'guitar' export const PIANO = 'piano' export default ({ type, open, layers }) => ( <instrument className={ [styles[type], open ? styles.open : ''].join(' ') }> { layers.map((strings, key) => ( <layer className={ styles.layer } key={ key }> { strings.map((boxes, key) => ( <string className={ styles.string } key={ key }> { boxes.map(({ clips = [null], style = {} } = {}, key) => ( <boxes className={ styles.boxes } key={ key }> { clips.map((clipPath, key) => ( <box key ={ key } className={ styles.box } style ={{ clipPath, ...style }} /> )) } </boxes> )) } </string> )) } </layer> )) } </instrument> )
module.exports = require('./src'); /** * @readme-quick-run * * ## test tar=js r_c=KabaneryFlow env=browser * * let {mount} = require('kabanery'); * let {m, RawInput} = KabaneryFlow; * * mount(m('div', { * value: { * name: 'abc' * }, * * onchange: (v) => { * console.log(v); // {name: 'new value'} * } * }, (bindValue) => [ * RawInput(bindValue('name', { * id: 'test' * })) * ]), document.body); * * console.log(document.getElementById('test').value); */
var RecipeTrackerServices = angular.module('recipeservices', ['ngResource']); RecipeTrackerServices.factory('Recipe', function($resource){ return $resource('/api/recipes/:id'); }) RecipeTrackerServices.factory('Week', function($resource){ return $resource('/api/week/:id', { id: '@_id' }, { update: { method: 'PUT' // this method issues a PUT request }, search:{ method: 'GET', id: '@_id' } }); });
function importModels () { ds.Model.all().remove(); // delete all existing records var lines = loadText(ds.getModelFolder().path + "Imports/models_table_export_data.txt").split("\n"); lines.splice(0,1) // remove the header lines.forEach( function(oneLine) { var columns = oneLine.split("\t"); var theModel = ds.Model(columns[0]); if (theModel == null) { theModel = new ds.Model( { ID : columns[0], Manufacturer : columns[1], Model : columns[1], CC : columns[2] }); theModel.save(); } else { theModel.ID = columns[0]; theModel.Manufacturer = columns[1]; theModel.Model = columns[1]; theModel.CC = columns[3]; theModel.save(); } }) newSequenceNo = ds.Model.max("ID") + 1; ds.Model.setAutoSequenceNumber(newSequenceNo); } importModels();
import React, {useEffect, useState} from 'react' import {useDispatch, useSelector} from 'react-redux' import {fetchDetails} from '../actions/venueActions' import Map from './Map' import {Link} from 'react-router-dom' import '../App.css'; //font awesome import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faHome } from '@fortawesome/free-solid-svg-icons' export default function VenueDetails(props) { //font awesome icon const home = <FontAwesomeIcon icon={faHome} /> console.log("details-props", props.history.location.state.icon) // console.log("details", props.history.location.state.venue.id) const id = props.history.location.state.venue.id const dispatch = useDispatch() const state = useSelector(state => state) const [venueDetails, setVenueDetails] = useState(state.details) const {lat, lng} = useSelector(state => state.details.location) useEffect(()=>{ dispatch(fetchDetails(id)) },[]) useEffect(()=>{ setVenueDetails(state.details) },[state.details]) useEffect(()=>{ console.log("deets", venueDetails) // console.log(venueDetails.location.crossStreet) },[venueDetails]) return ( <div className="details-container"> <Link className="home-icon" to="/"> {home} </Link> {venueDetails.bestPhoto && <img className="hero" src={venueDetails.bestPhoto.prefix + '900x700' + venueDetails.bestPhoto.suffix}/>} <div className="details-info"> <h3>{venueDetails.name}</h3> <a className="social" href={venueDetails.url}>{venueDetails.url}</a><br/> {venueDetails.name && <> {venueDetails.location.formattedAddress[0]} {venueDetails.location.crossStreet}</>} {venueDetails.contact && <p>{venueDetails.contact.formattedPhone}</p>} </div> <div className="map-container"> <Map lat={lat} lng={lng} icon={props.history.location.state.icon} /> </div> </div> ) }
import React, { Component } from 'react'; import { Modal, ModalHeader, ModalBody, ListGroup, ListGroupItem } from 'reactstrap'; const PlaylistSelect = ({ playlists, onPlaylistSelect, closePlaylistSelect, statePlaylistSelect }) => { if (!statePlaylistSelect) return <></> return ( <div className="modal is-active"> <div className="modal-background" onClick={closePlaylistSelect}></div> <div className="modal-close" onClick={closePlaylistSelect}></div> <div className="modal-content"> <h3>Select a Playlist</h3> <ul className="list"> <li className='list-item select' onClick={() => onPlaylistSelect('CREATE_NEW')} key='new'> <img className='playlist-img' src={require('../icons/add-playlist.png')} alt='playlist cover' /> <p>Create new playlist</p> </li> {playlists.map(p => <li className='list-item select' onClick={() => onPlaylistSelect(p.id, p.name)} key={p.id}> <img className='playlist-img' src={p.images && p.images.length === 3 ? p.images[2].url : require('../icons/no-cover.png')} alt='playlist cover' /> <p>{p.name}</p> </li> )} </ul> </div> </div> ); } export default PlaylistSelect;
'use strict'; /** * @ngdoc service * @name laoshiListApp.subjects * @description * # subjects * Constant in the laoshiListApp. */ // change to a variable angular.module('laoshiListApp') .constant('subjects', [ 'Algebra', 'AP Chemistry', 'AP Psychology', 'AP US History', 'Art', 'Basic Math', 'Basic Science', 'Biology', 'Business English', 'Calculus', 'Chemistry', 'Chinese', 'College Preparation', 'Computer Science', 'Economics', 'English', 'Reading Comprehension', 'French', 'Geometry', 'German', 'GMAT', 'GRE', 'Hebrew', 'High School Math', 'History', 'IELTS', 'ISEE', 'Italian', 'Japanese', 'Korean', 'LSAT', 'Middle School Math', 'Other', 'Performing Arts', 'Philosophy', 'Physical education', 'Physics', 'Portugese', 'Psychology', 'SAT', 'SAT II', 'Spanish', 'Spoken English', 'SSAT', 'Statistics', 'TOEFL', 'Trigonometry', 'Writing'] );
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const common_1 = require("../common"); function createLuluProviders(options) { return { provide: common_1.LULU_TOKEN, useValue: common_1.createLuluClient(options) }; } exports.createLuluProviders = createLuluProviders;
var EmployerProfile = { init: function () { this.cacheElements(); this.bindEvents(); this.addWidgets(); }, cacheElements: function () { this.$rating = $('select#rating'); this.$initialRating = $('input#initial-rating'); this.$rateButton = $('button#rate'); this.$yourRatingPoint = $('span#your-rating-point'); this.$ratingInstruction = $('p.rating-instruction'); this.$ratingAvgPoint = $('span#rating-avg-point'); this.$ratersCount = $('span#raters-count'); this.$canRate = $('input#can-rate'); }, bindEvents: function () { this.$rateButton.click(EmployerProfile.rateClick); }, addWidgets: function () { EmployerProfile.$rating.barrating({ theme: 'fontawesome-stars', initialRating: (EmployerProfile.$initialRating.val().length == 0) ? 0 : EmployerProfile.$initialRating.val(), readonly: (EmployerProfile.$canRate.val() == '0') ? true : false, }); }, /** * Ertekeles */ rateClick: function () { var $this = $(this); $this.prop('disabled', true); var ratingValue = EmployerProfile.$rating.val(); $.confirm({ icon: 'fa fa-question-circle', title: 'Megerősítés', content: 'Biztosan <strong>' + ratingValue + '</strong> ponttal értékeled a felhasználót?', confirm: function () { EmployerProfile.sendRateAjax($this, ratingValue); }, cancel: function () { $this.prop('disabled', false); }, confirmButton: 'IGEN', cancelButton: 'NEM' }); }, sendRateAjax: function ($button, ratingValue, userId) { var userId = $button.data('user_id'); var ajax = new AjaxBuilder(); var success = function (data) { if (data.error) { $button.prop('disabled', false); } else { EmployerProfile.$yourRatingPoint.text(data.rating); EmployerProfile.$ratingAvgPoint.text(data.avg); EmployerProfile.$ratersCount.text(data.raters_count); EmployerProfile.$ratingInstruction.fadeOut(function () { EmployerProfile.$ratingInstruction.hide(); }); EmployerProfile.$rateButton.fadeOut(function () { EmployerProfile.$rateButton.hide(); }); EmployerProfile.$rating.barrating('set', parseInt(data.avg)); EmployerProfile.$rating.barrating('readonly', true); } }; ajax.data({rating: ratingValue, user_id: userId}).url(ROOT + 'user/ajax/rate').success(success).send(); } }; $(document).ready(function () { EmployerProfile.init(); });
const cleanLoadableTags = (tags, stats, original) => { let parsed = original; tags.forEach(tag => { let chunk = stats.namedChunkGroups[tag]; chunk.assets.forEach(asset => { var re = new RegExp(`<script.*?${asset}.*?$`, 'mg'); parsed = parsed.replace(re, ''); }); chunk.chunks.forEach(chunkName => { chunkName = typeof chunkName === 'string' ? '"' + chunkName + '"' : chunkName; let re = new RegExp(`,${chunkName},`, 'mg'); parsed = parsed.replace(re, ''); re = new RegExp(`,${chunkName}\\]`, 'mg'); parsed = parsed.replace(re, ']'); re = new RegExp(`\\[${chunkName},`, 'mg'); parsed = parsed.replace(re, '['); re = new RegExp(`\\[${chunkName}\\]`, 'mg'); parsed = parsed.replace(re, '[]'); }); }); return parsed; }; export default cleanLoadableTags;
$(document).ready(function(){/* jQuery toggle layout */ $('#btnToggle').click(function(){ if ($(this).hasClass('on')) { $('#main .col-md-6').addClass('col-md-4').removeClass('col-md-6'); $(this).removeClass('on'); } else { $('#main .col-md-4').addClass('col-md-6').removeClass('col-md-4'); $(this).addClass('on'); } }); }); $(document).ready(function(){ $("div.container").on('submit','form#add_new_video', function(){ var video_src = $('#video_url').val(); var video_id = video_src.match(/youtube\.com.*(\?v=|\/embed\/)(.{11})/).pop(); if (video_id.length == 11) { //set the first thumbnail value $('#thumbnail_1').val('http://img.youtube.com/vi/'+video_id+'/0.jpg'); $('#thumbnail_2').val('http://img.youtube.com/vi/'+video_id+'/1.jpg'); $('#thumbnail_3').val('http://img.youtube.com/vi/'+video_id+'/2.jpg'); } }); });
import { SOCKET_DID_CONNECT, SOCKET_DID_MOUNT, } from './action-types' export const socketDidConnect = socket => ({ payload: socket, type: SOCKET_DID_CONNECT, }) export const socketDidMount = socket => ({ payload: socket, type: SOCKET_DID_MOUNT, })
const md5 = require('md5') const moment = require('moment-timezone') const client = require("@mailchimp/mailchimp_marketing"); client.setConfig({ apiKey: MAILCHIMP_API_KEY, server: "us4", }) module.exports = { //email, first, last, tel, course.name, course.start_date, course.end_date studentData: (email, first_name, last_name, tel, course, start_date, end_date, student_id, course_id, tags, code) => { //format start date const start = (start_date != 'Reserve') ? moment.utc(start_date.toDate()).format('MM/DD/YYYY') : moment.tz(moment(), "America/Los_Angeles").format("MM/DD/YYYY") //format end date const end = end_date ? moment.utc(end_date.toDate()).format('MM/DD/YYYY') : null //construct and return data // tags, return mc_data = { email_address: email, status: 'subscribed', tags, merge_fields: { FNAME: first_name, LNAME: last_name, PHONE: tel, COURSE: course, START: start, END: end, CODE: code, USER_ID: student_id, //user_id is used in the URLs found in transfer and post registration email bodies COURSE_ID: course_id //user_id is used in the URLs found in transfer and post registration email bodies } } }, /** * @param: Array of objects, string * @returns: Nothing */ //email updateStudentTags : async ( email, tags ) => { try { await client.lists.updateListMemberTags( STUDENT_LIST, md5(email.toLowerCase()), { tags } ) } catch (error) { //console log the error console.log(error) } }, employerData: ( email, settings, org_name, tel ) => { // Construct req data const mc_data = { email_address: email, status: 'subscribed', tags: settings, merge_fields: { NAME: org_name, PHONE: tel } } return mc_data }, subscribe: async ( list_id, postData ) => { try { // const data = JSON.stringify(postData) await client.lists.addListMember( list_id, postData ) } catch (error) { console.log('ERROR --> ', error ) } } }
import React from 'react' import ReactDOM from 'react-dom' import { JounalApp } from './JounalApp'; import './styles/style.scss' ReactDOM.render( <JounalApp />, document.getElementById('root') );
// convert python list to json array (this is done in a preceding script on the HTML page) // render amplitude var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var width = canvas.width; var height = canvas.height; var bar_width = 4; var bar_plus_space = 2*bar_width; for (let x=0; x<width; x++) { if (x % bar_plus_space == 0) { var i = Math.ceil(levels.length * (x/width)); var bar_height = ((levels[i] * height) / 2).toFixed(5); ctx.fillStyle = 'black'; ctx.fillRect(x, (height / 2) - bar_height, bar_width, bar_height); ctx.fillRect(x, (height / 2), bar_width, bar_height); } }
const dbProducts = require("../db/models") class productsController { static async getProducts(req, res) { const products = await dbProducts.Products.findAll() res.status(200).json(products); } static async postProducts(req, res) { const products = await req.body const result = await dbProducts.Products.create(products); res.status(200).json(result); } static async getProductsById(req, res) { const id = req.params.id const products = await dbProducts.Products.findOne({ where: { id: id }, attributes: { exclude: ['password'] } }); if (products == null) { res.status(404).json("Usúario não encontrado!") } else { res.status(200).json(products) } } static async updateProducts(req, res) { const id = req.params.id const product = await req.body const products = await dbProducts.Products.update(product, { where: { id: id } }) res.status(200).json(products) } static async deleteProducts(req, res) { const id = req.params.id const products = await dbProducts.Products.destroy({ where: { id: id } }) res.status(201).json(products) } }; module.exports = productsController
var connection = require('./db'); var path = require('path'); var dateFormat = require('dateformat'); var mydate = require('current-date'); module.exports = function(paymentRouter){ //API For Payment On Customer Module paymentRouter.post('/payment_details',function(req,res){ var booking_id = req.body.booking_id; var transaction_id = req.body.transaction_id; var payment_type = req.body.payment_type; var total_amount = req.body.total_amount; var payable_amount = req.body.payable_amount; var transaction_date = mydate('date'); var trans_time = mydate('time'); var transaction_datetime = transaction_date+' '+trans_time; if(payment_type == 'Wallet'){ var wallet_amount = req.body.wallet_amount; var sel_cusid = "select service_booking.customer_id as cus_id,customer_register.wallet as wallet_amount from service_booking inner join customer_register on customer_register.id = service_booking.customer_id where service_booking.job_no='"+booking_id+"'"; connection.query(sel_cusid,function(err,sel_cus,fields){ var customer_id = sel_cus[0]['cus_id']; var wallet_old_amount = sel_cus[0]['wallet_amount']; var balance_wallet = wallet_old_amount - wallet_amount; var up_wallet = "update customer_register set wallet='"+balance_wallet+"' where id='"+customer_id+"'"; connection.query(up_wallet,function(errors,update_wall,fields){ var sel_commission = "select commission_amount from commission order by id desc LIMIT 1"; console.log(sel_commission); connection.query(sel_commission,function(errors,commission_res,fields){ var commission_amount = commission_res[0]['commission_amount']; var pay_commission = payable_amount *(commission_amount/100); var ins_pay = "insert into payment_transaction (booking_id,transaction_id,transaction_date,transaction_datetime,payment_type,payment_mode,total_amount,wallet_amount,paid_amount,pay_commission) values ('"+booking_id+"','"+transaction_id+"','"+transaction_date+"','"+transaction_datetime+"','"+payment_type+"','Online','"+total_amount+"','"+wallet_amount+"','"+payable_amount+"','"+pay_commission+"')"; connection.query(ins_pay,function(errors,rows,fields){ if(rows){ var up_pay = "update service_booking set transaction_id='"+transaction_id+"',paid_amount='"+payable_amount+"',commission_amount='"+pay_commission+"',payment_type='"+payment_type+"',payment_status='Paid',payment_mode='Online' where job_no='"+booking_id+"'"; connection.query(up_pay,function(errors,results,fields){ var ins_wallet = "insert into wallet (booking_id,customer_id,type,create_date,paid_amount,amount) values ('"+booking_id+"','"+customer_id+"','Used','"+transaction_date+"','"+payable_amount+"','"+wallet_amount+"')"; connection.query(ins_wallet,function(errors,wallet_res,fields){ if(results){ res.format({ 'application/json': function(){ res.send({status : 'Success',response : 'Payment Done Successfully'}); } }); }else{ res.format({ 'application.json': function(){ res.send({status: 'Failure',response: 'Payment Failed'}); } }); } }); }); } }); }); }); }); }else{ var wallet_amount = 0; var sel_commission = "select commission_amount from commission order by id desc LIMIT 1"; connection.query(sel_commission,function(errors,commission_res,fields){ var commission_amount = commission_res[0]['commission_amount']; var pay_commission = payable_amount *(commission_amount/100); var ins_pay = "insert into payment_transaction (booking_id,transaction_id,transaction_date,transaction_datetime,payment_type,payment_mode,total_amount,wallet_amount,paid_amount,pay_commission) values ('"+booking_id+"','"+transaction_id+"','"+transaction_date+"','"+transaction_datetime+"','"+payment_type+"','Online','"+total_amount+"','"+wallet_amount+"','"+payable_amount+"','"+pay_commission+"')"; connection.query(ins_pay,function(errors,rows,fields){ if(rows){ var up_pay = "update service_booking set transaction_id='"+transaction_id+"',paid_amount='"+payable_amount+"',commission_amount='"+pay_commission+"',payment_type='"+payment_type+"',payment_status='Paid',payment_mode='Online' where job_no='"+booking_id+"'"; connection.query(up_pay,function(errors,results,fields){ if(results){ res.format({ 'application/json': function(){ res.send({status : 'Success',response : 'Payment Done Successfully'}); } }); }else{ res.format({ 'application.json': function(){ res.send({status: 'Failure',response: 'Payment Failed'}); } }); } }); } }); }); } }); }
import mongoose from 'mongoose'; /* Interactions are a catch-all object for meetings, calls, emails, virtual convenings, etc. Interactions allow us to connect materials that companies send or present as part of the process of trying to raise money from us, as well as any assessment or comments of those companies. Saving Interactions correctly will allow Learn Capital to analyze how team members spend their time, as well. */ const InteractionSchema = new mongoose.Schema({ atLocation: { type: mongoose.Schema.Types.ObjectId, ref: 'Location' }, interactionType: { type: String, enum: ['Email', 'Call', 'Meeting', 'Web Meeting', 'Ran Into','Meal'] }, startTime: { type: Date }, endTime: { type: Date }, includedContacts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Contact' }], interactionData: [{ type: mongoose.Schema.Types.ObjectId, ref: 'InteractionData' }] }); InteractionSchema.virtual('duration').get(function() { return this.endTime - this.startTime; }); const InteractionDataSchema = new mongoose.Schema({ name: { type: String }, url: { type: String }, fileType: { type: String }, fileKey: { type: String }, atOrganization: { type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }, atInteraction: { type: mongoose.Schema.Types.ObjectId, ref: 'Interaction' }, atContact: { type: mongoose.Schema.Types.ObjectId, ref: 'Contact' } }); let Interaction = mongoose.model('Interaction', InteractionSchema); let InteractionData = mongoose.model('InteractionData', InteractionDataSchema); export default {Interaction, InteractionData}
export function currentPageState(currentPage, contactsPerPage, data) { const indexOfLastPost = currentPage * contactsPerPage const indexOfFirstPost = indexOfLastPost - contactsPerPage const currentContacts = data.slice(indexOfFirstPost, indexOfLastPost) const totalPage = Math.ceil(data.length / contactsPerPage) return { currentContacts, totalPage } }
import React, { PropTypes, PureComponent } from 'react'; import Navigation from './Navigation'; import { Container } from 'components/Containers'; import Drawer from 'components/Drawer'; import styles from '../styles.scss'; export class NavigationDrawer extends PureComponent { static propTypes = { drawerComponent: PropTypes.element }; state = { isOpen: false }; get iconClass () { return this.state.isOpen ? this.createIconClassString(styles.iconOpen) : this.createIconClassString(styles.iconClose); } get titleBarClass () { return this.state.isOpen ? styles.drawerTitleBar : styles.drawerTitleBarClose; } render () { const { isOpen } = this.state; const { drawerComponent } = this.props; return ( <Drawer drawerComponent={drawerComponent} iconClass={this.iconClass} isOpen={isOpen} onToggle={this.handleMenuToggle} title='Navigation' titleBarClass={this.titleBarClass} > <Container className={styles.drawer}> <Navigation /> </Container> </Drawer> ); } createIconClassString (className) { return `fa fa-map-signs ${className}`; } handleMenuToggle = () => this.setState({ isOpen: !this.state.isOpen }) } export default NavigationDrawer;
import React from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import Select from 'react-select'; import './App.css'; const Q1 = [ { value: 1, label: 'Chocolate' }, { value: 2, label: 'Strawberry' }, { value: 3, label: 'Vanilla' }, { value: 4, label: 'Vanilla' }, ]; const Q2 = [ { value: 'chocolate', label: 'Chocolate' }, { value: 'strawberry', label: 'Strawberry' }, { value: 'vanilla', label: 'Vanilla' }, ]; class App extends React.Component { constructor(props) { super(props); this.state = { miasto: "", goraczka: false, wynik: 0, }; } handleChange1 = miasto => { this.setState({ miasto }); console.log(`Option selected:`, this.state.miasto); }; render(){ return ( <div className="App"> <div> <h1>Test na koronawirusa</h1> <p> tutaj jakies pierdolenie ze nie warto sie tym przejmowac </p> </div> <div className="testCard"> <div class="shadow p-3 mb-5 bg-white rounded"> <div> <h1>Wypełnij test i poznaj swój wynik</h1> </div> <p className="question">W jak duzej miejscowosci mieszkasz</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">W jakim jestes wieku</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">Czy miałeś styczność z osobą zarazona</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">W jak duzej miejscowosci mieszkasz</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">W jak duzej miejscowosci mieszkasz</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">W jak duzej miejscowosci mieszkasz</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">Czy masz aktualnie gorączkę</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">Czy masz aktualnie kaszel</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <p className="question">Czy masz aktualnie duszności</p> <p className="question">Czy masz aktualnie bóle mięśni</p> <p className="question">Czy masz aktualnie zmęczenie</p> <p className="question">W jak duzej miejscowosci mieszkasz</p> <Select value={this.state.miasto} onChange={this.handleChange1} options={Q1} /> <button>Sprawdz swój wynik</button> </div> </div> </div> ); } } export default App;
import React from 'react' import { Title } from 'bypass/ui/title' import { Wrapper, Container } from 'bypass/ui/page' import { ColumnLayout, RowLayout, Layout } from 'bypass/ui/layout' import { Bitcoin, Trouble } from './blocks' const Desktop = ({ btc, onBtcTopup, onCheckPayment, onTryCreateTicket }) => ( <Wrapper> <Container> <RowLayout> <Layout> <Title> {__i18n('LANG.SERVICE.LOAD_BALANCE')} </Title> </Layout> <Layout> <ColumnLayout> <Layout grow={1} /> <Layout> <Bitcoin {...btc} onBtcTopup={onBtcTopup} onCheckPayment={onCheckPayment} /> </Layout> <Layout grow={1} /> </ColumnLayout> </Layout> <Layout basis='20px' /> <Layout> <ColumnLayout justify='center' align='center'> <Layout> <Trouble onTryCreateTicket={onTryCreateTicket} /> </Layout> </ColumnLayout> </Layout> <Layout basis='20px' /> </RowLayout> </Container> </Wrapper> ) export default Desktop
'use strict'; angular.module('ligabaloncestoApp') .controller('EntrenadorController', function ($scope, $state, Entrenador) { $scope.entrenadors = []; $scope.loadAll = function() { Entrenador.query(function(result) { $scope.entrenadors = result; }); }; $scope.loadAll(); $scope.refresh = function () { $scope.loadAll(); $scope.clear(); }; $scope.clear = function () { $scope.entrenador = { nombreEntrenador: null, nacionalidad: null, anyosExperiencia: null, id: null }; }; });
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); export default new Vuex.Store({ state: { isLoading: true, brgrMnuOpn: false, currency: "EUR", currencies: ["EUR", "USD", "BTC", "CAD", "CHF", "GBP", "HKD", "RSD"], BPI_rate: 0, BPI_time: 0, chart_Data: [], chart_Labels: [], data_Length: 10, timeStart: 0, timeEnd: 0, }, mutations: { changeCurrency(state, currency) { state.currency = currency; state.chart_Data = []; state.chart_Labels = []; }, toggleMenu(state, id) { if (id === "navbarMenu") state.brgrMnuOpn = !state.brgrMnuOpn; if (id === "navbarMenuClose") state.brgrMnuOpn = false; if (id === "nav-lista") state.currncsMnuOpn = !state.currncsMnuOpn; if (id === "nav-listaClose") state.currncsMnuOpn = false; }, setData(state, obj) { state.BPI_rate = obj.rate; state.BPI_time = obj.time; state.chart_Data.push(obj.rate); state.chart_Labels.push(obj.time); if (state.chart_Data.length > state.data_Length) { state.chart_Data.splice(0, 1); state.chart_Labels.splice(0, 1); } if (state.isLoading === true) state.isLoading = false; state.timeStart = new Date(state.chart_Labels[0]); state.timeEnd = new Date(state.chart_Labels[state.chart_Labels.length - 1]); }, }, actions: { getCurrentData(context, curr) { const URL = `https://api.coindesk.com/v1/bpi/currentprice/${curr}.json`; fetch(URL) .then(response => response.json()) .then((data) => { const bpi = data.bpi[`${curr}`]; // console.log(data.time.updated, bpi.rate); context.commit("setData", { rate: parseFloat(bpi.rate_float), time: data.time.updated }); // console.log(context.state.currency, context.state.BPI_time, context.state.BPI_rate); }) .catch((error) => { console.error(error.statusText); }); setTimeout(() => { // ovde ne moze da nadje state of undefined // tako da context.$store izgleda nije definisan // kao ni context.commit.dispatch - is not a function // context.commit.dispatch("getCurrentData", context.state.currency); // pa sam prepravio na sledece context.dispatch("getCurrentData", context.state.currency); }, 5 * 1000); }, }, });
import React, { useContext, useState } from 'react'; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import Link from '@material-ui/core/Link'; import Box from '@material-ui/core/Box'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import { useHistory } from 'react-router'; import axios from 'axios'; import { AuthContext } from '../../context/authContext'; import MuiAlert from '@material-ui/lab/Alert'; import { CircularProgress, Paper, Snackbar } from '@material-ui/core'; function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link color="inherit"> Big Payment Solution </Link>{' '} {new Date().getFullYear()} {'.'} </Typography> ); } const Alert = ((props) => { return <MuiAlert elevation={6} variant="filled" {...props} />; }); const useStyles = makeStyles((theme) => ({ container: { border: `1px solid green`, borderRadius: '16px', }, paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, })); export default function SignInComponent() { const classes = useStyles(); const history = useHistory(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [message, setMessage] = useState(''); const [disabled, setDisabled]= useState(false); const authContext = useContext(AuthContext); const [open, setOpen] = React.useState(false); const [severity, setSeverity] = useState('success'); const signIn = async (e) => { setDisabled(true); e.preventDefault(); const data = {email, password}; try { const response = await axios.post(`${process.env.REACT_APP_API_URL}/auth/login`, data); if (response) { authContext.login(response.data.user._id,response.data.user.role, response.data.token); setTimeout(() => { setDisabled(false); history.push('/payments'); window.location.reload(); }, 1000); } } catch(error) { setSeverity('error'); setOpen(true); setMessage(error.response.data.message); setDisabled(false); } } const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; return ( <Paper> <Container component="main" maxWidth="xs"> <Snackbar open={open} autoHideDuration={3000} onClose={handleClose}> <Alert onClose={handleClose} severity={severity}> {message} </Alert> </Snackbar> <CssBaseline /> <div className={classes.paper}> <Box width="250px" height="100"> <img src="../assets/images/logo.png" alt="logo" style={{width: '100%', height: '100%'}} /> </Box> <Typography component="h1" variant="h5"> Sign in </Typography> <form className={classes.form} onSubmit={signIn}> <TextField variant="outlined" margin="normal" color="secondary" required type="email" fullWidth disabled={disabled} id="email" label="Email Address" name="email" onChange={ (e) => setEmail(e.target.value)} autoComplete="off" autoFocus /> <TextField variant="outlined" margin="normal" color="secondary" required fullWidth disabled={disabled} name="password" label="Password" onChange={ (e) => setPassword(e.target.value)} type="password" id="password" autoComplete="off" /> <Button type="submit" fullWidth variant="contained" color="secondary" className={classes.submit} > <span style={{ marginRight: '8px' }}> {(disabled) ? <CircularProgress size={20} /> : null} </span> Sign In </Button> {/* <Grid container> <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> </Grid> <Grid item> <Link href="#" variant="body2"> {"Don't have an account? Sign Up"} </Link> </Grid> </Grid> */} </form> </div> <Box mt={2} mb={2}> <Copyright /> </Box> </Container> </Paper> ); }
app.controller('HorseController', function($scope, $timeout, $q, GiveMeHorse) { //set up all the variables for the race $scope.numberOfHorses = 4 //default value of horses $scope.whichHorse = "" var horsesFinished = 0 var colourArray = [] $scope.howMuch = 0 //start money is 100 $scope.winnings = 100; $scope.betOnHorse = function(id) { resetHorses(true) var clickedHorse = $scope.horses.filter(obj => obj.id === id) clickedHorse[0].horseMainClass= "selectedHorse" $scope.whichHorse = id; } $scope.incBet = function(amount) { if (amount ===0) { $scope.howMuch = 0 } else { $scope.howMuch += amount } } //function to create all the horse objects. Run at the start of the game and every horse count change $scope.initGame = function() { //reset finished horses horsesFinished = 0 //reset selected horse $scope.whichHorse = "" //clear the messages array colourArray = [] for (var i = 1; i <= $scope.numberOfHorses; i++) { //create a horse object for each horse var pos = (i === $scope.numberOfHorses) ? "Last" : i var text = (i === 1) ? "Winner!!" : "Pos: " + i var text = (i === $scope.numberOfHorses) ? "Loser :(" : text var colour = { class: "button" + pos, text: text, } //push the horse object to the horses array colourArray.push(colour) } //clear the horses array $scope.horses = [] //loop through the number of horses that are needed for (var i = 1; i <= $scope.numberOfHorses; i++) { //create a horse object for each horse var oddsRand = (Math.floor(Math.random() * $scope.numberOfHorses) + 1) var horse = { horseMainClass: "indivHorse", horseClass: "buttonOff", imageURL: "images/horse" + (Math.floor(Math.random() * 4) + 1) + "_full.png", horseText: "Horse " + i, horseName: "Horse " + i, id: "horse_" + i, horseOdds: oddsRand } //push the horse object to the horses array $scope.horses.push(horse) } } //start the game on load. $scope.initGame() //function to give only the winning horse $scope.startRaceTimers = function() { if (checkBetsArePlaced()) { //reset the horses resetHorses() horsesFinished = 0 // start the race setAllHorseText('Racing..') $scope.bettingMessages = "Racing is underway" //use the horse_racing service to return the horse promises var horsePromises = []; for (var i = 1; i <= $scope.numberOfHorses; i++) { //create a promise for each horse var promise = GiveMeHorse.please('horse_' + i) //push the promise to the promises array horsePromises.push(promise) } //start the race with Promise.race. Will complete when the first promise is returned $q.race(horsePromises).then(function (value) { //call function to colour the winning cell timesUp(value, false) //call function to calculate winnings checkWinner(value, true) }) } } $scope.startTimers = function() { if (checkBetsArePlaced()) { //reset buttons and array of classes resetHorses() horsesFinished = 0 // start the race setAllHorseText('Racing..') $scope.bettingMessages = "Racing is underway" //start timers by using the horse_racing service which returns promises, then fire the timesUp function to colour the horse for (var i = 1; i <= $scope.numberOfHorses; i++) { //create a promise for each horse var promise = GiveMeHorse.please('horse_' + i, $scope.horses[i-1].horseOdds).then(function (id) { timesUp(id, true) checkWinner(id, false) }); } } } function timesUp(id, multi) { //go through each case and colour accordingly, using the first value from the colours array var finishedHorse = $scope.horses.filter(obj => obj.id === id) finishedHorse[0].horseClass = colourArray[horsesFinished].class finishedHorse[0].horseText = colourArray[horsesFinished].text horsesFinished ++ } //function to calculate winnings. function checkWinner(horse_id, singleHorse) { var finishedHorse = $scope.horses.filter(obj => obj.id === horse_id) if (!singleHorse && finishedHorse[0].id === $scope.whichHorse) { //the horse you bet on has finished. Calculate the winnings. if (horsesFinished <= 3){ var multiplier = 1/horsesFinished var winnings = Math.floor($scope.howMuch * (finishedHorse[0].horseOdds * multiplier)) $scope.winnings += winnings $scope.bettingMessages = "You won: £" + winnings } else { $scope.winnings -= $scope.howMuch $scope.bettingMessages = "You lost :(" } } else if (singleHorse) { if (horse_id === $scope.whichHorse) { $scope.winnings += ($scope.howMuch * $scope.numberOfHorses) $scope.bettingMessages = "You won: £" + $scope.howMuch * ($scope.numberOfHorses * 3) } else { $scope.winnings -= $scope.howMuch $scope.bettingMessages = "You lost :(" } } } //rest all the horses to white. function resetHorses(sel = false) { $scope.horses.forEach(function(horse) { horse.horseClass = "buttonOff" horse.horseText = horse.horseName if (sel) horse.horseMainClass = "indivHorse" }) } //function to write all messages in one go. function setAllHorseText(textVal){ $scope.horses.forEach(function(horse) { horse.horseText = textVal }) } function checkBetsArePlaced(){ var horseNotChosen = ($scope.whichHorse === "" || $scope.whichHorse === undefined) ? true : false var moneyNotPlaced = ($scope.howMuch === "" | $scope.howMuch === 0 || $scope.howMuch === undefined) ? true : false if (horseNotChosen && moneyNotPlaced){ $scope.bettingMessages = "You need to choose a horse and place a bet" return false } else if (horseNotChosen) { $scope.bettingMessages = "You need to choose a horse to bet on" return false } else if (moneyNotPlaced) { $scope.bettingMessages = "You need to place a bet" return false } else if ($scope.howMuch < 0) { $scope.bettingMessages = "You need to bet actual money" return false } else { return true } } });
"use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var __decorate = void 0 && (void 0).__decorate || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; } return c > 3 && r && Object.defineProperty(target, key, r), r; }; exports.__esModule = true; exports.AppModule = void 0; var core_1 = require("@angular/core"); var platform_browser_1 = require("@angular/platform-browser"); var app_routing_module_1 = require("./app-routing.module"); var app_component_1 = require("./app.component"); var AppModule = /** @class */ function () { function AppModule() {} AppModule = __decorate([core_1.NgModule({ declarations: [app_component_1.AppComponent], imports: [platform_browser_1.BrowserModule, app_routing_module_1.AppRoutingModule], providers: [], bootstrap: [app_component_1.AppComponent] })], AppModule); return AppModule; }(); exports.AppModule = AppModule;
{"siteTitle":"Testing","email":"test@auth.com"}
import React from 'react'; import PropTypes from 'prop-types'; import Img from 'react-image'; import ListItem from '@material-ui/core/ListItem'; import Typography from '@material-ui/core/Typography'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import Avatar from '@material-ui/core/Avatar'; import PersonIcon from '@material-ui/icons/Person'; import TimeAgo from 'react-timeago'; const Message = ({ author, content, createdAt, mine }) => { const fallbackIcon = <PersonIcon />; const authorText = author && author.realName + (mine ? ' (me)' : ''); return ( <ListItem alignItems="flex-start"> <ListItemAvatar> {author ? ( <Avatar> <Img src={author.imageUrl} loader={fallbackIcon} unloader={fallbackIcon} style={{ width: '100%', height: '100%' }} /> </Avatar> ) : ( fallbackIcon )} </ListItemAvatar> <ListItemText primary={authorText} secondary={ <React.Fragment> <Typography component="span" color="textPrimary"> {content} </Typography> <Typography component="span" variant="caption"> <TimeAgo date={new Date(createdAt)} minPeriod={60} /> </Typography> </React.Fragment> } /> </ListItem> ); }; export default Message; Message.propTypes = { /** author of the message */ author: PropTypes.shape({ imageUrl: PropTypes.string, realName: PropTypes.string }), content: PropTypes.node.isRequired, createdAt: PropTypes.string }; Message.defaultProps = { author: { realName: 'Unknown' } };
import express from 'express'; import https from "https"; // import {getReq} from './utils'; let router = express.Router(); let API_KEY = "&key=AIzaSyDrZk_oulORJtXOG2L87a2OVfH9e10JvCU"; let GEOCODING_URL = "https://maps.googleapis.com/maps/api/geocode/json?address="; let NEARBY_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="; let PAGE_URL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken="; let DETAIL_URL = "https://maps.googleapis.com/maps/api/place/details/json?placeid="; let PHOTO_URL = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=750&photoreference="; let OFFSET = 1609.34; let loc = "34.0266,-118.2831"; // let getData = getReq(); let getData = (url, func) => { https.get(url, res => { res.setEncoding("utf8"); let body = ""; res.on("data", data => { body += data; }); res.on("end", () => { body = JSON.parse(body); func(body); }); }); } let getGeocode = (url, func) =>{ getData(url, (res_data) => { func(res_data); }); } /* GET nearby. */ router.get('/nearby', (req, res) => { let keyword = req.query.keyword; let category = req.query.category; let distance = parseFloat(req.query.distance) * OFFSET; let from = req.query.from; let location = req.query.location; if (from==='other') { let geocode_url = GEOCODING_URL + encodeURIComponent(location) + API_KEY; getGeocode(geocode_url, (geo_res) => { if (geo_res["status"] != "OK") { res.send(geo_res); } else { location = geo_res["results"][0]["geometry"]["location"]["lat"] + "," + geo_res["results"][0]["geometry"]["location"]["lng"]; // $res["geo_loc"] = $location; let url = NEARBY_URL + location + "&radius=" + distance + "&keyword=" + encodeURIComponent(keyword) + API_KEY; if (category != "default") { url += "&type=" + category; } // console.log(url); getData(url, (res_data) => { res.send(res_data); }); } }); } else { let url = NEARBY_URL + location + "&radius=" + distance + "&keyword=" + encodeURIComponent(keyword) + API_KEY; if (category != "default") { url += "&type=" + category; } getData(url, (res_data) => { res.send(res_data); }); } }); router.get('/page', (req, res) => { let url = PAGE_URL + req.query.pagetoken + API_KEY; getData(url, (res_data) => { res.send(res_data); }); }); router.get('/detail', (req, res) => { let url = DETAIL_URL + req.query.id + API_KEY; getData(url, (res_data) => { res.send(res_data); }); }); router.get('/photo', (req, res) => { let url = PHOTO_URL + req.query.reference + API_KEY; getData(url, (res_data) => { res.send(res_data); }); }); module.exports = router;
/* * Copyright 2016 michael. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Abbozza.Main = { symbols : null, name: "main", init: function() { this.setHelpUrl(Abbozza.HELP_URL); this.setColour(Abbozza.FUNC_COLOR); this.appendDummyInput() .appendField(_("MAIN")); this.appendStatementInput("STATEMENTS") .setCheck("STATEMENT"); this.setTooltip(''); this.setMutator(new Blockly.Mutator()); // this.setMutator(new DynamicMutator( function() { // if ( Configuration.getParameter("option.noArrays") == "true") { // return ['devices_num_noconn', 'devices_string_noconn','devices_decimal_noconn', 'devices_boolean_noconn']; // } else if ( Configuration.getParameter("option.linArrays") == "true" ) { // return ['devices_num', 'devices_string','devices_decimal', 'devices_boolean','arr_dimension_noconn']; // } else { // return ['devices_num', 'devices_string','devices_decimal', 'devices_boolean','arr_dimension']; // } // })); this.setDeletable(false); }, setSymbolDB : function(db) { this.symbols = db; }, generateCode : function(generator) { var statements = generator.statementToCode(this, 'STATEMENTS', " "); var code = ""; code = code + "void setup() {\n"; code = code + this.symbols.toCode(" "); code = code + "###setuphook###\n"; code = code + Abbozza.blockMain.generateSetupCode(generator); code = code + statements; code = code + "\n}\n"; return code; }, /* check : function(block) { return "Test"; }, */ compose : function(topBlock) { Abbozza.composeSymbols(topBlock,this); }, decompose : function(workspace) { return Abbozza.decomposeSymbols(workspace,this,_("LOCALVARS"),false); }, mutationToDom: function() { // Abbozza.log("variables to Dom") var mutation = document.createElement('mutation'); if (this.symbols != null) mutation.appendChild(this.symbols.toDOM()); // Abbozza.log(mutation); return mutation; }, domToMutation: function(xmlElement) { var child; // Abbozza.log("variables from Dom") for ( var i = 0; i < xmlElement.childNodes.length; i++) { child = xmlElement.childNodes[i]; // Abbozza.log(child); if ( child.tagName == 'symbols') { if ( this.symbols == null ) { this.setSymbolDB(new SymbolDB(null)); } this.symbols.fromDOM(child); // Abbozza.log(this.symbols); } } }, updateLook: function() { var no = 0; while ( this.getInput("VAR"+no) ) { this.removeInput("VAR"+no); no = no+1; } no = 0; while ( this.getInput("PAR"+no) ) { this.removeInput("PAR"+no); no = no+1; } var entry; var variables = this.symbols.getVariables(true); for ( var i = 0; i < variables.length; i++ ) { entry = variables[i]; this.appendDummyInput("VAR"+i).appendField(_(entry[1]) + " " + entry[0] + Abbozza.lenAsString(entry[2])); if ( this.getInput("STATEMENTS")) this.moveInputBefore("VAR"+i,"STATEMENTS"); } } }; Blockly.Blocks['main'] = Abbozza.Main;
const webpack = require("webpack"); const path = require("path"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { devtool: "eval-cheap-module-source-map", resolve: { extensions: [".ts", ".tsx", ".js", ".jsx"], alias: { "@": path.join(__dirname, "../../src"), }, }, module: { rules: [ { test: /\.(t|j)sx?$/, use: [ { loader: "babel-loader", options: { presets: [ [ "@babel/preset-env", { modules: false, useBuiltIns: "usage", corejs: { version: 3, }, targets: { chrome: "60", firefox: "60", ie: "9", safari: "10", edge: "17", }, }, ], "@babel/preset-react", ], }, }, { loader: "ts-loader", options: { allowTsInNodeModules: true, }, }, ], exclude: /node_modules/, }, { test: /\.(jpg|png|bmp|gif|svg|woff|woff2|ttf|eot|jpeg)$/, use: [ { loader: "url-loader", options: { name: "[contenthash:10].[ext]", esModule: false, limit: 8 * 1024, }, }, ], }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { modules: true, }, }, "postcss-loader", ], }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { modules: true, }, }, "postcss-loader", "sass-loader", ], }, { test: /\.less$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { modules: true, }, }, "postcss-loader", "less-loader", ], }, ], }, plugins: [ new webpack.ProgressPlugin(), new webpack.ProvidePlugin({ React: "react", }), new MiniCssExtractPlugin({ filename: "index.css", }), new webpack.DefinePlugin({ SSR: false, }), ], };
viewport = [-3, -3, 3, 3]; var objects; function init() { objects = please.access('objects.jta').instance(); graph.add(objects); theta = 5; } function new_game() { // The play function will run the named action. This will change the // location of the bones (which are nodes in M.GRL). If you want to // combine a prepared action with a scripted animation, you probably // want to move the armature in your script, not the meshes. objects.play('hit'); }
/* // exercício 1 const minhaFuncao = (quantidade) => { const array = [] for(let i = 0; i < quantidade; i+=2) { for(let j = 0; j < i; j++) { array.push(j) } } return array } // a. Indique qual será o resultado da função caso ela seja chamada como `minhaFuncao(2)` //[0] // b. Indique qual será o resultado da função caso ela seja chamada como `minhaFuncao(5)` //[0, 1, 0, 1, 2, 3] // c. Indique qual será o resultado da função caso ela seja chamada como `minhaFuncao(8)` //[0, 1, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5] // exercício 2 let arrayDeNomes = ["Darvas", "Goli", "João", "Paulinha", "Soter"]; const funcao = (lista, nome) => { for (let i = 0; i < lista.length; i++) { if (lista[i] === nome) { return i; } } }; console.log(funcao(arrayDeNomes, "Darvas")); console.log(funcao(arrayDeNomes, "João")); console.log(funcao(arrayDeNomes, "Paula")); // a. Explicite quais são as saídas impressas no console // 0 // 2 // undefined // b. O código funcionaria se a lista fosse um array de números (ao invés de um array de string) e o nome fosse um número, ao se chamar a função? Justifique sua resposta. // Daria certo mas teria que ser o número sem aspas para não ser string. O comparador de if compara o tipo também. // Exercício 3 function metodo(array) { let resultadoA = 0; let resultadoB = 1; let arrayFinal = []; for (let x of array) { resultadoA += x; resultadoB *= x; } arrayFinal.push(resultadoA); arrayFinal.push(resultadoB); return arrayFinal; } // Fica undefined? Tive dificuldade neste exercício.. // Exercício 4 // a) function calculaIdade(idadeHumana){ let idadeCanina = Number(prompt("Quantos anos tem o seu cachorro?")) * 7; return idadeCanina; } console.log(calculaIdade()) // b) let nome = prompt("Qual seu nome?"); let idade = Number(prompt("Qual a sua idade?")); let endereco = prompt("qual o seu endereço?"); let estudante = confirm("Você estuda? Ok para true e cancel para não"); function montaFrase() { if (estudante === true){ console.log(`Olá, eu sou ${nome}, tenho ${idade} anos, moro em ${endereco} e sou estudante`); } else { console.log(`Olá, eu sou ${nome}, tenho ${idade} anos, moro em ${endereco} e não sou estudante`); } } montaFrase(); */ // Exercício 5 let ano = Number(prompt("Qual ano, você gostaria de saber o século?")); if (ano < 1000) { console.log("Este século não está contemplado!") } else if (ano > 1000 && ano < 1100) { console.log(`O ano ${ano} pertence ao século X`) } else if (ano > 1100 && ano < 1200) { console.log(`O ano ${ano} pertence ao século XI`) } else if (ano > 1200 && ano < 1300) { console.log(`O ano ${ano} pertence ao século XII`)
const express = require('express') const router = express.Router() const gcm = require('node-gcm') router.post('/register-device' , (req , res) => { }) router.get('/send-notification' , (req , res) => { }) module.exports = router
import React from "react"; import "./styles/stats.css"; import PlatformStats from "./stats/platformStats"; import MoneyStats from "./stats/moneyStats"; function Stats(props) { function moneyValue(items, priceType) { var money = 0; for(let i of items) { if(priceType === 1) { money += i.buyPrice; } else if(priceType === 2){ money += i.sellPrice; } } return money; } return ( <div id="statsContainer"> <div id="platform"> <PlatformStats soldItems={props.soldItems} /> </div> <div id="week"> <MoneyStats soldItems={props.soldItems} period="7" /> </div> <div id="month"> <MoneyStats soldItems={props.soldItems} period="30" /> </div> <div id="year"> <MoneyStats soldItems={props.soldItems} period="365" /> </div> <div id="details"> <div id="currentItems"> <p>Posiadane przedmioty: {props.currentItems.length}</p> <p>Wartość: {moneyValue(props.currentItems, 1)} PLN</p> </div> <div id="soldItems"> <p>Sprzedane przedmioty: {props.soldItems.length}</p> <p>Całkowity profit: {moneyValue(props.soldItems, 2)} PLN</p> </div> </div> </div> ); } export default Stats;
import "../Style/GoneFishing.css" export default function GoneFishing(){ console.log("hello world"); return ( <div> <p>hello world</p> </div> ) }
define(function(require, exports, module) { var PowerTextarea = require('modules/widget/textarea/powertextarea'); var AjaxForm = require('ajaxform'); var alertify = require('alertify'); var Dialog = require('dialog'); var juicer = require('juicer'); var user = require('user'); var template = [ '<form class="p_content" action="http://www.yinyuetai.com/report/create-report">', '<div class="select_area">', '<a href="javascript:;" class="g_select J_select">', '<span class="g_select_l"></span>', '<span class="con">选择举报类型</span>', '<span class="g_select_r"></span>', '</a>', '<ul class="select_area_down J_option_list">', '<li><a href="javascript:;" class="J_option" data-value="politics">时政违法</a></li>', '<li><a href="javascript:;" class="J_option" data-value="advertising">广告违法</a></li>', '<li><a href="javascript:;" class="J_option" data-value="vulgar">低俗违法</a></li>', '<li><a href="javascript:;" class="J_option" data-value="others">其他违法内容</a></li>', '</ul>', '</div>', '<div class="com_area_box ">', '<textarea class="com_area f14" name="reportDesc" placeholder="请输入5-500字的举报理由"></textarea>', '<span class="num c_6 J_count">还可以输入<strong>500</strong>字</span>', '</div>', '<p class="submit c_9"><button class="fr ico_not_release ico_ct_release">发 布</button>若您还有其他的意见或建议,请', '<a href="http://i.yinyuetai.com/2798004" class="special" target="_blank">联系管理员</a>', '</p>', '</form>']; var successTemplate = [ '<p class="p_report_info">您的举报信息已收到,我们会尽快处理。<br/>', '音悦台鼓励以音乐出发的讨论,但不赞赏人身攻击,谩骂等不良行为。<br/>', '一片音乐净土需要你我共建!<br/> ', '音悦台感谢你的不间断支持。</p>' ]; var reportType; $(document).click(function() { $('.J_option_list').hide(); }) $(document.body).on('click', '.J_select', function(e) { var $target = $(e.currentTarget); var $optionList = $target.next(); if ($optionList.css('display') == 'none') { e.stopPropagation(); $('J_option_list').hide(); $optionList.show(); } }) $(document.body).on('click', '.J_option', function(e) { var $target = $(e.currentTarget); $target.parents('.select_area').find('.con').html($target.html()); reportType = $target.data('value'); }); exports.show = function(params) { function addParam(key, value) { var $input = $(form[key]); if ($input.length == 0) { $input = $('<input type="hidden">').attr('name', key).appendTo($form); } $input.attr('value', value); }; reportType = undefined; var $form = $(juicer.to_html(template.join(''))), form = $form[0], $textarea = $form.find('textarea'); var dialog = new Dialog($form, { width : 320, title : '向音悦Tai举报违规内容', className : 'dialog p_report', height : 'auto' }); new AjaxForm($form, { onRequest : function() { if (!user.isLogined()) { user.login(function() { $form.find('button').click(); }) return false; } if ($form.find('button').hasClass('ico_not_release')) { setTimeout(function() { $textarea.addClass('err_input'); }, 25); setTimeout(function() { $textarea.removeClass('err_input'); }, 1000); return false; } if (!reportType) { alertify.error("请选择举报类型"); return false; } var key = _.keys(params)[0]; if (params && key && !form[key]) { _.each(params, function(value, key) { addParam(key, value); }) } addParam('reportType', reportType); return true; }, onComplete : function(result) { if (!result.error) { $textarea.val(''); powerTextarea.reset(); dialog.$el.removeClass('p_report').addClass('info'); $form.replaceWith($(successTemplate.join(''))); } else { alertify.error(result.message); } } }); var powerTextarea = new PowerTextarea($textarea, { count : { max : 500, min : 5, countBox : $form.find('.J_count'), type : "showLeftCount" }, button : { element : $form.find('button'), enableClass : 'ico_ct_release', disableClass : 'ico_not_release' } }) } })