text
stringlengths
7
3.69M
function ReadMessages(props) { return <div>Read messages here</div>; } export default ReadMessages;
// get access to another 2 other function tat I wrote: // Separation is for convenience... var imgAccess = require('../data/imgAccess/imgRetriever'); var util = require('../util/ExtractFilePath'); var fs = require('fs'); // Basicly GetRandomImage is a function that use the above function that I expliend above. // They are supused to read the dir (where the images) and list them and finaly return a Random image path. function GetRandomImage() { var files = imgAccess.GetImage(); var filePath = util.ExtractFilePath(files); return (filePath); } module.exports= { GetRandomImage:GetRandomImage }
import React from 'react'; import { Redirect } from 'react-router-dom'; class Dashboard extends React.Component { constructor(props) { super(props); this.state = { isGetLogClicked: false } this.handleGetLog = this.handleGetLog.bind(this) } handleLogout() { localStorage.clear(); window.location.href = "/login"; } handleGetLog() { this.setState({ isGetLogClicked: true }); } componentDidMount() { let username = (this.props.location.state) ? this.props.location.state.username : ''; console.log("Mounting Dashboard... with username " + username) } render() { let username = ( this.props.location.state) ? this.props.location.state.username : ''; return ( < div > <h1>WELCOME TO DASHBOARD {username}</h1> <button onClick={this.handleLogout} className="btn"> <i className="ti-power-off mR-10"></i> <span style={{ color: "Black" }}>Logout</span> </button> {(this.state.isGetLogClicked) ? <Redirect to={{ pathname: "/getlog", state: { username: username } }} /> : <button onClick={this.handleGetLog} className="btn"> <i className="ti-power-off mR-10"></i> <span style={{ color: "Black" }}>Getlog</span> </button>} </div > ); } } export default Dashboard;
angular.module('tripEdit', []);
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import SimpleAppBar from './Appbar' import * as V from 'victory'; import { VictoryChart, VictoryLine, VictoryTheme, VictoryAxis } from 'victory'; import Paper from '@material-ui/core/Paper'; import Typography from '@material-ui/core/Typography'; var generaldata = require('./backend/tst.json') class App extends Component { constructor(props){ super(props); this.state={ waterData:[ ], savingData:[ ], waterNow: 0, } } componentDidMount(){ var waterList = [] var savingList =[] console.log(generaldata.agua[0]) for(var i=0; i<generaldata.agua.length; i++){ waterList.push(generaldata.agua[i]) savingList.push(generaldata.dinheiro[i]) } this.setState({waterData: waterList}) this.setState({savingData: savingList}) this.setState({waterNow: generaldata.atual}) } render() { return ( <div className='wp'> <div className="wrapper"> <header className="header"> <SimpleAppBar/> </header> <article className="main"> <p>Esses são os gráficos relativos ao consumo e ao dinheiro economizado, respectivamente.</p> <div className="container"> <div className="item1"> Consumo Total: <VictoryChart theme={VictoryTheme.material}> <VictoryAxis dependentAxis label="Litros (10^3)" style={{ axisLabel: {fontSize: 15, padding:35} }}/> <VictoryAxis label="Dia" style={{ axisLabel: {fontSize: 15, padding:30} }} /> <VictoryLine data={this.state.waterData}/> </VictoryChart> </div> <div className="item2"> Economia Total: <VictoryChart theme={VictoryTheme.material}> <VictoryAxis dependentAxis label="Reais" style={{ axisLabel: {fontSize: 15, padding:35} }}/> <VictoryAxis label="Dia" style={{ axisLabel: {fontSize: 15, padding:30} }} /> <VictoryLine data={this.state.savingData}/> </VictoryChart> </div> </div> </article> <footer className="footer" style={{display:'flex', justifyContent:'center', alignItems:'center'}}> <Paper style={{display: 'flex', height: '6vh', width: '35vh', alignSelf: 'center', backgroundColor: '#4EB1BA', justifyContent:'center', alignItems:'center'}}> <Typography style={{color: '#E9E9E9', alignSelf: 'center', fontSize: '15px'}}> Quantidade de água disponível: {this.state.waterNow}L </Typography> </Paper> </footer> </div> </div> ); } } export default App;
//若一隻兔子每月生一隻兔子,一個月後小兔子也開始生產。起初只有一隻兔子,一個月後有兩隻兔子,兩個月後有三隻兔子,三個月後有5隻兔子,以此類推 //每個月兔子總數為1.1.2.3.5.8.13.21.34.55.89....費式數列 //公式如下: //fn = fn-1 +fn-2 if n > 1 //fn = n if n=0,1 //撰寫20個費式數列 let result = []; for (let i = 0; i < 20; i++) { if (i == 0 || i == 1) { result.push(1); } else { result.push(result[i - 1] + result[i - 2]); } } console.log(result);
function openTab() { var links = document.getElementsByTagName("a"); for (var i = 0; i < links.length; i++) { if(links[i].getAttribute("class") == "popup") { links[i].onclick = function() { popUp(this.getAttribute("href")); return false; } } } } function popUp(url) { window.open(url, "nuovaFinestra"); } function addDayColor() { var date = new Date(); var day = date.getDay(); if (day>0 && day<6) { var weekday=new Array(6); weekday[1]="mon"; weekday[2]="tue"; weekday[3]="wed"; weekday[4]="thu"; weekday[5]="fri"; var element = document.getElementById(weekday[day]); element.setAttribute("class", 'current_day'); }; } function replaceMap() { var map = document.getElementById('mapVisualization'); map.innerHTML = "<iframe class='stampano' id='Gmap_frame' src='https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d1400.460291941266!2d11.889645!3d45.410941!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x2c00159331ead3d8!2sRistorEsu+Nord+Piovego!5e0!3m2!1sit!2sit!4v1394028372446'></iframe><img id=\"Gmap\" class=\"stampasi\" src=\"images/map_mobile.png\" alt=\"Mappa raffigurante la posizione della mensa Piovego.\" />"; } function checkEmail(lang) { var string = document.getElementById("email").value; var errorMessage = document.getElementById("emailErrors"); var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (regex.test(string)) { errorMessage.innerHTML = ""; return true; } else { if (lang=="ita") { errorMessage.innerHTML = "La mail non è corretta"; } else { errorMessage.innerHTML = "Please check your mail address"; } return false; }; } function checkName(lang) { var string = document.getElementById("nome").value; var errorMessage = document.getElementById("nameErrors"); if (string.length < 2) { if (lang=="ita") { errorMessage.innerHTML = "Inserire un nome con almeno due caratteri"; } else { errorMessage.innerHTML = "Insert a name with at least two characters"; } return false; } else { if (string.length > 64) { if (lang=="ita") { errorMessage.innerHTML = "Il nome e' troppo lungo"; } else { errorMessage.innerHTML = "The name is too long"; } return false; } else { errorMessage.innerHTML = ""; return true; } }; } function checkComment(lang) { var string = document.getElementById("comment_text").value; var errorMessage = document.getElementById("commentErrors"); if (string.length < 2) { if (lang=="ita") { errorMessage.innerHTML = "Inserire un commento con almeno due caratteri"; } else { errorMessage.innerHTML = "Insert a comment with at least two characters"; } return false; } else { if (string.length > 2048) { if (lang=="ita") { errorMessage.innerHTML = "Il commento ha troppi caratteri"; } else { errorMessage.innerHTML = "The comment is too long"; } return false; } else { errorMessage.innerHTML = ""; return true; } }; } function completeCheck(lang) { var button = document.getElementById("submit_button"); button.disabled = true; var check1 = checkName(lang); var check2 = checkEmail(lang); var check3 = checkComment(lang); if (check1 && check2 && check3) { return true; } else { button.disabled = false; return false; } } function resetErrors() { var errorMessage1 = document.getElementById("emailErrors"); var errorMessage2 = document.getElementById("nameErrors"); var errorMessage3 = document.getElementById("commentErrors"); errorMessage1.innerHTML = ""; errorMessage2.innerHTML = ""; errorMessage3.innerHTML = ""; }
import GalleryItem from '../GalleryItem/GalleryItem.jsx'; function GalleryList({ gallery, addLikes }) { return ( <div> {' '} {gallery.map((pic, index) => { return <GalleryItem pic={pic} key={index} addLikes={addLikes} />; })} </div> ); } export default GalleryList;
/* MooFlow Viewer (extra JS MooFlowViewer.js) * v0.1dev useViewer:true */ MooFlow.implement({ attachViewer: function(){ return this; }, flowStart: function(){ this.hideIcon(); }, flowComplete: function(){ this.createIconTip(); }, createIconTip: function(){ var cur = this.getCurrent(); if(!$chk(cur.rel)||!$chk(cur.href)) return; this.tipFx = new Fx({link:'cancel'}); if(!$chk(this.icon)) { this.icon = new Element('a').addClass('show').setStyles({'display':'none','opacity':'0'}).inject(this.MooFlow); } this.icon.addEvent('click', this.onClickView.bind(this, cur)); this.icon.addEvent('mouseenter', this.showTip.bind(this, cur)); this.icon.addEvent('mouseleave', this.hideTip.bind(this, cur)); this.icon.addClass(cur.rel.toLowerCase()); this.icon.setStyle('display','block').fade(0.6); }, showTip: function(cur){ if (cur.alt) { this.cap.innerHTML = cur.alt; } }, hideTip: function(cur){ this.cap.innerHTML = cur.title; }, hideIcon: function(){ if($chk(this.icon) && $chk(this.icon.getParent())) this.icon.destroy(); if($chk(this.tip) && $chk(this.tip.getParent())) this.tip.destroy(); this.icon = this.tip = null; }, onClickView: function(cur){ switch (cur.rel.toLowerCase()){ case 'image': this.loadImage(cur); break; case 'link': window.open(cur.href, cur.target || '_blank'); break; default: } }, loadImage: function(cur){ this.icon.removeClass('image').addClass('viewerload'); this.image = new Asset.image(cur.href, {onload: this.showImage.bind(this)}); }, showImage: function(){ var cur = this.getCurrent(); var c = cur.con.getFirst().getCoordinates(); this.image.inject(document.body); this.image.addEvent('click', this.hideImage.bind(this)); this.image.setStyles({'left':c.left,'top':c.top,'width':c.width,'height':c.height,'position':'absolute','z-index':'103'}); var imageFx = new Fx.Morph(this.image, {transition: Fx.Transitions.Sine.easeOut}); var to = {x: this.image.get('width'), y: this.image.get('height')}; //var box = document.getSize(), scroll = document.getScroll(); //var pos = {x: scroll.x + ((box.x - to.x) / 2).toInt(), y: scroll.y + ((box.y - to.y) / 2).toInt() }; var pos = {x:c.left - (to.x - c.width) / 2, y:c.top - (to.y - c.height) / 2}; var vars = {left: pos.x, top: pos.y, width: to.x, height: to.y}; imageFx.start(vars); }, hideImage: function(){ this.icon.removeClass('viewerload').addClass('image'); this.image.dispose(); } });
import React, { Component,PropTypes } from 'react' import NodeIcon from './NodeIcon' export default class TreeNode extends Component { constructor(props) { super(props) this.state={ expanded:false, selected: props.selected ? props.selected : 'none', length: props.data.childs ? props.data.childs.length : 0, allCount: 0, partCount: 0, target: 'parent' } } componentWillReceiveProps = (nextProps) => { if (nextProps.selected === this.state.selected) { return } if (nextProps.target === 'parent') { const allCount = nextProps.selected ==='all' ? this.state.length : 0 this.setState({ selected: nextProps.selected, allCount, target: 'parent', partCount: 0, }) } } handleClick = () => { const { expanded } = this.state this.setState({ expanded: !expanded }) } triggerSelected = (selected) => { const { maxDepth, length, onChange, data, depth, onParentChange, } = this.props if (depth === maxDepth) { onChange(selected, data.value) }else { onParentChange(selected,depth,data) } } handleSelected = () => { const { triggerParentSelected } = this.props const { length, selected, }=this.state const nextSelected = selected === 'all' ? 'none' : 'all' const count = selected ==='all' ? 0 : length this.setState({ selected: nextSelected, target: 'parent', allCount: count, partCount: 0, },() => { this.triggerSelected(this.state.selected) if (triggerParentSelected) { triggerParentSelected(selected,nextSelected) } }) } triggerParentSelected = (childsSelected, childsNexSelected) => { const { length, allCount, partCount, selected, } = this.state let nextAllCount = allCount; let nextPartCount = partCount; const { triggerParentSelected } = this.props if (childsNexSelected === 'all') { nextAllCount ++ } if (childsSelected === 'all') { nextAllCount -- } if (childsNexSelected === 'part') { nextPartCount ++ } if (childsSelected === 'part') { nextPartCount -- } let nextSelected = 'none' if (nextAllCount === length) { nextSelected = 'all' }else if(nextAllCount + nextPartCount > 0) { nextSelected = 'part' } this.setState({ allCount: nextAllCount, partCount: nextPartCount, selected: nextSelected, target: 'self', }, () => { if (triggerParentSelected) { triggerParentSelected(selected, this.state.selected) } }) } render() { const { data, depth, maxDepth, onParentChange, onChange, } = this.props const { expanded, target, allCount, partCount, selected, } = this.state const { name, childs, } = data const styles = { paddingLeft: `${depth * 15}px`, } const childsStyle = { display: expanded ? 'block' : 'none', } return( <div> <div style={styles}> <NodeIcon selected={selected} onClick={this.handleSelected} /> <span onClick={this.handleClick}>{name} {allCount} : {partCount}}</span> </div> <div style={childsStyle}> { childs && childs.map((child,index) => ( <TreeNode data={child} maxDepth={maxDepth} depth={depth+1} key={index} target={target} triggerParentSelected={this.triggerParentSelected} onParentChange={onParentChange} onChange={onChange} selected={selected} /> )) } </div> </div> ) } } TreeNode.propTypes = { maxDepth: PropTypes.number, depth: PropTypes.number, data: PropTypes.object, }
class Herois{ constructor(array){ this.herois = array; } }
"use strict"; var SCORE = new (function() { var _self = this; var _elem = null; var _score = 0; var _isAnimating = false; // Private Functions function _showScore(num) { _elem.innerHTML = num || _score; } function _getShownScore() { return Number(_elem.innerText); } function _addScoreAnimated() { setTimeout(function () { if (!_isAnimating) return; var shownScore = _getShownScore(); _showScore(++shownScore); if (shownScore === _score) { _isAnimating = false; return; } _addScoreAnimated(); }, 10); } // Public Functions this.init = function() { _elem = document.getElementById("game-points-num"); }; this.add = function (num) { _score += num; if (_isAnimating) return; _isAnimating = true; _addScoreAnimated(); }; this.reset = function () { _isAnimating = false; _score = 0; _showScore(); }; this.get = function () { return _score; }; })();
let apimessages; try { apimessages = require("../setup/apimessages.project.config.js"); } catch(e){ console.log("Unable to load apimessages.project.config.js"); apimessages = require("../setup/apimessages.config.js"); } finally { if(Object.keys(apimessages).length === 0){ apimessages = require("../setup/apimessages.config.js"); } } module.exports = apimessages;
import { ChainIterator } from "."; export class FilterIterator extends ChainIterator { next() { let result; while (!(result = this.parent.next()).done) { if (this.fun(result.value, result.key)) { break; } } return result; } } export class FlipIterator extends ChainIterator { next() { const result = this.parent.next(); if (!result.done) { const { key, value } = result; result.key = this.fun(value, key); result.value = key; } return result; } }
const db = require("../database/config.js"); const Data_Sensor = require("../models/data_sensor"); const List_Alat = require("../models/list_alat"); const Report = require("../models/report"); List_Alat.hasMany(Data_Sensor, { as: "Data_Sensor1", foreignKey: "listAlatId", }); Data_Sensor.belongsTo(List_Alat, { as: "List_Alat1", foreignKey: "listAlatId", }); List_Alat.hasMany(Report, { as: "Report1", foreignKey: "listAlatId" }); Report.belongsTo(List_Alat, { as: "List_Alat1", foreignKey: "listAlatId" }); async function ConvertToMonthly() { const ID = await Report.findAll({ attributes: [[db.fn("DISTINCT", db.col("listAlatId")), "id"]], raw: true, }); for (let i = 0; i < ID.length; i++) { const data = await Report.findAll({ where: { listAlatId: ID[i].id, }, raw: true, }); // console.log(data); let data_weekly = data.filter((x) => x.tag == "weekly"); if (data_weekly.length == 4) { await Report.destroy({ where: { tag: "weekly", listAlatId: ID[i].id, }, raw: true, }); let report_monthly = { temp_avg: avg(data_weekly, "temp_avg"), temp_min: min(data_weekly, "temp_min"), temp_max: max(data_weekly, "temp_max"), ppg_avg: avg(data_weekly, "ppg_avg"), ppg_min: min(data_weekly, "ppg_min"), ppg_max: max(data_weekly, "ppg_max"), ekg_avg: avg(data_weekly, "ekg_avg"), ekg_min: min(data_weekly, "ekg_min"), ekg_max: max(data_weekly, "ekg_max"), nivac_avg: avg(data_weekly, "nivac_avg"), nivac_min: min(data_weekly, "nivac_min"), nivac_max: max(data_weekly, "nivac_max"), tag: "monthly", listAlatId: ID[i].id, }; await Report.create(report_monthly); } // console.log("data dengan tag daily:", data_daily); } } module.exports = ConvertToMonthly; function min(object, property) { let baru = object.map((x) => { // console.log(x[property]); let temp = { [property]: x[property], }; return temp[property]; }); // console.log(baru); let min = Math.min.apply(Math, baru); return min; } function max(object, property) { let baru = object.map((x) => { // console.log(x[property]); let temp = { [property]: x[property], }; return temp[property]; }); // console.log(baru); let max = Math.max.apply(Math, baru); return max; } function avg(object, property) { let baru = object.map((x) => { // console.log(x[property]); let temp = { [property]: x[property], }; return temp[property]; }); let sum = baru.reduce((total, value) => { return total + value; }); const count = baru.length; let result = sum / count; return Number(result.toFixed(2)); }
import bcrypt from 'bcrypt' import jwt from 'jsonwebtoken' import User from '../models/user' import config from '../config/main' const saltRounds = 10 const userRegister = async (req, res, next) => { const formData = req.body // Verify Duplicate email let user try { user = await User.findOne({ email: formData.email }) if(user) { return res.status(403).json({ success: false, message: 'Duplicate email', location: 'VALIDATE_DUPLICATE_USER', }) } } catch (error) { console.error('err validataion', error) return res.status(400).json({ success: false, message: "Server Error, Please Try Again.", location: 'VALIDATE_DUPLICATE_USER' }) } // create new user try { // hash password const hashPassword = await bcrypt.hash(formData.password, saltRounds) user = await User.create({ email: formData.email, password: hashPassword, active: true }) } catch (error) { console.error('error creating user', error) res.status(400).json({ success: false, message: "Server Error, Please Try Again.", location: 'CREATE_USER' }) return } console.log('USER CREATED') res.status(201).json({ success: true, message: 'user created' }) } //login Routes const userLogin = async (req, res, next) => { const { email, password } = req.body let user try { user = await User.findOne({ email }) if (!user) { return res.status(401).json({ success: false, message: 'Authorization Fail', location: 'USER_LOGIN' }) } if (!user.active) { return res.status(401).json({ success: false, message: 'Authorization Fail', location: 'USER_LOGIN' }) } } catch (error) { return res.status(401).json({ success: false, message: 'Server Error: ' + error.message, location: 'USER_LOGIN' }) } // compare password const isMatch = await bcrypt.compare(password, user.password) if (!isMatch) { return res.status(401).json({ success: false, message: 'Authorization Fail', location: 'USER_LOGIN' }) } const payload = { _id: user._id, username: user.email } // create a token const token = jwt.sign(payload, config.secret, { expiresIn: "1h" }) return res.status(200).json({ success: true, message: 'Login Success', data: { token, user: payload } }) } export { userRegister, userLogin, }
$(function(){ var time =$('#time').val(); if(time==''||time<=0){ $('.day').html('--'); $('.hour').html('--'); $('.min').html('--'); $('.sec').html('--'); alert("下一期未开始,请等待。。。"); }else{ showCountDown(time, $(".day"), $(".hour"), $(".min"), $(".sec"), function(){ alert("当前期已结束"); window.location.reload(); }); } var playCode =$('#playCode').val(); getNews(playCode); getAwardInfo(playCode); }); function getNews(playCode){ var newsType =1;//公告 var pageRow =5; var pageNum =1; $.ajax({ type: "POST", url: "/getLotteryNews.htm", data:"newsType="+newsType+"&pageRow="+pageRow+"&pageNum="+pageNum+"&playCode="+playCode, dataType: "json", success: function(msg){ var news =""; for(var i in msg){ news+="<li><a href=\"/info/info_detail.htm?newsId="+msg[i].newsId+"\" target=\"_blank\" >"+msg[i].shortTitle+"</a></li>"; } $('.info2').children('ul').html(news); } }); } function getAwardInfo(playCode){ var pageRow =10; var pageNum =1; $.ajax({ type: "POST", url: "/award/getAwardResult.htm", data:"pageRow="+pageRow+"&pageNum="+pageNum+"&playCode="+playCode, dataType: "json", success: function(msg){ var first =msg[0]; var lis =$('.award1').children('li'); lis.eq(0).html(first.issueNo+"期"); lis.eq(1).html(first.luckNum); lis.eq(2).html("开奖时间:"+first.awardTime); var result =""; for(var i in msg){ if(i>0){ result+="<li>"+msg[i].issueNo+"期&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>"+msg[i].luckNum+"</em></li>" } } $('.award2').html(result); } }); }
import React, { memo, useState } from "react"; import { StyleSheet, Text } from "react-native"; import Background from "../components/Background"; import Header from "../components/Header"; import Button from "../components/Button"; import TextInput from "../components/TextInput"; import { theme } from "../utility/theme"; import { usernameValidator, surnameValidator, passwordValidator, nameValidator, } from "../utility/utils"; import { useRegistration } from "../hooks/useRegistration"; const RegisterScreen = ({ navigation }) => { const [name, setName] = useState({ value: "", error: "" }); const [surname, setSurname] = useState({ value: "", error: "" }); const [username, setUsername] = useState({ value: "", error: "" }); const [password, setPassword] = useState({ value: "", error: "" }); const { isLoading, doRegistration, error, outcome } = useRegistration(); const _onSignUpPressed = () => { const nameError = nameValidator(name.value); const surnameError = surnameValidator(surname.value); const usernameError = usernameValidator(username.value); const passwordError = passwordValidator(password.value); if (usernameError || passwordError || nameError || surnameError) { setName({ ...name, error: nameError }); setSurname({ ...surname, error: surnameError }); setUsername({ ...username, error: usernameError }); setPassword({ ...password, error: passwordError }); return; } doRegistration(name, surname, username, password); }; return ( <Background> <Header>Registrazione</Header> <TextInput label="Nome" returnKeyType="next" value={name.value} onChangeText={(text) => setName({ value: text, error: "" })} error={!!name.error} errorText={name.error} /> <TextInput label="Cognome" returnKeyType="next" value={surname.value} onChangeText={(text) => setSurname({ value: text, error: "" })} error={!!surname.error} errorText={surname.error} /> <TextInput label="Username" returnKeyType="next" value={username.value} onChangeText={(text) => setUsername({ value: text, error: "" })} error={!!username.error} errorText={username.error} /> <TextInput label="Password" returnKeyType="done" value={password.value} onChangeText={(text) => setPassword({ value: text, error: "" })} error={!!password.error} errorText={password.error} secureTextEntry /> {outcome ? ( <Button mode="contained" onPress={() => navigation.navigate("LoginScreen")} style={styles.button} loading={isLoading} > Vai al login </Button> ) : ( <Button mode="contained" onPress={_onSignUpPressed} style={styles.button} > Registrati </Button> )} {outcome ? <Text style={styles.outcome}>{outcome}</Text> : null} {error ? <Text style={styles.error}>{error}</Text> : null} </Background> ); }; const styles = StyleSheet.create({ label: { color: theme.colors.secondary, }, button: { marginTop: 24, }, row: { flexDirection: "row", marginTop: 4, }, error: { margin: 20, color: theme.colors.error, fontWeight: "bold", }, outcome: { margin: 20, color: theme.colors.success, fontWeight: "bold", }, }); export default memo(RegisterScreen);
'use strict' // TODO: consider implementing browser metrics let metrics = null module.exports = function () { return metrics || (metrics = { // cache the metrics instance start: () => {}, stop: () => {}, track () { return { finish: () => {} } }, boolean () {}, histogram () {}, count () {}, gauge () {}, increment () {}, decrement () {} }) }
const AWS = require('aws-sdk'); const s3 = new AWS.S3({apiVersion: '2006-03-01'}); const fs = require('fs') const path = require('path'); const invalidateCache = require('../cache/invalidateCache') function scanFiles(dir){ let arrs = []; return new Promise(async (resolve, reject) => { scanDir(dir, (filePath, stat) => arrs.push(filePath)) resolve(arrs) }) } function scanDir(currentDirPath, callback) { var gitignore = fs.existsSync('.gitignore')? fs.readFileSync('.gitignore', 'utf8'): null var torusignore = fs.existsSync('.torusignore')? fs.readFileSync('.torusignore', 'utf8'): null var ignorePaths = {} if(gitignore && gitignore.length > 0) for(let path of gitignore.split('\n')) if(path.trim().length > 1) ignorePaths[path.trim()] = true if(torusignore && torusignore.length > 0) for(let path of torusignore.split('\n')) if(path.trim().length > 1) ignorePaths[path.trim()] = true fs.readdirSync(currentDirPath).forEach((name)=>{ var filePath = path.join(currentDirPath, name); var stat = fs.statSync(filePath); if(!ignorePaths[filePath]) { if (stat.isFile()) callback(filePath, stat); else if (stat.isDirectory()) scanDir(filePath, callback) } }); } /* function createFile(filePath, contents){ return new Promise((resolve, reject) => { if(fs.existsSync(filePath)) fs.promises.readFile(filePath, 'utf8').then(data => resolve(data)).catch(err => reject(err)) else { fs.promises.writeFile(filePath, contents) .then(() => resolve(contents)) .catch(err => reject(err)) } }) } */ function getFiles(root, path){ return new Promise((resolve, reject) => { if(!path && root) path = root if(!path || path === '*' || path === '/') scanFiles('./').then(files=>resolve(files)).catch(err=>reject(err)) else { var stat = fs.statSync(path) if(stat.isFile()) resolve([path]) else if(stat.isDirectory()) { scanFiles(path).then(files=>resolve(files)) .catch(err=>reject(err)) } else reject('path doesnt exist') } }) } function upload(bucketName, filePath, root) { return new Promise((resolve, reject) => { let ext = filePath.substring(filePath.lastIndexOf('.') + 1); let content_type = ''; let keyPath = filePath; //console.log('keyPATH ', keyPath) if(root) keyPath = keyPath.substr(root.length+1, keyPath.length) //console.log('CORRECTED_KEYPATH ', keyPath) if(ext =='svg') content_type = 'image/svg+xml' else if(ext =='jpg' || ext =='jpeg') content_type = 'image/jpeg' else if(ext =='png') content_type = 'image/png' else if(ext =='html') content_type = 'text/html' else if(ext =='css') content_type = 'text/css' else if(ext =='js') content_type = 'application/javascript' else if(ext =='txt') content_type = 'text/plain' else if(ext =='xml') content_type = 'text/xml' else if(ext =='mp4') content_type = 'video/mp4' let params = { Bucket: bucketName, Key: keyPath, Body: fs.readFileSync(filePath), ContentType: content_type }; //console.log(params.Key) s3.putObject(params).promise().then(()=>resolve(keyPath)) .catch(err => reject(err)) }) } function uploadFiles(domain, files, purge, updates, dir, cli){ return new Promise((resolve, reject) => { let customBar = cli? cli.progress({ barCompleteChar: '\u2588', barIncompleteChar: '\u2591', format: 'Uploading | \x1b[32m{bar}\x1b[0m | Files: {value}/{total} | ETA: {eta}s' }) : null let num = 0 let updated_files = [] let cached_files = [] let new_config = {} let local_config = fs.existsSync('./torus/uploads.json')? JSON.parse(fs.readFileSync('./torus/uploads.json', 'utf8')):{} for(let path of files) { new_config[path] = {updated:fs.statSync(path).mtimeMs, uploaded:null} if(local_config[path]){ if(new_config[path].updated > local_config[path].uploaded){ if(local_config[path].uploaded) cached_files.push(path) local_config[path].updated = new_config[path].updated updated_files.push(path) } } else { local_config[path] = new_config[path] updated_files.push(path) } } let upload_files = updates?updated_files:files let invalidate_files = updates?cached_files:files //console.log(upload_files) //console.log(invalidate_files) if(upload_files.length > 0){ if(cli) customBar.start(upload_files.length, 0, {speed: "N/A"}); for(let f in upload_files){ upload(domain, upload_files[f], dir).then(data => { cli? customBar.update(num+=1): console.log('uploaded '+ filepath) local_config[upload_files[f]].uploaded = new Date().getTime() if(num>=upload_files.length){ customBar.stop() fs.writeFileSync('./torus/uploads.json', JSON.stringify(local_config), 'utf8') if(purge && invalidate_files.length > 0){ cli?cli.action.start('Invalidating Cache'):console.log('Invalidating Cache . . .') invalidateCache.aws(domain, invalidate_files).then(()=>{ cli.action.stop() resolve('All Done!') }).catch(err=>reject(err)) } else resolve('All Done!') } }).catch(err=>reject(err)) } } else resolve('No changes detected') }) } module.exports = { getFiles, uploadFiles }
import { escape } from "../escape/escape" /** * Make safe for RegExp'ing * * @param {string} source Source string * * @returns {string} * * @tag String * @signature ( source: string ): string * * @example { example } * * escapeRegExp( "lorem. ipsum [dolor]" ) * // => "lorem \\. ipsum \\[dolor\\]" */ export const escapeRegExp = escape(/[$()*+.<>?[\\\]^{|}]/g)
export default { entityName: 'app' }
// Хелпер для для форматирования даты export const formatDate = (date, hour) => { const d = new Date(date); const month = 'Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь,Декабрь'.split(',') const minutes = (d.getMinutes() < 10 ? '0' : '') + d.getMinutes() return `${d.getDate()} ${month[d.getMonth()]} ${d.getFullYear()} @ ${d.getHours()}:${minutes}` };
// Node utility static class export default class SenseUtil { }
/** * Change all chart colors */ import AppConfig from './AppConfig'; const { primary, info, danger, success, warning, purple, secondary, yellow, white, greyLighten, grey } = AppConfig.themeColors; const ChartConfig = { color: { 'primary': primary, 'info': info, 'warning': warning, 'danger': danger, 'success': success, 'default': '#DEE4E8', 'purple': purple, 'secondary': secondary, 'yellow': yellow, 'white': '#FFFFFF', 'dark': white, 'greyLighten': greyLighten, 'grey': grey }, legendFontColor: '#AAAEB3', // only works on react chart js 2 chartGridColor: '#EAEAEA', axesColor: '#657786', shadowColor: 'rgba(0,0,0,0.6)' } // Tooltip Styles export const tooltipStyle = { backgroundColor: 'rgba(0,0,0,0.6)', border: '1px solid rgba(0,0,0,0.6)', borderRadius: '5px' } export const tooltipTextStyle = { color: '#FFF', fontSize: '12px', paddingTop: '5px', paddingBottom: '5px', lineHeight: '1' } export default ChartConfig;
import DOMHandler from 'modules/DOMHandler' import { posts } from 'modules/Posts' import { categories } from 'modules/Helpers/categories' export const handleModal = () => { let modal = document.getElementById('modal-background') document.addEventListener('keydown', e => hideModal(e.keyCode, modal)) modal.addEventListener('click', e => hideModal(e.target.id, modal)) modal.classList.remove('display-none') modal.classList.remove('modal-out') modal.classList.add('modal-in') appendCategories() } // Append the categories to the DOM in #list-category const appendCategories = () => { const list = document.getElementById('list-category') Object.keys(categories).forEach(category => { const option = DOMHandler.createNode('option') option.innerHTML = categories[category].label DOMHandler.append(list, option) }) } const hideModal = (e, modal) =>{ if(e === 'modal-background' || e === 27) { modal.classList.remove('modal-in') modal.classList.add('modal-out') setTimeout(async () => modal.classList.add('display-none'), 250) } } export const onSubmit = () => document.getElementById('modal-form').addEventListener('submit', e => submitModalForm(e)) // It'll create the json of the new post and add it to the existing list const submitModalForm = e => { e.preventDefault() const [ author, url, category, title ] = getFormValues() if(!author || !url || !category || !title) return alert("You need to fill all the fields.") const link = { meta: { author, title, url, }, category, comments: 0, created_at: Date.now(), upvotes: 0, } posts.setPost(link) const modal = document.getElementById('modal-background') modal.classList.remove('modal-in') modal.classList.add('modal-out') setTimeout(async () => modal.classList.add('display-none'), 250) } // Return the value of forms in array format const getFormValues = () => [ document.getElementById('modal-post-name').value, document.getElementById('modal-post-url').value, document.getElementById('list-category').value, document.getElementById('modal-post-textarea').value ] //Add event listener to the button export const setAddPostAction = () => { const button = document.getElementById('add-post') button.style.cursor = "pointer" button.addEventListener('click', handleModal) }
import React from 'react'; import styled from 'styled-components'; import { Card, CardImg } from 'reactstrap'; import PropTypes from 'prop-types'; const TechCardBody = styled.div` display: flex; justify-content: center; flex-wrap: wrap; align-items: center; width: 200px; height: auto; margin: 15px; border: none; `; const TechCard = ({ icon, tech, firebaseKey }) => ( <TechCardBody> <Card className='card border-0' key={firebaseKey}> <CardImg src={icon} alt={tech}></CardImg> </Card> </TechCardBody> ); TechCard.propTypes = { icon: PropTypes.string, tech: PropTypes.string.isRequired, firebaseKey: PropTypes.any }; export default TechCard;
'use strict'; (function () { var HEIGHT_PIN = 44; // высота пина var HEIGHT_AFTER_PIN = 18; // высота псевдо элемента var removePopup = function() { this.remove(); }; var openPopup = function(popup) { popup.classList.add('__visible'); setTimeout(function () { popup.addEventListener('transitionend', removePopup); popup.classList.remove('__visible'); }, 10000) }; window.help = { /* * метод для перемешивания массива */ sortRandomArray: function (array) { var j, temp; for (var i = array.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); temp = array[j]; array[j] = array[i]; array[i] = temp; } return array }, /* * метод для генерации случайного числа в заданных пределах */ getRandomNumber: function (minNumber, maxNumber) { return Math.floor(minNumber + Math.random() * (maxNumber + 1 - minNumber)); }, /* * метод для генерации и вывода случайного элемента массива */ generateArrayNumber: function (array) { var randomTypeNumber = Math.floor(array.length * Math.random()); return array[randomTypeNumber]; }, /* * Константы */ constants: { WIDTH_PIN: 40, // ширина пина All_HEIGHT_PIN: HEIGHT_PIN + HEIGHT_AFTER_PIN }, /* простой попап для различных всплывающих окон */ popup: function (msg, theme) { var popupWindow = document.createElement('div'); popupWindow.classList.add('help_popup'); switch (theme) { case 'error': { popupWindow.classList.add('__danger'); break; } case 'success': { popupWindow.classList.add('__success'); break; } default: { popupWindow.classList.add('__default'); break; } } popupWindow.textContent = msg; document.body.insertAdjacentElement('afterbegin', popupWindow); setTimeout(function () { openPopup(popupWindow); }, 500); } } })();
import BeeperContainer from './BeeperContainer'; export{ BeeperContainer };
module.exports = { meta: { description: 'Eslint rule to show error when non-declared variable/functions are accessed from window', category: 'problem' }, create: function(context) { let globalScope; function isGlobalProperty(node) { return globalScope.variables.some(variable => { return variable.name === node.name; }); } return { Program: function() { globalScope = context.getScope(); }, MemberExpression: function(node) { if (node.object.name === 'window' && !isGlobalProperty(node.property)) { context.report({ message: '{{propertyName}} scope piggybacks on {{objectName}} to extend the global scope', node, data: { propertyName: node.property.name, objectName: node.object.name } }); } } }; } };
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' angular.module('citizen-engagement', ['ionic', 'citizen-engagement.auth', 'citizen-engagement.issue', 'citizen-engagement.user', 'citizen-engagement.constants', 'citizen-engagement.map', 'citizen-engagement.image', 'leaflet-directive']) .run(function($ionicPlatform, $rootScope) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); }) /* .run(function($cordovaStatusbar) { $cordovaStatusbar.overlaysWebView(true) //$cordovaStatusBar.style(1) //Light $cordovaStatusBar.style(2) //Black, transulcent //$cordovaStatusBar.style(3) //Black, opaque }) */ .config(function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider // This is the abstract state for the tabs directive. .state('tab', { url: '/tab', abstract: true, templateUrl: 'templates/tabs.html' }) .state('tab.list', { url: '/issues/list', views: { 'tab-list': { controller: 'ListCtrl', templateUrl: 'templates/list.html' } } }) .state('tab.issue', { url: '/issue/:issueId', views: { 'tab-list': { controller: 'IssueCtrl', templateUrl: 'templates/details.html' } }, onEnter: function($rootScope) { $rootScope.$broadcast('refresh-comments-count'); } }) .state('tab.comments', { url: '/issue/:issueId/comments', views: { 'tab-list': { controller: 'CommentCtrl', templateUrl: 'templates/comments.html' } } }) .state('tab.map', { url: '/issues/map', views: { 'tab-map': { controller: 'MapCtrl', templateUrl: 'templates/map.html' } } }) /* .state('tab.new', { url: '/issues/new', views: { 'tab-new': { controller: 'NewIssueCtrl', templateUrl: 'templates/new.html' } }, onEnter: function($rootScope) { $rootScope.$broadcast('takePhoto'); } })*/ .state('login', { url: '/login', controller: 'LoginCtrl', templateUrl: 'templates/login.html' }) .state('account', { url: '/account', controller: 'AccountCtrl', templateUrl: 'templates/account.html' }) ; // Define the default state (i.e. the first screen displayed when the app opens). $urlRouterProvider.otherwise(function($injector) { $injector.get('$state').go('tab.list'); // Go to the new issue tab by default. }); }) .run(function(AuthService, $rootScope, $state) { // Listen for the $stateChangeStart event of AngularUI Router. // This event indicates that we are transitioning to a new state. // We have the possibility to cancel the transition in the callback function. $rootScope.$on('$stateChangeStart', function(event, toState) { // If the user is not logged in and is trying to access another state than "login"... if (!AuthService.currentUserId && toState.name != 'login') { // ... then cancel the transition and go to the "login" state instead. event.preventDefault(); $state.go('login'); } /*else { $rootScope.navBar = true; }*/ }) }) .config(function($httpProvider) { $httpProvider.interceptors.push('AuthInterceptor'); $httpProvider.interceptors.push('authHttpResponseInterceptor'); }) .run(function($rootScope, $state, AuthService, $ionicLoading) { $rootScope.$on('goToLogin401', function(){ $ionicLoading.hide(); AuthService.unsetUser(); $state.go('login'); }); }) .run(function($rootScope) { $rootScope.navBar = true; }) .controller('SideMenuCtrl', function($scope, $ionicSideMenuDelegate) { $scope.toggleMenu = function(){ $ionicSideMenuDelegate.toggleLeft(); } }) .config(function($compileProvider){ $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/); })
var links = { imageLink1: "https://bit.ly/2rMf896", imageLink2: "https://bit.ly/2GCkurM", imageLink3: "https://bit.ly/2k6uReQ", imageLink4: "https://bit.ly/2k78uGf", imageLink5: 'https://bit.ly/2kf0uTF', imageLink6: 'https://bit.ly/2x0gLET', imageLink7: 'https://bit.ly/2IGmBwU', imageLink8: 'https://bit.ly/2LlCMkL', imageLink9: 'https://bit.ly/2GDUWL4', imageLink10: 'https://bit.ly/2GCbcMA' }; var thumbDiv = document.querySelectorAll('div')[1]; var linkKeys = Object.keys(links); var view = document.querySelector("[data-imageview]"); var linkKeysIndex = ''; linkKeys.forEach(key => { var anchorCreate = document.createElement('a'); var imgCreate = document.createElement('img'); anchorCreate.setAttribute('data-thumb',''); anchorCreate.setAttribute('data-link', links[key]); anchorCreate.setAttribute('data-index', key); anchorCreate.setAttribute('class','nav-item card d-block'); imgCreate.setAttribute('src',links[key]); imgCreate.setAttribute('class','img-thumbnail'); anchorCreate.appendChild(imgCreate); thumbDiv.appendChild(anchorCreate) }); // function-event pair for enlarging image function zoom(event) { event.preventDefault(); var key = event.currentTarget.getAttribute('data-index'); var url = event.currentTarget.getAttribute('data-link'); document.querySelector('section').classList.remove('d-none'); view.setAttribute("src",url); view.setAttribute("data-index",key); console.log(key); linkKeysIndex = linkKeys.indexOf(view.getAttribute('data-index')); console.log(linkKeysIndex); document.querySelectorAll('[data-arrow]').forEach(element => {element.classList.remove('d-none')}); } // function-event pair for navigating with arrows function arrowNav(event) { event.preventDefault(); // find the index of the data-index in the object.keys, and then find the next item in object.keys, and find the url from that link. if (event.currentTarget.getAttribute('data-arrow')=='left') { if (linkKeysIndex>0) { var url = links[linkKeys[linkKeysIndex-1]]; linkKeysIndex -= 1; } else { var url = links[linkKeys[linkKeysIndex+linkKeys.length -1]] linkKeysIndex = linkKeysIndex+linkKeys.length -1; } } else if (event.currentTarget.getAttribute('data-arrow')=='right') { if (linkKeysIndex<linkKeys.length-1) { var url = links[linkKeys[linkKeysIndex+1]]; linkKeysIndex += 1; } else { var url = links[linkKeys[0]] linkKeysIndex = 0; } } view.setAttribute("src",url); } function interact(element, fn) { element.addEventListener('click',fn); } document.querySelectorAll('[data-arrow]').forEach(item => { interact(item, arrowNav) }); document.querySelectorAll('[data-thumb]').forEach(item => { interact(item, zoom) });
var app = getApp(); module.exports = { unique: function (array) {//数组去重 var r = []; for (var i = 0, l = array.length; i < l; i++) { for (var j = i + 1; j < l; j++) if (array[i] === array[j]) j = ++i; r.push(array[i]); } return r; }, toFix: function (value) { console.log(value) var val = parseFloat(value) return val.toFixed(2) //此处2为保留两位小数 }, // 验证手机号是否有误 isPhoneAvailable: function (phone) { var myreg = /^[1][1-9][0-9]{9}$/; if (!myreg.test(phone)) { return false; } else { return true; } }, authFind: function (val) { //查找權限 console.log(app) return true; }, // 函数参数必须是字符串,因为二代身份证号码是十八位,而在javascript中,十八位的数值会超出计算范围,造成不精确的结果,导致最后两位和计算的值不一致,从而该函数出现错误。 // 详情查看javascript的数值范围 checkIDCard: function (idcode) { // 加权因子 var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 校验码 var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; var code = idcode + ""; var last = idcode[17];//最后一个 var seventeen = code.substring(0, 17); // ISO 7064:1983.MOD 11-2 // 判断最后一位校验码是否正确 var arr = seventeen.split(""); var len = arr.length; var num = 0; for (var i = 0; i < len; i++) { num = num + arr[i] * weight_factor[i]; } // 获取余数 var resisue = num % 11; var last_no = check_code[resisue]; // 格式的正则 // 正则思路 /* 第一位不可能是0 第二位到第六位可以是0-9 第七位到第十位是年份,所以七八位为19或者20 十一位和十二位是月份,这两位是01-12之间的数值 十三位和十四位是日期,是从01-31之间的数值 十五,十六,十七都是数字0-9 十八位可能是数字0-9,也可能是X */ var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/; // 判断格式是否正确 var format = idcard_patter.test(idcode); // 返回验证结果,校验码和格式同时正确才算是合法的身份证号码 return last === last_no && format ? true : false; }, navTo: function (obj) { //次方法 防止用户的暴力点击 快速点击多次 多次进入同一页面 var app = getApp(); if (app.isClicked) { return; } app.isClicked = true; wx.navigateTo({ url: obj.url, success: typeof (obj.success) === 'function' ? obj.success : function () { }, fail: typeof (obj.fail) === 'function' ? obj.fail : function () { }, complete: function (res) { console.log(res) setTimeout(function () { app.isClicked = false; }, 2000); if (typeof (obj.complete) === 'function') { obj.complete() } }, }); },/*获取当前页带参数的url*/ getCurrentPageUrlWithArgs:function (){ var pages = getCurrentPages() //获取加载的页面 var currentPage = pages[pages.length - 1] //获取当前页面的对象 var url = currentPage.route //当前页面url var options = currentPage.options //如果要获取url中所带的参数可以查看options //拼接url的参数 var urlWithArgs = url + '?' for (var key in options) { var value = options[key] urlWithArgs += key + '=' + value + '&' } urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1) return urlWithArgs }, /*获取当前页url*/ getCurrentPageUrl: function (){ var pages = getCurrentPages() //获取加载的页面 var currentPage = pages[pages.length - 1] //获取当前页面的对象 var url = currentPage.route //当前页面url return url } }
import React, { useState, useEffect } from "react"; import DateFnsUtils from "@date-io/date-fns"; import { KeyboardDateTimePicker, MuiPickersUtilsProvider, } from "@material-ui/pickers"; import { post } from "axios"; import { withRouter } from "react-router-dom"; //--------------------------------- What was used from material ui core ------------------------------------- import { Dialog, Typography, Grid, withStyles, TextField, Button, Checkbox, } from "@material-ui/core"; //------------------------------------------------------------------------------------------------------------ //------------------------------ Another Components Used In This Component ----------------------------------- import { DragImport } from "../"; //------------------------------------------------------------------------------------------------------------ /* The dialog that appear in materials Page for "Files-Assignemnets-videos" */ const CreateFileForm = ({ onClose, isOpened, title, onSubmit, hasDate, classes, videoExtension, AvilableGroups, }) => { // ---------------------------- variables with it's states that we use it in this Dialog ------------------- const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [blobs, setBlobs] = useState([]); const [goodStartDate, setGoodStartDate] = useState(false); const [goodEndDate, setGoodEndDate] = useState(false); const [CurrentDate, setCurrentDate] = useState(new Date()); const [date, setDate] = useState({ start: new Date(), end: new Date(), }); const [num, setNum] = useState([]); const [TotalGradee, setTotalGrade] = useState(0); const choose = "choose"; // --------------------------------------------------------------------------------------------------------- const onDropBlobs = (blobs) => { setBlobs([...blobs]); }; const onDeleteBlob = () => { setBlobs([]); }; //----- this function reset Dialogs when it opened "Clear all textboxs" + when we press a create button ----- const resetStates = () => { setName(""); setDescription(""); setBlobs([]); setDate({ start: new Date(), end: new Date() }); setGoodStartDate(false); setGoodEndDate(false); setTotalGrade(0); setNum([]); }; //------------------------------------------------------------------------------------------------------------ const handleTotalGradeMethod = (value, CheckTitle) => { { setNum((prev) => prev.map((choicee) => choicee.number !== CheckTitle ? choicee : { ...choicee, choose: value } ) ); } }; useEffect(() => { setNum(AvilableGroups); }, [AvilableGroups]); return ( isOpened && ( <Dialog open={isOpened} maxWidth="sm" fullWidth PaperProps={{ className: classes.dialogPaper }} > <Grid container direction="column" alignItems="stretch" justify="center" className={classes.dialog} > <Grid item className={classes.titleContainer}> <Typography variant="h3" className={classes.boldText} align="center" > {title} </Typography> </Grid> <Grid item> <Grid container justify="space-around"> <Grid item xs={11}> <Grid container direction="column" alignItems="stretch" justify="center" spacing={3} > {/* Dialog Name */} <Grid item> <TextField label="Name" fullWidth value={name} onChange={(e) => { setName(e.target.value); }} variant="outlined" classes={{ root: classes.textFieldRoot, }} InputProps={{ classes: { notchedOutline: classes.notchedOutline, }, }} InputLabelProps={{ classes: { root: classes.label, }, }} /> </Grid> {/* Dialog Description */} <Grid item> <TextField label={"Description"} fullWidth multiline rows={3} value={description} onChange={(e) => { setDescription(e.target.value); }} variant="outlined" classes={{ root: classes.textFieldRoot, }} InputProps={{ classes: { notchedOutline: classes.notchedOutline, }, }} InputLabelProps={{ classes: { root: classes.label, }, }} /> </Grid> {hasDate && ( <Grid item> <TextField label="Total Grade" value={TotalGradee} type="number" onChange={(e) => { setTotalGrade(Number.parseInt(e.target.value)); }} variant="outlined" classes={{ root: classes.textFieldRoot, }} InputProps={{ classes: { notchedOutline: classes.notchedOutline, }, inputProps: { min: 0, }, }} InputLabelProps={{ classes: { root: classes.label, }, }} /> </Grid> )} {/* Upload Button */} {videoExtension && ( <Grid item> <DragImport editable video Extension=".webm , .mkv , .flv , .vob , .ogv, .ogg , .drc , .gif , .gifv , .mng ,.avi, .MTS, .M2TS, .TS ,.mov, .qt,.wmv,.yuv,.rm,.rmvb,.asf,.amv,.m4v,.mp4, .m4p,.mpg, .mp2, .mpeg, .mpe, .mpv,.mpg, .mpeg, .m2v,.m4v,.svi,.3gp,.3g2,.mxf,.roq,.nsv,.flv, .f4v ,.f4p ,.f4a ,.f4b" blobs={blobs} onDrop={onDropBlobs} onDeleteBlob={onDeleteBlob} /> </Grid> )} {!videoExtension && ( <Grid item> <DragImport editable blobs={blobs} onDrop={onDropBlobs} onDeleteBlob={onDeleteBlob} /> </Grid> )} {/*Start Date && End Date That will appear only when we deal with Assignemnets Dialog */} {hasDate && ( <Grid item> <Grid container justify="space-between"> <Grid item xs={5}> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDateTimePicker clearable autoOk label="Start Date" inputVariant="standard" value={date.start} onChange={(date) => { setDate((prev) => ({ ...prev, start: date })); setCurrentDate(new Date()); }} onError={(bad) => setGoodStartDate(!bad)} format="yyyy/MM/dd hh:mm a" /> </MuiPickersUtilsProvider> </Grid> <Grid item xs={5}> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDateTimePicker clearable autoOk label="End Date" value={date.end} onChange={(date) => { setDate((prev) => ({ ...prev, end: date })); setCurrentDate(new Date()); }} onError={(bad) => setGoodEndDate(!bad)} format="yyyy/MM/dd hh:mm a" /> </MuiPickersUtilsProvider> </Grid> </Grid> <Grid item style={{ marginTop: "30px", marginLeft: "-200px" }} > <Grid item style={{ marginLeft: "210px" }}> <Typography style={{ fontSize: "25px" }}> Groups : </Typography> </Grid> <Grid item style={{ marginTop: "-40px" }}> {num.map((choosee, index) => ( <Grid item style={ index % 2 ? { marginLeft: "500px", marginTop: "-38px" } : { marginLeft: "350px", marginTop: "5px" } } > <Grid item> <Typography style={{ fontSize: "25px" }}> {choosee.number} </Typography> </Grid> <Grid item style={{ marginTop: "-41px", marginLeft: "40px", }} > <Checkbox inputProps={{ "aria-label": "uncontrolled-checkbox", }} checked={choosee.choose} classes={{ root: classes.check, checked: classes.checked, }} onChange={(e) => { handleTotalGradeMethod( e.target.checked, choosee.number ); }} /> </Grid> </Grid> ))} </Grid> </Grid> </Grid> )} <Grid item> <Grid container justify="flex-end" spacing={1}> {/* Dialog Cancel Button */} <Grid item> <Button variant="outlined" className={classes.cancelButton} onClick={() => { resetStates(); onClose(); }} > <Typography variant="h6" className={classes.boldText} color="error" > Cancel </Typography> </Button> </Grid> {/* Dialog Create Button */} <Grid item> <Button variant="outlined" className={classes.createButton} disabled={ blobs.length !== 1 || name === "" || (hasDate && (!goodStartDate || !goodEndDate || date.start < CurrentDate || date.end < CurrentDate || date.start > date.end || TotalGradee === 0 || num?.filter((x) => x.choose == false).length >= num.length)) } onClick={() => { resetStates(); onSubmit({ blobs: blobs[0], name, description, date, num, TotalGradee, }); }} > <Typography variant="h6" className={ blobs.length !== 1 || name === "" || (hasDate && (!goodStartDate || !goodEndDate || date.start < CurrentDate || date.end < CurrentDate || date.start > date.end || TotalGradee === 0 || num?.filter((x) => x.choose == false) .length >= num.length)) ? classes.createText : classes.boldText } > Create </Typography> </Button> </Grid> </Grid> </Grid> </Grid> </Grid> </Grid> </Grid> </Grid> </Dialog> ) ); }; CreateFileForm.defaultProps = { hasDate: false, isLink: false, }; /* Dialog styles */ const styles = () => ({ dialog: { padding: "10px 0px", }, titleContainer: { marginBottom: "18px", }, textFieldRoot: { backgroundColor: "white", borderRadius: "7px", }, notchedOutline: { borderWidth: "1px", borderColor: `black !important`, }, label: { color: "black !important", fontWeight: "600", }, dialogPaper: { minHeight: "50vh", padding: "20px 0px", }, createButton: { height: "40px", width: "130px", borderRadius: "16px", border: "2px black solid", }, cancelButton: { height: "40px", width: "130px", borderRadius: "16px", border: "2px red solid", }, boldText: { fontWeight: "600", }, createText: { color: "silver", }, check: { "&$checked": { color: "#0e7c61", }, }, checked: {}, }); export default withStyles(styles)(withRouter(CreateFileForm));
module.exports = function(sequelize,DataTypes){ return sequelize.define('medicine',{ medicine_name:{ type:DataTypes.STRING, allowNull:false }, medicine_salt:{ type:DataTypes.STRING }, medicine_type:{ type:DataTypes.STRING }, mrp:{ type:DataTypes.INTEGER }, manufacturer:{ type:DataTypes.STRING } }); };
import React from 'react'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import Divider from '@material-ui/core/Divider'; import { makeStyles } from '@material-ui/core/styles'; import { connect } from 'react-redux'; import CustomButton from './CustomButton'; function Price(props) { const useStyles = makeStyles(theme => ({ root: { display: 'flex', flexDirection: 'column', textAlign: 'center', alignItems: 'center', background: props.backgroundColor, color: props.color, marginBottom: 50, [theme.breakpoints.up('sm')]: { marginTop: props.big ? -30 : 0, paddingBottom: props.big ? 50 : 0, marginBottom: 70, } }, content: { width: '80%', }, header: { color: props.headerColor, fontSize: '40px', }, })); const classes = useStyles(); return ( <Card className={classes.root}> <CardContent class={classes.content}> <p>{props.title}</p> <h1 className={classes.header}>${props.store.value ? parseFloat(props.price / 10 - 0.01).toFixed(2) : props.price}</h1> <Divider /> <p>{props.storage + ' Storage'}</p> <Divider /> <p>{props.users + ' Users Allowed'}</p> <Divider /> <p>{'Send up to ' + props.size + ' GB'}</p> <Divider /> <CustomButton content='Learn More' background={props.buttonTheme} backgroundHover={props.buttonThemeHover} border={props.buttonTextColor} color={props.buttonTextColor} colorHover={props.buttonTextColorHover} width='100%' /> </CardContent> </Card> ); } export default connect( state => ({ store: state, }), dispatch => ({ onSwitch: (value) => { dispatch({ type: 'switched', value: value }); } }) )(Price);
import React, { Component } from 'react'; import { Card, CardTitle } from 'material-ui/Card'; class Home extends Component { render() { return ( <div> <Card> <CardTitle title="Introduction" subtitle="Welcome to the Cosmere Compendium" /> </Card> </div> ); } } export default Home;
import findChordNames from 'util/findChordNames'; describe('findChordNames', function() { it('returns correct results', function() { let semitones; let modeIndex; let pitchSkip; let expectedResult; semitones = 12; modeIndex = 1; pitchSkip = 1; expectedResult = ['I', null, 'ii', null, 'iii', 'IV', null, 'V', null, 'vi', null, 'viiº']; expect(findChordNames(semitones, modeIndex, pitchSkip)).toMatchObject(expectedResult); semitones = 12; modeIndex = 1; pitchSkip = 7; expectedResult = ['I', 'V', 'ii', 'vi', 'iii', 'viiº', null, null, null, null, null, 'IV']; expect(findChordNames(semitones, modeIndex, pitchSkip)).toMatchObject(expectedResult); semitones = 12; modeIndex = 2; pitchSkip = 1; expectedResult = ['i', null, 'ii', 'III', null, 'IV', null, 'v', null, 'viº', 'VII', null]; expect(findChordNames(semitones, modeIndex, pitchSkip)).toMatchObject(expectedResult); semitones = 12; modeIndex = 2; pitchSkip = 7; expectedResult = ['i', 'v', 'ii', 'viº', null, null, null, null, null, 'III', 'VII', 'IV']; expect(findChordNames(semitones, modeIndex, pitchSkip)).toMatchObject(expectedResult); semitones = 6; modeIndex = 1; pitchSkip = 1; expectedResult = ['I', 'ii', 'iii', null, null, null]; expect(findChordNames(semitones, modeIndex, pitchSkip)).toMatchObject(expectedResult); semitones = 6; modeIndex = 1; pitchSkip = 5; expectedResult = ['I', null, null, null, 'iii', 'ii']; expect(findChordNames(semitones, modeIndex, pitchSkip)).toMatchObject(expectedResult); }); });
describe("Carousel", function() { var carousel; var mockContainer; var mockItemsContainer; var mockItems; var mockItemsWidth; var mockCssWidth; beforeEach(function() { mockContainer = jasmine.createSpyObj('mockContainer', ['find']); mockContainer.find.and.callFake(function(arg) { if(arg === 'ul.items') { return mockItemsContainer; } }); mockItemsContainer = jasmine.createSpyObj('mockItemsContainer', ['find', 'width', 'css', 'animate']); mockItemsContainer.css.and.callFake(function (rule, value) { if(rule === "left") { return mockCssWidth; } }); mockItemsContainer.find.and.callFake(function(arg) { if(arg === 'li.item') { return mockItems; } }); mockItems = jasmine.createSpyObj('mockItem', ['width']); mockItems.width.and.returnValue(mockItemsWidth); mockItems.length = 2; mockItemsWidth = 100; mockCssWidth = "100px"; carousel = new kitty.Carousel(mockContainer); }); describe("Creating a carousel", function() { it('Finds the carousel items container', function () { expect(mockContainer.find).toHaveBeenCalledWith("ul.items"); expect(carousel.ul).toBe(mockItemsContainer); }); it('Finds the carousel items collection', function () { expect(mockItemsContainer.find).toHaveBeenCalledWith('li.item'); expect(carousel.lis).toBe(mockItems); }); it('Sets the width of the items container to match the width of all the items in the carousel', function () { expect(mockItemsContainer.width).toHaveBeenCalledWith(mockItems.length*mockItemsWidth); }); }); describe('Moving the carousel to the next item', function () { beforeEach(function () { carousel.moveForwards(); }); it('Retrieves the left css value', function () { expect(mockItemsContainer.css).toHaveBeenCalledWith('left'); }); it('Animates the left css value by 200', function () { expect(mockItemsContainer.animate).toHaveBeenCalledWith({ left: "300px" }); }); }); describe('Moving the carousel to the previous item', function () { beforeEach(function () { carousel.moveBackwards(); }); it('Retrieves the left css value', function () { expect(mockItemsContainer.css).toHaveBeenCalledWith('left'); }); it('Animates the left css value by 200', function () { expect(mockItemsContainer.animate).toHaveBeenCalledWith({ left: "-100px" }); }); }); describe('Destroying the carousel', function () { it('Removes the width style from the items container', function () { carousel.destroy(); expect(mockItemsContainer.css).toHaveBeenCalledWith("width", ""); }); }); });
import { AppRegistry } from 'react-native'; import App from './App'; import {NativeModules} from 'react-native'; module.exports = NativeModules.MyModule; AppRegistry.registerComponent('nativecall', () => { return App; });
const express = require('express'); const router = express.Router(); const Form = require('../../models/Form'); const getAge = require('get-age'); //Get all the users router.get('/', (req, res, next) => { Form.find({}, null, {sort: {firstname: 1}}, function (err, forms) { if (err) { console.log(err); } console.log(forms); }) .then((forms) => { res.json(forms); }) .catch(err => console.log(err)) }); // Create a user router.post('/add', (req, res, next) => { const firstname = req.body.firstname; const lastname = req.body.lastname; const email = req.body.email; const dob = req.body.dob; const address = req.body.address; const university = req.body.university; const course = req.body.course; const cgpa = req.body.cgpa; newForm = new Form({ firstname: firstname, lastname: lastname, email: email, dob: dob, address: address, university: university, course: course, cgpa: cgpa, }); newForm.save() .then(form => { res.json(form); res.json({success : true}) }) .catch(err => console.log(err)); }); // to update a user router.put('/update/:id', (req, res, next) => { //Grab the id of the user let id = req.params.id; // find the user by id from the databasse Form.findById(id) .then(form => { users.firstname = req.body.firstname; users.lastname = req.body.lastname; users.email = req.body.email; users.dob = req.body.dob; users.address = req.body.address; users.university = req.body.university; users.course = req.body.course; users.cgpa = req.body.cgpa; users.save() .then(form =>{ res.send({message: 'Updated succesfully', status: 'sucess', form: form}) }) .catch(err => console.log(err)) }) .catch(err => console.log(err)) }); // make delete request router.delete('/:id', (req, res, next) => { let id = req.params.id; Form.findById(id) .then(form => { form.delete() .then(form =>{ res.send({message: 'Deleted succesfully', status: 'sucess', form: form}) }) .catch(err => console.log(err)) }) .catch(err => console.log(err)) }) // Get all one user router.get('/single/:id', (req, res, next) => { //Grab the id of a user let id = req.params.id; Form.findById(id) .then((form) => { res.json(form); }) .catch(err => console.log(err)) }); // ROUTES // app.get('/',function(req,res){ // res.sendFile(__dirname + '/Application-form.vue'); // }); // app.post('/uploadfile', upload.single('myFile'), (req, res, next) => { // const file = req.file // if (!file) { // const error = new Error('Please upload a file') // error.httpStatusCode = 400 // return next(error) // } // res.send(file) // }) module.exports = router;
const usernameElement = document.getElementById('username'); const passwordElement = document.getElementById('password'); const getExcelBtn = document.getElementById('getExcelBtn'); const spinningItem = document.getElementById('spinningItem'); const buttonTxt = document.getElementById('buttonTxt'); const snackbar = document.getElementById("snackbar"); usernameElement.addEventListener('keydown', ({key}) => { if (key === 'Enter') return callEndpoint(); }) passwordElement.addEventListener('keydown', ({key}) => { if (key === 'Enter') return callEndpoint(); }) window.onload = function populateDropdown() { const firstSunday = new Date('09-06-2020'); const today = new Date(); const lastSunday = new Date(today.setDate(today.getDate()-today.getDay())); const currentWeek = Math.round((lastSunday - firstSunday) / (7 * 24 * 60 * 60 * 1000)); const weekDropdown = document.getElementById('week'); for (let i = 5; i < 52; i++) { const option = document.createElement("option"); option.text = `Week ${i}`; option.value = i; weekDropdown.appendChild(option); } weekDropdown.value = currentWeek + 2; }; const downloadFileProcess = (workbookBase64, week, forename, last_name) => { const uri = `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,${workbookBase64}`; const downloadLink = document.createElement('a'); downloadLink.href = uri; downloadLink.download = `${last_name}, ${forename} Week ${week} - Timesheet.xlsx`; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } const showToast = (message) => { snackbar.className = "show"; snackbar.textContent = message; setTimeout(function(){ snackbar.classList.remove('show'); }, 3500); } const callEndpoint = async () => { try { getExcelBtn.disabled = true; spinningItem.classList.remove('visually-hidden'); buttonTxt.innerHTML = 'Loading...'; const createTemplateApi = '/api/createTemplate'; const username = usernameElement.value; const password = passwordElement.value; const weekDropdown = document.getElementById('week'); const selectedWeek = weekDropdown.options[weekDropdown.selectedIndex].value; // if username missing, red border if (!username) { return usernameElement.classList.add('inputWrongStyle'); } else { usernameElement.classList.replace('inputWrongStyle', 'inputDefaultStyle'); } // if psw missing, red border if (!password) { return passwordElement.classList.add('inputWrongStyle'); } else { passwordElement.classList.replace('inputWrongStyle', 'inputDefaultStyle'); } const response = await fetch(createTemplateApi, { method: 'POST', body: JSON.stringify({ username, password, selectedWeek }), headers: { 'content-type': 'application/json' } }); const body = await response.json(); const { workbookBase64, week, forename, last_name } = body; if (!workbookBase64) throw new Error(body.message); downloadFileProcess(workbookBase64, week, forename, last_name); showToast('Download has started!'); } catch (err) { showToast(err.message); } finally { document.getElementById('getExcelBtn').disabled = false; buttonTxt.innerHTML = 'GET EXCEL'; spinningItem.classList.add('visually-hidden'); } }
X.define("model.clearanceModel",function () { //临时测试数据 var query = "js/data/mockData/bidList.json"; var clearanceModel = X.model.create("model.clearanceModel",{idAttribute:"tenderId",service:{query:query}}); //提交报关单 clearanceModel.applyClearance = function(data,callback){ var option = {url: X.config.customerClearance.api.applyClearance,type:"POST",data:data,callback:function(result){ callback&&callback(result); }}; X.loadData(option); }; //提交添加账户信息 clearanceModel.postAcount = function(data,callback){ var option = {url: X.config.customerClearance.api.postAcount,type:"POST",data:data,callback:function(result){ callback&&callback(result); }}; X.loadData(option); }; //获取结汇/退税收款账户列表 clearanceModel.getAcountList = function(callback){ var option = {url: X.config.customerClearance.api.getAcountList,type:"GET",callback:function(result){ callback&&callback(result); }}; X.loadData(option); }; //提交添加联系人信息 clearanceModel.postContacts = function(data,callback){ var option = {url: X.config.customerClearance.api.postContacts,type:"POST",data:data,callback:function(result){ callback&&callback(result); }}; X.loadData(option); }; //修改联系人信息 clearanceModel.putContacts = function(data,callback){ var option = {url: X.config.customerClearance.api.postContacts,type:"PUT",data:data,callback:function(result){ callback&&callback(result); }}; X.loadData(option); }; //获取联系人列表 clearanceModel.getContactsList = function(callback){ var option = {url: X.config.customerClearance.api.getContactsList,type:"GET",callback:function(result){ callback&&callback(result); }}; X.loadData(option); }; return clearanceModel; });
(function () { var primeBaseUrl = "https://captivateprime.adobe.com"; var primeApiBaseUrl = primeBaseUrl + "/primeapi/v2"; var app_id = "9ed96675-162b-44fe-9c72-dcf02a5615cf"; var linkedinRedirectURI = 'https: //s3.amazonaws.com/hosted_data/LinkedInPOC/linkedin-learner-exp/index.html'; var logInUrl = '%2Faccountiplogin%3FipId%3D2770%26accesskey%3Dj6i06kr8o8r'; var accessToken = ''; var token_url = primeBaseUrl + "/oauth/token"; var app_secret = "bb4afc86-b182-4754-8b98-95516ebb1096"; // var linkedinApiBaseURL = "api.linkedin.com"; // var linkedinTokenURL = "https://www.linkedin.com/oauth/v2/accessToken"; // var linkedinSecretId = "cvSTlYFGqlUJcImR"; //var redirectURI = "http://127.0.0.1:34789/index.html"; //var linkedinAccessToken = ''; // var userEmail = ''; /*var getURLParameter = function (sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; var getUserEmail = function () { if (linkedinAccessToken == '') linkedinAccessToken = localStorage.getItem('linkedinAccessToken'); //var data = {}; var url = linkedinApiBaseURL + "/v1/people/~:(emailAddress)?oauth2_access_token=" + linkedinAccessToken + "&format=json"; $.ajax({ "url": url, "method": 'GET' }).done(function (data) { if (console && console.log) { console.log("Got data:", data); //callback(data); } }); } jQuery(document).ready(function () { var state = getURLParameter('state'); if (state != null && state == 'state1') { var code = getURLParameter('code'); var data = {}; data.grant_type = 'authorization_code'; data.code = code; data.client_id = linkedinAppId; data.client_secret = linkedinSecretId; data.redirect_uri = redirectURI; $.ajax({ type: "POST", url: linkedinTokenURL, data: data, success: function (data) { console.log('abmahesh'); console.log(data); linkedinAccessToken = data.access_token; localStorage.setItem('linkedinAccessToken', linkedinAccessToken); init(); getUserEmail(); }, failure: function () { console.log('onFailure'); } }); } }); */ function blockUI() { document.getElementById('opacity-provider').style.display = "block"; } window.addEventListener("message", function (event) { if (event.data == "status:close") { //document.getElementsByTagName('body')[0].removeChild(document.getElementById('thumbnail-video')); //document.getElementById('opacity-provider').style.display = "none"; document.getElementById("id_featured-course_thumbnail").setAttribute("style", "text-align:center;display:block"); document.getElementById("id_featured-course_iframe_parent").setAttribute("style", "text-align:center;display:none;width:100%"); } }); var getURLParameter = function (sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; var getToken = function () { var code = getURLParameter('code'); if (!code) return; var data = {}; data.code = code; data.client_id = app_id; data.client_secret = app_secret; return $.ajax({ type: "POST", url: token_url, data: data, success: function (data) { console.log(data); accessToken = data.access_token; localStorage.setItem('accessToken', accessToken); }, failure: function () { console.log('onFailure'); } }); } var populateFeaturedCourseMetadata = function () { getToken().then(function (data) { var path = '/learningObjects?include=enrollment&include=instances&page[limit]=10&filter.learnerState=enrolled,completed,started&sort=dueDate'; var method = 'GET'; $.ajax({ "url": primeApiBaseUrl + path, "method": method, "headers": { "Authorization": "oauth " + accessToken } }).done(function (data) { if (console && console.log) { console.log("Got data:", data); var firstCourseId = data['data'][0].id; document.getElementById("id_featured_course_title").innerHTML = data['data'][0].attributes.localizedMetadata[0].name; } }); }); }; var getFirstCourse = function () { var path = '/learningObjects?include=enrollment&include=instances&page[limit]=10&filter.learnerState=enrolled,completed,started&sort=dueDate'; var method = 'GET'; $.ajax({ "url": primeApiBaseUrl + path, "method": method, "headers": { "Authorization": "oauth " + accessToken } }).done(function (data) { if (console && console.log) { console.log("Got data:", data); var firstCourseId = data['data'][0].id; onCourseClick(firstCourseId); } }); }; var startPlayback = function () { if (accessToken.length > 0) { getFirstCourse(); } else { getToken().then(function (data) { getFirstCourse(); }); } }; function validateLogin(event) { window.location = primeBaseUrl + '/oauth/o/authorize?response_type=code&redirect_uri=' + linkedinRedirectURI + '&realm=1&client_id=' + app_id + '&scope=learner:read,learner:write&loginUrl=' + logInUrl; } function detectMob() { if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ) { return true; } else { return false; } } function onCourseClick(courseId) { //var elFrame = document.createElement('iframe'); //elFrame.id = "thumbnail-video"; //elFrame.src = primeBaseUrl + "/app/player?lo_id=" + courseId + "&access_token=" + accessToken; //document.getElementsByTagName('body')[0].appendChild(elFrame); //document.getElementById('thumbnail-video').setAttribute('style', 'position: absolute; display: block; width: 912px; height: 484px; z-index: 1001; background: lightgrey; margin-left: 14%; margin-top: -46%;'); //blockUI(); var elFrame = document.getElementById('id_featured-course_iframe'); elFrame.src = primeBaseUrl + "/app/player?lo_id=" + courseId + "&access_token=" + accessToken; document.getElementById("id_featured-course_thumbnail").setAttribute("style", "text-align:center;display:none"); document.getElementById("id_featured-course_iframe_parent").setAttribute("style", "text-align:center;display:block;"); if (!detectMob()) { document.getElementById("id_featured-course_iframe").setAttribute("height", "400"); document.getElementById("id_featured-course_iframe").setAttribute("width", "70%"); } else { document.getElementById("id_featured-course_iframe").setAttribute("height", "250"); document.getElementById("id_featured-course_iframe").setAttribute("width", "100%"); } } function init() { populateFeaturedCourseMetadata(); document.getElementById('course-thumbnail').addEventListener("click", startPlayback, false); } init(); })();
import Dispatcher from '../Dispatcher'; import Constants from '../Constants'; import {EventEmitter} from 'events'; import MessageGenerator from '../services/MessageGenerator'; import assign from 'object-assign'; import _ from 'lodash'; // data storage let _registeredMessages = []; let _clientMessages = []; let iClientId = 0; let iServerMessageId = 0; var messageGenerator = new MessageGenerator(['Paf']); // what would happen when a message is received from server (typically connected to a web socket function onMessageReceivedFromServer(message) { var nMessage = _.extend({}, message, {id: 'srv_' + iServerMessageId, status: Constants.STATUS_MESSAGE_CONFIRMED}); iServerMessageId++; //if the message has a clientId (so was issued by the client, it must be removed from the temporary stack) //well, that method not reentrant, but the purpose here is to make a demo, nope? if (message.clientId !== undefined) { _clientMessages = _.filter(_clientMessages, function (msg) { return msg.clientId !== message.clientId; }); } _registeredMessages.push(nMessage); //let everyone who registered know that the store has change MessageStore.emitChange(); }; //as we don't have any backnd server, we just simulate the behavior function fakeServerPostMessage(message) { //in 0.5 second, the message will be received from server setTimeout(function () { onMessageReceivedFromServer(message); }, 500); // and concurrently create two random message from your friend, with random time between now and +1 second messageGenerator.async(2, 500, function (message) { onMessageReceivedFromServer(message); }); }; // post a message, that, at this moment, only contain text and author function postMessage(content) { var clientId = 'client_' + iClientId; var message = _.extend({ clientId: clientId, id: clientId, date: new Date(), status: Constants.STATUS_MESSAGE_NOT_CONFIRMED }, content); iClientId++; _clientMessages.push(message); fakeServerPostMessage(message); MessageStore.emitChange(); } // Facebook style store creation. const MessageStore = assign({}, EventEmitter.prototype, { // Allow Controller-View to register itself with store addChangeListener(callback) { this.on(Constants.CHANGE_EVENT, callback); }, removeChangeListener(callback) { this.removeListener(Constants.CHANGE_EVENT, callback); }, // triggers change listener above, firing controller-view callback emitChange() { this.emit(Constants.CHANGE_EVENT); }, // concatenates received and sent (unconfirmed) messages getAllMessages() { return _.flatten([_registeredMessages, _clientMessages]); }, //count the different type of message counts() { return { received: _.filter(_registeredMessages, function (m) { return m.author !== '__ME__'; }).length, sentConfirmed: _.filter(_registeredMessages, function (m) { return m.author === '__ME__'; }).length, sentNotConfirmed: _clientMessages.length } }, // register store with dispatcher, allowing actions to flow through dispatcherIndex: Dispatcher.register(function (payload) { let {type, args} = payload; switch (type) { case Constants.MESSAGE_POSTED: let text = args.message.text.trim(); if (text !== '') { postMessage({text: text, author: '__ME__'}); } break; } }) }); export default MessageStore;
export const TEST = 'TEST' // AUTHENTICATION export const AUTH_METHOD_TOGGLE = 'AUTH_METHOD_TOGGLE'; export const AUTH_CREATE_FORMARR = "AUTH_CREATEFORMARR"; export const AUTH_SENDAUTH_EXEC = 'AUTH_SENDAUTH_EXEC'; export const AUTH_GET_ACCESSKEYS = 'AUTH_GET_ACCESSKEYS'; export const AUTH_SET_ACCESSKEYS = 'AUTH_SET_ACCESSKEYS'; export const AUTH_CHECK_ACCESSKEYS = 'AUTH_CHECK_ACCESSKEYS'; export const AUTH_GET_SGKEY = 'AUTH_GET_SGKEY'; export const AUTH_INPUT_UPDATED = 'AUTH_INPUT_UPDATED'; export const AUTH_TOTAL_VALIDITY = 'AUTH_TOTAL_VALIDITY'; export const AUTH_FAIL = 'AUTH_FAIL'; export const AUTH_SIGNIN_RESET = 'AUTH_SIGNIN_RESET'; export const AUTH_SIGNIN_ERROR = 'AUTH_SIGNIN_ERROR'; export const AUTH_SHOW_RESET_PASSWORD_FIELDS = 'AUTH_SHOW_RESET_PASSWORD_FIELDS'; //RESET export const AUTH_RESET_PASSWORD = 'AUTH_RESET_PASSWORD'; export const AUTH_SET_RESET_PASSWORD_MESSAGE = 'AUTH_SET_RESET_PASSWORD_MESSAGE'; export const AUTH_SET_RESET_PASSWORD_USER = 'AUTH_SET_RESET_PASSWORD_USER'; // SIGNUP export const AUTH_SIGNUP = 'AUTH_SIGNUP'; export const AUTH_SIGNUP_ERROR = 'AUTH_SIGNUP_ERROR'; export const AUTH_SIGNUP_RESET = 'AUTH_SIGNUP_RESET'; export const AUTH_SIGNUP_SUCCESS = 'AUTH_SIGNUP_SUCCESS'; export const AUTH_TOGGLE_PROP = 'AUTH_TOGGLE_PROP'; export const AUTH_TOGGLE_ERROR = 'AUTH_TOGGLE_ERROR'; export const AUTH_RESET_UI = 'AUTH_RESET_UI'; // MAIN export const MAIN_TEST = 'MAIN_TEST'; export const MAIN_SET_USER = 'MAIN_SET_USER'; export const MAIN_LOGGED_IN = "MAIN_LOGGED_IN"; export const MAIN_LOGIN_ERROR = "MAIN_LOGIN_ERROR"; export const MAIN_LOGOUT = 'MAIN_LOGOUT'; export const MAIN_TOGGLE_BACKGROUND = 'MAIN_TOGGLE_BACKGROUND'; export const MAIN_TOGGLE_AUTHINTRO = 'MAIN_TOGGLE_AUTHINTRO'; // CONTACT export const CONTACT_INIT = 'CONTACT_INIT'; export const CONTACT_RESET = 'CONTACT_RESET'; export const CONTACT_INPUT_UPDATED = 'CONTACT_INPUT_UPDATED'; export const CONTACT_TOTAL_VALIDITY = 'CONTACT_TOTAL_VALIDITY'; export const CONTACT_FORM_SUBMITTED = 'CONTACT_FORM_SUBMITTED'; // Skills export const SKILLS_LOAD_PROGRESS = 'SKILLS_LOAD_PROGRESS'; //Cover Letter export const COVERLETTER_LOADED = 'COVERLETTER_LOADED'; export const COVERLETTER_LOAD = 'COVERLETTER_LOAD'; export const COVERLETTER_SET_JOB = 'COVERLETTER_SET_JOB'; export const COVERLETTER_SET_CL = 'COVERLETTER_SET_CL';
import express, { response } from 'express'; import User from '../schema/User.js'; const router=express.Router(); router.post('/signin', async (req,res,next) => { const exist = await User.findOne({ username: req.body.username }); if(exist){ return res.status(401).json('Username already exist'); } User.create(req.body) .then(data => res.json(data)) .catch(next => console.log(next)); }) router.post('/login', async (req, res, next) => { const user = await User.findOne({username: req.body.username, password: req.body.password}); if(user) { return res.status(200).json(`${req.body.username} login successfull`); } else { return res.status(401).json('Invalid Login'); } }) export default router;
const mongoose = require("mongoose"); //Create reference to user model, associated with _id in database const ProfileSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "user" }, fullname:{ type: String }, contact:{ type: Number }, location: { rt:{ type: String, }, rw:{ type: String }, kode_post:{ type: String }, kelurahan:{ type: String }, kecamatan:{ type: String }, kabupaten:{ type: String }, coordinat:{ latitude:{ type: String }, longitude:{ type: String } } }, bio: { type: String }, social: { twitter: { type: String }, facebook: { type: String }, instagram: { type: String } }, date: { type: Date, default: Date.now } }); module.exports = Profile = mongoose.model("profile", ProfileSchema);
import React from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import SobrePage from './pages/SobrePage'; import HomePage from './pages/HomePage'; import TarefasPage from './pages/TarefasPage'; const Routes = props => { return( <BrowserRouter> <Route path="/" exact component={HomePage} /> <Route path="/tarefas/" component={TarefasPage} /> <Route path="/sobre/" component={SobrePage} /> </BrowserRouter> ) } export default Routes;
'use strict' module.exports = { flags: 'release', desc: 'Publish built images for release', run: argv => { throw new Error('This is an unexpected error') } }
// pages/auth/index.js import {login} from "../../utils/asyncWx.js"; Page({ data:{ }, onLoad:function(){ }, //获取用户信息openid handelGetUserInfo(e){ var that=this; let cart=wx.getStorageSync('cart')||[]; try { wx.login({ success: (result)=>{ wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', data: { appid:'wxc48c89daddbeb11a', secret:'ddd1e180e13b09286135f78206c4ed5a', js_code:result.code, grant_type:'authorization_code' }, method: 'GET', success: (result)=>{ const{openid}=result.data; wx.setStorageSync("openid", openid); wx.request({ url: getApp().globalData.serviceUrl + '/buyer/shopcart/one?openId='+openid, success:function(result){ let resData = result.data.data; that.setData({a:resData.length}); for(let i=0;i<resData.length;i++){ wx.request({ url: getApp().globalData.serviceUrl + '/buyer/product/singleOne?cateGory='+resData[i].cateGory+'&singleId='+resData[i].singleId, success: (result)=>{ cart[i]=result.data.data;//获取成功 cart[i].num=resData[i].count; cart[i].checked=resData[i].checked; wx.setStorageSync('cart',cart); }, }); } //for } }); wx.navigateBack({ delta: 1 }); } }); } }); } catch (error) { console.log(error); } } })
import React, { Component } from 'react' import PropTypes from 'prop-types' export default class TodoItem extends Component { constructor(props) { super(props); this.handleSave = this.handleSave.bind(this); } static propTypes = { onClick: PropTypes.func.isRequired, completed: PropTypes.bool.isRequired, } state = { editing: false, myValue: null } componentDidMount() { this.setState({ myValue: this.props.text }) } handleClick = () => { this.setState({ editing: true }) } // TODO сохранять данные после редактирования handleSave = (id, text) => { if (text.length === 0) { this.props.onDelete(id) } else { this.props.editTodo({id: id, text: text}) } this.setState({ editing: false, myValue: text }) } onChangeHandler = (event) => { console.log('e.target.value', event.target.value); this.setState({myValue: event.target.value}) } render() { const { onClick, onDelete, completed, id } = this.props let element; if (this.state.editing) { element = ( <div className="todo-view"> <input className='todo-input' value={this.state.myValue} onChange={this.onChangeHandler} /> <span onClick={(myValue) => this.handleSave(id, this.state.myValue)} className="save-todo"></span> </div>) } else { element = ( <div className="todo-view"> <span onClick={onClick} className="name-todo" style={{ textDecoration: completed ? 'line-through' : 'none' }}>{this.state.myValue}</span> <span onClick={this.handleClick} className="edit-todo"></span> <span onClick={onDelete} className="delete-todo"></span> </div>) } return ( <li> {element} </li> ) } }
angular .module('account', ['parseAccountVendor', 'facebook']) .service('account', ['parseAccountVendor', 'facebook', '$q', Account]); function Account(accountVendor, facebookVendor, $q) { var self = this; self.signUp = signUp; self.login = login; self.loginWithFB = loginWithFB; self.signOut = signOut; self.userChange = $q.defer(); self.user = undefined; self.facebookUser = {}; activate(); function activate() { accountVendor.init(); setUser(accountVendor.getUser()); } function login(u, p) { var loginPromise = accountVendor.signIn(u, p); loginPromise.then(setUser); return loginPromise; } function loginWithFB() { return facebookVendor.login().then( function (facebookUser) { setFacebookUser(facebookUser); return loginFacebookUserToVendor(facebookUser) }, unSetUser ); } function signUp(email, pass, playerName) { var signUpPromise = accountVendor.signUp(email, pass, playerName); signUpPromise.then(setUser); return signUpPromise; } function signOut() { return $q(function (resolve, reject) { accountVendor.signOut() .then(_facebookLogout) .finally(function () { unSetUser(); resolve(); }); }); } function _facebookLogout() { return $q(function (resolve, reject) { if (self.facebookUser.email) { self.facebookUser = {}; facebookVendor.logOut().then(resolve); } else { resolve(); } }) } function loginFacebookUserToVendor(facebookUser) { return accountVendor.signIn(facebookUser.email, facebookUser.id).then( setUser, createVendorAccountForFacebookUser.bind(undefined, facebookUser)); } function createVendorAccountForFacebookUser(facebookUser) { accountVendor.signUp(facebookUser.email, facebookUser.id, facebookUser.name) .then(setUser); } function setFacebookUser(user) { self.facebookUser = user } function setUser(user) { self.user = user; self.userChange.notify(); } function unSetUser() { self.user = undefined; self.userChange.notify(); } }
app.controller('myMealController', function($scope) { $scope.addForm = false; $scope.randomMealForm = false; $scope.recipeInfo = false; $scope.mealForm = false; $scope.recipeInfo2 = false; $scope.fullWeek = false; $scope.personalShoppingList = false; $scope.recipeButton1 = false; $scope.cancelButton =false; $scope.approveButton = false; $scope.ingredients = ''; $scope.query = ''; });
var pageSize = 4; //每页显示的记录条数 var curPage=1; //当前页 var count; //最后页 总数据量 var pageNums; //总页数 var temp //表结构 $(function(){ temp = $("#tb").clone(); //克隆表结构 first(); //跳转到分页查询首页 }); /** * 分页及查询所有班级 */ function splitPage(p){ $.ajax({ url:"../../selectAll.do", type:"post", dataType:"json", data:"pageCount="+curPage+"&pageSize="+pageSize, success:function(data){ count = data.count; pageNums = count%pageSize==0?Math.floor(count/pageSize):Math.ceil(count/pageSize); $("#totalNums").text(count); //显示数据量总条数 $("#pageSize").text(pageSize); //显示页面大小 $("#pageNums").text(pageNums); //显示页面数量 $("#inputPage").val(curPage); //显示当前页面 var temp1=temp.clone(); $("#tb").empty(); // $("#classCount").text(data.count); // $("#sumCount").text(count2); $.each(data.list,function(i,data1){ temp1.find("tr").attr("dataId",data1.class_id); temp1.find("#class_id").text(data1.class_id); temp1.find("#name").text(data1.name); temp1.find("#lesson").text(data1.lesson); temp1.find("#lecturer").text(data1.lecturer); temp1.find("#assistant").text(data1.assistant); temp1.find("#teacher").text(data1.teacher); temp1.find("#class_num").text(data1.class_num); temp1.find("#class_start").text(data1.class_start); temp1.find(".classAgo").text(data1.status); $("#tb").append(temp1.html()); console.log(temp1.find("tr").attr("dataId")); }); //传值 $("tr").dblclick(function () { if($(this).attr("dataId") != undefined){ location.href = "base_myClassDetails.html?dataId=" + $(this).attr("dataId"); } }); } }); } function first(){ curPage=1; //设置当前页面为1 splitPage(curPage); if(curPage==pageNums){ $(".pageUp").removeAttr('onclick'); $(".pageDown").removeAttr('onclick'); }else{ $(".pageUp").removeAttr('onclick'); //禁用上一页 $(".pageDown").attr('onclick',"pageDown()");//启用下一页 } } function pageUp(){ $(".pageDown").attr('onclick',"pageDown()"); //启用下一页 curPage--; //当前页面减1 splitPage(curPage); //如果当前页面等于1,禁用上一页 if(curPage==1){ $(".pageUp").removeAttr('onclick'); } } function pageDown(){ $(".pageUp").attr('onclick',"pageUp()"); //启用上一页 curPage++; //当前页面加1 splitPage(curPage); //如果当前页面等于最后一页,禁用下一页 if(curPage==pageNums){ $(".pageDown").removeAttr('onclick'); } } function last(){ curPage=pageNums; //设置当前页面为最后一页 splitPage(curPage); if(curPage==pageNums){ $(".pageUp").removeAttr('onclick'); $(".pageDown").removeAttr('onclick'); }else{ $(".pageDown").removeAttr('onclick'); //禁用下一页 $(".pageUp").attr('onclick',"pageDown()");//启用上一页 } } /** * 文本框跳转页面 */ function turnPage(input){ var page=$(input).val(); //取文本框值 var reg = /^[1-9]*$/; //1-9数字正则 if(page!=""){ //非空判断 if(reg.test(page)){ //正则校验 if(page>pageNums) //如果输入的值大于总页数,跳转到末页 last(); else if(page==1){ //如果输入的值等于1,跳转到首页 first(); }else { //否则跳转到输入页面,启用上下页 curPage=page; splitPage(curPage); $(".pageUp").attr('onclick',"pageUp()"); $(".pageDown").attr('onclick',"pageDown()"); } } } }
// Require mongoose var mongoose = require("mongoose"); // Get a reference to the mongoose Schema constructor var Schema = mongoose.Schema; // Using the Schema constructor, create a new ExampleSchema object // This is similar to a Sequelize model var UserSchema = new Schema({ id: { type: String, unique: true }, username: { type: String, unique: true }, gameStarted: { type: Boolean }, answer: { type: String }, attempts:{ type: Number } }); // This creates our model from the above schema, using mongoose's model method var User = mongoose.model("User", UserSchema); // Export the Example model module.exports = User;
import React, { Component } from 'react'; import adapters from '../adapters' export default class UserSignupForm extends Component { state = { username: '', password: '', avatar: null, avatarURL: null } usernameInputChange = (e) => { this.setState({ username: e.target.value }) } passwordInputChange = (e) => { this.setState({ password: e.target.value }) } submitForm = (event) => { event.preventDefault() const formData = new FormData(); formData.append('user[username]', this.state.username) formData.append('user[password]', this.state.password) if (this.state.avatar) { formData.append('user[avatar]', this.state.avatar) adapters.createUser(formData) } } handleFile = (e) => { const file = e.target.files[0] const fileReader = new FileReader() fileReader.onloadend = () => { this.setState({ avatar: file, photoURL: fileReader.result }) } if (file) { fileReader.readAsDataURL(file) } } render() { const preview = this.state.photoURL ? <img className="preview-img" alt="preview-img" src={this.state.photoURL}/> : null return ( <div className="form-container"> <form onSubmit={this.submitForm} className="form"> <h1>Register</h1> <p>Enter Username: <input name="username" onChange={this.usernameInputChange} value={this.state.username} /></p> <p>Enter Password: <input type="password" onChange={this.passwordInputChange} value={this.state.password} /></p> <p>Upload avatar below</p> <input type="file" onChange={this.handleFile} /> {preview} <button type="submit">Submit</button> </form> </div> ) } }
const App = { html: hyperHTML.bind(document.querySelector("#app")), data: {inputs: ["a", "b", "c"]}, onInput(event, index) { this.data.inputs[index] = event.target.value; this.render(); }, render() { this.html`${this.data.inputs.map( (inp, index) => hyperHTML.wire(this, ':' + index)` <input value=${inp} oninput=${e => this.onInput(e, index)}><br>` )}${JSON.stringify(this.data.inputs)}`; } }; App.render(); /* <div id="app"></div> */
var TouchStick = (function(){ var INNER_RADIUS = 40; var LIMIT_X = 40; var LIMIT_Y = 40; var _canvas, _touches = {}, _limits = []; function init(canvas, limits){ _canvas = canvas; _canvas.addEventListener("touchstart", onTouchStart, false); _canvas.addEventListener("touchmove", onTouchMove, false); _canvas.addEventListener("touchend", onTouchEnd, false); if(limits && limits.length > 0){ _limits = limits; } } function draw(ctx){ for(var i in _touches){ var touch = _touches[i]; console.log("draw", touch); var start = unOffset(touch.startX, touch.startY, ctx.canvas); var move = unOffset(touch.moveX, touch.moveY, ctx.canvas); var scaleX = ctx.canvas.width/ctx.canvas.clientWidth; var scaleY = ctx.canvas.height/ctx.canvas.clientHeight; ctx.lineWidth = 3; ctx.strokeStyle = "#FFFFFF"; ctx.fillStyle = "rgba(255, 255, 255, 0.5)"; ctx.beginPath(); ctx.arc(start.x*scaleX, start.y*scaleY, (INNER_RADIUS)*scaleX, 0, Math.PI*2, true); ctx.fill(); ctx.beginPath(); ctx.fillStyle = "white"; ctx.moveTo(move.x*scaleX + INNER_RADIUS*scaleX, move.y*scaleY); ctx.arc(move.x*scaleX, move.y*scaleY, INNER_RADIUS*scaleX, 0, Math.PI*2, true); ctx.fill(); } } function count(){ var ret = 0; for(var i in _touches){ ret++; } return ret; } function get(item){ var ret = []; for(var i in _touches){ var touch = _touches[i]; ret.push({x:(touch.moveX - touch.startX)/LIMIT_X, y:(touch.moveY - touch.startY)/LIMIT_Y, id:i}); } console.log("get", ret); if(item === undefined){ return ret; }else{ return ret[item]; } } function unOffset(x, y, elm){ if(elm.offsetParent){ var u = unOffset(x, y, elm.offsetParent); return {x:u.x - elm.offsetLeft, y:u.y - elm.offsetTop}; }else{ return {x:x - elm.offsetLeft, y:y - elm.offsetTop}; } } function onTouchStart(e){ var changedTouches = e.changedTouches; var limitIndex = count(); var limit; for(var i=0; i<changedTouches.length; i++, limitIndex++){ var touch = changedTouches[i]; if(limitIndex < _limits.length){ limit = _limits[limitIndex]; _touches["t"+touch.identifier] = {startX:touch.pageX, startY:touch.pageY, moveX:touch.pageX, moveY:touch.pageY, limitX:limit.limitX*LIMIT_X, limitY:limit.limitY*LIMIT_Y}; } } e.preventDefault(); return false; } function onTouchMove(e){ var changedTouches = e.changedTouches; for(var i=0; i<changedTouches.length; i++){ var touch = changedTouches[i]; var t = _touches["t"+touch.identifier]; limit(t, touch.pageX, touch.pageY, t.limitX, t.limitY); } e.preventDefault(); return false; } function onTouchEnd(e){ var changedTouches = e.changedTouches; for(var i=0; i<changedTouches.length; i++){ var touch = changedTouches[i]; delete _touches["t"+touch.identifier]; } e.preventDefault(); return false; } function limit(stick, x, y, limitX, limitY){ var dx = (x - stick.startX); var dy = (y - stick.startY); var dist = Math.sqrt(dx*dx + dy*dy); limitX *= dx/dist; limitY *= dy/dist; if(limitX == 0){ stick.moveX = stick.startX; }else if(limitX > 0){ stick.moveX = Math.min(dx, limitX) + stick.startX; }else if(limitX < 0){ stick.moveX = Math.max(dx, limitX) + stick.startX; } if(limitY == 0){ stick.moveY = stick.startY; }else if(limitY > 0){ stick.moveY = Math.min(dy, limitY) + stick.startY; }else if(limitY < 0){ stick.moveY = Math.max(dy, limitY) + stick.startY; }/* if(dist > limit){ stick.moveX = (x - stick.startX)/dist*limit + stick.startX; stick.moveY = (y - stick.startY)/dist*limit + stick.startY; }else{ stick.moveX = x; stick.moveY = y; }*/ } return {init:init, draw:draw, get:get, count:count}; })();
angular.module('starter.controllers', []) .directive('ionSelect', function () { 'use strict'; return { restrict: 'EAC', scope: { label: '@', labelField: '@', provider: '=', ngModel: '=?', ngValue: '=?', saveItemSelected: '&', }, require: '?ngModel', transclude: false, replace: false, templateUrl: 'templates/item-search.html', link: function (scope, element, attrs, ngModel, ctrl) { scope.ngValue = scope.ngValue !== undefined ? scope.ngValue : 'item'; scope.selecionar = function (item) { ngModel.$setViewValue(item); scope.showHide = false; }; element.bind('click', function () { if (ctrl && ctrl.isFocused(scope.id)) { element.find('input').focus(); } }); scope.open = function () { scope.ngModel = ""; return scope.showHide = !scope.showHide; }; scope.onKeyDown = function () { scope.showHide = true; if (!scope.ngModel) { scope.showHide = false; } } scope.saveitem = function () { console.log(scope.ngModel); scope.saveItemSelected(scope.ngModel); } scope.$watch('ngModel', function (newValue) { if (newValue) element.find('input').val(newValue[scope.labelField]); }); }, }; }) .controller('DashCtrl', function ($scope) { }) .controller('AboutCtrl', function ($scope) { }) .controller('CartsCtrl', function ($scope, $ionicModal, Carts) { $ionicModal.fromTemplateUrl('templates/cart-add-change-dialog.html', { scope: $scope, animation: 'slide-in-up' }).then(function (modal) { $scope.modal = modal; }); $scope.openModal = function () { $scope.edit = false; $scope.modal.show(); }; $scope.editModal = function (cart) { $scope.edit = true; $scope.cart = cart; $scope.modal.show(); }; $scope.closeModal = function () { //$scope.modal.remove(); $scope.modal.hide(); $scope.leaveAddChangeDialog(); }; // Cleanup the modal when we're done with it! $scope.$on('$destroy', function () { $scope.modal.remove(); }); // Execute action on hide modal $scope.$on('modal.hidden', function () { // Execute action }); // Execute action on remove modal $scope.$on('modal.removed', function () { // Execute action $scope.modal.remove(); }); $scope.leaveAddChangeDialog = function () { // Remove dialog $scope.modal.remove(); // Reload modal template to have cleared form $ionicModal.fromTemplateUrl('templates/cart-add-change-dialog.html', function (modal) { $scope.modal = modal; }, { scope: $scope, animation: 'slide-in-up' }); }; //Ionic Modal window code finish/////////// $scope.carts = Carts.all(); $scope.items = Carts.getItems(); $scope.remove = function (cart) { Carts.remove(cart); }; $scope.getItemsCount = function (cart) { var count = 0; angular.forEach(cart.Items, function (item) { count += item.Bought ? 0 : 1; }); return count; }; $scope.updateCart = function(cart){ for (var i = 0, len = $scope.carts.length; i < len; i++) { if ($scope.carts[i].CartID === cart.CartID) { $scope.carts[i].Name = cart.Name; } } $scope.leaveAddChangeDialog(); } $scope.createCart = function (name, isCopy, cartIDtoCopy) { if (name == null) name = "New Cart" var its = []; if (isCopy == null || cartIDtoCopy == null) its = []; else { // get the items from existing cart for (var i = 0, len = $scope.carts.length; i < len; i++) { if ($scope.carts[i].CartID === cartIDtoCopy) { angular.copy($scope.carts[i].Items,its); } } } if (its.length > 0) { for (var j = 0, ln = its.length; j < ln; j++) { its[j].Bought = false; } } var index = 0; for (var i = 0, len = $scope.carts.length; i < len; i++) { if ($scope.carts[i].CartID > index) { index = $scope.carts[i].CartID; } } var c = { CartID: index + 1, Name: name, Completed: false, Items: its } $scope.carts.unshift(c); $scope.leaveAddChangeDialog(); } }) .controller('CartDetailCtrl', function ($scope, $ionicModal, $stateParams, Carts) { $ionicModal.fromTemplateUrl('templates/cart-item-detail.html', { scope: $scope, animation: 'slide-in-up' }).then(function (modal) { $scope.modal = modal; }); $scope.openModal = function (item) { $scope.cartItem = item; $scope.Quantity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $scope.modal.show(); }; $scope.editModal = function (item) { $scope.cartItem = item; $scope.modal.show(); }; $scope.closeModal = function () { //$scope.modal.remove(); $scope.modal.hide(); $scope.leaveAddChangeDialog(); }; // Cleanup the modal when we're done with it! $scope.$on('$destroy', function () { $scope.modal.remove(); }); // Execute action on hide modal $scope.$on('modal.hidden', function () { // Execute action }); // Execute action on remove modal $scope.$on('modal.removed', function () { // Execute action $scope.modal.remove(); }); $scope.leaveAddChangeDialog = function () { // Remove dialog $scope.modal.remove(); // Reload modal template to have cleared form $ionicModal.fromTemplateUrl('templates/cart-item-detail.html', function (modal) { $scope.modal = modal; }, { scope: $scope, animation: 'slide-in-up' }); }; //Ionic Modal window code finish/////////// $scope.cart = Carts.get($stateParams.cartId); $scope.allItems = Carts.getItems(); var data = [{ id: 1, nmPlaca: 'IKC-1394' }, { id: 2, nmPlaca: 'IKY-5437' }, { id: 3, nmPlaca: 'IKC-1393' }, { id: 4, nmPlaca: 'IKI-5437' }, { id: 5, nmPlaca: 'IOC-8749' }, { id: 6, nmPlaca: 'IMG-6509' }]; $scope.veiculos = data; $scope.testa = function () { alert($scope.veiculo.nmPlaca); } $scope.saveItemSelected = function (val) { console.log('save Item Selected'); console.log(val); } $scope.getItemsCount = function () { var count = 0; angular.forEach($scope.cart.Items, function (item) { count += item.Bought ? 0 : 1; }); return count; }; $scope.getUniqueCategories = function (cart) { var unique = []; angular.forEach(cart.Items, function (item) { if (unique.indexOf(item.CategoryName) == -1) unique.push(item.CategoryName) }); return unique; }; $scope.getItemPrice = function (i) { var data angular.forEach($scope.allItems, function (item) { if (item.Item === i) data = item.Price1; }); if (data == 0) return ""; else return "$" + data; }; $scope.updateItem = function (item) { var index = $scope.cart.Items.indexOf(item); $scope.cart.Items.splice(index, 1, item); $scope.leaveAddChangeDialog(); } $scope.deleteItem = function (item) { var index = $scope.cart.Items.indexOf(item); $scope.cart.Items.splice(index, 1); $scope.leaveAddChangeDialog(); } $scope.markAllItemsUnBought = function () { angular.forEach($scope.cart.Items, function (item) { item.Bought = false; }); } $scope.deleteAllItems = function () { $scope.cart.Items.splice(0, $scope.cart.Items.length); } }) .controller('ItemsCtrl', function ($scope, Items) { $scope.items = Items.all(); $scope.remove = function (item) { Items.remove(item); } $scope.getUniqueCategories = function (){ var unique = []; angular.forEach($scope.items, function (item) { if (unique.indexOf(item.CategoryName) == -1) unique.push(item.CategoryName) }); return unique; } }) .controller('CartItemDetailCtrl', function ($scope, $stateParams, Carts) { }) .controller('ChatsCtrl', function($scope, Chats) { // With the new view caching in Ionic, Controllers are only called // when they are recreated or on app start, instead of every page change. // To listen for when this page is active (for example, to refresh data), // listen for the $ionicView.enter event: // //$scope.$on('$ionicView.enter', function(e) { //}); $scope.chats = Chats.all(); $scope.remove = function(chat) { Chats.remove(chat); }; }) .controller('ChatDetailCtrl', function($scope, $stateParams, Chats) { $scope.chat = Chats.get($stateParams.chatId); }) .controller('AccountCtrl', function($scope) { $scope.settings = { enableFriends: true }; })
import React from "react"; import ErrorView from "./ErrorView"; /** * ErrorBoundary * * A component that will catch an error thrown in a render-phase method of its * descendants and display an ErrorView. Note that this only catches render-phase * errors, so to catch an error in an asynchronous call or event handler, you * should add the error to the component's state and then rethrow it inside of * render(): * * class Foo extends React.Component<Props, State> { * state = { * error: undefined, * }; * * handleLoad = () => { * try { * // code that throws an error * } catch (error) { * this.setState({ error }); * } * } * * render() { * if (this.state.error) throw this.state.error; * * // render JSX * } * } * * const Bar = () => <ErrorBoundary><Foo /></ErrorBoundary>; */ class ErrorBoundary extends React.Component { state = { error: undefined, }; componentDidCatch(error) { console.log(error); this.setState({ error }); } render() { // eslint-disable-next-line react/prop-types const { children } = this.props; const { error } = this.state; return error ? <ErrorView error={error} /> : children; } } export default ErrorBoundary;
//drugdealer here /* te duci la drug house si dai getjob si work te duci la aeroport sa iei drogurile [15:37:9] aicipunemunpachetmareptdrug - -1644.8079833984375, -3181.781982421875, 13.584409713745117 [15:38:36] aiciducemdrogurilesiledescarcam - 1736.169921875, -1669.5384521484375, 112.5819320678711 */ var GetJobPointDrugDealer = new mp.Vector3(710.8890991210938, -909.504638671875, 23.70233154296875); var GetDrugsPos = new mp.Vector3(-106.04041290283203, 2796.39306640625, 52.5); mp.markers.new(1, new mp.Vector3(710.8890991210938, -909.504638671875, 22.5), 1, { color: [225, 0, 0, 255], visible: true, dimension: 0 }); mp.markers.new(1, new mp.Vector3(-106.04041290283203, 2796.39306640625, 52.5), 1, { color: [225, 0, 0, 255], visible: true, dimension: 0 }); mp.events.add({ 'render': () => { if (distance(player.position, GetJobPointDrugDealer) < 5) { mp.game.graphics.drawText("~b~Drug Dealer Job ~n~ ~r~[/getjob]", [GetJobPointDrugDealer.x, GetJobPointDrugDealer.y, GetJobPointDrugDealer.z], { font: 4, color: [255, 255, 255, 255], scale: [0.5, 0.5], outline: false, center: true }); } if (distance(player.position, GetDrugsPos) < 5) { mp.game.graphics.drawText("~b~Drug Dealer Job ~n~ ~r~[/getdrugs]", [GetDrugsPos.x, GetDrugsPos.y, GetDrugsPos.z + 1.5], { font: 4, color: [255, 255, 255, 255], scale: [0.5, 0.5], outline: false, center: true }); } } });
module.exports = function (app) { var path = require('path'); var cfenv = require("cfenv"); var appEnv = cfenv.getAppEnv(); var commentWallCloudant = appEnv.getService("commentWallCloudant"); var Cloudant = require('cloudant'); var cloudant = Cloudant(commentWallCloudant.credentials.url); var db = cloudant.db.use('scrapbook'); app.get('/', function(req, res) { res.render('index.html'); }); //TODO: Use unique ID for users so people can have the same names app.get('/api/getComments', function(req, res) { //TODO: filter out xml to prevent XXS attacks var requestedName = req.query.name; if(requestedName == '' || requestedName == null){ res.status(400).json({ok:false, msg:'name is a required parameter.'}); return; } db.list({include_docs:true},function(err, body) { if (err) { console.log("error getting comments: " + err); res.status(500).json({ok:false}); return; } var comments = []; // find all comments for the requested user and format them body.rows.forEach(function(entry) { if(entry.doc.to.toUpperCase() == requestedName.toUpperCase()){ comments.push({from: entry.doc.from, msg: entry.doc.msg}); } }); res.json({msgs:comments}); }); }); app.post('/api/addComment', function(req, res) { var toParam = req.body.to; var fromParam = req.body.from; var msgParam = req.body.msg; var comment = {to: toParam, from: fromParam, msg: msgParam}; db.insert(comment, function(err, body) { if (err){ console.log("error adding comment: " + err); res.status(500).json({ok:false}); return; } console.log('----------\nAdded comment for: ' + toParam + '\nfrom: ' + fromParam + '\nmessage: ' + msgParam + '\n----------'); res.json(body); }); }); }
import React, { useState, useEffect } from 'react' import client from '../lib/sanity'; import NavBar from '../components/navbar' import PageTitle from '../components/bits/pageTitle' import ArticleModule from '../components/articleModule' import PressKitModule from '../components/pressKitModule' import Footer from '../components/footer'; import Grid from '../components/bits/grid.js'; export default function PressPage(props) { const [moduleData, setModuleData] = useState([]); useEffect(() => { const query = `{ "pressPage": *[_type == "press"], "footerModule": *[_type == "footerModule"][0], }`; client.fetch(query).then(data => { setModuleData(data); }); }, []); const press = moduleData.length !== 0 && moduleData.pressPage[0] return ( <div className="press"> <Grid show={false}/> <NavBar {...props} theme="light" /> <div className="press__wrapper"> {press && <React.Fragment> <PageTitle title={press._id.charAt(0).toUpperCase() + press._id.slice(1)} subtitle={press.abstract} /> <div className="press__link"> <a href='#press-kit'>Take me to the press kit</a> </div> <ArticleModule articles={press.articles} /> </React.Fragment> } </div> <div id="press-kit" className="press__press-kit"> <div className="press__wrapper"> {press && <React.Fragment> <PageTitle title={press.pressKitTitle} subtitle={press.pressKitDescription} blue={true} /> <PressKitModule data={press} /> </React.Fragment> } </div> </div> { press ? <React.Fragment> <Footer m={moduleData.footerModule} /> </React.Fragment> : <div className="App">Loading</div> } </div> ) }
OC.L10N.register( "settings", { "Authentication error" : "அத்தாட்சிப்படுத்தலில் வழு", "Create" : "உருவாக்குக", "Delete" : "நீக்குக", "Share" : "பகிர்வு", "Language changed" : "மொழி மாற்றப்பட்டது", "Invalid request" : "செல்லுபடியற்ற வேண்டுகோள்", "All" : "எல்லாம்", "Disable" : "இயலுமைப்ப", "Enable" : "இயலுமைப்படுத்துக", "Groups" : "குழுக்கள்", "undo" : "முன் செயல் நீக்கம் ", "Delete group" : "குழுக்களை நீக்குக", "never" : "ஒருபோதும்", "Language" : "மொழி", "None" : "ஒன்றுமில்லை", "Save" : "சேமிக்க ", "Login" : "புகுபதிகை", "Encryption" : "மறைக்குறியீடு", "Server address" : "சேவையக முகவரி", "Port" : "துறை ", "Credentials" : "சான்று ஆவணங்கள்", "Add" : "சேர்க்க", "Cancel" : "இரத்து செய்க", "Email" : "மின்னஞ்சல்", "Your email address" : "உங்களுடைய மின்னஞ்சல் முகவரி", "Password" : "கடவுச்சொல்", "Unable to change your password" : "உங்களுடைய கடவுச்சொல்லை மாற்றமுடியாது", "Current password" : "தற்போதைய கடவுச்சொல்", "New password" : "புதிய கடவுச்சொல்", "Change password" : "கடவுச்சொல்லை மாற்றுக", "Help translate" : "மொழிபெயர்க்க உதவி", "Name" : "பெயர்", "Username" : "பயனாளர் பெயர்", "Personal" : "தனிப்பட்ட", "Admin" : "நிர்வாகம்", "Settings" : "அமைப்புகள்", "Default Quota" : "பொது இருப்பு பங்கு", "Other" : "மற்றவை", "Quota" : "பங்கு" }, "nplurals=2; plural=(n != 1);");
import Vue from 'vue' import Router from 'vue-router' import test from '@/components/test/index' Vue.use(Router) export const constantRouterMap = [ { path: '/', component: () => import('@/components/home/index'), hidden: true } ] export const asyncRouterMap = [ { } ] export default new Router({ // mode: 'history', routes: [ { path: '/', name: 'index', component: () => import('@/components/home/index') }, { path: '/test', name: 'test', component: test }, { path: '/list', name: 'list', component: () => import('@/components/articleList/index') }, { path: '/info', name: 'info', component: () => import('@/components/articleList/articleInfo') } ] })
import React, {Component, Fragment} from 'react' import cn from 'classnames' import styles from './styles.styl' class ShowMoreOrLess extends Component { constructor(props) { super(props); this.state = { isOpen: false, } } toggle = () => { this.setState({ isOpen: !this.state.isOpen }); } getRenderedItems() { const {row, perRowElements, items} = this.props if (this.state.isOpen) { return items; } // for (let i = 0 ; i< row && this.props.items.length > perRowElements; i++) { // elements.push( this.props.items.slice(0, 4)) // } // let elements = [] // for (let i = 0 ; i< row; i++) { // elements.push(items.slice(i*perRowElements, perRowElements*(i+1))) // } // // console.log(elements) // return elements return this.props.items.slice(0, row*perRowElements) } render() { return( <Fragment> <div className="row"> { this.getRenderedItems().map((item, id) => ( <div className="col-sm-6 col-md-4 col-lg-3 text-center" key={id}> <div className={cn(styles['my-4'], styles['px-4'], styles['w-100'])}> <img src={item} /> </div> </div> )) } </div> <button onClick={this.toggle} className={cn(styles['w-100'], styles['button-color'], 'btn btn-link')}> {this.state.isOpen ? 'Show Less' : 'View More'} </button> </Fragment> ); } } export default ShowMoreOrLess
var searchData= [ ['spawner',['Spawner',['../classSpawner.html',1,'']]], ['subject',['Subject',['../classSubject.html',1,'']]] ];
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * @author Nguyen Ba Uoc */ function CoreEditor() { this.autoDetectFire = false ; this.HTMLUtil = eXo.core.HTMLUtil ; } ; /** * * @param {Element} node */ CoreEditor.prototype.isContainerNode = function(node) { if (!node) return ; if (node.getAttribute && node.getAttribute('editcontainer') == 1) { return true ; } return false ; } ; /** * * @param {Element} node */ CoreEditor.prototype.isEditableNode = function(node) { if (!node) return ; if (node.getAttribute && node.getAttribute('editable') == '1') { return true ; } return false ; } ; CoreEditor.prototype.registerCoreEditors = function(node4Reg) { if (node4Reg && !node4Reg.nodeName) { node4Reg = document.getElementById(node4Reg) ; } if (!node4Reg || node4Reg.nodeType != 1) { node4Reg = document.body ; // throw (new Error('Error when register...')) ; } var nodeList = node4Reg.getElementsByTagName('*') ; for(var i=0; i<nodeList.length; i++) { var node = nodeList.item(i) ; if (node.nodeType == 1 && this.isContainerNode(node) && node.getAttribute('handler')) { this.registerSubCoreEditor(node) ; node.onclick = this.autoDetectSubCoreEditor ; } } } ; /** * * @param {Element} node */ CoreEditor.prototype.registerSubCoreEditor = function(node) { var childNodes = node.getElementsByTagName('*') ; for(var i=0; i<childNodes.length; i++) { var child = childNodes[i] ; if(this.isEditableNode(child) == 1) { child.onclick = function(event) { eXo.core.Keyboard.cancelEvent(event) ; return eXo.core.CoreEditor.init(this); } ; } } } ; /** * * @param {Event} event */ CoreEditor.prototype.autoDetectSubCoreEditor = function(event) { var childNodes = this.childNodes ; for(var i=0; i<childNodes.length; i++) { var child = childNodes[i] ; if(eXo.core.CoreEditor.isEditableNode(child) && child.onclick) { eXo.core.CoreEditor.autoDetectFire = true ; eXo.core.Keyboard.cancelEvent(event) ; return eXo.core.CoreEditor.init(child); } } } ; CoreEditor.prototype.init = function(node) { if(node == null) return ; if(this.isMultiSelection()) { return ; } if (!this.autoDetectHandler(node)) { throw (new Error('Missing keyboard handler!')) ; } var clickPosition = this.getClickPosition(node) ; this.clearSelection() ; var text = this.HTMLUtil.entitiesDecode(node.innerHTML) ; var beforeCursor = '' ; var afterCursor = '' ; if(clickPosition > 0) { beforeCursor = text.substring(0, clickPosition) ; afterCursor = text.substring(clickPosition, text.length) ; } else if(clickPosition == 0) { beforeCursor = '' ; afterCursor = text ; } beforeCursor = this.HTMLUtil.entitiesEncode(beforeCursor) ; afterCursor = this.HTMLUtil.entitiesEncode(afterCursor) ; this.handler.init(node, beforeCursor, afterCursor) ; this.handler.defaultWrite() ; eXo.core.Keyboard.finish() ; eXo.core.Keyboard.init() ; eXo.core.Keyboard.register(this.handler) ; document.onclick = eXo.core.CoreEditor.onFinish ; return false ; } ; /** * @param {Element} node * * @return {DefaultKeyboardListener} */ CoreEditor.prototype.autoDetectHandler = function(node) { if (!node) return ; var handler = false ; for (var nodeIter = node;; nodeIter = nodeIter.parentNode) { if (nodeIter.nodeType == 1) { if (nodeIter.className == 'UIWindow') break ; if (this.isContainerNode(nodeIter)) { handler = nodeIter.getAttribute('handler') ; break ; } } } try { this.handler = eval(handler) ; if (!this.handler) return false ; return true ; } catch (e) { return false ; } } ; /** * * @param {Element} node */ CoreEditor.prototype.isProcessMultiSelect = function(node) { if (!node) return ; while((node = node.parentNode) && node.className != 'UIWindow') { if (!this.isContainerNode(node)) break ; } if (node.getAttribute && node.getAttribute('multiselect') == '1') { return true ; } return false ; } ; CoreEditor.prototype.onFinish = function(event) { eXo.core.Keyboard.finish() ; if (eXo.core.CoreEditor.handler) { var containerNode = eXo.core.CoreEditor.handler.currentNode ; while (containerNode && (containerNode = containerNode.parentNode) && containerNode.className && containerNode.className != 'UIWindow') { if (eXo.core.CoreEditor.isContainerNode(containerNode)) { } } eXo.core.CoreEditor.handler.onFinish() ; } } ; CoreEditor.prototype.isMultiSelection = function() { if(window.getSelection) { // Netscape/Firefox/Opera if(window.getSelection().toString().length > 0) { return true ; } else { return false ; } } else if(document.selection && document.selection.createRange) { // IE Only if(document.selection.createRange().text.length > 0) { return true ; } else { return false ; } } } ; CoreEditor.prototype.clearSelection = function() { if (window.getSelection) { // Netscape/Firefox/Opera window.getSelection().removeAllRanges() ; } else if(document.selection && document.selection.createRange) { // IE Only document.selection.clear() ; } this.handler.removeCursor() ; } ; CoreEditor.prototype.getClickPosition = function(node) { if (this.autoDetectFire) { this.autoDetectFire = !this.autoDetectFire ; return node.innerHTML.length ; } if(window.getSelection) { // Netscape/Firefox/Opera var selObj = window.getSelection() ; var clickPos = selObj.anchorOffset ; if(selObj.anchorNode && selObj.anchorNode.nodeType == 3) { var tmpTextNode = selObj.anchorNode.previousSibling ; while(tmpTextNode) { if(tmpTextNode.nodeType == 3) { clickPos += tmpTextNode.nodeValue.length ; } tmpTextNode = tmpTextNode.previousSibling ; } } return clickPos ; } else if(document.selection && document.selection.createRange) { // IE Only var sel = document.selection.createRange(); var clone = sel.duplicate(); sel.collapse(true); clone.moveToElementText(node); clone.setEndPoint('EndToEnd', sel); return clone.text.length; } } ; eXo.core.CoreEditor = new CoreEditor() ;
import React from 'react' import PropTypes from 'prop-types' // Components import { reduxForm, Field } from 'redux-form' import {Select, Input, FieldWrapper} from '../../components/forms' import {createTranslate} from '../../../locales/translate' import {Form} from '../../components/controls/SemanticControls' // module stuff import config, {ClientLinkOptions, DocumentDateOptions, DocumentStatusOptions} from '../../../modules/form-templates/config' import validateTemplateProperties from '../../../modules/form-templates/validate' class TemplatePropertiesForm extends React.PureComponent { constructor (props) { super(props) this.message = createTranslate('formTemplates', this) this.clientLinkOptions = [ {id: ClientLinkOptions.NO_LINK, label: this.message('clientLinkOptions.noLink')}, {id: ClientLinkOptions.MANDATORY, label: this.message('clientLinkOptions.mandatory')} ] this.documentDateOptions = [ {id: DocumentDateOptions.USE_CREATION_DATE, label: this.message('documentDateOptions.useCreationDate')}, {id: DocumentDateOptions.SET_BY_USER, label: this.message('documentDateOptions.setByUser')} ] this.documentStatusOptions = [ {id: DocumentStatusOptions.NO_DRAFT, label: this.message('documentStatusOptions.noDraft')}, {id: DocumentStatusOptions.USE_DRAFT, label: this.message('documentStatusOptions.useDraft')} ] } render () { const {locale} = this.props return ( <Form> <Field name="clientLink" label={this.message('clientLink')} required component={FieldWrapper} InputControl={Select} locale={locale} options={this.clientLinkOptions} hasNoSelectionValue={false} /> <Field name="documentStatus" label={this.message('documentStatus')} required component={FieldWrapper} InputControl={Select} locale={locale} options={this.documentStatusOptions} hasNoSelectionValue={false} /> <Field name="documentDate" label={this.message('documentDate')} required component={FieldWrapper} InputControl={Select} locale={locale} options={this.documentDateOptions} hasNoSelectionValue={false} /> <label>{this.message('documentDateLabel')}</label> <div className="row"> <div className="col-6"> <Field name="documentDateLabels.fr" label={this.message('fr', 'common')} component={FieldWrapper} InputControl={Input} locale={locale} /> </div> <div className="col-6"> <Field name="documentDateLabels.en" label={this.message('en', 'common')} component={FieldWrapper} InputControl={Input} locale={locale} /> </div> </div> </Form> ) } } TemplatePropertiesForm.propTypes = { locale: PropTypes.string.isRequired } const ConnectedTemplatePropertiesForm = reduxForm({ form: config.entityName, validate: validateTemplateProperties })(TemplatePropertiesForm) export default ConnectedTemplatePropertiesForm
// Global namespace, window variables, etc. $ = jQuery; var App = { windowWidth: $(window).width(), windowHeight: $(window).height(), scrollTop: $(window).scrollTop(), }; $(window).resize(function() { App.windowWidth = $(window).width(); App.windowHeight = $(window).height(); }); $(window).scroll(function() { App.scrollTop = $(window).scrollTop(); }); App.breakpoint = function(checkIfSize) { var xs = 480; var sm = 768; var md = 992; var lg = 1200; var breakpoint; if(App.windowWidth < xs) { breakpoint = 'xs'; } else if(App.windowWidth >= md) { breakpoint = 'lg'; } else if(App.windowWidth >= sm) { breakpoint = 'md'; } else { breakpoint = 'sm'; } if(checkIfSize !== undefined) { if(checkIfSize == 'xs') { return App.windowWidth < xs; } else if(checkIfSize == 'sm') { return (App.windowWidth >= xs && App.windowWidth < sm); } else if(checkIfSize == 'md') { return (App.windowWidth >= sm && App.windowWidth < md); } else if(checkIfSize == 'lg') { return App.windowWidth >= md; } } else { return breakpoint; } }; App.breakpoint.isMobile = function() { return ( App.breakpoint('xs') || App.breakpoint('sm') ); }; $(document).on('mouseenter', '.flower-nav__leaf', function() { var $leaf = $(this); var orientation = $leaf.attr('data-orientation'); var $leafTitles = $('.flower-nav__leaf__title'); var $leafTitle = $('.flower-nav__leaf__title[data-orientation="' + orientation + '"]'); var $initialActive = $leafTitles.closest('.initial-active'); var chime = new Audio('audio/chime.wav'); chime.volume = 0.5; chime.play(); $leafTitles.removeClass('active'); $leafTitle.addClass('active'); }); $(document).on('mouseleave', '.flower-nav__leaf', function() { var $leafTitles = $('.flower-nav__leaf__title'); var $initialActive = $leafTitles.closest('.initial-active'); $leafTitles.removeClass('active'); $initialActive.addClass('active'); }); // Fix a problem where some browsers don't like anchors inside svg elements $(document).on('click touchstart', '.flower-nav__leaf a', function(e) { var url = $(this).attr('href'); if ( e.ctrlKey || e.shiftKey || e.metaKey || ( e.button && e.button == 1 ) ) { window.open( url ); } else { window.location = url; } }); $(function() { var $viewport = $('.parallax-viewport'); var $layers = $viewport.find('.parallax-layer'); $(document).on('mousemove', function(e) { $layers.each(function(index) { parallax(e, this, index + 1); }); }); function parallax(e, target, layer) { var layerCoeffX = ( App.windowWidth / 19 ) / layer; var layerCoeffY = ( App.windowHeight / 26 ) / layer; var x = ( App.windowWidth - target.offsetWidth) / 2 - (e.pageX - (App.windowWidth / 2) ) / layerCoeffX; var y = ( App.windowHeight - target.offsetHeight) / 2 - (e.pageY - (App.windowHeight / 2) ) / layerCoeffY; $(target).css({ transform: 'translate(' + x + 'px, ' + y + 'px)' }); } });
const {ObjectId} = require('mongodb'); class OperationError extends Error{ constructor(msg) { super(msg); } } function objectId (id) { if (id instanceof ObjectId) {return id;} if (typeof id !== "string" || id.length !== 24 || id.search(/^[0-9a-f]{24}$/ig)) {return null;} return ObjectId(id); } /** * 获取ID数组 * @param {Array | Id} id 数组或者Id * @return {Array} Id数组 */ function objectIdArray(id) { let ret =[]; if (id instanceof Array) { id.map(id=>{ id = objectId(id); if(id) {ret.push(id);} }) } else { id = objectId(id); if(id) {ret.push(id);} } return ret; } /** * 添加日志 */ async function addLog(refid, user, handle, name, explain) { switch (handle) { case 0: case false: handle = 0; name = "关闭工单"; break; case 1: case true: handle = 1; name = "创建工单"; break; case 3: name = "重新打开"; break; default: if (!handle) { handle = ""; name = ""; } else { handle = String(handle); } } if (!name) { name = ""; } else { name = String(name); } if (!(explain && typeof explain === "string")) { explain = ""; } await this.db.log.insert({refid: objectId(refid), user, date: new Date, handle, name, explain}); } async function getLog(refid) { return this.db.log.find({refid: objectId(refid)}).toArray(); } /** * 创建工单 * @param {String} options.group 工单分组 * @param {String} options.title 工单标题 * @param {String[]} options.flag 工单标志 * @param {String} options.refid 工单关联Id * @param {String} options.user 工单创建用户 * @param {Object<String[]>} options.category 工单分类 */ async function create({group, title, flag, refid, user, category}) { group = String(group); title = String(title); flag = Array.isArray(flag) ? flag.map(String) : (flag ? [String(flag)] : []); refid = String(refid); user = String(user); if (category && typeof category === "object") { let c = {}; for(let k in category) { let value = category[k]; if (typeof value === "string") { c[k] = value ? [value] : []; } else if (Array.isArray(value)){ c[k] = value.filter(x=>x).map(String).filter(x=>x); } } category = c; } else { category = {}; } if(!(group in this.group)) { throw new OperationError("工单组无效"); } if(!title) { throw new OperationError("请填写工单名称"); } if (!refid) { throw new OperationError("请填写关联Id"); } let value = { group: group, title: title, flag: flag, refid: refid, user: user, category: category, status: 3, //0关闭,1完成,2驳回,3处理中 createDate: new Date(), updateDate: new Date(), historyUser: [user], historyFlag: flag, }; let {insertedIds} = await this.db.list.insert(value); if (!insertedIds) { throw new OperationError("创建失败"); } let id = insertedIds[0]; if (id) { await this.addLog(id, user, true); return id; } throw new OperationError("创建失败"); } /** * 关闭工单 * @param {String} id 工单Id * @param {String} user 工单关闭用户 */ async function close(id, user) { if (!(id = objectId(id))) { throw new OperationError("工单无效"); } user = String(user); let {result} = await this.db.list.update( {_id: id, status: {$ne: 0}}, { $set:{status: 0, updateDate: new Date()}, $addToSet: {historyUser:user}, } ); if (result && result.ok && result.nModified) { await this.addLog(id, user, 0); return true; } return false; } /** * 重新开放驳回的工单 * @param {String} id 工单Id * @param {String} options.user 工单打开用户 * @param {String[]} options.flag 工单标志 * @param {Object<String[]>} options.category 工单分类 */ async function open(id, {user, flag, category}) { if (!(id = objectId(id))) { throw new OperationError("工单无效"); } user = String(user); flag = Array.isArray(flag) ? flag.map(String) : (flag ? [String(flag)] : null); if (category && typeof category === "object") { let c = {}; for(let k in category) { let value = category[k]; if (typeof value === "string") { c[k] = value ? [value] : []; } else if (Array.isArray(value)){ c[k] = value.filter(x=>x).map(String).filter(x=>x); } } category = c; } else { category = null; } const $set = {status: 3, updateDate: new Date()}; const $addToSet = {historyUser:user}; if (flag) { $set.flag = flag; $addToSet.historyFlag = {$each: flag}; } if (category) { $set.category = category; } let {result} = await this.db.list.update({_id: id, status: 2}, {$set, $addToSet}); if (result && result.ok && result.nModified) { await this.addLog(id, user, 3); return true; } return false; } /** * 移除工单 * @param {String} id 工单Id */ async function remove(id) { if (!(id = objectId(id))) { throw new OperationError("工单无效"); } let {result, matchedCount} = await this.db.list.remove({_id: id, status: 0}); if (result && result.ok && matchedCount) { await this.addLog(id, user, 0); return true; } return false; } /** * 获取工单信息 * @param {String} id 工单Id */ async function get(id, {group, flag} = {}) { if (Array.isArray(id)) { //获取一组工单,则直接获取信息 id = objectIdArray(id); const info = await this.db.list.find({_id:{$in:id}}).toArray(); info.forEach(info=>{info.id = info._id; delete info._id;}); return info; } else if (!(id = objectId(id))) { throw new OperationError("工单无效"); } const info = await this.db.list.findOne({_id: id}); if(!info) {throw new OperationError("找不到此工单");} info.id = info._id; delete info._id; if (Array.isArray(flag)) { flag = flag.map(String); } else { flag = null; } if (flag && flag.length && info.flag.length) { const g = info.flag; flag = flag.filter(x => g.has(x)); if (!flag.length) { throw new OperationError("工单标志无交集"); } } if (group && String(group) != info.group) { throw new OperationError("工单组不一致"); } else { const group = this.group[info.group]; if (group) { info.handle = await group.getOption(info.group, info.flag, info); } } return info; } /** * 处理工单 * @param {String} id 工单id * @param {String} options.handle 工单处理方式 * @param {String} options.group 限制工单组(选填,如果填,则必须为此组工单) * @param {String[]} options.flag 工单标志(选填,如果填,则必须有交集) * @param {String} options.user 工单处理用户 * @param {String} options.explain 工单处理说明 */ async function handle(id, {handle, group, flag, user, explain} = {}) { user = String(user); if (!(id = objectId(id))) { throw new OperationError("工单无效"); } if (!(handle && typeof handle === "string")) { throw new OperationError("操作无效") } let info = await this.db.list.findOne({_id: id, status: {$gte: 3}}); if(!info) { throw new OperationError("找不到此工单"); } if (group && String(group) != info.group) { throw new OperationError("工单组不一致"); } else { group = info.group; } const groupInfo = this.group[group]; if(!groupInfo) { throw new OperationError("找不到操作"); } if (Array.isArray(flag)) { flag = flag.map(String); } else { flag = null; } if (flag && flag.length && info.flag.length) { const g = info.flag; flag = flag.filter(x => g.has(x)); if (!flag.length) { throw new OperationError("工单标志无交集"); } } else { flag = info.flag; } info.id = info._id; delete info._id; //获取处理结果 let result = await groupInfo.handle(group, handle, flag, info); if (!result) { throw new OperationError("操作无效"); } const {status, flag:newFlag, set} = result; const $set = {}, $addToSet = {historyUser:user}; //状态 if (status === parseInt(status) && status >= 0) { $set.status = status; } //标志 if (Array.isArray(newFlag)) { $set.flag = newFlag.map(String); $addToSet.historyFlag = {$each:$set.flag}; } if (!Object.keys($set).length) { throw new OperationError("操作无效"); } //更新时间 $set.updateDate = new Date(); //更新 ({result} = await this.db.list.update({_id: id, status: info.status, group: info.group, flag: info.flag}, {$set, $addToSet})); //日志 await this.addLog(id, user, handle, groupInfo.option[handle], explain); return Boolean(result.ok); } /** * 获取工单列表 * @param {Number} options.status 工单状态 * @param {String | RegExp} options.title 工单标题 * @param {String | String[]} options.group 工单组 * @param {String | String[]} options.flag 工单标志 * @param {String | String[]} options.user 创建用户 * @param {String | String[]} options.historyUser 历史用户 * @param {String | String[]} options.historyFlag 历史标志 * @param {Object<String | String[]>} options.category 工单分类 * @param {Number} options.skip 跳过的记录数 * @param {Number} options.limit 最大返回数量 */ async function list({status, title, group, flag, user, historyUser, historyFlag, category, skip = 0, limit = 30,} = {}) { let condition = {}; //状态 if (status === parseInt(status) && status >= 0) { condition.status = status; } //标题 if(title instanceof RegExp) { condition.title = title; } else if (title && typeof title) { condition.title = new RegExp(title .replace(/\\/g,"\\\\").replace(/\./g,"\\.") .replace(/\[/g, "\\[").replace(/\]/g, "\\]") .replace(/\(/g, "\\(").replace(/\)/g, "\\)") .replace(/\(/g, "\\{").replace(/\)/g, "\\}") .replace(/\^/g, "\\^").replace(/\$/g, "\\$") .replace(/\+/g, "\\+").replace(/\*/g, "\\*").replace(/\?/g, "\\?") .replace(/\s+/g, ".*")); } //组 if (Array.isArray(group)) { let groups = this.group; group = group.map(String).filter(g => g in groups); if (group.length) { condition.group = {$in:group}; } } else if (group && (group = String(group)) && group in this.group) { condition.group = group; } //标志 if (Array.isArray(flag)) { flag = flag.map(String).filter(u => u); if (flag.length) { condition.flag = {$in:flag}; } } else if (flag && (flag = String(flag))) { condition.flag = flag; } //创建者 if (Array.isArray(user)) { user = user.map(String).filter(u => u); if (user.length) { condition.user = {$in:user}; } } else if (user && (user = String(user))) { condition.user = user; } //历史用户 if (Array.isArray(historyUser)) { historyUser = historyUser.map(String).filter(u => u); if (historyUser.length) { condition.historyUser = {$in:historyUser}; } } else if (historyUser && (historyUser = String(historyUser))) { condition.historyUser = historyUser; } //历史标志 if (Array.isArray(historyFlag)) { historyFlag = historyFlag.map(String).filter(u => u); if (historyFlag.length) { condition.historyFlag = {$in:historyFlag}; } } else if (historyFlag && (historyFlag = String(historyFlag))) { condition.historyFlag = historyFlag; } //类别 if (category && !Array.isArray(category) && typeof category === "object") { for (let k in category) { let value = category[k]; if (Array.isArray(value)) { value = value.filter(x=>x).map(String).filter(x=>x); } else if (value && typeof value === "string") { value = [value] } else { continue; } condition["category." + k] = value; } } const cursor = this.db.list.find(condition).sort({updateDate:1}).skip(skip).limit(limit); const [list, total] = await Promise.all([cursor.toArray(), cursor.count()]); list.forEach(info => { info.id = info._id; delete info._id; }); return {total, list}; } /** 获取用户可用标志 */ async function getUserFlag(group, ...args) { group = String(group); const groupInfo = this.group[group]; if(!groupInfo) { return []; } try { const flags = await groupInfo.getUserFlag(group, ...args); if (Array.isArray(flags)) { return flags.map(x => x ? String(x) : null).filter(x=>x); } return []; } catch(e) { return []; } } /** * 设置工单组 */ function setGroup(group, {getOption, handle, flag, title, option, getUserFlag}) { let groups = this.group; group = String(group); if (!group) { return false; } if (typeof getOption !== "function") { return false; } if (typeof handle !== "function") { return false; } if (typeof getUserFlag !== "function") { return false; } const flags = {}; if (flag && typeof flag === "object") { for (let k in flag) { let v = flag[k]; if (v && typeof v === "string") { flags[k] = v; } } } const options = {}; if (option && typeof option === "object") { for (let k in option) { let v = option[k]; if (v && typeof v === "string") { options[k] = v; } } } groups[group] = { title: String(title), getOption, handle, getUserFlag, flag: flags, option: options, } return true; } /** * 移除工单组 */ function removeGroup(group, entire) { let groups = this.group; group = String(group); if (!(group in groups)) { return false; } delete groups[group]; return true; } /** * 关闭工单组内全部工单 */ async function closeGroup(group) { await this.db.list.update({group: String(group), status: {$gte: 2}}, {$set:{status: 0, updateDate:new Date()}}, {multi: true}); } /** * 获取工单组列表 */ function getGroupList() { return Object.keys(this.group); } /** * 获取工单组标题列表 */ function getGroupTitleList() { const group = this.group; return Object.keys(group).map(k => [k, group[k].title]); } /** * 获取工单组信息 */ function getGroup(group) { let groups = this.group; group = String(group); if (!(group in groups)) { return null; } const {getOption, handle, getUserFlag, flag, title, option} = groups[group]; const flags = {}; for (let k in flag) { flags[k] = flag[k]; } const options = {}; for (let k in option) { options[k] = option[k]; } return {title, getOption, handle, getUserFlag, flag: flags, option: options}; } module.exports = async function init({collection}, init) { const ret = {}; const that = Object.create(ret); that.db = { list: collection.list, log: collection.log, }; if (init) { try {await that.db.navigation.ensureIndex({group: 1}, {name:"group"})} catch(e) {} try {await that.db.navigation.ensureIndex({flag: 1}, {name:"flag"})} catch(e) {} try {await that.db.navigation.ensureIndex({refid: 1}, {name:"refid"})} catch(e) {} try {await that.db.navigation.ensureIndex({status: 1}, {name:"status"})} catch(e) {} try {await that.db.navigation.ensureIndex({user: 1}, {name:"user"})} catch(e) {} try {await that.db.navigation.ensureIndex({createDate: 1}, {name:"createDate"})} catch(e) {} try {await that.db.navigation.ensureIndex({historyUser: 1}, {name:"historyUser"})} catch(e) {} try {await that.db.navigation.ensureIndex({historyFlag: 1}, {name:"historyFlag"})} catch(e) {} try {await that.db.navigation.ensureIndex({user: 1, group: 1}, {name:"user_group"})} catch(e) {} try {await that.db.navigation.ensureIndex({group: 1, user: 1}, {name:"group_user"})} catch(e) {} try {await that.db.navigation.ensureIndex({group: 1, flag: 1}, {name:"group_flag"})} catch(e) {} try {await that.db.navigation.ensureIndex({flag: 1, group: 1}, {name:"flag_group"})} catch(e) {} try {await that.db.navigation.ensureIndex({group: 1, refid: 1}, {name:"group_refid"})} catch(e) {} try {await that.db.navigation.ensureIndex({refid: 1, group: 1}, {name:"refid_group"})} catch(e) {} try {await that.db.navigation.ensureIndex({group: 1, historyFlag: 1}, {name:"group_historyFlag"})} catch(e) {} try {await that.db.navigation.ensureIndex({historyFlag: 1, group: 1}, {name:"historyFlag_group"})} catch(e) {} try {await that.db.log.ensureIndex({refid: 1}, {name:"refid"})} catch(e) {} } that.group = {}; that.addLog = addLog.bind(that); ret.create = create.bind(that); ret.list = list.bind(that); ret.close = close.bind(that); ret.open = open.bind(that); ret.remove = remove.bind(that); ret.get = get.bind(that); ret.handle = handle.bind(that); ret.getUserFlag = getUserFlag.bind(that); ret.setGroup = setGroup.bind(that); ret.removeGroup = removeGroup.bind(that); ret.closeGroup = closeGroup.bind(that); ret.getGroupList = getGroupList.bind(that); ret.getGroupTitleList = getGroupTitleList.bind(that); ret.getGroup = getGroup.bind(that); ret.log = getLog.bind(that); return ret; }
import {request} from './request' export function getResource() { return request({ url:'/getResource' }); } export function getfloorSwiper() { return request({ url:'/getfloorSwiper' }); }
/* eslint-disable no-unused-vars */ const DB_NAME = 'cfxnes'; const DB_VERSION = 1; let dbPromise; //========================================================= // Database //========================================================= function doWithDB(callback) { if (dbPromise == null) { dbPromise = openDB(); } return dbPromise.then(db => { return new Promise((resolve, reject) => callback(db, resolve, reject)); }); } function openDB() { return new Promise((resolve, reject) => { console.info(`Opening database ${DB_NAME} (version: ${DB_VERSION})`); const request = indexedDB.open(DB_NAME, DB_VERSION); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); request.onblocked = () => reject(new Error('Database is blocked and cannot be upgraded')); request.onupgradeneeded = event => upgrageDB(request, event.oldVersion, event.newVersion); }); } function upgrageDB(request, oldVersion, newVersion) { console.info(`Upgrading database ${DB_NAME} from version ${oldVersion} to ${newVersion}`); request.result.createObjectStore('nvram', {keyPath: 'sha1'}); } function closeDB() { if (dbPromise == null) { return Promise.resolve(); } return dbPromise.then(db => { console.info(`Closing database ${DB_NAME}`); db.close(); dbPromise = null; }); } function doWithClosedDB(callback) { return closeDB().then(() => new Promise(callback)); } function deleteDB() { return doWithClosedDB((resolve, reject) => { console.info(`Deleting database ${DB_NAME}`); const request = indexedDB.deleteDatabase(DB_NAME); request.onsuccess = () => resolve(); request.onerror = () => reject(request.error); request.onblocked = () => reject(new Error('Database is blocked and cannot be deleted')); }); } //========================================================= // NVRAM store //========================================================= function getNVRAM(sha1) { console.info(`Getting NVRAM from DB store for ${sha1}`); return doWithDB((db, resolve, reject) => { const transaction = db.transaction('nvram', 'readonly'); const store = transaction.objectStore('nvram'); const request = store.get(sha1); request.onsuccess = () => { const result = request.result; resolve((result && result['data']) || null); }; request.onerror = () => reject(request.error); }); } function putNVRAM(sha1, data) { console.info(`Putting NVRAM to DB store for ${sha1}`); return doWithDB((db, resolve, reject) => { const transaction = db.transaction('nvram', 'readwrite'); const store = transaction.objectStore('nvram'); const request = store.put({sha1, data}); request.onsuccess = () => resolve(); request.onerror = () => reject(request.error); }); } function clearNVRAM() { console.info('Clearing NVRAM DB store'); return doWithDB((db, resolve, reject) => { const transaction = db.transaction('nvram', 'readwrite'); const store = transaction.objectStore('nvram'); const request = store.clear(); request.onsuccess = () => resolve(); request.onerror = () => reject(request.error); }); } // export const nvramStore = {get: getNVRAM, put: putNVRAM, clear: clearNVRAM};
const request = require('request'); const forecast = (latitude, longitude, callback) => { const url = `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=weekly&units=metric&appid=664cea4f65edb1964993886313209e4c` request({url, json: true}, (error, {body}) => { if (error){ callback('Unable to connect to weather service!', undefined); } else if (body.message){ callback('Wrong latitude or longitude!', undefined); } else { callback(undefined, `It is currently ${body.current.temp} degrees out but it feels like ${body.current.feels_like}; also There's ${body.current.humidity}% humidity.`); }; } ) }; module.exports = forecast;
/** @jsx jsx */ import { jsx, Styled } from "theme-ui" import { AiOutlineMeh } from "react-icons/ai" import gold from "../../images/gold.svg" import silver from "../../images/silver.svg" import bronze from "../../images/bronze.svg" const Entry = ({ entry, scores, currentSeason }) => { const season = entry.season.findIndex( season => season.index === currentSeason ) return ( <div sx={{ borderBottom: "solid 2px", borderBottomColor: "muted", }} > <div sx={{ display: "grid", gridTemplateColumns: "10% 49% 10% 10% 10% 10%", alignItems: "center", py: 3, }} > <div sx={{ textAlign: "center", fontSize: 5 }}> {entry.season[season].points === scores[0] ? ( <img sx={{ width: "50%", mx: "auto" }} src={gold} alt="Gold" /> ) : entry.season[season].points === scores[1] ? ( <img sx={{ width: "50%", mx: "auto" }} src={silver} alt="Silver" /> ) : entry.season[season].points === scores[2] ? ( <img sx={{ width: "50%", mx: "auto" }} src={bronze} alt="Bronze" /> ) : ( <AiOutlineMeh /> )} </div> <Styled.h3 sx={{ textAlign: "left", mx: 4, my: 2, fontSize: 4, fontWeight: "heading", }} > {entry.name} </Styled.h3> <Styled.p sx={{ textAlign: "center", my: 0, fontSize: 4 }}> {entry.season[season].gold} </Styled.p> <Styled.p sx={{ textAlign: "center", my: 0, fontSize: 4 }}> {entry.season[season].silver} </Styled.p> <Styled.p sx={{ textAlign: "center", my: 0, fontSize: 4 }}> {entry.season[season].bronze} </Styled.p> <Styled.h3 sx={{ textAlign: "center", my: 0, fontSize: 5 }}> {entry.season[season].points}p </Styled.h3> </div> </div> ) } export default Entry
const venom = require('venom-bot') const {Query} = require('./mingo') const responders = require('./responders') venom.create() .then(start) .catch(console.error) const rules = [ { query: { from: '554197730230@c.us', type: 'chat', body: { $regex: '^o+i+(!+)?', $options: 'i' } }, response: { type: 'chat', body: 'Coé {{sender.name}}' } }, { query: { from: '554197730230@c.us', type: 'image', caption: { $regex: '^o+i+(!+)?', $options: 'i' } }, response: { type: 'chat', body: 'Que doidera bixo' } }, { query: { 'sender.name': 'Rafael', body: { $regex: '^o+i+(!+)?', $options: 'i' } }, response: { type: 'chat', body: 'porra {{sender.name}}, ta maluco? kkkkkk' } }, { query: { 'sender.name': { $regex: 'vinicius', $options: 'i' }, body: { $regex: '^o+i+(!+)?', $options: 'i' } }, response: { type: 'chat', body: 'fala {{sender.name}}, tudo beleza?' } } ] async function respond({response, message, client}) { const responder = responders[response.type] if (responder) { await responder({ response, message, client }) } } function start(client) { const compiled = rules.map(({query, response}) => ({ query: new Query(query), response })) client.onMessage(message => { const match = compiled.find(rule => rule.query.test(message)) if (match) { respond({ response: match.response, message, client }) } }) }
'use strict'; var Tester = require('./tester'); var ZSchema = require('../src/ZSchema'); // var Jassi = require('jassi'); var JaySchema = require('jayschema'); var jjv = require('jjv'); // var JsonSchemaSuite = require('json-schema-suite'); var JsonSchema = require('jsonschema'); var tv4 = require('tv4'); Tester.registerValidator({ name: 'z-schema', setup: function () { return new ZSchema({ sync: true }); }, test: function (instance, json, schema) { return instance.validate(json, schema) === true; } }); /* jassi is not included because it fails too many tests Tester.registerValidator({ name: 'jassi', setup: function () { return Jassi; }, test: function (instance, json, schema) { return instance(json, schema).length === 0; } }); */ Tester.registerValidator({ name: 'jayschema', setup: function () { return new JaySchema(); }, test: function (instance, json, schema) { return instance.validate(json, schema).length === 0; } }); Tester.registerValidator({ name: 'jjv', setup: function () { return jjv(); }, test: function (instance, json, schema) { return instance.validate(schema, json) === null; } }); /* Tester.registerValidator({ name: 'json-schema-suite', setup: function () { return new JsonSchemaSuite.Validator(); }, test: function (instance, json, schema) { return instance.validateRaw(schema, json) === true; } }); */ Tester.registerValidator({ name: 'jsonschema', setup: function () { return new JsonSchema.Validator(); }, test: function (instance, json, schema) { return instance.validate(json, schema).errors.length === 0; } }); Tester.registerValidator({ name: 'tv4', setup: function () { return tv4; }, test: function (instance, json, schema) { return instance.validateResult(json, schema).valid === true; } }); var basicObject = require('./basic_object.json'); var basicSchema = require('./basic_schema_v4.json'); Tester.runOne('basicObject', basicObject, basicSchema, true); var advancedObject = require('./advanced_object.json'); var advancedSchema = require('./advanced_schema_v4.json'); Tester.runOne('advancedObject', advancedObject, advancedSchema, true); Tester.runDirectory(__dirname + '/../json_schema_test_suite/tests/draft4/', { excludeFiles: ['optional/zeroTerminatedFloats.json'], excludeTests: [ // these two tests consider different uri then is desired to be valid 'validation of URIs, an invalid URI', 'validation of URIs, an invalid URI though valid URI reference', // these tests require validator to work with remote schema which they can't download in sync test 'valid definition, valid definition schema', 'invalid definition, invalid definition schema', 'remote ref, containing refs itself, remote ref valid', 'remote ref, containing refs itself, remote ref invalid', 'remote ref, remote ref valid', 'remote ref, remote ref invalid', 'fragment within remote ref, remote fragment valid', 'fragment within remote ref, remote fragment invalid', 'ref within remote ref, ref within ref valid', 'ref within remote ref, ref within ref invalid', 'change resolution scope, changed scope ref valid', 'change resolution scope, changed scope ref invalid' ] }); Tester.saveResults('results.html', 'results.template');
let Foo = (props, state = { dir: 1 }, update) => { function *handleToggle() { if (props.isActive) { // Invert direction var dir = -state.dir; yield update({ ...state }); yield props.onToggle(dir); } return update(state); }; return <div onClick={handleToggle} />; }; type Props = { addition ?: number }; type State = { counter : number }; export type Bar = (Props, State, Update) => Element; export let Bar : Bar = (props, state = { counter: 0 }, update) => { let { addition = 1 } = props; // Default props let handleToggle = (value) => update({ ...state, counter: state.counter + value }); let handleClick = () => { return update({ ...state, counter: state.counter + addition }); }; return ( <div onClick={handleClick}> <Foo onToggle={handleToggle} isActive /> </div> ); }; // Language trickery to get named arguments, default props and initial state // This is so not readable. // props : defaultProps : type definition // state = initialProps : type definition let Baz = ({ props : { addition = 5 } : { addition : number }, state = { counter : 1 } : { counter : number }, update : Update, context : any }) => { return <Bar addition={addition} />; };
import { Block } from '@tarojs/components' import Taro from '@tarojs/taro' import '@tarojs/async-await' import withWeapp from '@tarojs/with-weapp' import './app.scss' @withWeapp({ onLaunch: function() { // 展示本地存储能力 var logs = Taro.getStorageSync('logs') || [] logs.unshift(Date.now()) Taro.setStorageSync('logs', logs) // 登录 Taro.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId } }) // 获取用户信息 Taro.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 Taro.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this.globalData.userInfo = res.userInfo // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) }, globalData: { userInfo: null } }) class App extends Taro.Component { config = { pages: [ 'pages/cart/cart', 'pages/home/home', 'pages/index/index', 'pages/logs/logs', 'pages/classification/classification', 'pages/details/details', 'pages/share/share' ], window: { navigationBarTitleText: 'Welcome To Jerry Mall', navigationBarBackgroundColor: '#AB956D', backgroundColor: '#eeeeee', enablePullDownRefresh: true }, tabBar: { backgroundColor: '#fff', borderStyle: 'black', color: '#333', selectedColor: '#b30000', list: [ { pagePath: 'pages/home/home', iconPath: 'images/12.png', selectedIconPath: 'images/11.png', text: '首页' }, { pagePath: 'pages/classification/classification', iconPath: 'images/22.png', selectedIconPath: 'images/21.png', text: '分类' }, { pagePath: 'pages/cart/cart', iconPath: 'images/32.png', selectedIconPath: 'images/31.png', text: '购物车' }, { pagePath: 'pages/index/index', iconPath: 'images/42.png', selectedIconPath: 'images/41.png', text: '我的' } ] }, style: 'v2', sitemapLocation: 'sitemap.json' } render() { return null } } //app.js export default App Taro.render(<App />, document.getElementById('app'))
/** * Created by Þórður on 5.12.2014. */ var should = require('should'); var _ = require('lodash'); describe('tictactoe game context stubs', function(){ it('should route command to instantiated tictactoe game with event stream from store and return and store generated events', function(){ var calledWithEventStoreId; var storedEvents; var eventStoreStub = { loadEvents: function(aggregatedID){ calledWithEventStoreId = aggregatedID; return []; }, storeEvents: function(aggregatedID, events){ storedEvents = events; } }; var executedCommand = {}; var tictactoeStub = function(history){ return { executeCommand : function(cmd){ executedCommand = cmd; return []; } } }; var commandHandlers = tictactoeStub; var boundedContext = require('./tictactoeBoundedContext')(eventStoreStub, commandHandlers); var emptyCommand = { id: "1337" }; var events = boundedContext.handleCommand(emptyCommand); should(executedCommand.id).be.exactly("1337"); should(calledWithEventStoreId).be.exactly("1337"); should(events.length).be.exactly(0); should(storedEvents).be.exactly(events); }); });
"use realm"; import utils from morrr.editor; const Strong = { tag: 'b', inline: true, toBBCode: function(root) { var self = this; root.find('b').each(function(index, element) { $(element).replaceWith('[strong]' + utils.trimText($(element).text()) + '[/strong]'); }); } } export Strong
document.addEventListener("deviceready", onDeviceReady, false); var largeImage; function onDeviceReady () { document.querySelector("#snapPicture").addEventListener("touchend", snapPicture); document.querySelector("#getPhoto").addEventListener("touchend", getPhoto); largeImage = document.querySelector("#picture"); largeImage.style.display = "block"; setTimeout(function() { alert ("PhoneGapの読み込みが完了。Cameraが整いた。"); }, 0); } function snapPicture() { navigator.camera.getPicture(onSuccessSnap, onFail, { quality: 50, destinationType: Camera.DestinationType.DATA_URL }); } function getPhoto() { navigator.camera.getPicture(onSuccessPhoto, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM }); } function onSuccessSnap (imageData) { largeImage.src = "data:image/jpeg;base64," + imageData; } function onSuccessPhoto (imageURI) { largeImage.src = imageURI; } function onFail (message) { if (message.includes("cancelled.")) { return; } if (message.includes("no image selected")) { return; } setTimeout(function() { alert("エラーが発生しました: " + message); }, 0); }
/*! js Hot it | Objeto Mapa | 071113 */ function omapa(){ // ! clase q maneja el mapa this.bounds = new google.maps.LatLngBounds(); this.box = 'box-map'; this.map; this.markers = []; this.styles = []; this.markercluster = null; this.mlocation = null; this.draw = function(){ // * coloca el mapa en la interfaz var latlng_ = new google.maps.LatLng(19.357363,-99.196871); var zoom_ = 5; google.maps.visualRefresh = true; var myoptions_ = { zoom: zoom_, center: latlng_, streetViewControl: this.isstreet, mapTypeControlOptions:{ mapTypeIds: [google.maps.MapTypeId.ROADMAP,google.maps.MapTypeId.HYBRID] }, panControl: true, panControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, zoomControl: true, zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE, position: google.maps.ControlPosition.RIGHT_TOP } }; this.map = new google.maps.Map(document.getElementById(this.box), myoptions_); this.map.setMapTypeId(google.maps.MapTypeId.ROADMAP); // colocamos los estilos que llevaran los clusters this.styles = [{url: '/img/medium.png', height: 48, width: 32, anchor: [16, 0], textColor: '#ffffff', textSize: 10}, {url: '/img/hot.png', height: 48, width: 32, anchor: [16, 0], textColor: '#ffffff', textSize: 10}, {url: '/img/low.png', height: 48, width: 32, anchor: [16, 0], textColor: '#ffffff', textSize: 10}]; }; this.exists = function(){ // regresa si encuentra el mapa return (this.map != '' && this.map != null && this.map != undefined) ? true : false; }; this.put_marker = function(o){ // coloca el marker en el mapa var punto = new google.maps.LatLng(o.lat,o.lon); var marker = new google.maps.Marker({ position: punto, map: this.map, icon: '/img/low.png' }); this.markers.push(marker); this.bounds.extend(punto); }; this.put_cluster = function(){ // colocamos el cluster de los datos this.markercluster = new MarkerClusterer(this.map, this.markers, {maxZoom: 18, gridSize: 20, styles: this.styles}); }; this.clear = function(){ // limpiamos los markers for(var i = 0; i < this.markers; i++){ this.markers[i].setMap(Null); } this.markers.length = 0; if(this.markercluster != null){ this.markercluster.clearMarkers(); } this.bounds = new google.maps.LatLngBounds(); }; this.get_location = function(){ // ubica al usuario if(navigator.geolocation){ $('#ubicacion').html('Ubicando...'); navigator.geolocation.getCurrentPosition(put_location, error_location, {timeout:60000}); }else{ alert('El navegador no soporta geolocation.'); } }; this.put_location = function(lat, lon){ // colocamos le marker de la ubicación var punto = new google.maps.LatLng(lat,lon); if(this.mlocation == null){ this.mlocation = new google.maps.Marker({ position: punto, map: this.map, icon: '/img/pin.png' }); }else{ this.mlocation.setPosition(punto); } this.map.setCenter(punto); this.map.setZoom(11); }; } function put_location(geo){ // Colocamos la ubicación del usuario. var lat = geo.coords.latitude; var lon = geo.coords.longitude; m__.put_location(lat, lon); $('#ubicacion').html('Ubicame'); } function error_location(){ // No se pudo obtener la ubicación $('#ubicacion').html('Ubicame'); alert('No se pudo obtener la ubicación.') }
import React, { Component} from 'react' import { GridLoader } from 'react-spinners' import Puzzle from '../../services/Puzzle' import Fetch from '../../services/Fetch' import PuzzleGrid from '../../components/PuzzleGrid' import Header from '../../components/Header' import Footer from '../../components/Footer' import SolvedModal from '../../components/SolvedModal' import AboutModal from '../../components/AboutModal' import ShowSolutionModal from '../../components/ShowSolutionModal' const theme = { textColor: 'rgba(0,0,0,.65)', textSize: 16, font: '"Open Sans", sans-serif', modalStyle: { content: { top: '50%', left: '50%', right: 'auto', bottom: 'auto', padding: '5%', transform: 'translate(-50%, -50%)', }, overlay: { backgroundColor: 'rgba(0, 0, 0, 0.50)', } } } class App extends Component { /** * Tests whether drop site is valid for piece */ static isGoodTarget (source, target) { return source[0] - 1 == target[0] && source[1] === target[1] || // left source[0] + 1 === target[0] && source[1] === target[1] || // right source[0] === target[0] && source[1] + 1 === target[1] || // down source[0] === target[0] && source[1] - 1 === target[1] // up } constructor (props) { super(props) this.state = { puzzleInPlay: [], pieceHeight: 125, pieceWidth: 125, aboutOpen: false, solvedOpen: false, showSolutionOpen: false, } this.onDrag = this.onDrag.bind(this) this.onDrop = this.onDrop.bind(this) this.renderEasy = this.renderEasy.bind(this) this.loadNewPuzzle = this.loadNewPuzzle.bind(this) } componentDidMount () { this.loadNewPuzzle() } async loadNewPuzzle () { this.setState({ puzzleInPlay: [] }) this.puzzle = new Puzzle(await Fetch.randomImg()) await this.puzzle.slice() this.puzzle.shuffle() this.setState({ pieceWidth: this.puzzle.pieceWidth, pieceHeight: this.puzzle.pieceHeight, puzzleInPlay: this.puzzle.startModel, beingDragged: null, }) } renderEasy (){ this.setState({ puzzleInPlay: null, }) this.puzzle.simplify() this.setState({ puzzleInPlay: this.puzzle.startModel }) } toggleModal (key, isOpen) { this.setState({ [key]: isOpen }) } onDrag (x, y) { this.setState({ beingDragged: [x, y] }) } onDrop (x, y) { const { beingDragged, puzzleInPlay } = this.state if (App.isGoodTarget(beingDragged, [x, y])) { const newPuzzle = puzzleInPlay.map(row => row.slice()) newPuzzle[x][y] = newPuzzle[beingDragged[0]][beingDragged[1]] newPuzzle[beingDragged[0]][beingDragged[1]] = null this.setState({ puzzleInPlay: newPuzzle, beingDragged: null, }, () => { if (this.puzzle.isSolved(this.state.puzzleInPlay)) { this.toggleModal('solvedOpen', true) } }) } } render() { return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', fontFamily: theme.font, }}> <Header theme={theme} aboutAction={this.toggleModal.bind(this,'aboutOpen', true)} newPuzzleAction={this.loadNewPuzzle} showSolutionAction={this.toggleModal.bind(this, 'showSolutionOpen', true)} makeEasyAction={this.renderEasy} /> <div height={500}> <AboutModal theme={theme} open={this.state.aboutOpen} onClose={this.toggleModal.bind(this, 'aboutOpen', false)} /> <SolvedModal theme={theme} open={this.state.solvedOpen} onClose={this.toggleModal.bind(this, 'solvedOpen', false)} /> <ShowSolutionModal theme={theme} open={this.state.showSolutionOpen} srcUrl={this.puzzle ? this.puzzle.srcUrl : '' } onClose={this.toggleModal.bind(this, 'showSolutionOpen', false)} /> <GridLoader color={theme.textColor} loading={!this.state.puzzleInPlay.length} size={100} loaderStyle={{ margin: '75px auto', }} /> <PuzzleGrid puzzle={this.state.puzzleInPlay} onDrag={this.onDrag} onDrop={this.onDrop} width={this.state.pieceWidth} height={this.state.pieceHeight} /> </div> <Footer theme={theme} /> </div> ) } } export default App
 angular.module('RegistrationApp', []) .controller('RegistrationCtr', function ($scope, $http) { $(document).ready(function () { document.getElementById("spanSecondName").hidden = false; document.getElementById("spanFirstName").hidden = false; document.getElementById("spanLastName").hidden = false; document.getElementById("spanRegistrationNumber").hidden = false; document.getElementById("spanPhoneNumber").hidden = false; document.getElementById("spanPasswordValidation").hidden = false; document.getElementById("spanConPasswordValidation").hidden = false; document.getElementById("spanNameOrganisation").hidden = false; document.getElementById("spanEmail").hidden = false; // $('#layoutfooter').show(); $("#FormRegistrSubmit").submit(function() { $('#dvLoading').show(); $('#mask').show(); if ($scope.value.$invalid) { $scope.submitted = false; $('#mask').hide(); $('#dvLoading').fadeOut(1000); } else { $http.get("Account/CheckEmail?email=" + $scope.user.Email).success(function(data) { $http.post("Account/CheckPassword", $scope.user).success(function(passworddata) { console.log(passworddata); if (data === 'False' || passworddata === 'False') { console.log("234"); if (data === 'False') { $scope.showLink = true; $scope.submitted = false; $scope.checkemail = "Пользователь с данным Email уже зарегистрирован!!!"; $('#mask').hide(); $('#dvLoading').fadeOut(1000); } if (passworddata === 'False') { $scope.showPassword = true; $scope.submitted = false; $scope.checkpassword = "Пароли не совпадают!!!"; $('#mask').hide(); $('#dvLoading').fadeOut(1000); } } else { console.log("Ok"); $http.post('Account/Register', $scope.user).success(function(data) { console.log("123111"); //document.getElementById("myBtn").disabled = true; //$scope.showseccess = true; //$scope.uploading = "Регистрация прошла успешно!!!"; //$('#dvLoading').fadeOut(1000); if (data === 'True') { console.log("123111"); window.location.href = 'Cabinet/Cabinet'; } if (data === 'False') { $scope.register = "Регистрация не удалась"; $scope.showLink = true; $('#mask').hide(); $('#dvLoading').fadeOut(1000); } }).error(function(data) { // alert("Warning!!!"); $('#mask').hide(); $('#dvLoading').fadeOut(1000); }); } }).error(function(data) { // alert("Warning!!!"); $('#mask').hide(); $('#dvLoading').fadeOut(1000); }); }).error(function(data) { // alert("Warning!!!"); $('#mask').hide(); $('#dvLoading').fadeOut(1000); }); } }); }); $scope.changepassword = function () { $scope.showPassword = false; } $scope.changeemail = function () { $scope.showLink = false; } }) .controller('LoginCtr', function ($scope, $http) { $(document).ready(function () { document.getElementById("spanlogin").hidden = false; document.getElementById("spanpassword").hidden = false; console.log("123"); //$scope.submit = function () { // console.log(123); // if ($scope.LoginForm.$valid) // alert('send to server: ' + $scope.number); //} $("#FormLoginSubmit").submit(function () { $('#mask').show(); if ($scope.LoginForm.$invalid) { $scope.submitted = false; $('#dvLoading').show(); $('#mask').hide(); $('#dvLoading').fadeOut(1000); } else { $('#dvLoading').show(); $http.post("Account/Login", $scope.user).success(function (data) { if (data === 'True') { window.location.href = 'Cabinet/Cabinet'; } if (data === 'False') { $scope.submitted = false; $scope.auto = "Авторизация не удалась"; $scope.showLink = true; $('#mask').hide(); $('#dvLoading').fadeOut(1000); } }); } }); }); });
import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { Button, Header, Icon, Modal } from 'semantic-ui-react' import { closeBetWizard, bet, betWizardUIStates } from '../actions/index' class BetWizzard extends Component { render() { switch(this.props.onGoingBet.UIState) { case betWizardUIStates.CONFIRM_BET: const winnerIndex = this.props.onGoingBet.winnerIndex const looserIndex = winnerIndex ? 0 : 1 return ( <Modal open={true} size='small' > <Modal.Content> <span>Please confirm your bet of <strong>0.01 Ether</strong> that</span> <h1>{this.props.onGoingBet.match.teams[winnerIndex].name}</h1> <span> will win the match against {this.props.onGoingBet.match.teams[looserIndex].name} </span> </Modal.Content> <Modal.Actions> <Button secondary onClick={this.props.closeBetWizard}> Cancel </Button> <Button primary onClick={() => this.props.bet( this.props.onGoingBet.match, this.props.onGoingBet.tie, this.props.onGoingBet.winnerIndex )}> Bet on {this.props.onGoingBet.match.teams[winnerIndex].name} </Button> </Modal.Actions> </Modal> ) case betWizardUIStates.SENDING_BET: return ( <Modal open={true} size='small' > <Modal.Content> <h2>Sending bet to smart contract</h2> </Modal.Content> </Modal> ) case betWizardUIStates.BET_COMPLETE: return ( <Modal open={true} size='small' > <Modal.Content> <h2>Bet COMPLETE</h2> </Modal.Content> <Modal.Actions> <Button primary onClick={ () => this.props.closeBetWizard()}> OK </Button> </Modal.Actions> </Modal> ) default: return null } } } function mapStateToProps(state) { return { onGoingBet: state.onGoingBet } } function mapDispatchToProps(dispatch) { return bindActionCreators({closeBetWizard, bet}, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(BetWizzard);
import React, {Component} from 'react' import Card from './card' import styled from 'styled-components' import Button from './ui/button' export default class CardSelect extends Component { state={ selected:[] } toggleCard = (card) => { const selected = this.state.selected const exists = selected.findIndex(f=>f.name===card.name) if (exists !== -1) { selected.splice(exists, 1) } else { // if (selected.length > 5) { // console.log('dont allow') // return // } selected.push(card) } this.setState({selected}) } render(){ const {selected} = this.state const {cards, pickHand} = this.props const allCards = cards && cards.map((o,i)=>{ const picked = selected.find(f=>f.name===o.name) return( <Card key={i} card={o} toggleCard={this.toggleCard} selected={picked} index={i} inGame={false}/> ) }) return( <Envelope> <div> <span>Hand: {selected.length}/5</span> </div> <Frame> {allCards} </Frame> <Bottom> <Button label="Start" action={()=>pickHand(selected)}/> </Bottom> </Envelope>) } } const Envelope = styled.div` display:flex; flex-direction:column; padding:50px; height:100%; align-items: center; ` const Frame = styled.div` display:flex; width:50%; box-shadow: 0 15px 20px rgba(0, 0, 0, 0.3); padding:20px; border:4px dotted #333; background: #d6d6d6; flex-flow: row wrap; ` const Bottom = styled.div` margin:30px; text-align:center; `
var express = require('express'); var router = express.Router(); var path = require('path'); const Comment=require('../modules/comment'); const User = require('../modules/user'); const Article = require('../modules/article'); const bodyParser = require('body-parser'); router.post('/newcomment',function(req,res){ let date = new Date(Date.now()); // var diff; // if(req.body.idarticlechild) // { // diff=req.body.idarticlechild; // console.log("child"+diff) // } // elseif(req.body.idarticlefather) // { // diff=req.body.idarticlefather; // console.log("father"+diff) // } User.findOne({_id:req.user.id},function(err,person){ var Comments=new Comment({ _articleId:req.body.idarticle, _userid:req.user.id, creatDate:date.toString(), commentsText:req.body.text, parentId:req.body.parentid, commentName:person.firstName, image:person.image }); Comments.save(function (err) { if (err) { console.log(err); } }); }) res.redirect('http://localhost:3000/articles/showarticle?id='+req.body.idarticle); }); module.exports = router;
import React, { Component } from 'react'; import UserTableHeader from './header'; import { Card, CardBody, Table } from 'reactstrap'; import UserRow from './UserRow'; import UserForm from './UserForm' import defaultUserList from './defaultUserList'; const renderUserRow = (users, handleDelete, editUser) => ( users.map( user => <UserRow key={user.id} user={user} editUser={editUser} handleDelete={handleDelete} /> ) ) class UserList extends Component { state = { users: defaultUserList, user: { id: '', name: '', age: '' }, isEditing: false, } handleDelete = (id) => { const users = this.state.users const filterUsers = users.filter(user => user.id != id) this.setState({ users: filterUsers }) } handleInputChange = (event) => { const user = this.state.user this.setState({ user: { ...user, [event.target.name]: event.target.value} }) } addUser = () => { const users = this.state.users const newUserList = users.concat(this.state.user) this.setState({ users: newUserList, user: {id: '', name: "", age: ""} }) } editUser = (id) => { const user = this.state.users.find(user => user.id == id) this.setState({isEditing: true, user }) } updateUser = () => { const {users, user}= this.state const index = users.findIndex(u => u.id == this.state.user.id) const updateUsers = [ ...users.slice(0, index), user, ...users.slice(index+1)] this.setState({ users: updateUsers, isEditing: false, user: {id: '', name: '', age: ''} }) } redirectToHello = () => { this.props.history.push('/hello') } render(){ const { users, user, isEditing }= this.state; return ( <React.Fragment> <Table bgColor={this.props.theamColor}> <UserTableHeader /> <tbody> { renderUserRow(users, this.handleDelete, this.editUser) } </tbody> </Table> <SelfCard myCompoment= {<UserForm user={ user } handleSubmit={isEditing ? this.updateUser : this.addUser} handleInputChange={this.handleInputChange} />} /> <button onClick={this.redirectToHello}> Recirect To home </button> </React.Fragment> ) } } class SelfCard extends Component { state = { expand: true } handleExpandClick= () => { this.setState({ expand: !this.state.expand }) } render() { const {myCompoment} = this.props return ( <Card> <button onClick={this.handleExpandClick}>expand or collapse</button> <CardBody className={ this.state.expand ? '' : "d-none" }> { myCompoment } </CardBody> </Card> ) } } export default UserList;
const box = document.getElementById('box'); window.onmousemove = e => { const percentageX = e.screenX / window.innerWidth - 0.5; const percentageY = 0.5 - e.screenY / window.innerHeight; setRotate(percentageY * 20, percentageX * 20); } function setRotate(x, y) { box.style.transform = `rotateX(${x}deg) rotateY(${y}deg)`; } function gyro(e) { // beta for X, gamma for Y, 0 ~ 360 const percentageX = e.beta / 10; const percentageY = e.gamma / 10; // console.debug(percentageX * 10, percentageY * 10); setRotate(percentageX * 10, percentageY * 10); } if (typeof (DeviceMotionEvent) !== 'undefined') { // use gyro if (typeof (DeviceMotionEvent.requestPermission) === "function") { // add callback to document click document.onclick = () => { DeviceOrientationEvent.requestPermission().then(g => { if (g === 'granted') { // success window.ondeviceorientation = gyro; } else { alert('需要陀螺仪授权'); } }) } alert('请点击屏幕任意位置以获得陀螺仪权限'); } else { // android? just use window.ondeviceorientation = gyro; } } setRotate(0, 0);
export default function (column, changeTitlePlace, deleteColumn, isEdit) { let Title = document.getElementById(column); let Column = Title.closest('.droppable'); let ContainerSelf = Title.closest('.container'); let width = Column.getBoundingClientRect().width; let height = Column.getBoundingClientRect().height; if (!isEdit) { Title.onmousedown = function onmousedown(event) { if (event.target.className.indexOf('im') >= 0) return; let style = Column.style; Column.style.cursor = 'grabbing'; let shiftX = event.clientX - Column.getBoundingClientRect().left; shiftX -= Column.style.marginLeft.slice(-Column.style.marginLeft.length + 1, -2); let shiftY = event.clientY - Column.getBoundingClientRect().top; shiftY -= Column.style.marginTop.slice(-Column.style.marginTop.length + 1, -2); let div = document.createElement('div'); div.id = 'insertionPoint'; div.style.height = '100%'; div.style.paddingTop = '30px'; let div1 = document.createElement('div'); div1.id = 'insteadColumn'; div1.className = Column.className; div1.style.width = width + 'px'; div1.style.height = height + 'px'; div1.style.background = 'rgba(32,34,36,0.29)'; div1.style.borderRadius = '6px'; div.append(div1); ContainerSelf.before(div); Column.style.position = 'absolute'; Column.style.margin = 0; Column.style.zIndex = 1000; moveAt(event.pageX, event.pageY); function moveAt(pageX, pageY) { Column.style.left = pageX - shiftX + 'px'; Column.style.top = pageY - shiftY + 'px'; } let currentDroppable = null; let Container = null; let moved = true; let columnBelow = null; let isBefore = true; function onMouseMove(event) { if (moved) { Column.style.transformOrigin = `${shiftX}px ${shiftY}px`; Column.style.transform = 'rotate(3deg)'; Column.style.boxShadow = ' 0px 0px 1px rgba(0,0,0,0.5)'; moved = false; } moveAt(event.pageX, event.pageY); Column.style.visibility = 'hidden'; let elemBelow = document.elementFromPoint(event.clientX, event.clientY); Column.style.visibility = 'visible'; if (!elemBelow) { div.remove(); document.removeEventListener('mousemove', onMouseMove); Column.style = style; ContainerSelf.style.visibility = 'visible'; return; } if (elemBelow.id === 'delete') { Column.style.opacity = 0.3; } else { Column.style.opacity = 1; } let droppableBelow = elemBelow.closest('#delete'); let containerBelow = elemBelow.closest('.container'); if (containerBelow) { Container = containerBelow; if (Container) { div.remove(); let center = Container.getBoundingClientRect().left + Container.getBoundingClientRect().width / 2; if (columnBelow !== Container.querySelector('.droppable').id) { if (center > event.pageX) { Container.after(div); columnBelow = Container.querySelector('.droppable').id; isBefore = false; } else { Container.before(div); columnBelow = Container.querySelector('.droppable').id; isBefore = true; } } else { if (isBefore) { Container.after(div); isBefore = false; } else { Container.before(div); isBefore = true; } } } } if (droppableBelow && droppableBelow.id === 'delete') { div.remove(); Container = null; } if (currentDroppable !== droppableBelow) { if (currentDroppable) { leaveDroppable(currentDroppable); columnBelow = null; } currentDroppable = droppableBelow; if (currentDroppable) { enterDroppable(currentDroppable); } } } document.addEventListener('mousemove', onMouseMove); Column.onmouseup = function () { document.removeEventListener('mousemove', onMouseMove); Column.onmouseup = null; Column.style = style; div.remove(); if (columnBelow === null) return; if (currentDroppable) { leaveDroppable(currentDroppable); } if (currentDroppable && currentDroppable.id === 'delete') { deleteColumn(column.slice(1)); return; } else if (Container) { changeTitlePlace(column.slice(1), columnBelow, isBefore); } columnBelow = null; }; }; function enterDroppable(elem) { if (elem.id === 'delete') { elem.style.backgroundImage = 'url(82-512.webp), linear-gradient(45deg, #f8a261, #6e9fc9)'; elem.style.transform = 'scale(1.1)'; } } function leaveDroppable(elem) { if (elem.id === 'delete') { elem.style.background = ''; elem.style.border = ``; elem.style.transform = ''; } } Column.ondragstart = function () { return false; }; } }
window.onload = () => { count(); var lastuser; document.getElementById("guardarUser").addEventListener("click", main); document.getElementById("guardarUser").addEventListener("click", mostrar); // var lastuser = Number(sessionStorage.getItem("last")) + 1; function main(){ lastuser = sessionStorage.getItem("last"); let usr = crear(); emailp(usr); //redirect(); } function count(){ fetch('http://localhost:8080/ApiRest/User') //link para el GET de todos los usuarios .then(respuesta => respuesta.json()) .then(usuarios => { usuarios.forEach(usuarios => { sessionStorage.setItem("last", Number(usuarios.cliente_id)+1); }); }) .catch(error => console.log('Hubo un error : ' + error.message)) } function crear(){ let nom = document.getElementById("nombre").value; let phone = document.getElementById("tel").value; let email = document.getElementById("correo").value; let cumple = document.getElementById("inputBirth").value; let gender = document.getElementById("gender").value; var user = new Object(); user.cliente_id = lastuser; user.cel = phone; user.nombre = nom; user.email = email; user.contraseña = "pass"; user.cumple = cumple; user.genero = gender; user.foto_perfil = "/images/logo/divinite3.png"; user.fecha_registro = "2021-10-26 00:00:00"; return user; } function emailp(user){ let bandera; fetch('http://localhost:8080/ApiRest/User') //link para el GET de todos los usuarios .then(respuesta => respuesta.json()) .then(usuarios => { usuarios.forEach(usuarios => { if(usuarios != null){ if(usuarios.email === user.email){ bandera = true; } } }); if(bandera){ alert("Correo con cuenta ya creada"); }else{ adduser(user); } }) .catch(error => console.log('Hubo un error : ' + error.message)) } function adduser(user){ fetch("http://localhost:8080/ApiRest/User", { method: 'POST', // or 'PUT' body: JSON.stringify(user), // data can be `string` or {object}! headers:{ 'Content-Type': 'application/json' } }).then(res => res.json()) .catch(error => console.error('Error:', error)) .then(response => console.log('Success:', response)); sessionStorage.setItem("j", user.cliente_id); } function mostrar(){ fetch('http://localhost:8080/ApiRest/User') //link para el GET de todos los usuarios .then(respuesta => respuesta.json()) .then(usuarios => { usuarios.forEach(user => { if(user != null){ const itemHTML = `<table class="table table-hover" id="Tabla-Usuarios" style="width: 96%; text-align: center; margin: auto;"> <thead> <tr> <th scope="col">Cliente ID</th> <th scope="col">Nombre</th> <th scope="col">Télefono</th> <th scope="col">Correo</th> <th scope="col">Cumpleaños</th> <th scope="col">Servicio</th> <th scope="col">Hora</th> <th scope="col">Reservado</th> </tr> </thead> <tbody> <tr> <td>${user.cliente_id}</td> <td>${user.nombre}</td> <td>${user.cel}</td> <td>${user.email}</td> <td>${user.cumple}</td> <td>${user.servicio}</td> <td>${user.hora}</td> <td>${user.reservado}</td> </tr> </tbody> </table>` const itemsContainer = document.getElementById("mostrarUser"); itemsContainer.innerHTML += itemHTML; } }); }) .catch(error => console.log('Hubo un error : ' + error.message)) } }
const bcrypt = require("bcrypt"); const saltRounds = 2; const log = require("../config/log")("SEEDER", "bgYellow"); const db = require("../services/mongoose"); const User = require("../models/User"); const sampleUsers = [ ["billY", "bob"], ["gW", "bush"], ["hEy", "world"], ["BU", "nelly"], ["alVin", "chun"], ["alVin1", "chun"], ["alVin2", "chun"], ["alVin3", "chun"] ]; const icons = [ "068587", "F2B134", "ED553B", "47AB6C", "cd1e1f", "911EB4", "000075", "4363D8", "E6194B", "28dfbb" ]; const promises = sampleUsers .map(u => { return { username: u[0], password: u[1] }; }) .map(async ({ username, password }) => { const hash = await bcrypt.hash(password, saltRounds); const randomIconIdx = Math.floor(Math.random() * icons.length); return new User({ username, usernameKey: username.toLowerCase(), passwordHash: hash, icon: icons[randomIconIdx], points: 250, games: [], invites: [] }).save(); }); log(promises); db.dropDatabase().then(() => { log("db dropped!!"); Promise.all(promises).then(users => { log("following users seeded:", ...users.map(u => u.username)); db.close(); }); });
module.exports = { userModel: require("./userModel"), transactionModel: require("./transactionModel"), tokenModel: require("./tokenModel"), };
// db set up const mongoose = require("mongoose"); const BookingModel = mongoose.model("Bookings", { name: { type: String, require: true, trim: true, }, noOfPeople: { type: Number, trim: true, }, contactNumber: { type: String, trim: true, }, date: { type: Date, }, comment: { type: String, }, confirmed: { type: Boolean, default: false, }, }); module.exports = BookingModel;
const collapsedSymbol = "&rarr;"; const explicitCollapsedSymbol = "→"; const expandedSymbol = "&darr;"; const explicitExpandedSymbol = "↓"; function flipMasterInformation(){ let dot = document.getElementById("master-dot"); let content = document.getElementById("edu-entry-master"); _flipDot(dot); _toggleContentVisibility(content); } function flipBachelorInformation(){ let dot = document.getElementById("bachelor-dot"); let content = document.getElementById("edu-entry-bachelor"); _flipDot(dot); _toggleContentVisibility(content); } function flipAbiturInformation(){ let dot = document.getElementById("abitur-dot"); let content = document.getElementById("edu-entry-abitur"); _flipDot(dot); _toggleContentVisibility(content); } function _flipDot(dot){ if(dot.innerHTML === collapsedSymbol || dot.innerHTML === explicitCollapsedSymbol){ dot.innerHTML = expandedSymbol; }else if(dot.innerHTML === expandedSymbol || dot.innerHTML === explicitExpandedSymbol){ dot.innerHTML = collapsedSymbol; } } function _toggleContentVisibility(contentDiv){ if(contentDiv.style.display === "none"){ contentDiv.style.display = "inline"; }else if(contentDiv.style.display === "inline"){ contentDiv.style.display = "none"; } }
// www/pages/login.js import { Component } from 'react' import { JSON} from 'body-parser' import axios from 'axios' class Login extends React.Component { constructor (props) { super(props) this.state = { username: '', password: '' } } handleSubmit= async ()=> { var details = { 'username': this.state.username, 'password': this.state.password, 'accessToken':'' }; var formBody = []; for (var property in details) { var encodedKey = encodeURIComponent(property); var encodedValue = encodeURIComponent(details[property]); formBody.push(encodedKey + "=" + encodedValue); } formBody = formBody.join("&"); var accessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkFaRVJUWSIsImlkX2FkbWluIjo1LCJpYXQiOjE1ODQ3NTgxNDUsImV4cCI6MTU4NDc2MTc0NX0.nlGbmL1-7hrhQFlqcyVCDVcl-vBYtAc3C8twLxUq-c0'; try { const bodyParameters = { username: this.state.username, password: this.state.password, }; axios.post('http://localhost:3001/admins/signIn', { username :this.state.username, password :this.state.password, headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+accessToken }, }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); } catch (error) { console.error( 'You have an error in your code or there are Network issues.', error ) throw new Error(error) } } render () { return ( <div> <div className='login'> <label htmlFor='username'>GitHub username</label> <input type='text' id='username' name='username' value={this.state.username} onChange={e=>{this.setState({username: e.target.value})}} /> <input type='text' id='password' name='password' value={this.state.password} onChange={e=>{this.setState({password: e.target.value})}} /> <button onClick={this.handleSubmit}>Login</button> </div> <style jsx>{` .login { max-width: 340px; margin: 0 auto; padding: 1rem; border: 1px solid #ccc; border-radius: 4px; } form { display: flex; flex-flow: column; } label { font-weight: 600; } input { padding: 8px; margin: 0.3rem 0 1rem; border: 1px solid #ccc; border-radius: 4px; } .error { margin: 0.5rem 0 0; display: none; color: brown; } .error.show { display: block; } `}</style> </div> ) } } export default Login
var fs = require("fs"); var data = fs.readFileSync('/etc/hosts'); console.log(data.toString());
import React, { useEffect, useState } from 'react'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import IoIcons from 'react-native-vector-icons/Ionicons'; import Entypo from 'react-native-vector-icons/Entypo'; import firestore from '@react-native-firebase/firestore'; import AsyncStorage from '@react-native-async-storage/async-storage'; import Feed from './../components/Feed'; import AddPost from './../components/AddPost'; import Profile from './../components/Profile'; import Chat from './../components/Chat'; const Tab = createBottomTabNavigator(); const BottomTabStack = () => { const usersCollection = firestore().collection('Users'); const [userDetails, setUserDetails] = useState({}); useEffect(() => { getUserDetials(); }, []); const getUserDetials = async () => { try { const userID = await AsyncStorage.getItem('userID'); const user = await usersCollection.doc(userID).get(); setUserDetails({ _id: user.id, name: user.data().name, avatar: user.data().dp, }); } catch (e) { console.error(e); } }; return ( <Tab.Navigator tabBarOptions={{ style: { backgroundColor: '#111' }, showLabel: false, }}> <Tab.Screen name="Home" component={Feed} options={{ tabBarIcon: ({ color }) => ( <IoIcons name="home-outline" color={color} size={26} /> ), }} /> <Tab.Screen name="Post" component={AddPost} options={{ tabBarIcon: ({ color }) => ( <IoIcons name="add-circle-outline" color={color} size={26} /> ), }} /> <Tab.Screen name="Chat" children={() => <Chat currentUser={userDetails} />} options={{ tabBarIcon: ({ color }) => ( <Entypo name="chat" color={color} size={26} /> ), }} /> <Tab.Screen name="Profile" component={Profile} options={{ tabBarIcon: ({ color }) => ( <IoIcons name="person-circle-outline" color={color} size={26} /> ), }} /> </Tab.Navigator> ); }; export default BottomTabStack;