text
stringlengths
7
3.69M
import React, {useEffect, useState, useRef} from 'react'; import {View, SafeAreaView, StyleSheet} from 'react-native'; import PropTypes from 'prop-types'; import {useRoute} from '@react-navigation/native'; import {Searchbar} from 'react-native-paper'; import {Colors} from '../../theme'; import {Text, MovieItem, VerticalList} from '../../components'; function Search(props) { const route = useRoute(); const [moviesList, setMoviesList] = useState([]); const [searchQuery, setSearchQuery] = React.useState(''); const inputRef = useRef(null); let searchTimer; useEffect(() => { inputRef.current.focus(); }, []); const _getSearchData = (text) => { setSearchQuery(text) if (text.length === 0) { setMoviesList([]) } else if (text.length > 2) { const data = { query: text, page: 1 } clearTimeout(searchTimer); searchTimer = setTimeout(() => { props.getSearchAction(data) .then((res) => { setMoviesList(res.results); }) .catch((err) => { console.log(err); }); }, 400); } }; return ( <> <SafeAreaView style={{ flex: 1, backgroundColor: Colors.white }}> <Searchbar placeholder="Search" onChangeText={_getSearchData} value={searchQuery} ref={inputRef} /> <VerticalList data={moviesList} /> </SafeAreaView> </> ); } const styles = StyleSheet.create({}); Search.propTypes = { getSearchAction: PropTypes.func.isRequired, }; Search.defaultProps = {}; export default Search;
import React from 'react'; import {Popover,Form,Input,Button,Select} from 'antd' import BaseComponent from "./Base/BaseComponent"; export default class QuickPropover extends BaseComponent { render() { let { content,title,triggerText,placement='top' } = this.props; return ( <Popover placement={placement} onVisibleChange={v=> this.setState({popover:v})} visible={this.state.popover} title={title} content={content} trigger="click"> <Button>{triggerText}</Button> </Popover> ) } }
/** * Created by abe on 2/14/15. */ (function(){ var app = angular.module('musicApp', ['ngResource', 'ngMaterial', 'ngRoute']); app.config(['$mdThemingProvider', '$mdIconProvider', '$routeProvider', function($mdThemingProvider, $mdIconProvider, $routeProvider){ $mdIconProvider .icon('play', '/images/icons/av/svg/design/ic_play_circle_outline_48px.svg', 48) .icon('pause', '/images/icons/av/svg/design/ic_pause_circle_outline_48px.svg', 48) .icon('next', '/images/icons/av/svg/design/ic_skip_next_48px.svg', 48) .icon('previous', '/images/icons/av/svg/design/ic_skip_previous_48px.svg', 48) .icon('playlist_add', '/images/icons/av/svg/design/ic_playlist_add_48px.svg') .icon('repeat', '/images/icons/av/svg/design/ic_repeat_48px.svg') .icon('repeat_one', '/images/icons/av/svg/design/ic_repeat_one_48px.svg') .icon('shuffle', '/images/icons/av/svg/design/ic_shuffle_48px.svg'); $mdThemingProvider.theme('default') .primaryPalette('blue') .accentPalette('deep-orange'); }]) .factory('Song', ['$resource', function($resource){ return $resource('/api/songs/:id'); }]) .factory('Auth', ['$resource', function($resource){ return $resource('/api/'); }]) .factory('Playlist', ['$resource', function($resource){ return $resource('/api/playlists/:title'); }]) .factory('player',['$rootScope', '$interval', function($rootScope, $interval) { var player, queue = [], paused = false, audio = document.getElementById('player'), curr = { data: {}, url: '', albumArt: '', index: 0 }; function updateCurrent(){ player.current.data = queue[player.current.index].data; player.current.url = queue[player.current.index].url; player.current.albumArt = queue[player.current.index].albumArt; //console.log(current.data.title); } player = { queue: queue, current: curr, playing: false, repeat: false, shuffle: false, shuffleCnt: 0, oldRand: 0, play: function(){ if (!queue.length) return; updateCurrent(); audio.play(); player.playing = true; paused = false; }, pause: function(){ if (player.playing) { audio.pause(); player.playing = false; paused = true; } }, next: function() { if (!queue.length) return; paused = false; if (player.shuffle){ var randIndex = Math.floor((Math.random() * player.queue.length)); player.oldRand = randIndex; player.current.index = randIndex; player.shuffleCnt++; updateCurrent(); } else if (queue.length > (player.current.index + 1)) { player.current.index++; updateCurrent(); } else { player.current.index = 0; updateCurrent(); } console.log('next: ' + player.current.index); player.play(); }, previous: function() { if (!queue.length) return; paused = false; if (player.shuffle){ player.current.index = player.oldRand; updateCurrent(); } else if (player.current.index > 0) { player.current.index--; updateCurrent(); } else { player.current.index = queue.length - 1; updateCurrent(); } console.log('previous: ' + player.current.index); player.play(); }, changeTime: function(t) { audio.currentTime = player.ctime; } }; $interval(function(){ player.ctime = audio.currentTime.toFixed(1); player.duration = audio.duration.toFixed(1); },100); queue.add = function(song){ queue.push(song); }; queue.remove = function(index){ if (index == player.current.index) player.next(); queue.splice(index, 1); }; audio.addEventListener('ended', function() { if (player.current.index+1 == queue.length){ if (player.repeat || player.shuffle && !(player.shuffleCnt >= queue.length-1)){ $rootScope.$apply(player.next()); } else { console.log('playlist ended'); player.playing = false; player.shuffleCnt = 0; } } else { console.log('track ended'); $rootScope.$apply(player.next()); } }, false); return player; }]); app.controller('mainCtrl', ['$scope', '$sce', '$mdDialog', 'Song', 'Auth', 'player', 'Playlist', function($scope, $sce, $mdDialog, Song, Auth, player, Playlist){ Auth.get(); $scope.songs = Song.query(); $scope.player = player; $scope.$on('queueUpdate', function() { player.current.data = player.queue[player.current.index].data; player.current.url = player.queue[player.current.index].url; player.current.albumArt = player.queue[player.current.index].albumArt; }); $scope.trust = function(url){ return $sce.trustAsResourceUrl(url); }; $scope.addQueue = function(song){ Song.get({'id': song.id}) .$promise.then(function(res){ var item = { data: song, url: $sce.trustAsResourceUrl(res.streamUrl), albumArt: $sce.trustAsResourceUrl(angular.isDefined(song.albumArtRef) ? song.albumArtRef[0].url : "/images/default_album_art.png" ) }; console.log(item.data.title); player.queue.add(item); $scope.$emit('queueUpdate'); }); }; $scope.removeQueue = function(index){ player.queue.remove(index); $scope.$emit('queueUpdate'); }; $scope.showPlaylistSave = function(ev){ $mdDialog.show({ controller: function($scope, $mdDialog){ $scope.cancel = function(){ $mdDialog.cancel(); }; $scope.ok = function(title) { $mdDialog.hide(title); } }, templateUrl: '/partials/saveDialog.tmpl.html', targetEvent: ev }) .then(function(title){ console.log(title); $scope.postData = {"title": title, queue: []} player.queue.forEach(function(song){ $scope.postData.queue.push(song.data); }); console.log('saving'); $scope.playlist = new Playlist($scope.postData); $scope.playlist.$save(); }) } }]); })();
import React, { PureComponent } from "react"; import SelfCheckDataService from "../../services/selfcheck.service"; import UserService from "../../services/user.service"; import Form from "react-validation/build/form"; import Input from "react-validation/build/input"; import CheckButton from "react-validation/build/button"; import AuthService from "../../services/auth.service"; // import Navigation from "../navigation/navigation" import BurgerNavigation from "../navigation/burger-navigation" import jsPDF from 'jspdf' import moment from "moment"; import selfcheck from "../images/selfcheck.gif" import "../../App.css"; const required = value => { if (!value) { return ( <div className="alert alert-danger" role="alert"> This field is required! </div> ); } }; export default class AddSelfCheck extends PureComponent { constructor(props) { super(props); this.onChangeAge = this.onChangeAge.bind(this); this.onChangeGender = this.onChangeGender.bind(this); this.onChangeContact = this.onChangeContact.bind(this); this.onChangeQuarantine = this.onChangeQuarantine.bind(this); this.onChangeTemperature = this.onChangeTemperature.bind(this); this.onChangeDrycough = this.onChangeDrycough.bind(this); this.onChangeFatigue = this.onChangeFatigue.bind(this); this.onChangeSoreThroat = this.onChangeSoreThroat.bind(this); this.onChangeBreathe = this.onChangeBreathe.bind(this); this.onChangeBodypain = this.onChangeBodypain.bind(this); this.onChangeDiarrhoea = this.onChangeDiarrhoea.bind(this); this.onChangeRunnynose = this.onChangeRunnynose.bind(this); this.onChangeNausea = this.onChangeNausea.bind(this); this.onChangeReturnfromcountry = this.onChangeReturnfromcountry.bind(this); this.handleSelfCheck = this.handleSelfCheck.bind(this); this.state = { email: localStorage.getItem("email"), fullname: localStorage.getItem("fullname"), age: "", gender: "", contact: "", temperature: "", quarantine: "", drycough: "", fatigue: "", sorethroat: "", breathe: "", bodypain: "", diarrhoea: "", runnynose: "", nausea: "", returnfromcountry: "", status: "", errormessage: "", rightcontent: "", wrongcontent: "", successful: false, message: "", submitted: false, totalcount: 0, totalpersons: "", currentUser: AuthService.getCurrentUser(), }; } onChangeContact(e) { this.setState({ contact: e.target.value }); } onChangeAge(e) { this.setState({ age: e.target.value }); } onChangeGender(e) { this.setState({ gender: e.target.value }); } onChangeTemperature(e) { this.setState({ temperature: e.target.value }); } onChangeQuarantine(e) { this.setState({ quarantine: e.target.value }); } onChangeDrycough(e) { this.setState({ drycough: e.target.value }); } onChangeFatigue(e) { this.setState({ fatigue: e.target.value }); } onChangeSoreThroat(e) { this.setState({ sorethroat: e.target.value }); } onChangeBreathe(e) { this.setState({ breathe: e.target.value }); } onChangeBodypain(e) { this.setState({ bodypain: e.target.value }); } onChangeDiarrhoea(e) { this.setState({ diarrhoea: e.target.value }); } onChangeRunnynose(e) { this.setState({ runnynose: e.target.value }); } onChangeNausea(e) { this.setState({ nausea: e.target.value }); } onChangeReturnfromcountry(e) { this.setState({ returnfromcountry: e.target.value }); } handleSelfCheck(e) { e.preventDefault(); this.setState({ fullname: this.state.currentUser.fullname, message: "", successful: false }); this.form.validateAll(); var count = 0; if (this.checkBtn.context._errors.length === 0) { if (this.state.quarantine === "true") { count = count + 1; } else { count = count - 1; } if (this.state.sorethroat === "true") { count = count + 1; } else { count = count - 1; } if (this.state.drycough === "true") { count = count + 1; } else { count = count - 1; } if (this.state.fatigue === "true") { count = count + 1; } else { count = count - 1; } if (this.state.breathe === "true") { count = count + 1; } else { count = count - 1; } if (this.state.bodypain === "true") { count = count + 1; } else { count = count - 1; } if (this.state.diarrhoea === "true") { count = count + 1; } else { count = count - 1; } if (this.state.runnynose === "true") { count = count + 1; } else { count = count - 1; } if (this.state.nausea === "true") { count = count + 1; } else { count = count - 1; } if (this.state.returnfromcountry === "true") { count = count + 1; } else { count = count - 1; } console.log(count) this.setState({ totalcount: count }) var cstatus = ""; if (count >= 4) { cstatus = "Positive" } else { cstatus = "Negative" } console.log(cstatus) var data = { profession: this.state.profession, age: this.state.age, gender: this.state.gender, contact: this.state.contact, temperature: this.state.temperature, quarantine: this.state.quarantine, drycough: this.state.drycough, fatigue: this.state.fatigue, sorethroat: this.state.sorethroat, breathe: this.state.breathe, bodypain: this.state.bodypain, diarrhoea: this.state.diarrhoea, runnynose: this.state.runnynose, nausea: this.state.nausea, status: cstatus, returnfromcountry: this.state.returnfromcountry, currentuserfullname: this.state.currentUser.fullname, currentuseremail: this.state.currentUser.email, currentusername: this.state.currentUser.username, }; SelfCheckDataService.create(data) .then( response => { this.setState({ message: response.data.message, successful: true }); if (this.state.totalcount >= 4) { var lMargin = 15; //left margin in mm var rMargin = 15; //right margin in mm var pdfInMM = 210; // width of A4 in mm var doc = new jsPDF("p", "mm", "a4"); doc.setFontSize(18); doc.setFont('times') doc.setFontType('bold') doc.text(15, 25, 'Self Check Positive Report') doc.setFontSize(16); doc.setFont('times') doc.setFontType('normal') doc.text(15, 35, 'Your username: ' + this.state.currentUser.username) doc.setFontSize(16); doc.setFont('times') doc.setFontType('normal') doc.text(15, 42, 'Your contact number: ' + this.state.contact) doc.setFontSize(16); doc.setFont('times') doc.setFontType('normal') doc.text(15, 50, 'Date: ' + moment().format("dddd, MMMM Do YYYY, h:mm:ss a")) doc.setFontSize(14); doc.setFont('times') doc.setFontType('normal') doc.text(15, 65, 'Dear Sir/Madam,') doc.setFontSize(14); doc.setFont('times') doc.setFontType('normal') var paragraph = "As per you submissions and answers, it seems that you are experiencing matching symptoms of Covid-19 virus."; var lines = doc.splitTextToSize(paragraph, (pdfInMM - lMargin - rMargin)); doc.text(lMargin, 72, lines); doc.setFontSize(14); doc.setFont('times') var par1 = "However, a proper PCR test is still recommended to detect and confirm the transmission and existence of virus within you. Thus, keep calm and to keep your loved ones and people around you safe and away from chances of transmission, you should still take necessary precautions such as maintaing safe distance from the prople around you and keep yourself in home quaratine, avoid the contact with anyone else until further confirmation is done." var lines1 = doc.splitTextToSize(par1, (pdfInMM - lMargin - rMargin)); doc.text(lMargin, 85, lines1); doc.setFontSize(14); doc.setFont('times') var par2 = "To do that, please contact authorized testing facilities and hospitals to perform a proper test for confirmation." var lines2 = doc.splitTextToSize(par2, (pdfInMM - lMargin - rMargin)); doc.text(lMargin, 115, lines2); doc.setFontSize(14); doc.setFont('times') var par3 = 'Keep yourself and others around you safe by following provided guideline to stop the possibility of spreading the virus and contact the needed authorities as soon as possible.' var lines3 = doc.splitTextToSize(par3, (pdfInMM - lMargin - rMargin)); doc.text(lMargin, 127, lines3); doc.setFontSize(14); doc.setFont('times') doc.text(15, 142, 'List of links') doc.textWithLink('https://covid19.mohp.gov.np/', 15, 148, { url: 'https://covid19.mohp.gov.np/' }); doc.textWithLink('https://www.who.int/', 15, 154, { url: 'https://www.who.int/' }); doc.setFontSize(14); doc.setFont('times') doc.text(15, 165, 'Contact Numbers') doc.text(15, 172, '9851-255-834') doc.text(15, 178, '9851-255-837') doc.text(15, 184, '9851-255-839') doc.setFontSize(14); doc.setFont('times') doc.text(60, 165, 'Hotline Numbers') doc.text(60, 172, '1115') doc.text(60, 178, '1133') doc.setFontSize(14); doc.setFont('times') doc.text(15, 197, 'Thank You!') // Save the Data doc.save(this.state.currentUser.fullname + '-self-check-report-positive.pdf'); } else { var plMargin = 15; //left margin in mm var prMargin = 15; //right margin in mm var ppdfInMM = 210; // width of A4 in mm var negativedoc = new jsPDF("p", "mm", "a4"); negativedoc.setFontSize(18); negativedoc.setFont('times') negativedoc.setFontType('bold') negativedoc.text(15, 25, 'Self Check Negative Report') negativedoc.setFontSize(16); negativedoc.setFont('times') negativedoc.setFontType('normal') negativedoc.text(15, 35, 'Your username: ' + this.state.currentUser.username) negativedoc.setFontSize(16); negativedoc.setFont('times') negativedoc.setFontType('normal') negativedoc.text(15, 42, 'Your contact number: ' + this.state.contact) negativedoc.setFontSize(16); negativedoc.setFont('times') negativedoc.setFontType('normal') negativedoc.text(15, 50, 'Date: ' + moment().format("dddd, MMMM Do YYYY, h:mm:ss a")) negativedoc.setFontSize(14); negativedoc.setFont('times') negativedoc.setFontType('normal') negativedoc.text(15, 65, 'Dear Sir/Madam,') negativedoc.setFontSize(14); negativedoc.setFont('times') negativedoc.setFontType('normal') var pparagraph = "As per you submissions and answers, it seems that you are momentarily safe from Covid-19 virus."; var plines = negativedoc.splitTextToSize(pparagraph, (ppdfInMM - plMargin - prMargin)); negativedoc.text(plMargin, 72, plines); negativedoc.setFontSize(14); negativedoc.setFont('times') var ppar1 = "However, a proper PCR test is recommended to detect and confirm the transmission and existence of virus. Thus, you should still take necessary precautions such as maintaing safe distance from large group, maintain atleast 2 to 3 meter distance if you must go outside and always wear a mask. Use sanitizer or soap after your outside visits." var plines1 = negativedoc.splitTextToSize(ppar1, (ppdfInMM - plMargin - prMargin)); negativedoc.text(plMargin, 85, plines1); negativedoc.setFontSize(14); negativedoc.setFont('times') var ppar2 = "We have listed few contact numbers to help you get in touch with proper testing authorities as well as hospitals." var plines2 = negativedoc.splitTextToSize(ppar2, (ppdfInMM - plMargin - prMargin)); negativedoc.text(plMargin, 110, plines2); negativedoc.setFontSize(14); negativedoc.setFont('times') var ppar3 = 'Stay safe and follow provided guideline to stop the spread of virus.' var plines3 = negativedoc.splitTextToSize(ppar3, (ppdfInMM - plMargin - prMargin)); negativedoc.text(plMargin, 125, plines3); negativedoc.setFontSize(14); negativedoc.setFont('times') negativedoc.text(15, 137, 'List of links') negativedoc.textWithLink('https://covid19.mohp.gov.np/', 15, 143, { url: 'https://covid19.mohp.gov.np/' }); negativedoc.textWithLink('https://www.who.int/', 15, 150, { url: 'https://www.who.int/' }); negativedoc.setFontSize(14); negativedoc.setFont('times') negativedoc.text(15, 160, 'Contact Numbers') negativedoc.text(15, 167, '9851-255-834') negativedoc.text(15, 173, '9851-255-837') negativedoc.text(15, 179, '9851-255-839') negativedoc.setFontSize(14); negativedoc.setFont('times') negativedoc.text(60, 160, 'Hotline Numbers') negativedoc.text(60, 167, '1115') negativedoc.text(60, 173, '1133') negativedoc.setFontSize(14); negativedoc.setFont('times') negativedoc.text(15, 192, 'Thank You!') // Save the Data negativedoc.save(this.state.currentUser.fullname + '-self-check-report-negative.pdf'); } setTimeout(function () { window.location.reload() }, 3000); }, error => { const resMessage = (error.response && error.response.data && error.response.data.message) || error.message || error.toString(); this.setState({ successful: false, message: resMessage }); } ); } } componentDidMount() { UserService.getUserBoard().then( response => { this.setState({ rightcontent: response.data }); }, error => { this.setState({ wrongcontent: (error.response && error.response.data && error.response.data.message) || error.message || error.toString() }); } ); } render() { if (this.state.wrongcontent) { return <div><BurgerNavigation /> <div classNameName="container custom-container">{this.state.wrongcontent}</div></div> } else { return ( <div><BurgerNavigation /> <div className="container custom-container"> <h2 className="text-center">" It is always good to be concious about your own health "</h2> <img src={selfcheck} alt="suspect-one" className="rounded mx-auto d-block img-fluid" style={{ height: "230px", width: "auto" }} /> <div className="container user_card"> <div className="col-md-12"> <Form onSubmit={this.handleSelfCheck} ref={c => { this.form = c; }} > {!this.state.successful && ( <div> <h6 className="text-center">This procedure may seem time consuming but it is worth your health. </h6> <div className="form-group row"> <label htmlFor="fullname" className="col-sm-2 col-form-label">Fullname :</label> <div className="col-sm-10"> <input type="text" name="fullname" className="form-control-plaintext" id="staticEmail" value={this.state.fullname} disabled /> </div> </div> <div className="form-group row"> <label htmlFor="email" className="col-sm-2 col-form-label">Email :</label> <div className="col-sm-10"> <input type="email" name="email" className="form-control-plaintext" id="staticEmail" value={this.state.email} disabled /> </div> </div> <div className="form-group row"> <label htmlFor="contact" className="col-sm-2 col-form-label">Contact no. :</label> <div className="col-sm-10"> <input type="text" className="form-control" placeholder="contact" value={this.state.contact} onChange={this.onChangeContact} name="contact" validations={[required]} /> </div> </div> <div className="form-group row"> <label htmlFor="age" className="col-sm-2 col-form-label">Age :</label> <div className="col-sm-10"> <input type="number" className="form-control" placeholder="your age here" value={this.state.age} id="age" required onChange={this.onChangeAge} name="age" validations={[required]} /> </div> </div> <div className="form-group row"> <label htmlFor="gender" className="col-sm-2 col-form-label">Gender :</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="Male" checked={this.state.gender === "Male"} onChange={this.onChangeGender} /> <label className="form-check-label" htmlFor="inlineRadio1">Male</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="Female" checked={this.state.gender === "Female"} onChange={this.onChangeGender} /> <label className="form-check-label" htmlFor="inlineRadio1">Female</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="Other" checked={this.state.gender === "Other"} onChange={this.onChangeGender} /> <label className="form-check-label" htmlFor="inlineRadio1">Other</label> </div> </div> <div className="form-group row"> <label htmlFor="temperature" className="col-sm-2 col-form-label">Temperature :</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="Normal" checked={this.state.temperature === "Normal"} onChange={this.onChangeTemperature} /> <label className="form-check-label" htmlFor="inlineRadio1">Normal</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="Mild Fever" checked={this.state.temperature === "Mild Fever"} onChange={this.onChangeTemperature} /> <label className="form-check-label" htmlFor="inlineRadio1">Mild Fever</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="High Fever" checked={this.state.temperature === "High Fever"} onChange={this.onChangeTemperature} /> <label className="form-check-label" htmlFor="inlineRadio1"> High Fever </label> </div> </div> <div className="form-group row"> <label htmlFor="quarantine" className="col-sm-2 col-form-label">Quarantine?</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.quarantine === "true"} onChange={this.onChangeQuarantine} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.quarantine === "false"} onChange={this.onChangeQuarantine} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="drycough" className="col-sm-2 col-form-label">Dry Cough</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.drycough === "true"} onChange={this.onChangeDrycough} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.drycough === "false"} onChange={this.onChangeDrycough} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="fatigue" className="col-sm-2 col-form-label">Fatigue</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.fatigue === "true"} onChange={this.onChangeFatigue} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.fatigue === "false"} onChange={this.onChangeFatigue} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="sorethroat" className="col-sm-2 col-form-label">Sore Throat</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.sorethroat === "true"} onChange={this.onChangeSoreThroat} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.sorethroat === "false"} onChange={this.onChangeSoreThroat} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="quarantine" className="col-sm-2 col-form-label">Shortness of breathe</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.breathe === "true"} onChange={this.onChangeBreathe} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.breathe === "false"} onChange={this.onChangeBreathe} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="bodypain" className="col-sm-2 col-form-label">Body Pain</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.bodypain === "true"} onChange={this.onChangeBodypain} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.bodypain === "false"} onChange={this.onChangeBodypain} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="diarrhoea" className="col-sm-2 col-form-label">Diarrhoea</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.diarrhoea === "true"} onChange={this.onChangeDiarrhoea} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.diarrhoea === "false"} onChange={this.onChangeDiarrhoea} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="runnynose" className="col-sm-2 col-form-label">Runny Nose</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.runnynose === "true"} onChange={this.onChangeRunnynose} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.runnynose === "false"} onChange={this.onChangeRunnynose} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="nausea" className="col-sm-2 col-form-label">Nausea</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.nausea === "true"} onChange={this.onChangeNausea} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.nausea === "false"} onChange={this.onChangeNausea} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group row"> <label htmlFor="returnfromcountry" className="col-sm-2 col-form-label"> Travelled recently?</label> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="true" checked={this.state.returnfromcountry === "true"} onChange={this.onChangeReturnfromcountry} /> <label className="form-check-label" htmlFor="inlineRadio1">Yes</label> </div> <div className="form-check form-check-inline"> <input className="form-check-input" type="radio" value="false" checked={this.state.returnfromcountry === "false"} onChange={this.onChangeReturnfromcountry} /> <label className="form-check-label" htmlFor="inlineRadio1">No</label> </div> </div> <div className="form-group"> <button className="btn btn-success" >Submit </button> </div> </div> )} {this.state.message && ( <div className="form-group"> <div className={ this.state.successful ? "alert alert-success" : "alert alert-danger" } role="alert" > {this.state.message} </div> </div> )} <CheckButton style={{ display: "none" }} ref={c => { this.checkBtn = c; }} /> </Form> </div> </div> </div > </div > ); } } }
const express = require('express'); const notesDb = require('../data/helpers/notesHelper.js'); const protected = require('../middleware/protected.js'); const userIdVerify = require('../middleware/userIdVerification.js'); const router = express.Router(); const knex = require('knex'); // [GET] /api/notes // get all notes in table router.get('', protected, (req, res) => { notesDb.getNotes() .then(notes => { if (notes.length) { res.status(200).json(notes); } else { res.status(200).json({ code: 1, message: 'No notes in database' }); } }) .catch(err => { res.status(500).json({ code: 3, message: 'Error retrieving notes' }); }); }); // [GET] /api/notes/:id // get note by note id router.get('/:id', protected, userIdVerify, (req, res) => { const noteId = req.params.id; notesDb.getNote(noteId) .then(note => { if (note.length) { res.status(200).json(note); } else { res.status(404).json({ code: 2, message: 'Note id does not exist' }); } }) .catch(err => { res.status(500).json({ code: 3, message: 'Error retrieving note' }); }); }); // [PUT] /api/notes/:id router.put('/:id', protected, async (req, res) => { const updates = req.body; const noteId = req.params.id; let valid = true; const validUpdates = {}; // validate post request format Object.getOwnPropertyNames(updates).forEach(key => { switch (key) { case 'title': if (typeof updates[key] !== 'string' || updates[key] === '') { valid = false; } else { validUpdates.title = updates.title; } break; case 'textBody': if (typeof updates[key] !== 'string') { valid = false; } else { validUpdates.textBody = updates.textBody; } break; case 'tags': if (!Array.isArray(updates[key])) { valid = false; break; } else { if (!updates[key].every(element => typeof element === 'string' || typeof element === 'number')) { valid = false; break; }; updates.tags = updates.tags.join(','); validUpdates.tags = updates.tags; break; } default: break; } }); try { if (valid) { const currentNote = await notesDb.getNote(noteId); if (currentNote.length) { const finalized = Object.assign({}, currentNote[0], validUpdates); if (!isEquivalent(currentNote[0], finalized)) { finalized.updated_at = knex.fn.now(); const recordsUpdated = await notesDb.updateNote(noteId, finalized); if (recordsUpdated) { res.status(200).json({ code: 6, message: 'Successfully updated note' }); } } else { res.status(200).json({ code: 7, message: 'No changes detected, note unchanged' }); } } else { res.status(404).json({ code: 2, message: 'Note id does not exist' }); } } else { res.status(400).json({ code: 5, message: 'Request formatted incorrectly' }); } } catch (error) { res.status(500).json({ code: 3, message: 'Error updating note' }); } }); // [DELETE] /api/notes/:id router.delete('/:id', protected, (req, res) => { const noteId = req.params.id; notesDb.removeNote(noteId) .then(recordsDeleted => { if (recordsDeleted) { res.status(200).json({ code: 8, message: 'Successfully deleted note' }); } else { res.status(404).json({ code: 2, message: 'Note at id does not exist' }); } }) .catch(err => { res.status(500).json({ code: 3, message: 'Error deleting note' }); }); }); // helper function used in put request // returns if two objects are equivalent function isEquivalent(a, b) { var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b); if (aProps.length != bProps.length) { return false; } for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; if (a[propName] !== b[propName]) { return false; } } return true; }; module.exports = router;
import React from "react"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-ui/core/DialogTitle"; import Button from "@material-ui/core/Button"; export default class CampaignList extends React.Component { constructor(props) { super(props); this.state = { open: false, editItem: {} }; this.handleClose = this.handleClose.bind(this); this.handleEditPop = this.handleEditPop.bind(this); this.handleEditChange = this.handleEditChange.bind(this); } handleEdit(id) { this.setState({ open: true }); this.handleEditPop(id); } handleCheckboxChange(id) { this.props.handleCheckboxChange(id); } handleDelete(id) { this.props.handleDelete(id); } deleteBulk() { this.props.deleteBulk(); } handleClose() { this.setState({ open: false }); } handleEditPop(id) { let { data } = this.props; let editItem = data.find((ele, index) => ele._id == id); this.setState({ editItem }); } handleEditChange(event) { let { editItem } = this.state; let newEditItem = { ...editItem }; newEditItem[event.target.name] = event.target.value; this.setState({ editItem: newEditItem }); } render() { let { data } = this.props; let { editItem } = this.state; return ( <React.Fragment> <table> <tr> <td /> <td>ID</td> <td>NAME</td> <td>ACTION</td> </tr> {data.map((ele, index) => ( <tr key={ele._id}> <td> <input type="checkbox" onChange={this.handleCheckboxChange.bind(this, ele._id)} /> </td> <td> <span> {ele._id + ` `}</span> </td> <td> <span>{ele.name}</span> </td> <td> <span> <a href="#" onClick={this.handleEdit.bind(this, ele._id)}> edit </a> </span>{" "} <span> <a href="#" onClick={this.handleDelete.bind(this, ele._id)}> delete </a> </span> </td> </tr> ))} </table> <input type="button" value="Detete" onClick={this.deleteBulk.bind(this)} /> <Dialog open={this.state.open} onClose={this.handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">Edit</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> <input type="text" name="name" value={editItem.name} onChange={this.handleEditChange} /> </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleSubmitEdit} color="primary"> Edit </Button> <Button onClick={this.handleClose} color="primary" autoFocus> Cancel </Button> </DialogActions> </Dialog> </React.Fragment> ); } }
window.setTimeout(function() { var adbutton = document.querySelectorAll('.videoAdUiSkipButton')[0]; if (adbutton) { var mutebutton = document.querySelectorAll(".ytp-button-volume")[0]; mutebutton.click(); window.setTimeout(function() { adbutton.click(); mutebutton.click();}, 6000); }}, 500);
(function() { var app = angular.module('RouteWorkshop', ['ngRoute']); var pages = [ {name: 'Home', url: '', ctrl: 'HomeCtrl'}, {name: 'Page 1', url: 'page1'}, {name: 'Page 2', url: 'page2'} ]; //configure angular app app.config(function($locationProvider, $routeProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false }); angular.forEach(pages, function(page) { $routeProvider.when('/' + page.url, { templateUrl: 'pages/' + (!page.url ? 'index' : page.url) + '.html', controller: page.ctrl || 'DummyCtrl' }) }); $routeProvider.otherwise({ templateUrl: 'pages/index.html', controller: "HomeCtrl" }); }); //create controllers app.controller('DummyCtrl', angular.noop); app.controller('HomeCtrl', function($scope, TransactionStore) { $scope.transactions = []; TransactionStore.getTransactionsInMonth(moment().format('YYYY-MM')).then(function(items) { $scope.transactions = items; }); }); app.controller('NavCtrl', function($scope, $location) { $scope.pages = pages; $scope.linkClass = function(linkUrl) { return $location.path() == '/' + linkUrl ? 'selected' : ''; }; }); //create services app.factory('TransactionStore', function($http, $q) { return (function() { var URL = 'http://server.godev.ro:8080/api/dragos/transactions'; var getTransactionsInMonth = function(month) { return $q(function(resolve, reject) { $http({url: URL + '?month=' + month}) .then( function(xhr) { if (xhr.status == 200) { resolve(xhr.data); } else { reject(); } }, reject ); }); }; var add = function(data) { return $q(function(resolve, reject) { $http({ url: URL, method: 'POST', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(data) }) .then( function(xhr) { if (xhr.status == 201) { resolve(xhr.data); } else { reject(); } }, reject ); }); }; var del = function(id) { return $q(function(resolve, reject) { $http({ url: URL + '/' + id, method: 'DELETE' }) .then( function(xhr) { if (xhr.status == 204) { resolve(); } else { reject(); } }, reject ); }); }; return { getTransactionsInMonth: getTransactionsInMonth, add: add, delete: del }; })(); }); })();
/* eslint-disable no-undef */ const tc = require('text-censor') const BaseRest = require('../Base'); module.exports = class extends BaseRest { /** * 查询全部 评论的内容 * @returns {Promise.<void>} */ async indexAction () { const post_id = this.get('id') const userId = this.ctx.state.user.id const commentsModel = this.model('comments', {appId: this.appId}) const fields = [ 'comment_post_id as post_id', 'comment_author as author', 'comment_author_ip as ip', 'comment_date as date', 'comment_content as content', 'comment_parent as parent', 'user_id' ] const list = await commentsModel.field(fields).where({ comment_post_id: post_id }).order('date DESC').page(this.get('page'), 20).countSelect() const usersModel = this.model('users') for (let item of list.data) { // item.author = await usersModel.where({id: item.user_id}).find() item.author = await usersModel.getById(item.user_id) _formatOneMeta(item.author) item.date = this.ctx.moment(item.date).fromNow() // 取得头像地址 if (!think.isEmpty(item.author.meta[`picker_${this.appId}_wechat`])) { item.author.avatar = item.author.meta[`picker_${this.appId}_wechat`].avatarUrl // user.type = 'wechat' } Reflect.deleteProperty(item.author, 'meta') } return this.success(list) // exp. // { // "ID": 288, // "post": { // "ID": 7, // "title": "So should we be, like, blogging and stuff too?", // "type": "post", // }, // "author": { // "ID": 3742, // "login": "vtymkin", // "email": false, // "name": "Vashti", // "first_name": "Vashti", // "last_name": "Tymkin", // "nice_name": "vtymkin", // "URL": "http:\/\/learningmorestuff.wordpress.com", // "avatar_URL": "https:\/\/2.gravatar.com\/avatar\/b551bd04cc12ee09d2859e235d38a897?s=96&d=retro", // "profile_URL": "https:\/\/en.gravatar.com\/vtymkin", // "ip_address": false, // "site_ID": 73927561 // }, // "date": "2005-12-13T03:40:15+00:00", // "URL": "http:\/\/en.blog.wordpress.com\/2005\/09\/26\/blogging-and-stuff\/#comment-288", // "short_URL": "https:\/\/wp.me\/pf2B5-7%23comment-288", // "content": "<p>Super. Well done you guys! \ud83d\ude1b<\/p>\n", // "raw_content": "Super. Well done you guys! :-P", // "status": "approved", // "parent": false, // "type": "comment", // "like_count": 0, // "i_like": false, // "meta": { // "links": { // } // } // } } /** * New like * @returns {Promise.<*>} */ async newAction () { const curUser = this.ctx.state.user console.log(JSON.stringify(curUser)) const post_id = this.get('id') const data = this.post() // data.content const commentsModel = this.model('comments', {appId: this.appId}) const postData = { user_id: curUser.id, comment_post_id: post_id, // comment_author: data.author, comment_author: curUser.id, comment_author_email: data.email, comment_author_url: data.url, comment_author_ip: _ip2int(this.ip), comment_date: new Date().getTime(), comment_content: tc.filter(data.content), comment_parent: data.parent, comment_type: 'comment', comment_approved: 'approved' } await commentsModel.add(postData) let author = await this.model('users').getById(curUser.id) _formatOneMeta(author) // 取得头像地址 if (!think.isEmpty(author.meta[`picker_${this.appId}_wechat`])) { author.avatar = author.meta[`picker_${this.appId}_wechat`].avatarUrl // user.type = 'wechat' } Reflect.deleteProperty(author, 'meta') return this.success({ post_id: post_id, // post: { // id: post_id // }, author: author, date: this.ctx.moment(new Date().getTime()).fromNow(), content: postData.comment_content, status: postData.comment_approved, type: postData.comment_type, like_count: 0, i_like: false, meta: {} }) } /** * Default get * Get the current user's like status for a post * * Post action delete * Unlike apost * @returns {Promise.<void>} */ async mineAction () { const postMeta = this.model('postmeta', {appId: this.appId}) const userId = this.ctx.state.user.userInfo.id // 返回用户是否 like 此 post if (this.isGet) { // Current User const data = await postMeta.getLikeStatus(userId, this.id) // if (!think.isEmpty(data.value_index)) console.log(JSON.stringify(data)) const res = { 'i_like': data.contain === 1, 'like_count': data.like_count, 'post_id': this.id } return this.success(res) } if (this.isPost) { const action = this.get('action') if (action === 'delete') { await postMeta.unLike(userId, this.id) const likeCount = await postMeta.getLikedCount(this.id) const res = { 'i_like': false, 'like_count': likeCount, 'post_id': this.id } return this.success(res) } } } };
const mongoose = require('mongoose'); const Joi = require('@hapi/joi'); Joi.objectId = require('joi-objectid')(Joi); const ProjectFunction = mongoose.model('projectFunctions', new mongoose.Schema({ dailyrate: { type: Number, }, days: { type: Number, }, functionid: { type: mongoose.Schema.Types.ObjectId, ref: 'functions', required: false }, })); exports.ProjectFunction = ProjectFunction;
// Initiate the map function var map; var geocoder; var markers; var infowindow; // var latlng = marker.getPosition(); // var lat = latlng.lat(); // var long = latlng.lng(); function initMap() { var initialLocation; geocoder = new google.maps.Geocoder; markers = []; //Variable that holds the google map map = new google.maps.Map(document.getElementById('map'), { //This is where on the world map the page will load to center: { lat: 37.4419, lng: -122.1419 }, //This is the speciic level of zoom. zoom: 13 }); var delay = 5000 setTimeout(function () { //These are the variables that hold things relevant to the input var card = document.getElementById('pac-card'); var input = document.getElementById('pac-input'); var types = document.getElementById('type-selector'); //This is where the information that is used at the top will be pushed to for the user to see. map.controls[google.maps.ControlPosition.TOP_LEFT].push(card); //This is the autocomplete variable that holds... you guessed it the autcomplete that would be based on user's input. var autocomplete = new google.maps.places.Autocomplete(input); //Creating a bound for the autcomplete regarding the map. autocomplete.bindTo('bounds', map); //Function that will react when the location of where the map is focusing on changes. autocomplete.addListener('place_changed', function () { //Closes the infowindow infowindow.close(); //The marker that was plaed in the previous place is now not visible for the user. marker.setVisible(false); // Variable that holds the autocomplete places. var place = autocomplete.getPlace(); //If there is no information on the input, there will be an error. if (!place.geometry) { return; } // If the place has a geometry, then present it on a map. if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(17); } //Setting the position of the new marker, and making it visible for the user to see. marker.setPosition(place.geometry.location); marker.setVisible(true); //This is the variable that holds the address; its currently blank as it will be utilized later. address = ''; if (place.address_components) { address = [ (place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '') ].join(' '); } //appending children with these properties such as source and text content infowindowContent.children['place-icon'].src = place.icon; infowindowContent.children['place-name'].textContent = place.name; infowindowContent.children['place-address'].textContent = address; infowindow.open(map, marker); }); }, delay) // The variable that holds the infowindow which is basically a popwindow above the map. infowindow = new google.maps.InfoWindow({ content: document.getElementById('form') }); var messagewindow = new google.maps.InfoWindow({ content: document.getElementById('message') }); google.maps.event.addListener(map, 'click', function (event) { marker = new google.maps.Marker({ position: event.latLng, map: map }); }); // document.getElementById('submit').addEventListener('click', function () { // var valueOfTable = document.getElementById('latlng.value'); // var savingValuableTable = document.getElementById('tableSave'); // map.setCenter(valueOfTable); // geocodeLatLng(geocoder, map, infowindow); // infowindow.setContent(savingValuableTable); // }); var infowindowContent = document.getElementById('infowindow-content'); infowindow.setContent(infowindowContent); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; infowindow.setPosition(pos); marker = new google.maps.Marker({ position: pos, map: map }) infowindow.setContent(tableSave); infowindow.open(map); map.setCenter(pos); // navigator.geolocation.getCurrentPosition(function(position){ // map.setZoom(17); // marker = new google.maps.Marker({ // position: pos, // map: map // }) // }) }, function () { handleLocationError(true, infowindow, map.getCenter()); }); } else { // Browser doesn't support Geolocation handleLocationError(false, infowindow, map.getCenter()); } function handleLocationError(browserHasGeolocation, infowindow, pos) { infowindow.setPosition(pos); infowindow.open(map); } function lat() { } // I tried to make a feature that would save your data after inputting some data, and these variables would save those strings. var delay = 5000; setTimeout(function () { $('#saveButton').on('click', function () { var name = escape(document.getElementById('name').value); for (var i = 0; i < name.length; i++) { name = name.replace('%20', ' '); } for (var i = 0; i < name.length; i++) { name = name.replace(/%2C/g, ","); } console.log(name); var address = escape(document.getElementById('address').value); for (var i = 0; i < address.length; i++) { address = address.replace('%20', ' '); } console.log(address); // var type = document.getElementById('typeSelect'); //We need to fix this // console.log(type); var latlng = marker.getPosition(); var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address + '&lat=' + latlng.lat() + '&lng=' + latlng.lng(); //Checking to see if this would give us our latitude and longitude. console.log(latlng.lat()); console.log(latlng.lng()); //The downloadURL is vital as it responds to what happens when there is something in the textbox. THis is why I didn't simply comment out the entire savaData function. downloadUrl(url, function (data, responseCode) { if (responseCode == 200 && data.length <= 1) { infowindow.close(); messagewindow.open(map, marker); } }); }); }, delay); // function saveData() { // console.log(name); // console.log("Hello World"); // } //Marker variable that will hold the marker ability that Google Maps has. marker = new google.maps.Marker({ //The marker will be based on the map. map: map, //This is where the marker point will be at. anchorPoint: new google.maps.Point(0, -29) }); // Sets a listener on a button to change the filter type on Places // Autocomplete. function setupClickListener(id, types) { var Button = document.getElementById(id); Button.addEventListener('click', function () { autocomplete.setTypes(types); }); } setupClickListener('changetype-all', []); setupClickListener('changetype-address', ['address']); setupClickListener('changetype-establishment', ['establishment']); // setupClickListener('changetype-LatLng', ['latitude', 'longitude']); google.maps.event.addListener(map, 'click', function (event) { placeMarker(event.latLng); }); google.maps.event.addListener(marker, 'click', function () { infowindow.open(map, marker); }); } function setMapOnAll(maps) { for (var i = 0; i < marker.length; i++) { marker[i].setMap(maps); } } function clearMarkers() { setMapOnAll(null); } function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function () { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request.responseText, request.status); } }; request.open('GET', url, true); // request.send(null); } //This function is self-explanatory... function doNothing() { } //This will place a marker at the specified location. function placeMarker(location) { marker = new google.maps.Marker({ position: location, map: map }); } function geocodeLatLng(geocoder, map, infowindow) { var input = document.getElementById('latlng').value; var latlngStr = input.split(',', 2); var latlng = { lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1]) }; geocoder.geocode({ 'location': latlng }, function (results, status) { if (status === 'OK') { if (results[0]) { map.setZoom(17); marker = new google.maps.Marker({ position: latlng, map: map }); infowindow.setContent(results[0].formatted_address); infowindow.open(map, marker); } else { window.alert('No results found'); } } else { window.alert('Geocoder failed due to: ' + status); } }); }
function circumference(r){ console.log(2*Math.PI*r); } function area(r){ console.log( Math.PI*r*r); } module.exports = { circumference : circumference, area:area }
import Vue from 'vue'; import App from './App.vue'; import router from './router'; let vm = new Vue({ el: '#app', components:{App}, template:"<App/>", router }); // 我们可以通过根实例 vm 对象访问 $route 属性 console.log("通过根实例 vm 对象访问:"); console.log(vm.$route.path="/bar");
/** * Задача 7. * * Дан массив с числами `[1, 2, 3]`. * Создайте функцию `f`, которая принимает массив в качестве параметра, * а затем последовательно выводит на экран его элементы. * * Условия: * - Входной параметр должен быть не пустым массивом; * - Обязательно использовать рекурсию; * - Использовать цикл запрещено. * * Заметки: * - Возможно вам понадобится метод splice → https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/splice */ // Решение function f(array) { if (!isArray(array)) { throw new Error('parameter type should be an array'); } else if (isEmpty(array)) { throw new Error(`parameter can't be an empty`) } console.log(array.splice(0,1)[0]); if (array.length > 1) { f(array); } else { console.log(array[0]); } } function isEmpty(array) { return array.length === 0; } function isArray(data) { return Array.isArray(data); } /* не удалять */ f([1, 2, 3]); // 1 // 2 // 3 f(1, 2, 3); // Error: parameter type should be an array f('Content'); // Error: parameter type should be an array f([]); // Error: parameter can't be an empty export { f }; /* не удалять */
function TemplateString(props) { this.parts = props.parts; } TemplateString.prototype.toJSCode = function () { return this.parts.map(function (e) { if (e.type == TemplateString.TYPE_EXPRESSION) { return '(' + e.data + ')'; } else { return JSON.stringify(e.data); } }).join('+'); }; TemplateString.__partRegex = /(\{\{(([^\}]|(\}[^\}]))*)\}\})|(([^\{]|(\{[^\{]))+)/g; /** * @param {String} text */ TemplateString.__matchExpression = function (text) { if (text[0] == '{' && text[1] == '{' && text[text.length - 1] == '}' && text[text.length - 2] == '}') { return [text, text.substr(2, text.length - 4).trim()]; } else { return false; } }; TemplateString.TYPE_STRING = 0; TemplateString.TYPE_EXPRESSION = 1; TemplateString.parse = function (text) { text = text+''; var matchedParts = text.match(this.__partRegex); if (matchedParts) { var parts = matchedParts.map(function (e) { var matchedExp = this.__matchExpression(e); if (matchedExp) { return { type: this.TYPE_EXPRESSION, data: matchedExp[1] }; } else { return { type: this.TYPE_STRING, data: e }; } }.bind(this)); return new TemplateString({ parts: parts }); } else { return new TemplateString({ parts: [] }); } }; export default TemplateString;
define([ 'modules/globals' ], function(g){ var scope = function(w,h,$el){ this.$canvas = $('<canvas></canvas'); this.canvas = this.$canvas[0]; this.ctx = this.canvas.getContext('2d'); this.canvas.width = w; this.canvas.height = h; this.$canvas.width(w); this.$canvas.height(h); if(typeof $el !== 'undefined') $el.append(this.$canvas); }; return scope; });
'use strict'; describe('Controller:AuthCtrl', function(){ var authCtrl, scope, deferredSuccess, location; var authServiceMock = { register : function(){}, login : function(){}, createProfile : function(){} }; var testUser = {username : 'some user'}; var userResponse = {userName : 'response user'}; beforeEach(module('angularTestApp')); describe('user is logged in', function(){ beforeEach(inject(function($controller, $rootScope, $q, $location){ scope = $rootScope.$new(); location = $location; spyOn(location, 'path').andCallThrough(); authCtrl = $controller('AuthCtrl', { $scope: scope, authService: authServiceMock, authorizedUser: testUser }); })); it('should redirect to home page when user is logged in', function(){ expect(location.path).toHaveBeenCalledWith('/'); }); }); describe('registering user', function(){ beforeEach(inject(function($controller, $rootScope, $q, $location){ scope = $rootScope.$new(); deferredSuccess = $q.defer(); location = $location; spyOn(location, 'path').andCallThrough(); spyOn(authServiceMock, 'register').andCallThrough().andReturn(deferredSuccess.promise); spyOn(authServiceMock, 'login').andCallThrough().andReturn(deferredSuccess.promise); spyOn(authServiceMock, 'createProfile').andCallThrough().andReturn(deferredSuccess.promise); authCtrl = $controller('AuthCtrl', { $scope: scope, authService: authServiceMock, authorizedUser: null }); })); it('should call service register when registering user', function(){ scope.user = testUser; scope.register(); expect(authServiceMock.register).toHaveBeenCalledWith(testUser); }); it('should call service login when registering user', function(){ scope.user = testUser; deferredSuccess.resolve(userResponse); scope.register(); scope.$apply(); expect(authServiceMock.login).toHaveBeenCalledWith(testUser); }); it('should createProfile when user logged in after registering', function(){ scope.user = testUser; deferredSuccess.resolve(userResponse); scope.register(); scope.$apply(); expect(authServiceMock.createProfile).toHaveBeenCalledWith(userResponse); }); it('should redirect to home page when registered user logged in', function(){ scope.user = testUser; deferredSuccess.resolve(userResponse); scope.register(); scope.$apply(); expect(location.path).toHaveBeenCalledWith('/'); }); it('should not call service log in when register returned error', function(){ deferredSuccess.reject({}); scope.register(); scope.$apply(); expect(authServiceMock.login.callCount).toBe(0); }); it('should not call create profile when register returned error', function(){ deferredSuccess.reject({}); scope.register(); scope.$apply(); expect(authServiceMock.createProfile.callCount).toBe(0); }); it('should save error when register unsuccessful', function(){ var reason = "some error"; deferredSuccess.reject(reason); scope.register(); scope.$apply(); expect(scope.error).toBe(reason); }) }); describe ('user login', function(){ beforeEach(inject(function($controller, $rootScope, $q, $location){ scope = $rootScope.$new(); deferredSuccess = $q.defer(); location = $location; spyOn(location, 'path').andCallThrough(); spyOn(authServiceMock, 'login').andCallThrough().andReturn(deferredSuccess.promise); authCtrl = $controller('AuthCtrl', { $scope: scope, authService: authServiceMock, authorizedUser: null }); })); it('should call service login when logging in user', function(){ scope.user = testUser; scope.login(); expect(authServiceMock.login).toHaveBeenCalledWith(testUser); }); it('should redirect user to home page after login', function(){ scope.user = testUser; deferredSuccess.resolve(); scope.login(); scope.$apply(); expect(location.path).toHaveBeenCalledWith('/'); }); it('should not redirect to home page on unsuccessful login', function(){ deferredSuccess.reject({}); scope.login(); scope.$apply(); expect(location.path.callCount).toBe(0); }); it('should save error when register unsuccessful', function(){ var reason = "some error"; deferredSuccess.reject(reason); scope.login(); scope.$apply(); expect(scope.error).toBe(reason); }) }); });
var complete_8c = [ [ "mutt_complete", "complete_8c.html#a72b3c85bc14241321c26350fd4a26b37", null ] ];
import navbar from '../js/components/navbar/index.vue'; export default { title: 'Example/navbar', component: navbar, argTypes: { backgroundColor: { control: 'color' }, }, }; const Template = (args, { argTypes }) => ({ props: Object.keys(argTypes), components: { navbar }, template: '<navbar v-bind="$props" />', }); export const demo = Template.bind({}); demo.args = { demo:true, };
var searchData= [ ['zstrm_5fclose',['zstrm_close',['../zstrm_8c.html#a2e173793bbd1752cae2fa7def4609595',1,'zstrm.c']]], ['zstrm_5ffree',['zstrm_free',['../zstrm_8c.html#a67de0804fb4eb6b20a25c5a652907f37',1,'zstrm.c']]], ['zstrm_5fmalloc',['zstrm_malloc',['../zstrm_8c.html#a3aa3c66bbc4de02162b2fca964a5bdb9',1,'zstrm.c']]], ['zstrm_5fopen',['zstrm_open',['../zstrm_8c.html#a7eff633b4f47c7e001b56de4de948057',1,'zstrm.c']]], ['zstrm_5fpoll',['zstrm_poll',['../zstrm_8c.html#a3ddde77d86dc16911ae8355d5d8fc008',1,'zstrm.c']]], ['zstrm_5fread',['zstrm_read',['../zstrm_8c.html#afb613b98e23ffd5d98f8daac4fcf0e4a',1,'zstrm.c']]], ['zstrm_5fwrite',['zstrm_write',['../zstrm_8c.html#aeaee0ad1c8ca07fa3c66198a219d5241',1,'zstrm.c']]] ];
import React, { Component } from 'react' import $http from '../../utils/http.js' import Lazyload from 'react-lazyload' import { getCookie } from '../../utils/utils.js' // import { ToastContainer, toast } from 'react-toastify' // import { css } from 'glamor' import { connect } from 'react-redux' import { ADD_CART } from './../../store/reducers' import { T } from 'react-toast-mobile'; //弹窗 class Palceholder extends Component { render() { return <img src={require('../../static/img/img8.png')} /> } } class GoodsItem extends Component { constructor() { super() this.addCart = this.addCart.bind(this) this.toDetail = this.toDetail.bind(this) } render() { let { data } = this.props return ( <dl className='goods-item' onClick={() => { this.toDetail(data.goods_id) }}> <dt> <Lazyload overflow once height={'100%'} palceholder={<Palceholder></Palceholder>} debounce={100}> <img src={"http://www.lb717.com/" + data.obj_data} alt="" /> </Lazyload> </dt> <dd> <p className="goods-detail">{data.goods_name}</p> <p> <span className='goods-price'>{data.discount_price}</span> <span onClick={this.addCart} className='iconfont icon-gouwucheman'></span> </p> {/* <ToastContainer /> */} </dd> </dl> ) } addCart(e) { let { data } = this.props e.stopPropagation() if (getCookie('token')) { $http.post('/user/Cart/addCart', { goods_id: data.goods_id, goods_info: data, token: getCookie('token') }).then((res) => { if (res == 1) { T.notify('购物车添加成功') this.props.dispatch({ type: ADD_CART, data: { ...data, count: 1, selected: 0 } }) // this.props.history.push('/index/cart', { // from: location.pathname // }) } else { // toast(res.info, { // position: toast.POSITION.TOP_CENTER, // hideProgressBar: true, // className: css({ //更改样式 // background: 'black', // color: '#fff', // fontSize: ".24rem" // }) // }) let { history, location } = this.props console.log(this.props) history.push('/login', { from: location.pathname }) } }) } else { let { history, location } = this.props this.props.history.push('/login', { from: location.pathname }) } } toDetail(goods_id) { this.props.history.push('/detail?goods_id=' + goods_id, { goods_id: goods_id }) } } export default connect(null)(GoodsItem)
const usuarios = [ { nome: "Salvio", receitas: [115.3, 48.7, 98.3, 14.5], despesas: [85.3, 13.5, 19.9] }, { nome: "Marcio", receitas: [24.6, 214.3, 45.3], despesas: [185.3, 12.1, 120.0] }, { nome: "Lucia", receitas: [9.8, 120.3, 340.2, 45.3], despesas: [450.2, 29.9] } ]; function somaNumeros(numeros) { // Soma todos números dentro do array "numeros" let soma = 0; for (let i = 0; i < numeros.length; i++) { soma += numeros[i]; } return soma; } function calculaSaldo(receitas, despesas) { return somaNumeros(receitas) - somaNumeros(despesas); } for (usuario of usuarios) { let saldo = calculaSaldo(usuario.receitas, usuario.despesas); let msg; if (saldo >= 0) { msg = 'POSITIVO'; } else { msg = 'NEGATIVO'; } console.log(`${usuario.nome} possui saldo ${msg} de ${saldo.toFixed(2)}`) }
const buildModelParamsUrl = params => { const {daily_ssl, wkly_ssl, mthly_ssl,qrtly_ssl, yrly_ssl, ticker, prior, ma_lag, trainning_years} = params let seasonalities = '' if(daily_ssl){ seasonalities += 'd-' } if(wkly_ssl){ seasonalities += 'w-' } if(mthly_ssl){ seasonalities += 'm-' } if(qrtly_ssl){ seasonalities += 'q-' } if(yrly_ssl){ seasonalities += 'y-' } seasonalities = seasonalities.substring(0, seasonalities.length-1) return `/${ticker}?seasonalities=${seasonalities}&prior=${prior}&lag=${ma_lag}&start-date=2016-08-01` } export { buildModelParamsUrl } export default { buildModelParamsUrl }
const { GraphQLObjectType, GraphQLSchema } = require("graphql"); const usersSchema = require("./usersSchema"); const quizzesSchema = require("./quizzesSchema"); const questionsSchema = require("./questionsSchema"); const RootQuery = new GraphQLObjectType({ name: "Query", fields: () => ({ ...usersSchema.query, ...quizzesSchema.query, ...questionsSchema.query, }), }); const Mutation = new GraphQLObjectType({ name: "Mutation", fields: () => ({ ...usersSchema.mutation, ...quizzesSchema.mutation, ...questionsSchema.mutation, }), }); module.exports = new GraphQLSchema({ query: RootQuery, mutation: Mutation });
const FFmpeg = require('fluent-ffmpeg') var ffmpeg = require("ffmpeg-static"); var torrentStream = require("torrent-stream"); const readline = require('readline'); FFmpeg.setFfmpegPath(ffmpeg.path); const yifysubtitles = require('yifysubtitles'); path = require('path'); function formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } function progressionPrint(downloaded) { readline.cursorTo(process.stdout, 0); process.stdout.write(downloaded); } const fetchSubtitlesByImdbId = async (req, res) => { const imdbId = req.params.imdbId; yifysubtitles(imdbId, { path: __dirname + '/../client/public/subtitles', langs: ['en', 'fr', 'es'] }) .then(data => { res.json(data) }) .catch((err) => res.json({msg:"error"})); } const writeResHeader = (req, res, file) => { const total = file.length; const range = req.headers.range; const positions = range.match(/\d+/g).map(Number); const start = positions[0] | 0; const end = total - 1; const chunksize = (end - start) + 1; res.writeHead(206, { "Content-Range": "bytes " + start + "-" + end + "/" + total, "Accept-Ranges": "bytes", "Content-Length": chunksize, "Content-Type": "video/mp4", 'Connection': 'keep-alive' }); return { "start": start, "end": end, } } const streamTorrentByHash = async (req, res) => { const isChrome = req.headers['user-agent'].includes('Chrome'); const isFirefox = req.headers['user-agent'].includes('Firefox'); const hash = req.params.hash; const path = __dirname + '/../downloads'; const magnet = `magnet:?xt=urn:btih:${hash}&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://torrent.gresille.org:80/announce&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://p4p.arenabg.ch:1337&tr=udp://tracker.internetwarriors.net:1337`; const engine = torrentStream(magnet, { path: path, }); engine.on('ready', () => { engine.files.forEach((file) => { const extension = file.name.split('.').pop(); let stream; if (extension === 'mp4' || (extension === 'mkv' && isChrome)) { // console.log("> Currently streaming", file.name, formatBytes(file.length)); stream = file.createReadStream(writeResHeader(req, res, file)); stream.pipe(res); res.on('close', () => { engine.destroy(); }) } else if (extension === 'mkv' && isFirefox) { res.writeHead(200, { "Content-Type": "video/mp4", 'Connection': 'keep-alive' }); stream = file.createReadStream(); FFmpeg() .input(stream) .outputOptions(['-frag_duration 100', '-movflags frag_keyframe+empty_moov+faststart']) .outputFormat('mp4') .videoCodec('libx264') // .videoBitrate('2048') .audioCodec('aac') // .audioBitrate('256') // .on('start', (commandLine) => console.log('Spawned FFmpeg with command: ' + commandLine)) // .on('codecData', (data) => console.log('Input is ' + data.audio + ' audio with ' + data.video + ' video')) .on('error', (err, stdout, stderr) => {}) // .on('end', () => console.log('Processing finished successfully')) .pipe(res); res.on('close', () => { engine.destroy(); }) } else { file.deselect(); } }); }); // engine.on('download', () => { // progressionPrint(formatBytes(engine.swarm.downloaded)); // }); // engine.on('idle', function () { // console.log('Torrent downloaded'); // }); }; module.exports = exports = { streamTorrentByHash, fetchSubtitlesByImdbId, };
let express = require('express'); let app = express(); let bodyParser = require('body-parser'); let morgan = require('morgan'); let mongoose = require('mongoose'); let passport = require('passport'); // let config = require('./config/database'); // get db config file let config = require('config'); let User = require('./app/models/user'); // get the mongoose model let port = process.env.PORT || 8080; let jwt = require('jwt-simple'); // added to fix cors issue let cors = require('cors'); // handling image uploads let fs = require('fs'); let multer = require('multer'); let co = require('co'); //db connection let options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }, replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } }; mongoose.connect(config.DBHost, options); let db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); // get our request parameters app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); //don't show the log when it is test if(config.util.getEnv('NODE_ENV') !== 'test') { //use morgan to log at command line app.use(morgan('combined')); //'combined' outputs the Apache style LOGs } // // log to console // app.use(morgan('dev')); // Use the passport package in our application app.use(passport.initialize()); // Setup photo upload app.use(multer({dest:'./data/img/'}).single('photo')); // to fix cors issue app.use(cors()); ///////////// // demo Route (GET http://localhost:8080) app.get('/', function(req, res) { res.send('Hello! The API is at http://localhost:' + port + '/api'); }); //-------------------------------------------------------------------// // connect to database // mongoose.connect(config.database); // pass passport for configuration require('./config/passport')(passport); // bundle our routes let apiRoutes = express.Router(); // create a new user account (POST http://localhost:8080/api/signup) apiRoutes.post('/signup', function(req, res) { if (!req.body.name || !req.body.password) { return res.json({success: false, msg: 'Please pass name and password.'}); } else { let newUser = new User({ name: req.body.name, password: req.body.password }); User.getFirstEntry(function (err, id) { console.log(id); newUser.lastViewedUser = id._id; // save the user newUser.save(function(err) { if (err) { return res.json({success: false, msg: 'Username already exists.'}); } return res.json({success: true, msg: 'Successful created new user.'}); }); }); } }); // update user info (upon user creation). Change later to look for user token apiRoutes.put('/accountInfo', passport.authenticate('jwt', { session: false}), function(req, res) { console.log("TEST"); let token = getToken(req.headers); if (token) { let decoded = jwt.decode(token, config.secret); User.findOne({ name: decoded.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); } else { if (req.body.firstName != null) user.userInfo.firstName = req.body.firstName; if (req.body.lastName != null) user.userInfo.lastName = req.body.lastName; if (req.body.bio != null) user.userInfo.bio = req.body.bio; if (req.body.height != null) user.userInfo.height = req.body.height; if (req.body.weight != null) user.userInfo.weight = req.body.weight; if (req.body.gender != null) user.userInfo.gender = req.body.gender; if (req.body.age != null) user.userInfo.age = req.body.age; if (req.body.school != null) user.userInfo.schoolInfo.school = req.body.school; if (req.body.personalGoal != null) user.fitnessGoals.personal = req.body.personalGoal; if (req.body.workoutTime != null) user.fitnessGoals.workoutTime = req.body.workoutTime; if (req.body.fitnessLevel != null) user.fitnessGoals.fitnessLevel = req.body.fitnessLevel; if (req.body.goalWeight != null) user.fitnessGoals.goalWeight = req.body.goalWeight; if (req.body.genderPreference != null) user.fitnessGoals.genderPreference = req.body.genderPreference; user.save(function(err) { if (err) return res.send(err); return res.json({success: true, msg: 'update succesfull' + user}); }); } }); } else { return res.status(403).send({success: false, msg: 'No token provided.'}); } }); // Handle image uploads apiRoutes.put('/setphoto', passport.authenticate('jwt', { session: false}), function(req, res) { console.log(req.file); let token = getToken(req.headers); if (token) { let decoded = jwt.decode(token, config.secret); User.findOne({ name: decoded.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); } else { // res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'}); // if (req.body.photo != null) { user.userInfo.photos.data = fs.readFileSync(req.file.path); user.userInfo.photos.contentType = 'image/jpg'; console.log(user); // user.save(); user.save(function (err) { if (err) return res.send(err); return res.json({success: true, msg: 'image update succesfull' + user}); }); // } } }); } else { return res.status(403).send({success: false, msg: 'No token provided.'}); } }); // route to authenticate a user (POST http://localhost:8080/api/authenticate) apiRoutes.post('/authenticate', function(req, res) { User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.send({success: false, msg: 'Authentication failed. User not found.'}); } else { // check if password matches user.comparePassword(req.body.password, function (err, isMatch) { console.log("isMatch: " + isMatch); if (isMatch && !err) { // if user is found and password is right create a token let token = jwt.encode(user, config.secret); // return the information including token as JSON return res.json({success: true, token: 'JWT ' + token}); } else { res.send({success: false, msg: 'Authentication failed. Wrong password.'}); } }); } }); }); // route to a restricted info (GET http://localhost:8080/api/memberinfo) apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) { let token = getToken(req.headers); if (token) { let decoded = jwt.decode(token, config.secret); User.findOne({ name: decoded.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); } else { res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'}); } }); } else { return res.status(403).send({success: false, msg: 'No token provided.'}); } }); // Get the list of good matches. TEST ONLY apiRoutes.put('/getMatches', passport.authenticate('jwt', { session: false}), function(req, res) { var token = getToken(req.headers); if (token) { var decoded = jwt.decode(token, config.secret); console.log(decoded.user); User.findOne({ name: decoded.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); } else { // get all the users that match the same settings as the user console.log("Finding matches for " + user.name); User.find({ "name": {"$ne": user.name}, "$and": [{"fitnessGoals.genderPreference": user.genderPreference}, {"userInfo.schoolInfo.school": user.userInfo.schoolInfo.school}, {"fitnessGoals.workoutTime": user.fitnessGoals.workoutTime} ] }, {"name":1,_id:0}, function(err, users) { if (err) throw err; return res.json(users); }); } }); } else { return res.status(403).send({success: false, msg: 'No token provided.'}); } }); apiRoutes.post('/getMatch', function(req, res) { console.log(req.body); // Find a match and return it let currentUser = User.findOne({name: req.body.name}); currentUser.then(function(result) { co(function*() { const cursor = User.find({ _id : {$gte: result.lastViewedUser} }).cursor(); for (let nextUser = yield cursor.next(); nextUser != null; nextUser = yield cursor.next()) { // Print the user, with the `band` field populated console.log(nextUser); if ( nextUser.genderPreference === result.genderPreference && nextUser.userInfo.schoolInfo.school === result.userInfo.schoolInfo.school && nextUser.fitnessGoals.workoutTime === result.fitnessGoals.workoutTime ) { result.lastViewedUser = nextUser._id; return res.json(nextUser); } } }); }); }); apiRoutes.post('/likeUser', function(req, res) { console.log(req.body); // userId // Find a match and return it let currentUser = User.findOne({name: req.body.name}); currentUser.then(function(user) { let userToAdd = new User(); userToAdd.id = req.body.matchID; userToAdd. user.matches.accepted.push(userToAdd); user.save(function (err) { if (err) return res.send(err); return res.json({success: true, msg: 'user liked' + user}); }); }); }); apiRoutes.post('/passUser', function(req, res) { console.log(req.body); // userId // Find a match and return it let currentUser = User.findOne({name: req.body.name}); currentUser.then(function(user) { user.matches.passed.push(req.body.matchID); user.save(function (err) { if (err) return res.send(err); return res.json({success: true, msg: 'user liked' + user}); }); }); }); apiRoutes.post('/dislikeUser', function(req, res) { console.log(req.body); // userId // Find a match and return it let currentUser = User.findOne({name: req.body.name}); currentUser.then(function(user) { user.matches.blocked.push(req.body.matchID); user.save(function (err) { if (err) return res.send(err); return res.json({success: true, msg: 'user liked' + user}); }); }); }); apiRoutes.get('/getMessages', function(req, res) { console.log(req.body); // userId // Find a match and return it currentUser.then(function(user) { return res.json({success: true, data: user.matches.accepted}); }); }); apiRoutes.post('/sendMessage', function(req, res) { console.log(req.body); // userId // Find a match and return it // let currentUser = User.findOne({name: req.body.name}); // currentUser.then(function(user) { // user.matches.blocked.push(req.body.matchID); // user.save(function (err) { // if (err) // return res.send(err); // // return res.json({success: true, msg: 'user liked' + user}); // }); // }); }); /*TAKE THIS OUT*/ // Get the list of good matches apiRoutes.get('/getMatches', passport.authenticate('jwt', { session: false}), function(req, res) { var token = getToken(req.headers); if (token) { var decoded = jwt.decode(token, config.secret); User.findOne({ name: decoded.name }, function(err, user) { if (err) throw err; if (!user) { return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'}); // res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'}); } }); } else { return res.status(403).send({success: false, msg: 'No token provided.'}); } }); getToken = function (headers) { if (headers && headers.authorization) { let parted = headers.authorization.split(' '); if (parted.length === 2) { return parted[1]; } else { return null; } } else { return null; } }; compareUsers = function(user, nextUser) { return ( nextUser.fitnessGoals.genderPreference == user.genderPreference && nextUser.userInfo.schoolInfo.school == user.userInfo.schoolInfo.school && nextUser.fitnessGoals.workoutTime == user.fitnessGoals.workoutTime ); }; // connect the api routes under /api/* app.use('/api', apiRoutes); // Start the server app.listen(port); console.log('There will be dragons: http://localhost:' + port); module.exports = app; // for testing
const { Router } = require('express'); const statics = require('./pages'); const usuarioController = require('../app/controllers/usuarioController'); const pontoController = require('../app/controllers/pontoController'); const loginController = require('../app/controllers/loginController'); const authVerify = require('../middlewares/authVerify'); const authRH = require('../middlewares/authRH'); const routes = Router(); routes.use(statics); routes.post('/', loginController.auth); routes.post('/logout', loginController.logout); routes.get('/api/users/page/:num', usuarioController.pagination); routes.get('/api/users', authVerify, usuarioController.getAllUsers); routes.post('/api/users', authVerify, usuarioController.createUser); routes.get('/api/users/:id', authVerify, usuarioController.getSingleUser); routes.get('/api/users/:id/view', authVerify, usuarioController.viewUser); routes.post('/api/users/:id/ban', authVerify, usuarioController.banUser); routes.post('/api/users/update', authVerify, usuarioController.updateUser); routes.get('/api/users/:id/edit', authVerify, usuarioController.editUser); routes.post('/api/users/getuser', authVerify, pontoController.usuarioExp); routes.get('/api/schedules/time/:matricula', authVerify, pontoController.getScheduleTime); routes.get('/api/schedules/:matricula', authVerify, pontoController.getAllSchedules); routes.post('/api/schedules', authVerify, pontoController.createSchedule); routes.get('/api/schedules/:id/single', authVerify, pontoController.getSingleSchedule); routes.post('/api/schedules/update', authVerify, pontoController.updateSchedule); routes.get('/api/schedules/:id/edit', authVerify, pontoController.editSchedule); routes.get('/api/schedules/:id/view', authVerify, pontoController.viewSchedule); routes.post('/api/schedules/:id/delete', authVerify, pontoController.deleteSchedule); module.exports = routes;
import fs from "fs"; fs.rename("desktop.ini", "desktop-temp.ini", function (err) { if (err) console.log("ERROR: " + err); }); fs.rename("desktop.ini", "desktop.ini", function (err) { if (err) console.log("ERROR: " + err); });
const Animal = require("./models").Animal; const Sequelize = require("sequelize"); const Op = Sequelize.Op; module.exports = { getAllAnimals(callback) { return Animal.findAll() .then(animals => { callback(null, animals); }) .catch(err => { callback(err); }); }, getAvailableAnimals(callback) { return Animal.findAll({ where: { status: "Available" } }) .then(animals => { callback(null, animals); }) .catch(err => { callback(err); }); }, getAdoptedAnimals(callback) { return Animal.findAll({ where: { status: "Adopted" } }) .then(animals => { callback(null, animals); }) .catch(err => { callback(err); }); }, getPendingAdoptions(callback) { return Animal.findAll({ where: { status: "Pending" } }) .then(animals => { callback(null, animals); }) .catch(err => { callback(err); }); }, getSortedAnimals(query, callback) { let queryKeys = ["type", "size", "age"]; let where = { status: "Available" }; queryKeys.forEach(key => { if (query[key]) where[key] = query[key]; }); return Animal.findAll({ where }) .then(animals => { callback(null, animals); }) .catch(err => { callback(err); }); }, getAnimal(id, callback) { return Animal.findByPk(id) .then(animal => { callback(null, animal); }) .catch(err => { callback(err); }); }, addAnimal(newAnimal, callback) { return Animal.create({ type: newAnimal.type, size: newAnimal.size, age: newAnimal.age, breed: newAnimal.breed, gender: newAnimal.gender, status: newAnimal.status, name: newAnimal.name, description: newAnimal.description, photo: newAnimal.photo }) .then(animal => { callback(null, animal); }) .catch(err => { callback(err); }); }, updateAnimal(req, updatedAnimal, callback) { return Animal.findByPk(req.params.id).then(animal => { if (!animal) { return callback("Animal not found"); console.log("Animal not found"); } animal .update(updatedAnimal, { fields: Object.keys(updatedAnimal) }) .then(() => { callback(null, animal); }) .catch(err => { callback(err); }); }); } };
const userMenuIndexCopy = { "en": { "INDEX": { "TYPOGRAPHY": { "TEXT": [ "Cashier", "Account", "Logout" ] } } }, "kr": { "INDEX": { "TYPOGRAPHY": { "TEXT": [ "캐셔", "계좌", "로그아웃" ] } } }, "ch": { "INDEX": { "TYPOGRAPHY": { "TEXT": [ "收银台", "帐户", "登出" ] } } }, "jp": { "INDEX": { "TYPOGRAPHY": { "TEXT": [ "Cashier", "Account", "Logout" ] } } }, "ru": { "INDEX": { "TYPOGRAPHY": { "TEXT": [ "Касса", "Учетная запись", "Выйти" ] } } } } export default userMenuIndexCopy;
Grailbird.data.tweets_2012_02 = [ { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "172975577941286912", "text" : "There's a beautiful rising crescent moon rising in the sunset. The moon is coloured like a rainbow. I'll try to get a picture.", "id" : 172975577941286912, "created_at" : "2012-02-24 09:26:06 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "171309038393495552", "text" : "I dreamt I was listening to songs I don't remember writing. I listened to one titled 'Shadow of a Doubt'. When I woke up I recorded it.", "id" : 171309038393495552, "created_at" : "2012-02-19 19:03:52 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "Chris Franklin", "screen_name" : "Campster", "indices" : [ 0, 9 ], "id_str" : "13640822", "id" : 13640822 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "169407261884690433", "in_reply_to_user_id" : 13640822, "text" : "@Campster Errant Signal is good. Please keep it up.", "id" : 169407261884690433, "created_at" : "2012-02-14 13:06:53 +0000", "in_reply_to_screen_name" : "Campster", "in_reply_to_user_id_str" : "13640822", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "169288196281217025", "text" : "The whole web infrastructure should be p2p, using FTP as a back up. If sharing was evenly distributed individual data usage would be tiny.", "id" : 169288196281217025, "created_at" : "2012-02-14 05:13:45 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "168520887245619200", "text" : "I did it all for the gnocchi.", "id" : 168520887245619200, "created_at" : "2012-02-12 02:24:45 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ { "expanded_url" : "http:\/\/twitter.com\/james_a_forbes\/status\/168158282408656898\/photo\/1", "indices" : [ 10, 30 ], "url" : "http:\/\/t.co\/wQxzCJd3", "media_url" : "http:\/\/pbs.twimg.com\/media\/AlVrESFCAAAUILU.jpg", "id_str" : "168158282412851200", "id" : 168158282412851200, "media_url_https" : "https:\/\/pbs.twimg.com\/media\/AlVrESFCAAAUILU.jpg", "sizes" : [ { "h" : 453, "resize" : "fit", "w" : 340 }, { "h" : 150, "resize" : "crop", "w" : 150 }, { "h" : 3264, "resize" : "fit", "w" : 2448 }, { "h" : 800, "resize" : "fit", "w" : 600 }, { "h" : 1365, "resize" : "fit", "w" : 1024 } ], "display_url" : "pic.twitter.com\/wQxzCJd3" } ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "168158282408656898", "text" : "New book! http:\/\/t.co\/wQxzCJd3", "id" : 168158282408656898, "created_at" : "2012-02-11 02:23:56 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167806402214109187", "text" : "Anyone who ever paid for Windows, or an Xbox, or Microsoft Office, etc indirectly helped Bill Gates save kids from Malaria.", "id" : 167806402214109187, "created_at" : "2012-02-10 03:05:38 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167796752303398912", "text" : "Forget it Jake, it's Campsie.", "id" : 167796752303398912, "created_at" : "2012-02-10 02:27:17 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167744452302077952", "in_reply_to_user_id" : 93714279, "text" : "@Jemburula Doesn't really fit with Karmic balance. You found someone's keys so someone loses yours? Maybe Karma's evil twin brother.", "id" : 167744452302077952, "created_at" : "2012-02-09 22:59:28 +0000", "in_reply_to_screen_name" : "jsomau", "in_reply_to_user_id_str" : "93714279", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167690659866750976", "text" : "It's frustrating to always have songs unfinished. But, if I had all my ideas finished I'd be uncomfortable with the gulf of nothing new.", "id" : 167690659866750976, "created_at" : "2012-02-09 19:25:43 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167519186514485248", "text" : "This semester I wanted to hit the ground running. But so far I've just hit the ground.", "id" : 167519186514485248, "created_at" : "2012-02-09 08:04:21 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167501112834932736", "text" : "A friend was quoting 'Chinatown' when we saw Soundgarden near Chinatown. I hadn't seen it until just now. Brilliant ending.", "id" : 167501112834932736, "created_at" : "2012-02-09 06:52:31 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167283285200867328", "text" : "Ever since Obama I've noticed a lot more folks using the word folks. Reminds me of the end of a Looney Tunes cartoon.", "id" : 167283285200867328, "created_at" : "2012-02-08 16:26:57 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167280679841832960", "text" : "Porting an app from as3 to java. Just coding blind without testing seems to work. Twice the pride, double the fall.", "id" : 167280679841832960, "created_at" : "2012-02-08 16:16:36 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "Siena Somerset", "screen_name" : "doktorgoogle", "indices" : [ 3, 16 ], "id_str" : "486414259", "id" : 486414259 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167233328985030657", "text" : "RT @doktorgoogle: I'm new to Twitworld. I searched for Santa Claus and found several. How do I know if I am following the real Santa ?", "retweeted_status" : { "source" : "\u003Ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003ETwitter Web Client\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167232536232206337", "text" : "I'm new to Twitworld. I searched for Santa Claus and found several. How do I know if I am following the real Santa ?", "id" : 167232536232206337, "created_at" : "2012-02-08 13:05:18 +0000", "user" : { "name" : "Siena Somerset", "screen_name" : "doktorgoogle", "protected" : false, "id_str" : "486414259", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/524546925605842944\/hC2mg57N_normal.jpeg", "id" : 486414259, "verified" : false } }, "id" : 167233328985030657, "created_at" : "2012-02-08 13:08:27 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ { "indices" : [ 65, 85 ], "url" : "http:\/\/t.co\/K1mHrNdY", "expanded_url" : "http:\/\/www.foodprocessing.com.au\/news\/51081-Australian-egg-industry-is-a-cracker-report", "display_url" : "foodprocessing.com.au\/news\/51081-Aus\u2026" } ] }, "geo" : { }, "id_str" : "167118897936465920", "text" : "I think the increase in egg consumption is solely because of me.\nhttp:\/\/t.co\/K1mHrNdY", "id" : 167118897936465920, "created_at" : "2012-02-08 05:33:44 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "Terry", "screen_name" : "terrycavanagh", "indices" : [ 0, 14 ], "id_str" : "36457353", "id" : 36457353 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "in_reply_to_status_id_str" : "167026711408558082", "geo" : { }, "id_str" : "167109793545338881", "in_reply_to_user_id" : 36457353, "text" : "@terrycavanagh I don't have a console. If it was on computer I would be.", "id" : 167109793545338881, "in_reply_to_status_id" : 167026711408558082, "created_at" : "2012-02-08 04:57:34 +0000", "in_reply_to_screen_name" : "terrycavanagh", "in_reply_to_user_id_str" : "36457353", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "167082255741747200", "text" : "Had a dream about a game called Moses. You just hold the right key down for 40 years, while he walks in the desert. Sounds like a hit.", "id" : 167082255741747200, "created_at" : "2012-02-08 03:08:08 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ { "text" : "NBN", "indices" : [ 73, 77 ] } ], "urls" : [ ] }, "geo" : { }, "id_str" : "166882954470100992", "text" : "Working on a secret project with my brother. You'll all thank us later. #NBN", "id" : 166882954470100992, "created_at" : "2012-02-07 13:56:11 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "166808176233168896", "text" : "Man I need to learn slide.", "id" : 166808176233168896, "created_at" : "2012-02-07 08:59:03 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "Matt Williams", "screen_name" : "TheBritResistor", "indices" : [ 0, 16 ], "id_str" : "343058036", "id" : 343058036 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "in_reply_to_status_id_str" : "166513689426542592", "geo" : { }, "id_str" : "166719159181381633", "in_reply_to_user_id" : 343058036, "text" : "@TheBritResistor I am, what's the game?", "id" : 166719159181381633, "in_reply_to_status_id" : 166513689426542592, "created_at" : "2012-02-07 03:05:19 +0000", "in_reply_to_screen_name" : "TheBritResistor", "in_reply_to_user_id_str" : "343058036", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "166495142176501760", "text" : "If I could become as knowledgable about UDK as I am about as3 that would be really exciting.", "id" : 166495142176501760, "created_at" : "2012-02-06 12:15:09 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "166319276372922369", "text" : "Just ran my first ever C++ program.", "id" : 166319276372922369, "created_at" : "2012-02-06 00:36:20 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "166209471184519168", "text" : "'Killer feature' makes me think of the feature that ruins the 'killer app'. E.g. in Safari, the url bar and the search bar are separate.", "id" : 166209471184519168, "created_at" : "2012-02-05 17:20:00 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "166204113451892737", "text" : "I was about to try writing a program to store my bookmarks in a more visual way. But I'll check if any web browsers have this already.", "id" : 166204113451892737, "created_at" : "2012-02-05 16:58:43 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "166052075912962050", "text" : "Need a new mouse so bad.", "id" : 166052075912962050, "created_at" : "2012-02-05 06:54:34 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "165675024445997057", "text" : "Had an idea how to fake the physics in my game for a while now, been avoiding it. But at this point I just don't care. FAKE PHYSICS!", "id" : 165675024445997057, "created_at" : "2012-02-04 05:56:18 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "165491472672628736", "text" : "Been up all night under the assumption that flash's coordinate system behaved a way that it didn't. All calculations were bound to fail.", "id" : 165491472672628736, "created_at" : "2012-02-03 17:46:56 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "165332589245243392", "text" : "Finished a book I only bought two days ago. It once took me a year and a half to read Catch 22. Thats like 15000% faster.", "id" : 165332589245243392, "created_at" : "2012-02-03 07:15:35 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "Chevy Ray", "screen_name" : "ChevyRay", "indices" : [ 0, 9 ], "id_str" : "55472734", "id" : 55472734 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ { "indices" : [ 10, 30 ], "url" : "http:\/\/t.co\/aoqfulmF", "expanded_url" : "http:\/\/babyx.bandcamp.com\/", "display_url" : "babyx.bandcamp.com" } ] }, "in_reply_to_status_id_str" : "165251795956936704", "geo" : { }, "id_str" : "165330334215454720", "in_reply_to_user_id" : 55472734, "text" : "@ChevyRay http:\/\/t.co\/aoqfulmF", "id" : 165330334215454720, "in_reply_to_status_id" : 165251795956936704, "created_at" : "2012-02-03 07:06:38 +0000", "in_reply_to_screen_name" : "ChevyRay", "in_reply_to_user_id_str" : "55472734", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "BABY X", "screen_name" : "BABYXBAND", "indices" : [ 23, 33 ], "id_str" : "149419176", "id" : 149419176 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "164928878408761345", "text" : "Just found out my band @babyxband is playing Spectrum this Saturday. Never played Spectrum before.", "id" : 164928878408761345, "created_at" : "2012-02-02 04:31:23 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "Jake Kazdal", "screen_name" : "Jkooza", "indices" : [ 3, 10 ], "id_str" : "53789489", "id" : 53789489 }, { "name" : "Jean Snow", "screen_name" : "jeansnow", "indices" : [ 13, 22 ], "id_str" : "16125731", "id" : 16125731 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ { "indices" : [ 64, 84 ], "url" : "http:\/\/t.co\/lLToyMjr", "expanded_url" : "http:\/\/vimeo.com\/31240369", "display_url" : "vimeo.com\/31240369" } ] }, "geo" : { }, "id_str" : "164739040074137600", "text" : "RT @Jkooza: \u201C@jeansnow: Absolute insanity, mountain acrobatics: http:\/\/t.co\/lLToyMjr\u201D this is crazy, this is crazy", "retweeted_status" : { "source" : "\u003Ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003ETwitter for iPhone\u003C\/a\u003E", "entities" : { "user_mentions" : [ { "name" : "Jean Snow", "screen_name" : "jeansnow", "indices" : [ 1, 10 ], "id_str" : "16125731", "id" : 16125731 } ], "media" : [ ], "hashtags" : [ ], "urls" : [ { "indices" : [ 52, 72 ], "url" : "http:\/\/t.co\/lLToyMjr", "expanded_url" : "http:\/\/vimeo.com\/31240369", "display_url" : "vimeo.com\/31240369" } ] }, "geo" : { }, "id_str" : "164620904805048320", "text" : "\u201C@jeansnow: Absolute insanity, mountain acrobatics: http:\/\/t.co\/lLToyMjr\u201D this is crazy, this is crazy", "id" : 164620904805048320, "created_at" : "2012-02-01 08:07:36 +0000", "user" : { "name" : "Jake Kazdal", "screen_name" : "Jkooza", "protected" : false, "id_str" : "53789489", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/479776340363583489\/RtAF56pm_normal.png", "id" : 53789489, "verified" : false } }, "id" : 164739040074137600, "created_at" : "2012-02-01 15:57:02 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ { "text" : "GGJ", "indices" : [ 24, 28 ] } ], "urls" : [ ] }, "geo" : { }, "id_str" : "164737976918753281", "text" : "Just adding sound to my #GGJ game, sounds like a Dirty Projectors record. Trying to get the game up to scratch by Saturday.", "id" : 164737976918753281, "created_at" : "2012-02-01 15:52:49 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003ETwitter Web Client\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ { "text" : "Bastion", "indices" : [ 41, 49 ] } ], "urls" : [ ] }, "geo" : { }, "id_str" : "164702656038838273", "text" : "Finally got 'First Prize' in Camp Dauncy #Bastion", "id" : 164702656038838273, "created_at" : "2012-02-01 13:32:27 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"http:\/\/www.twitter.com\" rel=\"nofollow\"\u003ETwitter for Windows Phone\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ { "expanded_url" : "http:\/\/twitter.com\/james_a_forbes\/status\/164597086678040576\/photo\/1", "indices" : [ 9, 29 ], "url" : "http:\/\/t.co\/k4Wvf7l3", "media_url" : "http:\/\/pbs.twimg.com\/media\/AkjELaLCQAAPCYa.jpg", "id_str" : "164597086682234880", "id" : 164597086682234880, "media_url_https" : "https:\/\/pbs.twimg.com\/media\/AkjELaLCQAAPCYa.jpg", "sizes" : [ { "h" : 453, "resize" : "fit", "w" : 340 }, { "h" : 150, "resize" : "crop", "w" : 150 }, { "h" : 3264, "resize" : "fit", "w" : 2448 }, { "h" : 800, "resize" : "fit", "w" : 600 }, { "h" : 1365, "resize" : "fit", "w" : 1024 } ], "display_url" : "pic.twitter.com\/k4Wvf7l3" } ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "164597086678040576", "text" : "New book http:\/\/t.co\/k4Wvf7l3", "id" : 164597086678040576, "created_at" : "2012-02-01 06:32:59 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } }, { "source" : "\u003Ca href=\"https:\/\/about.twitter.com\/products\/tweetdeck\" rel=\"nofollow\"\u003ETweetDeck\u003C\/a\u003E", "entities" : { "user_mentions" : [ ], "media" : [ ], "hashtags" : [ ], "urls" : [ ] }, "geo" : { }, "id_str" : "164369012342521856", "text" : "Notepad I love you so much.", "id" : 164369012342521856, "created_at" : "2012-01-31 15:26:41 +0000", "user" : { "name" : "James Forbes", "screen_name" : "james_a_forbes", "protected" : false, "id_str" : "16025792", "profile_image_url_https" : "https:\/\/pbs.twimg.com\/profile_images\/571253075579396096\/_csqQudw_normal.jpeg", "id" : 16025792, "verified" : false } } ]
/* plugin version 1.0 */ /*eslint-disable*/ var myapp = (function () { 'use strict'; var __TEST = 1; function preproc (code) { return code } function postproc (code) { return code } /*! Main */ function jspp () { var filter = function (id) { return id || __TEST; }; return { name: 'jspp', run: function run(code, id) { if (typeof code != 'string') { code = '__CODE'; } if (!filter(id)) { return null } return postproc(preproc(code)) } } } return jspp; }()); /* follow me on Twitter! @amarcruz */
//this is just a test script
'use-strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var questionSchema = new Schema({ questionId : { type: Number, required: true, unique: true , index: true}, catagoryId : Number, title : String, question : String, postDate : Date, userId : Number, rate : Number, lastModify : Date, _user : [{ type: Schema.Types.ObjectId, ref: 'Users' }], }, { strict: false }); questionSchema.index({ question : 'text', title : 'text'}); questionSchema.virtual('PrimaryKey').get(function(){ return 'questionId'; }); questionSchema.virtual('CollectionName').get(function(){ return 'Questions'; }); var Questions = mongoose.model('Questions',questionSchema); module.exports = Questions;
const express = require('express'); const app = new express(); const ejs = require('ejs'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const fileUpload = require('express-fileupload'); const newPostController = require('./controllers/newPost'); const homeController = require('./controllers/home'); const storePostController = require('./controllers/storePost'); const getPostController = require('./controllers/getPost'); const validateMiddleWare = require('./middleware/validationMiddleware'); app.use(fileUpload()); mongoose.connect('mongodb://localhost/my_database', { useUnifiedTopology: true, useNewUrlParser: true }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.set('view engine', 'ejs'); app.use(express.static('public')); app.listen(4000, () => { console.log('App listening on port 4000 ...'); }); const myMiddleWare = (req, res, next) => { console.log('Custom middleware called') next() }; app.use(myMiddleWare); app.use('/posts/store', validateMiddleWare); app.get('/', homeController); app.get('/post/:id', getPostController); app.get('/posts/new', newPostController); app.post('/posts/store', storePostController);
import { BaseSession, createAuthService } from '@syncot/auth' import { createConnection } from '@syncot/connection' import { createContentBackend, createContentService, createContentStore, createPubSub, } from '@syncot/content' import { createContentType as createProseMirrorContentType } from '@syncot/content-type-prosemirror' import { createPing } from '@syncot/ping' import { SocketStream } from '@syncot/stream-socket' import WebSocket from 'ws' const path = '/syncot/websocket' const port = 10004 const server = new WebSocket.Server({ path, port }) const contentStore = createContentStore() const pubSub = createPubSub() const proseMirrorContentType = createProseMirrorContentType() const contentBackend = createContentBackend({ contentStore, pubSub, contentTypes: { demo: proseMirrorContentType, }, }) class DemoSession extends BaseSession { mayReadContent() { return true } mayWriteContent() { return true } mayReadPresence() { return true } mayWritePresence() { return true } } server.on('connection', (socket) => { const stream = new SocketStream(socket) const connection = createConnection() connection.connect(stream) stream.once('close', () => { connection.destroy() }) const auth = createAuthService({ connection, createSession() { return new DemoSession() }, }) const ping = createPing({ connection, timeout: 50000 }) const contentService = createContentService({ connection, auth, contentBackend, }) }) console.info(`SyncOT server listening on http://localhost:${port}${path}`)
function slideSwitch() { var $present = $('#slide img.present'); if ($present.length == 0) $present = $('#slide img:last'); var $next = $present.next().length ? $present.next() : $('#slide img:first'); $present.addClass('previous'); $next.css({ opacity: 0.0 }) .addClass('present') .animate({ opacity: 1.0 }, 1500, function () { $present.removeClass('present previous'); }); } $(function () { setInterval("slideSwitch()", 4000); });
import React from 'react'; import { connect } from 'react-redux'; import { Input, Button, Form, Icon, Table, Popconfirm } from 'antd'; import CustomBreadcrumb from '@/components/BreadCrumb'; import HostsModal from './hosts'; import HostgroupModal from './hostgroupModal'; import TemplateModal from './templatesModal'; import PluginsModal from './pluginsModal'; import { fetchHostgroup } from '../../store/reducers/portal/actions'; import API from '@/api'; const { Search } = Input; const { Item } = Form; class Portal extends React.Component { columns = [{ title: 'Name', dataIndex: 'grp_name' }, { title: 'Creator', dataIndex: 'create_user' }, { title: 'Host', dataIndex: 'id', render: text => <button className="button-text" type="button" onClick={() => { this.showModal(text); }}>view Hosts</button> }, { title: 'Operation', render: (text, record) => ( <> <Popconfirm title="Are you sure delete this group?" onConfirm={() => { this.onDeleteHost(record.id); }}> <button className="button-text" type="button">Delete</button> </Popconfirm> <button className="button-text" type="button" onClick={() => { this.editHostgroup(record); }}>Edit</button> <button className="button-text" type="button" onClick={() => { this.bindTemplate(record.id); }}>Templates</button> <button className="button-text" type="button" onClick={() => { this.bindPlugins(record.id); }}>Plugins</button> <button className="button-text" type="button" onClick={() => { this.props.history.push(`/portal/aggregator/${record.id}`); }}>Aggregator</button> </> ) }] constructor() { super(); this.state = {}; } componentDidMount() { const { hostGroups } = this.props; if (!hostGroups) { this.props.dispatch(fetchHostgroup()); } } onCancel = () => { this.setState({ visible: false }); } onDeleteHost = async (id) => { await API.delete(`/hostgroup/${id}`); this.props.dispatch(fetchHostgroup()); } editHostgroup = async (hostgroup) => { const { data } = await API.get(`/hostgroup/${hostgroup.id}`); this.setState({ ...data, groupModalVisible: true }); } showModal = async (id) => { const { data } = await API.get(`/hostgroup/${id}`); const { hosts, hostgroup } = data; this.setState({ hosts, title: `Group name: ${hostgroup.grp_name}`, hostgroup, visible: true }); } showGroupModal = () => { this.setState({ groupModalVisible: true, hostgroup: {}, hosts: [] }); } closeGroupModal = () => { this.setState({ groupModalVisible: false }); } bindTemplate = async (id) => { this.getBindTemplate(id); } getBindTemplate = async (id) => { const { data } = await API.get(`/hostgroup/${id}/template`); this.setState({ ...data, templateModalVisible: true }); } bindPlugins = (id) => { this.getPlugins(id); } getPlugins = async (id) => { const { data } = await API.get(`/hostgroup/${id}/plugins`); this.setState({ plugins: data, pluginsModalVisible: true, hostgroupId: id }); } closeTemplateModal = () => { this.setState({ templateModalVisible: false }); } closePluginsModal = () => { this.setState({ pluginsModalVisible: false }); } render() { const { hosts, visible, title, hostgroup, groupModalVisible, templates = [], templateModalVisible, pluginsModalVisible, plugins, hostgroupId } = this.state; const { getFieldDecorator } = this.props.form; const { hostGroups = [] } = this.props; return ( <> <CustomBreadcrumb arr={['HostGroups']} /> <Form layout="inline" style={{ marginBottom: 15 }}> <Item> { getFieldDecorator('q')( <Search style={{ width: 300 }} placeholder="Enter Host Group Name..." /> ) } </Item> <Item> <Button type="primary" onClick={this.showGroupModal}> <Icon type="plus" /> <span>Create HostGroups</span> </Button> </Item> </Form> <Table rowKey="id" bordered columns={this.columns} dataSource={hostGroups} /> <HostgroupModal visible={groupModalVisible} hosts={hosts} hostgroup={hostgroup} closeGroupModal={this.closeGroupModal} /> <HostsModal title={title} hosts={hosts} hostgroup={hostgroup} onCancel={this.onCancel} visible={visible} getHosts={this.showModal} /> <TemplateModal history={this.props.history} visible={templateModalVisible} hostgroup={hostgroup} templates={templates} onCancel={this.closeTemplateModal} getBindTemplate={this.getBindTemplate} /> <PluginsModal visible={pluginsModalVisible} plugins={plugins} hostgroup_id={hostgroupId} getPlugins={this.getPlugins} onCancel={this.closePluginsModal} /> </> ); } } const mapStateToProps = ({ portal }) => { const { hostGroups } = portal; return { hostGroups }; }; export default Form.create()(connect(mapStateToProps)(Portal));
const mongoose = require('mongoose'); const moment = require('moment'); const config = require('../../config'); const Schema = mongoose.Schema; mongoose.Promise = global.Promise; let ChargeorderSchema = new Schema({ orderno: { type: String, required: true, index: { unique: true }}, phoneInfo: {_id: {type: Schema.Types.ObjectId, ref: 'Simcard'}, phoneno: String, cardpackage: {name: String, fee: Number}}, exFeeEndDate: Date, newFeeEndDate: Date, statusCode: { type: Number, default: config.statusCode.unpaid }, fee: Number, orderTime: { type: Date, default: Date.now } }); module.exports = mongoose.model('Chargeorder', ChargeorderSchema);
export const validatePathName = (pathName) => { const re = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$|([<>:"\/\\|?*])|(\.|\s)$/gi; return re.test(pathName) && pathName !== "."; }; export const arrayToMap = (target) => { const map = new Map(target.map((value, index) => [index, value])); return map; }; export const extractMapValues = (target) => { return [...target.values()]; }; export const extractDescription = (target) => { return target.map((option) => option.description); };
function SaveAndOrder() { var name = document.getElementById("name").value; var add = document.getElementById("add").value; var mobile1 = document.getElementById("mobile").value; if(name =='') { alert("please enter name."); } else if(add=='') { alert("enter the address "); } else if(mobile1=='') { alert("Enter mobile number."); } else if(mobile1.length != 10) { alert("Enter valid 10 digit mobile number."); } else { alert('Thank You for Address details & Order is successful'); } } function reset() { document.getElementById("name").value = ''; document.getElementById("add").value = ''; document.getElementById("mobile").value = ''; }
import React from 'react'; import { css } from 'emotion/macro'; const footerStyle = css` max-width: 63.75em; margin-left: auto; margin-right: auto; border-radius: 0 0 4px 4px; color: #313030; text-align: center; padding-bottom: 2em; span { margin: 0; font-family: 'cornerstone', sans-serif; font-weight: 600; } `; const Footer = () => ( <footer className={footerStyle}> <span>&copy; My Ice Cream</span> </footer> ); export default Footer;
'use strict'; /* global io */ $(function () { const socket = io(window.location.origin); const $main = $('main'); const $input = $('input'); // function createUserMessage (messageDetails) { // return `<h3><span>${messageDetails.name}</span>: ${messageDetails.message}</h3>`; // } $input.on('keydown', function (event) { if (event.keyCode !== 13) return; const message = $input.val(); $input.val(null); socket.emit('newMessage', message); }); socket.on('connect', function () { console.log('new connection'); }); socket.on('chatMessage', function (message) { $main.append(`<span>${message.trim()} </span>`); }); });
// @flow import React from 'react'; import { View, StyleSheet, Text } from 'react-native'; import { UIComponent, UIStyle, UIColor, } from '../services/UIKit'; const styles = StyleSheet.create({ tableItem: { paddingTop: 12, paddingBottom: 12, borderTopColor: UIColor.whiteLight(), }, }); export default class Table extends UIComponent { render() { if (!this.props.items || !this.props.items.length) return null; return ( <View style={this.props.style}> {this.props.items.map((text, rank) => ( <View style={[styles.tableItem, { borderTopWidth: rank === 0 ? 0 : 1 }]} key={rank} > { typeof (text) === 'string' ? <Text style={[UIStyle.text.secondaryBodyRegular()]}>{text}</Text> : text } </View> ))} </View> ); } }
'use strict'; const rus = document.getElementById('rus'); const science = document.getElementById('science'); const technology = document.getElementById('technology'); const entertaiment = document.getElementById('entertaiment'); const main = document.getElementsByTagName('main')[0]; const apiKey = '10114b0fdf404dff99fe98fbad71ccfc'; const rusUrl = 'https://newsapi.org/v2/top-headlines?' + 'country=ru&' + 'apiKey='; const scienceUrl = 'https://newsapi.org/v2/top-headlines?country=ru&category=science&apiKey='; const technologyUrl = 'https://newsapi.org/v2/top-headlines?country=ru&category=technology&apiKey='; const entertaimentUrl = 'https://newsapi.org/v2/top-headlines?country=ru&category=entertainment&apiKey='; /* https://newsapi.org/docs/get-started#top-headlines https://medium.com/siliconwat/how-javascript-async-await-works-3cab4b7d21da */ async function getNews(url) { let response = await fetch(url + apiKey); let jsonResponse = await response.json(); let articlesArray = jsonResponse.articles.slice(0,5); return articlesArray; } function renderNews(articles) { articles.map((article, index) => { let articleRow = '<div class="articlerow">' + ' <div class="article">' + ' <h2 class="title">' + article.title + '</h2>' + ' <p> ' + article.description + '</p>' + ' <a href="' + article.url + '" target="_blank" class="readmore">Читать дальше</a>' + ' </div>' + ' <div class="images">' + ' <img class="img" src="' + article.urlToImage + '" />' + ' </div>' + '</div>'; main.innerHTML += articleRow; }); return articles; } // При нажатии на кнопку запускается рендер rus.addEventListener('click', function() { main.innerHTML = ' '; getNews(rusUrl).then(articlesArray => renderNews(articlesArray)); }, false); science.addEventListener('click', function() { main.innerHTML = ' '; getNews(scienceUrl).then(articlesArray => renderNews(articlesArray)); }, false); technology.addEventListener('click', function() { main.innerHTML = ' '; getNews(technologyUrl).then(articlesArray => renderNews(articlesArray)); }, false); entertaiment.addEventListener('click', function() { main.innerHTML = ' '; getNews(entertaimentUrl).then(articlesArray => renderNews(articlesArray)); }, false);
import React, { useEffect, useState } from 'react' import User from '../User'; import { dash, userDash } from '../../Data'; import Nsi from '../User/notsignedin'; import api from '../../api'; const UserPage = () => { const [islogin, setIslogin] = useState(false); useEffect(() => { api("api/home") .then((data) => { setIslogin(data.authentication); }) }, []); return ( <> <div style={islogin ? {display:"unset"} : {display:"none"}}> <User {...dash} data={userDash} /> </div> <div style={islogin ? {display:"none"} : {display:"unset"}}> <Nsi /> </div> </> ) } export default UserPage;
import ItemsAddress from "components/website/pages/contact-us/section-address/items/ItemsAddress"; // import {useEffect} from "react" export default function Address ( data ){ // useEffect(() => { // console.log(data); // }, []) return ( <section> <div className="sectionAddress"> { data.data ? ( <> { data.data.data.list.map((value, index) => ( <ItemsAddress key = {index} name={value.title} address={value.address} tel={value.phone} fax={value.fax} email={value.email} ></ItemsAddress> )) } </> ):( <> <ItemsAddress></ItemsAddress> <ItemsAddress name="HCM Office"></ItemsAddress> <ItemsAddress></ItemsAddress> </> )} </div> <style jsx>{` section{ width: 100%; display: flex; flex-direction: row; justify-content: center } .sectionAddress{ width: 100%; padding: 50px 5vw; display: flex; justify-content: center; position: relative; } @media screen and (max-width:767px) { .sectionAddress{ width: 100%; flex-wrap: wrap; } } `}</style> </section> ) }
'use strict'; var servicesModule = angular.module('servicesModule', []); var controllersModule = angular.module('controllersModule', []); var directivesModule = angular.module('directivesModule', []); var adminModule = angular.module('adminModule', ['controllersModule', 'servicesModule', 'directivesModule', 'ngRoute', 'ui.bootstrap', 'ngCookies']); adminModule.config(function ($routeProvider, $httpProvider) { $httpProvider.useApplyAsync(true); $routeProvider.when('/', { templateUrl: 'pages/admin/adminMain.csp', controller: 'adminController' }) .when('/categories', { templateUrl: 'pages/admin/categories.csp', controller: 'CategoriesController', controllerAs: 'vm' }) .when('/categories/edit', { templateUrl: 'pages/admin/editCategory.csp', controller: 'EditCatController', controllerAs: 'vm' }) .when('/categories/edit/:id', { templateUrl: 'pages/admin/editCategory.csp', controller: 'EditCatController', controllerAs: 'vm' }) .when('/area/edit/:id', { templateUrl: 'pages/admin/editArea.csp', controller: 'EditAreaController', controllerAs: 'vm' }) .when('/area/edit', { templateUrl: 'pages/admin/editArea.csp', controller: 'EditAreaController', controllerAs: 'vm' }) .when('/area', { templateUrl: 'pages/admin/area.csp', controller: 'AreaController', controllerAs: 'vm' }) .when('/responsible/edit/:id', { templateUrl: 'pages/admin/editResponsible.csp', controller: 'EditResponsibleController', controllerAs: 'vm' }) .when('/responsible/edit', { templateUrl: 'pages/admin/editResponsible.csp', controller: 'EditResponsibleController', controllerAs: 'vm' }) .when('/responsible', { templateUrl: 'pages/admin/responsible.csp', controller: 'ResponsibleController', controllerAs: 'vm' }) .when('/act', { templateUrl: 'pages/admin/act.csp', controller: 'ActController', controllerAs: 'vm' }) ; $routeProvider.otherwise({ redirectTo: '/' }); }); adminModule.controller('adminController', function ($scope, $http, $location) { var vm = this; // Get the Sidebar var mySidebar = document.getElementById("mySidebar"); // Get the DIV with overlay effect var overlayBg = document.getElementById("myOverlay"); vm.w3_open = w3_open; vm.w3_close = w3_close; // Toggle between showing and hiding the sidebar, and add overlay effect function w3_open() { if (mySidebar.style.display === 'block') { mySidebar.style.display = 'none'; overlayBg.style.display = "none"; } else { mySidebar.style.display = 'block'; overlayBg.style.display = "block"; } } // Close the sidebar with the close button function w3_close() { mySidebar.style.display = "none"; overlayBg.style.display = "none"; } $scope.admin = $.inArray($location.path(), ['/admin']) === 1; });
/** * @license * Copyright (c) 2018 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // Import statements in Polymer 3.0 can now use package names. // polymer-element.js now exports PolymerElement instead of Element, // so no need to change the symbol. import { PolymerElement, html } from '@polymer/polymer/polymer-element.js'; import '@polymer/polymer/lib/elements/dom-if.js'; import '@polymer/paper-checkbox/paper-checkbox.js'; import '@polymer/paper-input/paper-input.js'; import { setPassiveTouchGestures } from '@polymer/polymer/lib/utils/settings'; import './fields-group.js'; class StartPolymer3 extends PolymerElement { static get properties () { return { message: { type: String, value: '' }, pie: { type: Boolean, value: false, observer: 'togglePie' }, loadComplete: { type: Boolean, value: false } }; } constructor() { // If you override the constructor, always call the // superconstructor first. super(); // Resolve warning about scroll performance // See https://developers.google.com/web/updates/2016/06/passive-event-listeners setPassiveTouchGestures(true); this.message = 'Hello World! I\'m a Polymer element :)'; } ready(){ // If you override ready, always call super.ready() first. super.ready(); // Output the custom element's HTML tag to the browser console. // Open your browser's developer tools to view the output. console.log(this.tagName); } // <vaadin-horizontal-layout theme="spacing-xs"> // :host([theme~="spacing-xs"]) ::slotted(*) { // margin-left: var(--lumo-space-xs); // } togglePie(){ if(this.pie && !this.loadComplete) { // See https://developers.google.com/web/updates/2017/11/dynamic-import import('./lazy-element.js').then((LazyElement) => { console.log("LazyElement loaded"); }).catch((reason) => { console.log("LazyElement failed to load", reason); }); this.loadComplete = true; } } static get template () { // Template getter must return an instance of HTMLTemplateElement. // The html helper function makes this easy. return html` <custom-style> <style is="custom-style"> paper-input.custom2:hover { border: 1px solid #29B6F6; } paper-input.custom2 { border: 1px solid #BDBDBD; border-radius: 5px; margin-bottom: 14px; --paper-input-container: { padding: 8px 0px; }; --paper-input-container-underline-focus: { margin-left : 8px; margin-right : 8px }; --paper-input-container-label: { top: -16px; padding: 4px 4px 4px 4px; left: 8px; background: white; font-weight: bold; } --paper-input-container-underline: { display: none; }; --paper-input-container-input:{ padding-left: 8px; box-sizing: border-box; } --paper-input-container-label-floating: { width: auto; }; } paper-input.custom { margin-bottom: 14px; --primary-text-color: #01579B; --paper-input-container-color: black; --paper-input-container-focus-color: black; --paper-input-container-invalid-color: black; border: 1px solid #BDBDBD; border-radius: 5px; /* Reset some defaults */ --paper-input-container: { padding: 0;}; --paper-input-container-underline: { display: none; height: 0;}; --paper-input-container-underline-focus: { display: none; }; /* New custom styles */ --paper-input-container-input: { box-sizing: border-box; font-size: inherit; padding: 4px; }; --paper-input-container-input-focus: { background: rgba(0, 0, 0, 0.1); }; --paper-input-container-input-invalid: { background: rgba(255, 0, 0, 0.3); }; --paper-input-container-label: { top: -8px; left: 4px; background: white; padding: 2px; font-weight: bold; }; --paper-input-container-label-floating: { width: auto; }; } </style> </custom-style> <style> paper-checkbox { --paper-checkbox-checked-ink-color: #FFFFFF; --paper-checkbox-unchecked-ink-color: #FFFFFF; } .container3 { position: relative; display: flex; flex-flow: row wrap; padding-left:8px; padding-right:8px; margin-bottom : 16px; border : solid 1px yellow; } .container3 > paper-input { min-width: 200px; max-width: 400px; flex-basis: auto; /* default value */ flex-grow: 1; margin-left:8px; margin-right:8px margin-bottom : 8px; } .container { position: relative; display: flex; flex-flow: row wrap; padding-left:8px; padding-right:8px; } .container > paper-input { min-width: 200px; max-width: 400px; flex-basis: auto; /* default value */ flex-grow: 1; margin-left:8px; margin-right:8px } .container2 { position: relative; display: flex; flex-flow: row wrap; padding-left:8px; padding-right:8px; } .container2 > paper-input { min-width: 300px; max-width: 400px; flex-basis: auto; /* default value */ flex-grow: 1; margin-left:8px; margin-right:8px } .container2 > paper-input { --paper-input-container: { padding : 0px 0px 16px 0px; } } .oe-custom { --paper-input-container-input: { border: 1px solid var(--secondary-text-color); border-radius: 4px; padding: 12px 8px 4px 8px; box-sizing: border-box; } --paper-input-container-input-focus: { border-bottom-color: var(--primary-color); } --paper-input-container-input-invalid: { border-bottom-color: var(--error-color); } --paper-input-container-label: { top: 12px; left: 8px; } --paper-input-container-label-floating: { z-index: 2; top: 10px; display: flex; background:white; width:auto; } --paper-input-container-underline: { display: none; } --paper-input-container-underline-focus: { display: none; } } </style> <h1>Form Layout</h1> <div class="container3"> <paper-input class="oe-custom" label="Solution" value="All" invalid error-message="In error"></paper-input> <paper-input class="oe-custom" label="Solution" value="All"></paper-input> <paper-input class="oe-custom" label="Solution" value="All"></paper-input> </div> <div style="min-heght:16px"> </div> <div class="container"> <paper-input class="custom" always-float-label label="Name" value="Praveen"></paper-input> <paper-input label="Company" value="Infosys"></paper-input> <paper-input class="custom2" always-float-label label="Age" value="47"></paper-input> </div> <div class="container"> <paper-input label="Company" value="Infosys"></paper-input> <paper-input label="Product" value="Finacle"></paper-input> </div> <div class="container"> <paper-input label="Qualification" value="B.Tech."></paper-input> <paper-input label="Solution" value="All"></paper-input> </div> <div class="container2"> <paper-input label="Name" value="Praveen"></paper-input> <paper-input label="Age" value="47"></paper-input> <paper-input label="Company" value="Infosys"></paper-input> <paper-input label="Product" value="Finacle"></paper-input> <paper-input label="Qualification" value="B.Tech."></paper-input> <paper-input label="Solution" value="All"></paper-input> </div> <fields-group> <paper-input label="Name" value="Praveen"></paper-input> <paper-input label="Age" value="47"></paper-input> <paper-input label="Company" value="Infosys"></paper-input> <paper-input label="Product" value="Finacle"></paper-input> <paper-input label="Qualification" value="B.Tech."></paper-input> <paper-input label="Solution" value="All"></paper-input> </fields-group> `; } } // Register the element with the browser. customElements.define('start-polymer3', StartPolymer3);
export default mnBucketsDeleteDialogController; function mnBucketsDeleteDialogController($uibModalInstance, bucket, mnPromiseHelper, mnBucketsDetailsService) { var vm = this; vm.doDelete = doDelete; vm.bucketName = bucket.name; function doDelete() { var promise = mnBucketsDetailsService.deleteBucket(bucket); mnPromiseHelper(vm, promise, $uibModalInstance) .showGlobalSpinner() .catchGlobalErrors() .closeFinally() .showGlobalSuccess("Bucket deleted successfully!"); } }
var Stats = require('Stats') , properties = require('../properties') , boot = {}; boot.preload = function () { factory.preload_entities(); }; boot.create = function () { }; module.exports = boot;
/* * Jikuu Tumblr Theme - Layout Code * Copyright (C) 2013, Michiel Sikma <mike@letsdeliver.com> * All Rights Reserved * Date: 2013-06-08 * * @author Michiel Sikma * // ==ClosureCompiler== // @output_file_name jikuu.min.js // @compilation_level ADVANCED_OPTIMIZATIONS // @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/jquery-1.8.js // ==/ClosureCompiler== * */ (function($) { /** * @namespace Jikuu theme layout code. */ window["Jikuu"] = {}; /** * Main layout code. * jQuery objects are indicated by a $ variable name prefix. * * @static */ Jikuu["Main"] = (function() { var self = this; /* The Jikuu layout sections that can be decorated: */ var $section_me; // blog description section var $section_socmed; // social media links list var $section_nav; // primary navigation var $section_twitter; // latest tweets var $section_contributors; // blog contributors list var $section_following; // followed blogs list var $section_pagenav; // page archive navigation var $section_loader; // dynamic loading indicator var $_post; // an ordered array of posts var $container_posts; // the outer posts container var $container_tmp; // container for dynamic loading /* Other necessary items: */ var $root; // the outermost layout wrapper var $window; // window/viewport object /* * The posts are processed according to an algorithm that * positions them in either the left or the right column. * These columns are shown on the largest layout. * Therefore we keep track of the height of both columns. */ var posts_col_left = 0; // left column height var posts_col_right = 0; // right column height var posts_processed = {}; // object of processed posts /* Variables used for the sticky navigation menu. */ var window_scroll_top; // viewport vertical scroll amount var window_height; // viewport height /* Default settings. */ var defaults = { use_endless_scrolling : false, photoset_gutter_size : "8px", /* Settings that can't be configured using user theme settings. */ inf_scrolling_margin : 300 // page load distance from bottom }; var settings = {}; // container for final settings /** * Updates the window scroll amount and height variables. */ self.update_window_info = function() { window_scroll_top = $window.scrollTop(); window_height = $window.height(); } /** * Binds the screen update triggers (to the scroll and resize events). */ self.init_update_trigger = function() { Jikuu.Debug["info"]("Jikuu::Main.init_update_trigger(): adding update callback to window object (scroll, resize)"); $window.bind("scroll resize", function() { self.update_layout(); }); } /** * Locates all usable elements on the page and creates jQuery objects * out of them. * * @returns {boolean} true if successful, false if #root element could not be found. */ self.init_elements = function() { /* The browser window (used for binding update events). */ $window = $(window); /* #root contains all theme-related markup. */ $root = $("#root"); if ($root[0]) { Jikuu.Debug["log"]("found #root element %o", [$root[0]]); } else { /* When using the Jikuu theme's own HTML, this should never occur. */ Jikuu.Debug["error"]("Jikuu::Main.init_elements(): couldn't find root element"); return false; } /* #header contains the title image or text, and the blue line. */ $header = $("#header", $root); /* #title is the container for the title image or text. */ $title = $("#title", $root); /* #content contains all posts and blog information. */ $content = $("#content", $root); /* #content_sidebar contains all blog information and navigation sections. */ $content_sidebar = $("#content_sidebar", $root); /* #section_me contains the blog description and user picture. */ $section_me = $("#section_me", $root); /* #section_main_nav contains the main navigation, the search form * and any links to custom pages. */ $section_main_nav = $("#section_main_nav", $root); /* #form_search is the search form inside the main navigation. */ $form_search = $("#form_search", $root); /* #section_twitter contains the user's tweets. */ $section_twitter = $("#section_twitter", $root); /* #section_contributors contains a list of other blog members. */ $section_contributors = $("#section_contributors", $root); /* #section_following contains a list of blogs the user follows. */ $section_following = $("#section_following", $root); /* #content_main is the wrapper for the main content. */ $content_main = $("#content_main", $root); /* #container_posts contains all posts (and nothing else). */ $container_posts = $("#container_posts", $root); /* #container_nav contains the post navigation (links or a loading indicator). */ $container_nav = $("#container_nav", $root); /* #loader_posts is the loading indicator that's used for infinite scrolling. */ $loader_posts = $("#loader_posts", $root); return true; } /** * Waits for all image downloads to commence (to the point where the * image size is available) and then calls a callback. * TODO: test this properly, and possibly remove it if unnecessary */ self.after_images_loaded = function($el, callback) { var a, z; /* List the amount of images we have. */ var $_img = $("img", $el); var amount_total = $_img.length; var amount_preloaded = 0; function check_progress() { if (amount_preloaded >= amount_total) { callback.call(); } } for (a = 0, z = $_img.length; a < z; ++a) { $img = $($_img[a]); $img.one("load", function() { amount_preloaded += 1; check_progress(); }) .each(function() { if (this.complete || $img.height() > 0) { $(this).trigger("load"); } }); } } /** * Determines which page type we're currently viewing and then * calls the appropriate functions. * When on the index page, the posts loading and positioning code * is loaded. When on a permalink page, TODO fix description */ self.init_page_layout = function() { if (page_type == "index") { /* * Index pages: check post info and move them to * the appropriate column. */ self.after_images_loaded($container_posts, function() { self.determine_post_positions(); self.init_photoset_grids(); }); } else if (page_type == "permalink") { /* Permalink pages. */ } } /** * Lists all available posts and retrieves information on their size. * FIXME: first make determine_post_sizes() and then positions */ self.determine_post_positions = function() { Jikuu.Debug["log"]("Determining post positions"); $_post = $("> .post", $container_posts); Jikuu.Debug["log"]("Processing %i posts:", [$_post.length]); var processed, id, height, pull; for (var a = 0, z = $_post.length; a < z; ++a) { $post = $($_post[a]); id = $post.attr("data-id"); processed = posts_processed[id]; if (processed) { Jikuu.Debug["log"](" Post %i is already processed (skipping)", [id]); continue; } height = $post.height(); $post.removeClass("pull-left"); $post.removeClass("pull-right"); if (posts_col_left <= posts_col_right) { pull = "pull-left"; posts_col_left += height; } else { pull = "pull-right"; posts_col_right += height; } $post.addClass(pull); Jikuu.Debug["log"](" Post %i has been set to %i", [id, pull]); posts_processed[id] = true; $post.attr("data-height", height); } } /** * Empties out the post positioning cache in order to rebuild it from scratch. */ self.reset_posts = function() { posts_processed = {}; posts_col_left = 0; posts_col_right = 0; } /** * Finds and lists fixed elements. */ self.init_fixed_elements = function() { Jikuu.Debug["log"]("Initializing fixed elements"); $_fix_toggle_item = $(".fix-toggle-item", $root); self.scan_fixed_elements(); } // todo: necessary? self.scan_fixed_elements = function() { //Jikuu.Debug["log"]("Scanning fixed elements"); $_fix_toggle_item.each(function(n, fix_toggle_item) { var $fix_toggle_item = $(fix_toggle_item); var $fix_gap = $("> .fix-gap", $fix_toggle_item); var $fix_content = $("> .fix-content", $fix_toggle_item); var $fix_padding = $("> .fix-padding", $fix_toggle_item); var p_top = parseInt($fix_padding.css("padding-top"), 10); var p_bottom = parseInt($fix_padding.css("padding-bottom"), 10); var height = $fix_content.height(); //Jikuu.Debug["log"]("Element %o height: %d", [$fix_content[0], height]); $fix_gap.height(height+"px"); var offset = $fix_toggle_item.offset().top; var toggled = $fix_toggle_item.hasClass("pmode"); $.data(fix_toggle_item, "fixinfo_state", toggled); $.data(fix_toggle_item, "fixinfo", { $el: $fix_toggle_item, $ct: $fix_content, height: height, offset: offset, p_top: p_top, p_bottom: p_bottom }); }); } /** * Checks the navigation menu and activates the correct button * if necessary. (Tumblr doesn't set a server-side "active" class to * the menu item where we currently are, so we have to do it with JS.) */ self.update_menu_items = function() { var curr_path = window.location.pathname; Jikuu.Debug["info"]("Jikuu::Main.update_menu_items(): Current page: %i", [curr_path]); $_menu_item = $("ul.nav > li", $section_main_nav); $_menu_item.each(function(n, menu_item) { $menu_item = $(menu_item); var $menu_a = $("> a", $menu_item); var menu_href = $menu_a.attr("href"); if (menu_href == curr_path) { /* This is the current item. */ Jikuu.Debug["log"]("Setting menu item %o to active", [menu_item]); $menu_item.addClass("active"); } }); } /** * Activates the code needed to PHOTOSETS * todo: fix so that processed ones are cached */ self.init_photoset_grids = function() { var $photoset_grid, id; var gutter = settings.photoset_gutter_size; for (var a = 0, z = $_post.length; a < z; ++a) { $post = $($_post[a]); if ($post.hasClass("photoset")) { $photoset_grid = $(".photoset-grid", $post); id = $photoset_grid.attr("data-id"); $photoset_grid.photosetGrid({ highresLinks: true, rel: id, gutter: gutter, onComplete: function() { } }); } } } /** * Detaches and reattached fixed elements such as the main navigation. */ self.update_fixed_elements = function() { var fix_toggle_item, data, fixed; var $el, $ct, height, offset, p_top, p_bottom; for (var a = 0, z = $_fix_toggle_item.length; a < z; ++a) { fix_toggle_item = $_fix_toggle_item[a]; data = $.data(fix_toggle_item, "fixinfo"); fixed = $.data(fix_toggle_item, "fixinfo_state"); $el = data.$el; $ct = data.$ct; height = data.height; offset = data.offset; p_top = data.p_top; p_bottom = data.p_bottom; if (window_scroll_top > (offset - p_top)) { if (fixed == true) { continue; } $el.addClass("pmode"); $ct.css({paddingTop: p_top+"px", paddingBottom: p_bottom+"px"}); fixed = true; } else { if (fixed == false) { continue; } $el.removeClass("pmode"); $ct.css({paddingTop: 0, paddingBottom: 0}); fixed = false; } $.data(fix_toggle_item, "fixinfo_state", fixed); } } /** * Updates the screen once. */ self.update_layout = function() { self.update_window_info(); self.update_fixed_elements(); } /** * Initializes the user's settings and jumpstarts the code. */ self.__init__ = function(overrides) { /* Override default settings with user-supplied ones. */ settings = defaults; for (var key in overrides) { settings[key] = overrides[key]; } /* Version indicator. */ Jikuu.Debug["info"]("Jikuu Tumblr Theme v%d.%d%s", [ layout_version.major, layout_version.minor, layout_version.trunk == true ? " (trunk)" : "" ]); Jikuu.Debug["info"]("© 2013, Michiel Sikma"); Jikuu.Debug["info"]("Jikuu::Main.__init__(): initializing new Main instance"); /* Initialize all relevant elements. */ self.init_elements(); /* Update the menu to highlight the currently active page. */ self.update_menu_items(); /* Initialize elements that become fixed on scroll. */ self.init_fixed_elements(); /* Initialize the event triggers that update the dynamic elements. */ self.init_update_trigger(); /* Initialize page-specific code. */ self.init_page_layout(); /* All done. Ready for action. */ Jikuu.Debug["log"]("Done initializing instance"); } self.__init__(overrides); })(); /** * Console debugging static function. * * @static */ Jikuu.Debug = (function() { var self = this; /* Global switch for allowing console logging to take place. */ var permit_debug = true; /** * Turns debugging on or off. When off, debug calls silently fail. */ self["permit_debugging"] = function(permit) { permit_debug = permit; } /** * Info level log. */ self["info"] = function(str, vars) { return self["log"](str, vars, "info"); } /** * Warning level log. */ self["warn"] = function(str, vars) { return self["log"](str, vars, "warn"); } /** * Error level log. */ self["error"] = function(str, vars) { return self["log"](str, vars, "error"); } /** * Prints formatted messages to the console in case there's a console * available. If there's no console, nothing happens. * See the {@link http://getfirebug.com/logging|Firebug docs} for information on formatting log messages. * * @param {string} str String to print to the console * @param {Array} vars Variables to use for string formatting * @param {string} [func="log"] Severity level of log */ self["log"] = function(str, vars, func) { if (permit_debug != true || window.console == null) { return; } func = func == null ? "log" : func; vars = vars == null ? [] : vars; if (vars.constructor.toString().indexOf("Array") == -1) { vars = [vars]; } vars.unshift(str); console[func].apply(console, vars); } return self; })(); /** * Handles dynamic content decoration as the page loads. Every dynamic * item (page navigation, photosets, etc.) passes through here. * * @static */ Jikuu["Decorator"] = (function() { var self = this; /** * Processes a single element. * * @param {string} selector Unique identifier of the element */ self["add"] = function(selector) { console.warn("decorated %i", selector); } return self; })(); })(jQuery);
const firebase = require('firebase/app'); var config = { apiKey: 'AIzaSyBKj8yRgiOEsOuVcuJWINTl1Vlh5TmGAlQ', authDomain: 'test-project-ced88.firebaseapp.com', databaseURL: 'https://test-project-ced88.firebaseio.com', projectId: 'test-project-ced88', storageBucket: 'test-project-ced88.appspot.com', messagingSenderId: '637493183759' }; firebase.initializeApp(config); export default firebase;
import Page from '../layouts/main' import ExperimentItem from '../components/experiment-item' import PrimaryTitle from '../components/primary-title' import Grid from '../components/grid' import styles from './experiments.styles' import textEffect from '../styles/text-effect' const metaData = { title: 'Nipher - Experiments', description: 'Creative coding experiments', url: 'https://nipher.io/experiments' } const ExperimentsPage = ({ experiments }) => ( <Page meta={metaData}> <PrimaryTitle> <strong className='text-effect'>Feelings</strong> worth sharing </PrimaryTitle> { experiments.length > 1 ? <Grid className='experiments-page' type={"experiments"}>{experiments.map((experiment, i) => <ExperimentItem key={i} {...experiment} />)}</Grid> : experiments.map((experiment, i) => <ExperimentItem key={i} {...experiment} type={'loner'} />) } <style jsx>{styles}</style> <style jsx>{textEffect}</style> </Page> ) ExperimentsPage.getInitialProps = async ({ query, req }) => { if (query.build && typeof window === 'undefined') return query const postEndpoint = `/api/experiments.json` const fetch = await import('isomorphic-fetch') let res = null if (req) { res = await fetch(`${req.protocol}://${req.get('host')}${postEndpoint}`) } else { res = await fetch(`${location.origin}${postEndpoint}`) } return await res.json() } export default ExperimentsPage
class ConstructToolOptions { constructor() { this.visible = false; this.active = false; this.options = [ { constructName: "ELECT", active: false, hover: false, cost: 15, p: { x: 70, y: 76 }, show: function() { } }, { constructName: "TREE", active: false, hover: false, cost: 1, p: { x:70, y:126 }, show: function() { } } ]; } show() { for(let opt of this.options) { strokeWeight(1); stroke(255); if(opt.active===true) { fill(255, 90); } else if(opt.hover===true) { fill(255, 30); } else { noFill(); } rect(opt.p.x, opt.p.y, 50, 50); strokeWeight(0.5); fill(255); textAlign(CENTER); text(opt.constructName, opt.p.x+25, opt.p.y+14); opt.show(); } } getPositionMouse(p) { return mouseX > p.x && mouseX < p.x + 50 && mouseY > p.y && mouseY < p.y + 50; } getHover() { for(let opt of this.options) { if(this.getPositionMouse(opt.p)===true) { opt.hover = true; } else { opt.hover = false; } } } getActive() { for(let opt of this.options) { if(opt.hover===true) { this.cancelTools(); opt.active = true; this.active = true; } } } getActiveName() { for(let opt of this.options) { if(opt.active===true) { return opt.constructName; } } return false; } cancelTools() { for(let opt of this.options) { opt.active = false; } } }
import React, {Component} from 'react'; import './Form.css'; import flower from './flower.png'; class Form extends Component { constructor(props) { super(props); this.state = { email: '', message: '', name: '', } } onNameChange = (event)=> { this.setState({ name: event.target.value }) } onEmailChange = (event)=> { this.setState({ email: event.target.value }) } onMessageChange = (event)=> { this.setState({ message: event.target.value }) } onSubmitMessage = () => { if(document.querySelector('#formGroupExampleInput').value === '') { document.querySelector('.name').style.display = 'block'; } if(document.querySelector('#formGroupExampleInput').value === '') { document.querySelector('.email').style.display = 'block'; } if(document.querySelector('#formGroupExampleInput').value === '') { document.querySelector('.message').style.display = 'block'; } else { document.querySelector('.name').style.display = 'none'; document.querySelector('.email').style.display = 'none'; document.querySelector('.message').style.display = 'none'; fetch('https://quiet-temple-48121.herokuapp.com/message', { method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email: this.state.email, message: this.state.message, name: this.state.name }) }).then(response => response.json()) .catch(err => console.log(err)) } } onClick = () => this.props.history.push("/#message"); render() { return( <div> <div> <div className="text-center title"> <p>Contact</p> <img src={flower} className="" alt="flower"/> </div> <div className="d-flex justify-content-center py-5 mx-5 word"> <p style={{fontSize: '1.3rem'}}>I'm focused and friendly. You can find me sharing my projects on <span ><b><a style={{color: 'red'}} href="https://github.com/Graciey" target="blank">github</a></b></span>, interesting links on <span ><b><a href="https://linkedin.com/in/grace-amoko-370038149" style={{color: '#0077B5'}} target="blank">LinkedIn</a></b></span></p> </div> <div className="d-flex justify-content-center"> <form className="py-5 px-5 rounded shadow mb-5"> <div className="form-group"> <label htmlFor="formGroupExampleInput">Name</label> <input type="text" className="form-control" id="formGroupExampleInput" placeholder="Amoko Grace" onChange={this.onNameChange}/> </div> <div className="name alert alert-danger" role="alert"> <p> Name must be filled!</p> </div> <div className="form-group"> <label htmlFor="formGroupExampleInput2">Email</label> <input type="email" className="form-control" id="formGroupExampleInput2" placeholder="amokograce26@gmail.com" onChange={this.onEmailChange}/> </div> <div className="email alert alert-danger" role="alert"> <p>Email must be filled!</p> </div> <div className="form-group"> <label htmlFor="exampleFormControlTextarea1">Messsage</label> <textarea className="form-control" id="exampleFormControlTextarea1" rows="8" placeholder="hello Grace....." wrap="off" onChange={this.onMessageChange}></textarea> </div> <div className="message alert alert-danger" role="alert"> <p>Messsage must be filled!</p> </div> <button type="button" className="btn btn-primary btn-lg btn-block" onClick={this.onSubmitMessage}><span onClick={this.onClick}>Submit</span></button> </form> </div> </div> </div> ) } } export default Form;
'use strict'; /** * @ngdoc function * @name AngularSharePointApp.controller:SearchCtrl * @description * # SearchCtrl * Controller of the AngularSharePointApp */ /*global $:false */ /*global moment:false */ angular.module('AngularSharePointApp').controller('SearchCtrl', ['$rootScope', '$location', '$scope', 'ReportList', 'cfpLoadingBar', 'CommentList', 'SectionList', '$routeParams', 'Utils', function ($rootScope, $location, $scope, ReportList, cfpLoadingBar, CommentList, SectionList, $routeParams, Utils) { if (typeof $rootScope.isInitialize === 'undefined' || !$rootScope.isInitialize) { return $location.path('/gateway'); } $scope.reportType = $routeParams.type.toUpperCase(); $scope.title = $scope.reportType === 'UO' ? 'Unités d\'opération' : 'Services auxiliaires'; SectionList.find('$filter=ReportType eq \'' + $scope.reportType + '\'').then(function (sections) { $scope.sections = sections; }); var now = moment(); var datepicker = $('.datepicker').datepicker({ language: 'fr', todayHighlight: true, format: 'yyyy-mm-dd', autoclose: true, }); datepicker.on('changeDate', function (e) { cfpLoadingBar.start(); $scope.notFound = false; $scope.comments = []; $scope.reports = []; $scope.searchContext = ''; var rDate = moment(e.date).format(); var tDate = moment(e.date).add(1, 'days').format(); var filter = '$filter=(ReportType eq \''+ $scope.reportType + '\' and Created ge datetime\'' + rDate + '\' and Created le datetime\'' + tDate + '\' and IsActive eq 0)'; var select = '$select=Id,Created,Team,Period,Author/Id,Author/Title&$expand=Author'; ReportList.find(filter + '&' + select).then(function (results) { $scope.reports = results; if (results.length < 1) { $scope.notFound = true; } cfpLoadingBar.complete(); }); }); datepicker.datepicker('setDate', now.format()); $scope.back = function () { var currentDate = moment(datepicker.datepicker('getDate')); datepicker.datepicker('setDate', new Date(currentDate.subtract(1, 'days').format())); }; $scope.foward = function () { var currentDate = moment(datepicker.datepicker('getDate')); datepicker.datepicker('setDate', new Date(currentDate.add(1, 'days').format())); }; $scope.search = function () { if ($scope.searchContext.length < 3) { return window.alert('Vous devez au moins entrer trois charactères dans le champ de recherche'); } var odataExpand = '$expand=Author,Report'; var odataSelect = '$select=Author/Id,Author/Title,Report/Period,Report/Id,Report/Team,Report/Created,Report/ReportType'; var odataFilter = '$filter=substringof(\'' + $scope.searchContext + '\', Title) and Report/ReportType eq \'' + $scope.reportType.toLowerCase() + '\''; var odataOrder = '$orderby=Created desc'; cfpLoadingBar.start(); $scope.notFound = false; $scope.comments = []; $scope.reports = []; CommentList.find(odataFilter + '&' + odataSelect + '&' + odataExpand + '&' + odataOrder).then(function (reports) { $scope.reports = []; var isFound; reports.forEach(function (result) { isFound = false; for (var i=0, len = $scope.reports.length; i < len; i++) { if (result.Report.Id === $scope.reports[i].Id) { isFound = true; // console.log(result); break; } } if (!isFound && result.Report.ReportType === $scope.reportType.toLowerCase()) { $scope.reports.push({ Author: result.Author, Id: result.Report.Id, Team: result.Report.Team, Created: result.Report.Created, Period: result.Report.Period, }); } }); // $scope.reports = reports; if ($scope.reports.length < 1) { $scope.notFound = true; } cfpLoadingBar.complete(); }); }; $scope.openRapportEvenements = function (reportId) { var url = 'http://paradevsrv02/reportserver?/rapportsquart/rapportevenements&rs:Command=Render&rc:Toolbar=true&report='.concat(reportId); Utils.popupWindow(url, 1000, 800); }; $scope.openRapportLignes = function (reportId) { var url = 'http://paradevsrv02/reportserver?/rapportsquart/rapportlignes&rs:Command=Render&rc:Toolbar=true&report='.concat(reportId); Utils.popupWindow(url, 1000, 800); }; $scope.openRendementUsine = function (idx) { var startTime = calculateStartTime($scope.reports[idx]); var endTime = startTime + 12; var query = '?start_time=*-' + startTime + 'h&end_time=*-' + endTime + 'h'; Utils.popupWindow('http://intranet/SitePages/2.0/PI/Trend2.aspx'.concat(query), 1000, 800); }; $scope.openRendementUsine2 = function (idx) { var startTime = calculateStartTime($scope.reports[idx]); var endTime = startTime + 12; var query = '?start_time=*-' + startTime + 'h&end_time=*-' + endTime + 'h'; Utils.popupWindow('http://intranet/SitePages/2.0/PI/Trend3.aspx'.concat(query), 1000, 800); }; $scope.printComments = function (id) { var url = 'http://paradevsrv02/reportserver?/rapportsquart/commentaires&rs:Command=Render&rc:Toolbar=true&report=' + id + '&reporttype=' + $scope.reportType; Utils.popupWindow(url, 1000, 800); }; var calculateStartTime = function (report) { var now = moment(); var nbDays = now.diff(moment(new Date(report.Created)), 'days'); var shiftStart = report.Period === 'jour' ? 6 : 18; if (report.Period === 'nuit') { nbDays++; } return (now.hour() - shiftStart) + (nbDays * 24); }; }]);
function get(el) { if(typeof el === "string") return document.getElementById(el); return el; } var rand = function(max, min, _int) { var max = (max === 0 || max)?max:1, min = min || 0, gen = min + (max - min)*Math.random(); return (_int)?Math.round(gen):gen; } function isTouchDevice() { return (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); } function getFont(family) { family = (family || "").replace(/[^A-Za-z]/g, '').toLowerCase(); var sans = 'Helvetica, Arial, "Microsoft YaHei New", "Microsoft Yahei", "微软雅黑", 宋体, SimSun, STXihei, "华文细黑", sans-serif'; var serif = 'Georgia, "Times New Roman", "FangSong", "仿宋", STFangSong, "华文仿宋", serif'; var fonts = { helvetica : sans, verdana : "Verdana, Geneva," + sans, lucida : "Lucida Sans Unicode, Lucida Grande," + sans, tahoma : "Tahoma, Geneva," + sans, trebuchet : "Trebuchet MS," + sans, impact : "Impact, Charcoal, Arial Black," + sans, comicsans : "Comic Sans MS, Comic Sans, cursive," + sans, georgia : serif, palatino : "Palatino Linotype, Book Antiqua, Palatino," + serif, times : "Times New Roman, Times," + serif, courier : "Courier New, Courier, monospace, Times," + serif } var font = fonts[family] || fonts.helvetica; return font; } /*============================================*/ var HandWriting = (function(){ var container = get('widgetContainer'); var containerWidth, containerHeight; var isRunning = false; var isStop = false; var canvas = get("canvas"); var ctx = canvas.getContext('2d'); var lineTexts = new Array(); var removeTags = ["s","u","i","b"]; /*--- settings from banner flow ---*/ var text, speed, font, fontSize, color; var dashLen = 220, dashOffset = dashLen, x = 0, y = 0, indexText = 0, indexLine = 0; function loopAnimation() { if(isStop) { isRunning = false; return; } isRunning = true; if(!text || text.length == 0) { nextLine(); } else { ctx.clearRect(x, y, 60, 200); ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); dashOffset -= speed; ctx.strokeText(text[indexText], x, y); if (dashOffset > 0) requestAnimationFrame(loopAnimation); else { ctx.fillText(text[indexText], x, y); dashOffset = dashLen; x += ctx.measureText(text[indexText++]).width + ctx.lineWidth; if(indexText < text.length && text[indexText] === ' ') { x += ctx.measureText(text[indexText++]).width + ctx.lineWidth } if (indexText < text.length) requestAnimationFrame(loopAnimation); else { nextLine(); } } } } function nextLine() { if(indexLine < lineTexts.length) { indexText = 0; x = 0; y = fontSize * 5/4 * indexLine; text = lineTexts[indexLine++]; loopAnimation(); } else { isRunning = false; } } function startWidget(currentSesssion) { canvas.width = containerWidth; canvas.height = containerHeight; dashOffset = dashLen; indexText = 0; indexLine = 0; x = 0; y = 0; text = ""; if(!lineTexts || lineTexts.length == 0) return; ctx.font = fontSize + "px " + font; ctx.textBaseline = "top"; ctx.lineWidth = 1; ctx.lineJoin = "round"; ctx.strokeStyle = ctx.fillStyle = color; loopAnimation(); } /*==============================================*/ /*===== Start point of animation =====*/ /*==============================================*/ function reloadGlobalVariables() { containerWidth = parseInt(window.getComputedStyle(container).getPropertyValue('width')); containerHeight = parseInt(window.getComputedStyle(container).getPropertyValue('height')); } function stopCurrentAnimation(callback) { isStop = true; if(isRunning) { var timeout = setTimeout(function(){ clearTimeout(timeout); stopCurrentAnimation(callback); }, 200); } else { isStop = false; if(callback) callback(); } } function startAnimation(currentSesssion) { stopCurrentAnimation(function(){ startWidget(currentSesssion); }); } /*==============================================*/ /*===== Default settings from Banner Flow =====*/ /*==============================================*/ function loadSettings() { if(typeof BannerFlow !== "undefined") { color = BannerFlow.settings.color; speed = BannerFlow.settings.speed; if(speed <= 0) speed = 1; font = BannerFlow.settings.font; fontSize = BannerFlow.settings.fontSize; if(fontSize <= 0) fontSize = 30; } else { color = "#000"; speed = 5; font = "Arial"; fontSize = 45; // text = "Amazing Text Animation"; text = "<div><b><i><u><s>Amazing Text</s></u></i></b></div><div>the second line</div><div>the third line</div>"; var patt; for(var i=0;i<removeTags.length;i++) { var patt = new RegExp("</?" + removeTags[i] + ">", "g"); text = text.replace(patt, ""); } lineTexts = new Array(); patt = new RegExp("<div>([^<.]*)</div>", "g"); var m; lineTexts = new Array(); while(m = patt.exec(text)) { lineTexts.push(m[1]); } if(lineTexts.length == 0) lineTexts.push(text); } font = getFont(font); } /*====================================================*/ var timeoutStart; var sessionId = 0; function init() { if(timeoutStart) { clearTimeout(timeoutStart); timeoutStart = setTimeout(function() { loadSettings(); reloadGlobalVariables(); startAnimation(++sessionId); }, 500); } else { timeoutStart = setTimeout(function(){ loadSettings(); reloadGlobalVariables(); startAnimation(++sessionId); }, 0); } } function getLanguageText() { if(typeof BannerFlow !== "undefined"){ text = BannerFlow.text; var patt; for(var i=0;i<removeTags.length;i++) { var patt = new RegExp("</?" + removeTags[i] + ">", "g"); text = text.replace(patt, ""); } lineTexts = new Array(); patt = new RegExp("<div>([^<.]*)</div>", "g"); var m; lineTexts = new Array(); while(m = patt.exec(text)) { lineTexts.push(m[1]); } if(lineTexts.length == 0) lineTexts.push(text); } } // var isStartAnimation = false; function onStarted() { // if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode && isStartAnimation) { // return; // } // isStartAnimation = true; getLanguageText(); init(); } function onResized(){ if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode) { return; } init(); } function onSettingChanged(){ if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode) { return; } init(); } return { start: onStarted, onResized: onResized, onSettingChanged: onSettingChanged }; })(); if(typeof BannerFlow == "undefined"){ HandWriting.start(); } else { BannerFlow.addEventListener(BannerFlow.START_ANIMATION, function() { HandWriting.start(); }); BannerFlow.addEventListener(BannerFlow.RESIZE, function () { HandWriting.onResized(); }); BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, function () { HandWriting.onSettingChanged(); }); BannerFlow.addEventListener(BannerFlow.TEXT_CHANGED, function () { HandWriting.start(); }); }
import {cache} from 'nt-framework/src/model/cache'; function wait(ms) { return new Promise(r => setTimeout(r, ms)); } let time = 1; async function original(param, ctx) { await wait(200); time ++; if (param) { return { statusCode: '2000000', data: { param, time } }; } else { return { statusCode: '2000000', data: { time } }; } } const cached = cache(original, { key: 'biz-method.all' }); const cachedByParam = cache(original, { key: (param, ctx) => { return 'biz-method.cache.' + param.key; } }); async function clearCache(param, ctx) { ctx.store.remove('biz-method.all'); ctx.store.remove('biz-method.cache.1'); time ++; } export const modelcache = { original, cached, cachedByParam, clearCache };
const CCDCaseField = require('./CCDCaseField'); const fieldTemplate = { 'label': 'Case Reference Number', 'order': 1, 'field': { 'id': '[CASE_REFERENCE]', 'elementPath': null, 'metadata': true, 'field_type': null, 'show_condition': null }, 'display_context_parameter': null }; class SearchInputs extends CCDCaseField{ constructor(){ super(); this.config = { searchInputs: [] }; } addField(fieldConfig){ const fieldTemplateCopy = JSON.parse(JSON.stringify(fieldTemplate)); fieldTemplateCopy.order = this.config.searchInputs.length + 1; fieldTemplateCopy.label = fieldConfig.label; fieldTemplateCopy.field.id = fieldConfig.id; fieldTemplateCopy.field.show_condition = fieldConfig.show_condition ? fieldConfig : null; fieldTemplateCopy.display_context_parameter = fieldConfig.display_context_parameter ? fieldConfig.displaycontextParameter : null; fieldTemplateCopy.field.field_type = this.getCCDFieldTemplateCopy(fieldConfig).field_type; this.config.searchInputs.push(fieldTemplateCopy); return this; } getConfig(){ return this.config; } } module.exports = SearchInputs;
(function () { "use strict"; require('./values'); angular.module('agenda', [ 'ui.router', 'ngStorage', 'agenda.values', 'agenda.routes', 'agenda.factories', 'agenda.services', 'agenda.controllers', 'agenda.interceptories' ]); angular.module('agenda') .config(UrlRouterProvider); // angular.module('agenda').run([ // '$http', // 'AuthFactory', // '$rootScope', // '$state', // function ($http, AuthFactory, $rootScope, $state) { // Header($http, AuthFactory); // $rootScope.$on('$stateChangeStart', function (event, next, current) { // if (next.authorize) { // if (!AuthFactory.getToken()) { // event.preventDefault(); // $state.go('login'); // } // } // }); // } // ]); function UrlRouterProvider ($urlRouterProvider) { $urlRouterProvider.otherwise('/'); } // function Header ($http, AuthFactory) { // if (AuthFactory.getToken()) { // $http.defaults.headers.common.Authorization = 'Bearer ' + AuthFactory.getToken(); // } // } })();
define( ['service/logger'], function (logger) { logger.debug('Event module has initialized'); var events = {}; return { on: function (eventName, callback) { var event = events[eventName] || []; event.push(callback); events[eventName] = event; }, fireEvent: function (eventName) { var eventArray = events[eventName] || []; var i, j = eventArray.length; for (i = 0; i < j; i++) { if (typeof eventArray[i] === 'function') eventArray[i](); } } } } );
import React, { Component, Fragment } from 'react'; import { formatMessage } from 'umi/locale'; import { connect } from 'dva'; import Link from 'umi/link'; import { Icon } from 'antd'; import GlobalFooter from '@/components/GlobalFooter'; import DocumentTitle from 'react-document-title'; import SelectLang from '@/components/SelectLang'; import styles from './UserLayout.less'; import logo from '../assets/logo.svg'; import getPageTitle from '@/utils/getPageTitle'; import { onGetImageUrl } from '@/utils/FunctionSet'; const links = [ { key: 'help', title: formatMessage({ id: 'layout.user.link.help' }), href: '', }, { key: 'privacy', title: formatMessage({ id: 'layout.user.link.privacy' }), href: '', }, { key: 'terms', title: formatMessage({ id: 'layout.user.link.terms' }), href: '', }, ]; const copyright = ( <Fragment> Copyright <Icon type="copyright" /> 2019 精诚(中国)企业管理有限公司 </Fragment> ); class UserLayout extends Component { state = { loginBackground: '', }; componentDidMount() { const { dispatch, route: { routes, authority }, } = this.props; let backgroundImage = localStorage.getItem('loginBackground') ? onGetImageUrl(JSON.parse(localStorage.getItem('loginBackground'))[0]) : ''; this.setState({ backgroundImage, }); // dispatch({ // type: 'menu/getMenuData', // payload: { routes, authority }, // }); } render() { const { children, location: { pathname }, breadcrumbNameMap, } = this.props; let { backgroundImage } = this.state; let logoImg = JSON.parse(localStorage.getItem('loginLogoImg')); if (logoImg) { let newUrl = onGetImageUrl(logoImg[0]); logoImg[0].url = newUrl; } const loginLogo = logoImg && logoImg !== 'undefined' ? logoImg : []; return ( <DocumentTitle title={getPageTitle(pathname, breadcrumbNameMap)}> <div style={{ backgroundImage: backgroundImage ? `url(${backgroundImage})` : 'url(https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg)', }} className={styles.container} > {/* <div className={styles.lang}> <SelectLang /> </div> */} <div className={styles.content}> <div className={styles.top}> <div className={styles.header}> {/* <Link to="/"> */} {/* <img alt="logo" className={styles.logo} src="./logo.png" /> <span className={styles.title}>精诚供应链系统</span> */} <img alt="logo" className={styles.logo} src={loginLogo.length > 0 ? loginLogo[0].url : ''} /> <span className={styles.title}> {localStorage.getItem('loginMainTitle') && localStorage.getItem('loginMainTitle') !== 'undefined' ? localStorage.getItem('loginMainTitle') : ''} </span> {/* </Link> */} </div> {/* <div className={styles.desc}>上海市最具影响力的 Web 设计规范</div> */} <div style={{ height: '4rem' }} /> </div> {children} </div> <GlobalFooter // links={links} copyright={copyright} /> </div> </DocumentTitle> ); } } export default connect(({ menu: menuModel }) => ({ menuData: menuModel.menuData, breadcrumbNameMap: menuModel.breadcrumbNameMap, }))(UserLayout);
module.exports = function(app) { var config = require('./config'); app.Router = Ember.Router.extend({ rootURL: config.rootURL, location: config.location, }); app.Router.map(function() { this.route('site', { path: '/' }); this.route('helo', { path: '/h-e-l-o' }, function() { this.route('world', { path: '/world' }); }); this.route('notFound', { path: '/*path' }); }); };
class Boid { constructor(x, y, seperation=0.8, alignment=0.006, cohesion=0.007, obstacle_avoid=1) { this.loc = createVector(x,y); this.vel = p5.Vector.random2D().mult(3); this.acl = createVector(); this.desired_vel = this.vel.copy(); this.max_force = 0.6; this.max_vel = 3; this.goal = createVector(random(width), random(height)); this.seperation = seperation; this.alignment = alignment; this.cohesion = cohesion; this.obstacle_avoid = obstacle_avoid; this.veiw_size = 100; this.veiw_angle = 2*PI/3; this.size = 12; this.turn_dir = random([0,1]); this.collider = new Circle(this.loc.x, this.loc.y, this.size/2); this.vision = new Circle(this.loc.x, this.loc.y, this.veiw_size); } update() { this.flock(); this.obstacleAvoidance(); this.steer(); this.collisionHandling(); this.vel.add(this.acl); this.vel.limit(this.max_vel); this.loc.add(this.vel); this.acl.mult(0); this.collider = new Circle(this.loc.x, this.loc.y, this.size/2); this.vision = new Circle(this.loc.x, this.loc.y, this.veiw_size); if (random() < 0.01) this.turn_dir *= -1; } flock() { this.desired_vel = this.vel.copy(); let near = this.nearBoids(); if (near.length > 0) { // Do Seperation for (let boid of near) { let to_boid = boid.loc.copy().sub(this.loc); to_boid.setMag(min(1/to_boid.mag(), this.max_vel)).mult(-this.seperation); this.desired_vel.add(to_boid); } this.desired_vel.limit(this.max_vel); // Do Alignment and try move heading slightly to match average velocity angle of neighbors let avg_ang = 0; for (let boid of near) { avg_ang += boid.vel.heading(); } avg_ang /= near.length; this.desired_vel.rotate((avg_ang - this.vel.heading()) * -this.alignment); this.desired_vel.limit(this.max_vel); // Do Cohesion let mid = createVector(); for (let boid of near) { mid.add(boid.loc); } mid.div(near.length); this.desired_vel.add(mid.copy().sub(this.loc).mult(this.cohesion)); this.desired_vel.limit(this.max_vel); } } steer() { let change = this.desired_vel.copy().sub(this.vel); change.limit(this.max_force); this.acl.add(change); } nearBoids() { let near = []; for (let boid of flock) { if (this.inVision(boid.loc)) near.push(boid); } return near; } inVision(point) { if (this.loc.dist(point) < this.veiw_size) { let angle = abs(this.vel.heading() - point.copy().sub(this.loc).heading()); if (angle < this.veiw_angle) return true; } return false; } nearObstacles() { let near = []; for (let obstacle of obstacles) { if (this.vision.colliding(obstacle)) near.push(obstacle); } return near; } obstacleAvoidance() { let near = this.nearObstacles(); if (near.length == 0) return false; let dodge = false; let probe_num = 11; // plz make odd let unit = this.veiw_angle / (probe_num/2); let probe_v = this.vel.copy().setMag(this.veiw_size); let probe; for (let i = 0; i < probe_num; i++) { let probe_p = this.loc.copy().add(probe_v); probe = new Line(this.loc.x, this.loc.y, probe_p.x, probe_p.y); // stroke(200,150,150); // strokeWeight(0.5); // line(probe.p1.x, probe.p1.y, probe.p2.x, probe.p2.y); let is_clear = true; for (let obstacle of near) { if (probe.colliding(obstacle)) is_clear = false; } if (is_clear && i == 0) { dodge = false; break; } else if (is_clear) { dodge = true; break; } let sign = (i%2==this.turn_dir)*2 - 1; // 1 if i is divisable by 2, -1 else let angle = sign * i * unit; probe_v.setHeading(this.vel.heading() + angle); } if (dodge) { let angle_dif = probe_v.heading() - this.desired_vel.heading(); this.desired_vel.rotate(angle_dif * this.obstacle_avoid); this.desired_vel.limit(this.max_vel); } return true; } collisionHandling() { let near = this.nearObstacles(); if (near.length == 0) return false; for (let obstacle of near) { if (this.collider.colliding(obstacle)) { let normal = obstacle.normal(this.loc); this.vel.reflect(normal); this.loc.add(obstacle.handleCollision(this.collider)); // this.loc.add(normal.copy().setMag(this.size)); // this.vel.mult(0.5); } } return true; } draw(special=false) { fill(200, 200, 220, 200); stroke(250); strokeWeight(1); push(); translate(this.loc.x, this.loc.y); rotate(this.vel.heading()); if (special) { fill(250, 50); stroke(0); strokeWeight(0.5); arc(0, 0, 2*this.veiw_size, 2*this.veiw_size, -this.veiw_angle, this.veiw_angle); fill(200, 50, 50); stroke(250, 60, 60); strokeWeight(1); } // if (this.nearObstacles().length == 0) fill(0, 0, 0); triangle(this.size/2, 0, -this.size/2, this.size/3, -this.size/2, -this.size/3); pop(); // fill(200); // noStroke(); // circle(this.loc.x, this.loc.y, this.size*2); } }
const template = document.createElement('template') template.innerHTML = ` <div class="container"> <h1>Timeline</h1> <form id="post-form" class="post-form"> <textarea placeholder="Write something..." maxlength="480" required></textarea> <button class="post-form-button" hidden>Publish</button> </form> <div id="timeline-outlet" class="posts-wrapper"></div> </div> ` export default async function renderHomePage() { const page = /** @type {DocumentFragment} */ (template.content.cloneNode(true)) const postForm = /** @type {HTMLFormElement} */ (page.getElementById('post-form')) const postFormTextArea = postForm.querySelector('textarea') const postFormButton = postForm.querySelector('button') /** * @param {Event} ev */ const onPostFormSubmit = async ev => { ev.preventDefault() postFormTextArea.disabled = true postFormButton.disabled = true } postForm.addEventListener('submit', onPostFormSubmit) return page }
import React from 'react' import { mount, shallow } from 'enzyme' import Breadcrumbs from './Breadcrumbs' import { removeSpaces } from '../../helpers' describe('Breadcrumbs Component', () => { it('should render', () => { const component = shallow(<Breadcrumbs />) expect(component.find('.c-breadcrumbs').exists()).toBe(true) }) it('should label the breadcrumbs with the name supplied', () => { const mockProps = { list: [1, 2, 3], } const component = mount(<Breadcrumbs {...mockProps} />) expect(component.find('.c-breadcrumbs-link').first().text()).toContain(mockProps.list[0]) expect(component.find('.c-breadcrumbs-link').last().text()).toContain(mockProps.list[mockProps.list.length - 1]) }) it('should link the breadcrumbs to the supplied items without spaces', () => { const mockProps = { list: ['test 1', 'test2', 'test3'], } const component = mount(<Breadcrumbs {...mockProps} />) expect(component.find('.c-breadcrumbs-link').first().prop('href')).toEqual(removeSpaces(mockProps.list[0])) expect(component.find('.c-breadcrumbs-link').last().prop('href')).toEqual(removeSpaces(mockProps.list[mockProps.list.length - 1])) }) it('should not render any breadcrumbs if the list does not have more than 1 item', () => { let mockProps = { list: [], } let component = shallow(<Breadcrumbs {...mockProps} />) expect(component.find('.c-breadcrumbs-item')).toHaveLength(0) mockProps = { list: [1], } component = shallow(<Breadcrumbs {...mockProps} />) expect(component.find('.c-breadcrumbs-item')).toHaveLength(0) }) it('should render the breadcrumbs when there is more than 1 list item', () => { const mockProps = { list: [1, 2, 3], } const component = shallow(<Breadcrumbs {...mockProps} />) expect(component.find('.c-breadcrumbs-item')).toHaveLength(3) }) })
import React, { Component } from "react" import { connect } from 'react-redux'; import Form from '../../../components/DynamicForm/Index' import Validator from '../../../validators'; import axios from "../../../axios-orders" import config from "../../../config"; class AddCast extends Component { constructor(props) { super(props) this.state = { season_id:props.season_id, editItem:props.editItem, movie:props.movie } this.empty = true } static getDerivedStateFromProps(nextProps, prevState) { if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){ return null; } if(prevState.localUpdate){ return {...prevState,localUpdate:false} }else { return { season_id:nextProps.season_id, editItem:nextProps.editItem, movie:nextProps.movie } } } onSubmit = model => { if (this.state.submitting) { return } let formData = new FormData(); for (var key in model) { if(model[key] != null && typeof model[key] != "undefined") formData.append(key, model[key]); } //image formData.append("movie_id",this.state.movie.movie_id); formData.append("season_id",this.state.season_id); if(this.props.fromCastnCrew){ formData.append("fromCastnCrew",1); } const config = { headers: { 'Content-Type': 'multipart/form-data', } }; formData.append("resource_type",this.props.resource_type); formData.append("resource_id",this.props.resource_id); let url = '/movies/episode/create-cast'; if (this.state.editItem) { formData.append("cast_crew_member_id",this.state.editItem.cast_crew_member_id) formData.append("cast_id", this.state.editItem.cast_crew_id) } this.setState({localUpdate:true, submitting: true, error: null }); axios.post(url, formData, config) .then(response => { if (response.data.error) { this.setState({localUpdate:true, error: response.data.error, submitting: false }); } else { this.props.closeCastCreate({...response.data.item},response.data.message) } }).catch(err => { this.setState({localUpdate:true, submitting: false, error: err }); }); } render(){ let validator = [ ] let suggestionValue = [] if(this.state.editItem){ suggestionValue = [{title:this.state.editItem.name,image:this.state.editItem.image,id:this.state.editItem.cast_crew_id}] } let formFields = [] if(!this.state.editItem){ validator.push( { key: "cast_crew_member_id", validations: [ { "validator": Validator.int, "message": this.props.isCrew ? "Crew Member is required field" : "Cast Member is required field" } ] } ) formFields.push( { key: "cast_crew_member_id",type:"autosuggest",id:this.state.editItem ? this.state.editItem.cast_crew_id : "",imageSuffix:this.props.pageInfoData.imageSuffix,url:config.app_server+"/api/movies/cast/auto-suggest"+(this.props.fromCastnCrew ? "/movie" : ""),placeholder:"Search for a member...",suggestionValue:suggestionValue, label: "Cast Member", value: this.state.editItem ? this.state.editItem.name : null ,isRequired:true}, ) }else{ formFields.push( { key: "cast_crew_member_id", type:"text", label: "Cast Member", value: this.state.editItem ? this.state.editItem.name : null ,isRequired:true, props: { disabled: "disabled" }} ) } if(!this.props.isCrew){ validator.push({ key: "character", validations: [ { "validator": Validator.required, "message": "Character is required field" } ] }); formFields.push( { key: "character", type:"text", label: "Character", value: this.state.editItem ? this.state.editItem.character : null ,isRequired:true} ) }else{ validator.push({ key: "job", validations: [ { "validator": Validator.required, "message": "Job is required field" } ] }, { key: "department", validations: [ { "validator": Validator.required, "message": "Department is required field" } ] }); formFields.push( { key: "job", type:"autosuggest",departmentJob:this.props.pageInfoData.departments, label: "Job", value: this.state.editItem ? this.state.editItem.job : null ,isRequired:true}, { key: "department", type:"text", label: "Department", value: this.state.editItem ? this.state.editItem.department : null ,isRequired:true} ) } let defaultValues = {} if(this.empty){ formFields.forEach((elem) => { if (elem.value) defaultValues[elem.key] = elem.value }) } var empty = false if(this.empty){ empty = true this.empty = false } return ( <Form className="form" defaultValues={defaultValues} {...this.props} empty={empty} generalError={this.state.error} validators={validator} submitText={!this.state.submitting ? "Submit" : "Submitting..."} model={formFields} onSubmit={model => { this.onSubmit(model); }} /> ) } } const mapStateToProps = state => { return { pageInfoData: state.general.pageInfoData }; }; export default connect(mapStateToProps, null)(AddCast);
const {Pool} = require('pg'); const db = new Pool(); db.on( 'error', dberror => { console.log( '- ' + shardId + ': Error while connecting to the database: ' + dberror ); } ); db.query( 'SELECT guild, prefix FROM discord WHERE patreon IS NOT NULL' ).then( ({rows}) => { console.log( '- ' + shardId + ': Patreons successfully loaded.' ); rows.forEach( row => { patreons[row.guild] = row.prefix; } ); }, dberror => { console.log( '- ' + shardId + ': Error while getting the patreons: ' + dberror ); } ); db.query( 'SELECT guild, lang FROM discord WHERE voice IS NOT NULL' ).then( ({rows}) => { console.log( '- ' + shardId + ': Voice channels successfully loaded.' ); rows.forEach( row => { voice[row.guild] = row.lang; } ); }, dberror => { console.log( '- ' + shardId + ': Error while getting the voice channels: ' + dberror ); } ); module.exports = db;
const router = require("express").Router(); const path = require("path"); router.get("/", (req, res) => { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.sendFile(path.join(__dirname, "../index.html")); }); router.get("/styles.css", (req, res) => { res.setHeader("Content-Type", "text/css,*/*;q=0.1"); res.sendFile(path.join(__dirname, "../browser/styles.css")); }); router.get("/minesweeper.js", (req, res) => { res.setHeader("Content-Type", "text/javascript"); res.sendFile(path.join(__dirname, "../browser/minesweeper.js")); }); module.exports = router;
import Login from '../views/Login' import Home from '../views/Home' import Room from '../views/Room' import MyBaby from '../views/MyBaby' import Me from '../views/Me' import RoomList from '../views/RoomList' import Pay from '../views/Pay' import Service from '../views/Service' import Bill from '../views/Bill' import Ocode from '../views/Ocode' import Mycode from '../views/Mycode' import GameRecord from '../views/GameRecord' import Mailed from '../views/Mailed' import Cart from '../views/Cart' import Address from '../views/Address' import PayRecord from '../views/PayRecord' let routers = [ { path: '/', component: Login }, { path: '/home', name: 'Home', component: Home }, { path: '/room/list/:goodsId', name: 'RoomList', component: RoomList }, { path: '/room/:roomId/:startGame', name: 'Room', component: Room }, { path: '/mybaby', name: 'MyBaby', component: MyBaby }, { path: '/me', name: 'Me', component: Me }, { path: '/pay', name: 'Pay', component: Pay }, { path: '/service', name: 'Service', component: Service }, { path: '/bill', name: 'Bill', component: Bill }, { path: '/ocode/:code', name: 'Ocode', component: Ocode }, { path: '/mycode', name: 'Mycode', component: Mycode }, { path: '/gamerecord', name: 'GameRecord', component: GameRecord }, { path: '/mailed/:grabId', name: 'Mailed', component: Mailed }, { path: '/cart', name: 'Cart', component: Cart }, { path: '/address', name: 'Address', component: Address }, { path: '/payrecord', name: 'PayRecord', component: PayRecord } ] export default routers
var NAVTREEINDEX0 = { "ApplicationFacadeInterfaceWS_8java.html":[2,0,0,1,0], "ApplicationFacadeInterfaceWS_8java_source.html":[2,0,0,1,0], "BadDates_8java.html":[2,0,0,4,0], "BadDates_8java_source.html":[2,0,0,4,0], "DB4oManagerCreationException_8java.html":[2,0,0,4,1], "DB4oManagerCreationException_8java_source.html":[2,0,0,4,1], "FacadeImplementationWS_8java.html":[2,0,0,1,1], "FacadeImplementationWS_8java_source.html":[2,0,0,1,1], "Facade__Bean_8java.html":[2,0,0,0,0], "Facade__Bean_8java_source.html":[2,0,0,0,0], "HibernateDataAccess_8java.html":[2,0,0,2,0], "HibernateDataAccess_8java_source.html":[2,0,0,2,0], "HibernateUtil_8java.html":[2,0,0,5,0,0], "HibernateUtil_8java_source.html":[2,0,0,5,0,0], "Initialize_8java.html":[2,0,0,0,1], "Initialize_8java_source.html":[2,0,0,0,1], "IntegerAdapter_8java.html":[2,0,0,3,0], "IntegerAdapter_8java_source.html":[2,0,0,3,0], "OfferCanNotBeBooked_8java.html":[2,0,0,4,2], "OfferCanNotBeBooked_8java_source.html":[2,0,0,4,2], "Offer_8java.html":[2,0,0,3,1], "Offer_8java_source.html":[2,0,0,3,1], "OverlappingOfferExists_8java.html":[2,0,0,4,3], "OverlappingOfferExists_8java_source.html":[2,0,0,4,3], "Query__Bean_8java.html":[2,0,0,0,2], "Query__Bean_8java_source.html":[2,0,0,0,2], "RuralHouse_8java.html":[2,0,0,3,2], "RuralHouse_8java_source.html":[2,0,0,3,2], "Set__Bean_8java.html":[2,0,0,0,3], "Set__Bean_8java_source.html":[2,0,0,0,3], "annotated.html":[1,0], "classbean_1_1Facade__Bean.html":[1,0,0,0], "classbean_1_1Facade__Bean.html#a08e22d4f959a99c1dc688428ea48b184":[1,0,0,0,0], "classbean_1_1Facade__Bean.html#a1509a8136e8cd70766422d440ac54d7f":[1,0,0,0,1], "classbean_1_1Initialize.html":[1,0,0,1], "classbean_1_1Initialize.html#ac27694871d059edf0df3cdccc11f89ad":[1,0,0,1,0], "classbean_1_1Query__Bean.html":[1,0,0,2], "classbean_1_1Query__Bean.html#a008055cfab609b48b5c3e74ddc26303c":[1,0,0,2,6], "classbean_1_1Query__Bean.html#a05981f0ecf96a1afdd0227720934411c":[1,0,0,2,12], "classbean_1_1Query__Bean.html#a0d747c549bd5fb3981c5176b3532fdeb":[1,0,0,2,19], "classbean_1_1Query__Bean.html#a1cae7fad5445fcc2af20ffd9e0803ff7":[1,0,0,2,16], "classbean_1_1Query__Bean.html#a1d4d548f29f696871171ff5d7eca964a":[1,0,0,2,14], "classbean_1_1Query__Bean.html#a24e8cd9b440666b540a2272d5df12e24":[1,0,0,2,4], "classbean_1_1Query__Bean.html#a28c9ac3b9469671cb003f85a12b52dc7":[1,0,0,2,18], "classbean_1_1Query__Bean.html#a34d5b9a6d575a9270079c5376822bd00":[1,0,0,2,5], "classbean_1_1Query__Bean.html#a41a8d631f015a0b8df5a9b40f5cc3231":[1,0,0,2,24], "classbean_1_1Query__Bean.html#a47c80baa63310192373c60c0f09116bb":[1,0,0,2,0], "classbean_1_1Query__Bean.html#a69e1bb757c523c799cd3db72d7299fe1":[1,0,0,2,17], "classbean_1_1Query__Bean.html#a7334f280df18d4e790c5a086b8334a0f":[1,0,0,2,30], "classbean_1_1Query__Bean.html#a76fd38e1297497efc591fc46a6ae64f4":[1,0,0,2,28], "classbean_1_1Query__Bean.html#a82506db8f6c6211fb6ad55310c63d0b6":[1,0,0,2,7], "classbean_1_1Query__Bean.html#a84d256eca7a4f868d77e549b82d87ddf":[1,0,0,2,23], "classbean_1_1Query__Bean.html#a8724eb0d86b07b16a6af560390d77523":[1,0,0,2,13], "classbean_1_1Query__Bean.html#a8809176658727a8daec87ba0b2dda2de":[1,0,0,2,25], "classbean_1_1Query__Bean.html#a8c158c927390375bed7935b2db5e4f53":[1,0,0,2,27], "classbean_1_1Query__Bean.html#a906820e31a37424ec307634523ccfbdd":[1,0,0,2,11], "classbean_1_1Query__Bean.html#a959034af24769ce6348b49a1c0c57d6f":[1,0,0,2,10], "classbean_1_1Query__Bean.html#aac41676c3262ddf384539b5e11e473b7":[1,0,0,2,21], "classbean_1_1Query__Bean.html#ab1e76631718151a10efad6a17c43cb5d":[1,0,0,2,15], "classbean_1_1Query__Bean.html#ab2823ce229ec8c9e951e0d5e6861ccaf":[1,0,0,2,3], "classbean_1_1Query__Bean.html#ab3019b29aceba9be1d718c06f02efbf0":[1,0,0,2,22], "classbean_1_1Query__Bean.html#ab57fcbc9df417bf04f3ba9f4b205bd26":[1,0,0,2,1], "classbean_1_1Query__Bean.html#ab979d29b59d31df3848b6a2420cbbc70":[1,0,0,2,9], "classbean_1_1Query__Bean.html#ab994c486fce1a6f2f3fa9a7b333187ba":[1,0,0,2,29], "classbean_1_1Query__Bean.html#aefdbf74a5f2ddbf5b047f5ad56245de5":[1,0,0,2,8], "classbean_1_1Query__Bean.html#af1040de2275895452b9e60535b4983b6":[1,0,0,2,26], "classbean_1_1Query__Bean.html#af8dc33052ec073a2656c2209f9befb18":[1,0,0,2,2], "classbean_1_1Query__Bean.html#afec0f4b7677afcdfcae433fdb7e5583f":[1,0,0,2,20], "classbean_1_1Set__Bean.html":[1,0,0,3], "classbean_1_1Set__Bean.html#a097bfd9a811dface309cd5fb0d6d839e":[1,0,0,3,12], "classbean_1_1Set__Bean.html#a1476ea0d0fa314e92ff99f9a9499e5c0":[1,0,0,3,26], "classbean_1_1Set__Bean.html#a317933af35c5e82b4ee1dd1883376773":[1,0,0,3,6], "classbean_1_1Set__Bean.html#a336e607ada67dc0cbea19914fd8a93b0":[1,0,0,3,9], "classbean_1_1Set__Bean.html#a3e4017a00618c5e33c7479a5a15eb89d":[1,0,0,3,13], "classbean_1_1Set__Bean.html#a459251daa7964f459c7dd5ad67173345":[1,0,0,3,1], "classbean_1_1Set__Bean.html#a465bd2dc79465be5933720eadd23d137":[1,0,0,3,2], "classbean_1_1Set__Bean.html#a5b282bcf4e0aeb2283cf610f9a735a5a":[1,0,0,3,14], "classbean_1_1Set__Bean.html#a5f403451f5e63a57aa62d0ea72fb020b":[1,0,0,3,21], "classbean_1_1Set__Bean.html#a623256f1320812316c70b3b9bda4196c":[1,0,0,3,5], "classbean_1_1Set__Bean.html#a627ff4ed667dd2be57ea46f8c196cda7":[1,0,0,3,3], "classbean_1_1Set__Bean.html#a667afccf27f2b9861fecfb2f23bf9041":[1,0,0,3,25], "classbean_1_1Set__Bean.html#a6fbcd7695627e1f60eddd4e35bcb288f":[1,0,0,3,18], "classbean_1_1Set__Bean.html#a80c8bf1baec6aa3305f06e8f34c4905d":[1,0,0,3,22], "classbean_1_1Set__Bean.html#a84574fb21d6564cf7af43ebaa4cf8342":[1,0,0,3,10], "classbean_1_1Set__Bean.html#a846f27f98c7eae930bcbbb37c56073d2":[1,0,0,3,16], "classbean_1_1Set__Bean.html#aa0023cab21fcce9d36c517f53940f3ff":[1,0,0,3,19], "classbean_1_1Set__Bean.html#aa128159e71978a7593c243bba1b4e400":[1,0,0,3,15], "classbean_1_1Set__Bean.html#aaf052b9a61a529b4934d826791bb8fc8":[1,0,0,3,17], "classbean_1_1Set__Bean.html#ab7eaecf178a4ca10c791779a0bf72954":[1,0,0,3,24], "classbean_1_1Set__Bean.html#ab9e88a7d0e094271ff7f9fb337f66c11":[1,0,0,3,4], "classbean_1_1Set__Bean.html#ac31222c0c170d01be178adc206724cd1":[1,0,0,3,11], "classbean_1_1Set__Bean.html#ad9e455b4a923d74204c2d8d3ea4d99cb":[1,0,0,3,8], "classbean_1_1Set__Bean.html#adb0d58588e1704cbc2eeb74ead53175c":[1,0,0,3,7], "classbean_1_1Set__Bean.html#ade7defe328857d39eea0c4b4ca7b7645":[1,0,0,3,0], "classbean_1_1Set__Bean.html#af99beccb4531fab9e9e96b5277ea4b6c":[1,0,0,3,23], "classbean_1_1Set__Bean.html#afdf90e7df10b28094116c50ee84df11d":[1,0,0,3,20], "classbusinessLogic_1_1FacadeImplementationWS.html":[1,0,1,1], "classbusinessLogic_1_1FacadeImplementationWS.html#a0c3a269d277719643ca61e030580812a":[1,0,1,1,1], "classbusinessLogic_1_1FacadeImplementationWS.html#a22415eec1f4d0a160f02cfdc1ac80825":[1,0,1,1,0], "classbusinessLogic_1_1FacadeImplementationWS.html#a6e8399739161cbb6a2830ebb9279de90":[1,0,1,1,2], "classbusinessLogic_1_1FacadeImplementationWS.html#a7489fb15fdb8206b16daf6ed24fdfea0":[1,0,1,1,5], "classbusinessLogic_1_1FacadeImplementationWS.html#a94a4600e9c80794676f06c888e9e682d":[1,0,1,1,6], "classbusinessLogic_1_1FacadeImplementationWS.html#aa6f21ddb40ca6cd752a13e31ff016e7e":[1,0,1,1,4], "classbusinessLogic_1_1FacadeImplementationWS.html#ac7b3bdfd0815ea7c787da312de594cce":[1,0,1,1,3], "classdataAccess_1_1HibernateDataAccess.html":[1,0,2,0], "classdataAccess_1_1HibernateDataAccess.html#a16a54ece6133abc98eae6b61daa9d4db":[1,0,2,0,0], "classdataAccess_1_1HibernateDataAccess.html#a20de01b8c85e851ca310123cb7e6037d":[1,0,2,0,1], "classdataAccess_1_1HibernateDataAccess.html#a2d226cc2032db6a4522fc6e172315480":[1,0,2,0,2], "classdataAccess_1_1HibernateDataAccess.html#a3e70561f64924c0a6c5a1edfbc5528da":[1,0,2,0,4], "classdataAccess_1_1HibernateDataAccess.html#a60f1f7e00fb7ccec7fbb799e8a302295":[1,0,2,0,5], "classdataAccess_1_1HibernateDataAccess.html#aae72706f749c3cb823d6002f979835c7":[1,0,2,0,3], "classdomain_1_1IntegerAdapter.html":[1,0,3,0], "classdomain_1_1IntegerAdapter.html#a407b4872b78e54ed80c9ae597cae2451":[1,0,3,0,0], "classdomain_1_1IntegerAdapter.html#ad2bfc5af140573682dd03906b9264b51":[1,0,3,0,1], "classdomain_1_1Offer.html":[1,0,3,1], "classdomain_1_1Offer.html#a122573abd92911b25cde7d7e84f488f5":[1,0,3,1,19], "classdomain_1_1Offer.html#a194cfe9363c5bd9e745f56978b03e7fd":[1,0,3,1,18], "classdomain_1_1Offer.html#a2050ed4cf76a2a2863d08e89bdf4a7df":[1,0,3,1,12], "classdomain_1_1Offer.html#a35ebc81c0ebfe427d7bb68abaf811852":[1,0,3,1,8], "classdomain_1_1Offer.html#a3804f5f9ad3a3bf380e55389ccfa9dba":[1,0,3,1,7], "classdomain_1_1Offer.html#a4d415274c0e120dd3e66e4ad46d7e2b2":[1,0,3,1,16], "classdomain_1_1Offer.html#a4ebf9c6f415709b527e006fdffa3a0c3":[1,0,3,1,6], "classdomain_1_1Offer.html#a52363278771059c51820160889c2bed1":[1,0,3,1,10], "classdomain_1_1Offer.html#a8838b2d4c6616394f1829d4dc5572952":[1,0,3,1,13], "classdomain_1_1Offer.html#a8bd526902732e030571b6889c5507f4c":[1,0,3,1,11], "classdomain_1_1Offer.html#a8bf48365a8fc185dbdcaac80a9d84444":[1,0,3,1,4], "classdomain_1_1Offer.html#ab9e27c474ec6819a27eac1847d876c3a":[1,0,3,1,5], "classdomain_1_1Offer.html#ac30c7d7ca38555fecc523259c15bd6b0":[1,0,3,1,15], "classdomain_1_1Offer.html#aca5c8e3d34e700c8e51d1c9a0685e68f":[1,0,3,1,9], "classdomain_1_1Offer.html#ae13ac55ba469cb34e004d6aff68430fb":[1,0,3,1,3], "classdomain_1_1Offer.html#ae82665e8df101e5a20b41dc06f74a789":[1,0,3,1,0], "classdomain_1_1Offer.html#ae977cf0dae1332eb9d0b97252cc15078":[1,0,3,1,1], "classdomain_1_1Offer.html#af77beec2989adcfb9b7b7ef399f9b363":[1,0,3,1,17], "classdomain_1_1Offer.html#afea0a91aa8cd1382181dd2071b7c6a04":[1,0,3,1,14], "classdomain_1_1Offer.html#afebfadadf66b46ce87a9777d01fc2a41":[1,0,3,1,2], "classdomain_1_1RuralHouse.html":[1,0,3,2], "classdomain_1_1RuralHouse.html#a04f87e3266ab2b0d9b42bb8f947d6172":[1,0,3,2,11], "classdomain_1_1RuralHouse.html#a1052cfcd781ddfbaf6d5516737e06bf0":[1,0,3,2,1], "classdomain_1_1RuralHouse.html#a1168b2c788d2f3bca3c54eee3b8734cb":[1,0,3,2,18], "classdomain_1_1RuralHouse.html#a21b3359aa62984046a4da490fe8895e1":[1,0,3,2,5], "classdomain_1_1RuralHouse.html#a23272d170821f464d6b07595303c283e":[1,0,3,2,9], "classdomain_1_1RuralHouse.html#a240eebda76fe984b763e8eaa691f3c94":[1,0,3,2,14], "classdomain_1_1RuralHouse.html#a2937650ac9e726b75be724d264fa1bee":[1,0,3,2,15], "classdomain_1_1RuralHouse.html#a4ac1bd1de58f97487abbcb8dc27a8077":[1,0,3,2,16], "classdomain_1_1RuralHouse.html#a58e17e08a7b28a75bc1b8e3d6ac01764":[1,0,3,2,2], "classdomain_1_1RuralHouse.html#a5e1f42ad6b3992bfc5fdece628455552":[1,0,3,2,0], "classdomain_1_1RuralHouse.html#a67a45aa0b441b32d455d58c4a42446f1":[1,0,3,2,4], "classdomain_1_1RuralHouse.html#a849faba68dc8c0a71ed936bc509f5568":[1,0,3,2,6], "classdomain_1_1RuralHouse.html#a92f3f1fa5d605f34e95f4e4175ef2629":[1,0,3,2,3], "classdomain_1_1RuralHouse.html#ab80c8a3e186714dfb11557b626ecfb1c":[1,0,3,2,7], "classdomain_1_1RuralHouse.html#ab96f0810763d7df5b3f38622850f941e":[1,0,3,2,19], "classdomain_1_1RuralHouse.html#abe770c8a0fbcfed83a358d84bacd66f7":[1,0,3,2,8], "classdomain_1_1RuralHouse.html#ac5596b06728d8bf377993088520fbc9e":[1,0,3,2,10], "classdomain_1_1RuralHouse.html#afae7f7702581e18517472b1faa29273d":[1,0,3,2,13], "classdomain_1_1RuralHouse.html#afdc9d7b70bcc6baa94cae033a5684f0e":[1,0,3,2,17], "classdomain_1_1RuralHouse.html#aff9ad2c8f775b473256233e9c26456f1":[1,0,3,2,12], "classes.html":[1,1], "classexceptions_1_1BadDates.html":[1,0,4,0], "classexceptions_1_1BadDates.html#a1703e41273cdde53ece45e307839c449":[1,0,4,0,2], "classexceptions_1_1BadDates.html#a34213c984892e85612e3a2e44220e896":[1,0,4,0,1], "classexceptions_1_1BadDates.html#ad4918ff10b5e46df93774ea9087e6d04":[1,0,4,0,0], "classexceptions_1_1DB4oManagerCreationException.html":[1,0,4,1], "classexceptions_1_1DB4oManagerCreationException.html#a45281047a13292cbee85b6f04547adc5":[1,0,4,1,1], "classexceptions_1_1DB4oManagerCreationException.html#a5da5879180740606e8a3f1c2f88f01dc":[1,0,4,1,0], "classexceptions_1_1DB4oManagerCreationException.html#af611b151185c866376c172feb883428a":[1,0,4,1,2], "classexceptions_1_1OfferCanNotBeBooked.html":[1,0,4,2], "classexceptions_1_1OfferCanNotBeBooked.html#a08f25182868a230f2b49b37483560486":[1,0,4,2,1], "classexceptions_1_1OfferCanNotBeBooked.html#a0f0deac6a5fe9077f31bd1c90f1b0b59":[1,0,4,2,2], "classexceptions_1_1OfferCanNotBeBooked.html#a113511bf6eedf993448d483ff55cabb0":[1,0,4,2,0], "classexceptions_1_1OverlappingOfferExists.html":[1,0,4,3], "classexceptions_1_1OverlappingOfferExists.html#a053baab9b6c9e1da073098c4cfbcdc45":[1,0,4,3,1], "classexceptions_1_1OverlappingOfferExists.html#a1ba2d73acc9428e642786973e8b2b6b3":[1,0,4,3,0], "classexceptions_1_1OverlappingOfferExists.html#ab47bd08f41ac7a43204806e53aa1538a":[1,0,4,3,2], "classmodelo_1_1dominio_1_1HibernateUtil.html":[1,0,5,0,0], "classmodelo_1_1dominio_1_1HibernateUtil.html#a6a87317e9238a2010699289fbbc9be91":[1,0,5,0,0,0], "classmodelo_1_1dominio_1_1HibernateUtil.html#a9d3cf851e2a9db5174c8cf9a5cc1dcad":[1,0,5,0,0,2], "classmodelo_1_1dominio_1_1HibernateUtil.html#a9fd7b033d7c11fe7373e9d4c3dc556af":[1,0,5,0,0,1], "dir_108520459aa9d4bb59b3b177709be0f6.html":[2,0,0,1], "dir_4c6382d940b8114a9f3b254bc8169ae4.html":[2,0,0,2], "dir_59e154daa71ab644ff60a4d6c4d01bbf.html":[2,0,0,3], "dir_68267d1309a1af8e8297ef4c3efbcdba.html":[2,0,0], "dir_6e33d6500a76933db4361f663e54ab12.html":[2,0,0,4], "dir_80f0f503abfb39369235c25d2f6a7bf4.html":[2,0,0,5], "dir_90c39377213fb1a61b0365fceb63dc36.html":[2,0,0,0], "dir_c7a77c7d494d9ad1c1415f56a0ebc61f.html":[2,0,0,5,0], "files.html":[2,0], "functions.html":[1,3,0], "functions_func.html":[1,3,1], "functions_vars.html":[1,3,2], "hierarchy.html":[1,2], "index.html":[], "interfacebusinessLogic_1_1ApplicationFacadeInterfaceWS.html":[1,0,1,0], "interfacebusinessLogic_1_1ApplicationFacadeInterfaceWS.html#a0e8d2135ef1384a32e74f60bcea55f09":[1,0,1,0,2], "interfacebusinessLogic_1_1ApplicationFacadeInterfaceWS.html#a553cbfb37ea9f1621ba76ad8308a15da":[1,0,1,0,3], "interfacebusinessLogic_1_1ApplicationFacadeInterfaceWS.html#a59eacfa5890466c6a338d0df2e487965":[1,0,1,0,5], "interfacebusinessLogic_1_1ApplicationFacadeInterfaceWS.html#a9f2916ad64674d13dbfbe58252e28531":[1,0,1,0,0], "interfacebusinessLogic_1_1ApplicationFacadeInterfaceWS.html#aa56165d498ff54ccd651fe5ce9a50902":[1,0,1,0,1], "interfacebusinessLogic_1_1ApplicationFacadeInterfaceWS.html#ae338a96d039003c64fceb68d667736f1":[1,0,1,0,4], "namespacebean.html":[0,0,0], "namespacebean.html":[1,0,0], "namespacebusinessLogic.html":[1,0,1], "namespacebusinessLogic.html":[0,0,1], "namespacedataAccess.html":[0,0,2], "namespacedataAccess.html":[1,0,2], "namespacedomain.html":[1,0,3], "namespacedomain.html":[0,0,3], "namespaceexceptions.html":[1,0,4], "namespaceexceptions.html":[0,0,4], "namespacemodelo.html":[0,0,5], "namespacemodelo.html":[1,0,5], "namespacemodelo_1_1dominio.html":[0,0,5,0], "namespacemodelo_1_1dominio.html":[1,0,5,0], "namespaces.html":[0,0], "pages.html":[] };
angular.module('meaningApp') .factory('Post', function ($firebase, FIREBASE_URL) { var ref = new Firebase(FIREBASE_URL); var posts = $firebase(ref.child('posts')).$asArray(); return { all: posts, create: function (post) { var that = this; return posts.$add(post).then(function(postRef) { that.userPosts(post.creatorUID).$push(postRef.name()); return postRef; }); }, get: function (postId) { return $firebase(ref.child('posts').child(postId)).$asObject(); }, delete: function (post) { var $userPosts = this.userPosts(post.creatorUID).$asArray(); return posts.$remove(post).then(function() { return $userPosts.$loaded(); }).then(function(userPosts) { var elementIndex = _.findIndex(userPosts, function(pst) { return pst.$value === post.$id; }); return $userPosts.$remove(elementIndex); }); }, comments: function (postId) { return $firebase(ref.child('comments').child(postId)).$asArray(); }, userPosts: function(userId) { return $firebase(ref.child('user_posts').child(userId)); } }; });
import React, { PropTypes } from 'react'; import { intlShape, injectIntl } from 'react-intl'; import { Modal, Form, Select, message } from 'antd'; import { format } from 'client/common/i18n/helpers'; import messages from './message.i18n'; const formatMsg = format(messages); const FormItem = Form.Item; const Option = Select.Option; @injectIntl @Form.create() export default class SendModal extends React.Component { static propTypes = { intl: intlShape.isRequired, visible: PropTypes.bool.isRequired, tenantName: PropTypes.string.isRequired, tenantId: PropTypes.number.isRequired, loginName: PropTypes.string.isRequired, loginId: PropTypes.number.isRequired, shipment: PropTypes.shape({ trans_mode: PropTypes.string.isRequired, bl_no: PropTypes.string.isRequired, hawb: PropTypes.string.isRequired, }).isRequired, brokers: PropTypes.arrayOf(PropTypes.shape({ partner_id: PropTypes.number.isRequired, tid: PropTypes.number.isRequired, name: PropTypes.string.isRequired, partner_code: PropTypes.string.isRequired, })).isRequired, transps: PropTypes.arrayOf(PropTypes.shape({ partner_id: PropTypes.number.isRequired, tid: PropTypes.number.isRequired, name: PropTypes.string.isRequired, partner_code: PropTypes.string.isRequired, })).isRequired, closeModal: PropTypes.func.isRequired, sendInboundShipment: PropTypes.func.isRequired, reload: PropTypes.func.isRequired, } state = { region: { code: '', province: '', city: '', district: '', street: '', }, } handleDestRegionChange = (region) => { const [code, province, city, district, street] = region; this.setState({ region: { code, province, city, district, street, }, }); } msg = descriptor => formatMsg(this.props.intl, descriptor) render() { const { visible, brokers, transps, form: { getFieldProps } } = this.props; return ( <Modal title={this.msg('sendShipment')} visible={visible} onOk={this.handleOk} onCancel={this.handleCancel} > <Form horizontal> <FormItem label={this.msg('broker')} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}> <Select showSearch optionFilterProp="searched" allowClear {...form.getFieldProps('brkPartnerId', { rules: [{ required: true, type: 'number' }], })} > { brokers.map(pt => ( <Option searched={`${pt.partner_code}${pt.name}`} value={pt.partner_id} key={pt.partner_id} > {pt.name} </Option> )) } </Select> </FormItem> <FormItem label={this.msg('sendTrucking')} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}> <Select showSearch optionFilterProp="searched" allowClear {...getFieldProps('trsPartnerId', { rules: [{ required: true, type: 'number' }], })} /> </FormItem> <FormItem label={this.msg('transportDest')} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}> <Cascader {...getFieldProps('transportDest')} /> </FormItem> </Form> </Modal> ); } }
// Hola mundo console.log("Hola mundo!!"); //Variables y tipos de datos // declaracion de una variable // var nombrevariable = valordelavariable var edad = 24; var cantidadProductos = 4; // utilizando una variable e imprimiendo su valor console.log(edad); // asignar un valor nuevo a una variable edad=30; console.log(edad); //incrementando el valor de una variable a partir de su valor inicial cantidadProductos = cantidadProductos + 10 console.log(cantidadProductos); //jugando con operadores matematicos edad=edad*2+10; console.log(edad);
import request from "supertest"; import app, { test } from "../../server.js"; import newProduct from "../data/new-data.json"; import updatedProduct from "../data/updated-data.json"; import mongoose from "mongoose"; import { Key } from "../../Key.js"; import { expect } from "@jest/globals"; // to handle error that occurs when testing time is too short beforeAll(async () => { await test(); await mongoose.connect(Key, { useCreateIndex: true, useFindAndModify: false, useNewUrlParser: true, useUnifiedTopology: true, }); }); afterAll(async () => { await mongoose.disconnect(); }); describe("POST /api/products", () => { // POST '/' it(`POST /api/products`, async () => { const response = await request(app).post("/api/products").send(newProduct); expect(response.statusCode).toBe(201); expect(response.body.name).toBe(newProduct.name); expect(response.body.description).toBe(newProduct.description); expect(response.body.price).toBe(newProduct.price); }); // POST '/' ERROR it("should return 400 on POST /api/products", async () => { const response = await request(app).post("/api/products").send({ name: "ABCD", price: 15, }); expect(response.statusCode).toBe(400); expect(response.body).toStrictEqual({ message: "request is not correct", }); }); }); describe("GET /api/products", () => { let rProduct; // GET all documents it("GET /api/products", async () => { const response = await request(app).get("/api/products"); expect(response.statusCode).toBe(200); expect(Array.isArray(response.body)).toBeTruthy(); expect(response.body[0].name).toBeDefined(); expect(response.body[0].description).toBeDefined(); expect(response.body[0].price).toBeDefined(); // not recommended rProduct = response.body[0]; }); // GET by productId it("GET /api/products/:productId", async () => { const response = await request(app).get(`/api/products/${rProduct._id}`); expect(response.statusCode).toBe(200); expect(response.body.name).toBe(rProduct.name); expect(response.body.price).toBe(rProduct.price); expect(response.body.description).toBe(rProduct.description); }); // GET handling 404 it("should return 404 on GET /api/products/:productId", async () => { const response = await request(app).get( `/api/products/60c9302af3cb5642e012bef5` ); expect(response.statusCode).toBe(404); expect(response.body.message).toStrictEqual("(GET) No product found"); }); }); describe("Update /api/products", () => { let rProduct; beforeAll(async () => { const response = await request(app).get("/api/products"); rProduct = response.body[0]; }); // PUT by id it("PUT /api/products/:productId", async () => { const response = await request(app) .put(`/api/products/${rProduct._id}`) .send(updatedProduct); expect(response.statusCode).toBe(200); expect(response.body.name).toBe(updatedProduct.name); expect(response.body.description).toBe(updatedProduct.description); expect(response.body.price).toBe(updatedProduct.price); }); // PUT handling 404 it("should return 404 on PUT /api/products/:productId", async () => { const response = await request(app) .put(`/api/products/60c9302af3cb5642e012bef5`) .send(); expect(response.statusCode).toBe(404); }); }); describe("Delete /api/products/:productId", () => { let rProduct; beforeAll(async () => { const response = await request(app).get("/api/products"); rProduct = response.body[0]; }); // DEL by id it("DEL /api/products", async () => { const response = await request(app) .delete(`/api/products/${rProduct._id}`) .send(); expect(response.statusCode).toBe(200); }); // DEL handling 404 it("should return 404 on DELETE /api/products/:productId", async () => { const response = await request(app) .delete(`/api/products/${rProduct._id}`) .send(); expect(response.statusCode).toBe(404); }); });
import React from 'react'; import Task from './Task'; import WithDelete from './WithDelete'; const TaskWithDelete = WithDelete(Task); const Tasks = function ({todoList, updateStatus, handleDelete}) { const tasks = todoList.map(({task, status, id}) => ( <TaskWithDelete key={id} id={id} task={task} status={status} updateStatus={updateStatus} handleDelete={handleDelete} /> )); return <div>{tasks}</div>; }; export default Tasks;
export const getFetch = async function(type, url, params) { // console.log(fetch) let opts = {}; if (type == 'get') { opts = { method: "GET" } } else { opts = { method: "POST", body: JSON.stringify(params), // body: JSON.stringify({ // "x": "113.95599299999998", // "y": "22.56094300001027", // "radius": 500 // }), headers: { "Content-Type": "application/json;charset=UTF-8" } } } let res = await fetch(url, opts); let result = res.json(); return result; // let data = await fetch(url, opts).then(function(res) { // res.json().then(function(res) { // console.log(res) // return res; // }); // }).catch(error => { // // }); // return data; }
const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const User = require('../../models/users/index'); const logger = require('../../config/logger/index'); const saltRounds = 10; exports.signUp = (req, res, next) => { User.find({$or:[{ email: req.body.email }, { username: req.body.username }]}) .exec() .then(user => { if (user.length >= 1) { res.status(409).json({ message: 'Invalid Username or Email' }); } else { bcrypt.hash(req.body.password, saltRounds, (err, hash) => { if (err) { res.status(500).json({ error: err.message, }); } else { const user = new User({ _id: new mongoose.Types.ObjectId, email: req.body.email, username: req.body.username, name: { first_name: req.body.firstName, last_name: req.body.lastName, }, password: hash }); user .save() .then(result => { logger.log('info', result); res.status(201).json({ message: 'A New User has been Created Successfully' }); }) .catch(err => { logger.log('error', err); res.status(500).json({ message: 'There has been an error trying to save the user', error: err }); }) }; }); } }); }
if($('#svg').length > 0 ){ var svg = d3.select("#svg"), width = +svg.attr("width"), height = +svg.attr("height"), radius = 32; var circles = d3.range(20).map(function() { return { x: Math.round(Math.random() * (width - radius * 2) + radius), y: Math.round(Math.random() * (height - radius * 2) + radius) }; }); var color = d3.scaleOrdinal() .range(d3.schemeCategory20); svg.selectAll("circle") .data(circles) .enter().append("circle") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", radius) .style("fill", function(d, i) { return color(i); }) .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); function dragstarted(d) { d3.select(this).raise().classed("active", true); } function dragged(d) { d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y); } function dragended(d) { d3.select(this).classed("active", false); } }
/* eslint-disable no-unused-vars */ import Vue from 'vue'; import Vuex from 'vuex'; import { mount } from 'avoriaz'; import TitleBar from '@/components/TitleBar'; /* eslint-enable no-unused-vars */ Vue.use(Vuex); describe('TitleBar.vue', () => { const fakeState = { loggedIn: false, }; const mutations = { openCloseLogin: sinon.stub(), }; const actions = { login: sinon.stub(), }; let store = null; let wrapper = null; beforeEach(() => { store = new Vuex.Store({ getters: { isLoggedIn() { return fakeState.loggedIn; }, }, mutations, actions, }); }); it('should render correct contents and log In', () => { wrapper = mount(TitleBar, { store }); const title = wrapper.find('.Title'); expect(title[0].text()).to.equal('Assist 2'); const button = wrapper.find('.TitleButton'); expect(button[0].text()).to.equal('Log In'); // eslint-disable-next-line expect(mutations.openCloseLogin).not.to.be.calledOnce; wrapper.find('.SignInButton')[0].trigger('click'); // eslint-disable-next-line expect(mutations.openCloseLogin).to.be.calledOnce; }); it('should render correct contents and log Out', () => { fakeState.loggedIn = true; wrapper = mount(TitleBar, { store }); const button = wrapper.find('.TitleButton'); expect(button[0].text()).to.equal('Log Out'); // eslint-disable-next-line expect(actions.login).not.to.be.calledOnce; wrapper.find('.SignInButton')[0].trigger('click'); // eslint-disable-next-line expect(actions.login).to.be.calledOnce; }); });
/***************** 代码项Js zhengYunFei 2013-07-24**************/ var m; //弹出窗口对象 //初始化表格 function initChildData(url){ window['g'] = $("#maingrid").ligerGrid({ height:'90%', width:'99.7%', headerRowHeight:28, onAfterShowData:function() { $(".l-grid-row-cell-inner").css("height","auto"); //单元格高度自动化,撑开 var i=0; $("tr",".l-grid2","#maingrid").each(function () { $($("tr",".l-grid1","#maingrid")).css("height",$(this).height()); //2个表格的tr高度一致 i++; }); }, rowHeight:26, checkbox: true, columns: [ { display: '标识', name: 'valueId', width: '9%' }, { display: '配置项', name: 'confKey', width: '16%' }, { display: '配置项值', name: 'confValue', width: '14%' }, { display: '分类标识', name: 'sortCode', width: '8%' }, { display: '描述', name: 'confDes', width: '22%' }, { display: '备注', name: 'remark', width: '25%' } ], url:url, pageSize:20,rownumbers:true,pageParmName:"curNo",pagesizeParmName:"curSize" }); $("#pageloading").hide(); } /** * 添加项目配置参数信息 */ function add(sortCode){ var url= "../confManage/forInitSaveConfValue.shtml?sortCode="+sortCode; m=$.ligerDialog.open({ url: url, height: 450,width:550, title:'添加配置参数信息',isResize: true }); if(!m){ $.ligerDialog.error("添加项目配置参数信息失败!"); return; } } /** * 编辑项目配置参数信息 */ function edit(){ var rowid = g.getSelecteds(); if (rowid.length != 1 ){ $.ligerDialog.warn("请选择一行!"); return false; } var valueId = rowid[0].valueId var url= "../confManage/forInitUpdateConfValue.shtml?valueId="+valueId; m=$.ligerDialog.open({ url: url, height: 450,width:550, title:'编辑配置参数信息',isResize: true }); if(!m){ $.ligerDialog.error("编辑配置参数信息失败!"); return; } } /** * 将选中的项目配置参数信息删除 * */ function del() { var rowid = g.getSelecteds(); if (rowid.length == 0){ $.ligerDialog.warn("请至少选择一行!"); return false; } $.ligerDialog.confirm("确定将选中的记录删除吗?", function (yes){ var rIds=""; if(yes){ var url = "../confManage/delConfValue.shtml"; for(var i=0;i<rowid.length;i++){ var rId=rowid[i].valueId; rIds=rId+","+rIds; } $.ajax({ type : "post", url : url, data : { "valueIds" :rIds }, success : function(data) { //如果删除成功,则刷新页面! if(data["msg"]=="sucess") { $.ligerDialog.alert("删除成功!"); g.loadData(); //重新加载不查询数据库 }else if(data["msg"]=="error") { $.ligerDialog.error("失败!"); }else{ $.ligerDialog.error(data["msg"]); } }, error : function() { $.ligerDialog.error("操作失败!"); } }); } }); } //详细页面返回重新刷新列表 function reload(backMsg){ $.ligerDialog.success(backMsg); g.loadData(); //重新加载不查询数据库 m.close(); }
class Identicon { constructor(blockArray, blockColor){ this.blockColor = blockColor; this.blockArray = blockArray; } }
import { asynctextConstants } from './../constants'; function receivePosts(number, asyncText) { return { type: asynctextConstants.RECEIVE_POSTS, asyncText, number } } function requestPosts(number) { return { type: asynctextConstants.REQUEST_POSTS, number } } function invalidateSubreddit(number) { return { type: asynctextConstants.INVALIDATE_SUBREDDIT, number } } function fetchPosts(number) { return dispatch => { dispatch(requestPosts(number)) return fetch(`https://jsonplaceholder.typicode.com/posts/${number}`) .then(response => response.json()) .then(json => dispatch(receivePosts(number, json.title))) .catch(error => dispatch(invalidateSubreddit(number))); } } export const asyncTextActions = { fetchPosts }
/** * @module OBJET * @submodule Edition * @main OBJET */ OBJETS_Edition = { /* * Etats * */ form_prepared:false, /* * Instance du item {Film} en édition (if any) * */ current:null, /* * = MAIN = Demande d'édition du formulaire * * @param id Identifiant {String} du item à éditer * Si non fourni, c'est une création. */ edit:function(id) { if(!this.Dom.panneau_opened) this.Dom.show_panneau() if(!this.form_prepared) this.prepare_formulaire this.OBJS.Dom.show_formulaire if(undefined == id) { this.init_form } else { this.current = this.OBJS.get( id ) this.current.edit // @note: sait gérer le fait que le item ne soit pas encore chargé } }, /** * Pour enregistrer les modifications (ou créer un nouveau item) * * NOTES * ----- * * Si la méthode `get_values` rencontre des valeurs invalides, elle renvoie * false ce qui interrompt la procédure de sauvegarde. * * @method save * @return true en cas de succès, false en cas de valeur invalide. * */ save:function() { var values = this.get_values() if(values == false /* Donnée invalide */) return false var is_new_item = values.id == null if(is_new_item) { var id_new_item = this.id_from_mainprop( values[this.main_prop] ) this.current = new this.ItemClass( id_new_item ) } else this.current = this.OBJS.get( values.id ) this.current.dispatch( values ) if(is_new_item) this.current.id = id_new_item // a été écrasé par dispatch // === ENREGISTREMENT DU FILM === this.current.save( $.proxy(this[is_new_item ? 'update_item_list_with_new_item' : 'end'], this) ) return true }, /* * Demande de destruction du item d'identifiant +id+ * */ want_remove:function(id) { Edit.show({ id:'destroy_item', title: LOCALE[this.class_min].ask['want delete film'] + " “"+this.OBJS.get(id).titre+"” ?", buttons:{ cancel:{name:"Renoncer"}, ok:{name:LOCALE[this.class_min].label['destroy'], onclick:$.proxy(this.remove, this, id)} } }) }, /* * Destruction de l'item d'identifiant +id+ * */ remove:function(id) { Ajax.send({script:this.folder_ajax+'/destroy', collection:Collection.name, item_id:id}, $.proxy(this.suite_remove, this)) }, suite_remove:function(rajax) { if(rajax.ok) { var item = this.OBJS.get( rajax.item_id ) this.OBJS.Dom.remove_item(item.id) if(this.OBJS.DATA_PER_LETTER[item.let]) { var indice = this.OBJS.DATA_PER_LETTER[item.let].indexOf(item.id) console.log("indice: "+indice) this.OBJS.DATA_PER_LETTER[item.let].splice(indice, 1) } delete this.OBJS.DATA[item.id] with(this.OBJS.Dom) { remove_listing_letter(item.let) on_click_onglet(item.let) } } else F.error(rajax.message) }, /* * Appelé après `save' ci-dessus en cas de nouveau film * On doit actualiser la liste des films (pour ne pas avoir à la recharger) * et rafraichir l'affichage de la liste si nécessaire (si elle est affichée ou * construite, entendu que la lettre affichée n'est pas forcément la lettre du * film) * * @requis this.current Instance {Film} du nouveau film */ update_item_list_with_new_item:function() { var uitem = this.current uitem.is_new = true // encore utile ? // = Ajout à this.OBJS.DATA = this.OBJS.DATA[uitem.id] = uitem.data_mini // = Ajout à this.OBJS.DATA_PER_LETTER = // @note: si DATA_PER_LETTER a déjà été établie, c'est ici // qu'il faut ajouter le uitem. Sinon, il sera automatiquement // ajouté à la définition de DATA_PER_LETTER. if(this.OBJS.check_if_list_per_letter_ok) { this.OBJS.DATA_PER_LETTER[uitem.let].push( uitem.id ) this.OBJS.DATA_PER_LETTER[uitem.let].sort } // = Forcer l'actualisation du listing = this.OBJS.Dom.remove_listing_letter( uitem.let ) // = Finir et afficher le listing = this.end() }, /* * Pour terminer l'édition/création du film * * NOTES * ----- * = Cette méthode est appelée directement par le bouton "Renoncer", sans * passer par `save' ci-dessus * * = On peut venir aussi de `update_item_list_with_new_item' ci-dessus lorsque * c'est une création de film. */ end:function() { this.OBJS.Dom.hide_formulaire if(this.current && this.current.is_new) this.OBJS.Dom.on_click_onglet( this.current.let ) }, /** * Retourne un identifiant de l'objet à partir du +value+ fourni (le titre * du film, le mot du scénodico, etc.) * @method id_from_mainprop * @param {String} value Le mot, le titre du film, etc. * @return {String} Un identifiant valide pour l'objet. */ id_from_mainprop:function(value) { var t_fin, t = Texte.to_ascii( value ) t = t.titleize().replace(/[^a-zA-Z0-9]/g,'') if (this.OBJS.NAME == 'DICO') t_fin = t.substring(0,7) else t_fin = t var doublon_checked = false, id_doublon = null ; while (undefined != this.OBJS.DATA[t_fin] ) { // Si on passe par ici, c'est que l'identifiant existe déjà dans la // liste d'objets. On vérifie quand même que ce ne soit pas un doublon if(!doublon_checked) { if(this.OBJS.DATA[t_fin][this.main_prop] == value) { id_doublon = "" + t_fin } doublon_checked = true } if(t_fin.length < t.length) t_fin = t.substring(0, t_fin.length + 1) else t_fin += "0" // on finira bien par en trouver un } if( id_doublon ) { F.error(LOCALE.objet.error['objet already exists']. replace(/_VALUE_/, value). replace(/_ID_/, id_doublon). replace(/_OTHER_ID_/,t_fin) ) } // == débug suite à erreur sur Cinquième Élément == alert("L'identifiant trouvé d'après le titre est : "+t_fin+"\n\n"+ "[Pour supprimer ce message (si la méthode fonctionne bien) : il est généré "+ "dans\n`required/object/>OBJETS_Edition.js::id_from_mainprop`]") // == /débug return t_fin }, } /* * Propriétés complexes à ajouter aux sous-objets <OBJETS PLURIEL>.Edition * */ OBJETS_Edition_defined_properties = { /* * Raccourci pour obtenir <parent>.Dom (et pouvoir donc utiliser `this.Dom...') * */ "Dom":{get:function(){return this.OBJS.Dom}}, /* * Raccourci pour obtenir l'identifiant du panneau * */ "id_panneau":{ get:function(){ if(undefined == this._id_panneau) { this._id_panneau = this.OBJS.Dom.id_panneau } return this._id_panneau } }, /* * Raccourci pour obtenir le préfix utilisé par <OBJET PLURIEL>.Dom * */ "prefix":{ get:function(){ if(undefined == this._prefix) this._prefix = this.OBJS.Dom.prefix return this._prefix } }, /* * Return le {jQuerySet} du formulaire d'édition du film. * */ "form":{ get:function(){return $('div#'+this.id_panneau+'_edition div#'+this.prefix+'form')} }, /* * Préparation du formulaire * * NOTES * ----- * = Il est préparé masqué * = On place sur tous les champs de saisie textuels le gestionnaire * de focus et blur de UI.Input */ "prepare_formulaire":{ get:function(){ $('div#'+this.id_panneau+'_edition').html('') $('div#'+this.id_panneau+'_edition').append( this.html_form ) UI.Input.bind( this.form ) this.form_prepared = true } }, /* * Retourne le code HTML du formulaire * */ "html_form":{ get:function(){ return '<div id="'+this.prefix+'div_form" class="div_form_item">' + this.html_formulaire + this.html_div_buttons + '</div>' } }, /* * Construit un champ d'après les données dfield * */ "html_field":{ value:function(dfield){ if('string'==typeof dfield) return dfield var field = "" var type = dfield.type || 'text' if(dfield.id) dfield.id = this.class_min+'Edit-'+dfield.id switch(type) { case 'text': if(dfield.label) field += '<label class="libelle" for="'+dfield.id+'">'+dfield.label+'</label>' return field + this.html_balise_in_field(dfield) case 'textarea': if(dfield.label) field += '<label class="libelle" for="'+dfield.id+'">'+dfield.label+'</label>' var value = dfield.value; delete dfield.value if(dfield.class) dfield.class = dfield.class.split(' ') else dfield.class = [] dfield.class.push('returnable') dfield.class = dfield.class.join(' ') return field + this.html_balise_in_field(dfield) + (value ? value : "") + '</textarea>' case 'hidden': return '<input type="hidden" id="'+dfield.id+'" value="" />' } } }, /* * Retourne le code HTML des attributs du champ d'après ses données +dfield+ * */ "html_balise_in_field":{ value:function(dfield) { if(undefined == dfield.type) dfield.type = 'text' return "<" + (dfield.type == 'text' ? 'input' : dfield.type) + (dfield.type=='text'? ' type="text"' : '') + (dfield.id ? ' id="' +dfield.id +'"' : '') + (dfield.class ? ' class="' +dfield.class +'"' : '') + (dfield.data_type ? ' data-type="' +dfield.data_type +'"' : '') + (dfield.data_format ? ' data-format="' +dfield.data_format +'"' : '') + (dfield.value ? ' value="' +dfield.value +'"' : '') + (dfield.style ? ' style="' +dfield.style +'"' : '') + (dfield.title ? ' title="' +dfield.title +'"' : '') + (dfield.alt ? ' alt="' +dfield.alt +'"' : '') + (dfield.placeholder ? ' placeholder="' +dfield.placeholder +'"' : '') + (dfield.type=='text' ? ' />' : '>') } }, /* * Code HTML des boutons du formulaire * */ "html_div_buttons":{ get:function(){ dlog("-> "+this.NAME+".html_div_buttons", DB_FCT_ENTER) return '<div class="buttons">' + '<input type="button" value="Renoncer" onclick="$.proxy('+this.NAME+'.end, '+this.NAME+')()" class="fleft" />' + '<input type="button" value="Enregistrer" onclick="$.proxy('+this.NAME+'.save, '+this.NAME+')()" />' + '</div>' } } } // Extensions pour les films if(undefined == FILMS.Edition) FILMS.Edition = {} $.extend(FILMS.Edition, OBJETS_Edition) Object.defineProperties(FILMS.Edition, OBJETS_Edition_defined_properties) // Extensions pour le Scénodico if(undefined == DICO.Edition) DICO.Edition = {} $.extend(DICO.Edition, OBJETS_Edition) Object.defineProperties(DICO.Edition, OBJETS_Edition_defined_properties)
$(document).ready(function() { $('.js-add-task').on('click', function(){ form = $(this).parent('form'); data = form.serializeArray(); action = '/main/addTask'; $.ajax({ type: 'POST', url: action, dataType: 'json', data: data, success: function(r) { if (r.status == 'error') { alert(r.message); $.each(r.fields, function(i, e) { $('#field_'+e).addClass('is-error'); }); } if (r.status == 'ok') { alert(r.message); form.trigger("reset"); location.reload(); } } }) return false; }) }) $(document).ready(function() { $('.js-order option').on('click', function(){ order = $(this).val(); sort = $('.js-sort').attr('data-sort'); page = $('.js-pagination li.active a').attr('data-page'); tbody = $('.js-table tbody'); $.ajax({ type: 'POST', url: '/main/sortTask', dataType: 'json', data: { order: order, sort: sort, page: page, }, success: function(r) { if (r.status == 'ok') { tbody.html(r.content) } } }) return false; }) }) $(document).ready(function() { $('.js-sort').on('click', function(){ if ($(this).hasClass('up')) { $(this).removeClass('up') $(this).addClass('down') $(this).attr('data-sort', 'desc') } else { $(this).removeClass('down') $(this).addClass('up') $(this).attr('data-sort', 'asc') } order = $('.js-order').val(); sort = $(this).attr('data-sort'); page = $('.js-pagination li.active a').attr('data-page'); tbody = $('.js-table tbody'); $.ajax({ type: 'POST', url: '/main/sortTask', dataType: 'json', data: { order: order, sort: sort, page: page, }, success: function(r) { if (r.status == 'ok') { tbody.html(r.content) } } }) return false; }) }) $(document).ready(function() { $('.js-pagination li a').on('click', function(){ order = $('.js-order').val(); sort = $('.js-sort').attr('data-sort'); page = $(this).attr('data-page'); tbody = $('.js-table tbody'); $('.js-pagination li').removeClass('active'); $(this).parent('li').addClass('active'); $.ajax({ type: 'POST', url: '/main/sortTask', dataType: 'json', data: { order: order, sort: sort, page: page, }, success: function(r) { if (r.status == 'ok') { tbody.html(r.content) } } }) return false; }) }) $(document).ready(function() { $('.js-try-login').on('click', function(){ form = $(this).parent('form'); data = form.serializeArray(); action = '/admin/tryLogin'; $.ajax({ type: 'POST', url: action, dataType: 'json', data: data, success: function(r) { if (r.status == 'error') { alert(r.message); $.each(r.fields, function(i, e) { $('#field_'+e).addClass('is-error'); }); } if (r.status == 'ok') { location.href = '/'; } } }) return false; }) }) $(document).on('click', '.js-task-done', function(){ $this = $(this); id = $(this).parents('tr').attr('data-task'); action = '/main/taskDone'; $.ajax({ type: 'POST', url: action, dataType: 'json', data: { id: id, }, success: function(r) { if (r.status == 'errorAuth') { location.href = '/admin'; } if (r.status == 'ok') { alert('Задача отмечена выполненной!'); location.href = '/'; } } }) return false; }) $(document).on('click', '.js-task-edit', function(){ $this = $(this); id = $(this).parents('tr').attr('data-task'); name = $(this).parents('tr').find('input[name=name]').val(); email = $(this).parents('tr').find('input[name=email]').val(); task = $(this).parents('tr').find('textarea[name=task]').val(); action = '/main/taskEdit'; $.ajax({ type: 'POST', url: action, dataType: 'json', data: { id: id, name: name, email: email, task: task, }, success: function(r) { if (r.status == 'error') { alert(r.message); $.each(r.fields, function(i, e) { $('#field_'+e).addClass('is-error'); }); } if (r.status == 'errorAuth') { location.href = '/admin'; } if (r.status == 'ok') { alert('Задача отредактирована!'); location.href = '/'; } } }) return false; })
import axios from 'axios'; import React, { useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { addItemDoing, addItemDone, addItemToDo, removeItemDoing, removeItemDone, removeItemToDo } from '../Actions/index'; import './styles/output.css'; export default function Todo() { const [todo, setTodo] = useState(''); const [doing, setDoing] = useState(''); const [done, setDone] = useState(''); const dispatch = useDispatch(); const [response, setResponse] = useState(''); const ToDo = useSelector((state) => state.ToDo); const Doing = useSelector((state) => state.Doing); const Done = useSelector((state) => state.Done); const user = useSelector((state) => state.User); const [error, setError] = useState(false); function handleChangeToDo(e) { setTodo(e.target.value); } function handleAddToDo(e) { dispatch(addItemToDo(todo)); setTodo(''); } function handleRemoveToDo(e, obj) { let ObjToBeRemoved = Object.values(obj).pop(); dispatch(removeItemToDo(ObjToBeRemoved)) } // function handleDeleteList(e) { // // setList([]); // } // --------------------------------------------------------------------------------------------------- function handleChangeDoing(e) { setDoing(e.target.value); } function handleAddDoing(e) { dispatch(addItemDoing(doing)); setDoing(''); } function handleRemoveDoing(e, obj) { let ObjToBeRemoved = Object.values(obj).pop(); dispatch(removeItemDoing(ObjToBeRemoved)) } // --------------------------------------------------------------------------------------------------- function handleChangeDone(e) { setDone(e.target.value); } function handleAddDone(e) { dispatch(addItemDone(done)); setDone(''); } function handleRemoveDone(e, obj) { let ObjToBeRemoved = Object.values(obj).pop(); dispatch(removeItemDone(ObjToBeRemoved)) } // ------------------------------------------------------------------------------------------------------------------------ function handleAddDoingRemoveToDo(e, obj) { dispatch(addItemDoing(obj.obj)); handleRemoveToDo(e, obj); } function handleAddDoneRemoveDoing(e, obj) { dispatch(addItemDone(obj.obj)); handleRemoveDoing(e, obj); } function handleAddToDoRemoveDoing(e, obj) { dispatch(addItemToDo(obj.obj)); handleRemoveDoing(e, obj); } function handleAddDoingRemoveDone(e, obj) { dispatch(addItemDoing(obj.obj)); handleRemoveDone(e, obj); } function handleSave(e) { console.log(user + "user"); let todo = Object.assign({}, ToDo) let doing = Object.assign({}, Doing) let done = Object.assign({}, Done) let body = { userName: user, todo, doing, done } console.log(body); axios.put('https://todolistserver-snakshay.herokuapp.com/save', body) .then((response) => { setResponse(response.data) setError(false); setTimeout(() => { setResponse(''); }, 1000); }) .catch((error) => { // console.log('error'); setResponse('Error occured! please try again'); setError(true) }) } return ( <div> {/* ----------------------------------------Card Container-------------------------------------------------- */} <div className='card-container'> {/* -------------------------------------To-Do card ----------------------------------------------*/} <div className='card'> <div className='title'><i className="fas fa-clipboard-list"></i> To-Do</div> <ul className='list'> {ToDo.map((obj) => (<li key={obj}> {obj} <button className='trashButton fa-button' onClick={(e) => handleRemoveToDo(e, { obj })}><i className="fas fa-trash fa-button"></i></button> <button className='button-right fa-button' onClick={(e) => handleAddDoingRemoveToDo(e, { obj })}><i className="fas fa-caret-right fa-button"></i></button> <br /> </li>) )} </ul> <div className='cardFooter'> <input type='text' className='textbox' onChange={(e) => handleChangeToDo(e)} value={todo} placeholder='Add new item to To-Do'></input> {todo.length > 0 ? <span className='footerButtonAdd'><button className='addButton' onClick={(e) => handleAddToDo(e)}> <i className="fas fa-plus" ></i></button></span> : <span className='footerButtonAdd'><button className='addButton disabled' disabled> <i className="fas fa-plus"></i></button></span>} </div> </div> {/* -------------------------------------DOing card ----------------------------------------------*/} <div className='card'> <div className='title'><i className="far fa-edit"></i> Ongoing...</div> <ul className='list'> {Doing.map((obj) => (<li key={obj}> <button className='button-left' onClick={(e) => handleAddToDoRemoveDoing(e, { obj })}><i className="fas fa-caret-left fa-button"></i></button> {obj} <button className='trashButton ' onClick={(e) => handleRemoveDoing(e, { obj })}><i className="fas fa-trash fa-button"></i></button> <button className='button-right' onClick={(e) => handleAddDoneRemoveDoing(e, { obj })}><i className="fas fa-caret-right fa-button"></i></button> </li>) )} </ul> <div className='cardFooter'> <input type='text' className='textbox' onChange={(e) => handleChangeDoing(e)} value={doing} placeholder='Add new item to Ongoing'></input> {doing.length > 0 ? <span className='footerButtonAdd'><button className='addButton' onClick={(e) => handleAddDoing(e)}> <i className="fas fa-plus"></i></button></span> : <span className='footerButtonAdd'><button className='addButton disabled' disabled > <i className="fas fa-plus"></i></button></span>} </div> </div> {/* -------------------------------------DOne card ----------------------------------------------*/} <div className='card'> <div className='title'><i className="fas fa-clipboard-check"></i> Completed</div> <ul className='list'> {Done.map((obj) => (<li key={obj}> <button className='button-left' onClick={(e) => handleAddDoingRemoveDone(e, { obj })}><i className="fas fa-caret-left fa-button"></i></button> {obj} <button className='trashButton' onClick={(e) => handleRemoveDone(e, { obj })}><i className="fas fa-trash fa-button"></i></button></li>) )} </ul> <div className='cardFooter'> <input type='text' className='textbox' onChange={(e) => handleChangeDone(e)} value={done} placeholder='Add new item to Completed'></input> {done.length > 0 ? <span className='footerButtonAdd'><button className='addButton' onClick={(e) => handleAddDone(e)}> <i className="fas fa-plus"></i></button></span> : <span className='footerButtonAdd'><button className='addButton disabled' disabled> <i className="fas fa-plus"></i></button></span>} </div> </div> </div> {/* <div> <h3>To Do</h3> <input type='text' onChange={(e) => handleChangeToDo(e)} value={todo} placeholder='add new ToDO'></input> <br /> <button type='button' onClick={(e) => handleAddToDo(e)}>Add</button> <ul > {ToDo.map((obj) => (<li key={obj}> {obj} <button onClick={(e) => handleRemoveToDo(e, { obj })}>-</button></li>) )} </ul> <button type='button' onClick={(e) => handleDeleteList(e)}>Delete List</button> </div> <hr></hr> <div> <h3>Doing</h3> <input type='text' onChange={(e) => handleChangeDoing(e)} value={doing} placeholder='add new ToDO'></input> <br /> <button type='button' onClick={(e) => handleAddDoing(e)}>Add</button> <ul > {Doing.map((obj) => (<li key={obj}> {obj} <button onClick={(e) => handleRemoveDoing(e, { obj })}>-</button></li>) )} </ul> <button type='button' onClick={(e) => handleDeleteList(e)}>Delete List</button> </div> <hr></hr> <div> <h3>Done</h3> <input type='text' onChange={(e) => handleChangeDone(e)} value={done} placeholder='add new ToDO'></input> <br /> <button type='button' onClick={(e) => handleAddDone(e)}>Add</button> <ul > {Done.map((obj) => (<li key={obj}> {obj} <button onClick={(e) => handleRemoveDone(e, { obj })}>-</button></li>) )} </ul> <button type='button' onClick={(e) => handleDeleteList(e)}>Delete List</button> </div> <hr></hr> */} <div className='btn-container'> <button className='btnDark hover ' onClick={(e) => handleSave(e)}> Save</button><br /> {error ? <span style={{ color: 'red' }}> {response}</span> : <span>{response}</span>} </div> </div > ); }
const request = require("request"); const forecast = (lat, lon, callback) => { const forecastUrl = "https://api.darksky.net/forecast/d0466ef31da1f60311649ae34d683f3e/" + lat + "," + lon + "?units=si"; request({ url: forecastUrl, json: true }, (error, response) => { if (error) { callback( "Can't connect with weather server. Try again later.", undefined ); } else if (response.body.code === 400) { callback("Can't get forecast. Poorly formatted request.", undefined); } else { callback(undefined, { forecast: response.body.daily.data[0].summary + " Temperature is " + Math.round(response.body.currently.temperature) + " C°. Feels like " + Math.round(response.body.currently.apparentTemperature) + " C°. There is a " + response.body.currently.precipProbability + " % chance of ☔" }); } }); }; module.exports = forecast;
import aes from './aes'; // 加密字符串 function encryptStr(str) { return aes.encrypt(str); } // 按指定key,加密对象 function encryptObj(obj, encryptKey = []) { const tempObj = Object.assign({}, obj); Object.keys(tempObj).forEach((key) => { if (encryptKey.includes(key)) { tempObj[key] = tempObj[key] && aes.encrypt(tempObj[key]); } }); return tempObj; } // 按指定key,加密对象数组 [{}, {}] function encryptArr(arr, encryptKey = []) { const tempArr = []; if (!Array.isArray(arr)) { return tempArr; } arr.forEach((item) => { let el = Object.assign({}, item.map); Object.keys(el).forEach((key) => { if (encryptKey.includes(key)) { el[key] = aes.encrypt(el[key]); } }); tempArr.push(el); }); return tempArr; } // 加密消息 function encryptMessage(obj) { const tempObj = Object.assign({}, obj); const encryptKey = ['from', 'to', 'content']; encryptKey.forEach((key) => { if (key !== 'content') { tempObj[key] = aes.encrypt(tempObj[key]); } else { tempObj[key] = aes.encrypt(JSON.stringify(tempObj[key])); } }); return tempObj; } export default { encryptStr, encryptObj, encryptArr, encryptMessage };
exports.schema = [ { path: '/users', method: 'GET', case: 1, field_name: 'name', }, { path: '/generalSearch', method: 'POST', case: 2, fields_path: 'users', field_name: 'account', }, { path: '/users/search', method: 'GET', case: 1, fields_path: 'users', field_name: 'account', }, { path: '/user/:userName/following_users', method: 'GET', case: 2, fields_path: 'users', field_name: 'name', }, { path: '/user/:userName/followers', method: 'GET', case: 2, fields_path: 'followers', field_name: 'name', }, { path: '/user/:userName', method: 'GET', case: 3, field_name: 'name', }, { path: '/wobject/:authorPermlink/followers', method: 'POST', case: 1, fields_path: 'followers', field_name: 'name', }, { path: '/wobject/:authorPermlink/object_expertise', method: 'POST', case: 2, fields_path: 'users', field_name: 'name', }, ];
define("dr-media-springstreams-implementation", ["springstreams"], function (Springstreams) { "use strict"; var SpringstreamsImplementation = new Class({ initialize: function (player) { this.player = player; this.sensors = new SpringStreams("vmdkstream"); this.onPlay = this.bootstrap.bind(this); this.player.addEvent('play', this.onPlay); }, bootstrap: function () { this.player.removeEvent('play', this.onPlay); this.trackPlayEvent(); }, trackPlayEvent: function() { var options = this.player.options; var videoElement = this.player.videoElement; var date, time, channelId; var episode = this.player.resourceSlug(); var productionNumber = this.player.productionNumber(); var series = options.videoData.programSerieSlug; var filename = videoElement.currentSrc; var videoType = options.videoData.videoType == 'live' ? 'live' : 'OD'; if (this.player.programcardResult) { var pc = this.player.programcardResult; if (pc.PrimaryChannel !== null && pc.PrimaryChannel !== undefined) { var channelNameArr = pc.PrimaryChannel.split("/"); channelId = channelNameArr[channelNameArr.length-1]; } else { channelId = 'drdk'; } //PrimaryAssetStartPublish: "2013-07-09T20:05:00Z" date = pc.PrimaryAssetStartPublish.split("T")[0]; time = pc.PrimaryAssetStartPublish.split("T")[1].split("Z")[0]; } else { channelId = options.videoData.channelId; var dateObj = options.videoData.primaryAssetStartPublish; if (dateObj !== null && dateObj !== undefined) { date = dateObj.split("T")[0]; time = dateObj.split("T")[1].split("Z")[0]; } else { date = ""; time = ""; } } var desc = { "stream":"DR_" + videoType + "/" + channelId + "/" + episode + "/NULL/NULL/" + date + "/" + time + "/" + productionNumber, "duration": this.player.duration() /** * Tag order: * "BroadCaster_OD/Channel/Program/Episode/Season/Date_First_Broadcast/Time_First_Broadcast/STREAMID" * "BroadCaster_LIVE/Channel/Program/Episode/Season/Date_First_Broadcast/Time_First_Broadcast/STREAMID" * (season og episode vil altid være NULL, da vi slet ikke er så avancerede) */ }; this.sensors.track(this.player.videoElement, desc); } } ); return SpringstreamsImplementation; });
'use strict'; const bunyan = require('bunyan'); const ConsoleLoggerStream = require('./ConsoleLoggerStream'); class CoreLogger { static create(loggerName, streams) { let log = bunyan.createLogger({ name: loggerName, streams: streams }); return log; } static getDefaultLogger(loggerName, logLevel) { return CoreLogger.create(loggerName, [ {level: logLevel, type: 'raw', stream: ConsoleLoggerStream(bunyan)} ]); } static getConsoleLogger(loggerName, logLevel) { return CoreLogger.create(loggerName, [{ level: logLevel, stream: ConsoleLoggerStream(bunyan), type: 'raw' }]); } } module.exports = CoreLogger;
export function idValidator(id) { return /^[0-9a-fA-F]{24}$/.test(id) ? null : { _id: "Incorrect id" }; }
import axios from 'axios'; const host = "https://gittodoproject-server.run.goorm.io" // const host = "http://localhost:3002" // 전체 투두 리스트 데이터 불러오기 export async function getTodos() { const response = await axios.get(host + "/api/todos"); return response.data; } // 특정 투투 데이터 불러오기 export async function getTodo(id) { const response = await axios.get(`${host}/api/todos/${id}`); return response.data; } // 특정 투두 안 리스트 데이터 한개 추가 export async function createOneTodo(id, data = {}) { const response = await axios.put(`${host}/api/todos/${id}`, { type: 'C', data: { ...data } }); return response.data; } // 특정 투두 안 리스트 데이터 한개 삭제(수정) export async function deleteOneTodo(id, data = {}) { const response = await axios.put(`${host}/api/todos/${id}`, { type: 'D', data: { ...data } }); return response.data; } // 특정 투두 안 리스트 데이터 토글 변경 export async function toggleOneTodo(id, data = {}) { const response = await axios.put(`${host}/api/todos/${id}`, { type: 'T', data: { ...data } }); return response.data; }
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var modelName = 'FaultDtail'; var schemaTemp = new Schema({ faultItmID: { type: Schema.Types.ObjectId, required: true }, titlFa: { type: String, required: true }, abbrvation: { type: String, required: true }, dscription: { type: String, required: false }, needSOS: { type: Boolean, required: false }, Status: { type: String, required: true }, lastModifiedTime: { type: Date, required: true, default: Date.now } }); var FaultDtail = mongoose.model(modelName, schemaTemp); module.exports = FaultDtail;
const quotes = [ { text: "Life is about making an impact, not making an income.", author: "Kevin Kruse" }, { text: "Whatever the mind of man can conceive and believe, it can achieve.", author: "Napoleon Hill" }, { text: "Strive not to be a success, but rather to be of value.", author: "Albert Einstein" }, { text: "Two roads diverged in a wood, and I—I took the one less traveled by, And that has made all the difference.", author: "Robert Frost" }, ];
// credit to https://github.com/wildbit/postmark-templates module.exports = function(props) { return ` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Set up a new password for ${props.title}</title> </head> <body style="-webkit-text-size-adjust: none; box-sizing: border-box; color: #74787E; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; height: 100%; line-height: 1.4; margin: 0; width: 100% !important;" bgcolor="#F2F4F6"><style type="text/css"> body { width: 100% !important; height: 100%; margin: 0; line-height: 1.4; background-color: #F2F4F6; color: #74787E; -webkit-text-size-adjust: none; } @media only screen and (max-width: 600px) { .email-body_inner { width: 100% !important; } .email-footer { width: 100% !important; } } @media only screen and (max-width: 500px) { .button { width: 100% !important; } } </style> <span class="preheader" style="box-sizing: border-box; display: none !important; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 1px; line-height: 1px; max-height: 0; max-width: 0; mso-hide: all; opacity: 0; overflow: hidden; visibility: hidden;">Use this link to reset your password. The link is only valid for 24 hours.</span> <table class="email-wrapper" width="100%" cellpadding="0" cellspacing="0" style="box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; margin: 0; padding: 0; width: 100%;" bgcolor="#F2F4F6"> <tr> <td align="center" style="box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; word-break: break-word;"> <table class="email-content" width="100%" cellpadding="0" cellspacing="0" style="box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; margin: 0; padding: 0; width: 100%;"> <tr> <td class="email-masthead" style="box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; padding: 25px 0; word-break: break-word;" align="center"> <a href="https://example.com" class="email-masthead_name" style="box-sizing: border-box; color: #bbbfc3; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 16px; font-weight: bold; text-decoration: none; text-shadow: 0 1px 0 white;"> ${props.title} </a> </td> </tr> <tr> <td class="email-body" width="100%" cellpadding="0" cellspacing="0" style="-premailer-cellpadding: 0; -premailer-cellspacing: 0; border-bottom-color: #EDEFF2; border-bottom-style: solid; border-bottom-width: 1px; border-top-color: #EDEFF2; border-top-style: solid; border-top-width: 1px; box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; margin: 0; padding: 0; width: 100%; word-break: break-word;" bgcolor="#FFFFFF"> ${props.children} </td> </tr> <tr> <td style="box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; word-break: break-word;"> <table class="email-footer" align="center" width="570" cellpadding="0" cellspacing="0" style="box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; margin: 0 auto; padding: 0; text-align: center; width: 570px;"> <tr> <td class="content-cell" align="center" style="box-sizing: border-box; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; padding: 35px; word-break: break-word;"> <p class="sub align-center" style="box-sizing: border-box; color: #AEAEAE; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 1.5em; margin-top: 0;" align="center">${props.copyright}</p> <p class="sub align-center" style="box-sizing: border-box; color: #AEAEAE; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; font-size: 12px; line-height: 1.5em; margin-top: 0;" align="center"> ${props.address} </p> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </body> </html> `; }
var express = require('express'); var http = require("http"); var path = require('path'); var passport = require('passport'); var Strategy = require('passport-facebook').Strategy; var db = require("./db"); var nodemon = require("nodemon"); var cel = require('connect-ensure-login'); var bodyParser = require("body-parser"); var rand = require("./rand"); //var morgan = require('morgan'); //use passport for auth passport.use(new Strategy({ clientID: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, callbackURL: 'https://myvoting-app.herokuapp.com/login/facebook/return' }, function(accessToken, refreshToken, profile, cb) { return cb(null, profile); })); passport.serializeUser(function(user, cb) { cb(null, user); }); passport.deserializeUser(function(obj, cb) { cb(null, obj); }); // Create a new Express application. var app = express(); //app.use(morgan('combined')); app.use(express.static(path.join(__dirname, 'public'))); // Configure view engine to render EJS templates. app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(require('body-parser').urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true })); // Initialize Passport and restore authentication state, if any, from the // session. app.use(passport.initialize()); app.use(passport.session()); app.get('/favicon.ico', function(req, res) { res.sendStatus(204); }); // Define routes. app.get('/', function(req, res) { app.locals.session = req.sessionID; res.locals.isLogged = req.isAuthenticated(); if (res.locals.isLogged){ res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); } db.getConnection(function(err, connection) { if (err) throw err; connection.query("SELECT tabname FROM home", function (err, results){ if (err) throw err; var poll = []; for (var i in results){ for (var j in results[i]){ poll.push(results[i][j]); } } connection.query("SELECT quest FROM home", function (err, results){ if (err) throw err; var quest = []; for (var i in results){ for (var j in results[i]){ quest.push(results[i][j]); } } app.locals.poll = poll; app.locals.quest = quest; connection.release(); res.render('index'); }); }); }); }); app.get('/login/facebook', passport.authenticate('facebook')); app.get('/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/failure' }), cel.ensureLoggedIn(), function(req, res) { res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); res.locals.isLogged = req.isAuthenticated(); res.redirect('/'); }); app.get('/logout', function(req, res){ req.session.destroy(function (err) { res.locals.isLogged = req.isAuthenticated(); res.redirect('/'); }); }); app.get("/mypolls", function(req, res) { console.log(req); res.locals.isLogged = req.isAuthenticated(); res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); console.log("mypolls"); db.getConnection(function(err, connection) { if (err) throw err; connection.query("SELECT tabname FROM home WHERE author = ?", [res.locals.currentUser], function (err, results){ if (err) throw err; console.log(results); var poll = []; for (var i in results){ for (var j in results[i]){ poll.push(results[i][j]); } } connection.query("SELECT quest FROM home WHERE author = ?", [res.locals.currentUser], function (err, results){ if (err) throw err; console.log(results); var quest = []; for (var i in results){ for (var j in results[i]){ quest.push(results[i][j]); } } app.locals.poll = poll; console.log(app.locals.poll); app.locals.quest = quest; console.log(app.locals.quest); connection.release(); res.render('mypolls'); }); }); }); }); app.get("/newpoll", function(req, res) { console.log(req); res.locals.isLogged = req.isAuthenticated(); res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); res.render("newpoll"); }); app.post("/newpoll", function (req,res){ console.log(req); res.locals.isLogged = req.isAuthenticated(); res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); console.log(req.body.options); var title = req.body.title; console.log(title); var trim = req.body.options.replace(/ /g,''); var options = trim.split(","); console.log(options); var pollid = rand(); var create = 'CREATE TABLE ' + pollid + ' (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, question varchar(255), author varchar(255)'; var theend = ') DEFAULT CHARACTER SET utf8 ENGINE=InnoDB'; var opt = ""; for (var i=0;i<options.length;i++){ opt += ',' + '`' + options[i] + '`' + ' int(11) DEFAULT 0'; } var merge = create+opt+theend; db.getConnection(function(err, connection) { if (err) throw err; connection.query(merge, function (err, results){ if (err) throw err; console.log(results); connection.query("INSERT INTO home (tabname,quest,author) VALUES (?,?,?)", [pollid, title, res.locals.currentUser], function (err, results){ if (err) throw err; console.log(results); connection.query("INSERT INTO ?? (??,??) VALUES (?,?)", [pollid, 'question','author', title, res.locals.currentUser], function (err, results){ if (err) throw err; console.log(results); connection.release(); }); }); }); res.redirect(pollid); }); }); app.post("/delete", function(req, res) { console.log(req); var strip = req.headers.referer.substr(req.headers.referer.lastIndexOf('/') + 1); console.log(strip); res.locals.isLogged = req.isAuthenticated(); res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); db.getConnection(function(err, connection) { if (err) throw err; connection.query("DROP TABLE ??", [strip], function (err, results){ if (err) throw err; console.log(results); connection.query("DELETE FROM home WHERE tabname = ?", [strip], function (err, results){ if (err) throw err; console.log(results); }); }); connection.release(); res.redirect("mypolls"); }); }); app.post("/:id", function(req, res) { console.log(req); res.locals.isLogged = req.isAuthenticated(); if (res.locals.isLogged){ res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); } var pollid = req.params.id; var key = Object.keys(req.body)[0]; console.log(key); var val = req.body[key]; console.log(val); var param = [pollid, val, val]; db.getConnection(function(err, connection) { if (err) throw err; connection.query("UPDATE ?? SET ?? = ?? + 1", param, function (err, results){ if (err) throw err; console.log(results); connection.release(); res.redirect(pollid); }); }); }); app.get("/:id", function(req, res) { console.log(req); var id = req.params.id; console.log(id); console.log(req.body); res.locals.isLogged = req.isAuthenticated(); if (res.locals.isLogged){ res.locals.currentUser = req.user.displayName; console.log(res.locals.currentUser); } db.getConnection(function(err, connection) { if (err) throw err; connection.query("SELECT column_name FROM information_schema.columns WHERE table_name=?", [id], function (err, results){ var arrKeys = []; var sortingArr = []; if (err) throw err; for (var i in results){ for (var j in results[i]){ arrKeys.push(results[i][j]); sortingArr.push(results[i][j]); } } arrKeys.splice(0, 3); res.locals.arrKeys = arrKeys; connection.query("SELECT * FROM ??",[id] , function (err, results){ if (err) throw err; var arrOfObjects = results; res.locals.array = []; res.locals.nullarr = []; for (var i in results[0]){ if (results[0][i]!== 0){ res.locals.array.push(results[0][i]); } else{ res.locals.nullarr.push(results[0][i]); } } var sortedArr = []; arrOfObjects.forEach(function(obj) { sortingArr.forEach(function(k) { sortedArr.push(obj[k]); }); }); console.log(sortedArr); sortedArr.splice(0,3); res.locals.arrVals = sortedArr; connection.query("SELECT question FROM ??", [id], function (err, result){ if (err) throw err; for (var i in result){ for (var j in result[i]){ res.locals.que = result[i][j]; } } connection.query("SELECT author FROM home WHERE tabname=?",[id] , function (err, results){ if (err) throw err; var author = results[0].author; res.locals.author = author; console.log(author); connection.release(); res.render("poll"); }); }); }); }); }); }); app.use(function (req, res, next) { res.status(404); res.send('404: Page not found!'); }); app.use(function(err, req, res, next) { console.error(err); res.status(500).send({status:500, message: 'internal error', type:'internal'}); }); app.listen(process.env.PORT || 5000); console.log("Server running at http://localhost:5000/");
const { Pet } = require('../src/pet.js'); it('returns an objct', () => { expect(new Pet('Fido')).toBeInstanceOf(Object); }); it('Should create a new Pet with a name when called', () => { const cat = new Pet('Oscar'); expect(cat.name).toBe('Oscar'); }); describe('Growing up!', () => { let pet; beforeEach(() => { pet = new Pet('Logan'); }); it('growUp method should increase age by one', () => { pet.growUp(); expect(pet.age).toBe(1); }); }); describe('Gettting older and Unhealthy!', () => { let pet; beforeEach(() => { pet = new Pet('Logan'); }); it('growUp method should increase hunger by 5', () => { expect(pet.hunger).toBe(0); pet.growUp(); expect(pet.hunger).toBe(5); pet.growUp(); expect(pet.hunger).toBe(10); }); it('growUp method should decrease fitness by 3', () => { expect(pet.fitness).toBe(10); pet.growUp(); pet.feed(); expect(pet.fitness).toBe(7); pet.growUp(); pet.feed(); expect(pet.fitness).toBe(4); pet.growUp(); }); }); describe('Keeping Fit', () => { let pet; beforeEach(() => { pet = new Pet('Logan'); pet.growUp(); pet.feed(); pet.growUp(); }); it('should increase the fitness by 4', () => { expect(pet.fitness).toBe(4); pet.walk(); expect(pet.fitness).toBe(8); }); it('should not exceed fitness property by 10', () => { expect(pet.fitness).toBe(4); pet.walk(); pet.walk(); pet.walk(); expect(pet.fitness).toBe(10); }); }); describe('don\'t let me starve!', () => { let pet; beforeEach(() => { pet = new Pet('Logan'); }); it('hunger level goes down everytime we feed', () => { expect(pet.hunger).toBe(0); pet.growUp(); // cause the pet to need food! expect(pet.hunger).toBe(5); pet.feed(); // decrease hunger -> by 3 expect(pet.hunger).toBe(2); }); describe('Pets hunger can\'t go below zero', () => { let pet; beforeEach(() => { pet = new Pet('Logan'); }); it('can\'t go below zero', () => { pet.growUp(); pet.feed(); pet.growUp(); pet.feed(); pet.feed(); pet.feed(); pet.feed(); expect(pet.hunger).toBe(0); }); }); }); describe('Check-Up! - How are you feeling?', () => { let pet; beforeEach(() => { pet = new Pet('Logan'); }); it('checks levels of the pet.', () => { pet.growUp(); expect(pet.checkUp()).toEqual('I am hungry'); pet.feed(); pet.growUp(); expect(pet.checkUp()).toEqual('I am hungry'); pet.feed(); pet.growUp(); expect(pet.checkUp()).toEqual('I am hungry AND I need a walk'); }); it('checks if the pet is ok!', () => { expect(pet.checkUp()).toEqual('I feel great!'); }); }); describe('Are you alive! - \'getter\'', () => { let pet; beforeEach(() => { pet = new Pet('Logan'); }); it('isAlive is a property should be true if the pet is alive!', () => { expect(pet.isAlive).toBe(true); }); it('if we grow and don\'t feed we die', () => { pet.growUp(); pet.growUp(); expect(pet.isAlive).toBe(false); }); it('if we grow and don\'t walk we die', () => { pet.growUp(); pet.feed(); pet.growUp(); pet.feed(); pet.growUp(); pet.feed(); pet.growUp(); expect(pet.isAlive).toBe(false); }); it('if we grow too old we die', () => { pet.age = 29; expect(pet.isAlive).toBe(true); pet.growUp(); expect(pet.isAlive).toBe(false); }); }); describe('Guarding - Error checks', () => { let pet; beforeEach(() => { pet = new Pet('Oscar'); pet.hunger = 10; pet.fitness = 0; pet.age = 30; }); test('dead pet -> checkUp() should return :x !', () => { expect(pet.checkUp()).toBe('Your pet is no longer alive :('); }); test('dead pet -> walk() shouldn\'t work', () => { expect(pet.walk).toThrow('Your pet is no longer alive :('); }); test('dead pet -> feed() shouldn\'t work', () => { expect(pet.feed).toThrow('Your pet is no longer alive :('); }); test('dead pet -> growUp() shouldn\'t work', () => { expect(pet.growUp).toThrow('Your pet is no longer alive :('); }); }); describe('Children->?!', () => { let baby, pet; beforeEach(() => { pet = new Pet('Oscar'); baby = new Pet('Lulu'); }); test('can you adopt :)', () => { expect(baby.name).toBe('Lulu'); pet.adoption(baby); expect(pet.children).toContain(baby); expect(pet.children[0].name).toBe('Lulu'); }); });
const { Client, Message, MessageEmbed, MessageActionRow, MessageSelectMenu, } = require("discord.js"); const { oneLine } = require("common-tags"); const fs = require("fs"); const BoltyUtil = require("../../classes/BoltyUtil"); /** * * @param {Client} client * @param {Message} message * @param {String[]} args */ module.exports.run = async (client, message, args) => { const categories = fs.readdirSync("./commands/"); categories.forEach((category) => { const dir = client.commands.filter( (c) => c.help.category.toLowerCase() === category.toLowerCase() ); const capitalise = category.slice(0, 1).toUpperCase() + category.slice(1); }); const formatString = (str) => `${str[0].toUpperCase()}${str.slice(1).toLowerCase()}`; }; module.exports.help = { name: "", description: "", aliases: [""], usage: "", category: "", cooldown: "", };