text
stringlengths
7
3.69M
import faker from "faker"; const width = 980; const height = 400; export const getArticles = () => { let articles = []; for (let i = 0; i < 10; i++) { articles.push(getArticle(i)); } return articles; }; export const getArticle = (id) => { faker.locale = "nb_NO"; let article = { articleId: id, overline: id % 2 ? faker.lorem.sentence() : "", headline: faker.lorem.sentence(), tagline: id % 3 ? faker.lorem.sentence() : "", bodytext: faker.lorem.paragraphs(), imageUri: `https://picsum.photos/id/${id * 10}/${width}/${height}`, author: `${faker.internet.email()}`, photographer: `Photo: (c) ${faker.name.firstName()} ${faker.name.lastName()}, (${faker.internet.email()})`, updated: faker.date.recent() }; return article; };
module.exports = { inSufficientParameters:"Insufficient Parameters" }
import React from "react"; import AmCharts from "@amcharts/amcharts3-react"; import chartData from "./data"; const AnimatedTimeLinePieChar = () => { let currentYear = 1995; const config = { "type": "pie", "theme": "light", "dataProvider": [], "valueField": "size", "titleField": "sector", "startDuration": 0, "innerRadius": 80, "pullOutRadius": 20, "marginTop": 30, "titles": [{ "text": "South African Economy" }], "allLabels": [{ "y": "54%", "align": "center", "size": 25, "bold": true, "text": "1995", "color": "#555" }, { "y": "49%", "align": "center", "size": 15, "text": "Year", "color": "#555" }], "listeners": [{ "event": "init", "method": function (e) { const chart = e.chart; function getCurrentData() { const data = chartData[currentYear]; currentYear++; if (currentYear > 2014) currentYear = 1995; return data; } function loop() { chart.allLabels[0].text = currentYear; const data = getCurrentData(); chart.animateData(data, { duration: 1000, complete: function () { setTimeout(loop, 3000); } }); } loop(); } }], "export": { "enabled": true } }; return ( <div className="App"> <AmCharts.React style={{width: "100%", height: "500px"}} options={config}/> </div> ) } export default AnimatedTimeLinePieChar;
// Dashboard Styles import { backgroundColor, primaryColor, secondaryColor, warningColor } from "../../assets/jss/mainStyle"; import createMuiTheme from "@material-ui/core/styles/createMuiTheme"; const dashboardStyle = theme => ({ root: { [theme.breakpoints.down("sm")]: { margin: theme.spacing(3) / 2 }, [theme.breakpoints.up("sm")]: { margin: theme.spacing(3) } }, title: { color: "white", fontSize: 20 }, paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.text.secondary, backgroundColor: primaryColor }, tabs: { borderBottom: "1px solid #e8e8e8" }, tab: { color: "white", "&:hover": { color: "white", opacity: 1 } }, select: { "&:before": { borderColor: "white" }, "&:hover": { borderColor: "white" } } }); const monitoringStyle = theme => ({ card: { padding: 0, color: "white", backgroundColor: primaryColor, flex: 1 }, container: { display: "flex", height: "100%" }, cardContent: { paddingTop: 0, textAlign: "center" }, icon: { fontSize: "40px" } }); const uploadStyle = theme => ({ paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.text.secondary, backgroundColor: primaryColor }, input: { color: "white" } }); const historyStyle = theme => ({ paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.text.secondary, backgroundColor: primaryColor }, select: { "&:before": { borderColor: "white", }, "&:after": { borderColor: "white", }, color: "white", }, inputLabel: { color: "white" }, formControl: { color: "white" }, icon: { fill: "white" }, input: { color: "white" } }); export { dashboardStyle, monitoringStyle, uploadStyle, historyStyle };
if(moz) { extendEventObject(); extendElementModel(); emulateAttachEvent(); } function viewNews(aid){ if(aid==0) aid = getOneItem(); window.open("archives_do.php?aid="+aid+"&dopost=viewNewshives"); } function editNews(id, returnUrl){ location="AdminManageNews.do?act=get&id="+id+"&returnUrl=" + returnUrl; } function updateNews(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=makeNewshives&qstr="+qstr; } function checkNews(returnUrl){ var qstr=getCheckboxItem(); if(qstr.length > 0) location="AdminUpdateArticle.do?act=verify&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要审核的文章!"); } function moveNews(aid){ var qstr=getCheckboxItem(); if(aid==0) aid = getOneItem(); location="archives_do.php?aid="+aid+"&dopost=moveNewshives&qstr="+qstr; } function adNews(returnUrl){ var qstr=getCheckboxItem(); if(qstr.length > 0) location="AdminManageNews.do?act=command&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要推荐的资讯!"); } function delNews(returnUrl){ var qstr=getCheckboxItem(); //alert(qstr); //if(aid==0) aid = getOneItem(); if(qstr.length > 0) location="AdminManageNews.do?act=delete&arcID="+qstr+"&returnUrl="+returnUrl; else alert("请选择要删除的文章!"); } //上下文菜单 function ShowMenu(obj,aid,atitle) { var eobj,popupoptions popupoptions = [ new ContextItem("浏览文档",function(){ viewNews(aid); }), new ContextItem("编辑文档",function(){ editNews(aid); }), new ContextSeperator(), new ContextItem("更新HTML",function(){ updateNews(aid); }), new ContextItem("审核文档",function(){ checkNews(aid); }), new ContextItem("推荐文档",function(){ adNews(aid); }), new ContextSeperator(), new ContextItem("删除文档",function(){ delNews(aid); }), new ContextSeperator(), new ContextItem("全部选择",function(){ selAll(); }), new ContextItem("取消选择",function(){ noSelAll(); }), new ContextSeperator(), new ContextItem("频道管理",function(){ location="catalog_main.php"; }) ] ContextMenu.display(popupoptions) } //获得选中文件的文件名 function getCheckboxItem() { var allSel=""; if(document.form2.arcID.value) return document.form2.arcID.value; for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { if(allSel=="") allSel=document.form2.arcID[i].value; else allSel=allSel+"`"+document.form2.arcID[i].value; } } return allSel; } //获得选中其中一个的id function getOneItem() { var allSel=""; if(document.form2.arcID.value) return document.form2.arcID.value; for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { allSel = document.form2.arcID[i].value; break; } } return allSel; } function selAll() { for(i=0;i<document.form2.arcID.length;i++) { if(!document.form2.arcID[i].checked) { document.form2.arcID[i].checked=true; } } } function noSelAll() { for(i=0;i<document.form2.arcID.length;i++) { if(document.form2.arcID[i].checked) { document.form2.arcID[i].checked=false; } } }
const Augur = require("augurbot"), request = require("request-promise-native"), u = require("../utils/utils"), minecraft = require("../utils/minecraftAPI"); const Module = new Augur.Module() .addCommand({ name: "minecraftskin", description: "Gets the Minecraft skin of a user.", syntax: "[@user]", category: "Minecraft", process: async (msg, suffix) => { let user = false, name = false; if (u.userMentions(msg).size > 0) { user = u.userMentions(msg).first(); } else if (!suffix) { user = msg.author; } if (user) { let ign = await Module.db.ign.find(user.id, 'minecraft'); if (ign) name = encodeURIComponent(ign.ign); else { msg.channel.send(`${user} has not set a Minecraft name with \`!addign minecraft\`.`).then(u.clean); return; } } else name = encodeURIComponent(suffix); try { let uuid; try { uuid = await minecraft.getPlayerUUID(name); } catch(error) { u.noop(); } if (!uuid) { msg.channel.send("I couldn't find a Minecraft account with the username `" + name + "`.").then(u.clean); return; } // The "body" part of this has other options for other skin views, that can be implemented later. // let skinUrl = `https://crafatar.com/renders/body/${uuid}?overlay=true`; let skinUrl = `https://visage.surgeplay.com/full/512/${uuid}`; msg.channel.send({ files: [{attachment: skinUrl, name: `${name}.png`}] }); } catch (e) { u.errorHandler(e, msg); } } }); module.exports = Module;
// var months = ['January','February','March','April','May','June','July','August','September','October','November','December']; // var months2 = months.join(', '); // // console.log(months2); // // months2.typeOf() // console.log('hi') var inStock = ['apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrorts', 'broccoli', 'pizza']; var search; function print(message){ document.write('<p>' + message + '</p>'); } while(true){ search = prompt('Search for a product in our Store. Type quit to exit'); search = search.toLowerCase(); if( search === 'quit'){ break; } else if (search === 'list') { print(inStock.join(',')); } else { if(inStock.indexOf(search) > -1){ print('Yes, we have ' + search + ' in the store.') } else { print(search +" no we dont' have that item.") } } } // []
import React from 'react'; import {useParams,useLocation,useHistory} from "react-router-dom" import Nav from "./RouterNav" const User=()=>{ const {name}=useParams() const location=useLocation() let history=useHistory() console.log(history); function handleClick(){ history.goBack() } return( <> <Nav></Nav> <h2>Welcome {name}</h2> { location.pathname==="/user/sakib" ?<button>Click</button>:null } <button onClick={handleClick}>Go Back</button> </>) } export default User
//廣東快樂十分1 // ------------------------------ // score one time requests | // ------------------------------ window.addEventListener("load", function() { setTimeout(parse, 1000); }, true); function parse() { var dt=new Date(); // *抓現在的Date* var ret={}; ret.error=""; ret.loc="gd10"; ret.locname="廣東快樂十分1"; ret.lottoid=12; ret.locurl="https://www.666icp.com/gdkl10/kaijiang/"; ret.locwebname="愛彩票"; ret.loctype=2; ret.date=sprintf("%04d%02d%02d",dt.getFullYear(),dt.getMonth()+1,dt.getDate()); ret.data={}; // 處裡不要的資料 var findtr = $(".j-numslist>tbody>tr").next().next().next().next().length; if (findtr==0) { readyGo(); }else{ $(".j-numslist>tbody>tr").next().next().next().next().nextAll().each(function() { $(this).remove(); }); readyGo(); } function readyGo() { $(".j-numslist>tbody>tr").each(function() { var vDate=sprintf("%02d",dt.getDate()); var tdDate=$(this).find("td").first().find("span").first().html().substr(6,2); //20150903-048 if (tdDate<vDate || tdDate.length<1) {$(this).remove();} //td裡 不同日期[刪除] }); setTimeout(doscore, 3000); } function doscore() { $(".j-numslist>tbody>tr").each(function() { // array{} 期數 var issuecu=$(this).find("td").first().find("span").first().html(); //20190829-16 var issue=issuecu.replace("-",""); //2019082916 ret.data[issue]={}; // array{} 號碼 var num=[]; $(this).find("td").first().next().find("span").each(function() { num.push($(this).html()); }); ret.data[issue].Number=num.join(","); //array{} SP號碼 ret.data[issue].Number2=""; // TIME 開獎時間 (new) var year=issuecu.substr(0,4); //2019 var month=issuecu.substr(4,2); //06 var date=issuecu.substr(6,2); //13 var tm=$(this).find("td").first().find("span").next().html();//00:00 if (tm=="00:00") {ret.data[issue].Time=="";} else {ret.data[issue].Time=sprintf("%s-%s-%s %s:%02d",year,month,date,tm,0);} // *抓現在的時間* ret.data[issue].GetTime=sprintf("%04d-%02d-%02d %02d:%02d:%02d",dt.getFullYear(),dt.getMonth()+1,dt.getDate(),dt.getHours(),dt.getMinutes(),dt.getSeconds()); }); // 將 ret 資料送給 background.js chrome.extension.sendMessage(ret); //undefined } console.log("Ret>>") console.log(ret); setTimeout(function() {location.reload();}, 20000); } function alert(msg) {}
var promotionController = require('../controllers/PromotionController'); module.exports = function (app) { app.post('/promotion/getPromotionBy', function (req, res) { console.log('/promotion/getPromotionBy', req.body) promotionController.getPromotionBy(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/getPromotionByCode', function (req, res) { console.log('/promotion/getPromotionByCode', req.body) promotionController.getPromotionByCode(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/getPromotionByPromotionCode', function (req, res) { console.log('/promotion/getPromotionByPromotionCode', req.body) promotionController.getPromotionByPromotionCode(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/getPromotionByCol', function (req, res) { console.log('/promotion/getPromotionByCol', req.body) promotionController.getPromotionByCol(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/insertPromotion', function (req, res) { console.log('/promotion/insertPromotion', req.body) promotionController.insertPromotion(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/updatePromotion', function (req, res) { console.log('/promotion/updatePromotion', req.body) promotionController.updatePromotion(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/getPromotionByCode', function (req, res) { console.log('/promotion/getPromotionByCode', req.body) promotionController.getPromotionByCode(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/getPromotionByDiscountCode', function (req, res) { console.log('/promotion/getPromotionByDiscountCode', req.body) promotionController.getPromotionByDiscountCode(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/deletePromotion', function (req, res) { console.log('/promotion/deletePromotion', req.body) promotionController.deletePromotion(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) app.post('/promotion/getProductByFont', function (req, res) { console.log('/promotion/getProductByFont', req.body) promotionController.getProductByFont(req.body, function (err, task) { if (err) { res.send(err); } res.send(task); }); }) }
/* 网络消息序列化 2017/8/5 raintian */ let PBAdapter = require("./PBAdapter"); let BoxSerializer = require("./BoxSerializer"); let PBHelper = require("./protobufjs5/PBHelper"); cc.Class({ properties: { TAG: "NetSerializer", pbAdapter: null, pbHelper: null, boxSerializer: null, sn: 0, }, ctor() { var self = this; self.pbAdapter = new PBAdapter(); self.boxSerializer = new BoxSerializer(); self.pbHelper = new PBHelper(); }, //加载proto文件 loadProto(callBack) { var self = this; self.pbHelper.loadProtoFile(()=>{ if(callBack) callBack(); }); }, //封包接口 packMsg(cmd, body) { var self = this; var serializedBody = ""; //判空以兼容心跳等body无结构的消息 if (body) { var pbName = this.pbAdapter.findPBNameByCmd("req", cmd); if (pbName) { //序列化业务逻辑body serializedBody = self.pbHelper.encode(pbName, body); } } //封装safeShell var safeShellObj = { sign_type: 0, //暂时不使用签名校验 encrypt_type: 0, //默认不对body加密 uid: qf.cache.user.uin ? qf.cache.user.uin : 0, //登录填0,其他填uin random: Math.floor(Math.random() * 100000000), //随机数(int32) time: Date.parse(new Date()) / 1000, //本地时间 time_zone: 8, //本地时区(待修改) version: qf.cfg.VERSION, //版本号(待修改) channel: qf.cfg.CHANNEL, //渠道号(待修改) extra: "", //附加信息(待修改) body: serializedBody, //业务body序列化 sign: "" //签名,暂时不填写 }; //编码safeShell var safeShellPbName = self.pbAdapter.getSafeShellPbName(); var pbArrayBuffer = self.pbHelper.encode(safeShellPbName, safeShellObj); //封装box var boxArrayBuffer = self.boxSerializer.packBox(cmd, ++self.sn, pbArrayBuffer); return boxArrayBuffer; }, //解包接口 unpackMsg(data) { var self = this; //先解包box var boxData = self.boxSerializer.unpackBox(data); //再解包safeShell var safeShellPbName = self.pbAdapter.getSafeShellPbName(); var formatData = self.pbHelper.formatData(boxData.body); var safeShellObj = self.pbHelper.decode(safeShellPbName, formatData); if (!safeShellObj) { loge("message decode error!!!", self.TAG); return null; } var ret = {}; ret.cmd = boxData.cmd; ret.ret = boxData.ret; ret.sn = boxData.sn; if (ret.ret === 0) { //解包业务body, 加判断兼容空包 if (safeShellObj.body) { var pbName = self.pbAdapter.findPBNameByCmd("rsp", ret.cmd); if (pbName) { var body = self.pbHelper.decode(pbName, safeShellObj.body); ret.model = body; } } } //dump(ret); return ret; }, //解包带签名的部分 getDataBySignedBody(signedbody, cmd) { var self = this; //mark: 签名校验不通过,可能是数据转换有问题,先跳过 //var str = String.fromCharCode.apply(null, signedbody.body); // var str = ""; // for (var i=0; i<signedbody.body.byteLength; i++) { // str += String.fromCharCode(signedbody.body[i]) // } //var signOrigin = UNITY_PAY_SECRET + str; // var body = null; // var clientSign = md5(signOrigin); // if (signedbody.sign === clientSign) { // body = signedbody.body; // } else { // return null; // } var body = signedbody.body; var pbName = self.pbAdapter.findPBNameByCmd("rsp", cmd); if (!pbName) return null; var obj = self.pbHelper.decode(pbName, body); return obj; }, //获取消息序列号 getSn() { var self = this; return self.sn; } }); function NetBoxSerializerUnitTest() { logd("NetBoxSerializerUnitTest"); var netSerializer = new NetSerializer(); netSerializer.initPbHelper(()=>{ //模拟发包 var boxArrayBuffer = netSerializer.packMsg(qf.cmd.USER_PROP_CHANGE, {prop_type: 1, delta_amount: 1234567890123456, remain_amount: 3}); //模拟收包 var msg = netSerializer.unpackMsg(boxArrayBuffer); dump(msg); }); //构造extra字段 // var extraStr = JSON.stringify({cmd: cmd}); // var byteBuffer = new dcodeIO.ByteBuffer().writeIString(extraStr); // safeShellObj.extra = byteBuffer; // // var extraStr2 = byteBuffer.readIString(); // var extraStr = JSON.stringify({cmd: cmd}); // var extraStrLen = extraStr.length; // var data = new Uint8Array(extraStr.length); // for (var i = 0; i < extraStrLen; ++i) { // data[i] = extraStr.charCodeAt(i); // } // safeShellObj.extra = data.buffer; }
import React from 'react' import { Mark } from '../../../..' const BOLD = { fontWeight: 'bold' } export function renderMark(mark) { if (mark.type == 'bold') return BOLD } export function renderDecorations(text) { let { characters } = text let second = characters.get(1) let mark = Mark.create({ type: 'bold' }) let marks = second.marks.add(mark) second = second.merge({ marks }) characters = characters.set(1, second) return characters }
import { shape, oneOfType, number, string, bool, node, arrayOf } from "prop-types"; export const userType = shape({ id: number.isRequired, avatarSrc: string.isRequired, name: string.isRequired, nickName: string.isRequired, isV: bool.isRequired, desc: string.isRequired, followers: number.isRequired, following: number.isRequired, phone: number.isRequired, email: string.isRequired, location: string.isRequired, birthday: string.isRequired, registerTime: string.isRequired }); export const tweetType = shape({ id: number.isRequired, userId: number.isRequired, content: string.isRequired, createdTime: string.isRequired, replayAmount: number.isRequired, forewardAmount: number.isRequired, likeAmount: number.isRequired }); export const linkListType = arrayOf( shape({ to: string.isRequired, title: oneOfType([string, node]).isRequired, exact: bool }) ); export const positionType = shape({ left: number, right: number, top: number, bottom: number }); export const defaultPosition = { left: null, right: null, top: null, bottom: null };
import React from 'react' import PropTypes from 'prop-types' import { DatePicker, TimePicker } from 'antd' import moment from 'moment' export default class TimeSelector extends React.Component { static propTypes = { onDatechange: PropTypes.func, onTimeChange: PropTypes.func, } constructor(props) { super(props) this.state = { date: moment().add(-1, 'days'), time: moment('00:00:00','HH:mm:ss'), } } onDateChange = (date) => { this.setState({ date, }, () => { this.props.onDateChange(date) }) } onTimeChange = (time) => { this.setState({ time, }, () => { this.props.onTimeChange(time) }) } disabledDate = (current) => { return current && current < moment('2015-07-07') } render() { return ( <div> <p>选择日期和时间</p> <DatePicker defaultPickerValue={this.state.date} onChange={this.onDateChange} disabledDate={this.disabledDate} size='large' /> <TimePicker defaultValue={this.state.time} onChange={this.onTimeChange} size='large' /> </div> ) } }
import React, { Component } from 'react'; import { Text, View, Alert, TouchableOpacity, ImageBackground } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { FormLabel, FormInput, FormValidationMessage, Button } from 'react-native-elements' import signStyles from '../styles/signStyles.js'; const Realm = require('realm'); export default class URLinput extends Component<{}> { constructor(props) { super(props); this.state = { stateURL: "", realm : null, optionsObject: null, errorState : 0, errorMessage: "data error!", }; } componentWillMount() { Realm.open({ schema: [ {name: 'orderList', primaryKey: 'odCode', properties: {odCode: {type: 'string'}, odNameCht: {type: 'string', default: ""}, odChkSta : {type: 'string', default: "0"}, goodsDetail: {type: 'list', objectType:'listComponent', default: []} } }, {name: 'listComponent', properties: {odCode: {type: 'string' , default: ""}, goodCode: {type: 'string'}, goodNameCht: {type: 'string' , default: ""}, goodAmoOdoo: {type: 'string'}, goodAmoFir: {type: 'string', default: "0"}, goodAmoSec: {type: 'string', default: "0"}, goodChkStaFir:{type: 'string', default: "0"}, goodChkStaSec:{type: 'string', default: "2"} } }, {name: 'options', properties: {URL: {type: 'string'}, userAccount: {type: 'string'}, userPwd: {type: 'string'}, accIdentity: {type: 'int'}, manager: {type: 'bool'} } } ] }).then(realm => { let rmObjectOptions = realm.objects('options'); if (rmObjectOptions.length>0) { this.setState({ stateURL: rmObjectOptions[0].URL, }); } this.setState({ optionsObject: rmObjectOptions[0] }); this.setState({ realm }); }); } //func for inputText change URL changeStateURL(inputURL) { this.setState({ stateURL: inputURL }); } //input the settings to Realm inputDataRealmOptions() { this.state.realm.write(() => { this.state.optionsObject.URL = this.state.stateURL; }) Alert.alert( 'Success', '資料儲存成功', [ {text: 'OK', onPress: () => this.pressOK()} ], { cancelable: false } ) } pressOK() { this.setState({visible: false}); Actions.pop(); } render() { return ( <ImageBackground source={ require('../assets/mainBackground.png') } style={{height:667,width:360}}> <View style={signStyles.signContainer}> <View style={signStyles.inContainer}> <FormLabel>URL設定</FormLabel> <FormInput ref={"inputURL"} placeholder={this.state.stateURL} placeholderTextColor='#5F769A' onChangeText={(text)=>this.changeStateURL(text)} /> </View> { this.state.errorState == 1 && <View style={signStyles.inContainer}> <FormValidationMessage>{this.state.errorMessage}</FormValidationMessage> </View> } <View style={signStyles.inContainer}> <TouchableOpacity style={signStyles.loginBtn} onPress={ _ => this.inputDataRealmOptions()}> <Text style={signStyles.loginText}> 設定 </Text> </TouchableOpacity> </View> </View> </ImageBackground> ); } }
import React, { Component } from 'react'; import styles from './container.module.scss'; import axios from 'axios'; import { ReactComponent as RefreshIcon } from '../../assets/refresh.svg'; // Components import Checkbox from '../Checkbox/checkbox'; import LaunchTable from '../Launch/launchTable'; class Container extends Component { constructor(props) { super(props) this.state = { checkboxes: { land: false, reused: false, reddit: false, }, launches: [] } } componentDidMount() { this.callApi(); } callApi = () => { axios.get(`https://api.spacexdata.com/v2/launches`) .then(res => { let launches = res.data; // Map out needed data launches = launches.map(launch => { let land_success = false; let reused = false; let reddit = false; launch.rocket.first_stage.cores.forEach(core => { if (core.land_success) { land_success = true; } }); for (var i in launch.reuse) { if (launch.reuse[i]) { reused = true; } } for (var j in launch.links) { const filter = /reddit_/; if (filter.test(j)) { if (launch.links[j] !== null) { reddit = true; } } } const formatted = { flight_number: launch.flight_number, mission_patch_small: launch.links.mission_patch_small, rocket_name: launch.rocket.rocket_name, rocket_type: launch.rocket.rocket_type, launch_date_utc: launch.launch_date_utc, details: launch.details, article_link: launch.links.article_link, land_success: land_success, reused: reused, reddit: reddit, } return formatted; }); this.setState({ launches }); }) } updateCheckbox = (name, value) => { let prevState = {...this.state.checkboxes} prevState[name] = value; this.setState({ checkboxes: prevState }); } filterLaunches = () => { let launches = this.state.launches; if (this.state.checkboxes.land) { launches = launches.filter(launch => launch.land_success === true) } if (this.state.checkboxes.reused) { launches = launches.filter(launch => launch.reused === true) } if (this.state.checkboxes.reddit) { launches = launches.filter(launch => launch.reddit === true) } return launches; } render() { const launches = this.filterLaunches(); return ( <div> <div className={styles.root}> <div className={styles.bar}> <div className={styles.refresh}> <RefreshIcon className={styles.refreshIcon} fill="#eee" width="20px" onClick={this.callApi}/> </div> <div className={styles.checkboxes}> <Checkbox label="LAND SUCCESS" name="land" checked={this.state.checkboxes.land} updateCheckbox={this.updateCheckbox} /> <Checkbox label="REUSED" name="reused" checked={this.state.checkboxes.reused} updateCheckbox={this.updateCheckbox} /> <Checkbox label="WITH REDDIT" name="reddit" checked={this.state.checkboxes.reddit} updateCheckbox={this.updateCheckbox} /> </div> </div> <LaunchTable launches={launches} /> </div> </div> ) } } export default Container;
import React,{Component} from 'react' import TipBubble from '../../shareComponent/TipBubble' import {GUIDE_TEXT} from '../../../constants/ConstantData' const Empty = ({actions,hasGroup,hasData}) => { return ( <div className="emptyBox"> <img className='icon-empty' src={`${process.env.PUBLIC_URL}/images/icon/gd-noData.png`} alt=""/> { !hasGroup ?<p className='text-empty'>还没有入群页面,快去新建一个吧~</p> :!hasData?<p className='text-empty'>当前查询没有数据,请重新选择时间段查询数据~</p>:'' } { !hasGroup ?<div className="btn-empty" onClick={()=>{actions.goTo('/v2/GIScope')}}> <span>去新建</span> <div className="wave-square"></div> <TipBubble tipData ={GUIDE_TEXT.GI_BUILD} styles={{left:0,top:'56px'}}/> </div> :'' } </div> ) } export default Empty
window.PlacesCollection = Parse.Collection.extend({ model: PlaceModel });
import "./landing.css" import { Link } from "react-router-dom"; function Landing() { return ( <div className="div-home"> <h2 className="h1"> <Link to="/home" className="h1-link">Home</Link> </h2> </div> ); } export default Landing
;nibblecontact = { weeklyChart : null, name : 'nibblecontact', init : function () { $('#home-content').load('views/home/'+nibblecontact.name+'.html', function(){ //init stuff }); } };
/* eslint-env node, mocha */ const assert = require('chai').assert const github = require.main.require('lib/util/github') describe('GitHub util', function () { var invalidOptionsTests = [ { options: undefined }, { options: null }, { options: {} }, { options: { a: 'b' } }, { options: [] } ] describe('getGitHubIssuesQueryUrl()', function () { invalidOptionsTests.forEach((testData) => { it(`throws error if options is ${JSON.stringify(testData.options)}`, (done) => { try { github.getGitHubIssuesQueryUrl(testData.options) } catch (err) { assert.isNotNull(err) done() } }) }) it('succeeds if owner & repo is specified', () => { let url = github.getGitHubIssuesQueryUrl({ owner: 'foobar', repo: 'fizzbuzz' }) assert.equal(url, 'https://api.github.com/repos/foobar/fizzbuzz/issues?') }) it('succeeds if owner & repo is specified with labels', () => { let url = github.getGitHubIssuesQueryUrl({ owner: 'foobar', repo: 'fizzbuzz', labels: 'abc' }) assert.equal(url, 'https://api.github.com/repos/foobar/fizzbuzz/issues?labels=abc') }) it('succeeds if owner & repo is specified with milestone', () => { let url = github.getGitHubIssuesQueryUrl({ owner: 'foobar', repo: 'fizzbuzz', milestone: 'foo' }) assert.equal(url, 'https://api.github.com/repos/foobar/fizzbuzz/issues?milestone=foo') }) it('succeeds if owner & repo is specified with labels & milestone', () => { let url = github.getGitHubIssuesQueryUrl({ owner: 'foobar', repo: 'fizzbuzz', labels: 'abc,def', milestone: 'foo' }) assert.equal(url, 'https://api.github.com/repos/foobar/fizzbuzz/issues?milestone=foo&labels=abc%2Cdef') }) }) describe('getGitHubIssueUrl()', function () { invalidOptionsTests.forEach((testData) => { it(`throws error if options is ${JSON.stringify(testData.options)}`, (done) => { try { github.getGitHubIssueUrl(testData.options) } catch (err) { assert.isNotNull(err) done() } }) }) it('succeeds if owner, repo & issueNum is specified', function () { let url = github.getGitHubIssueUrl({ owner: 'foobar', repo: 'fizzbuzz', issueNum: '3' }) assert.equal(url, 'https://api.github.com/repos/foobar/fizzbuzz/issues/3') }) }) describe('getGitHubProjectsUrl()', function () { invalidOptionsTests.forEach((testData) => { it(`throws error if options is ${JSON.stringify(testData.options)}`, (done) => { try { github.getGitHubProjectsUrl(testData.options) } catch (err) { assert.isNotNull(err) done() } }) }) it('succeeds if owner is specified', function () { let url = github.getGitHubProjectsUrl({ owner: 'foobar' }) assert.equal(url, 'https://api.github.com/orgs/foobar/projects?status=open') }) }) })
import ReactDom from 'react-dom'; import React from 'react'; import MenuAppBar from './components/MenuAppBar' import Select from './components/Select' import FormGroup from "@material-ui/core/FormGroup"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Checkbox from "@material-ui/core/Checkbox"; import CheckBoxOutlineBlankIcon from "@material-ui/icons/CheckBoxOutlineBlank"; import CheckBoxIcon from "@material-ui/icons/CheckBox"; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import AppBar from '@material-ui/core'; import TextField from '@material-ui/core/TextField'; export default class Main extends React.Component{ constructor(){ super(); this.state={ notif:[], checkedA:true, checkedB:true, id_reclamacao: 0, listEstado: ["Ativo", "Inativo"], listTipo: ["Quebra", "Geral","Limpeza"], estado: 0, stateButton: true, sala: '' } this.clickState = this.clickState.bind(this); } getNotif = async() => { let res = await fetch('/reclamacoes', { method: 'GET' }) res = await res.json() var l = [] var v = [] for(var i = 0; i < res.length; i++){ if(this.state.sala === res[i].nome_sala){ l.push(res[i]) } else if(this.state.sala === ""){ l.push(res[i]) } } for(var i = 0; i < l.length; i++){ if(this.state.checkedA && !l[i].estado){ v.push(l[i]) } if(this.state.checkedB && l[i].estado){ v.push(l[i]) } } this.setState({notif: v}) } putState = async() => { let res = await fetch('/reclamacao' ,{ method: 'PUT', body: JSON.stringify({ "id_reclamacao": this.state.id_reclamacao, "estado": !(this.state.estado) }), headers: {"Content-Type": "application/json"} }) res = await res.json() console.log(res) } handleClick(ev){ fetch('/auth', { method: 'POST', body: JSON.stringify({ "email": this.state.email, "senha": this.state.senha }), headers: {"Content-Type": "application/json"} }) } getIdRow(id_rec, estado){ this.setState({id_reclamacao: id_rec, estado:estado, stateButton: false}) } handleChange = name => event => { this.setState({ [name]: event.target.checked }); this.getNotif() }; handleSalaChange = name => event => { this.setState({ [name]: event.target.value }); this.getNotif() }; clickState(){ if(this.state.id_reclamacao > 0){ this.putState() this.getNotif() } } componentWillMount(){ this.getNotif() } render(){ return( <Grid container spacing={16}> <Grid item xs={12}> <MenuAppBar/> </Grid> <Grid item xs={2}></Grid> <Grid item xs={4}> <TextField label="Sala:" onChange={this.handleSalaChange("sala")} /> </Grid> <Grid item xs={2}></Grid> <Grid item xs={4}> <FormGroup row > <FormControlLabel control={ <Checkbox checked={this.state.checkedA} onChange={this.handleChange("checkedA")} value="checkedA" color="primary" /> } label="Ativo" /> <FormControlLabel control={ <Checkbox checked={this.state.checkedB} onChange={this.handleChange("checkedB")} value="checkedB" color="primary" /> } label="Inativo" /> </FormGroup> </Grid> <Grid item xs={1}></Grid> <Grid item xs={10}> <Paper> <Table > <TableHead style = {{backgroundColor: "Gray"}}> <TableRow> <TableCell >Nome Sala</TableCell> <TableCell >Nome Usuario</TableCell> <TableCell >Tipo Reclamação</TableCell> <TableCell >Descricao</TableCell> <TableCell >Estado</TableCell> <TableCell >Horario</TableCell> </TableRow> </TableHead> <TableBody> {this.state.notif.map((line, index) => { return ( <TableRow onClick={() => this.getIdRow(line.id_reclamacao, line.estado)}> <TableCell >{line.nome_sala}</TableCell> <TableCell >{line.nome}</TableCell> <TableCell >{this.state.listTipo[line.tipo_r]}</TableCell> <TableCell >{line.descricao}</TableCell> <TableCell >{this.state.listEstado[line.estado]}</TableCell> <TableCell >{line.horario.slice(0,10)}</TableCell> </TableRow> ) })} </TableBody> </Table> </Paper> </Grid> <Grid item xs={1}></Grid> <Button variant="outlined" disabled = {this.state.stateButton} onClick = {this.clickState}>Mudar Estado</Button> </Grid> ); } }
'use strict'; // load environment variables const path = require('path'); const pwd = path.join(__dirname, '..', '/.env'); let config = require('config'); const seneca = require('seneca')(); const mailer = require('./lib/mailer'); // select desired transport method const patternPin = 'role:mailer'; seneca.use('seneca-amqp-transport'); let amqpUrl = config.has("rabbitmqCloudUrl") ? config.get("rabbitmqCloudUrl") : `amqp://${config.get('rabbitmq.username')}:${config.get('rabbitmq.password')}@${config.get('rabbitmq.host')}:${config.get('rabbitmq.port')}`; // init seneca and expose functions seneca .add(patternPin + ',cmd:send,subject:pwforget,', mailer.sendPwForgottenMail) .add(patternPin + ',cmd:send,subject:generic,', mailer.sendGenericMail) .add(patternPin + ',cmd:send,subject:confirmMail', mailer.sendConfirmationMail); seneca .listen({ type: 'amqp', url: amqpUrl, pin: patternPin }) .client({ type: 'amqp', url: amqpUrl, pin: 'role:user' });
const tmp = require('tmp-promise') const { promises: fs } = require('fs') const { join } = require('path') const child_process = require('child_process') const VM_BIN = join(__dirname, '..', '..', 'corewar') const OP = { LIVE: { code: 0x01, cycles: 10 }, LD: { code: 0x02, cycles: 5 }, ST: { code: 0x03, cycles: 5 }, ADD: { code: 0x04, cycles: 10 }, SUB: { code: 0x05, cycles: 10 }, AND: { code: 0x06, cycles: 6 }, OR: { code: 0x07, cycles: 6 }, XOR: { code: 0x08, cycles: 6 }, ZJMP: { code: 0x09, cycles: 20 }, LDI: { code: 0x0a, cycles: 25 }, STI: { code: 0x0b, cycles: 25 }, FORK: { code: 0x0c, cycles: 800 }, LLD: { code: 0x0d, cycles: 10 }, LLDI: { code: 0x0e, cycles: 50 }, LFORK: { code: 0x0f, cycles: 1000 }, AFF: { code: 0x10, cycles: 2 } }; function mem(index) { const MEM_SIZE = 4096; while (index < 0) { index += MEM_SIZE; } return (index % MEM_SIZE); } function idx(index) { const IDX_MOD = 4096 / 8; index %= IDX_MOD; index = mem(index); return(index); } function ocp(...types) { if (types.length > 4) throw new Error("Too much arguments"); let ocp = 0; for (const [i, type] of types.entries()) { switch (type){ case "DIRECT": ocp |= 0b10 << ((3 - i) * 2); break; case "INDIRECT": ocp |= 0b11 << ((3 - i) * 2); break; case "REGISTER": ocp |= 0b01 << ((3 - i) * 2); break; default: throw new Error(`Invalid type "${type}"`); } } return ocp; } function execVm(args) { return new Promise((resolve, reject) => { child_process.exec(`${VM_BIN} ${args}`, (err, stdout, stderr) => { if (err) reject(err) else { if (stderr) reject(new Error(stderr)); else { resolve(new Uint8Array(stdout .split('\n') .filter(l => l.length > 0) .map(l => l.slice(l.indexOf(":") + 1).trim().split(" ").map(n => parseInt(n, 16))) .reduce((c,v) => c.concat(v), []))) /* Zaz vm format resolve(new Uint8Array(stdout .slice(stdout.indexOf('0x0000')) .split('\n') .filter(l => l.length > 0) .map(l => l.slice(l.indexOf(":") + 1).trim().split(" ").map(n => parseInt(n, 16))) .reduce((c,v) => c.concat(v), [])));*/ } } }) }) } const NAME_LENGTH = 128 const NAME_PADDING = 4 const COMMENT_LENGTH = 2048 const COMMENT_PADDING = 4 const MAGIC = [0x00, 0xea, 0x83, 0xf3] // Magic const NAME = Array.from({ length: NAME_LENGTH + NAME_PADDING }).fill(0) const COMMENT = Array.from({ length: COMMENT_LENGTH + COMMENT_PADDING }).fill(0) async function runVm(memory, dumpAt) { const file = await tmp.file() const err = memory.findIndex(e => typeof e !== 'number') if (err != -1) throw new Error(`Invalid memory not all elem are numbers at ${err} value = "${memory[err]}"`) const length = new Uint8Array(4) new DataView(length.buffer).setUint32(0, memory.length); await fs.writeFile(file.path, new Uint8Array([...MAGIC, ...NAME, ...Array.from(length), ...COMMENT, ...memory])); try { return await execVm(`-d ${dumpAt} ${file.path}`) } finally { file.cleanup(); } } function dumpReg(code, reg) { const offset = code.length; return { code: code.concat([OP.ST.code, ocp("REGISTER", "INDIRECT"), reg, 0, 0]), readRegValue(dump) { return new DataView(dump.buffer).getInt32(offset); }, cycles: OP.ST.cycles } } function dumpCarry(code) { const newCode = code.concat([ OP.ZJMP.code, 0, 10, OP.LD.code, ocp("DIRECT", "REGISTER"), 0, 0, 0, 1, 15, ]) const { code: rCode, readRegValue, cycles } = dumpReg(newCode, 15); return { code: rCode, readCarry(dump) { const val = readRegValue(dump); if (val !== 0 && val !== 1) throw new Error(`Invalid value ${val}`); return !Boolean(val); }, cycles: OP.ZJMP.cycles + OP.LD.cycles + cycles } } function direct(val) { const buff = new Uint8Array(4) new DataView(buff.buffer).setInt32(0, val); return Array.from(buff) } function indirect(val) { const buff = new Uint8Array(2) new DataView(buff.buffer).setInt16(0, val); return Array.from(buff) } module.exports = { OP, ocp, runVm, dumpReg, dumpCarry, direct, indirect, mem, idx };
;(function(global){ //开启严格模式 "use strict"; //构造函数定义一个类 传参数 function Drag(inbox,outbox,limit) { this.inbox=document.querySelector(inbox); this.title=this.inbox.querySelector(".dragbur"); if(outbox=="window") { this.outWidth=document.documentElement.clientWidth; this.outHeight=document.documentElement.clientHeight; }else { this.outbox=document.querySelector(outbox); this.outWidth=this.outbox.offsetWidth; this.outHeight=this.outbox.offsetHeight; } this.limit=limit; } //原型链上提供方法 Drag.prototype.dragFn=function() { var that=this; this.title.onmousedown=function(event) { this.x=0; this.y=0; this.x=event.clientX-that.inbox.offsetLeft; this.y=event.clientY-that.inbox.offsetTop; var that2=this; document.onmousemove=function(event) { this.outX=event.clientX-that2.x; this.outY=event.clientY-that2.y; this.oWidth=that.outWidth-that.inbox.offsetWidth; this.oHeight=that.outHeight-that.inbox.offsetHeight; // console.log(oWidth+" "+oHeight); if(that.limit=="limitX") { if(this.outX<0) { this.outX=0; //限制左边 } else if (this.outX>this.oWidth) { this.outX=this.oWidth; //限制右边 } }else if(that.limit=="limitY") { if(this.outY<0) { this.outY=0; } else if (this.outY>this.oHeight) { this.outY=this.oHeight; } }else if(that.limit=="limitXY") { if(this.outX<0) { this.outX=0; } else if (this.outX>this.oWidth) { this.outX=this.oWidth; } if(this.outY<0) { this.outY=0; } else if (this.outY>this.oHeight) { this.outY=this.oHeight; } } that.inbox.style.left=this.outX+'px'; that.inbox.style.top=this.outY+'px'; }; document.onmouseup=function(event) { document.onmousemove=null; document.onmouseup=null; }; return false; }; }; //兼容CommonJs规范 if (typeof module !== 'undefined' && module.exports) { module.exports = Drag; }; //兼容AMD/CMD规范 if (typeof define === 'function') define(function() { return Drag; }); //注册全局变量,兼容直接使用script标签引入插件 if(global.Drag){ throw new Error("global.Drag Already exist") }else{ global.Drag = Drag; } })(this);
import { db } from './db'; export const getUrlById = ({ input: { id } }) => { return db .table('urls') .get(id) .run() .then(result => result); }; const createUrl = ({ input: { originalUrl } }) => { return db .table('urls') .insert({ id: `asdfasdf=${originalUrl}`, originalUrl, createdAt: new Date(), deletedAt: null, expiredAt: null, }) .run() .then(result => result.generated_keys[0]) .then(id => getUrlById({ input: { id } })); }; export { createUrl };
const mongoose = require('mongoose'); const uniqueValidator = require('mongoose-unique-validator'); const userSchema = new mongoose.Schema({ username: { type: 'String', unique: true, require: true }, password: String }); userSchema.plugin(uniqueValidator); var User = mongoose.model('User', userSchema); function login(body) { const { username, password } = body; return User.find({ username, password }); } function signup(user) { return User.create(user); } module.exports = { login, signup };
/** * @param {number[]} height * @return {number} */ var trap = function(height) { let water = 0; for (let left = 1; left < height.length - 1; left++) { let maxLeft = 0; let maxRight = 0; // Search the left part for max bar size for (let right = left; right >= 0; right--) { maxLeft = Math.max(maxLeft, height[right]); } // Search the right part for max bar size for (let right = left; right < height.length; right++) { maxRight = Math.max(maxRight, height[right]); } water += Math.min(maxLeft, maxRight) - height[left]; } return water; }; let input2 = [0, 1, 0, 1]; let input = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]; let result = trap(input); console.log(JSON.stringify(result));
function ingresarInmueble() { var error = false; var nombre = $("#inputNombreInmueble"); var descripcion = $("#inputDescripcionInmueble"); if (nombre.val() === "") { nombre.parent().addClass("has-error"); error = true; } else { nombre.parent().removeClass("has-error"); } if (descripcion.val() === "") { descripcion.parent().addClass("has-error"); error = true; } else { descripcion.parent().removeClass("has-error"); } if (!error) { crearNuevoInmuebleClient(JSON.stringify($('form').serializeObject())); } else { alertify.error("Complete los campos obligatorios"); } } /* ________________________ LLAMADOS AJAX ________________________ */ function crearNuevoInmuebleClient(serializedForm) { $.ajax({ type: "POST", url: "create", data: { 'data' : serializedForm } }) .done(function(msg) { console.log(msg); alertify.success("inmueble ingresado con exito"); }) .fail(function(msg){ console.log(msg); alertify.error("error interno de la aplicacion"); }) .always(function(){ }); }
let movements = [[0, 0], [0, 5], [-1, -3], [-3, 1], [2, -4], [3, 2]]; console.log(movements.filter((value)=>{ if(value[0] >=0 && value[1] >=0){ return value; }})); let map = movements.map((numbers)=> Math.abs(numbers[0]) + Math.abs(numbers[1]) ); console.log(map); movements.forEach((map, number)=>{ let x = Math.abs(map[0]) + Math.abs(map[1]); console.log(`Movement #${number}: ${x} steps`); }); let code = 'noggin oreo the moon time tele steed his tent apollo her lives though shoo tofu budapest'.split(' '); let reducer = function (accumlator, currentValue){ if(currentValue.length ===3){ return accumlator + ' '; } return accumlator + currentValue[currentValue.length-1].toUpperCase(); } console.log(code.reduce(reducer, ''));
import React, { Component } from 'react'; import { UserOutlined } from '@ant-design/icons'; import { withRouter } from 'react-router-dom'; import intl from 'react-intl-universal'; import { Avatar, Dropdown, Menu, Tag } from 'antd'; import Event from '@utils/event'; import './index.less'; class Index extends Component { constructor(props) { super(props); this.state = { lang: 'zh_CN' }; this.signOut = this.signOut.bind(this); } signOut() { const { history } = this.props; localStorage.token = ''; history.replace('/user/login'); } changeIntl = () => { Event.emit('changeLanguage', this.state.lang == 'zh_CN' ? 'en_US' : 'zh_CN'); this.setState({ lang: this.state.lang == 'zh_CN' ? 'en_US' : 'zh_CN' }); } render() { const menu = ( <Menu> <Menu.Item> <a target="_blank" rel="noopener noreferrer" href={false} onClick={this.signOut}> 退出 </a> </Menu.Item> </Menu> ); return ( <section className="layoutHeader"> <div className="headeLeft"> {intl.get('订单系统') ? intl.get('订单系统') : intl.get('ORDER-SYSTEM')} </div> <div className="headerRight"> <Tag className="intl" onClick={this.changeIntl}>{this.state.lang == 'zh_CN' ? '中文' : 'English'}</Tag> <span className="message">{intl.get('消息') ? intl.get('消息') : intl.get('MESSAGE')}</span> <Dropdown className="dropDown" overlay={menu}> <div> <Avatar className="avatar" size={28} icon={<UserOutlined />} /> <span className="name">{intl.get('飞科') ? intl.get('飞科') : intl.get('FAKER')}</span> </div> </Dropdown> </div> </section> ); } } export default withRouter(Index);
import {ImmutablePropTypes, PropTypes} from 'src/App/helpers' import { immutablePageTextModel, immutablePornstarsListWithLetterModel, pageRequestParamsModel, immutableSponsorsListModel, } from 'src/App/models' import {immutableVideoItemModel} from 'src/generic/VideoItem/models' const pornstarInfoForTableModelBuilder = process.env.NODE_ENV === 'production' ? null : (isImmutable) => { const exact = isImmutable ? ImmutablePropTypes.exact : PropTypes.exact, props = { name: PropTypes.string.isOptional, alias: PropTypes.string.isOptional, birthday: PropTypes.string.isOptional, astrologicalSign: PropTypes.string.isOptional, lifetime: PropTypes.string.isOptional, profession: PropTypes.string.isOptional, country: PropTypes.string.isOptional, city: PropTypes.string.isOptional, ethnicity: PropTypes.string.isOptional, colorEye: PropTypes.string.isOptional, colorHair: PropTypes.string.isOptional, height: PropTypes.number.isOptional, weight: PropTypes.number.isOptional, breast: PropTypes.number.isOptional, breastSizeType: PropTypes.string.isOptional, cupSize: PropTypes.string.isOptional, boobsFake: PropTypes.string.isOptional, shoeSize: PropTypes.number.isOptional, tatoos: PropTypes.string.isOptional, piercings: PropTypes.string.isOptional, waist: PropTypes.number.isOptional, hip: PropTypes.number.isOptional, penis: PropTypes.string.isOptional, bodyHair: PropTypes.string.isOptional, physiqueCustom: PropTypes.string.isOptional, sexualRole: PropTypes.string.isOptional, careerTime: PropTypes.string.isOptional, extra: PropTypes.string.isOptional, } return exact(props) }, pornstarInfoModelBuilder = process.env.NODE_ENV === 'production' ? null : isImmutable => { const exact = isImmutable ? ImmutablePropTypes.exact : PropTypes.exact, props = { id: PropTypes.number, // idTag: PropTypes.number, // thumbPath: PropTypes.string, thumbUrl: PropTypes.string, // urlGalleries: PropTypes.string, } return exact(props) } export const pornstarInfoForTableModel = process.env.NODE_ENV === 'production' ? null : pornstarInfoForTableModelBuilder(false), pornstarInfoModel = process.env.NODE_ENV === 'production' ? null : pornstarInfoModelBuilder(false) const immutablePornstarInfoForTableModel = process.env.NODE_ENV === 'production' ? null : pornstarInfoForTableModelBuilder(true), immutablePornstarInfoModel = process.env.NODE_ENV === 'production' ? null : pornstarInfoModelBuilder(true), model = process.env.NODE_ENV === 'production' ? null : ImmutablePropTypes.exact({ isLoading: PropTypes.bool, isLoaded: PropTypes.bool, isFailed: PropTypes.bool, tagId: PropTypes.number, lastPageRequestParams: PropTypes.nullable(pageRequestParamsModel), pageNumber: PropTypes.number, pageText: PropTypes.nullable(immutablePageTextModel), pagesCount: PropTypes.number, sortList: ImmutablePropTypes.listOf(ImmutablePropTypes.exact({ isActive: PropTypes.bool, code: PropTypes.string, })), currentSort: PropTypes.nullable(PropTypes.string), itemsCount: PropTypes.number, videoList: ImmutablePropTypes.listOf(immutableVideoItemModel), modelsList: immutablePornstarsListWithLetterModel, pornstarInfoForTable: immutablePornstarInfoForTableModel, pornstarInfoForTableKeysOrder: ImmutablePropTypes.listOf(PropTypes.string), pornstarInfo: PropTypes.nullable(immutablePornstarInfoModel), randomWidthList: PropTypes.nullable(ImmutablePropTypes.listOf(PropTypes.number)), sponsorsList: immutableSponsorsListModel, currentSponsor: PropTypes.nullable(PropTypes.string), }) export { immutablePornstarInfoForTableModel, immutablePornstarInfoModel, model, }
var saxnjs = require('saxn'); exports.createSaxnSaxjsParser = function(sax, base_handler, error_cb) { var saxn = saxnjs.createXmlParser(base_handler); sax.onopentag = function(tag) { saxn.onOpenTag(tag); }; sax.onclosetag = function(tag) { saxn.onCloseTag(tag); }; sax.ontext = function(text) { saxn.onText(text); }; sax.oncdata = function(data) { saxn.onCData(data); }; sax.oncomment = function(comment) { saxn.onComment(comment); }; sax.onerror = function(error) { error_cb(error); }; var parser = function(data) { sax.write(data); }; parser.userData = saxn.userData; return parser; };
//Questa funzione serve per nascondere o visualizzare il div che viene visualizzato quando //una pagina sta caricando qualcosa o salvando. function displayLoading(val) { if (val == 1) top.document.getElementById('divLoading').style.display = 'block'; else top.document.getElementById('divLoading').style.display = 'none'; }
import React, { Component } from 'react' import jsPdf from 'jspdf' import domtoimage from 'dom-to-image' export default class ExportToPDFButton extends Component { constructor() { super() this.export = this.export.bind(this) } export () { const pages = Array.from(document.querySelectorAll(this.props.pageClass)) const promises = pages.map((p) => { return domtoimage.toPng(p) .then(function (dataUrl) { return dataUrl }) .catch(err => console.log('Error at Dom-To-Image promises', err)) }) Promise.all(promises) .then((dataUrls) => { let doc = new jsPdf('p', 'px', 'a4', false); dataUrls.map((image, index) => { doc.addImage(image, 'PNG', 0, 0, 450, 630); if (index + 1 < dataUrls.length) { doc.addPage('a4'); } return 0; }) doc.save('export.pdf') }) .catch(err => console.log('Error at jsPdf promises', err)) } render() { return ( <button onClick = {this.export} className="downloadBtn"> DESCARGAR </button> ) } }
(function(){ angular .module('myApp') .controller('QALabController', ['$location','Data', QALabController ]) function QALabController($location, Data) { var vm = this; console.log('qa labs'); vm.labs = Data.formatted.qa_lab } })();
const express = require('express'); const router = express.Router(); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const User = require('../models/User.js'); const multer = require('multer'); const config = require('../config/server'); const path = require('path'); const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, path.join(config.user_profile_image_destination_path)); }, filename: (req, file, cb) => { cb(null, `${req.body.username}-${file.originalname}`); } }); const upload = multer({ storage: storage }); router.get('/register', (req, res, next) => { res.render('users/register', { title: 'Register' }); }); router.get('/login', (req, res, next) => { res.render('users/login', { title: 'Log In' }); }); router.post('/register', upload.single('profileimage'), (req, res, next) => { // Create a new user object with the information from the form let user = { name: req.body.name, email: req.body.email, username: req.body.username, password: req.body.password, password2: req.body.password2 }; // Form validation req.checkBody('name', 'Name field is required').notEmpty(); req.checkBody('email', 'Email field is required').notEmpty(); req.checkBody('email', 'Email not valid').isEmail(); req.checkBody('username', 'Username field is required').notEmpty(); req.checkBody('password', 'Password field is required').notEmpty(); req.checkBody('password2', 'Passwords do not match').equals(user.password); // Check for errors let errors = req.validationErrors(); if(errors) { res.render('users/register', { errors: errors, name: user.name, email: user.email, username: user.username, password: user.password, password2: user.password2 }); return; } else { let newUser = new User({ name: user.name, email: user.email, username: user.username, password: user.password, profileimage: req.file ? req.file.filename : 'noimage.png' }); // Create User User.createUser(newUser, (err, user) => { if(err) throw err; console.log(user); }); } // Success message req.flash('success_msg', 'You are now registered and may log in'); res.redirect('/users/login'); }); passport.use(new LocalStrategy((username, password, done) => User.authenticate(username, password, done) )); passport.serializeUser((user, done) => done(null, user.id)); passport.deserializeUser((id, done) => { User.getUserById(id, (err, user) => { if (err) { return done(err); } done(null, user); }); }); router.post('/login', passport.authenticate('local', { failureRedirect: '/users/login', failureFlash: true }), (req, res) => { req.flash('success_msg', 'Log in successfully'); res.redirect('/'); } ); router.get('/logout', (req, res) => { req.logout(); req.flash('success_msg', 'You are now logged out'); res.redirect('/users/login'); }); module.exports = router;
const WebpackDevServer = require('webpack-dev-server'); const webpack = require('webpack'); const webpackConfig = require('../config/webpack/webpack.config'); const builds = require('../config/builds'); const find = require('lodash/find'); const opn = require('opn'); const compiler = webpack(webpackConfig); const devServer = new WebpackDevServer(compiler, { contentBase: builds.map(({ paths }) => paths.public) }); const port = 8080; devServer.listen(port, (err, result) => { if (err) { return console.log(err); } console.log(`Starting the development server on port ${port}...`); console.log(); opn(`http://localhost:${port}`); });
import React, { Component } from 'react'; import axios from 'axios' import CastleDash from './CastleDash'; import Schedule from './Schedule' import '../../styles/index.css' import Hallows from '../presentation/Hallows'; import { CSSTransitionGroup } from 'react-transition-group' class School extends Component { constructor(props){ super(props) this.state = { students: [], staff: [], locations: [], houses: [], active: false, period: null } } componentDidMount(){ axios( { method: 'GET', url: '/api/students'}) .then( response => { this.setState({students: response.data}) }) .then( () => { axios( { method: 'GET', url: '/api/staff' }) .then( response => { this.setState({staff: response.data}) }) .then( () => { axios( { method: 'GET', url: '/api/locations' }) .then( response => { this.setState({locations: response.data}) }) .then( () => { axios({ method: 'GET', url: '/api/houses'}) .then( response => { this.setState({houses: response.data}) }) }) }) }) } activate = () => { this.setState( {active: true} ) } deactivate = () => { this.setState( {active: false} ) } setPeriod = period => { this.state.period !== period ? this.sendAll(period) : console.log('nothin to see here') } render() { return( <div className="School"> <Schedule setPeriod={this.setPeriod} /> {!this.state.active && ( <div className="appHeading"> <button onClick={this.activate}>I solemnly swear that I am up to no good</button> </div> )} {this.state.active && ( <div> <div className="appHeadingActive"> <button className="logoutButton" onClick={this.deactivate}>Mischief Managed</button> </div> <CastleDash houses={this.state.houses} locations={this.state.locations} sendUpdate={this.onUpdateRequest} staff={this.state.staff} students={this.state.students} /> </div> )} </div> ) } onUpdateRequest = ( update, amount) => { console.log(update, amount) axios({ method: 'PUT', url: '/api/students/' + update, data: { amount: amount }, }) .then(response =>{ let update = response.data this.setState( { students: this.state.students.map( student => { if( student.id === update.id ){ return Object.assign( {}, student, { points: update.points, updatedAt: update.updatedAt }) } else { return student } })} ) }).then(()=>{ this.syncScoreboard() }) } syncScoreboard = () => { axios({ method: 'GET', url: '/api/houses/score' }).then(response=>{ this.setState({houses:response.data}) }) } sendAll = block => { this.sendStaff(block) this.setState({period: block}) axios({ method: 'POST', url: '/api/schedule', data: { block: block } }).then(response =>{ this.setState( {students: response.data} ) }) } sendStaff = block => { console.log('sending staff') axios({ method: 'POST', url: '/api/schedule/staff', data: { block: block } }).then(response =>{ this.setState( {staff: response.data} ) }) } } export default School;
import React, {Fragment} from 'react'; import { StyleSheet, View, Text, TextInput, TouchableOpacity, } from 'react-native'; import {connect} from 'react-redux'; import {signIn, isSignedIn} from '../../redux/actions/auth.action'; import { billAccountInfo } from '../../redux/actions/payment.actions'; const width = '80%'; class CreditVisa extends React.Component { state = { card_number: '', expiration_date: '', security_code: '', zip_code: '', }; handleCardNumber = text => { this.setState({card_number: text}); }; handleExpirationDate = text => { this.setState({expiration_date: text}); }; handleSecurityCode = text => { this.setState({security_code: text}); }; handleZipCode = text => { this.setState({zip_code: text}); }; handleAddAccount= async () => { console.log("andle add account called"); const {dispatch} = this.props; try { console.log('ddddddddddddddddddddd'); await dispatch(billAccountInfo(this.state.card_number, this.state.expiration_date, this.state.security_code, this.state.zip_code)); // navigate("Home"); } catch (error) { console.log('dddddddddddddddds', error); } // this.props.route.params.updateAccountTypeInfo(this.state.card_number, this.state.expiration_date); this.props.navigation.navigate('BillPayment'); } render() { // const {navigation, route} = this.props; const {routing_number, account_number} = this.state; return ( <View style={styles.container}> <TextInput style={styles.inputContainer} underlineColorAndroid="rgba(0,0,0,0)" placeholder="Card Number" value={routing_number} id="card_number" placeholderTextColor="#ffffff" autoCapitalize="none" onChangeText={this.handleCardNumber} /> <TextInput style={styles.inputContainer} underlineColorAndroid="rgba(0,0,0,0)" placeholder="Expiration Date" id="expiration_date" value={account_number} secureTextEntry={true} placeholderTextColor="#ffffff" autoCapitalize="none" onChangeText={this.handleExpirationDate} /> <TextInput style={styles.inputContainer} underlineColorAndroid="rgba(0,0,0,0)" placeholder="Security Code" id="security_code" value={account_number} secureTextEntry={true} placeholderTextColor="#ffffff" autoCapitalize="none" onChangeText={this.handleSecurityCode} /> <TextInput style={styles.inputContainer} underlineColorAndroid="rgba(0,0,0,0)" placeholder="Zip Code" id="zip_number" value={account_number} secureTextEntry={true} placeholderTextColor="#ffffff" autoCapitalize="none" onChangeText={this.handleZipCode} /> <TouchableOpacity style={styles.buttonContainer}> <Text style={styles.buttonText} onPress={this.handleAddAccount}> Add Account </Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#455a64', alignItems: 'center', justifyContent: 'center', }, inputContainer: { width: width, backgroundColor: 'rgba(255,255,255,0.3)', borderColor: 'gray', borderWidth: 1, borderRadius: 25, paddingHorizontal: 16, fontSize: 16, color: '#ffffff', marginVertical: 10, }, textContainer: { color: 'blue', fontSize: 20, }, buttonContainer: { backgroundColor: '#1c313a', borderRadius: 25, width: width, marginVertical: 10, paddingVertical: 13, }, buttonText: { fontSize: 16, fontWeight: '500', color: '#ffffff', textAlign: 'center', }, signupTextContainer: { // flexGrow: 1, alignItems: 'flex-end', justifyContent: 'center', marginVertical: 16, fontSize: 16, flexDirection: 'row', }, signupText: { color: 'rgba(255,255,255,0.6)', fontSize: 16, }, signupButton: { color: '#ffffff', fontSize: 16, fontWeight: '500', }, }); const mapStateToProps = ({payment}) => ({payment}); export default connect(mapStateToProps)(CreditVisa);
import React, { useContext, useEffect, useState } from "react"; import { Link } from "react-router-dom"; import { UserContext } from "../../../contexts/UserContext"; import styled from "styled-components"; // helpers import { axiosWithAuth } from "../../../helpers/axiosWithAuth"; // components import Icon from "../../../components/atoms/icon/icon"; import Input from "../../../components/atoms/input/input"; import Button from "../../../components/atoms/button/button"; import Text from "../../../components/atoms/text/text"; import Select from "../../../components/atoms/select/select"; import LoadingSpinner from "../../../components/atoms/spinner"; // images import leftArrow from "../../../images/profile/leftArrow.svg"; import waves from "../../../images/Onboarding/waves.svg"; import editImage from "../../../images/profile/edit_img.svg"; //import DropdownMenu from './DropDownMenu'; const EditContainer = styled.div` /* border: 1px solid red; */ position: relative; width: 100vw; height: 100vh; overflow: hidden; background-image: url(${waves}); `; const ArrowVector = styled.div` position: absolute; left: 3.2rem; top: 6.2rem; `; const EditProfText = styled.p` height: 2.2rem; width: 37.5rem; position: absolute; left: 0; right: 0; top: 9.7rem; font-weight: bold; font-size: 2.4rem; line-height: 2.2rem; /*or 22px */ text-align: center; letter-spacing: 0.2rem; color: #e6e6e6; `; const ImageContainer = styled.div` position: absolute; left: 16rem; top: 14.1rem; border-radius: 50%; height: 6.4rem; width: 6.4rem; background: #c4c4c4; `; const UserImage = styled.img` position: absolute; left: 0; top: 0; border-radius: 50%; height: 6.4rem; width: 6.4rem; `; const CameraVector = styled.div` position: absolute; left: 4.8rem; right: 49.2%; top: 70%; bottom: 64.75%; /* card / shadow */ box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.05); `; const NameText = styled.label` position: absolute; left: 3.2rem; top: 23.5rem; font-weight: bold; font-size: 1.6rem; line-height: 2.6rem; letter-spacing: 0.035em; /* main / menu text */ color: #b8b7e1; `; const RoleText = styled.label` position: absolute; left: 3.2rem; top: 33.8rem; font-weight: bold; font-size: 16px; line-height: 26px; letter-spacing: 0.035em; /* main / menu text */ color: #b8b7e1; `; const PendingText = styled.label` position: absolute; left: 0.675rem; font-weight: bold; font-size: 1rem; line-height: 1.6rem; text-align: center; color: #fddcdc; `; const DescriptionText = styled.p` position: absolute; left: 3.1rem; top: 44.1rem; font-weight: bold; font-size: 16px; line-height: 26px; letter-spacing: 0.035em; /* main / menu text */ color: #b8b7e1; `; const PendingContainer = styled.div` position: absolute; left: 10.7rem; top: 34.3rem; width: 5.3rem; height: 1.5rem; background: #ca6162; border-radius: 0.9rem; `; const SubmitChangeBtn = styled.button` position: absolute; left: 9.2rem; top: 56rem; width: 21.4rem; height: 4.7rem; bottom: 2rem; /* primary / button color */ background: #e05cb3; border-radius: 0.5rem; `; const SubmitChangeText = styled.p` position: absolute; left: 1.6rem; top: 1rem; font-weight: 500; font-size: 1.6rem; line-height: 2.6rem; text-align: center; letter-spacing: 0.035em; /* main / TEXT */ color: #e6e6e6; `; const ProfileEdit = props => { // user context const activeUser = useContext(UserContext); const userRole = activeUser.user_roles; const roleTitle = userRole ? userRole[userRole.length - 1].role : ""; // set user role if (!activeUser.roleTitle && roleTitle) { activeUser.setUser({ ...activeUser, roleTitle }); } const [profileData, setProfileData] = useState({}); const [showLoading, setShowLoading] = useState(true); const updateProfile = e => { setShowLoading(true); e.preventDefault(); const data = { display_name: profileData.display_name, bio: profileData.bio }; axiosWithAuth() .put("/profile", data) .then(res => { setShowLoading(false); activeUser.setUser({...activeUser,...res.data.user_profile}) }) .catch(err => { console.error(err); }); }; const onChange = e => { console.log('e',e.target.value) setProfileData({ ...profileData, [e.target.name]: e.target.value }); }; return ( <> {/* {showLoading && <LoadingSpinner role="status" />} */} <EditContainer className="edit-container" /> <ArrowVector> <Link to="/dashboard"> <Icon svg={leftArrow} height={0.9} width={1.5} /> </Link> </ArrowVector> <EditProfText>Edit Profile</EditProfText> <ImageContainer> <UserImage src={activeUser.avatar} /> <CameraVector> <Icon svg={editImage} height={1.9} width={1.9} /> </CameraVector> </ImageContainer> <form onSubmit={updateProfile}> <NameText>NAME</NameText> <Input className="display_name" id="display_name" name="display_name" position={"absolute"} top={26.1} left={3.2} height={5.2} width={31.1} placeholder={` ${activeUser.display_name}`} color={"rgba(204, 201, 255, 0.4)"} value={profileData.display_name} type="text" onChange={onChange} /> <RoleText>ROLE</RoleText> <PendingContainer> <PendingText>PENDING</PendingText> </PendingContainer> <Select className="role_title" name="bio" position={"absolute"} top={36.4} left={3.2} height={5.2} width={31.1} color={"rgba(204, 201, 255, 0.4)"} placeholder={` ${activeUser.roleTitle}`} > <option>{activeUser.roleTitle}</option> <option>Student</option> <option>Team Lead</option> <option>Section Lead</option> <option>Admin</option> </Select> <DescriptionText>Description</DescriptionText> <Input className="bio" name="bio" type="text" position={"absolute"} top={46.7} left={3.2} height={5.2} width={31.1} placeholder={` ${activeUser.bio}`} value={profileData.bio} onChange={onChange} /> <Button backgroundColor={"#E05CB3"} fontSize={1.6} letterSpacing={0.035} position={"absolute"} left={6.2} top={61.4} onSubmit={() => console.log(`form submitted`)} type="submit" > <Text text={`Submit changes to profile`} fontSize={1.6} letterSpacing={0.035} /> </Button> </form> </> ); }; export default ProfileEdit;
var showpic = document.getElementById("slideshowimgcontainer"); var accowords = document.getElementById("accowords"); var next = document.getElementById("go"); var back = document.getElementById("back"); var favshowlist=["izombie","sexed","janethevirgin","breakingbad","mrrobot","policestory","you"] var wheretheshowpicr = "favmovie" var i=0; var w=0; go.addEventListener("click",()=>{ if(i<favshowlist.length){ console.log(i) showpic.style.backgroundImage=`url(./${wheretheshowpicr}/${favshowlist[i]}.jpg)`; i++; console.log(i) } else if(i==favshowlist.length){ console.log("reset") i= 0; console.log(i) showpic.style.backgroundImage="url(./favmovie/lucifier.jpg)"; } }) back.addEventListener("click",()=>{ i--; console.log(i) if(i>=0){ showpic.style.backgroundImage=`url(./${wheretheshowpicr}/${favshowlist[i]}.jpg)`; console.log(i) console.log("change") } else if(i==0){ showpic.style.backgroundImage="url(./favmovie/lucifier.jpg)"; } else if(i<0){ i=favshowlist.length; console.log(i) showpic.style.backgroundImage="url(./favmovie/lucifier.jpg)"; } }) //srolldown var setting= document.getElementById("setting"); setting.addEventListener("click",()=>{ window.scrollTo({ top: 0, behavior: 'smooth' }); }) //portfolio var portfoliobox = document.getElementsByClassName("portfolio") var portfolioclick = document.getElementsByClassName("modalcontainer") var mask = document.getElementById("modalbackgrond"); var closebuu = document.getElementsByClassName("closebuttmodal"); console.log(portfoliobox) for(let i=0; i<portfoliobox.length; i++){ portfoliobox[i].addEventListener("mouseover",()=>{ console.log("jijji"); console.log(portfoliobox[i].firstChild.nextSibling.id) console.log(portfoliobox[i].lastChild.previousSibling) let mask = portfoliobox[i].lastChild.previousSibling; console.log(mask.textContent) console.log( mask.firstChild.textContent) mask.firstChild.textContent=portfoliobox[i].firstChild.nextSibling.id; mask.style.display="grid"; }) portfoliobox[i].addEventListener("mouseout",()=>{ let mask = portfoliobox[i].lastChild.previousSibling; mask.firstChild.textContent=portfoliobox[i].firstChild.nextSibling.id; mask.style.display="none"; }) portfoliobox[i].addEventListener("click",()=>{ document.body.classList.add("stop-scrolling"); portfolioclick[i].classList.add("active"); setting.style.display="none"; console.log(setting) setTimeout(function(){portfolioclick[i].classList.add("smaller") }, 40); mask.style.display="block"; closebuu[i].addEventListener("click",()=>{ portfolioclick[i].classList.remove("smaller") portfolioclick[i].classList.remove("active") mask.style.display="none"; document.body.classList.remove("stop-scrolling") setting.style.display="block"; console.log(setting) console.log("butt") }) }) } //intro var introaccor = document.getElementsByClassName("acco"); var intr = document.getElementsByClassName("intro"); for (let i=0 ; i<introaccor.length; i++){ intr[i].addEventListener("click",()=>{ if(introaccor[i].style.maxHeight){ introaccor[i].style.maxHeight =null; } else{ introaccor[i].style.maxHeight= introaccor[i].scrollHeight+"px" } }) }
import {Entity, PrimaryColumn,CreateDateColumn, Column, OneToMany, ManyToMany, JoinTable, ManyToOne} from "typeorm"; import {Content} from "./Content"; import {Client} from "./Client"; import {Provider} from "./Provider"; @Entity() export class Payment { @PrimaryColumn("varchar") orderId ; @Column ("double") amount; @Column ("varchar") currency; @CreateDateColumn () create_time; @Column("integer",{ nullable: true }) providerId; @ManyToOne(type => Content, content => content.payments) content; @ManyToOne(type => Client, client => client.payments) client; @ManyToOne(type => Provider, provider => provider.payments) provider; }
function deleteByEmail() { const input = document.querySelector('input[name="email"]'); const rows = Array.from(document.querySelector('tbody').children); let removed = false; for (let row of rows) { if (row.children[1].textContent == input.value) { row.remove(); removed = true; } } if (removed) { document.getElementById('result').textContent = 'Deleted.' } else { document.getElementById('result').textContent = 'Not found.' } }
$(function () { //edit the profile (username, picture) (email and password could be added in the future) $("#editProfileButton").on('click', function () { // CONSTANTS ----------------------------------- const editButton = $(this); const usernameField = $("#username"); const selectFile = $("#fileChooser"); // --------------------------------------------- if (editButton.text() === "Profil bearbeiten") { const usernameText = usernameField.text(); // change usernameField into an inputField const usernameInputField = "<input style='font-size: 25px; border: 2px black solid' name=\"new_username\" value=\"" + usernameText + "\">"; //hier nutze ich den style tag nur, weil er aus dem css sheet irgendwie nicht geladen wurde usernameField.html(usernameInputField); // display field to change profile-picture const selectFileButton = "<input style='font-size: 18px' id=\"file-upload\" type=\"file\" accept=\"image/jpeg\" />" selectFile.html(selectFileButton); $("#file-upload").on('change', function () { readURL(this); }); editButton.text("Speichern"); } else if (editButton.text() === "Speichern") { const newUsername = document.forms["userForm"]["new_username"].value; if (newUsername === "") { alert("Your Username should not be empty"); } else { editButton.text("Profil bearbeiten"); usernameField.html(newUsername); //updateUsernameInDatabaseAndSession(newUsername); selectFile.html(""); updateUsernameInDatabaseAndSession(newUsername); } } }); //function to upload pictures async function readURL(input) { if (input.files && input.files[0]) { const file = input.files[0]; const fileType = file['type']; const validImageTypes = ['image/jpeg']; if (!validImageTypes.includes(fileType)) { alert("you can only choose jpegs") } else { const reader = new FileReader(); reader.onload = async function (e) { await uploadProfilePictureIntoDB(e.target.result); $('#profile-picture').attr('src', e.target.result); } reader.readAsDataURL(file);//Actually change the picture } } } }); function setup() { setupButtonOnclicksAndInputs(); //Buttons funktional machen getUsernameFromDatabase(); getGesamtpunkteFromDatabase(); getHighscoreFromDatabase(); getMailFromDatabase(); getTierFromDatabase(); getProfilePicFromDatabase(); getFriendsData(); } function setupButtonOnclicksAndInputs() { document.getElementById("chatWithWhoButton").onclick = function () { //onclick für Chat mit Freund input (Wem willst du schreiben?) setupChatStuff(document.getElementById("chatWithWhoInput").value) }; document.getElementById("sendMessageButton").onclick = function () { //onclick für Chat sendMessage let currentDate = new Date(); sendMessage(document.getElementById("sendMessageInput").value, currentDate.getTime()); }; //Enter-Funktionalität document.getElementById("sendMessageInput").addEventListener("keyup", function (event) { // Number 13 is the "Enter" key on the keyboard if (event.code === 'Enter') { // Cancel the default action, if needed event.preventDefault(); // Trigger the button element with a click document.getElementById("sendMessageButton").click(); } }); //Enter-Funktionalität document.getElementById("chatWithWhoInput").addEventListener("keyup", function (event) { // Number 13 is the "Enter" key on the keyboard if (event.code === 'Enter') { // Cancel the default action, if needed event.preventDefault(); // Trigger the button element with a click document.getElementById("chatWithWhoButton").click(); } }); //Enter-Funktionalität document.getElementById("addFriendInput").addEventListener("keyup", function (event) { // Number 13 is the "Enter" key on the keyboard if (event.code === 'Enter') { // Cancel the default action, if needed event.preventDefault(); // Trigger the button element with a click document.getElementById("addFriendButton").click(); } }); } //TODO update username und profilepic zusammenlegen // Sends a request to update the username in the session function updateUsernameInDatabaseAndSession(newUsername) { fetch("/profile/updateUsername", { method: 'POST', body: JSON.stringify({username: newUsername}), headers: {'Content-Type': 'application/json'}, credentials: 'include' } ).then( result => result.text() ).then(data => { let msg = data.toString(); console.log(msg); } ); } async function uploadProfilePictureIntoDB(image) { fetch('/profile/uploadProfilePicture', { method: 'POST', body: JSON.stringify({img: image}), headers: {'Content-Type': 'application/json'}, credentials: 'include' } ).then( result => result.text() ) } // Reads username from Database and updates html function getUsernameFromDatabase() { $.get("/getUsername", function (data, status) { document.getElementById("username").textContent = data }).fail(function (data, status) { document.getElementById("username").textContent = "Default Name"; alert("Couldn't retrieve username from database"); }); } //TODO hier evtl "getMail" route nutzen function getMailFromDatabase() { $.get("/profile/getMail", function (data, status) { document.getElementById("mail").textContent = "Email: " + data }).fail(function (data, status) { document.getElementById("mail").textContent = "Default Mail"; alert("Couldn't retrieve mail from database"); }); } function getGesamtpunkteFromDatabase() { $.get("/profile/getTotalPoints", function (data, status) { document.getElementById("gesamtpunkte").textContent = "Gesamtpunkte: " + data }).fail(function (data, status) { document.getElementById("gesamtpunkte").textContent = "Default Gesamtpunkte"; alert("Couldn't retrieve gesamtpunkte from database"); }); } function getHighscoreFromDatabase() { $.get("/profile/getHighScore", function (data, status) { document.getElementById("highscore").textContent = "Highscore: " + data }).fail(function (data, status) { document.getElementById("highscore").textContent = "Default Highscore"; alert("Couldn't retrieve highscore from database"); }); } function getTierFromDatabase() { $.get("/profile/getTierName", function (data, status) { document.getElementById("tier").textContent = "Rang: " + data }).fail(function (data, status) { document.getElementById("highscore").textContent = "Default Tier"; alert("Couldn't retrieve tier from database"); }); } function getProfilePicFromDatabase() { $.get("/profile/getProfilePic", function (data, status) { if (data != null) { document.getElementById("profile-picture").setAttribute("src", data) } else document.getElementById("profile-picture").setAttribute("src", "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"); }).fail(function (data, status) { alert("Couldn't retrieve Profile Picture from database"); }); } //onclick-function von friend aus friendlist (functions_friendlist.js) function setupInformationFromFriend(elm) { if (document.getElementById("editProfileButton").innerText === "Speichern") { //gegen seltenen Bug: während dem Editieren des Profiles das Profil eines Freundes anschauen alert("Bitte erst Profil speichern!") } else if (!viewOnly) { //Funktion wird nur ausgeführt, wenn man auf dem eigenen Profil ist const name = elm.childNodes[1].innerHTML; //childnodes[1] gibt das "name" child von friend friendGetUsernameFromDatabase(name); friendGetGesamtpunkteFromDatabase(name); friendGetHighscoreFromDatabase(name); friendGetMailFromDatabase(name); friendGetTierFromDatabase(name); friendGetProfilePicFromDatabase(name); deleteOldFriendList(); //Liste wird gelöscht, damit nur neue angezeigt wird friendGetFriendsData(name); hideSensibleStuff(); document.getElementById("backToMyProfileButton").style.display = "block"; //Zurück Button visible document.getElementById("chat_heading").textContent = "Chat"; //Chat-Überschrift neutral machen viewOnly = true; //in functions_friendlist.js wird der Freundeslisten hoverEffect und onclick nicht mehr ausgeführt (diese Funktion auch nicht) } } function backToMyProfile() { deleteOldFriendList(); //FreundesListe wird gelöscht, damit nur die vom logged in user angezeigt werden setup(); showSensibleStuff(); viewOnly = false; } function hideSensibleStuff() { document.getElementById("editProfileButton").style.display = "none"; //Edit-Profile-Knopf hidden document.getElementById("addFriendInputLabel").style.display = "none"; //Freund hinzufügen Label hidden document.getElementById("addFriendInput").style.display = "none"; //Freund hinzufügen Searchbar hidden document.getElementById("addFriendButton").style.display = "none"; //Freund hinzufügen Button hidden //chatStuff hiden document.getElementById("chatWithWhoInputLabel").style.display = "none"; document.getElementById("chatWithWhoInput").style.display = "none"; document.getElementById("chatWithWhoButton").style.display = "none"; document.getElementById("sendMessageInput").style.display = "none"; document.getElementById("sendMessageButton").style.display = "none"; document.getElementById("chatMessages_div").style.display = "none"; //alles Messages hiden } function showSensibleStuff() { document.getElementById("editProfileButton").style.display = "block"; //Edit-Profile-Knopf zeigen document.getElementById("addFriendInputLabel").style.display = "inline"; //Freund hinzufügen Label zeigen document.getElementById("addFriendInput").style.display = "inline"; //Freund hinzufügen Searchbar zeigen document.getElementById("addFriendButton").style.display = "inline"; //Freund hinzufügen Button zeigen document.getElementById("backToMyProfileButton").style.display = "none"; //Zurück Button verstecken //chatStuff zeigen document.getElementById("chatWithWhoInputLabel").style.display = "inline"; document.getElementById("chatWithWhoInput").style.display = "inline"; document.getElementById("chatWithWhoButton").style.display = "inline"; if (chatPartner !== undefined) { document.getElementById("sendMessageInput").style.display = "inline"; document.getElementById("sendMessageButton").style.display = "inline"; document.getElementById("chat_heading").textContent = "Chat mit " + chatPartner.toString().toUpperCase(); //Überschrift mit Username2 } document.getElementById("chatMessages_div").style.display = "block"; //alles Messages zeigen } //löscht Freundesliste um nur Freundesliste des Freundes zu sehen function deleteOldFriendList() { const friendList = document.getElementsByClassName("friend-list"); for (let i = 0; i < friendList.length; i++) { friendList.item(i).remove(); } } function friendGetUsernameFromDatabase(username) { fetch("/friendGetUsername", { method: 'POST', body: JSON.stringify(username), headers: { "Content-Type": "application/json" }, credentials: 'include' }).then(result => result.text()) .then(result => document.getElementById("username").textContent = result) } function friendGetMailFromDatabase(username) { fetch("/profile/friendGetMail", { method: 'POST', body: JSON.stringify(username), headers: { "Content-Type": "application/json" }, credentials: 'include' }).then(result => result.text()) .then(result => document.getElementById("mail").textContent = "Email: " + result) } function friendGetGesamtpunkteFromDatabase(username) { fetch("/profile/friendGetTotalPoints", { method: 'POST', body: JSON.stringify(username), headers: { "Content-Type": "application/json" }, credentials: 'include' }).then(result => result.text()) .then(result => document.getElementById("gesamtpunkte").textContent = "Gesamtpunkte: " + result) } function friendGetHighscoreFromDatabase(username) { fetch("/profile/friendGetHighScore", { method: 'POST', body: JSON.stringify(username), headers: { "Content-Type": "application/json" }, credentials: 'include' }).then(result => result.text()) .then(result => document.getElementById("highscore").textContent = "Highscore: " + result) } function friendGetTierFromDatabase(username) { fetch("/profile/friendGetTierName", { method: 'POST', body: JSON.stringify(username), headers: { "Content-Type": "application/json" }, credentials: 'include' }).then(result => result.text()) .then(result => document.getElementById("tier").textContent = "Rang: " + result) } function friendGetProfilePicFromDatabase(username) { fetch("/profile/friendGetProfilePic", { method: 'POST', body: JSON.stringify(username), headers: { "Content-Type": "application/json" }, credentials: 'include' }).then(result => result.json()) .then(result => setFriendsProfilePic(result)) .catch((error) => { alert("Couldn't retrieve Profile Picture from database"); console.error('Error:', error); }); } function setFriendsProfilePic(result) { if (result != null) { document.getElementById("profile-picture").setAttribute("src", result) } else document.getElementById("profile-picture").setAttribute("src", "https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png"); }
import React, { Fragment } from 'react' import { Grid, Checkbox, TextField, Button } from '@material-ui/core'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import { withStyles } from '@material-ui/core/styles'; import Radio from '@material-ui/core/Radio'; import RadioGroup from '@material-ui/core/RadioGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import { appService } from '../App/app.services'; import {connect} from 'react-redux' const styles = theme => ({ root: { width: '100%', marginTop: theme.spacing(3), overflowX: 'auto', }, table: { minWidth: 700, }, textField: { marginLeft: 24 }, formControl: { marginLeft: 24 } }); class ScanTab extends React.Component { state = { selectedTrackers: [], scanSelection: 'PAN ID', scanParameter: this.props.PANID } selectAll = () => { if(this.state.selectedTrackers.length === this.props.xbeeResponse.length) { this.setState({ selectedTrackers: [] }) } else { this.setState({ selectedTrackers: [...this.props.xbeeResponse] }) } } selectRow = (row) => { if(this.state.selectedTrackers.indexOf(row) === -1) { this.setState({ selectedTrackers: [...this.state.selectedTrackers, row] }) } else { this.setState({ selectedTrackers: [...this.state.selectedTrackers.filter(t => t.id !== row.id)] }) } } handleChange = (e) => { if(e.target.value === 'PAN ID') { this.setState({ scanSelection: e.target.value, scanParameter: this.props.PANID }) } else { this.setState({ scanSelection: e.target.value, scanParameter: '' }) } } inputChange = (e) =>{ this.setState({ scanParameter: e.target.value }) } scan = () => { if(this.state.scanSelection === 'PAN ID') { this.props.discover('00000') } else { this.props.discover(this.state.scanParameter) } } addTrackers = () => { this.props.addTrackers(this.state.selectedTrackers) } render() { const { classes, xbeeResponse } = this.props return ( <Fragment> <Grid container direction='column'> <Grid item> <FormControl component="fieldset" className={classes.formControl}> <RadioGroup row aria-label="Scan" name="scan" value={this.state.scanSelection} onChange={this.handleChange} > <FormControlLabel value="PAN ID" control={<Radio color='primary'/>} label="PAN ID" /> <FormControlLabel value="Device ID" control={<Radio color='primary'/>} label="Device ID" /> </RadioGroup> </FormControl> </Grid> <Grid item style={{marginBottom: 24}}> { this.state.scanSelection === 'PAN ID' ? <TextField id="scanParameter" className={classes.textField} value={this.state.scanParameter} onChange={this.inputChange} disabled={this.state.scanSelection === 'PAN ID'} margin="none" variant='outlined' /> : <TextField id="scanParameter" className={classes.textField} value={this.state.scanParameter} onChange={this.inputChange} placeholder='Device ID' margin="none" variant='outlined' /> } <Button color='primary' onClick={() => this.scan()} variant='contained' style={{marginLeft: 24, verticalAlign: 'bottom'}}>Scan</Button> </Grid> {xbeeResponse.length !== 0 && xbeeResponse !== undefined && <Grid item style={{textAlign: 'end', padding: 10, fontSize: 15}}> Selected Trackers: {this.state.selectedTrackers.length} </Grid>} {xbeeResponse.length !== 0 && xbeeResponse !== undefined && <Grid item> <Table className={classes.table}> <TableHead> <TableRow> <TableCell onClick={() => this.selectAll()} style={{cursor: 'pointer'}} > {xbeeResponse.length > 1 && xbeeResponse !== undefined && <Checkbox checked={this.state.selectedTrackers.length === xbeeResponse.length && this.state.selectedTrackers.length !== 0} color='primary' />} </TableCell> <TableCell >Row #</TableCell> <TableCell >Device ID</TableCell> <TableCell >Mac ID</TableCell> </TableRow> </TableHead> <TableBody> {xbeeResponse.length !== 0 && xbeeResponse !== undefined && xbeeResponse.map(res => { return ( <TableRow key={res.macID} onClick={() => this.selectRow(res)} style={{cursor: 'pointer'}} > <TableCell> <Checkbox checked={this.state.selectedTrackers.indexOf(res) !== -1} color='primary' /> </TableCell> <TableCell >{res.VALUES.split(',')[0]}</TableCell> <TableCell >{res.DID}</TableCell> <TableCell >{res.macID}</TableCell> </TableRow> )})} </TableBody> </Table> </Grid>}{xbeeResponse.length !== 0 && xbeeResponse !== undefined && <Grid item style={{textAlign: 'end'}}> <Button color='primary' disabled={this.state.selectedTrackers.length === 0} onClick={() => this.addTrackers()} variant='contained' style={{margin: 10}}>Add</Button> </Grid>} </Grid> </Fragment> ) } } function mapStateToProps(state) { const { xbeeResponse, PANID } = state.app return { xbeeResponse, PANID } } const mapDispatchToProps = (dispatch) => ({ discover : (did) => { dispatch({type: 'DISCOVER_REQUEST'}) appService.discover(did) .then(json => { dispatch({type: 'DISCOVER_SUCCESS'}) }, error => { dispatch({type: 'DISCOVER_FAILURE'}) }) }, addTrackers: (devices) => { dispatch({type: 'ADD_TRACKERS_REQUEST'}) appService.addTrackers(devices) .then(json => { dispatch({type: 'ADD_TRACKERS_SUCCESS', devices}) dispatch({type: 'GET_COMMISSIONING_DATA_REQUEST'}) appService.getCommissioningData() .then(json => { dispatch({type: 'GET_COMMISSIONING_DATA_SUCCESS', json}) }, error => { dispatch({type: 'GET_COMMISSIONING_DATA_FAILURE', error}) }) }, error => { dispatch({type: 'ADD_TRACKERS_FAILURE'}) }) } }) const connectedScanTab = connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ScanTab)) export {connectedScanTab as ScanTab}
import React, { Component } from 'react'; import Meteor, { createContainer } from 'react-native-meteor'; import { StyleSheet, Text, View, ScrollView, Dimensions, Image, TouchableWithoutFeedback, Linking, TextInput, ToastAndroid, } from 'react-native'; class LinkScreen extends Component { constructor(props){ super(props); this.state = {search: ''}; } static navigationOptions = { title: 'Links', heder:true, tabBarIcon: ({ tintColor }) => ( <Image source={require('../images/ic_near_me_white_24dp_1x.png')} style={{tintColor: tintColor}} /> ), }; handleLinking(url){ try { Linking.openURL(url).catch(err => console.error('An error occurred', err)); } catch (e) { ToastAndroid.show('Link is Not Available', ToastAndroid.SHORT); } } render() { const { navigate } = this.props.navigation; var {height, width} = Dimensions.get('window'); let searchlinks = this.props.links.filter((link)=>{ return(link.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !==-1) }) return ( <ScrollView style={styles.container}> <View style={{padding: 10}}> <TextInput style={{height: 40,borderWidth:1,borderRadius:5,zIndex:2,shadowOffset:{ width: 10, height: 10, },shadowColor: 'black',shadowOpacity: 1.0,backgroundColor:'#F5FCFF',color:'black'}} placeholder="Search Latest Movies To Download..." onChangeText={(search) => this.setState({search})} underlineColorAndroid="transparent" /> </View> {this.props.todosReady ? <Text>Wait</Text> : <View style={{display:'flex',flexDirection:'column',flex:1,marginTop:10,justifyContent:'center'}}> { searchlinks.length == 0 ? null : <View> { searchlinks.map((link,i)=>{ let timesplit =link.length.split('.') return( <View key={i} style={styles.cardContainer}> <View style={{display:'flex',width:width/4.5}}> <TouchableWithoutFeedback onPress={this.handleLinking.bind(this,link.dlink)}> <Image source={link.image == '' ? require('../images/noi.jpg') : {uri:link.image}} style={{width:80,height:80,borderRadius:50}} /> </TouchableWithoutFeedback> </View> <View style={{display:'flex'}}> <Text style={{paddingLeft:5,fontSize:15,color:'blue'}} onPress={this.handleLinking.bind(this,link.dlink)}>{link.name}</Text> <Text style={{paddingLeft:5,fontSize:13,color:'green'}}>Category: {link.category}</Text> <Text style={{paddingLeft:5,fontSize:13,color:'black'}}>length: {`${timesplit[0] ? timesplit[0] : null } : ${timesplit[1] ? timesplit[1] : null} : ${timesplit[2] ? timesplit[2] : null}`} Hrs.</Text> <Text style={{paddingLeft:5,fontSize:13,color:'black'}}>IMDB: {link.rating} </Text> <Text style={{paddingLeft:5,fontSize:13,color:'black'}}>Size: {link.size+' '+link.sizein}</Text> </View> </View> ) }) } </View> } </View> } </ScrollView> ); } } export default createContainer(params=>{ const handle = Meteor.subscribe('link'); return { todosReady: !handle.ready(), links: Meteor.collection('link').find(), }; }, LinkScreen) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, cardContainer:{ display:'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', margin: 5, padding:1, backgroundColor: "#fff", borderRadius: 2, shadowColor: "#000000", shadowOpacity: 0.7, shadowRadius: 1, shadowOffset: { height: 1, width: 0.3, }, }, })
var fs = require("fs"), fileSizeInBytes = fs.statSync("input.txt")["size"]; console.log(fileSizeInBytes);
/** * Test for BrowserContext#getCompilationUnits() and #getCompilationUnit(url) * Also tests CompilationUnit#getURL() and CompilationUnit#getBrowserContext() * * A HTML file with two scripts (one internal, one external). */ function runTest() { var browser = new FW.Firebug.BTI.Browser(); // TODO var url = FBTest.getHTTPURLBase()+"bti/browsercontext/testScripts.html"; browser.addEventListener("onContextCreated", function(context) { FBTest.progress("getCompilationUnits, context created"); FBTest.compare(context.getURL(), url, "URL of newly created context should be " +url); FBTest.progress("getCompilationUnits, retrieving compilation units"); context.getCompilationUnits(function(units) { FBTest.progress("getCompilationUnits, compilation units retrieved"); FBTest.compare(2, units.length, "Should be two compilation units"); var unit = context.getCompilationUnit(url); FBTest.ok(unit, "compilation unit does not exist: " + url); FBTest.compare(url, unit.getURL(), "compilation unit URL is not consistent"); FBTest.ok(unit.getBrowserContext() == context, "compilation unit browser context is " + "not consistent"); var other = FBTest.getHTTPURLBase()+"bti/browsercontext/simpleExternal.js"; unit = context.getCompilationUnit(other); FBTest.ok(unit, "compilation unit does not exist:" + other); FBTest.compare(other, unit.getURL(), "compilation unit URL is not consistent"); FBTest.ok(unit.getBrowserContext() == context, "compilation unit browser context is " + "not consistent"); FBTest.testDone(); }); }); FBTest.progress("getCompilationUnits, open test page "+url); FBTest.openNewTab(url, function(win) { FBTest.progress("getCompilationUnits, new tab opened "+url); }); }
//install serviceworker var cacheName = "restaurantV1" self.addEventListener('install', event => { event.waitUntil( caches.open(cacheName).then(cache => { return cache .addAll( [ 'index.html', 'restaurant.html', '/css/syles.css', '/data/restaurants.json', 'img/inf.png', '/js/', '/js/dbhelper.js', '/js/main.js', '/js/restaurant_info.js', '/js/serviceworker.js' ] ); }) ); }); //fetch cache as needed self.addEventListener("fetch", event => { //cache main restaurant page if (event.request.url.indexOf("restaurant.html") > -1) { event.request = new Request(restaurant.html); } //check head/get/post or simple headers if (URL(event.request.url).hostname !== "localhost") { event.request.mode = "no-cors"; } event.respondWith( caches.match(event.request).then(response => { return ( response || fetch(event.request) .then(fetchResponse => { //cache other pages return caches.open(cacheName).then(cache => { cache.put(event.request, fetchResponse.clone()); return fetchResponse; }); }) .catch(error => { //display image not found if (event.request.url.indexOf(".jpg") > -1) { return caches.match("/img/inf.png"); } //internet connection or "internet is down" return new Response("Check internet connection", { status: 404, statusText: "Check internet connection" }); }) ); }) ); });
const gulp = require("gulp"); const notify = require("gulp-notify"); const plumber = require("gulp-plumber"); const sass = require("gulp-sass"); const autoprefixer = require("gulp-autoprefixer"); const pug = require("gulp-pug"); const browserSync = require("browser-sync"); const styleguide = require('sc5-styleguide'); const outputPath = 'output'; //setting : paths const paths = { "scss": "./src/scss/", "css": "./dist/css/", "pug": "./src/pug/", "html": "./dist/", "js": "./dist/js/" } //setting : Sass Options const sassOptions = { //outputStyle: "expanded" outputStyle: "compact" //outputStyle: "compressed" } //setting : Pug sassOptions const pugOptions = { pretty: true } gulp.task('styleguide:generate', function() { return gulp.src('src/scss/**/*.scss') .pipe(styleguide.generate({ title: 'My Styleguide', server: true, port: 4000, rootPath: outputPath, overviewPath: 'src/scss/overview.md' })) .pipe(gulp.dest(outputPath)); }); gulp.task('styleguide:applystyles', function() { return gulp.src('src/scss/style.scss') .pipe(sass({ errLogToConsole: true })) .pipe(styleguide.applyStyles()) .pipe(gulp.dest(outputPath)); }); gulp.task('watch', ['styleguide'], function() { // Start watching changes and update styleguide whenever changes are detected // Styleguide automatically detects existing server instance gulp.watch(['src/scss/**/*.scss'], ['styleguide']); }); gulp.task('styleguide', ['styleguide:generate', 'styleguide:applystyles']); gulp.task('default', ['styleguide:generate', 'styleguide:applystyles']);
// set the dimensions and margins of the graph const margin = {top: 30, right: 30, bottom: 70, left: 60} const width = 460 - margin.left - margin.right const height = 400 - margin.top - margin.bottom // unfortunate global variables. Should never leave this file // DON'T IMPORT THIS FILE AS A SCRIPT TAG ANYWHERE // WILL CAUSE NAMESPACE CLASH let svg; let data; const x = d3.scaleBand() .range([ 0, width ]) .padding(1); const y = d3.scaleLinear() .range([height, 0]) // slightly annoying global variables // if someone smarter than me could think of a solution would be nice let xAxis; let yAxis; export const init = (selector, in_data) => { svg = d3.select(selector) .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") xAxis = svg.append("g") .attr("transform", "translate(0," + height + ")") yAxis = svg.append("g") .attr("class", "myYaxis") data = in_data setup_events("lol-button") render("Total_Increment") // could be more generic. Relies on specific heading names } const setup_events = (class_name) => { const buttons = document.getElementsByClassName(class_name) // grabs all elements with the class name // adds an onclick event to render correctly // bases onclick parameter on button id Array.from(buttons).forEach(button => { console.log(button) button.addEventListener("click", () => render(button.id)) }); } // A function that create / update the plot for a given variable: const render = (selectedVar) => { // Update axes x.domain(data.map(d => d.Species)) y.domain([0, d3.max(data, d => d[selectedVar] ) ]) xAxis.transition().duration(1000).call(d3.axisBottom(x)) yAxis.transition().duration(1000).call(d3.axisLeft(y)) const lines = svg.selectAll(".line") .data(data) lines.enter() .append("line") .attr("class", "line") .merge(lines) .transition() .duration(1000) .attr("x1", d => x(d.Species) ) .attr("x2", d => x(d.Species) ) .attr("y1", y(0)) .attr("y2", d => y(d[selectedVar])) .attr("stroke", "grey") // variable ball: map data to circle const ball = svg.selectAll("circle") .data(data) ball.enter() .append("circle") .merge(ball) .transition() .duration(1000) .attr("cx", d => x(d.Species) ) .attr("cy", d => y(d[selectedVar]) ) .attr("r", 8) .attr("fill", "#69b3a2"); }
import { Component } from 'react'; import Layout from '../../components/navigation'; const baseURL = 'http://localhost:5000/cards?name='; class Practice extends Component { state = { cardsName: '', flashCardList: [], prompts: [], targets: [], length: 0, currentStep: 0, playButton: true, playCards: false, wrongAnswer: false, answer: '', finished: false }; static getInitialProps({query}){ return {query}; }; componentDidMount(){ const name = this.props.query.flashCardName; this.setState({cardsName: name}); const url = baseURL + name; console.log('url is: ', url); console.log('name is: ', name); fetch(url,{method: "GET"}) .then(res => res.json()) .then(data => { this.setState({flashCardList:data[0].cards,playButton:true}) console.log('all data: ',data); console.log('name: ',data[0].name); console.log('cards: ',data[0].cards) }); }; startMemoryGame = () => { console.log('playing now'); var prompts = []; var targets = []; this.state.flashCardList.forEach((item,index) => { prompts[index] = item.prompt; targets[index] = item.target; }) this.setState({play:true,playButton:false,prompts:prompts,targets:targets,length:prompts.length}); }; renderListOfFlashCards(){ const nameList = this.state.flashCardList.map((item,index) => { //list out key values return <li key={index}>{item.prompt} {item.target}</li>; }); return( <div> <ul> {nameList} </ul> <button onClick={this.startMemoryGame}>Start Playing</button> </div> ); }; onSubmit = (event) => { event.preventDefault(); if(this.state.answer === this.state.targets[this.state.currentStep]){ console.log('Correct!'); var step = this.state.currentStep + 1; console.log('current step is: ',step); console.log('promts.length is: ', this.state.prompts.length); this.setState({wrongAnswer: false, currentStep: step}); if(step == this.state.prompts.length){ console.log('finished'); this.setState({play: false, finished: true}); } } else { console.log('Try again!'); this.setState({wrongAnswer: true}); } }; tryAgain(){ return( <h4>Wrong answer! Try Again!</h4> ); }; renderMemoryGame(){ return( <div> <h5>{this.state.prompts[this.state.currentStep]}</h5> {this.state.wrongAnswer && this.tryAgain()} <form onSubmit={this.onSubmit}> <input type="text" onChange={event => this.setState({answer: event.target.value})}/> <button type="submit">Enter</button> </form> </div> ); }; renderFinish(){ return( <h4>Finished! Good Work!</h4> ); }; render(){ return( <Layout> <h1>Flash Card Practice</h1> {this.state.playButton && this.renderListOfFlashCards()} {this.state.play && this.renderMemoryGame()} {this.state.finished && this.renderFinish()} </Layout> ); }; } export default Practice;
let mongoose = require('mongoose'); let ManagerSchema = require('../schemas/ManagerSchema'); let Manager = mongoose.model('manager',ManagerSchema); module.exports = Manager;
import React from 'react'; import { Avatar } from '@material-ui/core'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import './SidebarMessage.scss'; function SidebarMessage() { return ( <div className="sidebarMessage"> <Avatar src={`${process.env.PUBLIC_URL}/images/avatar.png`}/> <div className="sidebarMessage__message"> <h3>Ayar Hlaine</h3> <p>What?</p> </div> <div className="sidebarMessage__time"> <p>8/15/2020</p> <ExpandMoreIcon className="sidebarMessage__expand"/> </div> </div> ) } export default SidebarMessage
PaulSantoroWebsite.controller("experience-controller", ["$scope", "$window", function ExperienceController($scope, $window) { $scope.windowWidth = 0; $scope.projectImageView = []; // Images in the carousel $scope.experience = []; // Initializes the page. function initialize() { // Initialize the experience. $scope.experience = [ { title: "3D Modeling", description: "Blender has been my go to program for creating 3D models for the past few years. Blender has extensive functions for modeling, sculpting, texture painting, texture baking, material creation, rigging and animating, and rendering. I've used Blender to create all sorts of assets including characters, props, and textures.", imagesInCarousel: [ { source: "Experience/3DModelingImgs/3dmodeling_img1.png", altText: "3D Modeling Image 1", isVideo: false }, { source: "Experience/3DModelingImgs/3dmodeling_img2.png", altText: "3D Modeling Image 2", isVideo: false }, { source: "Experience/3DModelingImgs/3dmodeling_img3.png", altText: "3D Modeling Image 3", isVideo: false }, { source: "Experience/3DModelingImgs/3dmodeling_img4.png", altText: "3D Modeling Image 4", isVideo: false }, { source: "Experience/3DModelingImgs/3dmodeling_img5.png", altText: "3D Modeling Image 5", isVideo: false }, { source: "Experience/3DModelingImgs/3dmodeling_img6.png", altText: "3D Modeling Image 6", isVideo: false } ] }, { title: "Material Creation", description: "The main two programs I use when creating materials for 3D assets are Adobe Photoshop and Substance Painter. I use 3D meshes I create in Blender to generate normal, ambient occlusion, and curvature maps to assist in making materials. I've created multiple textures using Photoshop and used those textures as resources when making materials in Substance Painter.", imagesInCarousel: [ { source: "Experience/MaterialCreationImgs/materialcreation_img1.png", altText: "Material Creation Image 1", isVideo: false }, { source: "Experience/MaterialCreationImgs/materialcreation_img2.png", altText: "Material Creation Image 2", isVideo: false }, { source: "Experience/MaterialCreationImgs/materialcreation_img3.png", altText: "Material Creation Image 3", isVideo: false }, { source: "Experience/MaterialCreationImgs/materialcreation_img4.png", altText: "Material Creation Image 4", isVideo: false }, { source: "Experience/MaterialCreationImgs/materialcreation_img5.png", altText: "Material Creation Image 5", isVideo: false }, { source: "Experience/MaterialCreationImgs/materialcreation_img6.png", altText: "Material Creation Image 6", isVideo: false } ] }, { title: "Illustration", description: "I currently use Wacom drawing tablets to create illustrations in both Adobe Photoshop and Adobe Illustrator. I've created multiple illustrations including character designs, environment designs, wallpapers, references for 3D assets and more.", imagesInCarousel: [ { source: "Experience/IllustrationImgs/illustration_img1.png", altText: "Illustration Image 1", isVideo: false }, { source: "Experience/IllustrationImgs/illustration_img2.png", altText: "Illustration Image 2", isVideo: false }, { source: "Experience/IllustrationImgs/illustration_img3.png", altText: "Illustration Image 3", isVideo: false }, { source: "Experience/IllustrationImgs/illustration_img4.png", altText: "Illustration Image 4", isVideo: false }, { source: "Experience/IllustrationImgs/illustration_img5.png", altText: "Illustration Image 5", isVideo: false } ] }, ]; // Initialize the thumbnail images from the carousel images (max 6) for (let i = 0; i < $scope.experience.length; i++) { $scope.experience[i].firstThreeImagesInCarousel = []; for (let j = 0; j < Math.min($scope.experience[i].imagesInCarousel.length, 6); j++) { $scope.experience[i].firstThreeImagesInCarousel.push($scope.experience[i].imagesInCarousel[j]); } } // Threshold for project column reorganization. $scope.oneColumnMaxWidth = 940; $scope.onWindowResize(); } function isVideo(fileName) { if (fileName.endsWith(".mp4")) return true; else return false; } function onCarouselItemChanged(lastItemIndex) { let projectImage = $scope.projectImageView[lastItemIndex]; // console.log("Active Image Index == ", lastItemIndex); if (projectImage.isVideo) { // Stop the video. if (!projectImage.element) { projectImage.element = $("#" + projectImage.id)[0]; } projectImage.element.pause(); projectImage.element.currentTime = 0; } } function setColumnView(targetColumns) { if (targetColumns === 1) { setOneColumnView(); } else if (targetColumns === 2) { setTwoColumnView(); } } // Sets the page view to show one column. The project images are on the top and the description / images are on the bottom. function setOneColumnView() { console.log("Set one column view called"); $scope.isTwoColumns = false; } // Sets the page view to show two columns, where the left column has the project thumbnail and the right column has the project info. function setTwoColumnView() { console.log("Set two column view called"); $scope.isTwoColumns = true; } $scope.closeImageCarousel = function () { $scope.isImageCarouselOpen = false; }; // Initialize the carousel. $scope.onClickExperienceImage = function (experienceItem, imageIndex) { console.log("Called 'onClickExperienceImage'"); // Make it so that the images can be viewed. Don't modify this part of the code. $scope.projectImageView = []; for (let i = 0; i < experienceItem.imagesInCarousel.length; i++) { $scope.projectImageView.push({ alt: "Slide " + i, carouselIndicatorClass: i === imageIndex ? "active" : "", carouselInnerClass: i === imageIndex ? "carousel-item active" : "carousel-item", id: "carouselItem" + i, index: i, isVideo: isVideo(experienceItem.imagesInCarousel[i].source), src: experienceItem.imagesInCarousel[i].source }); } $scope.isImageCarouselOpen = true; }; // Redirect. $scope.onClickNavigationButton = function (href) { $window.location.href = href; }; // On resizing the window, determines how page data will be displayed. $scope.onWindowResize = function () { let previousWidth = $scope.windowWidth; let newWidth = $window.innerWidth; $scope.windowWidth = newWidth; // One-column view if (newWidth <= $scope.oneColumnMaxWidth && (previousWidth === 0 || previousWidth > $scope.oneColumnMaxWidth)) { // Shrinking the window or initialization setColumnView(1); return; } // Two-column view if ((newWidth > $scope.oneColumnMaxWidth && previousWidth <= $scope.oneColumnMaxWidth && previousWidth !== 0) // Growing the window || (newWidth > $scope.oneColumnMaxWidth && previousWidth === 0)) { // Initialization setColumnView(2); return; } }; // Calls the onWindowResize function and digests the $scope. This is necessary // to ensure the page is updated correctly when the window is resized manually // by the user. $scope.onWindowResizeDigest = function () { $scope.onWindowResize(); $scope.$digest(); }; // Unbind the window resize function from the $window. function cleanUp() { angular.element($window).off('resize', $scope.onWindowResizeDigest); } // Bind the window resize function to the $window. angular.element($window).on('resize', $scope.onWindowResizeDigest); // Clean up the page. $scope.$on('$destroy', cleanUp); // Handle changing the carousel images. $("#carouselProjectImages").bind("slide.bs.carousel", function (e) { //console.log("Slide Event Args == ", e); onCarouselItemChanged(e.from); }); // Initialize the page. This should only be done once all other functions have been declared. initialize(); }]);
$(document).ready(function(){ $("#add").click(function(){ $(this).css("background","red") $(this).val("!added") }) })
const defaultStateReading = [ { id: 0, showCheck: false, checked: false, answer: "", showTextExplain1: false, showTextExplain2: false } ]; const arrWordsReducer = (state = defaultStateReading, action) => { if (action.type === 'CLICK_CHECK') { return state.map(e => { if (e.id !== action.id) return e; return { ...e, showCheck: false, checked: true }; }); }; if (action.type === 'CLICK_CHOOSE') { return state.map(e => { if (e.id !== action.id) return e; return { ...e, showCheck: true, answer: action.choose }; }); }; if (action.type === 'CLICK_SHOW_ANSWER') { return state.map(e => { if (e.id !== action.id) return e; return { ...e, showTextExplain1: !e.showTextExplain1, showTextExplain2: false }; }); }; if (action.type === 'CLICK_TIPS') { return state.map(e => { if (e.id !== action.id) return e; return { ...e, showTextExplain1: false, showTextExplain2: !e.showTextExplain2 }; }); }; if (action.type === 'NEXT') { return state.concat([{ id: state.length, showCheck: false, checked: false, answer: "", showTextExplain1: false, showTextExplain2: false }]); } return state; }; export default arrWordsReducer;
var isy = require('./isy'); var pinger = require('./pinger'); var config = require('./devicelist.json'); var houseconfig = require('../houseconfig.json'); var isyConnection = new isy.ISY(houseconfig.isy.address, houseconfig.isy.username, houseconfig.isy.password); function reportdeviceState(targetInfo, found) { if(targetInfo.isyVariableId == 0) { return; } else { var valueToSet = 0; if (found == true) { valueToSet = 1; } isyConnection.setVariable(targetInfo.isyVariableId, valueToSet); } } var pingService = new pinger.Pinger(config, reportdeviceState, 30000, 3, 1500); pingService.start();
import React from 'react'; import ReactPlayer from "react-player"; import './VideoComponent.page.css' export default function VideoComponent({videoUrl, imageUrl}){ return( <div className="videoC" style={{backgroundImage:`url(${imageUrl})`}}> <div className="videoContainer"> <ReactPlayer url={videoUrl} /> </div> </div> ) }
define('/static/script/lib/plugin/ui/calender', [ ], function(require, exports, module) { function addEvent(obj,sEv,fn) { if(obj.attachEvent) { obj.attachEvent('on'+sEv,function(ev){ var oEvent=ev||event; if(fn.call(obj,oEvent)==false) { oEvent.cancelBubble=true; return false; } }); } else { obj.addEventListener(sEv,function(ev){ var oEvent=ev||event; if(fn.call(this,oEvent)==false) { oEvent.cancelBubble=true; oEvent.preventDefault(); } },false) } } function getXY(obj) { var x=0; var y=0; while(obj) { x+=obj.offsetLeft; y+=obj.offsetTop; obj=obj.offsetParent; } return {left:x,top:y}; } function setStyle(obj,json) { for (var i in json) { obj.style[i]=json[i]; } } function calendar(abj,index,fnSuc) { var num=abj.length; var added=false; if(!index)index=0; for (var i=0;i<num;i++) { _calendar(abj[i],index,fnSuc[i]); } function _calendar(obj,index,fnDo) { init(); var oNewDiv=document.createElement('div'); var left=obj.offsetLeft; var top=obj.offsetTop+obj.offsetHeight+5; oNewDiv.className='calenderWrap'; setStyle(oNewDiv,{position:'absolute',left:left+'px',top:top+'px',display:'none',zIndex:index}); oNewDiv.innerHTML= '<div class="calenderHead">'+ '<div class="calendar_month_left_btn"><a href="javascript:void(0)" class="left_btn"></a></div>'+ '<div class="calendar_month_head_content">6</div>'+ '<div>月</div>'+ '<div class="calendar_month_right_btn"><a href="javascript:void(0)" class="right_btn"></a></div>'+ '<div class="calendar_year_left_btn" style="margin-left:32px"><a href="javascript:void(0)" class="left_btn"></a></div>'+ '<div class="calendar_year_head_content">2012</div>'+ '<div>年</div>'+ '<div class="calendar_year_right_btn"><a href="javascript:void(0)" class="right_btn"></a></div>'+ '</div>'+ '<div class="calendar_week">'+ '<ul>'+ '<li>日</li>'+ '<li>一</li>'+ '<li>二</li>'+ '<li>三</li>'+ '<li>四</li>'+ '<li>五</li>'+ '<li>六</li>'+ '</ul>'+ '</div>'+ '<div class="calendar_content">'+ '<ul></ul>'+ '</div>'; var oMonth_l=oNewDiv.children[0].children[0]; var oMonth_r=oNewDiv.children[0].children[3]; var oYear_l=oNewDiv.children[0].children[4]; var oYear_r=oNewDiv.children[0].children[7]; var oMonth=oNewDiv.children[0].children[1]; var oYear=oNewDiv.children[0].children[5]; var oUl=oNewDiv.children[2].children[0]; var iNow=0; addEvent(obj,'click',function(){ if(oNewDiv.style.display=='none') { oNewDiv.style.display='block'; } else { oNewDiv.style.display='none'; } return false; }); addEvent(document,'click',function(){ oNewDiv.style.display='none'; }); refresh(iNow); addEvent(oMonth_l,'click',function(){ iNow--; refresh(iNow); return false; }); addEvent(oMonth_r,'click',function(){ iNow++; refresh(iNow); return false; }); addEvent(oYear_l,'click',function(){ iNow-=12; refresh(iNow); return false; }); addEvent(oYear_r,'click',function(){ iNow+=12; refresh(iNow); return false; }); function init() { obj.parentNode.style.position='relative'; } function refresh(iNow) { oUl.innerHTML=''; var num_day=howDays(); var num_blank=getFisrtDay(); var month=getNow().month; var year=getNow().year; oMonth.innerHTML=month; oYear.innerHTML=year; for (var i=0;i<num_blank;i++) { var oLi=document.createElement('li'); oLi.style.cursor='default'; oUl.appendChild(oLi); } for (var i=0;i<num_day;i++) { var oLi=document.createElement('li'); oLi.innerHTML=(i+1); oLi.onclick=function(ev) { var oEvent=ev||event; obj.value=year+'-'+month+'-'+this.innerHTML; oNewDiv.style.display='none'; fnDo&&fnDo(); oEvent.cancelBubble=true; }; oUl.appendChild(oLi); } while(oUl.children.length<42) { var oLi=document.createElement('li'); oLi.style.cursor='default'; oUl.appendChild(oLi); } function howDays() { var oDate=new Date(); oDate.setMonth(oDate.getMonth()+iNow+1); oDate.setDate(0); return oDate.getDate(); } function getFisrtDay() { var oDate=new Date(); oDate.setMonth(oDate.getMonth()+iNow); oDate.setDate(1); return oDate.getDay(); } function getNow() { var oDate=new Date(); oDate.setMonth(oDate.getMonth()+iNow); return {month:oDate.getMonth()+1,year:oDate.getFullYear()} } } if(!added) { var oHead=document.getElementsByTagName('head')[0]; var oLink=document.createElement('link'); oLink.rel='stylesheet'; oLink.type='text/css'; oLink.href='/static/css/lib/ui/plugin/calender.css'; oHead.appendChild(oLink); added=true; } obj.parentNode.appendChild(oNewDiv); } } return calendar; });
import React from "react" import { css } from "@emotion/core" export default ({ t, title }) => { return ( <h1 css={css` color: #000000; text-align: center; font-size: 36px; font-weight: 500; margin-top: 150px; @media (max-width: 1243px) { font-size: 24px; margin-top: 50px; } `} > {title} </h1> ) }
import { StyleSheet, Platform } from 'react-native'; import { Colors, Typography } from '@config/index'; const styles = StyleSheet.create({ container: { flexDirection: 'row', justifyContent: 'space-between', marginVertical: 4, backgroundColor: Colors.border, paddingVertical: 7, paddingHorizontal: 20, }, title: { flex: 1, borderColor: Colors.border, borderWidth: 0.5, height: 36, marginRight: 20, backgroundColor: Colors.background, borderRadius: 7, paddingLeft: 10, color: Colors.ColorBody, paddingBottom: Platform.OS === 'android' ? 9 : 0, }, box: { flexDirection: 'row', alignItems: 'center', }, boxBtn: (edit) => ({ borderColor: Colors.border, borderWidth: 0.5, height: 36, width: 30, justifyContent: 'center', alignItems: 'center', paddingTop: 3, backgroundColor: edit ? Colors.background : Colors.textColor, }), input: { width: 55, height: 36, fontSize: 17, color: Colors.ColorBody, textAlign: 'center', marginHorizontal: 10, backgroundColor: Colors.background, borderRadius: 7, paddingBottom: Platform.OS === 'android' ? 7 : 0, }, leftAction: { alignSelf: 'center', padding: 10, backgroundColor: Colors.red, }, deleteSwipe: { color: Colors.background, fontFamily: Typography.FONT_FAMILY.REGULAR, fontSize: 13, display: 'flex', }, input_container: { borderBottomColor: 'transparent', marginVertical: -27, marginLeft: 10, }, }); export default styles;
import React from 'react'; import s from './Post.module.css'; const Post = (props) => { return ( <div className={s.item}> <img src="https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg" alt=""/> {props.message} <div> {props.likeCounts} <span> likes</span> </div> </div> ) } export default Post;
const inquirer = require('inquirer'); const {nameCombine} = require('../../config/helpers'); module.exports = { confirmDelete: async (object) => { let toDelete; // Determine what type of object was inserted into the function with an if statement if(object.first_name) { // if it is an Employee, combine the first and last name toDelete = nameCombine(object); } else if(object.title) { // If it is a Role, use the title toDelete = object.title; } else { // If is is a Department, use the name toDelete = object.name; } const {confirm} = await inquirer.prompt([ { type: 'confirm', name: 'confirm', message: `Are you sure you want to delete ${toDelete}? The data can not be recovered.` } ]); if(!confirm) { console.log(`\nLet's go back.\n `); } return confirm; } }
function solve(str) { let tmpArr = [[],[]]; for(let i = 0;i < str.length;i++) { str[i] === str[i].toUpperCase() ? tmpArr[0][tmpArr[0].length] = str[i] : tmpArr[1][tmpArr[1].length] = str[i]; } return tmpArr[0].length > tmpArr[1].length ? str.toUpperCase() : str.toLowerCase(); }
import React from "react"; class Card extends React.Component { constructor() { super(); this.state = { title: "", director: "", stars: "", image: "", description: "", }; // this.userClick = this.userClick.bind(this); } componentDidMount() { fetch("http://localhost:8000/movies/") .then((response) => response.json()) .then((result) => { console.log("# 1 result:", result); // this.setState({ // }); }); } getCountry(country) { fetch("http://localhost:8000/movies/1") .then((response) => response.json()) .then((result) => { // let details = result.movieDetails[0]; console.log("# 2 result movieDetails:", result); // this.setState({ // title: details.title, // director: details.director, // stars: details.stars, // image: details.image, // description: details.description, // }); }) .catch((err) => console.log(err)); } // userClick(event) { // console.log("event.target.value", event.target.value); // this.setState({ // name: event.target.value, // }); // } render() { return ( <div > {this.getCountry()} </div> ); } } export default Card;
export { default as Logo } from "./Logo"; export { default as Navigation } from "./Navigation"; export { default as Thumbnail } from "./Thumbnail"; export { default as LineSeparator } from "./LineSeparator"; export { default as ThreeThumbsRow } from "./ThreeThumbsRow"; export { default as CustomLink } from "./CustomLink";
var check = function (num) { var numArray = num.toString().split(""); for (let i = numArray.length - 2; i > - 1; i -= 2) { var doubleNum = Number(numArray[i]) * 2; if (doubleNum > 9) { doubleNum -= 9; numArray[i] = doubleNum; } if (doubleNum < 10) { numArray[i] = doubleNum; } } var total = 0; for (let i = 0; i < numArray.length; i++) { total += Number(numArray[i]); } return total % 10 === 0; } module.exports = check;
var MAX_VERTICES = 8; // Да не се опитва повече от 10. Това чупи браузъра. var MAX_HEIGHTS = [0, 1, 2, 4, 8, 16, 32, 64, 100, 150, 250]; var MAX_HEIGHT = MAX_HEIGHTS[MAX_VERTICES]; var MIN_HEIGHT = -50; var ROUGHNESS = 0.5; var RADIUS = 40; var DIVE_OFFSET = 5; var BLACK = [0.1, 0.1, 0.1]; var WHITE = [1, 1, 1]; var GREEN = [0, 0.5, 0]; var YELLOW = [1, 1, 0]; class Bay { constructor() { this.size = Math.pow(2, MAX_VERTICES) + 1; this.max = this.size - 1; this.highest = new Point(0, 0, 0); this.colors = new ColorGradient(); this.generateBayVertices(); this.buffer = this.generateBufferData(); } generateBayVertices() { this.heightMap = new Float32Array(this.size * this.size).fill({ x: 0, y: 0, z: 0 }); this.set(0, 0, random(0, this.max / 2)); this.set(this.max, 0, random(0, this.max / 2)); this.set(this.max, this.max, random(0, this.max / 2)); this.set(0, this.max, random(0, this.max / 2)); this.divide(this.max); } generateBufferData() { var data = []; range(this.size - 1).forEach(x => { range(this.size - 1).forEach(y => { if (x == 0) { var point1 = new Point(x, y, MIN_HEIGHT); var point2 = new Point(x, y, this.get(x, y)); var point3 = new Point(x, y + 1, MIN_HEIGHT); var point4 = new Point(x, y + 1, this.get(x, y + 1)); this.generateWallData(data, point1, point2, point3, point4, true); } if (x == this.size - 2) { var point1 = new Point(x + 1, y, MIN_HEIGHT); var point2 = new Point(x + 1, y, this.get(x + 1, y)); var point3 = new Point(x + 1, y + 1, MIN_HEIGHT); var point4 = new Point(x + 1, y + 1, this.get(x + 1, y + 1)); this.generateWallData(data, point1, point2, point3, point4, true); } if (y == 0) { var point1 = new Point(x, y, MIN_HEIGHT); var point2 = new Point(x, y, this.get(x, y)); var point3 = new Point(x + 1, y, MIN_HEIGHT); var point4 = new Point(x + 1, y, this.get(x + 1, y)); this.generateWallData(data, point1, point2, point3, point4, true); } if (y == this.size - 2) { var point1 = new Point(x, y + 1, MIN_HEIGHT); var point2 = new Point(x, y + 1, this.get(x, y + 1)); var point3 = new Point(x + 1, y + 1, MIN_HEIGHT); var point4 = new Point(x + 1, y + 1, this.get(x + 1, y + 1)); this.generateWallData(data, point1, point2, point3, point4, true); } var point1 = new Point(x, y, this.get(x, y)); var point2 = new Point(x + 1, y, this.get(x + 1, y)); var point3 = new Point(x, y + 1, this.get(x, y + 1)); var point4 = new Point(x + 1, y + 1, this.get(x + 1, y + 1)); this.generateWallData(data, point1, point2, point3, point4, false); }); }); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW); return buffer; } generateWallData(data, point1, point2, point3, point4, isEdgeWall) { var average = Math.ceil(this.average([point1.z, point2.z, point3.z, point4.z])); if (average < 0) { average = 0; } if (isEdgeWall) { var color = { red: BLACK[0], green: BLACK[1], blue: BLACK[2] } } else { var color = this.colors.get(average); } var normalVector = generateNormalVector(point1, point3, point2); data.push(point1.x, point1.y, point1.z); data.push(normalVector.x, normalVector.y, normalVector.z); data.push(color.red, color.green, color.blue); data.push(point2.x, point2.y, point2.z); data.push(normalVector.x, normalVector.y, normalVector.z); data.push(color.red, color.green, color.blue); data.push(point4.x, point4.y, point4.z); data.push(normalVector.x, normalVector.y, normalVector.z); data.push(color.red, color.green, color.blue); normalVector = generateNormalVector(point1, point3, point4); data.push(point1.x, point1.y, point1.z); data.push(normalVector.x, normalVector.y, normalVector.z); data.push(color.red, color.green, color.blue); data.push(point3.x, point3.y, point3.z); data.push(normalVector.x, normalVector.y, normalVector.z); data.push(color.red, color.green, color.blue); data.push(point4.x, point4.y, point4.z); data.push(normalVector.x, normalVector.y, normalVector.z); data.push(color.red, color.green, color.blue); } get(x, y) { if (x < 0 || x > this.max || y < 0 || y > this.max) return -1; return this.heightMap[x + this.size * y]; } set(x, y, val) { if (val > MAX_HEIGHT) { val = MAX_HEIGHT; } if (val < MIN_HEIGHT) { val = MIN_HEIGHT; } if (val >= this.highest.z) { this.highest = new Point(x, y, val); } this.heightMap[x + this.size * y] = val; } divide(size) { var middle = size / 2; var scale = ROUGHNESS * size; if (middle < 1) { return; } for (var y = middle; y < this.max; y += size) { for (var x = middle; x < this.max; x += size) { this.square(x, y, middle, random(-scale, scale)); } } for (var y = 0; y <= this.max; y += middle) { for (var x = (y + middle) % size; x <= this.max; x += size) { this.diamond(x, y, middle, random(-scale, scale)); } } this.divide(size / 2); } average(values) { var valid = values.filter(value => { return value !== -1; }); var total = valid.reduce((sum, value) => { return sum + value; }, 0); return total / valid.length; } diamond(x, y, size, offset) { var ave = this.average([ this.get(x, y - size), this.get(x + size, y), this.get(x, y + size), this.get(x - size, y) ]); this.set(x, y, ave + offset); } square(x, y, size, offset) { var average = this.average([ this.get(x - size, y - size), this.get(x - size, y + size), this.get(x + size, y + size), this.get(x + size, y - size) ]); this.set(x, y, average + offset); } draw() { pushMatrix(); useMatrix(); gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer); gl.enableVertexAttribArray(aXYZ); gl.vertexAttribPointer(aXYZ, 3, gl.FLOAT, false, 9 * FLOATS, 0 * FLOATS); gl.enableVertexAttribArray(aNormal); gl.vertexAttribPointer(aNormal, 3, gl.FLOAT, false, 9 * FLOATS, 3 * FLOATS); gl.enableVertexAttribArray(aColor); gl.vertexAttribPointer(aColor, 3, gl.FLOAT, false, 9 * FLOATS, 6 * FLOATS) var dataCount = this.size * this.size * 6 + this.size * 11 + this.size - 24; gl.drawArrays(gl.TRIANGLES, 0, dataCount); popMatrix(); gl.disableVertexAttribArray(aColor); } } class Bird { constructor(peak, direction, speed, circleOffset, heightOffset, radius) { this.peak = peak; this.radius = radius; this.speed = speed; this.direction = direction; this.circleOffset = circleOffset; this.heightOffset = heightOffset; } draw(time) { time = time * this.direction + this.speed;; var circlePoint = this.getCirclePoint(time + this.circleOffset); var bird = new Sphere([circlePoint.x + this.peak.x, circlePoint.y + this.peak.y, this.peak.z + (Math.sin(time + this.heightOffset) * DIVE_OFFSET) + DIVE_OFFSET * DIVE_OFFSET ], 0.3); bird.color = BLACK; bird.draw(); } getCirclePoint(time) { return new Point(this.radius * Math.cos(time), this.radius * Math.sin(time), 0); } } class ColorGradient { constructor() { this.colors = this.generateColors(); } generateColors() { var colors = []; var height = MAX_HEIGHT + 1; var yellowGradient = this.generateGradient(YELLOW, GREEN, Math.ceil(height * 10 / 100)); var solidGreen = new Array(Math.ceil(height * 20 / 100)).fill({ red: GREEN[0], green: GREEN[1], blue: GREEN[2] }); var solidWhite = new Array(Math.ceil(height * 20 / 100)).fill({ red: WHITE[0], green: WHITE[1], blue: WHITE[2] }); var greenGradient = this.generateGradient(GREEN, WHITE, Math.ceil(height * 50 / 100)); colors = colors.concat(yellowGradient); colors = colors.concat(solidGreen); colors = colors.concat(greenGradient); colors = colors.concat(solidWhite); return colors; } generateGradient(start, end, steps) { var stepR = ((end[0] - start[0]) / (steps - 1)); var stepG = ((end[1] - start[1]) / (steps - 1)); var stepB = ((end[2] - start[2]) / (steps - 1)); var colors = []; integerRange({ upperBoundExclusive: steps }).forEach(i => { colors.push({ red: start[0] + (stepR * i), green: start[1] + (stepG * i), blue: start[2] + (stepB * i) }); }); return colors; } get(value) { return this.colors[value]; } nextColor() { return this.colors.pop(); } } class Point { constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } } function generateNormalVector(rawPoint1, rawPoint2, rawPoint3) { var point1 = [rawPoint1.x, rawPoint1.y, rawPoint1.z]; var point2 = [rawPoint2.x, rawPoint2.y, rawPoint2.z]; var point3 = [rawPoint3.x, rawPoint3.y, rawPoint3.z]; var rawVector = vectorProduct( vectorPoints(point1, point2), vectorPoints(point3, point2)); return new Point(rawVector[0], rawVector[1], rawVector[2]); } function integerRange({ upperBoundExclusive = 0, step = 1 } = {}) { var resultArray = []; for (var i = 0; i < upperBoundExclusive; i += step) { resultArray.push(i); } return resultArray; } function range(upperBound) { return Array.from(new Array(upperBound).keys()); }
const redisService = require("../services/redis"); const welcome = (req, res) => { res.json("Hola"); }; const welcomeAuth = (req, res) => { res.json("Hola, pero estás logueado"); }; module.exports = { welcome, welcomeAuth };
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import BootstrapVue from 'bootstrap-vue' import LearnApp from './LearnApp' import VueRouter from 'vue-router' import Routes from './routes' // Css Import import './css/main.css' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' Vue.use(BootstrapVue) Vue.use(VueRouter) Vue.config.productionTip = false const router = new VueRouter({ routes: Routes, mode: 'history' }) /* eslint-disable no-new */ new Vue({ el: '#learnApp', components: { LearnApp }, template: '<LearnApp/>', router: router })
console.log('test tools'); var _undefined = "undefined", _authid = "authid", _crossid = "crossid", _homoid = "homoid", _webid = "webid", _authtabid = "authtabid", _crosstabid = "crosstabid", _homotabid = "homotabid", _webtabid = "webtabid", _colid = "colid", _synoid = "synoid", _antoid = "antoid", _coltabid = "coltabid", _synotabid = "synotabid", _antotabid = "antotabid", _newktvid = "newktvid", _divtag = "DIV", _newLid = "newLeId", _confilid = "confil", _showfilterid = "filshow", _hidefilterid = "filhide"; function openWd(n, t) { var i = document.getElementById(n), r; i != null && typeof i != _undefined && i.tagName == _divtag && i.style.display == "none" && (i.style.display = "block", r = document.getElementById(t), r && (r.className = "tg_open")) } function switchWordsTab(n, t, i) { var r = document.getElementById(_colid), u = document.getElementById(_synoid), f = document.getElementById(_antoid), e = document.getElementById(_coltabid), o = document.getElementById(_synotabid), s = document.getElementById(_antotabid); r != null && typeof r != _undefined && r.tagName == _divtag && (n == "col" ? (r.style.display = "block", r.style.borderBottom = "1px solid white", e != null && (e.className = "tb_a")) : (r.style.display = "none", r.style.borderBottom = "", e != null && (e.className = "tb_b"))); u != null && typeof u != _undefined && u.tagName == _divtag && (n == "syno" ? (u.style.display = "block", u.style.borderBottom = "1px solid white", o != null && (o.className = "tb_a")) : (u.style.display = "none", u.style.borderBottom = "", o != null && (o.className = "tb_b"))); f != null && typeof f != _undefined && f.tagName == _divtag && (n == "anto" ? (f.style.display = "block", f.style.borderBottom = "1px solid white", s != null && (s.className = "tb_a")) : (f.style.display = "none", f.style.borderBottom = "", s != null && (s.className = "tb_b"))); openWd(t, i) } function switchDefiTab(n, t, i) { var r = document.getElementById(_authid), u = document.getElementById(_crossid), f = document.getElementById(_homoid), e = document.getElementById(_webid), o = document.getElementById(_authtabid), s = document.getElementById(_crosstabid), h = document.getElementById(_homotabid), c = document.getElementById(_webtabid); r != null && typeof r != _undefined && r.tagName == _divtag && (n == "auth" ? (r.style.display = "block", r.style.borderBottom = "1px solid white", o != null && (o.className = "tb_a")) : (r.style.display = "none", r.style.borderBottom = "", o != null && (o.className = "tb_b"))); u != null && typeof u != _undefined && u.tagName == _divtag && (n == "cross" ? (u.style.display = "block", u.style.borderBottom = "1px solid white", s != null && (s.className = "tb_a")) : (u.style.display = "none", u.style.borderBottom = "", s != null && (s.className = "tb_b"))); f != null && typeof f != _undefined && f.tagName == _divtag && (n == "homo" ? (f.style.display = "block", f.style.borderBottom = "1px solid white", h != null && (h.className = "tb_a")) : (f.style.display = "none", f.style.borderBottom = "", h != null && (h.className = "tb_b"))); e != null && typeof e != _undefined && e.tagName == _divtag && (n == "web" ? (e.style.display = "block", e.style.borderBottom = "1px solid white", c != null && (c.className = "tb_a")) : (e.style.display = "none", e.style.borderBottom = "", c != null && (c.className = "tb_b"))); openWd(t, i) } function alignWords(n, t, i) { var u = document.getElementsByName(t), r; if (u != null) for (r = 0; r < u.length; r++) u[r].onmouseout || (u[r].onmouseout = function() { alignWords(this, t, 0) }), i ? (u[r].style.color = "white", u[r].style.backgroundColor = "#04c") : (u[r].style.color = "", u[r].style.backgroundColor = "") } var Log = function(msg){ console.log( msg); }; var BilingualDict = { Play: function(n) { BilingualDict.Click(null, n, null, null, null); Log("audioClick "+ "BilingualDictionaryAudio "+ "BilingualDictionaryAudioInst") }, Click: function(n, t, i, r, u) { var f, e, o; if (t != "") { f = _ge(u); f == null && (f = _ge("dict_aud_cnt")); e = BilingualDict.GetPlayer(t); try { f.innerHTML = e } catch (s) { o = "pCont is null"; Log("Error " + "DictVerp " + o) } } }, GetPlayer: function(n) { if (navigator.userAgent.indexOf("Safari") > -1 || navigator.userAgent.indexOf("UCBrowser") > -1 || navigator.userAgent.indexOf("iPhone") > -1) { var t = document.createElement("audio"); return t.src = n, t.play(), t.innerHTML } return '<audio src="' + n + '" autoplay ><\/audio>' } }; _ge = function(n) { return document.getElementById(n) }; console.log('over');
import { initializeApp } from 'firebase/app'; import {getFirestore} from 'firebase/firestore' const firebaseConfig = { apiKey: "AIzaSyBBN97q-nDAaj5PGgfMCWF1TWiCjVwFNLo", authDomain: "clone-af1e7.firebaseapp.com", projectId: "clone-af1e7", storageBucket: "clone-af1e7.appspot.com", messagingSenderId: "487251503358", appId: "1:487251503358:web:02ed143940e39003229daf" }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); export default db;
/* for nodemoailer login confirmation */ var nodemailer = require('nodemailer'); var sendJSONresponse = function(res, status, content) { res.status(status); res.json(content); }; /* Send email */ module.exports.sendMail = function(req, res) { var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: 'harryac007@gmail.com', // your email here pass: process.env.EMAIL_SECRET // your password here } }); var mailOptions = { from: req.body.email, // sender address to : 'harry_ac07@yahoo.com', subject: 'feedback by '+req.body.name, // Subject line html: "<h3>This feedback was sent by : </h3>Email : "+req.body.email+"<br><br>"+req.body.feedback+"<br><br>sent at : "+Date() // html or text }; transporter.sendMail(mailOptions, function(err, info) { if (err) { return; } else if (!info) { sendJSONresponse(res, 404, { "message": "not found email." }); return; } else { console.log('Message sent: ' + info); sendJSONresponse(res, 200, info); } }); };
import React, { Component } from 'react' import { Container } from 'react-bootstrap' import Logo from '../assets/logocondor.png' import { FaFacebook, FaInstagram, FaTwitter, FaYoutube } from 'react-icons/fa'; import './Footer.css' export default class Footer extends Component { render() { return ( <div className="footer-container"> <div className="container-logo"> <img src={Logo} width="140px" /> </div> <div className="footer-direitos"> <p>@Condor 2020. Todos os direitos reservados.</p> </div> <div className="footer-redessociais"> <ul> <a href="https://www.facebook.com/RedeCondor/" ><li><FaFacebook color="white" size="25px"/></li></a> <a href="https://www.instagram.com/redecondor/"><li><FaInstagram color="white" size="25px"/></li></a> <a href="https://twitter.com/RedeCondor"><li><FaTwitter color="white" size="25px"/></li></a> <a href="https://www.youtube.com/user/redecondor"><li><FaYoutube color="white" size="25px"/></li></a> </ul> </div> </div> ) } }
var searchData= [ ['capabilities',['Capabilities',['../structvbe__info__block__t.html#a555521aede0ff448231fc7a404862bdb',1,'vbe_info_block_t']]], ['color',['color',['../structenemy__t.html#aa5f4d1eda21c196bd8401ff73f105073',1,'enemy_t']]], ['count_5fmode',['count_mode',['../group__timer.html#gabd6e94a182fc2daff67dfb46f732644a',1,'timer_status_field_val']]], ['cur_5fanimation',['cur_animation',['../structbullet__t.html#a50a73c2decef6a06fcba9d4097efb849',1,'bullet_t']]], ['cur_5fbullet_5fanim',['cur_bullet_anim',['../structgame__t.html#a267648c26397e1961832a25c48a83d7b',1,'game_t']]], ['current_5fammo',['current_ammo',['../structgame__t.html#abc6381cf5a100b9514e8e62d25679448',1,'game_t']]], ['currentbyte',['currentByte',['../structgame__t.html#a97751e93845a23236ff3a9871e246433',1,'game_t']]], ['currentindexformovback',['currentIndexForMovBack',['../structgame__t.html#a3ba0540e4fb82065272d3c039c835562',1,'game_t']]], ['currentpixmap',['currentPixmap',['../structenemy__t.html#a76e7a7a5d3aea2f0abafc4ba507e9003',1,'enemy_t::currentPixmap()'],['../structexplosion__t.html#a76e7a7a5d3aea2f0abafc4ba507e9003',1,'explosion_t::currentPixmap()']]], ['currentstate',['currentState',['../structstate__machine.html#a0bd6e13a9b3c78958bfb4bb9ff0f907c',1,'state_machine']]], ['cursor',['cursor',['../structgame__t.html#a8a6bb85bf44d1392b588a65de57652c0',1,'game_t']]], ['cursor_5fover',['cursor_over',['../structbutton__t.html#a63a85a00aeb4fa01d0e50ebbb0eb2b33',1,'button_t']]] ];
const input = require('prompt-sync')() function main(){ let codigo = 1; let selecoes = 0; let vflamengo = 0; let vvasco = 0; let empates = 0; let gol_1 = 0; let gol_2 = 0; } main() while(codigo === 1){ gol_1 = Number(input('Digite aqui quantos gols o Flamengo marcou num CLÁSSICO: ')); gol_2 = Number(input('Digite aqui quantos gols o Vasco marcou no CLÁSSICO: ')); } if (gol_1 > gol_2){ vflamengo++ }else if (gol_2 > gol_1){ vvasco++ }else{ empates++ } selecoes++ codigo = Number(input('Novo Clássico:(1-Sim; 2-Não): ')); } console.log(`Total de clássicos: ${selecoes}\nVitórias do Flamengo: ${vflamengo}\nVitórias do Vasco: ${vvasco}\nEmpates: ${empates}`); if (vflamengo > vvasco){ console.log('Se o Flamengo obter mais gols que o Vasco entre os clássicos!'); }else if (vvasco > vflamengo){ console.log('Se o Vasco obter mais gols que o Flamengo entre os clássicos!'); }else{ console.log('Não houve vencedor!'); } } } main()
var Game = (function () { function Game(id) { this.box = document.getElementById(id); this.canvas = document.createElement('canvas'); this.canvas.innerText = '您的浏览器不支持canvas,请升级Chrome浏览器'; this.box.appendChild(this.canvas); this.ctx = this.canvas.getContext('2d'); this.init(); this.zhuan = new Zhuan(this); this.ball = new Ball(this); this.zhuan.createZhuan(1); } Game.prototype.init = function () { this.setStyle(); this.bindEvent(); this.start(); }; // 设置样式 Game.prototype.setStyle = function () { this.width = document.body.clientWidth; this.height = document.body.clientHeight; this.canvas.width = this.width; this.canvas.height = this.height; // this.canvas.style.backgroundColor = '#cfc'; this.canvas.style.position = 'absolute'; }; // 游戏主循环 Game.prototype.start = function () { var that = this; var f = 0; this.timer = setInterval(function () { f++; that.ctx.clearRect(0,0,that.canvas.width,that.canvas.height); that.zhuan.createZhuan(1); if (that.ball.isSheng){ that.ball.shengzi.render(); } that.ball.update(); },16) }; // 事件监听 Game.prototype.bindEvent = function () { var that = this; // 移动版事件----开始 // 触摸事件 this.canvas.addEventListener('touchstart',function (event) { that.ball.shengzi.deg = 0; that.ball.jiantou = true; var x = event.targetTouches[0].clientX; // 滑动事件 that.canvas.addEventListener('touchmove',function (event) { that.ball.shengzi.deg = (event.targetTouches[0].clientX - x) / that.canvas.width * 90; console.log(x,that.ball.shengzi.deg) }); // 离开事件 that.canvas.addEventListener('touchend',function () { that.ball.jiantou = false; that.canvas.onmousemove = null; that.ball.lali = -5; that.ball.shengzi.length = 60; that.ball.isSheng = true; //console.log(that.ball.shengzi.length,that.ball.gx,that.ball.lali); that.ball.start(); }); event.preventDefault(); }) // 移动版事件----结束 /* // PC 版事件-----开始 this.canvas.onmousedown = function (event) { that.ball.jiantou = true; var x = event.clientX; that.canvas.onmousemove = function (event) { that.ball.shengzi.deg = (event.clientX - x) / that.canvas.width * 90; }; that.canvas.onmouseup = function () { that.ball.jiantou = false; that.canvas.onmousemove = null; that.ball.lali = -5; that.ball.shengzi.length = 60; that.ball.isSheng = true; //console.log(that.ball.shengzi.length,that.ball.gx,that.ball.lali); that.ball.start(); } } // PC 版事件-----结束 */ }; // 碰撞检测 Game.prototype.isBarrier = function () { var r = this.ball.R; for ( var i = 0 ; i < this.zhuan.data.length ; i++ ) { var x1 = this.zhuan.data[i].x - r, y1 = this.zhuan.data[i].y - r, x2 = x1 + 50 + r * 2, y2 = y1 + 50 + r * 2; if ( this.ball.y > y1 && this.ball.y < y2 && this.ball.x > x1 && this.ball.x < x2) { clearInterval(this.timer); } /* this.ctx.beginPath(); this.ctx.moveTo(x1,y1); this.ctx.lineTo(x1,y2); this.ctx.lineTo(x2,y2); this.ctx.lineTo(x2,y1); this.ctx.closePath(); this.ctx.strokeStyle = '#ccc'; this.ctx.stroke(); */ } }; return Game; })();
import React, { Component } from "react"; import { Provider } from "react-redux"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; // import { createStore, applyMiddleware } from "redux"; import HomePage from "./containers/home"; import LoginPage from "./containers/admin/login"; import HeaderSection from "./containers/admin/header"; import DashboardPage from "./containers/admin/dashboard"; import ImportPage from "./containers/admin/import"; import VideosPage from "./containers/admin/videos"; import VerificationMailPage from "./containers/admin/verification-mail"; import MasterVideoList from "./containers/admin/MasterVideoList"; // import createSagaMiddleware from 'redux-saga'; // import { composeWithDevTools } from 'redux-devtools-extension'; // import reducer from './reducers'; // import actionsSaga from './sagas'; import { initStore } from "./assets/redux/store"; // const sagaMiddleware = createSagaMiddleware(); // const store = createStore(reducer, composeWithDevTools(applyMiddleware(sagaMiddleware))); // sagaMiddleware.run(actionsSaga); class App extends Component { render() { return ( <Provider store={initStore}> <Route path="/" exact component={HomePage} /> <Route path="/admin" exact component={LoginPage} /> <Route path="/admin/*" component={HeaderSection} /> <Switch> <Route path="/admin/dashboard/" component={DashboardPage} /> <Route path="/admin/video/list" component={MasterVideoList} /> <Route path="/admin/import" component={ImportPage} /> <Route path="/admin/users/:id/videos" component={VideosPage} /> <Route path="/admin/mails" component={VerificationMailPage} /> </Switch> </Provider> ); } } export default App;
import React, {useEffect} from 'react' import {Switch, Route, useLocation, withRouter} from 'react-router-dom' import {AnimatePresence} from 'framer-motion' import Home from './pages/Home' import SingleWork from './pages/SingleWork' import About from './pages/About' import News from './pages/News' import SingleNews from './pages/SingleNews' import Contact from './pages/Contact' import Page404 from './pages/404' function App() { const location = useLocation() useEffect(() => { setTimeout(()=>{ window.scrollTo(0, 0) }, 1000) }, [location]) return ( <> <AnimatePresence initial={true} exitBeforeEnter> <Switch location={location} key={location.pathname}> <Route exact path='/'><Home /></Route> <Route path='/works-:workId'><SingleWork /></Route> <Route exact path='/about'><About /></Route> <Route exact path='/news'><News /></Route> <Route path='/single-news-:newsId'><SingleNews /></Route> <Route exact path='/contact'><Contact /></Route> <Route ><Page404 /></Route> </Switch> </AnimatePresence> </> ) } const WithRouterApp = withRouter(App); export default WithRouterApp
/** * MAPLE Lab Graphs * Highcharts.js * * created by Kyle Gauder */ $(document).ready(function () { $('#QJEP-2016-fig2-1').highcharts({ chart: { type: 'column', }, title: { text: 'Recognition of Sequences' // TITLE }, plotOptions: { column: { borderColor: '#000000', borderWidth: 1 } }, xAxis: { title: { text: 'Amplitude envelope' // X-AXIS LABEL }, categories: ["Percussive","Flat"], // X-AXIS CATEGORIES crosshair: true }, yAxis: { title: { text: 'Old/new sensitivity (d prime)' // Y-AXIS LABEL }, min: 0, max: 2.5 // Y-AXIS SCALE }, legend: { enabled: false }, credits: { enabled: false }, tooltip: { enabled: false }, series: [{ // First category of Data name: 'Data', color: 'grey', data: [{y: 1.01, color: 'white'},0.8807], }, { name: 'Data error', type: 'errorbar', data: [[0.75, 1.3], [0.6, 1.2]], //min t0 max // Next category? }] }); $('#QJEP-2016-fig2-2').highcharts({ chart: { type: 'column', }, title: { text: 'Recall of objects' // TITLE }, plotOptions: { column: { borderColor: '#000000', borderWidth: 1 } }, xAxis: { title: { text: 'Amplitude envelope' // X-AXIS LABEL }, categories: ["Percussive","Flat"], // X-AXIS CATEGORIES crosshair: true }, yAxis: { title: { text: 'As a percentage of sequences recognized' // Y-AXIS LABEL }, min: 0, max: 70 // Y-AXIS SCALE }, legend: { enabled: false }, credits: { enabled: false }, tooltip: { enabled: false }, series: [{ // First category of Data name: 'Data', color: 'grey', data: [{y: 52.9, color: 'white'},32.67], }, { name: 'Data error', type: 'errorbar', data: [[45, 61], [29, 36]], //min t0 max // Next category? }] }); });
var canvas = document.getElementById("field"); var ctx = canvas.getContext("2d"); var height = 20; var width = 20; var size = document.getElementById("field").width; var aliveCell = "#00E676"; var deadCell = "#B9F6CA"; var num = 1; var generNum = document.getElementById("generationNum"); function drawCanvas(ctx) { for (i = 1; i < height; i++) { ctx.beginPath(); ctx.moveTo(height*i, 0); ctx.lineTo(height*i, size); ctx.stroke(); } for (i = 1; i < width; i++) { ctx.beginPath(); ctx.moveTo(0, width*i); ctx.lineTo(size, width*i); ctx.stroke(); } } drawCanvas(ctx); var arr = []; for (var i = 0; i < height; i++) { arr.push([]); for (var j = 0; j < width; j++) { arr[i].push(false); } } function draw() { for (var i = 0; i < height; i++) { for (var j = 0; j < width; j++) { ctx.fillStyle = arr[i][j] ? aliveCell : deadCell; ctx.fillRect(i * height, j * width, height - 1, width - 1); } } } canvas.addEventListener("click", getClickPosition, false); function getClickPosition(e) { var x = e.clientX; var y = e.clientY; x -= canvas.offsetLeft; y -= canvas.offsetTop; arr[Math.floor(x/height)][Math.floor(y/width)] = !arr[Math.floor(x/height)][Math.floor(y/width)]; draw(); } var startButton = document.getElementById("start"); var stopButton = document.getElementById("stop"); function countAliveNeighbours(x, y) { var count = 0; var dx = [-1, 0, 1, 1, 1, 0, -1, -1]; var dy = [-1, -1, -1, 0, 1, 1, 1, 0]; for (var i = 0; i < 8; i++) { if (arr[(x + dx[i] + height) % height][(y + dy[i] + width) % width]) { count++; } } return count; } function nextGeneration() { generNum.innerHTML = num++; var sarr = []; for (var i = 0; i < height; i++) { sarr.push([]); for (var j = 0; j < width; j++) { if (countAliveNeighbours(i, j) == 3) sarr[i].push(true); if (countAliveNeighbours(i, j) == 2) sarr[i].push(arr[i][j]); if (countAliveNeighbours(i, j) != 3 && countAliveNeighbours(i, j) != 2) sarr[i].push(false); } } arr = sarr; draw (); } var interval; function start() { interval = setInterval(nextGeneration, 250) } function stop() { clearInterval(interval); } startButton.addEventListener("click", start); stopButton.addEventListener("click", stop); draw();
let stack = function() { this.head = null; this.count = 0; this.push = function(val) { if (!this.head) { this.head = { val: val }; } else { let node = { val: val }; node.next = this.head; this.head = node; } this.count++; }; this.pop = function() { let val = head.val; head = head.next; this.count--; return val; }; }; let setOfStacks = function(max) { let stacks = []; this.push = function(val) { if (stacks.length == 0) { stacks.push(new stack()); } let stackRef = stacks[stacks.length - 1]; if (stackRef.count >= max) { stacks.push(new stack()); } stackRef = stacks[stacks.length - 1]; stackRef.push(val); }; this.pop = function() { while (true) { if (stacks.length == 0) { return null; } let topStack = stacks.pop(); if (topStack.count != 0) { return topStack.pop(); } } }; this.popAt = function(index) { let stack = stacks[index]; return stack.pop(); }; }; function createStacks(cap, itemCount) { let sos = new setOfStacks(cap); for (let i = 0; i < itemCount; i++) { var min = 0; var max = 9; let random = Math.floor(Math.random() * (+max - +min)) + +min; sos.push(random); } } function print(stacks) { console.log("printing now..."); } let stacks = createStacks(5, 20); print(stacks);
import { combineReducers } from 'redux'; import { connectRouter } from 'connected-react-router'; import userReducer from '../../user/redux/userReducer'; import restReducer from '../../core/rest/restReducer'; import coinReducer from '../../coin/redux/coinReducer' export default function(history) { const allReducers = combineReducers({ router: connectRouter(history), user: userReducer, rest: restReducer, coins: coinReducer }) return function rootReducer(state = {}, action) { return allReducers(state, action) } }
var searchData= [ ['object_2ejava',['Object.java',['../_object_8java.html',1,'']]], ['ordenararray_2ejava',['OrdenarArray.java',['../_ordenar_array_8java.html',1,'']]] ];
// app/services/auth.js import { AsyncStorage } from "react-native"; const TOKEN_STORAGE_LOCATION = "TOKEN"; const MAIL_STORAGE_LOCATION = "MAIL"; export async function onSignIn(token: string, mail: string) { try { await Promise.all([ AsyncStorage.setItem(TOKEN_STORAGE_LOCATION, token), AsyncStorage.setItem(MAIL_STORAGE_LOCATION, mail) ]); } catch (error) { console.error(error); } } export async function onSignOut() { try { await Promise.all([ AsyncStorage.removeItem(TOKEN_STORAGE_LOCATION), AsyncStorage.removeItem(MAIL_STORAGE_LOCATION) ]); } catch (error) { console.error(error); } } export async function getToken(): string { let token = null; try { token = await AsyncStorage.getItem(TOKEN_STORAGE_LOCATION); } catch (error) { console.error(error.message); } return token; } export async function getMail(): string { let mail = null; try { mail = await AsyncStorage.getItem(MAIL_STORAGE_LOCATION); } catch (error) { console.error(error.message); } return mail; }
#pragma strict var mainCam : Camera; static var playerScore01 : int = 0; static var playerScore02 : int = 0; static var testTouch1 : float = 0; static var testTouch2 : float = 0; var theSkin : GUISkin; var theBall : Transform; function Start() { theBall = GameObject.FindGameObjectWithTag("Ball").transform; } static function Score (wallName : String) { if(wallName == "rightWall") { playerScore01 += 1; } else { playerScore02 += 1; } Debug.Log("Player score 1 is " + playerScore01); Debug.Log("Player score 2 is " + playerScore02); } function OnGUI() { GUI.skin = theSkin; GUI.Label (new Rect(Screen.width/2 - 150-20, 20, 100, 100),"" + playerScore01); GUI.Label (new Rect(Screen.width/2 + 150-20, 20, 100, 100),"" + playerScore02); GUI.Label (new Rect(Screen.width/2 - 150-20, Screen.height - 60, 100, 100),"" + testTouch1); GUI.Label (new Rect(Screen.width/2 + 150-20, Screen.height - 60, 100, 100),"" + testTouch2); if(GUI.Button(new Rect(Screen.width/2 - 121/2, 20, 121, 53) , "RESET")) { playerScore01 = 0; playerScore02 = 0; theBall.gameObject.SendMessage("ResetBall"); } }
//Minimal PDF rendering and text-selection example using pdf.js by Vivin Suresh Paliath (http://vivin.net) //This fiddle uses a built version of pdf.js that contains all modules that it requires. // //For demonstration purposes, the PDF data is not going to be obtained from an outside source. I will be //storing it in a variable. Mozilla's viewer does support PDF uploads but I haven't really gone through //that code. There are other ways to upload PDF data. For instance, I have a Spring app that accepts a //PDF for upload and then communicates the binary data back to the page as base64. I then convert this //into a Uint8Array manually. I will be demonstrating the same technique here. What matters most here is //how we render the PDF with text-selection enabled. The source of the PDF is not important; just assume //that we have the data as base64. // //The problem with understanding text selection was that the text selection code has heavily intertwined //with viewer.html and viewer.js. I have extracted the parts I need out of viewer.js into a separate file //which contains the bare minimum required to implement text selection. The key component is TextLayerBuilder, //which is the object that handles the creation of text-selection divs. I have added this code as an external //resource. // //This demo uses a PDF that only has one page. You can render other pages if you wish, but the focus here is //just to show you how you can render a PDF with text selection. Hence the code only loads up one page. // //The CSS used here is also very important since it sets up the CSS for the text layer divs overlays that //you actually end up selecting. // //For reference, the actual PDF document that is rendered is available at: //http://vivin.net/pub/pdfjs/TestDocument.pdf var scale = 1.5; //Set this to whatever you want. This is basically the "zoom" factor for the PDF. //Required to highlight entities on the PDF $.getScript("/js/lib/pdf/hilitor.js" ); var myHilitor; var GLentities; function loadPdf(pdfData, entities) { GLentities = entities; myHilitor = new Hilitor("pdfContainer"); setHighlight(); console.log("Loading pdf "+pdfData); PDFJS.disableWorker = true; //Not using web workers. Not disabling results in an error. This line is //missing in the example code for rendering a pdf. var $pdfContainer = jQuery("#pdfContainer"); $pdfContainer.empty(); var pdf = PDFJS.getDocument(pdfData); pdf.then(renderPdf); } var count = 0; function setHighlight(){ if(count<20) { //if($("#pdfContainer").is(':empty') ) { setTimeout(setHighlight, 100); highlightEntities(GLentities); count++; } } function renderPdf(pdf) { var total = pdf.numPages; for (i = 1; i <= total; i++){ pdf.getPage(i).then(renderPage); } } function renderPage(page) { var $canvas = jQuery("<canvas></canvas>"); var canvas = $canvas.get(0); var viewport = page.getViewport(scale); //page.getViewport(canvas.width / page.getViewport(1.0).width);// //Set the canvas height and width to the height and width of the viewport var context = canvas.getContext("2d"); canvas.height = viewport.height; canvas.width = viewport.width; //Append the canvas to the pdf container div var $pdfContainer = jQuery("#pdfContainer"); $pdfContainer.css("height", canvas.height + "px").css("width", canvas.width + "px"); //Create a second page div and attach it pdf container to it var $pageContainer = jQuery("<div></div>"); //Readjust the canvas so the borders show canvas.width = canvas.width - 3; canvas.height = canvas.height - 3; $pageContainer.append($canvas); //The following few lines of code set up scaling on the context if we are on a HiDPI display var outputScale = getOutputScale(); if (outputScale.scaled) { var cssScale = 'scale(' + (1 / outputScale.sx) + ', ' + (1 / outputScale.sy) + ')'; CustomStyle.setProp('transform', canvas, cssScale); CustomStyle.setProp('transformOrigin', canvas, '0% 0%'); if ($textLayerDiv.get(0)) { CustomStyle.setProp('transform', $textLayerDiv.get(0), cssScale); CustomStyle.setProp('transformOrigin', $textLayerDiv.get(0), '0% 0%'); } } context._scaleX = outputScale.sx; context._scaleY = outputScale.sy; if (outputScale.scaled) { context.scale(outputScale.sx, outputScale.sy); } var canvasOffset = $canvas.offset(); console.log(canvas.height); var $textLayerDiv = jQuery("<div />") .addClass("textLayer") .css("height", viewport.height + "px") .css("width", viewport.width + "px") .offset({ top: (canvas.height * (page.pageNumber-1)/*+5*/), left: canvasOffset.left //top: $canvas.top, //left: $canvas.left }); $pageContainer.append( $textLayerDiv ); $pageContainer.css( "overflow", "auto"); //Append the page container div to the pdf container $pdfContainer.append( $pageContainer ); page.getTextContent().then(function (textContent) { var textLayer = new TextLayerBuilder($textLayerDiv.get(0), 0); //The second zero is an index identifying //the page. It is set to page.number - 1. textLayer.setTextContent(textContent); var renderContext = { canvasContext: context, viewport: viewport, textLayer: textLayer }; page.render(renderContext); var layers = {}; //we must concatenate the text, since it comes in the form of array if( null != textContent.bidiTexts ){ var page_text = ""; var last_block = null; for( var k = 0; k < textContent.bidiTexts.length; k++ ){ var block = textContent.bidiTexts[k]; if( last_block != null && last_block.str[last_block.str.length-1] != ' '){ if( block.x < last_block.x ) page_text += "\r\n"; else if ( last_block.y != block.y && ( last_block.str.match(/^(\s?[a-zA-Z])$|^(.+\s[a-zA-Z])$/) == null )) page_text += ' '; } page_text += block.str; last_block = block; } } }); } function highlightEntities(entities){ var concat = "" entities.forEach(function(entry){ concat = concat +" "+ entry.text; }) myHilitor.apply(concat); }
var searchData= [ ['huffman',['Huffman',['../classHuffman.html',1,'']]] ];
 var DS_HopDong, DS_HopDong_TD, DS_HopDong_Loc, DS_HopDong_ChiTiet, DS_NhaThau, DS_LoaiHD, DS_HTMS, DS_LoaiVT, DS_VatTu, DS_DVT; var detailInit_e, v_STT; var VatTu_ID_Sua; var HopDong_ID; var Path, Path_Sua; var DS_NguonVon; $(document).ready(function () { document.oncontextmenu = function () { return false; } $("[id$=_hf_quyen_capnhat]").val() == "true" ? $("#tb_BoLoc").show() : $("#tb_BoLoc").hide(); //////// DataSource\\\\\\\\\\\\ DS_NhaThau = new kendo.data.DataSource({ serverFiltering: true, transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_DanhMuc.aspx", data: { cmd: 'DS_NhaThau' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=Hop_Dong.aspx"; } else { options.success(result); } } }); } } }); DS_HopDong = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong.aspx", data: { cmd: 'Lay_DS_HopDong' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); DS_HopDong_TD = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong.aspx", data: { cmd: 'Lay_DS_HopDong_TD' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); //Bộ lọc $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").hide(); $("#cmb_BoLoc").kendoDropDownList({ dataTextField: "text", dataValueField: "value", dataSource: [ { text: "Tình trạng hợp đồng", value: "1" }, { text: "Hình thức mua sắm", value: "2" }, { text: "Ngày kí hợp đồng", value: "3" }, { text: "Nhà thầu", value: "4" }, { text: "Ngày còn lại của hợp đồng", value: "5" }, { text: "Loại hợp đồng", value: "6" }, { text: "Tỷ lệ còn lại của hợp đồng", value: "7" } ], optionLabel: "--Tất cả--", select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.value; switch (value) { case "1": $("#grid_hopdong").data("kendoGrid").dataSource.filter({}); $("#Tr_Loc_TinhTrang").show(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").hide(); break; case "2": $("#grid_hopdong").data("kendoGrid").dataSource.filter({}); $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_HTMS").show(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").hide(); break; case "3": $("#txt_TuNgay").val(""); $("#txt_DenNgay").val(""); $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_NgayKi_HD").show(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_btn_loc").show(); $("#Tr_GiaTriConLaiHD").hide(); break; case "4": $("#grid_hopdong").data("kendoGrid").dataSource.filter({}); $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").show(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").hide(); break; case "5": $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_Loc_NgayConLai").show(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").hide(); break; case "6": $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_LoaiHD").show(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").hide(); break; case "7": $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_Loc_NgayConLai").hide(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").show(); break; default: $("#Tr_Loc_TinhTrang").hide(); $("#Tr_Loc_HTMS").hide(); $("#Tr_Loc_LoaiHD").hide(); $("#Tr_Loc_NgayKi_HD").hide(); $("#Tr_Loc_NhaThau").hide(); $("#Tr_btn_loc").hide(); $("#Tr_GiaTriConLaiHD").hide(); } } }); $("#cmb_Loc_ConLai").kendoDropDownList({ dataTextField: "text", dataValueField: "value", dataSource: [ { text: "60 ngày", value: "60" }, { text: "45 ngày", value: "45" }, { text: "30 ngày", value: "30" } ], optionLabel: "--Tất cả--", select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.value; if (value == "") { Load_DS_HopDong(DS_HopDong); } else { DS_HopDong_Loc = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong.aspx", data: { cmd: 'Lay_DS_HopDong_NgayConLai', NgayConLai: value }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); Load_DS_HopDong(DS_HopDong_Loc); } } }); $("#cmb_Loc_TinhTrang").kendoDropDownList({ dataTextField: "text", dataValueField: "value", dataSource: [ { text: "Hiệu lực", value: "0" }, { text: "Thanh lý", value: "1" } ], optionLabel: "--Tất cả--", select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.value; if (value == "") { $("#grid_hopdong").data("kendoGrid").dataSource.filter({}); } else { $("#grid_hopdong").data("kendoGrid").dataSource.filter({ field: "TinhTrang_HD", operator: "eq", value: parseInt(value) }); } } }); $("#cmb_Loc_HTMS").kendoDropDownList({ optionLabel: "--Tất cả--", dataTextField: "HinhThucMS_Ten", dataValueField: "HinhThucMS_ID", dataSource: new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong.aspx", data: { cmd: 'Lay_DS_HopDong_HTMS' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); } } }), select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.HinhThucMS_ID; if (value == "") { $("#grid_hopdong").data("kendoGrid").dataSource.filter({}); } else if (value == null) { $("#grid_hopdong").data("kendoGrid").dataSource.filter({ field: "HinhThucMS_ID", operator: "eq", value: value }); } else { $("#grid_hopdong").data("kendoGrid").dataSource.filter({ field: "HinhThucMS_ID", operator: "eq", value: parseInt(value) }); } } }); $("#cmb_Loc_LoaiHD").kendoDropDownList({ optionLabel: "--Tất cả--", dataTextField: "LoaiHD_Ten", dataValueField: "LoaiHD_ID", dataSource: new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong.aspx", data: { cmd: 'Lay_DS_HopDong_LoaiHD' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); } } }), select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.LoaiHD_ID; if (value == "") { $("#grid_hopdong").data("kendoGrid").dataSource.filter({}); } else if (value == null) { $("#grid_hopdong").data("kendoGrid").dataSource.filter({ field: "LoaiHD_ID", operator: "eq", value: value }); } else { $("#grid_hopdong").data("kendoGrid").dataSource.filter({ field: "LoaiHD_ID", operator: "eq", value: parseInt(value) }); } } }); $("#cmb_Loc_NhaThau").kendoDropDownList({ autoBind: true, optionLabel: "--Tất cả--", dataTextField: "TenNhaThau", dataValueField: "NhaThau_ID", dataSource: DS_NhaThau, select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.NhaThau_ID; if (value == "") { $("#grid_hopdong").data("kendoGrid").dataSource.filter({}); } else { $("#grid_hopdong").data("kendoGrid").dataSource.filter({ field: "NhaThau_ID", operator: "eq", value: parseInt(value) }); } } }); $("#btn_huy_loc").click(function () { Load_DS_HopDong(DS_HopDong); }); $("#btn_loc").click(function () { DS_HopDong_Loc = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong.aspx", data: { cmd: 'Lay_DS_HopDong_Ngay', TuNgay: $("#txt_TuNgay").val(), DenNgay: $("#txt_DenNgay").val() }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); Load_DS_HopDong(DS_HopDong_Loc); }); $("#cmb_Loc_TyLeConLai").kendoDropDownList({ dataTextField: "text", dataValueField: "value", dataSource: [ { text: "60 %", value: "60" }, { text: "50 %", value: "50" }, { text: "40 %", value: "40" }, { text: "30 %", value: "30" }, { text: "20 %", value: "20" } ], optionLabel: "--Tất cả--", select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.value; if (value == "") { Load_DS_HopDong(DS_HopDong); } else { DS_HopDong_Loc = new kendo.data.DataSource({ transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_TheoDoi.aspx", data: { cmd: 'TheoDoi_ConLai_HD', TyLe: value }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, pageSize: 7 }); Load_DS_HopDong(DS_HopDong_Loc); } } }); //#region Upload $('#files_upload').kendoUpload({ async: { autoUpload: false, saveUrl: 'UploadFileVB.aspx' }, error: function (e) { this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger'); }, localization: { dropFilesHere: 'Kéo thả file vào đây để upload', headerStatusUploaded: 'Đã upload xong', headerStatusUploading: 'Đang upload', select: 'Chọn file...', statusFailed: 'Upload không thành công', statusUploaded: 'Đã upload xong', statusUploading: 'Đang upload', uploadSelectedFiles: 'Upload' }, multiple: false, success: function (e) { Path = e.response.FilePath; this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath); this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success'); }, upload: function (e) { e.data = { LoaiFile: 'VBHopDong' }; }, select: function (e) { var ext = e.files[0].extension.toLowerCase(); if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") { e.preventDefault(); alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>'); return; } if (e.files[0].size > 10485760) { e.preventDefault(); alert('Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!'); return; } } }); $('#files_upload_sua').kendoUpload({ async: { autoUpload: false, saveUrl: 'UploadFileVB.aspx' }, error: function (e) { this.wrapper.closest('.row').siblings().eq(1).find('span').text('Upload không thành công!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-success').toggleClass('text-danger'); }, localization: { dropFilesHere: 'Kéo thả file vào đây để upload', headerStatusUploaded: 'Đã upload xong', headerStatusUploading: 'Đang upload', select: 'Chọn file...', statusFailed: 'Upload không thành công', statusUploaded: 'Đã upload xong', statusUploading: 'Đang upload', uploadSelectedFiles: 'Upload' }, multiple: false, success: function (e) { Path_Sua = e.response.FilePath; this.wrapper.closest('.row').siblings().eq(1).find('input').val(e.response.FilePath); this.wrapper.closest('.row').siblings().eq(1).find('span').text('Đã upload!'); this.wrapper.closest('.row').siblings().eq(1).find('span').toggleClass('text-danger').toggleClass('text-success'); }, upload: function (e) { e.data = { LoaiFile: 'VBHopDong' }; }, select: function (e) { var ext = e.files[0].extension.toLowerCase(); if (ext !== ".pdf" && ext !== ".doc" && ext !== ".docx") { e.preventDefault(); alert('Chỉ cho phép upload file văn bản ở định dạng <b>.pdf</b>, <b>.doc</b> hoặc <b>.docx</b>'); return; } if (e.files[0].size > 10485760) { e.preventDefault(); alert('Dung lượng file upload vượt quá giới hạn! Lớn hơn 10 Mb!'); return; } } }); //#endregion $("[id$=_hf_quyen_capnhat]").val() == "true" ? Load_DS_HopDong(DS_HopDong) : Load_DS_HopDong(DS_HopDong_TD); }); function Load_DS_HopDong(d) { $("#grid_hopdong").empty(); var grid = $("#grid_hopdong").kendoGrid({ dataSource: d, toolbar: kendo.template($("#Templ_ThemHD").html()), detailTemplate: kendo.template($("#Templ_ChiTiet_HopDong").html()), dataBound: function () { this.expandRow(this.tbody.find("tr.k-master-row").first()); }, detailExpand: function (e) { this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow)); }, sortable: true, pageable: { messages: { display: "Tổng số {2} hợp đồng", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, detailInit: detailInit, columns: [ { hidden: true, field: "HopDong_ID" }, { title: "Tình trạng", headerAttributes: { class: "header_css" }, field: "TinhTrang_HD", template: "#= HienThi_TinhTrang(TinhTrang_HD) #", width: "6%" }, { title: "Số HĐ", headerAttributes: { class: "header_css" }, field: "MaHD", template: function (data) { //if (data.SoNgayConLai <= 30) { // return '<img src="Images/alarm_2.gif" height="40" width="40" /><br><b>' + data.MaHD + '</b>'; //} //else { return '<b>' + data.MaHD + '</b>'; //} }, attributes: { class: "row_css" }, width: "12%" }, { title: "Nhà thầu", headerAttributes: { class: "header_css" }, field: "NhaThau_Ten", attributes: { class: "row_css" }, width: "12%" }, { title: "Ngày ký HĐ", headerAttributes: { class: "header_css" }, field: "NgayKy", template: "#= NgayKy_f #", attributes: { class: "row_css" }, width: "8%" }, { title: "HTMS", headerAttributes: { class: "header_css" }, field: "HinhThucMS_Ten", attributes: { class: "row_css" } }, { title: "Giá trị HĐ trước thuế", headerAttributes: { class: "header_css" }, field: "GiaTriTruocThue", template: "#= OnChangeFormat(GiaTriTruocThue) #", attributes: { class: "row_css" }, width: "12%" }, { title: "Ngày còn lại", headerAttributes: { class: "header_css" }, field: "SoNgayConLai", template: "#= HienThi_SoNgayConLai(data) #" }, { title: "Ngày hết hạn", headerAttributes: { class: "header_css" }, field: "NgayHetHan", //template: "#= NgayHetHan_f #", template: function (data) { if (data.SoNgayConLai <= 30) { return '<img src="Images/alarm_2.gif" height="40" width="40" /><br><b>' + data.NgayHetHan_f + '</b>'; } else { return '<b>' + data.NgayHetHan_f + '</b>'; } }, attributes: { class: "row_css" }, width: "8%" }, { title: "File văn bản", headerAttributes: { class: "header_css" }, field: "FileVB", template: '#= Ham_HienThi_VB(FileVB) #', width: "8%" } ] }); $("#txt_search_sohd").kendoAutoComplete({ dataTextField: "MaHD", dataSource: DS_HopDong, select: function (e) { var dataItem = this.dataItem(e.item.index()); var value = dataItem.MaHD; if (value) { grid.data("kendoGrid").dataSource.filter({ field: "MaHD", operator: "eq", value: value }); } else { grid.data("kendoGrid").dataSource.filter({}); } }, change: function () { $("#txt_search_sohd").val(''); } }); $("#btn_clear_sohd").click(function (e) { e.preventDefault(); $("#txt_search_sohd").val(''); grid.data("kendoGrid").dataSource.filter({}); }); ////////////////////////////////////////////////// $("#grid_hopdong_ex").empty(); var grid = $("#grid_hopdong_ex").kendoGrid({ excel: { allPages: true }, excelExport: function (e) { e.preventDefault(); var workbook = e.workbook; detailExportPromises = []; var masterData = e.data; for (var rowIndex = 0; rowIndex < masterData.length; rowIndex++) { exportChildData(masterData[rowIndex].HopDong_ID, rowIndex); } $.when.apply(null, detailExportPromises) .then(function () { // get the export results var detailExports = $.makeArray(arguments); // sort by masterRowIndex detailExports.sort(function (a, b) { return a.masterRowIndex - b.masterRowIndex; }); // add an empty column workbook.sheets[0].columns.unshift({ width: 30 }); // prepend an empty cell to each row for (var i = 0; i < workbook.sheets[0].rows.length; i++) { workbook.sheets[0].rows[i].cells.unshift({}); } // merge the detail export sheet rows with the master sheet rows // loop backwards so the masterRowIndex doesn't need to be updated for (var i = detailExports.length - 1; i >= 0; i--) { var masterRowIndex = detailExports[i].masterRowIndex + 1; // compensate for the header row var sheet = detailExports[i].sheet; // prepend an empty cell to each row for (var ci = 0; ci < sheet.rows.length; ci++) { if (sheet.rows[ci].cells[0].value) { sheet.rows[ci].cells.unshift({}); } } // insert the detail sheet rows after the master row [].splice.apply(workbook.sheets[0].rows, [masterRowIndex + 1, 0].concat(sheet.rows)); } // save the workbook kendo.saveAs({ dataURI: new kendo.ooxml.Workbook(workbook).toDataURL(), fileName: "Export.xlsx" }); }); }, dataSource: d, columns: [ { title: "Tên nhà thầu", field: "NhaThau_Ten", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Ngày kí hợp đồng", field: "NgayKy", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Số hợp đồng", field: "MaHD", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Giá trị trước thuế", field: "GiaTriTruocThue", template: "#= OnChangeFormat(GiaTriTruocThue) #", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Giá trị VAT", field: "VAT_HD", template: "#= OnChangeFormat(VAT_HD) #", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Giá trị trước thuế", field: "GiaTriTruocThue", template: "#= OnChangeFormat(GiaTriTruocThue) #", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Số tiền bằng chữ", field: "SoTienBangChu", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Ngày hết hạn", field: "NgayHetHan", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Ngày kế hoạch", field: "NgayKeHoach_NT", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Ngày hiệu lực", field: "NgayHieuLuc", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Nội dung", field: "NoiDung", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Người tạo hợp đồng", field: "NguoiTaoHD", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Ngày tạo hợp đồng", field: "NgayTao", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Loại hợp đồng", field: "LoaiHD_Ten", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Hình thức mua sắm", field: "HinhThucMS_Ten", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Ngày thanh lý", field: "NgayThanhLy", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Số ngày thực hiện", field: "SoNgayThucHien", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Số ngày còn lại", field: "SoNgayConLai", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Giá trị còn lại", field: "GiaTriConLai_HD", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } }, { title: "Tỷ lệ còn lại", field: "TyLeGiaTriConLai", headerAttributes: { class: "header_css" }, attributes: { class: "row_css" } } ], detailInit: function (e) { $("<div/>").appendTo(e.detailCell).kendoGrid({ dataSource: { transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong_CT.aspx", data: { cmd: 'Lay_DS_HopDong_CT', HopDong_ID: e.data.HopDong_ID }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, aggregate: [ { field: "ThanhTien", aggregate: "sum" } ] }, }); }, }); } function Ham_HD_Xuat_Ex() { $("#grid_hopdong_ex").data("kendoGrid").saveAsExcel(); //var ds = $('#grid_hopdong').data("kendoGrid").dataSource; //var rows = [{ // cells: [ // { value: "Tên nhà thầu", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Ngày kí hợp đồng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Số hợp đồng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Giá trị trước thuế", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Giá trị VAT", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Giá trị sau thuế", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Số tiền bằng chữ", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Ngày hết hạn", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Ngày kế hoạch", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Ngày hiệu lực", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Nội dung", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Người tạo hợp đồng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Ngày tạo hợp đồng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Loại hợp đồng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Hình thức mua sắm", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Ngày thanh lý", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, // { value: "Số ngày thực hiện", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" } // ] //}]; //var workbook; ////using fetch, so we can process the data when the request is successfully completed //ds.fetch(function () { // var data = this.data(); // for (var i = 0; i < data.length; i++) { // //push single row for every record // rows.push({ // cells: [ // { // value: data[i].NhaThau_Ten // ,vAlign: "center" // sets the vertical text alignment. // ,hAlign: "center" // sets the horizontal text alignment. // //,background:"#0000ff" //sets the background color of the cell. // ,bold:true //the cell value is displayed in bold. // //,color:"#ff0000"// sets the cell text color. // ,fontName:"Arial" // sets the font used to display the cell value. // //,fontSize // sets the font size of the cell value. // //,italic // the cell value is displayed in italic. // //,underline // the cell value is underlined. // }, // { value: data[i].NgayKy }, // { value: data[i].MaHD }, // { value: OnChangeFormat(data[i].GiaTriTruocThue) }, // { value: OnChangeFormat(data[i].VAT_HD) }, // { value: OnChangeFormat(data[i].GiaTriSauThue) }, // { value: data[i].SoTienBangChu }, // { value: data[i].NgayHetHan}, // { value: data[i].NgayKeHoach_NT }, // { value: data[i].NgayHieuLuc}, // { value: data[i].NoiDung }, // { value: data[i].NguoiTaoHD }, // { value: data[i].NgayTao }, // { value: data[i].LoaiHD_Ten}, // { value: data[i].HinhThucMS_Ten}, // { value: data[i].NgayThanhLy}, // { value: data[i].SoNgayThucHien} // ] // }) // } // workbook = new kendo.ooxml.Workbook({ // sheets: [ // { // freezePane: { // rowSplit: 1, // colSplit: 1 // }, // columns: [ // // Column settings (width) // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true }, // { autoWidth: true } // ], // // Title of the sheet // title: "Danh sách hợp đồng", // // Rows of the sheet // rows: rows // } // ] // }); // //save the file as Excel file with extension xlsx // kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "DanhSachHopDong.xlsx" }); //}); } function exportChildData(key_id, rowIndex) { var deferred = $.Deferred(); detailExportPromises.push(deferred); var rows = [{ cells: [ { value: "Vật tư", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "Số lượng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "Số hợp đồng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "Số lượng khả dụng", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "Đơn giá", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "Đơn vị tính", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "Thành tiền", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "VAT", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" }, { value: "Ghi chú", hAlign: "center", bold: true, background: "#e9ebec", fontName: "Arial" } ] }]; var exporter = new kendo.ExcelExporter({ columns: [ { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Mã tập đoàn", headerAttributes: { class: "header_css" }, field: "MaVatTu_TD", attributes: { class: "row_css", style: "font-weight:bold;" } }, { title: "Số lượng", headerAttributes: { class: "header_css" }, field: "SoLuong", attributes: { class: "row_css" } }, { title: "Số lượng khả dụng", headerAttributes: { class: "header_css" }, field: "SoLuong_KhaDung", attributes: { class: "row_css", style: "font-weight:bold;color:green;" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Thành tiền", headerAttributes: { class: "header_css" }, field: "ThanhTien", template: "#= OnChangeFormat(ThanhTien) #", attributes: { class: "row_css" } }, { title: "VAT", headerAttributes: { class: "header_css" }, field: "VAT", template: "#= OnChangeFormat(VAT) #", attributes: { class: "row_css" } }, { title: "Ghi chú", headerAttributes: { class: "header_css" }, field: "GhiChu", attributes: { class: "row_css" } } ], dataSource: { transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong_CT.aspx", data: { cmd: 'Lay_DS_HopDong_CT', HopDong_ID: key_id }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } } } }); exporter.workbook().then(function (book, data) { deferred.resolve({ masterRowIndex: rowIndex, sheet: book.sheets[0] }); }); } function HienThi_SoNgayConLai(model) { if (model.TinhTrang_HD == 0) { return '<center style="color:red;"><b>' + model.SoNgayConLai + '</b></center>'; } else { return ''; } } function HienThi_TinhTrang(TinhTrang_HD) { if (TinhTrang_HD == 0) { return '<center><span class="label label-success">Hiệu lực</span></center>'; } else { return '<center><span class="label label-important">Thanh lý</span></center>'; } } function Ham_HienThi_VB(value) { if (value == "" || value == null) { return '<center>Chưa upload </center>'; } else { //return '<center><a href= "' + value + '" class="k-button" target="_blank" style="font-size: 0.85em !important;min-width:8px !important;" ><span class="k-icon k-i-seek-s"></span></a></center>'; return '<center><a href= "' + value + '" target="_blank" class="btn btn-inverse" ><i class="fa fa-download"></i></a></center>'; } } function detailInit(e) { detailInit_e = e; var detailRow = e.detailRow; detailRow.find("#tabstrip").kendoTabStrip({ animation: { open: { effects: "fadeIn" } } }); detailRow.find("#tab_VatTu").kendoGrid({ dataSource: { transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_HopDong_CT.aspx", data: { cmd: 'Lay_DS_HopDong_CT', HopDong_ID: e.data.HopDong_ID }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThongKe_HopDong.aspx"; } else { options.success(result); } } }); }, parameterMap: function (options, operation) { if (operation !== "read" && options.models) { return { models: kendo.stringify(options.models) }; } } }, aggregate: [ { field: "ThanhTien", aggregate: "sum" } ] }, sortable: true, columns: [ { title: "Vật tư", headerAttributes: { class: "header_css" }, field: "VatTu_Ten", template: "<div>#= MaVatTu_TD #</div><br><div>#= VatTu_Ten #</div>", attributes: { class: "row_css", style: "font-weight:bold;" }, width: "15%" }, { title: "Số lượng", headerAttributes: { class: "header_css" }, field: "SoLuong", template: "#= OnChangeFormat(SoLuong) #", attributes: { class: "row_css" } }, { title: "Số lượng khả dụng", headerAttributes: { class: "header_css" }, field: "SoLuong_KhaDung", template: "#= OnChangeFormat(SoLuong_KhaDung) #", attributes: { class: "row_css", style: "font-weight:bold;color:green;" } }, { title: "Đơn giá", headerAttributes: { class: "header_css" }, field: "DonGia", template: "#= OnChangeFormat(DonGia) #", attributes: { class: "row_css" } }, { title: "Đơn vị tính", headerAttributes: { class: "header_css" }, field: "TenDVT", attributes: { class: "row_css" } }, { title: "Thành tiền trước thuế", headerAttributes: { class: "header_css" }, field: "ThanhTien", template: "#= OnChangeFormat(ThanhTien) #", attributes: { class: "row_css" }, aggregates: ["sum"], footerTemplate: "<div class=\"row_css\">#=OnChangeFormat(sum) #</div>", groupFooterTemplate: "<div class=\"row_css\">#=OnChangeFormat(sum) #</div>", width: "15%" }, { title: "VAT", headerAttributes: { class: "header_css" }, field: "VAT", template: "#= OnChangeFormat(VAT) #", attributes: { class: "row_css" }, width: "14%" }, { title: "Ghi chú", headerAttributes: { class: "header_css" }, field: "GhiChu", attributes: { class: "row_css" } } ] }); }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* forget.js :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdalil <mdalil@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/06 21:14:13 by mayday #+# #+# */ /* Updated: 2019/08/08 22:57:11 by mdalil ### ########.fr */ /* */ /* ************************************************************************** */ function createRecuperationMailView() { const feed = document.getElementById("feed"); const element = document.createElement("div"); const commentbox = document.createElement("div"); const form_list = [ {id: "mail", type: "text", text: "Mail"}, {id: "send_mail", type: "button", value: "send", onclick: "accountAction('send_recuperation_mail', this.form)"} ]; const form = generateForm(form_list); element.id = "element"; commentbox.id = "commentbox"; commentbox.appendChild(form); element.appendChild(commentbox); feed.appendChild(element); } function createRecuperationPasswordView(params) { const feed = document.getElementById("feed"); const element = document.createElement("div"); const commentbox = document.createElement("div"); const form_list = [ {id: "password", type: "password", text: "Password"}, {id: "password_confirm", type: "password", text: "Password confirm"}, {id: "user_id", type: "hidden", value: params.get("user_id")}, {id: "confirm", type: "hidden", value: params.get("confirm")}, {id: "send_password", type: "button", value: "send", onclick: "accountAction('send_new_password', this.form)"} ]; const form = generateForm(form_list); element.id = "element"; commentbox.id = "commentbox"; commentbox.appendChild(form); element.appendChild(commentbox); feed.appendChild(element); }
 angular.module('ngApp.home').controller('homeairlineULDEditController', function ($scope, $uibModal, $location, $log, $sce, $document, adminPopupIn, config) { $scope.airlineULD = {}; init(); function init() { $scope.airlineULD = adminPopupIn; $scope.ImgPath = config.BUILD_URL; } });
/** * Created by nnnyyy on 2018-11-28. */ 'use strict'; const SAVEFLAG = { SFLAG_INC_POINT: 0X01, SFLAG_MAX_COMBO: 0x02 }; class User { constructor(socket) { this.socket = socket; this.quizCombo = 0; this.saveFlag = 0; this.maxCombo = 0; this.incPoint = 0; this.lastQuizObjectStr = ""; } static getSaveFlag() { return SAVEFLAG; } } module.exports = User;
/** * php-task.js * ============ * Optimize the index.php file. * */ module.exports = (gulp, plugins, config) => { gulp.task('php', () => { const baseUrl = config.tools.browsersync.proxy.target.replace(/localhost:\d+/, 'localhost:' + config.tools.browsersync.port) + config.globs.folders.dest.root; const styleUrl = (config.debug) ? baseUrl + 'style.css' : '<?php bloginfo("stylesheet_url"); ?>'; const scriptUrl = (config.debug) ? baseUrl + 'js/bundle.js' : '<?php bloginfo("template_url"); ?>/js/bundle.js'; const options = { htmlmin: { removeComments: true, collapseWhitespace: true, collapseBooleanAttributes: true, removeAttributeQuotes: true, removeRedundantAttributes: true, removeEmptyAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, removeOptionalTags: true }, injectTags: { style: `<script type="text/javascript">var head=document.getElementsByTagName("head")[0],stylesheet=document.createElement("link");stylesheet.rel="stylesheet",stylesheet.type="text/css",stylesheet.href="${styleUrl}",stylesheet.media="non-existant-media",head.appendChild(stylesheet,head.firstChild),setTimeout(function(){stylesheet.media="all"});</script>`, script: `<script src="${scriptUrl}" async></script>` } }; return gulp.src(config.globs.php.src) .pipe(plugins.newer(config.globs.php.dest)) .pipe(plugins.replace('<!-- [inject:style] -->', options.injectTags.style)) .pipe(plugins.replace('<!-- [inject:script] -->', options.injectTags.script)) .pipe(!config.debug ? plugins.htmlmin(options.htmlmin) : plugins.util.noop()) .pipe(gulp.dest(config.globs.php.dest)).on('end', plugins.browserSync.reload); }); };
import global from './global'; export function submitRegister( version, mobile, password, email, first_name, last_name, birthday, gender, city_id, district_id, address, service_charge, machine_type, experience, work_done ) { let url; url = global.BASE_URL+`/do_register.api?version=${version}&mobile=${mobile}&password=${password}&email=${email}&first_name=${first_name}&last_name=${last_name}&last_name=${last_name}&birthday=${birthday}&gender=${gender}&city_id=${city_id}&district_id=${district_id}&address=${address}&service_charge=${service_charge}&machine_type=${machine_type}&experience=${experience}&work_done=${work_done}`; console.log(url); return fetch(url) .then(res => res.json()); }; export function updateMember( id, mobile, email, first_name, last_name, birthday, gender, city_id, district_id, address, service_charge, machine_type, experience, work_done ) { let url; url = global.BASE_URL+`/update_member.api?id=${id}&mobile=${mobile}&email=${email}&first_name=${first_name}&last_name=${last_name}&last_name=${last_name}&birthday=${birthday}&gender=${gender}&city_id=${city_id}&district_id=${district_id}&address=${address}&service_charge=${service_charge}&machine_type=${machine_type}&experience=${experience}&work_done=${work_done}`; console.log(url); return fetch(url) .then(res => res.json()); }; export function submitLogin (username, password, token, version, latitude, longitude) { let url; url = global.BASE_URL+`/do_login.api?username=${username}&password=${password}&token=${token}&version=${version}&latitude=${latitude}&longitude=${longitude}`; console.log(url); return fetch(url) .then(res => res.json()); }; export function getCalledList(guest_id, page){ let url; url = global.BASE_URL+`/get_called_list.api?guest_id=${guest_id}&page=${page}`; console.log(url); return fetch(url) .then(res => res.json()); }; export function getWorksMeasure(tech_id, page){ let url; url = global.BASE_URL+`/get_works_measure.api?tech_id=${tech_id}&page=${page}`; console.log(url); return fetch(url) .then(res => res.json()); }; export function getStaticsDetail(id){ let url; url = global.BASE_URL+`/get_statics_detail.api?id=${id}`; console.log(url); return fetch(url) .then(res => res.json()); }; export function requestVIP (member_id) { let url; url = global.BASE_URL+`/request_vip.api?member_id=${member_id}`; console.log(url); return fetch(url) .then(res => res.json()); }; export function getMemberInfo (id) { let url; url = global.BASE_URL+`/get_member_info.api?id=${id}`; console.log(url); return fetch(url) .then(res => res.json()); };
import React from 'react'; import Item from './Item.js'; function ItemPage(props) { return ( <div className="itemPage"> <ul> { props.items.map((item) => <li key={item.id}> <Item title={item.name} description={item.description} price={item.price}> <button type="button" className="buttonAddToCart" onClick={() => props.addItemToCart(item.id)}>Add to Cart</button> </Item> </li> ) } </ul> </div> ); } export default ItemPage;
import React from 'react'; import FA from 'react-fontawesome'; import { Link } from "react-router-dom"; export default class WorkpieceItem extends React.Component { render() { var color var form var order var date switch(this.props.item.color.actualValue == null ? this.props.item.color.toValue : this.props.item.color.actualValue ) { case "Orange": color = "orange" break; case "Blau": color = "blue" break; default: color = "blue" } switch(this.props.item.shape.actualValue == null ? this.props.item.shape.toValue : this.props.item.shape.actualValue ) { case "Kreis": form = ( <div> <FA name="circle" size="3x" style={{"color":color}}/> </div> ) break; case "Viereck": form = ( <div> <FA name="square" size="3x" style={{"color":color}}/> </div> ) break; case "Dreieck": form = ( <div> <FA name="play" className="fa-rotate-270" size="3x" style={{"color":color}}/> </div> ) break; default: form = ( <div> <FA name="question-circle" size="3x" style={{"color":color}}/> </div> ) } if(this.props.item.hasOwnProperty('order')){ order = <FA name="shopping-cart" size="2x"/> } else { order = <FA name="shopping-cart" size="2x" className="text-muted"/> } date = this.props.item.createdAt date = new Date(date).toLocaleString(); var linkDetails = "/admin/workpieces/" + this.props.item._id var linkMap = "/admin/map?id=" + this.props.item._id var linkEdit = "/admin/webnfc/" + this.props.item._id var main = ( <li className="list-group-item d-flex align-items-center mb-2"> <div className="container"> <div className="row"> <div className="col-2 col-sm-1 my-auto"> {form} </div> <div className="col-5 col-sm-4 col-md-3 col-lg-2 my-auto"> <span>{this.props.item.state.message}</span> </div> <div className="col-sm-2 col-md-1 my-auto d-none d-sm-block"> {order} </div> <div className="col-3 my-auto d-none d-md-block"> <span>{this.props.item.workpieceId}</span> </div> <div className="col-2 my-auto d-none d-lg-block"> <span>{date}</span> </div> <div className="col-sm-1 my-auto d-none d-sm-block"> <Link to={linkMap}><FA name="map" size="2x"/></Link> </div> <div className="col-3 col-sm-3 col-md-2 col-lg-1 my-auto"> <Link to={linkEdit}><FA name="tag" size="2x"/></Link> </div> <div className="col-2 col-sm-1 my-auto"> <Link to={linkDetails} className="nav-link float-right mr-2 p-0" ><FA name="search" size="2x"/></Link> </div> </div> </div> </li> ) return(main) } }
import io from 'socket.io-client'; export default function socketio(hash) { const socket = io(`${WARHOL_HOST}:${WARHOL_PORT}`, { query: { hash, sessionId: window.localStorage.getItem('sessionId'), }, }); return socket; }
import { getOffset, getFontSize } from '../dom-manipulations' import { objExtend } from '../../extensions/obj-extensions' /** * @typedef {Object} AnimationOptions * @property {number} [division=100] number of frames to execute. */ /** * * @type {AnimationOptions} */ const defaultAnimationOptions = { division: 100 } /** * @typedef {AnimationOptions} FadeInOptions * @property {string} [display='block'] */ /** * * @type {FadeInOptions} */ const defaultFadeInOptions = { ...defaultAnimationOptions, display: 'block', } /** * Progressively fade in an element in n frame. * @param {!Element} elem * @param {FadeInOptions} [options={display: 'block', division: 60}] * @return {CancelablePromise} */ export const fadeIn = (elem, options=defaultFadeInOptions) => { const { display, division } = objExtend({}, defaultFadeInOptions, options) elem.style.opacity = 0 elem.style.display = display const increment = 1 / division let canceled = false const promise = new Promise((resolve, reject) => { const fade = () => { if (canceled) return reject({error: 'canceled', message: 'fadeIn was canceled'}) let value = parseFloat(elem.style.opacity) + increment if (value <= 1) { elem.style.opacity = value requestAnimationFrame(fade) } else { resolve(division) } } fade() }) return { promise, cancel: () => canceled = true } } /** * Progressively fade out an element in n frame. * @param {!Element} elem * @param {AnimationOptions} [options] * @return {CancelablePromise} */ export const fadeOut = (elem, options=defaultAnimationOptions) => { const { division } = {...defaultAnimationOptions, ...options} elem.style.opacity = 1 const increment = 1 / division let canceled = false const promise = new Promise((resolve, reject) => { const fade = () => { if (canceled) return reject({error: 'canceled', message: 'fadeOut was canceled'}) if ((elem.style.opacity -= increment) <= 0) { elem.style.display = 'none' resolve() } else { requestAnimationFrame(fade) } } fade() }) return { promise, cancel: () => canceled = true } } /** * @typedef {AnimationOptions} MoveOutOptions * @property {number} [height=100] * @property {number} [width=100] */ /** * * @type {MoveOutOptions} */ const defaultMoveOptions = { height: 100, width: 100, division: 100 } /** * Move an element for height and width value. * @param {!Element} elem * @param {MoveOutOptions} [options={height: 100, width: 100, division: 100}] * @return {CancelablePromise} */ export const moveOut = (elem, options=defaultMoveOptions) => { const { height, width, division } = {...defaultMoveOptions, ...options} const moveHeight = height / division const moveWidth = width / division const offsets = getOffset(elem) const destinationX = offsets.left + width const destinationY = offsets.top + height elem.style.position = 'absolute' let canceled = false const promise = new Promise((resolve, reject) => { const move = () => { if (canceled) return reject({error: 'canceled', message: 'fadeOut was canceled'}) let endX = false, endY = false const { left, top } = getOffset(elem) if (left < destinationX) elem.style.left = left + moveWidth + 'px' else endX = true if (top < destinationY) elem.style.top = top + moveHeight + 'px' else endY = true if (!endX || !endY) requestAnimationFrame(move) else resolve() } move() }) return { promise, cancel: () => canceled = true} } /** * Deflate an element, making it disappear in n frames. * @param {!Element} elem * @param {AnimationOptions} [options] * @return {CancelablePromise} */ export const deflate = (elem, options=defaultAnimationOptions) => { const { division } = {...defaultAnimationOptions, ...options} const decrementX = Math.ceil(elem.offsetWidth / division) const decrementY = Math.ceil(elem.offsetHeight / division) const decrementFont = Math.ceil(getFontSize(elem) / division) elem.style.height = elem.offsetHeight + 'px' let canceled = false const promise = new Promise((resolve, reject) => { const defl = () => { if (canceled) return reject({error: 'canceled', message: 'fadeOut was canceled'}) let endX = false, endY = false if (elem.offsetWidth > 0) { elem.style.width = (elem.offsetWidth - decrementX) + 'px' } else { endX = true } if (elem.offsetHeight > 0) { elem.style.height = (elem.offsetHeight - decrementY) + 'px' } else { endY = true } elem.style.fontSize = (getFontSize(elem) - decrementFont) + 'px' if (!endX || !endY) { requestAnimationFrame(defl) } else { resolve() } } defl() }) return { promise, cancel: () => canceled = true } } /** * First param given to {@link AnimateAction} function call. * @typedef {Object} AnimationPayload * @property {?number} last if null, first call * @property {?number} current timestamp from requestAnimationFrame * @property {number} i number of times the animation ran. */ /** * @typedef {Object} AnimateAction * @property {!function(t: AnimationPayload, ...args: *):boolean} animation callback to requestAnimationFrame * @property {Array<*>} [args] */ /** * @typedef {Object} AnimateOptions * @property {boolean} [single=false] * @property {number} [repeat=100] * @property {boolean} [infinite=false] if infinite you must return true from a AnimateAction */ /** * * @type {AnimateOptions} */ const defaultAnimateOptions = { single: false, repeat: 100, infinite: false } /** * * @param {!Array<AnimateAction>} animations * @param {AnimateOptions} [options] * @return {CancelablePromise} */ export const animate = (animations, options=defaultAnimateOptions) => { let canceled = false, ts const { single, repeat, infinite } = objExtend({}, defaultAnimateOptions, options) const promise = new Promise((resolve, reject) => { if (infinite && !single) return reject({ error: 'invalid_option', message: 'Infinite can only be true with single.' }) let i = 0, handle const end = single ? repeat : animations.length const first = animations[0] handle = (timestamp) => new Promise((res, rej) => { if (canceled) rej({error: 'canceled'}) else if (!infinite && i >= end) resolve(i) else { const { animation, args } = single ? first : animation[i] const a = args || [] const stop = animation({last: ts, current: timestamp, i}, ...a) ts = timestamp if (!stop) { i++ res() } else { reject({error: 'animate_stop', frame: i}) } } }).then(() => requestAnimationFrame(handle)).catch(reject) requestAnimationFrame(handle) }) return { promise, cancel: () => canceled = true } }