text
stringlengths
7
3.69M
const Spritesmith = require('spritesmith'), fs = require("fs"); const helpers = ` @mixin sprite-width($sprite) { width: nth($sprite, 5); } @mixin sprite-height($sprite) { height: nth($sprite, 6); } @mixin sprite-position($sprite) { $sprite-offset-x: nth($sprite, 3); $sprite-offset-y: nth($sprite, 4); background-position: $sprite-offset-x $sprite-offset-y; } @mixin sprite-image($sprite) { $sprite-image: nth($sprite, 9); background-image: url(#{$sprite-image}); } @mixin sprite($sprite) { @include sprite-image($sprite); @include sprite-position($sprite); @include sprite-width($sprite); @include sprite-height($sprite); } @mixin sprites($sprites) { @each $sprite in $sprites { $sprite-name: nth($sprite, 10); .#{$sprite-name} { @include sprite($sprite); } } } `; function _generatePartialSCSS(filename,params,image,filePath,prefixName) { const name = prefixName + filename.split("\\").pop().split("/").pop().split(".").shift(); return ` $${name}-name: '${name}'; $${name}-x: ${params.x}px; $${name}-y: ${params.y}px; $${name}-offset-x: ${-params.x}px; $${name}-offset-y: ${-params.y}px; $${name}-width: ${params.width}px; $${name}-height: ${params.height}px; $${name}-total-width: ${image.width}px; $${name}-total-height: ${image.height}px; $${name}-image: '${filePath}'; $${name}: (${params.x}px, ${params.y}px, ${-params.x}px, ${-params.y}px, ${params.width}px, ${params.height}px, ${image.width}px, ${image.height}px, '${filePath}', '${name}', ); `; } function generateSCSS(imagesDirectory,spriteFilename,prefixName,padding=0){ Spritesmith.run({ src: fs.readdirSync(imagesDirectory).filter((s)=>s.indexOf("png")!==-1).map((s)=>imagesDirectory+'/'+s), padding: padding }, function handleResult(err, result) { if(err) { console.error(err); process.exit(1); } let str=``, names=[]; fs.writeFileSync(__dirname + `/../src/sass/generated/${spriteFilename}`,result.image) ; for(const i in result.coordinates){ if(result.coordinates.hasOwnProperty(i)){ str+=_generatePartialSCSS(i,result.coordinates[i],result.properties,`./generated/${spriteFilename}`,prefixName); names.push(`$${prefixName}` + i.split("\\").pop().split("/").pop().split(".").shift()); } } str+=` $spritesheet-width: ${result.properties.width}px; $spritesheet-height: ${result.properties.height}px; $spritesheet-image: './${spriteFilename}'; $spritesheet-sprites: (${names.join(', ')}, ); $spritesheet: (${result.properties.width}px, ${result.properties.height}px, './generated/${spriteFilename}', $spritesheet-sprites, ); `; fs.writeFileSync(__dirname + `/../src/sass/generated/${spriteFilename.replace(/\.\w+$/,'.scss')}`,str+helpers) ; console.log(`spriteFilename done.`); }); } generateSCSS(__dirname + '/../src/images/ships','ship-sprite.png','ship'); //4px should prevent stupid overlapping in browser. haha chrome. generateSCSS(__dirname + '/../src/images/locks','ship-locks.png', 'lock', 4);
$(document).ready(function () { $(window).load(function () { $('#preloader').fadeOut(200);//1500 é a duração do efeito (1.5 seg) }); $('.tgl').css('display', 'block') $('#MinMax').hide(); if ($("#list tr").length > 2) { $('.tgl').css('display', 'none') $('#MinMax').show(); } $('.span', '#box-toggle').click(function () { $(this).next().slideToggle('slow') .siblings('.tgl:visible').slideToggle('fast'); // aqui começa o funcionamento do plugin $('#MinMax').hide(); }); //get the height and width of the page var window_width = $(window).width(); var window_height = $(window).height(); $('.iframePrincipal').height = window_height; //vertical and horizontal centering of modal window(s) /*we will use each function so if we have more then 1 modal window we center them all*/ $('.modal_window').each(function () { //get the height and width of the modal var modal_height = $(this).outerHeight(); var modal_width = $(this).outerWidth(); //calculate top and left offset needed for centering var top = (window_height - modal_height) / 2; var left = (window_width - modal_width) / 2; //apply new top and left css values $(this).css({'top': top+300, 'left': left}); }); $('.activate_modal_contrato').click(function () { //get the id of the modal window stored in the name of the activating element var name = $(this).attr('name'); name = name.split("/"); var modal_id = name[0]; //use the function to show it $('iframe').attr("src","https://www.cambiobancopaulista.com.br/v2/comercial/contratos/show_contract_admin/"+name[1]); show_modal(modal_id); }); $('.activate_modal_cliente').click(function () { //get the id of the modal window stored in the name of the activating element var name = $(this).attr('name'); name = name.split("/"); var modal_id = name[0]; //use the function to show it $('iframe').attr("src","https://www.cambiobancopaulista.com.br/v2/comercial/clientes/show_cliente_admin/"+name[1]); show_modal(modal_id); }); $('.close_modal').click(function () { //use the function to close it close_modal(); }); //THE FUNCTIONS function close_modal() { //$('.marquee').show(); //hide the mask $('#mask').fadeOut(500); //hide modal window(s) $('.modal_window').fadeOut(500); $('iframe').attr("src", ""); $('#mask').css({'display': 'none', opacity: 0}); } function show_modal(modal_id) { //set display to block and opacity to 0 so we can use fadeTo //$('.marquee').hide(); $('#mask').css({'display': 'block', opacity: 0}); //fade in the mask to opacity 0.8 $('#mask').fadeTo(500, 0.8); //show the modal window $('#' + modal_id).fadeIn(500); } });
function TRS (spec) { this.host = spec.host; this.url = 'http://' + spec.host; this.trsAddr = ''; this.stbId = ''; this.send = function (u, body, b, callback) { // callback (err, resp) var host = this.host; if(!host) { if (typeof callback === 'function') callback(401, 'host are required!!'); return; } var url = ''; if (b) { url = 'http://' + this.trsAddr + u; } else { url = this.url + u; } console.log(url); var req = new XMLHttpRequest(); req.onreadystatechange = function () { if (req.readyState == '4') { switch (req.status) { case 100: case 200: case 201: case 202: case 203: case 204: case 205: if (typeof callback === 'function') callback(req.status, req.responseText); break; default: if (typeof callback === 'function') callback(req.status, req.responseText); } } }; //console.log(url); if (body) { //console.log('POST'); req.open('POST', url, true); //req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); req.send(JSON.stringify(body)); } else { //console.log('GET'); req.open('GET', url, true); req.send(); } }; } //XmlHttpRequest对象 function createXmlHttpRequest(){ if(window.ActiveXObject){ //如果是IE浏览器 return new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){ //非IE浏览器 return new XMLHttpRequest(); } } TRS.init = function (host) { return new TRS({ host: host }); }; TRS.prototype.getServer = function (phoneid, callback) { var url = '/GetServer/phone?phoneid=' + phoneid; this.send(url, null, false, callback); }; TRS.prototype.screen = function (body, callback){ var url = '/phone/screen'; this.send(url, body, true, callback); } TRS.prototype.getStbid = function (phoneid, callback){ var url = '/phone/GetStbid?phoneid=' + phoneid; this.send(url, null, false, callback); } TRS.prototype.transferMsg = function(body, callback){ //{“id”:”111”, “recid”:”222”} var url = '/transfermsgPost'; this.send(url, body, true, callback); } /*TRS.prototype.bindStb = function (phoneid, stbid, callback) { var url = '/phone/bindStb'; var body = {phoneid:phoneid, stbid:stbid}; this.send(url, body, callback); };*/
const { Sequelize, DataTypes } = require('sequelize'); const sequelize = require('../sequalize/dbConnection') const sq = sequelize.sequelize; exports.Testimonials = sq.define('Testimonials', { client_name: { type: DataTypes.STRING, allowNull: false }, image: { type: DataTypes.STRING, allowNull: false }, company: { type: DataTypes.STRING, allowNull: false }, description: { type: DataTypes.STRING, allowNull: false } })
var slidenumber=1; var timer1=0; var timer2=0; function slideright() { clearTimeout(timer1); clearTimeout(timer2); slidenumber= slidenumber; if (slidenumber>5) slidenumber=1; hide(); setTimeout("changeslide()",500); } function sliderleft() { clearTimeout(timer1); clearTimeout(timer2); slidenumber= slidenumber-2; if(slidenumber=0) slidenumber=5; hide(); setTimeout("changeslide()",500); } function hide() { $("#slider").fadeOut(500); } function changeslide() { slidenumber++;if(slidenumber>5) slidenumber=1; var slide="<img src=\"pics/"+slidenumber+".jpg\" style=\"width:780px;\"/>" document.getElementById("slider").innerHTML=slide; $("#slider").fadeIn(500); timer1=setTimeout("changeslide()",4000); timer2=setTimeout("hide()",3500); }
//Copyright 2012, John Wilson, Brighton Sussex UK. Licensed under the BSD License. See licence.txt var STATE_WAITING = 0 ; var STATE_RUNNING = 1 ; var STATE_FINISHED = 2 ; function Event(startTime,endTime,eventObj,eventParam) { this._state = STATE_WAITING ; this._runtime = 0 ; this._starttime = startTime ; this._duration = endTime-startTime ; this._eventObj = eventObj ; this._eventParam = eventParam ; this.className = 'Event' ; } Event.prototype = { constructor: Event, StartEvent: function() { this._eventObj.StartEvent() ; }, Running: function() { var nTime = this._runtime/this._duration ; this._eventObj.Running(nTime) ; }, EndEvent: function() { this._eventObj.EndEvent() ; }, IsFinished: function() { return (this._state == STATE_FINISHED) ; }, toString: function() { return "Event Debug() "+this._starttime+","+this._duration+","+this._runtime+","+this._state ; }, Update: function(ctime,dt) { var sstate = this._state if (sstate == STATE_WAITING) { if (ctime >= this._starttime) { this._runtime = 0.0 ; this.StartEvent() ; if (this._duration == 0) { this._state = STATE_FINISHED ; } else { this._state = STATE_RUNNING ; } } } else if (sstate == STATE_RUNNING) { this._runtime = this._runtime + dt ; if (this._runtime <= this._duration) { this.Running() ; } else { this.EndEvent() ; this._state = STATE_FINISHED ; } } } }
/*require配置:定义js文件路径*/ require.config({ paths: { jquery: 'lib/jquery', swiper:'lib/swiper', ejs: 'lib/ejs_production' } }); var back2top; var logout; require(["main","swiper"],function(){ var load_home=function(){ // alert(1); M.loading(); M.get('/index/home/'+city.city_id,{},function(data){ //alert(data); var home_page=$("#home_page").html(); var html = new EJS({url: '/ejs_template/index.ejs'}).render(home_page,data); $("#home_page").html(html); var swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', paginationClickable: true, spaceBetween: 30, centeredSlides: true, autoplay: 2500, autoplayDisableOnInteraction: false }); $(".swiper-slide").click(function(){ location='/detail?commodityid='+$(this).data("cid"); }); $(".recommend>div").click(function(){ location='/detail?commodityid='+$(this).data("cid"); }) $(".category>.col-md-3").click(function(){ location='list?typeid='+$(this).data("typeid")+'&is_top=0'; }); $(".bar_top").click(function(){ location='list?typeid='+$(this).data("typeid")+'&is_top=1'; }); setTimeout(function(){ M.loadingEnd();},200); M.renderImg('div'); }); } var currentCity=h5session_get("currentCity"); if(null==currentCity){ // h5session_set("currentCity",{}) var city={ city_name:"南通市", city_id:"320600" } h5session_set("currentCity",JSON.stringify(city)); $(".logo h5").html('南通市<i class="fa fa-chevron-down"></i>'); load_home(); }else{ var city=JSON.parse(currentCity); $(".logo h5").html(city.city_name+'<i class="fa fa-chevron-down"></i>'); load_home(); } back2top=function(){ $('body,html').animate({scrollTop:0},1000); } logout=function(){ if(sessionStorage.length){ sessionStorage.clear(); } location.href='/'; } $(".logo h5").click(function(){ location.href='/arealist'; }); //render page var footer_menu=$(".footer-menu").html(); var user=JSON.parse(h5session_get("user")); // var user = [{name:'张三', age:13, address:'北京'}]; var html = new EJS({url: '/ejs_template/bottom_bar.ejs'}).render(footer_menu,{user:user}); $(".footer-menu").html(html); $("#searchbutt").click(function(){ var keyword=encodeURI(encodeURI($("#keyword").val().trim())); location.href='/searchlist?keyword='+keyword; }); });
; (function (doc, tpl, tools) { // console.log(tools) // console.log(tpl) function MyTab(el) { this.el = doc.querySelector(el); this.data = JSON.parse(this.el.getAttribute('data')); this._index = 0; this.init(); } //init启动 MyTab.prototype.init = function () { //需要渲染 render this._render(); //绑定事件处理函数 this._bindEvent(); } MyTab.prototype._render = function () { var tabWrapper = doc.createElement('div'); var pageWrapper = doc.createElement('div'); //createdocumentfragment()方法创建了一虚拟的节点对象,节点对象包含所有属性和方法 var oFrag = doc.createDocumentFragment(); tabWrapper.className = 'tab-wrapper'; pageWrapper.className = 'page-wrapper'; this.data.forEach(function (item, index) { tabWrapper.innerHTML += tools.tplReplace(tpl.tab('tab'), { tab: item.tab, current: !index ? 'current' : ' ' }); pageWrapper.innerHTML += tools.tplReplace(tpl.tab('page'), { page: item.page, current: !index ? 'current' : ' ' }); }); oFrag.appendChild(tabWrapper); oFrag.appendChild(pageWrapper); this.el.appendChild(oFrag) // console.log(tabWrapper,pageWrapper); } MyTab.prototype._bindEvent = function () { var doms = { oTabItems: doc.querySelectorAll('.tab-item'), oPageItems: doc.querySelectorAll('.page-item') } this.el.addEventListener('click', this._handleTabClick.bind(this, doms), false); } MyTab.prototype._handleTabClick = function () { console.log(arguments); var _doms = arguments[0], tar = arguments[1].target, className = tar.className.trim(); if (className === 'tab-item') { _doms.oTabItems[this._index].className = 'tab-item'; _doms.oPageItems[this._index].className = 'page-item'; this._index = [].indexOf.call(_doms.oTabItems, tar) // console.log(this._index) tar.className += ' current'; _doms.oPageItems[this._index].className += ' current' } // console.log(_doms,tar,className) } window.MyTab = MyTab; })(document, tpl, tools);
var ExtractTextPlugin = require('extract-text-webpack-plugin'); var precss = require('precss'); module.exports = { context: __dirname + '/client', entry: ['./index.coffee', './index.css'], output: { filename: 'bundle.js', path: __dirname + '/public' }, module: { loaders: [ { test: /\.coffee$/, loader: "coffee-loader" }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader') } ] }, postcss: function () { return { defaults: [precss] } }, plugins: [ new ExtractTextPlugin('[name].css') ] }
/* Primitivos (imutáveis) - string, number, boolean, undefined, null, bigint e symbol -> Valor Referência (mutável) - array, object e function -> Passados por referência */ const personOne = { name: 'Robson', surname: 'Soares', }; const personTwo = {...personOne}; personOne.name = 'João' console.log(personOne); console.log(personTwo); // let a = [1, 2, 3]; // let b = [...a]; // let c = b; // console.log(a, b); // a.push(4); // console.log(a, b); // b.pop(); // console.log(a, b); // a.push('Luiz'); // console.log(a, c); // let a = 'A'; // let b = a; // Cópia // console.log(a, b); // a = 'Outra coisa'; // console.log(a, b) // let personName = 'Rob'; // personName[0] = 'L'; // console.log(personName[0]);
const { createContext, useContext, useState } = require("react"); export const ProfileContext = createContext(); export function ProfileProvider() { const [profile, setProfile] = useState(null); if (profile?.access_token) { localStorage.setItem("access_token", profile.access_token); return { profile, setProfile }; } const access_token = localStorage.getItem("access_token"); if (access_token) setProfile({ ...profile, access_token }); return { profile, setProfile }; } export function useProfile() { const { profile, setProfile } = useContext(ProfileContext); return { profile, setProfile }; }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { resetError } from 'robScoreCleanup/actions/Errors'; import { fetchMetricOptions } from 'robScoreCleanup/actions/Metrics'; import { fetchScoreOptions } from 'robScoreCleanup/actions/Scores'; import { fetchStudyTypeOptions } from 'robScoreCleanup/actions/StudyTypes'; import { fetchItemScores, clearItemScores, updateEditMetricIfNeeded } from 'robScoreCleanup/actions/Items'; import ScrollToErrorBox from 'shared/components/ScrollToErrorBox'; import MetricForm from 'robScoreCleanup/containers/MetricForm'; import MetricSelect from 'robScoreCleanup/containers/MetricSelect'; import ScoreList from 'robScoreCleanup/containers/ScoreList'; import ScoreSelect from 'robScoreCleanup/containers/ScoreSelect'; import StudyTypeSelect from 'robScoreCleanup/containers/StudyTypeSelect'; import './EditForm.css'; class EditForm extends Component { constructor(props) { super(props); this.loadMetrics = this.loadMetrics.bind(this); this.clearMetrics = this.clearMetrics.bind(this); this.state = { config: { display: 'all', isForm: 'false', riskofbias: { id: 0, }, }, }; } componentWillMount() { this.props.dispatch(fetchMetricOptions()); this.props.dispatch(fetchScoreOptions()); this.props.dispatch(fetchStudyTypeOptions()); } clearMetrics(e) { e.preventDefault(); this.props.dispatch(resetError()); this.props.dispatch(clearItemScores()); } loadMetrics(e) { e.preventDefault(); this.props.dispatch(resetError()); this.props.dispatch(fetchItemScores()); this.props.dispatch(updateEditMetricIfNeeded()); } submitForm(e) { e.preventDefault(); } render() { let { error } = this.props, { config } = this.state; return ( <div> <ScrollToErrorBox error={error} /> <div className='container-fluid cleanStudyMetricForm' > <div className='span6'> <MetricSelect /> <div> <button className='btn btn-primary space' onClick={this.loadMetrics}> Load responses </button> <button className='btn space' onClick={this.clearMetrics}> Hide currently shown responses </button> </div> </div> <div className='span6 container-fluid'> <div className='span6'> <ScoreSelect /> </div> <div className='span6'> <StudyTypeSelect /> </div> <p className='help-block'>To de-select a filter, click on the filter while holding ⌘ on Mac or Control on Windows</p> </div> </div> <MetricForm config={config} /> <ScoreList config={config} /> </div> ); } } function mapStateToProps(state){ const { error } = state; return { error, }; } export default connect(mapStateToProps)(EditForm);
const express = require("express"); const router = express.Router(); const petOwnerData = require("../data/petOwner"); const multer = require("multer"); const zipcodes = require("zipcodes"); /* required for multer --> */ const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "public/images/users"); }, filename: function (req, file, cb) { cb(null, Date.now() + "-" + file.originalname.replace(" ", "_")); }, }); const upload = multer({ storage: storage }); /* <-- required for multer */ //GET --> returns the user document router.get("/", async (req, res) => { try { if (req.session.user) { var email = req.body.userData.email; const petOwner = await petOwnerData.getPetOwnerByUserEmail(email); // console.log(petOwner); // //checking if user has given any shelter reviews if (petOwner.shelterReviewsGiven.length != 0) { try { const shelterReviewsInfo = await petOwnerData.getShelterReviews( petOwner._id ); petOwner.shelterReviewsGivenArray = shelterReviewsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } //checking if user has any favorite pets if (petOwner.favoritedPets.length != 0) { try { const userFavoritePetsInfo = await petOwnerData.getUserFavoritePets( petOwner.favoritedPets ); petOwner.favoritedPetsArray = userFavoritePetsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } res.status(200).render("users/petOwner", { petOwner, pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", }); } } catch (e) { res.status(e.status).send({ error: e.error }); return; } }); //POST --> Updates the user profile picture router.post( "/changeProfileImage", upload.single("profilePicture"), async (req, res) => { const imageData = req.body; // console.log(req.body); var email = req.session.user.email; const petOwner = await petOwnerData.getPetOwnerByUserEmail(email); // console.log(petOwner); // //checking if user has given any shelter reviews if (petOwner.shelterReviewsGiven.length != 0) { try { const shelterReviewsInfo = await petOwnerData.getShelterReviews( petOwner._id ); petOwner.shelterReviewsGivenArray = shelterReviewsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } //checking if user has any favorite pets if (petOwner.favoritedPets.length != 0) { try { const userFavoritePetsInfo = await petOwnerData.getUserFavoritePets( petOwner.favoritedPets ); petOwner.favoritedPetsArray = userFavoritePetsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } if (!req.file) { res.status(500).render("users/petOwner", { petOwner, status: "failed", error: "you must provide a picture", pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", }); return; } imageData.profilePicture = req.file.filename; let petOwnerDetails; try { petOwnerDetails = await petOwnerData.updateProfileImage( email, imageData.profilePicture ); res.status(200).render("users/petOwner", { petOwner: petOwnerDetails, status: "success", alertMessage: "Profile Picture Updated Successfully.", pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", }); } catch (e) { res.status(500).render("users/petOwner", { petOwner: petOwnerDetails, status: "failed", alertMessage: "Profile Picture Update Failed. Please try again.", pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", }); } } ); //handles change password request router.post("/changePassword", async (req, res) => { try { let plainTextPassword = req.body.password; // console.log(plainTextPassword); if (!plainTextPassword || plainTextPassword.trim() === "") { throw { status: 400, error: "Password must be provided" }; } if (plainTextPassword.trim().length < 6) { throw { status: 404, error: "Password must contain at least 6 characters.", }; } let email = req.body.userData.email; let existingUserData; try { existingUserData = await petOwnerData.getPetOwnerByUserEmail(email); } catch (e) { res.status(e.status).send({ error: e.error }); return; } try { const petOwner = await petOwnerData.updatePassword( existingUserData._id, plainTextPassword ); // console.log(petOwner); res.status(200).render("users/petOwner", { petOwner, status: "success", alertMessage: "Password Updated Successfully.", pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", }); } catch (e) { res.status(200).render("users/petOwner", { petOwner, status: "failed", alertMessage: "Password Update Failed. Please try again.", pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", }); } } catch (e) { res.status(e.status).send({ error: e.error }); return; } }); //handles user info changes router.post("/", async (req, res) => { try { const petOwnerInfo = req.body; // console.log(petOwnerInfo); // console.log(petOwnerInfo); var email = req.body.userData.email; //getting existing data of user let existingUserData; try { existingUserData = await petOwnerData.getPetOwnerByUserEmail(email); } catch (e) { res.status(404).json({ error: "user not found" }); return; } //console.log(existingUserData); const petOwnerDetails = await petOwnerData.getPetOwnerByUserEmail(email); // //checking if user has given any shelter reviews if (petOwnerDetails.shelterReviewsGiven.length != 0) { try { const shelterReviewsInfo = await petOwnerData.getShelterReviews( petOwnerDetails._id ); petOwnerDetails.shelterReviewsGivenArray = shelterReviewsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } //checking if user has any favorite pets if (petOwnerDetails.favoritedPets.length != 0) { try { const userFavoritePetsInfo = await petOwnerData.getUserFavoritePets( petOwnerDetails.favoritedPets ); petOwnerDetails.favoritedPetsArray = userFavoritePetsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } if ( !petOwnerInfo.firstName || !petOwnerInfo.lastName || !petOwnerInfo.dateOfBirth || !petOwnerInfo.phoneNumber || !petOwnerInfo.zipCode ) { throw { status: 404, error: "One of the mandatory fields is missing. generated by /routes/petOwner", }; } if ( petOwnerInfo.firstName.trim() == "" || petOwnerInfo.firstName == undefined ) { throw { status: 404, error: "First Name is Invalid. generated by /routes/petOwner", }; } if ( petOwnerInfo.lastName.trim() == "" || petOwnerInfo.lastName == undefined ) { throw { status: 404, error: "Last Name is Invalid. generated by /routes/petOwner", }; } if ( petOwnerInfo.dateOfBirth.trim() == "" || petOwnerInfo.dateOfBirth == undefined ) { throw { status: 404, error: "dateOfBirth is Invalid. generated by /routes/petOwner", }; } if ( petOwnerInfo.phoneNumber.trim() == "" || petOwnerInfo.phoneNumber == undefined ) { throw { status: 404, error: "phoneNumber is Invalid. generated by /routes/petOwner", }; } if ( petOwnerInfo.zipCode.trim() == "" || petOwnerInfo.zipCode == undefined ) { throw { status: 404, error: "zipCode is Invalid. generated by /routes/petOwner", }; } //checking is zipcode is valid if (zipcodes.lookup(petOwnerInfo.zipCode) === undefined) { res.status(200).render("users/petOwner", { petOwner: petOwnerDetails, pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", error: "Invalid zip code. Please try again.", }); return; } const phoneNumberRegex = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im; //regex to check phone Number if (!phoneNumberRegex.test(petOwnerInfo.phoneNumber)) { res.status(200).render("users/petOwner", { petOwner: petOwnerDetails, pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", error: "Invalid phone number. Please try again.", }); return; } function dateChecker(date1, date2 = new Date()) { var date1 = new Date(Date.parse(date1)); var date2 = new Date(Date.parse(date2)); var ageTime = date2.getTime() - date1.getTime(); if (ageTime < 0) { return false; //date2 is before date1 } else { return true; } } if (!dateChecker(petOwnerInfo.dateOfBirth)) { // throw { // status: 400, // error: // "Date of Birth cannot be a future date.", // }; res.status(200).render("users/petOwner", { petOwner: petOwnerDetails, pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", error: "Date of Birth cannot be a future date. Please try again.", }); return; } //console.log(existingUserData); let updatedData = {}; //checking if data was updated if (existingUserData.fullName.firstName != petOwnerInfo.firstName) { updatedData.fullName.firstName = petOwnerInfo.firstName; updatedData.fullName = { firstName: petOwnerInfo.firstName, lastName: "", }; } if (existingUserData.fullName.lastName != petOwnerInfo.lastName) { if ( updatedData.fullName && updatedData.fullName.hasOwnProperty("firstName") ) { updatedData.fullName = { lastName: petOwnerInfo.lastName, firstName: updatedData.fullName.firstName, }; } else { updatedData.fullName = { lastName: petOwnerInfo.lastName, firstName: "", }; } } if (existingUserData.dateOfBirth != petOwnerInfo.dateOfBirth) { updatedData.dateOfBirth = petOwnerInfo.dateOfBirth; } if (existingUserData.phoneNumber != petOwnerInfo.phoneNumber) { updatedData.phoneNumber = petOwnerInfo.phoneNumber; } if (existingUserData.zipCode != petOwnerInfo.zipCode) { updatedData.zipCode = petOwnerInfo.zipCode; } if (existingUserData.biography != petOwnerInfo.biography) { updatedData.biography = petOwnerInfo.biography; } //if user updates any data, calling db function to update it in DB if (Object.keys(updatedData).length != 0) { try { updatedData.email = email; const petOwnerAddInfo = await petOwnerData.updatePetOwner(updatedData); //console.log(petOwnerAddInfo); const petOwnerDetails = await petOwnerData.getPetOwnerByUserEmail( email ); if (petOwnerAddInfo.shelterReviewsGiven.length != 0) { try { const shelterReviewsInfo = await petOwnerData.getShelterReviews( petOwnerDetails._id ); petOwnerAddInfo.shelterReviewsGivenArray = shelterReviewsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } //checking if user has any favorite pets if (petOwnerAddInfo.favoritedPets.length != 0) { try { const userFavoritePetsInfo = await petOwnerData.getUserFavoritePets( petOwnerAddInfo.favoritedPets ); petOwnerAddInfo.favoritedPetsArray = userFavoritePetsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } res.status(200).render("users/petOwner", { petOwner: petOwnerAddInfo, pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", status: "success", alertMessage: "Information updated successfully.", }); } catch (e) { res.status(e.status).send({ error: e.error }); return; } } else { //user did not update any data. calling db function to get the existing data try { const petOwner = await petOwnerData.getPetOwnerByUserEmail(email); if (petOwner.shelterReviewsGiven.length != 0) { try { const shelterReviewsInfo = await petOwnerData.getShelterReviews( petOwner._id ); petOwner.shelterReviewsGivenArray = shelterReviewsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } //checking if user has any favorite pets if (petOwner.favoritedPets.length != 0) { try { const userFavoritePetsInfo = await petOwnerData.getUserFavoritePets( petOwner.favoritedPets ); petOwner.favoritedPetsArray = userFavoritePetsInfo; } catch (e) { res.status(e.status).send({ error: e.error }); return; } } //res.status(200).json(petOwner); res.status(200).render("users/petOwner", { petOwner, pageTitle: "Pet Owner/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", status: "success", alertMessage: "Information updated successfully.", }); } catch (e) { res.status(e.status).send({ error: e.error }); return; } } } catch (e) { res.status(e.status).send({ error: e.error }); return; } }); //updates the status of isVolunteerCandidate field router.post("/changeVolunteer", async (req, res) => { try { if (!req.body.status) { throw { status: 400, error: "volunteer status must be provided." }; } let isVolunteerStatus = req.body.status; let email = req.body.userData.email; let existingUserData; try { existingUserData = await petOwnerData.getPetOwnerByUserEmail(email); } catch (e) { res.status(e.status).send({ error: e.error }); return; } try { const petOwner = await petOwnerData.updateVolunteerStatus( existingUserData._id, isVolunteerStatus ); res .status(200) .render("users/petOwner", { petOwner, pageTitle: "Pet Owner/Pet Adopter/Pet Adopter", isLoggedIn: req.body.isLoggedIn, script: "userProfile", alertMessage: "Information updated successfully", }); } catch (e) { res.status(e.status).send({ error: e.error }); return; } } catch (e) { res.status(e.status).send({ error: e.error }); return; } }); module.exports = router;
let inject_init = () => { // eslint-disable-line no-unused-vars var accept_modal = $('#confirm-accept') var decline_modal = $('#confirm-decline') var injects = { header: $('body > div.wrapper > div.breadcrumbs > div > h1'), date_buttons: accept_modal.find('div > div > form > div.modal-body > div:nth-child(5) > label:nth-child(4)'), report_language: $('div.container.content > div > div > div > table.table > tbody > tr:nth-child(8) > td:nth-child(2)'), claim_report: $('div.container.content > div > div > div > table.table > tbody > tr:nth-child(10) > td:nth-child(2) > a'), spinner: $('#loading-spinner'), accept: { comment: accept_modal.find('div > div > form > div.modal-body > div:nth-child(7) > textarea'), form: accept_modal.find('div > div > form'), time: $('#datetimeselect'), reason: accept_modal.find('div > div > form > div.modal-body > div:nth-child(6) > input') }, bans: { table: $('#ban > div > table > tbody > tr'), header: $('#bans > div:nth-child(1) > h4 > a'), ban_toggler: $('#expired_bans_toggler').find('i') }, decline: { comment: decline_modal.find('div > div > form > div.modal-body > div > textarea'), form: decline_modal.find('div > div > form') }, summary: { first_column: $('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(1) > table > tbody > tr > td:nth-child(1)'), perpetrator_link: $('table > tbody > tr:nth-child(2) > td:nth-child(2) > kbd > a'), perpetrator_label: $('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(1) > table > tbody > tr:nth-child(2) > td:nth-child(1)'), previous_usernames: $('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(1) > table > tbody > tr:nth-child(3) > td:nth-child(1)'), reporter_link: $('table > tbody > tr:nth-child(1) > td:nth-child(2) > kbd > a'), reporter_label: $('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(1) > table > tbody > tr:nth-child(1) > td:nth-child(1)') } } const tbody = $('html').find('tbody').first(); const users = { reporter: tbody.find("tr:nth-child(1) > td:nth-child(2) a"), perpetrator: tbody.find("tr:nth-child(2) > td:nth-child(2) a"), admin: tbody.find("tr:nth-child(7) > td:nth-child(2) > a") }; let cannedVariables = { 'report.language': tbody.find("tr:nth-child(9) > td:nth-child(2)").text().trim(), 'report.reason': tbody.find('tr:nth-child(8) > td:nth-child(2) > strong').text(), 'user.username': users.reporter.text(), 'user.id': 0, 'perpetrator.username': users.perpetrator.text(), 'perpetrator.id': 0, 'perpetrator.steam_id': tbody.find("tr:nth-child(3) > td > a").text().trim(), 'admin.username': users.admin.text(), 'admin.id': 0, 'admin.group.name': 'Staff Member' }; try { cannedVariables["user.id"] = users.reporter.attr('href').split('/')[4] } catch (e) { console.log("Couldn't set canned variables for reporter ID: " + e.toString()) } try { cannedVariables["perpetrator.id"] = users.perpetrator.attr('href').split('/')[4] } catch (e) { console.log("Couldn't set canned variables for perpetrator ID: " + e.toString()) } try { cannedVariables["admin.id"] = (!users.admin.text() ? 0 : users.admin.attr('href').split('/')[4]) } catch (e) { console.log("Couldn't set canned variables for admin ID: " + e.toString()) } var perpetratorProfile; function fetchPerpetratorProfile () { $.ajax({ url: $(injects.summary.perpetrator_link).attr('href'), type: 'GET', success: function (data) { perpetratorProfile = data; if (settings.enablebanlength === true) checkBanLength(); registered(); } }); } function fetchAdminGroupName () { switch (users.admin.css('color').replaceAll(" ","")){ case 'rgb(244,67,54)': cannedVariables["admin.group.name"] = 'Game Moderator'; if (settings.localisedcomment) comment_language(); break; case 'rgb(255,82,82)': cannedVariables["admin.group.name"] = 'Report Moderator'; if (settings.localisedcomment) comment_language(); break; case 'rgb(211,47,47)': cannedVariables["admin.group.name"] = 'Game Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(183,28,28)': cannedVariables["admin.group.name"] = 'Senior Game Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(0,184,212)': cannedVariables["admin.group.name"] = 'Translation Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(0,166,212)': cannedVariables["admin.group.name"] = 'Senior Translation Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(21,101,192)': cannedVariables["admin.group.name"] = 'Event Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(13,71,161)': cannedVariables["admin.group.name"] = 'Senior Event Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(255,143,0)': cannedVariables["admin.group.name"] = 'Media Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(0,131,143)': cannedVariables["admin.group.name"] = 'Community Moderation Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(0,96,100)': cannedVariables["admin.group.name"] = 'Senior Community Moderation Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(236,64,122)': cannedVariables["admin.group.name"] = 'Support Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(216,27,96)': cannedVariables["admin.group.name"] = 'Senior Support Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(230,74,25)': cannedVariables["admin.group.name"] = 'Community Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(191,54,12)': cannedVariables["admin.group.name"] = 'Senior Community Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(126,87,194)': cannedVariables["admin.group.name"] = 'Add-On Manager'; if (settings.localisedcomment) comment_language(); break; case 'rgb(96,125,139)': cannedVariables["admin.group.name"] = 'Service and Data Analyst'; if (settings.localisedcomment) comment_language(); break; case 'rgb(103,58,183)': cannedVariables["admin.group.name"] = 'Developer'; if (settings.localisedcomment) comment_language(); break; default: $.ajax({ url: users.admin.attr('href'), type: 'GET', success: function (data) { console.log('admin role unknown or ambiguous, profile fetched'); var profile = $(data).find('div.profile-bio'); cannedVariables["admin.group.name"] = profile.text().substr(profile.text().indexOf('Rank:')).split("\n")[0].replace("Rank: ",""); if (settings.localisedcomment) comment_language(); } }); break; } } function registered () { var profile = $(perpetratorProfile).find('div.profile-bio'); var regDate = profile.text().substr(profile.text().indexOf('Member since:')).split("\n")[0].replace("Member since: ",""); injects.summary.perpetrator_label.next().find('#registerdate').text('Registered: ' + regDate); } // Fixes word dates var day = 60 * 60 * 24 * 1000 var fixDate = function (date) { if (date === '' || date === undefined) { return } var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] var d = new Date() date = date.replace('Today,', d.getDate() + ' ' + months[d.getMonth()]) var yesterday = new Date(d) yesterday.setTime(d.getTime() - day) date = date.replace('Yesterday,', yesterday.getDay() + ' ' + months[d.getMonth()]) var tomorrow = new Date(d) tomorrow.setTime(d.getTime() + day) date = date.replace('Tomorrow,', tomorrow.getDay() + ' ' + months[d.getMonth()]) if (!date.match(/20[0-9]{2}/)) { date += ' ' + (new Date()).getFullYear() } return date }; // Escape HTML due to HTML tags in Steam usernames function escapeHTML(s) { // eslint-disable-line no-unused-vars return s.replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') } function accept_modal_init() { var reasonMax = 190 var reasonLength = (injects.accept.reason.val() ? injects.accept.reason.val().length : 0) $('<div id="reasonCount">' + reasonLength + "/" + reasonMax + '</div>').insertAfter(injects.accept.reason) var reasonCount = $('#reasonCount') addButtons($('input[name=reason]'), '<div class="ban-reasons">' + construct_buttons('accept') + '</div>') addButtons($('div.container.content').find('textarea[name=comment]'), construct_buttons('comments')) $(injects.date_buttons).html(construct_dates(OwnDates)) //$('input[id="perma.false"]').prop('checked', true) // ===== DateTime and Reason inputs checking ===== injects.accept.form.on('submit', function (event) { var time_check = injects.accept.time.val() var perm_check = $('input[id="perma.true"]').prop('checked') var reason_check = injects.accept.reason.val() var error_style = { 'border-color': '#a94442', '-webkit-box-shadow': 'inset 0 1px 1px rgba(0,0,0,.075)', 'box-shadow': 'inset 0 1px 1px rgba(0,0,0,.075)' } var normal_style = { 'border-color': '', '-webkit-box-shadow': '', 'box-shadow': '' } if (!time_check && !perm_check) { injects.accept.time.css(error_style) event.preventDefault() } else { injects.accept.time.css(normal_style) } if (!reason_check) { injects.accept.reason.css(error_style) event.preventDefault() } else { injects.accept.reason.css(normal_style) } }) // ===== Reasons FTW ===== $('.plusreason').on('click', function (event) { event.preventDefault() var reason_val = injects.accept.reason.val(), sp = '' if (!checkDoubleSlash(injects.accept.reason[0])) { sp = (settings.separator) ? settings.separator : ','; } if ($(this).data('place') == 'before') { // prefixes injects.accept.reason.val(decodeURI(String($(this).data('text'))) + ' ' + reason_val.trimStart()) } else if ($(this).data('place') == 'after-wo') { // suffixes injects.accept.reason.val(reason_val.trim() + ' ' + decodeURI(String($(this).data('text')))) } else if (reason_val.length) { // reasons non-empty var pos = injects.accept.reason.prop('selectionStart'); if (!pos) { //cursor at start injects.accept.reason.val(reason_val.trimStart()); injects.accept.reason[0].setRangeText(decodeURI(String($(this).data('text'))) + (checkUrlOrDelimiter(reason_val.trim()) ? '' : sp) + (reason_val[0] === ' ' ? '' : ' '), 0, 0, 'end'); } else { //move cursor out of suffix if (reason_val.lastIndexOf(" // ") > reason_val.lastIndexOf(" || ")) { pos = Math.min(pos, reason_val.length - reason_val.split(" // ").pop().length - 4); } else if (reason_val.lastIndexOf(" // ") < reason_val.lastIndexOf(" || ")) { pos = Math.min(pos, reason_val.length - reason_val.split(" || ").pop().length - 4); } //move cursor behind current word var new_pos = reason_val.trimEnd().length; [',',' - http',' http',' /'].forEach(el => { if (reason_val.indexOf(el, pos-2) > -1) new_pos = Math.min(new_pos, reason_val.indexOf(el, pos-2)); }); pos = reason_val[new_pos] == ',' ? new_pos + 1 : new_pos; //Insert var before = reason_val.substring(0, pos).trimEnd(); var len = before.length - 1 switch (before[len]) { case ',': injects.accept.reason[0].setRangeText(before + ' ' + decodeURI(String($(this).data('text'))) + (checkUrlOrDelimiter(reason_val.substr(pos).trim()) ? '' : sp) + ' ', 0, pos + 1, 'end'); break; case '/': case '+': if (before[len - 1] === " ") { injects.accept.reason[0].setRangeText(before + ' ' + decodeURI(String($(this).data('text'))) + (checkUrlOrDelimiter(reason_val.substr(pos).trim()) ? '' : sp) + ' ', 0, pos + 1, 'end'); break; } default: if (before.split(" ").pop().startsWith('http')) injects.accept.reason[0].setRangeText(before + ' / ' + decodeURI(String($(this).data('text'))) + ' ', 0, pos + 1, 'end'); else injects.accept.reason[0].setRangeText(before + sp + ' ' + decodeURI(String($(this).data('text'))) + ' ', 0, pos + 1, 'end'); break; } } } else { // reasons empty injects.accept.reason.val(decodeURI(String($(this).data('text'))) + ' ') } injects.accept.reason.focus() checkReasonLength() }) $('button#reason_clear').on('click', function (event) { event.preventDefault() injects.accept.reason.val('') }) // ===== Timing FTW! ===== var unban_time = moment.utc() if ($('#datetimeselect').length && $('#datetimeselect').val().length) { unban_time = moment($('#datetimeselect').val()) } console.log('TMP Improved (inject/reports)', unban_time) $('.plusdate').on('click', function (event) { event.preventDefault() var number = $(this).data('number') switch (number) { case 'clear': unban_time = moment.utc() break; default: var key = $(this).data('key') unban_time.add(number, key) break; } injects.accept.time.val(unban_time.format('YYYY-MM-DD HH:mm')) }) //Ban reason length check function checkReasonLength() { if (injects.accept.reason.val().length > reasonMax) { injects.accept.reason.css({ 'background-color': 'rgba(255, 0, 0, 0.5)', 'color': '#fff' }) reasonCount.css({ 'color': 'red', 'font-weight': 'bold' }) } else { reasonCount.css({ 'color': '', 'font-weight': '' }) injects.accept.reason.css({ 'background-color': '', 'color': '' }) } reasonCount.html(injects.accept.reason.val().length + '/' + reasonMax) } //check if input beginning is URL or non-alphanumeric function checkUrlOrDelimiter(str) { if (str.startsWith('http')) return true; var code = str.charCodeAt(0); if (!(code > 47 && code < 58) && // numeric (0-9) !(code > 64 && code < 91) && // upper alpha (A-Z) !(code > 96 && code < 123)) return true;// lower alpha (a-z) return false; } injects.accept.reason.keyup(function () { checkReasonLength() }) } function decline_modal_init() { addButtons(injects.decline.comment, construct_buttons('decline')) injects.decline.form.on('submit', function (event) { var comment_check = injects.decline.comment.val() var error_style = { 'border-color': '#a94442', '-webkit-box-shadow': 'inset 0 1px 1px rgba(0,0,0,.075)', 'box-shadow': 'inset 0 1px 1px rgba(0,0,0,.075)' } var normal_style = { 'border-color': '', '-webkit-box-shadow': '', 'box-shadow': '' } if (!comment_check) { injects.decline.comment.css(error_style) event.preventDefault() } else { injects.decline.comment.css(normal_style) } }) $('.plusdecline').on('click', function (event) { event.preventDefault() setReason(injects.decline.comment, decodeURI(String($(this).data('text')))) switch ($(this).data('action')) { case 'negative': $("input[id='decline.rating.negative']").prop('checked', true) break; case 'positive': $("input[id='decline.rating.positive']").prop('checked', true) break; } injects.decline.comment.focus() }) $('button#decline_clear').on('click', function (event) { event.preventDefault() injects.decline.comment.val('') }) } var lastinsertpos; function setReason(reason, reason_val) { reason_val = updateMessageWithCannedVariables(reason_val); if ($(reason).val() == "") { $(reason).val(reason_val); } else { var pos = $(reason).prop('selectionStart'); $(reason)[0].setRangeText((lastinsertpos === pos ? "\n\n" : "") + reason_val, pos, pos, 'end'); lastinsertpos = $(reason).prop('selectionStart'); } $(reason).focus(); } const updateMessageWithCannedVariables = original => { let new_msg = original; Object.keys(cannedVariables).forEach(k => { new_msg = new_msg.replace(`%${k}%`, cannedVariables[k]); }); return new_msg; } $('body').append("<div class='modal fade ets2mp-modal' id='videoModal' tabindex='-1' role='dialog''TMP Improved (inject/reports)', aria-labelledby='videoModalLabel' aria-hidden='true'><div class='modal-dialog 'TMP Improved (inject/reports)', modal-lg' role='document'><div class='modal-content'><div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button><h4 class='modal-title' id='videoModalLabel'>Video preview</h4></div><div class='modal-body' style='padding:0;'></div></div></div></div>") /*function copyToClipboard(text) { const input = document.createElement('input') input.style.position = 'fixed' input.style.opacity = '0' input.value = text document.body.appendChild(input) input.select() document.execCommand('Copy') document.body.removeChild(input) }*/ function comment_language() { var report_language = injects.report_language.text().trim() var comment if (!settings.own_comment) { switch (report_language) { case 'German': comment = 'Wir bedanken uns für deinen Report :) Es ist zu bedenken, dass die zur Verfügung gestellten Beweise sowohl für die gesamte Dauer des Banns als auch einen Monat darüber hinaus verfügbar sein müssen.' break; case 'Turkish': comment = 'Raporunuz için teşekkürler :) Lütfen sunduğunuz kanıtın, yasağın uygulandığı ve takiben gelen bir(1) aylık süreç boyunca kullanılabilir olması gerektiğini lütfen unutmayın.' break; case 'Norwegian': comment = 'Takk for rapporten :) Vennligst husk at bevis må være tilgjengelig for hele bannlysningspreioden pluss 1 måned' break; case 'Spanish': comment = 'Muchas gracias por tu reporte :) Recuerda que las pruebas/evidencias deben estar disponibles durante toda la vigencia de la prohibicion y más 1 mes.' break; case 'Dutch': comment = 'Bedankt voor je rapport :) Onthoud alsjeblieft dat het bewijs beschikbaar moet zijn voor de volledige lengte van de ban PLUS 1 maand.' break; case 'Polish': comment = 'Dziękuję za report :) Proszę pamiętać o tym że dowód musi być dostępny przez cały okres bana, plus jeden miesiąc. ' break; case 'Russian': comment = 'Спасибо за репорт :) Помните, что доказательства должны быть доступны весь период бана ПЛЮС 1 месяц.' break; case 'French': comment = 'Merci pour votre rapport :) Notez que la preuve doit être disponible durant toute la durée du ban PLUS 1 mois.' break; case 'Lithuanian': comment = 'Thank you for your report :) Please, remember that evidence must be available for the full duration of the ban PLUS 1 month.' break; case 'Portuguese': comment = 'Obrigado por seu relatório :) Por favor, lembre-se que as provas devem estar disponíveis para a duração total da proibição MAIS 1 mês.' break; default: comment = 'Thank you for your report :) Please, remember that evidence must be available for the full duration of the ban PLUS 1 month.' } } else { comment = updateMessageWithCannedVariables(settings.own_comment); } injects.accept.comment.val(comment) } function bans_count_fetch() { function getUnbanTime(unban_time_td, banned_reason_td) { var content = unban_time_td.split(/:\d\d/) unban_time_td = unban_time_td.replace(content[1], "") var unban_time now = moment.utc() if (unban_time_td.indexOf('Today') !== -1) { unban_time = now } else if (unban_time_td.indexOf('Tomorrow') !== -1) { unban_time = now.add(1, 'd') } else if (unban_time_td.indexOf('Yesterday') !== -1) { unban_time = now.add(1, 'd') } else { nb_parts = unban_time_td.split(' ').length if (nb_parts == 3) { unban_time = moment(unban_time_td, 'DD MMM HH:mm') } else if (nb_parts == 4) { unban_time = moment(unban_time_td, 'DD MMM YYYY HH:mm') } else { unban_time = moment(unban_time_td) console.log('TMP Improved (inject/reports)', [ unban_time_td, nb_parts, unban_time ]) } } if (unban_time.year() == '2001') { unban_time.year(now.year()) } if (banned_reason_td == '@BANBYMISTAKE') { unban_time.year('1998') } return unban_time } var bans_count = 0 var expired_bans_count = 0 var nb_parts console.log(injects.bans.table) injects.bans.table.each(function () { var ban_time_td = $(this).find('td:nth-child(1)').text() var unban_time_td = $(this).find('td:nth-child(2)').text() var banned_reason_td = $(this).find('td:nth-child(3)').text() var unban_time if (unban_time_td == 'Never') { unban_time = getUnbanTime(ban_time_td, banned_reason_td) } else { unban_time = getUnbanTime(unban_time_td, banned_reason_td) } if (unban_time.isValid()) { if (Math.abs(unban_time.diff(now, 'd')) >= 365) { $(this).hide() $(this).addClass('expired_bans') $(this).find('td').css('color', '#555') expired_bans_count++ } else { bans_count++ } } }) injects.bans.header.html(bans_count + ' counted bans<small>, including deleted. This is a website issue.</small>') if (bans_count >= 3) { injects.bans.header.css('color', '#d43f3a') } if (expired_bans_count > 0) { injects.bans.header.html(bans_count + ' counted bans<small>, including deleted. This is a website issue.</small> <a href="#" id="expired_bans_toggler"><i class="fas fa-toggle-off data-toggle="tooltip" title="Show/hide bans further than 12 months and @BANBYMISTAKE"></i></a>') $('#expired_bans_toggler').on('click', function (event) { event.preventDefault() $('.expired_bans').fadeToggle('slow') if (injects.bans.ban_toggler.hasClass('fa-toggle-off')) { injects.bans.ban_toggler.removeClass('fa-toggle-off') injects.bans.ban_toggler.addClass('fa-toggle-on') } else { injects.bans.ban_toggler.removeClass('fa-toggle-on') injects.bans.ban_toggler.addClass('fa-toggle-off') } }) } if ($('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(2) > table.table.table-responsive > tbody > tr:nth-child(2) > td:nth-child(5) > i').hasClass('fa-check')) { $('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(2) > table.table.table-responsive > tbody > tr:nth-child(2)').find('td').css({ 'color': '#d43f3a' }) } } function ban_history_table_improving() { // Make the table with other reports better $('#report > table > tbody > tr').each(function () { // Skip it when no reports have been found if ($(this).find('td:nth-child(1)').text().trim() === 'No reports found') { return } // View button $(this).find('td:nth-child(6) > a').addClass('btn btn-default btn-block btn-sm').text('View') // Claim button let claimButton = $(this).find('td:nth-child(5) > a') console.log('TMP Improved (inject/reports)', "Thing:", claimButton) claimButton.addClass('btn btn-primary btn-block btn-sm claim') let text = claimButton.text().replace('Report', '').trim() if (text === 'Claim') { claimButton.html(text + " <i class='fas fa-external-link-alt'></i>") if (settings.viewreportblank) { claimButton.attr('target', '_blank') } } else { claimButton.html(text) } // Already claimed if ($(this).find('td:nth-child(5)').text().trim() === 'Already claimed') { $(this).find('td').css('color', '#555') } // Date let dateColumn = $(this).find('td:nth-child(1)') text = dateColumn.text() if (text.split(' ').length !== 4) { text = text.replace('Today,', moment().format('DD MMM')) text = moment(text, 'DD MMM HH:mm').format('DD MMM YYYY HH:mm') dateColumn.text(text) } // Switch claim button $(this).children(':eq(5)').after($(this).children(':eq(4)')) }) // Claim link click $('a.claim').click(function (event) { $(this).addClass('clicked') $(this).text('Claimed!') if (settings.viewreportblank) { event.preventDefault() if (event.ctrlKey) { window.open($(this).attr('href'), '_top') } else { window.open($(this).attr('href'), '_blank') } } }) } function dropdown_enchancements() { $('ul.dropdown-menu').css('top', '95%') $('.dropdown').hover(function () { $('.dropdown-menu', this).stop(true, true).fadeIn('fast') $(this).toggleClass('open') $('b', this).toggleClass('caret caret-up') }, function () { $('.dropdown-menu', this).stop(true, true).fadeOut('fast') $(this).toggleClass('open') $('b', this).toggleClass('caret caret-up') }) $('a.hovery').hover(function (e) { $(this).css('background', e.type === 'mouseenter' ? '#303030' : 'transparent') $(this).css('color', e.type === 'mouseenter' ? '#999!important' : '') }) } function bannedInit() { var isBanned = $('body > div.wrapper > div.container.content > div > div > div.col-md-6:nth-child(2) > table').find('i.fa-check') if (isBanned.length > 0) { var perpetrator = $('body > div.wrapper > div.container.content > div > div > div.col-md-6:nth-child(1) > table > tbody > tr:nth-child(2) > td:nth-child(2)') $(perpetrator).append('<span class="badge badge-red badge-banned">Banned</span>') } } function viewReportBlankInit() { if (settings.viewreportblank) { $('#reports > #report > div:nth-child(1) > table').find('a:contains("View")').prop('target', '_blank'); } else { $('#reports > #report > div:nth-child(1) > table').find('a:contains("View")').prop('target', ''); } } function construct_buttons(type) { var html = '' switch (type) { case 'comments': html += each_type_new('Comments', OwnReasons.comments) html += '<button type="button" class="btn btn-link" id="comments_clear">Clear</button>' break; case 'accept': html += each_type_new('Reasons', OwnReasons.reasons) html += ' ' + each_type_new('Prefixes', OwnReasons.prefixes) html += ' ' + each_type_new('Postfixes', OwnReasons.postfixes) html += '<button type="button" class="btn btn-link" id="reason_clear">Clear</button>' break; case 'decline': html += each_type_new('Declines', OwnReasons.declines) html += ' ' + each_type_new('Declines (Positive)', OwnReasons.declinesPositive) html += ' ' + each_type_new('Declines (Negative)', OwnReasons.declinesNegative) html += '<button type="button" class="btn btn-link" id="decline_clear">Clear</button>' break; } return html function each_type_new(type, buttons) { var place, color, change, action switch (type) { case 'Prefixes': place = 'before' color = 'warning' change = 'reason' action = '' break; case 'Reasons': place = 'after' color = 'default' change = 'reason' action = '' break; case 'Postfixes': place = 'after-wo' color = 'danger' change = 'reason' action = '' break; case 'Declines': place = 'after' color = 'info' change = 'decline' action = '' break; case 'Declines (Positive)': place = 'after' color = 'warning' change = 'decline' action = 'positive' break; case 'Declines (Negative)': place = 'after' color = 'danger' change = 'decline' action = 'negative' break; case 'Comments': place = 'after' color = 'u' change = 'comment' action = '' break; } var snippet = '<div class="btn-group dropdown mega-menu-fullwidth"><a class="btn btn-' + color + ' dropdown-toggle" data-toggle="dropdown" href="#">' + type + ' <span class="caret"></span></a><ul class="dropdown-menu"><li><div class="mega-menu-content disable-icons" style="padding: 4px 15px;"><div class="container" style="width: 800px !important;"><div class="row equal-height" style="display: flex;">' var md = 12 / (Math.max(buttons.length, 1)) $.each(buttons, function (key, val) { snippet += '<div class="col-md-' + md + ' equal-height-in" style="border-left: 1px solid #333; padding: 5px 0;"><ul class="list-unstyled equal-height-list">' if (Array.isArray(val)) { val.forEach(function (item) { snippet += '<li><a style="display: block; margin-bottom: 1px; position: relative; border-bottom: none; padding: 6px 12px; text-decoration: none" href="#" class="hovery plus' + change + '" data-place="' + place + '" data-action="' + action + '" data-text="' + encodeURI(item.trim()) + '">' + item.trim() + '</a></li>' }) } else { $.each(val, function (title, item) { snippet += '<li><a style="display: block; margin-bottom: 1px; position: relative; border-bottom: none; padding: 6px 12px; text-decoration: none" href="#" class="hovery plus' + change + '" data-place="' + place + '" data-action="' + action + '" data-text="' + encodeURI(item.trim()) + '">' + title.trim() + '</a></li>' }) } snippet += '</ul></div>' }) snippet += '</div></div></div></li></ul></div> ' return snippet } } // function supportInit() { // if (injects.claim_report.length == 0) { // var select = $('select[name=visibility]') // $(select).find('option:selected').removeProp('selected') // $(select).find('option[value=Private]').prop('selected', 'selected') // } // } function evidencePasteInit() { injects.accept.reason.bind('paste', function (e) { var self = this, data = e.originalEvent.clipboardData.getData('Text').trim(), dataLower = data.toLowerCase() if ((dataLower.indexOf('http://') == 0 || dataLower.indexOf('https://') == 0) && !checkDoubleSlash(this) && settings.autoinsertsep) { e.preventDefault() insertAtCaret($(self)[0], '- ' + data, true) } }) } function fixModals() { var path = 'div.modal-body > div.form-group:last-child' var rateAccept = injects.accept.form.find(path) rateAccept.find("input[id='rating.positive']").attr('id', 'accept.rating.positive') rateAccept.find("input[id='rating.negative']").attr('id', 'accept.rating.negative') rateAccept.find("label[for='rating.positive']").attr('for', 'accept.rating.positive') rateAccept.find("label[for='rating.negative']").attr('for', 'accept.rating.negative') if (settings.defaultratings) rateAccept.find("input[id='accept.rating.positive']").prop("checked", true); var rateDecline = injects.decline.form.find(path) rateDecline.find("input[id='rating.positive']").attr('id', 'decline.rating.positive') rateDecline.find("input[id='rating.negative']").attr('id', 'decline.rating.negative') rateDecline.find("label[for='rating.positive']").attr('for', 'decline.rating.positive') rateDecline.find("label[for='rating.negative']").attr('for', 'decline.rating.negative') if (settings.defaultratings) rateDecline.find("input[id='decline.rating.negative']").prop("checked", true); $('#loading-spinner').hide() } function addButtons(textArea, html) { if (typeof textArea !== 'undefined' && html.length > 0) { $(textArea).css('margin-bottom', '10px') $(html).insertAfter(textArea) } } /* INIT SCRIPT */ function init() { content_links() fetchPerpetratorProfile() if (settings.localisedcomment) comment_language() //bans_count_fetch() ban_history_table_improving() accept_modal_init() decline_modal_init() dropdown_enchancements() // supportInit() bannedInit() viewReportBlankInit() evidencePasteInit() fixModals() if (users.admin.text()) setTimeout(fetchAdminGroupName, 500) } var now = moment.utc() // Moment.js init $(document).ready(function () { if (settings.wide !== false) { $('div.container.content').css('width', '85%') } injects.summary.perpetrator_label.next().append('<br><kbd id="registerdate" style="margin-left: 2px;">Registered: ...</kbd>'); injects.summary.perpetrator_label.next().find('kbd:nth-child(1)').after('<a style="margin-left: 1px;" id="copyname"><i class="fas fa-copy fa-fw" data-toggle="tooltip" title="" data-original-title="Copy username"></i></a>'); injects.summary.perpetrator_label.next().find('span').after('<a style="margin-left: 1px;" id="copyid"><i class="fas fa-copy fa-fw" data-toggle="tooltip" title="" data-original-title="Copy TMP ID"></i></a>'); tbody.find('tr:nth-child(3) > td > a').append('<a id="copysteamid"><i class="fas fa-copy fa-fw" data-toggle="tooltip" title="" data-original-title="Copy SteamID"></i></a>'); injects.accept.reason.attr('autocomplete','off'); $('#copyname').on('click', function (event) { event.preventDefault() copyToClipboard(cannedVariables["perpetrator.username"]) $(this).children().first().removeClass("fa-copy").addClass("fa-check"); setTimeout(() => { $(this).children().first().removeClass("fa-check").addClass("fa-copy"); },2000); }) $('#copyid').on('click', function (event) { event.preventDefault() copyToClipboard(cannedVariables["perpetrator.id"]) $(this).children().first().removeClass("fa-copy").addClass("fa-check"); setTimeout(() => { $(this).children().first().removeClass("fa-check").addClass("fa-copy"); },2000); }) $('#copysteamid').on('click', function (event) { event.preventDefault() copyToClipboard(cannedVariables["perpetrator.steam_id"]) $(this).children().first().removeClass("fa-copy").addClass("fa-check"); setTimeout(() => { $(this).children().first().removeClass("fa-check").addClass("fa-copy"); },2000); }) $('.youtube').YouTubeModal({ autoplay: 0, width: 640, height: 480 }) var videoBtns = $('.video') var videoModal = $('#videoModal') videoBtns.click(function (e) { e.preventDefault() videoModal.find('.modal-body').html("<div class='embed-responsive-16by9 embed-responsive'><iframe src='" + $(this).attr('href') + "' width='640' height='480' frameborder='0' scrolling='no' allowfullscreen='true' style='padding:0; box-sizing:border-box; border:0; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; margin:0.5%; width: 99%; height: 98.5%;'></iframe></div>") videoModal.modal('show') }) videoModal.on('hidden.bs.modal', function () { videoModal.find('.modal-body').html('') }) var occurred = tbody.find('tr:nth-child(5) > td:nth-child(2)'); var occurdate = Date.parse(fixDate(occurred.text())); var now = (new Date()).getTime(); if (now - occurdate >= day * 32) occurred.css('color', 'red'); else if (now - occurdate >= day * 27) occurred.css('color', 'orange'); else occurred.css('color', 'green'); if (settings.enablebanlength === true) { $('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(2)').append('<hr class="small" /><h4>Recommended Ban length</h4><div style="display: flex"><div class="col-md-12"><div class="text-center"><div class="loading-for-bans" style="display: none;">Loading...</div>' + /*<a class="btn btn-block btn-success" href="#" id="check-ban-length">Check the recommended length of the next ban</a> + */'</div></div>'); } /*$('#check-ban-length').click(function (e) { e.preventDefault() checkBanLength() })*/ }) function checkBanLength () { $('#loading-spinner').show() //$('#check-ban-length').remove() $('div.loading-for-bans').show() // Gets all bans var bans = $(perpetratorProfile).find('.profile-body .panel-profile:last-child .timeline-v2 > li') var activeBans = 0, bans1m = 0, bans3m = 0, totalBans = 0 var active1m = false, two_active_hist_bans = false, active3m = false // If the user is banned var banned = false if ($(perpetratorProfile).find('.profile-body .panel-profile .profile-bio .label-red').text().toLowerCase().includes('banned')) { banned = true } $.each(bans, function (index, ban) { // @BANBYMISTAKE is not counted var reason = $(ban).find('.autolink').text().replaceAll(/(\s)+/g," ").replace("Reason: ","").trim() if (reason === '@BANBYMISTAKE' || $(ban).find('.cbp_tmicon').css('background-color') === 'rgb(255, 0, 38)') { return } var date = $($(ban).next().find('div.modal-body > div').children()[$(ban).next().find('div.modal-body > div').children().length - 2]).text().split(/:\s/)[0].trim() //$(ban).find('.cbp_tmtime span:last-of-type').text() var issuedOn = Date.parse(fixDate(date)) var dateExp = $(ban).find('.autolink').next().text().replaceAll(/(\s)+/g," ").replace("Expires ","").trim() //getKeyValueByNameFromBanRows($(ban).find('.cbp_tmlabel > p'), "Expires", ': ')[1] if (dateExp === 'Never' || dateExp === 'Permanent') { dateExp = date } var expires = Date.parse(fixDate(dateExp)) totalBans++; if (expires - issuedOn >= day * 85) { bans3m++ } else if (expires - issuedOn >= day * 27) { bans1m++ } if ((new Date()).getTime() - day * 365 <= expires) { activeBans++ if (expires - issuedOn >= day * 85) { if (active3m || active1m) two_active_hist_bans = true; active3m = true } else if (expires - issuedOn >= day * 27) { if (active1m || active3m) two_active_hist_bans = true; active1m = true } } }) var html = '<div class="col-md-6 text-center" style="align-self: center"><kbd' if (banned) { html += ' style="color: rgb(212, 63, 58)">The user is already banned!</kbd><br />Length of the next ban: <kbd' } // Length checks if (two_active_hist_bans || (activeBans >= 4 && active1m)) { html += ' style="color: rgb(212, 63, 58)">Permanent' } else if (activeBans >= 3) { html += ' style="color: rgb(212, 63, 58)">1 month' } else { html += '>You can choose :)' } html += '</kbd><br /><br /><em>This tool is very accurate, but please check the profile to avoid mistakes.</em></div>' // Information html += '<div class="col-md-6 text-center">' //html += 'Banned: <kbd' + (banned ? ' style="color: rgb(212, 63, 58)">yes' : '>no') + '</kbd><br />' html += 'Active bans: ' + activeBans + '<br />' html += 'Total bans: ' + totalBans + '<br />' html += '1 month bans: ' + bans1m + '<br />' html += '3 month bans: ' + bans3m + '<br />' html += 'Active 1 month ban: ' + (active1m || active3m)/* + '<br />' html += 'Active 3 month ban: ' + active3m*/ //html += '<br/><br/></div><div class="text-center"><em>This tool is very accurate, but please check the profile to avoid mistakes.</em></div></div>' html += '</div>' $('body > div.wrapper > div.container.content > div > div.clearfix > div:nth-child(2)').append(html) $('#loading-spinner').hide() $('div.loading-for-bans').hide() } init() $('.pluscomment').on('click', function (event) { event.preventDefault() setReason($('form').find('textarea').not($('.modal-body').find('textarea')), decodeURI(String($(this).data('text')))) }) $('button#comments_clear').on('click', function (event) { event.preventDefault() $('form').find('textarea[name=comment]').val('') }) }
define(["jquery", "ajax_helper"], function ($, ajaxHelper) { /** * Биндинг эвентов для кнопок * @returns {} */ function bind() { $("#add-form").submit(function(event) { event.preventDefault(); ajaxHelper.addCase(); }); $("#remove-all-btn").click(function(event) { event.preventDefault(); ajaxHelper.removeAll(); });; $(".remove-btn").click(function(event) { event.preventDefault(); var btnId = this.id; var id = btnId.substring(11); ajaxHelper.removeCase(id); }); } return { bind: bind } });
import { combineReducers } from 'redux'; import series from './seriesDashboard'; const seriesDashboardReducers = combineReducers({ series }); export default seriesDashboardReducers;
import react, { Component } from "react"; const textStyle = { fontSize: "30px", color: 'green' } class About extends Component { render() { return ( <div style={textStyle}> About Us </div> ); } } export default About;
const Reversi = require('./reversi/reversi.js'); const fs = require('fs'); const app = require('express')(); const https = require('https'); const privateKey = fs.readFileSync('./privkey.pem', 'utf8'); const certificate = fs.readFileSync('./cert.pem', 'utf8'); const ca = fs.readFileSync('./chain.pem', 'utf8'); const credentials = { key: privateKey, cert: certificate, ca: ca }; const httpsServer = https.createServer(credentials, app); //const http = require('http').Server(app); const io = require('socket.io')(httpsServer); const currentUsers = new Map(); const generateId = () => { const charz = 'abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/-'; let genId = ""; while(currentUsers.has(genId) || genId.length < 5){ genId+=charz[Math.floor(Math.random()*charz.length)]; } currentUsers.set(genId, {game:new Reversi(), color: 'B'}); return genId; } io.on('connection', (socket) =>{ let id = generateId(); let currentUser = currentUsers.get(id); currentUser.socket = socket; currentUsers.set(id, currentUser); let game = currentUser.game; let color = currentUser.color; socket.emit('game ready', currentUser.game.rawGrid); socket.on('new game', (data)=>{ currentUser.game = new Reversi(); currentUsers.set(id, currentUser); game = currentUser.game; color = currentUser.color; socket.emit('game ready', currentUser.game.rawGrid); }); socket.on('click', (data) =>{ let col = game.grid._colNames[data.col]; let row = game.grid._rowNames[data.row]; if(game.play(col, row, color)){ while(!game._isFinished && game._turn === 'W'){ game.AI_PlayRandom('W'); } if(game._isFinished){ socket.emit('game finished', {_currentCount: game.grid._currentCount, grid:game.rawGrid, transcript:game.transcript}); } } socket.emit('turn', game.rawGrid); }); socket.on('disconnect', ()=>{ currentUsers.delete(id); }) }); app.get('/', (req, res) => { res.sendFile(`${__dirname}/reversi/index-express.html`); }); /*http.listen(2345, () => { console.log('listening http on *:2345'); });*/ httpsServer.listen(3456, () => { console.log('listening https on *:3456'); });
import React from 'react'; class Clock extends React.Component { constructor(props){ super(props); let time = new Date(); let hours = time.getHours() % 12; hours = hours == 0 ? 12 : hours; let mins = time.getMinutes(); let secs = time.getSeconds(); this.state = {hours: hours, mins: mins, secs: secs}; this.updateTime = this.updateTime.bind(this); setInterval(this.updateTime, 1000); } updateTime(){ let secs = this.state.secs + 1; let mins = this.state.mins; let hours = this.state.hours; if (secs > 59){ secs = 0; mins++; } if (mins > 59){ mins = 0; hours++; } if (hours > 12){ hours = 1; } this.setState({secs: secs, mins: mins, hours: hours}); } render(){ let hours = this.state.hours < 10 ? `0${this.state.hours}` : this.state.hours; let mins = this.state.mins < 10 ? `0${this.state.mins}` : this.state.mins; let secs = this.state.secs < 10 ? `0${this.state.secs}` : this.state.secs; return( <div className="holder"> <div className="clock">{hours}:{mins}:{secs}</div> </div> ); } } export default Clock;
import React, { Component } from "react"; import Indicators from "./indicators"; import Barchart from "./barchart"; import Linechart from "./linechart"; import PivotTable from './pivottable'; class Dashboard extends Component { render() { return ( <div> <div className="row tile_count"> <Indicators /> </div> <div className="row"> <Barchart /> </div> <div className="row"> <Linechart /> </div> <div className="row"> <PivotTable /> </div> </div> ) } } export default Dashboard
function greaterNums(array1, array2) { let confirm = array1.every((item) => { return array2.includes(item); }) let greaterNumber = []; if (confirm) { for (let i = 0; i < array1.length; i++) { for (let j = array2.indexOf(array1[i]); j < array2.length; j++) { if (array2[j] > array1[i]) { greaterNumber.push(array2[j]); break; } } if (greaterNumber.length === i) { greaterNumber.push(-1); } } } return greaterNumber; } console.log(greaterNums([4, 1, 2], [1, 3, 4, 2]));
function mostrar() { //alert('iteración while'); var contador; contador=0; while (contador<10) { contador++; console.log("Hola"+contador); //contador=contador+1; //contador++; } } //FIN DE LA FUNCIÓN //El contador siempre tiene que etsan igualado a 0 //Y el contador a la cantidad de repeticiones //Si quiero que el contador comienzo el 1 tiene que ir arriba
let firstNumber = 10 ; let secondNumber = 2 ; while ((firstNumber / secondNumber) > 1) { let result = firstNumber / secondNumber; firstNumber = result; let content = document.createElement("p"); content.textContent = result ; document.body.append(content); } // Créer deux variables firstNumber et secondNumber. Leur donner une valeur comprise entre 1 et 10. Tant que le résultat de la division des deux nombres est supérieur à 1: // Afficher le résultat. // Assigner le résultat à firstNumber
import React, {useState} from 'react' //components import Error from './Error' function Form ({ criptomonedas, saveMoney }){ const [ money, setMoney ] = useState('') const [ cripto, setCripto] = useState('') const [ error, setError ] = useState(false) const checkMoney = e =>{ e.preventDefault() //validacion de campos if(money === '' || cripto === ''){ setError(true) return } setError(false) saveMoney(money, cripto) } const component = (error) ? <Error message={'debes seleccionar los dos campos'} /> : null return( <form onSubmit={checkMoney}> {component} <div className="form-group"> <label className="text-light"> Elige tu moneda </label> <select name="" className="form-control" onChange={e => setMoney(e.target.value)} > <option value="">Elige tu moneda</option> <option value="USD">Dolar Estadounidense</option> <option value="COP">Peso Colombiano</option> <option value="EUR">Euro</option> <option value="GBP">Libras</option> </select> </div> <div className="form-group"> <label className="text-light"> Elige Tu Criptomoneda </label> <select name="" className="form-control" onChange={ e => setCripto(e.target.value)} > <option value="">Elige la Cripotomoneda</option> { criptomonedas.map(criptomoneda =>( <option key={criptomoneda.CoinInfo.Id} value={criptomoneda.CoinInfo.Name} > {criptomoneda.CoinInfo.FullName} </option> )) } </select> </div> <button className="btn btn-outline-light btn-block"> check </button> </form> ) } export default Form
const dbpool = require("../config/dbpoolconfig"); const usersModel = { getAllUser(params){ return new Promise((resolve,reject)=>{ dbpool.connect("SELECT * FROM yd_manager AS a,yd_role AS b WHERE a.role=b.role_id limit ?,?",params,(err,data)=>{ resolve(data); }) }) }, usersPage(){ return new Promise((resolve,reject)=>{ dbpool.connect("select count(*) as a from yd_manager",[],(err,data)=>{ resolve(data) }) }) }, getrole(){ return new Promise((resolve,reject)=>{ dbpool.connect("select * from yd_role",[],(err,data)=>{ resolve(data) }) }) }, getUser(params){ return new Promise((resolve,reject)=>{ dbpool.connect("select * from yd_manager where mg_id=?",params,(err,data)=>{ resolve(data) }) }) }, changeUser(params){ return new Promise((resolve,reject)=>{ dbpool.connect("update yd_manager set account=?,mg_name=?,sex=?,birth=?,role=?,status=?,head_img=? where mg_id=?",params,(err,data)=>{ if(!err){ resolve(data) }else{ reject(err) } }) }) }, addUser(params){ return new Promise((resolve,reject)=>{ dbpool.connect("insert into yd_manager values (null,?,default,?,?,?,?,?,?)",params,(err,data)=>{ if(!err){ resolve(data) }else{ reject(err) } }) }) }, deleUser(params){ return new Promise((resolve,reject)=>{ dbpool.connect("delete from yd_manager where mg_id=?",params,(err,data)=>{ if(!err){ resolve(data) }else{ reject(err) } }) }) } }; module.exports=usersModel;
define([ 'exports', 'view.panel.workspace' ], function( exports, workspaceView ){ // 模拟上传骨骼纹理图 // 暴露在全局下方便调试 exports.uploadTexture = window.uploadTexture = function(parent, texture){ var img = new Image(), boneData = {}; parent && (boneData.parent = parent); img.src = boneData.texture = texture || 'img/defaultTexture.png'; img.onload = function(){ if(img.width){ boneData.w = img.width; boneData.jointX = img.width / 2; } if(img.height){ boneData.h = img.height; boneData.jointY = img.height / 2; } if(workspaceView._activeBone){ boneData.parent = workspaceView._activeBone.id; } workspaceView.trigger('addBone', boneData); }; }; });
System.config({ packages: { '{universe:react-chartjs}': { main: 'index', format: 'register', map: { '.': System.normalizeSync('{universe:react-chartjs}') } } } });
import React, { Component } from 'react'; import {connect} from 'react-redux'; import {addArticle} from '../actions/index'; import {Link} from 'react-router-dom'; const mapDispatchToProps = dispatch => { return { addArticle: article => dispatch(addArticle(article)) }; }; class ConnectedForm extends Component{ constructor(props){ super(props); this.state = { title: '', description: '' }; this.handleTitleChange = this.handleTitleChange.bind(this); this.handleDescChange = this.handleDescChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleTitleChange(event){ this.setState({title: event.target.value}); } handleDescChange(event){ this.setState({description: event.target.value}); } handleSubmit(event){ event.preventDefault(); const {title} = this.state; const id = Date.now(); const {description} = this.state; this.props.addArticle({title, id, description}); this.setState({title: '', description: ''}); } render(){ const {title, description} = this.state; return ( <div className="container text-center"> <form onSubmit={this.handleSubmit}> <div className="form-group"> <label htmlFor="title">Title</label> <input type="text" className="form-control" id="title" value={title} onChange={this.handleTitleChange} /> </div> <div className="form-group"> <label htmlFor="descriptionInput">Description</label> <textarea className="form-control" id="descriptionInput" rows="3" value={description} onChange={this.handleDescChange}> </textarea> </div> <button type="submit" className="btn btn-success"> Create </button> {' '} <Link to="/documents" className="btn btn-secondary">Cancel</Link> </form> </div> ); } }; const Form = connect(null, mapDispatchToProps)(ConnectedForm); export default Form;
'use strict'; angular.module('foosenshaftApp') .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'app/match/match.html', controller: 'MatchCtrl' }); });
import React from "react"; import { Form, Row } from "react-bootstrap"; import "./style.css"; const Console = props => { return ( <Row> <Form.Control as="textarea" readOnly className="console" value={"Output: " + props.output} /> </Row> ); }; export default Console;
import React from 'react'; import Head from 'next/head'; import Header from '../components/Header/Header'; import { PageWrap } from '../styles/PageWrap'; import { MainScreenStyles } from '../components/MainScreen/MainScreenStyles'; import AuthBox from '../components/AuthBox/AuthBox'; const Registet = () => ( <> <Head> <title>Register | SpoilMyCats</title> <link rel="icon" href="/favicon.ico" /> </Head> <PageWrap> <Header /> <MainScreenStyles> <AuthBox initialScreen="register" /> </MainScreenStyles> </PageWrap> </> ); export default Registet;
// @ts-check /* author gwc0721*/ /* eslint-env node */ const fs = require('fs'); const { promisify } = require('util'); const args = Array.from(process.argv); if (args.length > 0 && /node\.exe$/.test(args[0])) { args.shift(); } if (args.length > 0 && /convert\.js$/.test(args[0])) { args.shift(); } if (args.length === 0) { process.stderr.write('node convert.js <file>'); process.exit(-1); } const filepath = args[0]; let output = null; if (args[1]) { output = args[1]; } (async function() { const data = await promisify(fs.readFile)(filepath); for (let i = 0; i < data.length; ++i) { data[i] ^= 73; } if (output) { await promisify(fs.writeFile)(output, data); } else { process.stdout.write(output); } })();
var cifra=""; var a=0; var r=0; var vec=new Array(5); vec[0]='<img src="Imagenes/descarga.jpg" width="300px" height="150px">'; vec[1]='<img src="Imagenes/CACTUS.jpg" width="300px" height="150px">'; vec[2]='<img src="Imagenes/chiles.jpg" width="300px" height="150px">'; vec[3]='<img src="Imagenes/nachos.jpg" width="300px" height="150px">'; vec[4]='<img src="Imagenes/taco_17.jpg" width="300px" height="150px">'; var msg; var z=""; function vaciar(num){ document.getElementById("n1").value=""; } function imp(num1){ document.getElementById('n1').value=cifra+num1; cifra=document.getElementById("n1").value; a=Number(num); r=Number(r)+Number(a); z=z+vec[0]; if(cierto){ document.getElementById("uno").value="Usado"; cierto=false; } else{ document.getElementById("uno").value = 1; cierto=true; } } function imp(num){ document.getElementById('n1').value=cifra+1; cifra=document.getElementById('n1').value; a=Number(num); r=Number(r)+Number(a); z=z+vec[0]; } function imp1(num){ document.getElementById('n1').value=cifra+2; cifra=document.getElementById('n1').value; a=Number(num); r=Number(r)+Number(a); z=z+vec[1]; } function imp2(num){ document.getElementById('n1').value=cifra+3; cifra=document.getElementById('n1').value; a=Number(num); r=Number(r)+Number(a); z=z+vec[2]; } function imp3(num){ document.getElementById('n1').value=cifra+4; cifra=document.getElementById('n1').value; a=Number(num); r=Number(r)+Number(a); z=z+vec[3]; } function imp4(num){ document.getElementById('n1').value=cifra+5; cifra=document.getElementById('n1').value; a=Number(num); r=Number(r)+Number(a); z=z+vec[4]; } function Carrito(){ document.getElementById('res').innerHTML=" Monto a pagar "+r+"<br>"; document.getElementById('cmt').innerHTML="Has comprado estos objetos"+"<br>"+z; $(document).ready(function(){ $("label").hide().fadeIn(5000); }); }
const path = require('path') const fs = require('fs') const appDir = fs.realpathSync(process.cwd()) const resolVe = rela => path.resolve(appDir, rela) module.exports = { contentBase: resolVe('public'), publicPath: '/', compress: true, //port: 9000 }
const siteSetting = require("../model/sitesetting_model"); const mongoose = require("mongoose"); /** * @param: passing key need to increament (auto increament) * @returns: data will return */ exports.commonSetting = (field)=>{ return new Promise((resolve,reject)=>{ let condition = {}; switch (field) { case "lead": condition = {$inc:{lead:1}} break; case "quotation": condition = {$inc:{quotation:1}} break; case "order": condition = {$inc:{order:1}} break; case "shipment": condition = {$inc:{shipment:1}} break; case "invoice": condition = {$inc:{shipment:1}} break; } siteSetting.findOneAndUpdate({_id:mongoose.Types.ObjectId("604506bcfb0e4f6bfc9ab34b")},condition).then(setting=>{ return resolve(setting) }).catch(err=>{ return reject(err) }) }) }
const i = "foo";
// Initialize state let state = { wakeTime: 0, fraction: 0, margin: 0, stopMargin: 0, walkAway: 0, maxVwap: 0, minSlope: 0, maxVolatility: 0, minLoss: 0, maxRSI: 0, minRelVol: 0, strategy: "change", isTesting: "on", maxOrders: 0, }; // Initialize elements let elements = { inputs: nullifyStateAttributes(state), values: nullifyStateAttributes(state), }; // Init walk/resume action buttons let actionButtons = { walk: null, resume: null, }; function nullifyStateAttributes(state) { return { ...Object.keys(state).reduce((acc, attr) => { return { ...acc, [attr]: null }; }, {}), }; } function showConditionalControls(strategy) { const conditionalControls = [ "minLoss", "maxVolatility", "maxVwap", "minSlope", "minRelVol", ]; const conditionalElMap = { change: ["minLoss"], volatility: ["maxVolatility"], compositeScore: ["maxVwap", "minSlope"], vwap: ["maxVwap"], slope: ["minSlope"], relativeVolume: ["minRelVol"], }; const getWrapper = (id) => document.querySelector(`.input-wrapper#${id}`); conditionalControls.forEach((id) => { getWrapper(id).classList.add("hide"); }); conditionalElMap[strategy].forEach((id) => { getWrapper(id).classList.remove("hide"); }); } function render(state) { Object.entries(state).forEach(function ([attr, val]) { elements.values[attr].innerText = val; elements.inputs[attr].value = val; }); } function setState(attr, value) { state[attr] = value; } function onChange(attr) { return function ({ target }) { if (target.name === "strategy") { showConditionalControls(target.value); } if (target.tagName === "BUTTON") { target.classList.remove(state[attr]); setState(attr, state[attr] === "on" ? "off" : "on"); target.classList.add(state[attr]); } else { const newValue = +target.value; setState(attr, !isNaN(newValue) ? newValue : target.value); } render(state); console.log(state); }; } function bootstrapInput(elements, attr, elType) { const eventTypes = { select: "change", input: "input", button: "click", }; elements.inputs[attr] = document.querySelector(`#${attr} ${elType}`); elements.values[attr] = document.querySelector(`#${attr} .value`); elements.inputs[attr].addEventListener(eventTypes[elType], onChange(attr)); } function getPercentValue(val) { const str = val.toString(); if (str.length > 5) { return +val.toFixed(3); } return val; } function initializeState(config) { Object.entries(config).forEach(function ([attr, val]) { if (attr === "wakeTime") { setState("wakeTime", +config.wakeTime.match(/(\d+)(s|m|h)/)[1]); } else if (attr === "isTesting") { setState("isTesting", val ? "on" : "off"); } else if (attr === "strategy") { setState("strategy", val); } else if (attr === "maxOrders") { setState("maxOrders", val); } else if (attr === "minRelVol") { setState("minRelVol", val); } else if (attr === "maxRSI") { setState("maxRSI", val); } else { setState(attr, getPercentValue(val * 100)); } }); } function setNotification(message, level) { const notifyEl = document.getElementById("notification"); switch (level) { case "info": notifyEl.classList.add("info"); notifyEl.innerText = message; break; case "error": notifyEl.classList.add("error"); notifyEl.innerText = message; break; default: // do nothing } setTimeout(() => { notifyEl.className = ""; notifyEl.innerText = ""; }, 3000); } async function sendWalk() { const res = await fetch("/api/walk"); const portfolio = await res.json(); setWalkButtons(portfolio.frozen); if (portfolio.frozen) { setNotification("Walked away successfully", "info"); } else { setNotification("Walk away failed", "error"); } } async function sendResume() { const res = await fetch("/api/resume"); const portfolio = await res.json(); setWalkButtons(portfolio.frozen); if (!portfolio.frozen) { setNotification("Resumed successfully", "info"); } else { setNotification("Resume failed", "error"); } } async function sendConfig() { const reqData = {}; Object.entries(state).forEach(function ([attr, val]) { if (attr === "wakeTime") { reqData.wakeTime = `${val}m`; } else if (attr === "isTesting") { reqData.isTesting = val === "on"; } else if (attr === "strategy") { reqData.strategy = val; } else if (attr === "maxOrders") { reqData.maxOrders = val; } else if (attr === "minRelVol") { reqData.minRelVol = val; } else if (attr === "maxRSI") { reqData.maxRSI = val; } else { reqData[attr] = val / 100; } }); try { const res = await fetch("/api/config", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(reqData), }); console.log(await res.json()); setNotification("New configuration successful", "info"); } catch (err) { console.error("FAILED POST"); } } function setWalkButtons(frozen) { if (frozen) { actionButtons.walk.classList.remove("on"); actionButtons.resume.classList.add("on"); } else { actionButtons.walk.classList.add("on"); actionButtons.resume.classList.remove("on"); } } window.onload = async function main() { const configRes = await fetch("/api/config"); const config = await configRes.json(); console.log(config); const portfolioRes = await fetch("/api/portfolio"); const portfolio = await portfolioRes.json(); const marketStateRes = await fetch("/api/state"); const marketState = await marketStateRes.json(); bootstrapInput(elements, "strategy", "select"); bootstrapInput(elements, "wakeTime", "input"); bootstrapInput(elements, "maxOrders", "input"); bootstrapInput(elements, "fraction", "input"); bootstrapInput(elements, "margin", "input"); bootstrapInput(elements, "stopMargin", "input"); bootstrapInput(elements, "walkAway", "input"); bootstrapInput(elements, "maxVwap", "input"); bootstrapInput(elements, "minSlope", "input"); bootstrapInput(elements, "maxVolatility", "input"); bootstrapInput(elements, "minLoss", "input"); bootstrapInput(elements, "minRelVol", "input"); bootstrapInput(elements, "maxRSI", "input"); bootstrapInput(elements, "minLoss", "input"); bootstrapInput(elements, "isTesting", "button"); // PERSONAL GAIN const gainDisplayEl = document.getElementById("gain-display"); gainDisplayEl.classList.add(portfolio.gain >= 0 ? "green" : "red"); gainDisplayEl.innerText = `${(portfolio.gain * 100).toFixed(2)}%`; // MARKET GAIN const marketGainDisplayEl = document.getElementById("market-gain"); const marketGain = marketState.marketGain != null ? marketState.marketGain : 0; marketGainDisplayEl.classList.add( marketState.marketGain >= 0 ? "green" : "red" ); marketGainDisplayEl.innerText = `${(marketGain * 100).toFixed(2)}%`; // BTC GAIN const btcGainDisplayEl = document.getElementById("btc-gain"); const btcProduct = marketState.products ? marketState.products.find((prod) => prod.id === "BTC-USD") || { change: 0, } : { change: 0 }; btcGainDisplayEl.classList.add(btcProduct.change >= 0 ? "green" : "red"); btcGainDisplayEl.innerText = `${(btcProduct.change * 100).toFixed(2)}%`; // MARKET SLOPE const marketSlopeEl = document.getElementById("market-slope"); marketSlopeEl.className = ""; switch (marketState.marketSlopeCategory) { case 1: marketSlopeEl.innerHTML = "&darr;"; marketSlopeEl.classList.add("red"); break; case 2: marketSlopeEl.innerHTML = "&searr;"; marketSlopeEl.classList.add("red"); break; case 3: marketSlopeEl.innerHTML = "&rarr;"; marketSlopeEl.classList.add("orange"); break; case 4: marketSlopeEl.innerHTML = "&nearr;"; marketSlopeEl.classList.add("green"); break; case 5: marketSlopeEl.innerHTML = "&uarr;"; marketSlopeEl.classList.add("green"); break; default: marketSlopeEl.innerHTML = "&rarr;"; } const applyButton = document.getElementById("apply"); applyButton.addEventListener("click", sendConfig); actionButtons.walk = document.getElementById("force-walk"); actionButtons.walk.addEventListener("click", sendWalk); actionButtons.resume = document.getElementById("force-resume"); actionButtons.resume.addEventListener("click", sendResume); setWalkButtons(portfolio.frozen); const refreshButton = document.getElementById("refresh"); refreshButton.addEventListener("click", () => window.location.reload()); initializeState(config); elements.inputs["isTesting"].classList.add(state.isTesting); showConditionalControls(state.strategy); render(state); };
import React, { Component } from 'react'; import TodoListItemView from '../presentational/todo_list_item_view'; import NavBar from './nav_bar.js'; import { loadItemData, loadAllTodoLists, updateTodoNoRedirect, deleteItem } from '../actions/index.js'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import RichTextEditor from 'react-rte'; class TodoListItem extends Component { constructor(props) { super(props); this.state = { richTextValue: RichTextEditor.createValueFromString( this.props.initialRichTextValue, 'html' ) }; } componentDidMount() { const itemId = this.props.match.params.itemId; const listName = this.props.match.params.listName; this.props.loadItemData(listName, itemId); } componentWillReceiveProps(nextProps) { return this.setState({ richTextValue: RichTextEditor.createValueFromString( nextProps.initialRichTextValue, 'html' ) }); } getListName = () => { return this.props.match.params.listName; }; toggleCompleted = todo => { const updatedTodo = Object.assign({}, todo, { completed: !todo.completed }); this.props.updateTodoNoRedirect( this.getListName(), this.props.todo.todoId, updatedTodo ); }; saveLocation = location => { const updatedTodo = Object.assign({}, this.props.todo, { latitude: location.lat(), longitude: location.lng() }); this.props.updateTodoNoRedirect( this.getListName(), this.props.todo.todoId, updatedTodo ); }; delete = () => { this.props.history.push(`/list/${this.getListName()}`); return this.props.deleteItem(this.getListName(), this.props.todo.todoId); }; render() { return ( <div> <NavBar /> <TodoListItemView loading={this.props.loading} todo={this.props.todo} listName={this.props.match.params.listName} toggleCompleted={this.toggleCompleted} delete={this.delete} location={{ lat: this.props.todo.latitude, lng: this.props.todo.longitude }} saveLocation={this.saveLocation} richTextValue={this.state.richTextValue} /> </div> ); } } function mapStateToProps(state) { //Whatever is returned will show up as props inside of this component return { todo: state.item.model, loading: state.item.meta.loading, initialRichTextValue: state.item.model.richTextComment //set app state (this.state.RTV) to redux state (this.props.RTV) in didMount/willRecProps }; } function mapDispatchToProps(dispatch) { //Whatever is returned will show up as props inside of the component return bindActionCreators( { loadItemData: loadItemData, loadAllTodoLists: loadAllTodoLists, updateTodoNoRedirect: updateTodoNoRedirect, deleteItem: deleteItem }, dispatch ); } export default connect(mapStateToProps, mapDispatchToProps)(TodoListItem);
import axios from 'axios' import Qs from 'qs' import BASE_URL from '../../common/config/base-url' class BaseApi { static isinIt=false; constructor () { this.createAxios(); this.initNotice() } createAxios () { if (BaseApi.isinIt) { return this.axios=BaseApi.isinIt } let api = axios.create({ // 请求的接口,在请求的时候,如axios.get(url,config);这里的url会覆盖掉config中的url url: '', // 请求方法同上 method: 'post', // default // 基础url前缀 baseURL: BASE_URL, transformRequest: [function (data) { // 这里可以在发送请求之前对请求数据做处理,比如form-data格式化等,这里可以使用开头引入的Qs(这个模块在安装axios的时候就已经安装了,不需要另外安装) data = Qs.stringify(data) return data }], transformResponse: [function (data) { // 这里提前处理返回的数据 try { return JSON.parse(data) } catch (e) { return data } }], // 请求头信息 headers: { }, // parameter参数 params: { }, // post参数,使用axios.post(url,{},config);如果没有额外的也必须要用一个空对象,否则会报错 data: { }, // 设置超时时间 timeout: 5000, // 返回数据类型 responseType: 'json', // default }) api.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; api.interceptors.request.use( (config) => { return this.request(config) }, (err) => { return this.reject(err) }) api.interceptors.response.use( (response) => { return this.response(response) }, (error) => { return this.reject(error) } ) BaseApi.isinIt=this.axios = api } request () { throw Error('必须实现request函数!!!') } response () { throw Error('必须实现response函数!!!') } reject () { throw Error('必须实现reject函数!!!') } initNotice () { throw Error('必须实现通知函数!!!') } } export default BaseApi
var cgi = require('../common/cgi').label, data = require('../data/data').label, striker = $(window.striker); var Label = {}, _this = Label; var tmpl = { list : require('../../tpl/label/list.ejs'), one : require('../../tpl/label/one.ejs') }; module.exports = Label; function getList(){ cgi.list(function(res){ if(res.code === 0){ } }); } Label.label = function(name){ this.dom = $("#"+name); this.nowDom = this.dom.find('.now-label-list'); this.addDom = this.dom.find('.add-label-area'); // if(type === 'sub'){ // this.addDom = $('#addSubLabel'); // this.nowDom = $('#nowSubLabel'); // }else{ // this.addDom = $('#addArtLabel'); // this.nowDom = $('#nowArtLabel'); // } this.listDom = this.addDom.find('.label-list'); this.btnDom = this.addDom.find('.btn'); this.inputDom = this.addDom.find('.form-control'); this._selectDom;//当前选中的元素 //默认没有标签 this.nowDom.hide(); this.addDom.hide(); //已经选中的idmap this.idmap = {}; this.map = {}; this.getData(); this.bindAction(); } Label.label.prototype.bindAction = function(){ var _this = this; this.dom.bind('click',function(e){ var target = $(e.target), action = target.data('action'); _this._selectDom = target; if(_this[action]){ _this[action](e); } }); // // this.nowDom.bind('click',function(e){ // var target = $(e.target), // action = target.data('action'); // _this._selectDom = target; // if(_this[action]){ // _this[action](e); // } // }); } Label.label.prototype.create = function(){ var val = this.inputDom.val(); if(val !== ''){ var param = { name : val }; var _this = this; cgi.create(param,function(res){ if(res.code === 0){ _this.map[res.data.id] = res.data; var html = tmpl.list({list:[res.data]}); _this.listDom.append(html); } }); } } Label.label.prototype.showlist = function(e){ // /console.log(this._selectDom); if(this._selectDom.hasClass('fui-plus')){ this._selectDom.removeClass('fui-plus').addClass('fui-cross'); this.addDom.show(); }else{ this._selectDom.addClass('fui-plus').removeClass('fui-cross'); this.addDom.hide(); } //this.addDom.show(); //this.nowDom.show(); //fui-cross //fui-plus } Label.label.prototype.getData = function(){ var _this = this; cgi.list({},function(res){ if(res.code === 0){ var html = tmpl.list({list:res.data}); _this.listDom.html(html); for(var i = 0,l=res.data.length;i<l;i++){ var item = res.data[i]; _this.map[item.id] = item; } } }); } Label.label.prototype.showEdit = function(data){ var html = tmpl.one({list:data}); this.nowDom.html(html).show(); } Label.label.prototype.select = function(e){ var id = this._selectDom.data('id'); var param = { list : [this.map[id]] } this.idmap[id] = 1; if(this.nowDom.find('.label'+id).length === 0){ var html = tmpl.one(param); this.nowDom.append(html).show(); } } Label.label.prototype.getLabelList = function(){ var list = []; // console.log(this.nowDom.find(".tag").length); // this.nowDom.find(".tag").each(function(e){ // var target = $(e.target), // id = target.data('id'); // if(id){ // list.push(id); // } // }) for(var i in this.idmap){ list.push(i); } return list; } Label.label.prototype.clear = function(){ this.idmap = {}; this.nowDom.html('').hide(); var dom = this.dom.find('.show-btn'); dom.addClass('fui-plus').removeClass('fui-cross'); this.addDom.hide(); } //删除 Label.label.prototype.remove = function(e){ var target = $(e.target), p = target.parent(); var id = p.data('id'); delete this.idmap[id]; p.remove(); } Label.init = function(){ }
var path = require('path'); var core = require(path.join(__dirname, '..')); module.exports = core({ conString: 'epoch_test' });
import styled from "styled-components" export const Container = styled.div` height: 100%; overflow: auto; background: #f5f5f5; .city_body { background: #ebebeb; .hot_city{ line-height: 0.6rem; font-size: 0.28rem; .hot_title{ font-size:.3rem; line-height:.6rem;padding-left: 0.26rem; } .hot_city_list{ width: 96%; background: #f5f5f5; padding-bottom: 0.16rem; display: flex; flex-wrap: wrap; line-height: 0.9rem; padding-left: 0.25rem; .hot_city_name{ margin-top: 0.3rem; margin-right: 0.26rem; width: 1.9rem; height: 0.66rem; background: #fff; text-align: center; line-height: 0.66rem; font-size: 0.28rem; border: 2px solid #e6e6e6; margin-right: 0.26rem; } } } .city_list{ &>div{ width: 100%; } .city_list_item{ .city_title_letter{ line-height: 0.6rem; padding-right: 0.26rem; padding-left: 0.25rem; font-size: 0.4rem; } .city_list_name{ width: 96%; background: #f5f5f5; padding-left: 0.25rem; line-height: 0.9rem; margin-right: 0.26rem; border-bottom: 2px solid #e6e6e6; } } } } /*城市列表下标*/ .city_list_index{ position: fixed; right: 0; top: 0.5rem; &>div{ padding: 0.1rem 0.05rem; font-size: 0.25rem; display: flex; justify-content: center; align-items: center; } } `
/* * @lc app=leetcode.cn id=128 lang=javascript * * [128] 最长连续序列 */ // @lc code=start /** * @param {number[]} nums * @return {number} */ var longestConsecutive = function(nums) { let ans = 0, map = new Map(); for (let i = 0; i < nums.length; i++) { map.set(nums[i], map.get(nums[i]) + 1 || 1); } for (let i = 0; i < nums.length; i++) { let count = 1, num = nums[i]; if (!map.has(num - 1)) { while (map.has(num + 1 )) { num = num + 1; count++; } } ans = Math.max(ans, count); } return ans; }; // @lc code=end
import React from "react" import { Link } from "gatsby" import BackgroundImage from "gatsby-background-image" import Layout from "../components/layout" import SEO from "../components/seo" import MainNav from "../components/MainNav" import MobileNav from "../components/MobileNav" import BtnRequest from "../components/BtnRequest" import BtnContactUs from "../components/BtnContactUs" import BtnViewProducts from "../components/BtnViewProducts" import NewsSection from "../components/NewsSection" import Footer from "../components/Footer" import BackgroundSectionIndex from "../components/image" import { css } from "@emotion/core" import { useTranslation } from "react-i18next" import backenvelopes from "../images/background-envelopes.svg" import machine from "../images/machine.jpg" import ukraine from "../images/ukraine.png" import logosClient from "../images/logos_web.jpg" const IndexPage = props => { const T = useTranslation() if (T.i18n.language !== props.pageContext.langKey) { T.i18n.changeLanguage(props.pageContext.langKey) } const t = key => (typeof key === "string" ? T.t(key) : key[T.i18n.language]) return ( <Layout> <SEO title={t("seoHome")} description={t("metaDescrIndex")} /> <MainNav isHome {...props} /> <MobileNav {...props} /> <BackgroundImage Tag="section" fluid={BackgroundSectionIndex()} css={css` height: calc(100vh - 86.59px); min-height: 590px; display: flex; justify-content: center; align-items: center; @media screen and (min-width: 1250px) { height: 100vh; min-height: 740px; } `} > <div css={css` width: 620px; height: 464px; background: rgba(56, 56, 56, 0.732); border-radius: 3px; color: white; text-align: center; z-index: 3; @media (max-width: 767px) { width: 305px; height: 333px; } `} > <h1 css={css` font-weight: bold; font-size: 64px; margin-bottom: 27px; @media (max-width: 767px) { font-size: 36px; text-align: center; margin: 10px; } `} > {t("mainSlogan")} </h1> <div css={css` @media (max-width: 767px) { display: flex; flex-direction: column-reverse; } `} > <p css={css` font-weight: 500; font-size: 16px; line-height: 24px; margin: 17px 80px 0 80px; @media (max-width: 767px) { display: none; } `} > {t("titleText")} </p> <div css={css` display: flex; justify-content: space-between; margin: 35px 80px 35px 80px; @media (max-width: 767px) { flex-direction: column; margin: 10px auto 15px auto; } `} > <div css={css` width: 205px; @media (max-width: 767px) { width: 220px; margin-bottom: 25px; } `} > <BtnRequest /> </div> <BtnViewProducts /> </div> </div> </div> </BackgroundImage> <section css={css` width: 85%; display: flex; justify-content: center; align-items: center; margin: 100px auto; @media (max-width: 768px) { flex-direction: column-reverse; width: 100%; } `} > <div className="w-full md\:w-1\/3" css={css` background: url(${backenvelopes}), #c5003e; height: 594px; color: white; padding: 40px 50px 0 100px; @media (max-width: 768px) { padding: 26px 26px; height: auto; } `} > <h1 css={css` font-weight: bold; font-size: 48px; padding-bottom: 30px; border-bottom: 1px solid white; width: 201px; transform: rotate(-0.29deg); @media (max-width: 768px) { font-size: 24px; border-bottom: none; text-align: center; margin: 0; padding: 0; width: 100%; } `} > {t("about")} </h1> <p css={css` padding: 40px 0; font-weight: normal; font-size: 18px; line-height: 27px; @media (max-width: 768px) { font-size: 14px; } `} > {t("indexAbout")} </p> <Link to="/about" css={css` color: white; cursor: pointer; font-weight: bold; font-size: 18px; text-decoration: none; @media (max-width: 768px) { font-weight: 900; font-size: 14px; text-decoration: underline; text-align: center; display: block; } `} > {t("learnMore")} </Link> </div> <div className="w-full md\:w-2\/3" css={css` height: 594px; background: url(${machine}); background-size: cover; background-repeat: no-repeat; @media (max-width: 768px) { height: 234px; } `} ></div> </section> <NewsSection /> <section css={css` margin: 80px auto; padding-top: 60px; display: flex; flex-direction: row; justify-content: center; @media (max-width: 768px) { flex-direction: column; margin: 40px auto; } `} > <div css={css` display: flex; align-items: center; padding: 0 20px; `} > <img src={ukraine} alt={`map of Ukraine`} /> </div> <div css={css` padding: 80px 60px; width: 500px; @media (max-width: 768px) { width: 100%; padding: 30px 40px; } `} > <h2 css={css` font-weight: 500; font-size: 48px; @media (max-width: 768px) { font-size: 24px; text-align: center; } `} > {t("indexContactUsTitle")} </h2> <p css={css` font-weight: normal; font-size: 18px; padding: 36px 0; @media (max-width: 768px) { font-size: 16px; } `} > {t("indexContactUs")} </p> <div css={css` width: 100%; > a { @media (max-width: 768px) { margin: 0 auto; } } `} > <BtnContactUs /> </div> </div> </section> <section css={css` background: #ffffff; margin: 45px 0; padding: 45px 0; `} > <h3 css={css` font-weight: 500; font-size: 48px; text-align: center; margin: 0; `} > {t("ourClients")} </h3> <img src={logosClient} alt="client-logos" /> </section> <Footer /> </Layout> ) } export default IndexPage
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import App from './components/app/App.js'; import Main from './components/main/Main.js' // import Project from './components/project/Project.js' import './index.css' const router = ( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={Main} /> </Route> </Router> ) ReactDOM.render( router, document.getElementById('root') );
import React from 'react'; import { Link } from 'react-router'; import NotFoundPage from './NotFoundPage'; import guitarists from '../data/guitarists'; export default class GuitaristPage extends React.Component { render() { const id = this.props.params.id; const guitarist = guitarists.filter((guitarist) => guitarist.id == id)[0]; if (!guitarist) { return <NotFoundPage/>; } return ( <div className="guitarist-full"> <div className="guitarist"> <header/> <div className="picture-container"> <img src={guitarist.image}/> <h2 className="name">{guitarist.name}</h2> </div> <section className="description"> {guitarist.description} </section> </div> <div className="navigateBack"> <Link to="/"> Back to the index</Link> </div> </div> ); } }
"use strict"; var boardLen = 500; var canvas, ctx; var timerId; function getNextPointSerialize(n, posX, posY, lastPosX, lastPosY) { return Module.ccall('getNextPointSerialize', 'number', ['number', 'number', 'number', 'number', 'number'], [n, posX, posY, lastPosX, lastPosY]); } function drawPoint(posX, posY, step) { ctx.beginPath(); ctx.arc(step * posX, step * posY, 3, 0, 360, false); ctx.fillStyle = 'royalblue'; ctx.fill(); ctx.closePath(); } function drawLine(posX, posY, nextPosX, nextPosY, step, color) { ctx.beginPath(); ctx.moveTo(step * posX, step * posY); ctx.lineTo(step * nextPosX, step * nextPosY); ctx.strokeStyle = color; ctx.stroke(); ctx.closePath(); } document.addEventListener('DOMContentLoaded', function() { canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d'); ctx.lineWidth = 1; drawEmptyBoard(); }); function drawEmptyBoard() { var bs = document.getElementById('boardSize'); if (bs.validity.valid) { // Clear original board ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw new board var n = bs.value, step = boardLen / (n - 1); for (var i = 0; i < n; i++) { drawLine(i, 0, i, n, step, 'black'); // Draw a horizontal line from (i, 0) to (i, n) drawLine(0, i, n, i, step, 'black'); // Draw a vertical line from (0, i) to (n, i) } } } /// @param n board size /// @param ms sleep time after drawing a line, in ms function draw(n, ms) { var step = boardLen / (n - 1); var posX = 2, posY = 0, lastPosX = 0, lastPosY = 1; function drawInner() { var nextPos = getNextPointSerialize(n, posX, posY, lastPosX, lastPosY), nextPosX = nextPos / n | 0, nextPosY = nextPos % n; drawPoint(posX, posY, step); drawLine(posX, posY, nextPosX, nextPosY, step, 'deeppink'); if (nextPosX == 2 && nextPosY == 0) /* the Knight has returned to the beginning point */ { stopDraw(); // Clear timer, for the case ms != 0 return true; // Indicate that the drawing has finished, for the case ms == 0 } else { lastPosX = posX; lastPosY = posY; posX = nextPosX; posY = nextPosY; return false; } } if (ms == 0) while (!drawInner()) continue; else timerId = setInterval(drawInner, ms); } function startDraw() { var bs = document.getElementById('boardSize'), st = document.getElementById('strokeTime'); if (bs.validity.valid && st.validity.valid) draw(parseInt(bs.value), parseInt(st.value)); } function stopDraw() { if (timerId) { clearInterval(timerId); timerId = null; } }
var ST = jQuery.noConflict(); ST(document).ready(function(){ ST('#nepaliDate1').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate2').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate4').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate5').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate6').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate7').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate8').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate9').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate10').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate11').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate12').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate13').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate14').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate15').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate16').nepaliDatePicker({ onFocus: true, npdMonth: true, npdYear: true, ndpTriggerButton: false, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate25').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate26').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate27').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#nepaliDate').nepaliDatePicker({ ndpEnglishInput: 'englishDate' }); ST('#nepaliDate2').nepaliDatePicker(); ST('#nepaliDate3').nepaliDatePicker({ onFocus: false, npdMonth: true, npdYear: true, ndpTriggerButton: true, ndpTriggerButtonText: 'Date', ndpTriggerButtonClass: 'btn btn-primary btn-sm' }); ST('#englishDate').change(function(){ ST('#nepaliDate').val(AD2BS(ST('#englishDate').val())); }); ST('#englishDate9').change(function(){ ST('#nepaliDate9').val(AD2BS(ST('#englishDate9').val())); }); ST('#nepaliDate9').change(function(){ ST('#englishDate9').val(BS2AD(ST('#nepaliDate9').val())); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("./utils"); // Devise Token Auth update the token on each controller or every 7 seconds // In this example, 3 requests are made with 3 different token // Login user utils_1.updatePasswordByToken(); // // GET /users 7.5sec after login // setTimeout(() => { // getUsers(); // }, 7500); // // GET /users/2 15sec after login // setTimeout(() => { // getUserById(2); // }, 15000); // // GET /users/2 16sec after login // setTimeout(() => { // signOut(); // }, 16000); // // Reset password // setTimeout(() => { // resetPassword(); // }, 20000);
/** * Make sure the browser supports `history.pushState`. */ const pushState = () => !window.history.pushState; /** * Make sure there is an `el` and `href`. */ const exists = ({ el, href }) => !el || !href; /** * If the user is pressing ctrl + click, the browser will open a new tab. */ const newTab = ({ event }) => event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey; /** * If the link has `_blank` target. */ const blank = ({ el }) => el.hasAttribute('target') && el.target === '_blank'; /** * If the link has download attribute. */ const download = ({ el }) => el.getAttribute && typeof el.getAttribute('download') === 'string'; /** * If the links contains [data-transition-prevent] or [data-transition-prevent="self"]. */ const preventSelf = ({ el }) => el.hasAttribute('data-prevent'); export class Prevent { constructor() { this.suite = []; this.tests = new Map(); this.init(); } init() { // Add defaults this.add('pushState', pushState); this.add('exists', exists); this.add('newTab', newTab); this.add('blank', blank); this.add('download', download); this.add('preventSelf', preventSelf); } add(name, check, suite = true) { this.tests.set(name, check); suite && this.suite.push(name); } /** * Run individual test */ run(name, el, event, href) { return this.tests.get(name)({ el, event, href, }); } /** * Run test suite */ checkLink(el, event, href) { return this.suite.some((name) => this.run(name, el, event, href)); } }
import React, { useState } from "react"; export default function Login({userData, handleLogin = f => f}) { const [data, setData] = useState({ email: "", pass: "" }); const [error, setError] = useState(""); const [logged, setLogged] = useState(false); function validateEmail(email) { const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function validate() { let error = ""; if(!validateEmail(data["email"])) { error = "To nie jest adres e-mail"; } if (error === ""){ for(const user of userData) { if (data["email"] === user.email && data["pass"] === user.password) { setError(""); return user; } } error = "Nieprawidłowy e-mail lub hasło"; } setError(error); return false; } function submit(e) { e.preventDefault(); let user = validate(); if(user !== false) { setLogged(true); handleLogin(user); } } return ( <form onSubmit={submit}> <label>E-mail:</label><br/> <input value={data.email} type="text" required onChange={ (e) => {setData({email: e.target.value, pass: data.pass})} }/><br/> <label>Hasło:</label><br/> <input value={data.pass} type="password" required onChange={ (e) => {setData({email: data.email, pass: e.target.value})} }/><br/> <input type="submit" value="Zaloguj się"/> {logged && <p>Pomyślnie zalogowano!</p>} <p>{error}</p> </form> ) }
import React from "react"; export default function UpArrow() { return ( <svg aria-hidden="true" focusable="false" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" > <path fill="currentColor" d="M8 256C8 119 119 8 256 8s248 111 248 248-111 248-248 248S8 393 8 256zm143.6 28.9l72.4-75.5V392c0 13.3 10.7 24 24 24h16c13.3 0 24-10.7 24-24V209.4l72.4 75.5c9.3 9.7 24.8 9.9 34.3.4l10.9-11c9.4-9.4 9.4-24.6 0-33.9L273 107.7c-9.4-9.4-24.6-9.4-33.9 0L106.3 240.4c-9.4 9.4-9.4 24.6 0 33.9l10.9 11c9.6 9.5 25.1 9.3 34.4-.4z" ></path> </svg> ); }
declare function Test(message: string, testFunction: Function): void; declare function pass(message: string): void; declare function fail(message: string): void;
import React from 'react'; import { Link } from 'react-router-dom'; import TodoButton from '../TodoButton'; const Home = () => ( <TodoButton component={Link} to="/tasks"> Go to the todo list </TodoButton> ); export default Home;
import React from 'react' import { Link } from 'gatsby' import Layout from '../components/layout' const AudioExamples = () => ( <Layout> <Link to="/"><i class="fa fa-home" aria-hidden="true"></i></Link> <br></br> <br></br> <h1>Audio Examples</h1> <p>Below are some examples of Benjamin Kleeman's audio skills -- writing, performing, recording, and producing.</p> <div> <h2><a href="https://thewaysofteaandfailure.bandcamp.com/" target="_blank">The Ways of Tea and Failure</a></h2> <h5>2016 - Present</h5> <a href="https://thewaysofteaandfailure.bandcamp.com/" target="_blank"><img src="https://f4.bcbits.com/img/a2805234254_2.jpg" style={{ height: `13rem`, width: `13rem` }}></img></a> <p>A solo electronic music project that began in 2016 when Benjamin first began working with synthesizers in a DAW.</p> </div> <div> <h2><a href="https://hexeddecimal.bandcamp.com/releases" target="_blank">Hexed Decimal - Spectral Embrace</a></h2> <h5>2018</h5> <a href="https://hexeddecimal.bandcamp.com/releases" target="_blank"><img src="https://f4.bcbits.com/img/a0407812987_16.jpg/" style={{ height: `13rem`, width: `13rem` }}></img></a> <p>An all analog song stylized as a classic video game score.</p> </div> <Link to="/">Go back to the homepage</Link> </Layout> ) export default AudioExamples
import Axios from "axios"; import EventBus from './../../event-bus'; var _ = require('lodash'); export default { template: "<Lightlog/>", data() { return { lightLogs: [] } }, mounted() { this.GetLightLogs(); EventBus.$on("LightsChanged", () => { this.GetLightLogs(); }); }, methods: { GetLightLogs: function () { Axios.get('/api/lights/logs').then(result => { this.lightLogs = result.data; }); } }, computed: { orderedLogs: function () { return _.orderBy(this.lightLogs, 'unixTimeStamp', 'desc') } } };
import React from "react" import { useDispatch, useSelector } from "react-redux" import { vote } from "../reducers/anecdoteReducer" import { showNotification } from "../reducers/notificationReducer" const AnecdoteList = () => { const anecdotes = useSelector((state) => state.anecdotes) const filter = useSelector((state) => state.filter) const dispatch = useDispatch() function sortByVotes(a, b) { return a.votes < b.votes ? 1 : a.votes > b.votes ? -1 : 0 } function voteAnecdote(anecdote) { dispatch(vote(anecdote)) dispatch(showNotification(`You just voted '${anecdote.content}'`)) } const visibleAnecdotes = filter ? anecdotes.filter((anec) => anec.content.toUpperCase().includes(filter.toUpperCase()) ) : anecdotes return ( <div> {visibleAnecdotes.sort(sortByVotes).map((anecdote) => ( <div key={anecdote.id}> <div>{anecdote.content}</div> <div> has {anecdote.votes} <button onClick={() => voteAnecdote(anecdote)}>vote</button> </div> </div> ))} </div> ) } export default AnecdoteList
import React from "react"; import "./Item.css"; let Item = (props) => ( <div> <h1>{props.data.name}</h1> <h3>{props.data.desc}</h3> <img alt="" src={props.data.url} /> <button type="submit" onClick={props.handleRemove}>Remove</button> </div> ) export default Item;
const {shaders, Sphere} = spritejs.ext3d; const defaultEarthFragment = `precision highp float; precision highp int; varying vec3 vNormal; varying vec4 vColor; uniform vec4 directionalLight; //平行光 uniform sampler2D tMap; varying vec2 vUv; varying float fCos; uniform vec4 pointLightColor; // 点光源颜色 uniform vec4 ambientColor; // 环境光 uniform vec2 uResolution; void main() { vec4 color = vColor; vec4 texColor = texture2D(tMap, vUv); vec2 st = gl_FragCoord.xy / uResolution; vec3 light = normalize(directionalLight.xyz); float shading = dot(vNormal, light) * directionalLight.w; float alpha = texColor.a; color.rgb = mix(texColor.rgb, color.rgb, 1.0 - alpha); color.a = texColor.a + (1.0 - texColor.a) * color.a; vec3 diffuse = pointLightColor.rgb * color.rgb * pointLightColor.a * fCos;// 计算点光源漫反射颜色 vec3 ambient = ambientColor.rgb * color.rgb;// 计算环境光反射颜色 color = vec4(diffuse + ambient, color.a); float d = distance(st, vec2(0.5)); gl_FragColor.rgb = color.rgb + shading + 0.3 * pow((1.0 - d), 3.0); gl_FragColor.a = color.a; } `; const defaultEarthVertex = shaders.GEOMETRY_WITH_TEXTURE.vertex; export function createEarth(layer, {vertex = defaultEarthVertex, fragment = defaultEarthFragment, texture, ...attrs} = {}) { const program = layer.createProgram({ fragment, vertex, // transparent: true, cullFace: null, texture, }); attrs = Object.assign({ widthSegments: 64, heightSegments: 32, }, attrs); const earth = new Sphere(program, attrs); layer.append(earth); return earth; }
/** * toString() --Tranforma uma array em uma string, separado por virgula * join() -- Tranforma uma array em uma string * indexOf() --Procura um elemento especifico na array e retorna seu index, caso contrario -1 * array.pop() --Exclui o ultimo item da lista * array.shift() --Exclui o primeiro item da lista * array.push() --Adiciona um novo item na lista * array[index] = 'item' --para alterar ou também adicionar um novo item na lista * array.splice(p:index que deseja remover, p:quantidade que deseja remover). ex: lista.splice(1, 1) * array1.concat(array2) --Concatena duas lista * array.sort() -- Organiza a lista em ordem alfabetica * array.reverse() --Organiza em ordem decrescente * array.map(function) --Mapeia a lista e executa uma função em cada elemento da lista * array.filter(function) --filtra a lista e retorna true || false dependendo da condição * array.every() --aplica a todos elementos de uma array uma condição, se for satisfeita retorna true, caso contrario, false * array.some() --aplica a alguns elementos de uma array uma condição, se for satisfeita retorna true, caso contrario, false * array.find() --procura determinado item na lista e retorna o mesmo, caso a condição for satisfeta * array.findIndex() --o nome já explicativo * */ let lista = [50, 7, 8, 15, 20]; let lista2 = []; /* //function map lista2 = lista.map(function(item) { return item * 2; }) for(let i in lista){ lista2.push(lista[i]*2); } */ /* lista2 = lista.filter(function(item) { if(item >= 20) { return true; }else { return false; } }) lista2 = lista.every(function(item){ // podemos usar some() aqui tb dependendo do caso return (item < 20)? true : false//return ()? true:false == if() {return true} else {return false} }) */ let cadastro = [ {id:1, nome:'Renato', sobrenome: 'Oliveira'}, {id:2, nome:'Rai', sobrenome: 'Silva'}, {id:3, nome:'Ricardo', sobrenome: 'Crispim'}, ] let pessoa = cadastro.find(function(item) { return (item.id == 2) ? true : false; }) let res = pessoa; console.log(res)
import React from 'react'; import logo from './logo.svg'; import './App.css'; class App extends React.Component { constructor(props) { super(props); this.state = { greenClass: 'green', yellowClass: 'yellowOff', redClass: 'redOff' } } handleGreenClick = () => { this.setState({greenClass: !this.state.greenClass}); this.setState({yellowClass: 'yellowOff'}); this.setState({redClass: 'redOff'}); } handleYellowClick = () => { this.setState({yellowClass: !this.state.yellowClass}); this.setState({greenClass: 'greenOff'}); this.setState({redClass: 'redOff'}); } handleRedClick = () => { this.setState({redClass: !this.state.redClass}); this.setState({greenClass: 'greenOff'}); this.setState({yellowClass: 'yellowOff'}); } render() { return ( <div> <h3> Click the stoplights to change them </h3> <div class="container"> <br /> <div class={this.state.greenClass ? 'greenOff': 'green'} onClick= {this.handleGreenClick}></div> <br /> <div class={this.state.yellowClass ? 'yellowOff': 'yellow'} onClick={this.handleYellowClick}></div> <br /> <div class={this.state.redClass ? 'redOff': 'red'} onClick={this.handleRedClick}></div> </div> </div> ); } } export default App;
/** * user相关reducer */ import * as actionTypes from '../action/actionTypes'; import * as nativeApi from '../config/nativeApi'; const initialState = { user: {}, // 用户登录信息 userShop: {}, // 选择登录的店铺信息 userRole:[], // 根据用户选择的店铺的权限 userFinanceInfo: {}, merchantData:{},//商户基本信息 userRoleList: [], // 用户权限key merchant:[ { name: '主播', merchantType: "anchor", agreement:'ZB', auditStatus:'unSubmit' }, { name: '家族长', merchantType: "familyL1", agreement:'FAMILY', auditStatus:'unSubmit' }, { name: '公会', merchantType: "familyL2", agreement:'TRADE_UNION', auditStatus:'unSubmit' }, { name: '商户', merchantType: "shops", agreement:'MERCHANT', auditStatus:'unSubmit' }, { name: '合伙人', merchantType: "company", agreement:'PARTNER', auditStatus:'unSubmit' }, { name: '个人/团队/公司', merchantType: "personal", agreement:'PERSONAL', auditStatus:'unSubmit' }, ], messageData:[],//系统消息 }; export default (state = JSON.parse(JSON.stringify(initialState)), action) => { switch (action.type) { case actionTypes.FETCH_REGISTER: return { ...JSON.parse(JSON.stringify(initialState)), user: action.data, userShop:{} } case actionTypes.FETCH_LOGIN: return { ...JSON.parse(JSON.stringify(initialState)), user: action.data } case actionTypes.CHOOSE_SHOP: return { ...state, userShop: action.data } case actionTypes.CHANGE_STATE: return { ...state, ...action.data } case actionTypes.USERROLELIST: return { ...state, userRoleList: action.data } default: return state } };
import mockNaja from './setup/mockNaja'; import fakeXhr from './setup/fakeXhr'; import {assert} from 'chai'; import UniqueExtension from '../src/extensions/UniqueExtension'; describe('UniqueExtension', function () { fakeXhr(); it('aborts previous request', function () { const naja = mockNaja(); new UniqueExtension(naja); naja.makeRequest('GET', '/UniqueExtension/enabled/first'); naja.makeRequest('GET', '/UniqueExtension/enabled/second'); assert.isTrue(this.requests[0].aborted); }); it('does not abort request if disabled', function (done) { const naja = mockNaja(); new UniqueExtension(naja); naja.makeRequest('GET', '/UniqueExtension/disabled/first').then(() => { done(); }); naja.makeRequest('GET', '/UniqueExtension/disabled/second', null, {unique: false}); this.requests[0].respond(200, {'Content-Type': 'application/json'}, JSON.stringify({answer: 42})); }); });
var searchData= [ ['vl53l0x_5fcalibration_5fparameter_5fs_91',['VL53L0X_Calibration_Parameter_S',['../structVL53L0X__Calibration__Parameter__S.html',1,'']]] ];
import React from 'react' import './fnMobx.scss' import { inject, observer } from 'mobx-react' import styled from 'styled-components' const Div = styled.div` font-size:36px; color: red; ` function fnMobx(props) { // console.log(props) // console.log(props.fnMobxStore) // console.log(props.fnMobxStore.fnMobxCount) let { fnMobxCount: count } = props.fnMobxStore const add = () => { console.log('add') props.fnMobxStore.add(2) } const subtract = () => { console.log('subtract') props.fnMobxStore.subtract(3) } // console.log(fnMobxStore) return ( <> <Div>fn Mobx</Div> <div className="fnMobx"> <div className="count">{count}</div> <div className="calculator"> <button onClick={() => add()}>+</button> <button onClick={() => subtract()}>-</button> </div> </div> </> ) } export default inject('fnMobxStore')(observer(fnMobx)) // export default fnMobx
import React from 'react'; import TextInput from '../common/TextInput'; import CheckBox from '../common/CheckBox'; import PropTypes from 'prop-types'; const MessageForm = ({message, onSave, onChange}) => { return ( <form> <h1>Ajouter un message</h1> <TextInput name="message" label="Message" value={message.message} onChange={onChange} /> <CheckBox name="private" label="Privé" onChange={onChange} /> <input type="submit" value='Sauvegarder' className="btn btn-primary" onClick={onSave} /> </form> ); }; MessageForm.propTypes = { message: PropTypes.object.isRequired, onSave: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, }; export default MessageForm;
angular.module('app.component2', ['ngRoute', 'app.component2.templates']) .config(function($routeProvider) { 'use strict'; $routeProvider.when('/component-2/dialog-b', { templateUrl: 'component-2/dialog-b/dialog-b.html', controller: 'BookFilterController', resolve: { genres: function($http) { return $http.get('/component-2/bookGenres.json'); }, books: function(bookDataFactory) { bookDataFactory.getBooks(); } } }); });
const markrXML = require("../markrXML"); describe("markrXML middleware", () => { const mockResObj = () => { const res = {}; res.status = jest.fn().mockReturnValue(res); res.send = jest.fn().mockReturnValue(res); return res; }; const mockRes = mockResObj(); const mockNext = jest.fn(); afterEach(() => { mockRes.status.mockClear(); mockRes.send.mockClear(); mockNext.mockClear(); }); it("should proceed if the content type is valid", () => { const mockReq = { header: jest.fn().mockReturnValue("text/xml+markr") }; markrXML(mockReq, mockRes, mockNext); expect(mockRes.status.mock.calls.length).toBe(0); expect(mockRes.send.mock.calls.length).toBe(0); expect(mockNext.mock.calls.length).toBe(1); }); it("should send 415 if the content type is xml", () => { invalidCase("text/xml"); }); it("should send 415 if the content type is json", () => { invalidCase("application/json"); }); it("should send 415 if the content type is not defined", () => { invalidCase(undefined); }); function invalidCase(contentType) { const mockReq = { header: jest.fn().mockReturnValue(contentType) }; markrXML(mockReq, mockRes, mockNext); expect(mockRes.status.mock.calls.length).toBe(1); expect(mockRes.status.mock.calls[0][0]).toBe(415); expect(mockRes.send.mock.calls.length).toBe(1); expect(mockRes.send.mock.calls[0][0]).toBe("Unsupported Media Type"); expect(mockNext.mock.calls.length).toBe(0); } });
var express= require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); var mailer = require('nodemailer'); var transporter = mailer.createTransport('smtps://jamie337nichols%40gmail.com:E32414D9BD@smtp.gmail.com'); var mailOptions = { from:'"Big Bug ?" <jamie337nichols@gmail.com>', to:'jamie337nichols@gmail.com', subject:"Someone Joined", text:"Someone joined the game. come play http://allmyfiles.ddns.net:2046", html:"<h1>Someone Joined</h1><a href='http://allmyfiles.ddns.net:2046'>Come play</a>" }; var bootTime = 300; var requestRate = bootTime/2; requestRate *= 1000; bootTime*=1000; var bugies = {}; connections = []; server.listen(process.env.PORT || 2046); app.use(express.static(__dirname + '/')); app.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); }); io.sockets.on('connection',function(socket){ transporter.sendMail(mailOptions,function(error,info){ if(error){ return console.log(error); } console.log("Message Sent: " + info.response); }); connections.push(socket); console.log("Connected: %s sockets connected",connections.length); //disconnect socket.on("disconnect",function(data){ connections.splice(connections.indexOf(socket),1); bugid = socket.id.replace("/#",""); delete bugies[bugid]; io.sockets.emit("remove bug",bugid); console.log("Disconnected: %s sockets connected",Object.keys(bugies).length); console.log("Buggies Object Has "+Object.keys(bugies).join(", ") + " in it"); console.log(bugies); }); socket.on('boot',function(bugid){ bootBug("You've been idle too long","Refresh Page and stay active"); io.sockets.connected["/X"+bugid].disconnect(); }); socket.emit('start',bugies); socket.on('add bugy',function(bug){ console.log("buggy added"); console.log(bug); if(bug){ bugies[bug.id] = bug; console.log(); io.sockets.emit('bugy added',bug); } }); setInterval(function(){ io.sockets.emit('request update'); },requestRate); var to = setTimeout(function(){ bootBug("You've been idle too long","Refresh Page and stay active"); },bootTime); socket.on('update bug',function(bug){ if(parseInt(bug.x) != parseInt(bugies[bug.id].x) || parseInt(bug.y) != parseInt(bugies[bug.id].y)){ clearTimeout(to); to = setTimeout(function(){ bootBug("You've been idle too long","Refresh Page and stay active"); },bootTime); } bugies[bug.id] = bug; io.sockets.emit('update a bug',bug); }); socket.on('remove bug',function(bug){ delete bugies[bug.id]; }); socket.on('request update',function(){ io.sockets.emit('request update'); }); function bootBug(r,f){ socket.emit("force disconnect",{reason:r,fix:f}); socket.disconnect(); } });
require('dotenv').config() const express = require('express') const morgan = require('morgan') const cors = require('cors') const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) const jwt = require('express-jwt') const jwksRsa = require('jwks-rsa') const PORT = process.env.PORT || 4000 const app = express() // Set up Auth0 configuration const authConfig = { domain: 'rosenmatt1.auth0.com', audience: 'http://localhost4000' } // Define middleware that validates incoming bearer tokens // using JWKS from YOUR_DOMAIN const checkJwt = jwt({ secret: jwksRsa.expressJwtSecret({ cache: true, rateLimit: true, jwksRequestsPerMinute: 5, jwksUri: `https://${authConfig.domain}/.well-known/jwks.json` }), audience: authConfig.audience, issuer: `https://${authConfig.domain}/`, algorithm: ['RS256'] }) // Middleware app.use(cors()) app.use(morgan('dev')) app.use(express.json()) //give body parsing // Sequelize Models const db = require('./models') const Category = db.Category const Product = db.Product // Router files app.post('/api/checkout', async (req, res, next) => { const lineItem = req.body const lineItems = [lineItem] try { //Create the session const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: lineItems, success_url: 'http://localhost:3000/success', cancel_url: 'http://localhost:3000/cancel', }) //send session to client res.json({ session }) } catch (error) { next(error) // res.status(400).json({ error }) } }) // Routes app.get('/api/test', (req, res) => { res.json({ message: 'Route working' }) // const error = new Error('it blew up') // next(error) }) app.get('/api/categories', (req, res, next) => { Category.findAll({ include:[{ model: Product }] }) .then(categories => { res.json({ categories }) }) .catch(error => { next(error) }) }) app.get('/api/products', (req, res, next) => { Product.findAll({ include: [{ model: Category }] }) .then(products => { res.json({ products }) }) .catch(error => { next(error) }) }) app.get('/api/products/:id', (req, res, next) => { const id = req.params.id Product.findByPk(id) .then(product => { res.json({ product }) }) .catch(error => { console.log(error) }) }) // Define an endpoint that must be called with an access token app.get('/api/external', checkJwt, (req, res) => { res.send({ msg: 'Your Access Token was successfully validated!' }) }) // Error handling // The following 2 `app.use`'s MUST follow ALL your routes/middleware app.use(notFound) app.use(errorHandler) // eslint-disable-next-line function notFound(req, res, next) { res.status(404).send({ error: 'Not found!', status: 404, url: req.originalUrl }) } // eslint-disable-next-line function errorHandler(err, req, res, next) { console.error('ERROR', err) const stack = process.env.NODE_ENV !== 'production' ? err.stack : undefined res.status(500).send({ error: err.message, stack, url: req.originalUrl }) } app.listen(PORT, () => { console.log(`Server running on port: ${PORT}`) })
export default { zh: { netAnalysis: { uploadtip: '只能上传txt/egde/excel/csv文件', // uploadtip: '只能上传txt/egde/excel/csv文件,且不超过500kb', displayDiagTitle: '网络可视化', importMatrix: '导入矩阵' } }, en: { netAnalysis: { uploadtip: 'Only submit matrix as txt/egde/excel/csv types.', // uploadtip: 'Only submit file as txt/egde/excel/csv types. And no more than 500kbyte', displayDiagTitle: 'Network Viewer', importMatrix: 'import matrix' } } }
function compressor(str) { let builder = ""; let arr = str.split(""); let curr = arr[0]; let counter = 1; let gotsmaller = false; for (let i = 1; i < arr.length; i++) { if (curr == arr[i]) { gotsmaller = true; counter++; } else { builder += curr + counter; curr = arr[i]; counter = 1; } } builder += curr + counter; if (gotsmaller) { return builder; } else { return str; } } console.log(compressor("aabcccccaaa")); console.log(compressor("abcde"));
export const DRAW_X = 'DRAW_X' export const DRAW_O = 'DRAW_O' export const PLAYER_X = 'PLAYER_X' export const PLAYER_O = 'PLAYER_X' export const TURN = 'TURN' export const X_WINS = 'X_WINS' export const O_WINS = 'O_WINS' export const TIE = 'TIE'
/* * @Description: 这是一个工厂函数导出app的实例 * @Autor: ZFY * @Date: 2019-11-11 14:47:35 * @LastEditTime: 2019-11-15 17:17:56 */ import '@babel/polyfill' import Vue from 'vue' import App from './App.vue' import createRouter from './router/index' import createI18n from './lang' import { sync } from 'vuex-router-sync' import ElementLocale from 'element-ui/lib/locale' import '@/config' import '@/styles/index.scss' // global css import '@/icons' // icon export function createApp(store) { const router = createRouter(store) // <--- pass `store` to `createRouter` function const i18n = createI18n(store) ElementLocale.i18n((key, value) => i18n.t(key, value)) sync(store, router) const app = new Vue({ router, store, i18n, render: (h) => h(App) }) return { app, router, store } }
const urlExists = require('url-exists'); const fetch = require('node-fetch'); module.exports.validateUrls = (urls) => { return new Promise((resolve, reject) => { let response = [] let i = 1 for (let link of urls){ response.push(fetch(link)) } Promise.allSettled(response).then((res)=>{ const newArray = res.map((item,index)=>{ //console.log(!item.value); if (!item.value) { urls[index].status = 400 urls[index].statusText = 'Fail' } else { urls[index].status = item.value.status urls[index].statusText = item.value.statusText } return urls[index]; }) resolve(newArray); }).catch(err => { reject(err); }) }) }
import { $, urlencode, makeCSS, getElement, load } from "./router/utils.js"; import MatSpinner from "./custom-elements/matspinner.js"; export const ProdMode = () => location.hostname !== "localhost"; export const _URLHOST = window.location.host.includes("localhost") ? "localhost:5000" : "webmsg.herokuapp.com"; export const URLBASE = `${window.location.protocol}//${_URLHOST}`; export const localWebsocketURL = a => `${ "https:" === window.location.protocol ? "wss://" : "ws://" }${_URLHOST}/${a}`; class SocketConn { __defaultOnMessage(e) { if (["ping", "pong"].includes(e.data)) { return; } const data = JSON.parse(e.data); this._socketID = data.socket_id; } startConn(_ws_) { return new Promise((resolve, reject) => { this.socket = new WebSocket(localWebsocketURL(_ws_)); this.socket.onopen = () => { this.socket.send("__init__"); this.socket.onmessage = this.__defaultOnMessage; this._pingPongs(); resolve(this.socket); }; this.socket.onerror = e => reject(e); }); } close() { try { this.socket.close(); } catch (e) { console.warn(e); } } send(data) { return this.socket.send(JSON.stringify(data)); } sendString(data) { return this.socket.send(data); } /** * @param {(MessageEvent) => void} func */ set onmessage(func) { this.socket.onmessage = e => { if (e.data === "ping" || e.data === "pong") { return; } else { return func(e); } }; } get readyState() { return this.socket.readyState; } get isUsable() { if (!this.socket) { return true; } return [WebSocket.OPEN, WebSocket.CONNECTING].includes( this.socket.readyState ); } _pingPongs() { this.pingtimer = setTimeout(() => { if (this.socket.readyState === this.socket.OPEN) { this.socket.send("ping"); this._pingPongs(); } else { clearTimeout(this.pingtimer); } }, 20000); } constructor() {} } let socketConnection; /** * @returns {SocketConn} * */ export const getSocket = () => { return !!(socketConnection || {}).isUsable ? socketConnection : ((socketConnection = new SocketConn()), socketConnection); }; export class Requests { static async get(_url, relative = true, headers = {}) { let url; if (relative) { url = URLBASE + _url; } else { url = _url; } return await fetch(url, { headers, credentials: "include" }); } static async post( _url, relative = true, data, headers = { "content-type": "application/x-www-form-urlencoded" } ) { let url; if (relative) { url = URLBASE + _url; } else { url = _url; } return await fetch(url, { method: "post", body: data, headers, credentials: "include" }); } } export const matInput = (() => { function onblur(c, d) { if (!c.attrs.value || !c.attrs.value.trim()) { const f = getElement(c, d); f.attrs.class.delete("moveup"); f.attrs.class.add("movedown"); f.update(); setTimeout(() => (f.attrs.class.delete("movedown"), f.update()), 110); } } function onfocus(c, d) { const f = getElement(c, d); f.attrs.class.add("moveup"); f.attrs.class.delete("movedown"); f.update(); } const a = (b, listeners = {}, d, placeHolderId) => { const defaultListeners = {}; if (!listeners.blur) { defaultListeners.blur = function() { onblur(this, placeHolderId); this.update(); }; } if (!listeners.focus) { defaultListeners.focus = function() { this.attrs.untouched = false; onfocus(this, placeHolderId); }; if (!listeners.keydown) { defaultListeners.keydown = function(e) { if (e.keyCode === 85 && e.ctrlKey) { e.preventDefault(); this.$$element.value = this.$$element.value.slice( this.$$element.selectionStart, this.$$element.value.length ); this.$$element.setSelectionRange(0, 0); } }; } if (!listeners.keyup) { defaultListeners.keyup = function() { return (this.attrs.value = this.$$element.value); }; } } return { idx: b, element: "input", attrs: { type: d ? "password" : "text", spellcheck: !1, class: "paper-input" }, onrender() { this.attrs.value ? this.$$element.focus() : ((this.attrs.untouched = !0), (this.attrs.clean = !0)); }, events: { ...listeners, ...defaultListeners } }; }; return ( placeHolderId, placeHolderText, inputId, inputEventListeners, isPassword = false ) => ({ element: "div", children: [ { idx: placeHolderId, onrender() { const n = getElement(this, inputId); n && n.$$element && n.$$element.value.trim() && (this.attrs.class = new Set(["_animate", "moveup"])); }, element: "div", textContent: placeHolderText, attrs: { class: "_animate" } }, a(inputId, inputEventListeners, isPassword, placeHolderId) ] }); })(); const connErrComponent = router => ({ element: "div", status: 503, textContent: "An error occured while contacting the server..please reload the page and try again", attrs: { style: { margin: "auto", "text-align": "center" }, class: "_errComponent" }, children: [ { element: "button", attrs: { style: { background: "#fff", color: "#000", border: "1px solid #6f70ee", "border-radius": "20px", display: "block", margin: "auto", "margin-top": "20px", padding: "8px", width: "20%", outline: "none", cursor: "pointer" }, class: "ripple" }, textContent: "Reload", events: { click() { return getConnection(router); } } } ] }); const _getConnOnError = (e, router) => { console.log(e); return ( router.registerRoute(connErrComponent(router), !0), setTimeout( () => (router.pushStatus(503), (router.stopSubsequentRenders = true)), 500 ) ); }; const _makeRequest = async (st = true) => { router.stopSubsequentRenders = false; $.empty(router.root); router.root.appendChild( new MatSpinner( null, null, makeCSS({ margin: "auto", position: "fixed", top: 0, bottom: 0, left: 0, right: 0 }) ) ); router.root.appendChild( (() => { const div = $.create("div", { style: "margin:auto;text-align:center" }); div.textContent = "Connecting to the server"; return div; })() ); await Requests.get("/api/gen_204"); setTimeout(() => (st ? router.startLoad() : void 0), 450); }; export async function getConnection(router, st) { return retry(() => _makeRequest(st), 2, e => { _getConnOnError(e, router); throw new Error("e"); }); } class UtilsService { _setVars() { this.chatID = this.THERE = null; } async getIntegrity() { const a = await (await Requests.post( "/api/integrity/", true, urlencode({ integrity: this.Integrity }) )).json(); const resp = a.key; this.Integrity = resp; return resp; } async getUser(forceRecheck = false, getName = false) { if (!navigator.onLine) { return localStorage.getItem("$$user"); } if (this.HERE && !forceRecheck) { if (getName) { return this.HERE; } return true; } try { const resp = await Requests.post("/api/getuser"); if (resp.ok && !resp.error) { const user = await resp.text(); this.HERE = user.substr(3); localStorage.setItem("$$user", this.HERE); if (getName) { return this.HERE; } return true; } else { return false; } } catch (e) { console.log(e); return false; } } constructor() { this._setVars(); } } export const utilService = new UtilsService(); export const retry = async (func, rCount, onerror) => { let d; for (let e = 0; e < rCount; e++) { try { return await func(); } catch (f) { d = f; } await (() => new Promise(resolve => { setTimeout(() => resolve(), 100); }))(); } onerror(d); }; /** * * @param {any} data * @param {HashChangeEvent} navdata */ export const noAuth = async (data, navdata = {}) => { const next = `/?${urlencode({ continue: data || location.hash.substr(1) })}`; const fullURL = `${location.protocol}//${location.host}/#${next}`; const user = await utilService.getUser(!0, !0); if (!user) { if (fullURL == navdata.oldURL) { console.log("Same url navigation"); return { stopExec: !0 }; } else { return console.log("Not logged in"), load(next), { stopExec: !0 }; } } else { return false; } }; export const blobToArrayBuffer = a => new Promise((b, c) => { const d = new FileReader(); (d.onload = e => b(e.target.result)), (d.onerror = e => c(e)), d.readAsArrayBuffer(a); }); export const arrayBufferToBlob = (a, b) => new Blob([a], { type: b }); export const arrayBufferToBase64 = a => new Promise(b => { const c = new Blob([a], { type: "application/octet-binary" }), d = new FileReader(); (d.onload = e => { const f = e.target.result; b(f.substr(f.indexOf(",") + 1)); }), d.readAsDataURL(c); }); export const base64ToArrayBuffer = async a => { const b = await fetch(`data:application/octet-stream;base64,${a}`); return await b.arrayBuffer(); }; export const base64ToBlob = async (a, b) => arrayBufferToBlob(await base64ToArrayBuffer(a), b); export const ImgAsBlob = async a => { try { const b = await fetch(a), c = await b.blob(); return URL.createObjectURL(c); } catch (b) { return ( console.warn( `An error occured while fetching:${a}.Returning ${a} back...` ), a ); } }; export function slidein(a) { (a.style.overflow = "hidden"), (a.style.padding = "0px"), (a.style.opacity = 0), (a.style.height = "0"), (a.style.border = "none"), (a.style.width = "0"); } export function slideout(a) { (a.style.padding = "5px"), (a.style.opacity = 1), (a.style.height = "auto"), (a.style.width = "auto"), (a.style.border = "2px solid #e3e3e3"), (a.style.overflow = "visible"); }
import React, { useState } from 'react'; import { Link, withRouter } from 'react-router-dom'; import { compose } from 'recompose'; import { withFirebase } from '../Firebase/index'; import * as ROUTES from '../../constants/routes'; import './SignUp.css'; const SignUp = () => { return ( <div className="d-flex justify-content-center"> <div className="main-div sign-up-div rounded"> <h1 className="text-white">Sign Up</h1> <SignUpForm /> </div> </div> ); } const SignUpFormBase = (props) => { const initialState = { email: '', username: '', passwordOne: '', passwordTwo: '', error: null } const [userState, setUserState] = useState({...initialState}); let onSubmit = (e) => { const {username, email, passwordOne} = userState; props.firebase .doCreateUserWithEmailAndPassword(email, passwordOne) .then(authUser => { return props.firebase .user(authUser.user.uid) .set({username, email}, { merge: true } ); }) .then(() => { setUserState({...initialState}); props.history.push(ROUTES.HOME); }) .catch(error => { setUserState({...userState, error: error}); }); e.preventDefault(); } let onChange = (e) => { setUserState({...userState, [e.target.name]: e.target.value}); } const {username, email, passwordOne, passwordTwo, error} = userState; const isInvalid = passwordOne !== passwordTwo || passwordOne.trim() === '' || email.trim() === '' || username.trim() === ''; return( <div> <form onSubmit={onSubmit} className="form-group"> <input className="form-control col-sm-8 offset-2 mb-2 bg-dark text-white sign-up-input" name="username" value={username} onChange={onChange} type="text" placeholder="What would you like to be called?" /> <input className="form-control col-sm-8 offset-2 mb-2 bg-dark text-white sign-up-input" name="email" value={email} onChange={onChange} type="text" placeholder="Enter a valid email" /> <input className="form-control col-sm-8 offset-2 mb-2 bg-dark text-white sign-up-input" name="passwordOne" value={passwordOne} onChange={onChange} type="password" placeholder="Create a password at least 6 characters long" /> <input className="form-control col-sm-8 offset-2 mb-2 bg-dark text-white sign-up-input" name="passwordTwo" value={passwordTwo} onChange={onChange} type="password" placeholder="Confirm password" /> <button disabled={isInvalid} type="submit" className="btn btn-primary">Create Account</button> {error && <p className="text-white mt-2">{error.message}</p>} </form> <p className="text-white sign-in-link mb-2 rounded col-sm-6 offset-3">Already have an account? <Link to={ROUTES.SIGN_IN} className="text-primary">Sign In</Link></p> </div> ) } const SignUpLink = () => ( <p className="text-white rounded">Don't have an account? <Link to={ROUTES.SIGN_UP} className="text-primary">Sign Up</Link></p> ); //compose nests higher order components //withRouter is a higher order component that gives access to React Router const SignUpForm = compose( withRouter, withFirebase, )(SignUpFormBase); export default SignUp; export { SignUpForm, SignUpLink };
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import randomColor from 'randomcolor'; import Chat from '../components/chat'; import Home from '../components/home'; import Main from '../components/main'; import 'bootstrap/dist/css/bootstrap.min.css'; import 'react-chat-elements/dist/main.css'; class Index extends React.Component { constructor(props) { super(props); this.state = { users: new Map(), oldPropsUsers: [], oldWhispers: [], whispers: new Map(), selectedChat: 'channel', showMain: true, }; } static getDerivedStateFromProps(props, state) { let newState = { }; // Handling user joinings / leavings if (props.userEvents.length > state.oldPropsUsers.length) { const newUser = props.userEvents[props.userEvents.length - 1]; // Mirroring props to the state (we cannot compare like in legacy Reactjs) newState = { oldPropsUsers: props.userEvents, users: new Map(state.users) }; if (newUser.command === 'Botapichat.UserUpdateEventRequest') { let color = randomColor(); // Checking if color is repeated // eslint-disable-next-line no-loop-func while ([...state.users].some(([user_id, user]) => user.color === color)) { color = randomColor(); } newState.users.set( newUser.payload.user_id, { ...newUser.payload, color, date: newUser.date }, ); } else if (newUser.command === 'Botapichat.UserLeaveEventRequest') { // User is leaving, must unset all his data since user_id will not match again newState.whispers = new Map(state.whispers); const user = newState.users.get(newUser.payload.user_id); if (state.selectedChat === user.toon_name) { // newState.selectedChat = 'channel'; newState.showMain = true; } newState.whispers.delete(user.toon_name); newState.users.delete(newUser.payload.user_id); } } // Set new whispers if (props.whispersArray.length > state.oldWhispers.length) { newState = { ...newState, oldWhispers: props.whispersArray, whispers: new Map(state.whispers), }; const whisper = props.whispersArray[props.whispersArray.length - 1]; // Whisper can be received or sent if (whisper.command !== 'Botapichat.SendWhisperResponse') { const user = state.users.get(whisper.payload.user_id); const conversation = state.whispers.get(user.toon_name) || []; conversation.push(whisper); newState.whispers.set(user.toon_name, conversation); } else { const botWhisper = props.botChat.find(c => c.request_id === whisper.request_id && c.command === 'Botapichat.SendWhisperRequest'); const user = state.users.get(botWhisper.payload.user_id); const conversation = state.whispers.get(user.toon_name) || []; conversation.push({ ...botWhisper, date: whisper.date, bot: true }); newState.whispers.set(user.toon_name, conversation); } } return Object.keys(newState).length > 0 ? newState : null; } onSelectChat(data) { this.setState({ selectedChat: data.id || 'channel' }); } changeView() { const { showMain } = this.state; this.setState({ showMain: !showMain }); } render() { const { connection, chat, botChat } = this.props; const { users, selectedChat, whispers, showMain } = this.state; const connectionData = connection.find(con => con.command === 'Botapichat.ConnectEventRequest') || {}; // Getting last message from each conversation const lastChannelMessage = chat[chat.length - 1]; const lastChannelMessageUser = lastChannelMessage && lastChannelMessage.command !== 'Botapichat.SendMessageResponse' && lastChannelMessage.command !== 'Botapichat.SendWhisperResponse' ? (users.get(lastChannelMessage.payload.user_id) ? users.get(lastChannelMessage.payload.user_id).toon_name : '*Player left channel*') : 'You'; const lastChannelBotChat = lastChannelMessage && (lastChannelMessage.command === 'Botapichat.SendMessageResponse' || lastChannelMessage.command === 'Botapichat.SendWhisperResponse') && botChat.length > 0 ? botChat[botChat.length - 1].payload.message : ''; // Setting up the chatlist with channel and whispers const chatListData = Object.keys(connectionData).length > 0 ? [ { avatar: '/static/reforged.png', alt: `${connectionData.payload.channel} (${users.size})`, title: `${connectionData.payload.channel} (${users.size})`, subtitle: chat.length > 0 ? `${lastChannelMessageUser}: ${lastChannelBotChat || lastChannelMessage.payload.message}` : '', date: chat.length > 0 ? lastChannelMessage.date : '', unread: 0, }, ...[...whispers].map((whisper) => { const sourceUser = users.get(whisper[1][0].payload.user_id); return { id: sourceUser.toon_name, avatar: '/static/reforged.png', alt: sourceUser.toon_name, title: sourceUser.toon_name, subtitle: whisper[1].length > 0 ? whisper[1][whisper[1].length - 1].payload.message : '', date: whisper[1].length > 0 ? whisper[1][whisper[1].length - 1].date : '', unread: 0, }; }), ] : []; return ( <div> { connection.length === 0 || connection[connection.length - 1].command === 'Botapichat.DisconnectResponse' ? <Home /> : !showMain ? ( <Chat chat={selectedChat === 'channel' ? chat : whispers.get(selectedChat)} botChat={botChat} users={users} selectedChat={selectedChat} channel={connectionData.payload.channel} changeView={() => { this.changeView(); }} /> ) : ( <Main chatListData={chatListData} changeView={() => { this.changeView(); }} onSelectChat={(data) => { this.onSelectChat(data); }} /> ) } </div> ); } } const mapStateToProps = (state) => { const props = { chat: [], userEvents: [], botChat: [], connection: [], whispersArray: [], }; state.messages.forEach(m => { switch (m.command) { case 'Botapichat.MessageEventRequest': { if (m.payload.type === 'Channel' || m.payload.type === 'Emote') { props.chat.push(m); } if (m.payload.type === 'Whisper') { props.whispersArray.push(m); } break; } case 'Botapichat.UserUpdateEventRequest': case 'Botapichat.UserLeaveEventRequest': { props.userEvents.push(m); break; } case 'Botapichat.SendWhisperResponse': { props.whispersArray.push(m); break; } case 'Botapichat.SendMessageResponse': { props.chat.push(m); break; } case 'Botapichat.DisconnectResponse': case 'Botapichat.ConnectEventRequest': { props.connection.push(m); break; } default: { break; } } }); state.events.forEach(e => { switch (e.command) { case 'Botapichat.SendWhisperRequest': case 'Botapichat.SendMessageRequest': { props.botChat.push(e); break; } default: break; } }); return props; }; Index.propTypes = { chat: PropTypes.array, userEvents: PropTypes.array, botChat: PropTypes.array, connection: PropTypes.array, }; Index.defaultProps = { chat: [], userEvents: [], botChat: [], connection: [], }; export default connect(mapStateToProps)(Index);
const commands = { HELP: { name: 'help', description: 'このヘルプが表示されますわ。' }, SUMMON: { name: 'summon', description: '私がボイスチャットにお邪魔して、読み上げを開始しますわよ。' }, BYE: { name: 'bye', description: '読み上げを終了しますわ。' }, /*WORD_ADD: { name: 'wd', description: '[単語] [よみかた]の順序で、私に読み方を教えてくださいまし。' }, WORD_REMOVE: { name: 'wr', description: '[単語]の読み方を辞書から削除しますわ。' },*/ SET_VOICE: { name: 'vs', description: 'あなたのチャットの読み上げ音声を設定しますわ。' }, LIST_VOICE: { name: 'vl', description: '設定可能な音声ファイルのリストを表示しますわ。' } } module.exports = commands
angular .module('altairApp') .controller('main_headerCtrl', [ '$timeout', '$rootScope', '$scope', '$window', 'sessionService', '$http', '$cookies', 'Upload', 'mainService', 'Idle', '$state', '$location', 'sweet', function ($timeout,$rootScope,$scope,$window,sessionService,$http,$cookies,Upload,mainService,Idle,$state,$location,sweet) { $scope.isLoggedIn = sessionService.isLoggedIn; mainService.withdomain('get','/user/service/ujson') .then(function(data){ $rootScope.user = data; $scope.user=data; }); $('.dropify').dropify(); $scope.logout = sessionService.logout; $http.get("/getMessages") .then(function(response) { $scope.messages = response.data; /*if ($scope.messages.messages.filter(function(x){ return x.isread == false; }).length > 0){ $scope.showMessage($scope.messages.messages.filter(function(x){ return x.isread == false; })[0]); $cookies.put("last_message_id",$scope.messages.messages.filter(function(x){ return x.isread == false; })[0].id); } else if ($scope.messages.alerts.filter(function(x){ return x.isread == false; }).length > 0){ $scope.showMessage($scope.messages.alerts.filter(function(x){ return x.isread == false; })[0]); $cookies.put("last_message_id",$scope.messages.alerts.filter(function(x){ return x.isread == false; })[0].id); }*/ $scope.unread_msgs = $scope.messages.messages.filter(function(x){ return x.isread == false; }).length; $scope.unread_alerts = $scope.messages.alerts.filter(function(x){ return x.isread == false; }).length; }); $scope.user_data = { name: "Lue Feest", avatar: "assets/img/avatars/avatar_11_tn.png", alerts: [ { "title": "Hic expedita eaque.", "content": "Nemo nemo voluptatem officia voluptatum minus.", "type": "warning" }, { "title": "Voluptatibus sed eveniet.", "content": "Tempora magnam aut ea.", "type": "success" }, { "title": "Perferendis voluptatem explicabo.", "content": "Enim et voluptatem maiores ab fugiat commodi aut repellendus.", "type": "danger" }, { "title": "Quod minima ipsa.", "content": "Vel dignissimos neque enim ad praesentium optio.", "type": "primary" } ], messages: [ { "title": "Reiciendis aut rerum.", "content": "In adipisci amet nostrum natus recusandae animi fugit consequatur.", "sender": "Korbin Doyle", "color": "cyan" }, { "title": "Tenetur commodi animi.", "content": "Voluptate aut quis rerum laborum expedita qui eaque doloremque a corporis.", "sender": "Alia Walter", "color": "indigo", "avatar": "assets/img/avatars/avatar_07_tn.png" }, { "title": "At quia quis.", "content": "Fugiat rerum aperiam et deleniti fugiat corporis incidunt aut enim et distinctio.", "sender": "William Block", "color": "light-green" }, { "title": "Incidunt sunt.", "content": "Accusamus necessitatibus officia porro nisi consectetur dolorem.", "sender": "Delilah Littel", "color": "blue", "avatar": "assets/img/avatars/avatar_02_tn.png" }, { "title": "Porro ut.", "content": "Est vitae magni eum expedita odit quisquam natus vel maiores.", "sender": "Amira Hagenes", "color": "amber", "avatar": "assets/img/avatars/avatar_09_tn.png" } ] }; $scope.changeUserDataDialog = function(){ UIkit.modal("#changeUserdataDialog").show(); } $scope.getUserAvatar = function($files){ if ($files.length > 0){ $scope.user.avatar_file = $files[0]; } } $scope.submitChangePasswordReq = function(){ mainService.withdata("post","/changeUserPassword",$scope.p).then(function(data){ if (data == true){ UIkit.modal("#changePasswordDialog").hide(); sweet.show('Мэдэгдэл', 'Таны нууц үг амжилттай солигдлоо.', 'success'); } }); } var changePasswordDialogModalObj = UIkit.modal("#changePasswordDialog"); $scope.changePasswordDialog=function(){ UIkit.modal("#changePasswordDialog").show(); } $scope.alerts_length = $scope.user_data.alerts.length; $scope.messages_length = $scope.user_data.messages.length; $scope.showMessage = function(news){ if (news.isread == false){ $http.get("/markAsReadMessage/" + news.id) .then(function(response) { if (response == true){ news.isread = true; if (news.status == 1){ $scope.unread_alerts = $scope.unread_alerts - 1; } else{ $scope.unread_msgs = $scope.unread_msgs - 1; } } }); } UIkit.modal.alert("<h2>" + news.title + "</h2><p class='uk-overflow-container' style='white-space: pre-line;text-align: justify;'>"+news.description+"<br><span class='uk-text-muted'>"+news.createdat+"</span></p>") } $('#menu_top').children('[data-uk-dropdown]').on('show.uk.dropdown', function(){ $timeout(function() { $($window).resize(); },280) }); // append modal to <body> $('body').append('<div class="uk-modal" id="modal_idle">' + '<div class="uk-modal-dialog">' + '<div class="uk-modal-header">' + '<h3 class="uk-modal-title">Анхааруулга!</h3>' + '</div>' + '<p>Системийн аюулгүй байдлын үүднээс идэвхигүй 30 минут болоход анхааруулга идэвхижэж 1 минутын дараа холболтыг автоматаар таслана. </p>' + '<p>Холболтоо таслахыг хүсэхгүй байвал үйлдэл хийнэ үү. </p>' + '<p>Үлдсэн хугацаа <span class="uk-text-bold md-color-red-500" id="sessionSecondsRemaining"></span> секунт.</p>' + '</div>' + '</div>'); var modal = UIkit.modal("#modal_idle", { bgclose: false }), $sessionCounter = $('#sessionSecondsRemaining'); Idle.watch(); $scope.$on('IdleWarn', function(e, countdown) { modal.show(); $sessionCounter.html(countdown) }); $scope.$on('IdleEnd', function() { modal.hide(); $sessionCounter.html(''); }); $scope.$on('IdleTimeout', function() { modal.hide(); $http.post("/logout", {}).success(function($state) { $rootScope.authenticated = false; $location.path("/login"); localStorage.setItem("session", false); }); }); } ]) .config(function(IdleProvider, KeepaliveProvider) { // configure Idle settings IdleProvider.idle(1800); // in seconds IdleProvider.timeout(60); // in seconds IdleProvider.keepalive(false); });
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: shipment/deliverynote/detail // ================================================================================ { var i; var str = ""; weblet.loadview(); var ivalues = { schema : 'mne_shipment', query : 'deliverynote_detail', orderweblet : 'crm_order', orderselect : 'all', okfunction : 'deliverynote_ok', delfunction : 'deliverynote_del', deliverfunction : 'deliverynote_ready', invoicefunction : 'deliverynote_invoice', report : "mne_deliverynote", invoiceweblet : 'shipment_invoice', invoiceselect : 'all', orderweblet : 'crm_order', orderselect : 'all', }; var svalues = { table : 'deliverynote' }; weblet.initDefaults(ivalues, svalues); var attr = { hinput : false, selectInput : { selectlist : weblet.initpar.selectlist } } weblet.findIO(attr); weblet.showLabel(); weblet.delbuttons('add'); weblet.obj.mkbuttons.push({ id: 'deliver', value : weblet.txtGetText('#mne_lang#Ausliefern#'), space : 'before' }); weblet.obj.mkbuttons.push({ id: 'invoice', value : weblet.txtGetText('#mne_lang#Rechnung#') }); weblet.showids = new Array("deliverynoteid"); weblet.titleString.add = weblet.txtGetText("#mne_lang#Lieferschein hinzufügen"); weblet.titleString.mod = weblet.txtGetText("#mne_lang#Lieferschein bearbeiten"); weblet.titleString.del = weblet.txtGetText("#mne_lang#Lieferschein <$1> wirklich löschen"); weblet.titleString.delname = 'deliverynotenumber'; weblet.showValue = function(weblet) { MneAjaxWeblet.prototype.showValue.call(this, weblet ); this.obj.buttons.del.disabled = false; this.obj.buttons.invoice.disabled = true; this.obj.buttons.deliver.disabled = false; if ( this.act_values.delivered == "#mne_lang#wahr" ) { this.obj.buttons.del.disabled = true; this.obj.buttons.deliver.disabled = true; if ( this.act_values.invoicenum == '' ) this.obj.buttons.invoice.disabled = false; } } weblet.add = function() { } weblet.del = function() { if ( this.confirm(this.txtSprintf(this.titleString.del,this.act_values[this.titleString.delname])) == false ) return false; var p = { schema : this.initpar.schema, name : this.initpar.delfunction, par0 : this.act_values.deliverynoteid, typ0 : "text", sqlend : 1 }; if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { if ( this.act_values.result != 'failed' ) { var i; for ( i in this.obj.inputs ) this.obj.inputs[i].value = ''; for ( i in this.obj.outputs ) this.obj.outputs[i].innerHTML = ' '; this.setDepends("del"); } return false; } return true; } weblet.ok = function() { var p = { schema : this.initpar.schema, name : this.initpar.okfunction, par0 : this.act_values.deliverynoteid, typ0 : "text", par1 : this.obj.inputs.ownerid.value, typ1 : "text", par2 : this.obj.inputs.contactid.value, typ2 : "text", sqlend : 1 }; if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { this.showValue(this); this.setDepends("showValue"); return false; } return true; } weblet.print = function() { var p = { wval : this.act_values.deliverynoteid, wop : "=", wcol : 'deliverynoteid', sort : '', macro0 : "lettersubject,\\Hordernumber: \\Bordernumber\\newline\\Hdeliverynotenumber: \\Bdeliverynotenumber", macro1 : "nosalutation,true", language : this.act_values.language, sqlend : 1 }; MneAjaxWeblet.prototype.print.call(this,p); return false; } weblet.deliver = function() { var p = { schema : this.initpar.schema, name : this.initpar.deliverfunction, par0 : this.act_values.deliverynoteid, typ0 : "text", sqlend : 1 }; if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { if ( this.act_values.result == this.act_values.deliverynoteid ) { this.showValue(this); this.setDepends("showValue"); this.print(); } return false; } return true; } weblet.invoice = function() { var p = { schema : this.initpar.schema, name : this.initpar.invoicefunction, par0 : this.act_values.deliverynoteid, typ0 : "text", sqlend : 1 }; if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok') { var w = this.parent; var result = this.act_values.result; w.show(weblet.initpar.invoiceweblet); w.subweblets[weblet.initpar.invoiceselect].setValue("invoiceid : '" + result + "'"); return false; } return true; } weblet.ordernumber = function() { if ( typeof this.act_values.orderid == 'undefined' ) { this.error("#mne_lang#Keine Lieferschein ausgewählt"); return false; } if ( this.win.mne_config.group.erpcrm == true || this.win.mne_config.username == 'admindb') { var w = this.parent; var result = this.act_values.orderid; w.show(weblet.initpar.orderweblet); w.subweblets[weblet.initpar.orderselect].setValue("orderid : '" + result + "'"); } return true; } weblet.invoicenum = function() { if ( typeof this.act_values.invoiceid == 'undefined' || this.act_values.invoiceid == '' ) { this.error("#mne_lang#Keine Rechnung vorhanden"); return false; } { var w = this.parent; var result = this.act_values.invoiceid; w.show(weblet.initpar.invoiceweblet); w.subweblets[weblet.initpar.invoiceselect].setValue("invoiceid : '" + result + "'"); } return true; } }
/* eslint-disable no-underscore-dangle */ /* eslint-disable no-undef */ /* eslint-disable func-names */ require("dotenv").config(); const request = require("supertest"); const bcrypt = require("bcryptjs"); const Role = require("../_helpers/role"); const { dropDB, closeConnection, User } = require("../_helpers/db"); const app = require("../server"); const { generateTOTP } = require("../_helpers/mfa"); const userLoginData = { username: "User", password: "123456789", }; const adminLoginData = { username: "Admin", password: "123456789", }; async function createUser() { const userParam = { username: "User", password: "123456789", firstName: "Max", lastName: "Mustermann", role: JSON.stringify(Role.User), }; const user = new User(userParam); user.hash = bcrypt.hashSync(userParam.password, 10); await user.save(); console.log("User saved!"); } async function createAdmin() { const userParam = { username: "Admin", password: "123456789", firstName: "Maxim", lastName: "Markow", role: JSON.stringify(Role.Admin), }; const user = new User(userParam); user.hash = bcrypt.hashSync(userParam.password, 10); await user.save(); console.log("Admin saved!"); } async function login(user) { return request(app).post("/users/login").send(user); } describe("/users", function () { afterEach(async function () { await dropDB(); }); before(async function () { await dropDB(); }); after(async function () { app.close(); await closeConnection(); }); describe("POST /refresh", function () { describe("Successes", function () { it("respond with 200 ok, because of valid refreshToken", async function () { await createUser(); const user = await login(userLoginData); const data = { refreshToken: user.body.refreshToken, }; await request(app) .post("/users/refresh") .send(data) .expect(200); }); }); describe("Errors", function () { it("respond with 401 Unauthorized, because of invalid refreshToken either because its malformed or logged out", async function () { const data = { refreshToken: "00000000000000000iIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1ZjQ2Nzg3MDY3YjhlMzE2YjVmMjc5ZmEiLCJyb2xlIjoie1wibmFtZVwiOlwiVXNlclwiLFwicmFua1wiOlwiMVwifSIsImlhdCI6MTU5ODQ1Mzg3N30.gPLtiP590kdbYfb267Zc3Gm7z5oDfNcuSS0XI9rJSH", }; await request(app) .post("/users/refresh") .send(data) .expect(401, { Error: "Unauthorized", message: "The refresh token is invalid.", }); }); it("respond with 422 Unprocessable Entity, because of no refreshToken", async function () { const data = { refreshToken: "", }; await request(app) .post("/users/refresh") .send(data) .expect(422, { Error: "Validation Error", message: [ { refreshToken: "Not Allowed to be empty.", }, { refreshToken: "Too short for a JWT.", }, ], }); }); }); }); describe("POST /mfa", function () { describe("Successes", function () { it("respond with 200 ok, because mfa got activated", async function () { await createUser(); const user = await login(userLoginData); const generateSecret = await request(app) .post("/users/mfa/generate") .set("Authorization", `Bearer ${user.body.accessToken}`); const totp = generateTOTP(generateSecret.body.userSecret, 0); await request(app) .post("/users/mfa/enable") .set("Authorization", `Bearer ${user.body.accessToken}`) .send({ token: totp }) .expect(200); }); it("respond with 200 ok, because mfa got deactivated", async function () { await createUser(); const user = await login(userLoginData); const generateSecret = await request(app) .post("/users/mfa/generate") .set("Authorization", `Bearer ${user.body.accessToken}`); const totp = generateTOTP(generateSecret.body.userSecret, 0); await request(app) .post("/users/mfa/enable") .set("Authorization", `Bearer ${user.body.accessToken}`) .send({ token: totp }); await request(app) .post("/users/mfa/disable") .set("Authorization", `Bearer ${user.body.accessToken}`) .send({ token: totp }) .expect(200); }); it("respond with 200 ok, because mfa got activated and used", async function () { await createUser(); const user = await login(userLoginData); const generateSecret = await request(app) .post("/users/mfa/generate") .set("Authorization", `Bearer ${user.body.accessToken}`); const totp = generateTOTP(generateSecret.body.userSecret, 0); await request(app) .post("/users/mfa/enable") .set("Authorization", `Bearer ${user.body.accessToken}`) .send({ token: totp }); await request(app) .post("/users/logout") .send({ refreshToken: user.body.refreshToken }); const loginResponse = await login(userLoginData); await request(app) .post("/users/mfa/verify") .send({ refreshToken: loginResponse.body.refreshToken, totp, }) .expect(200); }); }); describe("Errors", function () { it("respond with 401 unauthorized, because totp wrong", async function () { await createUser(); const user = await login(userLoginData); await request(app) .post("/users/mfa/generate") .set("Authorization", `Bearer ${user.body.accessToken}`); await request(app) .post("/users/mfa/enable") .set("Authorization", `Bearer ${user.body.accessToken}`) .send({ token: "000000" }) .expect(401, { Error: "Unauthorized", message: "TOTP Token is incorrect. Mfa Activation process exited.", }); }); it("respond with 401 Unauthorized, because mfa got activated and used but wrong totp", async function () { await createUser(); const user = await login(userLoginData); const generateSecret = await request(app) .post("/users/mfa/generate") .set("Authorization", `Bearer ${user.body.accessToken}`); const generatedTotp = generateTOTP( generateSecret.body.userSecret, 0, ); await request(app) .post("/users/mfa/enable") .set("Authorization", `Bearer ${user.body.accessToken}`) .send({ token: generatedTotp }); await request(app) .post("/users/logout") .send({ refreshToken: user.body.refreshToken }); const loginResponse = await login(userLoginData); await request(app) .post("/users/mfa/verify") .send({ refreshToken: loginResponse.body.refreshToken, totp: "A00000", }) .expect(401); }); }); }); describe("POST /register", function () { describe("Successes", function () { it("respond with 200 ok, because of correct input", async function () { const data = { username: "CreationTest", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(200); }); }); describe("Errors", function () { it("respond with 500 internal server error, because of already existing username", async function () { const data = { username: "User", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await createUser(); await request(app) .post("/users/register") .send(data) .expect(500, { Error: "Not Unique", message: "Username User is already taken", }); }); it("respond with 422 malformed, because a role was supplied but is not allowed", async function () { const data = { username: "User", password: "123456789", firstName: "Max", lastName: "Mustermann", role: "something", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { role: "Invalid value", }, ], }); }); it("respond with 422 malformed, because of no input", async function () { await request(app) .post("/users/register") .expect(422, { Error: "Validation Error", message: [ { username: "Not Allowed to be empty.", }, { username: "Has to exist.", }, { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, { password: "Has to exist.", }, { firstName: "Not Allowed to be empty.", }, { firstName: "Has to exist.", }, { lastName: "Not Allowed to be empty.", }, { lastName: "Has to exist.", }, ], }); }); it("respond with 422 malformed, because of too short password", async function () { const data = { username: "CreationTest", password: "1234", firstName: "Max", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of too long password", async function () { const data = { username: "CreationTest", password: "1234567891561f89e6w1f896we1f98we61f9856we1f89w1e569f189we1f896w5e18fw1e6584f", firstName: "Max", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of a missing password", async function () { const data = { username: "CreationTest", password: "", firstName: "Max", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of too long username", async function () { const data = { username: "CreationTestvger4g89561er6584g98aerg1g1aer65g1ae91ga85e9r6w", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { username: "Too long, not more then 25 characters.", }, ], }); }); it("respond with 422 malformed, because of missing username", async function () { const data = { username: "", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { username: "Not Allowed to be empty.", }, ], }); }); it("respond with 422 malformed, because of too long firstName", async function () { const data = { username: "CreationTest", password: "123456789", firstName: "Maxgf1re64754g1685sr4e1g61areg691rea6g1fg1a6wer1gf86aw1egf96aw81egf65aerae861g", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { firstName: "Too long, not more then 25 characters.", }, ], }); }); it("respond with 422 malformed, because of missing firstName", async function () { const data = { username: "CreationTest", password: "123456789", firstName: "", lastName: "Mustermann", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { firstName: "Not Allowed to be empty.", }, ], }); }); it("respond with 422 malformed, because of too long lastName", async function () { const data = { username: "CreationTest", password: "123456789", firstName: "Max", lastName: "Mustermanngre1869g51er68sag16era81g6a1er86g1ae8r6g186eraw4g18ae6rg1ae6r8g1ae86", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { lastName: "Too long, not more then 25 characters.", }, ], }); }); it("respond with 422 malformed, because of missing lastName", async function () { const data = { username: "CreationTest", password: "123456789", firstName: "Max", lastName: "", }; await request(app) .post("/users/register") .send(data) .expect(422, { Error: "Validation Error", message: [ { lastName: "Not Allowed to be empty.", }, ], }); }); }); }); describe("UPDATE /", function () { describe("Successes", function () { it("respond with 200 ok, because of correct input and unique username", async function () { const updates = { username: "User1", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(200); }); it("respond with 200 ok, because of correct input and the same username", async function () { const updates = { username: "User", password: "123456789", firstName: "Peter", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(200); }); it("respond with 200 ok, because of correct input and the same username and admin can update all", async function () { const updates = { username: "User", password: "123456789", firstName: "Peter", lastName: "Mustermann", }; await createAdmin(); await createUser(); const user = await login(userLoginData); const admin = await login(adminLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${admin.body.accessToken}`) .send(updates) .expect(200); }); }); describe("Errors", function () { it("respond with 500 forbidden, because the username already exists", async function () { const updates = { username: "Admin", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await createAdmin(); await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(500, { Error: "Not Unique", message: "Username Admin is already taken", }); }); it("respond with 403 forbidden, because a standard user cant update other users", async function () { const updates = { username: "Admin", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await createAdmin(); await createUser(); const user = await login(userLoginData); const admin = await login(adminLoginData); await request(app) .put(`/users/${admin.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(403, { Error: "Forbidden", message: "Forbidden for your rank, if its not your own account.", }); }); it("respond with 422 malformed, because of no input", async function () { await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .expect(422, { Error: "Validation Error", message: [ { username: "Not Allowed to be empty.", }, { username: "Has to exist.", }, { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, { password: "Has to exist.", }, { firstName: "Not Allowed to be empty.", }, { firstName: "Has to exist.", }, { lastName: "Not Allowed to be empty.", }, { lastName: "Has to exist.", }, ], }); }); it("respond with 422 malformed, because of too short password", async function () { const updates = { username: "CreationTest", password: "1234", firstName: "Max", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of too long password", async function () { const updates = { username: "CreationTest", password: "1234567891561f89e6w1f896we1f98we61f9856we1f89w1e569f189we1f896w5e18fw1e6584f", firstName: "Max", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of a missing password", async function () { const updates = { username: "CreationTest", password: "", firstName: "Max", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of too long username", async function () { const updates = { username: "CreationTestvger4g89561er6584g98aerg1g1aer65g1ae91ga85e9r6w", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { username: "Too long, not more then 25 characters.", }, ], }); }); it("respond with 422 malformed, because of missing username", async function () { const updates = { username: "", password: "123456789", firstName: "Max", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { username: "Not Allowed to be empty.", }, ], }); }); it("respond with 422 malformed, because of too long firstName", async function () { const updates = { username: "CreationTest", password: "123456789", firstName: "Maxgf1re64754g1685sr4e1g61areg691rea6g1fg1a6wer1gf86aw1egf96aw81egf65aerae861g", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { firstName: "Too long, not more then 25 characters.", }, ], }); }); it("respond with 422 malformed, because of missing firstName", async function () { const updates = { username: "CreationTest", password: "123456789", firstName: "", lastName: "Mustermann", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { firstName: "Not Allowed to be empty.", }, ], }); }); it("respond with 422 malformed, because of too long lastName", async function () { const updates = { username: "CreationTest", password: "123456789", firstName: "Max", lastName: "Mustermanngre1869g51er68sag16era81g6a1er86g1ae8r6g186eraw4g18ae6rg1ae6r8g1ae86", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { lastName: "Too long, not more then 25 characters.", }, ], }); }); it("respond with 422 malformed, because of missing lastName", async function () { const updates = { username: "CreationTest", password: "123456789", firstName: "Max", lastName: "", }; await createUser(); const user = await login(userLoginData); await request(app) .put(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .send(updates) .expect(422, { Error: "Validation Error", message: [ { lastName: "Not Allowed to be empty.", }, ], }); }); }); }); describe("GET /", function () { describe("Successes", function () { it("respond with 200 ok, because admin can get himself", async function () { await createAdmin(); const admin = await login(adminLoginData); await request(app) .get(`/users/${admin.body._id}`) .set("Authorization", `Bearer ${admin.body.accessToken}`) .expect(200); }); it("respond with 200 ok, because user can get himself", async function () { await createUser(); const user = await login(userLoginData); await request(app) .get(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .expect(200); }); it("respond with 200 ok, because admins can get others", async function () { await createAdmin(); await createUser(); const user = await login(userLoginData); const admin = await login(adminLoginData); await request(app) .get(`/users/${user.body._id}`) .set("Authorization", `Bearer ${admin.body.accessToken}`) .expect(200); }); it("respond with 200 ok, because of correct token and role", async function () { await createAdmin(); const admin = await login(adminLoginData); await request(app) .get("/users") .set("Authorization", `Bearer ${admin.body.accessToken}`) .expect(200); }); }); describe("Errors", function () { it("respond with 401 unauthorized, because user cant get other users", async function () { await createAdmin(); await createUser(); const user = await login(userLoginData); const admin = await login(adminLoginData); await request(app) .get(`/users/${admin.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .expect(403, { Error: "Forbidden", message: "Forbidden for your rank, if its not your own account.", }); }); it("respond with 401 unauthorized, because of correct token but wrong role", async function () { await createUser(); const user = await login(userLoginData); await request(app) .get("/users") .set("Authorization", `Bearer ${user.body.accessToken}`) .expect(401, { Error: "Unauthorized", message: "You dont have a role with the required Permissions for this.", }); }); it("respond with 422 unauthorized, because of missing token", async function () { await request(app) .get("/users") .expect(422, { Error: "Validation Error", message: [ { authorization: "Not Allowed to be empty.", }, { authorization: "Has to exist.", }, { authorization: "Too short for a JWT.", }, ], }); }); it("respond with 422 unauthorized, because of Bearer ", async function () { await request(app) .get("/users") .set("Authorization", "Bearer ") .expect(422, { Error: "Validation Error", message: [ { authorization: "Too short for a JWT.", }, ], }); }); it("respond with 401 unauthorized, because of malformed token", async function () { await request(app) .get("/users") .set( "Authorization", "Bearer 1f56ew1afg68qerw1gf98erqw1gf98qer1g89qer1f89qeds1fg89qwer1fg98qwe1f89qw", ) .expect(401, { Error: "Unauthorized", message: "The token is invalid.", }); }); }); }); describe("DELETE /", function () { describe("Successes", function () { it("respond with 200 ok, because he is allowed to delete himself", async function () { await createUser(); const user = await login(userLoginData); await request(app) .delete(`/users/${user.body._id}`) .set("Authorization", `Bearer ${user.body.accessToken}`) .expect(200); }); it("respond with 200 ok, because admins are allowed to delete all users", async function () { await createAdmin(); await createUser(); const user = await login(userLoginData); const admin = await login(adminLoginData); await request(app) .delete(`/users/${user.body._id}`) .set("Authorization", `Bearer ${admin.body.accessToken}`) .expect(200); }); }); describe("Errors", function () { it("respond with 403 forbidden, because a standard user cant delete other users", async function () { await createUser(); const responseBody = await login(userLoginData); await request(app) .delete("/users/0000000000006204aefc242c") .set( "Authorization", `Bearer ${responseBody.body.accessToken}`, ) .expect(403, { Error: "Forbidden", message: "Forbidden for your rank, if its not your own account.", }); }); }); }); describe("POST /logout", function () { describe("Successes", function () { it("respond with 200 ok, because of valid refreshToken", async function () { await createUser(); const user = await login(userLoginData); const refreshToken = { refreshToken: user.body.refreshToken, }; await request(app) .post("/users/logout") .send(refreshToken) .expect(200); }); }); describe("Errors", function () { it("respond with 401 Unauthorized, because of invalid refreshToken", async function () { const data = { refreshToken: "1fe56w1f56we1f00000056a1w6f156awe1f56w1e6f1awe56f1aw51f6aw1f561aew65f165awe1f561ew56", }; await request(app) .post("/users/logout") .send(data) .expect(401, { Error: "Unauthorized", message: "The refresh token is invalid.", }); }); it("respond with 422 Unprocessable Entity, because of no refreshToken", async function () { const data = { refreshToken: "", }; await request(app) .post("/users/logout") .send(data) .expect(422, { Error: "Validation Error", message: [ { refreshToken: "Not Allowed to be empty.", }, { refreshToken: "Too short for a JWT.", }, ], }); }); }); }); describe("POST /login", function () { describe("Successes", function () { it("respond with 200 ok, because of correct input", async function () { await createUser(); await request(app) .post("/users/login") .send(userLoginData) .expect(200); }); }); describe("Errors", function () { it("respond with 401 Unauthorized, because of wrong password", async function () { const loginData = { username: "User", password: "1234563249", }; await createUser(); await request(app) .post("/users/login") .send(loginData) .expect(401, { Error: "Unauthorized", message: "Username or Password is incorrect.", }); }); it("respond with 422 malformed, because of no input", async function () { await request(app) .post("/users/login") .expect(422, { Error: "Validation Error", message: [ { username: "Not Allowed to be empty.", }, { username: "Has to exist.", }, { password: "Not Allowed to be empty.", }, { password: "Has to exist.", }, { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of too short password", async function () { const loginData = { username: "User", password: "123456", }; await request(app) .post("/users/login") .send(loginData) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of too long password", async function () { const loginData = { username: "User", password: "123456159198464fdeasf48es64fgsed86fg4ews6f84sed8f4se64f86es", }; await request(app) .post("/users/login") .send(loginData) .expect(422, { Error: "Validation Error", message: [ { password: "Too short or too long, needs atleast 8 characters and not more then 25.", }, ], }); }); it("respond with 422 malformed, because of too long username", async function () { const loginData = { username: "Usefwefwefgwefjuiwenfiuoawefnbzuiaeowhfiewzqghfrzuoagwerofzugewaqzurwaezuir", password: "123456789", }; await request(app) .post("/users/login") .send(loginData) .expect(422, { Error: "Validation Error", message: [ { username: "Too long, not more then 25 characters.", }, ], }); }); }); }); });
/* # HERE is the equation to find any coordinates on the slope of two points m = (y2-y1)/(x2-x1) or (y2-y1) = (x2-x1)m By given an Known point(x1,y1) and either given a second x2 or y2 we can calculate the unkonwn and get a new point that's on the slope */ var width_element = document.querySelector('input[name="width"]'); var height_element = document.querySelector('input[name="height"]'); var division = document.querySelector('input[name="division"]'); var username = document.querySelector('input[name="username"]'); // display calculated coordinates var board = document.querySelector('code.coords'); var cls = document.querySelector('#cls'); var get = document.querySelector('#getPoints'); // alphabet to charcode var at = document.querySelector('.ccode'); var letter = document.querySelector('input[name="letter"]'); // Attach event listener letter.addEventListener('keyup', atoCode, false); letter.addEventListener('click', clear, false); cls.addEventListener('click', clsBoard, false); username.addEventListener('keyup', BubbleName.redraw, false); function generatePoints() { board.innerHTML = ''; Maker.output(); } function atoCode() { // alphabet-to-char code var code = letter.value.charCodeAt("0"); at.innerHTML = code; } function clear() { letter.value = ''; at.innerHTML = ''; } function clsBoard() { board.innerHTML = ''; // clear shifted points Maker.clearCollectPoint(); // clear canvas BubbleName.draw(1); } function hypo() { return Math.round(Math.sqrt(Math.pow(Maker.letterWide()/(4/division.value), 2) + Math.pow(height_element.value, 2))); }
import { iteratee } from './utils' function chunk(array, size = 1) { // Little hack faster than Math.floor const chunksNumbers = Math.ceil(array.length / size) const res = Array.from({ length: chunksNumbers }, () => []) let buffer for (let i = 0; i < array.length / chunksNumbers; i++) { for (let j = 0; j < chunksNumbers; j++) { buffer = array[size * j + i] if (buffer) res[j][i] = buffer } } return res } function compact(array = []) { return array.filter(value => !!value) } function concat() { return [].concat(...arguments) } function baseDiff(array, exclusions, iteratee, comparator = (f, s) => f === s) { const res = [] if (iteratee) exclusions = exclusions.map(iteratee) let value for (let i in array) { value = iteratee ? iteratee(array[i]) : array[i] if (exclusions.findIndex(ex => comparator(value, ex)) === -1) res.push(array[i]) } return res } function difference(array, ...arrays) { if (!arrays.length) return array return baseDiff(array, concat(...arrays)) } function differenceBy(array, ...properties) { let last = properties.splice(-1, 1)[0] if (typeof last === 'object' || Array.isArray(last)) return baseDiff(array, concat([...properties, last])) return baseDiff(array, concat(...properties), last ? iteratee(last) : undefined) } function differenceWith(array, ...properties) { let comparator = properties.splice(-1, 1)[0] return baseDiff(array, concat(...properties), undefined, comparator) } function drop(array = [], n = 1) { return array.splice(0, n), array } function dropRight(array = [], n = 1) { return array.splice(-n, n), array } function dropRightWhile(array = [], predicate) { if(!predicate) return [] predicate = iteratee(predicate) let index = 0 for(let i = array.length - 1; i >= 0; i--) { if(!predicate(array[i])) { index = i break } } return array.splice(index + 1, array.length - index), array } function dropWhile(array, predicate) { if(!predicate) return [] predicate = iteratee(predicate) let index = 0 for(let i = 0; i < array.length; i++) { if(!predicate(array[i])) { index = i break } } return array.splice(0, index), array } function fill(array, value, start = 0, end = array.length) { for(let i = start; i < end; i++) array[i] = value return array } function baseFindIndex(array, iteratee, start, reverse) { let index = start + (reverse ? 1 : -1) while(reverse ? index-- > 0 : index++ < array.length) { if(iteratee(array[index])) return index } return -1 } // We could be using built-in Array.prototype.findIndex but // findLastIndex would be slower than findIndex // Thus, both functions have a similar execution time function findIndex(array, predicate, start = 0) { return baseFindIndex(array, iteratee(predicate), start) } function findLastIndex(array, predicate, start = array.length - 1) { return baseFindIndex(array, iteratee(predicate), start, true) } function first(array) { return array ? array[0] : undefined } function fromPairs(array) { return array.reduce((acc, obj) => ({...acc, [obj[0]]: obj[1]}), {}) } function baseIntersect(arrays, iteratee, comparator = (f, s) => f === s) { const res = [], seen = [] let index for(let i in arrays) { arrays[i].forEach(obj => { let value = iteratee ? iteratee(obj) : obj if((index = seen.findIndex(ex => comparator(value, ex.iteratee))) === -1) seen.push({ raw: obj, iteratee: value }) else res.push(seen[index].raw) }) } return res } function intersection(...properties) { return baseIntersect(properties) } function intersectionBy(...properties) { let last = properties.splice(-1, 1)[0] if (typeof last === 'object' || Array.isArray(last)) return baseIntersect([...properties, last]) return baseIntersect(properties, last ? iteratee(last) : undefined) } function intersectionWith(...properties) { let comparator = properties.splice(-1, 1)[0] return baseIntersect(properties, undefined, comparator) } function last(array) { return array.splice(-1, 1)[0] } function nth(array, n = 0) { return array ? array[n >= 0 ? n : array.length + n] : undefined } function reverse(array) { return array ? array.reverse() : array } export default { chunk, compact, concat, difference, differenceBy, differenceWith, drop, dropRight, dropRightWhile, dropWhile, fill, findIndex, findLastIndex, first, fromPairs, intersection, intersectionBy, intersectionWith, last, nth, reverse }
const v_in = 9; const resistors = [ 3.3, 22, 82, 100, 150, 220, 270, 300, 330, 750, 1000, 1500, 1800, 2200, 2700, 3300, 9100, 10000, 1_000_000, ]; const resistorPairs = []; let minimumDifference = 9999999; let minimumPair; for (let i = 0; i < resistors.length - 1; i++) { for (let j = i + 1; j < resistors.length; j++) { resistorPairs.push([resistors[i], resistors[j]]); } } resistorPairs.forEach((pair) => { const r1 = pair[0]; const r2 = pair[1]; const v_out_1 = (r2 / (r1 + r2)) * v_in; const v_out_2 = (r1 / (r2 + r1)) * v_in; let temp1 = Math.abs(5 - v_out_1); let temp2 = Math.abs(5 - v_out_2); if (temp1 < minimumDifference) { minimumDifference = temp1; minimumPair = pair; } if (temp2 < minimumDifference) { minimumDifference = temp2; minimumPair = pair; } }); console.log(5 - minimumDifference) console.log(minimumPair)
import styled from 'styled-components' export const Character = styled.div` font-weight: bold; font-size: 30px; line-height: 1.2; font-family: Montserrat; text-transform: uppercase; @media (max-width: 999px) { font-size: 25px; } @media (max-width: 641px) { font-size: 20px; } `
import express from 'express'; import Company from '../models/company'; import {isAuthenticatedAdmin} from '../authenticate'; function handleIdParam(req, res, next, id) { Company.findById(id, (err, company) => { if (err) { return res.status(404).send('Company not found: ' + err); } if (!company) { return res.status(500).send('No Company object returned'); } req.company = company; return next(); }); } function handleGet(req, res, next) { Company.find({}, (err, companies) => { if (err || !companies) { return res.status(500).send('Error when retreiving company list: ' + err); } return res.send([for (c of companies) c.toObject()]); }); } function handleGetById(req, res, next) { res.send(req.company); } function handleCreate(req, res, next) { if (!req.body.name) { return res.status(412).send('Company field "name" is requried'); } else if (!req.body.description) { return res.status(412).send('Company field "description" is requried'); } else if ((!req.body.punchcard_lifetime) || (parseInt(req.body.punchcard_lifetime) <= 0)) { return res.status(412).send('Company field "punchcard_lifetime" is requried and must be a positive integer'); } let c = new Company({ name: req.body.name, description: req.body.description, punchcard_lifetime: req.body.punchcard_lifetime }); c.save((err) => { if (err) { return res.status(500).send('Error when creating company: ' + err); } return res.status(201).send({ company_id: c._id }); }); } const companyRouter = express.Router(); companyRouter.param('id', handleIdParam); companyRouter.get('/', handleGet); companyRouter.post('/', isAuthenticatedAdmin, handleCreate); companyRouter.get('/:id', handleGetById); export default companyRouter;
var https = require("https"); var weather = require ('./weather'); var tides = []; exports.get = function () { return tides; } exports.load = function (callback) { var data = ''; tides = []; var options = { hostname: 'admiraltyapi.azure-api.net', path: `/uktidalapi/api/V1/Stations/${config.tides.tideStation}/TidalEvents`, method: 'GET', headers: { "Ocp-Apim-Subscription-Key": config.tides.key, "content": "application/json" } }; var req = https.request(options, (res) => { // console.log("statusCode: ", res.statusCode); // console.log("headers: ", res.headers); res.on('data', function (d) { data += d; }); res.on('close', () => { try { var tideData = JSON.parse(data); var firstDay = moment(tideData[0].DateTime); tideData.forEach(tide => { var dt = moment(tide.DateTime); var day = dt.format("dddd Do"); var dayNo = dt.diff(firstDay, 'days', false); // console.log(`Tide[${day}] ${dt.format('HH.mm')} ${tide.EventType}, ${parseFloat(tide.Height).toFixed(2)}`); dayTides = tides.find((t) => t.day == day); if (!dayTides) { tides.push({ day: day, tides: [] }); dayTides = tides.find((t) => t.day == day); } dayTides.tides.push({ time: dt.format('HH.mm'), height: parseFloat(tide.Height).toFixed(2), varHeight: ((weather.avgPressure() - weather.getPressure(dayNo)) * 0.01).toFixed(2) // cm/mBar }) }); } catch (ex) { console.error(ex); // Deal with JSON.parse error } // console.log(tides[0]); if (callback) callback(); }) }); req.on('error', function (e) { console.error(e); }); req.end(); } exports.show = function (request, response) { response.render("tides", { map: tides }); }
import React from 'react'; import { getDOMNode } from '@test/testUtils'; import { testStandardProps } from '@test/commonCases'; import Divider from '../Divider'; describe('Divider', () => { testStandardProps(<Divider />); it('Should render a Divider', () => { const instance = getDOMNode(<Divider />); const classes = instance.className; assert.include(classes, 'rs-divider'); assert.include(classes, 'rs-divider-horizontal'); }); it('Should be vertical', () => { const instance = getDOMNode(<Divider vertical />); const classes = instance.className; assert.include(classes, 'rs-divider-vertical'); assert.equal(instance.getAttribute('aria-orientation'), 'vertical'); }); it('Should hava a children', () => { const instance = getDOMNode(<Divider>abc</Divider>); const classes = instance.className; assert.include(classes, 'rs-divider-with-text'); }); });
import { createStackNavigator } from "@react-navigation/stack"; import Colors from "../constants/Colors"; import ProductsOverviewScreen from "../screens/shop/ProductsOverviewScreen"; import React from "react"; import { NavigationContainer } from "@react-navigation/native"; import ProductDetailsScreen from "../screens/shop/ProductDetailsScreen"; import { Button, View } from "react-native"; import { HeaderButtons, Item, OverflowMenuProvider, } from "react-navigation-header-buttons"; import CustomHeaderButton from "../components/UI/HeaderButton"; import ProductsCartScreen from "../screens/shop/ProductsCartScreen"; const Stack = createStackNavigator(); const defaultScreenOptions = { headerStyle: { backgroundColor: Colors.primaryColor, }, headerTitleStyle: { fontFamily: "open-sans-bold", }, headerTintColor: "white", }; function ProductNavigator() { return ( <NavigationContainer> <OverflowMenuProvider> <Stack.Navigator screenOptions={defaultScreenOptions}> <Stack.Screen name="Products" component={ProductsOverviewScreen} // options={{ // headerRight: () => ( // <HeaderButtons HeaderButtonComponent={CustomHeaderButton}> // <Item // title="Cart" // iconName="md-cart" // onPress={() => alert("Add to cart")} // /> // </HeaderButtons> // ), // }} /> <Stack.Screen name="Product Details" component={ProductDetailsScreen} options={({ route }) => ({ title: route.params.productTitle, })} /> <Stack.Screen name="Cart" component={ProductsCartScreen} /> </Stack.Navigator> </OverflowMenuProvider> </NavigationContainer> ); } export default ProductNavigator; // export default createAppContainer(ProductNavigator); // const ProductNavigator = createStackNavigator( // { // ProductsOverview: ProductsOverviewScreen, // }, // { // defaultNavigationOptions: { // headerStyle: { // backgroundColor: "red", // }, // }, // } // );
angular.module('ngApp.exchangeRate').factory('ExchangeRateService', function ($http, config, SessionService) { var GetOperationZone = function () { return $http.get(config.SERVICE_URL + '/ExchangeRate/GetOperationZone'); }; var GetCurrencyDetail = function () { return $http.get(config.SERVICE_URL + '/ExchangeRate/GetCurrencyDetail'); }; var GetOperationExchangeRate = function (operationZoneId) { return $http.get(config.SERVICE_URL + '/ExchangeRate/GetOperationExchangeRate', { params: { operationZoneId: operationZoneId } }); }; var GetExchangeYears = function (OperationZoneId, Type) { return $http.get(config.SERVICE_URL + '/ExchangeRate/DistinctYear', { params: { OperationZoneId: OperationZoneId, Type: Type } }); }; var GetExchangeMonth = function (OperationZoneId, Type) { return $http.get(config.SERVICE_URL + '/ExchangeRate/DistinctMonth', { params: { OperationZoneId: OperationZoneId, Type: Type } }); }; var SaveExchangeRate = function (exchangeRate) { return $http.post(config.SERVICE_URL + '/ExchangeRate/SaveExchangeRate', exchangeRate); }; var GetOperationExchangeRateHistory = function (search) { return $http.post(config.SERVICE_URL + '/ExchangeRate/ExchangeRateHistory',search); }; return { GetOperationZone: GetOperationZone, GetCurrencyDetail: GetCurrencyDetail, SaveExchangeRate: SaveExchangeRate, GetOperationExchangeRate: GetOperationExchangeRate, GetExchangeYears: GetExchangeYears, GetExchangeMonth: GetExchangeMonth, GetOperationExchangeRateHistory: GetOperationExchangeRateHistory }; });
const db = require('../../entities/Database'); const Image = require('../../entities/Image'); module.exports = async (req, res) => { const imageId = req.params.id; const imgRaw = db.findOne(imageId); const img = new Image(imgRaw); res.type(img.mimetype).sendFile(img.getFullPath()); };
import React, {Component} from 'react'; import ButtonListItem from './buttonListItem'; class ButtonList extends Component { render(){ const buttonItems = this.props.graphs.map((graph) => { return <ButtonListItem updateGraphs={this.props.updateGraphs} key={graph.id} graph={graph}/> }) return( <ul className="list-group"> {buttonItems} </ul> ); } } export default ButtonList;
/* jshint indent: 1 */ module.exports = function(sequelize, DataTypes) { const authority = sequelize.define('authority', { id: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true }, menu: { type: DataTypes.STRING(255), allowNull: true }, name:{ type: DataTypes.STRING(255), allowNull: true }, url: { type: DataTypes.STRING(255), allowNull: true }, state: { type: DataTypes.INTEGER(11), allowNull: true }, level: { type: DataTypes.INTEGER(11), allowNull: true }, parent: { type: DataTypes.INTEGER(11), allowNull: true }, remark: { type: DataTypes.STRING(255), allowNull: true }, createdAt: { type: DataTypes.DATE, allowNull: true }, updatedAt: { type: DataTypes.DATE, allowNull: true } }, { freezeTableName: true, tableName: 'authority', classMethods: { associate: function (models) { authority.belongsToMany(models.roles, {foreignKey: "AuthorityId", through: models.authorityRole}); } } }); return authority; };
document.getElementById("contactphone").onclick = setPhoneRequired; document.getElementById("contactmobile").onclick = setMobileRequired; document.getElementById("contactemail").onclick = setEmailRequired; var el = document.getElementById("magzine"); el.addEventListener("click", disableMagazine); document.getElementById("surname").onchange = surnameCheck; document.getElementById("othername").onchange = othernameCheck; document.getElementById("cusmobile").onchange = mobileCheck; document.getElementById("cusphone").onchange = phoneCheck; document.getElementById("cusemail").onchange = emailCheck; document.getElementById("joinusername").onchange = userNameCheck; document.getElementById("postcode").onchange = postCodeCheck; document.getElementById("joinpass").onchange = passwordCheck; document.getElementById("verifypass").onchange = passwordConfirm; document.getElementById("submit").onclick = formValidate;
import React, {useReducer} from 'react' import axios from 'axios' import CategoryContext from './categoryContext' import CategoryReducer from './CategoryReducer' import { CREATE_SUCCESS, CREATE_FAIL, LIST_SUCCESS, LIST_FAIL, CLEAR_CATEGORY_ERRORS, CATEGORY_DELETED, CATEGORY_DELETE_FAIL, CLEAR_CATEGORY_MESSAGE, } from '../types' import setAuthToken from '../../utills/setAuthToken' const CategoryState = props => { const initialState = { categories: [], category: null, error: null, message: null, } const [state, dispatch] = useReducer(CategoryReducer, initialState) //setting auth token for headers if (localStorage.token) { setAuthToken(localStorage.token) } const createCategory = async (name, userId) => { const config = { headers: { "Content-Type": "application/json" }, name, } try { const res = await axios.post(`/categories/create/${userId}`, config) dispatch({ type: CREATE_SUCCESS, payload: res.data }) } catch (err) { dispatch({ type: CREATE_FAIL, payload: err.response.data.msg }) } } const listCategories = async () => { const config = { headers: { "Content-Type": "application/json" }, } try { const res = await axios.get('/categories', config) dispatch({ type: LIST_SUCCESS, payload: res.data.results }) } catch (err) { dispatch({ type: LIST_FAIL, payload: err.response.data.msg, }) } } const removeCategory = async (categoryId, userId) => { const config = { headers: { "Content-Type": "application/json" }, } try { const res = await axios.delete(`/categories/${categoryId}/${userId}`, config) dispatch({ type: CATEGORY_DELETED, payload: res.data }) } catch (err) { dispatch({ type: CATEGORY_DELETE_FAIL, payload: err.response.data.msg, }) } } const clearErrors = () => { dispatch({ type: CLEAR_CATEGORY_ERRORS, }) } const clearMessage = () => { dispatch({ type: CLEAR_CATEGORY_MESSAGE, }) } return ( <CategoryContext.Provider value={{ categories: state.categories, category: state.category, error: state.error, message: state.message, createCategory, listCategories, clearErrors, removeCategory, clearMessage, }} > {props.children} </CategoryContext.Provider> ) } export default CategoryState
/* See license.txt for terms of usage */ define([ "firebug/lib/trace", ], function (FBTrace) { // ********************************************************************************************* // // Remote Debugging Protocol Types var RDP = {}; /** * Set of debug protocol request types that specify the protocol request being * sent to the server. */ RDP.DebugProtocolTypes = { "assign": "assign", "attach": "attach", "clientEvaluate": "clientEvaluate", "delete": "delete", "detach": "detach", "frames": "frames", "interrupt": "interrupt", "listTabs": "listTabs", "nameAndParameters": "nameAndParameters", "ownPropertyNames": "ownPropertyNames", "property": "property", "prototype": "prototype", "prototypeAndProperties": "prototypeAndProperties", "resume": "resume", "scripts": "scripts", "setBreakpoint": "setBreakpoint" }; // ********************************************************************************************* // /** * Set of protocol messages that affect thread state, and the * state the actor is in after each message. */ RDP.ThreadStateTypes = { "paused": "paused", "resumed": "attached", "detached": "detached" }; // ********************************************************************************************* // /** * Set of protocol messages that are sent by the server without a prior request * by the client. */ RDP.UnsolicitedNotifications = { "newSource": "newSource", "tabDetached": "tabDetached", "tabNavigated": "tabNavigated" }; // ********************************************************************************************* // // Registration return RDP; // ********************************************************************************************* // });
class dadoDemograficoC { constructor(id, nomeMae, nomePai, situacaoFamiliar, dataNascimento, indicadorDiaNascimento, indicadorMesNascimento, indicadorAnoNascimento, seguimento, dataObito, indicadorDiaObito, indicadorMesObito, indicadorAnoObito, fonteNotificacao, etnia, genero, nacionalidade, pais, estado, cidade, dataEntradaNoBrasil, pluralidadeNascimento, ordemNascimento, comentarioIdentificacao){ this.id = id; this.nomeMae = nomeMae; this.nomePai = nomePai; this.situacaoFamiliar = situacaoFamiliar; this.dataNascimento = dataNascimento; this.indicadorDiaNascimento = indicadorDiaNascimento; this.indicadorMesNascimento = indicadorMesNascimento; this.indicadorAnoNascimento = indicadorAnoNascimento; this.seguimento = seguimento; this.dataObito = dataObito; this.indicadorDiaObito = indicadorDiaObito; this.indicadorMesObito = indicadorMesObito; this.indicadorAnoObito = indicadorAnoObito; this.fonteNotificacao = fonteNotificacao; this.etnia = etnia; this.genero = genero; this.nacionalidade = nacionalidade; this.pais = pais; this.estado = estado; this.cidade = cidade; this.dataEntradaNoBrasil = dataEntradaNoBrasil; this.pluralidadeNascimento = pluralidadeNascimento; this.ordemNascimento = ordemNascimento; this.comentarioIdentificacao = comentarioIdentificacao; } }
/* * Sonatype Nexus (TM) Open Source Version. Copyright (c) 2008 Sonatype, Inc. * All rights reserved. Includes the third-party code listed at * http://nexus.sonatype.org/dev/attributions.html This program is licensed to * you under Version 3 only of the GNU General Public License as published by * the Free Software Foundation. This program is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License Version 3 for more details. You should have received a copy of * the GNU General Public License Version 3 along with this program. If not, see * http://www.gnu.org/licenses/. Sonatype Nexus (TM) Professional Version is * available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. */ Sonatype.repoServer.AbstractRepositorySummaryPanel = function(config) { var config = config || {}; var defaultConfig = {}; Ext.apply(this, config, defaultConfig); var abstractItems = [{ xtype : 'textfield', fieldLabel : 'Repository Information', hidden : true }, { xtype : 'textarea', name : 'informationField', anchor : Sonatype.view.FIELD_OFFSET, readOnly : true, hideLabel : true, height : 150 }]; Sonatype.repoServer.AbstractRepositorySummaryPanel.superclass.constructor.call(this, { uri : this.payload.data.resourceURI + '/meta', readOnly : true, dataModifiers : { load : { 'rootData' : this.populateFields.createDelegate(this) }, save : {} }, items : abstractItems.concat(this.items) }); }; Ext.extend(Sonatype.repoServer.AbstractRepositorySummaryPanel, Sonatype.ext.FormPanel, { getActionURL : function() { return this.uri; }, populateFields : function(arr, srcObj, fpanel) { this.populateInformationField('Repository ID: ' + srcObj.id + '\n'); this.populateInformationField('Repository Name: ' + this.payload.data.name + '\n'); this.populateInformationField('Repository Type: ' + this.payload.data.repoType + '\n'); this.populateInformationField('Repository Policy: ' + this.payload.data.repoPolicy + '\n'); this.populateInformationField('Repository Format: ' + this.payload.data.format + '\n'); this.populateInformationField('Contained in groups: ' + '\n' + this.combineGroups(srcObj.groups) + '\n'); }, populateInformationField : function(text) { var infoText = this.find('name', 'informationField')[0].getValue(); infoText += text; this.find('name', 'informationField')[0].setRawValue(infoText); }, combineGroups : function(groups) { var combinedGroups = ''; if (groups != undefined && groups.length > 0) { for (var i = 0; i < groups.length; i++) { var group = this.groupStore.getAt(this.groupStore.findBy(function(rec, recid) { return rec.data.id == groups[i]; }, this)); if (group) { if (combinedGroups.length > 0) { combinedGroups += '\n'; } combinedGroups += ' ' + group.data.name; } } } return combinedGroups; } }); Sonatype.repoServer.HostedRepositorySummaryPanel = function(config) { var config = config || {}; var defaultConfig = {}; Ext.apply(this, config, defaultConfig); Sonatype.repoServer.HostedRepositorySummaryPanel.superclass.constructor.call(this, { items : [{ xtype : 'textfield', fieldLabel : 'Distribution Management', hidden : true }, { xtype : 'textarea', name : 'distMgmtField', anchor : Sonatype.view.FIELD_OFFSET, readOnly : true, hideLabel : true, height : 100 }] }); }; Ext.extend(Sonatype.repoServer.HostedRepositorySummaryPanel, Sonatype.repoServer.AbstractRepositorySummaryPanel, { populateFields : function(arr, srcObj, fpanel) { Sonatype.repoServer.HostedRepositorySummaryPanel.superclass.populateFields.call(this, arr, srcObj, fpanel); this.populateDistributionManagementField(this.payload.data.id, this.payload.data.repoPolicy, this.payload.data.contentResourceURI); }, populateDistributionManagementField : function(id, policy, uri) { var distMgmtString = '<distributionManagement>\n <${repositoryType}>\n <id>${repositoryId}</id>\n <url>${repositoryUrl}</url>\n </${repositoryType}>\n</distributionManagement>'; distMgmtString = distMgmtString.replaceAll('${repositoryType}', policy == 'Release' ? 'repository' : 'snapshotRepository'); distMgmtString = distMgmtString.replaceAll('${repositoryId}', id); distMgmtString = distMgmtString.replaceAll('${repositoryUrl}', uri); this.find('name', 'distMgmtField')[0].setRawValue(distMgmtString); } }); Sonatype.repoServer.ProxyRepositorySummaryPanel = function(config) { var config = config || {}; var defaultConfig = {}; Ext.apply(this, config, defaultConfig); Sonatype.repoServer.ProxyRepositorySummaryPanel.superclass.constructor.call(this, { items : [] }); }; Ext.extend(Sonatype.repoServer.ProxyRepositorySummaryPanel, Sonatype.repoServer.AbstractRepositorySummaryPanel, { populateFields : function(arr, srcObj, fpanel) { Sonatype.repoServer.ProxyRepositorySummaryPanel.superclass.populateFields.call(this, arr, srcObj, fpanel); var remoteUri = this.payload.data.remoteUri; if (remoteUri == undefined) { remoteUri = this.payload.data.remoteStorage.remoteStorageUrl; } this.populateInformationField('Remote URL: ' + remoteUri + '\n'); } }); Sonatype.repoServer.VirtualRepositorySummaryPanel = function(config) { var config = config || {}; var defaultConfig = {}; Ext.apply(this, config, defaultConfig); Sonatype.repoServer.VirtualRepositorySummaryPanel.superclass.constructor.call(this, { items : [] }); }; Ext.extend(Sonatype.repoServer.VirtualRepositorySummaryPanel, Sonatype.repoServer.AbstractRepositorySummaryPanel, {}); Sonatype.Events.addListener('repositoryViewInit', function(cardPanel, rec, gridPanel) { var sp = Sonatype.lib.Permissions; var repoPanels = { hosted : Sonatype.repoServer.HostedRepositorySummaryPanel, proxy : Sonatype.repoServer.ProxyRepositorySummaryPanel, virtual : Sonatype.repoServer.VirtualRepositorySummaryPanel }; var panel = repoPanels[rec.data.repoType]; if (panel && rec.data.resourceURI && sp.checkPermission('nexus:repometa', sp.READ)) { cardPanel.add(new panel({ tabTitle : 'Summary', name : 'summary', payload : rec, groupStore : gridPanel.groupStore })); } });
// miniprogram/pages/dataAnalysis/dataAnalysis.js import { formatTime } from '../../utils/api.js'; Page({ /** * 页面的初始数据 */ data: { discussShow: false, topicId: '', commentNum: 0, commentText: '', comment: [], userInfo: [], voteOption:[], optionId:[], sum: 0, lastImg:'', headTitle:'', commentTitle:'', lasttime: 0 }, discussAct() { this.setData({ discussShow: !this.data.discussShow }) }, // // 跳转到详情页面 _twoComment(e) { console.log(e) wx.navigateTo({ url: '../comment-detail/comment-detail?commentId=' + e.currentTarget.dataset.id, }) }, //输入框文字改变时同步至输入框 onCommentTextChange(e) { // console.log(e) this.setData({ commentText: e.detail.value }) }, // 往数据库里添加评论 addComment() { let that = this; //判断用户是否输入了内容 if (that.data.commentText == '') { wx.showToast({ title: '评论内容不能为空', icon: 'none', duration: 2000 }) } else { wx.cloud.callFunction({ name: 'addComment', data: { commentText: that.data.commentText, info: that.data.userInfo, topicId: that.data.topicId }, success() { console.log('插入成功'); wx.cloud.callFunction({ name: 'getComment', data: { topicId: that.data.topicId }, success(res) { let newComment = that.newTime(res.result.newcomment) that.setData({ comment: newComment, commentNum: res.result.newcomment.length }) } }) // 评论成功后清空数据,关闭评论框 that.setData({ discussShow: false, commentText: '' }) } }) } }, // 格式化时间 newTime(comment) { let newComment = [] let length = comment.length for (let i = 0; i < length; i++) { comment[i].time = formatTime(comment[i].time) } return comment }, //提前改变 _dianzan(e) { var that = this; let d = new Date(); let nowtime = d.getTime();//获取点击时间 if (nowtime - that.data.lasttime > 1500) { that._dianzan1(e); } else { wx.showToast({ title: '您点击的太快了', duration: 1000, icon: 'none' }) } that.setData({ lasttime: nowtime }) }, //点赞功能 _dianzan1(e) { console.log(e.currentTarget.dataset.id) let that = this; //提前在页面做好改变 // var thisComment = that.data.comment[e.currentTarget.dataset.index]; if (that.data.comment[e.currentTarget.dataset.index].bool) { that.data.comment[e.currentTarget.dataset.index].bool = false; that.data.comment[e.currentTarget.dataset.index].DZ_num = that.data.comment[e.currentTarget.dataset.index].DZ_num - 1; } else { that.data.comment[e.currentTarget.dataset.index].bool = true; that.data.comment[e.currentTarget.dataset.index].DZ_num = that.data.comment[e.currentTarget.dataset.index].DZ_num + 1; } that.setData({ comment: that.data.comment }) wx.cloud.callFunction({ name: 'Dianzan', data: { // userId: commentId: e.currentTarget.dataset.id, topicId: that.data.topicId }, success(res) { let newComment = that.newTime(res.result.newcomment) that.setData({ comment: newComment }) console.log(res) console.log(that.data.comment) }, fail(error) { console.log(error) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { const that = this; const opId = JSON.parse(options.optionId) wx.setNavigationBarTitle({ title: options.topicTitle }) // 获取传过来的 话题Id 和 选中项Id that.setData({ topicId: options.topicId, optionId: opId }) console.log(that.data.optionId) // 获取当前用户的信息 wx.login({ success: function () { wx.getUserInfo({ success: function (res) { // var simpleUser = res.userInfo; // console.log(simpleUser); that.setData({ userInfo: res.userInfo }) }, fail: function (error) { console.log(error) } }); } }); //获取当前数据库中评论信息 wx.cloud.callFunction({ name: 'getComment', data: { topicId: that.data.topicId }, success(res) { let newComment = that.newTime(res.result.newcomment) that.setData({ comment: newComment, commentNum: res.result.newcomment.length }) // console.log(res.result.data) } }) //获取当前话题的数据 wx.cloud.callFunction({ name: 'getTopic', data: { topicId: that.data.topicId }, success(res) { // console.log(res) console.log(res); that.setData({ commentTitle: res.result.oneTopic.data[0].topicTitle }) } }) //获取当前的投票选项 wx.cloud.callFunction({ name: 'getVoteOption', data: { topicId: that.data.topicId, optionId: that.data.optionId }, success(res) { // console.log(res) that.setData({ voteOption: res.result.voteOption1, sum: res.result.sum }) // console.log(res) that.selectOption(that) that.selected(that) console.log(that.data.voteOption) }, fail(res){ console.log(res) } }) // 测试用 // wx.cloud.callFunction({ // name: 'test', // data: { // topicId: that.data.topicId, // optionId: that.data.optionId // }, // success(res) { // console.log(res) // }, // fail(res){ // console.log(res) // } // }) // console.log(this.data) }, // 选择最后一个选项 selectOption(that){ const length = that.data.optionId.length let optionId = that.data.optionId[length-1]; for (let option of that.data.voteOption){ if (optionId == option._id){ that.setData({ lastImg: option.optionImg, headTitle: option.optionDesc }) } } }, selected(that){ let vo = that.data.voteOption const length = that.data.optionId.length for(let i = 0; i < length; i++){ for (let option of vo) { if (that.data.optionId[i] == option._id){ option.selected = true } } } that.setData({ voteOption : vo }) }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, })