text
stringlengths
7
3.69M
import axios from 'axios' import qs from 'qs' import { defaturl } from './apiUrl' axios.defaults.baseURL = defaturl axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' // --------------- 经济指标 ---------------------- // 新增 // export const addEconomic = (params, callback) => { return axios.post('/ll/addEconomic', qs.stringify({ ...params })).then((data) => { callback(data) }) } export const addEconomic = (params, callback, errorback) => { return axios.post('/ll/addEconomic', (params), { headers: { 'Content-Type': 'application/json' } }).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 查询所有 export const allIndexlist = (params, callback) => { return axios.get('/ll/searchs', { params }).then((data) => { callback(data) }).catch(function () { }) } // 根据ID查询 export const indexById = (params, callback) => { return axios.post('/ll/searchById', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function () { }) } // 编辑 // export const editIndex = (params, callback) => { return axios.post('/ll/updateEconomic', qs.stringify({ ...params })).then((data) => { callback(data) }) } export const editIndex = (params, callback, errorback) => { return axios.post('/ll/updateEconomic', (params), { headers: { 'Content-Type': 'application/json' } }).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 根据时间查询 export const yearIndexlist = (params, callback) => { return axios.get('/ll/searchByYear', { params }).then((data) => { callback(data) }).catch(function () { }) } // 搜索查询 export const getFilterIndexlist = (params, callback) => { return axios.post('/ll/searchFilterPage', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 手动修改材料报送状态 export const changeFormState = (params, callback) => { return axios.post('/ll/updateFormstatusById', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 修改总体进度 export const changeTotalState = (params, callback) => { return axios.post('/ll/updateTotalstatusById', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 承办单位指标管理 export const getDistrictIndexlist = (params, callback) => { return axios.post('/cc/searchFilterPage', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 根据ID查询 export const indexByIdDistrict = (params, callback) => { return axios.post('/cc/searchById', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function () { }) } // 新增 // export const adddDistrictEconomic = (params, callback) => { return axios.post('/cc/addEconomicDept', qs.stringify({ ...params })).then((data) => { callback(data) }) } export const adddDistrictEconomic = (params, callback, errorback) => { return axios.post('/cc/addEconomicDept', (params), { headers: { 'Content-Type': 'application/json' } }).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 编辑 // export const editIndexDistrict = (params, callback) => { return axios.post('/cc/updateEconomicDept', qs.stringify({ ...params })).then((data) => { callback(data) }) } export const editIndexDistrict = (params, callback, errorback) => { return axios.post('/cc/updateEconomicDept', (params), { headers: { 'Content-Type': 'application/json' } }).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 查询所有 export const getAllCheng = (params, callback) => { return axios.get('/cc/searchs', { params }).then((data) => { callback(data) }).catch(function () { }) } // 手动修改材料报送状态 export const changeChengFormState = (params, callback) => { return axios.post('/cc/updateFormstatusById', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 修改总体进度 export const changeChengTotalState = (params, callback) => { return axios.post('/cc/updateTotalstatusById', qs.stringify({ ...params })).then((data) => { callback(data) }) } // ---------------- 区(市)县管理 ------------------ // 新增 export const addDistrict = (params, callback) => { return axios.post('/targetDistrict/addDistrict', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 查询所有 export const allArealist = (params, callback) => { return axios.get('/targetDistrict/searchs', { params }).then((data) => { callback(data) }).catch(function () { }) } // 根据ID查询 export const areaById = (params, callback) => { return axios.get('/targetDistrict/searchById', { params }).then((data) => { callback(data) }).catch(function () { }) } // 查询类别列表 export const typelist = (params, callback) => { return axios.get('/Type/searchAll', { params }).then((data) => { callback(data) }).catch(function () { }) } // 编辑 export const editDistrict = (params, callback) => { return axios.post('/targetDistrict/updateDistrict', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 新增类别 export const addTypes = (params, callback) => { return axios.post('/Type/addType', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 搜索查询 export const getFilterArea = (params, callback) => { return axios.post('/targetDistrict/searchPage', qs.stringify({ ...params })).then((data) => { callback(data) }) } // ----------------------------- 其他区县管理 ------------------- // 新增 export const addOtherfill = (params, callback) => { return axios.post('/OtherEconomic/addOEconomic', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 查询所有 export const getAllOtherfill = (params, callback) => { return axios.get('/OtherEconomic/searchAll', { params }).then((data) => { callback(data) }).catch(function () { }) } // 搜索查询 export const getFilterOtherfill = (params, callback) => { return axios.get('/OtherEconomic/searchFilterPage', { params }).then((data) => { callback(data) }).catch(function () { }) } // 争先工作 // 汇总表 export const getCountAll = (params, callback) => { return axios.post('/targetPrize/countPrizePage', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 填报列表 export const getAllHonor = (params, callback) => { return axios.post('/targetPrize/searchPageFilter', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 填报新增 export const addFillHonor = (params, callback) => { return axios.post('/targetPrize/addTargetPrize', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 填报编辑 export const editFillHonor = (params, callback) => { return axios.post('/targetPrize/updateTargetPrize', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 非经济指标 // 进展汇总表 export const getmicList = (params, callback) => { return axios.get('/mic/searchAll', { params }).then((data) => { callback(data) }).catch(function () { }) } // 进展汇总表 - 新增 export const addSummary = (params, callback) => { return axios.post('/mic/addNoneconomic', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 修改 export const editSummary = (params, callback) => { return axios.post('/mic/updateNoneconomic', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 根据ID查询 export const summarylistId = (params, callback) => { return axios.get('/mic/searchById', { params }).then((data) => { callback(data) }).catch(function () { }) } // 新增进展汇报 export const addSummartReport = (params, callback) => { return axios.post('/ort/addReport', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 添加承办单位 export const adddutyReport = (params, callback) => { return axios.post('/zer/addOrganizer', qs.stringify({ ...params })).then((data) => { callback(data) }) } // 目标责任分解表 export const aimListall = (params, callback) => { return axios.get('/mic/searchAim', { params }).then((data) => { callback(data) }).catch(function () { }) }
// document.getElementById("swimButton").addEventListener("click", startSwimming) document.querySelector("[data-btn='swimButton']").addEventListener('click', startSwimming); function startSwimming() { let swimmers = document.querySelectorAll('[data-swimmer]'); //loop through the 3 HTML elements in 'swimmers' and //add className swimmer + the proper class index for (var i = 0; i < swimmers.length; i++) { swimmers[i].className += " swimmer"+(i+1); } }
export default function () { return new Promise(function (resolve) { setTimeout(function () { resolve([{ id: '16n5jkgfc0d4k760', name: 'Take a shower' }, { id: '9a2889n7f55s410v', name: 'Walk the dog' }, { id: 'pmakvvvb1s2aapkf', name: 'Go to work' }]); }, 1500); }); }
// import { useEffect } from 'react'; import { useSelector } from 'react-redux'; import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; import ResponsiveDrawer from './Layout'; import AdminFamily from './AdminFamily'; import adminProperty from './adminProperty'; import Home from './Home'; import SignIn from './SignIn'; // import CompanySignUp from './SignUp/CompanySignUp'; const LayoutedRoute = ({ component: Component, layout: Layout, ...rest }) => { const connected = useSelector((state) => state.auth.isAuth); if (!connected) { return <Redirect to="/signin" />; } return ( <Route {...rest} render={(props) => { return ( <Layout> <Component {...props} /> </Layout> ); }} /> ); }; export default function Router() { return ( <BrowserRouter> <Switch> <Route path="/signin" component={SignIn} /> {/* <Route path="/signup" component={CompanySignUp} /> */} <LayoutedRoute path="/adminFamily" layout={ResponsiveDrawer} component={AdminFamily} /> <LayoutedRoute path="/adminProperty" layout={ResponsiveDrawer} component={adminProperty} /> <LayoutedRoute exact path="/" layout={ResponsiveDrawer} component={Home} /> </Switch> </BrowserRouter> ); } LayoutedRoute.propTypes = { component: PropTypes.node.isRequired, layout: PropTypes.node.isRequired, };
const express = require('express') const app = express() const server = require('http').Server(app) const cors = require('cors') // const Scrapper = require('./app/Scrapper') // const userName = process.argv.indexOf('-s') > -1 ? process.argv[3] : process.argv[2] // const postsNumber = process.argv.indexOf('-s') > -1 ? process.argv[4] : process.argv[3] // const scrap = new Scrapper(userName) app.use(cors()) app.use(require('./app/routes/routes')) server.listen(3333) // process.argv.indexOf('-s') > -1 ? // scrap.static().catch(error => console.error(error)) : // scrap.dynamic(postsNumber).catch(error => console.error(error))
function httpRequest(url,callback) { var xhr = new XMLHttpRequest(); xhr.open("GET", url,true); xhr.onreadystatechange = function() { if(xhr.readyState == 4){ callback(xhr.responseText); } } xhr.send(); } var weekday=new Array(7); weekday[0]="星期天"; weekday[1]="星期一"; weekday[2]="星期二"; weekday[3]="星期三"; weekday[4]="星期四"; weekday[5]="星期五"; weekday[6]="星期六"; function showWeather(result){ result = JSON.parse(result); var list = result.list; var table = "<p id='city'><a href='options.html'>"+localStorage.city+"</a></p>"; table += "<table><tr><th>日期</th><th>星期</th><th>天气</th><th>最低温度</th><th>最高温度</th></tr>"; for(var i in list){ var d = new Date(list[i].dt*1000); table += "<tr>"; table += "<td>"+d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+"</td>"; table += "<td>"+weekday[d.getDay()]+"</td>"; table += "<td>"+list[i].weather[0].description+"</td>"; table += "<td>"+Math.round(list[i].temp.min-273.15)+" °C</td>"; table += "<td>"+Math.round(list[i].temp.max-273.15)+" °C</td>"; table += "</tr>" } table += "</table>"; document.getElementById("weather").innerHTML = table; } var city = localStorage.city; city = city?city:"beijing"; var url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q='+city+',china&lang=zh_cn&APPID=65d1bd8ddc51490ee98f0d478e91db85'; httpRequest(url, showWeather);
function run(){return!0}function call_it(n){console.log(n)}call_it(name);
'use strict'; var Basic = require('hapi-auth-basic'); /** * Have a short list of users * * @type {{john: {un: string, pw: string, nm: string, id: string}, jane: {un: string, pw: string, nm: string, id: string}}} */ var users = { john: { un: 'john', pw: 'letmein', nm: 'John Doe', id: '1' }, jane: { un: 'jane', pw: 'letmein', nm: 'Jane Doe', id: '2' } }; /** * Validate user credentials * * @param request * @param username * @param password * @param callback */ var simpleValidation = function(request, username, password, callback){ var user = users[username], isValid, err; // no user should return if user is not found if ( !user ) { return callback(null, false); } // compare password otherwise isValid = user.pw == password; // create error if password didn't match if( !isValid ) { err = new Error('Invalid Credentials'); } callback(err, isValid, { id: user.id, name: user.nm}); }; module.exports = function(server) { server.register(Basic, function(err){ if (err) { throw err }; server.auth.strategy('simple', 'basic', { validateFunc: simpleValidation }); }); };
const _ = require('lodash'); const fs = require('fs'); const activation = require('./lib/activation.js'); function NeuroNet(){ this.weights; this.biases; this.beta; //for widrow weight init this.w_deltas; this.b_deltas; this.w_moment; this.errors; this.nodes; this.options; this.error; this.test_error; this.square_errors; this.act; this.der; this.lr; this.stop; this.data_size; this.defaults = { hidden:[2], input:2, output:1, learn_rate: 0.3, moment:0.1, l2:0, //l2 regularization coefficient batch:1, test:0, //calculate test error during training every n epoch. dy default n = 0, so it doesnt calculate at all csv:false, emergency_save:true, //save net if process was interrupted activation:'sigmoid', //'sigmoid', 'bipolar_sigmoid' initial_weights:'standard', //'standard', 'widrow' max_epoch: 20000, est_error: 0.005, console_logging: { show: true, step: 1000, show_iter: true, show_error: true, show_test_error: false, show_weights: false, show_w_deltas: false } }; } NeuroNet.prototype.setData = function(d){ if (typeof(d) === 'object') return d; else if (typeof(d) === 'string') { var data = fs.readFileSync(d,'utf-8'); if(this.options.csv) return this.getCSVData(data); else return JSON.parse(data); } } NeuroNet.prototype.load = require('./lib/fs_handler.js').load; NeuroNet.prototype.save = require('./lib/fs_handler.js').save; NeuroNet.prototype.saveSync = require('./lib/fs_handler.js').saveSync; NeuroNet.prototype.getCSVData = require('./lib/fs_handler.js').getCSVData; NeuroNet.prototype.init = function(options){ this.options = options || {}; for (let opt in this.defaults){ if(typeof(this.options[opt]) == 'object') { for (let inner_opt in this.defaults[opt]) { if(!this.options[opt][inner_opt]) this.options[opt][inner_opt] = this.defaults[opt][inner_opt]; //defaults for array and object options } } else if(!this.options[opt]) this.options[opt]=this.defaults[opt] //defaults for other options } this.setLayers(); this.weights = this.weights || this.getInitialWeights(); this.biases = this.biases || this.getInitialBiases(); this.act = activation[this.options.activation], this.der = activation[`derivative_${this.options.activation}`]; this.lr = this.options.learn_rate; return this; } NeuroNet.prototype.getInitialWeights = require('./lib/get_initial_weights.js'); NeuroNet.prototype.getInitialBiases = require('./lib/get_initial_biases.js'); NeuroNet.prototype.setLayers = require('./lib/set_layers.js'); NeuroNet.prototype.run = require('./lib/run.js'); NeuroNet.prototype.show_progress = require('./lib/show_progress.js') NeuroNet.prototype.train_once = require('./lib/train.js'); NeuroNet.prototype.train = function(data, testData){ let goalReached = false; let iter = 0; let max_epoch = this.options.max_epoch; this.stop = false; data = this.setData(data); this.data_size = data.length; this.saveOnInterrupt(); for (let iter = 0; iter <= max_epoch; iter++){ this.square_errors = []; if(this.stop || goalReached) break; for (let step = data.length - 1; step >=0; step--){ this.train_once(data[step].input, data[step].output, step); } this.error = _.mean(this.square_errors); if(this.options.test > 0 && iter % this.options.test === 0) this.test(testData); this.show_progress(iter); if (this.error < this.options.est_error) goalReached = true; } return this; } NeuroNet.prototype.test = function(data){ data = this.setData(data); let square_errors = []; for (let step = data.length - 1; step >=0; step--){ let output = this.run(data[step].input); let target = data[step].output; target.forEach((t,index) => { square_errors.push((t - output[index])**2) }) } this.test_error = _.mean(square_errors); return this; } NeuroNet.prototype.applyTrainUpdate = function (){ let l2 = this.options.l2, lr = this.lr, ds = this.data_size; for (let i = 0; i < this.weights.length; i++){ for (let j = this.weights[i].length-1; j>=0; j--){ this.biases[i][j] += lr * this.b_deltas[i][j]; this.b_deltas[i][j] = 0.0; for (let k = this.weights[i][j].length-1; k>=0; k--){ let adjust = this.w_moment[i][j][k]; if(l2 > 0) adjust = lr * (this.w_deltas[i][j][k] + (l2/ds) * this.weights[i][j][k]) + this.options.moment * adjust; else adjust = lr * this.w_deltas[i][j][k] + this.options.moment * adjust; this.w_moment[i][j][k] = adjust; this.weights[i][j][k] += adjust; this.w_deltas[i][j][k] = 0.0; } } } for (let i = this.biases[this.biases.length-1].length-1; i>=0; i--){ //apply biases of output layer this.biases[this.biases.length-1][i] += lr * this.b_deltas[this.biases.length-1][i]; this.b_deltas[this.biases.length-1][i] = 0.0; } } NeuroNet.prototype.saveOnInterrupt = function(stop){ if (process.platform === "win32") { var rl = require("readline").createInterface({ input: process.stdin, output: process.stdout }); rl.on("SIGINT", function () { process.emit("SIGINT"); }); } process.on('SIGINT', ()=>{ this.stop = true; console.log('siginit') this.saveSync('emergency_save_net2.dat') process.exit(); }); } module.exports = NeuroNet;
///// Mapas base var osm = L.tileLayer('https://a.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: 'Map Data &copy; OpenstreetMap contributors'}); var terrain = new L.StamenTileLayer("terrain"); var toner = new L.StamenTileLayer("toner"); var map = L.map('map',{ center:[16.200, -100.000], timeDimensionControl: true, timeDimensionControlOptions: { position: 'bottomright', autoPlay: false, timeSlider: true, loopButton: true, timeSliderDragUpdate: true, playerOptions: { transitionTime: 125, loop: true, } }, timeDimension: true, zoom:7, minZoom: 6.5, layers:[terrain, toner] }); var googleTerrain = L.tileLayer('https://{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }).addTo (map); var googleSat = L.tileLayer('https://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }).addTo (map); var googleStreets = L.tileLayer('https://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }).addTo (map); var googleHybrid = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}',{ maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'] }).addTo (map); var carto = L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png",{ "attribution": "\u0026copy; \u003ca href=\"http://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors \u0026copy; \u003ca href=\"http://cartodb.com/attributions\"\u003eCartoDB\u003c/a\u003e, CartoDB \u003ca href =\"http://cartodb.com/attributions\"\u003eattributions\u003c/a\u003e", "detectRetina": false, "maxNativeZoom": 18, "maxZoom": 18, "minZoom": 0, "noWrap": false, "opacity": 1, "subdomains": "abc", "tms": false} ).addTo (map); var baseMaps = { "<b>Mapa en blanco y negro</b>": toner, "<b>Mapa de calles</b>": googleStreets, "<b>Imagen de satélite</b>": googleSat, "<b>Mapa Híbrido</b>": googleHybrid, "<b>Mapa de relieve</b>": googleTerrain, "<b>Mapa de terreno</b>": terrain, "<b>Mapa en tonos claros</b>": carto }; L.control.layers(baseMaps).addTo (map); //// Mapa de placas tectónicas function placas_style(feature) { return { fillColor: 'white', weight: 2, opacity: 1, color: '#d95a0b', dashArray: '5', fillOpacity: 0 }; } L.geoJson(placas, { style: placas_style }).addTo(map); //// Mapa de estados function edo_style(feature) { return { fillColor: 'white', weight: 1.5, opacity: 1, color: 'black', dashArray: '1', fillOpacity: 0.35 }; } L.geoJson(estados, { style: edo_style }).addTo(map); //// Mapa del estado de Guerrero function gro_style(feature) { return { fillColor: 'white', weight: 5, opacity: 1, color: '#ad0707', dashArray: '1', fillOpacity: 0.1 }; } L.geoJson(guerrero, { style: gro_style }).addTo(map); //// Mapa de municipios de Guerrero function color_ca (ca) { return ca == "Alta" ? '#2ca25f': ca == "Media" ? '#99d8c9': ca == "Baja" ? '#e5f5f9': '#ffffff'; } function style_ca (feature) { return { fillColor: color_ca(feature.properties.CAP_ADAP), weight: 0.3, opacity: 1, color: 'black', dashArray: '0', fillOpacity: 0.7 }; } //// Funciones de información por municipio function highlightFeature(e) { var layer = e.target; layer.setStyle({ weight: 3, color: '#666', dashArray: '', fillOpacity: 0.5 }); info.update(layer.feature.properties); } function resetHighlight(e) { municipios.resetStyle(e.target); info.update(); } function zoomToFeature(e) { map.fitBounds(e.target.getBounds()); } function onEachFeature(feature, layer) { layer.on({ mouseover: highlightFeature, mouseout: resetHighlight, click: zoomToFeature }); } municipios = L.geoJson(municipios_gro, { style: style_ca, onEachFeature: onEachFeature }).addTo(map); ////// Control de información de municipios var info = L.control(); info.onAdd = function (map) { this._div = L.DomUtil.create('div', 'info'); this.update(); return this._div; }; info.update = function (props) { this._div.innerHTML = '<h4>Información por municipio</h4>' + (props ? '<b>' + props.NOMGEO + '</b><br />' + '<br><b>Grado de Vulnerabilidad:</b> ' + props.VUL_CC + '<br><b>Peligro a ciclones tropicales:</b> ' + props.RCla_CicTr : 'Pase el cursor sobre un municipio'); }; info.addTo(map); /////Simbología de Mapa municipios var capadaplegend = L.control({position: "topleft"}); capadaplegend.onAdd = function (map) { var div = L.DomUtil.create('div', 'info legend'); div.innerHTML += "<b> Capacidad de adaptación </b></br>"; div.innerHTML += '<i style="background: #e5f5f9"></i><span>Baja</span><br>'; div.innerHTML += '<i style="background: #99d8c9"></i><span>Media</span><br>'; div.innerHTML += '<i style="background: #2ca25f"></i><span>Alta</span><br>'; return div; }; capadaplegend.addTo(map); ///// Información popUp de Sismos function popUpInfo (feature, layer) { if (feature.properties && feature.properties.mag){ layer.bindPopup("<b>Magnitud (Richter):</b> "+ feature.properties.mag+"<br><b>Fecha:</b> "+ feature.properties.time+"<br><b>Profundidad (Km):</b> "+ feature.properties.depth+"<br><b>Lugar:</b> "+ feature.properties.place); } } ///// Funciones para definir leyenda de los sismos function Colorsismos(d) { return d > 6.8 ? '#5c021d' : d > 6.2 ? '#b00909' : d > 5.6 ? '#c76708' : d > 5.0 ? '#e3c502' : d > 4.4 ? '#f5f578': '#f5f5c4'; } function stylesismo(feature) { return { weight: 1, opacity: 0.2, color: 'black', dashArray: '2.5', fillOpacity: 0.45, fillColor: Colorsismos(feature.properties.mag) }; } var minValue = 4.5; var minRadius = 3; function calcRadius(val) { return 1.25 * Math.pow(val/minValue, 6.5) * minRadius; } ///// Capa de sismos ///// Simbologías ///SISMOS var sismolegend = L.control({position: "bottomleft"}); sismolegend.onAdd = function (map) { var div = L.DomUtil.create('div', 'info legend'), grades = [4.4, 5.0, 5.6, 6.2, 6.8], labels = ["<b> Magnitud de los sismos en escala de Richter</b>"], from, to; for (var i = 0; i < grades.length; i++) { from = grades[i]; to = grades[i + 0.6]; labels.push( '<i style="background:' + Colorsismos(from + 0.6) + ' "></i> ' + from + (to ? + to: ' - ') + (to ? + to: from + 0.5)); } div.innerHTML = labels.join('<br>'); return div; }; sismolegend.addTo(map); L.TimeDimension.Layer.CDrift = L.TimeDimension.Layer.GeoJson.extend({ // CDrift data has property time in seconds, not in millis. _getFeatureTimes: function(feature) { if (!feature.properties) { return []; } if (feature.properties.hasOwnProperty('coordTimes')) { return feature.properties.coordTimes; } if (feature.properties.hasOwnProperty('times')) { return feature.properties.times; } if (feature.properties.hasOwnProperty('linestringTimestamps')) { return feature.properties.linestringTimestamps; } if (feature.properties.hasOwnProperty('time')) { return [new Date(feature.properties.time).getTime()]; } return []; }, // Do not modify features. Just return the feature if it intersects // the time interval _getFeatureBetweenDates: function(feature, minTime, maxTime) { var featureStringTimes = this._getFeatureTimes(feature); if (featureStringTimes.length == 0) { return feature; } var featureTimes = []; for (var i = 0, l = featureStringTimes.length; i < l; i++) { var time = featureStringTimes[i] if (typeof time == 'string' || time instanceof String) { time = Date.parse(time.trim()); } featureTimes.push(time); } if (featureTimes[0] > maxTime || featureTimes[l - 1] < minTime) { return null; } return feature; }, }); L.timeDimension.layer.cDrift = function(layer, options) { return new L.TimeDimension.Layer.CDrift(layer, options); }; var startDate = new Date(); startDate.setUTCHours(0, 0, 0, 0); var oReq = new XMLHttpRequest(); oReq.addEventListener("load", (function(xhr) { var response = xhr.currentTarget.response; var data = JSON.parse(response); var cdriftLayer = L.geoJson(data, { style: stylesismo, pointToLayer: function (feature, latlng) { return L.circleMarker(latlng, { radius: calcRadius(feature.properties.mag) }); } }); var cdriftTimeLayer = L.timeDimension.layer.cDrift(cdriftLayer, { updateTimeDimension: true, updateTimeDimensionMode: 'replace', addlastPoint: false, duration: 'P10D' //period: "P5D" }); cdriftTimeLayer.addTo(map); var cDriftLegend = L.control({ position: 'bottomright' }); map.timeDimension.on('timeload', function(data) { var date = new Date(map.timeDimension.getCurrentTime()); if (data.time == map.timeDimension.getCurrentTime()) { var totalTimes = map.timeDimension.getAvailableTimes().length; var position = map.timeDimension.getAvailableTimes().indexOf(data.time); } }); })); oReq.open("GET", 'https://drive.google.com/file/d/1eFLJ8dR1zKNlstI8SFY6Xc13ZlwYe0vx/view?usp=sharing'); oReq.send();
import React, { Component } from 'react'; import Link from 'next/link'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faSearch as search } from '@fortawesome/free-solid-svg-icons'; import Dropdown from './Dropdopwn'; const linkStyle = { marginRight: 22, } const DDSteez = { marginRight: 22, fontSize: "18px", fontFamily: "Arial"} const Header = () => ( <header> <ul className="top-head"> <li> <Link href="/contact"> <a style={linkStyle}>Contact Us</a> </Link> </li> <li> <Link href="https://yapicentral.chargebeeportal.com/portal/login"> <a>Billing Portal</a> </Link> </li> </ul> <div className="logo-wrapper"> <Link href="/"> <a> <img src="/static/images/Logo.png"></img> </a> </Link> </div> <ul className="head-right"> <li> {/* <Link href="/"> */} <Dropdown steez={DDSteez}/> {/* <a style={linkStyle}>Products</a> */} {/* </Link> */} </li> <li> <Link href="/pricing"> <a style={linkStyle}>Pricing</a> </Link> </li> <li> <Link href="/customerStories"> <a style={linkStyle}>Customer Stories</a> </Link> </li> <li> <Link href="/blog"> <a style={linkStyle}>Blog</a> </Link> </li> <li> <Link href="https://help.yapicentral.com"> <a style={linkStyle}>Help Center</a> </Link> </li> <li> <Link href="/search"> <FontAwesomeIcon icon={search} /> </Link> </li> </ul> <style jsx>{` header{ display: grid; grid-template-columns: 165px 1fr; grid-template-rows: 36px auto; padding: 0 30px 15px; border-bottom: 1px solid #ebebeb; } .top-head { grid-column: 2 / 3; grid-row: 1 / 2; justify-self: end } .logo-wrapper{ width: 100%; grid-column: 1 / 2; grid-row: 2 / 3; display: flex; align-items: center; justify-content: center; align-self: center; justify-self:center; } .logo-wrapper > a > img { width: 100%; height: auto; } .head-right { grid-column: 2 / 3; grid-row: 2 / 3; align-self:center; justify-self: end; } header ul { margin: 0; padding: 0; } li { list-style: none; display: inline; margin: 5px 0; color: #9e9e9e; } a { text-decoration: none; // color: blue; font-family: "Arial"; color: #9e9e9e; font-size: 15px; } .head-right a{ font-size: 18px } a:hover { opacity: 0.6; } `}</style> </header> ) export default Header
window.addEventListener("load", function(){ if(localStorage.getItem("username") == undefined || localStorage.getItem("password") == undefined || localStorage.getItem("username") == null || localStorage.getItem("password") == null) { window.location = "index.html"; } }, false)
$(function() { $(".avatar-div-div").mousemove(function(){ $(".avatar-div-div").css("display","inline"); }); $(".avatar-div-div").mouseleave(function(){ $(".avatar-div-div").css("display","none"); }); $("#avatar").mousemove(function(){ $(".avatar-div-div").css("display","inline"); }); $("#avatar").mouseleave(function(){ $(".avatar-div-div").css("display","none"); }); });
/* This file is part of web3.js. web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see <http://www.gnu.org/licenses/>. */ /** * @file utils.js * @author Marek Kotewicz <marek@ethdev.com> * @date 2015 */ /** * Utils * * @module utils */ /** * Utility functions * * @class [utils] utils * @constructor */ var BigNumber = require('bignumber.js'); var sha3 = require('./sha3.js'); var utf8 = require('utf8'); var unitMap = { 'noether': '0', 'wei': '1', 'kwei': '1000', 'Kwei': '1000', 'babbage': '1000', 'femtoether': '1000', 'mwei': '1000000', 'Mwei': '1000000', 'lovelace': '1000000', 'picoether': '1000000', 'gwei': '1000000000', 'Gwei': '1000000000', 'shannon': '1000000000', 'nanoether': '1000000000', 'nano': '1000000000', 'szabo': '1000000000000', 'microether': '1000000000000', 'micro': '1000000000000', 'finney': '1000000000000000', 'milliether': '1000000000000000', 'milli': '1000000000000000', 'ether': '1000000000000000000', 'kether': '1000000000000000000000', 'grand': '1000000000000000000000', 'mether': '1000000000000000000000000', 'gether': '1000000000000000000000000000', 'tether': '1000000000000000000000000000000' }; /** * Should be called to pad string to expected length * * @method padLeft * @param {String} string to be padded * @param {Number} characters that result string should have * @param {String} sign, by default 0 * @returns {String} right aligned string */ var padLeft = function (string, chars, sign) { return new Array(chars - string.length + 1).join(sign ? sign : "0") + string; }; /** * Should be called to pad string to expected length * * @method padRight * @param {String} string to be padded * @param {Number} characters that result string should have * @param {String} sign, by default 0 * @returns {String} right aligned string */ var padRight = function (string, chars, sign) { return string + (new Array(chars - string.length + 1).join(sign ? sign : "0")); }; /** * Should be called to get utf8 from it's hex representation * * @method toUtf8 * @param {String} string in hex * @returns {String} ascii string representation of hex value */ var toUtf8 = function(hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); if (code === 0) break; str += String.fromCharCode(code); } return utf8.decode(str); }; /** * Should be called to get ascii from it's hex representation * * @method toAscii * @param {String} string in hex * @returns {String} ascii string representation of hex value */ var toAscii = function(hex) { // Find termination var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { i = 2; } for (; i < l; i+=2) { var code = parseInt(hex.substr(i, 2), 16); str += String.fromCharCode(code); } return str; }; /** * Should be called to get hex representation (prefixed by 0x) of utf8 string * * @method fromUtf8 * @param {String} string * @param {Boolean} allowZero to convert code point zero to 00 instead of end of string * @returns {String} hex representation of input string */ var fromUtf8 = function(str, allowZero) { str = utf8.encode(str); var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); if (code === 0) { if (allowZero) { hex += '00'; } else { break; } } else { var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } } return "0x" + hex; }; /** * Should be called to get hex representation (prefixed by 0x) of ascii string * * @method fromAscii * @param {String} string * @param {Number} optional padding * @returns {String} hex representation of input string */ var fromAscii = function(str, num) { var hex = ""; for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } return "0x" + hex.padEnd(num,'0'); }; /** * Should be used to create full function/event name from json abi * * @method transformToFullName * @param {Object} json-abi * @return {String} full fnction/event name */ var transformToFullName = function (json) { if (json.name.indexOf('(') !== -1) { return json.name; } var typeName = json.inputs.map(function(i){return i.type; }).join(); return json.name + '(' + typeName + ')'; }; /** * Should be called to get display name of contract function * * @method extractDisplayName * @param {String} name of function/event * @returns {String} display name for function/event eg. multiply(uint256) -> multiply */ var extractDisplayName = function (name) { var stBracket = name.indexOf('('); var endBracket = name.indexOf(')'); return (stBracket !== -1 && endBracket !== -1) ? name.substr(0, stBracket) : name; }; /** * Should be called to get type name of contract function * * @method extractTypeName * @param {String} name of function/event * @returns {String} type name for function/event eg. multiply(uint256) -> uint256 */ var extractTypeName = function (name) { var stBracket = name.indexOf('('); var endBracket = name.indexOf(')'); return (stBracket !== -1 && endBracket !== -1) ? name.substr(stBracket + 1, endBracket - stBracket - 1).replace(' ', '') : ""; }; /** * Converts value to it's decimal representation in string * * @method toDecimal * @param {String|Number|BigNumber} * @return {String} */ var toDecimal = function (value) { return toBigNumber(value).toNumber(); }; /** * Converts value to it's hex representation * * @method fromDecimal * @param {String|Number|BigNumber} * @return {String} */ var fromDecimal = function (value) { var number = toBigNumber(value); var result = number.toString(16); return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result; }; /** * Auto converts any given value into it's hex representation. * * And even stringifys objects before. * * @method toHex * @param {String|Number|BigNumber|Object} * @return {String} */ var toHex = function (val) { /*jshint maxcomplexity: 8 */ if (isBoolean(val)) return fromDecimal(+val); if (isBigNumber(val)) return fromDecimal(val); if (typeof val === 'object') return fromUtf8(JSON.stringify(val)); // if its a negative number, pass it through fromDecimal if (isString(val)) { if (val.indexOf('-0x') === 0) return fromDecimal(val); else if(val.indexOf('0x') === 0) return val; else if (!isFinite(val)) return fromUtf8(val,1); } return fromDecimal(val); }; /** * Returns value of unit in Wei * * @method getValueOfUnit * @param {String} unit the unit to convert to, default ether * @returns {BigNumber} value of the unit (in Wei) * @throws error if the unit is not correct:w */ var getValueOfUnit = function (unit) { unit = unit ? unit.toLowerCase() : 'ether'; var unitValue = unitMap[unit]; if (unitValue === undefined) { throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2)); } return new BigNumber(unitValue, 10); }; /** * Takes a number of wei and converts it to any other ether unit. * * Possible units are: * SI Short SI Full Effigy Other * - kwei femtoether babbage * - mwei picoether lovelace * - gwei nanoether shannon nano * - -- microether szabo micro * - -- milliether finney milli * - ether -- -- * - kether -- grand * - mether * - gether * - tether * * @method fromWei * @param {Number|String} number can be a number, number string or a HEX of a decimal * @param {String} unit the unit to convert to, default ether * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number */ var fromWei = function(number, unit) { var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }; /** * Takes a number of a unit and converts it to wei. * * Possible units are: * SI Short SI Full Effigy Other * - kwei femtoether babbage * - mwei picoether lovelace * - gwei nanoether shannon nano * - -- microether szabo micro * - -- milliether finney milli * - ether -- -- * - kether -- grand * - mether * - gether * - tether * * @method toWei * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal * @param {String} unit the unit to convert from, default ether * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number */ var toWei = function(number, unit) { var returnValue = toBigNumber(number).times(getValueOfUnit(unit)); return isBigNumber(number) ? returnValue : returnValue.toString(10); }; /** * Takes an input and transforms it into an bignumber * * @method toBigNumber * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber * @return {BigNumber} BigNumber */ var toBigNumber = function(number) { /*jshint maxcomplexity:5 */ number = number || 0; if (isBigNumber(number)) return number; if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) { return new BigNumber(number.replace('0x',''), 16); } return new BigNumber(number.toString(10), 10); }; /** * Takes and input transforms it into bignumber and if it is negative value, into two's complement * * @method toTwosComplement * @param {Number|String|BigNumber} * @return {BigNumber} */ var toTwosComplement = function (number) { var bigNumber = toBigNumber(number).round(); if (bigNumber.lessThan(0)) { return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); } return bigNumber; }; /** * Checks if the given string is strictly an address * * @method isStrictAddress * @param {String} address the given HEX adress * @return {Boolean} */ var isStrictAddress = function (address) { return /^0x[0-9a-f]{40}$/i.test(address); }; /** * Checks if the given string is an address * * @method isAddress * @param {String} address the given HEX adress * @return {Boolean} */ var isAddress = function (address) { if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { // check if it has the basic requirements of an address return false; } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { // If it's all small caps or all all caps, return true return true; } else { // Otherwise check each case return isChecksumAddress(address); } }; /** * Checks if the given string is a checksummed address * * @method isChecksumAddress * @param {String} address the given HEX adress * @return {Boolean} */ var isChecksumAddress = function (address) { // Check each case address = address.replace('0x',''); var addressHash = sha3(address.toLowerCase()); for (var i = 0; i < 40; i++ ) { // the nth letter should be uppercase if the nth digit of casemap is 1 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { return false; } } return true; }; /** * Makes a checksum address * * @method toChecksumAddress * @param {String} address the given HEX adress * @return {String} */ var toChecksumAddress = function (address) { if (typeof address === 'undefined') return ''; address = address.toLowerCase().replace('0x',''); var addressHash = sha3(address); var checksumAddress = '0x'; for (var i = 0; i < address.length; i++ ) { // If ith character is 9 to f then make it uppercase if (parseInt(addressHash[i], 16) > 7) { checksumAddress += address[i].toUpperCase(); } else { checksumAddress += address[i]; } } return checksumAddress; }; /** * Transforms given string to valid 20 bytes-length addres with 0x prefix * * @method toAddress * @param {String} address * @return {String} formatted address */ var toAddress = function (address) { if (isStrictAddress(address)) { return address; } if (/^[0-9a-f]{40}$/.test(address)) { return '0x' + address; } return '0x' + padLeft(toHex(address).substr(2), 40); }; /** * Returns true if object is BigNumber, otherwise false * * @method isBigNumber * @param {Object} * @return {Boolean} */ var isBigNumber = function (object) { return object instanceof BigNumber || (object && object.constructor && object.constructor.name === 'BigNumber'); }; /** * Returns true if object is string, otherwise false * * @method isString * @param {Object} * @return {Boolean} */ var isString = function (object) { return typeof object === 'string' || (object && object.constructor && object.constructor.name === 'String'); }; /** * Returns true if object is function, otherwise false * * @method isFunction * @param {Object} * @return {Boolean} */ var isFunction = function (object) { return typeof object === 'function'; }; /** * Returns true if object is Objet, otherwise false * * @method isObject * @param {Object} * @return {Boolean} */ var isObject = function (object) { return object !== null && !(Array.isArray(object)) && typeof object === 'object'; }; /** * Returns true if object is boolean, otherwise false * * @method isBoolean * @param {Object} * @return {Boolean} */ var isBoolean = function (object) { return typeof object === 'boolean'; }; /** * Returns true if object is array, otherwise false * * @method isArray * @param {Object} * @return {Boolean} */ var isArray = function (object) { return Array.isArray(object); }; /** * Returns true if given string is valid json object * * @method isJson * @param {String} * @return {Boolean} */ var isJson = function (str) { try { return !!JSON.parse(str); } catch (e) { return false; } }; /** * Returns true if given string is a valid Ethereum block header bloom. * * @method isBloom * @param {String} hex encoded bloom filter * @return {Boolean} */ var isBloom = function (bloom) { if (!/^(0x)?[0-9a-f]{512}$/i.test(bloom)) { return false; } else if (/^(0x)?[0-9a-f]{512}$/.test(bloom) || /^(0x)?[0-9A-F]{512}$/.test(bloom)) { return true; } return false; }; /** * Returns true if given string is a valid log topic. * * @method isTopic * @param {String} hex encoded topic * @return {Boolean} */ var isTopic = function (topic) { if (!/^(0x)?[0-9a-f]{64}$/i.test(topic)) { return false; } else if (/^(0x)?[0-9a-f]{64}$/.test(topic) || /^(0x)?[0-9A-F]{64}$/.test(topic)) { return true; } return false; }; module.exports = { padLeft: padLeft, padRight: padRight, toHex: toHex, toDecimal: toDecimal, fromDecimal: fromDecimal, toUtf8: toUtf8, toAscii: toAscii, fromUtf8: fromUtf8, fromAscii: fromAscii, transformToFullName: transformToFullName, extractDisplayName: extractDisplayName, extractTypeName: extractTypeName, toWei: toWei, fromWei: fromWei, toBigNumber: toBigNumber, toTwosComplement: toTwosComplement, toAddress: toAddress, isBigNumber: isBigNumber, isStrictAddress: isStrictAddress, isAddress: isAddress, isChecksumAddress: isChecksumAddress, toChecksumAddress: toChecksumAddress, isFunction: isFunction, isString: isString, isObject: isObject, isBoolean: isBoolean, isArray: isArray, isJson: isJson, isBloom: isBloom, isTopic: isTopic, };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var my_first_library_1 = require("my-first-library"); var result = my_first_library_1.CalculatorService.add(3, 4, 5); console.log(result);
/* * @lc app=leetcode.cn id=752 lang=javascript * * [752] 打开转盘锁 */ // @lc code=start /** * @param {string[]} deadends * @param {string} target * @return {number} */ var openLock = function (deadends, target) { const increaseOne = (str, index) => { let arr = str.split(""); if (arr[index] === "9") { arr[index] = "0"; } else { arr[index]++; } return arr.join(""); }; const decreaseOne = (str, index) => { let arr = str.split(""); if (arr[index] === "0") { arr[index] = "9"; } else { arr[index]--; } return arr.join(""); }; let queue = ["0000"], visited = new Set(), step = 0; visited.add("0000"); while (queue.length) { let len = queue.length; for (let i = 0; i < len; i++) { const node = queue.shift(); if (deadends.includes(node)) continue; if (node === target) return step; for (let index = 0; index < 4; index++) { const increaseStr = increaseOne(node, index); if (!visited.has(increaseStr)) { queue.push(increaseStr); visited.add(increaseStr); } const decreasedStr = decreaseOne(node, index); if (!visited.has(decreasedStr)) { queue.push(decreasedStr); visited.add(decreasedStr); } } } step++; } return -1; }; // @lc code=end
export default function setPost(post, posts, setPostContext){ var arr_posts = posts; for(var u of arr_posts){ if(u === post){ u = post; setPostContext(arr_posts); return true; } } return false; }
'use strict'; angular.module('myApp.view1.editUser', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1.editUser', { templateUrl: 'edit-user/edit.html', controller: 'EditUserCtrl' }); }]) .controller('EditUserCtrl', ['$scope','$http','$location','UserService',function($scope,$http,$location,UserService) { // $scope.user=UserService.one($routeParams.name); // $scope.action= $scope.user? '更新用户':'新增用户'; $scope.onSubmit=function(){ // console.log($scope.user); $http.post('http://localhost/boot/edit-user.php',$scope.user) .then(function(res){ // console.log(res); var result=res.data; if(result.success){ UserService.setUsers(result.data); console.log(UserService.getUsers()); // console.log($scope.users); $location.path('/view1'); }else{ alert('保存失败,请重试') } }) } }]);
$('.box').owlCarousel({ margin:10, loop:true, autoplay:true, autoplayTimeout:2000, // 2sc autoplayHoverPause:true, responsive:{ 0:{ items:1, nav:false }, 600:{ items:2, nav:false }, 1000:{ items:3, nav:false } } }); // sign-up form let signUp = document.querySelector(".sign-up"), signBtn = document.querySelector("#btn-sign"), closeBtn = document.querySelector("#close"), inputs = document.querySelectorAll(".form-control"); signBtn.addEventListener("click",()=>{ if(signUp.classList.contains("sign-up-active")) { signUp.classList.remove("sign-up-active"); }else { signUp.classList.add("sign-up-active"); } }) closeBtn.addEventListener("click",()=>{ signUp.classList.remove("sign-up-active"); }) for(var i = 0; i<inputs.length;i++) { inputs[i].addEventListener("blur",(e)=>{ if(e.target.value.length<4) { e.target.nextElementSibling.style.display="block"; }else { e.target.nextElementSibling.style.display="none"; } }) } let login = document.querySelector(".log"), logBtn = document.querySelector("#login"), closeBtn1 = document.querySelector(".log #close"); logBtn.addEventListener("click",()=>{ if(login.classList.contains("log-active")) { login.classList.remove("log-active"); }else { login.classList.add("log-active"); } }); closeBtn1.addEventListener("click",()=>{ login.classList.remove("log-active"); }) // log setTimeout(function(){ login.classList.add("log-active"); }, 10000) // popup-video let popupVideo = document.querySelector(".popup-video"), icon = document.querySelector(".icon"), closeBtn2 = document.querySelector(".popup-video .close"); icon.addEventListener("click",()=>{ if(popupVideo.classList.contains("popup-video-active")) { popupVideo.classList.remove("popup-video-active"); }else { popupVideo.classList.add("popup-video-active"); } }); closeBtn2.addEventListener("click",()=>{ popupVideo.classList.remove("popup-video-active"); })
import React from 'react'; import "./App.css"; import Chip from './assets/chip.png'; import Amex from './assets/amex.png'; const Card = () => { return (<> <div className="full"> <div className="card"> <div className="logo-row w100"> <div><img src={Chip} className="w70 h55"></img></div> <div><img src={Amex} className="w70 h55"></img></div> </div> <div className="num-row w100 info"> <div>####</div><div>####</div><div>####</div><div>####</div> </div> <div className="info-row w100"> <div> <div className="label"> Card Holder </div> <div className="info"> VASHISHT GUPTA </div> </div> <div> <div className="label"> Expires </div> <div className="info"> MM/YY </div> </div> </div> </div> <div className="form"> </div> </div> </>) } export default Card;
import User from '../model/User.js'; import passport from 'passport'; import { Strategy } from 'passport-http-bearer'; import bcrypt from 'bcrypt'; class UsersManager { constructor() { } findOneUser(user, callback) { User.findOne({ username: user.username }, (err,user) => { callback(err,user) }) } findAllUsers(callback) { User.find({}, (err,users) => { callback(err,users); }); } addUser(request,callback) { const saltRounds = 10; const plainPassword = request.password; bcrypt.hash(plainPassword, saltRounds, (err,hash) => { const newUser = new User({...request}); newUser.password = hash; newUser.save((err)=>{ callback(err); }); }) } deleteUser(idToDelete,callback) { User.deleteOne({_id:idToDelete}, (err) => { callback(err); }); } modfifyUser(request,idToUpdate,callback) { if(request.password !== null) { const saltRounds = 10; const plainPassword = request.password; bcrypt.hash(plainPassword, saltRounds, (err,hash) => { User.updateOne({ _id : idToUpdate}, {...request,"password":hash},(err) => { callback(err); }); }) } else { User.updateOne({ _id : idToUpdate}, {...request},(err) => { callback(err); }); } } } export default new UsersManager();
var app = angular.module("app", []).config(function($routeProvider) { $routeProvider.when('/login', { templateUrl: 'templates/login.html', controller: 'LoginController' }); $routeProvider.when('/home', { templateUrl: 'templates/home.html', controller: 'HomeController' }); $routeProvider.otherwise({ redirectTo: '/login' }); }); app.config(function($httpProvider) { var logsOutUserOn401 = function($location, $q, SessionService, FlashService) { var success= function(response) { return response; }; var error= function(response) { if(response.status === 401) { SessionService.unset('authenticated'); FlashService.show(response.data.flash); $location.path('/login'); return $q.reject(response); }else { return $q.reject(response); } }; return function(promise) { return.promise.then(success, error) }; }); app.run(function($rootScope,$location, AuthenticationService,FlashService) { var routesThatRequireAuth = ['/home']; $rootScope.$on('$routeChangeStart', function(event, next, current) { if(_(routesThatRequireAuth).contains($location.path())) && !AuthenticationService.isLoggedIn()) { $location.path('/login'); FlashService.show("Please Log in To Continue"); } }); }); app.factory("FlashService",function(){ return { show: function(message) { $rootScope.flash = message; }, clear: function() { $rootScope.flash = ""; } }; }); app.factory(("SessionService", function() { return { get: function(key) { return sessionStorage.getItem(key); }, set: function(key, value) { return sessionStorage.setItem(key, value); }, unset: function(key) { return sessionStorage.removeItem(key); } }; }); app.factory("AuthenticationService", function($http, $location, SessionService, FlashService) { var cacheSession = function() { SessionService.set('authenticated',true); }; var uncacheSession = function() { SessionService.unset('authenticated'); }; var loginError = function() { FlashService.show(response.flash); }; login: function(credentials) { var login = $http.post("/auth/signin", credentials).success(function() { login.success(cacheSession); login.success(FlashService.clear; login.error(loginError); return login; }); }, logout: function() { var logout = $http.get("/auth/logout").success(function(){ logout.success(uncacheSession); return logout; }); }, isLoggedIn: function() { return SessionService.get('authenticated'); } }; }); app.controller('LoginController',function($scope, AuthenticationService) { $scope.crendentials = { username: "", password: ""}; $scope.login = function() { AuthenticationService.login($scope.credentials); }; }); app.controller('HomeController',function($scope, $locationb) { $scope.logout = function() { AuthenticationService.logout().success(function(){ $location.path('/login'); }); } });
import React from 'react'; import TableRow from '@material-ui/core/TableRow'; //각 사용자 정보들을 한 행씩으로 담을 수 있다. import TableCell from '@material-ui/core/TableCell'; //테이블에 들어가는 각 원소들을 TableCell로 사용함 import CustomerDelete from './CustomerDelete'; class Customer extends React.Component { render() { return ( <TableRow> <TableCell>{this.props.id}</TableCell> <TableCell><img src = {this.props.image} alt = "profile" style={{width:64,height:64}}/></TableCell> <TableCell>{this.props.name}</TableCell> <TableCell>{this.props.birthday}</TableCell> <TableCell>{this.props.gender}</TableCell> <TableCell>{this.props.job}</TableCell> <TableCell><CustomerDelete stateRefresh={this.props.stateRefresh} id={this.props.id} /></TableCell> </TableRow> ) } } export default Customer;
const inquirer = require('inquirer'); module.exports = { // The listChoice func will prompt the user with a dynamically created list of answers and return an object listChoice: async (array, param1, param2) => { let choices; // Determine if param2 is present if(param2) { // If so, map the entry with 2 parameters choices = array.map(entry => `${entry.id}: ${entry[param1]} ${entry[param2]}`); } else { // If not, map with only 1 parameter choices = array.map(entry => `${entry.id}: ${entry[param1]}`) } // Prompt the user to choose one of the mapped values const {answer} = await inquirer.prompt([ { type: 'list', name: 'answer', message: 'Which one?', choices: choices } ]); // Extract the id from the answer const id = answer.split(':')[0]; // Find the object with the matching id in the array let objectToReturn = array.find(entry => entry.id === Number(id)); // Return the id number and text in an obj return objectToReturn; } }
import React, { useState } from 'react'; import propTypes from 'prop-types'; import UserContext from './UseContext'; const Provider = ({ children }) => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [name, setName] = useState(''); const [loginRequest, setLoginRequest] = useState(''); const [totalPrice, setTotalPrice] = useState('0.00'); const [checkoutProducts, setCheckoutProducts] = useState([]); const contextValue = { name, setName, email, setEmail, password, setPassword, loginRequest, setLoginRequest, totalPrice, setTotalPrice, checkoutProducts, setCheckoutProducts, }; return ( <UserContext.Provider value={ contextValue }> { children } </UserContext.Provider> ); }; Provider.propTypes = { children: propTypes.node.isRequired, }; export default Provider;
var Stack = function(){ top = null; } Stack.makeNode = function(val) { return {data:val, next:null} }; Stack.prototype.pop = function(){ if (this.top == null) { //alert("STACK is EMPTY"); return null; } // console.log("POP ", this.top.data); var n = this.top; this.top = n.next; return n.data; }; Stack.prototype.push = function(val){ var newNode = Stack.makeNode(val); // console.log("push ", newNode.data); newNode.next = this.top; this.top = newNode; // console.log("top >>> ", this.top.data); }; Stack.prototype.traverse = function(){ var t = this.top; var len = 0 while(t != null) { console.log("TRAVERSE>>> ",t.data); t = t.next; len = len + 1; } return len; }; var validParens = function(str){ var len = str.length; var c = ""; var n = ""; var s = new Stack(); var valid = true; var closeParens = [')', ']', '}']; var openParens = ['(', '[', '{']; var parensMatches = { ')': '(', ']': '[', '}': '{'} for (i=0; i< len; i++) { c = str.charAt(i); if (closeParens.includes(c)) { n = s.pop(); if ( n == null || n != parensMatches[c]) { valid = false; break; } //alert("Popping >>>>> " + n + "; comparing to "+ c); } if (openParens.includes(c)) { //alert("Pushing >>>>> "+ c); s.push(c); } } if (s.pop() != null ) { valid = false } return valid; } alert('(ab] is ' + validParens('(ab]')); alert('([[{{ab] is ' + validParens('([[{{ab]')); alert('ab]}}p) is ' + validParens('ab]}}p)')); alert('{{abcd}} is ' + validParens('{{abcd}}')); // s = new Stack(); // s.pop(); // s.push(10); // s.push(12); // // s.traverse(); // var dat = s.pop(); // s.traverse();
function clamp(x,a,b){return b===undefined?x>a?a:x<-a?-a:x:x>b?b:x<a?a:x} var tau = 6.283185307179586 if (settings.DEBUG) { window.onerror = function (error, url, line) { document.body.innerHTML = "<p>Error in: "+url+"<p>line "+line+"<pre>"+error+"</pre>" } } var canvas = document.getElementById("canvas") canvas.width = settings.w canvas.height = settings.h var context = canvas.getContext("2d") UFX.draw.setcontext(context) var sx, sy UFX.maximize.onadjust = function (canvas, csx, csy) { sx = csx sy = csy background.reset() } function fH(n) { return Math.ceil(sy / 16 * n) } function f(n) { return Math.ceil(sy / settings.h * n) } UFX.maximize.fill(canvas, "aspect") UFX.scene.init({ ups: 60, maxupf: 12 }) UFX.key.init() UFX.key.remaparrows(true) UFX.key.remap({ enter: "space" }) UFX.key.watchlist = "up down left right space".split(" ") UFX.resource.loadwebfonts("Viga", "Berkshire Swash") UFX.resource.load({ die: "die.ogg", dink: "dink.ogg", hurt: "hurt.ogg", jump: "jump.ogg", portal: "portal.ogg", splash: "splash.ogg", knight: "knight.ogg", yellow: "yellow.ogg", }) function playsound(soundname) { UFX.resource.sounds[soundname].play() } var music = null function playmusic(musicname) { if (musicname == music) return if (music) { UFX.resource.sounds[music].pause() } var m = UFX.resource.sounds[musicname] if (m) { m.volume = 0.5 m.loop = true m.currentTime = 0 m.play() } music = musicname } UFX.resource.onloading = function (f) { UFX.scenes.load.f = f } UFX.resource.onload = function () { UFX.scenes.load.loaded = true } UFX.scenes.load = { start: function (loaded) { this.f = 0 this.loaded = loaded }, think: function (dt) { var kstate = UFX.key.state() if (this.loaded && kstate.down.space) { UFX.scene.swap("play") } }, draw: function () { UFX.draw("fs #A00 f0") background.drawtitle() if (this.loaded) { background.drawsubtitle("Space: begin") } else { background.drawsubtitle("Loading... (" + Math.round(100 * this.f) + "%)") } }, } UFX.scene.push("load") UFX.scenes.youwin = { draw: function () { UFX.draw("fs #A00 f0") background.drawtitle() background.drawsubtitle("You win! Congratulations.") }, } UFX.scene.push("load") UFX.scenes.play = { start: function () { resetstate() background.current = "intro" playmusic("knight") this.ground = new Platform(-1, 1, settings.w + 2) this.blocks = [ this.ground, new Platform(6, 3, 5), new Platform(14, 5, 4), new Platform(19, 7, 2), new Platform(18, 10, 2), new Platform(13, 12, 4), new Platform(4, 13, 5), new Platform(3, 8, 3), ] this.you = new You(12, 10) this.you.hp = state.maxhp this.mals = [] this.boss = null this.bullets = [] // hurts mals this.hazards = [] // hurts player this.portals = [ new Portal(this.ground, 17, "cain", "polly"), new Portal(this.ground, 16, "carmen", "dana"), new Portal(this.blocks[1], undefined, "lex", "sally"), new Portal(this.blocks[1], undefined, "dana", "pilar"), new Portal(this.blocks[2], undefined, "meg", "eli"), new Portal(this.blocks[4], undefined, "polly", "pilar"), new Portal(this.blocks[5], undefined, "lex", "cain"), new Portal(this.blocks[5], undefined, "dana", "roger"), new Portal(this.blocks[6], undefined, "carmen", "tanya"), new Portal(this.blocks[7], undefined, "polly", "carmen"), new Portal(this.blocks[7], undefined, "pilar", "meg"), ] var starps = "m 0.000 2.000 l 0.588 0.809 l 1.902 0.618 l 0.951 -0.309 l 1.176 -1.618 l 0.000 -1.000 l -1.176 -1.618 l -0.951 -0.309 l -1.902 0.618 l -0.588 0.809" var windowpath = [ "b m -1 -1 c -1 3 1 3 1 -1 fs #AAC f", "b m 0 -1 l 0 2 ss #963 lw 0.2 s", "b m -0.8 0 l 0.8 0 ss #963 lw 0.2 s", "b m -1 -1 c -1 3 1 3 1 -1 ss #852 lw 0.4 s", "b m -1.3 -1 l 1.3 -1 ss #963 lw 0.5 s", ] var sunpath = "( m 0.000 1.400 l 0.410 1.128 l 0.900 1.072 l 1.039 0.600 l 1.379 0.243 l 1.182 -0.208 l 1.212 -0.700 l 0.771 -0.919 l 0.479 -1.316 l 0.000 -1.200 l -0.479 -1.316 l -0.771 -0.919 l -1.212 -0.700 l -1.182 -0.208 l -1.379 0.243 l -1.039 0.600 l -0.900 1.072 l -0.410 1.128 ) fs yellow ss black lw 0.05 f s b o 0 0 1.1 f s" var moonpath = ["r 0.6 ( a 0.5 0 1", tau/6, tau*5/6, "aa 1.5 0 1", tau*4/6, tau*2/6, ") ss black lw 0.1 s fs white f"] var cloudpath = ["b o -0.8 0 0.9 o 0.8 0.1 0.9 o -0.1 0.6 0.8 o -0.2 -0.5 0.8 ss black lw 0.1 s fs white b o -0.8 0 0.9 f b o 0.8 0.1 0.9 f b o -0.1 0.6 0.8 f b o -0.2 -0.5 0.8 f"] var planetpath = [ "[ r -0.2 b o 0 0 1 fs purple f", "[ z 2 0.5 lw 0.3 ss orange b o 0 0 1 s ]", "tr -2 0 4 4 clip b o 0 0 1 fs purple f ]", ] var planetpath2 = [ "[ r 0.6 b o 0 0 1 fs green f", "[ z 2 0.5 lw 0.3 ss cyan b o 0 0 1 s ]", "tr -2 0 4 4 clip b o 0 0 1 fs green f ]", ] this.decorations = [ new DanglingDecoration(20, 13, sunpath, ["lex", "pilar"]), new DanglingDecoration(16, 9, moonpath, ["cain", "carmen"]), new DanglingDecoration(2, 12, ["r 0.6 z 0.3 0.3 (", starps, ") ss black lw 0.1 s fs #FFA f"], ["cain", "carmen"]), new DanglingDecoration(7, 10, ["r 0.6 z 0.3 0.3 (", starps, ") ss black lw 0.1 s fs #FAA f"], ["cain", "carmen"]), new DanglingDecoration(18, 13, ["r 0.6 z 0.3 0.3 (", starps, ") ss black lw 0.1 s fs #AAF f"], ["cain", "carmen"]), new DanglingDecoration(6, 10, planetpath, ["dana"]), new DanglingDecoration(15, 7, planetpath2, ["dana"]), new DanglingDecoration(4, 4, ["r 0.6 z 0.3 0.3 (", starps, ") ss black lw 0.1 s fs #FAA f"], ["dana"]), new DanglingDecoration(10, 5, ["r 0.6 z 0.3 0.3 (", starps, ") ss black lw 0.1 s fs #AAF f"], ["dana"]), new DanglingDecoration(11, 11, ["r 0.6 z 0.3 0.3 (", starps, ") ss black lw 0.1 s fs #FAF f"], ["cain", "carmen", "dana"]), new DanglingDecoration(22, 12, ["r 0.6 z 0.3 0.3 (", starps, ") ss black lw 0.1 s fs #AFF f"], ["cain", "carmen", "dana"]), new DanglingDecoration(21, 12, cloudpath, ["polly", "meg"]), new DanglingDecoration(16, 8, cloudpath, ["polly", "meg"]), new DanglingDecoration(4, 11, cloudpath, ["polly", "meg"]), new DanglingDecoration(9, 10, cloudpath, ["polly", "meg", "lex", "pilar"]), new DanglingDecoration(8, 8, windowpath, ["sally", "tanya", "roger", "eli"]), new DanglingDecoration(16, 8, windowpath, ["sally", "tanya", "roger", "eli"]), // new DanglingDecoration(18, settings.h - 6, "b o -1 0 1 o 1 0 1 o 0 0.5 1 ss black lw 0.1 s fs white f", ["hub"]), ] this.effects = [] }, thinkargs: function (dt) { return [dt, UFX.key.state()] }, think: function (dt, kstate) { if (background.scenes[state.place] == "day") { if (UFX.random.flip(0.5 * dt)) { this.mals.push(new Waver()) } } else if (background.scenes[state.place] == "rain") { if (UFX.random.flip(0.2 * dt)) { this.mals.push(new BallLightning()) } } else if (background.scenes[state.place] == "night") { if (UFX.random.flip(1 * dt)) { this.hazards.push(new Hopper()) } } else if (background.scenes[state.place] == "space") { if (UFX.random.flip(2 * dt)) { this.hazards.push(new Meteor()) } } this.you.control(kstate, dt) if (kstate.down.down && this.you.parent) { for (var j = 0 ; j < this.portals.length ; ++j) { var portal = this.portals[j] if (portal.goesto() && portal.nearby(this.you)) { state.place = portal.goesto() playsound("portal") if (bosstypes[state.place] && !state.donebosses[state.place] && !this.boss) { this.mals.push(new Talisman(state.place)) } if (state.bombs[state.place]) { this.mals.push(new Bomb(state.place)) } } } } function think(obj) { obj.think(dt) } this.blocks.forEach(think) this.mals.forEach(think) if (this.boss && this.boss.hp == 1) this.boss.think(dt) this.bullets.forEach(think) this.hazards.forEach(think) this.portals.forEach(think) this.decorations.forEach(think) this.effects.forEach(think) think(this.you) var blocks = this.blocks, bullets = this.bullets this.you.constrain(blocks) this.mals.forEach(function (mal) { mal.constrain(blocks) }) this.mals.forEach(function (mal) { mal.collide(bullets) }) this.you.collide(this.hazards) this.bullets.forEach(function (bullet) { bullet.constrain(blocks) }) this.hazards.forEach(function (bullet) { bullet.constrain(blocks) }) function unfaded(obj) { return !obj.faded } this.mals = this.mals.filter(unfaded) this.bullets = this.bullets.filter(unfaded) this.effects = this.effects.filter(unfaded) this.hazards = this.hazards.filter(unfaded) background.think(dt) if (this.you.faded || (this.boss && this.boss.faded)) { state.place = "intro" background.think(0) if (background.f <= 0) { UFX.scene.swap(this.you.faded ? "load" : "youwin", true) playmusic() } } }, draw: function () { background.draw() var z = sy / settings.h UFX.draw("[ t", 0, sy, "z", z, -z) function draw(obj) { context.save() obj.draw() context.restore() } this.decorations.forEach(draw) UFX.draw("[ fs black alpha 0.25 fr 0 0", settings.w, settings.h, "]") this.blocks.forEach(draw) this.portals.forEach(draw) this.mals.forEach(draw) if (!this.you.faded) draw(this.you) this.bullets.forEach(draw) this.hazards.forEach(draw) this.effects.forEach(draw) UFX.draw("]") for (var j = 0 ; j < state.maxhp ; ++j) { UFX.draw("ss white fs", j < this.you.hp ? "red" : "black", "lw", f(0.04), "fsr", f(0.55 * j + 0.1), f(0.1), f(0.35), f(0.8)) } if (this.boss) { for (var j = 0 ; j < 3 ; ++j) { UFX.draw("ss white fs", j < this.boss.hp ? "blue" : "black", "lw", f(0.04), "fsr", f(0.55 * j + 0.1), f(1.1), f(0.35), f(0.8)) } } else { UFX.draw("font " + fH(0.5) + "px~'Viga' textalign right textbaseline bottom fs white") ;["f11: fullscreen", "down: scene change", "up: double jump", "space/enter: shoot"].forEach(function (text, j) { context.fillText(text, sx - fH(0.2), sy - fH(0.2 + 0.6 * j)) }) } if (settings.EASY && state.place != "intro") { UFX.draw("[ font " + fH(1) + "px~'Viga' textalign center textbaseline bottom fs yellow sh black", fH(0.05), fH(0.05), 0, "t", sx/2, sy * 0.98, "ft0", state.place, "]") } background.drawcurtain() if (settings.DEBUG) { UFX.draw("[ font " + fH(0.5) + "px~'Viga' fs white textalign left textbaseline bottom") context.fillText(UFX.ticker.getrates(), fH(0.2), sy - fH(0.2)) context.fillText("Location: " + state.place, fH(0.2), sy - fH(0.8)) UFX.draw("]") } }, } function addeffect(effect) { UFX.scenes.play.effects.push(effect) }
// main.js // Jquery var $ = require('jquery'); // Boostrap 4 require('bootstrap'); // Iconos fontawesome //import fontawesome from '@fortawesome/fontawesome'; //import { faPlus, faEye, faEdit, faTrash, faList, faSave, faHome, faAddressBook, faUser, faSignOutAlt } from '@fortawesome/fontawesome-free-solid'; //fontawesome.library.add(faPlus, faEye, faEdit, faTrash, faList, faSave, faHome, faAddressBook, faUser, faSignOutAlt ); // Imágenes //require('../img/x-office-address-book.png'); require('../img/agenda2.png'); //require('../img/user-id.png'); // Tooltips $(document).ready(function() { $('[data-toggle="popover"]').popover(); });
import React from 'react'; import {BrowserRouter, Route, Switch, withRouter, Redirect} from 'react-router-dom'; import SideMenu from '../components/sideMenu'; import View from '../components/view'; import Form from '../components/form'; import Dashboard from '../components/dashboard'; import Faucet from '../components/faucet'; import Wallet from '../components/wallet'; import Modal from '../components/result'; const renderHeader = (path) => { switch(path){ case '/offers': return 'Latest Loan Offers'; case '/requests': return 'Latest Loan Requests'; case '/create_offer': return 'New Loan Offer'; case '/create_request': return 'New Loan Request'; case '/dashboard/offers': return 'Dashboard'; case '/dashboard/requests': return 'Dashboard'; case '/wallet': return 'Wallet'; case '/faucet': return 'Faucet'; default: return 'Page Not Found'; } } const Layout = (props) => { const path = props.location.pathname; return( <div className="flex-column flex-lg-row" id="main_container"> <div id="main_container_left" className="h-10 h-lg-100 w-100 w-lg-15"> <SideMenu /> </div> <div id="main_container_right" className="h-90 h-lg-100 w-100 w-lg-85"> <div id="global_header_container"> <span id="global_header_text">{renderHeader(path)}</span> </div> <div id="sub_container"> <Modal /> <Switch> <Redirect from="/" to="/offers" exact /> <Route path="/offers" component={View} /> <Route path="/requests" render={(props) => <View mode={true} {...props} />} /> <Route path="/create_request" render={() => <Form mode={true} key={"request"} />} /> <Route path="/create_offer" render={() => <Form key={"offer"} />} /> <Route path="/faucet" component={Faucet} /> <Route path="/dashboard/:mode" render={(props) => <Dashboard key={props.match.params.mode} {...props} />} /> <Route path="/wallet" component={Wallet} /> </Switch> </div> </div> </div> ); } const App = withRouter(Layout); const AppRouter = () => ( <BrowserRouter> <App /> </BrowserRouter> ); export default AppRouter;
/** * Created by chadsfather on 28/12/15. */ var strategy = require('passport-local').Strategy, models = require("./../models"); module.exports = new strategy(function (username, password, callback) { console.log('------------------------------------'); console.log(username); console.log(password); console.log('------------------------------------'); models.modelo('User') .find({ 'username': username, 'password': password }) .exec(function (err, res) { if (err) return callback(err) if (!user) return callback(null, false); if (user.password != password) return callback(null, false); return callback(null, res); }) });
besgamApp .controller("redirect-live", function( $scope, $route, $http, $interpolate, $sessionStorage, eventTrack ) { var id_feed = $route.current.params.id_feed, id_bet = $route.current.params.id_bet, id_bid = $route.current.params.id_bid, url = null, confFeed = { method: 'GET', url: 'json/feeds.json', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' } }; /* Traqueamos el evento */ eventTrack.new({ name: "redirect", category: "live", label: id_feed+"-"+id_bet }); /* Carga de datos de feeds */ $http(confFeed). success(function(dataFeed, status, headers, config) { $scope.img_feed = dataFeed[ id_feed ].str_image; id_bid = dataFeed[ id_feed ].str_bid; var getBetSlip = { method: 'POST', url: 'php/redirect-live.php', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, data: "id_feed=" + id_feed + "&id_bet=" + id_bet + "&id_bid=" + id_bid + "&id_user=" + $sessionStorage.iduser } /* Recuperamos datos del evento */ $http(getBetSlip). success(function(dataBet, status, headers, config) { /* Componemos la url */ url = $interpolate( dataBet.url )($scope); document.location.href = url; }); }); });
export { default } from './ModalCustom';
(function() { 'use strict'; angular .module('app') .config(config); config.injector = ['$stateProvider', '$urlRouterProvider']; function config($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('cloud', { url: '/cloud', templateUrl: 'templates/cloud/index.html', controller: 'CloudController as cloud' }); } })();
const os = require('os') const { app, BrowserWindow, Tray, ipcMain, shell,Menu,dialog } = require('electron'); const { spawn } = require('child_process'); const path = require('path'); const { Parser } = require('m3u8-parser'); const fs = require('fs'); const async = require('async'); const dateFormat = require('dateformat'); const download = require('download'); const crypto = require('crypto'); const got = require('got'); const { Readable} = require('stream'); const ffmpeg = require('fluent-ffmpeg'); const package_self = require('./package.json'); const appInfo = package_self; const winston = require('winston'); const nconf = require('nconf'); const { dir } = require('console'); let isdelts = true; let mainWindow = null; let playerWindow = null; let tray = null; let AppTitle = 'HLS Downloader' let firstHide = true; var configVideos = []; let globalCond ={}; const globalConfigDir = app.getPath('userData'); const globalConfigPath = path.join(globalConfigDir,'config.json'); const globalConfigVideoPath = path.join(globalConfigDir,'config_videos.json'); const httpTimeout = {socket: 300000, request: 300000, response:300000}; const referer = `https://tools.heisir.cn/M3U8Soft-Client?v=${package_self.version}`; const logger = winston.createLogger({ level: 'debug', format: winston.format.simple(), transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'logs/error.log', level: 'error' }), new winston.transports.File({ filename: 'logs/combined.log' }), ], }); if(!fs.existsSync(globalConfigDir)) { fs.mkdirSync(globalConfigDir, { recursive: true }); } nconf.argv().env() try { nconf.file({ file: globalConfigPath }) } catch (error) { logger.error('Please correct the mistakes in your configuration file: [%s].\n' + error, configFilePath) } process.on('uncaughtException',logger.error); process.on('unhandledRejection',logger.error); logger.info(`\n\n----- ${appInfo.name} | v${appInfo.version} | ${os.platform()} -----\n\n`) function createWindow() { // 创建浏览器窗口 mainWindow = new BrowserWindow({ width: 1024, height: 600, skipTaskbar: false, transparent: false, frame: false, resizable: true, webPreferences: { nodeIntegration: true, spellcheck: false }, icon: path.join(__dirname, 'icon/logo.png'), alwaysOnTop: false, hasShadow: false, }); mainWindow.setMenu(null) // 加载index.html文件 mainWindow.loadFile(path.join(__dirname, 'index.html')); //mainWindow.openDevTools(); // 当 window 被关闭,这个事件会被触发。 mainWindow.on('closed', () => { // 取消引用 window 对象,如果你的应用支持多窗口的话, // 通常会把多个 window 对象存放在一个数组里面, // 与此同时,你应该删除相应的元素。 mainWindow = null; }) //mainWindow.webContents.openDevTools(); } function createPlayerWindow(src) { if(playerWindow == null) { // 创建浏览器窗口 playerWindow = new BrowserWindow({ width: 1024, height: 600, skipTaskbar: false, transparent: false, frame: false, resizable: true, webPreferences: { nodeIntegration: true }, icon: path.join(__dirname, 'icon/logo.png'), alwaysOnTop: false, hasShadow: false, parent:mainWindow }); playerWindow.setMenu(null) playerWindow.on('closed', () => { // 取消引用 window 对象,如果你的应用支持多窗口的话, // 通常会把多个 window 对象存放在一个数组里面, // 与此同时,你应该删除相应的元素。 logger.info('playerWindow close.') playerWindow = null; }) } // 加载index.html文件 playerWindow.loadFile(path.join(__dirname, 'player.html'),{search:"src="+src}); } async function checkUpdate(){ //const { body } =await got("https://raw.githubusercontent.com/HeiSir2014/M3U8-Downloader/master/package.json").catch(logger.error); const { body } =await got("https://tools.heisir.cn/HLSDownload/package.json").catch(logger.error); if(body != '') { try { let _package = JSON.parse(body); if(_package.version != package_self.version) { if(dialog.showMessageBoxSync(mainWindow,{type:'question',buttons:["Yes","No"],message:`检测到新版本(${_package.version}),是否要打开升级页面,下载最新版`}) == 0) { shell.openExternal("https://tools.heisir.cn/HLSDownload/"); return; } } } catch (error) { logger.error(error); } } } app.on('ready', () => { createWindow(); tray = new Tray(path.join(__dirname, 'icon/logo.png')) tray.setTitle(AppTitle); tray.setToolTip(AppTitle); tray.on("double-click",()=>{ mainWindow.show(); }); tray.on("double-click",()=>{ mainWindow.show(); }); const contextMenu = Menu.buildFromTemplate([ { label: '显示窗口', type: 'normal',click:()=>{ mainWindow.show(); }}, { label: '退出', type: 'normal' ,click:()=>{ if(playerWindow) { playerWindow.close(); } mainWindow.close(); app.quit() }} ]) tray.setContextMenu(contextMenu); try { configVideos = JSON.parse(fs.readFileSync(globalConfigVideoPath)); } catch (error) { logger.error(error); } //百度统计代码 (async ()=>{ try { checkUpdate(); setInterval(checkUpdate,600000); let HMACCOUNT = nconf.get('HMACCOUNT'); if(!HMACCOUNT) HMACCOUNT = ''; const {headers} = await got("http://hm.baidu.com/hm.js?300991eff395036b1ba22ae155143ff3",{headers:{"Referer": referer,"Cookie":"HMACCOUNT="+HMACCOUNT}}); try { HMACCOUNT = headers['set-cookie'] && headers['set-cookie'][0].match(/HMACCOUNT=(.*?);/i)[1]; if(HMACCOUNT) { nconf.set('HMACCOUNT',HMACCOUNT); nconf.save(logger.error); } // fs.writeFileSync('tongji.ini',HMACCOUNT,{encoding:"utf-8",flag:"w"}) } catch (error_) { logger.error(error_) } logger.info(HMACCOUNT); await got(`http://hm.baidu.com/hm.gif?hca=${HMACCOUNT}&cc=1&ck=1&cl=24-bit&ds=1920x1080&vl=977&ep=6621%2C1598&et=3&ja=0&ln=zh-cn&lo=0&lt=${(new Date().getTime()/1000)}&rnd=0&si=300991eff395036b1ba22ae155143ff3&v=1.2.74&lv=3&sn=0&r=0&ww=1920&u=${encodeURIComponent(referer)}`,{headers:{"Referer": referer,"Cookie":"HMACCOUNT="+HMACCOUNT}}); await got(`http://hm.baidu.com/hm.gif?cc=1&ck=1&cl=24-bit&ds=1920x1080&vl=977&et=0&ja=0&ln=zh-cn&lo=0&rnd=0&si=300991eff395036b1ba22ae155143ff3&v=1.2.74&lv=1&sn=0&r=0&ww=1920&ct=!!&tt=M3U8Soft-Client`,{headers:{"Referer": referer,"Cookie":"HMACCOUNT="+HMACCOUNT}}); logger.info("call baidu-tong-ji end."); } catch (error) { logger.error(error) } })(); }); // 当全部窗口关闭时退出。 app.on('window-all-closed', async () => { let HMACCOUNT = nconf.get('HMACCOUNT'); // if(fs.existsSync('tongji.ini')) // { // HMACCOUNT = fs.readFileSync('tongji.ini',{encoding:"utf-8",flag:"r"}); // } await got(`http://hm.baidu.com/hm.gif?cc=1&ck=1&cl=24-bit&ds=1920x1080&vl=977&et=0&ja=0&ln=zh-cn&lo=0&rnd=0&si=300991eff395036b1ba22ae155143ff3&v=1.2.74&lv=1&sn=0&r=0&ww=1920&ct=!!&tt=M3U8Soft-Client`,{headers:{"Referer": referer,"Cookie":"HMACCOUNT="+HMACCOUNT}}); // 在 macOS 上,除非用户用 Cmd + Q 确定地退出, // 否则绝大部分应用及其菜单栏会保持激活。 if (process.platform !== 'darwin') { tray = null; app.quit(); }; }) app.on('activate', () => { // 在macOS上,当单击dock图标并且没有其他窗口打开时, // 通常在应用程序中重新创建一个窗口。 if (mainWindow === null) { createWindow() } }) ipcMain.on("hide-windows",function(){ if (mainWindow != null) { mainWindow.hide(); if(firstHide && tray) { tray.displayBalloon({ iconType :null, title :"温馨提示", content :"我隐藏到这里了哦,双击我显示主窗口!" }) firstHide = false; } } }); ipcMain.on('get-all-videos', function (event, arg) { event.sender.send('get-all-videos-reply', configVideos); }); ipcMain.on('task-add', async function (event, arg, headers) { logger.info(arg); let hlsSrc = arg; let _headers = {}; if(headers != '') { let __ = headers.match(/(.*?): ?(.*?)(\n|\r|$)/g); __ && __.forEach((_)=>{ let ___ = _.match(/(.*?): ?(.*?)(\n|\r|$)/i); ___ && (_headers[___[1]] = ___[2]); }); } let mes = hlsSrc.match(/^https?:\/\/[^/]*/); let _hosts = ''; if(mes && mes.length >= 1) { _hosts = mes[0]; } if(_headers['Origin'] == null && _headers['origin'] == null) { _headers['Origin'] = _hosts; } if(_headers['Referer'] == null && _headers['referer'] == null) { _headers['Referer'] = _hosts; } const response = await got(hlsSrc,{headers:_headers,timeout:httpTimeout}).catch(logger.error); { let info = ''; let code = 0; code = -1; info = '解析资源失败!'; if (response && response.body != null && response.body != '') { let parser = new Parser(); parser.push(response.body); parser.end(); let count_seg = parser.manifest.segments.length; if (count_seg > 0) { code = 0; if (parser.manifest.endList) { let duration = 0; parser.manifest.segments.forEach(segment => { duration += segment.duration; }); info = `点播资源解析成功,有 ${count_seg} 个片段,时长:${formatTime(duration)},即将开始缓存...`; startDownload(hlsSrc,_headers); } else { info = `直播资源解析成功,即将开始缓存...`; startDownloadLive(hlsSrc,_headers); } } } event.sender.send('task-add-reply', { code: code, message: info }); } }); class QueueObject { constructor() { this.segment = null; this.url = ''; this.headers = ''; this.id = 0; this.idx = 0; this.dir = ''; this.then = this.catch = null; } async callback( _callback ) { try{ if(!globalCond[this.id]) { logger.debug(`globalCond[this.id] is not exsited.`); return; } let partent_uri = this.url.replace(/([^\/]*\?.*$)|([^\/]*$)/g, ''); let segment = this.segment; let uri_ts = ''; if (/^http.*/.test(segment.uri)) { uri_ts = segment.uri; } else if(/^\/.*/.test(segment.uri)) { let mes = this.url.match(/^https?:\/\/[^/]*/); if(mes && mes.length >= 1) { uri_ts = mes[0] + segment.uri; } else { uri_ts = partent_uri + segment.uri; } } else { uri_ts = partent_uri + segment.uri; } let filename = `${ ((this.idx + 1) +'').padStart(6,'0')}.ts`; let filpath = path.join(this.dir, filename); let filpath_dl = path.join(this.dir, filename+".dl"); logger.debug(`2 ${segment.uri}`,`${filename}`); //检测文件是否存在 for (let index = 0; index < 3 && !fs.existsSync(filpath); index++) { // 下载的时候使用.dl后缀的文件名,下载完成后重命名 let that = this; await download (uri_ts, that.dir, {filename:filename + ".dl",timeout:httpTimeout,headers:that.headers}).catch((err)=>{ logger.error(err) if(fs.existsSync(filpath_dl)) fs.unlinkSync( filpath_dl); }); if(!fs.existsSync(filpath_dl)) continue; if( fs.statSync(filpath_dl).size <= 0 ) { fs.unlinkSync(filpath_dl); } if(segment.key != null && segment.key.method != null) { //标准解密TS流 let aes_path = path.join(this.dir, "aes.key" ); if(!fs.existsSync( aes_path )) { let key_uri = segment.key.uri; if (! /^http.*/.test(segment.key.uri)) { key_uri = partent_uri + segment.key.uri; } else if(/^\/.*/.test(key_uri)) { let mes = this.url.match(/^https?:\/\/[^/]*/); if(mes && mes.length >= 1) { key_uri = mes[0] + segment.key.uri; } else { key_uri = partent_uri + segment.key.uri; } } await download (key_uri, that.dir, { filename: "aes.key" ,headers:that.headers,timeout:httpTimeout}).catch(console.error); } if(fs.existsSync( aes_path )) { try { let key_ = fs.readFileSync( aes_path ); let iv_ = segment.key.iv != null ? Buffer.from(segment.key.iv.buffer) :Buffer.from(that.idx.toString(16).padStart(32,'0') ,'hex' ); let cipher = crypto.createDecipheriv((segment.key.method+"-cbc").toLowerCase(), key_, iv_); cipher.on('error', console.error); let inputData = fs.readFileSync( filpath_dl ); let outputData =Buffer.concat([cipher.update(inputData),cipher.final()]); fs.writeFileSync(filpath,outputData); if(fs.existsSync(filpath_dl)) fs.unlinkSync(filpath_dl); that.then && that.then(); } catch (error) { logger.error(error) if(fs.existsSync( filpath_dl )) fs.unlinkSync(filpath_dl); } return; } } else { fs.renameSync(filpath_dl , filpath); break; } } if(fs.existsSync(filpath)) { this.then && this.then(); } else { this.catch && this.catch(); } } catch(e) { logger.error(e); } finally { _callback(); } } } function queue_callback(that,callback) { that.callback(callback); } async function startDownload(url, headers = null ,nId = null) { let id = nId == null ? new Date().getTime():nId; let dir = path.join(app.getAppPath().replace(/resources\\app.asar$/g,""), 'download/'+id); logger.info(dir); let filesegments = []; if(!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } const response = await got(url,{headers:headers,timeout:httpTimeout}).catch(logger.error); if(response == null || response.body == null || response.body == '') { return; } let parser = new Parser(); parser.push(response.body); parser.end(); //并发 2 个线程下载 var tsQueues = async.queue(queue_callback, 2 ); let count_seg = parser.manifest.segments.length; let count_downloaded = 0; var video = { id:id, url:url, dir:dir, segment_total:count_seg, segment_downloaded:count_downloaded, time: dateFormat(new Date(),"yyyy-mm-dd HH:MM:ss"), status:'初始化...', isLiving:false, headers:headers, videopath:'' }; if(nId == null) { mainWindow.webContents.send('task-notify-create',video); } globalCond[id] = true; let segments = parser.manifest.segments; for (let iSeg = 0; iSeg < segments.length; iSeg++) { let qo = new QueueObject(); qo.dir = dir; qo.idx = iSeg; qo.id = id; qo.url = url; qo.headers = headers; qo.segment = segments[iSeg]; qo.then = function(){ count_downloaded = count_downloaded + 1 video.segment_downloaded = count_downloaded; video.status = `下载中...${count_downloaded}/${count_seg}` mainWindow.webContents.send('task-notify-update',video); }; tsQueues.push(qo); } tsQueues.drain(()=>{ logger.info('download success'); video.status = "已完成,合并中..." mainWindow.webContents.send('task-notify-end',video); let indexData = ''; for (let iSeg = 0; iSeg < segments.length; iSeg++) { let filpath = path.join(dir, `${ ((iSeg + 1) +'').padStart(6,'0') }.ts`); indexData += `file '${filpath}'\r\n`; filesegments.push(filpath); } fs.writeFileSync(path.join(dir,'index.txt'),indexData); let outPathMP4 = path.join(dir,id+'.mp4'); let ffmpegBin = path.join(app.getAppPath().replace(/resources\\app.asar$/g,""),"ffmpeg.exe"); if(!fs.existsSync(ffmpegBin)) { ffmpegBin = path.join(app.getAppPath().replace(/resources\\app.asar$/g,""),"ffmpeg"); } if(fs.existsSync(ffmpegBin)) { var p = spawn(ffmpegBin,["-f","concat","-safe","0","-i",`${path.join(dir,'index.txt')}`,"-c","copy","-f","mp4",`${outPathMP4}`]); p.on("close",()=>{ if(fs.existsSync(outPathMP4)) { video.videopath = outPathMP4; video.status = "已完成" mainWindow.webContents.send('task-notify-end',video); if(isdelts) { let index_path = path.join(dir,'index.txt'); if(fs.existsSync(index_path)) { fs.unlinkSync(index_path); } filesegments.forEach(fileseg=>{ if(fs.existsSync(fileseg)) { fs.unlinkSync(fileseg); } }); } } else { video.videopath = outPathMP4; video.status = "合成失败,可能是非标准加密视频源,请联系客服定制。" mainWindow.webContents.send('task-notify-end',video); } configVideos.push(video); fs.writeFileSync(globalConfigVideoPath,JSON.stringify(configVideos)); }); p.on("data",logger.info); } else{ video.videopath = outPathMP4; video.status = "已完成,未发现本地FFMPEG,不进行合成。" mainWindow.webContents.send('task-notify-end',video); } }); logger.info("drain over"); } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } class FFmpegStreamReadable extends Readable { constructor(opt) { super(opt); } _read() {} } async function startDownloadLive(url,headers = null,nId = null) { let id = nId == null ? new Date().getTime() : nId; let dir = path.join(app.getAppPath().replace(/resources\\app.asar$/g,""), 'download/'+id); logger.info(dir); if(!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } let count_downloaded = 0; let count_seg = 100; var video = { id:id, url:url, dir:dir, segment_total:count_seg, segment_downloaded:count_downloaded, time: dateFormat(new Date(),"yyyy-mm-dd HH:MM:ss"), status:'初始化...', isLiving:true, headers:headers, videopath:'' }; configVideos.push(video); fs.writeFileSync(globalConfigVideoPath,JSON.stringify(configVideos)); if(nId == null) { mainWindow.webContents.send('task-notify-create',video); } let partent_uri = url.replace(/([^\/]*\?.*$)|([^\/]*$)/g, ''); let segmentSet = new Set(); let ffmpegInputStream = null; let ffmpegObj = null; globalCond[id] = true; while (globalCond[id]) { try { const response = await got(url,{headers:headers,timeout:httpTimeout}).catch(logger.error); if(response == null || response.body == null || response.body == '') { break; } let parser = new Parser(); parser.push(response.body); parser.end(); let count_seg = parser.manifest.segments.length; let segments = parser.manifest.segments; logger.info(`解析到 ${count_seg} 片段`) if (count_seg > 0) { //开始下载片段的时间,下载完毕后,需要计算下次请求的时间 let _startTime = new Date(); let _videoDuration = 0; for (let iSeg = 0; iSeg < segments.length; iSeg++) { let segment = segments[iSeg]; if(segmentSet.has(segment.uri)) { continue; } if(!globalCond[id]) { break; } _videoDuration = _videoDuration + segment.duration*1000; let uri_ts = ''; if (/^http.*/.test(segment.uri)) { uri_ts = segment.uri; } else if(/^\/.*/.test(segment.uri)) { let mes = url.match(/^https?:\/\/[^/]*/); if(mes && mes.length >= 1) { uri_ts = mes[0] + segment.uri; } else { uri_ts = partent_uri + segment.uri; } } else { uri_ts = partent_uri + segment.uri; } let filename = `${ ((count_downloaded + 1) +'').padStart(6,'0') }.ts`; let filpath = path.join(dir, filename); let filpath_dl = path.join(dir, filename+".dl"); for (let index = 0; index < 3; index++) { if(!globalCond[id]) { break; } //let tsStream = await got.get(uri_ts, {responseType:'buffer', timeout:httpTimeout ,headers:headers}).catch(logger.error).body(); await download (uri_ts, dir, { filename: filename + ".dl", timeout:httpTimeout ,headers:headers}).catch((err)=>{ logger.error(err) if(fs.existsSync( filpath_dl )) { fs.unlinkSync( filpath_dl ); } }); if( fs.existsSync(filpath_dl) ) { let stat = fs.statSync(filpath_dl); if(stat.size > 0) { fs.renameSync(filpath_dl,filpath); } else { fs.unlinkSync( filpath_dl); } } if( fs.existsSync(filpath) ) { segmentSet.add(segment.uri); if(ffmpegObj == null) { let outPathMP4 = path.join(dir,id+'.mp4'); let newid = id; //不要覆盖之前下载的直播内容 while(fs.existsSync(outPathMP4)) { outPathMP4 = path.join(dir,newid+'.mp4'); newid = newid + 1; } let ffmpegBin = path.join(app.getAppPath().replace(/resources\\app.asar$/g,""),"ffmpeg.exe"); if(!fs.existsSync(ffmpegBin)) { ffmpegBin = path.join(app.getAppPath().replace(/resources\\app.asar$/g,""),"ffmpeg"); } if(fs.existsSync(ffmpegBin)) { ffmpegInputStream = new FFmpegStreamReadable(null); ffmpegObj = new ffmpeg(ffmpegInputStream) .setFfmpegPath(ffmpegBin) .videoCodec('copy') .audioCodec('copy') .save(outPathMP4) .on('error', logger.info) .on('end', function(){ video.videopath = outPathMP4; video.status = "已完成"; mainWindow.webContents.send('task-notify-end',video); fs.writeFileSync(globalConfigVideoPath,JSON.stringify(configVideos)); }) .on('progress', logger.info); } else{ video.videopath = outPathMP4; video.status = "已完成,未发现本地FFMPEG,不进行合成。" mainWindow.webContents.send('task-notify-update',video); } } if(ffmpegInputStream) { ffmpegInputStream.push(fs.readFileSync(filpath)); fs.unlinkSync( filpath ); } //fs.appendFileSync(path.join(dir,'index.txt'),`file '${filpath}'\r\n`); count_downloaded = count_downloaded + 1; video.segment_downloaded = count_downloaded; video.status = `直播中... [${count_downloaded}]`; mainWindow.webContents.send('task-notify-update',video); break; } } } if(globalCond[id]) { //使下次下载M3U8时间提前1秒钟。 _videoDuration = _videoDuration - 1000; let _downloadTime = (new Date().getTime() - _startTime.getTime()); if(_downloadTime < _videoDuration) { await sleep(_videoDuration - _downloadTime); } } } else { break; } parser = null; } catch (error) { logger.info(error.response.body); } } if(ffmpegInputStream) { ffmpegInputStream.push(null); } if(count_downloaded <= 0) { video.videopath = ''; video.status = "已完成,下载失败" mainWindow.webContents.send('task-notify-end',video); return; } } function formatTime(duration) { let sec = Math.floor(duration % 60).toLocaleString(); let min = Math.floor(duration / 60 % 60).toLocaleString(); let hour = Math.floor(duration / 3600 % 60).toLocaleString(); if (sec.length != 2) sec = '0' + sec; if (min.length != 2) min = '0' + min; if (hour.length != 2) hour = '0' + hour; return hour + ":" + min + ":" + sec; } ipcMain.on('delvideo', function (event, id) { configVideos.forEach(Element=>{ if(Element.id==id) { try { if(fs.existsSync(Element.dir)) { var files = fs.readdirSync(Element.dir) files.forEach(e=>{ fs.unlinkSync(path.join(Element.dir,e) ); }) fs.rmdirSync(Element.dir,{recursive :true}) } var nIdx = configVideos.indexOf(Element); if( nIdx > -1) { configVideos.splice(nIdx,1); fs.writeFileSync(globalConfigVideoPath,JSON.stringify(configVideos)); } event.sender.send("delvideo-reply",Element); } catch (error) { logger.error(error) } } }); }); ipcMain.on('opendir', function (event, arg) { shell.openExternal(arg); }); ipcMain.on('playvideo', function (event, arg) { createPlayerWindow(arg); }); ipcMain.on('StartOrStop', function (event, arg) { logger.info(arg); let id = Number.parseInt(arg); if(globalCond[id] == null) { logger.info("不存在此任务") return; } globalCond[id] = !globalCond[ id]; if(globalCond[ id] == true) { configVideos.forEach(Element=>{ if(Element.id==id) { if(Element.isLiving == true) { startDownloadLive(Element.url, Element.headers,id); } else { startDownload(Element.url, Element.headers, id); } } }); } }); ipcMain.on('setting_isdelts', function (event, arg) { isdelts = arg; });
const CBOR = artifacts.require("CBOR") const Witnet = artifacts.require("Witnet") module.exports = function (deployer, network) { console.log(`> Migrating CBOR and Witnet into ${network} network`) deployer.deploy(CBOR).then(function () { deployer.link(CBOR, Witnet) return deployer.deploy(Witnet) }) }
const express = require("express"); const app = express(); const { randomBytes } = require("crypto"); const cors = require("cors"); const axios = require("axios"); app.use(express.json()); app.use(cors()); let comments = []; // create comment for a specific post // post request app.post("/posts/:id/comments", async (req, res) => { let id = randomBytes(4).toString("hex"); let { content } = req.body; let { id: postid } = req.params; let newcomment = { postid, content, id, status: "pending" }; comments.push(newcomment); await axios.post("http://localhost:4005/events", { // await axios.post("http://eventbus-srv:4005/events", { type: "CommentCreated", data: { postid, content, id, status: "pending" }, }); res.status(201).send(newcomment); }); // get all comments for a specific post // get request app.get("/posts/:id/comments", (req, res) => { let { id } = req.params; let comm = comments.filter((c) => { return c.postid == id; }); res.status(200).send(comm); }); // Route to receive event // POST request app.post("/events", async (req, res) => { let { type, data } = req.body; console.log(`Event received of type ${type}`); if (type == "CommentModerated") { comments.map((c) => { if (c.id == data.id) { c.status = data.status; } }); let event = req.body; event.type = "CommentUpdated"; await axios.post("http://localhost:4005/events", event); // await axios.post("http://eventbus-srv:4005/events", event); } res.status(200).send({ status: "OK" }); }); app.listen(4001, () => { console.log("comments service is listening on port 4001"); });
//6B: Password Game //In your Javascript file, hardcode a password (e.g. `var password = "monkeybrains";` but pick your own password) Prompt the user for a password; if it matches your stored password, give them an `alert()` that says "Good job!" If it doesn't match, give them an `alert()` that says something to the effect of `"Sorry, the password is actually monkeybrains."` Make sure to use the variable storing the password instead of the string-literal that represents the password text so your program can easily change. var password = "123password!"; var userPassword = prompt("Please enter a password"); if (userPassword === password) { alert("Great job!"); } if (userPassword != password) { alert("NOPE"); }
'use strict'; const getArticleCategoriesIds = (article) => article.categories.map((item) => item.id); module.exports = { getArticleCategoriesIds, };
import React from "react" import { Link } from "react-router-dom" import validator from "validator" import PropTypes from "prop-types" import useForm from "../../hooks/useForm" import { Button, Col, Form, FormFeedback, FormGroup, FormText, Input, Row } from "reactstrap" const validateUserSignUp = formData => ({ username: formData.username === "" ? "Username cannot be blank" : formData.username.length < 4 ? "Username must be at least 4 characters long" : formData.username.length > 20 ? "Username cannot be longer than 20 characters" : "", email: formData.email === "" ? "E-mail cannot be blank" : !validator.isEmail(formData.email) ? "This E-mail is not valid" : "", password: formData.password === "" ? "Password cannot be blank" : formData.password.length < 3 ? "Password must be at least 3 characters long" : formData.password.length > 20 ? "Password cannot be longer than 20 characters" : "", confirmPassword: formData.confirmPassword === "" ? "Confirm Password must be informed" : formData.confirmPassword !== formData.password ? "Password and Confirm Password must match" : "" }) const INITIAL_FORM_DATA = { username: "", email: "", password: "", confirmPassword: "" } const INITIAL_FORM_ERRORS = { username: "", email: "", password: "", confirmPassword: "" } const SignUpForm = ({ onSubmit }) => { const { values, errors, handleChange, handleSubmit, validateForm } = useForm( INITIAL_FORM_DATA, INITIAL_FORM_ERRORS, validateUserSignUp, onSubmit ) return ( <Form className="py-4 px-2" onSubmit={handleSubmit}> <FormGroup className="mb-4"> <Input type="text" name="username" id="usernameInput" placeholder="Username" value={values.username} onChange={handleChange} onKeyUp={validateForm} invalid={!!errors.username} /> <FormFeedback>{errors.username}</FormFeedback> <FormText> Enter a username to identify yourself within the community </FormText> </FormGroup> <FormGroup className="mb-4"> <Input type="email" name="email" id="emailInput" placeholder="E-mail Address" value={values.email} onChange={handleChange} onKeyUp={validateForm} invalid={!!errors.email} /> <FormFeedback>{errors.email}</FormFeedback> <FormText>Enter a valid an active e-mail address</FormText> </FormGroup> <FormGroup className="mb-4"> <Input type="password" name="password" id="passwordInput" placeholder="Password" value={values.password} onChange={handleChange} onKeyUp={validateForm} invalid={!!errors.password} /> <FormFeedback>{errors.password}</FormFeedback> <FormText>Inform a secure password</FormText> </FormGroup> <FormGroup className="mb-4"> <Input type="password" name="confirmPassword" id="confirmPasswordInput" placeholder="Confirm Password" value={values.confirmPassword} onChange={handleChange} onKeyUp={validateForm} invalid={!!errors.confirmPassword} /> <FormFeedback>{errors.confirmPassword}</FormFeedback> <FormText> Retype your password here to make sure there aren't any typos </FormText> </FormGroup> <Row> <Col> <Button color="primary">Submit</Button> </Col> <Col> <Link to="/signin" className="btn btn-light"> Have an account? Sign In Here </Link> </Col> </Row> </Form> ) } SignUpForm.propTypes = { onSubmit: PropTypes.func.isRequired } export default SignUpForm
/** * 年度价格的前端控制JS * 作者:吕淑兰 * */ $(function(){ var minunitprice=null; var maxunitprice=null; var startDate=null; var endDate=null; var feeyear=null; //设置系统页面标题 $("span#mainpagetille").html("年度价格管理"); //显示年度价格列表 $("table#YearPriceGrid").jqGrid({ url: host+'yearPrice/list/condition/page', datatype: "json", colModel: [ { label: '收费年度', name: 'feeyear', width: 50 }, { label: '单价', name: 'unitprice', width: 50 }, { label: '开始日期', name: 'startDate', width: 50 }, { label: '结束日期', name: 'endDate', width: 50}, { label: '描述', name: 'pricedesc', width: 50 } ], caption:"年度价格列表", viewrecords: true, //显示总记录数 autowidth: true, height: 400, rowNum: 10, rowList:[10,15,20], jsonReader : { root: "list", page: "page", total: "pageCount", records: "count", repeatitems: true, id: "feeyear"}, pager: "#YearPriceGridPager", multiselect:false, onSelectRow:function(fno){ feeyear=fno; } }); //设置检索参数,更新jQGrid的列表显示 function reloadYearPriceList() { $("table#YearPriceGrid").jqGrid('setGridParam',{postData:{ minunitprice:minunitprice,maxunitprice:maxunitprice,startDate:startDate,endDate:endDate}}).trigger("reloadGrid"); } //定义的更新事件的处理 $("input#minunitprice").off().on("change",function(){ minunitprice=$("input#minunitprice").val(); reloadYearPriceList(); }); $("input#maxunitprice").off().on("change",function(){ maxunitprice=$("input#maxunitprice").val(); reloadYearPriceList(); }); //定义的更新事件的处理 $("input#startDate").off().on("change",function(){ startDate=$("input#startDate").val(); reloadYearPriceList(); }); $("input#endDate").off().on("change",function(){ endDate=$("input#endDate").val(); reloadYearPriceList(); }); //===========================增加年度价格处理================================================ $("a#YearPriceAddLink").off().on("click",function(){ $("div#YearPriceDialogArea").load("yearprice/add.html",function(){ //取得年度价格列表,填充年度价格下拉框 $.getJSON(host+"feeItem/list/all",function(List){ if(List){ $.each(List,function(index,item){ $("div#FeeItemList").append("<input type='checkbox' name='feeItems' value='"+item.no+"' />"+item.name); }); } }); //验证提交数据 $("form#YearPriceAddForm").validate({ rules: { feeyear: { required: true } }, message:{ feeyear: { required: "收费年度为空" } } }); //增加年度价格的弹窗 $("div#YearPriceDialogArea").dialog({ title:"增加年度价格", width:600 }); //拦截增加提交表单 $("form#YearPriceAddForm").ajaxForm(function(result){ if(result.status=="OK"){ reloadYearPriceList(); //更新年度价格列表 } //alert(result.message); //BootstrapDialog.alert(result.message); BootstrapDialog.show({ title: '年度价格操作信息', message:result.message, buttons: [{ label: '确定', action: function(dialog) { dialog.close(); } }] }); $("div#YearPriceDialogArea" ).dialog( "close" ); $("div#YearPriceDialogArea" ).dialog( "destroy" ); $("div#YearPriceDialogArea").html(""); }); //点击取消按钮处理 $("input[value='取消']").on("click",function(){ $("div#YearPriceDialogArea" ).dialog( "close" ); $("div#YearPriceDialogArea" ).dialog( "destroy" ); $("div#YearPriceDialogArea").html(""); }); }); }); //===============================修改年度价格处理============================= $("a#YearPriceModifyLink").off().on("click",function(){ if(feeyear==null){ BootstrapDialog.show({ title: '年度价格操作信息', message:"请选择要修改的年度价格", buttons: [{ label: '确定', action: function(dialog) { dialog.close(); } }] }); } else{ $("div#YearPriceDialogArea").load("yearprice/modify.html",function(){ //取得年度价格列表,填充收费项目下拉框 $.getJSON(host+"feeItem/list/all",function(List){ if(List){ $.each(List,function(index,item){ $("div#FeeItemList").append("<input type='checkbox' name='feeItems' value='"+item.no+"' />"+item.name); }); } }); //取得选择的年度价格 $.getJSON(host+"yearPrice/get",{feeyear:feeyear},function(YearPrice){ if(YearPrice){ //alert(itemno); $("input[name='feeyear']").val(feeyear); $("input[name='unitprice']").val(YearPrice.unitprice); $("input[name='startDate']").val(YearPrice.startDate); $("input[name='endDate']").val(YearPrice.endDate); $("input[name='pricedesc']").val(YearPrice.pricedesc); if(YearPrice.item){ $.each(YearPrice.item,function(index,FeeItemModel){ $("input[name='feeItems'][value='"+FeeItemModel.no+"']").attr("checked","true"); }); } } }); //弹出Dialog $("div#YearPriceDialogArea").dialog({ title:"年度价格修改", width:600 }); $("form#YearPriceModifyForm").ajaxForm(function(result){ if(result.status=="OK"){ reloadYearPriceList(); //更新年度价格列表 } //alert(result.message); //BootstrapDialog.alert(result.message); BootstrapDialog.show({ title: '年度价格操作信息', message:result.message, buttons: [{ label: '确定', action: function(dialog) { dialog.close(); } }] }); $("div#YearPriceDialogArea" ).dialog( "close" ); $("div#YearPriceDialogArea" ).dialog( "destroy" ); $("div#YearPriceDialogArea").html(""); }); //点击取消按钮处理 $("input[value='取消']").on("click",function(){ $("div#YearPriceDialogArea" ).dialog( "close" ); $("div#YearPriceDialogArea" ).dialog( "destroy" ); $("div#YearPriceDialogArea").html(""); }); }); } }); //===============================删除年度价格处理===================================== $("a#YearPriceDeleteLink").off().on("click",function(){ if(feeyear==null){ BootstrapDialog.show({ title: '年度价格操作信息', message:"请选择要删除的年度价格", buttons: [{ label: '确定', action: function(dialog) { dialog.close(); } }] }); } else { BootstrapDialog.confirm('确认删除此收费年度么?', function(result){ if(result) { $.post("yearPrice/delete",{feeyear:feeyear},function(result){ if(result.status=="OK"){ reloadYearPriceList(); //更新年度价格列表 } BootstrapDialog.show({ title: '年度价格操作信息', message:result.message, buttons: [{ label: '确定', action: function(dialog) { dialog.close(); } }] }); }); } }); } }); //================================查看年度价格处理==================================== $("a#YearPriceViewLink").off().on("click",function(){ if(feeyear==null){ BootstrapDialog.show({ title: '年度价格操作信息', message:"请选择要查看的年度价格", buttons: [{ label: '确定', action: function(dialog) { dialog.close(); } }] }); } else{ $("div#YearPriceDialogArea").load("yearprice/view.html",function(){ //取得选择的年度价格 $.getJSON(host+"yearPrice/get",{feeyear:feeyear},function(YearPrice){ if(YearPrice){ $("span#feeyear").html(YearPrice.feeyear); $("span#unitprice").html(YearPrice.unitprice); $("span#startDate").html(YearPrice.startDate); $("span#endDate").html(YearPrice.endDate); $("span#pricedesc").html(YearPrice.pricedesc); if(YearPrice.item){ $.each(YearPrice.item,function(index,FeeItemModel){ $("span#feeitems").append(FeeItemModel.name+" "); }); } } }); //弹出Dialog $("div#YearPriceDialogArea").dialog({ title:"年度价格详细", width:600 }); //点击取消按钮处理 $("input[value='关闭']").on("click",function(){ $("div#YearPriceDialogArea").dialog( "close" ); $("div#YearPriceDialogArea").dialog( "destroy" ); $("div#YearPriceDialogArea").html(""); }); }); } }); //================================查看年度价格收费项目处理==================================== $("a#FeeItemViewLink").off().on("click",function(){ if(feeyear==null){ BootstrapDialog.show({ title: '年度价格操作信息', message:"请选择要查看的年度价格", buttons: [{ label: '确定', action: function(dialog) { dialog.close(); } }] }); } else{ $("div#YearPriceDialogArea").load("yearprice/feeitemview.html",function(){ //取得选择的年度价格 $.getJSON(host+"yearPrice/get",{feeyear:feeyear},function(YearPrice){ if(YearPrice){ $("span#feeyear").html(YearPrice.feeyear); if(YearPrice.item){ $.each(YearPrice.item,function(index,FeeItemModel){ $("span#feeitems").append(FeeItemModel.name+" "); }); } } }); //弹出Dialog $("div#YearPriceDialogArea").dialog({ title:"年度价格详细", width:600 }); //点击取消按钮处理 $("input[value='关闭']").on("click",function(){ $("div#YearPriceDialogArea").dialog( "close" ); $("div#YearPriceDialogArea").dialog( "destroy" ); $("div#YearPriceDialogArea").html(""); }); }); } }); });
const ArticleVerif = require('../../../db/ArticleVerif'), Article = require('../../../db/Article'), User = require('../../../db/User') module.exports = { list: async (req, res) => { const dbArticle = await Article.find({}) res.render('admin/article/listArticle', { dbArticle : dbArticle, ArticleU:req.flash('ArticleU') }) }, view: (req, res) => { res.render('admin/article/viewArticle') }, edit: (req, res) => { res.render('admin/article/editArticle') } }
function findPoisonedBottle(bottles, strips) { runTest(bottles, strips); positive = getPositiveOnDay(strips, 7); return setBits(positive); } /** * * @param {Array[]<Bottle>} bottles * @param {Array[]<TestStrip>} strips */ function runTest(bottles, strips) { for (int i = 0; i < bottles.length; i++) { const bottleId = bottles[i].getId(); let bitIndex = 0; while(id > 0){ if((id & 1) === 1){ testStrips.get(bitIndex).addDropOnDay(0, bottle); } bitIndex++; id >>=1; } } } /** * * @param {Array[]<TestStrip>} * @param {number} day */ function getPositiveOnDay(testStrips, day){ let positive = []; for (let i = 0; i < testStrips.length; i++) { const strip = testStrips[i]; const id = strip.getId(); if(strip.isPositiveOnDay(day)){ positive.add(id); } } return positive; } /** * * @param {Array[number]} positive array containing 1's and 0's to be converted * to a number * */ function setBits(positive) { id = 0; for (int i = 0; i < positive.length; i++) { i |= 1 << bitIndex; } return id; } class Bottle { constructor(id) { this.id = id; this.poisoned = false; } getId() { return this.id; } setAsPoisoned() { this.poisoned = true; } isPoisoned() { return this.poisoned; } } class TestStrip { static DAYS_FOR_RESULT = 7; constructor(id) { this.id = id; this.dropsByDay = []; } sizeDropsForDay(day) { while (this.dropsByDay.length < day) { this.dropsByDay.push([]); } } addDropOnDay(day, bottle) { sizeDropsForDay(day); let drops = this.dropsByDay[day]; drops.push(bottle); } hasPoison(bottles) { for (let i = 0; i < bottles.length; i++) { if (bottles[i].isPoisoned()) { return true; } } return false; } getLastWeekBottles(day) { if (day < this.DAYS_FOR_RESULT) { return null; } return this.dropsByDay[day - this.DAYS_FOR_RESULT]; } isPositiveOnDay(day) { const testDay = day - this.DAYS_FOR_RESULT; if(testDay < 0 || testDay>=dropsByDay[day]){ return false; } for(let i = 0; i < testDay; i++){ bottles = this.dropsByDay[day]; if(hasPoison(bottles)){ return true; } } return false; } }
const models = require('../models'); const sendError = (err, res) => { res.status(500).send(`Error while doing operation: ${err.name}, ${err.message}`); }; exports.findAll = function findAll(req, res) { const searchText = req.query.searchText ? `%${req.query.searchText}%` : '%%'; const limit = req.query.pageSize ? parseInt(req.query.pageSize, 10) : 10; const currentPage = req.query.currentPage ? parseInt(req.query.currentPage, 10) : 1; const offset = (currentPage - 1) * limit; models.Role.findAndCountAll({ where: { $or: [ { code: { $ilike: searchText } }, { name: { $ilike: searchText } }, ], }, limit, offset, }) .then((roles) => { res.json(roles); }) .catch((err) => { sendError(err, res); }); }; exports.findOne = function findOne(req, res) { models.Role.findOne({ where: { id: req.params.roleId }, }) .then((role) => { res.json(role); }) .catch((err) => { sendError(err, res); }); }; exports.create = function create(req, res) { const roleForm = req.body; models.Role.create(roleForm) .then((role) => { res.json(role); }) .catch((err) => { sendError(err, res); }); }; exports.update = function update(req, res) { const roleForm = req.body; models.Role.update( roleForm, { where: { id: req.params.roleId }, }) .then((result) => { res.json(result); }) .catch((err) => { sendError(err, res); }); }; exports.destroy = function destroy(req, res) { models.Role.destroy( { where: { id: req.params.roleId }, }) .then((result) => { res.json(result); }) .catch((err) => { sendError(err, res); }); };
import React, { Component } from "react"; import { Link } from "react-router-dom"; import "./LandingPage.css"; export default class LandingPage extends Component { render() { return ( <div className="landingPage"> <div className="links"> <Link className="landing" to="/"> Home </Link> <br /> <Link className="holdings" to="/home"> Holdings </Link> </div> <header className="landingHeader"> <h1>Pocket Stocks</h1> {/* <button className="join_button" type="submit">Sign up</button> */} </header> <section className="briefOV"> <h2>Stock predictions in the palm of your hand</h2> <p> Everyone wants to say "I told you so". Say it with your stock market predictions! </p> </section> <section className="appDesc"> <p> To use this app, simply navigate to the 'Holdings' page, enter the required information: </p> <ul> <li>Ticker Symbol</li> <li>Purchase Price</li> <li>Recommendation Status</li> <li> Your Post, defending your position, forecasting, or just an opinion </li> </ul> <p> Your post will be added to our database where other users can read your post along with all others. </p> </section> <div className="navHoldings"> <Link className="navHold" to="/home"> Get Started! </Link> </div> </div> ); } }
var express = require('express'); var app = express(); var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'qwer1234', database: 'myDB' }); connection.connect(function(err, results){ if(err) console.log('Connection Error: ' + err.message); else console.log('Database Connected!'); connection.query("truncate myTABLE",function(err){ }); }); app.get('/',function( req,res ){ var time = getTIME(); var co2 = parseInt(req.query.co2); var tempe = parseFloat(req.query.tempe); var humi = parseFloat(req.query.humi); console.log(req.query); var values = { 'TEMPE' : tempe, 'CO2' : co2, 'HUMI' : humi ,'TIME' : time }; connection.query('INSERT INTO myTABLE SET ?', values, function(err,res){ }); //var DI = 0.72*(tempe+humi) + 40.6; //res.send('0'); if(tempe <= 25.0) res.send('0'); else if(tempe <= 26.0) res.send('1'); else if(tempe <= 27.0) res.send('2'); else res.send('3'); }); app.get('/table',function(req,res ){ connection.query("SELECT * from myTABLE", function(err,rows){ console.log(rows); }); }); app.listen(3000, function(){ console.log("access"); }); function getTIME( ){ var date = new Date(); var hour = date.getHours(); var inthour = parseInt(hour) + 9; if( inthour >= 24 ) inthour -= 24; hour = inthour.toString(); hour = (hour < 10 ? "0" : "") + hour; var min = date.getMinutes(); min = (min < 10 ? "0" : "") + min; var sec = date.getSeconds(); sec = (sec < 10 ? "0" : "") + sec; return hour + ":" + min + ":" + sec; }
//Access the router on Express const router = require('express').Router(); const passport = require('passport'); //Access the controllers const controller = require('../controllers/index'); //READ router.get("/appel", passport.authenticate('jwt', { session: false }), function (req, res) { // we protect this route controller.readAppel(req, res); }); module.exports = router;
import React, { useEffect } from "react"; import { useDispatch } from "react-redux"; import { makeStyles } from "@material-ui/core/styles"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import { fetchItems } from "src/redux/items/actions"; import { useItemsByCategory } from "src/redux/items/selectors"; import ItemCard from "src/components/items/ItemCard"; import Link from "src/components/common/CombinedLink"; import NewItemButton from "src/components/items/NewItemButton"; import PrivateComponent from "src/components/auth/PrivateComponent"; const useStyles = makeStyles(theme => ({ title: { marginTop: "1em" } })); export const MainPageCategory = ({ category }) => { const classes = useStyles(); const dispatch = useDispatch(); const items = useItemsByCategory(category); useEffect(() => { dispatch(fetchItems({ category })); }, [dispatch, category]); return ( <> <Grid container spacing={1} className={classes.title} alignItems="center" > <Grid item> <Typography variant="h4">{category}</Typography> <Link to={`/categories/${category}`}>View all</Link> </Grid> <PrivateComponent adminOnly> <Grid item component={NewItemButton} category={category} /> </PrivateComponent> </Grid> <Grid container justify="space-evenly" spacing={0}> {items.slice(0, 4).map(item => ( <ItemCard key={item._id} item={item} /> ))} </Grid> </> ); }; export default MainPageCategory;
import React, {useEffect, useState} from "react"; import { Box, Button, Divider, Grid, LinearProgress, MenuItem, Paper, Select, Table, TableBody, TableCell, TableContainer, TableHead, TablePagination, TableRow, Typography } from "@material-ui/core"; import {Alert} from "@material-ui/lab"; import {makeStyles} from "@material-ui/styles"; import {useDispatch, useSelector} from "react-redux"; import {getBanks} from "../../redux/banks/banks-action-creators"; import {getLogins} from "../../redux/logins/logins-action-creators"; import {useSnackbar} from "notistack"; import BuyLoginDialog from "../modals/buy-login-dialog"; const BankLoginsProducts = () => { const useStyles = makeStyles(theme => { return { container: { paddingTop: 32 }, textField: { marginTop: 8, marginBottom: 8 }, divider: { marginTop: 8, marginBottom: 8 }, button: { borderWidth: 2, borderStyle: 'solid', backgroundColor: theme.palette.primary.main, transition: 'all 300ms ease-in-out', borderRadius: 32, '&:hover': { backgroundColor: theme.palette.primary.dark, } }, logo: { width: 100, height: 100 }, title: { textTransform: 'uppercase' }, } }); const classes = useStyles(); const {logins, loading, error, loginsCount} = useSelector(state => state.logins); const {token} = useSelector(state => state.auth); const {banks} = useSelector(state => state.banks); const [selectedLogin, setSelectedLogin] = useState(null); const [page, setPage] = useState(0); const dispatch = useDispatch(); const [country, setCountry] = useState('All'); const [bank, setBank] = useState('All'); const query = `page=${page + 1}&${country === 'All' ? '' : `country=${country}`}${country !== 'All' && bank !== 'All' ? '&' : ''}${bank === 'All' ? '' : `bank=${bank}`}`; const {enqueueSnackbar} = useSnackbar(); const handlePageChange = (event, page) => { setPage(page); } const handleCountryChange = (event) => { setCountry(event.target.value); } const handleBankChange = (event) => { setBank(event.target.value); } useEffect(() => { dispatch(getBanks(token)); }, [dispatch, token]); useEffect(() => { const showNotification = (message, options) => { enqueueSnackbar(message, options); } dispatch(getLogins(token, query, showNotification)); }, [dispatch, enqueueSnackbar, query, token]); const handleBuyLogin = login => { setSelectedLogin(login); } return ( <div className={classes.container}> {loading && <LinearProgress variant="query"/>} {error && <Alert variant="standard" severity="error" title="Error">{error}</Alert>} <Box className={classes.box}> <Grid container={true} justifyContent="space-between" spacing={2} alignItems="center"> <Grid item={true} xs={12} md={6}> <Typography color="textSecondary" className={classes.title} variant="h5" gutterBottom={true}> Bank Logins ({logins.length}) </Typography> </Grid> <Grid item={true} xs={12} md={3}> <Select onChange={handleCountryChange} fullWidth={true} label={<Typography variant="body2">Country</Typography>} margin="dense" variant="outlined" value={country}> <MenuItem value='All'>Select Country</MenuItem> <MenuItem value="UK">UK</MenuItem> <MenuItem value="USA">USA</MenuItem> <MenuItem value="Canada">Canada</MenuItem> </Select> </Grid> <Grid item={true} xs={12} md={3}> <Select onChange={handleBankChange} fullWidth={true} label={<Typography variant="body2">Type</Typography>} margin="dense" variant="outlined" value={bank}> <MenuItem value='All'>Select Bank</MenuItem> {banks && banks.map((b, i) => { return ( <MenuItem key={i} value={b._id}>{b.name}</MenuItem> ) })} </Select> </Grid> </Grid> <Divider variant="fullWidth" className={classes.divider}/> {logins && logins.length === 0 ? ( <Box> <Typography className={classes.title} color="textSecondary" variant="h6"> No bank logins available </Typography> </Box> ) : ( <TableContainer component={Paper}> <Table> <TableHead> <TableRow> <TableCell>#</TableCell> <TableCell>Type</TableCell> <TableCell>Price</TableCell> <TableCell>Bank</TableCell> <TableCell>Country</TableCell> <TableCell>Balance</TableCell> <TableCell>Includes</TableCell> <TableCell/> </TableRow> </TableHead> <TableBody> {logins && logins.map((login, index) => { return ( <TableRow hover={true} key={index}> <TableCell>{index + 1}</TableCell> <TableCell>{login.type}</TableCell> <TableCell> ${parseFloat(login.price).toFixed(2)} </TableCell> <TableCell>{login.bank.name}</TableCell> <TableCell>{login.bank.country}</TableCell> <TableCell> ${parseFloat(login.balance).toFixed(2)} </TableCell> <TableCell> {login.includes === 0 ? <Typography> Nothing Included </Typography> : ( <Typography variant="body2"> {login.includes.join(', ')} </Typography> )} </TableCell> <TableCell> <Button onClick={() => handleBuyLogin(login)} variant="contained" disableElevation={true} size="small" color="secondary" className={classes.button}> Buy </Button> </TableCell> </TableRow> ) })} </TableBody> <TablePagination count={loginsCount} page={page} onPageChange={handlePageChange} rowsPerPage={20} /> </Table> </TableContainer> )} </Box> { selectedLogin && <BuyLoginDialog bankLogin={selectedLogin} handleClose={() => setSelectedLogin(null)} open={Boolean(selectedLogin)} /> } </div> ) } export default BankLoginsProducts;
import React, { PropTypes } from 'react'; import Markdown from 'rsg-components/Markdown'; import Styled from 'rsg-components/Styled'; import { DOCS_COMPONENTS } from '../../../scripts/consts'; const styles = () => ({ root: { maxWidth: 900, margin: [[0, 'auto']], padding: 30, }, }); export function WelcomeRenderer({ classes }) { return ( <div className={classes.root}> <Markdown text={` # Welcome to React Styleguidist! ## Point Styleguidist to your React components We couldn’t find any components defined in your style guide config or using the default pattern \`src/components/**/*.js\`. Create **styleguide.config.js** file in your project root directory like this: module.exports = { components: 'src/components/**/*.js' }; Read more in the [locating components guide](${DOCS_COMPONENTS}). `} /> </div> ); } WelcomeRenderer.propTypes = { classes: PropTypes.object.isRequired, }; export default Styled(styles)(WelcomeRenderer);
import React from 'react'; import styled from 'styled-components'; const RadioGroup = styled.div` margin-top: 5px; `; const Radio = styled.span` margin-right: 24px; `; const RadioBtn = props => { const value = props.value; const groupName = props.groupName; const displayValue = props.displayValue; const onValueChange = props.onValueChange; const selectedOption = props.selectedOption; return( <Radio className="form-radio"> <label> <input style={{marginRight: '2px'}} type="radio" name={ groupName } value={ value } checked={ selectedOption === value } onChange={ onValueChange } /> <span>{ displayValue }</span> </label> </Radio> ) } const Radios = props => { const groupName = props.groupName; const options = props.options; const onValueChange = props.onValueChange; const selectedOption = props.selectedOption; const heading = props.heading; return( <> { heading && <span>{ heading }</span> } {' '} <RadioGroup className="form-radio-group"> { options && options.length > 0 && options.map((option, index) => ( <RadioBtn key={ index } groupName={ groupName } value={ option.value } displayValue={ option.displayValue } selectedOption={ selectedOption } onValueChange={ onValueChange } /> )) } </RadioGroup> </> ) } export default Radios;
import React from "react"; import Image from "../Image/Image"; import styles from "./card.module.scss"; const Cards = ({ image, title, text, imageType, items }) => { const rootClass = imageType === "wide" ? "col-12 col-md-8" : "col-12 col-md-4"; return ( <div className={rootClass + " mb-2 position"}> <div className={styles.card_container}> <Image url={image} /> <div className={styles.text_overlay}> <span>{text}</span> <h2 className={styles.title}>{title}</h2> <div className="d-inline-flex mt-3"> {items.map((item, key) => ( <div> <img src={item.image} /> </div> ))} </div> </div> </div> </div> ); }; export default Cards;
var fs = require("fs"); fs.readFileSync("input.txt").toString().split("\n").forEach(function (line) { if (line !== "") { readMore(line); } }); function readMore(line) { var result = line.trim(); if (result.length > 55) { result = trimString(result); } console.log(result); } function trimString(str) { var words = str.split(" "), result = ""; if (words[0].length >= 40) { return str.substr(0, 40) + "... <Read More>"; } for (var i = 0; i < words.length; i++) { if (result.length + words[i].length + 1 <= 40) { result += " " + words[i]; } else { break; } } return result.trim() + "... <Read More>"; }
require('./config'); const Schema = require('./model-poke-delete-name');
import React from 'react'; const Results = ({ result }) => { return ( <> <div className="card"> <div className="card-header bg-danger text-dark">{result.title}</div> <div className="card-body"> <div className="row"> <div className="col-sm-3"> <img src={result.image_url} alt="img" style={{ width: "100%" }} /> </div> <div className="col-sm-9"> <h5>Score: {result.score}</h5> <h5>Episodes: {result.episodes}</h5> <p>Description: {result.synopsis}</p> </div> </div> </div> </div> </> ); }; export default Results;
module.exports = { // The number of days to run the initial backtest on before starting backtestRange: 1, // The approximate number of candles between updating the strategy settings updateSettingsTime: 24, paperTrader: true, liveTrader: false, // Some tests will trade only once yet still be the most profitable. That isnt // sustainable. This will filter out those invalid test settings minimumAllowedTrades: 4, // This should match the config in gekkos web/vue/UIconfig.js, making sure // that port is available. apiEndpoint: 'http://127.0.0.1:3000', // Port for the frontend to run on. port: 8080, // verbose, debug, silent logging: 'debug', watch: { exchange: 'poloniex', currency: 'BTC', asset: 'XEM', }, genetic: { iterations: 10, size: 40, crossover: 0.9, mutation: 0.8, skip: 0, fittestAlwaysSurvives: true } }
function vaciar1() { document.getElementById("dolares").value=""; } function convertir() { var t1=document.getElementById("dolares"); var pp=(t1.value)*565; pp=pp.toFixed(2); document.getElementById("res").innerHTML=pp+" colones"; }
import React, { Component } from 'react'; import NavBar from '../NavBar'; import ShowOrders from '../ShowOrders'; //bootstrap style imports import Tabs from 'react-bootstrap/Tabs'; import Tab from 'react-bootstrap/Tab'; class Deliver extends Component { constructor() { super(); this.state = { orders: [], toDeliver: [], delivered: [] } } fetchApi = (url, data, meth) => { fetch(url, { method: meth, body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }).then(res => res.json()) .then(response => console.log('mongoDB responde', JSON.stringify(response))) .catch(error => console.log('Error ', error)); } componentDidMount() { const url = "https://backbq.herokuapp.com/order"; fetch(url) .then(res => res.json()) .then((orderAsJson) => { this.setState({ orders: orderAsJson }, console.log('mongoDB orders', orderAsJson)) }) } render(){ /* quiza deberia llenar estas variables desde el componente padre const { toDeliver, delivered } = this.state*/ let toDeliver; let delivered; if(this.state.orders.orders){ toDeliver = this.state.orders.orders.filter((order)=>{return (order.status === 'ready')}); console.log(toDeliver); delivered = this.state.orders.orders.filter((order)=>{return (order.status === 'delivered')}); } return( <container> <div className="row"> <div className="row"> <NavBar /> </div> </div> <div className="row"> <div className="col"> <h2>Entregas</h2> <Tabs defaultActiveKey="Orders" id="uncontrolled-tab-example"> <Tab eventKey="Orders" title="Para entregar"> <div className="row"> <div className="card-container"> {this.state.orders.orders ? toDeliver.map((order, index) => ( <ShowOrders id={order._id} name={order.clientname} items={order.items} status={order.status} onChangeStatus={this.onChangeStatus} /> )) : console.log('waiting for orders response')/*implementar animacion de espera*/} </div> </div> </Tab> <Tab eventKey="DeliveredOrders" title="Entregadas"> <div className="row"> <div className="card-container"> {this.state.orders.orders ? delivered.map((order, index) => ( <ShowOrders id={order._id} name={order.clientname} items={order.items} status={order.status} onChangeStatus={this.onChangeStatus} /> )) : console.log('waiting for orders response')} </div> </div> </Tab> </Tabs> </div> </div> </container> ) } } export default Deliver;
/* Create a function that takes in an array (slot machine outcome) and returns true if all elements in the array are identical, and false otherwise. The array will contain 4 elements. */ function testJackpot(result) { for(let i=1; i<result.length; i++){ if(result[i] != result[i-1]){ return false; } } return true; // return new Set(result).size === 1; }
import moment from "moment/moment"; export const DateFormat = 'YYYY-MM-DD'; export const TimeFormat = 'HH:mm'; export const mappedDateAndTimeWithValues = (values) => { return { ...values, 'startDate': values['startDate'].format(DateFormat), 'endDate': values['endDate'].format(DateFormat), 'startTime': values['startTime'].format(TimeFormat), 'endTime': values['endTime'].format(TimeFormat), } }; export const mapDateAndTimeToMoment = (event) => { return { ...event, startDate: moment(event.startDate, DateFormat), endDate: moment(event.endDate, DateFormat), startTime: moment(event.startTime, TimeFormat), endTime: moment(event.endTime, TimeFormat), } };
export const UPLOAD_NEWRECIPE_START = 'UPLOAD_NEWRECIPE_START'; export const UPLOAD_NEWRECIPE_SUCCESS = 'UPLOAD_NEWRECIPE_SUCCESS'; export const UPLOAD_NEWRECIPE_FAIL = 'UPLOAD_NEWRECIPE_FAIL'; export const FETCH_RECIPES_START = 'FETCH_RECIPES_START'; export const FETCH_RECIPES_SUCCESS = 'FETCH_RECIPES_SUCCESS'; export const FETCH_RECIPES_FAIL = 'FETCH_RECIPES_FAIL'; export const AUTH_START = 'AUTH_START'; export const AUTH_SUCCESS = 'AUTH_SUCCESS'; export const AUTH_FAIL = 'AUTH_FAIL'; export const AUTH_LOGOUT = 'AUTH_LOGOUT'; export const SET_AUTH_REDIRECT_PATH = 'SET_AUTH_REDIRECT_PATH';
Template.reports.events({ "submit #report-form": function(event, template) { event.preventDefault() var nameFile = 'SpaceCadet_Dockings_' + new Date().getTime() + '.csv'; var startAnal = event.target.startAnal.value var endAnal = event.target.endAnal.value if(startAnal && endAnal) { var startAnal = new Date(startAnal) var endAnal = new Date(endAnal) Meteor.call('mart/report/carts', startAnal, endAnal, function(err, fileContent) { if(fileContent){ var blob = new Blob([fileContent], {type: "text/plain;charset=utf-8"}); saveAs(blob, nameFile); } }); } }, "click .export-properties": function(event, template) { var nameFile = 'SpaceCadet_Properties_' + new Date().getTime() + '.csv'; Meteor.call('mart/report/storefronts', function(err, fileContent) { if(fileContent){ var blob = new Blob([fileContent], {type: "text/plain;charset=utf-8"}); saveAs(blob, nameFile); } }); }, "click .export-spaces": function(event, template) { var nameFile = 'SpaceCadet_Spaces_' + new Date().getTime() + '.csv'; Meteor.call('mart/report/products', function(err, fileContent) { if(fileContent){ var blob = new Blob([fileContent], {type: "text/plain;charset=utf-8"}); saveAs(blob, nameFile); } }); } });
/** * Created by dell on 2016/8/11. */ jQuery( document ).ready(function( $ ) { $('#abook').click(function () { $('#book').toggle(); }); $('#asearch').click(function(){ $('#search').toggle(); }); $('#search_btn').click(function(){ $.ajax({ type: "GET", url: "/book/", data:{'search_book':$('input[name=search_book]').val()}, success:function(data){ var html = ""; //第一个each:index为booksObj values为Object $.each(data,function(index,values){ //第二个each:index为所有匹配到的笔记本个数 value为Object $.each(values,function(index,value){ //第三个each:index为字段名title val为每个字段对应的title值 $.each(value,function(index,val){ html += "<form method='GET' action='/biji/'><div class='book_list' ><button type='submit' class='book_list_btn'>"+val+"</button></div><input type='hidden' name='search_title' value='"+val+"'/></form>"; }); }); }); $('#book_list').html(html); } }); }); });
const { users } = require('../services'); const { httpStatus } = require('../constants'); const get = async (req, res) => { const { username } = req.params; const { success, error, user, code } = await users.get(username); if (!success) { return res.status(code).send({ error }); } return res.json(user); }; const register = async (req, res) => { const { username } = req.params; const { success, error, code } = await users.register({ username }); if (!success) { return res.status(code).send({ error }); } return res.json({ success: true }); }; module.exports = { get, register, };
const Job = require('../lib/models/job.model'); const assert = require('chai').assert; const testInvalid = require('./test-invalid')(Job); let testJob = { jobType: 'Unskilled', jobLevel: 'Mid-level', monthlySalary: 1500, promotionInterval: 24 }; describe('tests Job Model', () => { it('validation fails without jobType value', () => { return testInvalid({ jobLevel: 'Mid-level', monthlySalary: 1500, promotionInterval: 24 }); }); it('validation fails without jobLevel value', () => { return testInvalid({ jobType: 'Unskilled', monthlySalary: 1500, promotionInterval: 24 }); }); it('validation fails without monthlySalary value', () => { return testInvalid({ jobType: 'Unskilled', jobLevel: 'Mid-level', promotionInterval: 24 }); }); it('validation fails without promotionInterval value', () => { return testInvalid({ jobType: 'Unskilled', jobLevel: 'Mid-level', monthlySalary: 1500 }); }); it('validation passes with all values', () => { return new Job(testJob) .validate(); }); });
'use strict'; angular.module('AdminApp') .controller('AgentCtrl',function AgentCtrl($rootScope,$scope,$http,Regions,Agents,$window){ loading(); $scope.ph_numbr = /^(\d{3})[- ](\d{3})[- ](\d{4})$/; function getAllAgents(){ return Agents.query(); } function loading() { var list =[]; Regions.query(function(regions){ for(var i=0; i<regions.data.length; i++){ list.push({"text" : regions.data[i].name}); } Agents.query(function(result){ $scope.agents = result; $scope.region_tags = regions.data; }); }); } $scope.create = function(isValid){ Agents.save($scope.agent,function(result){ if(result.status == 'ok'){ $http.post('/api/agent/register/sendEmail',{agent: $scope.agent, password:$scope.agent.password}) .success(function(data,status,headers,config){ ShowGritterCenter('System Notification','Agent has been created'); setInterval(function(){ $window.location='/admin/agent/detail/' + result.data._id; }, 2000); }) } else if(result.status == 'exist'){ ShowGritterCenter('System Notification',result.messages); } else { ShowGritterCenter('System Notification','Agent create fail'); } }) } $scope.generate = function() { $scope.agent.password = randomPassword(8); } function randomPassword(length) { var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP1234567890"; var pass = ""; for (var x = 0; x < length; x++) { var i = Math.floor(Math.random() * chars.length); pass += chars.charAt(i); } $("#agent_pwd").get(0).type ='text'; return pass; } }) .controller('AgentDetailCtrl',function AgentDetailCtrl($rootScope,$scope,$http,Agents,Students,StudentByAgent,Meterials, Constants,$window,$document){ var agent_id = url_params.id; loading(); $scope.ph_numbr = /^(\d{3})[- ](\d{3})[- ](\d{4})$/; function loading() { if(agent_id !=null){ Agents.get({id:agent_id}, function(result){ $scope.agent = result.data; Students.getStudentsByAgent({id : $scope.agent._id}, function(result){ $scope.students = result.data; }); }); Constants.get({name:"Country"}, function(result){ var regions = result.data; var list =[] for(var i=0; i<regions.length; i++){ list.push({"name" : regions[i]}); } $scope.regionsList = list; }); Meterials.getMaterialByAgentId({id:agent_id},function(result){ if(result.status ="ok"){ $scope.materials = result.data; console.log($scope.materials ); } }); } } $scope.update = function(isValid) { Agents.update($scope.agent, function(result){ if(result.status == 'ok'){ ShowGritterCenter('System Notification','Agent has been updated'); setInterval(function(){ $window.location='/admin/agent/detail/' + agent_id; }, 2000); }else{ ShowGritterCenter('System Notification','Material document update fail : ' + result.messages.err); } }) } $scope.resetpwd = function(isValid) { $scope.agent.password = $scope.resetpassword; Agents.update($scope.agent, function(result){ if(result.status == 'ok'){ ShowGritterCenter('System Notification','Agent passowrd has been updated'); $http.post('/api/agent/resetpassword/sendEmail',{agent: $scope.agent}) .success(function(data,status,headers,config){ setInterval(function(){ $window.location='/admin/agent/detail/' + $scope.agent._id; }, 2000); }) .error(function(data,status,headers,config){ console.log("fail to send registration email") }); } }) } $scope.createStudent = function(isValid){ $scope.student.agent_id = agent_id; StudentByAgent.save($scope.student,function(result){ var message = result.messages; $rootScope.returnMessage = message; $window.location='/admin/agent/detail/'+ agent_id; }) } $scope.generate = function() { $scope.resetpassword = randomPassword(8); } function randomPassword(length) { var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP1234567890"; var pass = ""; for (var x = 0; x < length; x++) { var i = Math.floor(Math.random() * chars.length); pass += chars.charAt(i); } $("#agent_pwd").get(0).type ='text'; return pass; } });
const express = require("express"); const { Client } = require("pg"); const router = express.Router(); const bodyParser = require("body-parser"); const queries = require("../db/queries"); const bcrypt = require("bcrypt"); const middleware = require("./middleware"); const transaction = require("../db/transaction"); router.use(bodyParser.urlencoded({ extended: false })); const jsonParser = bodyParser.json(); //console.log("bodyParser", bodyParser); router.get("/:email", (req, res) => { transaction .getPool() .connect() .then(client => { client .query(queries.begin) .then(() => { const sql = queries.getUserDetail; let params = [req.params.email]; return client.query(sql, params); }) .then(results => { res.status(200).json(results); transaction.commit(client); }) .catch(err => { console.log("error", err); transaction.rollback(client); }) .then(() => { client.query(queries.end); client.release(); }); }); }); router.post("/", (req, res, next) => { //console.log(req.body); //console.log(req.files.image); //const client = new Client(); //if (middleware.validUser(req.body)) { if (req.headers.cookie) { // UPDATE user transaction .getPool() .connect() .then(client => { client .query(queries.begin) .then(() => { const sql = queries.updateUserDetail; let params = [ req.body.email, req.body.name, req.body.surname, req.body.country, req.body.city, req.body.phone, req.body.image ]; return client.query(sql, params); /*bcrypt .hash(req.body.password, 10) .then(hash => { const sql = queries.updateUserDetail; let params = [ req.body.email, //hash, req.body.name, req.body.surname, req.body.country, req.body.city, req.body.phone, req.files.image ]; return client.query(sql, params); }) .then(results => { console.log(results); res.status(200).json(results); transaction.commit(client); }) .catch(err => { console.log("error", err); transaction.rollback(client); }) .then(() => { client.release(); });*/ }) .then(results => { console.log(results); res.status(200).json(results); transaction.commit(client); }) .catch(err => { console.log("error", err); transaction.rollback(client); }) .then(() => { client.release(); }); }); } else { console.log("req.body: ", req.body); if (middleware.validUser(req.body)) { // INSERT user transaction .getPool() .connect() .then(client => { client .query(queries.begin) .then(() => { // Unique email const sql = queries.getEmail; let params = [req.body.email]; return client.query(sql, params); }) .then(results => { if (results.rowCount === 0) { // hashPassword(plaintext, saltRounds) bcrypt .hash(req.body.password, 10) .then(hash => { const sql = queries.postUser; let params = [ req.body.email, hash, req.body.name, req.body.surname, new Date(req.body.birth_date), req.body.country, req.body.city, req.body.phone, req.body.image ]; return client.query(sql, params); }) .then(id => { console.log(id); res.status(200).json(id); transaction.commit(client); }) .catch(err => { console.log("error", err); transaction.rollback(client); }) .then(() => { client.release(); }); } else { next(new Error("Email in use!")); } }) .catch(err => { console.log("error", err); }); }); } else { next(new Error("Invalid user!")); } } /*} else { next(new Error("Invalid user!")); }*/ }); module.exports = router;
const excelToJson = require('convert-excel-to-json'); const fs = require('fs'); const path = require('path'); var List = [ {'index':2,'WIN':'WIN-VNet Name','LNX':'LNX-VNet Name'}, {'index':6,'WIN':'WIN-Subnet Name','LNX':'LNX-Subnet Name'}, {'index':14,'WIN':'WIN-VM Name','LNX':'LNX-VM Name'}, {'index':16,'WIN':'WIN-VM Size','LNX':'LNX-VM Size'}, {'index':23,'WIN':'WIN-VM Publisher','LNX':'LNX-VM Publisher'}, {'index':24,'WIN':'WIN-VM Offer','LNX':'LNX-VM Offer'}, {'index':25,'WIN':'WIN-VM SKU','LNX':'LNX-VM SKU'}, {'index':26,'WIN':'WIN-Computer Name','LNX':'LNX-Computer Name'}, {'index':27,'WIN':'WIN-Username','LNX':'LNX-Username'}, {'index':28,'WIN':'WIN-Password','LNX':'LNX-Password'}] var formatted_json = {}; var sheet_name = 'Virtual Machine (VM)' var columns_to_fetch_data; var result; var no_of_VMs_to_be_created; var excel_file; //Convert "Virtual Machine (VM)" sheet into JSON function get_json() { try{ no_of_VMs_to_be_created = columns_to_fetch_data.length var columnKeys = {B: 'key'} var i=1 columns_to_fetch_data.forEach(key => { columnKeys[key] = `value${i}` i=i+1 }); var JSON = excelToJson({ source: fs.readFileSync(excel_file), header:{ rows: 1 }, sheets: [sheet_name], range: 'A1:L34', columnToKey: columnKeys }); result = JSON[sheet_name] }catch(err){ console.log('Error occurred while getting JSON of VM sheet') console.log('Error: ',err) } } //Take first RGName and RGLocation function insert_rgName_and_Location_into_json() { try{ var location_for_all_VMs=[]; for (let i=0; i<no_of_VMs_to_be_created; i++) { location_for_all_VMs.push(result[1].value1) } formatted_json[result[0].key] = result[0].value1 //Resource Group Name formatted_json[result[1].key] = result[1].value1 //Resource Group Location formatted_json[result[3].key] = location_for_all_VMs //Virtual Network Location formatted_json[result[15].key] = location_for_all_VMs //Virtual Machine Location }catch(err){ console.log('Error occurred while inserting RG-Name and RG-Location in VM-Excel') console.log('Error: ',err) } } //Format Address Space (VNet,Subnet,Firewall) function get_address_space() { try{ //Virtual Network Address Space, Subnet Address Space var list = []; list.push([result[4],result[5],'Virtual Network Address Space']); list.push([result[7],result[8],'Subnet Address Space']); list.forEach(element => { delete element[0].key delete element[1].key var values = []; for (let i=0; i<no_of_VMs_to_be_created; i++) { values.push(element[0][`value${i+1}`] + '/' + element[1][`value${i+1}`]) } formatted_json[element[2]] = values //VNet,Subnet }); //Firewall Subnet Address Space var subnet_ip_addresses = result[11] delete subnet_ip_addresses.key var subnet_ip_addresses_cidr = result[12] delete subnet_ip_addresses_cidr.key var values2 = [] for (let i=0; i<no_of_VMs_to_be_created; i++) { if (subnet_ip_addresses[`value${i+1}`] && subnet_ip_addresses_cidr[`value${i+1}`]) { values2.push(subnet_ip_addresses[`value${i+1}`] + '/' + subnet_ip_addresses_cidr[`value${i+1}`]) } } var unique_firewall_subnet_address_space = [] values2.forEach(element => { if(!unique_firewall_subnet_address_space.includes(element)) { unique_firewall_subnet_address_space.push(element) } }); formatted_json['Firewall Subnet Address Space'] = unique_firewall_subnet_address_space //Firewall }catch(err){ console.log('Error occurred while getting Address Space') console.log('Error: ',err) } } //Seperating resources on the basis of availability set function seperating_resources_for_win_and_lnx() { try{ List.forEach(element => { formatted_json[element["WIN"]] = [] formatted_json[element["LNX"]] = [] }); formatted_json['Virtual Machine Location for Win']=[] for (let i=0; i<no_of_VMs_to_be_created; i++) { if ((result[23][`value${i+1}`]).includes('MicrosoftWindows')) { List.forEach(element => { formatted_json[element["WIN"]].push((result[element.index])[`value${i+1}`]) }); formatted_json['Virtual Machine Location for Win'].push(result[15][`value${i+1}`]) } else { List.forEach(element => { formatted_json[element["LNX"]].push((result[element.index])[`value${i+1}`]) }); } } }catch(err){ console.log('Error occurred while sepearting resources for WIN and LINUX') console.log('Error: ',err) } } function formatting_json_for_remanining_fields() { try{ var row_number = [2,6,10,13,14,17,18,19,20,21,22] row_number.forEach(num => { var data = result[num] var key = data.key delete data.key var values = Object.values(data); values = values.filter( function( val ) { return val !== ''; }); formatted_json[key] = values }); // Azure Firewall Vnet var firewallName_data = result[9] delete firewallName_data.key var unique_firewallName_data = [] var indexes = [] for(let i=1; i<no_of_VMs_to_be_created+1; i++){ if(firewallName_data[`value${i}`] && (!unique_firewallName_data.includes(firewallName_data[`value${i}`]))) { unique_firewallName_data.push(firewallName_data[`value${i}`]) indexes.push(`value${i}`) } } formatted_json['Azure Firewall Vnet'] = [] indexes.forEach(index => { formatted_json['Azure Firewall Vnet'].push(result[2][index]) }); formatted_json['Firewall Name*'] = unique_firewallName_data //Tags key-value var list = [] list.push([result[29],result[30]]) //Tag1 list.push([result[31],result[32]]) //Tag2 list.forEach(element => { var tag_keys_key= element[0].key delete element[0].key var tag_values_key= element[1].key delete element[1].key formatted_json[tag_keys_key]=[] //Tag 1 Key or Tag 2 Key formatted_json[tag_values_key]=[] //Tag 1 Value or Tag 2 Value var values= Object.values(element[1]) if(values.length >0) { for(var i=0; i<values.length; i++){ formatted_json[tag_keys_key].push((Object.values(element[0]))[0]) formatted_json[tag_values_key].push(values[i]) } }else{ formatted_json[tag_keys_key].push("") formatted_json[tag_values_key].push("") } }); //If any value is [] then replace [] --by--> [""] List.forEach(ele => { if(formatted_json[ele["WIN"]].length===0){ formatted_json[ele["WIN"]].push("") } if(formatted_json[ele["LNX"]].length===0){ formatted_json[ele["LNX"]].push("") } }); }catch(err){ console.log('Error occurred while formatting json for VM sheet remaining fields') console.log('Error: ',err) } } function get_formatted_json(file,columns) { try{ excel_file = path.join(__dirname, `../../../uploads/${file}`); columns_to_fetch_data = columns get_json(); insert_rgName_and_Location_into_json(); get_address_space(); seperating_resources_for_win_and_lnx(); formatting_json_for_remanining_fields(); columns_to_fetch_data = [] return formatted_json }catch(err){ console.log('Error occurred while formatting JSON of VM sheet.') console.log('Error: ',err) } } module.exports = { get_formatted_json }
const DBF = require('stream-dbf'); const createCsvWriter = require('csv-writer').createObjectCsvWriter; const HEADER = [ { id: 'POSTALCODE', title: 'POSTALCODE'}, { id: 'IFNSFL', title: 'IFNSFL'}, { id: 'TERRIFNSFL', title: 'TERRIFNSFL'}, { id: 'IFNSUL', title: 'IFNSUL'}, { id: 'TERRIFNSUL', title: 'TERRIFNSUL'}, { id: 'OKATO', title: 'OKATO'}, { id: 'OKTMO', title: 'OKTMO'}, { id: 'UPDATEDATE', title: 'UPDATEDATE'}, { id: 'HOUSENUM', title: 'HOUSENUM'}, { id: 'ESTSTATUS ', title: 'ESTSTATUS'}, { id: 'BUILDNUM', title: 'BUILDNUM'}, { id: 'STRUCNUM', title: 'STRUCNUM'}, { id: 'STRSTATUS', title: 'STRSTATUS'}, { id: 'HOUSEID', title: 'HOUSEID'}, { id: 'HOUSEGUID', title: 'HOUSEGUID'}, { id: 'AOGUID', title: 'AOGUID'}, { id: 'STARTDATE', title: 'STARTDATE'}, { id: 'ENDDATE', title: 'ENDDATE'}, { id: 'STATSTATUS', title: 'STATSTATUS'}, { id: 'NORMDOC', title: 'NORMDOC'}, { id: 'COUNTER', title: 'COUNTER'}, { id: 'CADNUM', title: 'CADNUM'}, { id: 'DIVTYPE', title: 'DIVTYPE'} ] const parseHouse = (filename) => new Promise((resolve, reject) => { const FILE_NAME = filename; // let data = []; let data = {}; let index = 0; const limit = 100000; let part = 1; const parser = new DBF(`./files/fias_dbf/${FILE_NAME}`, {encoding: 'cp866', /*withMeta: false, lowercase: true , */}); const stream = parser.stream; stream.on('data', async function(record) { // Создание поля в объекте if (!data.hasOwnProperty(`part_${part}`)) { data[`part_${part}`] = []; } data[`part_${part}`].push(record); index = record["@sequenceNumber"]; // (record["@sequenceNumber"] < limit * part) ? part : part++; // console.log(`============= Читаем запись ${record["@sequenceNumber"]} из файла ${FILE_NAME} =============`); if (record["@sequenceNumber"] == limit * part) { // console.log(`${filename}, part ${part}`) const writeCSV = () => new Promise ((resolve, reject) => { const csvWriter = createCsvWriter({ path: `./files/csv/house/${FILE_NAME}_part_${part}.csv`, header: [...HEADER] }); csvWriter .writeRecords(data[`part_${part}`]) .then(() => { console.log(`======== ${FILE_NAME}_part_${part}.csv created ========`); resolve(); }); }) stream.pause() await writeCSV(); delete data[`part_${part}`] part++; stream.resume(); } }); stream.on('error', reject); stream.on('end', () => { console.log('finished'); const test = Object.keys(data); console.log(test) // for (let item of test) { // console.log(data[item].length); // console.log(item); const csvWriter = createCsvWriter({ // path: `./files/csv/house/${FILE_NAME}_${item}.csv`, path: `./files/csv/house/${FILE_NAME}_part_${part}.csv`, header: [ { id: 'POSTALCODE', title: 'POSTALCODE'}, { id: 'IFNSFL', title: 'IFNSFL'}, { id: 'TERRIFNSFL', title: 'TERRIFNSFL'}, { id: 'IFNSUL', title: 'IFNSUL'}, { id: 'TERRIFNSUL', title: 'TERRIFNSUL'}, { id: 'OKATO', title: 'OKATO'}, { id: 'OKTMO', title: 'OKTMO'}, { id: 'UPDATEDATE', title: 'UPDATEDATE'}, { id: 'HOUSENUM', title: 'HOUSENUM'}, { id: 'ESTSTATUS ', title: 'ESTSTATUS'}, { id: 'BUILDNUM', title: 'BUILDNUM'}, { id: 'STRUCNUM', title: 'STRUCNUM'}, { id: 'STRSTATUS', title: 'STRSTATUS'}, { id: 'HOUSEID', title: 'HOUSEID'}, { id: 'HOUSEGUID', title: 'HOUSEGUID'}, { id: 'AOGUID', title: 'AOGUID'}, { id: 'STARTDATE', title: 'STARTDATE'}, { id: 'ENDDATE', title: 'ENDDATE'}, { id: 'STATSTATUS', title: 'STATSTATUS'}, { id: 'NORMDOC', title: 'NORMDOC'}, { id: 'COUNTER', title: 'COUNTER'}, { id: 'CADNUM', title: 'CADNUM'}, { id: 'DIVTYPE', title: 'DIVTYPE'} ] }); csvWriter // .writeRecords(data[item]) .writeRecords(data[`part_${part}`]) .then(() => console.log(`${FILE_NAME}_part_${part}.csv created`)) // } // console.log("Закончили разбор файла"); resolve(index); }); }); module.exports = parseHouse;
const { runRequestAt } = require('../libs'); describe('libs.runRequestAt', () => { test.each([ 'unsupported', 'shibuya', 'kawasaki', ])( 'runRequestAt(date, %s) throw Error for unsupported location', (location) => { expect(() => runRequestAt(new Date(), location)).toThrow(); }, ); test.each([ ['2018-09-01', 'bonfim', '2018-07-01'], ['2019-01-31', 'bonfim', '2018-11-30'], // there is no 31 Nov ['2018-04-31', 'bonfim', '2018-03-01'], // there is no 31 Feb ['2018-04-30', 'bonfim', '2018-02-28'], ['2020-02-29', 'bonfim', '2019-12-29'], // check leap year in 2020 ['2020-04-31', 'bonfim', '2020-03-01'], ['2020-04-30', 'bonfim', '2020-02-29'], ])( 'runRequestAt(%s, %s) should return %s', (reservationDate, location, expected) => { const actionableDate = runRequestAt(reservationDate, location); const expectedDate = new Date(expected); expect(actionableDate.toISOString()).toEqual(expectedDate.toISOString()); }, ); });
const { scrollY, vertical, flex, layerParent, fillParent } = require('csstips/lib') module.exports = ({ colors = {} } = {}) => { return [ // padding(em(2), em(8)), vertical, // horizontal, flex, fillParent, layerParent, { $debugName: 'App', color: colors.default, fontSize: '2.2rem', '& .container': { backgroundColor: colors.background, backgroundPosition: 'center', // ...fillParent, // background: 'red' // ...scrollY // minHeight: '40vh', // marginTop: 'calc(60vh + 11rem)', // maxWidth: '120rem', // margin: '0 auto 8rem', // '& > *': { // // background: 'red' // // ...scrollY // // padding: '2.4rem', // }, }, '& .banner': { // ...pageTop, height: '100vh', width: '100%', position: 'fixed', // backgroundPosition: 'center 11rem', // backgroundSize: 'auto 40rem', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', marginTop: '11rem' }, '& h2': { marginBottom: '2rem', // fontSize: '2.4rem' }, '& small': { fontSize: '1.5rem' }, // backgroundSize: 'contain', // backgroundRepeat: 'no-repeat', // ...layerParent, // backgroundAttachment: 'fixed', // backgroundPosition: '0 8em', // // background // // '& > img': { // // maxHeight: viewHeight(42) // // } // ...verticallySpaced(em(1)) } ] }
describe('Autocomplete Directive', function () { // This is NOT a complete set of tests! // but there's a handful to show that the overall testing-framework works, // and the autocomplete opens at appropriate times // Helper functions for dealing with DOM manipulation var setCursor = function(e, position) { if (e.setSelectionRange) { e.focus(); e.setSelectionRange(position, position); } /* WebKit */ else if (e.createTextRange) { var range = e.createTextRange(); range.collapse(true); range.moveEnd('character', position); range.moveStart('character', position); range.select(); } /* IE */ }; var typeKey = function (element, char) { var e = $.Event("keydown"); e.which = char.charCodeAt(0); element.trigger(e); var oldVal = $(element).val(); $(element).focus(); $(element).val(oldVal+char); $(element).text(oldVal+char); setCursor($(element)[0], oldVal.length+1); var e2 = $.Event("keyup"); e2.which = char.charCodeAt(0); element.trigger(e2); }; var typeString = function(element, str, done) { $.each(str.split(''), function(i, c) { typeKey(element,c); }); }; // end of helper functions var doc, element, scope, listElement; beforeEach(module('h_autocomplete')); beforeEach(function(done) { inject(function ($compile, $rootScope, $httpBackend) { // get json-data for testing without using webserver $httpBackend.expectGET('/data.json').respond(readJSON('data.json')); scope = $rootScope.$new(); scope.$on('autocompleteReady', function() { done(); // asynchronous wait for jquery to finish before testing }); doc = $compile('<div><textarea ng-autocomplete></textarea></div>')(scope); // this is hacky but it allows easier DOM testing in karma, // by using karma's own document context. $('body').append(doc); $httpBackend.flush(); }); }); beforeEach(function() { // element is the main textarea element = doc.children(':first'); // listElement is the <ul> list of users listElement = element.next('.textcomplete-dropdown'); }); it('should have a list of names in the DOM, after the textarea', function() { expect(listElement.length).toEqual(1); }); it('should not be visible initially', function() { expect(listElement.css('display')).toEqual('none'); }); describe('behavior after typing "martin"', function() { beforeEach(function() { typeString(element, 'martin'); }); it('should now be visible', function() { expect(listElement.css('display')).toEqual('block'); }); }); describe('behavior after typing @', function() { beforeEach(function() { typeString(element, '@'); }); it("should now be visible", function() { expect(listElement.css('display')).toEqual('block'); }); }); afterEach(function() { element.parent().remove(); }); });
require('./bootstrap') import Vue from 'vue' import Module from './sa/Module' import VueResource from 'vue-resource' import router from './sa/routes' // import store from './HumanResource/store' import ElementUI from 'element-ui' import locale from 'element-ui/lib/locale/lang/en' import 'element-ui/lib/theme-default/index.css' Vue.use(ElementUI, { locale }) Vue.config.productionTip = true Vue.use(VueResource) /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<Module />', components: { Module } })
/* Name:Jeramie Brehm Date:06MAR2014 Class & Section: WIA-1403 Comments: "HTML5 Canvas Drawing" */ window.onload = function(){ if(Modernizr.canvas){ /******************************************* HTML5 Shape Drawing Activity 1. Setup the canvas and 2d context 2. Draw out each shape in the sections below ********************************************/ /******************************************* FILE SETUP // Setup up 7 different Canvases in index.html one for each problem. //Link Modernizr.js // Link the main.js file // Setup the call to that canvas and get it's 2d context //Use Modernizr to verify that your browser supports canvas, include a fallback message /******************************************* PART 1 Draw a rectangle starting at point (0 ,0) That has a width of 50 px and a heigh of 100px Set the color of the rectangle to a shade of blue. Set the stroke color to black and the dimension of the stroke are the same as the rectangle. Reminder - set the style first then draw. ********************************************/ var recTangle = document.getElementById("rectangle"); if(recTangle){ var tangle = recTangle.getContext('2d'); if (tangle){ tangle.strokeStyle = "#000"; tangle.fillStyle = "lightblue"; tangle.lineWidth = 10; tangle.fillRect(0,0,50,100); tangle.strokeRect(0,0,50,100); //stroke looks crazy due to top and left side being cut in half because it's being drawn outside of the canvas } } /******************************************* PART 2 Draw a circle starting at point (50 ,50) That has a radius of 20 px Set the color of the circle to a shade of red and set the alpha to .5 Set the stroke color to black and use a radius of 30px for this circle. Reminder - set the style first then draw. Use the arc method ********************************************/ var circles = document.getElementById("circleArcs"); if(circles){ var arcs = circles.getContext('2d'); if (arcs){ arcs.fillStyle = 'rgba(255, 0, 0, .5)'; arcs.lineWidth = 3; arcs.beginPath(); arcs.arc(50,50,20,0,2*Math.PI,true); arcs.fill(); arcs.strokeStyle = 'black'; arcs.beginPath(); arcs.arc(50,50,30,0,2*Math.PI,true); arcs.stroke(); } } /******************************************* PART 3 Practice using Path drawing. Create a 5-point star shaped pattern using the lineTo method. Begin this shape at (100, 100) Height and width and color are up to you. ********************************************/ var multiPaths = document.getElementById("path"); if(circles){ var star = multiPaths.getContext('2d'); if (star){ star.strokeStyle = 'blue'; star.lineWidth = 5; star.lineJoin = 'round'; star.beginPath(); star.moveTo(100,100); star.lineTo(150,100); star.lineTo(170,50); star.lineTo(190,100); star.lineTo(240,100); star.lineTo(200,135); star.lineTo(220,185); star.lineTo(175,155); star.lineTo(137,185); star.lineTo(145,135); star.closePath(); star.stroke(); } } /******************************************* PART 4 Practice drawing with Bezier curves. Try drawing the top to an umbrella. This should have one large arc (a half circle) on the top and scalloped edges on the bottom. Position, height, width and color are your choice. Do not overlap any other object. ********************************************/ var bezier = document.getElementById("bezierCurves"); if(bezier && bezier.getContext){ var bzc = bezier.getContext('2d'); if (bzc){ bzc.strokeStyle='#000'; bzc.lineWidth = 5; bzc.beginPath(); bzc.moveTo(25,250); //bezierCurveTo(cx,cy,cx2,cy2,x,y) bzc.bezierCurveTo(75,140,175,140,225,250); bzc.bezierCurveTo(190,240,200,240,175,250); bzc.bezierCurveTo(140,240,150,240,125,250); bzc.bezierCurveTo(90,240,100,240,75,250); bzc.bezierCurveTo(40,240,50,240,25,250); bzc.closePath(); bzc.stroke(); } } /******************************************* PART 5 Practice using text. Draw text into your canvas. It can said whatever you would like in any color. ********************************************/ var render = document.getElementById("textRender"); if(render && render.getContext){ var text = render.getContext('2d'); if(text){ var squishyFilling = 'UNLEASH THE FURY'; text.font = '25pt Impact'; text.fillStyle = 'red'; text.fillText(squishyFilling,20,150); } } /******************************************* PART 6 Pixel manipulation. Draw the image logo.png into the canvas in the following 3 ways. 1. The image exactly as it is. 2. Shrink the image by 50% 3. Slice a section of the logo out and draw that onto the canvas. Reminder to use the drawImage method for all 3 of the ways. ********************************************/ var imgMat = document.getElementById("imgDraw"); if(imgMat && imgMat.getContext){ var pic = imgMat.getContext('2d'); if(pic){ var photo = document.getElementById('image1'); pic.drawImage(photo, 0,0); //photo does not display well in canvas due to size being 3k x 1.1k without resizing but implemented "as is". pic.drawImage(photo,0,0,1650,550); //photo at 50 percent still way too big for formatted 300 x 300 box. pic.drawImage(photo,0,0,300,100); //resized to fit box to fulfill spirit of assignment. pic.drawImage(photo,0,125,150,50); // resized to 50 percent of refitted img from line above. pic.drawImage(photo,1000,475,1650,300,5,225,290,50);//focused down on bouncing ball } } /******************************************* PART 7 Putting it all together. Using a combination of all the methods. Create a complex scene. You must use at least 3 different methods. ********************************************/ var freestyle = document.getElementById("combo"); if(freestyle && freestyle.getContext){ var stuff = freestyle.getContext('2d'); if (stuff){ stuff.strokeStyle = "gray"; stuff.fillStyle = "darkblue"; stuff.lineWidth = 10; stuff.fillRect(200,75,300,150); stuff.strokeRect(200,75,300,150); stuff.strokeStyle='red'; stuff.lineWidth = 10; stuff.beginPath(); stuff.moveTo(50,275); stuff.bezierCurveTo(100,150,425,160,550,140); stuff.bezierCurveTo(600,275,800,240,880,60); stuff.stroke(); var logoImg = document.getElementById("image1"); stuff.drawImage(logoImg, 550,175,300,100); } } }else{ document.getElementById('errorBox').innerHTML="Your Browser does not support HTML5 Canvas. Upgrade to a later browser to experience site content." } };
/* eslint-disable no-underscore-dangle */ // const bcrypt = require('bcrypt'); const _ = require('lodash'); const ArtistController = require('./artist-controller'); const { User, validateUser, validateUpdate } = require('../models/user'); // const mailService = require('../services/mail-service'); // const { NODE_ENV } = require('../config/env'); const UserService = require('../services/user-service'); /** * Retrieve a user */ exports.detail = async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).send({ success: false, message: 'user not found' }); res.status(200).send({ success: true, message: 'success', data: user }); }; /** * List/Fetch all users */ exports.list = async (req, res) => { const users = await User.find(); if (_.isEmpty(users)) return res.status(404).send({ success: false, message: 'users not found' }); res.status(200).send({ success: true, message: 'success', data: users }); }; /** * Create a user */ exports.create = async (req, res) => { // if it is an artist, go here if (req.body.role === 'artist') { return ArtistController.create(req, res); } // validate req.body const validData = await validateUser(_.omit(req.body, ['stageName', 'role'])); let user = await User.findOne({ email: validData.email }); if (user) return res.status(409).send({ success: false, message: 'user already exist' }); user = await UserService.createUser(req, res); // log the user in const token = user.generateAuthToken(); return res.header('token', token).status(201).send({ success: true, message: 'success', data: { user, token } }); }; /** * Update a user */ exports.update = async (req, res) => { let requestBody = await validateUpdate(req.body); // is Owner : check if it is the artist const isSelf = await User.findOne({ _id: req.params.id }); if (isSelf._id !== req.user._id) { return res.status(401).send({ success: false, message: 'Permission denied or user does not exist' }); } // remove password and role from req.body requestBody = _.omit(req.body, ['password', 'role']); const options = { new: true, runValidators: true }; await User.findByIdAndUpdate(req.params.id, { ...requestBody }, options, async (error, user) => { if (error) throw error; if (!user) return res.status(404).send({ success: false, message: 'user not found' }); res.status(200).send({ success: true, message: 'success', data: user }); }); }; /** * Delete a user */ exports.delete = async (req, res) => { // validate, // only a user will can delete itself, admin can also delete // if (req.user._id !== req.params.id) return res.status(400).send('Bad request'); // is Owner : check if it is the artist const isSelf = await User.findOne({ _id: req.params.id }); if (isSelf._id !== req.user._id) { return res.status(401).send({ success: false, message: 'Permission denied or user does not exist' }); } const user = await User.findByIdAndRemove(req.params.id); if (!user) return res.status(404).send({ success: false, message: 'user not found' }); res.status(200).send({ success: true, message: 'success', data: user }); };
/** * Created by xiangran.kong on 16/08/09. */ import {getUnit, eventUnit, cookieUnit} from './../unit/unit.js'; class AddCart { constructor ($this, opts){ this.$this = $this; this.bindName = opts.bindName; this.$status = opts.$status; //购物车状态,显示数量 this.productId = parseInt($this.attr('data-pid')); //产品id this.number = parseInt(this.$addNumber || 1) ; //加入购物车数量,默认1 this._eventBind(); } _eventBind (){ let that = this; $(document).on('click', '.J_AddCart', function(e){ if(that.productId && that.number>0){ that._sendAjax(that.productId,that.number); } }); } _sendAjax (proId, number){ let [that]= [this]; $.ajax({ url: '', type:'post', data: {'productId': proId, 'number': number}, beforeSend: function(){ if(!proId){ return false; } }, success: function(data){ data = { success: false, msg: '加入购物车失败', sum:2 }; if(data.success){ $.pop({ type: 'tips', hideTimes: 5000, message: data.msg }); that.$status.text(data.sum); }else{ $.pop({ type: 'tips', hideTimes: 5000, message: data.msg }) } } }); } } /** * 加入购物车 * 加入购物车的按钮中要有class: J_AddCart, data-pid="27598"(产品pid) * opts.$addNumber 要记入购物的数量,默认为1 * opts.$status 要显示购物车数量的jquery对象 * **/ $.fn.addCart = function(opts){ if(opts && opts.$status){ let ac = new AddCart($(this), opts); } };
var mongoose = require('mongoose'); var PostModel = require('../models/test-post'); var UserModel = require('../models/test-post'); var TestUserSchema = new mongoose.Schema({ username: {type: String} }); module.exports = mongoose.model('TestUser',TestUserSchema);
import React, { Component } from 'react' export default class Footer extends Component { render() { return ( <div className='Footer_container container-fluid'> <div className="footer_content"> <div className="footer_up row"> <div className="col-3"> <p className='footer_up_title'>123PHIM</p> <div className="footer_up_docx row"> <div className="footer_up_docx_right col-6"> <p><a>FAQ</a></p> <p><a>Branch Guidelines</a></p> </div> <div className="footer_up_docx_left col-6"> <p><a>Thỏa thuận sử dụng</a></p> <p><a>Quy chế hoạt động</a></p> <p><a>Chính sách bảo mật</a></p> <p><a>Quyền lợi thành viện</a></p> </div> </div> </div> <div className="col-3"> <p className='footer_up_title'>ĐỐI TÁC</p> <div className="row footer_partner"> <div className="footer_partner_icon"> <img src="./images/bhd.png" alt="" /> <img src="./images/plaza.png" alt="" /> <img src="./images/lotte.png" alt="" /> <img src="./images/line.png" alt="" /> <img src="./images/vietcombank.png" alt="" /> <img src="./images/momo.png" alt="" /> </div> </div> </div> <div className="col-3"> <p className='footer_up_title'>MOBILE APP</p> <div className="footer_mobileApp"> <img src="./images/iconAndroid.png" alt="" /> <img src="./images/iconApple.png" alt="" /> </div> </div> <div className="col-3"> <p className='footer_up_title'>SOCIAL</p> <div className="footer_social"> <img src="./images/facebook.png" alt="" /> <img src="./images/zalo.png" alt="" /> </div> </div> </div> <div className="footer_down row"> <div className="col-9"> <div class="row"> <div className="col-3"> <img src="./images/vinaGame.png" alt="" /> </div> <div className="col-9"> <h5>123PHIM-SẢN PHẨM CỦA CÔNG TY CỔ PHẦN ZION-MỘT THÀNH VIÊN CỦA CÔNG TY VNG</h5> <p>Địa chỉ: 52 NGuyễn Ngọc Lộc , Phường 14 , Quận 10 , Thành Phố Hồ Chí Minh</p> <p>Mã số thuế : 001705</p> </div> </div> </div> <div className="col-3"> <img src="./images/boCongThuong.png" alt="" /> </div> </div> </div> </div> ) } }
/** * @param {number} x * @param {number} y * @param {number} z * @constructor */ function Point(x, y, z) { this.x = x; this.y = y; this.z = z; } /** * Shorthand Point construction. * @param {number} x * @param {number} y * @param {number} z * @returns {Point} */ function P(x, y, z) { return new Point(x, y, z); } /** * @returns {string} * @method */ Point.prototype.toString = function() { return "(" + this.x + ", " + this.y + ", " + this.z + ")"; }; /** * @returns {string} a CSS rgba() string. * @method */ Point.prototype.toColor = function() { return 'rgba(' + ~~(255 * this.x) + ',' + ~~(255 * this.y) + ',' + ~~(255 * this.z) + ',1)'; }; /** * @returns {number} the distance from the origin. * @method */ Point.prototype.abs = function() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }; /** * @param {number} s Divisor. * @returns {Point} a new point. * @method */ Point.prototype.div = function(s) { return new Point(this.x / s, this.y / s, this.z / s); }; /** * @param {number} s Multiplier. * @returns {Point} a new point. * @method */ Point.prototype.mult = function(s) { return new Point(this.x * s, this.y * s, this.z * s); }; /** * @param {Point} point * @returns {Point} a new point. * @method */ Point.prototype.plus = function(point) { return new Point(this.x + point.x, this.y + point.y, this.z + point.z); }; /** * Project this point onto a 2D surface, with the camera pointed at * the origin along the z-axis. The origin is on the surface. * @param {number} fl Focal length (distance between camera and surface). * @returns {Point} * @method */ Point.prototype.project = function(fl) { return new Point((fl * this.x) / (fl + this.z), (fl * this.y) / (fl + this.z)); }; /** * @param {number} a A rotation angle (radians). * @returns {Point} this point rotated about the X axis. * @method */ Point.prototype.rotateX = function(a) { return new Point(this.x, this.y * Math.cos(a) - this.z * Math.sin(a), this.y * Math.sin(a) + this.z * Math.cos(a)); }; /** * @param {number} a A rotation angle (radians). * @returns {Point} this point rotated about the Y axis. * @method */ Point.prototype.rotateY = function(a) { return new Point(this.z * Math.sin(a) + this.x * Math.cos(a), this.y, this.z * Math.cos(a) - this.x * Math.sin(a)); }; /** * @returns {Point} this point normalized. * @method */ Point.prototype.normalize = function() { return this.div(this.abs()); }; /** * Select a point inside a unit sphere and project it onto the sphere. * @returns {Point} A uniformly random point on the outside of a unit sphere. */ Point.random = function() { function r() { return Math.random() * 2 - 1; } do { var p = new Point(r(), r(), r()); } while (p.abs() > 1); return p.normalize(); }; /** * Select two spherical coordinate angles and set radius to 1. * @returns {Point} A biased random point on the outside of a unit sphere. */ Point.randomSpherical = function() { var q = Math.random() * Math.PI * 2, f = Math.random() * Math.PI * 2; return new Point(Math.sin(q) * Math.cos(f), Math.sin(q) * Math.sin(f), Math.cos(q)); }; /** * Select a point in the unit cube and project it into the sphere. * @returns {Point} A biased random point on the outside of a unit sphere. */ Point.randomCube = function() { function unit() { return Math.random() * 2 - 1; } return P(unit(), unit(), unit()).normalize(); };
const Pessoas = require('../models/Pessoas'); module.exports = { async index(req, res) { const pessoas = await Pessoas.findAll(); return res.json(pessoas); }, async store(req, res) { const { id } = req.params; const { name, surname, email, zip_code, state, city, street, doc_number, cellphone, nationality } = req.body; let pessoas = "" if (id) { Pessoas.update( { 'name': name, 'surname': surname, 'email': email, 'zip_code': zip_code, 'state': state, 'city': city, 'street': street, 'doc_number': doc_number, 'cellphone': cellphone, 'nationality': nationality }, { where: { id: id } } ); } else { try { const pessoas = await Pessoas.create({ 'name': name, 'surname': surname, 'email': email, 'zip_code': zip_code, 'state': state, 'city': city, 'street': street, 'doc_number': doc_number, 'cellphone': cellphone, 'nationality': nationality }); } catch (error) { if (error.name === "SequelizeUniqueConstraintError") { return res.json("CPF já existe") } else { return res.json(error); } } } return res.json(pessoas); }, async show(req, res) { const { id } = req.params; const pessoas = await Pessoas.findByPk(id); return res.json(pessoas); }, async destroy(req, res) { const { id } = req.params; Pessoas.destroy({ where: { id: id } }); return res.json('ok'); } };
import React from 'react' import { Button, ButtonGroup, PageHeader} from 'react-bootstrap'; import { render } from 'react-dom'; export default class MyGermany extends React.Component { render() { return <div> <header> <PageHeader>Gute Raise! <small>Connect between tourists and local people</small></PageHeader> <ButtonGroup justified> <Button href="http://localhost:8080/#/myprofile?_k=mrmiwk">My profile</Button> <Button href="http://localhost:8080/#/about?_k=ybh5au">Prep for Germany</Button> <Button href="http://localhost:8080/#/searchpartner?_k=lhlql7">Look for a Tandem Partner</Button> <Button href="http://localhost:8080/#/mygermany?_k=if77ga">My Germany</Button> </ButtonGroup> </header> </div> } }
var fs = require("fs"); fs.readFileSync("input.txt").toString().split("\n").forEach(function (line) { if (line !== "") { capitalizeWords(line); } }); function capitalizeWords(line) { var result = line.trim().split(" ").map(function (w) { if (w.length === 1) { return w[0].toUpperCase(); } else { return w[0].toUpperCase() + w.substr(1); } }).join(" "); console.log(result); }
/** * Created by bastien on 11/04/2017. */ import {html} from 'snabbdom-jsx'; import xs from 'xstream'; export function NewUser(sources) { const clicks$ = sources.DOM.select('.get-random').events('click'); const newUserClick$ = sources.DOM.select('.create-new-user').events('click'); const getRandomUser$ = clicks$.map(() => { const randomNumber = Math.round(Math.random() * 9) + 1; return { url: 'https://jsonplaceholder.typicode.com/users/' + String(randomNumber), category: 'users', method: 'GET' } }); const goToNewUser$ = newUserClick$.map(() => '/other'); const userStorage$ = sources.HTTP.select('users') .flatten() .map(res => res.body) .map(user => ({ key: 'users-local', value: JSON.stringify(user) })); const vtree$ = sources .storage.local .getItem('users-local') .map(JSON.parse) .startWith(null) .map(user => ( <div> <button className="get-random ui button">Get random user</button> <button className="create-new-user ui button">Create new user</button> <br/> {user ? ( <div className="ui card"> <div className="content"> <div className="header">{user.name}</div> <div className="meta">{user.email}</div> <div className="description">{user.company.catchPhrase}</div> </div> </div> ) : ''} </div> )); return { DOM: vtree$, storage: userStorage$, HTTP: getRandomUser$, router: goToNewUser$ }; }
var searchData= [ ['locateunit',['locateUnit',['../class_master.html#a355cd520378a1ee4bbf340badf4163ae',1,'Master::locateUnit(Unit *inputUnit)'],['../class_master.html#a1401033a876ae9e4b38e5879537c5b2a',1,'Master::locateUnit(int row, int col)']]] ];
/* * Intercepteur * Ajoute le token en paramètre de la request * (Intercepteur enregistré dans app.js) */ app.factory('AddTokenToRequestInterceptor', function (TokenHandler, $q, constants) { return { 'request': function (config) { if (config // Si la requête est destinée au backend && config.url.substr(0, 22) === constants.CONTEXTPATH // Si la requête ne provient pas de la page de login (pas besoin de token pour ce cas) && config.url !== constants.CONTEXTPATH + 'login' // Si un token est présent en session && TokenHandler.isSet()) { if (typeof config.params === 'undefined') { config.params = {}; } // On l'ajoute en paramètre à la requête config.params.token = TokenHandler.get(); } return config || $q.when(config); } }; });
const components = { MuiButtonBase: { defaultProps: { disableRipple: true, }, }, MuiLink: { defaultProps: { underline: "hover", }, }, MuiCardHeader: { defaultProps: { titleTypographyProps: { variant: "h6", }, }, styleOverrides: { action: { marginTop: "-4px", marginRight: "-4px", }, }, }, MuiCard: { styleOverrides: { root: { borderRadius: "6px", boxShadow: "rgba(50, 50, 93, 0.025) 0px 2px 5px -1px, rgba(0, 0, 0, 0.05) 0px 1px 3px -1px", backgroundImage: "none", }, }, }, MuiPaper: { styleOverrides: { root: { backgroundImage: "none", }, }, }, MuiPickersDay: { styleOverrides: { day: { fontWeight: "300", }, }, }, MuiPickersYear: { styleOverrides: { root: { height: "64px", }, }, }, MuiPickersCalendar: { styleOverrides: { transitionContainer: { marginTop: "6px", }, }, }, MuiPickersCalendarHeader: { styleOverrides: { iconButton: { backgroundColor: "transparent", "& > *": { backgroundColor: "transparent", }, }, switchHeader: { marginTop: "2px", marginBottom: "4px", }, }, }, MuiPickersClock: { styleOverrides: { container: { margin: `32px 0 4px`, }, }, }, MuiPickersClockNumber: { styleOverrides: { clockNumber: { left: `calc(50% - 16px)`, width: "32px", height: "32px", }, }, }, MuiPickerDTHeader: { styleOverrides: { dateHeader: { "& h4": { fontSize: "2.125rem", fontWeight: 400, }, }, timeHeader: { "& h3": { fontSize: "3rem", fontWeight: 400, }, }, }, }, MuiPickersTimePicker: { styleOverrides: { hourMinuteLabel: { "& h2": { fontSize: "3.75rem", fontWeight: 300, }, }, }, }, MuiPickersToolbar: { styleOverrides: { toolbar: { "& h4": { fontSize: "2.125rem", fontWeight: 400, }, }, }, }, MuiChip: { styleOverrides: { root: { borderRadius: "6px", }, }, }, }; export default components;
const repos = require('./repos') const api = require('./api') module.exports = (pluginContext) => { return (name, env = {}) => { return new Promise((resolve, reject) => { resolve(repos(api, pluginContext, name)) }) } }
import React, {Component} from 'react'; class ListStudent extends Component { constructor(props) { super(props) this.state = { students: [], isLoaded: false, error: null } this.deleteStudent = this.deleteStudent.bind(this); this.editStudent = this.editStudent.bind(this); this.addStudent = this.addStudent.bind(this); this.reloadStudentList = this.reloadStudentList.bind(this); } componentDidMount() { this.reloadStudentList(); } reloadStudentList() { fetch("http://localhost:8080/student") .then(res => res.json()) .then(students => { this.setState({ isLoaded: true, students })}, (error) => { this.setState({ isLoaded: true, error }); }) } deleteStudent(studentId) { fetch("http://localhost:8080/student/" + studentId, {method: 'DELETE', headers: { 'Accept':'application/json', 'Content-Type':'application/json' }}) .then(res => { this.setState({ students: this.state.students.filter(student => student.id !== studentId)}) }) } editStudent(id) { window.localStorage.setItem("studentId", id); this.props.history.push('/edit-student'); } addStudent() { this.props.history.push('/add-student'); } render() { const { error, isLoaded, students } = this.state; if (error) { return <div>Ошибка: {error.message}</div>; } else if (!isLoaded) { return <div>Загрузка...</div>; } else { return( <div> <h2 className="text-center">Student Details</h2> <button className="btn btn-danger" onClick={() => this.addStudent()}>Add Student</button> <table className="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">FirstName</th> <th scope="col">LastName</th> <th scope="col">Contact</th> <th scope="col">Birthday</th> <th scope="col">Subscription</th> <th scope="col">Group</th> <th>Delete</th> <th>Edit</th> </tr> </thead> <tbody> { students.map( student => <tr key={student.id}> <td>{student.id}</td> <td>{student.firstName}</td> <td>{student.lastName}</td> <td>{student.contact}</td> <th>{student.birthday}</th> <th>{student.subscription}</th> <th>{student.group}</th> <td> <button className="btn btn-success" onClick={() => this.deleteStudent(student.id)}> Delete</button> </td> <td> <button className="btn btn-success" onClick={() => this.editStudent(student.id)}> Edit</button> </td> </tr> )} </tbody> </table> </div> ) } } } export default ListStudent;
const formData = require('form-data'); const Mailgun = require('mailgun.js'); const mailgun = new Mailgun(formData); const templateLoader = require('./templateLoader'); const getPath = (email, recoveryCode) => { const baseurl = process.env.PROD_MAIL_ENV || 'http://localhost:3000'; return `${baseurl}/#!/reset/${email}/${recoveryCode}` } const recovery = async (email, recoveryCode) => { return new Promise(async (resolve, reject) => { if(!process.env.PROD_MAIL_ENV) { return resolve(`reset link: ${getPath(email, recoveryCode)}`) } const data = { from: 'brmodeloweb@gmail.com', to: [email], subject: 'Recuperação de senha', html: templateLoader.loadRecovery(getPath(email, recoveryCode)), }; const mg = mailgun.client({ username: 'api', key: process.env.PROD_MAILGUN_API_KEY }); mg.messages.create('brmodeloweb.com', data) .then(msg => resolve(msg)) .catch(err => reject(err)); }); }; const sender = { recovery }; module.exports = sender;
var cometClient; var channel; var chatBox; var messageDiv; function sendMessage(msg) { if (cometClient && channel) { cometClient.publish(channel, msg); } } function showChatMessage(msg) { showMessage(msg, 'chatMsg'); } function showMessage(msg, cssStyle) { // var messageDiv = document.getElementById('messages'); var span = document.createElement('span'); span.setAttribute('class', cssStyle); span.setAttribute('className', cssStyle); span.appendChild(document.createTextNode(msg)) messageDiv.appendChild(span); messageDiv.appendChild(document.createElement('br')); messageDiv.scrollTop = messageDiv.scrollHeight; } function handleChatMessageReceived(msg) { showChatMessage(msg); } /** * Send a chat message to the server */ function handleSendChat(e) { // showChatMessage(e.type + ', ' + e.target + ', ' + e.which + ', ' + e.keyCode + ', ' + e.srcElement); var charCode; var target; if (e.which) { charCode = e.which; } else if (e.keyCode) { charCode = e.keyCode; } if (e.target) { target = e.target.id; } else if (e.srcElement) { target = e.srcElement.id; } if (target != 'chatBox'|| charCode != 13) { return false; } else { var msg = chatBox.value; if ( (msg != null) && (msg != '')) { sendMessage(msg); chatBox.value = ''; } chatBox.focus(); } return false; } function createChatWidgetsInContainer(chatDiv) { /* messageDiv = document.createElement('div'); messageDiv.setAttribute('id', 'messages'); messageDiv.setAttribute('class', 'scroll'); chatDiv.append(messageDiv); */ chatDiv.append('<div id="messages" class="scroll"></div>'); chatDiv.append('<span>Chat: </span>'); chatDiv.append('<input type="text" id="chatBox" class="chatBox"/>'); messageDiv = document.getElementById('messages'); chatBox = document.getElementById('chatBox'); } function initChat(chatDivId, gameId, gameSessionId) { var chatDiv = $('#' + chatDivId);// document.getElementById(chatDivId); createChatWidgetsInContainer(chatDiv); var url = 'http://' + window.location.host + '/comet'; showChatMessage('connecting to: ' + url); cometClient = new Faye.Client(url); var clientAuth = { // attach an auth token to subscription messages outgoing: function(message, callback) { // Again, leave non-subscribe messages alone if (message.channel !== '/meta/subscribe') { return callback(message); } showChatMessage('subscribing...'); // Add ext field if it's not present if (!message.ext) message.ext = {}; // Set the auth token message.ext.authToken = authToken; // Carry on and send the message to the server callback(message); } }; cometClient.addExtension(clientAuth); parseCookie(); channel = '/' + gameId + (gameSessionId ? ('/' + gameSessionId) : ''); projectSub = cometClient.subscribe(channel, handleChatMessageReceived); projectSub.callback(function() { showChatMessage('Subscribed to channel ' + channel); // bind the chat function to the prompt $('#chatBox').bind('keyup', handleSendChat); }); projectSub.errback(function(error) { showChatMessage('Subscription failed: ' + error.message); }); } function getCookieValue(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function parseCookie() { if (document.cookie) { authToken = getCookieValue('authToken'); } }
const db = require("./Db-Config"); const config = require("../Backend/config/auth.config"); var jwt = require("jsonwebtoken"); var bcrypt = require("bcryptjs"); const { isEmpty } = require("lodash"); const signup = (request, response) => { const Email = request.body.Email; const Passsword = bcrypt.hashSync(request.body.Password, 8); const Name = request.body.Name; response.status(200).send("Rabi yahfdk"); }; const signin = async (request, response) => { const Email = request.body.Email; const Passsword = request.body.Password; await db.pooldb.query( 'SELECT "Name", "Email", "Passsword", "ID" FROM public."Users" where "Email"= $1 and "Passsword" = $2 ', [Email, Passsword], (error, results) => { if (error) { throw error; } response.status(200).json(results.rows); } ); }; const getAgencies = async (request, response) => { const id = parseInt(request.params.id); console.log(id); await db.pooldb.query( 'SELECT "NameAgence", "Address", "Wilaya", "Commune", "Phone", "Created At" FROM public."Agencies" where "Userid"=$1', [id], (error, results) => { if (error) { throw error; } response.status(200).json(results.rows); } ); }; const getUsers = async (request, response) => { await db.pooldb.query( 'SELECT * FROM public."Users" ORDER BY id ASC ', (error, results) => { if (error) { throw error; } response.status(200).json(results.rows); } ); }; const createAgence = async (request, response) => { const id = parseInt(request.params.id); const NameAgence = request.body.NameAgence; const Address = request.body.Address; const Wilaya = request.body.Wilaya; const Commune = request.body.Commune; const Phone = request.body.Phone; await db.pooldb.query( ' INSERT INTO public."Agencies"("NameAgence", "Address", "Wilaya", "Commune", "Phone", "Created At", "Userid") VALUES ($1, $2, $3, $4, $5, 1254,$6)', [NameAgence, Address, Wilaya, Commune, Phone, id], (error, results) => { if (error) { throw error; } response.status(201).send(`Agencies added with ID: ${results.insertId}`); } ); }; const BedlUser = async (request, response) => { const id = parseInt(request.params.id); const NameAgence = request.body.NameAgence; const Address = request.body.Address; const Wilaya = request.body.Wilaya; const Commune = request.body.Commune; const Phone = request.body.Phone; await db.pooldb.query( 'UPDATE public."Agencies" SET "NameAgence"=$1, "Address"=$2, "Wilaya"=$3, "Commune"=$4, "Phone"=$5 WHERE "Userid"=$6;', [NameAgence, Address, Wilaya, Commune, Phone, id], (error, results) => { if (error) { throw error; } response.status(200).send(`Agencies modified with ID:`); } ); }; const deleteAgence = async (request, response) => { const id = parseInt(request.params.id); const NameAgence = request.body.oldData.NameAgence; console.log(NameAgence); await db.pooldb.query( 'DELETE FROM public."Agencies" WHERE "Userid"=$1 and "NameAgence"=$2', [id, NameAgence], (error, results) => { if (error) { throw error; } response.status(200).send(`Agencies deleted with ID:`); } ); }; module.exports = { getUsers, deleteAgence, signin, signup, BedlUser, createAgence, getAgencies, };
//var app = angular.module('myApp', ['ngRoute','ngGrid']) var app = angular.module('myApp', ['ngRoute', 'ngTouch', 'ui.grid', 'ui.grid.edit', 'googlechart', 'addressFormatter']) //'ui.grid.edit', 'ui.grid.rowEdit', 'ui.grid.cellNav', 'addressFormatter']) angular.module('addressFormatter', []).filter('address', function () { return function (input) { return input.street + ', ' + input.city + ', ' + input.state + ', ' + input.zip; }; }) .config(['$routeProvider', function ($routeProvider) { $routeProvider //.when('/grid', { // templateUrl: 'views/grid.html', // controller: 'gridController' //}) .when('/uigridcrud', { templateUrl: 'views/uigridcrud.html', controller: 'uigridcrudController' }) .when('/uigrid', { templateUrl: 'views/uigrid.html', controller: 'uigridController' }) .when('/', { templateUrl: 'views/home.html', controller: 'homeController' }) .when('/about', { templateUrl: 'views/about.html', controller: 'aboutController' }) .when('/basics', { templateUrl: 'views/basics.html', controller: 'basicsController' }) .when('/select', { templateUrl: 'views/select.html', controller: 'selectController' }) .when('/formSubmission', { templateUrl: 'views/formSubmission.html', controller: 'formSubmissionController' }) .when('/chart', { templateUrl: 'views/chart.html', controller: 'chartController' }) .otherwise({ redirectTo: '/' }); }]).value('googleChartApiConfig', { version: '1', optionalSettings: { packages: ['corechart', 'gauge'], //language: 'fr' language: 'en' } }) .controller('mainController', function ($scope) { $scope.message = "Main Content"; });;
// ------------------------------------------------------------------------ // Setup // ------------------------------------------------------------------------ "use strict"; const _ = require('lodash'); const args = require('minimist')(process.argv.slice(2)); const path = require('path'); const fs = require('fs'); const P = require('bluebird'); let dev = false; //check arguments if ((args.d) || (args.dev)) { // they just want help console.log("Dev Environment Set"); dev = true; } const config = dev ? require('../config/configFactory').getConfig('dev') : require('../config/configFactory').getConfig(); const utils = require('../lib/utils'); const commands = require('../lib/commands'); const parser = require('../lib/parsers/scene'); const log = require('../lib/loggerFactory'); const plex = require('../lib/plexUpdater'); const Torrent = require('../lib/models/Torrent'); const logger = log.getLogger(); const tv = (!((args.m) || (args.movie))); const movie = ((args.m) || (args.movie)); // ------------------------------------------------------------------------ // Main // ------------------------------------------------------------------------ return main() .then(processTorrent) .then(updatePlex) .then(notify) .catch((obj) => { logger.error(obj.msg); return process.exit(obj.code); }); // ------------------------------------------------------------------------ // Private Functions // ------------------------------------------------------------------------ /** * Processes the torrent file * currently supports: * - TV Single Episodes * - TV Seasons * - Movies * @returns {*} */ function processTorrent() { if(args._.length === 0) throw new Error({msg: config.help.processTv, code: 1}); let srcFile = args._[0]; if (!utils.exists(srcFile)) throw new Error({msg: `${srcFile} does not exist`, code: 1}); if(tv) { const fileObject = parser.parse(path.basename(srcFile)); return processTv(fileObject); } } /** * Processes the Tv file * @param fileObject * @returns {*} */ function processTv(fileObject) { if(fileObject.isSeason) return processSeason(fileObject); let directoryStructure = config.directoryStructure; directoryStructure = directoryStructure.replace(/%n/, fileObject.seriesName); directoryStructure = directoryStructure.replace(/%s/, fileObject.season.toString()); directoryStructure = directoryStructure.replace(/%o/, fileObject.fileName); utils.exists(config.tvDestDirectory + path.dirname(directoryStructure), true); const success = commands.symlink(fileObject.fileName, config.tvDestDirectory + directoryStructure); if (!success) throw new Error({ msg: "Error creating the symlink", code: 1}); logger.info('symlink created: ' + config.tvDestDirectory + directoryStructure); } /** * processes the file if its a season * @param fileObject */ function processSeason(fileObject) { let directoryStructureSeason = config.directoryStructureSeason; directoryStructureSeason = directoryStructureSeason.replace(/%n/, fileObject.seriesName); directoryStructureSeason = directoryStructureSeason.replace(/%s/, fileObject.season); utils.exists(config.tvDestDirectory + directoryStructureSeason, true); const list = fs.readdirSync(fileObject.fileName); // for each file in the season create the symlink _.each(list, (file) => commands.symlink(fileObject.fileName + '/' + file, config.tvDestDirectory + directoryStructureSeason + '/' + file)); } /** * makes sure we are good to go as far as directories existing */ function main() { return new P((resolve, reject) => { //1. check to see if destination directory exists and make it if not utils.exists(config.tvDestDirectory, true); //2. test to make sure the staging directory is there if not exit thats bad if (!utils.exists(config.tvStagingDirectory)) { return reject({msg: 'Staging directory does not exist', code: 1}); } //check arguments if ((args.h) || (args.help)) { // they just want help logger.error(config.help.processTv); return reject({msg: config.help.processTv, code: 0}); } return resolve(); }); } /** * notifies via an provider, in this case prowl */ function notify() { if (!logger.prowl) return; let msg = path.basename(srcFile) + ' Successfully Downloaded'; logger.prowl.push(msg, 'What', ( error ) => { if( error ) throw error }); } /** * updates the plex libraries when something new has been added * @returns {Promise.<TResult>} */ function updatePlex() { return plex.findLibraries(tv ? 'show' : 'movie') .then((directories) => plex.refreshLibraries(_.map(directories, 'key'))); }
const userSchema = require('../models/user'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); /** * Find user by ID. Use like middleware in ExpressJS */ exports.authenticateUser = (req, res, next) => { if (req.params.username && req.params.username != '' && req.params.password && req.params.password != '') { userSchema.findOne({ 'local.username': req.params.username }, (err, doc) => { if (err) { res.status(500).send(err.message); } else { bcrypt.hash(req.params.password, 10).then(function (hash) { bcrypt.compare(hash, doc.local.password, (err, sucess) => { if (err) { res.status(401).send('Not valid Username'); } else if (!sucess) { res.status(401).send('Passwords not match'); } else { jwt.sign({ 'username': doc.local.username, 'rol': doc.rol, 'userGroups': doc.userGroups }, process.jwtSecret || 'mysecret', { algorithm: 'HS256', expiresIn: 60 * 60 }, (err, token) => { res.status(200).jsonp({ 'token': token }); }); } }); }); } }); } else { res.status(500).send('Not valid Username'); } } /** * Middleware for checking if a token is valid */ exports.loginUser = (req, res, next) => { var token = req.headers.token; if (!token) { req.user = false; next(); } else { jwt.verify(token, process.jwtSecret || 'mysecret', function (err, decoded) { if (err) { req.user = false; next(); } else { req.user = decoded; next(); } }); } }
var util = require('util'), events = require('events'), redis = require('redis'); function RedisEvent(host, channelsList) { events.EventEmitter.call(this); var self=this; self._connectedCount=0; if (!host) { throw new Error("No hostname specified to RedisEvent"); } this.channelsList = channelsList; this.pubRedis = redis.createClient( 6379, host, { enable_offline_queue: false, no_ready_check: true, retry_strategy: function (options) { return 3000 + Math.round(Math.random() * 3000); } } ); this.pubRedis.on('error', function(e){ console.log(e); }); this.pubRedis.on('ready', function() { self._connectedCount++; if (self._connectedCount == 2) { self.emit('ready'); } }); this.pubRedis.on('end', function() {self._connectedCount--; }); if(channelsList != null) { this.subRedis = redis.createClient( 6379, host, { enable_offline_queue: false, no_ready_check: true, retry_strategy: function (options) { return 3000 + Math.round(Math.random() * 3000); } } ); this.subRedis.on('error', function(e){ console.log(e); }); this.subRedis.on('ready', function() { self._connectedCount++; self._subscribe(); if (self._connectedCount == 2) { self.emit('ready'); } }); this.subRedis.on('end', function() {self._connectedCount--; }); this.subRedis.on("message", this._onMessage.bind(this)); } } util.inherits(RedisEvent, events.EventEmitter); RedisEvent.prototype._subscribe = function() { var self=this; this.channelsList.forEach(function(channelName) { self.subRedis.subscribe(channelName); }); }; RedisEvent.prototype._onMessage = function(channel, message) { var data = null, eventName = null; try { data = JSON.parse(message); if (data && data.event) { eventName = channel + ':' +data.event; } } catch(e) { } if (data && eventName) { this.emit(eventName, data.payload); } }; RedisEvent.prototype.pub = function(eventName, payload) { var split = eventName.split(':'); if (split.length!=2) { console.log("ev warning: eventName '%s' is incorrect", eventName); return false; } var data = { event: split[1], payload: payload }; this.pubRedis.publish(split[0], JSON.stringify(data), function(){}); }; RedisEvent.prototype.quit = function() { this.subRedis.quit(); this.pubRedis.quit(); }; module.exports = RedisEvent;
const mongoose = require("mongoose"); require("../schemas/product"); require("../schemas/category"); require("../schemas/user"); mongoose.connect(process.env.DATABASE_URL, () => console.log("database connected") );
showScreen(); function showScreen() { var url = new URL(window.location.href); var screensetParam = url.searchParams.get("screen-set"); var screenIdParam = url.searchParams.get("screen-id"); if (typeof(screensetParam) === 'undefined' || typeof(screenIdParam) === 'undefined' || screensetParam === '' || screensetParam === null ) { return; } var params = { screenSet: screensetParam, startScreen: screenIdParam, containerID: "div", onError: errorHandler }; gigya.accounts.showScreenSet(params); } function errorHandler(e) { console.log(e); document.getElementById('div').innerHTML = "<pre>"+JSON.stringify(e, undefined, 2)+"</pre>"; }
import React from 'react'; const style ={ backgroundColor:'white', font:'inherit', border: '1px solid blue', padding:'2px', cursor:'pointer' } const UserInput = (props) => { return( <div> <input style={style} type="text" onChange={props.changed} /> </div> ) } export default UserInput;
export const ADD_TO_CART='ADD_TO_CART' export const REMOVE_TO_CART='REMOVE_TO_CART' export const addToCart=id=>{ return{type:ADD_TO_CART, id} } export const removeFromCart=id=>{ return{type:REMOVE_TO_CART, id} }
import { LightningBoltIcon, FilmIcon, SearchIcon, DesktopComputerIcon, } from "@heroicons/react/solid"; import { useState } from "react"; import { Link } from "react-router-dom"; const Navbar = () => { const [activeNav, setActiveNav] = useState(); const navItems = [ { id: 0, title: "HOME", route: "/", icon: LightningBoltIcon, }, { id: 1, title: "MOVIES", route: "/movies", icon: FilmIcon, }, { id: 2, title: "TV", route: "/tv-shows", icon: DesktopComputerIcon, }, { id: 3, title: "SEARCH", route: "/search", icon: SearchIcon, }, ]; return ( <nav className="fixed bottom-0 inset-x-0 border-t-2 bg-[#06202a] z-50"> <div className="flex flex-grow m-4 mb-1 justify-evenly md:justify-center md:mb-2 "> {navItems.map((navItem) => ( <Link key={navItem.id} to={navItem.route}> <div className={`flex flex-col items-center cursor-pointer group w-12 sm:w-20 hover:text-red-400 ${ activeNav === navItem.id ? "text-red-400" : null }`} onClick={() => setActiveNav(navItem.id)} > <navItem.icon className="w-5 h-5 md:h-8 md:w-8 group-hover:animate-bounce" /> <p className="tracking-widest opacity-100 md:opacity-0 group-hover:opacity-100"> {navItem.title} </p> </div> </Link> ))} </div> </nav> ); }; export default Navbar;
// const { connectors } = require('./connectors'); const { connectors } = require('./dummy'); const resolvers = { Query: { person: (obj, { id }, context, info) => { return connectors.getPersonById(id); }, people: (obj, args, context, info) => { return connectors.getPeople(); }, }, Mutation: { createPerson: (obj, { input }, context, info) => { return connectors.createPerson(input); }, updatePerson: (obj, { id, input }, context, info) => { return connectors.updatePerson(id, input); }, deletePerson: (obj, { id }, context, info) => { return connectors.deletePerson(id); }, }, }; module.exports = { resolvers };