text
stringlengths
7
3.69M
Template.favorisList.helpers({ favoris: function() { return Favoris.getCollByUserId(Meteor.userId()); } }); Template.favorisList.events({ "click #deleteFavoris": function() { return Meteor.call("favorisDeleteByFavorisId", this._id); } }); Template.favorisList.rendered = function() { Meteor.subscribe("favorisUser", Meteor.userId()); }
var app = getApp(); Page({ data: { uploadedImages: [], imgBoolean: true, content: "", openid: '', circleid:' ', t:3, imgs: [], ss:[] }, onLoad: function (options) { var that = this; wx.getStorage({ key: 'userInfo', success: function (res) { console.log("cheng"); that.setData({ userInfo: res.data }) }, }); wx.getStorage({ key: 'openid', success: function (res) { console.log(res) console.log(res.data) that.setData({ openid: res.data }) }, }) }, chooseImg() { let that = this; let len = this.data.imgs; if (len >= 3) { this.setData({ lenMore: 1 }) return; } wx.chooseImage({ success: (res) => { let tempFilePaths = res.tempFilePaths; console.log(tempFilePaths) let imgs = that.data.imgs; for (let i = 0; i < tempFilePaths.length; i++) { if (imgs.length <3 ) { imgs.push(tempFilePaths[i]) } else { that.setData({ imgs:that.data.imgs }) wx.showModal({ title: '提示', content: '最多只能有三张图片' }) return; } } that.setData({ imgs:that.data.imgs }) } }) }, previewImg(e) { let index = e.currentTarget.dataset.index; let imgs = this.data.imgs; wx.previewImage({ current: imgs[index], urls: imgs, }) }, deleteImg(e) { let _index = e.currentTarget.dataset.index; let imgs = this.data.imgs; imgs.splice(_index, 1); this.setData({ imgs }) }, input: function (e) { var that=this; that.setData({ content:e.detail.value, }) console.log(that.data.content) }, //发布按钮事件 send: function () { var that = this; wx.showLoading({ title: '上传中', }) console.log(that.data.content) wx.request({ url: 'https://www.lieyanwenhua.com/cirinsert', method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, data: { openid: that.data.openid, mess: that.data.content }, success: function (res) { var id; that.setData({ id: res.data }) that.data.circleid = that.data.id; app.globalData.flag = res.data console.log("成功") wx.hideLoading(); console.log(that.data.circleid) var uploadImgCount = 0; console.log(that.data.imgs) console.log(that.data.uploadedImages) if(that.data.imgs.length!= 0){ for (var i = 0, h = that.data.imgs.length; i < h; i++) { console.log(that.data.imgs[i]) wx.uploadFile({ url: 'https://lieyan-1257158697.cos.ap-shanghai.myqcloud.com/', //开 //开发者服务器的 url filePath: that.data.imgs[i], // 要上传文件资源的路径 String类型!!! name: 'file', // 文件对应的 key ,(后台接口规定的关于图片的请求参数) header: { 'content-type': 'multipart/form-data' }, // 设置请求的 header formData: { 'key': "circle/" + res.data + "image_" + i + ".png" }, // HTTP 请求中其他额外的参数 success: function (res) { }, fail: function (res) { } }) } } if(that.data.imgs.length>0){ wx.request({ url: 'https://www.lieyanwenhua.com/cirimage', method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, data: { circleid: res.data, image1: 'https://lieyan-1257158697.cos.ap-shanghai.myqcloud.com/' + "circle/" + res.data + "image_" + 0 + ".png", image2: 'https://lieyan-1257158697.cos.ap-shanghai.myqcloud.com/' + "circle/" + res.data + "image_" + 1 + ".png", image3: 'https://lieyan-1257158697.cos.ap-shanghai.myqcloud.com/' + "circle/" + res.data + "image_" + 2 + ".png" }, success: function (res) { wx.showToast({ title: '发布成功', }) wx.switchTab({ url: '../friend/friend', }) } }) } wx.showToast({ title: '发表成功', },2000) wx.switchTab({ url: '../friend/friend', }) } }) } })
var Note = React.createClass({ render: function() { return( <div> <img src={this.props.src} /> <p> {this.props.children} </p> </div> ); } }); var List = React.createClass({ getInitialState(){ return({ mang: [ {src: "images/1.jpg", noiDung: "hello"}, {src: "images/2.jpg", noiDung: "hanh"}, {src: "images/3.jpg", noiDung: "ahii"} ] }) }, add: function() { this.state.mang.push({src: "images/4.jpg", noiDung: "ahaha"}); this.setState(this.state); }, render: function(){ return( <div> <button onClick={this.add}>Them</button> { this.state.mang.map(function(note, index){ return <Note key={index} src={note.src}>{note.noiDung}</Note> }) } </div> ) } }); ReactDOM.render( <div> <List /> </div>, document.getElementById('root') );
import axios from './api' // https://api.idongde.com/miniapp/v4/content/info/028Da5E9406bF5eA/v2 //只需要将参数传进来就可以了 // https://wxapi.iduoha.com/v1/content/AabCa987eBa531fA/view const indexServer = { IndexInfo(params){ return axios.get(`content/${params}`).then((res) => { return res.data }) }, Tongji(params) { return axios.get(`content/${params}/view`).then((res) => { return res.data }) } } export default indexServer
// Grab the articles as a json $.getJSON("/articles", function(data) { // For each one $("#articles").empty(); if(data.length == 0){ $("#articles").append("<h4>Uh oh! Looks like you aren't viewing any articles. Click the button Scrape New Articles!</h4>"); } else{ for (var i = 0; i < data.length; i++) { // Display the apropos information on the page $("#articles").append("<div class='col-md-4 displayedArt'><div class='card mb-4 shadow-sm'><div style='width: 18rem' class = 'card' data-id='" + data[i]._id + "'> <img class ='card-img-top' src='" + data[i].img +"'><div class='card-body'> <h6 class='card-title'> <a href=https://www.washingtonpost.com"+data[i].link + "? class='card-link' target='_blank'>"+data[i].title + "</a> </h6> <p class='card-text'>"+ data[i].description + "</p> </div><div class='card-footer'><button type='button' data-id='" + data[i]._id + "' class=' addNote btn btn-primary' data-toggle='modal' data-target='#noteModal'> View Notes</button></div></div></div>"); } } }); $(document).on("click", "#clear", function() { // Grab the id associated with the article from the submit button // Run a POST request to change the note, using what's entered in the inputs $.ajax({ method: "GET", url: "/clear" }) // With that done .then(function(data) { // Log the response console.log(data); // Empty the notes section $("#articles").empty(); $("#articles").append("<h4>Uh oh! Looks like you aren't viewing any articles. Click the button Scrape New Articles!</h4>"); }); }); $(document).on("click", "#add", function() { // Grab the id associated with the article from the submit button // Run a POST request to change the note, using what's entered in the inputs $.ajax({ method: "GET", url: "/scrape" }) // With that done .then(function(data) { // Log the response console.log(data); location.reload(); // $("#articles").empty(); // for (var i = 0; i < data.length; i++) { // // Display the apropos information on the page // $("#articles").append("<div class='col-md-4 displayedArt'><div class='card mb-4 shadow-sm'><div style='width: 18rem' class = 'card' data-id='" + data[i]._id + "'> <img class ='card-img-top' src='" + data[i].img +"'><div class='card-body'> <h6 class='card-title'> <a href=https://www.washingtonpost.com"+data[i].link + "? class='card-link' target='_blank'>"+data[i].title + "</a> </h6> <p class='card-text'>"+ data[i].description + "</p> </div><div class='card-footer'><button type='button' data-id='" + data[i]._id + "' class=' addNote btn btn-primary' data-toggle='modal' data-target='#noteModal'> View Notes</button></div></div></div>"); // } }); }); // Whenever someone clicks a p tag $(document).on("click", ".addNote", function() { // Empty the notes from the note section $("#notes").empty(); $("#notesBody").empty(); var thisId = $(this).attr("data-id"); console.log(thisId); // Now make an ajax call for the Article $.ajax({ method: "GET", url: "/articles/" + thisId }) // With that done, add the note information to the page .then(function(data) { console.log(data); // The title of the article $("#notes").append( data.title ); console.log(data.notes.length); for(var i = 0; i<data.notes.length; i++){ console.log(data.notes[i].title); $("#notesBody").append( "<p>" + data.notes[i].body + " <button class='btn btn-danger' data-id='" + data.notes[i]._id + "' id='delnote'>X</button></p>" ); } // An input to enter a new title $("#notesBody").append("<input placeholder='Title' id='titleinput' name='title' >"); // A textarea to add a new note body<h2>" + data.title + "</h2> $("#notesBody").append("<textarea placeholder='Note...' id='bodyinput' name='body'></textarea>"); // A button to submit a new note, with the id of the article saved to it $("#notesBody").append("<button class='btn btn-primary' data-id='" + data._id + "' id='savenote'>Save Note</button>"); // // If there's a note in the article // if (data.note) { // // Place the title of the note in the title input // $("#titleinput").val(data.note.title); // // Place the body of the note in the body textarea // $("#bodyinput").val(data.note.body); // } }); }); // When you click the savenote button $(document).on("click", "#savenote", function() { // Grab the id associated with the article from the submit button var thisId = $(this).attr("data-id"); console.log(thisId); // Run a POST request to change the note, using what's entered in the inputs $.ajax({ method: "POST", url: "/submit/" + thisId, data: { // Value taken from title input title: $("#titleinput").val(), // Value taken from note textarea body: $("#bodyinput").val() } }) // With that done .then(function(data) { // Log the response console.log(data); // Empty the notes section //$("#notes").empty(); }); location.reload(); // Also, remove the values entered in the input and textarea for note entry $("#titleinput").val(""); $("#bodyinput").val(""); }); // When user clicks the delete button for a note $(document).on("click", "#delnote", function() { // Save the p tag that encloses the button var thisId = $(this).attr("data-id"); // Make an AJAX GET request to delete the specific note // this uses the data-id of the p-tag, which is linked to the specific note $.ajax({ type: "GET", url: "/delete/" + thisId, // On successful call success: function(response) { // Remove the p-tag from the DOM // selected.remove(); location.reload(); // Clear the note and title inputs // $("#note").val(""); // $("#title").val(""); // Make sure the #action-button is submit (in case it's update) // $("#action-button").html("<button id='make-new'>Submit</button>"); } }); }); //========== Modal to Display Youtube ================================ var modal = document.getElementById('noteModal'); var btn = document.getElementsByClassName("addNote"); // var span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } // span.onclick = function() { // modal.style.display = "none"; // $("#noteModal").empty(); // } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }
console.log('From 2-nd app'); module.exports = function() { // Экспортируемая функция поскольку в фреймворке есть ее вызов. если там закомментировать то можно и без нее };
var data = { labels: [ "Research", "Information", "Product Design", "Packaging" ], datasets: [ { data: [62, 17, 13, 8], backgroundColor: [ "#85c875", "#0bc4df", "#1e75eb", "#f1a80a" ], hoverBackgroundColor: [ "#85c875", "#0bc4df", "#1e75eb", "#f1a80a" ], borderWidth: 0, }], }; Chart.defaults.global.legend.display = false; var promisedDeliveryChart = new Chart(document.getElementById('doughnut-pie'), { type: 'doughnut', plugins:[ {beforeDraw: function(chart){ var width=chart.chart.width, height=chart.chart.height, ctx= chart.chart.ctx; ctx.restore(); var fontSize=(height/55).toFixed(2); //розмір шрифта (підбирай число замість 150) ctx.font=fontSize+"em sans-serif"; ctx.textBaseline="middle"; var text="MC", textX=Math.round((width-ctx.measureText(text).width)/2), //вирівнювання по горизонталі textY=height/2; //вирівнювання по вертикалі ctx.fillText(text, textX, textY); ctx.save(); } } ], data: data, options: { responsive: true, cutoutPercentage: 65, maintainAspectRatio: false, legend: { display: false } } });
var searchData= [ ['quitkey',['QuitKey',['../class_otter_1_1_game.html#a8756fa4466909d292cb5ebf182b0a92f',1,'Otter::Game']]] ];
import Geral from '../model/geral'; import Cordenador from '../model/cordenacao'; import Aluno from '../model/Aluno'; import Colaborador from '../model/colaborador'; import Curso from '../model/curso'; exports.getIndex = async (req, res, next) => { const cordenador = await Cordenador.showDate(); const aluno = await Aluno.shows(); const colaborador = await Colaborador.showDate(); res.render('pages/admin/admin', { wel: req.flash('welcome'), cordenador, aluno, colaborador, }); }; exports.cadastrar = async (req, res, next) => { const [cursos] = await Geral.Dates(); const dados = await Cordenador.showDate(); res.render('pages/admin/cadastrar', { cursos, dados }); }; exports.detalhes = async (req, res, next) => { const id = req.params.id; const [cursos] = await Geral.Dates(); const cordenador = await Cordenador.show(id); res.render('pages/admin/detalhes', { dado: cordenador[0], cursos }); }; exports.gerir = async (req, res, next) => { const dados1 = await Aluno.shows(); const dados2 = await Colaborador.showDate(); const dados = [dados1, dados2]; res.render('pages/admin/gerir', { dados }); }; exports.postCadastrarCordenador = async (req, res) => { const { nome, bi, curso, descricao } = req.body; const [filePhonto, fileBI] = req.files; const cursos = await Curso.store({ nomeCurso : curso, descricao }); const cordenador = new Cordenador( nome, bi, fileBI.filename, filePhonto.filename, cursos ); await cordenador.save(); res.redirect('/admin/cadastrar'); }; exports.updatePassword = async (req, res, nex) => { const { password, id } = req.body; await Aluno.update(id, { palavraPasse: password }); req.session.destroy(() => { res.redirect('/gerir'); }); };
(function(){ if(window.location.href.indexOf('debug') != -1){ render([{ title: { text: '' }, data: Util.getChartDataExample() }]); }else{ if(window.location.host == 'testing.sng.local'){ console.log('需要较长的加载分析时间。有问题请反馈给maltoseli'); var srcs = [ 'http://liyatang.github.io/HCharts/Highcharts/js/highcharts.src.js', 'http://liyatang.github.io/HCharts/Highcharts/js/themes/grid.js', 'http://liyatang.github.io/HCharts/Highcharts/js/modules/exporting.src.js', 'http://liyatang.github.io/HCharts/js/util.js', 'http://liyatang.github.io/HCharts/js/report_manager.js', 'http://liyatang.github.io/HCharts/js/source_manager.js', 'http://liyatang.github.io/HCharts/config/config.js' ]; // javascript:(function(){var w=window,d=w.document,b=d.body,s=d.createElement("script");s.src="http://liyatang.github.io/HCharts/js/index.js";b.appendChild(s);})(); loadHChartsScript(srcs, function(){ if(!confirm("ok AndroidQQ 消息监控自动化测试运行报告 \ncancel 【QTA】AndroidQQ+核心专项自动化(一二期-不含流量)运行报告")){ config.source.realReport = config.source.realReport2; } var page = $('div.pages .current').html() || 1; config.source.realReport.page = page; var dom = $('<div><span>loading...</span><div></div></div>'); dom.css({ position: 'fixed', width: '100%', height: '100%', top: '0px', overflow: 'scroll' }); $(document.body).append(dom); var sourceManagerRealTime = sourceManagerFactory.getSourceManagerRealTime(function(){ console.log('getSourceManagerRealTime'); var data = sourceManagerRealTime.getDataRealTime(); render(data, dom.find('div')); }, window.location.href.indexOf('getAll') != -1, getParamter('page') || 2); }); }else{ var sourceManager = sourceManagerFactory.getSourceManager(function(){ var data = sourceManager.getData(); render(data); }); } } function getParamter(name){var r=new RegExp("(\\?|#|&)"+name+"=([^&#]*)(&|#|$)");var m=location.href.match(r);return(!m?"":m[2]);} function render(data, contain){ var html = '<div class="charts_container"><span class="title">title</span><div class="charts"></div></div>'; console.log('render'); console.log(data); if(!contain){ contain = $(document.body); } for(var i = 0; i < data.length; i ++){ var d = data[i]; var dom = $(html); dom.find('.title').html(d.title.text); dom.find('.charts').highcharts(d.data); contain.append(dom); } } function loadHChartsScript(srcs, callback, i){ if(i == null){ i = 0; } loadScript(srcs[i], function(src){ console.log(src); if(i == srcs.length - 1){ callback(); }else{ loadHChartsScript(srcs, callback, i +1); } }) } function loadScript(src, callback){ $.getScript(src, function(){ callback(src); }) } })();
var gulp = require('gulp'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); gulp.task('default', function() { return gulp.src([ 'lib/stdio.js', // necessary 'lib/structure/binary-heap.js', 'lib/graph/Dijkstra.js', // code snippets 'src/main.js' // main source ]).pipe(sourcemaps.init()) .pipe(concat('main.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest('dist')); });
document.addEventListener('DOMContentLoaded', () => { const $ = require('jquery') console.log('App Initialized') })
export * from "./Clover";
'use strict'; describe('lists location socials', function () { var $scope; var element; var $location; var socialFactory; var locationFactory; var splashFactory; var q; var deferred; var $httpBackend; beforeEach(module('myApp', function($provide) { socialFactory = { query: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, get: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, update: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, }; $provide.value("Social", socialFactory); })); beforeEach(module('components/reports/social/_show.html')); describe('new social tests', function() { beforeEach(inject(function($compile, $rootScope, $q, _$location_, $injector) { $httpBackend = $injector.get('$httpBackend'); $httpBackend.whenGET('template/pagination/pagination.html').respond(""); $scope = $rootScope; $location = _$location_; q = $q; $scope.voucher = { unique_id: 123 }; element = angular.element('<analytics><list-social></list-social></analytics>'); $compile(element)($rootScope) element.scope().$apply(); })); // Arg, the bloody require directive // xit("should display the voucher socials", function() { spyOn(socialFactory, 'get').andCallThrough() expect(element.isolateScope().loading).toBe(true) var socials = {social: [{ username: 'simons' }] } deferred.resolve(socials); $scope.$apply() expect(element.isolateScope().socials[0]).toBe(socials.social[0]); expect(element.isolateScope().loading).toBe(undefined) }); }); describe('new social show', function() { beforeEach(inject(function($compile, $rootScope, $q, _$location_, $injector) { $scope = $rootScope; $location = _$location_; q = $q; $scope.voucher = { unique_id: 123 } $scope.social = {} element = angular.element('<show-social></show-social>'); $compile(element)($rootScope) element.scope().$apply(); })); it("should display the socials details", function() { spyOn(socialFactory, 'query').andCallThrough() expect(element.isolateScope().loading).toBe(true) var social = { social: { username: 'simons' }, clients: [{ man: 123 }]} deferred.resolve(social); $scope.$apply() expect(element.isolateScope().social).toBe(social.social); expect(element.isolateScope().clients).toBe(social.clients); expect(element.isolateScope().loading).toBe(undefined) }); it("should update the socials details", function() { spyOn(socialFactory, 'update').andCallThrough() element.isolateScope().social = { state: 'xxx' }; element.isolateScope().update() expect(element.isolateScope().social.state).toBe('updating') var social = { social: { username: 'simons' }, client: { man: 123 } } deferred.resolve(social); $scope.$apply() expect(element.isolateScope().social.state).toBe('updated') }); it("should not update the socials details", function() { spyOn(socialFactory, 'update').andCallThrough() element.isolateScope().social = { state: 'xxx' }; element.isolateScope().update() expect(element.isolateScope().social.state).toBe('updating') var social = { social: { username: 'simons' }, client: { man: 123 } } deferred.reject(social); $scope.$apply() expect(element.isolateScope().social.state).toBe(undefined) expect(element.isolateScope().social.errors).toBe('There was a problem updating this user.') }); }); });
import React from "react"; import HistoryBody from "./history-components/HistoryBody.js"; import HistoryHeader from "./history-components/HistoryHeader.js"; const History = () => { return ( <div id="history"> <HistoryHeader /> <HistoryBody /> </div> ) } export default History
(function(){ var ListAllUsersCtrl = function($scope, $location, $routeParams, $window, userServices) { console.log('Page loaded.'); $scope.items = []; $scope.returntomenu = function(){ window.location="/menuadmin"; }; userServices.logged() .then(function(result) { console.log('User data loaded.'); $scope.user = result.data; $scope.userid = result.data.idusers; userServices.getAllUsers() .then(function (users) { console.log(users.data); $scope.users = users.data; console.log($scope.users); var i; }) .catch(function (err) { $scope.items.pop(); $scope.items.push(err.data.message); }); }) .catch(function(err) { $scope.items.pop(); $scope.items.push(err.data.message); }); $scope.pop = function () { $scope.items.pop(); }; }; // Injecting modules used for better minifing later on ListAllUsersCtrl.$inject = ['$scope', '$location', '$routeParams', '$window','userServices']; // Enabling the controller in the app angular.module('ideasmanagement').controller('ListAllUsersCtrl', ListAllUsersCtrl); }());
/** * @author v.lugovsky * created on 16.12.2015 */ (function () { 'use strict'; angular.module('BlurAdmin.pages.app.specialmenu.specialbranch', []) .config(routeConfig); /** @ngInject */ function routeConfig($stateProvider) { $stateProvider .state('app.specialmenu.specialbranch', { url: '/specialbranch', templateUrl: 'app/pages/app/specialmenu/specialbranch/specialbranch.html', controller: 'SpecialBranchCtrl', title: 'special.special branch', sidebarMeta: { icon: 'ion-android-home', order: 4, }, }); } })();
var http = require('http'), fs = require('fs'); function serveStaticFile(res, path, contentType, response) { if(!responseCode) responseCode = 200; fs.readFile(__dirname + path, function(err, data){ if(err) { res.writeHead(500, {'content-type': 'text/plain'}); res.end('500 - Internal Error'); }else{ res.writeHead(responseCode, {'Content-Type': contentType}); res.end(data); } }) } http.createServer(function(req, res){ }).listen(3000);
function solve(args){ var encStr = args[0], magicKey = +args[1], matrix = args, newMatrix = [], mLen, numbers = [], code = [], letters = [], result; mLen = matrix.length; for(var i = 2; i < mLen; i+=1){ newMatrix[i] = matrix[i].split(' '); } newMatrix = newMatrix.filter(Boolean); var nmLen = newMatrix.length; var currentLen = newMatrix[0].length; for(var j = 0; j < nmLen; j+=1){ for(var k = 0; k < currentLen; k+= 1){ newMatrix[j][k] = +newMatrix[j][k]; var l = 0; while(l < nmLen){ var m = 0; while(m < currentLen){ currentNumber = +newMatrix[l][m]; //console.log(newMatrix[j][k]+currentNumber) if(((newMatrix[j][k]+currentNumber) === magicKey && l!==j) || ((newMatrix[j][k]+currentNumber) === magicKey && m!==k) ){ numbers.push(l); numbers.push(m); } m+=1; } l+=1; } } } var numLen = numbers.length; var sum = 0; for(var n = 0; n < numLen; n+=1){ sum+=numbers[n]; } var strLen = encStr.length; for(var p = 0; p < strLen; p+=1){ if(p%2===0){ code[p] = encStr.charCodeAt(p) + sum; } else { code[p] = encStr.charCodeAt(p) - sum; } letters[p] = String.fromCharCode(code[p]); } result = letters.join(''); console.log(result); } test = [ 'Vi`ujr!sihtudts', '0', '0 0 120 300', '100 9 300 100', '1 290 370 100', '10 11 100 550']; solve(test);
const express = require("express"); const router = express.Router(); const Movie = require("../models/Movie.model"); // Movies list router.get("/list", (req, res, next) => { Movie.find({ genre: { $regex: req.query.genre } }) .where({ "imdbrating": { "$ne": "N/A" } }) .sort({ 'imdbrating': -1 }).limit(100) .then(MoviesByGenre => res.render('movies/movies-list', { movies: MoviesByGenre })) .catch(error => console.log(error)) }) // Movie Detail router.get("/detail", (req, res, next) => { Movie.findOne({ netflixid: req.query.netflix_id }) .then(theMovie => { let favouriteAdded = false; let blackAdded = false; let viewAdded = false; if (req.user) { if (req.user.favList.includes(theMovie._id)) favouriteAdded = true if (req.user.blackList.includes(theMovie._id)) blackAdded = true if (req.user.viewList.includes(theMovie._id)) viewAdded = true } res.render("movies/movie-detail", { user: req.user, movie: theMovie, // movieJSON: JSON.stringify(theMovie), favouriteAdded, blackAdded, viewAdded }); }) .catch(error => console.log(error)); }); // Update router.post("/edit", (req, res, next) => { console.log('-----------------------------------------') const { netflixid, title, image, synopsis, genre, type, released, largeimage, unogsdate, imdbid, download, imdbrating } = req.body console.log('antes de actualizar', download) Movie.findOneAndUpdate({ netflixid: netflixid }, { $set: { netflixid, title, image, synopsis, genre, type, released, largeimage, unogsdate, imdbid, download, imdbrating } }, { new: true }) .then(movieUpdated => { res.redirect(`/detail?netflix_id=${netflixid}`) }) .catch(error => console.log(error)); }) // Delete movie router.post('/delete', (req, res, next) => { // console.log(req.body.netflixid) Movie.findOneAndDelete({ netflixid: req.body.netflixid }) .then(theMovie => { res.redirect('/') }) .catch(error => console.log(error)) }) module.exports = router;
Ext.define('PWApp2.Application', { name: 'PWApp2', extend: 'Ext.app.Application', views: [ 'layout.MapView', 'layout.RecordView', // 'layout.ScoreCardView', 'layout.HelpView', 'filter.View', 'filter.ChemLineView', 'filter.BasinLineView', 'layout.LegendView', 'layout.CiteListView' ], controllers: [ 'MapController', // 'ScoreCardController', 'RecordController', 'HelpController', 'FilterController', 'LegendController' // 'NationalController' ], stores: [ ] });
function getRandomInt() { return Math.floor(Math.random()*4); } function initPlayers() { let players = [] players[1] = { name: "Francesca", score: 0, } return players } function SetStateOccupied() { if (!IsOccupied()){ console.log("La cella è occupata!");} } function SetStateFree () { var cell=[]; for (let i=0; i<6; i++) { for (let j=0; j<6; j++) { if(cell[i]=="" && cell[j]=="") return true; } } } function IsOccupied () { var cell=[]; for (let i=0; i<6; i++) { for (let j=0; j<6; j++) { if(cell[i]!="" && cell[j]!="") return false; } } } function initGrid() { let table = document.getElementById("table") let cells = [] for(let i = 0; i < 6; i++) { let row = document.createElement("tr") for(let j = 0; j < 6; j++) { let cell = document.createElement("td") cell.id = i * 6 + j + 1 row.appendChild(cell) cells.push(cell) } table.appendChild(row); } return cells } var players = initPlayers() initGrid(); class BasePiece { constructor(ui) { putOnGrid() } }
/* Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers. */ function order(words) { var newArr=[] newWords=words.split(' ') let k = 1 for (let i=0;i<newWords.length;i++) { if (newWords[i].indexOf(k)>-1) { newArr.push(newWords[i]); i=-1 k++ } } console.log(newArr) return newArr.join(' ') } order("is2 Thi1s T4est 3a") /*function order(words){ let i=0 let onlyNumb=[] let newArr=[] let newWords=words.split(' ') for (i; i<newWords.length;i++){ let regExpNum = /\d+/g; onlyNumb=words.match( regExpNum ); onlyNumb.sort(); } } order("is2 Thi1s T4est 3a") */
import reducer from "./reducer"; import * as constants from "./actionTypes" import * as actionCreators from "./actionCreators" export {reducer, constants, actionCreators}
var _ = require('lodash'), expect = require('chai').expect, request = require('request'), sinon = require('sinon'), elemez2csv = require('../lib/elemez2csv'); describe('elemez2csv', function() { var argv; beforeEach(function() { argv = ['node', 'elemez2csv', '--token', 'TOKEN']; }); it('should return error if you do not provide token', function(done) { argv.splice(2, 2); elemez2csv(argv, function(e) { expect(e).to.equal('Usage: elemez2csv --token <TOKEN> [--types <TYPES>] [--data <ADDITIONALDATAFIELDS>]'); return done(); }); }); describe('with one page of data', function() { beforeEach(function() { sinon.stub(console, 'log'); sinon.stub(request, 'get'); var events = _.map(_.range(0, 5), function(i) { return { key: 'k' + i, scheme: 'sch' + i, schemeid: 'sid' + i, received: Date.UTC(2014, i, 1), raised: Date.UTC(2014, i, 2), sender: 'sdr' + i, source: 'src' + i, type: 't' + i, data: { a: i, b: { c: i } } }; }); var response0 = { lastKey: 'X', events: events }; var response1 = { lastKey: null, events: [ ] }; request.get.onCall(0).yields(null, null, response0); request.get.onCall(1).yields(null, null, response1); }); afterEach(function() { console.log.restore(); request.get.restore(); }); it('should call request correctly', function(done) { return elemez2csv(argv, function() { expect(request.get.calledTwice).to.be.true; var options0 = { url: 'https://elemez.com/raw/1', json: true, headers: { token: 'TOKEN' } }; expect(request.get.args[0][0]).to.deep.equal(options0); var options1 = { url: 'https://elemez.com/raw/1', json: true, headers: { token: 'TOKEN' }, qs: { lastkey: 'X', limit: 1000 } }; expect(request.get.args[1][0]).to.deep.equal(options1); return done(); }); }); it('should console.log the data as CSV', function(done) { return elemez2csv(argv, function() { expect(console.log.callCount).to.equal(5); expect(console.log.args[0][0]).to.equal('k0,sch0,sid0,2014-01-01T00:00:00.000Z,2014-01-02T00:00:00.000Z,sdr0,src0,t0'); expect(console.log.args[1][0]).to.equal('k1,sch1,sid1,2014-02-01T00:00:00.000Z,2014-02-02T00:00:00.000Z,sdr1,src1,t1'); expect(console.log.args[2][0]).to.equal('k2,sch2,sid2,2014-03-01T00:00:00.000Z,2014-03-02T00:00:00.000Z,sdr2,src2,t2'); expect(console.log.args[3][0]).to.equal('k3,sch3,sid3,2014-04-01T00:00:00.000Z,2014-04-02T00:00:00.000Z,sdr3,src3,t3'); expect(console.log.args[4][0]).to.equal('k4,sch4,sid4,2014-05-01T00:00:00.000Z,2014-05-02T00:00:00.000Z,sdr4,src4,t4'); return done(); }); }); it('should filter types if passed', function(done) { argv = ['node', 'elemez2csv', '--token', 'TOKEN', '--types', 't2,t3']; return elemez2csv(argv, function() { expect(console.log.callCount).to.equal(2); expect(console.log.args[0][0]).to.equal('k2,sch2,sid2,2014-03-01T00:00:00.000Z,2014-03-02T00:00:00.000Z,sdr2,src2,t2'); expect(console.log.args[1][0]).to.equal('k3,sch3,sid3,2014-04-01T00:00:00.000Z,2014-04-02T00:00:00.000Z,sdr3,src3,t3'); return done(); }); }); it('should return data if passed', function(done) { argv = ['node', 'elemez2csv', '--token', 'TOKEN', '--data', 'a,c']; return elemez2csv(argv, function() { expect(console.log.callCount).to.equal(5); expect(console.log.args[0][0]).to.equal('k0,sch0,sid0,2014-01-01T00:00:00.000Z,2014-01-02T00:00:00.000Z,sdr0,src0,t0,0,0'); expect(console.log.args[1][0]).to.equal('k1,sch1,sid1,2014-02-01T00:00:00.000Z,2014-02-02T00:00:00.000Z,sdr1,src1,t1,1,1'); expect(console.log.args[2][0]).to.equal('k2,sch2,sid2,2014-03-01T00:00:00.000Z,2014-03-02T00:00:00.000Z,sdr2,src2,t2,2,2'); expect(console.log.args[3][0]).to.equal('k3,sch3,sid3,2014-04-01T00:00:00.000Z,2014-04-02T00:00:00.000Z,sdr3,src3,t3,3,3'); expect(console.log.args[4][0]).to.equal('k4,sch4,sid4,2014-05-01T00:00:00.000Z,2014-05-02T00:00:00.000Z,sdr4,src4,t4,4,4'); return done(); }); }); }); });
var fs = require('fs') var parseOpts = (txt) => { var lines = txt.split("\n") var regline = /\s+--([a-zA-Z]+)\s(.+)\s\[(.*)\]/ let opt = null let opts = [] lines.forEach(element => { let res = /\s+-(\S+)\s(-*\d+)\.+(\S+)\s\[(.*)\]/.exec(element) if(res) { if(opt) opts.push(opt) opt = { name: res[1], min: parseFloat(res[2]), max: parseFloat(res[3]), default: res[4], description: "" } } else { res = regline.exec(element) if(res) { if(opt) opts.push(opt) opt = { name: res[1], select: res[2].split("|"), default: res[3], description: "" } } else { res = /\s+--.*/.exec(element) if(res) { if(opt) opts.push(opt) opt = null } else if(opt) opt.description += element } } }); console.log(opts) } try { var data = fs.readFileSync('test.txt', 'utf8'); parseOpts(data.toString()); } catch(e) { console.log('Error:', e.stack); }
const cityClasses = document.body.classList; console.log(cityClasses); if (cityClasses.contains('preston')) { var page = "Preston"; var locID = "id=5604473"; } else if (cityClasses.contains('sodaSprings')) { var page = "SodaSprings"; var locID = "id=5607916"; } else if (cityClasses.contains("fishHaven")) { var page = "FishHaven"; var locID = "lat=42.0380399&lon=-111.4048681"; } const apiURL = "https://api.openweathermap.org/data/2.5/weather?" + locID + "&appid=164f498c15ca0ca0e8f322a9fd449b46&units=imperial"; const forecastURL = "https://api.openweathermap.org/data/2.5/forecast?" + locID + "&appid=164f498c15ca0ca0e8f322a9fd449b46&units=imperial"; console.log(apiURL); fetch(apiURL) .then((response) => response.json()) .then((jsObject) => { console.log(jsObject); let temp = jsObject.main.temp; let windSpeed = jsObject.wind.speed; //Current Condition document.getElementById('currentCondition').textContent = jsObject.weather[0].main; //Current Temp document.getElementById('currentTemp').textContent = Math.round(jsObject.main.temp) + " °F"; //Highest Temp document.getElementById('high-temp').textContent = Math.round(jsObject.main.temp_max) + " °F"; //Wind Speed document.getElementById('wind-speed').textContent = jsObject.wind.speed; //Wind Chill let speed = Math.pow(windSpeed, 0.16); let windChill = Math.round(35.75 + (0.6215 * temp) - (35.75 * speed) + (0.4275 * temp * speed)); if (temp <= 50 && windSpeed > 3) { document.getElementById('wind-chill').textContent = windChill + " °F"; } else { document.getElementById('wind-chill').textContent = "N/A"; } //Humidity Level document.getElementById('humidity').textContent = jsObject.main.humidity + " %"; }); fetch(forecastURL) .then((response) => response.json()) .then((jsObject) => { console.log(jsObject); const fiveDays = jsObject.list.filter(item => item.dt_txt.includes('18:00:00')); console.log() for (i = 0; i < 1; i++) { fiveDays.forEach(forecast => { console.log(forecast); let card = document.createElement('section'); let weekDay = document.createElement('p'); let image = document.createElement('img'); let temp = document.createElement('p'); var date = new Date(forecast.dt_txt); var day = date.toString(); day = day.slice(0, 3); weekDay.textContent = day; image.setAttribute('src', "https://via.placeholder.com/100.png?text=Placeholder"); image.setAttribute('data-src', 'https://openweathermap.org/img/wn/' + forecast.weather[0].icon + '@2x.png'); image.setAttribute('alt', forecast.weather[0].description); temp.textContent = Math.round(forecast.main.temp) + " °F"; card.className = "days"; card.appendChild(weekDay); card.appendChild(image); card.appendChild(temp); document.querySelector('div.town-cards').appendChild(card); }) } }) .then(function(imagesToLoad = document.querySelectorAll('img[data-src]')) { const loadImages = (image) => { image.setAttribute('src', image.getAttribute('data-src')); image.onload = () => { image.removeAttribute('data-src'); }; }; const imgOptions = { threshold: 0 }; if ('IntersectionObserver' in window) { const observer = new IntersectionObserver((items, observer) => { items.forEach((item) => { if (item.isIntersecting) { loadImages(item.target); observer.unobserve(item.target); } }); }, imgOptions); imagesToLoad.forEach((img) => { observer.observe(img); }); } else { imagesToLoad.forEach((img) => { loadImages(img); }); } } );
const dateToText = (date) => { const monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; let formattedDate = ''; if (date !== '') { const currentDate = new Date(date); const day = currentDate.getUTCDate(); const month = currentDate.getUTCMonth(); const year = currentDate.getUTCFullYear(); formattedDate = monthNames[month] + " " + day + ", " + year; } return formattedDate; } export const getOrderedArray = (events) => { const orderedArray = events.sort(function (a, b) { return parseInt(a.date.replace(/-/gi, '')) - parseInt(a.date.replace(/-/gi, '')); }); return orderedArray } export default dateToText;
/* Created By - Valasubramanian.s on 10-May-2015 * ------------------------------------------------------------------------------------------------- * Modified By - * ------------------------------------------------------------------------------------------------- * Purpose - Custome Validation jQuery Plugin * -------------------------------------------------------------------------------------------------*/ function PageValidation(vid, Title, liTitle, isStepValidation) { return Validation.Start(vid, Title, liTitle, isStepValidation); } var Validation = new function () { this._$divid = ""; this._$container = ""; this._errMessage = ""; this._isrequired = false; this._nbr = '0123456789'; this._$currentdate = ""; this._lwr = 'abcdefghijklmnopqrstuvwxyz'; this._uwr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; this._msgTitle = ""; this._msgliTitle = ""; this._isStepValidation = true; this.Start = function (vid, Title, liTitle, isStepValidation) { if (isStepValidation == undefined) { isStepValidation = true; } Validation._msgTitle = Title; Validation._msgliTitle = liTitle; Validation._isStepValidation = isStepValidation; return Validation.initvalidation("", "", vid); } this.initvalidation = function (divid, errcontainer, vid) { Validation._$container = "#" + errcontainer; Validation._$divid = "#" + divid; var _isValid = true; var _olcontent = ""; if (Validation._isStepValidation) { $("#" + vid + ":visible .validate").each(function () { var _this = this; if (!Validation._$Jvalidate(_this)) { _isValid = false; Validation.appednStepValidationAlert(_this, Validation._errMessage); return false; } }); } else { $("#" + vid + ":visible .validate").each(function () { var _this = this; if (!Validation._$Jvalidate(_this)) { _olcontent = _olcontent + '<li id="li_' + _this.id + '" class="div100 dleft"><label class="error dleft" id="lbl_' + _this.id + '" for="' + _this.id + '">' + Validation._errMessage + '</label></li>'; _isValid = false; } }); if (!_isValid) { alert((Validation._msgliTitle + "<ul class='msgul'>" + _olcontent + "</ul>"), Validation._msgTitle, ""); //bsc.WAlert("<ul class='msgul mrgtop10 div100 dleft'>" + _olcontent + "</ul>", "Validation"); } } return _isValid; } this.appednStepValidationAlert = function (_this, errMsg) { var _target = _this; var th = $(_this); var _body = $('body'); var _validAlert = $("<div class='step-validation' for='" + _this.id + "'><span class='top-arrow'>&nbsp;</span><div class='step-validation-msg'><i class='fa fa-ban'></i>&nbsp;&nbsp;" + errMsg + "</div></div>"); var _pos = Validation.GetScreenCordinates(_target); _validAlert.css({ top: _pos.y + th.height() + 20 + 'px' }); if (th.parent('.form-group,.input-group').length > 0) { _pos = Validation.GetScreenCordinates(th.parent('.form-group,.input-group')[0]); } _validAlert.css({ left: _pos.x + 'px' }); _validAlert.css("max-width", $(_target).width() - 10 + 'px'); Validation.removeStepValidationAlert(); _body.append(_validAlert); setTimeout(function () { Validation.removeStepValidationAlert(true); }, 2000); th.bind('click', function () { Validation.removeStepValidationAlert(); }); th.bind('keypress', function () { Validation.removeStepValidationAlert(); }); $(window).resize(function () { Validation.reappendStepValidationAlert(); }); } this.removeStepValidationAlert = function (isSlide) { if (isSlide == undefined) { isSlide = false; } if (isSlide) { $('div.step-validation').slideUp(function () { $(this).remove() }); } else { $('div.step-validation').remove(); } } this.reappendStepValidationAlert = function () { var _sv = $('div.step-validation'); if (_sv.length > 0) { var _target = $('#' + _sv.attr('for')); if (_target != undefined && _target.length > 0) { var _pos = Validation.GetScreenCordinates(_target[0]); _sv.css({ top: _pos.y + _target.height() + 20 + 'px' }); if (_target.parent('.form-group,.input-group').length > 0) { _pos = Validation.GetScreenCordinates(_target.parent('.form-group,.input-group')[0]); } _sv.css({ left: _pos.x + 'px' }); } } } this._$Jvalidate = function (obj) { if (obj.id == "") { return true; } var _$obj = $(obj); var _clsName = obj.className; var _arrval = new Array(); _arrval = _clsName.split("{"); Validation._isrequired = false; if (_arrval.length > 0) { _clsName = _arrval[_arrval.length - 1]; _arrval = _clsName.split("}"); _clsName = _arrval[0]; _arrval = _clsName.split(","); var _valtype = ""; if (_arrval.length > 0) { for (var _evali = 0; _evali < _arrval.length - 1; _evali++) { _valtype = _arrval[_evali].toLowerCase(); switch (_valtype) { case "req": case "required": case "dreq": case "visreq": case "togglereq": case "chkreq": case "ereq": Validation._isrequired = true; var _blnResult = true; if (!_$obj.hasClass("vroff")) { if (_valtype == "dreq") { _evali = _evali + 1; var _trimVal = _RTrim(obj.value).toLowerCase(); var notValue = _arrval[_evali].toLowerCase(); _blnResult = (_trimVal == "" || _trimVal == notValue) ? false : _blnResult; if (!_blnResult && _trimVal != "") { Validation._errMessage = _arrval[_arrval.length - 1] + " value should not be " + notValue + "."; return false; } } else if (_valtype == "togglereq" || _valtype == "chkreq") { _evali = _evali + 1; var _chkobj = $('#' + _arrval[_evali]); if (_chkobj.length > 0) { _blnResult = (_valtype == "togglereq" && !_chkobj[0].checked) ? Validation.RequiredValidate(obj) : (_valtype == "chkreq" && _chkobj[0].checked) ? Validation.RequiredValidate(obj) : _blnResult; } } else { _blnResult = (_valtype == "req" || _valtype == "required" || _valtype == "ereq" || (_valtype == "visreq" && _$obj.filter(":visible").length > 0 && _$obj.filter('[disabled="disabled"]')).length == 0) ? Validation.RequiredValidate(obj) : _blnResult; } if (_blnResult == false) { switch (obj.type) { case "text": case "password": Validation._errMessage = (_valtype == "ereq") ? _arrval[_arrval.length - 1] : _arrval[_arrval.length - 1] + " " + _$required; break; case "select-one": Validation._errMessage = (_valtype == "ereq") ? _arrval[_arrval.length - 1] : _arrval[_arrval.length - 1] + " " + _$required; break; case "checkbox": Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$requiredchk; break; default: Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$required; break; } return false; } } break; case "emailcmp": case "pwdcmp": _evali = _evali + 1; var pwd = $('#' + _arrval[_evali]); if (pwd.length > 0 && obj.value != pwd[0].value) { Validation._errMessage = _valtype == "emailcmp" ? _$emailcmp : _$pwdcmp; /*Validation._errMessage = Validation._errMessage.replace(/xxxx/, _arrval[_evali + 1]);*/ return false; } break; case "domain": var dname = _RTrim(obj.value); for (var j = 0; j < dname.length; j++) { var dh = dname.charAt(j); var hh = dh.charCodeAt(0); if ((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46) { if ((j == 0 || j == dname.length - 1) && hh == 45) { Validation._errMessage = _arrval[_evali + 1] + " should not begin or end with '-'"; return false; } } else { Validation._errMessage = _arrval[_evali + 1] + " should not have special characters"; return false; } } break; case "email": if (Validation.EmailValidation(obj) == false) { Validation._errMessage = _$email; return false; } break; case "url": if (Validation.isUrl(obj.value) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$url; return false; } break; case "cusurl": //validate start with "http" / "https" / "ftp" / "www" / "/" if (Validation.isCusUrl(obj.value) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$url; return false; } break; case "mincl": _evali = _evali + 1; if (_RTrim(obj.value).length < _arrval[_evali]) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$mincl.replace(/xxxx/, _arrval[_evali]); return false; } break; case "maxcl": _evali = _evali + 1; if (_RTrim(obj.value).length > parseInt(_arrval[_evali], 10)) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$maxcl.replace(/xxxx/, _arrval[_evali]); return false; } break; case "eqcl": _evali = _evali + 1; var _trimVal = _RTrim(obj.value); if (_trimVal.length > 0 && _trimVal.length != parseInt(_arrval[_evali], 10)) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$eqcl.replace(/xxxx/, _arrval[_evali]); return false; } break; case "date": case "mmddyy": case "ddmmyy": case "yymmdd": case "mmddyyyy": var _type = (_valtype == "date" || _valtype == "mmddyy") ? 1 : (_valtype == "ddmmyy") ? 2 : (_valtype == "yymmdd") ? 3 : (_valtype == "mmddyyyy") ? 4 : 0; if (_type != 0) { if (Validation.datevalidate(obj, _type) == false) { _type = (_valtype == "date" || _valtype == "mmddyy") ? "mm/dd/yy" : (_valtype == "ddmmyy") ? "dd/mm/yy" : (_valtype == "yymmdd") ? "yy/mm/dd" : (_valtype == "mmddyyyy") ? "mm/dd/yyyy" : ""; Validation._errMessage = _arrval[_arrval.length - 1] + " " + Validation._errMessage.replace(/xxxx/, _type); return false; } } break; case "amt": case "dbl": case "double": case "dbl3d": case "dbl4d": var _digit = (_valtype == "dbl3d") ? 3 : (_valtype == "dbl4d") ? 4 : 2; if (Validation.IsDouble(obj, _digit) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + Validation._errMessage; return false; } break; case "num": case "number": if (Validation.isValid(Validation._nbr, obj.value) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$nbr; return false; } break; case "greaterthan": case "graterthan": case "gt": _evali = _evali + 1; var _grVal = _arrval[_evali]; if (parseInt(obj.value, 10) <= parseInt(_grVal, 10)) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$gt + " " + _grVal + "."; return false; } break; case "lessthan": case "lt": _evali = _evali + 1; var _grVal = _arrval[_evali]; if (parseInt(obj.value, 10) > parseInt(_grVal, 10)) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$max + " " + _grVal + "."; return false; } break; case "cmptocurdate": if (Validation.CurrentDateCompare(obj, _arrval[_evali - 1].toLowerCase()) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$cmpdate; return false; } break; case "ext": _evali = _evali + 1; if (Validation.Validateext(obj, _arrval[_evali]) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$filetype.replace(/xxxx/, _arrval[_evali].replace(/[.]/g, ',')); return false; } break; case "pwd": if (Validation.isAlphaNumeric(obj.value) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$pwd; return false; } break; case "alphanum": if (Validation.isValid(Validation._nbr + Validation._lwr + Validation._uwr, obj.value) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$anbr; return false; } break; case "notstartwith": _evali = _evali + 1; var _len = _arrval[_evali].length; if (_RTrim(obj.value).substring(0, _len).toLowerCase() == _arrval[_evali].toLowerCase()) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$notstartwith.replace(/xxxx/, _RTrim(obj.value).substring(0, _len)); return false; } break; case "chkgrpreq": case "rdbgrpreq": _evali = _evali + 1; var _chkRdoObj = $('#' + obj.id); if (!_chkRdoObj.hasClass(_arrval[_evali])) { _chkRdoObj.addClass(_arrval[_evali]); } if (Validation.ValidateCheckBoxList($('.' + _arrval[_evali])) == false) { Validation._errMessage = _arrval[_arrval.length - 1]; return false; } break; case "visichkgrpreq": case "visirdbgrpreq": _evali = _evali + 1; var _chkRdoObj = $('#' + obj.id); if (!_chkRdoObj.filter(':visible').hasClass(_arrval[_evali])) { _chkRdoObj.addClass(_arrval[_evali]); } if (Validation.ValidateCheckBoxList($('.' + _arrval[_evali]).filter(':visible')) == false) { Validation._errMessage = _arrval[_arrval.length - 1]; return false; } break; case "filegrpreq": _evali += 1; var _fileObj = $('#' + obj.id); if (!_fileObj.hasClass(_arrval[_evali])) { _fileObj.addClass(_arrval[_evali]); } if (Validation.ValidateFilesList($('.' + _arrval[_evali])) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$required; return false; } break; case "txtgrpreq": _evali = _evali + 1; var blnAllow = false; $("." + _arrval[_evali]).each(function () { if (Validation.RequiredValidate(this)) { blnAllow = true; } }); if (!blnAllow) { Validation._errMessage = _arrval[_arrval.length - 1]; return false; } break; case "datepattern": if (_$obj.filter(":visible").length > 0) { if (Validation.IsDatePattern(obj) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$dtptt; return false; } } break; case "timepattern": if (_$obj.filter(":visible").length > 0) { if (Validation.IsTimePattern(obj) == false) { Validation._errMessage = _arrval[_arrval.length - 1] + " " + _$dtptt; return false; } } break; case "methodreq": case "mreq": _evali = _evali + 1; var _Val = _arrval[_evali]; _Val = eval(_Val); if (!_Val) { Validation._errMessage = _arrval[_arrval.length - 1]; return false; } break; } } return true; } } } this.isValid = function (key, val) { var parm = val; for (i = 0; i < parm.length; i++) { if (key.indexOf(parm.charAt(i), 0) == -1) { return false; } } return true; } this.RequiredValidate = function (obj) { var _trimVal = _RTrim(obj.value); switch (obj.type) { case "text": case "password": case "file": case "textarea": if (_trimVal == "") { return false; } break; case "select-one": if (_trimVal == "" || _trimVal == "-1" || _trimVal == "0") { return false; } break; case "checkbox": if (obj.checked == false) { return false; } break; } return true; } this.IsDatePattern = function (obj) { return Validation.isValid("dMy ,-/", obj.value); } this.IsTimePattern = function (obj) { return Validation.isValid("hHmst :", obj.value); } this.Validateext = function (obj, _type) { var _fval = _RTrim(obj.value).toLowerCase(); var arr_strType = new Array(); _type = _type.toLowerCase(); arr_strType = _fval.split('.'); if (arr_strType.length <= 1) { return false; } _fval = arr_strType[arr_strType.length - 1]; if (_type.indexOf(_fval, 0) == -1) { return false; } return true; } this.CurrentDateCompare = function (obj, type) { if (_RTrim(obj.value) == "") { return true; } var ADate = _RTrim(obj.value); var arrDate = new Array(); arrDate = ADate.split('/'); if (type == "mmddyy") { var month = arrDate[0]; var day = arrDate[1]; var year = "20" + arrDate[2]; } else if (type == "ddmmyy") { var month = arrDate[1]; var day = arrDate[0]; var year = "20" + arrDate[2]; } else if (type == "yymmdd") { var month = arrDate[1]; var day = arrDate[2]; var year = "20" + arrDate[0]; } ADate = month + "/" + day + "/" + year; var _curdate = new Date(Validation._$currentdate); var _actdate = new Date(ADate); if (_curdate < _actdate) { return false; } return true; } this.IsDouble = function (obj, digit) { if (digit == undefined) { digit = 2; } if (_RTrim(obj.value) == "") { return true; } if (Validation.isValid(Validation._nbr + ".", obj.value) == false) { Validation._errMessage = _$number; return false; } var arr = new Array(); arr = _RTrim(obj.value).split('.'); if (arr.length > 2) { Validation._errMessage = " is in incorrect format. The decimal values should not be more than " + digit + " digits."; return false; } else { if (arr.length == 2) { if (arr[1].length > digit) { Validation._errMessage = " is in incorrect format. The decimal values should not be more than " + digit + " digits."; return false; } } } return true; } this.isUrl = function (s) { return /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(s); } this.isWWWUrl = function (s) { return /^www.*/i.test(s); } this.isCusUrl = function (s) { var iResult = Validation.isUrl(s); if (iResult == false) { iResult = Validation.isWWWUrl(s); if (iResult == false) { iResult = /^\//.test(s); } } return iResult; } this.EmailValidation = function (obj) { var _pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var _inputval = _RTrim(obj.value); if (_pattern.test(_inputval) || _inputval == "") { return true; } else { return false; } } this.isAlphaNumeric = function (val) { var parm = val; var key1 = Validation._nbr; var key2 = Validation._lwr + Validation._uwr; var isChar = false; var isNum = false; for (i = 0; i < parm.length; i++) { if (key1.indexOf(parm.charAt(i), 0) == -1) { isChar = true; if (key2.indexOf(parm.charAt(i), 0) == -1) { return false; } } else { isNum = true; } } if (isChar == true && isNum == true) { return true; } else { return false; } } this.datevalidate = function (obj, type) { if (_RTrim(obj.value) == "") { return true; } var ADate = _RTrim(obj.value); var arrDate = new Array(); arrDate = ADate.split('/'); if (arrDate.length != 3) { Validation._errMessage = _$date; return false; } if (type == 2) { if (arrDate[0].length > 2 || arrDate[1].length > 2 || arrDate[2].length > 2) { Validation._errMessage = _$date; return false; } } else if (type == 4) { if (arrDate[0].length > 2 || arrDate[1].length > 2 || arrDate[2].length > 4) { Validation._errMessage = _$date; return false; } } if (type == 1) { var month = arrDate[0]; var day = arrDate[1]; var year = "20" + arrDate[2]; } else if (type == 2) { var month = arrDate[1]; var day = arrDate[0]; var year = "20" + arrDate[2]; } else if (type == 3) { var month = arrDate[1]; var day = arrDate[2]; var year = "20" + arrDate[0]; } else if (type == 4) { var month = arrDate[0]; var day = arrDate[1]; var year = "20" + arrDate[2]; } ADate = month + "/" + day + "/" + year; if (Validation.isValid(Validation._nbr, day) == false) { Validation._errMessage = _$ndateday; return false; } if (Validation.isValid(Validation._nbr, month) == false) { Validation._errMessage = _$ndatemon; return false; } if (Validation.isValid(Validation._nbr, year) == false) { Validation._errMessage = _$ndateyr; return false; } var NDate = new Date(ADate); if (NDate.getDate() != day) { Validation._errMessage = _$dateday; return (false); } else if (NDate.getMonth() != month - 1) { Validation._errMessage = _$datemon; return (false); } else if (NDate.getFullYear() != year) { Validation._errMessage = _$dateyr; return (false); } return true; } this.ValidateCheckBoxList = function (_cblObj) { var _isValidCheck = _cblObj.length > 0 ? false : true; if (!_isValidCheck) { _isValidCheck = (_cblObj.filter(":" + _cblObj[0].type + ":checked").length > 0) ? true : false; } return _isValidCheck; } this.ValidateFilesList = function (_cblObj) { var isFileAvil = _cblObj.length > 0 ? false : true; if (!isFileAvil) { isFileAvil = (_cblObj.filter("[type=" + _cblObj[0].type + "][value!='']").length > 0) ? true : false; } return isFileAvil; } this.GetScreenCordinates = function(obj) { var p = {}; p.x = obj.offsetLeft; p.y = obj.offsetTop; while (obj.offsetParent) { p.x = p.x + obj.offsetParent.offsetLeft; p.y = p.y + obj.offsetParent.offsetTop; if (obj == document.getElementsByTagName("body")[0]) { break; } else { obj = obj.offsetParent; } } return p; } } function RValidate(id, msg) { var obj = $("#" + id)[0]; if (Validation.RequiredValidate(obj) == false) { jAlert(msg, "Alert Message"); return false; } return true; } function _RTrim(Val) { return Val.replace(/\s+$/, ""); } function ValCallBack() { HideAlertPopup(); } var _$required = "is required."; var _$requiredsel = "field is required. Please choose from the dropdown list."; var _$requiredchk = "is a required field. Please select it."; var _$email = "Please enter a valid email address. For example: user@domain.com"; var _$url = "is not having valid url."; var _$emailfmt = "is in the incorrect format. Please enter a valid email address."; var _$date = "is in incorrect date format. The date format should be: xxxx"; var _$ddmm = "is in incorrect format. The format should be: dd/mm"; var _$filetype = "is in incorrect file type. The file type should be: (xxxx)"; var _$postcode = "is in incorrect format. Please enter a valid UK postcode"; var _$dateday = "is a invalid Date. Please enter the valid day."; var _$ndateday = "is a invalid Date. Day should be a numeric field."; var _$datemon = "is a invalid Date. Please enter the valid month."; var _$ndatemon = "is a invalid Date. Month should be a numeric field."; var _$dateyr = "is a invalid Date. Please enter the valid year."; var _$ndateyr = "is a invalid Date. Year should be a numeric field."; var _$cmpdate = "should be today or earlier."; var _$number = "should be a numeric field."; var _$nbr = "is in the incorrect format. The format should be a number."; var _$pwd = "should contain atleast one number and alphabet."; var _$anbr = "should be a alphanumeric."; var _$double = "is in the incorrect format. The format should be a '#.##' or '##.##' or '###.##'..."; var _$double3d = "is in the incorrect format. The format should be a '#.##' or '#.###' or '##.##' or '##.###'..."; var _$double4d = "is in the incorrect format. The format should be a '#.##' or '#.###' or '##.##' or '##.####'..."; var _$creditcard = "Please enter a valid credit card number."; var _$equalTo = ""; var _$range = ""; var _$max = "should be less than or equal to "; var _$min = "Please enter a value greater than or equal to "; var _$mincl = "should have atleast xxxx characters."; var _$maxcl = "should be less than xxxx character."; var _$eqcl = "should be xxxx character."; var _$emailcmp = "Emails do not match"; var _$pwdcmp = "Passwords do not match"; var _$gt = "should be greater than"; var _$dtptt = "input string is not in a correct format"; var _$session = "Your session has expired after a period of inactivity or is no longer valid.<br/>Please try again."; var _$sessionhead = "Session Expired"; var _$notstartwith = "can not starts with 'xxxx'"; var _$gtz = "should be greater than 0"; var _$sortc = "Sort code is not valid";
var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; var TwitterStrategy = require('passport-twitter').Strategy; var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var User = require('../models/user').User; var configAuth = require('./../config/auth'); var gravatar = require('./gravatar'); function getUsernameFromEmail(email){ var username = email.split('@'); username = username[0]; return username; } module.exports = function(passport) { passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); passport.use('local-login', new LocalStrategy({ usernameField : 'email', passwordField : 'password', passReqToCallback : true }, function(req, email, password, done) { if (email) email = email.toLowerCase(); process.nextTick(function() { User.findOne({ 'email' : email }, function(err, user) { if (err) return done(err); if (!user) return done(null, false, req.flash('loginMessage', 'No user found.')); if (!user.validPassword(password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); else return done(null, user); }); }); })); passport.use('local-signup', new LocalStrategy({ usernameField : 'email', passwordField : 'password', passReqToCallback : true }, function(req, email, password, done) { if (email) email = email.toLowerCase(); process.nextTick(function() { if (!req.user) { User.findOne({ 'email' : email }, function(err, user) { if (err) return done(err); if (user) { return done(null, false, req.flash('signupMessage', 'That email is already taken.')); } else { var newUser = new User(); //username newUser.username = getUsernameFromEmail(email); newUser.email = email; newUser.password = newUser.generateHash(password); //gravatar newUser.profile_pic.gravatar_url = gravatar.url(email, {s: '200', r: 'pg', d: '404'}); newUser.save(function(err) { if (err) return done(err); return done(null, newUser); }); } }); } else if ( !req.user.email ) { User.findOne({ 'email' : email }, function(err, user) { if (err) return done(err); if (user) { return done(null, false, req.flash('loginMessage', 'That email is already taken.')); } else { var user = req.user; user.username = getUsernameFromEmail(email); user.email = email; user.password = user.generateHash(password); user.profile_pic.gravatar_url = gravatar.url(req.user.email, {s: '75', r: 'pg', d: '404'}); user.save(function (err) { if (err) return done(err); return done(null,user); }); } }); } else { return done(null, req.user); } }); })); passport.use(new FacebookStrategy({ clientID : configAuth.facebookAuth.clientID, clientSecret : configAuth.facebookAuth.clientSecret, callbackURL : configAuth.facebookAuth.callbackURL, passReqToCallback : true }, function(req, token, refreshToken, profile, done) { process.nextTick(function() { if (!req.user) { User.findOne({ 'services.facebook.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { if (!user.services.facebook.token) { user.services.facebook.token = token; user.services.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; user.services.facebook.email = (profile.emails[0].value || '').toLowerCase(); //name if (!user.name) { user.name = profile.name.givenName + ' ' + profile.name.familyName; } //email if (!user.email){ user.email = (profile.emails[0].value || '').toLowerCase(); } //gravatar user.profile_pic.gravatar_url = gravatar.url(user.email, {s: '200', r: 'pg', d: '404'}); user.save(function(err) { if (err) return done(err); return done(null, user); }); } return done(null, user); } else { var newUser = new User(); newUser.services.facebook.id = profile.id; newUser.services.facebook.token = token; newUser.services.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; newUser.services.facebook.email = (profile.emails[0].value || '').toLowerCase(); //name newUser.name = profile.name.givenName + ' ' + profile.name.familyName; //email newUser.email = (profile.emails[0].value || '').toLowerCase(); //gravatar newUser.profile_pic.gravatar_url = gravatar.url((profile.emails[0].value || '').toLowerCase(), {s: '200', r: 'pg', d: '404'}); newUser.save(function(err) { if (err) return done(err); return done(null, newUser); }); } }); } else { var user = req.user; user.services.facebook.id = profile.id; user.services.facebook.token = token; user.services.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; user.services.facebook.email = (profile.emails[0].value || '').toLowerCase(); //name if (!user.name) { user.name = profile.name.givenName + ' ' + profile.name.familyName; } //email if (!user.email) { user.email = (profile.emails[0].value || '').toLowerCase(); } //gravatar user.profile_pic.gravatar_url = user.profile_pic.gravatar_url = gravatar.url(user.email, {s: '200', r: 'pg', d: '404'}); user.save(function(err) { if (err) return done(err); return done(null, user); }); } }); })); passport.use(new TwitterStrategy({ consumerKey : configAuth.twitterAuth.consumerKey, consumerSecret : configAuth.twitterAuth.consumerSecret, callbackURL : configAuth.twitterAuth.callbackURL, passReqToCallback : true }, function(req, token, tokenSecret, profile, done) { process.nextTick(function() { if (!req.user) { User.findOne({ 'services.twitter.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { if (!user.services.twitter.token) { user.services.twitter.token = token; user.services.twitter.username = profile.username; user.services.twitter.displayName = profile.displayName; //username if(!user.username){ user.username = profile.username; } //name if(!user.name){ user.name = profile.displayName; } user.save(function(err) { if (err) return done(err); return done(null, user); }); } return done(null, user); } else { var newUser = new User(); newUser.services.twitter.id = profile.id; newUser.services.twitter.token = token; newUser.services.twitter.username = profile.username; newUser.services.twitter.displayName = profile.displayName; newUser.username = profile.username; newUser.name = profile.displayName; newUser.save(function(err) { if (err) return done(err); return done(null, newUser); }); } }); } else { var user = req.user; user.services.twitter.id = profile.id; user.services.twitter.token = token; user.services.twitter.username = profile.username; user.services.twitter.displayName = profile.displayName; //username if(!user.username){ user.username = profile.username; } //name if(!user.name){ user.name = profile.displayName; } user.save(function(err) { if (err) return done(err); return done(null, user); }); } }); })); passport.use(new GoogleStrategy({ clientID : configAuth.googleAuth.clientID, clientSecret : configAuth.googleAuth.clientSecret, callbackURL : configAuth.googleAuth.callbackURL, passReqToCallback : true }, function(req, token, refreshToken, profile, done) { process.nextTick(function() { if (!req.user) { User.findOne({ 'services.google.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { if (!user.services.google.token) { user.services.google.token = token; user.services.google.name = profile.displayName; user.services.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email user.save(function(err) { if (err) return done(err); return done(null, user); }); } return done(null, user); } else { var newUser = new User(); newUser.services.google.id = profile.id; newUser.services.google.token = token; newUser.services.google.name = profile.displayName; newUser.services.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email newUser.save(function(err) { if (err) return done(err); return done(null, newUser); }); } }); } else { // user already exists and is logged in, we have to link accounts var user = req.user; // pull the user out of the session user.services.google.id = profile.id; user.services.google.token = token; user.services.google.name = profile.displayName; user.services.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email user.save(function(err) { if (err) return done(err); return done(null, user); }); } }); })); };
// == Import : npm import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import { Reset } from 'styled-reset'; // == Import : local import store from './store'; import GlobalStyle from './components/GlobalStyle'; import App from './containers/App'; // == Render // 1. Élément React racine (celui qui contient l'ensemble de l'app) // => crée une structure d'objets imbriqués (DOM virtuel) const rootReactElement = ( <Provider store={store}> <BrowserRouter> <Reset /> <GlobalStyle /> <App /> </BrowserRouter> </Provider> ); render(rootReactElement, document.getElementById('root'));
var properties = require('./properties').getProperties(), serviceLocator = require('./lib/utils/serviceLocator').createServiceLocator(), nodemailer = require('nodemailer'), databaseAdaptor = require('./lib/database').createDatabaseAdaptor(properties), Application = require('./lib/expressApplication'), Controllers = require('./lib/bundled/controllers'), DomainModels = require('./lib/bundled/domainModels'), bundleManager = require('./lib/bundled/bundleManager').createBundleManager(serviceLocator), app, globalViewHelpers = require('./viewHelpers/global'); // Register the global services needed by your entire application serviceLocator .register('mailer', nodemailer.send_mail) .register('logger', require('./lib/logger').createLogger(properties)); bundleManager.addBundles(__dirname + '/bundles/', [ 'home', 'administrator', 'admin', 'rolesAdmin' // 'promo', // 'promoAdmin', // 'editableContent', // 'editableContentAdmin', // 'recommendation' ]); module.exports = app = Application.createApplication(properties, serviceLocator, bundleManager, databaseAdaptor); databaseAdaptor.createConnection(function(connection) { serviceLocator .register('databaseConnections', { main: connection }); bundleManager.initBundles(app, properties, serviceLocator); // Make the bundle manager avaialbe to views app.configure(function() { app .dynamicHelpers({ bundleManager: function(req, res) { return bundleManager; } }); }); // Add helpers globalViewHelpers.createHelpers(properties, app); app.start(); });
import React, { useState, useEffect } from 'react' import { makeStyles } from '@material-ui/core/styles' import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos' import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos' import Grid from '@material-ui/core/Grid' import GridList from '@material-ui/core/GridList' import GridListTile from '@material-ui/core/GridListTile' import IconButton from '@material-ui/core/IconButton' import Typography from '@material-ui/core/Typography' import axios from 'axios' const useStyles = makeStyles((theme) => ({ content: { flexGrow: 1, padding: theme.spacing(3), }, gridList: { width: '75vw', maxWidth: '100%', overflow: 'hidden', [(theme.breakpoints.down('sm'))]: { width: '110vw' } }, card: { maxHeight: 300, minHeight: 300, position: 'relative', }, // necessary for content to be below app bar // toolbar: { // [(theme.breakpoints.down('sm'))]: { // transform: 'translateX(-5%)' // }, // }, title: { color: 'black', maxHeight: 20, }, submenu: { color: 'grey', fontSize: 11, marginLeft: 15, }, caption: { fontSize: '1rem', [(theme.breakpoints.down('sm'))]: { fontSize: '.8rem' } } })) const fileStructure = { 'BAThesis': { size: 13, filePrefix: 'Ciara-Post' }, 'SelectedWorks': { size: 6, filePrefix: 'Ciara-Post-SW' } } const Artwork = ({ filePath }) => { const classes = useStyles() const [activeStep, setActiveStep] = useState(1) const [titles, setTitles] = useState(null) useEffect(() => { setActiveStep(1) axios.get(`https://us-central1-ciara-post-portfolio.cloudfunctions.net/api/titles?path=${filePath}`).then((res) => { setTitles(res.data) }) }, [filePath]) const imageInfo = (fileName) => { if (!titles) return return titles.map((item) => { if (item.src === `${filePath}/${fileName}`) { return ( <div key={item.title} style={{ height: 'auto' }}> <Typography className={classes.caption}>{item.title}</Typography> <Typography className={classes.caption}>{item.medium}</Typography> <Typography className={classes.caption}>{item.dimensions}</Typography> <Typography className={classes.caption}>{item.date}</Typography> </div> ) } return null }) } const handleNext = () => { setActiveStep((prevActiveStep) => prevActiveStep + 1) } const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1) } return ( <main className={classes.content}> <Grid container direction='row' alignItems='center' justify='center' className={classes.toolbar} > <Grid item xs={3}> <IconButton onClick={handleBack} disabled={activeStep === 1} > <ArrowBackIosIcon fontSize='small'/> </IconButton> </Grid> <Grid item xs={6}> <GridList cols={1} className={classes.gridList}> <GridListTile style={{ height: '100%', display: 'block' }} key={`Ciara-Post-${activeStep}`} cols={1}> <img src={require(`../img/${filePath}/${fileStructure[filePath].filePrefix}-${activeStep}.jpg`)} alt={`Ciara-Post-${activeStep}`} height={'100%'} width={'100%'} /> {imageInfo(`${fileStructure[filePath].filePrefix}-${activeStep}.jpg`)} </GridListTile> </GridList> </Grid> <Grid item xs={3}> <IconButton onClick={handleNext} disabled={activeStep === (fileStructure[filePath].size)}> <ArrowForwardIosIcon fontSize='small' /> </IconButton> </Grid> </Grid> </main> ); } export default Artwork
/* RETRY Say you have a function primitiveMultiply that in 20 percent of cases multiplies two numbers and in the other 80 percent of cases raises an exception of type MultiplicatorUnitFailure. Write a function that wraps this clunky function and just keeps trying until a call succeeds, after which it returns the result. */ class MultiplicatorUnitFailure extends Error {} function primitiveMultiply(a, b) { if (Math.random() < 0.2) { return a * b; } else { throw new MultiplicatorUnitFailure("Klunk"); } } function reliableMultiply(a, b) { for (;;) { try { return primitiveMultiply(a, b); } catch (e) { if (!(e instanceof MultiplicatorUnitFailure)) { throw e; } } } } console.log(reliableMultiply(8, 8)); // → 64 // test 1: make a typo function reliableMultiply(a, b) { for (;;) { try { return primitiveMultiply(a, b); } catch (e) { if (!(e instanceof MultiplicatorUnitFailure)) { throw e; } } } } console.log(reliableMultiply(8, 8)); // → ReferenceError: primitveMultiply is not defined
import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import Slideshow from './index' const slideshowJSON = { certifiedDate: '2017-01-06', legal: { disclaimerText: 'Disclaimer text', }, credits: { author: { name: 'Zaphod Beeblebrox', }, primaryReviewers: [ { name: 'Ford Prefect', }, { name: 'Arthur Dent', }, ], secondaryReviewers: [ { name: 'Trillian', }, { name: 'Marvin, the Paranoid Android', }, ], }, html: ` <ol> <li> <h2 class="HwCmd">Slide 1</h2 class="HwCmd"> <img src="http://via.placeholder.com/400x400"> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </li> <li> <h2 class="HwCmd">Slide 2</h2 class="HwCmd"> <img src="http://via.placeholder.com/400x400"> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </li> <li> <h2 class="HwCmd">Slide 3</h2 class="HwCmd"> <img src="http://via.placeholder.com/400x400"> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </li> </ol> `, } storiesOf('content|Slideshow', module) .add('with slideshow only', () => <Slideshow item={slideshowJSON} />, { info: ` Demonstrates default slideshow rendering `, }) .add( 'with slideshow & hidden disclaimer', () => <Slideshow item={slideshowJSON} hideDisclaimer />, { info: ` Demonstrates slideshow rendering with hidden disclaimer `, } ) .add( 'with slideshow & slide select event', () => ( <Slideshow item={slideshowJSON} hideDisclaimer onSlideSelected={action('slide selected')} /> ), { info: ` Demonstrates slideshow rendering with hidden disclaimer & slide select event `, } )
console.log("========= Time Function ===========") var dd=new Date() console.log(dd) console.log("============old date===============") var dd=new Date("2015:04:21") console.log(dd) console.log("=============present date==========") var dd=new Date() console.log(dd) console.log("year : ", dd.getFullYear()) console.log("date : ", dd.getDate()) console.log("month : ", dd.getMonth()) console.log(dd.getDay()) console.log("=============Time Zone wise time+===================") var dd=new Date() console.log(dd.toDateString()) console.log(dd.toTimeString()) console.log(dd.toTimeString()) console.log(dd.toString()) console.log(dd.toLocaleDateString()) console.log(dd.toLocaleTimeString()) console.log("===============example====================") let text; const today = new Date(); const someday = new Date(); someday.setFullYear(2100, 0, 14); if (someday > today) { text = "Today is before January 14, 2100."; console.log(text) } else { text = "Today is after January 14, 2100."; console.log(text) } console.log("==============ECMA-6 feature=====================") var date=Intl.DateTimeFormat("en-Us") var dd = date.format(new Date()) console.log(dd) console.log("-------------------------------------------") var date=Intl.DateTimeFormat("en-Us",{datestyle:"full"}) var dd = date.format(new Date()) console.log(dd) console.log("-------------------------------------------") var date=Intl.DateTimeFormat("en-Us",{datestyle:"long"}) var dd = date.format(new Date()) console.log(dd) console.log("-------------------------------------------") var date=Intl.DateTimeFormat("en-Us",{datestyle:"medium"}) var dd = date.format(new Date()) console.log(dd) console.log("-------------------------------------------") var date=Intl.DateTimeFormat("en-Us",{datestyle:"short"}) var dd = date.format(new Date()) console.log(dd)
// Model and express imports const router = require('express').Router(); const Event = require('../db/models/event.model'); const clientId = require('../db/ClientId'); const request = require("request"); const util = require('util') const requestPromise = util.promisify(request); // const ObjectId = require("mongodb").ObjectID; /*** * This file handles all the routes for the events. */ // get all events router.get("/", async (req, res) => { try { const events = await Event.find(); return res.status(200).json({ success: true, data: events }); } catch (err) { return res.status(500).json({ error: err.message }); } }) // get specific event router.get("/:id", async (req, res) => { try { const id = req.params.id; const savedEvent = await Event.findById(id); return res.status(200).json({ success: true, data: savedEvent }); } catch (err) { return res.status(500).json({ error: err.message }); } }) // The POST route: Check with front end team for any other additions/changes router.post("/post", async (req, res) => { try { const { title, time, description, signup, subevents} = req.body; let parsedSubevents = JSON.parse(subevents) var imgs = []; if (req.files != null) { if (!Array.isArray(req.files.file)) { imgs.push(req.files.file) } else { imgs = req.files.file } } // Upload images to imgur and save their links var img_array = [] for (const img of imgs) { var options = { 'method': 'POST', 'url': 'https://api.imgur.com/3/image', 'headers': { 'Authorization': `Client-ID ${clientId}` }, formData: { 'image': img.data } }; const response = await requestPromise(options); const jsonBody = JSON.parse(response.body); const deletehash = jsonBody.data.deletehash; const link = jsonBody.data.link; const image = { deletehash, link } img_array.push(image); }; const event = new Event({ title: title, time: time, description: description, imgs: img_array, signup: signup, subevents: parsedSubevents }); // console.log(typeof(parsedSubevents)) const savedEvent = await event.save(); res.send(savedEvent); } catch (err) { console.log(err) res.status(500).json({ error: err.message }); } }) // The DELETE route: Check with front end team for any other additions/changes router.delete("/delete/:id", async (req, res) => { try { const id = req.params.id; const savedEvent = await Event.findById(id); if (!savedEvent) { return res.status(404).json({ error: "Resource not found" }); } // Remove images belonging to this event for (const img in savedEvent.imgs) { const deleteHash = img.deletehash; var options = { 'method': 'DELETE', 'url': `https://api.imgur.com/3/image/${deleteHash}`, 'headers': { 'Authorization': `Client-ID ${clientId}` }, formData: { } }; await requestPromise(options); } savedEvent.remove(); res.status(200).json({ msg: "Success" }); } catch (err) { res.status(500).json({ error: err.message }); } }) /* Update the specified event including its subevents, images and text fields */ router.patch("/update/:id", async (req, res) => { try { console.log(req.params) const id = req.params.id; const retrievedEvent = await Event.findById(id); if (!retrievedEvent) { return res.status(404).json({ error: "Resource not found" }); } const { title, time, description, signup, subevents } = req.body; let parsedSubevents = JSON.parse(subevents) var imgs = []; if (req.files != null) { if (!Array.isArray(req.files.file)) { imgs.push(req.files.file) } else { imgs = req.files.file } } var img_array = []; for (const img of imgs) { var options = { 'method': 'POST', 'url': 'https://api.imgur.com/3/image', 'headers': { 'Authorization': `Client-ID ${clientId}` }, formData: { 'image': img.data } }; const response = await requestPromise(options); const jsonBody = JSON.parse(response.body); const deletehash = jsonBody.data.deletehash; const link = jsonBody.data.link; const image = { deletehash, link } img_array.push(image); }; retrievedEvent.title = title; retrievedEvent.time = time; retrievedEvent.description = description; retrievedEvent.imgs = retrievedEvent.imgs.concat(img_array); retrievedEvent.signup = signup; retrievedEvent.subevents = parsedSubevents; const savedEvent = await retrievedEvent.save(); res.send(savedEvent); } catch (err) { res.status(500).json({ error: err.message }); } }) // Image routes router.delete("/deleteimage/:id/:idx", async (req, res) => { try { const id = req.params.id; const index = req.params.idx; const retrievedEvent = await Event.findById(id); if (!retrievedEvent) { return res.status(404).json({ error: "Resource not found" }); } const deleteHash = retrievedEvent.imgs[index].deletehash; var options = { 'method': 'DELETE', 'url': `https://api.imgur.com/3/image/${deleteHash}`, 'headers': { 'Authorization': `Client-ID ${clientId}` }, formData: { } }; await requestPromise(options); retrievedEvent.imgs.splice(index, 1); const savedEvent = await retrievedEvent.save(); res.send(savedEvent); } catch (err) { res.status(500).json({ error: err.message }); } }) // router.post("/upload/:id", async (req, res) => { // try { // const {imgs} = req.body; // if (!imgs) { // return res.status(400).json({ msg: "No images provided." }); // } // const id = req.params.id; // const retrievedEvent = await Event.findById(id); // if (!retrievedEvent) { // return res.status(404).json({ error: "Resource not found" }); // } // var img_array = [] // for (const img of imgs) { // var options = { // 'method': 'POST', // 'url': 'https://api.imgur.com/3/image', // 'headers': { // 'Authorization': 'Client-ID 23cded91461ac64' // }, // formData: { // 'image': img // } // }; // const response = await requestPromise(options); // const jsonBody = JSON.parse(response.body); // const deletehash = jsonBody.data.deletehash; // const link = jsonBody.data.link; // const image = { // deletehash, // link // } // img_array.push(image); // }; // retrievedEvent.imgs = retrievedEvent.imgs.concat(img_array); // const savedEvent = await retrievedEvent.save(); // res.send(savedEvent); // } // catch (err) { // res.status(500).json({ error: err.message }); // } // }) // Sub Event Routes // router.post("/addsubevent/:id", async (req, res) => { // try { // const {title, description, signup} = req.body; // if (!title) { // return res.status(400).json({ msg: "No title provided." }); // } // const id = req.params.id; // const retrievedEvent = await Event.findById(id); // if (!retrievedEvent) { // return res.status(404).json({ error: "Resource not found" }); // } // const subevent = { // title, // description, // signup // } // retrievedEvent.subevents.push(subevent) // const savedEvent = await retrievedEvent.save(); // res.send(savedEvent); // } // catch (err) { // res.status(500).json({ error: err.message }); // } // }) // router.patch("/updatesubevent/:id/:idx", async (req, res) => { // try { // const {title, description, signup} = req.body; // if (!title) { // return res.status(400).json({ msg: "No title provided." }); // } // const id = req.params.id; // const index = req.params.idx; // const retrievedEvent = await Event.findById(id); // if (!retrievedEvent) { // return res.status(404).json({ error: "Resource not found" }); // } // const subevent = { // title, // description, // signup // } // retrievedEvent.subevents[index] = subevent; // const savedEvent = await retrievedEvent.save(); // res.send(savedEvent); // } // catch (err) { // res.status(500).json({ error: err.message }); // } // }) module.exports = router;
import {DELETE_CURRENT_USER, SUCCESS, FAILURE, LOGIN, GET_DRIVERS, CHANGE_USER_NAME} from './loginActions' const initialState = { isAuthenticated: false, user: {}, list: [] }; const loginReducer = (state = initialState, action = {}) => { switch (action.type) { case LOGIN + FAILURE: let message = action.error.message; return { ...state, isAuthenticated: false, user: {errors: message} }; case LOGIN + SUCCESS: return { ...state, isAuthenticated: true, user: {...action.response.result} }; case GET_DRIVERS + FAILURE: return { ...state, list: [] }; case GET_DRIVERS + SUCCESS: return { ...state, list: action.response.result }; case DELETE_CURRENT_USER: return { ...state, isAuthenticated: false, user: {} }; case CHANGE_USER_NAME + SUCCESS: let optionalParams = action.name; return { ...state, isAuthenticated: true, user: {...state.user, name: optionalParams} }; default: return state; } } export default loginReducer
function Item(typeId, typeName, stackSize) { this.typeId = typeId; this.typeName = typeName; this.stackSize = stackSize; } Item.prototype.create = function () { return new Item(this.typeId, this.typeName, this.stackSize); } Item.prototype.copy = function () { return new Item(this.typeId, this.typeName, this.stackSize); } module.exports = Item;
class ArrayRotator { rotateLeft(arr, n){ arr.push(...arr.splice(0, n)); return arr; } } module.exports = ArrayRotator;
/* * node-lazurite * * Copyright [Naotaka Saito] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ module.exports = function(config) { config = config || {}; let node = this; const events = require("events"); const emitter = new events.EventEmitter(); const lib = require("./build/Release/lazurite_wrap"); let isOpen = false; let timer = null; let isBegin = false; let be = config.be || false; // for debug of endian let binaryMode = config.binaryMode; // undef development let interval = config.interval || 10; /* * #define EIO 5 // hardware error * #define EAGAIN 11 // over 10% duty * #define ENOMEM 12 // data size error * #define EFAULT 14 // bad pointer * #define EBUSY 16 // resource busy(CCA) * #define EINVAL 22 // invalid parameters * #define EFBIG 27 // File too large * #define EDEADLK 35 // Resource deadlock would occur * #define EBADE 52 // crc error * #define EADDRNOTAVAIL 99 // Cannot assign requested address * #define ETIMEDOUT 11 // no ack */ const ERROR = { "-5" : "hareware error", "-11" : "over 10% duty", "-12" : "data size error", "-14" : "bad pointer", "-16" : "CCA busy", "-22" : "invalid parameters", "-27" : "payload over size", "-35" : "unknown deadlock", "-52" : "crc error", "-99" : "address error", "-110" : "no ack", }; node.init= function() { let result; config = config || {}; if(isOpen === false) { isOpen = true; result = lib.dlopen(); if(result === true) { result = lib.init(); } } return result; } node.begin = function(msg) { if(!msg.ch) { throw new Error("lazurite begin msg.ch is undefined"); } if(!msg.panid) { throw new Error("lazurite begin msg.panid is undefined"); } if(!msg.baud) { throw new Error("lazurite begin msg.baud is undefined"); } if(!msg.pwr) { throw new Error("lazurite begin msg.pwr is undefined"); } if(isBegin === true) { lib.close(); } if(!lib.begin(msg.ch,msg.panid,msg.baud,msg.pwr)) { throw new Error("lazurite begin fail."); } isBegin = true; } node.close = function() { isBegin = false; if(!lib.close()) { throw new Error("lazurite close fail."); } } node.send64 = function(msg) { let ret; let dst_addr; let result = {}; if(typeof msg.dst_addr === "string") { dst_addr = BigInt(msg.dst_addr); } else if(typeof msg.dst_addr === "number") { dst_addr = BigInt(msg.dst_addr); } else if(typeof msg.dst_addr === "bigint") { dst_addr = msg.dst_addr; } else { throw new Error('dst_addr format error'); } let dst_array = []; for(let i = 0; i < 8 ; i++) { dst_array.push(parseInt(dst_addr%256n)); dst_addr = (dst_addr >> 8n); } if(be === false) { ret = lib.send64le(dst_array,msg.payload); } else { let dst_be = []; for(let i = 0; i < 8 ; i++) { dst_be.push(dst_array[7-i]); } ret = lib.send64be(dst_be,msg.payload); } if(ret >= 0) { result.success = true; result.rssi = ret; } else { result.success = false; result.errcode = ret; result.errmsg = ERROR[ret]; } return result; } node.send = function(msg) { let ret; let result = {}; let dst_addr; if(typeof msg.dst_addr === "string") { dst_addr = BigInt(msg.dst_addr); } else { dst_addr = msg.dst_addr; } if(dst_addr > 65535) { let dst_array = []; for(let i = 0; i < 8 ; i++) { dst_array.push(parseInt(dst_addr%256n)); dst_addr = (dst_addr >> 8n); } let tmp = ""; for(let i = 7; i >= 0 ; i--) { tmp += ("00"+dst_array[i].toString(16)).substr(-2); } ret = lib.send64le(dst_array,msg.payload); if(ret >= 0) { result.success = true; result.rssi = ret; } else { result.success = false; result.errcode = ret; result.errmsg = ERROR[ret]; } } else if(isNaN(msg.panid) === false) { ret = lib.send(parseInt(msg.panid),parseInt(msg.dst_addr),msg.payload); if(ret >= 0) { result.success = true; result.rssi = ret; } else { result.success = false; result.errcode = ret; result.errmsg = ERROR[ret]; } if(ret > 0 ) { result.eack = lib.getEnhanceAck(); } } else { throw new Error("lazurite send msg.panid error.\nmsg.dst_addr > 65535 : 64bit addressing mode. msg.panid is not required.\nmsg.dst_addr <= 65535 : short addressing mode. msg.panid is required.\nif force to send 64bit addressing mode in case of msg.dst_addr <=65535,please use send64") } return result; } node.rxEnable = function() { if(!lib.rxEnable()) { throw new Error("lazurite rxEnable fail."); }; } node.rxDisable = function() { if(!lib.rxDisable()) { throw new Error("lazurite rxDisable fail."); } } node.getMyAddr64 = function() { let myaddr64 = lib.getMyAddr64(); let d = "0x"; for(let a of myaddr64) { d = d + ("00"+a.toString(16)).substr(-2); } return d; } node.getMyAddress = function() { return lib.getMyAddress(); } node.setMyAddress = function(a) { if(isNaN(a) === true) { throw new Error("lazurite setMyAddress panid is not a number"); } return lib.setMyAddress(parseInt(a)); } node.setAckReq = function(on) { if(typeof on !== "boolean") { throw new Error("lazurite setAckReq must be boolean"); } return lib.setAckReq(on); } node.setBroadcastEnb = function(on) { if(typeof on !== "boolean") { throw new Error("lazurite setBroadcastEnb must be boolean"); } return lib.setBroadcastEnb(on); } /* setKey format * input : "" : aes off * 128bit(16byte HEX string) */ node.setKey = function(key) { if(typeof key !== "string"){ throw new Error("key must be string and the length is 32"); } return lib.setKey(key); } /* setEnhanceAck format * input: [ * { * addr: (target short address), * data: [ enhance ack data array (uint_8). max length = 16 ] * }, * .... * { * addr: 0xFFFF, // in case of address unmatch * data: [ enhance ack data array (uint_8). max length = 16 ] * } * ] * * output: Uint8Array [ * [headr] * 0: lower byte of device count * 1: upper byte of device count * 2: lower byte of ack size * 3: uptter byte of ack size * [data] * 4 + n * (ackSize + 2) + 0: lower byte of target short address * 4 + n * (ackSize + 2) + 1: upper byte of target short address * 4 + n * (ackSize + 2) + 2: ack data[0] * 4 + n * (ackSize + 2) + 3: ack data[1] * ... * ] */ node.setEnhanceAck = function(eack) { let devCount = eack.length; let ackSize = eack[0].data.length; if((devCount == 0) || (ackSize == 0)) { lib.setEnhanceAck(null,0); return; } if(ackSize > 16) { lib.setEnhanceAck(null,0); throw new Error('EnhanceAck length error'); } let buffSize = devCount * (ackSize + 2) + 4; let buffer = new ArrayBuffer(buffSize); let uint8Array = new Uint8Array(buffer,0,buffSize); let index = 4; uint8Array[0] = devCount&0x0ff; uint8Array[1] = devCount >> 8; uint8Array[2] = ackSize&0x0ff; uint8Array[3] = ackSize >> 8; for(var d of eack) { if(ackSize != d.data.length) { lazurite.lib.setEnhanceAck(null,0); throw new Error(`Lazurite EnhanceAck different length is included. ${d}`); } uint8Array[index] = d.addr&0x0ff,index += 1; uint8Array[index] = d.addr>>8,index += 1; for(var a of d.data) { uint8Array[index] = a,index += 1; } } lib.setEnhanceAck(uint8Array,buffSize); } node.setPromiscuous = function(on) { if(isBegin) { throw new Error("lazurite setPromiscous can be change after close"); } return lib.setPromisecous(on); } node.on = function(type,callback) { if(type === "rx") { if(timer === null) { timer = setInterval(timerFunc,interval); } emitter.on(type,callback); } } node.removeListener = function(type,listener) { emitter.removeListener(type,listener); if(emitter.listenerCount("rx") === 0) { clearInterval(timer); timer = null; } } node.remove = function() { if(isOpen === true) { if(timer) clearInterval(timer); timer = null; emitter.removeAllListeners(); lib.remove(); isOpen = false; } } function timerFunc() { let data = lib.read(node.binaryMode); if(data.payload.length > 0) { for(let d of data.payload) { let addr; if(d.src_addr.length === 8) { addr = BigInt(0); for(let i = d.src_addr.length -1 ; i >= 0; i--) { addr = addr*256n + BigInt(d.src_addr[i]); } } else { addr = 0; for(let i = d.src_addr.length -1 ; i >= 0; i--) { addr = addr*256 + d.src_addr[i]; } } d.src_addr = addr; if(d.dst_addr.length === 8) { addr = BigInt(0); for(let i = d.dst_addr.length-1; i >= 0; i--) { addr = addr*256n + BigInt(d.dst_addr[i]); } } else { addr = 0; for(let i = d.dst_addr.length-1; i >= 0; i--) { addr = addr*256 + d.dst_addr[i]; } } d.dst_addr = addr; d.rxtime = d.sec* 1000+parseInt(d.nsec/1000000); delete d.sec; delete d.nsec; emitter.emit("rx",d); } } } return node; }
var path = require('path'); var express = require('express'); var app = express(); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var config = require('./webpack.config'); var configProduction = require('./webpack.production.config'); var isProduction = process.env.NODE_ENV === 'production'; var port = process.env.PORT || 8080; module.exports = { app: function () { const app = express() const indexPath = path.join(__dirname, '/../index.html') const publicPath = express.static(path.join(__dirname, '../public')) app.use('/public', publicPath) app.get('/', function (_, res) { res.sendFile(indexPath) }) return app } }; app.use(express.static(__dirname + '/dist')); app.listen(port, function(err, result) { if (err) { return console.error(err) } console.log('Listening on port: ' + port); })
var express = require('express'); var router = express.Router(); var mongodb = require('mongodb'); var monk = require('monk'); var credentials = require('../credentials'); var db = monk(credentials.uri); var cors = require('cors'); router.get("/", cors(), function(req, res) { console.log("GET top scores"); // Read the request parameter var num = req.params.number; console.log(num); var collection = db.get("scores"); // Get all scores, but limit the number of results collection.find({}, { limit: num, sort: { time : 1 } }, function(err, docs) { if (err) { console.error("Failed to get scores", err); res.status(500).send("Failed to get scores"); } else { res.json(docs); } }); }); module.exports = router;
import React, {Component} from 'react'; export default class MyTasks extends Component { onSubmit(e) { e.preventDefault(); var el = $(e.target); var username = el.find("#username").val(); var password = el.find("#password").val(); Meteor.loginWithPassword(username, password, (er)=> { if (er) { console.log(er); Materialize.toast(er.reason, 4000); } else { window.location.reload(); } }); } render() { return ( <div className="row"> <form onSubmit={this.onSubmit} className="col offset-s4 s4"> <div className="row"> <div className="input-field col s12"> <input id="username" type="email" className="validate"/> <label htmlFor="username">Email</label> </div> </div> <div className="row"> <div className="input-field col s12"> <input id="password" type="password" className="validate"/> <label htmlFor="password">Password</label> </div> </div> <div className="row"> <button className="waves-effect waves-light btn">login</button> </div> </form> </div> ); } }
const express = require('express'); const db = require('../db/mysql'); const {fetchCategories} = require('../models/categories'); const {fetchQuestions} = require('../models/questions'); const router = express.Router(); router.get('/', async function (req, res) { const subj = await fetchCategories(); const questions = await fetchQuestions(); res.render('index', { subj, questions, }); }); module.exports = router;
(function(){ (function(first, last, id){ //老的写法 // var name = 'Your name is ' + first + ' ' + last + '.'; // var url = 'http://localhost:3000/api/messages/' + id; //新的写法 , 反引号 var name = `Your name is ${first} ${last}` var url = `http://localhost:3000/api/messages/${id}` console.log(name + ',' + url); }('c','yh',11)); }())
import React, { useState } from "react"; import { Container } from "./Slices.style"; import Dropdown from "./Dropdown"; import DropdownList from "./DropdownList"; import FilterLabels from "./FilterLabels"; import Card from "../Card/Card"; const Slices = (props) => { const [selectedYear, setSelectedYear] = useState("2019"); const changeYear = (year) => { setSelectedYear(year); }; const filterByYear = props.items.filter((val) => { return val.date.getFullYear().toString() === selectedYear; }); return ( <Container> <Card> <Dropdown selected={selectedYear} onChangeYear={changeYear} /> <FilterLabels vals={filterByYear} /> <DropdownList items={filterByYear} /> </Card> </Container> ); }; export default Slices;
$(document).ready(function(){ "use strict"; //initialize var input1; var input2; var sort1; var sort2; var iparr1; var iparr2; var sortarr1; var sortarr2; var oparr; var paired; var yoffset = 15; var av_name = "PairToSortCONPI"; var av = new JSAV(av_name); var Frames = PIFRAMES.init(av_name); // Load the config object with interpreter and code created by odsaUtils.js var config = ODSA.UTILS.loadConfig({av_name: av_name}), interpret = config.interpreter, // get the interpreter code = config.code; // get the code object var goNext = false; //frame 1 av.umsg("This module introduces an important concept for understanding the relationships between problems, called reduction. Reduction allows us to solve one problem in terms of another. Equally importantly, when we wish to understand the difficulty of a problem, reduction allows us to make relative statements about upper and lower bounds on the cost of a problem (as opposed to an algorithm or program)."); av.displayInit(); //frame 2 av.umsg(Frames.addQuestion("q0")); av.step(); //frame 3 av.umsg("Because the concept of a problem is discussed extensively in this chapter, we want notation to simplify problem descriptions. Throughout this chapter, a problem will be defined in terms of a mapping between inputs and outputs, and the name of the problem will be given in all capital letters. Thus, a complete definition of the sorting problem could appear as follows:"); var l1 = av.label("<br><br><b>Sorting </b>" +"<br><br><b>Input:</b>" + "A sequence of integers x0,x1,x2,…,xn−1." + "<br><br><b>Output:</b>" + "A permutation y0,y1,y2,…,yn−1 of the sequence such that yi ≤ yj whenever i < j.",{top:60}); av.step(); l1.hide(); //frame 4 av.umsg("Here is a visual explanation about Sorting Problem. We Have:" + "<br><br><b><u>Input:</u></b>"+"An unsorted array of records: R1, R2, ..., Rn with associated key values: K1, K2, ..., kn"); //left array var arr; var arr_values = []; for (var i = 0; i < 6; i++) { arr_values.push("K" + (i + 1)); } //rectangle var rect = av.g.rect(250, 200, 75, 50); arr = av.ds.array(arr_values, {left: 0, top: 200, indexed: true}); var line1 = av.g.line(188, 230, 250, 230); var rectLabel = av.label("Sorting" + "<br>Problem", {top: 190, left: 260}); var label1 = av.label("input", {top: 190, left: 200}); av.step(); //frame 5 av.umsg("Here is a visual explanation about Sorting Problem. We Have:" + "<br><br><b><u>Input:</u></b>"+"An unsorted array of records: R1, R2, ..., Rn with associated key values: K1, K2, ..., kn" + "<br><br><b><u>Output:</u></b>" + "the permutation Ks1, Ks2, ..., Ksn such that Ks1 <= Ks2 <= ... <= Ksn."); var line2 = av.g.line(325, 230, 395, 230); var label2 = av.label("output", {top: 190, left: 338}); var arr_values_out = []; //right array for (var i = 0; i < 6; i++) { arr_values_out.push("Ks" + (i + 1)); } var arr2 = av.ds.array(arr_values_out, {left: 395, top: 200, indexed: true}); av.step(); //frame 6 av.umsg("Here we see an example of a Sorting problem instance in which we have initialized an unsorted array and we obtained the sorted array as a result."); var count = 0; while (count < 6) { var value = Math.round(Math.random() * 5); if (arr_values.indexOf(value) === -1) { arr_values[count] = value; count++; } } arr.hide(); arr = av.ds.array(arr_values, {left: 0, top: 200, indexed: false}); arr2.hide(); arr2 = av.ds.array([0,1,2,3,4,5], {left: 395, top: 200, indexed: false}); av.step(); //frame 7 av.umsg(Frames.addQuestion("q01")); av.step(); arr.hide(); arr2.hide(); line1.hide(); line2.hide(); rect.hide(); label1.hide(); label2.hide(); rectLabel.hide(); //frame 8 av.umsg("When you buy or write a program to solve one problem, such as sorting, you might be able to use it to help solve a different problem. This is known in software engineering as software reuse. To illustrate this, let us consider another problem."); av.step(); //frame 9 av.umsg(Frames.addQuestion("q02")); av.step(); //frame 10 av.umsg("<b>PAIRING</b>"+"<br><br><br><b>Input: </b>"+"Two sequences of integers <b>X</b> = (x0,x1,...,xn−1) and <b>Y</b> = (y0,y1,...,yn−1)."+"<br><br><b>Output: </b>"+"A pairing of the elements in the two sequences such that the least value in <b>X</b> is paired with the least value in <b>Y</b>, the next least value in <b>X</b> is paired with the next least value in Y and so on."); var verRect1 = av.g.rect(30, 180, 40, 250); var verRect2 = av.g.rect(230, 180, 40, 250); var l23 = av.label("23", {top: 175, left: 40}); var r48 = av.label("48", {top: 175, left: 240}); var arrow11 = av.g.line(70, 200, 230, 410, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow12 = av.g.line(230, 410, 70, 200, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var l42 = av.label("42", {top: 205, left: 40}); var r59 = av.label("59", {top: 205, left: 240}); var arrow21 = av.g.line(70, 230, 230, 200, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow22 = av.g.line(230, 200, 70, 230, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var l17 = av.label("17", {top: 235, left: 40}); var r11 = av.label("11", {top: 235, left: 240}); var arrow31 = av.g.line(70, 255, 230, 320, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow32 = av.g.line(230, 320, 70, 255, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var l93 = av.label("93", {top: 265, left: 40}); var r89 = av.label("89", {top: 265, left: 240}); var arrow41 = av.g.line(70, 290, 230, 350, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow42 = av.g.line(230, 350, 70, 290, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var l88 = av.label("88", {top: 295, left: 40}); var r12 = av.label("12", {top: 295, left: 240}); var arrow51 = av.g.line(70, 320, 230, 380, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow52 = av.g.line(230, 380, 70, 320, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var l12 = av.label("12", {top: 325, left: 40}); var r91 = av.label("91", {top: 325, left: 240}); var arrow61 = av.g.line(70, 350, 230, 255, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow62 = av.g.line(230, 255, 70, 350, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var l57 = av.label("57", {top: 355, left: 40}); var r64 = av.label("64", {top: 355, left: 240}); var arrow71 = av.g.line(70, 380, 230, 230, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow72 = av.g.line(230, 230, 70, 380, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var l90 = av.label("90", {top: 385, left: 40}); var r34 = av.label("34", {top: 385, left: 240}); var arrow81 = av.g.line(70, 410, 230, 290, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var arrow82 = av.g.line(230, 290, 70, 410, {"stroke-width": 2, "arrow-end": "classic-wide-long"}); var caption02 = av.label("Figure 0.2.1: An illustration of PAIRING. The two lists of numbers are paired up so that the least values from each list make a pair, the next smallest values from each list make a pair, and so on.", {top: 420, left: 0}); av.step(); //frame 11 verRect1.hide(); verRect2.hide(); l23.hide(); l42.hide(); l17.hide(); l93.hide(); l88.hide(); l12.hide(); l57.hide(); l90.hide(); r48.hide(); r59.hide(); r11.hide(); r89.hide(); r12.hide(); r91.hide(); r64.hide(); r34.hide(); arrow11.hide(); arrow21.hide(); arrow31.hide(); arrow41.hide(); arrow51.hide(); arrow61.hide(); arrow71.hide(); arrow81.hide(); arrow12.hide(); arrow22.hide(); arrow32.hide(); arrow42.hide(); arrow52.hide(); arrow62.hide(); arrow72.hide(); arrow82.hide(); caption02.hide(); av.umsg(Frames.addQuestion("q1")); av.step(); //frame12 av.umsg(Frames.addQuestion("q2")); av.step(); //frame13 var ex = av.label("In terms of asymptotic notation, assuming that we can find one method to convert the inputs to PAIRING into inputs to SORTING fast enough, and a second method to convert the result of SORTING back to the correct result for PAIRING fast enough, then the asymptotic cost of PAIRING cannot be more than the cost of SORTING." + "<br><br>In this case, there is little work to be done to convert from PAIRING to SORTING, or to convert the answer from SORTING back to the answer for PAIRING, so the dominant cost of this solution is performing the sort operation. Thus, an upper bound for PAIRING is in O(nlogn).", {top: 10, left: 0}); av.umsg(Frames.addQuestion("q31")); av.step(); //frame 14 av.umsg(Frames.addQuestion("q32")); av.step(); //frame 15 av.umsg(Frames.addQuestion("q33")); av.step(); ex.hide(); //frame 16 //graph rectangle 1 av.umsg("Pairing of two arrays by reduction to sorting"); input1 = new Array(23,42,17,93,88,12,57,90); input2 = new Array(48,59,11,89,12,91,64,34); var r1 = av.g.rect(15, yoffset,550,40); iparr1 = av.ds.array(input1, {left: 17, top: yoffset - 10}); for(var i=0;i<input1.length;i++) iparr1.css(i,{"background-color":"AntiqueWhite"}); iparr2 = av.ds.array(input2, {left: 317, top: yoffset - 10}); for(var i=0;i<input2.length;i++) iparr2.css(i,{"background-color":"AntiqueWhite"}); av.label("<b>Arrays to be paired</b>",{left: 200, top: yoffset - 32}); av.step(); //frame 17 av.umsg("The arrays are fed as input to the sorting problem directly"); var r12 = av.g.rect(15,80 + yoffset,550,40); iparr1 = av.ds.array(input1, {left: 17, top: 70+ yoffset}); for(var i=0;i<input1.length;i++) iparr1.css(i,{"background-color":"AntiqueWhite"}); iparr2 = av.ds.array(input2, {left: 317, top: 70 + yoffset}); for(var i=0;i<input2.length;i++) iparr2.css(i,{"background-color":"AntiqueWhite"}); var l11 = av.g.line(300, yoffset + 40,300,80+ yoffset); av.label("<b>Transformation - Identity function Cost= O(n)</b>",{left: 310, top: 27 + yoffset}); av.step(); //frame18 av.umsg(Frames.addQuestion("q4")); var textlabel = av.label("Reduction is a three-step process. The first step is to convert an instance of PAIRING into two instances of SORTING. The conversion step in this example is not very interesting; it simply takes each sequence and assigns it to an array to be passed to SORTING. The second step is to sort the two arrays (i.e., apply SORTING to each array). The third step is to convert the output of SORTING to the output for PAIRING. This is done by pairing the first elements in the sorted arrays, the second elements, and so on.",{left: 0, top: 130 + yoffset}); av.step(); textlabel.hide(); //frame 19 av.umsg(""); //get rid the problem which is diplayed var l1= av.g.line(120,120 + yoffset,120,140 + yoffset); var l2= av.g.line(420,120 + yoffset,420,140 + yoffset); var r2 = av.g.rect(90,140 + yoffset,60,30); var r3 = av.g.rect(390,140 + yoffset,60,30); av.label("<b>Sort</b>",{left: 105, top: 130 + yoffset}); av.label("<b>Sort</b>",{left: 405, top: 130 + yoffset}); var l3=av.g.line(120,170 + yoffset,120,190 + yoffset); var l4= av.g.line(420,170 + yoffset,420,190 + yoffset); sort1 = new Array(12,17,23,42,57,88,90,93); sort2 = new Array(11,12,34,48,59,64,89,91); var r4 = av.g.rect(15,190 + yoffset,550,40); sortarr1 = av.ds.array(sort1, {left: 17, top: 180 + yoffset}); av.label("Sorted arrays",{left:250,top:150 + yoffset}); sortarr2 = av.ds.array(sort2, {left: 317, top: 180 + yoffset}); av.step() //frame 20 //pair var r4 = av.g.rect(15,260 + yoffset,550,40); var l12 = av.g.line(300,230 + yoffset,300,260 + yoffset); av.label("<b>Reverse Transformation Cost= O(n)</b>",{left: 310, top: 220 + yoffset}); oparr= av.ds.array([" "," "," "," "," "," "," "," "], {left: 140, top: 250 + yoffset}); av.step(); //frame 21-30 //show pair step by step for(var i=0;i<8;i++){ if(i>0){ sortarr1.unhighlight(i-1); sortarr2.unhighlight(i-1); oparr.unhighlight(i-1); } var str="&nbsp"+sortarr1.value(i)+","+sortarr2.value(i)+"&nbsp"; oparr.value(i,str); sortarr1.highlight(i); sortarr2.highlight(i); oparr.highlight(i); av.umsg("Pairing "+sortarr1.value(i)+" with "+sortarr2.value(i)); if (i == 2){ //frame 18 av.umsg(Frames.addQuestion("q5")); av.step(); //frame 19 av.umsg(""); } av.step() } //frame 31 //result av.umsg("The output array gives the pairing" ); sortarr1.unhighlight(i-1); sortarr2.unhighlight(i-1); oparr.unhighlight(i-1); av.step(); av.umsg("Cost of pairing = O(n) + Cost of sorting"); var l13 = av.g.line(300,300 + yoffset,300,330 + yoffset); l13.show(); var oparr2= av.ds.array([" "," "," "," "," "," "," "," "], {left: 140, top: 315 + yoffset}); for(var i=0;i<8;i++) oparr2.value(i,oparr.value(i)); for(var i=0;i<8;i++) oparr2.css(i,{"background-color":"#CCFF99"}); av.label("<b>Paired array</b>",{left:510,top:310 + yoffset}); av.step(); av.recorded(); });
$(document).ready(function(){ $("img").addClass("img_s rounded mx-auto d-block") });
/* * jQuery plugin: fieldSelection - v0.1.0 - last change: 2006-12-16 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd */ (function() { var fieldSelection = { getSelection: function() { var e = this.jquery ? this[0] : this; return ( /* mozilla / dom 3.0 */ ('selectionStart' in e && function() { var l = e.selectionEnd - e.selectionStart; return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) }; }) || /* exploder */ (document.selection && function() { e.focus(); var r = document.selection.createRange(); if (r == null) { return { start: 0, end: e.value.length, length: 0 } } var re = e.createTextRange(); var rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); /* vs hack */ var subtract = 0; for( var vs = 0; vs < rc.text.length; vs++ ) { if (rc.text.charCodeAt(vs).toString(16) == 'd') { subtract += 1; } } /* vs hack end */ return { start: rc.text.length-subtract, end: rc.text.length-subtract + r.text.length, length: r.text.length-subtract, text: r.text }; }) || /* browser not supported */ function() { return { start: 0, end: e.value.length, length: 0 }; } )(); } }; jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; }); })(); new function($) { $.fn.setCursorPosition = function(pos) { if ($(this).get(0).setSelectionRange) { $(this).get(0).setSelectionRange(pos, pos); } else if ($(this).get(0).createTextRange) { var range = $(this).get(0).createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } }(jQuery);
import React, { Fragment } from 'react'; const About = () => <Fragment> <h1>I'm the About Page</h1> <p> You will enjoy the food here, I promise you </p> </Fragment> export default About
import { CartContext } from '../context/cartContext'; import { useContext } from 'react'; import { Container, Button, Row, Col, Image } from 'react-bootstrap' import LinkedButton from './LinkedButton' import { ImageContext } from '../context/imagesContext'; function Cart (){ const cart = useContext(CartContext) const img = useContext(ImageContext) const link = '/ItemListContainer' const emptyCart = <div> <div className="titulo">Aún no has agregado items a tu carrito</div> <div className="text-center"><LinkedButton className="m-3" variant="primary" size="s" link={link} message='Ver Productos'></LinkedButton></div> </div> function clearItems(){ cart.clearCart() } function removeItem(id){ cart.removeFromCart(id) } return ( <Container fluid className='container pt-3'> {cart.itemsSize === 0 ? <div>{emptyCart}</div> : <div> <Row className="titulo text-center"> <Col></Col> <Col>Nombre</Col> <Col>Precio</Col> <Col>Cantidad</Col> <Col></Col> </Row> {cart.items.map(i => <Row className="text-center itemList" key={i.item.id}> <Col><Image src={img.getImage(i.item.pictureUrl)} className='iconCart'></Image></Col> <Col className="mt-5">{i.item.title}</Col> <Col className="mt-5"> ${i.item.price}</Col> <Col className="mt-5">{i.quantity} u. <Col>(${i.item.price * i.quantity})</Col> </Col> <Col className="mt-5"><Button variant="danger" onClick={() => removeItem(i.item.id)}>X</Button></Col> </Row>)} <Row className="text-center bg-warning mt-4 price"> <Col></Col><Col></Col><Col></Col> <Col>Total:</Col> <Col>${cart.totalPrice()}</Col> </Row> <Row className="text-center mt-5"> <Col><LinkedButton variant="outline-primary" size="lg" className="btn buttonsCart m-5" link={link} message='Seguir comprando'></LinkedButton></Col> <Col></Col> <Col><Button variant="outline-danger" size="lg" className="btn buttonsCart m-5" onClick={() => clearItems()}>Vaciar Carrito</Button></Col> <Col><LinkedButton variant="success" size="lg" className="btn buttonsCart m-5" link={'/BuyForm'} message='Finalizar y pagar'></LinkedButton></Col> </Row> </div>} </Container> ) } export default Cart;
let postItem = { props: { text: String, title: String, subtitle: String, date: String, }, template: `<div class="box"> <div class="title-dates-container"> <div class="titles-container"> <h1 class="title">{{ title }}</h1> <h2 class="subtitle">{{ subtitle }}</h2> </div> <div class="dates"> <h2>{{ date }}</h2> </div> </div> <p>{{ text }}</p> </div>`, } let postContainer = { props: { bigTitle: String, text: String, title: String, subtitle: String, }, template: `<div class="box"> <h1 class="title">{{bigTitle}}</h1> <post-item :title="title" :subtitle="subtitle" :text="text"></post-item> </div>`, components: { 'post-item': postItem, }, } //Root Instance let app = new Vue({ el: '#app', data: {}, components: { 'post-item': postItem, 'post-container': postContainer, }, })
/************对内-PC-流程查询**************/ $(document).ready(function() { //初始加载该页面获取orderNum直接查询 testTbObj.initTable(); }); (function(){ //input 提示语placeholder ie兼容初始化 placeholder("#jobName"); })(); //本页面对象 var testTbObj = { //变量 //urlSearch: getOutUrl(getRootPath_web(),"/process/queryProcess?flag=int&orderNum="+orderNum+"&sysCode="+sysCode+"&jobName="+jobName) //urlSearch:getRootPath_web()+"/process/queryProcess"//"/js/data/inflow-table.json" //初始数据 initTable: function(){ var orderNum = getUrlParam("orderNum"); var sysCode = $('#sysCode').val(); var jobName = $('#jobName').val(); $('#table').bootstrapTable("destroy"); $('#table').bootstrapTable({ // url: "http://localhost:8080/testSpringMvc/test/list.do", url: getRootPath_web() + "/process/queryProcess?flag=int&orderNum="+orderNum+"&sysCode="+sysCode+"&jobName="+jobName, dataType : 'json', method:"post", contentType:"application/x-www-form-urlencoded", queryParams:"queryParams", pagination:false, sidePagination:"server", pageSize:"10", pageList:"[5, 10, 20, 50 ]", showRefresh:false, showToggle:false, showPaginationSwitch:false, showColumns:false, search:false, searchAlign:"left", }); } } //【查询】按钮 $(".submitBtn").click(function(){ testTbObj.initTable(); }); //【重置】按钮 $(".resetBtn").click(function(){ $('#searchForm').resetForm(); $('#table').bootstrapTable("destroy"); $('#table').bootstrapTable(); });
import React, { Component } from 'react'; import FList from '../components/FList'; import { SafeAreaView, View, Text, Image, StyleSheet, TouchableOpacity, Button } from 'react-native'; import { ScrollView } from 'react-native-gesture-handler'; import { Icon } from 'react-native-elements' import { SearchBar } from 'react-native-elements'; import Modal from 'react-native-modal' import BottomNavigation, { FullTab } from 'react-native-material-bottom-navigation' export default class YenaChat extends Component { constructor(props) { super(props); this.state={ modalVisible: false, img: 0 }; this.setModalVisible = this.setModalVisible.bind(this); } static navigationOptions = { header: null, }; setModalVisible(visible) { this.setState({modalVisible: visible}); } handleButtonPress() { this.setModalVisible(true); } continueToMain() { this.setModalVisible(false); this.setState({img: 1}); } render() { let modalContent = <View style={{ backgroundColor: '#FFFFFF', height: 236, width:370, alignSelf: 'center', borderRadius: 20, alignItems: 'center'}}> <Text style={{fontWeight: 'bold', marginTop: 20, fontSize: 17}}>Notice!</Text> <Text style={{textAlign: 'center', marginTop: 5, lineHeight: 20,}}>Yena will only receive this if she also sends you something!</Text> <View style={{backgroundColor: '#925dc5', borderRadius:40, height:57, width:278, justifyContent:'center', marginTop: 30}}> <Button color='#FFFFFF' title={'SEND'} onPress={() => this.continueToMain()}/> </View> <Button color='#925dc5' title={'cancel'} onPress={() => this.setModalVisible(false)}/> </View> let img; if (this.state.img === 0) { img = <Image source={require('../../assets/yenachat.jpg')} style={{width:410, height: 780, marginLeft: 0, marginTop: 70, position:'absolute'}}/> } else { img = <Image source={require('../../assets/yenachatwithtext.jpg')} style={{width:410, height: 780, marginLeft: 0, marginTop: 70, position:'absolute'}}/> } return ( <View> <TouchableOpacity onPress={() => this.handleButtonPress()}> {img} </TouchableOpacity> <Modal isVisible={this.state.modalVisible}> {modalContent} </Modal> </View> ); } } const styles = StyleSheet.create({ heading: { alignItems: 'center', fontSize: 20, margin: 20 }, newHeading: { alignItems: 'center', marginBottom: 20 }, title: { fontSize: 20, marginTop: 70, marginBottom: 20 }, image: { marginRight: 10, borderRadius: 10, overflow: 'hidden', textAlign: 'center' }, details: { margin: 10 }, name: { fontSize: 20 }, search: { padding: 20, } });
function RockPaperScissors(userChoice){ var game; var userStr; var compStr; var computer = 1 + Math.floor((Math.random()*3)); if (userChoice === 1 ) { userStr = "Rock"; } else if (userChoice === 2) { userStr = "Paper"; } else if (userChoice === 3) { userStr = "Scissors"; } else { console.log("Selection not valid"); } if (computer === 1 ) { compStr = "Rock"; } else if (computer === 2) { compStr = "Paper"; } else { compStr = "Scissors"; } game = (3 + userChoice - computer) % 3; switch (game) { case 0: console.log("User: " + userStr); console.log("Computer: " + compStr); console.log("Tie"); break; case 1: console.log("User: " + userStr); console.log("Computer: " + compStr); console.log("User Wins"); break; case 2: console.log("User: " + userStr); console.log("Computer: " + compStr); console.log("Computer Wins"); break; } } RockPaperScissors(2); Rock, paper, scissors - rock beats scissors, scissors cut paper, paper covers rock.
$(function() { /* * Flot Interactive Chart ----------------------- */ /* * DONUT CHART ----------- */ var donutData = [ { label : 'Series2', data : 30, color : '#f08080' }, { label : 'Series3', data : 20, color : '#3c8dbc' } ]; $.plot('#donut-chart', donutData, { series : { pie : { show : true, radius : 1, innerRadius : 0.5, label : { show : true, radius : 2 / 3, formatter : labelFormatter, threshold : 0.1 } } }, legend : { show : false } }); $.plot('#donut-chart2', donutData, { series : { pie : { show : true, radius : 1, innerRadius : 0.5, label : { show : true, radius : 2 / 3, formatter : labelFormatter, threshold : 0.1 } } }, legend : { show : false } }); /* * END DONUT CHART */ }); /* * Custom Label formatter ---------------------- */ function labelFormatter(label, series) { return '<div style="font-size:13px; text-align:center; padding:2px; color: #fff; font-weight: 600;">' + label + '<br>' + Math.round(series.percent) + '%</div>'; }
import Ember from 'ember'; export default Ember.Route.extend({ session: Ember.inject.service(), actions: { register(username,password) { this.get('session').register(username,password).then((response) => { alert('Succesfully registered!'); this.transitionTo('posts'); }).catch((err) => { alert(`Error with registration ${err.payload.error}`); }); } } });
//class Input extends Div function Input(_type, _callBackOnChange) { Div.call(this, _type, _type, "input"); //Extends DIV this.type = _type; this.callBackOnChange = _callBackOnChange || function(){}; var _that = this; /** - create (construtor) Seto os atributos type e name com o tipo do input; Executo um timer para executar a função addListener; **/ this.create = function(){ this.setAttribute("type", this.type); this.setAttribute("name", main.navigator.currentSection.id); window.setTimeout( function(){ _that.addListener(); }, 1); } /** - addListener Adiciona o listener do evento especifico do objeto. Pega o objeto jQuery e adiciona o evento click, passando o método _callBackOnChange como argumento; **/ this.addListener = function(){ this.getjQueryObject().click( function(){ _that.callBackOnChange(); } ) } // // // this.create(); }
/** * Configure your Gatsby site with this file. * * See: https://www.gatsbyjs.com/docs/gatsby-config/ */ module.exports = { /* Your site config here */ siteMetadata: { title: "ngnails", titleTemplate: "ngnails template", author: 'Aniela Katana-Matłok', siteUrl: 'https://ngnails.pl', description: "NGNails.pl - tutoriale jak wykonać 'krok po kroku' manicure hybrydowy i żelowy, inspiracje paznokciowe na różne okazje oraz testy produktów hybrydowych i żelowych", url: "https://anielakm.pl", // No trailing slash allowed! image: "/logo.png", // Path to your image you placed in the 'static' folder // twitterUsername: "@occlumency", }, plugins: [ `gatsby-plugin-styled-components`, `gatsby-plugin-smoothscroll`, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, { resolve: 'gatsby-plugin-web-font-loader', options: { google: { families: ['Playfair Display:200,300,400,500,600,700,800,900', 'Lato:200,300,400,500,600,700,800,900'] } } }, { resolve: `gatsby-source-youtube-v2`, options: { channelId: ['UCguUVgW3EHhh-Mqc7QQqeYw'], apiKey: 'AIzaSyDbF6u7NDpsNEBy0ZCH63QotVEn_WUWa-E', maxVideos: 50 // Defaults to 50 }, }, // { // resolve: `gatsby-source-instagram-all`, // options: { // access_token: "IGQVJXTU5FcDJESjQtZAElaV2FLelM4ZAmJZAajVNUXlLSEp5b0hobldseC1ZAOGg3WThXbS1VcXVkR3NwNU9ZAblhCOE1zdEtzM20xX2dfcFhydHlLV2lnNy10MFZALdVFnc0ZAabGpYUDl4bnoxMllQa1ZAlbwZDZD", // } // }, { resolve: `gatsby-plugin-manifest`, options: { name: `NGNails`, short_name: `NGNails`, icon: `src/images/ngn-logo.png`, start_url: `/`, background_color: `#d4beb3`, theme_color: `#d4beb3`, display: `standalone`, }, }, { resolve: `gatsby-source-wordpress-experimental`, options: { url: process.env.WPGRAPHQL_URL || `https://www.blog-ngn.pl/graphql`, schema: { //Prefixes all WP Types with "Wp" so "Post and allPost" become "WpPost and allWpPost". typePrefix: `Wordpress`, }, type: { Post: { limit: process.env.NODE_ENV === `development` ? // Lets just pull 50 posts in development to make it easy on ourselves (aka. faster). 50 : // and we don't actually need more than 5000 in production for this particular site 5000, }, }, }, }, { resolve: `gatsby-plugin-google-analytics`, options: { // The property ID; the tracking code won't be generated without it trackingId: "UA-62318221-2", // Defines where to place the tracking script - `true` in the head and `false` in the body head: true, // Defers execution of google analytics script after page load defer: false, // Any additional optional fields sampleRate: 5, siteSpeedSampleRate: 10, }, }, ] }
import { sumar, restar, multiplicar, dividir } from '../maths'; describe('Cálculos matemáticos', () => { test('Prueba de sumas ', () => { expect( sumar(1, 1) ).toBe(2); }) test('Multiplicar ', () => { expect( multiplicar(2, 2) ).toBe(4); }) test('Prueba de restas ', () => { expect( restar(4, 1) ).toBe(3); }) test('Dividir ', () => { expect( dividir(2, 2) ).toBe(1); }) })
/* jshint esnext:true */ const socket = io(); // could take a url, but default to same origin const sendBtn = document.querySelector('#sendBtn'); sendBtn.addEventListener('click', handleSend); function handleSend(evt) { const message = document.querySelector('#message').value; socket.emit('chat message', message); } socket.on('chat message', (data) => { document.body.appendChild( document.createElement('div')) .textContent = data; });
/** * @param {Array<Array<number>>} board * @return {boolean} */ const validSudoku = (board) => { // 9 sub grids let rowStart = 0; let rowEnd = 3; let colStart = 0; let colEnd = 3; while (rowStart < 9) { let hashMap = {}; let rowHash = {}; let colHash = {}; for (let row = rowStart; row < rowEnd; row++) { // row check let rowNumbers = board[row]; for (let i = 0; i < rowNumbers.length; i++) { if (rowHash[board[row][i]] !== undefined && board[row][i] !== 0) { return false; } rowHash[board[row][i]] = true; } rowHash = {}; for (let column = colStart; column < colEnd; column++) { // column check let colNumbers = board[column]; for (let i = 0; i < colNumbers.length; i++) { if ( colHash[board[i][column]] !== undefined && board[i][column] !== 0 ) { return false; } colHash[board[i][column]] = true; } colHash = {}; // box check if ( hashMap[board[row][column]] !== undefined && board[row][column] !== 0 ) { return false; } hashMap[board[row][column]] = true; } } colStart += 3; if (colStart > 9) { colStart = 0; rowStart += 3; } } return true; // 9 rows and 9 columns // brute force // take first row and put in hash map // check if all unique // take first column and put in hash map // check if all unique // take second column and put in hash map // check if all unique }; let result = validSudoku([ [5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0], [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3], [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6], [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5], [0, 0, 0, 0, 8, 0, 0, 7, 9] ]); console.log(result);
const info = require('./information/information.service.js'); const addresses = require('./addresses/addresses.service.js'); const tokens = require('./tokens/tokens.service.js'); const accounts = require('./accounts/accounts.service.js'); const txns = require('./txns/txns.service.js'); const tokenTxns = require('./token-txns/token-txns.service.js'); const balance = require('./balance/balance.service.js'); const pushNotificationSubs = require('./push-notification-subs/push-notification-subs.service.js'); const notificationSubs = require('./notification-subs/notification-subs.service.js'); const feelevels = require('./feelevels/feelevels.service.js'); // eslint-disable-next-line no-unused-vars module.exports = function (app) { app.configure(info); app.configure(addresses); app.configure(tokens); app.configure(accounts); app.configure(txns); app.configure(tokenTxns); app.configure(balance); app.configure(pushNotificationSubs); app.configure(notificationSubs); app.configure(feelevels); };
import React from 'react' import PropTypes from 'prop-types' class MultipaneResizer extends React.Component { render() { const { children } = this.props return( <div className={'multipane-resizer'}> {children} </div> ) } } MultipaneResizer.propTypes = { children: PropTypes.node } export default MultipaneResizer
function colourizeRarity(){ elements = document.getElementsByClassName("rarity"); for (i = 0; i < elements.length; i++){ switch(elements[i].innerHTML){ case "Common": elements[i].style.color = "gray"; break; case "Uncommon": elements[i].style.color = "#66CD48"; break; case "Rare": elements[i].style.color = "blue"; break; case "Ultra-Rare": elements[i].style.color = "purple"; break; case "Legendary": elements[i].style.color = "orange"; break; default: elements[i].style.color = "black"; } } } function colourizeMass(){ element = document.getElementById("carryCapacity"); if(element != null) { elementContent = element.innerHTML; //(5/10) newStringArray = elementContent.split("/"); // 0=> current Mass, 1=> Maximum mass massPercentage = parseInt(newStringArray[0].substr(1)) / parseInt(newStringArray[1].slice(0, -1)); if (massPercentage >= 1){ element.style.color = "red"; } else if(massPercentage >= 0.8){ element.style.color = "orange"; } else if(massPercentage >= 0.6){ //yellow element.style.color = "yellow"; } else{ //green element.style.color = "#3DAF3D"; } } } window.onload = function(){ colourizeRarity(); colourizeMass(); }
function Controller() { function getInformation() { _ws_request = { atoken: args.params.token, date: new Date().getTime() }; APP.showActivityindicator(); APP.http.request({ url: L("ws_getmyalertsettings"), type: "GET", format: "JSON", data: _ws_request }, function(_result) { if (0 == _result._result) { alert(L("something_wrong")); APP.closeWindow(); } else if (0 != _result._data.errorcode) { alert(_result._data.message); APP.closeWindow(); } else setInformation(_result._data.data[0]); APP.hideActivityindicator(); return true; }); return true; } function saveInformation() { APP.showActivityindicator(); APP.getCurrentLocation(function(event) { if (event.success) { _ws_request = { atoken: args.params.token, flat: event.lat, flon: event.lon, falertEAemail: _falertEAemail, falertEAcell: $.falertEAcell.value ? "Y" : "N", falertcell: $.falertcell.value ? "Y" : "N", falertemail: $.falertemail.value ? "Y" : "N", fnalertemail: $.fnalertemail.value ? "Y" : "N", falertMediaEmail: $.falertMediaEmail.value ? "Y" : "N", fealertemail: $.fealertemail.value ? "Y" : "N", falertIDEmail: $.falertIDEmail.value ? "Y" : "N", fsodemail: $.fsodemail.value ? "Y" : "N", falertWeatherEmail: $.falertWeatherEmail.value ? "Y" : "N", fweatherlevel: _fweatherlevel, falertlevel: _falertlevel, fatidistance: _fatidistance, fati: $.ati_switch.value ? "Y" : "N", fdistance: _fdistance }; APP.http.request({ url: L("ws_putmyalertsettings"), type: "GET", format: "JSON", data: _ws_request }, function(_result) { if (0 == _result._result) alert(L("something_wrong")); else if (0 != _result._data.errorcode) alert(_result._data.message); else { alert(L("save_successful")); _result._data.data[0].atoken; APP.closeWindow(); } APP.hideActivityindicator(); return true; }); } else { APP.hideActivityindicator(); alert(L("failed_to_get_current_location")); } }); return true; } function setAlertLevel(event) { _falertlevel = String(event.value || this.value); $.cb_1.setImage("/images/bt_radio_unselect.png"); $.cb_2.setImage("/images/bt_radio_unselect.png"); $.cb_3.setImage("/images/bt_radio_unselect.png"); $.cb_4.setImage("/images/bt_radio_unselect.png"); $.cb_5.setImage("/images/bt_radio_unselect.png"); $["cb_" + _falertlevel].setImage("/images/bt_radio_select.png"); return true; } function setCellValue(cell_checker, value) { cell_checker.setImage(value ? "/images/ic_phone_active.png" : "/images/ic_phone_inactive.png"); cell_checker.value = Boolean(value); return true; } function setEmailValue(email_checker, value) { email_checker.setImage(value ? "/images/ic_mail_active.png" : "/images/ic_mail_inactive.png"); email_checker.value = Boolean(value); return true; } function setInformation(data) { data.atoken; _fatidistance = String(data.fatidistance); _fdistance = String(data.fdistance); $.ati_switch.setValue("Y" == data.fati); setState({ value: $.ati_switch.value }); _falertEAemail = data.falertEAemail; setCellValue($.falertEAcell, "Y" == data.falertEAcell); setCellValue($.falertcell, "Y" == data.falertcell); setEmailValue($.falertemail, "Y" == data.falertemail); setEmailValue($.fnalertemail, "Y" == data.fnalertemail); setEmailValue($.falertMediaEmail, "Y" == data.falertMediaEmail); setEmailValue($.fealertemail, "Y" == data.fealertemail); setEmailValue($.falertIDEmail, "Y" == data.falertIDEmail); setEmailValue($.fsodemail, "Y" == data.fsodemail); setEmailValue($.falertWeatherEmail, "Y" == data.falertWeatherEmail); "Y" == data.falertWeatherEmail && ($.weather_select.height = 40); setWeather({ value: parseInt(data.fweatherlevel), show: "Y" == data.falertWeatherEmail }); setAlertLevel({ value: String(data.falertlevel) }); return true; } function setState(event) { if (event.value) { $.distance_picker.setHeight(0); $.threat_distance.setText(_fdistance + (1 == _fdistance ? "Mile." : " Miles.")); } else { $.distance_picker.setHeight(Ti.UI.SIZE); switch (String(_fatidistance)) { case "0.25": $.threat_distance.setText(L("td_0_25")); break; case "0.5": $.threat_distance.setText(L("td_0_5")); break; case "1": $.threat_distance.setText(L("td_1")); break; case "2": $.threat_distance.setText(L("td_2")); break; case "3": $.threat_distance.setText(L("td_3")); } } return true; } function setThreatDistance() { _fatidistance = String(this.value); $.threat_distance.setText(this.text); $.distance_picker.setHeight(0); return true; } function setWeather(event) { _fweatherlevel = String(event.value || this.value); switch (parseInt(_fweatherlevel)) { case 1: $.fweatherlevel.setText(L("wl_extreme")); break; case 2: $.fweatherlevel.setText(L("wl_severe")); break; case 3: $.fweatherlevel.setText(L("wl_moderate")); break; case 4: $.fweatherlevel.setText(L("wl_minor")); } $.weather_picker.setHeight(0); return true; } function toggleCellValue() { setCellValue(this, !Boolean(this.value)); return true; } function toggleEmailValue() { setEmailValue(this, !Boolean(this.value)); return true; } function toggleEmailWeatherAlerts() { setEmailValue(this, !Boolean(this.value)); if (Boolean(this.value)) { $.weather_select.setHeight(40); $.spin_arr.setImage("/images/ic_down_arrow.png"); } else { $.weather_select.setHeight(0); $.weather_picker.setHeight(0); $.spin_arr.setImage("/images/ic_up_arrow.png"); } return true; } function toggleThreatDistancePicker() { $.ati_switch.value || (0 == $.distance_picker.height ? $.distance_picker.setHeight(Ti.UI.SIZE) : $.distance_picker.setHeight(0)); return true; } function toggleWeatherPicker() { if (Boolean($.falertWeatherEmail.value)) if (0 == $.weather_picker.height) { $.weather_picker.setHeight(Ti.UI.SIZE); $.spin_arr.setImage("/images/ic_up_arrow.png"); } else { $.weather_picker.setHeight(0); $.spin_arr.setImage("/images/ic_down_arrow.png"); } return true; } function initialize() { _saveButton = Ti.UI.createButton({ title: "Save", right: 5, width: 50, height: 44, color: "white", backgroundImage: "transparent" }); _saveButton.addEventListener("click", saveInformation); args.toolBar.removeAllCustomViews(); args.toolBar.setRightButton(0, false); args.toolBar.setTitle(L("my_alert_settings")); args.toolBar.addCustomView(_saveButton); getInformation(); return true; } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "Settings/MyAlertSettings"; arguments[0] ? arguments[0]["__parentSymbol"] : null; arguments[0] ? arguments[0]["$model"] : null; arguments[0] ? arguments[0]["__itemTemplate"] : null; var $ = this; var exports = {}; var __defers = {}; $.__views.MyAlertSettings = Ti.UI.createScrollView({ backgroundColor: "#ecf1f4", layout: "vertical", scrollType: "vertical", showVerticalScrollIndicator: true, contentHeight: 1e3, id: "MyAlertSettings" }); $.__views.MyAlertSettings && $.addTopLevelView($.__views.MyAlertSettings); $.__views.__alloyId1099 = Ti.UI.createView({ height: Alloy.Globals.CONTENT_TOP, id: "__alloyId1099" }); $.__views.MyAlertSettings.add($.__views.__alloyId1099); $.__views.__alloyId1100 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1100" }); $.__views.MyAlertSettings.add($.__views.__alloyId1100); $.__views.__alloyId1101 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, textid: "ati", id: "__alloyId1101" }); $.__views.__alloyId1100.add($.__views.__alloyId1101); $.__views.ati_switch = Ti.UI.createSwitch({ right: 15, value: false, id: "ati_switch" }); $.__views.__alloyId1100.add($.__views.ati_switch); setState ? $.__views.ati_switch.addEventListener("change", setState) : __defers["$.__views.ati_switch!change!setState"] = true; $.__views.__alloyId1102 = Ti.UI.createView({ backgroundColor: "#CCC", width: Ti.UI.FILL, height: 1, top: 0, id: "__alloyId1102" }); $.__views.MyAlertSettings.add($.__views.__alloyId1102); $.__views.__alloyId1103 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1103" }); $.__views.MyAlertSettings.add($.__views.__alloyId1103); toggleThreatDistancePicker ? $.__views.__alloyId1103.addEventListener("click", toggleThreatDistancePicker) : __defers["$.__views.__alloyId1103!click!toggleThreatDistancePicker"] = true; $.__views.threat_distance_tag = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, textid: "threat_distance", right: 100, id: "threat_distance_tag" }); $.__views.__alloyId1103.add($.__views.threat_distance_tag); $.__views.threat_distance = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: null, textid: "td_0_25", right: 15, id: "threat_distance" }); $.__views.__alloyId1103.add($.__views.threat_distance); $.__views.distance_picker = Ti.UI.createView({ height: 0, left: 0, right: 0, layout: "vertical", id: "distance_picker" }); $.__views.MyAlertSettings.add($.__views.distance_picker); $.__views.__alloyId1104 = Ti.UI.createView({ backgroundColor: "white", backgroundImage: "/images/bg_post_flex.png", backgroundLeftCap: 10, backgroundTopCap: 10, height: Ti.UI.SIZE, left: 15, right: 15, layout: "vertical", id: "__alloyId1104" }); $.__views.distance_picker.add($.__views.__alloyId1104); $.__views.__alloyId1105 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, text: "0.25 Miles.", value: "0.25", id: "__alloyId1105" }); $.__views.__alloyId1104.add($.__views.__alloyId1105); setThreatDistance ? $.__views.__alloyId1105.addEventListener("click", setThreatDistance) : __defers["$.__views.__alloyId1105!click!setThreatDistance"] = true; $.__views.__alloyId1106 = Ti.UI.createView({ backgroundColor: "#1FB9E5", height: 1, top: 0, left: 5, right: 5, id: "__alloyId1106" }); $.__views.__alloyId1104.add($.__views.__alloyId1106); $.__views.__alloyId1107 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, text: "0.5 Miles.", value: "0.5", id: "__alloyId1107" }); $.__views.__alloyId1104.add($.__views.__alloyId1107); setThreatDistance ? $.__views.__alloyId1107.addEventListener("click", setThreatDistance) : __defers["$.__views.__alloyId1107!click!setThreatDistance"] = true; $.__views.__alloyId1108 = Ti.UI.createView({ backgroundColor: "#1FB9E5", height: 1, top: 0, left: 5, right: 5, id: "__alloyId1108" }); $.__views.__alloyId1104.add($.__views.__alloyId1108); $.__views.__alloyId1109 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, text: "1 Mile.", value: "1", id: "__alloyId1109" }); $.__views.__alloyId1104.add($.__views.__alloyId1109); setThreatDistance ? $.__views.__alloyId1109.addEventListener("click", setThreatDistance) : __defers["$.__views.__alloyId1109!click!setThreatDistance"] = true; $.__views.__alloyId1110 = Ti.UI.createView({ backgroundColor: "#1FB9E5", height: 1, top: 0, left: 5, right: 5, id: "__alloyId1110" }); $.__views.__alloyId1104.add($.__views.__alloyId1110); $.__views.__alloyId1111 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, text: "2 Miles.", value: "2", id: "__alloyId1111" }); $.__views.__alloyId1104.add($.__views.__alloyId1111); setThreatDistance ? $.__views.__alloyId1111.addEventListener("click", setThreatDistance) : __defers["$.__views.__alloyId1111!click!setThreatDistance"] = true; $.__views.__alloyId1112 = Ti.UI.createView({ backgroundColor: "#1FB9E5", height: 1, top: 0, left: 5, right: 5, id: "__alloyId1112" }); $.__views.__alloyId1104.add($.__views.__alloyId1112); $.__views.__alloyId1113 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, text: "3 Miles.", value: "3", id: "__alloyId1113" }); $.__views.__alloyId1104.add($.__views.__alloyId1113); setThreatDistance ? $.__views.__alloyId1113.addEventListener("click", setThreatDistance) : __defers["$.__views.__alloyId1113!click!setThreatDistance"] = true; $.__views.__alloyId1114 = Ti.UI.createView({ height: 10, id: "__alloyId1114" }); $.__views.distance_picker.add($.__views.__alloyId1114); $.__views.separator = Ti.UI.createView({ backgroundColor: "#CCC", width: Ti.UI.FILL, height: 1, top: 0, id: "separator" }); $.__views.MyAlertSettings.add($.__views.separator); $.__views.__alloyId1115 = Ti.UI.createView({ height: Ti.UI.SIZE, left: 0, right: 0, layout: "vertical", id: "__alloyId1115" }); $.__views.MyAlertSettings.add($.__views.__alloyId1115); $.__views.__alloyId1116 = Ti.UI.createLabel({ color: "black", font: { fontSize: 16 }, textAlign: "left", left: 15, height: 40, textid: "alert_types", id: "__alloyId1116" }); $.__views.__alloyId1115.add($.__views.__alloyId1116); $.__views.__alloyId1117 = Ti.UI.createView({ backgroundColor: "white", backgroundImage: "/images/bg_post_flex.png", backgroundLeftCap: 10, backgroundTopCap: 10, height: Ti.UI.SIZE, left: 15, right: 15, layout: "vertical", id: "__alloyId1117" }); $.__views.__alloyId1115.add($.__views.__alloyId1117); $.__views.__alloyId1118 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1118" }); $.__views.__alloyId1117.add($.__views.__alloyId1118); $.__views.__alloyId1119 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_cf_emergency_alert", id: "__alloyId1119" }); $.__views.__alloyId1118.add($.__views.__alloyId1119); $.__views.falertEAcell = Ti.UI.createImageView({ image: "/images/ic_phone_inactive.png", width: 30, height: 30, right: 55, value: false, id: "falertEAcell" }); $.__views.__alloyId1118.add($.__views.falertEAcell); toggleCellValue ? $.__views.falertEAcell.addEventListener("click", toggleCellValue) : __defers["$.__views.falertEAcell!click!toggleCellValue"] = true; $.__views.falert_ea_email = Ti.UI.createImageView({ image: "/images/ic_mail_nonselection.png", width: 30, height: 30, right: 15, value: false, id: "falert_ea_email" }); $.__views.__alloyId1118.add($.__views.falert_ea_email); $.__views.__alloyId1120 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1120" }); $.__views.__alloyId1117.add($.__views.__alloyId1120); $.__views.__alloyId1121 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_cf_advisory", id: "__alloyId1121" }); $.__views.__alloyId1120.add($.__views.__alloyId1121); $.__views.falertcell = Ti.UI.createImageView({ image: "/images/ic_phone_inactive.png", width: 30, height: 30, right: 55, value: false, id: "falertcell" }); $.__views.__alloyId1120.add($.__views.falertcell); toggleCellValue ? $.__views.falertcell.addEventListener("click", toggleCellValue) : __defers["$.__views.falertcell!click!toggleCellValue"] = true; $.__views.falertemail = Ti.UI.createImageView({ image: "/images/ic_mail_inactive.png", width: 30, height: 30, right: 15, value: false, id: "falertemail" }); $.__views.__alloyId1120.add($.__views.falertemail); toggleEmailValue ? $.__views.falertemail.addEventListener("click", toggleEmailValue) : __defers["$.__views.falertemail!click!toggleEmailValue"] = true; $.__views.__alloyId1122 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1122" }); $.__views.__alloyId1117.add($.__views.__alloyId1122); $.__views.__alloyId1123 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_nw_discussions", id: "__alloyId1123" }); $.__views.__alloyId1122.add($.__views.__alloyId1123); $.__views.fnalertemail = Ti.UI.createImageView({ image: "/images/ic_mail_inactive.png", width: 30, height: 30, right: 15, value: false, id: "fnalertemail" }); $.__views.__alloyId1122.add($.__views.fnalertemail); toggleEmailValue ? $.__views.fnalertemail.addEventListener("click", toggleEmailValue) : __defers["$.__views.fnalertemail!click!toggleEmailValue"] = true; $.__views.__alloyId1124 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1124" }); $.__views.__alloyId1117.add($.__views.__alloyId1124); $.__views.__alloyId1125 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_new_stories", id: "__alloyId1125" }); $.__views.__alloyId1124.add($.__views.__alloyId1125); $.__views.falertMediaEmail = Ti.UI.createImageView({ image: "/images/ic_mail_inactive.png", width: 30, height: 30, right: 15, value: false, id: "falertMediaEmail" }); $.__views.__alloyId1124.add($.__views.falertMediaEmail); toggleEmailValue ? $.__views.falertMediaEmail.addEventListener("click", toggleEmailValue) : __defers["$.__views.falertMediaEmail!click!toggleEmailValue"] = true; $.__views.__alloyId1126 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1126" }); $.__views.__alloyId1117.add($.__views.__alloyId1126); $.__views.__alloyId1127 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_earthquake_advisory", id: "__alloyId1127" }); $.__views.__alloyId1126.add($.__views.__alloyId1127); $.__views.fealertemail = Ti.UI.createImageView({ image: "/images/ic_mail_inactive.png", width: 30, height: 30, right: 15, value: false, id: "fealertemail" }); $.__views.__alloyId1126.add($.__views.fealertemail); toggleEmailValue ? $.__views.fealertemail.addEventListener("click", toggleEmailValue) : __defers["$.__views.fealertemail!click!toggleEmailValue"] = true; $.__views.__alloyId1128 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1128" }); $.__views.__alloyId1117.add($.__views.__alloyId1128); $.__views.__alloyId1129 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_alertid_ut", id: "__alloyId1129" }); $.__views.__alloyId1128.add($.__views.__alloyId1129); $.__views.falertIDEmail = Ti.UI.createImageView({ image: "/images/ic_mail_inactive.png", width: 30, height: 30, right: 15, value: false, id: "falertIDEmail" }); $.__views.__alloyId1128.add($.__views.falertIDEmail); toggleEmailValue ? $.__views.falertIDEmail.addEventListener("click", toggleEmailValue) : __defers["$.__views.falertIDEmail!click!toggleEmailValue"] = true; $.__views.__alloyId1130 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1130" }); $.__views.__alloyId1117.add($.__views.__alloyId1130); $.__views.__alloyId1131 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_sex_offender_alerts", id: "__alloyId1131" }); $.__views.__alloyId1130.add($.__views.__alloyId1131); $.__views.fsodemail = Ti.UI.createImageView({ image: "/images/ic_mail_inactive.png", width: 30, height: 30, right: 15, value: false, id: "fsodemail" }); $.__views.__alloyId1130.add($.__views.fsodemail); toggleEmailValue ? $.__views.fsodemail.addEventListener("click", toggleEmailValue) : __defers["$.__views.fsodemail!click!toggleEmailValue"] = true; $.__views.__alloyId1132 = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", id: "__alloyId1132" }); $.__views.__alloyId1117.add($.__views.__alloyId1132); $.__views.__alloyId1133 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, right: 100, textid: "at_severe_weather_alerts", id: "__alloyId1133" }); $.__views.__alloyId1132.add($.__views.__alloyId1133); $.__views.falertWeatherEmail = Ti.UI.createImageView({ image: "/images/ic_mail_inactive.png", width: 30, height: 30, right: 15, value: false, id: "falertWeatherEmail" }); $.__views.__alloyId1132.add($.__views.falertWeatherEmail); toggleEmailWeatherAlerts ? $.__views.falertWeatherEmail.addEventListener("click", toggleEmailWeatherAlerts) : __defers["$.__views.falertWeatherEmail!click!toggleEmailWeatherAlerts"] = true; $.__views.weather_select = Ti.UI.createView({ height: 0, left: 0, right: 0, layout: "absolute", id: "weather_select" }); $.__views.__alloyId1117.add($.__views.weather_select); toggleWeatherPicker ? $.__views.weather_select.addEventListener("click", toggleWeatherPicker) : __defers["$.__views.weather_select!click!toggleWeatherPicker"] = true; $.__views.fweatherlevel = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "right", left: 110, right: 35, textid: "wl_extreme", id: "fweatherlevel" }); $.__views.weather_select.add($.__views.fweatherlevel); $.__views.spin_arr = Ti.UI.createImageView({ image: "/images/ic_down_arrow.png", right: 15, width: 12, height: 8, id: "spin_arr" }); $.__views.weather_select.add($.__views.spin_arr); $.__views.weather_picker = Ti.UI.createView({ height: 0, left: 0, right: 0, layout: "vertical", id: "weather_picker" }); $.__views.__alloyId1117.add($.__views.weather_picker); $.__views.__alloyId1134 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, textid: "wl_extreme", value: "1", id: "__alloyId1134" }); $.__views.weather_picker.add($.__views.__alloyId1134); setWeather ? $.__views.__alloyId1134.addEventListener("click", setWeather) : __defers["$.__views.__alloyId1134!click!setWeather"] = true; $.__views.__alloyId1135 = Ti.UI.createView({ backgroundColor: "#1FB9E5", height: 1, top: 0, left: 5, right: 5, id: "__alloyId1135" }); $.__views.weather_picker.add($.__views.__alloyId1135); $.__views.__alloyId1136 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, textid: "wl_severe", value: "2", id: "__alloyId1136" }); $.__views.weather_picker.add($.__views.__alloyId1136); setWeather ? $.__views.__alloyId1136.addEventListener("click", setWeather) : __defers["$.__views.__alloyId1136!click!setWeather"] = true; $.__views.__alloyId1137 = Ti.UI.createView({ backgroundColor: "#1FB9E5", height: 1, top: 0, left: 5, right: 5, id: "__alloyId1137" }); $.__views.weather_picker.add($.__views.__alloyId1137); $.__views.__alloyId1138 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, textid: "wl_moderate", value: "3", id: "__alloyId1138" }); $.__views.weather_picker.add($.__views.__alloyId1138); setWeather ? $.__views.__alloyId1138.addEventListener("click", setWeather) : __defers["$.__views.__alloyId1138!click!setWeather"] = true; $.__views.__alloyId1139 = Ti.UI.createView({ backgroundColor: "#1FB9E5", height: 1, top: 0, left: 5, right: 5, id: "__alloyId1139" }); $.__views.weather_picker.add($.__views.__alloyId1139); $.__views.__alloyId1140 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, height: 35, right: 15, textid: "wl_minor", value: "4", id: "__alloyId1140" }); $.__views.weather_picker.add($.__views.__alloyId1140); setWeather ? $.__views.__alloyId1140.addEventListener("click", setWeather) : __defers["$.__views.__alloyId1140!click!setWeather"] = true; $.__views.__alloyId1141 = Ti.UI.createView({ height: 10, id: "__alloyId1141" }); $.__views.__alloyId1115.add($.__views.__alloyId1141); $.__views.__alloyId1142 = Ti.UI.createView({ backgroundColor: "#CCC", width: Ti.UI.FILL, height: 1, top: 0, id: "__alloyId1142" }); $.__views.MyAlertSettings.add($.__views.__alloyId1142); $.__views.__alloyId1143 = Ti.UI.createView({ height: Ti.UI.SIZE, left: 0, right: 0, layout: "vertical", id: "__alloyId1143" }); $.__views.MyAlertSettings.add($.__views.__alloyId1143); $.__views.__alloyId1144 = Ti.UI.createLabel({ color: "black", font: { fontSize: 16 }, textAlign: "left", left: 15, height: 40, textid: "cfw_advisory_level", id: "__alloyId1144" }); $.__views.__alloyId1143.add($.__views.__alloyId1144); $.__views.severe = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", backgroundColor: "#1FB9E5", id: "severe", value: "1" }); $.__views.__alloyId1143.add($.__views.severe); setAlertLevel ? $.__views.severe.addEventListener("click", setAlertLevel) : __defers["$.__views.severe!click!setAlertLevel"] = true; $.__views.__alloyId1145 = Ti.UI.createLabel({ color: "white", font: { fontSize: 14 }, textAlign: "left", left: 15, textid: "cfw_severe", id: "__alloyId1145" }); $.__views.severe.add($.__views.__alloyId1145); $.__views.cb_1 = Ti.UI.createImageView({ image: "/images/bt_radio_unselect.png", width: 23, height: 23, right: 15, id: "cb_1" }); $.__views.severe.add($.__views.cb_1); $.__views.red = Ti.UI.createView({ right: 0, width: 7, backgroundColor: "#ED3A44", id: "red" }); $.__views.severe.add($.__views.red); $.__views.high = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", backgroundColor: "#1CACD5", id: "high", value: "2" }); $.__views.__alloyId1143.add($.__views.high); setAlertLevel ? $.__views.high.addEventListener("click", setAlertLevel) : __defers["$.__views.high!click!setAlertLevel"] = true; $.__views.__alloyId1146 = Ti.UI.createLabel({ color: "white", font: { fontSize: 14 }, textAlign: "left", left: 15, textid: "cfw_high", id: "__alloyId1146" }); $.__views.high.add($.__views.__alloyId1146); $.__views.cb_2 = Ti.UI.createImageView({ image: "/images/bt_radio_unselect.png", width: 23, height: 23, right: 15, id: "cb_2" }); $.__views.high.add($.__views.cb_2); $.__views.orange = Ti.UI.createView({ right: 0, width: 7, backgroundColor: "#F99C29", id: "orange" }); $.__views.high.add($.__views.orange); $.__views.elevated = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", backgroundColor: "#19A0C6", id: "elevated", value: "3" }); $.__views.__alloyId1143.add($.__views.elevated); setAlertLevel ? $.__views.elevated.addEventListener("click", setAlertLevel) : __defers["$.__views.elevated!click!setAlertLevel"] = true; $.__views.__alloyId1147 = Ti.UI.createLabel({ color: "white", font: { fontSize: 14 }, textAlign: "left", left: 15, textid: "cfw_elevated", id: "__alloyId1147" }); $.__views.elevated.add($.__views.__alloyId1147); $.__views.cb_3 = Ti.UI.createImageView({ image: "/images/bt_radio_unselect.png", width: 23, height: 23, right: 15, id: "cb_3" }); $.__views.elevated.add($.__views.cb_3); $.__views.yellow = Ti.UI.createView({ right: 0, width: 7, backgroundColor: "#EAD530", id: "yellow" }); $.__views.elevated.add($.__views.yellow); $.__views.guarded = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", backgroundColor: "#1794B7", id: "guarded", value: "4" }); $.__views.__alloyId1143.add($.__views.guarded); setAlertLevel ? $.__views.guarded.addEventListener("click", setAlertLevel) : __defers["$.__views.guarded!click!setAlertLevel"] = true; $.__views.__alloyId1148 = Ti.UI.createLabel({ color: "white", font: { fontSize: 14 }, textAlign: "left", left: 15, textid: "cfw_guarded", id: "__alloyId1148" }); $.__views.guarded.add($.__views.__alloyId1148); $.__views.cb_4 = Ti.UI.createImageView({ image: "/images/bt_radio_unselect.png", width: 23, height: 23, right: 15, id: "cb_4" }); $.__views.guarded.add($.__views.cb_4); $.__views.blue = Ti.UI.createView({ right: 0, width: 7, backgroundColor: "#317BCA", id: "blue" }); $.__views.guarded.add($.__views.blue); $.__views.low = Ti.UI.createView({ height: 40, left: 0, right: 0, layout: "absolute", backgroundColor: "#1488A8", id: "low", value: "5" }); $.__views.__alloyId1143.add($.__views.low); setAlertLevel ? $.__views.low.addEventListener("click", setAlertLevel) : __defers["$.__views.low!click!setAlertLevel"] = true; $.__views.__alloyId1149 = Ti.UI.createLabel({ color: "white", font: { fontSize: 14 }, textAlign: "left", left: 15, textid: "cfw_low", id: "__alloyId1149" }); $.__views.low.add($.__views.__alloyId1149); $.__views.cb_5 = Ti.UI.createImageView({ image: "/images/bt_radio_unselect.png", width: 23, height: 23, right: 15, id: "cb_5" }); $.__views.low.add($.__views.cb_5); $.__views.green = Ti.UI.createView({ right: 0, width: 7, backgroundColor: "#18A56B", id: "green" }); $.__views.low.add($.__views.green); $.__views.__alloyId1150 = Ti.UI.createLabel({ color: "#333", font: { fontSize: 14 }, textAlign: "left", left: 15, text: "arr", id: "__alloyId1150" }); $.__views.green.add($.__views.__alloyId1150); exports.destroy = function() {}; _.extend($, $.__views); var APP = require("/core"); var args = arguments[0] || {}; var _ws_request, _falertEAemail = "", _fatidistance = 1, _fdistance = 2, _fweatherlevel = 1, _falertlevel = 1; initialize(); __defers["$.__views.ati_switch!change!setState"] && $.__views.ati_switch.addEventListener("change", setState); __defers["$.__views.__alloyId1103!click!toggleThreatDistancePicker"] && $.__views.__alloyId1103.addEventListener("click", toggleThreatDistancePicker); __defers["$.__views.__alloyId1105!click!setThreatDistance"] && $.__views.__alloyId1105.addEventListener("click", setThreatDistance); __defers["$.__views.__alloyId1107!click!setThreatDistance"] && $.__views.__alloyId1107.addEventListener("click", setThreatDistance); __defers["$.__views.__alloyId1109!click!setThreatDistance"] && $.__views.__alloyId1109.addEventListener("click", setThreatDistance); __defers["$.__views.__alloyId1111!click!setThreatDistance"] && $.__views.__alloyId1111.addEventListener("click", setThreatDistance); __defers["$.__views.__alloyId1113!click!setThreatDistance"] && $.__views.__alloyId1113.addEventListener("click", setThreatDistance); __defers["$.__views.falertEAcell!click!toggleCellValue"] && $.__views.falertEAcell.addEventListener("click", toggleCellValue); __defers["$.__views.falertcell!click!toggleCellValue"] && $.__views.falertcell.addEventListener("click", toggleCellValue); __defers["$.__views.falertemail!click!toggleEmailValue"] && $.__views.falertemail.addEventListener("click", toggleEmailValue); __defers["$.__views.fnalertemail!click!toggleEmailValue"] && $.__views.fnalertemail.addEventListener("click", toggleEmailValue); __defers["$.__views.falertMediaEmail!click!toggleEmailValue"] && $.__views.falertMediaEmail.addEventListener("click", toggleEmailValue); __defers["$.__views.fealertemail!click!toggleEmailValue"] && $.__views.fealertemail.addEventListener("click", toggleEmailValue); __defers["$.__views.falertIDEmail!click!toggleEmailValue"] && $.__views.falertIDEmail.addEventListener("click", toggleEmailValue); __defers["$.__views.fsodemail!click!toggleEmailValue"] && $.__views.fsodemail.addEventListener("click", toggleEmailValue); __defers["$.__views.falertWeatherEmail!click!toggleEmailWeatherAlerts"] && $.__views.falertWeatherEmail.addEventListener("click", toggleEmailWeatherAlerts); __defers["$.__views.weather_select!click!toggleWeatherPicker"] && $.__views.weather_select.addEventListener("click", toggleWeatherPicker); __defers["$.__views.__alloyId1134!click!setWeather"] && $.__views.__alloyId1134.addEventListener("click", setWeather); __defers["$.__views.__alloyId1136!click!setWeather"] && $.__views.__alloyId1136.addEventListener("click", setWeather); __defers["$.__views.__alloyId1138!click!setWeather"] && $.__views.__alloyId1138.addEventListener("click", setWeather); __defers["$.__views.__alloyId1140!click!setWeather"] && $.__views.__alloyId1140.addEventListener("click", setWeather); __defers["$.__views.severe!click!setAlertLevel"] && $.__views.severe.addEventListener("click", setAlertLevel); __defers["$.__views.high!click!setAlertLevel"] && $.__views.high.addEventListener("click", setAlertLevel); __defers["$.__views.elevated!click!setAlertLevel"] && $.__views.elevated.addEventListener("click", setAlertLevel); __defers["$.__views.guarded!click!setAlertLevel"] && $.__views.guarded.addEventListener("click", setAlertLevel); __defers["$.__views.low!click!setAlertLevel"] && $.__views.low.addEventListener("click", setAlertLevel); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
({ doInit: function(component, event, helper) { var currentTaskflow = component.get("v.currentTaskFlow"); // alert('Init'+component.get("v.resume")); helper.fetchgroupInformation(component); alert('Resume'+component.get("v.resume")); var chatperName = ""; if (!$A.util.isEmpty(currentTaskflow)) { helper.fetchTaskChapters(component, currentTaskflow); } else { console.log("currentTaskFlow attribute is null"); } }, })
"use strict"; let lastPosition = 100; // initialize a threshold for hiding nav window.onscroll = () => { // when user scrolls, this fires if (screen.width < 800) { // run only on mobile device let currentPosition = window.pageYOffset; // set currentPosition const nav = document.getElementById('nav-menu'); // get entire nav component if (currentPosition > lastPosition) { // detect if user has scrolled down nav.style.display = "none"; // if so, hide entire nav } else if (currentPosition < lastPosition) { // but if user has scrolled up nav.style.display = ""; // show nav again } lastPosition = currentPosition; // reset value for 'lastPosition'; } }
$(document).ready(function() { if (countUrlSegments() == 9) { var melody_id = getLastUrlSegment(); if (melody_id) { var melody_scroll = $("#melody" + parseInt(melody_id)).parent().prevAll("tr").eq(5).get(); // scrolling to 5 lines before the line we are looking for, so that the line is not completely on top var element_scroll = (melody_scroll < 1) ? ".push:first" : melody_scroll; // for the first 1 verses, scrolling to the top of the page (just in case the user refreshes the page from the bottom) $(element_scroll).ScrollTo(); $("#melody" + melody_id).parent("tr").children("td").effect("highlight", {}, 2000); } } });
const CompoundDisposable = require('../disposable/compoundDisposable') const Disposable = require('../disposable/disposable') class Subscriber { constructor(next, complete, error) { this.next = next this.complete = complete this.error = error this.disposable = new CompoundDisposable() this.disposable.addDisposable( new Disposable(() => { this.next = null this.complete = null this.error = null }) ) } sendNext(v) { this.next && this.next(v) } sendComplete() { let complete = this.complete this.disposable.dispose() complete && complete() } sendError(err) { let error = this.error this.disposable.dispose() error && error(err) } didSubscribeWithContextDisposable(disposable) { if (disposable.disposed) { return } this.disposable.addDisposable(disposable) disposable.addDisposable( new Disposable(() => { this.disposable.removeDisposable(disposable) }) ) } } module.exports = Subscriber
let ssllabs = require("node-ssllabs"); const noteModule = require('../modules/noteModule'); const userModule = require('../modules/userModule') module.exports = { runSslLabs: runSslLabs, info: info, sslgetStatusCodes: sslgetStatusCodes, writeSSLdataToNotes: writeSSLdataToNotes }; let rootNoteName = "SSL Labs Results" /*this call is used to check if the ssl labs api is online */ function info() { return new Promise(function (resolve, reject) { ssllabs.info(function (err, info) { return resolve(info) }) }); } /*this call is deprecated because it doesnt actually return valid data, just the same long string of things the ssl labs api checks */ function sslgetStatusCodes() { return new Promise(function (resolve, reject) { ssllabs.getStatusCodes(function (err, statusCodes) { return resolve(statusCodes) }); }); } /* main function, checks if the host is valid and turns it into notes if all is well it should return OK */ function runSslLabs(body, user_uuid) { console.log('Running SSL LABS') return new Promise(function (resolve, reject) { scan(body.target).then(host => { if (host.status !== 'ERROR') { writeSSLdataToNotes(host, user_uuid, body.projectId).then(host => { return resolve(host) }) } else { return reject({ message: "Error: " + host.statusMessage }) } },err => { return reject({message: "Error: "+ "cannot connect to SSL Labs"}) }) }) } /* scans the given url through ssl labs api */ function scan(target) { return new Promise(function (resolve, reject) { ssllabs.scan( { "host": target, "isPublic": false, "startNew": true, "ignoreMismatch": true } , function (err, host) { if (err === null) { return resolve(host) } else { return reject(err) } }) }) } /* writes the ssl labs data to notes */ function writeSSLdataToNotes(host, user_uuid, project_uuid) { return new Promise(function (resolve) { //super short summary of the ssl labs result let rootNodeContent = "<h2>host: <strong>" + host.host + "</strong>" + "<h2>port: <strong>" + host.port + "</strong><br>" rootNodeContent += host.endpoints.length + " endpoint(s): " Object.keys(host.endpoints).forEach(function (key) { rootNodeContent += "<h2>IP: <strong>" + host.endpoints[key].ipAddress + "</strong><br>" + "<h2>Grade: <strong>" + host.endpoints[key].grade + "</strong>" }) rootNodeContent += "<br>" let hostNodeContent = "<h2>host: <strong>" + host.host + "</strong> <br>" + "ports: <strong>" + host.port + "</strong> <br>" + "start time: <strong>" + host.startTime + "</strong> <br>" + "test time: <strong>" + host.testTime + "</strong> <br>" + "engine version: <strong>" + host.engineVersion + "</strong> <br>" + "criteria version: <strong>" + host.criteriaVersion + "</strong> <br>" + "Total endpoints: <strong>" + host.endpoints.length + "</strong> </h2>" let path = noteModule.getProjectDir(project_uuid); //bestaat er al een rootfolder? if (noteModule.CheckIfRootexist(path, rootNoteName)) { //pak de UUID van die rootfolder rootNoteuuid = noteModule.getNoteUUidFromNoteLocation(path, rootNoteName) //als we de UUID hebben kunnen we de content ophalen noteModule.getNote(project_uuid, rootNoteuuid).then(note => { //voor elke summary in de rootnote moet voor elke eindpoint ook wat data worden weergegeven rootNodeContent = rootNodeContent + " <br> " + note //update de bestaande rootnote met de nieuuwe content noteModule.updateNote(project_uuid, rootNoteuuid, rootNodeContent).then(uuid => { noteModule.createNote(project_uuid, host.host, uuid, "", user_uuid, hostNodeContent).then(uuid => { host.uuid = uuid toNotes(host.endpoints, uuid, project_uuid, user_uuid).then(function () { return resolve(host) }) }) }) }) } else { noteModule.createNote(project_uuid, rootNoteName, "", "", user_uuid, rootNodeContent).then(uuid => { //uuid for to See full report button noteModule.createNote(project_uuid, host.host, uuid, "", user_uuid, hostNodeContent).then(uuid => { host.uuid = uuid toNotes(host.endpoints, uuid, project_uuid, user_uuid).then(function () { return resolve(host) }) }) }) } }) } /* used for the child notes of the host note */ function toNotes(nodeList, parent_note_uuid, project_uuid, user_uuid) { return new Promise(function (resolve) { promiseList = []; Object.keys(nodeList).forEach(function (key) { let childNode = nodeList[key] promiseList.push( noteModule.createNote(project_uuid, childNode.ipAddress, parent_note_uuid, "", user_uuid, recursivePrinter(childNode))) }) Promise.all(promiseList).then(() =>{ return resolve('All done') }) }) } /* squirts out all the data from the ssl labs api and makes it more readable for the notes */ function recursivePrinter(object) { let result = ""; for (let [key, value] of Object.entries(object)) { if (value === null) { value = "None Found" } if (typeof value === "object") { result += recursivePrinter(value); } else { result += ("<strong>" + key + "</strong> : " + value + '<br>'); } } return result; }
export const SELECT_SUBJECT = "SELECT_SUBJECT" export const UNSELECT_SUBJECT = "UNSELECT_SUBJECT" export const selectSubject = (message) => { return dispatch => { dispatch({ type: SELECT_SUBJECT, payload: message }) } } export const unselectSubject = (data) => { return dispatch => { dispatch({type: UNSELECT_SUBJECT, data}) } }
define([ ],function () { var submodule = function(){ this.init = function(app){ // PUBLIC NAVIGATION METHODS app.rpcNext = function (){ app.webrtc.rpc("nextSlide"); }; app.rpcPrev = function() { app.webrtc.rpc("prevSlide"); }; app.rpcJumpToURL = function (url){ var remoteCall = "jumpToByURL"; var options = new Object(); options.dataURL = url; app.webrtc.rpc(remoteCall,options); }; app.rpcJumpToIndex = function(index){ var remoteCall = "jumpToByIndex"; var options = new Object(); options.index = index; app.webrtc.rpc(remoteCall,options); }; app.rpcRemoveImage = function(index){ var remoteCall = "removeImage"; var options = new Object(); options.index = index; app.webrtc.rpc(remoteCall,options); }; app.rpcTransformImage = function(index, transform, dims){ var remoteCall = "transformImage"; var options = new Object(); options.index = index; options.transform = transform; options.dims = dims; console.log(transform); console.log(dims); app.webrtc.rpc(remoteCall,options); }; app.retransmitFiles = function(destPeer){ if(destPeer){ var self = app; console.log("Retransmit files!"); app.slideCollection.each(function(slide){ var index = self.slideCollection.indexOf(slide); var src = slide.get("src"); var metadata = { index:index, src:src }; console.log(slide); var dataUrl = slide.get("dataURL"); var file = null; if (src === 'local'){ console.log("To file: "+dataUrl); try{ file = self.imageProcessor.dataURLtoFile(dataUrl); } catch(err){ null; } } // send web links only if owner (to avoid duplicates) else if (src === 'web' && self.webrtc.isOwner()){ file = dataUrl; } if (file != null){ self.webrtc.sendFile(file,metadata,destPeer); } }, app); app.rpcJumpToIndex(app.slideCollection.currentSlideIndex); } }; // CHAT app.sendMessage = function(message, destPeer){ app.webrtc.sendMessage(message,{},destPeer); app.messageCollection.add({sender:'me',message:message}); }; }; }; return submodule; });
export default () => { const req = require.context('@/icons/svg', false, /\.svg$/) const requireAll = requireContext => requireContext.keys().map(i => requireContext(i)) const svgContent = requireAll(req) let symbolContent = '' svgContent.map(item => { symbolContent = symbolContent + item.default.content }) const pageContent = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0" id="__SVG_SPRITE_NODE__"> ${symbolContent} </svg>` return pageContent }
;(function( $ ) { /** * Extends JQuery to include some methods for chess games. */ $.fn.extend({ chessboard: function(func, options) { if(!options) { if(typeof func === "object" && func) { var options = func; var func = 'init'; } if(!func) { var func = 'init'; var options = {}; } } var defaults = { showHeader: true, showFooter: true, squareSize: '40px', showCaptured: true, clearInside: true, blackSquareColor: '#ddd', whiteSquareColor: '#eee', startingPosition: null, whoseTurn: 'white', moveHistory: [], onSelect: function($piece) {}, onMoveStart: function($piece) {}, onMoveEnd: function ($piece) {}, onGameOver: function(winner) {} }; if (typeof options == 'string') { var paramStr = options; var options = $(this).data('options'); } else { var options = $.extend(defaults, options); } var pieceHTML = { 'WK': '&#9812', 'WQ': '&#9813', 'WR': '&#9814', 'WB': '&#9815', 'WN': '&#9816', 'WP': '&#9817', 'BK': '&#9818', 'BQ': '&#9819', 'BR': '&#9820', 'BB': '&#9821', 'BN': '&#9822', 'BP': '&#9823', }; var pieces = options.startingPosition; if(!pieces) { var pieces = { 'a8': 'BR', 'b8': 'BN', 'c8': 'BB', 'd8': 'BQ', 'e8': 'BK', 'f8': 'BB', 'g8': 'BN', 'h8': 'BR', 'a7': 'BP', 'b7': 'BP', 'c7': 'BP', 'd7': 'BP', 'e7': 'BP', 'f7': 'BP', 'g7': 'BP', 'h7': 'BP', 'a2': 'WP', 'b2': 'WP', 'c2': 'WP', 'd2': 'WP', 'e2': 'WP', 'f2': 'WP', 'g2': 'WP', 'h2': 'WP', 'a1': 'WR', 'b1': 'WN', 'c1': 'WB', 'd1': 'WQ', 'e1': 'WK', 'f1': 'WB', 'g1': 'WN', 'h1': 'WR', }; } var rows = ['8', '7', '6', '5', '4', '3', '2', '1']; var cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; var generateBoardHTML = function() { /** * Internal method to generate the HTML of the board */ var $board = $('<div/>'); for(var y = 0; y < rows.length; y++) { var $row = $('<div/>'); for(var x = 0; x < cols.length; x++) { $square = $('<div/>') .addClass('square') .addClass(cols[x] + rows[y]) .css({ 'height': options.squareSize, 'width': options.squareSize, 'display': 'inline-block', 'position': 'relative' }); $row.append($square); } $board.append($row); } $board.children('div:even').children('div:even').css({ 'background': options.whiteSquareColor }).end().end() .children('div:odd').children('div:even').css({ 'background': options.blackSquareColor }).end().end() .children('div:even').children('div:odd').css({ 'background': options.blackSquareColor }).end().end() .children('div:odd').children('div:odd').css({ 'background': options.whiteSquareColor }).end().end() .children().children() .on('click.chessboard', handleSquareClick); return $board; } var initializePieces = function($board) { /** * Puts the pieces in their default locations. */ var colorNames = {'B': 'black', 'W': 'white'}; var pieceNames = { 'R': 'rook', 'N': 'knight', 'B': 'bishop', 'Q': 'queen', 'K': 'king', 'P': 'pawn' } for(var i in pieces) { $piece = $('<div/>') .addClass(colorNames[pieces[i][0]]) .addClass(pieceNames[pieces[i][1]]) .html(pieceHTML[pieces[i]]) .css({ 'font-size': options.squareSize, 'width': '100%', 'height': '100%', 'text-align': 'center', 'position': 'absolute' }) .on("click.chessboard", handlePieceClick); $board.find('.' + i).append($piece); } return $board; } var executeMove = function(move) { /** * Execute a move from options.moveHistory */ switch(move[0]) { case 'N': var pieceType = 'knight'; var move = move.substring(1) break; case 'B': var pieceType = 'bishop'; var move = move.substring(1) break; case 'R': var pieceType = 'rook'; var move = move.substring(1) break; case 'Q': var pieceType = 'queen'; var move = move.substring(1) break; case 'K': var pieceType = 'king'; var move = move.substring(1) break; default: var pieceType = 'pawn'; break; } var $pieces = $('.' + options.whoseTurn); $pieces = $pieces.filter('.' + pieceType); var $piece = $([]); var $target = $('.' + move.substr(move.length - 2)); move = move.substr(0, move.length - 2, $target); if(move[move.length-1] == 'x') { var isCapture = true; move = move.substr(0, move.length -1) } else var isCapture = false; var $from = $('.square').filter(function() { return squareName($(this)).indexOf(move) >= 0; }); for(var i = 0; i < $pieces.length; i++) { var $p = $pieces.eq(i); var $sq = $p.parent(); if(!isCapture && validMoves($p).index($target) >= 0) { if($from.index($sq)) $piece = $piece.add($p); } if(isCapture && validCaptures($p).index($target) >= 0) { if($from.index($sq)) $piece = $piece.add($p); } } if($piece.length !== 1) { return false; } if(!isCapture) moveTo($piece, $target); else capture($piece, $target.children().eq(0)); options.moveHistory.pop(); nextTurn(); } var handlePieceClick = function() { if($(this).hasClass(options.whoseTurn)) { console.log($(this)); if(options.onSelect($(this)) == false) return false; $('.chessboard-active-piece') .removeClass('chessboard-active-piece'); $(this).addClass('chessboard-active-piece'); removeHighlighting(); validMoves($(this)) .addClass('chessboard-valid-move'); validCaptures($(this)) .addClass('chessboard-valid-capture'); } else if($(this).parent().hasClass('chessboard-valid-capture')) { var $active = $('.chessboard-active-piece'); capture($active, $(this)); nextTurn(); } return false; } var kill = function($piece) { $piece .css({ 'position': '', 'height': '', 'width': '', 'text-align': '', 'display': 'inline' }) .off('.chessboard'); if($piece.hasClass('white')) { $piece.appendTo('.chessboard-white-captured'); } else { $piece.appendTo('.chessboard-black-captured'); } } var handleSquareClick = function() { var $piece = $('.chessboard-active-piece'); if($(this).hasClass('chessboard-valid-move')) { if($(this).children().length == 0) { moveTo($piece, $(this)); nextTurn(); } } return false; } var squareName = function($square) { var classes = $square.attr('class').split(' '); var isNext = false; for(var i = 0; i < classes.length; i++) { if(isNext == true) return classes[i]; isNext = (classes[i] == 'square'); } return false; } var shortName = function($piece) { if($piece.hasClass('pawn')) return ''; if($piece.hasClass('knight')) return 'N'; if($piece.hasClass('bishop')) return 'B'; if($piece.hasClass('rook')) return 'R'; if($piece.hasClass('queen')) return 'Q'; if($piece.hasClass('king')) return 'K'; } var moveTo = function($piece, $target) { if(options.onMoveStart($piece) === false) return false; var $origin = $piece.parent(); $target.html($piece); options.moveHistory.push(shortName($piece) + squareName($target)); options.onMoveEnd($piece, options.moveHistory.slice(-1)[0]); } var capture = function($piece, $victim) { var $origin = $piece.parent(); var $target = $victim.parent(); options.moveHistory.push(shortName($piece) + 'x' + squareName($target)); kill($victim.clone()); $target.html($piece); options.onMoveEnd($piece, options.moveHistory.slice(-1)[0]); } var capFirst = function(string) { return string[0].toUpperCase() + string.substring(1); } var nextTurn = function() { removeHighlighting(); $('.chessboard-active-piece') .removeClass('chessboard-active-piece'); if(options.whoseTurn == 'white') { options.whoseTurn = 'black'; } else { options.whoseTurn = 'white'; } $('.chessboard-turn-shower') .html(capFirst(options.whoseTurn)+"'s Turn"); console.log(kingIsInCheck(options.whoseTurn)); return; } var removeHighlighting = function() { $('.chessboard-valid-move') .removeClass('chessboard-valid-move'); $('.chessboard-valid-capture') .removeClass('chessboard-valid-capture'); return; } var relativeSquare = function($piece, yOffset, xOffset) { /** * Returns the square relative to the piece. * +y is forward, -y is backward, +x is right, -x is left. */ if(!xOffset) var xOffset = 0; if(!yOffset) var yOffset = 0; if(!$piece) return $([]); var $square = $piece.parent(); var $row = $square.parent(); var $board = $row.parent(); var oldY = $board.children().index($row); var oldX = $row.children().index($square); if($piece.hasClass('white')) { var newY = oldY - yOffset; } else { var newY = oldY + yOffset; } var newX = oldX + xOffset; if(newX < 0 || newY < 0) return $([]); $target = $board .children().eq(newY) .children().eq(newX); return $target; } var validMoves = function($piece) { var $moves = $([]); var validKingMoves = function($piece) { var $moves = $([]); $moves = $moves.add(relativeSquare($piece, -1, -1)); $moves = $moves.add(relativeSquare($piece, 0, -1)); $moves = $moves.add(relativeSquare($piece, 1, -1)); $moves = $moves.add(relativeSquare($piece, -1, 0)); $moves = $moves.add(relativeSquare($piece, 1, 0)); $moves = $moves.add(relativeSquare($piece, -1, 1)); $moves = $moves.add(relativeSquare($piece, 0, 1)); $moves = $moves.add(relativeSquare($piece, 1, 1)); return $moves; } var validQueenMoves = function($piece) { var $moves = $([]); $moves = $moves.add(validRookMoves($piece)) $moves = $moves.add(validBishopMoves($piece)) return $moves; } var validRookMoves = function($piece) { var $moves = $([]); var x = 1; while(!relativeSquare($piece, 0, x).children().length) { if(!relativeSquare($piece, 0, x).length) { break; } $moves = $moves.add(relativeSquare($piece, 0, x)); x++; } var x = -1; while(!relativeSquare($piece, 0, x).children().length) { if(!relativeSquare($piece, 0, x).length) { break; } $moves = $moves.add(relativeSquare($piece, 0, x)); x--; } var y = 1; while(!relativeSquare($piece, y, 0).children().length) { if(!relativeSquare($piece, y, 0).length) { break; } $moves = $moves.add(relativeSquare($piece, y, 0)); y++; } var y = -1; while(!relativeSquare($piece, y, 0).children().length) { if(!relativeSquare($piece, y, 0).length) { break; } $moves = $moves.add(relativeSquare($piece, y, 0)); y--; } return $moves; } var validBishopMoves = function($piece) { var $moves = $([]); var i = 1; while(!relativeSquare($piece, i, i).children().length) { if(!relativeSquare($piece, i, i).length) { break; } $moves = $moves.add(relativeSquare($piece, i, i)); i++; } var i = -1; while(!relativeSquare($piece, i, i).children().length) { if(!relativeSquare($piece, i, i).length) { break; } $moves = $moves.add(relativeSquare($piece, i, i)); i--; } var i = 1; while(!relativeSquare($piece, i, -i).children().length) { if(!relativeSquare($piece, i, -i).length) { break; } $moves = $moves.add(relativeSquare($piece, i, -i)); i++; } var i = -1; while(!relativeSquare($piece, i, -i).children().length) { if(!relativeSquare($piece, i, -i).length) { break; } $moves = $moves.add(relativeSquare($piece, i, -i)); i--; } return $moves; } var validKnightMoves = function($piece) { var $moves = $([]); $moves = $moves.add(relativeSquare($piece, -2, -1)); $moves = $moves.add(relativeSquare($piece, -1, -2)); $moves = $moves.add(relativeSquare($piece, -2, 1)); $moves = $moves.add(relativeSquare($piece, -1, 2)); $moves = $moves.add(relativeSquare($piece, 2, -1)); $moves = $moves.add(relativeSquare($piece, 1, -2)); $moves = $moves.add(relativeSquare($piece, 2, 1)); $moves = $moves.add(relativeSquare($piece, 1, 2)); return $moves; } var validPawnMoves = function($piece) { var $moves = $([]); $moves = $moves.add(relativeSquare($piece, 1, 0)); if(!relativeSquare($piece, -2, 0).length) { $moves = $moves.add(relativeSquare($piece, 2, 0)); } return $moves; } //if($piece.hasClass(options.whoseTurn)) { if($piece.hasClass('king')) { $moves = $moves.add(validKingMoves($piece)); } if($piece.hasClass('queen')) { $moves = $moves.add(validQueenMoves($piece)); } if($piece.hasClass('rook')) { $moves = $moves.add(validRookMoves($piece)); } if($piece.hasClass('bishop')) { $moves = $moves.add(validBishopMoves($piece)); } if($piece.hasClass('knight')) { $moves = $moves.add(validKnightMoves($piece)); } if($piece.hasClass('pawn')) { $moves = $moves.add(validPawnMoves($piece)); } //} $moves.each(function() { if($(this).children().length !== 0) { // If a square is not empty, you can't moveTo there if // you're not capturing a piece. $moves = $moves.not(this); } }); return $moves; } var validCaptures = function($piece) { var validKingCaptures = function($piece) { var $moves = $([]); $moves = $moves.add(relativeSquare($piece, -1, -1)); $moves = $moves.add(relativeSquare($piece, 0, -1)); $moves = $moves.add(relativeSquare($piece, 1, -1)); $moves = $moves.add(relativeSquare($piece, -1, 0)); $moves = $moves.add(relativeSquare($piece, 1, 0)); $moves = $moves.add(relativeSquare($piece, -1, 1)); $moves = $moves.add(relativeSquare($piece, 0, 1)); $moves = $moves.add(relativeSquare($piece, 1, 1)); return $moves; } var validQueenCaptures = function($piece) { var $moves = $([]); $moves = $moves.add(validRookCaptures($piece)) $moves = $moves.add(validBishopCaptures($piece)) return $moves; } var validRookCaptures = function($piece) { var $moves = $([]); var x = 1; while(!relativeSquare($piece, 0, x).children().length) { if(!relativeSquare($piece, 0, x).length) { break; } x++; } $moves = $moves.add(relativeSquare($piece, 0, x)); var x = -1; while(!relativeSquare($piece, 0, x).children().length) { if(!relativeSquare($piece, 0, x).length) { break; } x--; } $moves = $moves.add(relativeSquare($piece, 0, x)); var y = 1; while(!relativeSquare($piece, y, 0).children().length) { if(!relativeSquare($piece, y, 0).length) { break; } y++; } $moves = $moves.add(relativeSquare($piece, y, 0)); var y = -1; while(!relativeSquare($piece, y, 0).children().length) { if(!relativeSquare($piece, y, 0).length) { break; } y--; } $moves = $moves.add(relativeSquare($piece, y, 0)); return $moves; } var validBishopCaptures = function($piece) { var $moves = $([]); var i = 1; while(!relativeSquare($piece, i, i).children().length) { if(!relativeSquare($piece, i, i).length) { break; } i++; } $moves = $moves.add(relativeSquare($piece, i, i)); var i = -1; while(!relativeSquare($piece, i, i).children().length) { if(!relativeSquare($piece, i, i).length) { break; } i--; } $moves = $moves.add(relativeSquare($piece, i, i)); var i = 1; while(!relativeSquare($piece, i, -i).children().length) { if(!relativeSquare($piece, i, -i).length) { break; } i++; } $moves = $moves.add(relativeSquare($piece, i, -i)); var i = -1; while(!relativeSquare($piece, i, -i).children().length) { if(!relativeSquare($piece, i, -i).length) { break; } i--; } $moves = $moves.add(relativeSquare($piece, i, -i)); return $moves; } var validKnightCaptures = function($piece) { var $moves = $([]); $moves = $moves.add(relativeSquare($piece, -2, -1)); $moves = $moves.add(relativeSquare($piece, -1, -2)); $moves = $moves.add(relativeSquare($piece, -2, 1)); $moves = $moves.add(relativeSquare($piece, -1, 2)); $moves = $moves.add(relativeSquare($piece, 2, -1)); $moves = $moves.add(relativeSquare($piece, 1, -2)); $moves = $moves.add(relativeSquare($piece, 2, 1)); $moves = $moves.add(relativeSquare($piece, 1, 2)); return $moves; } var validPawnCaptures = function($piece) { var $moves = $([]); $moves = $moves.add(relativeSquare($piece, 1, -1)); $moves = $moves.add(relativeSquare($piece, 1, 1)); return $moves; } var $moves = $([]); //if($piece.hasClass(options.whoseTurn)) { if($piece.hasClass('king')) { $moves = $moves.add(validKingCaptures($piece)); } if($piece.hasClass('queen')) { $moves = $moves.add(validQueenCaptures($piece)); } if($piece.hasClass('rook')) { $moves = $moves.add(validRookCaptures($piece)); } if($piece.hasClass('bishop')) { $moves = $moves.add(validBishopCaptures($piece)); } if($piece.hasClass('knight')) { $moves = $moves.add(validKnightCaptures($piece)); } if($piece.hasClass('pawn')) { $moves = $moves.add(validPawnCaptures($piece)); } //} $moves.each(function() { if($(this).children().length == 0) { // If a square is empty, you can't capture the piece // in that square. $moves = $moves.not(this); } if($(this).children().hasClass(color($piece))) { // You can't capture your own pieces. $moves = $moves.not(this); } }); return $moves; } var color = function($piece) { return $piece.hasClass('white') ? 'white' : 'black'; } var otherColor = function(playerColor) { return playerColor == 'white' ? 'black' : 'white'; } var kingIsInCheck = function(playerColor) { var kingIsInCheck = false; king = $('.king.'+playerColor)[0]; $('.' + otherColor(playerColor)).each(function () { //console.log(validCaptures($(this))); $vc = validCaptures($(this)); if($vc.length) { console.log($(this)); for(var i = 0; i < $vc.length; i++) { console.log($vc.eq(i).attr('class')); } } if(validCaptures($(this)).filter('.king').length > 0) { kingIsInCheck = true; } }); return kingIsInCheck; } var hasValidMoves = function(color) { $validMoves = $([]); $('.' + color).each(function() { $validMoves = $validMoves.add(validMoves($(this))); $validMoves = $validMoves.add(validCaptures($(this))); }); $validMoves = $validMoves.filter('.square, .black, .white'); if($validMoves.length > 0) return $validMoves; else return false; } return this.each(function() { if(func == 'init') { $(this).data({ options: options, pieces: pieces }); if(options.showHeader) { var $header = $('<div/>').addClass('chessBoard-header'); var $turnShower = $('<h1/>') .addClass('chessboard-turn-shower') .css({'text-align': 'center'}) .html(capFirst(options.whoseTurn)+"'s Turn"); $header.append($turnShower); $(this).append($header); } var $board = generateBoardHTML(); $(this).append($board); initializePieces($board); $board.css({ }); if(options.showFooter) { var $footer = $('<div/>').addClass('chessBoard-footer'); $whiteCaptured = $('<div/>') .addClass('chessboard-white-captured') .css({ 'width': $board.height() / 2 + 'px', 'display': 'inline-block', }); $blackCaptured = $('<div/>') .addClass('chessboard-black-captured') .css({ 'width': $board.height() / 2 + 'px', 'display': 'inline-block', }); $footer.append($whiteCaptured); $footer.append($blackCaptured); $(this).append($footer); } for(var i = 0; i < options.moveHistory.length; i++) { executeMove(options.moveHistory[i]); } } if(func == 'move') { console.log("Move:"+paramStr); executeMove(paramStr); if(!hasValidMoves(options.whoseTurn)) { console.log(options.whoseTurn,'loses.') if(options.whoseTurn == 'white') { options.onGameOver('black'); } else options.onGameOver('white'); } } }); } }); })(jQuery);
import React, { Component } from 'react'; import baityfooter from 'assets/img/baityfooter.png'; import { TiSocialTwitter, TiSocialInstagram, TiSocialFacebook, TiMail } from 'react-icons/lib/ti'; import styled from 'styled-components' import { LinkContainer } from "react-router-bootstrap"; import { IndexLinkContainer } from 'react-router-bootstrap'; import logo_placeholder from 'assets/img/logo-placeholder.jpg'; import Homepage from 'assets/img/Unselected-homepage.png'; import Idea from 'assets/img/Unselected-idea.png'; import Product from 'assets/img/UNselected-product.png'; import Profile from 'assets/img/Unselected-profile.png'; import ActiveProfile from 'assets/img/Profile-icon.png'; import ActiveIdea from 'assets/img/Selected-idea.png'; import ActiveHomepage from 'assets/img/Selected-homepage.png'; import ActiveProduct from 'assets/img/Selected-product.png'; const MobileDiv = styled.div` display: flex; flex-wrap: wrap; justify-content: space-between; padding-left:7px; padding-right:7px; } ` const IconImg = styled.img` width:25px; height:25px; ;` const UserImg = styled.img` width:30px; height:30px; border-radius: 50%; ` const UserName = styled.p` display:block; margin-left:auto; margin-right:auto; text-align:center; font-size:10px; padding:0; margin-bottom:1px; color:inherit; ` class Footer extends Component { constructor(props) { super(props); this.state = { userImg: "", year: new Date().getFullYear() }; } render() { return [ <footer className="myfooter" key="pc" fixed="true"> <div className="container" style={{ margin: '15px 5px' }}> <h4 style={{ display: 'inline-block', width: '20%' }}> <span> <img src={baityfooter} alt="" /></span> </h4> <h4 style={{ display: 'inline-block', width: '60%', textAlign: "center", fontSize: '21px' }}> {this.state.year} جميع الحقوق محفوظة </h4> <h6 style={{ display: 'inline-block', width: '20%', fontSize: '23px' }}> <a style={{ color: 'white' }}> <TiMail className="icons" /></a> <a style={{ color: 'white' }} href="https://twitter.com/baity_sa"> <TiSocialTwitter className="icons" /></a> <a style={{ color: 'white' }} href="https://www.instagram.com/baity_sa/"> <TiSocialInstagram className="icons" /></a> <a style={{ color: 'white' }} href="https://www.facebook.com/profile.php?id=100025094470933"> <TiSocialFacebook className="icons" /></a> </h6> </div> </footer>, <footer className="mopilefooter" key="mobile" fixed="true"> <MobileDiv > <IndexLinkContainer to="/" activeClassName="activePage"> <span> <IconImg src={Homepage} className="icons" /> <IconImg src={ActiveHomepage} className="activeIcons" /> <UserName> الرئيسية </UserName> </span> </IndexLinkContainer> <LinkContainer to="/productspages" activeClassName="activePage"> <span> <IconImg src={Product} className="icons" /> <IconImg src={ActiveProduct} className="activeIcons" /> <UserName> المنتجات </UserName> </span> </LinkContainer> <LinkContainer to="/ideaspage" activeClassName="activePage"> <span> <IconImg src={Idea} className="icons" /> <IconImg src={ActiveIdea} className="activeIcons" /> <UserName> التصاميم </UserName> </span> </LinkContainer> {!this.props.authenticated ? ( <LinkContainer to="/login" activeClassName="activePage"> {/* <UserImg src={logo_placeholder}/> */} <span> <IconImg src={ActiveProfile} className="activeIcons" /> <IconImg src={Profile} className="icons" /> <UserName> حسابي </UserName> </span> </LinkContainer> ) : ( <LinkContainer to="/myprofile" activeClassName="imgActivePage" // style={{display:'block',marginLeft:'auto',marginRight:'auto',padding:'0'}} > {this.props.userImg && this.props.userImg !== 'undefined' ? <UserImg src={this.props.userImg} /> : <UserImg src={logo_placeholder} /> } </LinkContainer> )} </MobileDiv> </footer>, ]; } } export default Footer;
function Utils(){ } Utils.removeChildren = function(viewObject){ var children = viewObject.children; for (var i = 0; i < children.length; ++i) { viewObject.remove(children[i]); } }; Utils.inArray = function(needle, haystack,property) { var length = haystack.length; var index = -1; for(var i = 0; i < length; i++){ if(!property){ if(haystack[i] == needle){ index = i; i = length; } }else{ if(haystack[i][property] == needle){ index = i; i = length; } } } return index; }; Utils.toMoney = function(precio){ precio = parseFloat(precio); return precio.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"); }; exports.capitalize = function(cadena){ return cadena[0].toUpperCase() + cadena.slice(1); };
const mysql = require('mysql') const config = require('./configs') const conn = mysql.createConnection(config.database.mysql) conn.connect((err) => { if (err) console.log(err) console.log('connected to database') }) module.exports = conn
import Maybe from "crocks/Maybe" import constant from "crocks/combinators/constant" import curry from "crocks/helpers/curry" import isEmpty from "crocks/predicates/isEmpty" import isObject from "crocks/predicates/isObject" import isSameType from "crocks/predicates/isSameType" import merge from "crocks/pointfree/merge" import not from "crocks/logic/not" import prop from "crocks/Maybe/prop" import safe from "crocks/Maybe/safe" import toPairs from "crocks/Pair/toPairs" import traverse from "crocks/pointfree/traverse" // isObjValueSameType :: Object -> String -> a -> Boolean const isObjValueSameType = curry((obj, key, val) => safe(isObject, obj) .chain(prop(key)) .chain(safe(isSameType(val))) .either(constant(false), constant(true)) ) // objPropsSameType :: Object -> Object -> Maybe Object const objPropsSameType = curry((objSrc, objToCheck) => safe(not(isEmpty), objToCheck) .map(toPairs) .chain(traverse(Maybe, safe(merge(isObjValueSameType(objSrc))))) .map(constant(objToCheck)) ) export default objPropsSameType
/** * Container that holds the content with the cursor, and manages the graphical blinking * of the cursor with regards to focusing, typing, and other requisite events. * * Modifies the passed-in content and cursor elements. * * @param content jQuery element holding the content * @param cursor jQuery element defining the cursor * @param blinkRate cursor blink rate * @param reblinkDelay delay after forced non-blinking period (eg typing) to blink again */ var access = require('./util/js/access.js'), getter = access.getter; module.exports = function(content, cursor, blinkRate, reblinkDelay) { // whether this element is focused // default false var focused = false; content.focus(function() { cursor.css('visibility', 'visible'); setCursorBlink(true); focused = true; }); content.blur(function() { cursor.css('visibility', 'hidden'); setCursorBlink(false); focused = false; }); // the interval that blinks the cursor var cursorBlinkInterval; // the function that toggles the cursor wrt blinking var blinkCursorFunc = function() { if(cursor.css('visibility') == 'visible') { cursor.css('visibility', 'hidden'); } else { cursor.css('visibility', 'visible'); } }; var isBlinking = false; var setCursorBlink = function(on) { if(on) { if(!isBlinking) { cursorBlinkInterval = setInterval(blinkCursorFunc, blinkRate); isBlinking = true; } } else { if(isBlinking) { clearInterval(cursorBlinkInterval); isBlinking = false; } } }; // Disables blinking while typing, and restarts it after a reblink delay. // TODO: Find a better way to do this var numKeyEvents = 0; content.keydown(function(e) { // start of non-blinking period if(numKeyEvents == 0) cursor.css('visibility', 'visible'); setCursorBlink(false); numKeyEvents++; setTimeout(function() { numKeyEvents--; if(numKeyEvents == 0) setCursorBlink(true); }, reblinkDelay); }); // Disables blinking with mouse down. content.mousedown(function() { setCursorBlink(false); cursor.css('visibility', 'visible'); }); content.mouseup(function() { setCursorBlink(true); }); // package up content.append(cursor); return { focused_: getter(focused), isBlinking_: getter(isBlinking), setCursorBlink_: setCursorBlink }; }
const floor = val => (val >= 0 || -1) * Math.floor(Math.abs(val)); /** * The extended Euclidean algorithm is an algorithm to * compute integers x and y such that given a and b. * ax + by = gcd(a, b) * @param {Number} a Coefficient of x * @param {Number} b Coefficient of y * @return {Object} Object containing value of x, y and gcd */ const extendedEuclidean = (a, b) => { const terminate = 1; let x = 1; let y = 0; let m = 0; let n = 1; if (a === 0) { return { gcd: b, x: y, y: n }; } if (b === 0) { return { gcd: a, x, y: m }; } let q; let result = { gcd: undefined, x: undefined, y: undefined }; while (terminate) { q = floor(a / b); a %= b; x -= q * y; m -= q * n; if (a === 0) { result = { gcd: b, x: y, y: n }; break; } q = floor(b / a); b %= a; y -= q * x; n -= q * m; if (b === 0) { result = { gcd: a, x, y: m }; break; } } return result; }; module.exports = extendedEuclidean;
import _ from 'lodash'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; class WeatherList extends Component { renderWeather(cityData) { const findAverages = (data) => { const daysData = []; const finalData = []; let i = 1; while (i <= 5) { const set = data.splice(0, 8); daysData.push(set); i++; } daysData.forEach((dayData) => { finalData.push({temprature: _.round(_.sum(dayData) / dayData.length)}); }); return finalData; } const name = cityData.city.name; const tempraturesAvgs = findAverages(cityData.list.map(weather => weather.main.temp)); const pressureAvgs = findAverages(cityData.list.map(weather => weather.main.pressure)); const humidityAvgs = findAverages(cityData.list.map(weather => weather.main.humidity)); return ( <tr key={name}> <td>{name}</td> <td> <Chart width={150} height={30} data={tempraturesAvgs} lineType='monotone' dataKey='temprature' strokeColor='#000000' strokeWidth='2' /> </td> <td> <Chart width={150} height={30} data={pressureAvgs} lineType='monotone' dataKey='temprature' strokeColor='#000000' strokeWidth='2' /> </td> <td> <Chart width={150} height={30} data={humidityAvgs} lineType='monotone' dataKey='temprature' strokeColor='#000000' strokeWidth='2' /> </td> </tr> ); } render() { return ( <table className='table table-hover'> <thead> <tr> <th>City</th> <th>Temprature</th> <th>Pressure</th> <th>Humidity</th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> ); } } // Note: in the ({ weather }), because we're pulling a single property (weather) from state // Equaivlent to (state) then using state.weather function mapStateToProps({ weather }) { // {weather} = {weather: weather} return { weather }; } export default connect(mapStateToProps)(WeatherList);
import swaggerJSDoc from 'swagger-jsdoc'; const swaggerDefinition = { openapi: '3.0.0', info: { title: 'REST API for #BuildForSDG app named CliquePay', // Title of the documentation version: '1.0.0', // Version of the app description: 'This is the REST API for a #BuildForSG project called CliquePay', // short description of the app }, servers: [ { url: 'https://build-for-sdg-team-387.herokuapp.com/api/v1', description: 'Deployed server' }, { url: 'http://localhost:5000/api/v1', description: 'Local development/testing server' }, ], components: { securitySchemes: { ApiKeyAuth: { type: 'apiKey', in: 'header', name: 'token', }, }, }, }; // options for the swagger docs const options = { // import swaggerDefinitions swaggerDefinition, // path to the API docs apis: ['server/docs/**/*.yaml'], }; // initialize swagger-jsdoc export default swaggerJSDoc(options);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const DataHelper_1 = require("../../../helpers/DataHelper"); class FinanceUpdate { constructor(model) { if (!model) return; this.userId = model.userId; this.financialYear = model.financialYear; this.currentBas = model.currentBas; this.currentProfit = model.currentProfit; this.grossIncome = model.grossIncome; this.expenseYear = model.expenseYear; this.incomeTax = model.incomeTax; this.integratedClient = model.integratedClient; this.estimatedTax = model.estimatedTax; this.putAsidedBas = model.putAsidedBas; this.monthlyDetail = model.monthlyDetail; DataHelper_1.default.handleDataModelInput(this); } } Object.seal(FinanceUpdate); exports.default = FinanceUpdate;
const request = require('supertest'); const app = require('../../src/app'); const connection = require('../../src/database/connection'); describe('Verifying if an ID is already used by an ONG', () => { beforeAll(async () => { await connection('ongs').insert({ id: 'apadteste', password: 'apadsenha', name: 'APAD - Teste', email: 'contato@teste.com', whatsapp: '5547912345678', city: 'Rio do Sul', uf: 'SC' }); }); afterAll(async () => { await connection('ongs').truncate(); await connection.destroy(); }); it('should verify if the ID passed exists and return true', async () => { const response = await request(app) .get('/ongs/verifyId/apadteste') .send(); expect(response.body).toHaveProperty('exists'); expect(response.body.exists).toBe(true); }); it('should verify if the ID passed exists and return false', async () => { const response = await request(app) .get('/ongs/verifyId/outraong') .send(); expect(response.body).toHaveProperty('exists'); expect(response.body.exists).toBe(false); }); });
/** * Created by clicklabs on 6/22/17. */ 'use strict' const Joi = require('joi'); //create logger const log = require('Utils/logger.js'); const logger = log.getLogger(); const userReffralCodeHandler = require( 'handler/config/userreffralcodehandler.js' ); const HttpErrors = require('Utils/httperrors.js'); module.exports.register = function(server, options, next) { server.route([ { method: 'POST', path: '/reffralcode', config: { auth: false, handler: userReffralCodeHandler.createReffralCode, //swagger related description: 'Create Reffral Code for User', notes: 'Create Reffral Code for User', tags: ['api','reff'], plugins: { 'hapi-swagger': { payloadType: 'form', responseMessages: HttpErrors.standardHTTPErrors } }, validate: { payload: { user_id : Joi.string() }, headers: { Authorization : Joi.string().description('User access token is required.') }, options: {abortEarly: false, allowUnknown: true} } } }, { method: 'POST', path: '/reffralcode/apply', config: { auth: false, handler: userReffralCodeHandler.applyReffralCode, //swagger related description: 'Apply Reffral Code for User at signup', notes: 'Apply Reffral Code for User at signup', tags: ['api','reff'], plugins: { 'hapi-swagger': { payloadType: 'form', responseMessages: HttpErrors.standardHTTPErrors } }, validate: { payload: { user_id : Joi.string(), reff_code : Joi.string(), reg_as : Joi.string().valid('SEEKER' , 'PROVIDER').required(), }, headers: { //Authorization : Joi.string().description('User access token is required.') }, options: {abortEarly: false, allowUnknown: true} } } } ]) next(); } module.exports.register.attributes = { name: 'futrun-reffralcode-module', version: '0.0.1' };
export const state = () => ({ prediction: "", image: "" }) export const mutations = { addimage(state, image){ state.image = image }, add(state, response){ state.prediction = response } }
import Icon from 'react-icons-kit' import { refreshCw , uploadCloud, downloadCloud, trash, send , logOut} from 'react-icons-kit/feather' import styled from 'styled-components' const Row = ({ children, title, description, icon, onclick }) => { const desc = description >= 30 ? `${description.substr(0, 50)}...` : description let actionIcon switch (icon) { case 'import': actionIcon = (<Icon icon={uploadCloud} />); break; case 'export': actionIcon = (<Icon icon={downloadCloud} />); break; case 'trash': actionIcon = (<Icon icon={trash} />); break; case 'award': actionIcon = (<Icon icon={send} />); break; case 'signOut': actionIcon = (<Icon icon={logOut} />); case 'sync': actionIcon = (<Icon icon={refreshCw} />); break; default: // code } return ( <List onClick={onclick}> <Indicator/> <Subli> <Title >{title}</Title> <Desc>{desc}</Desc> </Subli> {actionIcon} </List> ) } export default Row; const List = styled.li` cursor:pointer; user-select:none; display:flex; padding:10px; user-select:none; `; const Indicator = styled.span` margin: 0px; border-radius: 25px; margin-top:1em; height: 5px; width: 5px; background: red; `; const Subli = styled.div` flex:1 0; display:flex; flex-direction:column; line-height:1em; `; const Title = styled.span` font-weight:600; padding:5px; font-size:1.1em; ` const Desc = styled.span` color:#aaa; padding:5px; font-size:1em; `;
import Ember from 'ember'; const { Component, computed } = Ember; export default Component.extend({ list: null, //passed in });
import Ember from 'ember'; export default Ember.Route.extend({ model() { return this.store.query('candidate', { sort: '-probability' }); } });
"use strict"; document.addEventListener("DOMContentLoaded", function() { // fires validation document.getElementById("submit").addEventListener("click", changeColor1); document.getElementById("submit1").addEventListener("click", changeColor2); document.getElementById("submit2").addEventListener("click", changeColor3); document.getElementById("rub").addEventListener("click", rubay); function rubay() { let elem = document.getElementById("main-cont"); let elem2 = document.getElementById("rub"); if (elem.className == "container-fluid white-container") { elem.className = "container-fluid black-container" elem2.className = "rub-off" } else { elem.className = "container-fluid white-container" elem2.className = "rub-on" } } function win() { if (document.getElementById("main-cont").className == "container-fluid black-container") { return true } } function turnOn(id) { document.getElementById("b"+id).className = "b-on"; if (winwin()) { showReward(); return false } else { return true } } function toggleBulb(id) { let elem = document.getElementById("b"+id); if(elem.className == "b-off") { elem.className = "b-on"; } else { elem.className = "b-off"; } } // validates user input on submit function changeColor1() { if (win()) { if (turnOn(1)) { turnOn(2); } return } let id1 = Math.floor(Math.random() * 6); let id2 = Math.floor(Math.random() * 6); while (id1 == id2) { id2 = Math.floor(Math.random() * 6); } toggleBulb(id1); if (id2 <= 3) { toggleBulb(id2); } if (winwin()) { if (Math.floor(Math.random() * 10) <= 2) { showReward(); } } } function changeColor2() { if (win()) { if (turnOn(3)) { turnOn(4); } return } let id1 = Math.floor(Math.random() * 6); let id2 = Math.floor(Math.random() * 6); while (id1 == id2) { id2 = Math.floor(Math.random() * 6); } toggleBulb(id1); if (id2 <= 3) { toggleBulb(id2); } if (winwin()) { toggleBulb(0); } } function changeColor3() { if (win()) { if (turnOn(5)) { turnOn(0); } return } let id1 = Math.floor(Math.random() * 6); let id2 = Math.floor(Math.random() * 6); while (id1 == id2) { id2 = Math.floor(Math.random() * 6); } toggleBulb(id1); if (id2 <= 3) { toggleBulb(id2); } if (winwin()) { toggleBulb(5); } } function winwin() { let elem = document.getElementsByClassName("b-on"); console.log(elem.length) if (elem.length == 6) { return true } } function showReward() { alert("Ура! Ви розв'язали задачу. Перейдіть до наступної сторінки."); document.getElementById("final").className += " show"; } //////end of block/////// });
(function(app) { app.ContactsPage = ng.core.Component({ selector: 'contacts-page' }) .View({ templateUrl: '/licket/component/contacts-page/view' }) .Class({ constructor: function() { this.model = { }; } }); })(window.app || (window.app = {}));
import { useRedux } from 'Hooks/useRedux'; import { getUser } from 'State/user'; const TOKEN = process.env.REACT_APP_TOKEN_KEY; const useAuth = () => { const getToken = () => { return localStorage.getItem(TOKEN) || '' } const token = getToken(); const user = useRedux(['user'], getUser, { token }); const register = (newToken) => { localStorage.setItem(TOKEN, newToken); } const clear = () => { localStorage.removeItem(TOKEN); } return { isLoading: user.isLoading, authed: !user.error && token && user.data ? true : false, token, register, clear, info: user.data } } export default useAuth;
// require('./bootstrap'); window.Vue = require('vue'); require('vue-resource'); new Vue({ el: '#app', data: { products: [], }, created() { this.$http.get('/admin/product') .then(function (response) { console.log(response); this.products = response.body; }); }, methods: { createOrder(product) { this.$http .post('/admin/order', { ...product.order, product_id: product.id }, { headers: { 'X-CSRF-TOKEN': window.Laravel.csrf } }) .then(function (response) { console.log(response); }, function (err) { console.log(err); }); // 'a' + 'b' => 'ab' // 'a' . 'b' => 'ab' // array_concat([1, 2], [3, 4]) => [1, 2, 3, 4] // [1, 2].concat([3, 4]) => [1, 2, 3, 4] // [...[1, 2], ...[3, 4]] => [1, 2, 3, 4] ES6 // { id: product.id, name: product.order.name } // Object.assign({}, product.order, { id: product.id }) // => { id: product.id, name: product.order.name, ... } // { ...product.order, id: product.id } // => { id: product.id, name: product.order.name, ... } } } }); Vue.component('orders', require('./components/Orders.vue')); // <orders></orders> new Vue({ el: '#orders', });
{ "todos": [ { "id": 1, "title": "1 Lorem ipsum dolor sit amet", "isDone": false, "description": "f you are going \nto use a passage of L\norem Ipsum, you need to be sure t\nhere isn't anything em\nbarrassing hidden in t." }, { "id": 2, "title": "Donec nec justo eget feli", "isDone": true, "description": "to generate Lorem Ipsum \nwhich looks reasonable. The generated Lorem Ipsum \nis therefore always free from repetition, injected humour, \nor non-characteristic words etc." }, { "id": 3, "title": "Morbi in sem quis dui", "isDone": false, "description": "" }, { "id": 4, "title": "Praesent dapibus, neque id cursus faucibus", "isDone": true, "description": "" } ] }
"use strict"; const arr = [1, 2, 3, 4, 5]; /** * * @param {Array} arr to be processed * @param {*} cbk to map the elements * @returns {Array} of mapped elements * make new array * loop through arr * - call cbk(eachElement) and get return value and push it into new array * - return the resulting new array */ function myMap(arr, cbk) { const newArray = []; for (let i = 0; i < arr.length; i++) { newArray.push(cbk(arr[i], i, arr)); } return newArray; } const dblFun = (num, index) => index + ": " + (num * 2); const squareFun = num => num * num; console.log("expect [2, 4, 6,8,10] ", arr.map(dblFun)); console.log("expect [2, 4, 6,8,10] ", myMap(arr, dblFun)); console.log("expect [1, 4, 9, 16, 25] ", arr.map(squareFun)); console.log("expect [1, 4, 9, 16, 25] ", myMap(arr, squareFun)); /** * * @param {Array} arr to be processed * @param {Function} cbk callback * @param {*} initialVal value for the reduction * @returns {*} the reduction of the array * go through the array, call cbk with accumulator and element * return value of cbk becomes accumulator for next loop */ function myReduce(arr, cbk, initialVal) { let accumulator = initialVal; for (const element of arr){ accumulator = cbk(accumulator, element); } return accumulator; } const sumFun = (accum, val) => accum + val; const mulFun = (accum, val) => accum * val; console.log("expect: 15: ", arr.reduce(sumFun, 0)); console.log("expect: 15: ", myReduce(arr, sumFun, 0)); console.log("expect: 120: ", arr.reduce(mulFun, 1)); console.log("expect: 120: ", myReduce(arr, mulFun, 1));
// Show how to decode the word "DEED" /*global ODSA */ $(document).ready(function() { "use strict"; var av_name = "huffmanDecodeCON"; var config = ODSA.UTILS.loadConfig( {av_name: av_name, json_path: "/AV/Binary/huffman.json"}), interpret = config.interpreter; // get the interpreter var av = new JSAV(av_name); var t = construct_tree(av); var r = t.root(); // Slide 1 av.umsg(interpret("av_c8")); t.layout(); av.displayInit(); // Slide 2 av.umsg(interpret("av_c9")); av.step(); // Slide 3 av.umsg(interpret("av_c10") + interpret("av_c11")); r.highlight(); av.step(); // Slide 4 av.umsg(interpret("av_c10") + interpret("av_c12")); r.right().highlight(); av.step(); // Slide 5 av.umsg(interpret("av_c10") + interpret("av_c13")); r.right().left().highlight(); av.step(); // Slide 6 av.umsg(interpret("av_c10") + interpret("av_c14")); r.right().left().right().highlight(); av.step(); // Slide 7 av.umsg(interpret("av_c10") + interpret("av_c15")); av.step(); // Slide 8 av.umsg(interpret("av_c10") + interpret("av_c16")); r.right().unhighlight(); r.right().left().unhighlight(); r.right().left().right().unhighlight(); av.step(); // Slide 9 av.umsg(interpret("av_c10") + interpret("av_c17")); r.left().highlight(); av.step(); // Slide 10 av.umsg(interpret("av_c10") + interpret("av_c18")); av.step(); // Slide 11 r.left().unhighlight(); av.umsg(interpret("av_c10") + interpret("av_c19")); av.step(); // Slide 12 av.umsg(interpret("av_c10") + interpret("av_c20")); r.left().highlight(); av.step(); // Slide 13 av.umsg(interpret("av_c10") + interpret("av_c21")); r.left().unhighlight(); av.step(); // Slide 14 av.umsg(interpret("av_c10") + interpret("av_c22")); r.right().highlight(); av.step(); // Slide 15 av.umsg(interpret("av_c10") + interpret("av_c23")); r.right().left().highlight(); av.step(); // Slide 16 av.umsg(interpret("av_c10") + interpret("av_c22")); r.right().left().right().highlight(); av.step(); // Slide 17 av.umsg(interpret("av_c24")); av.recorded(); // Constructs the standard tree used in the slideshow function construct_tree(theav) { var theTree = theav.ds.binarytree({nodegap: 25}); var rt = theTree.root(""); // constructs tree rt.left("E<br>120"); rt.right("").right("").right("").right("").right("M<br>24"); rt.right().left("").left("U<br>37"); rt.right().left().right("D<br>42"); rt.right().right().left("L<br>42"); rt.right().right().right().left("C<br>32"); rt.right().right().right().right().left(""); rt.right().right().right().right().left().left("Z<br>2"); rt.right().right().right().right().left().right("K<br>7"); // Add more classes for leaf nodes for css styling rt.left().addClass("huffmanleaf"); rt.right().right().right().right().right().addClass("huffmanleaf"); rt.right().left().left().addClass("huffmanleaf"); rt.right().left().right().addClass("huffmanleaf"); rt.right().right().left().addClass("huffmanleaf"); rt.right().right().right().left().addClass("huffmanleaf"); rt.right().right().right().right().left().left().addClass("huffmanleaf"); rt.right().right().right().right().left().right().addClass("huffmanleaf"); // Add edge labels rt.edgeToLeft().label("0"); rt.edgeToRight().label("1"); rt.right().edgeToLeft().label("0"); rt.right().left().edgeToLeft().label("0"); rt.right().left().edgeToRight().label("1"); rt.right().edgeToRight().label("1"); rt.right().right().edgeToLeft().label("0"); rt.right().right().edgeToRight().label("1"); rt.right().right().right().edgeToLeft().label("0"); rt.right().right().right().edgeToRight().label("1"); rt.right().right().right().right().edgeToRight().label("1"); rt.right().right().right().right().edgeToLeft().label("0"); rt.right().right().right().right().left().edgeToLeft().label("0"); rt.right().right().right().right().left().edgeToRight().label("1"); return theTree; } });
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 reportTerm = (params, callback) => { return axios.post('/allReport/searchTerm', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function () { }) } // 保存进展汇报 export const saveReportInfo = (params, callback) => { return axios.post('/allReport/submitAllReport', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function () { }) } // 项目进展汇报 export const addProjectReportData = (params, callback, errorback) => { return axios.post('/progress/addProgress', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 批交办进展提交 export const addAssignReport = (params, callback, errorback) => { return axios.post('/checkReceipt/addCheckReceipt', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 三年行动计划 export const addPlanReport = (params, callback, errorback) => { return axios.post('/threeReport/addThreeReport', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 重要工作进展提交 export const addKeyworkReport = (params, callback, errorback) => { return axios.post('/tripleWorkProgressReport/addTripleWorkProgressReport', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 重要片区 export const addKeyareaReport = (params, callback, errorback) => { return axios.post('/tripleAreaProgressReport/addTripleAreaProgressReport', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) } // 重大项目 export const addItemReport = (params, callback, errorback) => { return axios.post('/situationProgress/addDecisionIAreaReport', qs.stringify({ ...params })).then((data) => { callback(data) }).catch(function (error) { errorback(error) }) }
import util from 'util'; import bodyParser from 'body-parser'; import request from 'request'; import session from 'express-session'; const RedisStore = require('connect-redis')(session); let options; const defaults = { api: { endpoint: '/api', host: undefined, port: 80, tokenOverride: undefined }, auth: { clientId: undefined, clientSecret: undefined, endpoint: undefined }, debug: false, endpoint: '/api', sessionStore: { type: 'memory', resave: false, saveUninitialized: false } }; function debug(...args) { if (options.debug) { const utilOptions = { depth: 12, colors: true }; console.log(util.inspect(args, utilOptions)); } } function parse(obj) { try { return JSON.parse(obj); } catch (error) { return null; } } function configure(overrides) { options = Object.assign(defaults, overrides); debug('JWT Config options:', options); } function refreshAuth(req, res) { return new Promise((resolve, reject) => { debug('refreshing token'); const form = { grant_type: 'refresh_token', refresh_token: req.session.refresh_token } request({ method: 'POST', url: options.auth.endpoint, headers: { 'Content-Type': 'application/vnd.api+json' }, json: true, body: form }, (error, response, body) => { if (error || !response || !response.body || !response.body.access_token) { debug('failed to refresh token', error); reject(error); } else { storeToken(req, response.body); resolve(); } }); }); } function storeToken(req, tokenData) { return new Promise((resolve, reject) => { if (!tokenData) { reject('no token data received to store') } if (!req.session) { reject('no session retrieved from store. is redis down?'); } req.session.access_token = tokenData.access_token; req.session.refresh_token = tokenData.refresh_token; req.session.expires_in = tokenData.expires_in; req.session.created_at = tokenData.created_at; debug('auth returned access token', req.session.access_token); debug('auth returned refresh token', req.session.refresh_token); debug('auth returned expires in', req.session.expires_in); debug('auth returned created at', req.session.created_at); req.session.save((err) => { if (err) { reject(err); } else { resolve('token stored'); } }); }) } function handleAuthResponse(error, response, body, req, res) { if (error || !response || !response.body || !response.body.access_token) { debug('auth error', body); res.sendStatus(401); } else { storeToken(req, response.body) .then(() => { res.status(200).json({ result: 'Success' }); }) .catch((err) => { debug(err); res.sendStatus(401); }) } } function login(req, res) { const form = { grant_type: 'password', email: req.body.user.email, password: req.body.user.password } // client id and secret are not always required, only add if specified if (options.auth.clientId && options.auth.clientSecret) { form.jwtClientId = options.auth.clientId; form.jwtClientSecret = options.auth.clientSecret; } request({ method: 'POST', url: options.auth.endpoint, headers: { 'Content-Type': 'application/vnd.api+json' }, json: true, body: form }, (error, response, body) => { // console.log('got response from auth server:', error, response); handleAuthResponse(error, response, body, req, res); }); } function logout(req, res) { if (req.session) { req.session.destroy((err) => { debug('error destroying session', err); }); } else { debug('error destroying session. does not exist. is redis down?'); } res.status(200).json({ result: 'Success' }); } function apiProxy(req, res) { let headers = {}; headers['Content-Type'] = 'application/vnd.api+json'; if (req.session && req.session.access_token) { const now = new Date().getTime() / 1000; const secondsSinceCreation = Math.round(now - Number(req.session.created_at)); const hasExpired = secondsSinceCreation > Number(req.session.expires_in); debug('seconds since creation', secondsSinceCreation); debug('greater than expiry?', hasExpired); if (hasExpired && req.session.refresh_token) { debug('access token expired'); refreshAuth(req, res).then(() => { debug('refresh auth successful, now making proxied call'); headers.authorization = `Bearer ${req.session.access_token}` makeProxiedCall(req, res, headers); }).catch(() => { debug('failed to refresh token'); headers.authorization = `Bearer ${req.session.access_token}` makeProxiedCall(req, res, headers); }) } else { debug('adding token:', req.session.access_token); headers.authorization = `Bearer ${req.session.access_token}` makeProxiedCall(req, res, headers); } } else if (options.api.tokenOverride && process.env.NODE_ENV === 'development') { debug('overriding with token:', options.api.tokenOverride); headers.authorization = `Bearer ${options.api.tokenOverride}`; makeProxiedCall(req, res, headers); } else { debug('no token to add or no session exists'); makeProxiedCall(req, res, headers); } }; function makeProxiedCall(req, res, headers) { let requestOptions = { method: req.method, headers: headers, url: options.api.host + ':' + options.api.port + options.api.endpoint + req.url } if (req.method !== 'GET') { requestOptions.json = true; requestOptions.body = req.body; } debug('proxying to api', requestOptions); request(requestOptions, (error, serviceResponse, body) => { if (!error && serviceResponse && serviceResponse.statusCode >= 200 && serviceResponse.statusCode < 400) { res.status(serviceResponse.statusCode); res.set(serviceResponse.headers); res.json(body); } else if (serviceResponse) { debug('api not ok.', serviceResponse.statusCode, error, body); res.status(serviceResponse.statusCode); res.json(body); } else { debug('api not ok. no response.', error, body); res.send(error); } }); } function setupSessionManager(app, options) { if (options.sessionStore.type === 'redis') { const redisConfig = Object.assign(options.sessionStore, { store: new RedisStore(options.sessionStore) }); // object assign is removing these if not specified in project config redisConfig.resave = false; redisConfig.saveUninitialized = false; debug('Using Redis for session store'); app.use(session(redisConfig)); } else { debug('Using memory session store.'); app.use(session(options.sessionStore)); } } function addSessionStateHeader(req, res, next) { if (req.session && req.session.access_token) { res.set('logged-in', true); } else { res.set('logged-in', false); } next(); } export default function (app, overrides) { configure(overrides); setupSessionManager(app, options); app.use(`${options.endpoint}`, bodyParser.json()); app.post(`${options.endpoint}/login`, login); app.post(`${options.endpoint}/logout`, logout); app.use(addSessionStateHeader); app.use(`${options.endpoint}`, apiProxy); }