text
stringlengths
7
3.69M
/** * Created by jzj on 16/1/30. */ var TWColor = function(r,g,b,a){ var color = { r: r, g: g, b: b, a: a }; color.__proto__ = TWColorFunc; return color; }; var TWColorFunc = { toStyle: function(){ var s = 'rgba('+this.r+','+this.g+','+this.b+','+this.a+')'; return s; } }; var TWCalender = function(x,y,width,height) { var calender = { sectionNum: 7 }; tw_injectObjVar(calender, TWLayer(x,y,width,height)); calender.style.gridMarginTop = 40; calender.style.topTextMarginTop = 20; calender.style.textStyle = 'black'; calender.style.textLag = 'zh'; calender.style.bgColor = TWColor(33,153,232,1); calender.style.lineColor = TWColor(212,212,212,1); calender.__proto__ = TWCalenderFunc; return calender; }; var TWCalenderFunc = { createPath: function() { if(this.sectionNum <= 1) return; var sectionWidth = this.size.x / this.sectionNum; this.beginPath(); for(var i=1;i<this.sectionNum;++i) { this.moveTo(i*sectionWidth,this.style.gridMarginTop); this.lineTo(i*sectionWidth,this.size.y); } }, drawGrid: function() { this.save(); this.createPath(); this.setStrokeStyle(this.style.lineColor.toStyle()); this.setLineWidth(this.style.lineWidth = 0.5); this.stroke(); this.restore(); }, drawText: function() { this.save(); this.setTextAlign('center'); this.setTextBaseline('middle'); this.setFillStyle(this.style.textStyle); var days = 0, secs = this.sectionNum*2, secsWidth = this.size.x / secs; for(var i=0;i<secs;++i) { if(i%2 === 0) continue; var text = gtw_daysText[this.style.textLag][days], txtWidth = this.measureText(text).width / 2, centerX = secsWidth*i; this.fillText(text,centerX,this.style.topTextMarginTop); days += 1; } this.restore(); }, draw: function(){ this.drawGrid(); this.drawText(); }, alignViewsToSec: function(views){ var secs = this.sectionNum*2, secsWidth = this.size.x / secs, viewSub = 0; for(var i=0;i<secs;++i) { if(i%2 === 0) continue; var centerX = secsWidth* i, vhw = views[viewSub].size.x/ 2, vh = views[viewSub].size.y; // 在这里调用其他对象的功能也可以 TWViewFunc.movePos.apply(this,[views[viewSub],centerX-vhw,this.style.gridMarginTop,0]); viewSub += 1; } } }; TWCalenderFunc.__proto__ = TWLayerFunc; var gtw_daysText = { en: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'], zh: ['一','二','三','四','五','六','日'] }; // TWStackView class .............. var TWStackView = function(layers,x,y,width){ var stackView = { layers: [], margin: 5 }; tw_injectObjVar(stackView, TWView(x,y,0,0)); stackView.__proto__ = TWStackViewFunc; for(var l in layers){ if(!layers.hasOwnProperty(l)) continue; stackView.layers.push(layers[l]); } stackView.size.x = width; stackView.alignLayers(); return stackView; }; var TWStackViewFunc = { alignLayers: function(){ var x = 0, y = 0; this.size.y = 0; for(var l in this.layers){ if(!this.layers.hasOwnProperty(l)) continue; this.movePos(this.layers[l],x,y,1000); this.size.y += this.layers[l].size.y; this.size.y += this.margin; y = this.size.y; } }, addLayer: function(layer){ this.layers.push(layer); this.alignLayers(); }, appendLayer: function(layer){ this.layers.push(layer); this.setPos(layer,0,this.size.y + 180); this.alignLayers(); }, removeAt: function(pos,deleteCount){ var dc = typeof(deleteCount) !== 'number' ? 1 : deleteCount; if(!this.layers[pos] || !this.layers[pos+dc]) return; var objsRemoved = this.layers.splice(pos,dc); this.alignLayers(); return objsRemoved; }, //drawLayers: function(){ // for(var l in this.layers){ // if(!this.layers.hasOwnProperty(l)) continue; // this.layers[l].draw(); // } //}, draw: function(){ this.__proto__.__proto__.draw.apply(this,[true,true]); //this.drawLayers(); } }; TWStackViewFunc.__proto__ = TWViewFunc;
(function() { 'use strict'; function sendPostRequest(event) { event.preventDefault(); var self = this; $.post($(this).attr('href'), function(data) { /* data = { * votes: int, * action: string [upvote|downvote|unvote] * } */ data = JSON.parse(data); // Update arrow highlight. $(self).siblings().addBack().removeClass('active'); if (data.action === 'upvote') { $(self).addClass('active'); } else if (data.action === 'downvote') { $(self).addClass('active'); } // Update text display. $(self).siblings('.count').text(data.votes); }); } // .upvote and .downvote should be siblings with a .count. $('.upvote').click(sendPostRequest); $('.downvote').click(sendPostRequest); })();
import React, {Component} from 'react' // import {connect} from 'react-redux'; import {View, Text, Image, TouchableHighlight, TouchableOpacity} from 'react-native'; // import ProfUserImg from './ProfUserImg' import styles from './styles' class NetworkDetail extends Component{ render(){ const { params } = this.props.navigation.state return( <View> <View style={styles.detail_top}> <Image style={styles.detail_img} source={params.userImg ? {uri: params.userImg} : require('../../assets/defaultUser.jpg')}/> <Text style={styles.detail_name}>{params.name}</Text> <Text style={styles.detail_univ}>{params.univ} 인액터스</Text> <Text style={styles.detail_selfIntro}>{params.selfIntro}</Text> </View> </View> ) } } export default NetworkDetail
//Set text filter export const setTextFilter=(text="")=>({ type:'SET_TEXT', text }); //Set Start Date export const setStartDate=(startDate)=>({ type:'SET_START_DATE', startDate }) //Set End Date export const setEndDate=(endDate)=>({ type:'SET_END_DATE', endDate }) //SetSortByDate export const setSortByDate =()=>({ type:'SET_SORT_BY_DATE' }) //SetSortByAmount export const setSortByAmount=()=>({ type:'SET_SORT_BY_AMOUNT' })
$(function () { /*--- global animations init ---*/ /*---------------------------------------------------------------------*/ $(window).on('load', function() { Animation.initGlobalAnimations({ container: '.out', selfTriggeredElems: { el1: { selector: '.header', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.jumbotron', triggerHook: 1, class: 'is_animated' }, el3: { selector: '.info', triggerHook: 1, class: 'is_animated' }, el4: { selector: '.collection', triggerHook: 1, class: 'is_animated' }, el5: { selector: '.gallery', triggerHook: 1, class: 'is_animated' }, el6: { selector: '.magazin', triggerHook: 1, class: 'is_animated' }, el7: { selector: '.news', triggerHook: 1, class: 'is_animated' }, el8: { selector: '.footer', triggerHook: 1, class: 'is_animated' } } }); Animation.initGlobalAnimations({ container: '.jumbotron', selfTriggeredElems: { el1: { selector: '.jumbotron__figure', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.jumbotron__mark', triggerHook: 1, class: 'is_animated' }, el3: { selector: '.jumbotron__title', triggerHook: 1, class: 'is_animated' }, el4: { selector: '.jumbotron__footer', triggerHook: 1, class: 'is_animated' } } }); Animation.initGlobalAnimations({ container: '.info', selfTriggeredElems: { el1: { selector: '.info__item', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.info__content', triggerHook: 1, class: 'is_animated' }, el3: { selector: '.btn', triggerHook: 1, class: 'is_animated' } } }); Animation.initGlobalAnimations({ container: '.collection', selfTriggeredElems: { el1: { selector: '.title__article', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.collection__wrap', triggerHook: 1, class: 'is_animated' } } }); Animation.initGlobalAnimations({ container: '.gallery', selfTriggeredElems: { el1: { selector: '.title__article', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.gallery__item', triggerHook: 1, class: 'is_animated' }, el3: { selector: '.btn', triggerHook: 1, class: 'is_animated' } } }); Animation.initGlobalAnimations({ container: '.magazin', selfTriggeredElems: { el1: { selector: '.magazin__pic', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.magazin__content', triggerHook: 1, class: 'is_animated' }, el3: { selector: '.btn', triggerHook: 1, class: 'is_animated' } } }); Animation.initGlobalAnimations({ container: '.news', selfTriggeredElems: { el1: { selector: '.title__article', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.news__link', triggerHook: 1, class: 'is_animated' }, el3: { selector: '.btn', triggerHook: 1, class: 'is_animated' } } }); // comlect Animation.initGlobalAnimations({ container: '.complectations', selfTriggeredElems: { el1: { selector: '.title__article', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.complect', triggerHook: 1, class: 'is_animated' } } }); // section Animation.initGlobalAnimations({ container: '.section', selfTriggeredElems: { el1: { selector: '.title__article', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.new', triggerHook: 1, class: 'is_animated' }, el3: { selector: '.title__subtitle', triggerHook: 1, class: 'is_animated' }, el4: { selector: '.title__middle', triggerHook: 1, class: 'is_animated' }, el5: { selector: '.garant__fieldset', triggerHook: 1, class: 'is_animated' }, el6: { selector: '.doc', triggerHook: 1, class: 'is_animated' }, el7: { selector: '.promo', triggerHook: 1, class: 'is_animated' }, el8: { selector: '.title__subtitle', triggerHook: 1, class: 'is_animated' }, el9: { selector: '.variant', triggerHook: 1, class: 'is_animated' }, el10: { selector: '.liability', triggerHook: 1, class: 'is_animated' }, el11: { selector: '.collage', triggerHook: 1, class: 'is_animated' } } }); // specifications Animation.initGlobalAnimations({ container: '.specifications', selfTriggeredElems: { el1: { selector: '.specifications__title', triggerHook: 1, class: 'is_animated' }, el2: { selector: '.specifications__table tr', triggerHook: 1, class: 'is_animated' } } }); }); });
/* Program Table Definition Input: getting name Processing: adding the name to the scripture Output: show the result of the concatenation */ function scripture(){ let name = document.getElementById("name").value; let scripture1 = "I, "; let scripture2 = ", having been born of goodly parents, therefore I was taught somewhat in all the learning of my father; and having seen many afflictions in the course of my days, nevertheless, having been highly favored of the Lord in all my days; yea, having had a great knowledge of the goodness and the mysteries of God, therefore I make a record of my proceedings in my days."; let scriptFinal =scripture1 +name+scripture2; document.getElementById("output").innerHTML = scriptFinal; }
export default function Select({ label, name, value, onChange, options }) { return ( <> <div className="root"> {label && <label htmlFor={name}>{label}</label>} <select name={name} value={value} onChange={onChange}> {options.map((option) => ( <option value={option.id} key={option.id}> {option.text} </option> ))} </select> </div> <style jsx>{` .root { width: 100%; } label { font-size: 0.8rem; color: var(--text-small-color); margin-bottom: 0.4rem; display: inline-block; } select { display: block; width: 100%; line-height: 1.6; font-size: 1rem; font-family: "system-ui", monospace, sans-serif; color: white; border: none; padding: 0.625rem 0.875rem; padding-right: 1.1rem; border-radius: 6px; /* Arrow trick */ position: relative; -moz-appearance: none; -webkit-appearance: none; appearance: none; background: #31333f url("data:image/svg+xml;utf8,<svg viewBox='0 0 140 140' width='24' height='24' xmlns='http://www.w3.org/2000/svg'><g><path d='m121.3,34.6c-1.6-1.6-4.2-1.6-5.8,0l-51,51.1-51.1-51.1c-1.6-1.6-4.2-1.6-5.8,0-1.6,1.6-1.6,4.2 0,5.8l53.9,53.9c0.8,0.8 1.8,1.2 2.9,1.2 1,0 2.1-0.4 2.9-1.2l53.9-53.9c1.7-1.6 1.7-4.2 0.1-5.8z' fill='white'/></g></svg>") no-repeat; background-position: right 1.1rem top 50%; } `}</style> </> ); }
import React ,{ Component } from 'react'; import {View , Text, StyleSheet,Dimensions, Platform, Image } from 'react-native'; import { Constants, Permissions, Notifications, FacebookAds } from 'expo'; import { connect } from 'react-redux'; import * as actions from '../actions'; import PercentageCircle from 'react-native-percentage-circle'; import AndroidCircle from '../src/AndroidCircle'; import { Header } from '../src/Header'; import { Card } from '../src/Card'; import { Button } from '../src/Button'; const moment = require('moment'); const duration = require("moment-duration-format"); var {height, width} = Dimensions.get('window'); class CountDownScreen extends Component { state = { percent: 0, endTime : null, km: 0, status: "idle", humanize : null, humanizeEndTime: "-" }; static navigationOptions = ({ navigation }) => { return { tabBarVisible : false, headerTintColor: "#fff", swipeEnabled: false, headerStyle : { marginTop : Platform.OS === 'android' ? 24 : 0, backgroundColor : "#EB3349" }, } }; async componentDidMount(){ let result = await Permissions.askAsync(Permissions.NOTIFICATIONS); if (Constants.isDevice && result.status !== 'granted') { alert( 'You should enable notifications for this app otherwise you will not know when your timers expire!' ); return; } if(Platform.OS === 'android'){ FacebookAds.InterstitialAdManager.showAd('449422098768727_449426018768335') .then(didClick => {}) .catch(error => {}) }else{ FacebookAds.InterstitialAdManager.showAd('449422098768727_449426618768275') .then(didClick => {console.log("clicked ad");}) .catch(error => {console.log("error:", error);}) } } async _fireNotification(fireDate){ const notificationId = await Notifications.scheduleLocalNotificationAsync( { title: 'Süre Doldu!', body: "Süre doldu otobandan çıkış yapabilirsiniz.", ios: { sound: true, }, android: { sound: true, }, }, { time: fireDate, } ); } async _cancelAllNotification(){ await Notifications.cancelAllScheduledNotificationsAsync() } _ınfoTitle (){ return this.props.selectedRoute.FirstGate +" - " + this.props.selectedRoute.LastGate; } _ınfoKM (){ let km = parseInt(this.props.selectedRoute.Km).toFixed(1); return km; } _totalTime = km => { if(km){ kmInt = parseInt(km); let second = Math.floor(kmInt / parseInt(this.props.selectedRoute.speed) * 3600)+100 ; return second; } return 0; } secondToHuminzeString (km){ let second = this._totalTime(km); var humVal = moment.duration(second,'seconds').format("hh:mm:ss"); return humVal; } async _startTimer (){ if(this.state.status == "idle"){ let second = this._totalTime(this.props.selectedRoute.Km); await this.props.setEndTime(moment().add(second,'seconds')); const { endTime } = this.props; let hour = endTime.hour() < 10 ? "0" + endTime.hour() : endTime.hour(); let min = endTime.minute() < 10 ? "0"+ endTime.minute() : endTime.minute(); let sec = endTime.second() < 10 ? "0"+endTime.second() : endTime.second(); var huminzeEndTime = hour+":"+min+":"+sec; this.setState({ status: "started", humanizeEndTime: hour+":"+min+":"+sec }) this._renderTimer(); return; } // İptal Et else if(this.state.status == "started"){ await this.props.setEndTime(0); clearInterval(this._timer); this._timer = null; this.setState({ percent : 0, humanize : null, status : "idle", humanizeEndTime: "-" }) this._cancelAllNotification(); this.props.navigation.navigate('oldTrips'); } } _renderSecond(second){ var humVal = moment.duration(second,'seconds').format("hh:mm:ss"); this.setState({ humanize : humVal }) } _renderTimer(){ if(this.props.endTime > 0){ let startTime = moment(); this._fireNotification(this.props.endTime.valueOf()); this._timer = setInterval( () => { let lastTick = moment(); if (lastTick.valueOf() > this.props.endTime.valueOf()) { this._renderSecond(0); this.setState({ percent : 100, humanize: 'Çıkış yapabilirsiniz', status: 'ended' }) } else { let percent = Math.floor((lastTick.valueOf()-startTime.valueOf())/(this.props.endTime.valueOf()-startTime.valueOf())*100); this.setState({ percent : percent }) var differenceSec = this.props.endTime.diff(lastTick, 'seconds',true); this._renderSecond(differenceSec); } }, 166 ); } } _renderBanner(){ if(Platform.OS === 'android'){ return( <FacebookAds.BannerView placementId="449422098768727_449423225435281" type="standard" onPress={() => console.log('click')} onError={(err) => console.log('error', err)} /> ) }else{ return( <FacebookAds.BannerView placementId="449422098768727_449426432101627" type="standard" onPress={() => console.log('click')} onError={(err) => console.log('error', err)} /> ) } } _renderCircle(){ if(Platform.OS === 'android'){ return( <AndroidCircle radius={105} percent={this.state.percent} borderWidth ={12} color={"#640204"} innerColor={"#7E8B7D"}> <Text style={[styles.percentText]}> {this.state.status == "idle" ? "Sayacı Başlatınız" : " % " + this.state.percent }</Text> <Text style={[styles.countDownText]}>{this.state.humanize ? this.state.humanize : this.secondToHuminzeString(this.props.selectedRoute.Km) } </Text> </AndroidCircle> ) }else{ return( <PercentageCircle radius={105} percent={this.state.percent} borderWidth ={12} color={"#640204"} innerColor={"#7E8B7D"}> <Text style={[styles.percentText]}> {this.state.status == "idle" ? "Sayacı Başlatınız" : " % " + this.state.percent }</Text> <Text style={[styles.countDownText]}>{this.state.humanize ? this.state.humanize : this.secondToHuminzeString(this.props.selectedRoute.Km) } </Text> </PercentageCircle> ) } } _renderButton(){ if(this.state.status == "idle"){ return 'Başlat'; }else if(this.state.status == "started"){ return'İptal Et' }else if(this.state.status == "ended"){ return 'Bitti' } } render(){ return( <Image source={require('../img/count.png')} style={styles.backgroundImage}> <Header headerText ={ this._ınfoTitle()} /> <View style={styles.container}> {this._renderCircle()} <View style={styles.infoContainer}> <View style={{flexDirection:'row', justifyContent:'space-between',width:width,paddingRight:15,paddingLeft:15}}> <Card style={styles.cardStyle}> <Text style={styles.cardText}>Toplam Mesafe</Text> <View style={{flexDirection:'row',justifyContent :'center', alignItems:'flex-end'}}> <Text style={{fontSize:24, fontWeight: '700',color:'#fff'}}>{this._ınfoKM()} </Text> <Text style={{fontSize:18,fontWeight:'700', color :'#fff',paddingBottom:2 }}>KM</Text> </View> </Card> <Card style={styles.cardStyle}> <Text style={styles.cardText}>Tahmini Varış</Text> <View style={{flexDirection:'row',justifyContent :'center', alignItems:'flex-end'}}> <Text style={{fontSize:24, fontWeight: '700',color:'#fff',textAlign:'center'}}>{this.state.humanizeEndTime} </Text> </View> </Card> </View> <View style={{height: 70, width : width ,paddingTop:20}}> <Button onPress={() => this._startTimer()}>{this._renderButton()}</Button> </View> </View> </View> {this._renderBanner()} </Image> ); } } const styles ={ container: { flex: 1, justifyContent: 'space-around', alignItems: 'center', paddingTop:20, }, percentText: { fontSize: 21, paddingBottom : 15, fontWeight:'600', alignItems : 'center', alignSelf: 'center', color: "#fff" }, countDownText :{ fontSize : 24, fontWeight : '600', alignItems : 'center', alignSelf :'center', color: "#fff" }, itemContainer :{ height : 200, width : 250, backgroundColor :'rgba(0,0,0,0)', }, buttonContainer : { height : 50, width :250, }, InfoContainer : { width:width, justifyContent:'center' }, backgroundImage: { flex: 1, width: null, height: null, resizeMode: 'cover', }, cardStyle:{ height : 60, width : null, alignItems: 'center', }, infoContainer : { }, cardText:{ fontSize : 14, color :'#fff', fontWeight :'700', paddingLeft:10, paddingRight : 10 } }; const mapStateToProps = state => { return { selectedRoute : state.selectedRoute, endTime : state.endTime } }; export default connect(mapStateToProps,actions)(CountDownScreen);
const express = require("express"); const visitObj = require("../module-controllers/visit"); const doctorObj = require("../module-controllers/doctor"); const patientObj = require("../module-controllers/patient"); const nurseObj = require("../module-controllers/nurse"); const appointmentObj = require("../module-controllers/appointment"); const app = express.Router(); // =================Get All Visits====================== app.get("/api/visits", async (request, response) => { try { const visits = await visitObj.getVisits(); if (visits.length > 0) response.json(visits); response.status(404).send("no visit found"); } catch (err) { response.status(500).send("Something went wrong, please try again..!!!"); } }); //= =================Add New Visit========================= app.post("/api/visits", async (request, response) => { try { //console.log(request.body); if (request.body.appointment) { const patient = await patientObj.getPatientByUserName( request.body.appointment ); if (patient === null) { response.status(404).send("no patient found with given username"); } else { const appointment = await appointmentObj.getAppointmentByPatient( patient._id.toString() ); if (appointment.length === 0) { response.status(404).send("no appointment found with given patient"); } else { request.body.appointment = appointment[0]._id.toString(); console.log(typeof request.body.appointment); } } } if (request.body.patient) { const patient = await patientObj.getPatientByUserName( request.body.patient ); if (patient === null) { response.status(404).send("no patient found with given username"); } else { request.body.patient = patient._id.toString(); } } const doctor = await doctorObj.getDoctorByUserName( request.body.diagnosedBy ); console.log(doctor); if (doctor === null) { response.status(404).send("No doctor found with the given username"); } else { const nurse = await nurseObj.getNurseByUserName(request.body.nursedBy); if (nurse === null) { response.status(404).send("No Nurse found with the given username"); } else { request.body.diagnosedBy = doctor._id.toString(); request.body.nursedBy = nurse._id.toString(); console.log(request.body); const { error } = visitObj.validateVisit(request.body); // result.error (object destructor) console.log(error); if (error) { response.status(400).send(error.details[0].message); } const newVisit = visitObj.addVisit(request.body); response.json(newVisit); } } } catch (err) { response.status(500).send("Something went wrong, please try again..!!!"); } }); //= =================Get Visit By Id======================== app.get("/api/visits/:visitId", async (request, response) => { try { const visit = await visitObj .getVisitById(request.params.visitId) .catch(() => { response.status(404).send("Requested id not found"); }); if (visit === null) { response.status(400).send("No Visit found with the given id"); } response.json(visit); } catch (err) { response.status(500).send("Something went wrong, please try again..!!!"); } }); //= =================Get Visit By Patient======================== app.get("/api/visits/patient/:patient", async (request, response) => { try { const visit = await visitObj .getVisitByPatient(request.params.patient) .catch(() => { response.status(404).send("Requested id not found"); }); if (visit === null) { response.status(400).send("No Visit found with the given Patient"); } response.json(visit); } catch (err) { response.status(500).send("Something went wrong, please try again..!!!"); } }); // ========================Update Visit By Id====================== app.put("/api/visits/:visitId", async (request, response) => { try { const doctor = await doctorObj.getDoctorByUserName(request.body.doctor); const patient = await patientObj.getPatientByUserName(request.body.patient); const nurse = await nurseObj.getNurseByUserName(request.body.createdBy); if (doctor === null) { response.status(400).send("No Doctor found with the given username"); } else if (patient === null) { response.status(400).send("No Patient found with the given username"); } else if (nurse === null) { response.status(400).send("No Nurse found with the given username"); } else { request.body.doctor = doctor._id.toString(); request.body.patient = patient._id.toString(); request.body.createdBy = nurse._id.toString(); console.log(request.body); const { error } = visitObj.validateVisit(request.body); // result.error (object destructor) if (error) { response.status(400).send(error.details[0].message); } else { const visit = await visitObj .updateVisitById(request.params.visitId, request.body) .catch(() => { response.status(404).send("Requested id not found"); }); if (visit === null) { response.status(400).send("No Visit found with the given id"); } response.json(visit); } } } catch (err) { response.status(500).send("Something went wrong, please try again..!!!"); } }); // ===========Delete Visit By Id=========================== app.delete("/api/visits/:visitId", async (request, response) => { try { const visit = await visitObj .deleteVisitById(request.params.visitId) .then(() => { response.status(204).send("deleted successfully"); }) .catch(() => { response.status(404).send("Requested id not found"); }); if (visit === null) { response.status(400).send("No Visit found with the given id"); } response.json(visit); } catch (err) { response.status(500).send("Something went wrong, please try again..!!!"); } }); module.exports = { app };
const staticCacheName = ['restaurant-static-v80']; const pageUrls = [ '/', '/index.html', '/restaurant.html' ]; const scriptUrls = [ '/js/dbhelper.js', '/js/main.js', '/js/restaurant_info.js', '/js/Dialog.js', '/js/swhelper.js' ]; const dataUrls = ['./data/restaurants.json']; const stylesUrls = [ '/css/styles.css', '/css/responsive.css', 'css/modal.css' ]; const imgsUrls = [ '/img/1.jpg', '/img/1_300.jpg', '/img/1_400.jpg', '/img/1_600.jpg', '/img/2.jpg', '/img/2_300.jpg', '/img/2_400.jpg', '/img/2_600.jpg', '/img/3.jpg', '/img/3_300.jpg', '/img/3_400.jpg', '/img/3_600.jpg', '/img/4.jpg', '/img/4_300.jpg', '/img/4_400.jpg', '/img/4_600.jpg', '/img/5.jpg', '/img/5_300.jpg', '/img/5_400.jpg', '/img/5_600.jpg', '/img/6.jpg', '/img/6_300.jpg', '/img/6_400.jpg', '/img/6_600.jpg', '/img/7.jpg', '/img/7_300.jpg', '/img/7_400.jpg', '/img/7_600.jpg', '/img/8.jpg', '/img/8_300.jpg', '/img/8_400.jpg', '/img/8_600.jpg', '/img/9.jpg', '/img/9_300.jpg', '/img/9_400.jpg', '/img/9_600.jpg', '/img/10.jpg', '/img/10_300.jpg', '/img/10_400.jpg', '/img/10_600.jpg' ]; const allCaches = [ ...pageUrls, ...scriptUrls, ...dataUrls, ...stylesUrls, ...imgsUrls ]; self.addEventListener('install', function (event) { event.waitUntil( caches.open(staticCacheName).then(function (cache) { console.log('Cache oppend for install') return cache.addAll(allCaches); }) ); }); // Delete resources from the cache that is not longer needed. self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(keys => Promise.all( keys.map(key => { if (!staticCacheName.includes(key)) { return caches.delete(key); } }) )).then(() => { console.log(staticCacheName[0] +' now ready to handle fetches!'); }) ); }); self.addEventListener('fetch', function (event) { if (event.request.url.startsWith('https://maps.googleapis.com/')) { event.respondWith(serveGoogleMap(event)); return; } event.respondWith( caches.match(event.request, { 'ignoreSearch': true }).then(async response => { if(response) return response; let networkFetchRequest = event.request.clone(); return await fetch(networkFetchRequest).then(response =>{ if(!response) return response; let cacheResponse = response.clone(); caches.open(staticCacheName).then(cache=>{ cache.put(event.request, cacheResponse); }); return response; }); }) .catch(err => console.log(err, event.request)) ); }); self.addEventListener('message', function (event) { if (event.data.action === 'skipWaiting') { self.skipWaiting(); this.console.log('Skip waiting'); } }); function serveGoogleMap(event){ return caches.match(event.request).then(async response => { if(response) return response; let networkFetchRequest = event.request.clone(); return await fetch(networkFetchRequest).then(response =>{ if(!response) return response; let cacheResponse = response.clone(); caches.open(staticCacheName).then(cache=>{ cache.put(event.request, cacheResponse); }); return response; }); }) .catch((err) =>{ console.log(err, event.request); }) }
//requiring todolist model const TodoLists = require("../models/TodoLists"); //home controller to render home page with form and list on it module.exports.home = function (req, res) { TodoLists.find({}, function (err, logs) { if (err) { console.log("Error in fetching contacts from the user"); return; } return res.render("listview", { title: "Tasky - Manage your valuable resources", message: "Personal To-do List", Logs: logs, }); }); }; //createLog controller for creating and saving a new entry to the database module.exports.createLog = async function (req, res) { try { const post = new TodoLists({ name: req.body.description, worktype: req.body.category, date: req.body.duedate, }); await post.save(); } catch { return res.redirect("/"); } return res.redirect("back"); }; //deleteLog controller for deleting a new entry from the database module.exports.deletelogs = function (req, res) { let arrid = req.query.id; if (!Array.isArray(arrid)) { deleteById(arrid); } else { for (i of arrid) { deleteById(i); } } return res.redirect("back"); }; //This is a dummy route to see the mesages relayed by the google pubsub module.exports.webhooks = async (req, res) => { // if(req.query.token !== ''){ // res.status(400).send('Invalid request'); // return; // } console.log(req.headers); // The message is a unicode string encoded in base64. const message = Buffer.from(req.body.message.data, "base64").toString( "utf-8" ); console.log("Message is ", message); messages.push(message); req.body ? console.log(req.body) : console.log(req); res.status(200).json({ message: "ack" }); }; //deletemany function deleteById(i) { TodoLists.findByIdAndDelete(i, (err) => { if (err) { console.log("Error in deleting an object in the database"); return; } }); }
const CucumberReportLogger = require('../../../codeceptCommon/reportLogger'); var { defineSupportCode } = require('cucumber'); const jsonpath = require('jsonpath'); const BrowserWaits = require('../../../e2e/support/customWaits'); // const MockApp = require('../../../nodeMock/app'); const CCDCaseConfig = require('../../mockData/ccd/ccdCaseConfig/caseCreateConfigGenerator'); const SoftAssert = require('../../../ngIntegration/util/softAssert'); const { DataTableArgument } = require('codeceptjs'); Given('I create mock Case event {string}', function (moduleRef) { const mockCaseEvent = new CCDCaseConfig("Mock event ", "Mock jurisdiction", "test description " + moduleRef); global.scenarioData[moduleRef] = mockCaseEvent; }); Given('I add page to event {string}', function (moduleRef,datatable) { const pageConfig = datatable.parse().hashes()[0]; const mockCaseEvent = global.scenarioData[moduleRef]; mockCaseEvent.addWizardPage(pageConfig.id, pageConfig.label); global.scenarioData[pageConfig.reference] = mockCaseEvent.getWizardPageConfig(pageConfig.id); }); Given('I add fields to page {string} in event {string}',function (pageRef,moduleRef, datatable) { const fieldConfigs = datatable.parse().hashes(); for (let i = 0; i < fieldConfigs.length; i++){ const fieldConfig = fieldConfigs[i]; const mockCaseEvent = global.scenarioData[moduleRef]; const pageConfig = global.scenarioData[pageRef]; const fieldStructure = fieldConfig.id.split("."); if (fieldStructure.length === 1){ mockCaseEvent.addCCDFieldToPage(pageConfig, { id: fieldStructure[0], type: fieldConfig.type, label: fieldConfig.label }); }else{ let deepFieldConfig = mockCaseEvent.getCaseFieldConfig(fieldStructure[0]); for (let i = 1; i < fieldStructure.length -1; i++) { if (deepFieldConfig.field_type.type === "Complex"){ deepFieldConfig = deepFieldConfig.field_type.complex_fields.filter(f => f.id === fieldStructure[i])[0]; if (!deepFieldConfig){ throw new Error(`${fieldStructure[i]} is not fiund in structure ${fieldConfig.id}`); } } else if (deepFieldConfig.field_type.type === "Collection"){ deepFieldConfig = deepFieldConfig.field_type.collection_field_type; if (!deepFieldConfig) { throw new Error(`${fieldStructure[i]} is not fiund in structure ${fieldConfig.id}`); } } } const fieldConfigToAdd = mockCaseEvent.getCCDFieldTemplateCopy({ id: fieldStructure[fieldStructure.length - 1], type: fieldConfig.type, label: fieldConfig.label }); if (deepFieldConfig.field_type){ if (deepFieldConfig.field_type.type === "Complex") { deepFieldConfig.field_type.complex_fields.push(fieldConfigToAdd); } else if (deepFieldConfig.field_type.type === "Collection") { deepFieldConfig.field_type.collection_field_type = fieldConfigToAdd.field_type; } }else{ if (deepFieldConfig.type === "Complex") { deepFieldConfig.complex_fields.push(fieldConfigToAdd); } else if (deepFieldConfig.type === "Collection") { deepFieldConfig.field_type.collection_field_type = fieldConfigToAdd.field_type; } } } } }); Given('I set field properties for field with id {string} in event {string}', function (fieldId, moduleRef, datatable){ const mockCaseEvent = global.scenarioData[moduleRef]; const fieldProps = datatable.parse().hashes(); const fieldpropsObj = {}; for (let i = 0; i < fieldProps.length; i++){ fieldpropsObj[fieldProps[i].key] = fieldProps[i].value; } mockCaseEvent.updateFieldProps(fieldId, fieldpropsObj); }); Given('I set fixed list ietms to field {string} in event {string}', async function(fieldId,eventRef,fixedListDatatable){ const mockCaseEvent = global.scenarioData[eventRef]; mockCaseEvent.setFixedListItems(fieldId, fixedListdatatable.parse().hashes()); }); Given('I set case event {string} in mock', function(eventRef){ const mockCaseEvent = global.scenarioData[eventRef]; CucumberReportLogger.AddJsonToReportOnly(mockCaseEvent.getCase()); MockApp.onGet('/data/internal/case-types/:jurisdiction/event-triggers/:caseType', (req,res) => { CucumberReportLogger.AddMessage(`event /data/internal/case-types/:jurisdiction/event-triggers/:caseType `); res.send(mockCaseEvent.getCase()); }); }); When('I enter case event field values for event {string}', async function (eventRef, fielValuesDT){ const mockCaseEvent = global.scenarioData[eventRef] ; const fieldValues = fielValuesDT.hashes(); for (let i = 0; i < fieldValues.length; i++) { const pathArr = fieldValues[i].path.split("."); const fieldConfig = mockCaseEvent.getCaseFieldConfig(pathArr[0]); const inputFieldConfig = mockCaseEvent.getInputFieldConfig(fieldConfig, pathArr); await caseEditPage.inputCaseField(inputFieldConfig, fieldValues[i].value, fieldValues[i].cssSelector) } }); Given('I set complex field overrides for case field {string} in event {string}', async function (fieldId, eventRef, overrides){ const mockCaseEvent = global.scenarioData[eventRef]; const overridesHashes = overrides.parse().hashes(); mockCaseEvent.addComplexFieldOverridesToCaseField(fieldId, overridesHashes) }); Given('I set caseField values in event config {string}', async function (eventRef, fields){ const mockCaseEvent = global.scenarioData[eventRef]; const fieldHashes = fields.parse().hashes(); for (let i = 0; i < fieldHashes.length; i++){ mockCaseEvent.setCaseFieldValue(fieldHashes[i].id, fieldHashes[i].value); } }); Given('I set event default values for event {string}', async function (eventRef){ const mockCaseEvent = global.scenarioData[eventRef]; const caseFields = mockCaseEvent.getCase().case_fields; const eventData = {}; for (let i = 0; i < caseFields.length; i++){ eventData[caseFields[i].id] = mockCaseEvent.getCaseFieldDefaultValue(caseFields[i].id) caseFields[i].value = eventData[caseFields[i].id]; } console.log(JSON.stringify(eventData)) }); When('I click collection add new btn for field {string} in event {string}', async function (fieldPath,eventRef){ const mockCaseEvent = global.scenarioData[eventRef]; const pathArr = fieldPath.split("."); const caseFieldConfig = mockCaseEvent.getCaseFieldConfig(pathArr[0]); await caseEditPage.clickAddNewCollectionItemBtn(caseFieldConfig, fieldPath); }); Then('I validate request body {string} of event validate api', async function(requestBodyReference,datatable){ // step definition code here await BrowserWaits.waitForCondition(() => global.scenarioData[requestBodyReference] !== null ); const reqBody = global.scenarioData[requestBodyReference]; const softAsseert = new SoftAssert(); const dataTableHashes = datatable.parse().hashes(); CucumberReportLogger.AddMessage("Request body in validation"); CucumberReportLogger.AddJson(reqBody); for(let i = 0; i < dataTableHashes.length; i++){ const matchValues = jsonpath.query(reqBody, dataTableHashes[i].pathExpression); softAsseert.setScenario(`Validate case field present in req body ${dataTableHashes[i].pathExpression}`); await softAsseert.assert(() => expect(matchValues.length > 0, `path ${dataTableHashes[i].pathExpression} not found in req body`).to.be.true); if (matchValues.length > 0){ softAsseert.setScenario(`Validate feidl valUe in req body ${dataTableHashes[i].pathExpression}`) await softAsseert.assert(() => expect(matchValues[0], `path ${dataTableHashes[i].pathExpression} not matching expected`).to.equal(dataTableHashes[i].value)); } } softAsseert.finally(); }); When('I click continue in event edit page', async function(){ await caseEditPage.clickContinue(); });
let patientName = 'Rahim Chacha'; // patientName = 'Fatema Khala'; console.log(patientName); let sum = 0; for(var i = 0; i < 10; i++){ sum = sum + i; } console.log(i);
var AuthmanFactory = artifacts.require("./AuthmanFactory.sol"); var AuthmanService = artifacts.require("./AuthmanService.sol"); var zeroAddress = '0x0000000000000000000000000000000000000000'; contract('AuthmanFactory', function(accounts) { var factory; var serviceAddress; var dataAddress; var account_one = accounts[0]; beforeEach('setup contract for each test', function () { return AuthmanFactory.deployed().then(function(instance) { factory = instance; return factory.newService({from: account_one}); }).then(function(instance) { console.log("dataAddress: " + JSON.stringify(instance.logs[0].args)); console.log("serviceAddress: " + JSON.stringify(instance.logs[1].args)); serviceAddress = instance.logs[1].args.serviceAddress; }); }); it("should create a valid new service", function() { return factory.getService.call().then(function(_serviceAddress) { serviceAddress = _serviceAddress; assert.notEqual(serviceAddress, zeroAddress, "Factory save service address cannot be zero."); return factory.getData.call(); }).then(function(_dataAddress) { dataAddress = _dataAddress; assert.notEqual(dataAddress, zeroAddress, "Factory data address cannot be zero."); assert.notEqual(dataAddress, serviceAddress, "Data and save service address cannot be equal."); }); }); /*it("should create authman with no phone", function() { /* AuthmanService service = AuthmanService(serviceAddress); var (_index, errorCode) = service.createOrUpdateAuthman(0x1, "titu","bhowmick","123456789","2000-12-31","1234"); if (dataAddress == address(0)) { dataAddress = factory.getData(); } AuthmanData dao = AuthmanData(dataAddress); address authmanAddress = dao.getAuthmanByIndex(_index); Assert.isNotZero(authmanAddress, "Authman address cannot be zero."); verifyAuthmanByAddress(true, false, authmanAddress, _index); verifyAuthman2ByAddress(true, authmanAddress); var service = AuthmanService.at(serviceAddress); return service.createOrUpdateAuthman('0x1', "titu","bhowmick","123456789","2000-12-31","1234", {from: account_one}) .then(function(instance) { }); return factory.getService.call().then(function(_serviceAddress) { serviceAddress = _serviceAddress; assert.notEqual(serviceAddress, zeroAddress, "Factory save service address cannot be zero."); return factory.getData.call(); }).then(function(_dataAddress) { dataAddress = _dataAddress; assert.notEqual(dataAddress, zeroAddress, "Factory data address cannot be zero."); assert.notEqual(dataAddress, serviceAddress, "Data and save service address cannot be equal."); }); });*/ });
class Item { build(socket) { socket.player.stone -= this.costs.stone; socket.player.wood -= this.costs.wood; socket.player.food -= this.costs.food; socket.player.buildCode = this.id; } constructor(id, use, buildable) { this.id = id; this.use = use; this.costs = { stone: 0, wood: 0, food: 0 } } } var items = []; items[0] = new Item(0, me => { // Apple var heal = 20; if (me.health === me.maxHealth) { return; } else if (me.health + heal > me.maxHealth) { // Only heal what is needed me.health = me.maxHealth; } else { me.health += heal; } me.buildCode = -1; }, false); items[0].costs.food = 20; module.exports = { Item: Item, items: items }
import styled from "@emotion/styled"; import React, { useMemo, useCallback } from "react"; const InputGroup = styled.div` label { margin-right: 1rem; } input { width: 4em; border-top-right-radius: 0; border-bottom-right-radius: 0; } select { border-top-left-radius: 0; border-bottom-left-radius: 0; padding-left: 0; } `; const BorderRadiusInput = ({ label, name, radius, baseWidth, onChange }) => { const value = useMemo(() => { const match = radius.match(/(\d*)(px|%)$/); return match?.[1] || 0; }, [radius]); const unit = useMemo(() => { const match = radius.match(/(\d*)(px|%)$/); return match?.[2] || "px"; }, [radius]); const changeRadiusValue = useCallback( (e) => { const { value } = e.target; onChange({ name, value: `${value}${unit}`, }); }, [name, unit, onChange] ); const changeUnitValue = useCallback( (e) => { const { value: unit } = e.target; onChange({ name, value: `${ unit === "px" ? (value * baseWidth) / 100 : (value / baseWidth) * 100 }${unit}`, }); }, [name, value, baseWidth, onChange] ); return ( <InputGroup> <label>{label}</label> <input type="number" min="0" value={value} onChange={changeRadiusValue} /> <select value={unit} onChange={changeUnitValue} tabIndex="-1"> <option value="px">px</option> <option value="%">%</option> </select> </InputGroup> ); }; export default BorderRadiusInput;
$(function(){ var ID = $('.topbar-info .ID'); if(!!sessionStorage.getItem('ID')){ var txt =sessionStorage.getItem('ID') ID.text(`欢迎:${txt}`); ID.href ="javascript:disabled"; }else{ ID.text('登录'); ID.href = "./login.html"; } })
const test = require('tape'); const arrayToHtmlList = require('./arrayToHtmlList.js'); test('Testing arrayToHtmlList', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof arrayToHtmlList === 'function', 'arrayToHtmlList is a Function'); t.pass('Tested by @chalarangelo on 16/02/2018'); //t.deepEqual(arrayToHtmlList(args..), 'Expected'); //t.equal(arrayToHtmlList(args..), 'Expected'); //t.false(arrayToHtmlList(args..), 'Expected'); //t.throws(arrayToHtmlList(args..), 'Expected'); t.end(); });
import './App.css'; import React from 'react'; import Hello from './components/Hello' class App extends React.Component { constructor(){ super() this.state = { // color: 'red', // show: true, func:'' } console.log('1') } componentDidMount(){ // console.log('2') // setTimeout(()=>{ // this.setState({color:'yellow'}) // }, 5000); } shouldComponentUpdate(){ return true //return false if you dont want any changes } componentDidUpdate(){ // const {color} = this.state; // // document.getElementById('new').innerHTML = // 'Current Color: ' + color } getSnapshotBeforeUpdate(prevProps, prevState){ // const {color} = this.state; // // Displaying the previous value of the state // // const news = document.getElementById('prev').innerHTML = // 'Previous Color Is: ' + prevState.color; // return news } render(){ // const {color} = this.state; // // console.log('3') // // const change = () =>{ // this.setState({color:'green'}) // } const info = () => { console.log('func') } const {func} = this.state; return ( <Hello func={info}/> //exersizes // <h1>my fav color is {color}</h1> // <button onClick={change}>press me</button> // <div id='prev'></div> // <div id='new'></div> // <h3>{show} ); } } export default App;
'use strict'; export default { USER_EXISTS: [10001, '用户已存在'], USER_NOT_EXISTS: [10002, '用户不存在'], PASSWORD_INVALID: [10003, '密码错误'], UPLOAD_ERR_TYPE: [20001, '上传文件类型错误'], LACK_APP_ID: [20002, '缺少app_id'], APP_NOT_EXIST: [20003, 'app_id对应的app不存在'], UPLOAD_EMPTY_FILE: [20004, '上传文件为空'], APP_NAME_NOT_EMPTY: [30001, 'app name不能为空'], APP_KEY_SECRET_ERROR: [30002, 'app key或secret错误,请检查'], APP_PACKAGE_NOT_MATCH: [30003, 'app package不匹配'] };
import * as Users from "resources/users" import calculatePanePosition from "helpers/calculate-pane-position" import uniqueID from "helpers/unique-id" export function createPane(tree, data) { const panesCreated = tree.get("panesCreated") const panesCursor = tree.select("panes") const attributes = Object.assign({ synched: true }, data, { paneID: uniqueID(), position: calculatePanePosition(panesCursor.get().length), creationOrder: panesCreated }) panesCursor.push(attributes) tree.set("panesCreated", panesCreated + 1) tree.commit() } export function bringPaneToFront(tree, index) { const panesCursor = tree.select("panes") const panes = panesCursor.get() const pane = Object.assign({}, panesCursor.get(index)) pane.minimized = false panesCursor.set(index, pane) // Skip panes that are already at the top. if (index !== panes.length - 1) { panesCursor.splice([index, 1]) panesCursor.push(pane) } tree.commit() } export function closePane(tree, index) { tree.select("panes").splice([index, 1]) tree.commit() } export function getPaneFromRoute(tree, username, entryID) { const create = createPane.bind(null, tree) const user = Users.recordsByUsername[username] if (typeof user === "undefined") { return create({ component: "Catastrophe", synched: false, applicationProps: { contentTitle: "SYNCHRONIZE ERROR" } }) } const entry = user.entries.find(e => e.id === entryID) if (typeof entry !== "undefined") { // Show entry. return create({ component: "Spectra", applicationProps: { prominent: true, body: entry.body, contentTitle: entry.contentTitle } }) } // Show entries index. create({ component: "Entries", applicationProps: { contentTitle: `${user.firstName}'s Holographs`, header: user.fullName, subHeader: user.description, entries: user.entries, username } }) } export function setPaneAttributes(tree, index, attributes) { const panesCursor = tree.select("panes") const panesCount = panesCursor.get().length const paneCursor = panesCursor.select(index) paneCursor.merge(attributes) tree.commit() function bringFirstVisiblePaneToFront(pane, index) { if (pane.minimized) return false bringPaneToFront(tree, index) return true } if (paneCursor.get("maximized")) { return bringPaneToFront(tree, index) } // The previous pane should take focus if this pane isn't visible. if (panesCount - 1 === index && panesCount > 1 && paneCursor.get("minimized")) { panesCursor.get() .slice() .reverse() // Reverse because the next desired pane is behind this one. .some(bringFirstVisiblePaneToFront) } }
import React from 'react' import BuildsData from 'components/builds/BuildsData' import BuildProfil from 'components-lib/buildProfil/BuildProfil' import BuildsList from 'components-lib/buildsList/BuildsList' import BuildInfos from 'components-lib/buildInfos/BuildInfos' import './Builds.scss'; /* This class was auto-generated by the JavaScriptWriter */ class Builds extends React.Component { constructor(props) { super(props); } componentWillMount() { BuildsData.register(this) } componentWillUnmount() { BuildsData.unregister() } render() { return ( <div className='sm-builds'> <div className="row sm-max-height"> <div className={"col-xs-12 " + (this.state.isExpanded ? "sm-hide" : "")}> <BuildsList/> </div> <div className={"col-xs-12 " + (this.state.isExpanded ? "sm-hide" : "")}> <BuildInfos/> </div> <div className={"col-xs-12 " + (this.state.isExpanded ? "sm-max-height" : "sm-builds-profil")}> <BuildProfil /> </div> </div> </div> ); } } export default Builds;
const styles = require('../styles') //Documentation for Phaser's (2.6.2) text:: phaser.io/docs/2.6.2/Phaser.Text.html class ChartLabel extends Phaser.Text { //initialization code in the constructor constructor(game, x, y, text) { super(game, x, y, text, styles.fonts.medium(game)); this.anchor.set(0.5, 0.5); } //Code ran on each frame of game update() {} } module.exports = ChartLabel;
const fs = require('fs'); const minimist = require('minimist'); const path = require('path'); const spawn = require('cross-spawn'); const copyTemplateFiles = require('./inc/copy-template-files'); const extract = require('./inc/extract'); const updatePakageScripts = require('./inc/update-package-scripts'); const appDirectory = fs.realpathSync(process.cwd()); const appPkg = require(path.resolve(appDirectory, 'package.json')); const helpText = ` Useage: $0 [options] Options: -h, --help Print usage Information. -t, --template Copy template files. -f, --force Forces copying of template files (will overwrite). -c, --campaign Campaign name (will default to package name). `; function spawnGenerate(variant) { const result = spawn.sync( 'node', [ path.resolve(__dirname, './generate'), variant ? `--variant=${variant}` : '--auto' ], { stdio: 'inherit', cwd: appDirectory } ); if (result.signal) { if (result.signal === 'SIGKILL') { console.log( 'The build failed because the process exited too early. ' + 'This probably means the system ran out of memory or someone called ' + '`kill -9` on the process.' ); } else if (result.signal === 'SIGTERM') { console.log( 'The build failed because the process exited too early. ' + 'Someone might have called `kill` or `killall`, or the system could ' + 'be shutting down.' ); } process.exit(1); } } async function main(argv) { if (argv.help) { console.log(helpText); } else { updatePakageScripts(appDirectory); await copyTemplateFiles(appDirectory, argv); const campaign = argv.campaign; const configDir = path.resolve(appDirectory, 'config'); const configFile = path.resolve(configDir, 'maxymiser-workflow.json'); const config = require(configFile); config.campaign = campaign; fs.writeFileSync(configFile, JSON.stringify(config, null, 2)); let variant; if (!argv.template && !argv.force) { let variants = await extract(); if (variants.length > 0) { variant = variants[0]; } } spawnGenerate(variant); } } const args = process.argv.slice(2); const argv = minimist(args, { boolean: ['force', 'help', 'template'], string: ['campaign'], default: { help: false, force: false, template: false, campaign: appPkg.name }, alias: { h: 'help', c: 'campaign', f: 'force', t: 'template' } }); main(argv);
const cp = process.cwd() + "/Controllers/"; const provinces = require(cp + "support/ProvincesController"); module.exports = function(fastify, opts, next) { fastify.get('/provinces', { preValidation: [fastify.auth] }, provinces.index) fastify.patch('/provinces/update', { preValidation: [fastify.auth] }, provinces.update) fastify.post('/provinces/store', { preValidation: [fastify.auth] }, provinces.store) fastify.delete('/provinces/destroy/:id', { preValidation: [fastify.auth] }, provinces.destroy) next(); };
Join = { web3Provider: null, contracts: {}, init: async function() { await Init.init(); Join.getAccountInfo(); }, getAccountInfo: function() { web3.eth.getAccounts(function(error,accounts){ Join.makeSelect(accounts); return Join.bindEvents(); }); }, makeSelect: function(list) { var html = ''; html += '<option value="">Select</a>'; for (var i = 0; i < list.length; i++) { html += '<option value="' + list[i] + '">' + list[i] + '</a>'; } $('.custom-select').html(html); }, bindEvents: function() { $(document).on('click', '.btn-facebook', Join.join); $(document).on('change', '#selectAccount', Join.changeSelect); }, changeSelect: function(){ var ether; var address = $('#selectAccount').val(); $('#address').text(address); web3.eth.getBalance(address, (err, balance) => { ether = parseInt(web3.utils.fromWei(balance, "ether")).toFixed(2); $('#etherValue').text(ether + " ETH"); }); Init.membershipInstance.getMemberInfo({from:address}).then(function (result) { if (result) { $('#register').html("<font color='green'><b>YES</b></font>"); } else { $('#register').html("<font color='red'>NO</font>"); } }).catch(function(error){ console.log(error); }); }, join: function(){ var address = $('#address').text(); Init.membershipInstance.registerMember({from:address}).then(function(result){ // console.log(result); alert("Successfully Register!"); $('#register').html("<font color='green'><b>YES</b></font>"); }).catch(function (error){ console.log(error); alert("Already Registered"); }); } }; $(function() { $(window).load(function() { Join.init(); }); });
import { gql } from 'apollo-server-micro'; export default gql` type Mutation { login(accessToken: String!): String! saveLetter( email: String! message: String! anonymous: Boolean! templateId: ObjectId! ): Letter sendThankYouMessage(message: String!, letterId: ObjectId!): Letter deleteLetter(letterId: ObjectId!): Boolean } `;
"use strict"; var twitterIcon = document.querySelector('.twiiter_icon'); var content = document.querySelector('.main_content_body'); var navButton = document.querySelector('.navButton'); var sideDrawerBtn = document.querySelector('.side_drawer_button'); twitterIcon.addEventListener("click", function () { document.getElementById("small_nav").style.transform = "translateX(0%)"; }); navButton.addEventListener("click", function () { document.getElementById("small_nav").style.transform = "translateX(-100%)"; }); content.addEventListener("click", function () { document.getElementById("small_nav").style.transform = "translateX(-100%)"; }); sideDrawerBtn.addEventListener("click", function () { document.getElementById("small_nav").style.transform = "translateX(0%)"; });
var util = require("util"); function Base() { this.name = "base"; this.base = 1991; this.say = function() { console.log("Hello "+this.name); }; } Base.prototype.showName = function(){ console.log(this.name); }; function Sub() { this.name = "sub"; } /* * 注意:Sub 仅仅继承了Base 在原型中定义的函数, * 而构造函数内部创造的 base 属 性和 sayHello 函数都没有被 Sub 继承。 * 同时,在原型中定义的属性不会被console.log 作 为对象的属性输出。 */ util.inherits(Sub,Base); var baseObj = new Base(); baseObj.showName(); baseObj.say(); console.log(baseObj); var subObj = new Sub(); subObj.showName(); //subObj.say():该方法无法调用,因为不属于原型 console.log(subObj);
// $(document).on("change", '#filter-form input[type="radio"]', function() { // var create_report_form_input = $('#create-monthly-report-form').find('#' + $(this).attr('id')); // create_report_form_input.prop('checked', true); // }); // // // $(document).on("change", '#filter-form select', function() { // var create_report_form_input = $('#create-monthly-report-form').find('#' + $(this).attr('id')); // create_report_form_input.val($(this).val()); // });
import '../stylesheets/javascript30.scss'; const controllers = document.querySelectorAll('.controller'); function handleValueUpdate() { const suffix = this.dataset.sizing || ''; document.documentElement.style.setProperty(`--${this.name}`, `${this.value}${suffix}` ); } controllers.forEach( controller => controller.addEventListener('change',handleValueUpdate) ); controllers.forEach( controller => controller.addEventListener('mousemove',handleValueUpdate) );
$('[data-toggle="popover"]').popover(); $('body').on('click', function (e) { $('[data-toggle="popover"]').each(function () { if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) { $(this).popover('hide'); } }); }); let rangeSlider = function () { let slider = $('.range-slider'), range = $('.range-slider-range'), value = $('.range-slider-value'); slider.each(function () { value.each(function () { let value = $(this).prev().attr('value'); $(this).html(value); }); range.on('input', function () { $(this).next(value).html(this.value); }); }); }; rangeSlider(); $("#chat_bg_remove_image").click(function() { chat_id = $(this).data("id"); $.ajax({ url: "/chat/" + chat_id + "/removebgimage", success: function(){ $("#chat_bg_image_preview").remove(); $("#chat_bg_remove_image").remove(); } }); }); $("#chat_title_font").change(function() { let selectedFont = $("#chat_title_font option:selected").val(); let iframeUrl = "../../fontpreview?font=" + selectedFont; $('iframe#chat_title_font_iframe').attr('src', iframeUrl); }).change(); $("#chat_username_font").change(function() { let selectedFont = $("#chat_username_font option:selected").val(); let iframeUrl = "../../fontpreview?font=" + selectedFont; $('iframe#chat_username_font_iframe').attr('src', iframeUrl); }).change(); $("#chat_msg_font").change(function() { let selectedFont = $("#chat_msg_font option:selected").val(); let iframeUrl = "../../fontpreview?font=" + selectedFont; $('iframe#chat_msg_font_iframe').attr('src', iframeUrl); }).change(); $('#chat_use_twitch_colors').click(function() { if ($(this).prop('checked') === true) { $('input[name=chat_username_color]').val('').addClass('disabled').attr('disabled', 'disabled').attr('readonly', 'readonly'); } else { $('input[name=chat_username_color]').removeClass('disabled').removeAttr('disabled').removeAttr('readonly'); } }); $('#chat_msg_twitch_colors').click(function() { if ($(this).prop('checked') === true) { $('input[name=chat_msg_color]').val('').addClass('disabled').attr('disabled', 'disabled').attr('readonly', 'readonly'); } else { $('input[name=chat_msg_color]').removeClass('disabled').removeAttr('disabled').removeAttr('readonly'); } }); $('#chat_text_shadow').click(function() { if ($(this).prop('checked') === true) { $('input[name=chat_text_shadow_color]').removeClass('disabled').removeAttr('disabled').removeAttr('readonly'); } else { $('input[name=chat_text_shadow_color]').val('').addClass('disabled').attr('disabled', 'disabled').attr('readonly', 'readonly'); } }); $('#chat_title_text_shadow').click(function() { if ($(this).prop('checked') === true) { $('input[name=chat_title_text_shadow_color]').removeClass('disabled').removeAttr('disabled').removeAttr('readonly'); } else { $('input[name=chat_title_text_shadow_color]').val('').addClass('disabled').attr('disabled', 'disabled').attr('readonly', 'readonly'); } }); $('#chat_template').change(function() { if ($(this).val() === '2') { $('#gradient-options').show(); } else { $('#gradient-options').hide(); } }).change(); //$('input, select, checkbox').change(function() { // document.getElementById('chat_preview_iframe').contentDocument.location.reload(true); //}).change();
//====================================================== // 出品するボタンを押したとき、銀行情報があるかいかを確認する //====================================================== $(document).on('click', '#js-bank_confirm', function (e) { e.preventDefault(); const msg = this.id === 'js-bank_confirm' ? '出品するためには、売上金の振込先である銀行情報等を登録していただく必要がございます。登録ページに遷移します。' : '売上金の振込先である銀行情報等が登録されておりません。登録ページに遷移します。' $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url: '/ajaxbankconfirm', type: 'get', dataType: 'json', }) // Ajaxリクエストが成功した場合 .done(function (data) { if (data[0] === false) { location.href = "/login"; }else if (data[1] === true) { location.href = "/products/new"; } else if (data[1] === false) { const result = window.confirm(msg); result && (location.href = "/mypage/edit"); } }) // Ajaxリクエストが失敗した場合 .fail(function (data) { const result = window.confirm(msg); result && (location.href = "/mypage/edit"); }); });
import React from 'react'; import { useQuery } from '@apollo/client'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Control from 'react-leaflet-control'; import { tablesEditingStatus as setEditingStatus } from '../../apollo/cache'; import { GET_EDITING_STATUS } from './requests'; import './index.css'; const TablesEditingControl = ({ stylization, position }) => { const { data, loading, error } = useQuery(GET_EDITING_STATUS); if (loading || error) return null; const { status } = data; return ( <Control position={position}> <div className={classNames('editing-tables-control', 'leaflet-control-layers', stylization)}> <button className="control-button" type="button" onClick={() => setEditingStatus(!status)}> <span>Редактировать столы</span> <i className={classNames('fas fa-edit', status && 'control-icon-focus')} /> </button> </div> </Control> ); }; TablesEditingControl.propTypes = { stylization: PropTypes.string, position: PropTypes.string }; TablesEditingControl.defaultProps = { stylization: '', position: 'topleft' }; export default TablesEditingControl;
import React, { Component } from 'react'; import { StyleSheet, View, Text, StatusBar, TouchableOpacity, Dimensions } from 'react-native'; import LinearGradient from 'react-native-linear-gradient'; import AsyncStorage from '@react-native-community/async-storage'; import firebase from 'react-native-firebase'; import { USER } from '../common/Constants'; import { StackActions, NavigationActions } from 'react-navigation'; import Spinner from '../common/Loading'; const { height, width } = Dimensions.get('window') export default class FirstScreen extends Component { constructor() { super() this.state = { spinner: true, // login: } // AsyncStorage.getItem('Login') // .then((value) => { // this.setState({ login: value }) // if (value == 1) // this.props.navigation.navigate('Profile') // }) } async componentDidMount() { const firebaseUser = firebase.auth().currentUser; console.log('firebaseUser', firebaseUser); if (firebaseUser) { let user = await AsyncStorage.getItem(USER); // console.log('user', user); if (user) { user = await JSON.parse(user); console.log('user First Screen', user); const resetAction = StackActions.reset({ index: 0, actions: [NavigationActions.navigate({ routeName: 'Drawer', params: { user } })], // actions: [NavigationActions.navigate({ routeName: 'Drawer', params: { user } })], }); this.props.navigation.dispatch(resetAction); } else { // firebase.auth().signOut(); // AsyncStorage.removeItem(USER) } } this.setState({ spinner: false }) } render() { const { spinner } = this.state; if (spinner) { return <Spinner /> } else { return ( <View> <StatusBar backgroundColor='#2c233d' barStyle="light-content" /> <View style={styles.basicBackground}> <View style={{ flexDirection: 'row' }}> <Text style={styles.header1}>C</Text> <Text style={styles.header2}>areer Hub</Text> </View> <View style={styles.background}> <Text style={styles.text}>How do you want {"\n"} to continue</Text> <View style={{ paddingTop: height * 0.01, paddingHorizontal: width * 0.01 }}> <TouchableOpacity onPress={() => { this.props.navigation.navigate('Login') // const user = firebase.auth().currentUser; // console.log('user', user); }}> <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} colors={['#5653e2', '#795EE3', '#ae71f2']} style={styles.linearGradient}> <Text style={styles.bottonText}>Log in</Text> </LinearGradient> </TouchableOpacity> <TouchableOpacity onPress={() => this.props.navigation.navigate('Indicator')}> <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} colors={['#5653e2', '#795EE3', '#ae71f2']} style={styles.linearGradient}> <Text style={styles.bottonText}>Sign up</Text> </LinearGradient> </TouchableOpacity> </View> <Text style={styles.subtittle}>Developed by career hub team</Text> </View> </View> </View> ); } }; } const styles = StyleSheet.create({ basicBackground: { backgroundColor: '#382d4b', height: '100%', width: '100%', alignItems: 'center', }, background: { backgroundColor: '#ffffff', height: '75%', width: '100%', borderTopStartRadius: 30, borderTopEndRadius: 30, alignItems: 'center', marginTop: height * 0.08, paddingTop: height * 0.1, }, header1: { color: '#ffffff', fontSize: 90, fontWeight: 'bold', marginTop: height * 0.09, }, header2: { color: '#ffffff', fontSize: 60, fontWeight: 'bold', marginTop: height * 0.125, }, text: { color: '#000000', fontWeight: 'bold', fontSize: 30, textAlign: 'center', }, linearGradient: { alignItems: 'center', justifyContent: 'center', borderRadius: 15, marginTop: height * 0.04, width: width * 0.75, height: height * 0.055, }, bottonText: { color: '#ffffff', fontSize: 20, fontWeight: 'bold', }, subtittle: { color: 'gray', fontSize: 15, marginTop: height * 0.15, } });
/** * @namespace */ vonline.Dialog = function(options) { this.options = this.getOptions(options); this.background = $('<div/>').addClass('dialog_background').appendTo('body'); this.container = $('<div/>').addClass('dialog_container').appendTo(this.background); this.content = $('<div/>').html(this.options.text).appendTo(this.container); this.buttons = $('<div/>').addClass('dialog_buttons').appendTo(this.container); this.createButtons(); this.options.init(); var that = this; function onResize() { that.container.css({ top: $('body').height() / 2 - that.container.outerHeight() + 'px', left: ($('body').width() - that.container.outerWidth()) / 2 + 'px' }); } onResize(); } vonline.Dialog.prototype.defaultOptions = {text: '', init: function() {}} vonline.Dialog.prototype.getOptions = function(options) { return $.extend({}, this.defaultOptions, options); } vonline.Dialog.prototype.createButtons = function() { var that = this; $('<button/>').addClass('dialog_cancel cancel').text('close').appendTo(this.buttons).click(function() { that.close(); }); } vonline.Dialog.prototype.close = function() { this.background.detach(); this.container.detach(); } /** * @namespace */ vonline.ConfirmDialog = function(options) { vonline.Dialog.apply(this, [options]); }; vonline.ConfirmDialog.prototype = new vonline.Dialog(); vonline.ConfirmDialog.prototype.defaultOptions = $.extend({}, vonline.Dialog.prototype.defaultOptions, {confirm: function() {}, cancel: function() {}}); vonline.ConfirmDialog.prototype.createButtons = function() { var that = this; this.cancel = $('<button/>').addClass('dialog_cancel cancel').text('cancel').appendTo(this.buttons).click(function() { that.close(); that.options.cancel(); }) this.submit = $('<button/>').addClass('dialog_ok ok').text('ok').appendTo(this.buttons).click(function() { that.close(); that.options.confirm(); }); function keyHandler (event) { event.stopPropagation(); if (event.keyCode == 13) { that.submit.triggerHandler('click'); $(window).unbind('keydown', keyHandler); $(window).unbind('keypress', keyHandler); } else if (event.keyCode == 27) { that.cancel.triggerHandler('click'); $(window).unbind('keydown', keyHandler); $(window).unbind('keypress', keyHandler); } } $(window).bind('keydown', keyHandler); $(window).bind('keypress', keyHandler); } /** * @namespace */ vonline.InputDialog = function(options) { var that = this; options = this.getOptions(options); var input = $('<input/>').attr({type: 'text', value: options.value}); options.text = $('<div/>').append($('<div/>').text(options.text)).append($('<div/>').html(input)); options.init = function() { input.focus(); that.submit.unbind('click'); that.submit.click(function() { that.close(); that.options.confirm(input.val()); }); } vonline.ConfirmDialog.apply(this, [options]); }; vonline.InputDialog.prototype = new vonline.ConfirmDialog(); vonline.InputDialog.prototype.defaultOptions = $.extend({}, vonline.ConfirmDialog.prototype.defaultOptions, {value: ''});
function objKeyCheck(keyToCheck, obj) { return keyToCheck in obj; } module.exports = objKeyCheck;
const data = { '2020-08-01': false, '2020-08-02': false, '2020-08-03': false, '2020-08-04': false, '2020-08-05': false, '2020-08-06': false, '2020-08-07': false, '2020-08-08': false, '2020-08-09': false, '2020-08-10': false, '2020-08-11': false, '2020-08-12': false, '2020-08-13': false, '2020-08-14': true, '2020-08-15': false, '2020-08-16': false, '2020-08-17': false, '2020-08-18': true, '2020-08-19': false, '2020-08-20': true, '2020-08-21': true, '2020-08-22': false, '2020-08-23': false, '2020-08-24': false, '2020-08-25': false, '2020-08-26': false, '2020-08-27': false, '2020-08-28': false, '2020-08-29': false, '2020-08-30': false, '2020-08-31': false, } module.exports = [ // get user info { url: '/admin/v1/calender/data', type: 'get', response: config => { return { code: 20000, data: { item: data } } } } ]
import React, { Component } from "react"; import Logo from './Thomas Krief Art Logo Noir.png'; class Header extends Component { state = { show: false } toggleMenu = () => { const doesShow = this.state.show; this.setState({ show: !doesShow }) } render() { return ( <div className="site-header"> <div className="site-header-wrapper"> <header className="main-header"> <div className="main-header-top"> <div className="main-header-center"> <div className="nav-menu d-none d-sm-none d-md-flex"> <div className="nav-menu-item"><a href="#Créations">CREATIONS</a></div> <div className="nav-menu-item"><a href="#Artiste">L'ARTISTE</a></div> <div className=""><img src={Logo} id="logo" alt="Logo" /> </div> <div className="nav-menu-item"><a href="#Biographie">BIOGRAPHIE</a></div> <div className=""> <a id="hire-me" href="mailto:thomas.krief@gmail.com" title="hire-me" className="btn-ghost"> Contactez-moi</a> </div> </div> <div className="mobile mobile-menu"> <div className="mobile-header"> <div className="menu-logo"><img src={Logo} id="logo" alt="Logo" /> </div> <div className="menu-toggle" onClick={this.toggleMenu}> <div className="line"></div> <div className="line"></div> <div className="line"></div> </div> </div> { this.state.show ? <div className="mobile-nav"> <div className="menu-toggle" onClick={this.toggleMenu}> <div className="line-active"></div> <div className="line-active"></div> <div className="line-active"></div> </div> <div className="mobile-nav-menu"> <h2 className="mobile-nav-title">Navigation</h2> <ul> <li><a href="#Créations" onClick={this.toggleMenu}>Créations</a></li> <li><a href="#Artiste" onClick={this.toggleMenu}>L'Artiste</a></li> <li><a href="#Biographie" onClick={this.toggleMenu}>Biographie</a></li> <li><a href="mailto:thomas.krief@gmail.com" onClick={this.toggleMenu}>Contact</a></li> </ul> </div> </div> : null } </div> </div> </div> </header> </div> </div> ); } } export default Header;
// Definindo variáveis const nome = "Silvana"; const sexo = "F"; const idade = 48; const contribuicao = 23; // Calculo para a regra 85-95 const aux = idade + contribuicao; if ((sexo === 'M' && contribuicao >= 35) || (sexo === 'F' && contribuicao >= 30)) { // Se o usuário tiver acima da tempo mínimo de contribuição. if ((sexo === 'M' && aux >= 95) || (sexo === 'F' && aux >= 85)) { // pode recerber a aposentadoria. console.log(`${nome}, você pode se aposentar!`); } else { // não pode receber a aposentadoria. console.log(`${nome}, você ainda não pode se aposentar!`); } } else { // Senão estiver acima do tempo mínimo de contribuição console.log(`${nome}, você ainda não pode se aposentar!`); }
var confige = require("confige"); cc.Class({ extends: cc.Component, properties: { }, onLoad: function () { console.log("onInit!!!!!!!!!!!!!!!!!!!!!!!"); }, onInit:function(){ confige.loadNode = this; cc.game.addPersistRootNode(this.node); this.pointItem = this.node.getChildByName("point"); this.progressBar = this.node.getChildByName("fileProgress").getComponent("cc.ProgressBar"); this.progressNum = this.node.getChildByName("fileProgress").getChildByName("fileNum").getComponent("cc.Label"); this.progressCount = 0; }, showNode:function(){ this.node.active = true; }, hideNode:function(){ this.pointItem.rotation = 0; this.node.active = false; this.progressBar.progress = 0; this.progressCount = 0; this.progressNum.string = ""; }, setProgress:function(percent,num){ this.pointItem.rotation = percent*1280; if(percent > this.progressCount) { this.progressBar.progress = percent; this.progressCount = percent; } // console.log("setProgress1111===="+percent); this.progressNum.string = parseInt(percent*100)+"%"; if(parseInt(percent*100) > 99) { this.hideNode(); } // console.log("setProgress333333===="+this.progressNum.string); }, });
function ProfilePicture(props) { // console.log(props.currentPicture) // onMouseOver not working yet :/ return( <div> <div>Profile Picture</div> <select defaultValue={props.currentPicture} onChange={props.onSelectProfilePicture}> <option value='0' onMouseOver={props.onHoverProfilePicture}>Dog Picture 0</option> <option value='1' onMouseOver={props.onHoverProfilePicture}>Dog Picture 1</option> <option value='2' onMouseOver={props.onHoverProfilePicture}>Dog Picture 2</option> <option value='3'>Dog Picture 3</option> <option value='4'>Dog Picture 4</option> </select> </div> ) } export default ProfilePicture
import React, { useEffect } from 'react' import Article from './Article/Article' import { Grid, Typography } from '@material-ui/core' import config from '../../api-config/config.json' import useFetchAll from '../../services/useFetchAll' import Spinner from '../UI/Spinner/Spinner' export default function ArticleList() { const { data, loading, error } = useFetchAll(config.articleUrls) const articlesData = data.map(dataItem => dataItem.searchResults.filter(item => item.name === 'Articles') .map(article => article.results).flat(2)) return ( <div> <Grid item xs={6} style={{ margin: '5px 0' }}> <Typography align='left' variant='h4' >Articles</Typography> </Grid> {loading ? <Spinner /> : articlesData.map(article => ( <Article key={article.name} {...article} /> ))} </div> ) }
import React from 'react'; import { rhythm } from '../utils/typography'; class Footer extends React.Component { render() { return ( <footer style={{ marginTop: rhythm(2.5), paddingTop: rhythm(1), }} > © {new Date().getFullYear()} {' '}&bull;{' '} <a href="https://mobile.twitter.com/samxeshun" target="_blank" rel="noopener noreferrer" > twitter </a>{' '} &bull;{' '} <a href="https://github.com/kwakueshun" target="_blank" rel="noopener noreferrer" > github </a>{' '} &bull;{' '} <a href="mailto:samuel.eshun13@gmail.com" target="_blank" rel="noopener noreferrer" > email </a>{' '} {' '} &bull;{' '} <a href="https://www.linkedin.com/in/samuel-eshun-84186075/" target="_blank" rel="noopener noreferrer" > linkedin </a>{' '} <div style={{ float: 'right' }}> <a href="/rss.xml" target="_blank" rel="noopener noreferrer"> rss </a> </div> </footer> ); } } export default Footer;
// @ts-check import axios from 'axios'; import React from 'react'; import update from 'immutability-helper'; import Item from './Item.jsx'; import routes from './routes.js'; // BEGIN (write your solution here) const compare = ( a, b ) => { if ( a.id > b.id ){ return -1; } if ( a.id < b.id ){ return 1; } return 0; } class TodoBox extends React.Component { constructor (props) { super (props); this.state = { text : '', tasks: [] }; } async componentDidMount () { const res = await axios.get(routes.tasksPath()); console.log(res.data); this.setState ({ tasks: res.data }); } onChangeText = async (e) => { const value = e.target.value; this.setState({ text: value }); } modifyTask = (task) => { const allTasks = this.state.tasks; const filtered = allTasks.filter (x=>x.id !== task.id); this.setState ({ tasks: [task, ...filtered] }); } onActivateTask = (id) => (e) => { console.log(`activate ${id}`); axios.patch(routes.activateTaskPath(id)) .then((response) => { //console.log(response.data) this.modifyTask (response.data); }); } onFinishTask = (id) => (e) => { console.log(`finish ${id}`); axios.patch(routes.finishTaskPath(id)) .then((response) => { // console.log(response.data) this.modifyTask (response.data); }); } handleSubmit = async (e) => { e.preventDefault (); const res = await axios.post(routes.tasksPath(), {text: this.state.text}); const tasks = this.state.tasks; this.setState ({ text: '', tasks: [res.data, ...tasks] }); } renderActiveTasks () { const active = this.state.tasks.filter (x=>x.state==='active').sort(compare); return active.length > 0 && <div className="todo-active-tasks"> {active.map (x=><Item key={x.id} state={x.state} onClick={this.onFinishTask(x.id)} text={x.text} id={x.id}/>)} </div>; } renderFinishedTasks () { const active = this.state.tasks.filter (x=>x.state==='finished').sort(compare); return active.length > 0 && <div className="todo-finished-tasks"> {active.map (x=><Item key={x.id} state={x.state} onClick={this.onActivateTask(x.id)} text={x.text} id={x.id}/>)} </div>; } render () { const text = this.state.text; return <div> <div className="mb-3"> <form onSubmit={this.handleSubmit} className="todo-form form-inline mx-3"> <div className="form-group"> <input type="text" onChange = {this.onChangeText} value={text} required={true} className="form-control mr-3" placeholder="I am going..."/> </div> <button type="submit" className="btn btn-primary">add</button> </form> </div> {this.renderActiveTasks()} {this.renderFinishedTasks()} </div>; } } export default TodoBox; // END
// @flow class Status { // Getting access to status codes constants static SUCCESS = 200; static CREATED = 201; static CONFLICT = 409; static INVALID = 400; static NOT_AUTHORIZED = 401; static FORBIDDEN = 403; static NOT_FOUND = 404; /** * Check if the api status code is 200 or 201 * @param {number} statusCode api status code * @returns {boolean} */ static isSuccess = (statusCode: number): boolean => { if (statusCode === Status.SUCCESS || statusCode === Status.CREATED) { return true; } return false; }; /** * Check if the api status code is 409 * @param {number} statusCode api status code * @returns {boolean} */ static isConflict = (statusCode: number): boolean => { if (statusCode === Status.CONFLICT) { return true; } return false; }; /** * Check if the api status code is 400 * @param {number} statusCode api status code * @returns {boolean} */ static isInvalid = (statusCode: number): boolean => { if (statusCode === Status.INVALID) { return true; } return false; }; /** * Check if the api status code is 401 * @param {number} statusCode api status code * @returns {boolean} */ static isNotAuthorized = (statusCode: number): boolean => { if (statusCode === Status.NOT_AUTHORIZED) { return true; } return false; }; /** * Check if the api status code is 403 * @param {number} statusCode api status code * @returns {boolean} */ static isForbidden = (statusCode: number): boolean => { if (statusCode === Status.FORBIDDEN) { return true; } return false; }; /** * Check if the api status code is 404 * @param {number} statusCode api status code * @returns {boolean} */ static isNotFound = (statusCode: number): boolean => { if (statusCode === Status.NOT_FOUND) { return true; } return false; }; } export default Status;
const { Schema, model } = require("mongoose"); let RequestSchema = new Schema({ requested: { type: Schema.Types.ObjectId, ref: 'user' }, searcher: { type: Schema.Types.ObjectId, ref: 'user' }, status: { type: String, default: 'pending' }, request_date: Date, message: String, requested_talent: String }); //define model let RequestModel = model('request', RequestSchema); //export model module.exports = RequestModel;
'use strict'; import * as chai from 'chai'; const chaiAsPromised = require('chai-as-promised'); const chaiThings = require('chai-things'); const expect = chai.expect; import * as sinon from 'sinon'; import * as sinonAsPromised from 'sinon-as-promised'; const sinonChai = require('sinon-chai'); const awsMock = require('aws-sdk-mock'); const AWS = require('aws-sdk'); import { EmailQueue } from './email_queue'; import { EnqueuedEmail } from './enqueued_email'; import { SendEmailService } from './send_email_service'; import * as sqsMessages from './sqs_receive_messages_response.json'; chai.use(sinonChai); chai.use(chaiAsPromised); chai.use(chaiThings); describe('SendEmailService', () => { let sqsClient; let email; let queue; const lambdaContext = { functionName: 'lambda-function-name', getRemainingTimeInMillis: () => {} }; let contextStub; let lambdaClient; before(() => { awsMock.mock('SQS', 'receiveMessage', sqsMessages); awsMock.mock('SQS', 'deleteMessage', { ResponseMetadata: { RequestId: 'e21774f2-6974-5d8b-adb2-3ba82afacdfc' } }); sqsClient = new AWS.SQS(); queue = new EmailQueue(sqsClient, { url: 'https://some_url.com'}); contextStub = sinon.stub(lambdaContext, 'getRemainingTimeInMillis').returns(100000); awsMock.mock('Lambda', 'invoke', 'ok'); awsMock.mock('SNS', 'publish', 'ok'); lambdaClient = new AWS.Lambda(); }); describe('#sendBatch()', () => { context('when there are messages in the queue', () => { let senderService; const emailHandles = sqsMessages.Messages.map((message) => { return {ReceiptHandle: message.ReceiptHandle, Id: message.MessageId}; }); before(() => { senderService = new SendEmailService(queue, null, contextStub); awsMock.mock('SES', 'sendEmail', { MessageId: 'some_message_id' }); }); it('returns the sent emails message handles', (done) => { expect(senderService.sendBatch()).to.eventually.deep.have.members(emailHandles).notify(done); }); it('publish an SNS message for every sent email', (done) => { senderService.snsClient.publish.reset(); senderService.sendBatch().then(() => { expect(senderService.snsClient.publish).to.be.calledOnce; const snsParams = senderService.snsClient.publish.lastCall.args[0]; const snsPayload = JSON.parse(snsParams.Message); for (let sentEmail of snsPayload) { expect(sentEmail).to.have.property('messageId'); expect(sentEmail).to.have.property('campaignId'); expect(sentEmail).to.have.property('listId'); expect(sentEmail).to.have.property('recipientId'); expect(sentEmail).to.have.property('status'); } done(); }).catch(done); }); it('delivers all the emails', (done) => { sinon.spy(senderService, 'deliver'); senderService.sendBatch().then(() => { expect(senderService.deliver.callCount).to.equal(emailHandles.length); senderService.deliver.restore(); done(); }); }); context('when the sending rate is exceeded', () => { before(() => { sinon.stub(senderService, 'deliver').rejects({code: 'Throttling', message: 'Maximum sending rate exceeded'}); }); it('should leave the message in the queue', done => { senderService.sendBatch().then(() => { const emailsToDelete = JSON.parse(senderService.snsClient.publish.lastCall.args[0].Message); expect(emailsToDelete.length).to.equal(0); done(); }); }); after(() => senderService.deliver.restore()); }); context('when the message is rejected', () => { before(() => { const deliverStub = sinon.stub(senderService, 'deliver'); deliverStub .onFirstCall().resolves({ MessageId: 'some_message_id' }) .onSecondCall().rejects({code: 'MessageRejected'}); }); it('should stop the execution', done => { senderService.sendBatch().catch(err => { expect(err).to.deep.equal({code: 'MessageRejected'}); const emailsToDelete = JSON.parse(senderService.snsClient.publish.lastCall.args[0].Message); expect(emailsToDelete.length).to.equal(1); done(); }); }); after(() => senderService.deliver.restore()); }); context('when the daily quota is exceeded', () => { before(() => { sinon.stub(senderService, 'deliver') .onFirstCall().resolves({ MessageId: 'some_message_id' }) .onSecondCall().rejects({code: 'Throttling', message: 'Daily message quota exceeded'}); }); it('should stop the execution', done => { senderService.sendBatch().catch(err => { expect(err).to.have.property('code', 'Throttling'); const emailsToDelete = JSON.parse(senderService.snsClient.publish.lastCall.args[0].Message); expect(emailsToDelete.length).to.equal(1); done(); }); }); after(() => senderService.deliver.restore()); }); context('when an unexpected error occurs', () => { before(() => { sinon.stub(senderService, 'deliver').rejects({code: 'SomethingUnexpected'}); }); it('should delete the message from the queue', done => { senderService.sendBatch().then(emailsToDelete => { const emailsToSave = JSON.parse(senderService.snsClient.publish.lastCall.args[0].Message); expect(emailsToSave.length).to.equal(0); expect(emailsToDelete.length).to.equal(emailHandles.length); done(); }); }); after(() => senderService.deliver.restore()); }); after(() => { awsMock.restore('SES'); }); }); }); describe('#sendNextBatch()', () => { context('when there is time for a new batch', () => { it('gets a new batch and delivers it', (done) => { const senderService = new SendEmailService(queue, lambdaClient, contextStub); done(); }); }); }); describe('#deliver()', () => { before(() => { awsMock.mock('SES', 'sendRawEmail', { MessageId: 'some_message_id' }); const sqsMessage = sqsMessages.Messages[0]; email = new EnqueuedEmail(JSON.parse(sqsMessage.Body), sqsMessage.ReceiptHandle); sinon.stub(email, 'toSesRawParams').resolves('test data'); }); it('sends the email', (done) => { const senderService = new SendEmailService(queue, null, contextStub); const emailClient = senderService.setEmailClient(email); senderService.deliver(email).then(res => { expect(emailClient.sendRawEmail).to.have.been.calledOnce; expect(emailClient.sendRawEmail).to.have.been.calledWith('test data'); done(); }).catch(done); }); after(() => { awsMock.restore('SES'); }); }); after(() => { awsMock.restore('SQS'); awsMock.restore('SNS'); awsMock.restore('Lambda'); contextStub.restore(); }); });
/*TODO 对象模板(构造函数) function Storage(){ this.length = 10; this.setItem = function(){} }*/ /*TODO 创建 Storage 的两个对象 window.sessionStorage = new Storage(); window.localStorage = new Storage(); */
export default function useTemplate() { return 'You are using the default template.' }
"use strict"; var Item = require('../models/models').Item; var _ = require('lodash'); var items = { crear: function(req, res) { var nuevoItem = { _id : req.body._id, descripcion : req.body.descripcion, costo : req.body.costo, precioMin : req.body.precioMin, precioMax : req.body.precioMax, existencia : req.body.existencia, disponible : req.body.disponible, material : req.body.material, categoria : req.body.categoria }; Item.create(nuevoItem, function(err, item){ if (err) return res.status(500).json({ msg: 'error interno en la base de datos', error: err }); res.status(201).json({ msg: 'item creado', item: item }); }); }, // fin crear actualizar: function(req, res) { var itemData = {}; var itemId = req.params.itemId; // recorre el objeto req.body en busca de campos para llenar el objeto itemData _.forOwn(req.body, function(val, key) { if (key) itemData[key] = val; }); Item.update({ _id: itemId }, { $set: itemData }, function(err) { if(err) return res.status(500).json({ msg: 'error interno en la base de datos actualizando item', error: err }); res.status(200).json({ msg: 'item actualizado' }); }); // fin Item.update }, // fin actualizar borrar: function(req, res) { Item.remove({ _id: req.params.itemId }, function(err) { if(err) return res.status(500).json({ msg: 'error interno en la base de datos borrando item', error: err }); res.status(204).json({ msg: 'item removido' }); }); }, // fin borrar obtenerTodos: function(req, res) { Item .find({}) .select('-__v') .exec(function(err, items) { if (err) return res.status(500).json({ msg: "error interno en la base de datos obteniendo items", error: err }); if (!items) return res.status(404).json({ msg: 'no se encontraron items requeridos' }); res.status(200).json({ items: items }); }); }, obtenerQuery: function(req, res) { var id = req.query.id, categoria = req.query.categoria, material = req.query.material; if (id) { Item .findById({ _id: id }) .select('-__v') .exec(function(err, item) { if (err) return res.status(500).json({ msg: 'error interno en la base de datos obteniendo item', error: err }); if (!item) return res.status(404).json({ msg: 'no se encontro el item requerido' }); res.status(200).json({ item: item }); }); } else if (categoria) { Item .find({ categoria: categoria }) .select('-__v') .exec(function(err, items) { if (err) return res.status(500).json({ msg: 'error interno en la base de datos obteniendo items', error: err }); if (!items.length) return res.status(404).json({ msg: 'no se encontraron los items requeridos' }); res.status(200).json({ items: items }); }); } else if (material) { Item .find({material: material}) .select('-__v') .exec(function(err, items) { if (err) return res.status(500).json({ msg: 'error interno en la base de datos obteniendo items', error: err }); if (!items.length) return res.status(404).json({ msg: 'no se encontraron los items requeridos' }); res.status(200).json({ items: items }); }); } else { return res.status(400).json({ msg: 'peticion mal formulada' }); } } // fin obtenerQuery }; // fin items module.exports = items;
'use strict'; const FileChecker = require('./file-checker'); const SpellChecker = require('./index'); const path = require('path'); const pathToDict = path.resolve(path.join(__dirname, './dictionaries')); class FakeReporter { constructor() { this.entries = []; } push(entry) { console.log(entry); this.entries.push(entry); } } module.exports = class { constructor(dictionaryName, pathToDictionary = pathToDict) { const fakeReporter = new FakeReporter(); const pushFunction = fakeReporter.push.bind(fakeReporter); const spellChecker = new SpellChecker(pushFunction, pathToDictionary, dictionaryName); const fileChecker = new FileChecker(spellChecker); this.fileChecker = fileChecker; } processFiles(files) { return this.fileChecker.checkFiles(files); } };
const apiKey = '1adbf2cc'; const getRate = async (id) => { const url = `https://www.omdbapi.com/?i=${id}&apikey=${apiKey}`; const res = await window.fetch(url); if (!res.ok) throw new Error(res.status); const data = await res.json(); return data.imdbRating; }; const getSearchResults = async (searchValue, page) => { const url = encodeURI( `https://www.omdbapi.com/?s=${searchValue.trim()}&page=${page}&apikey=${apiKey}` ); const res = await window.fetch(url); if (!res.ok) throw new Error(res.status); const {Search, totalResults, Response} = await res.json(); if (Response === 'True') { const ratings = await Promise.all(Search.map(({imdbID}) => getRate(imdbID))); return { data: Search.map((movie, index) => ({...movie, rating: ratings[index]})), totalResults, page, }; } return { data: [], totalResults: 0, page, }; }; const getSearchTranslation = async (searchText) => { const url = encodeURI( `https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20200425T170620Z.55c8b9394267ab3a.3447d744700d3f2e8e6216551e211e2089052f54&lang=ru-en&text=${searchText}` ); const res = await window.fetch(url); if (!res.ok) throw new Error(res.status); const data = await res.json(); return data.text[0]; }; export default { getSearchResults, getSearchTranslation, };
/** * LINKURIOUS CONFIDENTIAL * Copyright Linkurious SAS 2012 - 2018 * * - Created on 2015-06-29. */ 'use strict'; /** * A generic parser to cleanly remove/retrieve string literals from strings, while respecting escaping. * * @param {string[]} delimiters the string literal delimiters (e.g. [', "] * @param {string} escapeChar the escape character (e.g. \) * @constructor LiteralsParser */ function LiteralsParser(delimiters, escapeChar) { // index the delimiters this.delimiters = {}; delimiters.forEach(d => { this.delimiters[d] = true; }); this.escapeChar = escapeChar; // don't allow for any state persistence, this class must be purely static Object.freeze(this); } /** * Remove string literals * * @param {string} s a string to remove literals from * @returns {string} a copy of the input with string literals removed */ LiteralsParser.prototype.removeLiterals = function(s) { const result = []; let afterEscape = false, inLiteral = null, char; for (let i = 0, l = s.length; i < l; ++i) { char = s[i]; if (afterEscape) { // previous char was an escape char if (inLiteral === null) { result.push(char); } afterEscape = false; continue; } // not after an escape char if (char === this.escapeChar) { // current char is a escape char if (inLiteral === null) { result.push(char); } afterEscape = true; continue; } // not at or after an escape char if (this.delimiters[char]) { // current char is a delimiter if (inLiteral === null) { // not yet in a literal? we are now inLiteral = char; continue; } else if (inLiteral === char) { // already in a literal that started with the same char we are on? end of literal inLiteral = null; continue; } } // at a normal char if (inLiteral === null) { result.push(char); } } return result.join(''); }; /** * Get all string literals * * @param {string} s a string to get the literals from * @returns {string[]} literals */ LiteralsParser.prototype.retrieveAllLiterals = function(s) { let currentLiteral = null; const result = []; let afterEscape = false; let currentDelimiter = null; for (let i = 0, l = s.length; i < l; ++i) { const char = s[i]; // if i'm not in a literal and the char isn't a delimiter if (currentLiteral === null && !this.delimiters[char]) { // do nothing continue; } // if i'm not in a literal and the char is a delimiter if (currentLiteral === null && this.delimiters[char]) { // enter in a literal currentLiteral = ''; currentDelimiter = char; continue; } // If I'm here, I'm in a literal // Previous char was an escape character if (afterEscape) { // char was escaped, so it's part of the literal currentLiteral += char; afterEscape = false; continue; } // If I'm here, I'm in a literal and the previous character wasn't an escape // Current character is the same delimiter that started the literal if (currentDelimiter === char) { result.push(currentLiteral); currentDelimiter = null; currentLiteral = null; continue; } // Current character is an escape if (char === this.escapeChar) { if (currentLiteral !== null) { afterEscape = true; } continue; } currentLiteral += char; } return result; }; module.exports = LiteralsParser;
var btnRegister = document.forms['register-form']['btn-register']; btnRegister.onclick = function() { var firstName = document.forms['register-form']['firstName'].value; var lastName = document.forms['register-form']['lastName'].value; var password = document.forms['register-form']['password'].value; var address = document.forms['register-form']['address'].value; var phone = document.forms['register-form']['phone'].value; var avatar = document.forms['register-form']['avatar'].value; var gender = document.forms['register-form']['gender'].value; var email = document.forms['register-form']['email'].value; var birthday = document.forms['register-form']['birthday'].value; var obj = { 'firstName': firstName, 'lastName': lastName, 'password': password, 'address': address, 'phone': phone, 'avatar': avatar, 'gender': gender, 'email': email, 'birthday': birthday, }; var jsonObj = JSON.stringify(obj); var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 201) { var responseObj = JSON.parse(this.responseText); console.log(responseObj); alert('Register Success!'); window.location.href = 'login.html' } else { alert('Register Failed!'); window.location.reload(true); } } else { console.log('Bad Request!!!'); } } xmlHttpRequest.open('POST', 'https://2-dot-backup-server-002.appspot.com/_api/v2/members'); xmlHttpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlHttpRequest.send(jsonObj); }
import requestCreator from 'core/helpers/request'; import { AuthStore } from 'src/modules/auth'; import userModule from 'src/modules/user'; import Common from '../stores/common'; import Ui from '../stores/ui'; // All our actions are listed here export const storesCreator = (state = {}, accessToken) => { function getBasicAuth(clientId, clientSecret) { return btoa(`${clientId}:${clientSecret}`); } const { common } = state; const basicAuthorization = `Basic ${getBasicAuth(common.clientId, common.clientSecret)}`; const request = requestCreator(state.common.backend, { basicAuthorization, accessToken, }); const storages = { common: new Common(request, state.common), auth: new AuthStore(request, state.user), user: new userModule.Store(request, state.user), ui: new Ui(state.ui), }; return storages; }; // Initialize actions and state export default process.env.BROWSER ? storesCreator(window.__STATE) : {};
var app = angular.module('plunker', ['chart.js']); app.controller('MainController', function($scope, $http) { var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var cw=canvas.width; var ch=canvas.height; var line = document.getElementById("line"); var ctx1 = line.getContext("2d"); console.log(ctx1); Chart.defaults.global.animation = false; Chart.defaults.global.scaleFontSize = 28; Chart.defaults.Line.pointDotRadius = 15; console.log(Chart.defaults.global); console.log(Chart.defaults.Line); var tx_data = []; var rx_data = []; // $scope.labels = ["January", "February", "March", "April", "May", "June", "July"]; $scope.series = ["TX", "RX"]; // $scope.fillColor = "rgba(255,0,0,0.2)", // $scope.strokeColor = "rgba(255,0,0,1)", // $scope.pointColor = "rgba(255,0,0,1)", // $scope.data = [ // [65, 59, 80, 81, 56, 55, 40] // ]; $scope.onClick = function (points, evt) { console.log(points, evt); }; var it = 0; var label = []; setInterval(function() { $http.get('/networkStats').success(function(res) { tx_data.push(res.tx); rx_data.push(res.rx); if(tx_data.length > 100) { tx_data.shift(); rx_data.shift(); label.shift(); } label.push( (it++).toString()); console.log(label, res.tx); $scope.opts = { "fillColor": "rgba(255,0,0,0.2)", "strokeColor": "rgba(255,0,0,1)", "pointColor": "rgba(255,0,0,1)", "pointStrokeColor": "#fff", "pointHighlightFill": "#fff", "pointHighlightStroke": "rgba(255,0,0,1)" } // it++; $scope.data = [ tx_data, rx_data ]; $scope.labels = label; }); }, 1000); $scope.routes = null; var routes = null; var m = []; var previousNum; var callAgain = 0; var active = 'NO' $scope.sixlbrConfig = null; $scope.nvm_data = null $http.get('/sixlbrConfig').success(function(res) { $scope.sixlbrConfig = res; $scope.nvm_data = res.nvm_data; }); $scope.pushSixlbrConfig = function() { console.log($scope.sixlbrConfig); var sixlbrConfig = $scope.sixlbrConfig; sixlbrConfig.nvm_data = $scope.nvm_data; $http.post('/updateSixlbrConfig', sixlbrConfig).then(function(resp) { console.log('update successful - ', resp); }, function(err) { console.error('http post- updateSixlbrConfig failed ', err); }); } $scope.isNumber = function(val) { return typeof val == 'number' } // this.interval = setInterval(function(){ function getRoutes() { $http.get('/routes').success(function(res) { ctx.clearRect(0, 0, cw, ch); $scope.routes = res; routes = res; active = 'Yes'; var root_x = 700; var root_y = 700; var radius = 5; var font = "10px Arial"; var factor = 30; ctx.beginPath(); ctx.arc(root_x, root_y, radius*2, 0, 2 * Math.PI); ctx.fillStyle="blue"; ctx.fill(); function drawEdge(to, from, ln) { ctx.beginPath(); ctx.lineJoin="round"; ctx.moveTo(to.x,to.y); ctx.lineTo(from.x,from.y); ctx.fillText(ln, (to.x + from.x) / 2, (to.y + from.y ) / 2); ctx.stroke(); } var numOfNodes = Object.keys(routes).length; var directlyConnected = 0; if(previousNum != numOfNodes) { m = []; previousNum = numOfNodes; } var deg = 360/numOfNodes; var x = (3.14/180)*deg; //radians var n = 0; var ln = 5; console.log('ROUTES: ', routes); Object.keys(routes).forEach(function(node, n, array) { var via = routes[node].parentId; //alternate length if((n % 2) == 0) { ln = 12; } else { ln = 20; } if(typeof m[node] == 'undefined') { m[node] = []; m[node][0] = ln * Math.cos(n*x) * factor + root_x; m[node][1] = ln * Math.sin(n*x) * factor + root_y; } // console.log('vertice: ', m[node] + ' n: ', n + ' ln: ', ln + ' node: ', node); var parent = {}; // console.log('via: ', via); if(via === node) { //connected directly to root directlyConnected++; parent = { x: root_x, y: root_y } } else { //connected to via if(typeof m[via] != 'undefined' ) { parent = { x: m[via][0], y: m[via][1] } } else { } } // console.log('parent: ', parent); ctx.beginPath(); ctx.arc(m[node][0], m[node][1], radius, 0, 2 * Math.PI); ctx.fillStyle="red"; ctx.fill(); ctx.font= font; ctx.fillStyle="black"; ctx.fillText(node, m[node][0] - 3*radius , m[node][1] + 4*radius); // ctx.fillText('rank: ' + routes[node].data['rank'], m[node][0] - 4*radius , m[node][1] + 6*radius + 2*radius) Object.keys(routes[node].data).forEach(function(key, index, array) { ctx.fillText(key + ': ' + routes[node].data[key], m[node][0] - 4*radius , m[node][1] + 6*radius + index*2*radius) }) ctx.font= "30px Arial"; ctx.fillText('Active Nodes: ' + numOfNodes, 1500 , 700) if(n == array.length - 1) { ctx.fillText('Directly Connected: ' + directlyConnected, 1500 , 725); callAgain = 1; } ctx.stroke(); drawEdge(parent, {x: m[node][0], y: m[node][1]}, ''); if(callAgain) { // active = 'No' callAgain = 0; setTimeout(function() { getRoutes(); }, 1000) } }); }); } getRoutes(); // setInterval(function() { // ctx.beginPath(); // ctx.font= "30px Arial"; // ctx.fillStyle="black"; // ctx.fillText('Active: ' + active, 1500 , 750) // ctx.stroke(); // }, 100); // setInterval(function() { // active = 'No'; // }, 2000); // }, 1000); });
var _viewer = this; /* * 删除前方法执行 */ rh.vi.listView.prototype.beforeDelete = function(pkArray) { showVerify(pkArray,_viewer); };
import * as sectionApi from '@/module/project-manage/api/section' import * as sysApi from '@/base/api/user' const state = { allSections: [], sections: [], total:0, // 标段详情数据 list:{ id: { value: '', label: 'id', hidden: true }, delFlag: { value: '', label: '其他标段', hidden: true }, itemId : { value: '', label: '所属项目', hidden: true }, sectionTitle: { value: '', label: '标段名称', disabled: false, list: null, isDate: null }, origin: { value: null, label: '起点', disabled: false, list: null, isDate: null }, terminus: { value: null, label: '终点', disabled: false, list: null, isDate: null }, disDirectors: { value: [], label: '配施人员', list: [], listKey: 'id', listLabel: 'nickName', listLabel2: 'jobNumber', isDate: null, filterable: true, clearable: true, multiple: true, disabled: false, }, constructionUnit: { value: null, label: '施工单位', disabled: false, list: null, isDate: null }, supervisorUnit: { value: null, label: '监理单位', disabled: false, list: null, isDate: null }, startTime: { value: null, label: '开工日期', format: 'yyyy-MM-dd HH:mm:ss', disabled: false, list: null, isDate: true, type: 'date' }, endTime: { value: null, label: '竣工日期', format: 'yyyy-MM-dd HH:mm:ss', disabled: false, list: null, isDate: true, type: 'date' }, comment: { value: null, label: '备注', disabled: false, list: null, isDate: null }, }, } // 格式化 const getters = { sectionEnumFormat: (state) => (key) => { for (let item of state.allSections) { if (item.id === key) { return item.sectionTitle } } return null }, } // 初始化 const actions = { initList ({ commit }, {id, action}) { sectionApi.getById(id).then(re => { commit('setList', re.result) if (action !== undefined) { action() } }) }, initSections ({ commit },itemId) { sectionApi.findByItemId(itemId).then(re => { commit('setAllSections', re.result) }) }, initSectionsByParam ({ commit },param) { sectionApi.getByCondition(param).then(re => { commit('setSections', re.result.content) commit('setSectionTotal', re.result.totalElements) }) }, // 给菜单下拉框初始化 initUsers ({ commit }) { sysApi.findAllUser().then(res => { commit('setUsers', res.result) }) }, } // 取值 const mutations = { setList: (state, list) => { for (let i in state.list) { if (i==='disDirectors') { if (typeof list[i] == 'string') state.list[i].value = list[i].split(',') else state.list[i].value = [] } else state.list[i].value = list[i] } }, setUsers: (state, users) => { state.list.disDirectors.list = JSON.parse(JSON.stringify(users)) }, setAllSections: (state, sections) => { state.allSections = sections }, setSections: (state, sections) => { state.sections = sections }, setSectionTotal: (state, total) => { state.total = total }, } export default { namespaced: true, state, getters, actions, mutations }
var maze; function setup() { createCanvas(CELLS_ACROSS * CELL_SIZE + STROKE_WEIGHT, CELLS_DOWN * CELL_SIZE + STROKE_WEIGHT); maze = new Maze(CELLS_ACROSS, CELLS_DOWN); rectMode(CORNERS); strokeWeight(STROKE_WEIGHT); } function draw() { maze.step(); background(128); maze.draw(); }
document.addEventListener('init', function (event) { var page = event.target; if (page.id === 'BasketPage') { } else if (page.id === 'OrderPage') { backBasket(); } }); const getBasketForUser = (user) => { $("#showBasket").empty(); var countItem = 0; db.collection("Pets").get().then(function (querySnapshot) { querySnapshot.forEach(function (doc) { if (doc.data().Basket.includes(user.uid)) { const result = /*html*/ ` <div class="borderItem"> <ons-row class="d-flex justify-content-center align-items-center mt-2"> <img class="BasketPets" src="${doc.data().photoURL}" id="${doc.data().Breed}" width="170" height="140"> <div class="ml-2"> <div class="title-basket">Breed : ${doc.data().Breed}</div> <div class="title-basket">Breeder : ${doc.data().Breeder}</div> <ons-row class="d-flex justify-content-between" style="color: rgb(255, 0, 0);"> <div class="title-basket">ราคา :</div> <div class="title-basket">${doc.data().Price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")} บาท</div> </ons-row> <div class="justify-content-between mt-2"> <button class="btn button_color btn-xs confirmOrder" id="${doc.data().Breed}">ยืนยัน</button> <button class="btn button_color_Delete btn-xs" onclick="deleteBasket('${doc.id}','${doc.data().Breed}')">ลบออก</button> </div> </div> </ons-row> </div> ` $("#showBasket").append(result) countItem++; } }); if (countItem == 0) { const result = /*html*/ ` <div class="text-center mt-5 noBasket"> No Basket Now </div> ` $("#showBasket").append(result) } $(".BasketPets").click(function () { const Breed = $(this).attr('id'); basketSelectPets(Breed) document.querySelector("#Navigator_basket").pushPage('views/Basket/SelectBasket.html'); }) $(".confirmOrder").click(function () { const Breed = $(this).attr('id'); orderPage(Breed) document.querySelector("#Navigator_basket").pushPage('views/Basket/Order.html'); }) }); } const basketSelectPets = (Breed) => { db.collection("Pets").where("Breed", "==", Breed).get().then(function (querySnapshot) { querySnapshot.forEach(function (doc) { const result = /*html*/ ` <div class="containerSelect text-center" style="background-color:white; margin:0.70rem;"> <img src="${doc.data().photoURL}" width="60%" height="200px"> </div> <div class="textSelect"> <div><b>Breed</b> : ${doc.data().Breed}</div> <div><b>Breeder</b> : ${doc.data().Breeder}</div> <div><b>location</b> : ที่อยู่ : 0/23 ถนน.14 sector 3 เขตครึ่งเสี้ยวหลัง ดวงจันทร์</div> <div><b>Daddy</b> : ${doc.data().Daddy} </div> <div><b>Mommy</b> : ${doc.data().Mommy}</div> <div><b>Gender</b> : ${doc.data().Gender}</div> <div><b>Price</b> : ${doc.data().Price}</div> <div><b>Description</b> : ${doc.data().Description} </div> </div> ` selectBasketShop(doc.data().Breeder); $("#showSelectBasketPets").append(result) }); }); }; const selectBasketShop = (Shop) => { db.collection("Shops").where("Name", "==", Shop).get().then(function (querySnapshot) { querySnapshot.forEach(function (doc) { const result = /*html*/ ` <ons-fab position="top left" style="color: black; background-color: rgb(252, 186, 3);" id="BackSelectBasket"> <i class="material-icons md-48" style="margin-top: 16px;">arrow_back</i> </ons-fab> <div class="Shopprofile"> <ons-row class="d-flex justify-content-around pl-1 pr-1 textprofile"> <ons-col class="col-5"> <img src="${doc.data().PhotoURL}" class="pixprofile" style="border-radius: 100%; border: 5px solid white;"> </ons-col> <ons-col class="col-7 text"> <div>${doc.data().Name}</div> <ons-row class="d-flex justify-content-start container1"> <ons-col class="col-4 editH"> ${doc.data().Type} </ons-col> </ons-row> <div>คะแนนร้านค้า : ${doc.data().Rating}</div> </ons-col> </ons-row> </div> ` $('#showSelectBasketShop').append(result); }); $("#BackSelectBasket").click(function () { document.querySelector("#Navigator_basket").popPage(); }) }); }; const deleteBasket = (docID, Breed) => { const user = firebase.auth().currentUser; ons.notification.confirm({ message: "Are You Sure ?", title: "Delete " + Breed, primaryButtonIndex: 1, callback: function (index) { if (index == 1) { db.collection("Pets").doc(docID).update({ Basket: firebase.firestore.FieldValue.arrayRemove(user.uid) }).then(function () { getBasketForUser(user); }).catch(function () { }) } } }) }; const orderPage = (Breed) => { db.collection("Pets").where("Breed", "==", Breed).get().then(function (querySnapshot) { querySnapshot.forEach(function (doc) { const result = /*html*/ ` <div class="ml-4 mt-4 h5">ร้านค้า ${doc.data().Breeder}</div> <div class="borderItem"> <ons-row class="d-flex justify-content-center align-items-center mt-2"> <img class="BasketPets" src="${doc.data().photoURL}" id="${doc.data().Breed}" width="170" height="140"> <div class="ml-2"> <div class="title-basket">Breed : ${doc.data().Breed}</div> <div class="title-basket">Breeder : ${doc.data().Breeder}</div> <ons-row class="d-flex justify-content-between" style="color: rgb(255, 0, 0);"> <div class="title-basket">ราคา :</div> <div class="title-basket">${doc.data().Price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")} บาท</div> </ons-row> </div> </ons-row> </div> <div class="m-4"> <ons-row class="locationBox p-2"> <ons-col class="col-3 pr-0"> <img src="/assets/image/Location.png" width="55" alt="" srcset=""> </ons-col> <ons-col class="col-9 pl-0" id="showLocation"> <div class="location"> 32/11 หมู่ 1 ถ.วิชิตสงคราม ต.กะทู้ อ.กะทู้ จ.ภูเก็ต 83120 </div> </ons-col> </ons-row> </div> <div class="ml-4 mr-4 mt-3"> <button type="button" class="btn btn-primary btn-block btn-lg font-weight-bold" onclick="Payment('${doc.data().Breed}','${doc.data().Breeder}','${doc.data().Price}','${doc.id}')" style="background-color: #CE9A35;border-color: #CE9A35;">PAYMENT</button> </div> ` $("#showOrderPets").append(result) }); }); } const backBasket = () => { $("#BackBasket").click(function () { document.querySelector("#Navigator_basket").popPage(); }) } const Payment = (Breed, Breeder, Price, docID) => { const user = firebase.auth().currentUser; ons.notification.confirm({ title: Breed, message: "ยืนยันชำระเงิน", callback: function (index) { if (index == 1) { db.collection("History").add({ Breed: Breed, Breeder: Breeder, Price: Price, Owner: user.uid, timestamp: firebase.firestore.FieldValue.serverTimestamp(), }).then(function (docRef) { db.collection("Pets").doc(docID).update({ Basket: firebase.firestore.FieldValue.arrayRemove(user.uid) }).then(function () { getBasketForUser(user); ons.notification.alert({ title: "Animaru", message: "Payment Success", }).then(function () { getHistory(); document.querySelector("#Navigator_basket").popPage(); }) }).catch(function () { }) }).catch(function (error) { ons.notification.alert({ title: "Animaru", message: error, }); }); } } }) }
import request from "superagent"; import { baseUrl } from "./ads"; export const LOGIN_SUCCESS = "LOGIN_SUCCESS"; const loginSuccess = jwt => { return { type: LOGIN_SUCCESS, jwt }; }; export const login = data => dispatch => { request .post(`${baseUrl}/logins`) .send(data) .then(res => dispatch(loginSuccess(res.body))); };
'use strict'; const express = require('express'); const router = express.Router(); let userController = require('../controllers/userController'); let commentController = require('../controllers/commentController'); let headerController = require('../controllers/headerController'); // API PRIVATE router.use('/api/v1/user', require('./userRoutes')); router.use('/api/v1/comment', require('./commentRoutes')); router.use('/api/v1/header', require('./headerRoutes')); module.exports = router;
/* global define */ /** * @description Util fn for use with Crockford's functional inheritance structure (i.e. drivers) * Creates object with reference to all the original super fny, that can be used by the extending class. * * @usage implement immediately after extending super object: * var that = basicDriver(options, data, containerTag, timelineRef, template); * var __super = objectSuper(that); * Then, later in code: __super.init(), __super.myNotOverwrittenSuperFunction() * */ define( [], function () { "use strict"; var os = function(pThat){ var __super = {}; function makeSuperMethod(prop){ var method = pThat[prop]; __super[prop] = function(){ return method.apply(pThat, arguments); }; } for(var prop in pThat){ if(pThat.hasOwnProperty(prop) && typeof pThat[prop] === 'function'){ makeSuperMethod(prop); } } return __super; }; return os; } );
/** * Created by eamonnmaguire on 08/07/2016. */ var citation_summary = (function () { var self_cite_colors = d3.scale.ordinal().domain(["self", "not self"]).range(["#e74c3c", "#3498db"]); var subject_area_colors = d3.scale.ordinal().range(["#95a5a6", "#7f8c8d", "#34495e", "#8e44ad"]); var citation_type_colors = d3.scale.ordinal().domain(["preprint", "article"]).range(["#3498db", "#2980b9"]) var date_format = "%d %b %Y"; var formatNumber = d3.format(",d"), formatDate = d3.time.format(date_format), formatTime = d3.time.format("%I:%M %p"), normalised_number_format = d3.format("s"); var parseDate = function (d) { return new Date(d.substring(0, 4), d.substring(5, 7), d.substring(8)); }; var calculate_window_width = function () { return $(window).width(); }; var calculate_vis_width = function (window_width, normal_width_ratio) { if (window_width <= 900) { return window_width * .63; } else { return window_width * normal_width_ratio; } }; var process_data = function (data) { data.forEach(function (d, i) { d.index = i; d.cited_paper_date = parseDate(d.cited_paper_date); d.citation_date = parseDate(d.citation_date); }); }; return { render: function (url, options) { d3.json(url, function (result) { var citation_data = result.citations; process_data(citation_data); var observed_papers = []; var papers = crossfilter(citation_data), papers_by_date = papers.dimension(function (d) { return d.cited_paper_date; }), citations_by_date = papers.dimension(function (d) { return d.citation_date; }), citation_type = papers.dimension(function (d) { return d.citation_type; }), self_citation = papers.dimension(function (d) { return d.self_citation ? "self" : "not self"; }), subject_area = papers.dimension(function (d) { return d.citation_subject; }), citation_count_group = citations_by_date.group().reduce(function (p, v) { return p + 1; }, function (p, v) { return p - 1 }, function () { return 0 }), papers_count_group = papers_by_date.group().reduce(function (p, v) { if(observed_papers.indexOf(v.cited_paper_id) == -1) { observed_papers.push(v.cited_paper_id); return p + 1; } }, function (p, v) { if(observed_papers.indexOf(v.cited_paper_id) !== -1) { delete observed_papers[v.cited_paper_id] return p - 1 } }, function () { return 0 }), citation_type_count = citation_type.group().reduce(function (p, v) { return p + 1; }, function (p, v) { return p - 1 }, function () { return 0 }), self_type_count = self_citation.group().reduce(function (p, v) { return p + 1; }, function (p, v) { return p - 1 }, function () { return 0 }), subject_area_count = subject_area.group().reduce(function (p, v) { return p + 1; }, function (p, v) { return p - 1 }, function () { return 0 }); var top_value = 0; var cumulative_citation_group = { all: function () { var cumulate = 0; var g = []; citation_count_group.all().forEach(function (d, i) { cumulate += d.value; top_value = cumulate; g.push({ key: d.key, value: cumulate, single_value: d.value }) }); return g; } }; var minCitationDate = new Date(citations_by_date.bottom(1)[0].citation_date); var maxCitationDate = new Date(citations_by_date.top(1)[0].citation_date); var minPaperDate = new Date(papers_by_date.bottom(1)[0].cited_paper_date); var maxPaperDate = new Date(papers_by_date.top(1)[0].cited_paper_date); var minDate = minCitationDate < minPaperDate ? minCitationDate : minPaperDate; var maxDate = maxCitationDate > maxPaperDate ? maxCitationDate : maxPaperDate; minDate.setDate(minDate.getDate() - 30); maxDate.setDate(maxDate.getDate() + 30); var window_width = calculate_window_width(); var rptLine = dc.compositeChart(document.getElementById("citations")); rptLine .width(calculate_vis_width(window_width, 0.85)) .height(300) .margins({top: 10, right: 50, bottom: 30, left: 60}) .x(d3.time.scale().domain([minDate, maxDate])) .xUnits(d3.time.months) .renderHorizontalGridLines(true) .dimension(citations_by_date) .renderVerticalGridLines(true) .compose([ dc.lineChart(rptLine) .group(cumulative_citation_group, 'Cumulative Citations') .valueAccessor(function (d) { return d.value; }) .colors('#3498db'), dc.barChart(rptLine) .group(cumulative_citation_group, 'Citations') .valueAccessor(function (d) { return d.single_value; }) .colors('#3498db'), dc.barChart(rptLine) .group(papers_count_group, 'Papers') .colors('#2c3e50') ]); rptLine.legend(dc.legend().x(80).y(20).itemHeight(13).gap(5)) .brushOn(true); dc.pieChart("#citation_subjects") .dimension(citation_type) .group(citation_type_count) .colors(citation_type_colors); dc.pieChart("#self_cites") .dimension(self_citation) .group(self_type_count) .colors(self_cite_colors); dc.pieChart("#subject_area") .dimension(subject_area) .group(subject_area_count) .colors(subject_area_colors); dc.renderAll(); }); } } })();
import React from 'react'; import Component from './componentes/Componente'; import getContentComponents from './assets/getContentComponent'; import './global.css'; export default function App() { const data = getContentComponents(); return ( <div className="container_components"> { data.map((component)=>{ return <Component data={component}/> }) } </div> ); }
'use strict'; // Imports const chai = require('chai'); const expect = chai.expect; const jsdom = require('jsdom').jsdom; const _$ = require('jquery'); const chaiJquery = require('chai-jquery'); // Setup document const documentHTML = '<!doctype html><html>' + '<body><input id="longitude"><input id="latitude"><button id="coordinate_submit" disabled>Search!</button>' + '<a id="current-pokemon" class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect route-button" style="display: none">Current Pokemon</a>' + '<a id="set-location" class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect route-button">Set Location</a>' + '<a id="notification-options" class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect route-button">Notification Options</a>' + '<li class="mdl-menu__item" id="facebook-button"><i class="fa fa-facebook-official social-icon"></i>Facebook</li>' + '<li class="mdl-menu__item" id="twitter-button"><i class="fa fa-twitter social-icon"></i>Twitter</li>' + '<li class="mdl-menu__item" id="github-button"><i class="fa fa-github social-icon"></i>Github</li>' + '<a class="gps-current-location">' + '<div id="pokemon_list_container"></div>'+ '</body></html>'; global.document = jsdom(documentHTML); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); // Begin Tests describe('Longitude and latitude validation', function () { let popup; beforeEach(function () { global.chrome = require('sinon-chrome'); popup = require('../../app/scripts.babel/popup') }); it('should fail validation if value is null', function () { expect(popup.isValidLatitude(null)).to.equal(false); expect(popup.isValidLongitude(null)).to.equal(false); }); it('should fail validation if value is undefined', function () { expect(popup.isValidLatitude(undefined)).to.equal(false); expect(popup.isValidLongitude(undefined)).to.equal(false); }); it('should fail validation if value is non numeric characters', function () { expect(popup.isValidLatitude('abc')).to.equal(false); expect(popup.isValidLongitude('abc')).to.equal(false); }); it('should fail validation if value exceeds limit', function () { expect(popup.isValidLatitude(91)).to.equal(false); expect(popup.isValidLongitude(181)).to.equal(false); }); it('should fail validation if value is below range', function () { expect(popup.isValidLatitude(-91)).to.equal(false); expect(popup.isValidLongitude(-181)).to.equal(false); }); it('should pass validation if value within range with falsy value', function () { expect(popup.isValidLatitude(0)).to.equal(true); expect(popup.isValidLongitude(0)).to.equal(true); }); it('should pass validation if value within range', function () { expect(popup.isValidLatitude(-90)).to.equal(true); expect(popup.isValidLatitude(55)).to.equal(true); expect(popup.isValidLatitude(90)).to.equal(true); expect(popup.isValidLongitude(-180)).to.equal(true); expect(popup.isValidLongitude(55)).to.equal(true); expect(popup.isValidLongitude(180)).to.equal(true); }); }); describe('DOM manipulation tests', function() { let popup; let renderCurrentPokemonList; let response; beforeEach(function () { global.chrome = require('sinon-chrome'); popup = require('../../app/scripts.babel/popup'); renderCurrentPokemonList = popup.renderCurrentPokemonList; response = { currentPokemon: [{ pokemonId: 1, latitude: 12, longitude: 34 }, { pokemonId: 4, latitude: 14, longitude: 43 }], PokemonMap: { 1: 'bulbasaur', 4: 'charmander'}, latitude: 24, longitude: 36 }; }); describe('Current Pokemon list rendering', function() { beforeEach(function () { renderCurrentPokemonList(response); }); it('should render a list item for each pokemon', function() { const items = document.querySelectorAll('.pokemon-list-item'); expect(items.length).to.equal(2); }); it('should should contain span with pokemon name', function() { const items = $('.pokemon-list-item'); expect(items.eq(0)).to.contain('Bulbasaur'); expect(items.eq(1)).to.contain('Charmander'); }); it('should should contain correct image for each pokemon', function() { const items = $('.pokemon-list-item'); expect(items.eq(0).find('img')).to.exist; expect(items.eq(0).find('img')).to.have.prop('src','images/pokemon/1.png'); expect(items.eq(1).find('img')).to.exist; expect(items.eq(1).find('img')).to.have.prop('src','images/pokemon/4.png'); }); }) })
import React from 'react' import Img from 'gatsby-image' import { Link } from 'gatsby' import { makeStyles } from '@material-ui/core/styles' import Container from '@material-ui/core/Container' import Card from '@material-ui/core/Card' import CardActions from '@material-ui/core/CardActions' import CardContent from '@material-ui/core/CardContent' import Button from '@material-ui/core/Button' import Slider from 'react-slick' import Typography from '@material-ui/core/Typography' const useStyles = makeStyles((theme) => ({ container: { paddingTop: '65px', paddingLeft: '0', paddingRight: '0', overflow: 'hidden' }, containerInner: { height: '100%', maxHeight: '80vh', minHeight: '80vh', position: 'relative', [theme.breakpoints.up('md')]: { maxHeight: '70vh', minHeight: '70vh' }, [theme.breakpoints.up('lg')]: { maxHeight: '80vh', minHeight: '80vh' } }, containerImage: { height: '100%', maxHeight: '80vh', minHeight: '80vh', [theme.breakpoints.up('md')]: { maxHeight: '70vh', minHeight: '70vh' }, [theme.breakpoints.up('lg')]: { maxHeight: '80vh', minHeight: '80vh' } }, containerOverlay: { width: '100%', height: '100%', backgroundColor: theme.palette.secondary.transparent, top: 0, bottom: 0, left: 0, right: 0, position: 'absolute', zIndex: 1 }, card: { zIndex: 2, backgroundColor: 'transparent', color: theme.palette.white.main }, title: { color: theme.palette.white.main } })) const Hero = ({ data, lang }) => { const classes = useStyles() const { slider } = data const settings = { dots: false, infinite: true, slidesToShow: 1, slidesToScroll: 1, lazyLoad: true, autoplay: true, speed: 2000, autoplaySpeed: 8000, cssEase: 'ease-in-out', pauseOnHover: true, accessibility: true, centerMode: true, centerPadding: '0', className: classes.containerInner } return ( <Container maxWidth={false} className={classes.container}> <Slider {...settings}> {slider.edges.map((node, index) => { const { projectTitle, projectDescription, projectImages, projectSlug } = node.node const heroImage = projectImages[0] const { fluid, description } = heroImage return ( <div className={classes.containerInner} key={index}> <div className={classes.containerOverlay}/> <Img fluid={fluid} alt={description} className={classes.containerImage}/> <Container maxWidth={'md'} style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 2 }}> <Card className={classes.card} elevation={0}> <CardContent> <Typography component={'h2'} variant={'h3'} className={classes.title} color="textSecondary" gutterBottom> {projectTitle} </Typography> <Typography variant="body2" component="p"> <span dangerouslySetInnerHTML={{ __html: projectDescription.childMarkdownRemark.excerpt }}/> </Typography> </CardContent> <CardActions> <Button variant={'contained'} component={Link} color={'secondary'} size="small" to={lang === 'de' ? `projekte/${projectSlug}` : `en/projects/${projectSlug}`} aria-label={'learn more about this project.'}>{lang === 'de' ? `Mehr Informationen` : `Learn More`}</Button> </CardActions> </Card> </Container> </div> ) })} </Slider> </Container> ) } export default Hero
var path = require('path'), webpack = require('webpack'), libPath = path.join(__dirname, 'lib'), distPath = path.join(__dirname, 'dist'), HtmlWebpackPlugin = require('html-webpack-plugin'), ImageminPlugin = require('imagemin-webpack-plugin').default, OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'), ProgressBarPlugin = require('progress-bar-webpack-plugin'), // To be delete when webpack will accept the flag --progress in the devserver and not only in CMD autoprefixer = require('autoprefixer'), ExtractTextPlugin = require("extract-text-webpack-plugin"), sassLintPlugin = require('sasslint-webpack-plugin'); var extractCSS = new ExtractTextPlugin('[name]-[hash].css'); var cf = { entry: path.join(libPath, 'index.js'), output: { path: path.join(distPath), filename: 'bundle-[hash:6].js' }, resolve: { root: [path.resolve(__dirname, 'lib'), path.resolve(__dirname, 'node_modules')], extensions: ['', '.js', '.json', '.scss'] }, debug: false, stats: { children: false }, resolveLoader: { root: path.join(__dirname, 'node_modules') }, module: { loaders: [ { test: /\.html$/, loader: 'ngtemplate!html' }, { test: /\.less$/, loader: extractCSS.extract(['css', 'less', 'resolve-url', 'postcss-loader']) }, { test: /\.scss$|\.css$/, loader: extractCSS.extract(['css-loader', 'resolve-url', 'postcss-loader', 'sass?sourceMap']) }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff&&name=lib/font/[name]-[hash].[ext]' }, { test: /\.jpe?g$|\.gif$|\.png$/, loaders: ['file?hash=sha512&digest=hex&name=lib/img/[name].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'] }, { test: /\.ttf$|\.eot$|\.wav$|\.svg$/, loader: "file?name=lib/font/[name]-[hash].[ext]" }, { test: /\.json$/, loaders: ["raw-loader", "file?name=lib/languages/[name].[ext]"] }, { test: /\.js$/, exclude: /(node_modules)/, loaders: ['ng-annotate?add=true&map=false', 'babel-loader'] } ] }, eslint: { configFile: './.eslintrc' }, postcss: function () { return [autoprefixer]; }, plugins: [ new HtmlWebpackPlugin({ inject: true, template: path.join(libPath, 'index.ejs'), title: 'My App', cache: false, hash: false, minify: { collapseWhitespace: true, removeComments: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true }, chunksSortMode: 'auto' }), // Deduplication: find duplicate dependencies & prevents duplicate inclusion : https://github.com/webpack/docs/wiki/optimization#deduplication new webpack.optimize.DedupePlugin(), // OccurenceOrderPlugin: Assign the module and chunk ids by occurrence count. : https://webpack.github.io/docs/list-of-plugins.html#occurenceorderplugin new webpack.optimize.OccurenceOrderPlugin(), new OptimizeCssAssetsPlugin({ cssProcessor: require('cssnano'), cssProcessorOptions: { discardComments: {removeAll: true } }, canPrint: true }), new ImageminPlugin({ disable: false, optipng: { optimizationLevel: 3 }, gifsicle: { optimizationLevel: 1 }, jpegtran: { progressive: false }, svgo: { }, pngquant: null, // pngquant is not run unless you pass options here plugins: [] }), // a faire uniquement en prod new webpack.optimize.UglifyJsPlugin ({ sourceMap: false, minimize: true, comments: false, compressor: { warnings: false } }), new webpack.optimize.AggressiveMergingPlugin(), extractCSS, new sassLintPlugin({ glob: 'lib/**/*.s?(a|c)ss', ignorePlugins: [ 'extract-text-webpack-plugin' ], configFile: '.sass-lint.yml' }), new ProgressBarPlugin({format: ' build [:bar] ' + (':percent') + ' (:elapsed seconds)'}) ] }; module.exports = cf;
var DiContainer = require('../DiContainer'); describe('Dicontainer', () => { var container; beforeEach(() => { container = new DiContainer(); }); describe('register(name, dependencies, func)', () => { it('인자가 하나라도 빠졌거나 ㅏ입이 잘못되면 예외를 던진다.', () => { var badArgs = [ //인자가 없는경우 [], //이름만 있는경우 ['Name'], //이름과 Di만 있는경우 ['Name', ['Dependency1', 'Dependency2']], //Di가 빠진경우 ['Name', function() {}], //타입이 잘못된 예들 [1, ['a', 'b'], function() {}], ['Name', [1, 2], function() {}], ['Name', ['a', 'b'], 'should be a function'] ]; badArgs.forEach(arg => { expect(() => { container.register.apply(container, arg); }).toThrowError(container.messages.registerRequiresArgs); }); }); }); describe('get(name)', () => { it('성명이 등록되어 있지 않으면 undefined를 반환 한다', () => expect(container.get('notDefined')).toBeUndefined()); it('등록된 함수를 실행한 결과를 반환한다', () => { var name = 'MyName', returnFromRegisteredFunction = 'something'; container.register(name, [], () => { return returnFromRegisteredFunction; }); expect(container.get(name)).toBe(returnFromRegisteredFunction); }); it('등록된 함수에 의존성을 제공한다', () => { let main = 'main', mainFunc, dep1 = 'dep1', dep2 = 'dep2'; container.register(main, [dep1, dep2], (dep1Func, dep2Func) => { return function() { return dep1Func() + dep2Func(); }; }); container.register(dep1, [], () => { return function() { return 1; }; }); container.register(dep2, [], () => { return function() { return 2; }; }); mainFunc = container.get(main); expect(mainFunc()).toBe(3); }); }); });
const config = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN.firebaseapp.com', databaseURL: 'https://YOUR_AUTH_DOMAIN.firebaseio.com', projectId: 'YOUR_AUTH_DOMAIN', storageBucket: 'YOUR_AUTH_DOMAIN.appspot.com', messagingSenderId: 'YOUR_MESSAGING_SENDER_ID' }; export default config;
google.charts.load("current", { packages: ["bar"] }); google.charts.setOnLoadCallback(drawBarChart2); function drawBarChart2() { const arrayLength = monthly_spendings.length; let content = [["Commission", "amount of commission"]]; for (var i = 0; i < arrayLength; i++) { content.push([months[i], monthly_spendings[i]]); } var data = new google.visualization.arrayToDataTable(content); var options = { // width: 800, legend: { position: "none" }, chart: { title: "Monthly Spendings", }, axes: { x: { 0: { side: "bottom", label: "monthly spending" }, }, }, bar: { groupWidth: "50%" }, }; var chart = new google.charts.Bar( document.getElementById("cusMonthlySpending") ); // Convert the Classic options to Material options. chart.draw(data, google.charts.Bar.convertOptions(options)); }
const express = require('express'); const routes = express.Router(); const usuario = require('../controllers/usuario'); const ferramenta = require('../controllers/ferramenta'); const alugueis = require('../controllers/alugueis'); /*Rotas de usuário*/ routes.post('/usuario', usuario.create); routes.get('/usuario', usuario.list); routes.put('/usuario', usuario.alter); routes.delete('/usuario', usuario.delete); routes.get('/usuario/:id', usuario.show);/*Não finalizado*/ /*Rotas de ferramenta*/ routes.post('/ferramenta', ferramenta.create); routes.get('/ferramenta', ferramenta.list); routes.put('/ferramenta', ferramenta.alter); routes.delete('/ferramenta', ferramenta.delete); routes.get('/ferramenta/:id', ferramenta.count); /*Rotas de alugueis*/ routes.post('/alugueis', alugueis.create); routes.get('/alugueis', alugueis.list); routes.put('/alugueis', alugueis.alter); routes.delete('/alugueis', alugueis.delete); module.exports = routes;
// #7 Class // Create a Str class with methods to: // Add lower method to convert a string to lower case. // Str.lower('MAKAN') // makan // Add upper method to convert a string to upper case. // Str.upper('malam') // MALAM // Add capitalize method to capitalize all first letter of words. // Str.capitalize('saya ingin makan') // Saya Ingin Makan // Add reverse method to reverse a string. // Str.reverse('kasur') // rusak // Add contains method to determine a text – contains a string or more. // Str.contains('Saya ingin makan sate', 'makan') // true // Str.contains('Saya ingin makan sate', 'rujak') // false // Str.contains('Saya ingin makan sate', ['sate', 'rujak']) // true // Create a random aplhanum string. By default it will generate 16 random chars. But if you pass a number as 1st parameter, it will generate random chars based on that number. // Str.random() // hef2nCi273c8D2dz // Str.random(6) // ckS3jP // Str.random(32) // tbFGeCycTBy8FTfXqOTkDd0YtlQngLt4 // Convert a string into slug and ignore all non-alphanum chars. // Str.slug('Kotlin & Swift semakin populer di 2018?') // kotlin-swift-semakin-populer-di-2018 // Right Answer class Str { static lower(string) { return string.toLowerCase() } static upper(string) { return string.toUpperCase() } static capitalize(string) { return string .split(' ') .map(str => str.charAt(0).toUpperCase() + str.substr(1)) .join(' ') } static contains(string, value) { if (typeof value === 'string') { return string.includes(value) } if (Array.isArray(value)) { return Boolean(value.find(val => string.includes(val))) } } static random(count = 16) { const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' let text = '' for (let i = 0; i < count; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)) return text } static slug(string) { return string .toLowerCase() .replace(/\W/gi, '-') .replace(/-{2,}/gi, '-') .replace(/-$/, '') } } console.log(Str.lower('MAKAN')) console.log(Str.upper('makan')) console.log(Str.capitalize('makan dan minum')) console.log(Str.contains('Saya ingin makan sate', 'makan')) console.log(Str.contains('Saya ingin makan sate', 'rujak')) console.log(Str.contains('Saya ingin makan sate', ['makan', 'rujak'])) console.log(Str.random()) console.log(Str.random(6)) console.log(Str.random(32)) console.log(Str.slug('Kotlin & Swift semakin populer di 2018?'))
import {trackingTransitionBlock} from './init-animations'; const scrollContainer = document.querySelector('.scroll-container'); const scrollTranslator = document.querySelector('.scroll-translator'); const scroller = document.querySelector('.scroller'); const horizontalScrollBlock = document.querySelector('.horizontal-scroll'); const horizontalScrollWrapper = document.querySelector('.horizontal-scroll__content'); const horizontalScrollItems = document.querySelectorAll('.horizontal-scroll__item'); const horizontalScrollTitle = document.querySelector('.horizontal-scroll__title'); const horizontalScrollImgs = document.querySelectorAll('.horizontal-scroll__item-img'); const allActiveElement = document.querySelectorAll('input, checkbox, a, button, textarea, radio, select, option'); let horizontalTop; let horizontalScrollWidth; let horizontalScrollBlockOffset; let horizontalScrollTitleWidth; let horizontalScrollImgOffset; let horizontalScrollImgWidth; let current = 0; let coefficient; let activeElement; let activeShift; const easeOutQuad = (a, b, t) => { return (1 - t) * a + t * b; }; const animate = () => { const i = easeOutQuad(current, window.pageYOffset, 0.08); current = Math.floor(i * 100) / 100; if (horizontalScrollBlock) { setHorizontalScroll(current); animateHorizontalImgs(); } else { setStandartScroll(current); } window.requestAnimationFrame(animate); }; const setStandartScroll = (current) => { scrollTranslator.style.transform = 'translate3d(0,' + -current + 'px, 0)'; }; const setHorizontalScroll = (current) => { setStandartScroll(current); if (current - horizontalTop >= horizontalScrollWidth) { scrollTranslator.style.transform = 'translate3d(0,' + -(current - horizontalScrollWidth) + 'px, 0)'; } else if (current >= horizontalTop) { horizontalScrollWrapper.style.transform = 'translate3d(' + (-current + horizontalTop) + 'px, 0, 0)'; horizontalScrollTitle.style.transform = 'translate3d(' + (-current + horizontalTop) / ((horizontalScrollWidth / horizontalScrollTitleWidth) * 2) + 'px, 0, 0)'; scrollTranslator.style.transform = 'translate3d(0,' + -horizontalTop + 'px, 0)'; } else { horizontalScrollWrapper.style.transform = 'translate3d(0, 0, 0)'; } }; const returnHorizontalScrollWidth = (arr) => { let width = 0; arr.forEach((el, index) => { if (index === arr.length - 1) { return; } const margin = Number(window.getComputedStyle(el, null).getPropertyValue('margin-right').split('px')[0]); if (margin) { width += el.getBoundingClientRect().width + margin; } else { width += el.getBoundingClientRect().width; } }); return width; }; const setScrollerHeight = () => { scroller.style.height = scrollTranslator.scrollHeight + 'px'; if (horizontalScrollBlock) { horizontalScrollWidth = returnHorizontalScrollWidth(horizontalScrollItems); horizontalScrollTitleWidth = horizontalScrollTitle.getBoundingClientRect().width; horizontalTop = horizontalScrollBlock.offsetTop; scroller.style.height = scrollTranslator.scrollHeight + returnHorizontalScrollWidth(horizontalScrollItems) + 'px'; } }; const animateHorizontalImgs = () => { horizontalScrollImgs.forEach((el, i) => { horizontalScrollImgOffset = el.getBoundingClientRect().x; horizontalScrollImgWidth = el.getBoundingClientRect().width; if (horizontalScrollImgOffset < (horizontalScrollImgWidth / 2)) { coefficient = (horizontalScrollImgOffset + horizontalScrollImgWidth) / horizontalScrollImgWidth; el.style.opacity = coefficient; el.style.filter = 'grayscale(' + (1 - coefficient) + ')'; } else { el.style.opacity = 1; el.style.filter = 'grayscale(0)'; } }); }; const returnActiveIndex = () => { let index; allActiveElement.forEach((el, i) => { if (el.classList.contains('active-element')) { el.classList.remove('active-element'); index = i; } }); return index; }; const movingOnTabClick = (el) => { document.body.classList.add('moving'); const parent = el.closest('.tab-area'); activeShift = parent.getBoundingClientRect().top + window.pageYOffset; if (parent && parent.classList.contains('horizontal-scroll')) { const closestParent = el.closest('.horizontal-scroll__item'); if (closestParent) { horizontalScrollBlockOffset = closestParent.getBoundingClientRect().x; activeShift = parent.getBoundingClientRect().top + window.pageYOffset + horizontalScrollBlockOffset; } } el.classList.add('active-element'); window.scrollTo(0, activeShift); setTimeout(() => { trackingTransitionBlock(); }, 600); setTimeout(() => { el.focus(); }, 1200); setTimeout(() => { document.body.classList.remove('moving'); }, 1500); }; const tabMoving = (e) => { if (e.keyCode === 9 && !e.shiftKey) { e.preventDefault(); if (e.target === document.body && !document.body.classList.contains('moving')) { activeElement = allActiveElement[0]; movingOnTabClick(activeElement); } else if (!document.body.classList.contains('moving')) { activeElement = allActiveElement[returnActiveIndex() + 1]; if (!activeElement) { activeElement = allActiveElement[0]; } movingOnTabClick(activeElement); } } if (e.shiftKey && e.keyCode === 9) { e.preventDefault(); if (e.target === document.body && !document.body.classList.contains('moving')) { activeElement = allActiveElement[allActiveElement.length - 1]; movingOnTabClick(activeElement); } else if (!document.body.classList.contains('moving')) { activeElement = allActiveElement[returnActiveIndex() - 1]; if (!activeElement) { activeElement = allActiveElement[allActiveElement.length - 1]; } movingOnTabClick(activeElement); } } }; const initCustomScroll = () => { if (scrollContainer) { setScrollerHeight(); animate(); window.addEventListener('resize', setScrollerHeight); window.addEventListener('keydown', tabMoving); } }; export default initCustomScroll;
import styled from 'styled-components'; export const Wrapper = styled.div` max-width: ${({ theme }) => theme.constants.maxWidth}; padding: 0 1.6rem; margin-bottom: ${({ extraHeadingMargin }) => extraHeadingMargin ? '4.8rem' : '2.4rem'}; width: 100%; @media ${({ theme }) => theme.mediaQueries.tablet} { padding: 0 2.4rem; } @media ${({ theme }) => theme.mediaQueries.desktop} { padding: 0; } `; export const Container = styled.div` display: grid; gap: 1.2rem; text-align: ${({ alignHeading }) => alignHeading}; width: 100%; @media ${({ theme }) => theme.mediaQueries.tablet} { margin: 0 auto; max-width: 75%; } @media ${({ theme }) => theme.mediaQueries.desktop} { max-width: 100%; } `;
import React, { useState } from 'react'; import * as THREE from 'three'; export const useSceneData = () => { const [controls, setControls] = useState(null); const setupScene = (mount) => { const sizes = { width: window.innerWidth, height: window.innerHeight, }; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); camera.position.z = 5; mount.current.appendChild(renderer.domElement); const animate = () => { if(controls) controls.update(); requestAnimationFrame(animate); renderer.render(scene, camera); }; const setupEventListeners = () => { window.addEventListener("resize", () => { // Update sizes sizes.width = window.innerWidth; sizes.height = window.innerHeight; // Update camera camera.aspect = sizes.width / sizes.height; camera.updateProjectionMatrix(); // Update renderer renderer.setSize(sizes.width, sizes.height); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); }); }; animate(); setupEventListeners(); } const addObjects = (scene) => { // const geometry = new THREE.BoxGeometry(1, 1, 1); // const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // const cube = new THREE.Mesh(geometry, material); // scene.add(cube); } return { setupScene, addObjects } }
import React from 'react' import HomeBody from '../../components/HomeBody/HomeBody' export default function AdminHome() { return ( <div> <HomeBody/> </div> ) }
import parseArgs from './config/args'; export async function cli(args) { const cl = parseArgs(args); let cmd = cl.command[1]; if(cl.options.version) { cmd = 'version'; } if(cl.options.help || !cmd) { cmd = 'help'; } // actions loaded w/ dynamic imports to improve cli performance switch(cmd) { case 'init': await (await import('./actions/create')).default(cl.options); break; case 'version': await (await import('./actions/version')).default(); break; case 'help': (await import('./actions/help')).default(cl.command[2]); break; default: console.error(`"${cmd}" is not a valid command!`); } process.exit(); }
import React, { useState, useReducer } from 'react' import { initialState, todoReducer } from '../reducers/reducer' const TodoForm = () => { const[newTodo, setNewTodo] = useState() const[state, dispatch] = useReducer(todoReducer, initialState) const handleSubmit = e => { e.preventDefault() } const handleChanges = event => { setNewTodo(event.target.value) } return( <div> <form onSubmit={handleSubmit}> <input placeholder='Next Todo' type='text' name='item' onChange={handleChanges} /> <button onClick={() => dispatch({ type: 'ADD_TODO', payload: newTodo })}>Add Todo</button> <button onClick={() => dispatch({ type: 'CLEAR_COMPLETED', payload: newTodo})}>Clear Todo </button> </form> {state.todos.map(todo => <div key={todo.id}> <p className={`todo ${todo.completed ? ' completed' : ''}`} onClick={() => dispatch({ type: 'TOGGLE_COMPLETED', payload: todo.id }) }>{todo.item}</p> </div> )} </div> ) } export default TodoForm;
// server.js // where your node app starts // init project const express = require('express'); const app = express(); // we've started you off with Express, // but feel free to use whatever libs or frameworks you'd like through `package.json`. // http://expressjs.com/en/starter/static-files.html app.use(express.static('public')); // http://expressjs.com/en/starter/basic-routing.html app.get('/', function(request, response) { response.sendFile(__dirname + '/views/index.html'); }); // listen for requests :) const listener = app.listen(process.env.PORT, function() { console.log('Your app is listening on port ' + listener.address().port); }); const revai = require('revai-node-sdk'); const fs = require('fs'); const token = "02qpETqg3XvjGChGn7F1wc-5dHgQuOOtpe7MzS7AsskYSO5XN9EMfQkyz-48fsXmpBE2dLN7vFRVZAy-Z3BFv-r0MvGBo"; let url = "https://cdn.glitch.com/a713bb55-db98-4862-84ad-39777182d9bf%2FTest%20clip.mp3?v=1569794815724" // equire('./config/config.json').access_token; const dofunction = async () => { // Initialize your client with your revai access token var client = new revai.RevAiApiClient(token); console.log(revai.RevAiApiClient) return // Get account details var account = await client.getAccount(); console.log(`Account: ${account.email}`); console.log(`Balance: ${account.balance_seconds} seconds`); const jobOptions = { metadata: "InternalOrderNumber=123456789", // callback_url: "https://jsonplaceholder.typicode.com/posts", skip_diarization: false, custom_vocabularies: [{ phrases: [ "add", "custom", "vocabularies", "here" ] }] }; // Media may be submitted from a url let url = "https://cdn.glitch.com/a713bb55-db98-4862-84ad-39777182d9bf%2FTest%20clip.mp3?v=1569794815724" var job = await client.submitJobUrl(url, jobOptions); console.log(`Job Id: ${job.id}`); console.log(`Status: ${job.status}`); console.log(`Created On: ${job.created_on}`); /** * Waits 5 seconds between each status check to see if job is complete. * note: polling for job status is not recommended in a non-testing environment. * Use the callback_url option (see: https://www.rev.ai/docs#section/Node-SDK) * to receive the response asynchronously on job completion */ let jobStatus; while((jobStatus = (await client.getJobDetails(job.id)).status) == revai.JobStatus.InProgress) { console.log(`Job ${job.id} is ${jobStatus}`); await new Promise( resolve => setTimeout(resolve, 5000)); } /** * Get transcript as plain text * Transcripts can also be gotten as Object, Text Stream, Object Stream, * or as captions */ var transcriptText = await client.getTranscriptText(job.id); // var transcriptTextStream = await client.getTranscriptTextStream(job.id); // var transcriptObject = await client.getTranscriptObject(job.id); // var transcriptObjectStream = await client.getTranscriptObjectStream(job.id); // var captionsStream = await client.getCaptions(job.id); fs.writeFile("./outputs/async_url_transcript.txt", transcriptText, (err) => { if (err) throw err; console.log("Success! Check the examples/outputs/ directory for the transcript.") }); /** * Delete a job * Job deletion will remove all information about the job from the servers */ // await client.deleteJob(job.id); } try{ // dofunction() }catch(e){ console.log(e + "") } const client = new revai.RevAiApiClient(token) const revTest = async () => { const account = await client.getAccount() const job = await client.submitJobUrl(url) const id = job.id console.log(job) const details = { id: '2qw6Nbz5O6eK', created_on: '2019-09-29T23:29:04.763Z', completed_on: '2019-09-29T23:29:39.348Z', name: 'a713bb55-db98-4862-84ad-39777182d9bfTestclip.mp3', media_url: 'https://cdn.glitch.com/a713bb55-db98-4862-84ad-39777182d9bf%2FTest%20clip.mp3?v=1569794815724', status: 'transcribed', duration_seconds: 29.88, type: 'async' } const transcriptObject = await client.getTranscriptObject(id); // console.log(transcriptObject) fs.writeFile("./output/transcript1.json", transcriptObject, (err) => { if (err) throw err; console.log("Success! Check the examples/outputs/ directory for the transcript.") }); } const jobInfo = async (id) => { const info = await client.getJobDetails(id).then(info => console.log(info)) return info } //revTest() //transcriptObject = await client.getTranscriptObject(job.id)
/------------------------------ ตั้งค่า firebase ------------------------------/ const db = firebase.firestore();//สร้าตัวแปร object สำหรับอ้างอิง firestore function myFunction() { var username = document.getElementById("start").value; var element = document.getElementById("chart"); if(element != null){ element.parentNode.removeChild(element); } var element1 = document.getElementById("content"); if(element1 != null){ element1.parentNode.removeChild(element1); } //format วันที่ เป็น yyyy/m/d var today = new Date(username); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); var today = yyyy + '-' + mm + '-' + dd; console.log(today); if(today === "NaN-NaN-NaN"){ window.alert("กรุณาเลือกวันที่ด้วยค่ะ"); } //ดึงค่า นับหมวดหมู่ที่มากที่สุดออกมาดู //ก่อกำเนิดกราฟ var report_day = []; var report = []; var key_array = []; // var raw_data = []; var docRef = db.collection("Count_Intent").doc(today); docRef.get().then(function (doc) { //console.log("Document data:", doc.data()); let key = Object.keys(doc.data()); let data = Object.values(doc.data()); console.log("key = " + key) console.log("data =" + data ) graph(key,data); // report.push(doc.data());//เก็บ ข้อมูล key และ ค่าของข้อมูล }); function graph(key,data){ //สร้างกราฟ var iDiv = document.createElement('div'); iDiv.id = 'chart'; iDiv.className = 'block1'; document.getElementsByTagName('body')[0].appendChild(iDiv); //สร้างตาราง var iDiv1 = document.createElement('div'); iDiv1.id = 'content'; iDiv1.className = 'block2'; document.getElementsByTagName('body')[0].appendChild(iDiv1); var options = { series: [{ name:"จำนวน", data: data }], chart: { type: 'bar', height: 350, }, plotOptions: { bar: { horizontal: true, } }, dataLabels: { enabled: false }, xaxis: { categories: key } }; var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); chart.resetSeries() showData(key,data); } function showData(report_month, number) { var MOUNTAINS = []; // เตรียมข้อมูล for (var i = 0; i < report_month.length; i++) { MOUNTAINS.push({ "name": report_month[i], "ถูก": number[i]}); } //draw table var table = document.createElement("table"); table.className = "gridtable"; var thead = document.createElement("thead"); var tbody = document.createElement("tbody"); var headRow = document.createElement("tr"); ["หัวข้อ", "จำนวนถูก"].forEach(function (el) { var th = document.createElement("th"); th.appendChild(document.createTextNode(el)); headRow.appendChild(th); }); thead.appendChild(headRow); table.appendChild(thead); MOUNTAINS.forEach(function (el) { var tr = document.createElement("tr"); for (var o in el) { var td = document.createElement("td"); td.appendChild(document.createTextNode(el[o])) tr.appendChild(td); } tbody.appendChild(tr); }); table.appendChild(tbody); document.getElementById("content").appendChild(table); } }
"use strict"; var vert_code=`#version 300 es in vec2 a_position; in vec2 a_texCoords; uniform vec2 res; out vec2 texCoords; void main() { //convert the pixel locations to (0.0 to 1.0) form vec2 zeroOne=a_position/res; //convert them to (0.0 to 2.0) form vec2 zeroTwo=zeroOne*2.0; //convert them to (-1.0 to 1.0) form vec2 clipSpace=zeroTwo-1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); texCoords=a_texCoords; } `; var frag_code=`#version 300 es precision highp float; in vec2 texCoords; uniform sampler2D u_image; uniform float u_kernel[9]; uniform float u_kernelWeight; out vec4 frag_color; void main() { /* vec2 pixel=vec2(1.0)/vec2(textureSize(u_image,0)); //frag_color=texture(u_image,texCoords); vec4 colorSum=texture(u_image,texCoords+pixel*vec2(-1,-1))*u_kernel[0]+ texture(u_image,texCoords+pixel*vec2(0,-1))*u_kernel[1]+ texture(u_image,texCoords+pixel*vec2(1,-1))*u_kernel[2]+ texture(u_image,texCoords+pixel*vec2(-1,0))*u_kernel[3]+ texture(u_image,texCoords+pixel*vec2(0,0))*u_kernel[4]+ texture(u_image,texCoords+pixel*vec2(1,0))*u_kernel[5]+ texture(u_image,texCoords+pixel*vec2(-1,1))*u_kernel[6]+ texture(u_image,texCoords+pixel*vec2(0,1))*u_kernel[7]+ texture(u_image,texCoords+pixel*vec2(1,1))*u_kernel[8]; frag_color=vec4((colorSum/u_kernelWeight).rgb,1);*/ vec2 onePixel = vec2(1) / vec2(textureSize(u_image, 0)); vec4 colorSum =texture(u_image, texCoords + onePixel * vec2(-1, -1)) * u_kernel[0] + texture(u_image, texCoords + onePixel * vec2( 0, -1)) * u_kernel[1] + texture(u_image, texCoords + onePixel * vec2( 1, -1)) * u_kernel[2] + texture(u_image, texCoords + onePixel * vec2(-1, 0)) * u_kernel[3] + texture(u_image, texCoords + onePixel * vec2( 0, 0)) * u_kernel[4] + texture(u_image, texCoords + onePixel * vec2( 1, 0)) * u_kernel[5] + texture(u_image, texCoords + onePixel * vec2(-1, 1)) * u_kernel[6] + texture(u_image, texCoords + onePixel * vec2( 0, 1)) * u_kernel[7] + texture(u_image, texCoords + onePixel * vec2( 1, 1)) * u_kernel[8] ; frag_color = vec4((colorSum / u_kernelWeight).rgb, 1); } `; function makeShader(gl,type,source) { var shader=gl.createShader(type); gl.shaderSource(shader,source); gl.compileShader(shader); var success=gl.getShaderParameter(shader, gl.COMPILE_STATUS); if(success) { return shader; } console.log(gl.getShaderInfoLog(shader)); gl.deleteShader(shader); return undefined; } function makeProgram(gl,vert_shader,frag_shader) { var program=gl.createProgram(); gl.attachShader(program, vert_shader); gl.attachShader(program, frag_shader); gl.linkProgram(program); var success=gl.getProgramParameter(program, gl.LINK_STATUS); if(success) { return program; } console.log(gl.getProgramInfoLog(program)); gl.deleteProgram(program); return undefined; } function setRectangle(gl,x,y,width,height) { var x1,x2,y1,y2; x1=x; x2=x+width; y1=y; y2=y+height; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ x1,y1, x2,y1, x1,y2, x1,y2, x2,y1, x2,y2 ]),gl.STATIC_DRAW); } function render(image) { //Creating the shaders var vert_shader=makeShader(gl,gl.VERTEX_SHADER,vert_code); var frag_shader=makeShader(gl,gl.FRAGMENT_SHADER,frag_code); //Creating the shader program var program=makeProgram(gl,vert_shader,frag_shader); //Create and bind the vertex array object var vao=gl.createVertexArray(); gl.bindVertexArray(vao); //Adding position coordinates var pos_buffer=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,pos_buffer); setRectangle(gl,0,0,image.width,image.height); var posLoc=gl.getAttribLocation(program,"a_position"); gl.enableVertexAttribArray(posLoc); gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0); //Adding texture coordinates var texCoords=[ 0.0,0.0, 1.0,0.0, 0.0,1.0, 0.0,1.0, 1.0,0.0, 1.0,1.0 ]; var tex_buffer=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,tex_buffer); gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(texCoords),gl.STATIC_DRAW); var texLoc=gl.getAttribLocation(program,"a_texCoords"); gl.enableVertexAttribArray(texLoc); gl.vertexAttribPointer(texLoc, 2, gl.FLOAT, false, 0, 0); //Setting the texture var texture=gl.createTexture(); gl.activeTexture(gl.TEXTURE0 + 0);//make unit 0 the active texture unit gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); var mipLevel = 0; // the largest mip var internalFormat = gl.RGBA; // format we want in the texture var srcFormat = gl.RGBA; // format of data we are supplying var srcType = gl.UNSIGNED_BYTE; // type of data we are supplying gl.texImage2D(gl.TEXTURE_2D,mipLevel,internalFormat,srcFormat,srcType,image); //Get uniform locations var resLoc=gl.getUniformLocation(program, "res"); var texLoc=gl.getUniformLocation(program,"u_image"); var kernelLoc=gl.getUniformLocation(program,"u_kernel[0]"); var kernelWeightLoc=gl.getUniformLocation(program,"u_kernelWeight"); gl.viewport(0,0,gl.canvas.width,gl.canvas.height); gl.clearColor(0.0,0.5,0.8,1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.useProgram(program); gl.bindVertexArray(vao); kernel_menu(); function kernel_menu() { var kernels = { normal: [ 0, 0, 0, 0, 1, 0, 0, 0, 0, ], gaussianBlur: [ 0.045, 0.122, 0.045, 0.122, 0.332, 0.122, 0.045, 0.122, 0.045, ], gaussianBlur2: [ 1, 2, 1, 2, 4, 2, 1, 2, 1, ], gaussianBlur3: [ 0, 1, 0, 1, 1, 1, 0, 1, 0, ], unsharpen: [ -1, -1, -1, -1, 9, -1, -1, -1, -1, ], sharpness: [ 0, -1, 0, -1, 5, -1, 0, -1, 0, ], sharpen: [ -1, -1, -1, -1, 16, -1, -1, -1, -1, ], edgeDetect: [ -0.125, -0.125, -0.125, -0.125, 1, -0.125, -0.125, -0.125, -0.125, ], edgeDetect2: [ -1, -1, -1, -1, 8, -1, -1, -1, -1, ], edgeDetect3: [ -5, 0, 0, 0, 0, 0, 0, 0, 5, ], edgeDetect4: [ -1, -1, -1, 0, 0, 0, 1, 1, 1, ], edgeDetect5: [ -1, -1, -1, 2, 2, 2, -1, -1, -1, ], edgeDetect6: [ -5, -5, -5, -5, 39, -5, -5, -5, -5, ], sobelHorizontal: [ 1, 2, 1, 0, 0, 0, -1, -2, -1, ], sobelVertical: [ 1, 0, -1, 2, 0, -2, 1, 0, -1, ], previtHorizontal: [ 1, 1, 1, 0, 0, 0, -1, -1, -1, ], previtVertical: [ 1, 0, -1, 1, 0, -1, 1, 0, -1, ], boxBlur: [ 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, ], triangleBlur: [ 0.0625, 0.125, 0.0625, 0.125, 0.25, 0.125, 0.0625, 0.125, 0.0625, ], emboss: [ -2, -1, 0, -1, 1, 1, 0, 1, 2, ], }; var initialSelection = 'edgeDetect2'; var selection=initialSelection; var ui=document.getElementById("ui"); var select=document.createElement("select"); for(var kernel in kernels) { var option=document.createElement("option"); option.value=kernel; if (kernel=== initialSelection) { option.selected = true; } option.appendChild(document.createTextNode(kernel)); select.appendChild(option); } select.onchange=function(){ selection=this.options[this.selectedIndex].value; drawImage(kernels[selection]); } drawImage(kernels[initialSelection]); ui.appendChild(select); } function drawImage(kernel) { for(var i=0;i<9;i++) { console.log(kernel[i]); } var kernelWeight=computeWeight(kernel); //Set the uniforms gl.uniform2f(resLoc, gl.canvas.width, gl.canvas.height); gl.uniform1i(texLoc,0); gl.uniform1fv(kernelLoc, kernel); gl.uniform1f(kernelWeightLoc, kernelWeight); //Draw the triangle gl.enable(gl.DEPTH_TEST); gl.drawArrays(gl.TRIANGLES, 0, 6); } } //Creating image var canvas= document.getElementById('c'); var gl=canvas.getContext('webgl2'); if(gl) { console.log("WebGL works"); } var image=new Image(); //image.src="./textures/airplane.png"; var extra=document.getElementById("texture"); image.src=extra.src; image.onload=function() { render(image); } function computeWeight(mat) { var sum=0; for(var int in mat) { sum+=mat[int]; } if(sum>0) return sum; else return 1.0; }
var Canvas2dRenderingSystem = System.extend('Canvas2dRenderingSystem', function Canvas2dRenderingSystem(ctx) { System.call(this); this.ctx = ctx; }, { aspects: { cameras: Aspect.all(['Camera2d', 'Transform2d']), objects: Aspect.all(['SimpleGraphics', 'Transform2d']) }, getWorldRect: function(pos, size) { var result = { x: pos.x - size.x / 2, y: pos.y - size.y / 2, w: size.x, h: size.y }; if (!isFinite(result.x) || !isFinite(result.y)) throw new Error('FUCK WATCH UR NUMBERS'); return result; }, onUpdate: function(dt, nodes) { var cameras = nodes.cameras; var objects = nodes.objects; var self = this; objects.sort(function(a, b) { return self.ecs.getComponent('SimpleGraphics', b).zIndex - self.ecs.getComponent('SimpleGraphics', a).zIndex; }); for (var i = 0; i < cameras.length; ++i) { var camera = cameras[i]; var camera_transform = this.ecs.getComponent('Transform2d', camera); var camera_data = this.ecs.getComponent('Camera2d', camera); var camera_view = this.getWorldRect(camera_transform.worldPos(), camera_data.viewSize); var render_target = camera.renderTarget || this.ctx; render_target.fillStyle = '#000000'; render_target.clearRect(0, 0, render_target.canvas.width, render_target.canvas.height); render_target.save(); var PTM_X = render_target.canvas.width / camera_data.viewSize.x * camera_data.zoom.x; var PTM_Y = render_target.canvas.height / camera_data.viewSize.y * camera_data.zoom.y; var PTM_AVG = (PTM_X + PTM_Y) / 2; render_target.scale(1, -1); render_target.scale(PTM_X, PTM_Y); render_target.translate( -camera_transform.worldPos().x + camera_data.viewSize.x/2, -camera_transform.worldPos().y - camera_data.viewSize.y/2 ); render_target.lineWidth /= PTM_AVG; for (var j = 0; j < objects.length; ++j) { var obj = objects[j]; var transform = this.ecs.getComponent('Transform2d', obj); var graphics = this.ecs.getComponent('SimpleGraphics', obj); var obj_world_rect = this.getWorldRect(transform.worldPos(), graphics.size); if (!Util.Geometry.rectsIntersect(obj_world_rect, camera_view)) continue; this.renderShape(render_target, graphics, obj_world_rect); } render_target.lineWidth *= 1; render_target.strokeStyle = 'red'; render_target.beginPath(); render_target.moveTo(camera_view.x, camera_view.y); render_target.lineTo(camera_view.x + camera_view.w, camera_view.y); render_target.lineTo(camera_view.x + camera_view.w, camera_view.y + camera_view.h); render_target.lineTo(camera_view.x, camera_view.y + camera_view.h); render_target.lineTo(camera_view.x, camera_view.y); render_target.stroke(); render_target.restore(); } }, renderShape: function(render_target, graphics, targetRect) { render_target.save(); render_target.fillStyle = graphics.getColorHex(); /*targetRect = { x: targetRect.x * render_target.canvas.width, y: targetRect.y * render_target.canvas.height, w: targetRect.w * render_target.canvas.width, h: targetRect.h * render_target.canvas.height };*/ switch (graphics.shape) { case 'rect': case 'rectangle': //console.log(targetRect); render_target.beginPath(); render_target.rect(targetRect.x, targetRect.y, targetRect.w, targetRect.h); render_target.fill(); //console.log('Target rect: ', targetRect); break; case 'circle': var x = (targetRect.x + targetRect.w / 2)/* | 0*/; var y = (targetRect.y + targetRect.h / 2)/* | 0*/; var r = (Math.max(targetRect.w, targetRect.h) / 2)/* | 0*/; render_target.beginPath(); render_target.arc(x, y, r, 0, 2 * Math.PI, false); render_target.fill(); break; default: throw new Error('Invalid graphics shape type: ' + graphics.shape.toString()) } render_target.restore(); } }); BUILTIN_COMPONENTS['SimpleGraphics'] = { zIndex: 0, shape: 'rect', color: 'white', size: {x: 1.0, y: 1.0}, onInit: function() { this.setColor(this.color); }, setColor: function(color) { this.color = color; this._parsedColor = Util.Color.parseToHex(this.color); }, getColor: function(){ return this.color; }, getColorHex: function() { return this._parsedColor; }, _parsedColor: null }; BUILTIN_COMPONENTS['Camera2d'] = { renderTarget: null, //viewport: {x: -25.0, y: -25.0, w: 25.0, h: 25.0}, viewSize: {x: 100, y: 100}, zoom: {x: 1, y: 1} };
$(document).ready(function(){ ///// JEQUERY GOES HERE });
X.define("modules.commodityManage.commodityManageList", ["modules.common.routerHelper", "model.commodityManageModel", "data.currencyEntireData", "common.commonMethod"], function (routerHelper, commodityManageModel, currencyEntireData, commonMethod) { //初始化视图对象 var view = X.view.newOne({ el: $(".xbn-content"), url: X.config.commodityManage.tpl.commodityManageList }); //初始化控制器 var ctrl = X.controller.newOne({ view: view }); ctrl.rendering = function () { return view.render({},function () { activeTabLiInfo = route.getRoute() || activeTabLiInfo; ctrl.initPage(); }); }; /** @method getRoute 路由 */ var getRoute = function () { var route = {panel:activeTabLiInfo, ldata:lists[activeTabLiInfo].val()}; return route; }; var header = (function () { return { "tabAll" : [ { field:{ name:"", title:"", type:"int" }, itemRenderer: { render: function (data, field, index, grid) { return '<input type="checkbox" />'; } }, width:"5%" }, { field:{ name:"commodityAttachmentList", title:"商品图片", type:"string" }, itemRenderer: { render: function(data) { var imgHost = X.constructor.prototype.config.PATH_FILE.path.imageStoreUrl, imageUrl = data.commodityAttachmentList[0].filePath.indexOf(imgHost) > -1? data.commodityAttachmentList[0].filePath: (imgHost +'/'+data.commodityAttachmentList[0].filePath) return '<img class="mt5" style="max-width:80px; max-height: 80px;" src="' + imageUrl + '">' } }, width:"13%", className:"tL" }, { field:{ name: "commodityNumber", title:"商品编号", type:"string" }, width:"10%" }, { field:{ name:"title", title:"商品标题", type:"string" }, itemRenderer: { render: function(data) { return '<p class="word-cut w160" title="' + data.title + '">'+ data.title +'</p>'; } }, width:"14%" }, { field:{ name:"price", title:"价格", type:"string" }, itemRenderer: { render: function(data) { if(data.currency != -1) { return commonMethod.formatMoney(data.price, 2, true) + ' ' + currencyEntireData.source[data.currency].value; } } }, width:"13%" }, { field:{ name:"commodityStatus", title:"状态", type:"string" }, itemRenderer: { render: function(data) { return commodityManageModel.CONSTANTS.status[data.commodityStatus].value; } }, width:"7%" }, { field:{ name:"status", title:"操作", type:"string" }, itemRenderer: { render: function (data) { if (data.commodityStatus === '0') { return '<a class="orange-font curp ml10 mr10 js-edit">编辑</a>'; } else if (data.commodityStatus === '1') { return '<a class="orange-font curp mr10 js-detail">查看</a>|<a class="orange-font curp ml10 js-edit">编辑</a>'; } } }, className: "operation_main", width:"10%" } ] } })(); var schemas = (function(){ var schemas = { "tabAll" :{ searchMeta: { schema: { simple:[ { name:"tagKeyword", inputName: "formNumber", title:"关键字查询", ctrlType:"TextBox", placeholder:"请输入关键字", className : "mr60" }, { name:"commodityNumber", inputName: "formNumber", title:"商品编号", ctrlType:"TextBox", placeholder:"请输入商品编号", className : "mr60" }, ] }, search: { onSearch : function (data) { return data; } }, reset :{ show:false }, selector: "tabAll", }, toolbar: { items: [ { ctrlType: "ToolbarButton", name: "add", title: "新增商品 ", icon:"icon-add", className: "mr10", click: function (item) { X.publish(X.CONSTANTS.channel.menuCall, {m: "commodityManage.addCommodity"}); } }, { ctrlType: "ToolbarButton", name: "remove", title: "删除", icon: "icon-lajitong", click: function (item) { var selectedRows = lists[activeTabLiInfo].toolbar.target.getSelectedRows(); if (selectedRows.length > 0) { var layerDelete = layer.confirm("确认删除", { title: "提示", content: "<div class='tac'>确认删除?</div>", yes: function () { layer.close(layerDelete); var commodityIds = []; for (var i = 0, len = selectedRows.length; i < len; i++) { commodityIds.push(selectedRows[i].data.commodityId); } var temp = {}; temp.commodityIds = commodityIds; commodityManageModel.deleteCommodity(temp, function (result) { ctrl.load(); }); } }); } else { layer.open({ title: '提示', closeBtn: 0, content: "<div class='tac'>至少选择一个商品</div>", btn:["确定"] }); } } } ] }, gridMeta :{ columns : header["tabAll"], showCheckbox : true, afterRowRender: function (row, data) { $(row.dom).find('.js-detail').on("click", function (event) { X.publish(X.CONSTANTS.channel.menuCall, {m: "commodityManage.commodityDetail", para: {commodityId: data["commodityId"]}}); }); $(row.dom).find('.js-edit').on("click", function (event) { X.publish(X.CONSTANTS.channel.menuCall, {m: "commodityManage.addCommodity", para: {commodityId: data["commodityId"],commodityStatus: data["commodityStatus"]}}); }); }, afterTableRender: function () { ctrl.view.el.find("input[type=checkbox]:first").attr("checked", false); } }, pageInfo : { pageSize : '10', totalPages : '10', pageNo: '1', smallPapogation: { isShow: false, elem: '.js_small_papogation1' } }, //type: "GET", url : X.config.commodityManage.api.commodityManageList } }; return schemas; })(); var lists = {}; var activeTabLiInfo = 'tabAll'; /** @method initTabPage 初始化Tab页面 */ function initTabPage($elem,schema,tabPage) { var list = X.controls.getControl("List",$elem,schema); list.init(); lists[tabPage] = list; } /** @method initPage 初始化页面 */ ctrl.initPage =function (){ var tabPannel = X.controls.getControl("TabPanel",$('.js_tabPannel1'), { activeTabInfo: activeTabLiInfo, beforeChangeTab: function (tabLiInfo, targetLi, index, tabPage) { activeTabLiInfo = tabLiInfo; // 刊登状态 不同 var page = $(tabPage); if(!page.data("hasInited")){ var schema = schemas[tabLiInfo]; if(schema){ initTabPage(page,schema,tabLiInfo); } page.data("hasInited",true); } // 为了样式效果,把当前选中的前一个加上样式名 targetLi.prev().removeClass('tab_lineNone'); return true; }, afterChangeTab: function (tabLiInfo, targetLi, index, tabPage, oldTab) { activeTabLiInfo = tabLiInfo; activeTabLi = targetLi; // 为了样式效果,把当前选中的前一个加上样式名 targetLi.prev().addClass('tab_lineNone'); if(tabLiInfo != oldTab){ route.setRoute({panel:tabLiInfo}); } } }); }; /** @method load 加载 */ ctrl.load = function (para) { ctrl.rendering(); }; var route = new routerHelper("commodityManage.commodityManageList", schemas, getRoute); return ctrl; });
'use strict' const mongoose = require('mongoose'); const co = require('co'); const parallel = require('co-parallel'); const moment = require('moment'); const config = require('../config'); const Simcard = require('../app/models/simcard'); const DataPackage = require('../app/models/dataPackage'); const PurchaseHistory = require('../app/models/purchaseHistory'); const RechargeHistory = require('../app/models/rechargehistory'); const Order = require('../app/models/order'); mongoose.Promise = global.Promise; mongoose.connect(config.database); let db = mongoose.connection; // 条件为未激活 const CONDITIONS = { 'orderDate': { $lt: "2016-07-31T16:00:00.000Z" }, 'mobileAccount.statusCode': 0 }; let count = 0; const QUANTITY = 1; const DOWN_DATE = '2016-10-31T16:00:00.000Z'; db.once('open', () => { co(function* () { try { let simcards = yield Simcard.find(CONDITIONS, 'phoneno mobileAccount basicDataPackage'); let reqs = simcards.map(operate); yield* parallel(reqs, 20); } catch(err) { console.error(err); } finally { db.close(() => console.log('Database has disconnected!')); } }) .catch(err => console.error(err)); }); function* operate(simcard) { // 查询基础套餐 const basicDataPackageId = simcard.basicDataPackage._id? simcard.basicDataPackage._id.toString() : '574d9d16dc4b4b65ccb92557'; const dataPackage = yield DataPackage.findById(basicDataPackageId); // 扣除余额 const balance = simcard.mobileAccount.balance; simcard.mobileAccount.balance -= (dataPackage.fee * QUANTITY); simcard.mobileAccount.theMonthTotalData += dataPackage.packageData; simcard.mobileAccount.theMonthLeftData += dataPackage.packageData; if(simcard.mobileAccount.statusCode === 0) simcard.mobileAccount.statusCode = 1; if(balance >= 0 && simcard.mobileAccount.balance < 0) { simcard.mobileAccount.statusCode = config.statusCodeDef.halt; simcard.mobileAccount.downDate = DOWN_DATE; } yield simcard.save(); // 订购套餐包 const newPurchaseHistory = { '_simcardId': simcard._id, 'simcardNo': simcard.phoneno, 'time': '', 'dataPackage': { '_id': dataPackage._id, 'name': dataPackage.name, 'fee': dataPackage.fee }, 'quantity': 1 } //newPurchaseHistory['time'] = '2016-07-31T16:00:00.000Z'; yield PurchaseHistory.create(newPurchaseHistory); //newPurchaseHistory['time'] = '2016-08-31T16:00:00.000Z'; yield PurchaseHistory.create(newPurchaseHistory); newPurchaseHistory['time'] = '2016-09-30T16:00:00.000Z'; yield PurchaseHistory.create(newPurchaseHistory); console.log(`${++count}: 号码${simcard.phoneno}处理完毕...`); return; }
import React from 'react'; const makeProps = (props)=> { const nprops = Object.assign({}, props); delete nprops.children; return nprops; }; const makeChildren = (children)=> { if (Array.isArray(children)) { return children; } return [children]; }; const areElementsEq = (actual, expected, eq, testers)=> { if (!eq(actual.type, expected.type, testers)) { return false; } if (!eq(makeProps(actual.props), makeProps(expected.props), testers)) { return false; } const actChildren = makeChildren(actual.props.children); const expChildren = makeChildren(expected.props.children); for (let idx = 0; idx < actChildren.length; idx++) { const ac = actChildren[idx]; const ex = expChildren[idx]; if (React.isValidElement(ac)) { if (!areElementsEq(ac, ex, eq, testers)) { return false; } } else { if (!eq(ac, ex, testers)) { return false; } } } return true; }; export default { toEqualElement(util, testers) { return { compare(actual, expected) { const res = {}; res.pass = areElementsEq(actual, expected, util.equals, testers); return res; }, }; }, };
class Annotate { constructor (element, opts) { this.element = element this.options = { prompt: { width: 200, height: 50, text: 'Adding notes', className: 'annotation-prompt' }, content: { className: 'annotation-content' } } if (typeof opts === 'object') { this.options = Object.assign(this.options, opts) } this.annotations = [] this.itemCheckBoxLen = this.options.itemCheckBoxLen this.vueRoot = this.options.vueRoot this.selection = { selection: null, text: '', start: null, end: null, off: true } this.data = { arrow: null } this.init() this.bindEvents() } resizeCanvas () { this.DOM.content = this.element.querySelector('.' + this.options.content.className) this.DOM.canvas.width = this.DOM.content.clientWidth this.DOM.canvas.height = this.DOM.content.clientHeight var children = this.DOM.content.childNodes for (let i = 0; i < children.length; i++) { if (children[i].getBoundingClientRect) { var rect = children[i].getBoundingClientRect() this.data.lineHeight = rect.height break } } } changeContent (text) { this.data.content = text.replace(/\t|\n/g, '').trim() this.DOM.content.innerHTML = this.data.content } init () { this.element.style.position = 'relative' this.DOM = {} this.data.content = this.element.innerHTML.replace(/\t|\n/g, '').trim() this.element.innerHTML = '<div class="' + this.options.content.className + '">' + this.data.content + '</div>' this.DOM.content = this.element.querySelector('.' + this.options.content.className) // prompt this.DOM.prompt = document.createElement('div') this.DOM.prompt.style.width = this.options.prompt.width + 'px' this.DOM.prompt.style.minWidth = this.options.prompt.width + 'px' this.DOM.prompt.style.minHeight = this.options.prompt.height + 'px' this.DOM.prompt.style.backgroundColor = 'red' this.DOM.prompt.style.display = 'none' this.DOM.prompt.style.position = 'absolute' this.DOM.prompt.className = this.options.prompt.className // annotate button this.DOM.btnAnnotate = document.createElement('button') this.DOM.btnAnnotate.textContent = this.options.prompt.text this.DOM.prompt.appendChild(this.DOM.btnAnnotate) // canvas this.DOM.canvas = document.createElement('canvas') this.DOM.canvas.width = this.DOM.content.clientWidth this.DOM.canvas.height = this.DOM.content.clientHeight this.DOM.canvas.className = 'annotation-canvas' this.DOM.canvas = this.element.appendChild(this.DOM.canvas) this.DOM.prompt = this.element.appendChild(this.DOM.prompt) // detect line height var children = this.DOM.content.childNodes for (let i = 0; i < children.length; i++) { if (children[i].getBoundingClientRect) { var rect = children[i].getBoundingClientRect() this.data.lineHeight = rect.height break } } // detect element offset this.data.offset = { left: 0, top: 0 } rect = this.element.getBoundingClientRect() this.data.offset.top = rect.top this.data.offset.left = rect.left // load arrow img this.data.arrow = document.createElement('img') this.data.arrow.src = '/static/img/arrow.png' if (!this.data.lineHeight) { console.log('failed detecting line height') } var $this = this var node = this.element do { if (typeof node.scrollTop === 'number') { node.addEventListener('scroll', function (e) { e.stopPropagation() if ($this.isClickArea(e.clientX, e.clientY) !== false) { // arrow $this.DOM.content.style.cursor = 'pointer' } else { $this.DOM.content.style.cursor = '' } }, false) node.scrollTop = 0 } node = node.parentNode } while (node.tagName !== 'BODY') } bindEvents () { var $this = this document.addEventListener('selectionchange', function (e) { $this.setSelection(window.getSelection()) }, false) this.element.addEventListener('mouseup', function (e) { e.stopPropagation() // console.log(this) // console.log($this) $this.annotationPrompt() }, false) this.element.addEventListener('mousedown', function (e) { $this.DOM.prompt.style.display = 'none' /* * remove old selection tags before new selection if ($this.selection.off === true && ! /Firefox/.test(navigator.userAgent)) { $this.DOM.content.innerHTML = $this.data.content; } */ }, false) this.element.addEventListener('click', function (e) { e.stopPropagation() // console.log('element click') if ($this.selection.off === true) { $this.DOM.prompt.style.display = 'none' $this.DOM.content.innerHTML = $this.data.content } }, false) // this.element.addEventListener('mousemove', function (e) { // e.stopPropagation() // console.log('mousemove') // if ($this.isClickArea(e.clientX, e.clientY) !== false) { // // arrow // $this.DOM.content.style.cursor = 'pointer' // } else { // $this.DOM.content.style.cursor = '' // } // }, false) this.DOM.prompt.addEventListener('mousedown', function (e) { e.stopPropagation() }, false) this.DOM.btnAnnotate.addEventListener('click', function (e) { e.stopPropagation() $this.annotate() }, false) // update annotations on resize window.addEventListener('resize', function () { setTimeout(function () { // $this.onResize.call($this) $this.onResize() }, 100) }, false) } setSelection (selection) { // console.log('setSelection') if (selection.type !== 'Range') { this.selection.off = true return false } else { this.selection.off = false } this.selection.selection = selection this.selection.anchorNode = selection.anchorNode this.selection.focusNode = selection.focusNode var offset = { start: 0, end: 0, length: 0, startFound: false } for (let i = 0; i < this.DOM.content.childNodes.length; i++) { // skip comments if (this.DOM.content.childNodes[i].nodeType === 8) { continue } var nodeContents if (this.DOM.content.childNodes[i].nodeType === 1) { nodeContents = this.DOM.content.childNodes[i].outerHTML } else { nodeContents = this.DOM.content.childNodes[i].textContent } var isEndnode = ( selection.focusNode === this.DOM.content.childNodes[i] || selection.anchorNode === this.DOM.content.childNodes[i] || selection.focusNode.parentNode === this.DOM.content.childNodes[i] || selection.anchorNode.parentNode === this.DOM.content.childNodes[i] ) if (offset.startFound === false && !isEndnode) { offset.start += nodeContents.length } if (offset.startFound === true && !isEndnode) { offset.length += nodeContents.length } var tags if (this.DOM.content.childNodes[i].nodeType === 1) { tags = this.DOM.content.childNodes[i].outerHTML.split((this.DOM.content.childNodes[i].firstChild === null ? this.DOM.content.childNodes[i].textContent : this.DOM.content.childNodes[i].firstChild.textContent)) if (tags.length === 1) { tags[1] = '' } } else { tags = ['', ''] } if (isEndnode) { let selOffset = selection.anchorNode === this.DOM.content.childNodes[i] ? selection.anchorOffset : selection.focusOffset if (offset.startFound === false) { // found the beginning of selection offset.startFound = true // this could be the end too if (selection.anchorNode === selection.focusNode) { // the end too if (selection.anchorOffset < selection.focusOffset) { offset.start += selection.anchorOffset } else { offset.start += selection.focusOffset } offset.start += tags[0].length if (selOffset === this.DOM.content.childNodes[i].textContent.length) { offset.length += tags[1].length } offset.length += Math.max(selection.anchorOffset, selection.focusOffset) - Math.min(selection.anchorOffset, selection.focusOffset) break } else { // start but not the end if (selection.anchorNode === this.DOM.content.childNodes[i] || selection.anchorNode.parentNode === this.DOM.content.childNodes[i]) { offset.start += selection.anchorOffset offset.start += tags[0].length offset.length += (nodeContents.length - selection.anchorOffset - tags[0].length - tags[1].length) } else { offset.start += selection.focusOffset + tags[0].length offset.length += (nodeContents.length - selection.focusOffset - tags[0].length - tags[1].length) } offset.length += tags[1].length } } else { // end found // console.log('end', selOffset, this.DOM.content.childNodes[i]) offset.length += tags[0].length offset.length += this.DOM.content.childNodes[i] === selection.anchorNode || this.DOM.content.childNodes[i] === selection.anchorNode.parentNode ? selection.anchorOffset : selection.focusOffset break } } } offset.end = offset.start + offset.length this.selection.start = offset.start this.selection.end = offset.end this.selection.text = this.DOM.content.innerHTML.substring(this.selection.start, this.selection.end) // console.log(this.selection.text) } annotationPrompt (nocheck) { // console.log('annotationPrompt', nocheck) if (typeof nocheck === 'undefined' || nocheck === true) { if (this.selection.start === null || this.selection.end === null) { return false } var sel = window.getSelection() if (sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset) { return false } sel.removeAllRanges() } this.DOM.content.innerHTML = this.data.content this.DOM.prompt.style.display = 'none' // good for debugging the selection // console.log(this.DOM.content.innerHTML.substring(this.selection.start, this.selection.end)) // highlight selection this.wrap(this.selection.start, this.selection.end) // calculate offset left var offset = { top: 0, left: 0 } var node = this.element.querySelector('.annotation-selection') if (!node) { // console.log(node) } do { if (getComputedStyle(node).position !== 'static') { offset.left += node.offsetLeft offset.top += node.offsetTop } node = node.parentNode } while (node !== this.element) // offset center var size = this.DOM.content.querySelector('.annotation-selection').getBoundingClientRect() offset.left += Math.round(size.width / 2) // remove tmp span // this.DOM.content.innerHTML = html; // annotation prompt display var left = offset.left - this.options.prompt.width / 2 if (left + this.options.prompt.width / 2 > this.element.clientWidth) { left = this.element.clientWidth - this.options.prompt.width } else if (left < 0) { left = 0 } var top = offset.top - this.options.prompt.height // console.log(top) if (top < 0) { top = this.data.lineHeight + 15 } this.DOM.prompt.style.left = left + 'px' this.DOM.prompt.style.top = top + 'px' this.DOM.prompt.style.display = 'block' } annotate (annotation) { if (typeof annotation !== 'object') { annotation = { id: this.annotations.length + 1, start: this.selection.start, end: this.selection.end, bounds: [], itemRadioContents: [], itemCheckBoxContents: [], itemInputContents: [] } for (let num = 0; num < this.annotations.length; num++) { let start = this.annotations[num].start let end = this.annotations[num].end if ((annotation.start < start && annotation.end > start) || (annotation.end > end && annotation.start < end)) { console.log('re annotate') return } } for (let num = 0; num < this.itemCheckBoxLen; num++) { if (!Array.isArray(annotation.itemCheckBoxContents[num])) { // 将itemCheckBoxContents变成三维数组 this.vueRoot.$set(annotation.itemCheckBoxContents, num, []) } } } else { annotation.bounds = [] } var ctx = this.DOM.canvas.getContext('2d') // calculate bounds and draw to canvas var parts = document.querySelectorAll('.annotation-selection') for (let i = 0; i < parts.length; i++) { var rect = parts[i].getBoundingClientRect() if (!this.data.lineHeight) { this.data.lineHeight = rect.height } var rows = Math.round(rect.height / this.data.lineHeight) if (rows === 0) { rows = 1 } if (rows <= 1) { // one row var bounds = { left: rect.left - this.data.offset.left, top: rect.top - this.data.offset.top + this.scrollTop(), width: rect.width, height: rect.height } annotation.bounds.push(bounds) } else { // part spans more than 1 row var currentRow = 0 var offset = 0 bounds = false var tagOpening = false var tag = '' var openTags = [] do { this.DOM.content.innerHTML = this.data.content.substring(0, this.selection.start + offset) + '<span class="annotation-tmp">' + this.data.content.substring(this.selection.start + offset, this.selection.start + offset + 1) + '</span>' + openTags.map(function (tag) { return tag.replace('<', '</') }).join('') + this.data.content.substring(this.selection.start + offset + 1) if (this.data.content.substring(this.selection.start + offset, this.selection.start + offset + 1) === '<') { tagOpening = true offset++ tag = '<' continue } if (tagOpening === true) { if (this.data.content.substring(this.selection.start + offset, this.selection.start + offset + 1) === '>') { tagOpening = false var closingTag = false for (let j = 0; j < openTags.length; j++) { if (openTags[j].replace('<', '</') === tag) { closingTag = true openTags.splice(j, 1) break } } tag += '>' if (!closingTag) { openTags.push(tag) } tag = '' offset++ continue } else { tag += this.data.content.substring(this.selection.start + offset, this.selection.start + offset + 1) offset++ continue } } rect = this.DOM.content.querySelector('.annotation-tmp').getBoundingClientRect() if (bounds !== false) { var top = (rect.top - this.data.offset.top + this.scrollTop()) - (annotation.bounds.length > 0 ? annotation.bounds[0].top : bounds.top) var rowH = (annotation.bounds.length > 0 ? annotation.bounds[0].height : bounds.height) + 16 var cRow = Math.round(top / rowH) } else { top = 0 rowH = rect.height + 16 cRow = 0 bounds = { left: rect.left - this.data.offset.left, top: rect.top - this.data.offset.top + this.scrollTop(), width: rect.width, height: rect.height } offset++ continue } if (cRow !== currentRow) { annotation.bounds.push(bounds) bounds = { left: rect.left - this.data.offset.left, top: rect.top - this.data.offset.top + this.scrollTop(), width: rect.width, height: rect.height } currentRow = cRow } else { // in the same row bounds.width += rect.width } // next offset++ } while (this.selection.start + offset < this.selection.end) annotation.bounds.push(bounds) } } ctx.fillStyle = 'rgba(255, 0, 0, 1)' for (let i = 0; i < annotation.bounds.length; i++) { let bounds = annotation.bounds[i] ctx.fillRect(bounds.left, bounds.top + bounds.height - 1, bounds.width, 1) } // reset HTML this.DOM.content.innerHTML = this.data.content // hide prompt this.DOM.prompt.style.display = 'none' this.annotations.push(annotation) this.drawArrow(annotation) } drawArrow (annotation) { var ctx = this.DOM.canvas.getContext('2d') var bounds = annotation.bounds[annotation.bounds.length - 1] // draw arrow let arrowX = bounds.left + bounds.width - this.data.arrow.width let arrowY = bounds.top - this.data.arrow.height // console.log(arrowX, arrowY) // if (arrowY < 0) { // arrowY = 0 // } ctx.drawImage(this.data.arrow, arrowX, arrowY) // draw id var fs = 11 var ts = ctx.measureText(annotation.id) ctx.fontStyle = fs + 'px arial' ctx.fillStyle = 'black' ctx.textBaseline = 'bottom' ctx.fillText(annotation.id, bounds.left + bounds.width - ts.width - this.data.arrow.height, bounds.top) // store/update click area annotation.clickArea = { left: bounds.left + bounds.width - ts.width - this.data.arrow.height, top: bounds.top - this.data.arrow.height, width: ts.width + this.data.arrow.width, height: this.data.arrow.height } } annotateAll (annotations) { var sel = Object.assign({}, this.selection) for (let i = 0; i < annotations.length; i++) { this.selection.start = annotations[i].start this.selection.end = annotations[i].end this.wrap(annotations[i].start, annotations[i].end) this.annotate(annotations[i]) } this.selection = sel } getResult () { var annotations = [] for (let i = 0; i < this.annotations.length; i++) { let annotation = { id: this.annotations[i].id, start: this.annotations[i].start, end: this.annotations[i].end, itemRadioContents: this.annotations[i].itemRadioContents, itemCheckBoxContents: this.annotations[i].itemCheckBoxContents, itemInputContents: this.annotations[i].itemInputContents } annotations.push(annotation) } return annotations } Load (annotations) { // this.annotations = annotations this.annotateAll(annotations) } HideAll () { var annotations = document.querySelectorAll('.annotation') if (annotations == null) { return true } for (var i = 0; i < annotations.length; i++) { annotations[i].className = 'annotation annotation-hidden' } } ShowAll () { var annotations = document.querySelectorAll('.annotation') if (annotations == null) { return true } for (var i = 0; i < annotations.length; i++) { annotations[i].className = 'annotation' } } Reset () { this.annotations.splice(0, this.annotations.length) this.annotations.length = 0 this.DOM.content.innerHTML = this.data.content var ctx = this.DOM.canvas.getContext('2d') ctx.clearRect(0, 0, this.DOM.canvas.width, this.DOM.canvas.height) } getById (annotationId) { for (var i = 0; i < this.annotations.length; i++) { if (this.annotations[i].id + '' === annotationId) { return this.annotations[i] } } return false } wrap (sStart, sEnd) { var offset = 0 var nodes = Array.from(this.DOM.content.childNodes) for (let i = 0; i < nodes.length; i++) { // skip comments if (nodes[i].nodeType === 8) { continue } var nodeContents if (nodes[i].nodeType !== 3) { nodeContents = nodes[i].outerHTML } else { nodeContents = nodes[i].textContent } var offsetStart = offset offset += nodeContents.length // check if this element should be affected if ( (offsetStart >= sStart && offsetStart < sEnd) || (offsetStart <= sStart && offset > sStart) ) { var start = Math.max(0, sStart - offsetStart) var end = Math.min(sEnd - offsetStart, nodeContents.length) if (nodes[i].nodeType === 1) { var tags = nodes[i].outerHTML.split(nodes[i].firstChild === null ? nodes[i].textContent : nodes[i].firstChild.textContent) if (tags.length > 2) { continue } if (sEnd < offset) { // end -= tags[1].length; } else { end -= tags[1].length } if (sStart > offsetStart) { } else { // start += tags[0].length; } if (nodes[i].tagName === 'BR') { continue } var replacement = ( nodes[i].outerHTML.substring(0, start) + '<div class="annotation-selection">' + nodes[i].outerHTML.substring(start, end) + '</div>' + nodes[i].outerHTML.substring(end) ) nodes[i].insertAdjacentHTML('beforebegin', replacement) nodes[i].parentNode.removeChild(nodes[i]) } else { // var oldLen = nodes[i].textContent.length var pre = nodes[i].textContent.substring(0, start) var suf = nodes[i].textContent.substring(end) var content = document.createElement('div') content.className = 'annotation-selection' content.textContent = nodes[i].textContent.substring(start, end) content = nodes[i].parentNode.insertBefore(content, nodes[i]) var html = pre + content.outerHTML + suf content.insertAdjacentHTML('beforebegin', html) nodes[i].parentNode.removeChild(content) nodes[i].parentNode.removeChild(nodes[i]) } } } } deleteAnnotation (annotationId) { for (let i = 0; i < this.annotations.length; i++) { if (this.annotations[i].id === annotationId) { var ctx = this.DOM.canvas.getContext('2d') ctx.clearRect(0, 0, this.DOM.canvas.width, this.DOM.canvas.height) this.annotations.splice(i, 1) let annotations = this.getResult() this.annotations.length = 0 for (let j = 0; j < annotations.length; j++) { if (annotations[j].id > annotationId) { annotations[j].id-- // console.log(annotations[j]) } } this.annotateAll(annotations) return true } } return false } scrollTop () { var top = 0 var node = this.element do { if (typeof node.scrollTop === 'number') { top += node.scrollTop } node = node.parentNode } while (node.tagName !== 'BODY') return top } isClickArea (x, y) { // calculate offset left var offset = { top: 0, left: 0 } var node = this.element do { if (getComputedStyle(node).position !== 'static') { offset.left += node.offsetLeft offset.top += node.offsetTop } node = node.parentNode } while (node !== document.body) x -= offset.left y -= offset.top for (let i = 0; i < this.annotations.length; i++) { var ca = this.annotations[i].clickArea if (typeof ca === 'undefined') { continue } var xIn = x > ca.left && x < ca.left + ca.width var yIn = y > ca.top && y < ca.top + ca.height if (xIn && yIn) { return true } } return false } getClickArea (x, y) { // calculate offset left var offset = { top: 0, left: 0 } var node = this.element do { if (getComputedStyle(node).position !== 'static') { offset.left += node.offsetLeft offset.top += node.offsetTop } node = node.parentNode } while (node !== document.body) x -= offset.left y -= offset.top - this.scrollTop() for (let i = 0; i < this.annotations.length; i++) { var ca = this.annotations[i].clickArea if (typeof ca === 'undefined') { continue } var xIn = x > ca.left && x < ca.left + ca.width var yIn = y > ca.top && y < ca.top + ca.height if (xIn && yIn) { return this.annotations[i] } } return false } onResize () { // console.log('onResize') // console.log(this.DOM.content) this.DOM.canvas.width = this.DOM.content.clientWidth this.DOM.canvas.height = this.DOM.content.clientHeight let annotations = this.getResult() this.annotations.length = 0 this.annotateAll(annotations) } } export default Annotate
$(document).ready( () => { const modal = $("#modal-box")[0]; const formEdit = $("#editForm"); $(document).on("click", ".edit-btn", () => { modal.style.display = "block"; // Get data-id of edit-button and assign it to edit-form let studentId = $(event.target).attr('data-id'); formEdit.attr('data-id', studentId); // Get data-name of edit-button and assign it to edit-form // to use it instead of empty input let studentName = $(event.target).attr('data-name'); formEdit.attr('data-name', studentName); $("#editName").attr('value', studentName); // Get data-surname of edit-button and assign it to edit-form // to use it instead of empty input let studentSurname = $(event.target).attr('data-surname'); formEdit.attr('data-surname', studentSurname); $("#editSurname").attr('value', studentSurname); }); // close modal-box --> click close-button or click outside modal-box const closeBtn = document.getElementsByClassName("close")[0]; closeBtn.onclick = () => { modal.style.display = "none"; } window.onclick = (event) => { if (event.target == modal) { modal.style.display = "none"; } } });
/*(function () {*/ 'use strict'; dmtApplication.factory("invoiceService", invoiceService); function invoiceService($http, __env, $window) { var service = { getAllInVoices : getAllInVoices, getAllInvoiceType : getAllInvoiceType, create : create, update : update, deleteRow : deleteRow }, url = __env.baseUrl + __env.context return service; function getAllInVoices() { return $http.get(url + "/invoices/readAll"); } function getAllInvoiceType() { return $http.get("./mock/invoiceType.json"); } function create(jsonData) { return $http({ url : url + '/invoices/create', method : "POST", data : jsonData }).then(function(response) { // success }, function(response) { // optional // failed }); } function update(jsonData) { return $http({ url : url + '/invoices/update', method : "POST", data : jsonData }).then(function(response) { // success }, function(response) { // optional // failed }); } function deleteRow(data) { return $http({ url : url + '/invoices/delete?id=' + data, method : "POST" }).then(function(response) { // success }, function(response) { // optional // failed }); } } /* }()); */
alert("olá mundo"); console.log(document.querySelector(".titulo_principal")); var titulo = document.querySelector(".titulo_principal"); titulo.textContent = "Avaliação Fisica Senai"; console.log(titulo.textContent); var paciente = document.querySelectorAll(".paciente"); for(var i=0;i<paciente.length;i++){ var tdnome = paciente[i].querySelector(".info-nome"); var nomePaciente = tdnome.textContent; console.log(nomePaciente); var tdpeso = paciente[i].querySelector(".info-peso"); var pesoPaciente = tdpeso.textContent; console.log(pesoPaciente); var tdaltura = paciente[i].querySelector(".info-altura"); var alturaPaciente = tdaltura.textContent; console.log(alturaPaciente); var tdgordura = paciente[i].querySelector(".info-gordura"); var gorduraPaciente = tdgordura.textContent; console.log(gorduraPaciente); var tdclassificacao = paciente[i].querySelector(".info-classificacao"); var classificacaoPaciente = tdclassificacao.textContent; console.log(classificacaoPaciente); console.log( "O paciente "+ nomePaciente +" possui "+pesoPaciente+" kg e "+alturaPaciente+" de altura"); var idImc = paciente[i].querySelector(".info-imc"); var pesoValido=validaPeso(pesoPaciente); var alturaValida=validaAltura(alturaPaciente); if(alturaValida && pesoValido){ console.log(idImc); var imc = calculaIMC(pesoPaciente,alturaPaciente); console.log(imc); paciente[i].classList.remove("cor"); validaClassificacao(imc,tdclassificacao,tdnome); idImc.textContent= imc; } else{ // idImc.style.color="red"; idImc.classList.add("invalido"); idImc.textContent = "Peso ou altura inválida"; tdclassificacao.textContent = "Peso ou altura inválida"; } } function calculaIMC(peso,altura){ return (peso / (altura * altura)).toFixed(2); } function validaPeso(pesoPaciente){ if(pesoPaciente<=0 || pesoPaciente>= 500){ pesoValido=false; console.log("Peso Inválido " + pesoValido); } else{ pesoValido=true; console.log("Peso Valido " + pesoValido); } return pesoValido; } function validaAltura(alturaPaciente){ if(alturaPaciente<=0 || alturaPaciente>= 3.0){ alturaValida=false; console.log("Altura Inválido " + alturaValida); } else{ alturaValida=true; console.log("Altura Valido " + pesoValido); } return alturaValida; } function validaClassificacao(imc,tdclassificacao,tdnome){ if(imc<=18.5){ tdclassificacao.textContent="Desnutrição"; tdclassificacao.style.background="violet"; tdnome.style.background="red"; } else if(imc>=18.5 && imc<=24.9){ tdclassificacao.textContent="Peso Normal"; console.log("Peso Normal"); tdclassificacao.style.background="lightblue"; } else if(imc>=25.0 && imc <=29.9){ tdclassificacao.textContent="Pré Obesidade"; console.log("Pré Obesidade"); tdclassificacao.style.background="lightyellow"; } else if(imc>=30 && imc <=34.9){ tdclassificacao.textContent="Obesidade Grau 1"; console.log("Obesidade Grau 1"); tdclassificacao.style.background="#BBFFFF"; } else if(imc>=35 && imc <=39.9){ tdclassificacao.textContent="Obesidade Grau 2"; console.log("Obesidade Grau 2"); tdclassificacao.style.background="lightgreen"; } else if(imc>40){ tdclassificacao.textContent="Obesidade Grau 3"; console.log("Obesidade Grau 3"); tdclassificacao.style.background="orange"; tdnome.style.background="red"; } }
import "./App.css"; import { useState } from "react"; function Header(props) { return ( <header> <p> Hello {props.name} </p> <button onClick={props.click}>Trocar usuário</button> {props.children} <hr /> </header> ) } function Form() { const [nome, setNome] = useState(""); const handleNome = (e) => { setNome(e.target.value) } return ( <> <p>{nome}</p> <input type="text" placeholder="Digite seu nome" value= {nome} onChange={handleNome}/> </> ) } function App() { //useState é uma variavel de estado const [user, setUser] = useState("Fulano"); const handleClick = () => { if (user === "Fulano") setUser("Bianca") else setUser("Fulano") } return ( <div className="App"> <Header name="Bianca" click={handleClick}> <p>Filho 1</p> <p>Filho 2</p> </Header> <p> My React App </p> <p> Nome do usuário: {user} </p> <hr /> <Form /> </div> ); } export default App;
const express = require('express'); const bodyParser = require('body-parser'); const PORT = process.env.PORT || 3000; const app = express(); // body parser app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // set header app.use(function(req, res, next) { res.setHeader('charset', 'utf-8'); next(); }); // controllers const clientController = require('./client/controllers/shipmentController.js'); app.get('/', (req, res) => { res.send('Hello world!'); }); clientController(app); app.listen(PORT, () => console.log('App listen on PORT ' + PORT)); module.exports = app; // MAKE BETTER // I CAN DO IT
// include a script programmatically, by appending it // to the head of the page. guards against re-insertion, // and returns 'loaded' when successful. function liveRequire(x, callback) { var scripts = document.head.getElementsByTagName('script'); for (var i = 0; i < scripts.length; i++) { if (scripts[i].src == x) return 'loaded'; } var scr = document.head.appendChild(document.createElement('script')); scr.onload = callback; scr.src = x; } if (typeof module !== 'undefined') module.exports = liveRequire;
#!/usr/bin/env node require("../dist/backup");
import React, {useState, useEffect} from "react"; import { useDispatch} from "react-redux"; import { validateTokenAPICreator } from "../redux/actions/auth"; import Header from "../components/Header"; import Navbar from "../components/Navbar"; import Main from "../components/Main"; import Aside from "../components/Aside"; import FilterModal from "../components/modals/FilterModal" import "../App.css"; import BottomNav from "../components/BottomNav"; export default function Home () { const [state, setState] = useState({isShow: true, modalShow:false}) const [page, setPage] = useState(1) const handleHideShow = () => { setState({...state, isShow: !state.isShow }); }; const dispatch = useDispatch() useEffect(() => { dispatch(validateTokenAPICreator()) }, [dispatch]) return ( <> <FilterModal onHide={() => setState({...state, modalShow:false})} show={state.modalShow} /> <div className='app'> <Header hideShowFunction={handleHideShow} onHide={() => setState({...state, modalShow:true})} setPage={setPage} /> <div className='wrapper'> <div className='nav-main'> {state.isShow ? ( <Navbar/> ) : null} <Main setPage={setPage} page={page} /> </div> <Aside /> </div> </div> <BottomNav/> </> ); }
import isPlainObject from 'lodash/lang/isPlainObject'; export default function meldPartialState(handler, initialState, previousState) { let stateOut = previousState; // @todo support for Maps! if (isPlainObject(initialState)) { const isComplete = isEquivStructure(initialState, previousState); if (!isComplete) { stateOut = Object.assign({}, initialState, previousState); } } return stateOut; } function isEquivStructure(obj1, obj2) { let prop; for (prop in obj1) { if (obj1.hasOwnProperty(prop) && !obj2.hasOwnProperty(prop)) return false; } for (prop in obj2) { if (obj2.hasOwnProperty(prop) && !obj1.hasOwnProperty(prop)) return false; } return true; }
import React from 'react'; import {Form, Message} from 'semantic-ui-react'; import LoadingButton from './common/LoadingButton'; const ReplyForm = (props) => { const {onSubmit, status, content} = props; return ( <Form reply onSubmit={onSubmit}> <Form.TextArea id='comment__reply'/> <LoadingButton labelPosition='left' icon='edit' type='submit' primary content={content ||'Add Reply'} status={status} /> </Form> ) } export default ReplyForm;
const { SERVER_ERROR } = require('../configs/constants'); const CentralizedErrorHandler = ((err, req, res, next) => { // если у ошибки нет статуса, выставляем 500 const { statusCode = 500, message } = err; // проверяем статус и выставляем сообщение в зависимости от него res.status(statusCode).send({ message: statusCode === 500 ? SERVER_ERROR : message }); next(); }); module.exports = { CentralizedErrorHandler, };