text
stringlengths
7
3.69M
var cesar = cesar || (function(){ var proceso = function(txt, desp, action){ var remplazo = (function(){ var abc = ['a','b','c','d','e','f','g','h','i','j', 'k','l','m','n','o','p','q','r','s','t', 'u','v','w','x','y','z']; var l = abc.length; return function(c){ var i = abc.indexOf(c.toLowerCase()) if (i!=-1){ var pos = i; if (action){ pos+=desp; pos -= (pos >= i)?i:0; }else{ pos -= desp; pos += (pos < 0)?l:0; } return abc[pos]; } return c; }; })(); var re = (/[a-z]/ig); return String(txt).remplazo(re, function(match){ return remplazo(match); }) }; return{ encode:function(txt, desp){ return proceso(txt, desp, true); }, decode:function(txt,desp){ return proceso(txt, desp, false); } }; })(); function cifrar(){ document.getElementById("resultado").innerHTML = cesar.encode(document.getElementById("cadena").value, 3); } function descifrar(){ document.getElementById("resultado").innerHTML = cesar.encode(document.getElementById("cadena").value, 3); }
/* * Copyright (C) 2012-2013 DFKI GmbH * Deutsches Forschungszentrum fuer Kuenstliche Intelligenz * German Research Center for Artificial Intelligence * http://www.dfki.de * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ newMediaPlugin = { initialize: function(callBack){ var _pluginName = 'nuanceTextToSpeech'; //separator char for language- / country-code var _langSeparator = '_'; var languageManager = require('languageManager'); var commonUtils = require('commonUtils'); callBack({ textToSpeech: function (parameter, successCallBack, failureCallBack, startCallBack){ try{ var text; if((typeof parameter !== 'undefined')&& commonUtils.isArray(parameter) ){ //TODO implement pausing similar to maryTextToSpeech.js (i.e. in JS code); use XML? text = parameter.join('\n');//FIXME may need 2 newlines here: in some cases the Nuance TTS does not make pause, when there is only 1 newline (why?!?...) } else { //FIXME implement evaluation / handling the parameter similar to treatment in maryTextToSpeech.js text = parameter; } window.plugins.nuancePlugin.speak( text, successCallBack, failureCallBack, languageManager.getLanguageConfig(_pluginName, 'language', _langSeparator) //TODO get & set voice (API in plugin is missing for that ... currently...) //, languageManager.getLanguageConfig(_pluginName, 'voice') ); //TODO implement real start-callback (needs to be done within java-/javascript-plugin) if(startCallBack){ startCallBack(); } } catch(e){ if(failureCallBack){ failureCallBack(e); } } }, cancelSpeech: function(successCallBack,failureCallBack){ //FIXME currently, NuancePlugin returns failure on successful cancel-performance, so we call the function with switched failure, success arguments... // -> switch back, when NuancePlugin returns PluginResults correctly... window.plugins.nuancePlugin.cancel(failureCallBack, successCallBack); }, setTextToSpeechVolume: function(newValue){ //FIXME implement this? how? Nuance library gives no access to audio volume (we could set the Android volume level ...) } }); } };
var tokki = angular.module("tokkiFilters").filter('despacho', function() { return function(input){ switch(input) { case 0: case "0": return 'Despacho Interno'; break; case 1: case "1": return 'Despacho por Receptor'; break; case 2: case "2": return 'Despacho por Emisor'; break; case 3: case "3": return 'Despacho a otras instalaciones'; break; } } })
// JavaScript - Node v8.1.3 var arr = [1, 2]; swapValues(arr); Test.assertEquals(arr[0], 2, 'Failed swapping numbers'); Test.assertEquals(arr[1], 1, 'Failed swapping numbers');
'use strict'; var $ = require('jquery'); var _ = require('underscore'); var Backbone = require('backbone'); var AppModel = require('../../models/appModel'); var AppRouter = require('../../routers/appRouter'); var App = Backbone.View.extend({ model: null, loaded: 0, loading:0, preloadBar: null, initialize: function() { this.preloadBar = $('#loading-bar'); this.model = new AppModel(); this.listenTo(this.model, 'change', this.onModelLoaded); this.loading++; this.model.fetch(); this.manifest = [ 'images/icon01.png', 'images/icon02.png', 'images/icon03.png', 'images/icon04.png', 'images/icon05.png', 'images/icon06.png', 'images/icon07.png', 'images/icon08.png', 'images/icon09.png', 'images/icon10.png', 'images/icon11.png', 'images/icon12.png', 'images/icon13.png', 'images/icon14.png', 'images/icon15.png', 'images/icon16.png', 'images/icon17.png', 'images/icon18.png', 'images/icon19.png', 'images/icon20.png', 'images/icon21.png', 'images/icon22.png', 'images/icon23.png', 'images/lever-x.png', 'images/card-bg-grey.jpg', 'images/rotate-tablet.png', 'images/rotate-device.jpg', 'images/UpAnim.gif', 'images/DownAnim.gif' ]; for (var i = 0; i < this.manifest.length; i++) { this.loadImage(this.manifest[i]); } }, loadImage: function( path ) { this.loading++; var image = new Image(); $( image ).on('load', this.onImageLoaded.bind(this)); image.src = path; }, onImageLoaded: function() { this.loaded++; this.preloadBar.css( 'width', ((this.loaded / this.loading) * 100) + '%' ); var _model = this.model; var _show = this.show.bind(this); if ( ((this.loaded / this.loading) * 100) === 100 ){ TweenMax.to( this.preloadBar.parent(), 0.25, { autoAlpha: 0, display: 'none', onComplete: function() { var appRouter = new AppRouter(); appRouter.start( _model ); _show(); } }); } }, show: function() { TweenMax.to(this.el, 0, {alpha: 0}); this.$el.removeClass('displayNone'); TweenMax.to(this.el, 0.25, {delay: 0.5, alpha: 1}); }, onModelLoaded: function() { this.stopListening(this.model, 'change', this.onModelLoaded); this.onImageLoaded(); } }); module.exports = App;
$(document).ready(function() { var selected_dates = []; // gets all the events from the database using AJAX selected_dates = getSelectedDates(); $('#datepicker').datepicker({ inline: true, dateFormat: 'dd-mm-yy', showOtherMonths: true, dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], beforeShowDay: function (date) { // gets the current month, day and year // Attention: the month counting starts from 0 that's why you'll need to +1 to get the month right var mm = date.getMonth() + 1, dd = date.getDate(), yy = date.getFullYear(); var dt = yy + "-" + mm + "-" + dd; if(typeof selected_dates[dt] != 'undefined') { // puts a special class to the dates in which you have events, so that you could distinguish it from the other ones // the "true" parameter is used to know which are the clickable dates return [true, " my_class"]; } return [false, ""]; }, onSelect: function(date) { $(this).change(); } }) .change(function() { window.location.href = "http://localhost/app/events/date/" + this.value; }); $("#refresh").click(function() { $("#captcha").attr("src","http://localhost/app/util/visual-captcha.php?" + Math.random()); }); $('#loginform').submit(function(e) { var thisForm = $('#loginform'); //Prevent the default form action e.preventDefault(); //Post the form to the send script $.ajax({ type: 'POST', url: thisForm.attr("action"), data: thisForm.serialize(), //Wait for a successful response success: function(data){ //Hide the "loading" message $("#loginloading").fadeOut(function(){ //Display the "success" message $("#loginsuccess").html(data).fadeIn(); }); }, complete:function() { $('#addresform').each(function() { this.reset(); }); } }); }); $('#addressForm').validate({ errorClass: "authError", errorElement: "div", rules: { signupname: "required", signupemail: { required: true, email: true } }, messages: { signupname: "Please enter your name", signupemail: { required: "We need your email address to send the newsletter", email: "Your email address must be in the format of name@example.com" } }, errorPlacement: function (error, element) { error.insertBefore(element); }, highlight: function(element, errorClass) { $(element).removeClass(errorClass); }, submitHandler: function(form) { var thisForm = $('#addressForm'); $("#signupsuccess").html("Signing you up...").fadeIn("slow"); //Post the form to the send script $.ajax({ type: 'POST', url: 'http://localhost/util/NewsletterSignup.php', data: thisForm.serialize(), //Wait for a successful response success: function(data) { //Hide the "loading" message $("#signupsuccess").fadeOut("slow", function() { //Display the "success" message $("#signupsuccess").html(data).fadeIn("slow"); }); }, complete:function() { thisForm.each(function() { this.reset(); }); }, error: function(xhr, textStatus, errorThrown) { alert('request failed'); } }); } }); $("#signupname").bind('focusin', function(e) { $(this).data('content', $(this).val()).val(''); }) .bind('focusout', function(e) { if ( $(this).val() === '' ) { $(this).val( $(this).data('content') ); } }); $("#signupemail").bind('focusin', function(e) { $(this).data('content', $(this).val()).val(''); }) .bind('focusout', function(e) { if ( $(this).val() === '' ){ $(this).val( $(this).data('content') ); } }); $("#loginUsername").bind('focusin', function(e) { $(this).data('content', $(this).val()).val(''); }) .bind('focusout', function(e) { if ( $(this).val() === '' ) { $(this).val( $(this).data('content') ); } }); $("#loginPassword").bind('focusin', function(e) { $(this).data('content', $(this).val()).val(''); }) .bind('focusout', function(e) { if ( $(this).val() === '' ){ $(this).val( $(this).data('content') ); } }); $(".text-input").focus(function(){ $('#form_result').hide(); }); $('#form_result').hide(); $('#sending').hide(); $('#refresh').click(function() { $("#captchaimg").attr("src","/app/util/visual-captcha.php?" + Math.random()); }); $('#social-nav a').stop().animate({'marginLeft':'-60px'},1000); $('#social-nav > li').hover( function () { $('a',$(this)).stop().animate({'marginLeft':'-2px'},200); }, function () { $('a',$(this)).stop().animate({'marginLeft':'-60px'},200); } ); }); function getSelectedDates() { var the_selected_dates = []; $.ajax( { url: 'http://localhost/app/util/events.php', dataType: 'json', async: false, success: function(data) { $.each(data, function(n, val) { the_selected_dates[val.eventdate] = val; }); } }); return the_selected_dates; } function forumFlag(ids) { var id = ids.substr(7); $.ajax({ type :'POST', url: 'http://localhost/mvc/util/report.php', data : 'messageid='+id, success : function() { $('p#reported_'+id).text('Post reported to moderator').show(); $('a#report_'+id).hide(); }, error: function(){ alert("Something went wrong. Please try again"); } }); }
import React, { AppRegistry, Component } from 'react-native'; import LoginPage from '../components/LoginPage'; export default class App extends Component { render() { return ( <LoginPage /> ); } }
/** * Created by xuwusheng on 15/12/18. */ define(['../../../app'], function (app) { app.factory('tackGoodsDifference', ['$http','$q','$filter','HOST',function ($http,$q,$filter,HOST) { return { getThead: function () { return [ {name:'序号',type:'pl4GridCount',style:'width:50px;'}, {field:'taskId',name:'业务单号'}, {field:'custTaskId',name:'客户单号'}, {field:'taskType',name:'业务类型'}, {field:'ckName',name:'仓库名称'}, {field:'receMan',name:'收货人'}, {field:'updateTime',name:'收货日期'}, {field:'count',name:'差异数量'}, {field:'countMoney',name:'差异金额'}, {field:'op',name:'操作',type:'operate',buttons: [{ text: '查看', btnType: 'link', state: 'differenceCheck' }]}, ] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/differentMonitor/getDicLists',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function (url,data) { //将parm转换成json字符串 data.param=$filter('json')(data.param); var deferred=$q.defer(); $http.post(url, data) .success(function (data) { deferred.resolve(data); }) .error(function (e) { deferred.reject('error:'+e); }); return deferred.promise; } } }]); });
const mongoose = require('mongoose') const schema = new mongoose.Schema({ name: { type: String },//名称 spec: { type: String },//规格 avatar: { type: String },//头像 banner: { type: String }, categories: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'GoodsCategory' }],//关联分类 //评分 scores: { difficult: { type: Number }, skills: { type: Number }, effect: { type: Number }, utility: { type: Number }, }, // 产品使用出装 items1: [{ type: mongoose.SchemaTypes.ObjectId, ref: 'Item' }], color: { type: String }, feature: { type: String }, scope: { type: String }, // 搭档 partners: [{ goodse: { type: mongoose.SchemaTypes.ObjectId, ref: 'Goodse' }, description: { type: String } }] }) module.exports = mongoose.model('Goods', schema)
alert("hola"); alert("hola2"); //este es un archivo de prueba 2 //prueba 2 jjjjjj kkkk jjjjj
$(document).ready(function () { $("#wizard").steps(); $("#form").steps({ labels: { current: "current step:", pagination: "Pagination", finish: "Kaydet", next: "İleri", previous: "Geri", loading: "Yükleniyor.." }, bodyTag: "fieldset", transitionEffect: "slideLeft", stepsOrientation: "vertical", onStepChanging: function (event, currentIndex, newIndex) { // Always allow going backward even if the current step contains invalid fields! if (currentIndex > newIndex) { return true; } // Forbid suppressing "Warning" step if the user is to young if (newIndex === 1) { var check = true; if ($("#KategoriSelect").val() == "") { bilgilendirme_toast("<div >Lütfen Kategori Seciniz</div>"); check = false; } if ($("#DersAdi").val() == "") { bilgilendirme_toast("<div >Lütfen Ders Adi Giriniz</div>"); check = false; } if ($("#DersKoduInput").val() == "") { bilgilendirme_toast("<div >Ders Kodu Boş Bırakılamaz</div>"); check = false; } if ($("#Acıklama").val() == "") { bilgilendirme_toast("<div >Lütfen Açıklama Yazınız</div>"); check = false; } if ($("#EgitimTuru").val() == "") { bilgilendirme_toast("<div >Lütfen Eğitim Türünü Seçiniz</div>"); check = false; } } if (newIndex === 2) { var check = true; if ($("#EgitimSorumlusu").val() == "") { bilgilendirme_toast("<div >Lütfen Eğitim Sorumlusunu Yazınız</div>"); check = false; } if ($("#HedefKitle").val() == "") { bilgilendirme_toast("<div >Lütfen Hedef Kitleyi Yazınız</div>"); check = false; } if ($("#Seans").val() == "") { bilgilendirme_toast("<div >Lütfen Seans Giriniz</div>"); check = false; } if ($("#SeansPeriyod").val() == "") { bilgilendirme_toast("<div >Lütfen Seans Periyodunu Belirtiniz</div>"); check = false; } if ($("#Egitmen").val() == "") { bilgilendirme_toast("<div >Lütfen Eğitimeni Yazınız</div>"); check = false; } if ($("#OgrenimHedefleri").val() == "") { bilgilendirme_toast("<div >Lütfen Ogrenim Hedeflerini Belirtiniz</div>"); check = false; } if ($("#Sure").val() == "") { bilgilendirme_toast("<div >Lütfen Sure Yazınız</div>"); check = false; } if ($("#OrtamGereklilikleri").val() == "") { bilgilendirme_toast("<div >Lütfen Ortam Gereklilikleri Yazınız</div>"); check = false; } if ($("#Medya").val() == "") { bilgilendirme_toast("<div >Lütfen Medya Belirtiniz</div>"); check = false; } if ($("#BasarımOlcuteri").val() == "") { bilgilendirme_toast("<div>Lütfen Basarım Olcutleri Yazınız</div>"); check = false; } } if (newIndex === 3) { var check = true; if ($("#Egitmen").val() == "") { bilgilendirme_toast("<div >Lütfen Eğitmen Giriniz</div>"); check = false; return check; } if ($("#Medya").val() == "") { bilgilendirme_toast("<div >Lütfen Medya Giriniz</div>"); check = false; return check; } } var form = $(this); // Clean up if user went backward before if (currentIndex < newIndex) { // To remove error styles $(".body:eq(" + newIndex + ") label.error", form).remove(); $(".body:eq(" + newIndex + ") .error", form).removeClass("error"); } // Disable validation on fields that are disabled or hidden. form.validate().settings.ignore = ":disabled,:hidden"; // Start validation; Prevent going forward if false return form.valid(); }, onStepChanged: function (event, currentIndex, priorIndex) { if (currentIndex == 2) { var egitimturu = $("#EgitimTuru").val(); if ($("#Seans").val() == "tek") { var seanssayi = 1; } else { var seanssayi = $("#SeansSayisiInput").val(); } $("#accordion").empty(); for (var i = 1; i <= seanssayi; i++) { var collapse = ""; var arti = "fa fa-plus"; if (i == 1) { collapse = "in"; arti = "fa fa-minus"; } if (egitimturu == "Online") { $("#accordion").append(` <div class="panel panel-default"> <div class="panel-heading" style="background-color:#ddeedd;"> <h4 class="panel-title"> <a class="buton ${arti}" data-toggle="collapse" href="#collapse${i}" > </a> <a >Seans ${i}</a> <a style="margin-left:810px;background-color:#f8ac59" class="kapat btn btn btn-danger btn-xs fa fa-trash" data-veri-varmi="0" data-grup-value="collapse${i}" ></a> </h4> </div> <div id="collapse${i}" class="panel-collapse collapse ${collapse}"> <div class="panel-body"><div class="form-group row" > <label class="col-md-2 control-label"> <span>Eğitmen</span> </label> <div class="col-md-4"> <input class="form-control" name="Egitmen" id="Egitmen" type="text" /> </div> <label class="col-md-2 control-label"> <span>Öğrenim Hedefleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OgrenimHedef" id="OgrenimHedef" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Süre</span> </label> <div class="col-md-4"> <input class="form-control" name="Sure" id="Sure" type="time" /> </div> <label class="col-md-2 control-label"> <span>Ortam Gereklilikleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OrtamGereklilik" id="OrtamGereklilik" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Medya</span> </label> <div class="col-md-4"> <input class="form-control" name="Medya" id="Medya" type="file" /> </div> <div class="col-md-2"> </div> </div> </div> </div> </div> `); } else { $("#accordion").append(`<div class="panel panel-default"> <div class="panel-heading" style="background-color:#ddeedd;"> <h4 class="panel-title"> <a class="buton ${arti}" data-toggle="collapse" href="#collapse${i}" > </a> <a >Seans ${i}</a> <a style="margin-left:810px;background-color:#f8ac59" class="kapat btn btn btn-danger btn-xs fa fa-trash" data-veri-varmi="0" data-grup-value="collapse${i}" ></a> </h4> </div> <div id="collapse${i}" class="panel-collapse collapse ${collapse}"> <div class="panel-body"><div class="form-group row" > <label class="col-md-2 control-label"> <span>Öğrenim Hedefleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OgrenimHedefleri" id="OgrenimHedef" type="text" /> </div> <label class="col-md-2 control-label"> <span>Eğitmen</span> </label> <div class="col-md-4"> <input class="form-control" name="Egitmen" id="Egitmen" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Süre</span> </label> <div class="col-md-4"> <input class="form-control" name="Sure" id="Sure" type="time" /> </div> <label class="col-md-2 control-label"> <span>Ortam Gereklilikleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OrtamGereklilikleri" id="OrtamGereklilik" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Araçlar</span> </label> <div class="col-md-4"> <input class="form-control" name="Araclar" id="Araclar" type="text" /> </div> <label class="col-md-2 control-label"> <span>Egitim Medya</span> </label> <div class="col-md-4"> <input class="form-control" name="EgitmenMedya" id="EgitmenMedya" type="file" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Egitmen Yetkinlikleri</span> </label> <div class="col-md-4"> <input class="form-control" name="EgitmenYetkinlikleri" id="EgitmenYetkinlikleri" type="text" /> </div> </div> <div class="col-md-2"> </div> </div> </div> </div> </div> `); } } if ($("#Seans").val() == "tek") { $("#seansekle").hide(); $(".kapat").hide(); } else { $("#seansekle").show(); $(".kapat").show(); } } }, onFinishing: function (event, currentIndex) { var form = $(this); var check = true; return check; }, onFinished: function (event, currentIndex) { var form = $(this); form.submit(); } }).validate({ errorPlacement: function (error, element) { element.before(error); }, rules: { confirm: { equalTo: "#passw" } } }); $("#Seans").on("change", function () { if ($("#Seans").val() == "cok") { $("#SeansSayisi").append(`<label class="col-md-4 control-label"> <span>Seans Sayısı</span> <span class="zorunlu">*</span>: </label> <div class="col-md-8"> <input class="form-control" name="SeansSayisiInput" id="SeansSayisiInput" type="number" required /> </div>`); } if ($("#Seans").val() == "tek") { $("#SeansSayisi").empty(); } }); $('a[href="#finish"]').addClass("buttonToAction"); $('.chosen-select').chosen({ width: "100%" }); }); $(document).on("click", ".buton", function () { if ($(this).attr('class') == "buton fa fa-plus") { $(this).removeClass(); $(this).addClass("buton fa fa-minus"); } else { $(this).removeClass(); $(this).addClass("buton fa fa-plus"); } }); $(document).on("click", ".kapat", function () { var silinecek = this.parentElement.parentElement.parentElement; var seanssayisi = $("#SeansSayisiInput").val(); $("#SeansSayisiInput").val(seanssayisi - 1); silinecek.remove(); }); $(document).on('click', "#seansekle", function () { var sonseanssayi = Number($("#SeansSayisiInput").val()); var eklenenseanssayi = sonseanssayi + 1; $("#SeansSayisiInput").val(sonseanssayi + 1); var collapses = ""; var artii = "fa fa-plus"; if (eklenenseanssayi == 1) { collapses = "in"; artii = "fa fa-minus"; } var egitimturuekle = $("#EgitimTuru").val(); if (egitimturuekle == "Online") { $("#accordion").append(` <div class="panel panel-default"> <div class="panel-heading" style="background-color:#ddeedd;"> <h4 class="panel-title"> <a class="buton ${artii}" data-toggle="collapse" href="#collapse${eklenenseanssayi}" > </a> <a >Seans ${eklenenseanssayi}</a> <a style="margin-left:810px;background-color:#f8ac59" class="kapat btn btn btn-danger btn-xs fa fa-trash" data-veri-varmi="0" data-grup-value="collapse${eklenenseanssayi}" ></a> </h4> </div> <div id="collapse${eklenenseanssayi}" class="panel-collapse collapse ${collapses}"> <div class="panel-body"><div class="form-group row" > <label class="col-md-2 control-label"> <span>Eğitmen</span> </label> <div class="col-md-4"> <input class="form-control" name="Egitmen" id="Egitmen" type="text" /> </div> <label class="col-md-2 control-label"> <span>Öğrenim Hedefleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OgrenimHedef" id="OgrenimHedef" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Süre</span> </label> <div class="col-md-4"> <input class="form-control" name="Sure" id="Sure" type="time" /> </div> <label class="col-md-2 control-label"> <span>Ortam Gereklilikleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OrtamGereklilik" id="OrtamGereklilik" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Medya</span> </label> <div class="col-md-4"> <input class="form-control" name="Medya" id="Medya" type="file" /> </div> <div class="col-md-2"> </div> </div> </div> </div> </div> `); } else { $("#accordion").append(`<div class="panel panel-default"> <div class="panel-heading" style="background-color:#ddeedd;"> <h4 class="panel-title"> <a class="buton ${artii}" data-toggle="collapse" href="#collapse${eklenenseanssayi}" > </a> <a >Seans ${eklenenseanssayi}</a> <a style="margin-left:810px;background-color:#f8ac59" class="kapat btn btn btn-danger btn-xs fa fa-trash" data-veri-varmi="0" data-grup-value="collapse${eklenenseanssayi}" ></a> </h4> </div> <div id="collapse${eklenenseanssayi}" class="panel-collapse collapse ${collapses}"> <div class="panel-body"><div class="form-group row" > <label class="col-md-2 control-label"> <span>Öğrenim Hedefleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OgrenimHedefleri" id="OgrenimHedef" type="text" /> </div> <label class="col-md-2 control-label"> <span>Eğitmen</span> </label> <div class="col-md-4"> <input class="form-control" name="Egitmen" id="Egitmen" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Süre</span> </label> <div class="col-md-4"> <input class="form-control" name="Sure" id="Sure" type="time" /> </div> <label class="col-md-2 control-label"> <span>Ortam Gereklilikleri</span> </label> <div class="col-md-4"> <input class="form-control" name="OrtamGereklilikleri" id="OrtamGereklilik" type="text" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Araçlar</span> </label> <div class="col-md-4"> <input class="form-control" name="Araclar" id="Araclar" type="text" /> </div> <label class="col-md-2 control-label"> <span>Egitim Medya</span> </label> <div class="col-md-4"> <input class="form-control" name="EgitmenMedya" id="EgitmenMedya" type="file" /> </div> </div> <div class="form-group row"> <label class="col-md-2 control-label"> <span>Egitmen Yetkinlikleri</span> </label> <div class="col-md-4"> <input class="form-control" name="EgitmenYetkinlikleri" id="EgitmenYetkinlikleri" type="text" /> </div> </div> <div class="col-md-2"> </div> </div> </div> </div> </div> `); } }); function bilgilendirme_toast(mesaj) { Command: toastr["warning"]( mesaj); toastr.options = { "closeButton": true, "debug": false, "progressBar": false, "positionClass": "toast-top-right", "onclick": null, "showDuration": "400", "hideDuration": "1000", "timeOut": "7000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } } $("#fotograf_sil").on('click', function () { $('#FirmaImage').val(""); $('#foto_varmi_kontrol').val(1); $("#fotograf").attr('src', firmaImagePath); const lightBoxGallery_href = document.getElementById("lightBoxGallery_href"); lightBoxGallery_href.href = firmaImagePath; }); model_gelen_foto_ayarla(); function model_gelen_foto_ayarla() { // modelden gelen fotografi fotogral alani icerisinde boyutuna gore ayarlar const img = document.getElementById('fotograf'); const width = img.clientWidth; const height = img.clientHeight; if (height > width) { img.style.width = 'auto'; img.style.height = '100%'; } else { img.style.width = '100%'; img.style.height = 'auto'; } } var _URL = window.URL || window.webkitURL; $("#FirmaImage").change(function (e) { var file, img; $('#foto_varmi_kontrol').val(1); if ((file = this.files[0])) { img = new Image(); img.onload = function () { //alert(this.width + " " + this.height); $('#fotograf').attr('src', this.src); $('#fotograf').hide(); $('#fotograf').fadeIn(650); var foto_heigth, foto_width; foto_heigth = this.height; foto_width = this.width; const yourImg = document.getElementById('fotograf'); if ((foto_heigth > foto_width)) { yourImg.style.width = '80%'; yourImg.style.height = '100%'; } else { yourImg.style.width = '100%'; yourImg.style.height = '80%'; } }; img.onerror = function () { alert(`not a valid file: ${file.type}`); }; img.src = _URL.createObjectURL(file); const lightBoxGallery_href = document.getElementById("lightBoxGallery_href"); lightBoxGallery_href.href = _URL.createObjectURL(file); } });
/** * Created by xiaojiu on 2017/4/24. */ define(['../../../app'], function (app) { app.factory('thirdPartyFreightPay', ['$http','$q','$filter','HOST',function ($http,$q,$filter,HOST) { return { getThead: function () { return [ {name:'序号',type:'pl4GridCount'}, {field:'taskId',name:'业务单号'}, {field:'createTime',name:'订单时间'}, {field:'chuHuoName',name:'发件方'}, {field:'chuHTel',name:'发件方电话'}, {field:'chuHuoAddress',name:'发件方地址'}, {field:'receiverName',name:'收件方'}, {field:'receTel',name:'收件方电话'}, {field:'receiverAddress',name:'收件方地址'}, {field:'thirdWlId',name:'第三方单号'}, {field:'thirdpartyPay',name:'第三方运费'}, {field:'shippedFreightStatu',name:'是否结算'}, {field:'userName',name:'付款人'}, { field: 'op', name: '操作', type: 'operate', style:'width:50px;', buttons: [{ text: '付款', call: 'updateGift', btnType: 'button', openModal: '#workLogModal' }] }] }, getSearch: function() { var deferred = $q.defer(); $http.post(HOST + '/deliveryPartyPay/thirdPartyFreightPayDicList',{}) .success(function(data) { deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; }, getDataTable: function( url, data) { //将param转换成json字符串 data.param = $filter('json')(data.param); //console.log(data) var deferred = $q.defer(); $http.post(HOST + url, data) .success(function(data) { //console.log(data) deferred.resolve(data); }) .error(function(e) { deferred.reject('error:' + e); }); return deferred.promise; } } }]); });
const Appacitive = require('appacitive'); const promise = Appacitive.initialize({ apikey: "MEk6aMTDtliwwwQvQgT7GXNS+Ak8P7FI6Q/pqYTpgVY=", env: "sandbox", appId: "168002687610258053" }); /* function contractUserObject(userData){ let user = {}; user.username = userData.username; user.password = userData.password; user.firstname = userData.firstname; return user } */ async function listUserConnection(authToken, listID) { var connection = Appacitive.Connection.extend('owns'); let user = await Appacitive.User.getUserByToken(authToken), userID = user.get("__id") console.log(userID) var owner = new connection({ endpoints: [{ objectid: userID, label: "user" }, { objectid: listID, label: "lists" }] }); try { let saveConnection = await owner.save() } catch (err) { console.log(err.message) } } async function getListItems(listObj) { var items = []; var listObject = new Appacitive.Object.extend('lists'); var list = new listObject({__id: listObj.id}); var query = list.getConnectedObjects({ relation: 'contains_items', //mandatory returnEdge: false, label: 'items', //mandatory }); let queryResult = await query.fetch() for (let i = 0; i < queryResult.length; i++) { items[i] = queryResult[i].get("title") } return items } module.exports = { deleteItem: async function (item) { try { let itemObject = Appacitive.Object.extend('items'); itemToDelete = new itemObject({__id: item}) let deleteResult = await itemToDelete.destroy(true); return deleteResult } catch (err) { console.log(err.message) } }, deleteList: async function (list) { try { let itemObject = Appacitive.Object.extend('lists'); listToDelete = new itemObject({__id: list}) let deleteResult = await lsitToDelete.destroy(true); return deleteResult } catch (err) { console.log(err.message) } } }
$(document).ready(function(){ $(".burger").click(function(){ $(".menu_list").css({ "margin-top": "15px", "background-color": "rgb(134,128,135)" }).toggle(); $("li a").css({ "padding-right": "60px", }); }); $(".left_img").mouseenter(function(){ $(".left").css({ "width": "97%", "border-right": "0", "z-index": "2" }); $(".right").css("z-index", "1"); $(".left").css({ "animation-name": "left", "animation-duration": "2s" }); $(".title").css("left", "15vw"); $(".title").css({ "animation-name": "left_title", "animation-duration": "2s" }); $(this).css({ "top": "-18vw", "right": "21vw", "transform": "none" }); $(".right_block, .right_img").hide(1000); $(".left_block").css({ "top": "-18vw", "right": "21vw" }); $(".right_button").css("z-index", "2").show(2000); $(".left_item").show(2000); }); $(".right_img").mouseenter(function(){ $(".right").css({ "width": "97%", "border-left": "0", "z-index": "2" }); $(".left").css("z-index", "1"); $(".right").css({ "animation-name": "right", "animation-duration": "2s" }); $(".right").css("left", "-3.5vw"); $(".title").css("left", "15vw"); $(".title").css({ "animation-name": "right_title", "animation-duration": "2s" }); $(this).css({ "top": "7vw", "right": "23.5vw", "transform": "none" }); $(this).css({ "animation-name": "right_img", "animation-duration": "2s" }); $(".left_block, .left_img").hide(1000); $(".right_block").css({ "top": "7vw", "right": "23.5vw" }); $(".right_block").css({ "animation-name": "right_block", "animation-duration": "2s" }); $(".left_button").css("z-index","2").show(2000); $(".point1").css("animation-name", "right_point1"); $(".point2").css("animation-name", "right_point2"); $(".point3").css("animation-name", "right_point3"); $(".right_item").show(2000); }); $(".right_button").click(function(){ $(this).hide(); $(".right_item").hide(); $(".right").css({ "width": "97%", "border-left": "0", "z-index": "2" }); $(".left").css("z-index", "1"); $(".right").css("left", "-3.5vw"); $(".right_img").hide(); $(".right_img_button").css({ "top": "7vw", "right": "23.5vw", "transform": "none" }).show(); $(".right_block").css({ "top": "7vw", "right": "23.5vw" }).show(); $(".left_button").css("z-index","2").show(2000); $(".point1").css("animation-name", "right_point1"); $(".point2").css("animation-name", "right_point2"); $(".point3").css("animation-name", "right_point3"); $(".right_item").show(2000); }); $(".left_button").click(function(){ $(this).hide(); $(".left_item").hide(); $(".left").css({ "width": "97%", "border-right": "0", "z-index": "2" }); $(".right").css("z-index", "1"); $(".left_img").hide(); $(".left_img_button").css({ "top": "-18vw", "right": "21vw", "transform": "none" }).show(); $(".left_block").css({ "top": "-18vw", "right": "21vw" }).show(); $(".right_button").css("left", "55vw").show(2000); $(".point1").css("animation-name", "left_point1"); $(".point2").css("animation-name", "left_point2"); $(".point3").css("animation-name", "left_point3"); $(".left_item").show(2000); }); $(".mobile_left_item").show(1000); $(".mobile_right_button").click(function(){ $(this).hide(); $(".mobile_left_item").hide(); $(".mobile_right_item").hide(); $(".mobile_right").css("width", "93%"); $(".mobile_left").css("width", "7%"); $(".mobile_left_img").hide(); $(".mobile_right_img").show(); $(".mobile_left_block").hide(); $(".mobile_right_block").show(); $(".mobile_left_button").show(); $(".mobile_point1").css("animation-name", "right_point1"); $(".mobile_point2").css("animation-name", "right_point2"); $(".mobile_point3").css("animation-name", "right_point3"); $(".mobile_right_item").show(1000); }); $(".mobile_left_button").click(function(){ $(this).hide(); $(".mobile_right_item").hide(); $(".mobile_left_item").hide(); $(".mobile_left").css("width", "93%"); $(".mobile_right").css("width", "7%"); $(".mobile_right_img").hide(); $(".mobile_left_img").show(); $(".mobile_right_block").hide(); $(".mobile_left_block").show(); $(".mobile_right_button").show(); $(".mobile_point1").css("animation-name", "left_point1"); $(".mobile_point2").css("animation-name", "left_point2"); $(".mobile_point3").css("animation-name", "left_point3"); $(".mobile_left_item").show(1000); }); });
import { LoadingOutlined } from '@ant-design/icons'; import React, { useEffect, useState } from 'react'; import { useSelector } from 'react-redux'; import { useParams } from 'react-router'; import { toast } from 'react-toastify'; import { getLeague } from '../../../api/league'; import { createTeam, getTeams, removeTeam } from '../../../api/team'; import { CreateTeamForm, TeamCard, UserNav } from '../../../components'; const CreateTeam = (p) => { const { user } = useSelector((state) => ({ ...state })); const { lid } = useParams(); const initialValues = { team_name:'', league:lid, image:'' } const [loading, setLoading] = useState(false); const [league, setleague] = useState('') const [teams, setTeams] = useState('') const [values, setValues] = useState(initialValues); useEffect(() => { loadDetails() }, []) const loadteams = (id) => { getTeams(id) .then(res => { setTeams(res.data) setLoading(false) }) .catch(err => { console.log(err) }) } const loadDetails = () => { setLoading(true) getLeague(lid) .then(res => { setleague(res.data) loadteams(lid) }) .catch(err => { console.log(err) }) } const handleSubmit = (e) => { e.preventDefault(); setLoading(true); createTeam(user.token, values) .then((res) => { setLoading(false); setValues(initialValues); loadDetails() toast.success(`"${res.data.team_name}" is created`); }) .catch((err) => { setLoading(false); toast.error(err.response.data); console.log(err); }); }; const handleRemove = (id) => { if (window.confirm("Delete?")) { removeTeam(user.token, id) .then(res => { toast.success(`"${res.data.team_name}" is deleted`); loadDetails() }) .catch(err => { toast.error('Some error in del plaease try later'); }) } } return ( <div className="container-fluid"> <div className="row"> <div className="col-md-2"> <UserNav /> </div> <div className="col text-center"> <div className='loading'> {loading ? (<LoadingOutlined className="text-info h1" />) : ''} </div> <div className="create-team"> <div className="create-team-top"> <h1>{league.league_name}</h1> </div> <div className="create-team-bottom"> <div className='all-teams' style={{ display: 'flex', justifyContent: 'flex-start', margin: '25px 0' }}> { (teams && teams.length) ? teams.map(each => { return <TeamCard key={each._id} team={each} handleRemove={handleRemove} /> }) : '' } </div> <div className="create-team-new"> <h3>Create new team </h3> <CreateTeamForm handleSubmit={handleSubmit} values={values} setValues={setValues} league={league} /> </div> </div> </div> </div> </div> </div> ); }; export default CreateTeam;
import React from 'react'; import { PropTypes as T } from 'prop-types'; import styled from 'styled-components'; import { getTarget } from '../../../../utils/targets'; import { getArrow } from '../../../../utils/arrows'; import { themeVal } from '../../../../styles/utils/general'; import collecticon from '../../../../styles/collecticons'; import { glsp } from '../../../../styles/utils/theme-values'; import Target from '../../../common/target'; import Heading from '../../../../styles/type/heading'; import { visuallyHidden } from '../../../../styles/helpers'; import Table from '../../../../styles/table'; import { arrayRange } from '../../../../utils/array'; import get from 'lodash.get'; import { round } from '../../../../utils/format'; import Dl from '../../../../styles/type/definition-list'; const Inpage = styled.div` display: grid; grid-gap: ${glsp(2)}; `; const TargetList = styled.ul` display: grid; justify-content: center; grid-gap: ${glsp(2)}; `; const TargetListItem = styled.li` display: grid; grid-gap: ${glsp()}; grid-template-columns: 1fr; align-items: center; `; const TargetHeatmap = styled.div` width: 15rem; `; const TargetStats = styled.div` ${Dl} { grid-row-gap: ${glsp(0.5)}; } `; const ArrowId = styled(Heading)` text-align: center; &::before { ${collecticon('compass-2')} vertical-align: top; margin-right: 0.5rem; font-size: 1rem; } `; const HitTargets = styled.section` h1 { ${visuallyHidden()} } `; const HitBreakdown = styled.section` h1 { ${visuallyHidden()} } tr th:not(:first-child), tr td:not(:first-child) { text-align: right; } tr:last-child { font-weight: ${themeVal('type.base.bold')}; } `; function Analytics (props) { const { config: { rounds, arrows, target }, hits } = props.session; const targetDef = getTarget(target); const arrowDef = getArrow(arrows.type); const getArrowStats = (aIdx) => { const arrowHits = hits.reduce((acc, round) => { return round[aIdx] ? acc + 1 : acc; }, 0); const centroid = hits .reduce( (acc, round) => { const arrow = round[aIdx]; if (!arrow) return acc; const { cx, cy } = arrow; const [x, y] = acc; return [x + cx, y + cy]; }, [0, 0] ) .map((v) => v / arrowHits || 0); const extent = hits.reduce( (acc, round) => { const arrow = round[aIdx]; if (!arrow) return acc; const { cx, cy } = arrow; if (!acc) { return [ [cx, cy], [cx, cy] ]; } const [[xMin, yMin], [xMax, yMax]] = acc; return [ [Math.min(xMin, cx), Math.min(yMin, cy)], [Math.max(xMax, cx), Math.max(yMax, cy)] ]; }, // Init as null so the first is taken into account. null ) || [ [0, 0], [0, 0] ]; const distance = [ Math.abs(extent[0][0] - extent[1][0]), Math.abs(extent[0][1] - extent[1][1]) ]; return { center: centroid.map((v) => round(v)), area: round(((distance[0] / 2) * (distance[1] / 2) * Math.PI) / 100), roundness: round(distance[0] / distance[1]) }; }; return ( <Inpage> <HitTargets> <h1>Targets</h1> <TargetList> {arrows.ids.map((a, aIdx) => { const arrowStats = getArrowStats(aIdx); return ( <TargetListItem key={a}> <ArrowId as='h2' size='large'> {a} </ArrowId> <TargetHeatmap> <Target rings={targetDef.rings} arrow={arrowDef} hits={hits.map((round) => round[aIdx])} /> </TargetHeatmap> <TargetStats> <Dl type='horizontal'> <dt>Group center</dt> <dd> <em>x:</em> {arrowStats.center[0]} <em>y:</em>{' '} {arrowStats.center[1]} </dd> <dt>Group area</dt> <dd> {arrowStats.area || 0} cm<sup>2</sup> </dd> <dt>Group roundness</dt> <dd>{arrowStats.roundness || 0}</dd> </Dl> </TargetStats> </TargetListItem> ); })} </TargetList> </HitTargets> <HitBreakdown> <h1>Breakdown</h1> <Table> <thead> <tr> <th>#</th> {arrows.ids.map((a) => ( <th key={a}>{a}</th> ))} </tr> </thead> <tbody> { // There are as many rows as rounds defined in the settings. // We have to create a range because the results array will be // filled as it is scored. arrayRange(1, rounds).map((s, sIdx) => { return ( <tr key={s}> <td>{s}</td> {arrows.ids.map((a, aIdx) => { const arrowHit = get(hits, [sIdx, aIdx, 'value'], ''); return <td key={`${s}-${a}`}>{arrowHit}</td>; })} </tr> ); }) } <tr> <td>Total</td> {arrows.ids.map((a, aIdx) => { const sum = hits.reduce((acc, round) => { return acc + get(round, [aIdx, 'value'], 0); }, 0); return <td key={a}>{sum}</td>; })} </tr> </tbody> </Table> </HitBreakdown> </Inpage> ); } Analytics.propTypes = { session: T.object }; export default Analytics; // Group Center is the statistical center of the shot group. The first number is the X-coordinate center, the second number if the Y-coordinate center. Both numbers are in millimeters. // Group Area is the size of the statistical representation of the shot group. It is also the size of the shot group ellipse. This is measured in millimeters squared. // Group Roundness is a unit-less metric measuring how round the shot group is. A shot group with roundness 1.00 is perfectly round. A roundness value greater than 1 is more elongated along the X-axis, less then 1 the group is more elongated along the Y-axis. Groups with a roundness between .75 and 1.50 may generally be considered round.
import React from "react"; import MessageType from "../uitils/MessageTypeUtils"; const AlertMessage = ({ message, messageType }) => { const alertClassTypes = messageType === MessageType.SUCCESS ? " alert-success" : " alert-danger"; const alertClasses = `alert ${alertClassTypes} alert-dismissible fade show`; return ( <div className="row"> <div className={alertClasses}> <strong>{messageType}!</strong> {message}. <button type="button" className="btn-close" data-bs-dismiss="alert" aria-label="Close" ></button> </div> </div> ); }; export default AlertMessage;
/** * TODO * Maybe add an implementation for a real hardware joystick, like: https://www.play-zone.ch/en/ps2-daumen-joystick-mit-select-button-breakout-board.html */ const J5 = require('johnny-five'); class Joypad { constructor({ wsConnection, pins, player }) { this.wsConnection = wsConnection; this.pins = pins; this.player = player; this.connectPins(); } connectPins() { const buttons = ['up', 'bottom', 'left', 'right', 'fire']; buttons.forEach((b) => { new J5.Button({ pin: this.pins[b] }) .on('down', this.sendInput.bind(this, b, 'down')) .on('up', this.sendInput.bind(this, b, 'up')); }); } sendInput(command, type) { this.wsConnection.send(JSON.stringify({ player: this.player, command, type })); } }; module.exports.Joypad = Joypad;
//make the NYC station list selectable $( document ).ready(function() { var available_NYCTraffic={ 1:"#1 - 11th ave n ganservoort - 12th ave @ 40th st", 2:"#2 - 11th ave s ganservoort - west st @ spring st", 3:"#3 - 12th ave @ 45th - 11 ave ganservoort st", 4:"#4 - 12th Ave N 40th - 57th St", 106:"#106 - 12th Ave S 57th St - 45th St", 107:"#107 - 278 E BRUNSWICK AVENUE - SIE E SOUTH AVENUE", 108:"#108 - 278 E BRUNSWICK AVENUE - WSE S SOUTH AVENUE", 110:"#110 - 440 N FRANCIS STREET - WSE N TYRELLAN AVE", 119:"#119 - BBT E Manhattan Portal - Toll Plaza", 122:"#122 - BBT Manhattan Portal inbound - West St N Watts St", 123:"#123 - BBT Manhattan Portal inbound - West St S Battery Place", 124:"#124 - BBT W Toll Plaza - Manhattan Portal", 129:"#129 - BE N STRATFORD AVENUE - CASTLE HILL AVE", 137:"#137 - BE S CASTLE HILL AVENUE - STRATFORD AVENUE", 140:"#140 - BE S TBB EXIT RAMP - MANHATTAN LIFT SPAN", 141:"#141 - BE S TBB EXIT RAMP - QUEENS ANCHORAGE", 145:"#145 - BKN Bridge Manhattan Side - FDR N Catherine Slip", 148:"#148 - BQE N ATLANTIC AVENUE - LEONARD STREET", 149:"#149 - BQE N Atlantic Ave - BKN Bridge Manhattan Side", 150:"#150 - BQE N Atlantic Ave - MAN Bridge Manhattan Side", 153:"#153 - BQE N LEONARD STREET - 46TH STREET", 154:"#154 - BQE S - GOW S ALTANTIC AVENUE - 9TH STREET", 155:"#155 - BQE S 46TH STREET - LEONARD STREET", 157:"#157 - BQE S LEONARD STREET - ATLANTIC AVENUE", 159:"#159 - BRP N WATSON AVENUE - FORDHAM ROAD ", 160:"#160 - BRP S FORDHAM ROAD - WATSON AVENUE", 164:"#164 - BWB N Queens Anchorage - Toll Plaza ", 165:"#165 - BWB N Toll Plaza - HRP N Lafayatte Ave", 167:"#167 - BWB S Queens Anchorage - WSE S Exit 14 (Linden Pl)", 168:"#168 - BWB S Toll Plaza - Queens Anchorage", 169:"#169 - Belt Pkwy E 182nd St - Laurelton Pkwy N @ SSP", 170:"#170 - Belt Pkwy W 182nd St - JFK Expressway", 171:"#171 - Belt Pkwy W JFK Expressway - VWE N Jamaica Ave", 172:"#172 - CBE AMSTERDAM AVE (L/LVL) - MORRIS AVE", 177:"#177 - CBE E AMSTERDAM AVE(U/LVL) - MORRIS AVE", 178:"#178 - CBE E CASTLE HILL AVE - BE N WATERBURY AVE", 184:"#184 - CBE E TAYLOR AVENUE - CASTLE HILL AVENUE", 185:"#185 - CBE W CASTLE HILL AVENUE - TAYLOR AVENUE", 186:"#186 - CBE W L/LE V AMSTERDAM AVE - I 95 S LOC LNS", 190:"#190 - CBE W MORRIS AVE - GWB W AMSTERDAM AVE (L/LVL)", 191:"#191 - CBE W MORRIS AVE - GWB W AMSTERDAM AVE (U/LVL)", 195:"#195 - CBE W U/LEV AMSTERDAM AVE - I95 S EXP LNS", 199:"#199 - CIP N Hempstead Tpk - LIE", 204:"#204 - CIP N TNB - Whitestone Expwy S Exit 14 (Linden Pl)", 205:"#205 - CIP NB GCP - TNB", 207:"#207 - CIP S Hempstead Tpk - Laurelton Pkwy @ SSP", 208:"#208 - CIP S LIE - Hempstead Tpk", 211:"#211 - CVE NB GCP - WILLETS PT BLVD", 212:"#212 - CVE NB LIE - WILLETS PT BLVD", 213:"#213 - FDR N - TBB E 116TH STREET - MANHATTAN TRUSS", 215:"#215 - FDR N 25th - 63rd St", 217:"#217 - FDR N Catherine Slip - 25th St", 221:"#221 - FDR S 25th St - Catherine Slip", 222:"#222 - FDR S 63rd - 25th St", 223:"#223 - FDR S Catherine Slip - BKN Bridge Manhattan Side", 224:"#224 - FDR S Catherine Slip - Whitehall St", 225:"#225 - FDR S Whitehall St - BBT Manhattan Portal outbound", 257:"#257 - GOW N 7TH AVENUE - 9TH STREET", 258:"#258 - GOW N 92ND STREET - 7TH AVENUE", 259:"#259 - GOW N 9TH STREET - ATLANTIC AVENUE", 261:"#261 - GOW S 7TH AVENUE - 92ND STREET", 262:"#262 - GOW S 9TH STREET - 7TH AVENUE", 263:"#263 - GOW S VNB W 92ND STREET - BKLYN GANTRY LOWER LEVEL", 264:"#264 - GOW S VNB W 92ND STREET - BKLYN GANTRY UPPER LEVEL", 265:"#265 - GWB E LOWER LEVEL PLAZA - CBE E LOWER LEVEL AMSTERDAM AVE", 295:"#295 - HRP N LAFAYETTE AVENUE - E TREMONT AVENUE", 298:"#298 - HRP S Lafayette Ave - BWB S Toll Plaza", 311:"#311 - LIE E 84TH ST - 108TH ST", 313:"#313 - LIE E QMT TOLL PLAZA - 84TH ST", 315:"#315 - LIE W 108TH ST - 84TH ST", 316:"#316 - LIE W 84TH ST - QMT TOLL PLAZA", 318:"#318 - LIE WB LITTLE NECK PKWY - NB CIP", 319:"#319 - LIE WB LITTLE NECK PKWY - NB CVE", 324:"#324 - LINCOLN TUNNEL E CENTER TUBE NJ - NY", 325:"#325 - LINCOLN TUNNEL E SOUTH TUBE - NJ - NY", 329:"#329 - LINCOLN TUNNEL W CENTER TUBE NY - NJ", 330:"#330 - LINCOLN TUNNEL W NORTH TUBE NY - NJ", 331:"#331 - Laurelton Pkwy N @ SSP - CIP N Hempstead Tpk", 332:"#332 - Laurelton Pkwy S @ SSP - Belt Pkwy W 182nd St", 339:"#339 - MDE N VAN CORTLAND PARK - NYST N EXIT 1 (MP.48)", 344:"#344 - MDE S HARLEM RIVER PARK - GWB W AMSTERDAM AVENUE LOWER LEVEL", 345:"#345 - MDE S HARLEM RIVER PARK - GWB W AMSTERDAM AVENUE UPPER LEVEL", 347:"#347 - MDE S TBB EXIT RAMP - QUEENS ANCHORAGE", 349:"#349 - MLK N WALKER STREET - NJ ROUTE 169", 350:"#350 - MLK S - SIE E WALKER STREET - WOOLEY AVENUE", 351:"#351 - MLK S - SIE W WALKER STREET - RICHMOND AVENUE", 364:"#364 - QMT E Manhattan Side - Toll Plaza", 365:"#365 - QMT W Toll Plaza - Manhattan Side", 369:"#369 - ROUTE 169 S - MLK WALKER STREET", 375:"#375 - SIE E BRADLEY AVENUE - CLOVE ROAD", 376:"#376 - SIE E CLOVE ROAD - FINGERBOARD ROAD", 377:"#377 - SIE E RICHMOND AVENUE - WOOLEY AVENUE", 378:"#378 - SIE E SOUTH AVENUE - RICHMOND AVENUE", 379:"#379 - SIE E VNB E FINGERBOARD ROAD - SI GANTRY LOWER LEVEL", 380:"#380 - SIE E VNB E FINGERBOARD ROAD - SI GANTRY UPPER LEVEL", 381:"#381 - SIE E WOOLEY AVENUE - BRADLEY AVENUE", 382:"#382 - SIE E-MLK N RICHMOND AVENUE - WALKER STREET", 383:"#383 - SIE W - MLK N WOOLEY AVENUE - WLAKER STREET", 384:"#384 - SIE W - WSE S SOUTH AVENUE - SOUTH AVENUE", 385:"#385 - SIE W BRADLEY AVENUE - WOOLEY AVENUE", 387:"#387 - SIE W FINGERBOARD ROAD - CLOVE ROAD", 388:"#388 - SIE W RICHMOND AVENUE - SOUTH AVENUE", 389:"#389 - SIE W SOUTH AVENUE - 278 W BRUNSWICK AVENUE", 390:"#390 - SIE W WOOLEY AVENUE - RICHMOND AVENUE", 394:"#394 - TBB N QUEENS ANCHORAGE - BE N", 395:"#395 - TBB N QUEENS ANCHORAGE - MANHATTAN LIFT SPAN", 398:"#398 - TBB S MANHATTAN LIFT SPAN - QUEENS ANCHORAGE", 399:"#399 - TBB W - FDR S MANHATTAN TRUSS - E116TH STREET", 402:"#402 - TNB N Queens Anchorage - Toll Plaza", 405:"#405 - TNB S Qns Anchorage - CIP S @ TNB", 406:"#406 - TNB S Toll Plaza - Queens Anchorage", 410:"#410 - VNB E SI GANTRY LOWER LEVEL - BROOLKYN GANTRY LOWER LEVEL", 411:"#411 - VNB E SI GANTRY UPPER LEVEL - BROOKLYN GANTRY UPPER LEVEL", 412:"#412 - VNB E-GOWANUS N BROOKLYN GANTRY LOWER LEVEL - 92ND STREET", 413:"#413 - VNB E-GOWANUS N BROOKLYN GANTRY UPPER LEVEL - 92ND STREET", 416:"#416 - VNB W BROOKLYN GANTRY LOWER LEVEL - SI GANTRY LOWER LEVEL", 417:"#417 - VNB W BROOKLYN GANTRY UPPER LEVEL - SI GANTRY UPPER LEVEL", 418:"#418 - VNB W-SIE W SI GANTRY LOWER LEVEL - FINGERBOARD ROAD", 419:"#419 - VNB W-SIE W SI GANTRY UPPER LEVEL - FINGERBOARD ROAD", 422:"#422 - VWE N MP4.63 (Exit 6 - Jamaica Ave) - MP6.39 (Exit 11 Jewel Ave)", 423:"#423 - VWE N MP6.39 (Exit 11 Jewel Ave) - MP8.65 (Exit 13 Northern Blvd)", 424:"#424 - VWE N MP8.64 (Exit 13 Northern Blvd) - Whitestone Expwy Exit 14 (Linden Pl)", 425:"#425 - VWE S MP2.66 (Exit 2 Rockaway Blvd) - Belt Pkwy E 182nd St", 426:"#426 - VWE S MP4.63 (Exit 6 Jamaica Ave) - MP2.66 (Exit 2 Roackaway Blvd)", 427:"#427 - VWE S MP6.39 (Exit 11 Jewel Ave) - MP4.63 (Exit 6 Jamaica Ave)", 428:"#428 - VWE S MP8.65 (Exit 13 Northern Blvd) - MP6.39 (Exit 11 Jewel Ave)", 430:"#430 - WSE N ARDEN AVENUE - VICTORY BLVD", 431:"#431 - WSE N BLOOMUINGDALE ROAD - ARDEN AVENUE", 432:"#432 - WSE N SOUTH AVENUE - 278 W BRUNSWICK AVENUE", 433:"#433 - WSE N TYRELLAN AVENUE - BLOOMINGDALE ROAD", 434:"#434 - WSE N VICTORY BLVD - SOUTH AVENUE", 435:"#435 - WSE N-SIE E SOUTH AVENUE - SOUTH AVENUE", 436:"#436 - WSE S ARDEN AVENUE - BLOOMINGDALE ROAD", 437:"#437 - WSE S BLLOMINGDALE ROAD - TYRELLAN AVENUE", 439:"#439 - WSE S SOUTH AVENUE - VICTORY BOULEVARD", 440:"#440 - WSE S TYRELLAN AVENUE - 440 S FRANCIS STREET", 441:"#441 - WSE S VICTORY BOULEVARD - ARDEN AVENUE", 442:"#442 - West St N Whitehall - Watts St", 443:"#443 - West St S Battery Pl - BKN Bridge Manhattan Side", 444:"#444 - West St S Battery Pl - FDR N Catherine Slip", 445:"#445 - West St S Spring St - BBT Manhattan Portal outbound", 446:"#446 - West St S Spring St - Battery Pl", 447:"#447 - West St Watts St - 11th Ave Ganesvoort", 448:"#448 - Westside Hwy N 57th St - GWB", 450:"#450 - Westside Hwy S GWB - 57th St", 451:"#451 - Whitestone Expwy N Exit 14 (Linden Pl) - BWB N Queens Anchorage", 453:"#453 - Whitestone Expwy S Exit 14 (Linden Pl) - VWE S MP8.65 (Exit 13 Northern Blvd)", 206:"#206 - CIP N LIE ramp - TNB", 354:"#354 - I-87 NYST S Exit 1 - MDE S Van Cortlandt Park", 202:"#202 - CIP N ramp to TNB - TNB Queens Anchorage", 142:"#142 - BE S Griswold - Castle Hill Avenue", 126:"#126 - BE N Castle Hill Avenue - Griswold Ave", 338:"#338 - MDE N RFK Bridge - 142nd St" }; for (var id in available_NYCTraffic){//for each available section //make an option in the module list if (available_NYCTraffic.hasOwnProperty(id)){ var listItem = document.createElement("li"); listItem.innerHTML = available_NYCTraffic[id]; listItem.value = id; $('#ul_NYCTraffic_station').append(listItem); $('#ul_NYCTraffic_station>li:last-child').addClass("ui-widget-content"); if ($('#ul_NYCTraffic_station>li').length==1)$('#ul_NYCTraffic_station>li:last-child').addClass("list_firstelement"); } } var selected_NYCTraffic=[]; $(function() { $( "#ul_NYCTraffic_station" ).selectable({ stop: function() { selected_NYCTraffic.length = 0;//clear the array $( ".ui-selected", this ).each(function() { selected_NYCTraffic.push(this.value ); }); } }); }); $(".input").on("click", '.btn_NYCTrafficload',function(){ if (selected_NYCTraffic.length > 0){ var sourceLbl = document.createElement("div"); sourceLbl.innerHTML = "<label>NYC Real-time Traffic Speed</label>"; $('#input_channels').append(sourceLbl); $('#input_channels>div:last-child').addClass("input_source changeWithPanel NYCtraffic_input loaded_channel"); var sourceUl = document.createElement("ul"); $('#input_channels').append(sourceUl); selected_NYCTraffic.every(function(element,index,array){//for each selected station inputData["NYCTraffic_"+element]=[]; var listItem = document.createElement("li"); var channelnm = $( "#ul_NYCTraffic_station li[value='"+element+"']" ).text(); listItem.innerHTML = " <div>"+ " <a class='channel_title'>"+channelnm+"</a>"+ " <button class='channel_delete' type='button'> - delete </button>"+ " <button class='channel_timestamp' type='button' title='set the input as a time-stamp'><span class='fa fa-clock-o'></span></button>"+ " <label class='channel_origin'>NYC_Traffic</label>"+ " <label class='channel_parameter NYCstationid'>" + element + "</label>" + " </div>"; $('#input_channels>ul:last-child').append(listItem); $('#input_channels>ul:last-child>li:last-child').addClass("NYCTraffic_channel active"); $('#input_channels>ul:last-child>li:last-child .channel_origin').hide(); $('#input_channels>ul:last-child>li:last-child .channel_parameter').hide(); InputNms["NYCTraffic_"+element]="rt";//the real-time input data return true; }); $('.input').removeClass('active'); $('.input').find('.panel_title').addClass('active'); $('.input').find('.vertical_bar').addClass('active'); $('.input').find('#lbl_inputchannels').text("Available Data:"); $('#div_addChoice').slideUp(); $('#input_modules').slideUp(); } }); }); function rt_fetchNYC(){ var output; var http = new XMLHttpRequest(); http.open("GET", "http://207.251.86.229/nyc-links-cams/LinkSpeedQuery.txt", true); http.onreadystatechange = function(){ if(http.readyState == 4){ if(http.status==200){ output = "Bad JSON: "+http.responseText; output = http.responseText.match(/\w+|"[^"]+"/g); var org_output=[]; var org_row = []; var org_id; output.every(function(element,index,array){ if (index%13==0){ if (org_row.length>0) org_output[org_id]=org_row; org_row = []; org_id = "NYCTraffic_"+element.slice(1,element.length-1); }else{ org_row.push(element); } return true; }); fetched_NYC = org_output; for (var key in inputData){ if (key.includes("NYCTraffic")){ var cv = fetched_NYC[key][0]; cv = cv.slice(1,cv.length-1); inputData[key]=Number(cv); } } }else{ output = "Error "+http.status; } } } http.send(); }
const NotificationActionTypes = { NOTIFICATION_HIDDEN: "NOTIFICATION_HIDDEN", ALL_REQUEST_SUCCESS: "ALL_REQUEST_SUCCESS" }; export default NotificationActionTypes;
///TODO: REVIEW /** * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ var rotate = function(matrix) { if(!matrix || matrix.length === 1) return; var n = matrix.length; for (var i = 0; i <= n/2; i++) { for (var j = i; j < n-1-i; j++) { var temp = matrix[i][j]; matrix[i][j] = matrix[n-j-1][i]; matrix[n-j-1][i] = matrix[n-i-1][n-j-1]; matrix[n-i-1][n-j-1] = matrix[j][n-i-1]; matrix[j][n-i-1] = temp; } } console.log(matrix); }; var a = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ]; rotate(a);
export const LOAD_CEREMONY_DETAILS = 'my-project/ceremony/LOAD_CEREMONY_DETAILS'; export const LOAD_CEREMONY_DETAILS_SUCCESS = 'my-project/ceremony/LOAD_CEREMONY_DETAILS_SUCCESS'; export const LOAD_CEREMONY_DETAILS_FAILURE = 'my-project/ceremony/LOAD_CEREMONY_DETAILS_FAILURE'; export const LOAD_SIMILAR_CEREMONIES = 'my-project/ceremony/LOAD_SIMILAR_CEREMONIES'; export const LOAD_SIMILAR_CEREMONIES_SUCCESS = 'my-project/ceremony/LOAD_SIMILAR_CEREMONIES_SUCCESS'; export const LOAD_SIMILAR_CEREMONIES_FAILURE = 'my-project/ceremony/LOAD_SIMILAR_CEREMONIES_FAILURE'; export const LOAD_ALL_VENDORS = 'my-project/ceremony/LOAD_ALL_VENDORS'; export const LOAD_ALL_VENDORS_SUCCESS = 'my-project/ceremony/LOAD_ALL_VENDORS_SUCCESS'; export const LOAD_ALL_VENDORS_FAILURE = 'my-project/ceremony/LOAD_ALL_VENDORS_FAILURE'; export const CLEAR_CEREMONY_DETAILS = 'my-project/ceremony/CLEAR_CEREMONY_DETAILS'; export const UPDATE_CATEGORY_ORDER = 'my-project/ceremony/UPDATE_CATEGORY_ORDER';
(function(){ var app = angular.module('openmuc'); app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider. state('home', { url: "/", templateUrl: '/openmuc/html/sessions/new.html', controller: 'LoginController', requireLogin: false, }). state('dashboard', { url: "/dashboard", templateUrl: "/openmuc/html/dashboard/index.html", controller: 'DashboardController', requireLogin: true, resolve: { openmuc: ['AppsDependenciesService', function (AppsDependenciesService) { return AppsDependenciesService.loadDependencies(); }] } }) }]); app.run(['$rootScope', '$alert', '$state', 'AuthService', function ($rootScope, $alert, $state, AuthService) { $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){ if (toState.requireLogin && !AuthService.isLoggedIn()){ $alert({content: 'You need to be authenticated to see this page!', type: 'warning'}); AuthService.redirectToLogin(); event.preventDefault(); } }); }]); })();
import React, { Component } from "react"; import { withRouter } from "react-router-dom"; import { connect } from "react-redux"; import ReactDOM from "react-dom"; // Actions import * as actionCreators from "../store/actions"; //Components import PostMessageForm from "./PostMessageForm"; import Loading from "../components/Loading"; class Messages extends Component { timer = null; state = { timestamp: "" }; async componentDidMount() { let channelID = this.props.match.params.channelID; await this.props.fetchMessageList(channelID); this.fetchMessages(); this.props.getChannelByID(channelID); this.scrollToBottom(); } componentWillUnmount() { if (this.timer) { clearInterval(this.timer); } } componentDidUpdate(prevState) { let channelID = this.props.match.params.channelID; if ( prevState.match.params.channelID !== this.props.match.params.channelID && this.props.message_list.length !== 0 ) { clearInterval(this.timer); this.props.fetchMessageList(channelID); this.fetchMessages(); this.props.getChannelByID(channelID); } this.scrollToBottom(); } scrollToBottom = () => { if (this.messagesEnd) { this.messagesEnd.scrollIntoView({ behavior: "smooth" }); } }; fetchMessages = () => { if (this.props.message_list.length !== 0) { clearInterval(this.timer); this.timer = setInterval(() => { let last_message = this.props.message_list[ this.props.message_list.length - 1 ]; this.props.fetchMessageWithTiemstamp( this.props.match.params.channelID, last_message.timestamp ); }, 3000); //get data and rerender the component every 3s } }; getTime = message => { return message.timestamp.slice(11, 16); }; getDate = (message, lastMessage) => { const current_msg_year = message.timestamp.slice(0, 4); const current_msg_month = message.timestamp.slice(5, 7); const current_msg_day = message.timestamp.slice(8, 10); const last_msg_year = lastMessage.timestamp.slice(0, 4); const last_msg_month = lastMessage.timestamp.slice(5, 7); const last_msg_day = lastMessage.timestamp.slice(8, 10); if ( !+current_msg_year >= +last_msg_year || +current_msg_month >= +last_msg_month || +current_msg_day !== +last_msg_day ) { return ( <p style={{ textAlign: "center" }}> {current_msg_year}-{current_msg_month}-{current_msg_day} </p> ); } return <p>{""}</p>; }; render() { const message_list = this.props.message_list; const channelID = this.props.match.params.channelID; const listOfMessages = message_list.map(message => { return ( <div> {this.props.user.username === message.username ? ( <div> {this.getDate(message, this.props.lastMessage)} <li className="sent"> <p> <span className="sent_username" style={{ color: "#95a5a6" }}> > {message.username} </span> <br /> <span className="sent_msg" style={{ fontWeight: "bold" }}> {message.message} </span> <br /> <span className="sent_time float-right" style={{ fontSize: "9px" }} > {this.getTime(message)} </span> <br /> </p> </li> </div> ) : ( <div> <li className="replies text-secondary"> <p className=""> <span className="replies_username float-left" style={{ color: "#95a5a6" }} > > {message.username} </span> <br /> <span className="replies_msg float-left" style={{ fontWeight: "bold" }} > {message.message} </span> <br /> <span className="replies_time float-right" style={{ fontSize: "9px" }} > {this.getTime(message)} </span> <br /> </p> </li> </div> )} </div> ); }); if (this.props.msg_loading) { return <Loading />; } else { return ( // <div className="messages float-left w-100"> // tries to show latest messages ... // bottom_aligner <div className="messages w-100" style={{ // display: "table", // display: "table-cell", // "vertical-align": "bottom", scrollPaddingBottom: "0px" }} > <ul>{listOfMessages}</ul> <div style={{ float: "left", clear: "both" }} ref={el => { this.messagesEnd = el; }} > {""} </div> <PostMessageForm channelID={channelID} /> </div> ); } } } const mapStateToProps = state => { return { message_list: state.filteredMessages.filteredMessages, user: state.auth.user, message: state.message, channels: state.channels, channel: state.channel, msg_loading: state.messages.msg_loading, lastMessage: state.message.lastMessage, lastYear: state.message.lastYear, lastMonth: state.message.lastMonth, lastDay: state.message.lastDay }; }; const mapDispatchToProps = dispatch => { return { fetchMessageList: (channelID, timestamp) => dispatch(actionCreators.fetchMessageList(channelID, timestamp)), fetchMessageWithTiemstamp: (channelID, timestamp) => dispatch( actionCreators.fetchMessageListWithTimestamp(channelID, timestamp) ), getChannelByID: (channelID, channels) => dispatch(actionCreators.getChannelByID(channelID, channels)) }; }; export default withRouter( connect( mapStateToProps, mapDispatchToProps )(Messages) );
$('.b-slider-main-photo').slick({ infinite: true, speed: 500, fade: true, cssEase: 'linear', arrow: true, prevArrow: '.arrows-left-1', nextArrow: '.arrows-right-1', responsive: [{ breakpoint: 1275, settings: { dots: true } }, { breakpoint: 790, settings: { dots: true } } ] }); let btnRight = document.querySelector(".arrows-right-1"); let i = 0; let pl = document.querySelectorAll(".slide-choose-next-photo-points li"); let btnLeft = document.querySelector(".arrows-left-1"); btnRight.addEventListener("click", function() { if (i < 3) { pl[i].classList.remove("points-active"); pl[i].classList.add("points-simple-point"); pl[i + 1].classList.add("points-active"); pl[i + 1].classList.remove("points-simple-point"); i++; } else { pl[i].classList.remove("points-active"); pl[i].classList.add("points-simple-point"); pl[0].classList.add("points-active"); pl[0].classList.remove("points-simple-point"); i = 0; } }) btnLeft.addEventListener("click", function() { if (i > 0) { pl[i - 1].classList.add("points-active"); pl[i - 1].classList.remove("points-simple-point"); pl[i].classList.remove("points-active"); pl[i].classList.add("points-simple-point"); i--; } else { i = 3; pl[0].classList.add("points-simple-point"); pl[0].classList.remove("points-active"); pl[i].classList.remove("points-simple-point"); pl[i].classList.add("points-active"); } })
// @flow import { curry2, curry3, curry5 } from "./utils"; type ParseResult<A> = { parsed: A, remaining: string } | null; type Parser<A> = string => ParseResult<A>; const numerals = new Set([ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]); function number(str: string) : ParseResult<number> { let i = 0, found = ""; while(numerals.has(str[i])) { found = found.concat(str[i]); i++; }; if (!found.length) return null; return { parsed: parseInt(found), remaining: str.slice(found.length) }; } console.log(number("123")); console.log(number("123abc")); console.log(number(" 123")); function string(sought: string) : Parser<string> { return input => { if (!input.startsWith(sought)) return null; return { parsed: sought, remaining: input.slice(sought.length) }; }; }; console.log(string("a")("abc")); console.log(string("abc")("abc")); console.log(string("bc")("abc")); function numberDashNumber(str: string) : ParseResult<[number, number]> { const first = number(str); if (!first) return null; const second = string("-")(first.remaining); if (!second) return null; const third = number(first.remaining); if (!third) return null; return { parsed: [first.parsed, third.parsed], remaining: third.remaining }; } console.log(numberDashNumber("1-23")); function map<A, B>(fn: A => B, a: Parser<A>) : Parser<B> { return str => { const parseResult = a(str); if (parseResult === null) return null; return { parsed: fn(parseResult.parsed), remaining: parseResult.remaining }; } }; function ap<A, B>(fnParser: Parser<A => B>, aParser: Parser<A>) : Parser<B> { return str => { const firstParse = fnParser(str); if (firstParse === null) return null; const secondParse = aParser(firstParse.remaining); if (secondParse === null) return null; return { parsed: firstParse.parsed(secondParse.parsed), remaining: secondParse.remaining }; }; } function pure<A>(a: A) : Parser<A> { return str => ({ parsed: a, remaining: str }); } function collectNumbers(n1: number, dash: string, n2: number) { return [n1, n2]; } function liftA3<A, B, C, R>( fn: (A, B) => R, p1: Parser<A>, p2: Parser<B>, p3: Parser<C>) : Parser<R> { return ap(ap(ap(pure(curry3(fn)), p1), p2), p3); } const numberDashNumberAgain = liftA3( curry3(collectNumbers), number, string("-"), number); console.log(numberDashNumberAgain("1-23"));
function Socket(paramPosX, paramPosY, figure) { this.x = paramPosX; this.y = paramPosY; this.figure = figure; } Socket.prototype.draw = function () { ctx.strokeStyle = strokeSocketColor; this.figure.draw(this.x, this.y, true); } Socket.prototype.checkIfFigureIsInside = function (fig) { if (fig === this.figure) { if (this.x < fig.x + socketDifficulty && this.x > fig.x - (socketDifficulty * 2) && this.y < fig.y + socketDifficulty && this.y > fig.y - (socketDifficulty * 2)) { fig.draw(this.x, this.y, false); clearBackground(); drawContext(); drawFigures(); fig.done = true; click2.load(); click2.play(); checkGameEnded(); } } };
// Config Variables var colorchange = 5; var colorstop = 1; var clear = 2.5; var flashstart = 0.2; // Declare Variables var colordif = (colorchange-colorstop) var realtime; //Current time var realtimedisplay; //Current time display var json; //JSON Array var targettime; //Target Time var remainingtime; //Time String var events; //Event String var notes; //Notes String var color; //Timer Color var reltime; //Second between target and now var bgcolor; //Background Color //Function resize function resize(){ var textheight = (document.getElementById('clockdiv').offsetWidth)/10; clocktable.style.fontSize = (textheight) + 'px'; clock.style.height = (textheight*1.1) + 'px'; } //Start of loop setInterval(function(){ //Read JSON $.ajax({ 'async': false, 'global': false, 'url': 'json.json?'+(Math.random()), 'dataType': "json", 'success': function (data) { json = data; } }); //Clock realtime=new Date(); realtimedisplay=(("0"+(realtime.getHours()%12 || 12)).substr(-2))+':'+("0"+realtime.getMinutes()).substr(-2)+':'+("0"+realtime.getSeconds()).substr(-2); //If Countdown if (json.task=='countdown') { targettime = json.remainingtime remainingtime = new Date(targettime-realtime+(realtime.getTimezoneOffset()*60000)); reltime = Math.floor(((new Date(targettime-realtime).getTime())+(clear*60000))/1000); color = ((((new Date(targettime-realtime)).getTime())/500)); color = Math.floor((color/colordif)-(colorstop*30)); if (color > 120) { color = 120 } if (color < 1) { color = 0 } if (targettime < realtime) { remainingtime = '00:00:00' } else { remainingtime = '00:'+("0"+remainingtime.getMinutes()).substr(-2)+':'+("0"+remainingtime.getSeconds()).substr(-2) } color = 'hsl('+color+',100%,50%)'; bgcolor = 'hsl(0,100%,0%)'; notes = json.notes; events = json.events; if (reltime < ((flashstart*60)+(clear*60))) { if(reltime & 1) { color = 'hsl(0,0%,0%)'; bgcolor = 'hsl(0,100%,50%)'; } else { color = 'hsl(0,100%,50%)'; bgcolor = 'hsl(0,100%,0%)'; } } if (reltime < (clear*60)) { color = 'hsl(0,100%,50%)'; bgcolor = 'hsl(0,100%,0%)'; } if (reltime < 1) { json.task = 'clear' } } //If Clear if (json.task=='clear') { remainingtime = '00:00:00'; notes = ''; events = ''; color = 'hsl(0,0%,50%)'; bgcolor = 'hsl(0,100%,0%)'; } //If Display if (json.task=='display') { remainingtime = '00:00:00'; notes = json.notes; events = json.events; color = 'hsl(0,0%,50%)'; bgcolor = 'hsl(0,100%,0%)'; } //Build Display timer.style.color = (color); home.style.backgroundColor = (bgcolor); clockdiv.style.backgroundColor = (bgcolor); document.getElementById('clock').innerHTML=realtimedisplay; document.getElementById('timer').innerHTML=remainingtime; document.getElementById('eventnotes').innerHTML=events+'<br />'+notes; {resize()} },1000);
module.exports = { url: 'https://devmountain-qa.github.io/weatherman/build/index.html', elements: { searchBar: '.enter-location__input', submitBtn: { selector: '//button', locateStrategy: 'xpath' }, resultCity:{ selector: '//h3[@class="current-weather__location"]', locateStrategy: 'xpath' }, } }
import test from 'tape' import filterMap from '../../../signals/processes/filterMap' import { spy } from 'sinon' import equals from 'ramda/src/equals' test('filterMap', (assert) => { const signal = spy() const next = spy() filterMap(equals(1))(signal)(next) const handler = signal.getCall(0).args[0] handler(1) handler(2) assert.equal(next.getCall(0).args[0], true) assert.ok(!next.getCall(1)) assert.end() })
// creating link to public remote communications const remote = require('electron').remote; const main = remote.require('./main.js'); module.exports = { generate: function(text) { var result = main.generateERD(text); } }
(function() { 'use strict'; angular .module('webHipsterApp') .controller('LivroDetailController', LivroDetailController); LivroDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'previousState', 'entity', 'Livro', 'Editora']; function LivroDetailController($scope, $rootScope, $stateParams, previousState, entity, Livro, Editora) { var vm = this; vm.livro = entity; vm.previousState = previousState.name; var unsubscribe = $rootScope.$on('webHipsterApp:livroUpdate', function(event, result) { vm.livro = result; }); $scope.$on('$destroy', unsubscribe); } })();
/** * * BitReaderLSB.js * * copyright 2003,2013 Kevin Lindsey * */ /** * BitReaderLSB * * @param {Array<Byte>} data * @returns {BitReaderLSB} */ function BitReaderLSB(data) { this.data = data; this.index = 0; this.mask = 0x01; this.currentByte = null; } /** * readBit * * @returns {Boolean} */ BitReaderLSB.prototype.readBit = function() { var result = null; if ( this.mask === 0x01 ) { if ( this.index < this.data.length ) { this.currentByte = this.data[this.index++]; } } if ( this.currentByte !== null ) { result = this.currentByte & this.mask; this.mask <<= 1; if ( this.mask === 0x100 ) { this.mask = 0x01; this.currentByte = null; } } if ( result !== null ) { result = (result === 0) ? 0 : 1; } return result; }; /** * readBits * * @param {Integer} bitCount * @returns {Byte} */ BitReaderLSB.prototype.readBits = function(bitCount) { var end = 1 << bitCount; var result = 0; for ( var mask = 1; mask !== end; mask <<= 1 ) { if ( this.readBit() === 1) result |= mask; } return result; }; if (typeof module !== "undefined") { module.exports = BitReaderLSB; }
(function () { 'use strict'; angular.module('myapp.tracking', ["ngMap"]); }());
function initOperDialog() { $("#operHold").bootstrapValidator({ // 提示的图标 feedbackIcons: { valid: 'glyphicon glyphicon-ok', // 有效的 invalid: 'glyphicon glyphicon-remove', // 无效的 validating: 'glyphicon glyphicon-refresh' // 刷新的 }, // 属性对应的是表单元素的名字 fields: { // 匹配校验规则 num: { // 规则 validators: { message: '数量无效', // 默认提示信息 notEmpty: { message: '数量不能为空' }, regexp: {/* 只需加此键值对,包含正则表达式,和提示 */ regexp: /^\d+(\.\d+)?$/, message: '含有非法字符.' }, fun: { message: 'fun函数无效的示例' } } }, price: { validators: { message: '价格无效', notEmpty: { message: '价格不能为空' }, regexp: { regexp: /^\d+(\.\d+)?$/, message: '含有非法字符' }, } }, } }).on('success.form.bv', function (e) { // 表单校验成功 /*禁用默认提交的事件 因为要使用ajax提交而不是默认的提交方式*/ e.preventDefault(); /*获取当前的表单*/ var form = $(e.target); // 可以通过选择器直接选择 // console.log(form.serialize()); // name=root&password=123456 $.ajax({ type: "post", url: "invest/processAccount", data: `userId=${Cookies.get("user_id")}&${form.serialize()}`, dataType: 'json', success: function (response) { console.log(response); if (response != null && response.result) { location.href = 'hold_history.html'; alert("操作成功"); } else { alert("操作失败"); } } }); }); // 重置功能 $(".pull-left[type='reset']").on('click', function () { $('#login').data('bootstrapValidator').resetForm(); }); } $(function () { initOperDialog(); });
import React, {Component, PropTypes} from 'react'; class Option extends Component{ render(){ var obj = this.props.option; return ( <div className={this.props.className} onMouseEnter={this.props.mouseEnter} onMouseLeave={this.props.mouseLeave} onMouseDown={this.props.mouseDown} onClick={this.props.mouseDown}> <span className={"flag-icon flag-icon-" + obj.value + " flag-icon-squared"}></span> {obj.label} </div> ); } } Option.propTypes = { option: PropTypes.object, className: PropTypes.string }; export default Option;
// class Spectrum{ // constructor(folder,scanId,spectrumId,centerValue){ // this.folder = folder ; // this.scanId = scanId ; // this.spectrumId = spectrumId; // this.centerValue = centerValue ; // } // getSpectrum(){ // console.log("this.scanId : "+ this.scanId); // let scanId = this.scanId; // let folder = this.folder; // let spectrumId = this.spectrumId; // $("."+this.spectrumId).show(); // var file_name = "../../topfd/"+folder+"/spectrum"+scanId+".js"; // let temp_script= document.createElement('script'); // temp_script.src = file_name; // document.head.appendChild(temp_script); // temp_script.onload = function() // { // let ms_data; // if(folder == "ms1_json") ms_data = ms1_data ; // else ms_data = ms2_data; // let peakList = getPeakData(ms_data); // let envelopList = getEnvelopeData(ms_data); // addSpectrum(spectrumId,peakList,envelopList,this.centerValue); // } // } // } // function getPeakData(json_data){ // let peakList = []; // let i = json_data.peaks.length ; // /* Pass the data into peakmass and peakintensity ----------------------------*/ // while(i--) // { // mz = parseFloat(json_data.peaks[i].mz); // intensity = parseFloat(json_data.peaks[i].intensity); // peak = {mz:mz, intensity:intensity} // peakList[i] = peak // } // peakList.sort(function(x,y){ // return d3.ascending(x.mz, y.mz); // }) // return peakList; // } // function getEnvelopeData(json_data){ // circleColor_list = ["red","orange","blue","green"]; // let envelopList = []; // json_data.envelopes.sort(function(x,y){ // return d3.ascending(x.env_peaks[0].mz, y.env_peaks[0].mz); // }) // let i = json_data.envelopes.length ; // let colorListsize = circleColor_list.length; // while(i--) // { // let env_peaks = []; // let mono_mass = parseFloat(json_data.envelopes[i].mono_mass); // let charge = parseFloat(json_data.envelopes[i].charge); // let color = circleColor_list[i%colorListsize]; // j = json_data.envelopes[i].env_peaks.length ; // while(j--){ // let mz = parseFloat(json_data.envelopes[i].env_peaks[j].mz); // let intensity = parseFloat(json_data.envelopes[i].env_peaks[j].intensity); // let env_peak = {mz:mz,intensity:intensity} // env_peaks[j] = env_peak ; // } // let envelope = {mono_mass:mono_mass,charge:charge,env_peaks:env_peaks,color:color}; // envelopList[i] = envelope; // } // return envelopList; // }
import React, {Component} from 'react'; import {Resumo3, Resumo4, Resumo6, Resumo7, Resumo10, Resumo11, Resumo12} from './Content/resumos'; class Resume extends Component { render(){ return( <div className="corpo_resumo"> <Resumo12/> <Resumo11/> <Resumo10/> <Resumo4/> <Resumo7/> <Resumo6/> </div> ) } } export default Resume;
besgamApp .controller('tweets', function( $scope, dataFactory ) { var now = new Date(); $scope.offsetutc = now.getTimezoneOffset(); dataFactory.getDataTwitter().then( function(response) { $scope.tweets = response.data; }); $scope.submit = function(form) { var href = "./newsletter/" + $scope.email; document.location.href = href; //document.forms[form].submit(); }; });
const urlsToCache = [ { url: "/", revision: "1" }, { url: "/nav.html", revision: "1" }, { url: "/index.html", revision: "1" }, { url: "/detailsTeam.html", revision: "1" }, { url: "/manifest.json", revision: "1" }, { url: "assets/images/logo/brandPL.png", revision: "1" }, { url: "assets/images/icons/favicon-16x16.png", revision: "1" }, { url: "assets/images/icons/favicon-32x32.png", revision: "1" }, { url: "assets/images/icons/favicon-96x96.png", revision: "1" }, { url: "assets/images/icons/icon-144x144.png", revision: "1" }, { url: "assets/images/icons/android-icon-36x36.png", revision: "1" }, { url: "assets/images/icons/android-icon-48x48.png", revision: "1" }, { url: "assets/images/icons/android-icon-72x72.png", revision: "1" }, { url: "assets/images/icons/android-icon-96x96.png", revision: "1" }, { url: "assets/images/icons/android-icon-144x144.png", revision: "1" }, { url: "assets/images/icons/android-icon-192x192.png", revision: "1" }, { url: "assets/images/icons/apple-icon.png", revision: "1" }, { url: "assets/images/icons/apple-icon-57x57.png", revision: "1" }, { url: "assets/images/icons/apple-icon-60x60.png", revision: "1" }, { url: "assets/images/icons/apple-icon-72x72.png", revision: "1" }, { url: "assets/images/icons/apple-icon-76x76.png", revision: "1" }, { url: "assets/images/icons/apple-icon-114x114.png", revision: "1" }, { url: "assets/images/icons/apple-icon-120x120.png", revision: "1" }, { url: "assets/images/icons/apple-icon-144x144.png", revision: "1" }, { url: "assets/images/icons/apple-icon-152x152.png", revision: "1" }, { url: "assets/images/icons/apple-icon-180x180.png", revision: "1" }, { url: "assets/images/icons/apple-icon-precomposed.png", revision: "1" }, { url: "assets/images/icons/ms-icon-70x70.png", revision: "1" }, { url: "assets/images/icons/ms-icon-144x144.png", revision: "1" }, { url: "assets/images/icons/ms-icon-150x150.png", revision: "1" }, { url: "assets/images/icons/ms-icon-310x310.png", revision: "1" }, { url: "assets/images/icons/favicon.ico", revision: "1" }, { url: "/assets/css/customizeStyle.css", revision: "1" }, { url: "/assets/css/materialize-icon.css", revision: "1" }, { url: "/assets/css/materialize.min.css", revision: "1" }, { url: "/assets/js/materialize.min.js", revision: "1" }, { url: "/assets/js/footballAPI.js", revision: "1" }, { url: "/assets/js/register.js", revision: "1" }, { url: "/assets/js/db.js", revision: "1" }, { url: "/assets/js/cardsHtml.js", revision: "1" }, { url: "/assets/js/idb.js", revision: "1" }, { url: "/assets/js/details.js", revision: "1" }, { url: "/assets/js/index.js", revision: "1" }, { url: "/assets/js/swRegister.js", revision: "1" }, { url: "/assets/components/nav.js", revision: "1" }, ]; importScripts( "https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js" ); if (workbox) { console.log(`workbox berhasil dimuat 🎉`); workbox.precaching.precacheAndRoute(urlsToCache, { ignoreUrlParametersMatching: [/.*/], }); workbox.routing.registerRoute( new RegExp("/"), workbox.strategies.networkFirst({ networkTimeoutSeconds: 1, }) ); // cache semua file image workbox.routing.registerRoute( /\.(?:png|gif|jpg|jpeg|svg)$/, workbox.strategies.cacheFirst({ cacheName: "images", plugins: [ new workbox.cacheableResponse.Plugin({ statuses: [200], }), new workbox.expiration.Plugin({ maxEntries: 100, maxAgeSeconds: 30 * 24 * 60 * 60, }), ], }) ); workbox.routing.registerRoute( new RegExp("https://api.football-data.org/"), workbox.strategies.staleWhileRevalidate({ cacheName: "footballApi", plugins: [ new workbox.cacheableResponse.Plugin({ statuses: [200], }), ], }) ); workbox.routing.registerRoute( /\.(?:js|css)$/, new workbox.strategies.StaleWhileRevalidate({ cacheName: "resource-css-Js", }) ); workbox.routing.registerRoute( new RegExp("/pages/"), workbox.strategies.staleWhileRevalidate({ cacheName: "pages", }) ); // Kode untuk event push agar service worker dapat menerima push notification. self.addEventListener("push", (event) => { let body; if (event.data) { body = event.data.text(); } else { body = "Push message no payload"; } let options = { body: body, icon: "./assets/images/icons/ms-icon-70x70.png", vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), primaryKey: 1, }, }; event.waitUntil( clients.matchAll().then((c) => { console.log(c); if (c.length === 0) { // Show notification self.registration.showNotification("Push Notification", options); } else { // Send a message to the page to update the UI console.log("Application is already open!"); } }) ); }); } else { console.log(`workbox gagal dimuat 😬`); }
$(document).ready(function(){ $("a").on('click', function(event) { if (this.hash !== "") { event.preventDefault(); var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 800, function(){ window.location.hash = hash; }); } }); }); AOS.init(); var coll = document.getElementsByClassName("act-header"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.maxHeight){ content.style.maxHeight = null; } else { content.style.maxHeight = content.scrollHeight + "px"; } }); }
var clienteClass = Backbone.Model.extend({ initialize: function() { if (!this.get("nombres")) { this.set("nombres", this.attributes.fields.usuario[0]); } if (!this.get("apellidos")) { this.set("apellidos", this.attributes.fields.usuario[1]); } if (!this.get("cedula")) { this.set("cedula", this.attributes.fields.usuario[2]); } if (!this.get("email")) { this.set("email", this.attributes.fields.usuario[3]); } if (!this.get("direccion")) { this.set("direccion", this.attributes.fields.direccion); } if (!this.get("fecha_nacimiento")) { this.set("fecha_nacimiento", this.attributes.fields.usuario[4]); } this.set("id", this.attributes.pk); }, defaults: { edwin: "Hola", } });
import BannerCategory from 'components/Banner/Banner'; import BreadCrumbs from 'components/BreadCrumbs/BreadCrumbs'; import Sidebar from 'components/Sidebar/Sidebar'; import Flex from 'components/UI/Flex'; import MainLayout from 'layouts/MainLayout'; import React, {useMemo} from 'react'; import { useParams } from 'react-router-dom'; import ProductList from 'components/Products/ProductList/ProductList'; import ProductToolbarHeader from 'components/Products/ProductToolbarHeader/ProductToolbarHeader'; import styles from './_goods.module.scss'; import { useMediaQuery } from 'react-responsive'; import { deviceSize } from 'utils/consts'; import OptionsDialog from 'components/OptionsDialog'; import { useSelector } from 'react-redux'; import { CSSTransition } from 'react-transition-group'; import Banner from "components/Banner/Banner"; import banner from './../../static/images/Banners.png' const Goods = () => { const isMobile = useMediaQuery({ maxWidth: deviceSize.mobile }); const params = useParams(); const categories = useSelector(({products}) => products.categories.data) const open = useSelector(({ modal }) => modal.optionsDialog.open); const getName = () => { const first = categories.find((item) => item.slug == params.categoryIndex); const subCategory = first?.children?.find((item) => item.slug === params?.subCategoryIndex); const targetCategory = subCategory?.children?.find((item) => item.slug === params?.categoryName); return targetCategory?.title; }; const name = useMemo(() => getName(), [params]) return ( <div className={styles.main}> <MainLayout> <div className={styles.wrapper}> <BreadCrumbs params={params} /> <Banner title={name} banner={banner} /> <Flex> {!isMobile && <Sidebar params={params} />} <div className={styles.products_list}> <ProductToolbarHeader results={1000} /> <ProductList /> </div> </Flex> </div> </MainLayout> <CSSTransition in={open} classNames="options-menu" unmountOnExit timeout={500}> <OptionsDialog /> </CSSTransition> </div> ); }; export default Goods;
import React from 'react'; import style from "./ProfilePage.module.css" import ProfilePage from "./ProfilePage"; import * as axios from "axios"; import {withRouter} from "react-router-dom"; class ProfileContainer extends React.Component { componentDidMount() { //this.props.toggleIsFetching(true) debugger let userId = this.props.match.params.userId if(!userId){userId=2} axios.get(`https://social-network.samuraijs.com/api/1.0/profile/`+ userId) .then(response => { this.props.setProfile(response.data) //this.props.toggleIsFetching(false) }) } render() { let changePostText = (e) => { let newPostText = e.currentTarget.value this.props.onChangePostText(newPostText) } let addPostClick = () => { let newPostText = this.props.newPostText let newPost = {id: 7, postText: newPostText, likes: 5} this.props.onAddPostClick(newPost) } return ( <div className={style.profile}> <ProfilePage {...this.props} changePostText={changePostText} addPostClick={addPostClick}/> </div> ) } } let WithUrlDataContainer = withRouter(ProfileContainer) export default WithUrlDataContainer
"use strict"; const TelegramBot = require("node-telegram-bot-api"); const config = require("../../../config/index"); const { telegram: { botToken }, } = config; const deubgBotToken = process.argv[2]; const bot = new TelegramBot(deubgBotToken || botToken, { polling: { interval: 10000, // Optional. How often check updates (in ms).npm params: { // Optional. Use polling. timeout: 20, // Optional. Update polling timeout (0 - short polling). }, }, }); function getBot() { return bot; } module.exports = { getBot, };
const assert = require('chai').assert const { sorter, athletes, Animal, TuringStudent } = require('../01-26-17') describe('Problems', () => { it.skip('should return a string stating who the winningest athlete was', () => { assert.strictEqual(sorter(athletes), 'Tom Brady has won the most titles with 4.'); }); it('the Animal constructor should return the correct information with any given new Animal', () => { const killerBunny = new Animal({ species: 'rabbit', extinct: false, favoredFood: 'buffalos', }) assert.strictEqual(killerBunny.species, 'rabbit'); assert.strictEqual(killerBunny.kingdom, 'animal'); assert.strictEqual(killerBunny.eat(), 'The rabbit eats buffalos.'); }); it('the TuringStudent constructor should properly inherit from Animal', () => { const hilary = new TuringStudent({ name: 'Hilary', languages: ['English'], nationality: 'United States', mod: 4, program: 'Front End', }) assert.strictEqual(hilary.nationality, 'United States'); assert.strictEqual(hilary.name, 'Hilary'); assert.strictEqual(hilary.program, 'Front End'); }); });
const Url = "https://exam1api.sebbeprojects.com/wp-json/wp/v2/posts?_embed&per_page=18"; const blogPost = document.querySelector(".blogpost-content"); let moreContentbutton = document.querySelector("#more-contentbtn"); moreContentbutton.onclick = loadMore; function loadMore() { console.log("test"); const iterations = lastIndexLoaded + numberOfImagesToLoadNext + 1; for (let i = lastIndexLoaded + 1; i < iterations; i++) { console.log("i: ", i); console.log("lastIndexLoaded: ", lastIndexLoaded); console.log("numberofiagesnextt: ", numberOfImagesToLoadNext); blogPost.innerHTML += ` <a href="singleblog.html?id=${result[i].id}"> <div> <img src="${result[i]._embedded["wp:featuredmedia"]["0"].source_url}" alt= "${result[i].title.rendered}"> <h4>${result[i].title.rendered}</h4> </div> `; lastIndexLoaded++; } if (lastIndexLoaded >= numberOfImages - 1) { moreContentbutton.style.display = "none"; } } async function blogsApifetch() { try { const response = await fetch(Url); const result = await response.json(); return result; } catch (error) { console.log("Fail"); } } function blogContent(res) { blogPost.innerHTML = ""; for (let i = 0; i < numberOfImagesToLoadInitially; i++) { blogPost.innerHTML += ` <a href="singleblog.html?id=${res[i].id}"> <div> <img src="${res[i]._embedded["wp:featuredmedia"]["0"].source_url}" alt= "${res[i].title.rendered}"> <h4>${res[i].title.rendered}</h4> </div> `; } } const numberOfImagesToLoadInitially = 9; const numberOfImagesToLoadNext = 3; let result; let numberOfImages; blogsApifetch().then((res) => { blogContent(res); result = res; numberOfImages = res.length; }); let lastIndexLoaded = 8;
var path = require('path'); var fs = require('fs'); var _ = require('lodash'); var crypto = require('crypto'); module.exports = function (Galleon, query, callback) { if (!Galleon.connection.collections.queue) return callback(new Error('Collection Not Found!')); Galleon.connection.collections.queue.findOne({ association: query.email, eID: query.eID.substring(1) }).exec(function (error, mail) { if (error) return callback(error); if (!mail) return callback("Mail not found!"); if (!query.file) return callback("No file received"); // Make sure mail.attachments is an array if (!_.isArray(mail.attachments)) mail.attachments = []; var reference = crypto.randomBytes(8).toString('hex'); mail.attachments.push({ id: (query.file.filename) ? (query.file.filename.split("_")[1] || null) : null, cid: null, /* Not implemented yet */ fileName: query.file.originalname, path: query.file.path, transferEncoding: query.file.encoding, contentType: query.file.mimetype, checksum: null, /* Not implemented yet */ length: query.file.size, ref: reference }) Galleon.connection.collections.queue.update({ association: query.email, eID: query.eID.substring(1) }, { attachments: mail.attachments }).exec(function (error, mail) { if (error) return callback(error); if (!mail) return callback("Mail not found!"); // Else callback(null, { ref: reference }); }) }) }
/// <reference path="../..\..\bower_components/polymer-ts/polymer-ts.d.ts"/> var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var AuthenticationBar = (function (_super) { __extends(AuthenticationBar, _super); function AuthenticationBar() { _super.apply(this, arguments); this.greet = "Hello"; this.provider = ""; this.message = ""; this.email = ""; } AuthenticationBar.prototype.greetChanged = function (newValue, oldValue) { console.log("greet has changed from " + oldValue + " to " + newValue); }; AuthenticationBar.prototype.userChanged = function (newValue, oldValue) { console.log(newValue); }; AuthenticationBar.prototype.greetAll = function (test) { return this.greet + " to all"; }; AuthenticationBar.prototype.computeLoginStatus = function (statusKnown, user) { if (statusKnown && user) { return "Logged in"; } if (statusKnown) { return "Logged out"; } return "Unknown status"; }; AuthenticationBar.prototype.computeLoginHidden = function (statusKnown, user) { return !statusKnown || !!user; }; AuthenticationBar.prototype.handleClick = function (e) { this.greet = "Holà"; this.fire("greet-event"); }; AuthenticationBar.prototype.onButtonWasClicked = function (e) { console.log('event "greet-event" received'); }; AuthenticationBar.prototype.ready = function () { console.log(this['is'], "ready!"); }; AuthenticationBar.prototype.created = function () { console.log(this['is'], "created!"); }; AuthenticationBar.prototype.attached = function () { console.log(this['is'], "attached!"); }; AuthenticationBar.prototype.detached = function () { console.log(this['is'], "detachecd!"); }; __decorate([ property({ type: String }), __metadata('design:type', String) ], AuthenticationBar.prototype, "greet"); __decorate([ property({ type: String }), __metadata('design:type', String) ], AuthenticationBar.prototype, "provider"); __decorate([ property({ type: String }), __metadata('design:type', String) ], AuthenticationBar.prototype, "message"); __decorate([ property({ type: String }), __metadata('design:type', String) ], AuthenticationBar.prototype, "email"); __decorate([ property({ type: Object }), __metadata('design:type', Object) ], AuthenticationBar.prototype, "user"); __decorate([ property({ type: Boolean }), __metadata('design:type', Boolean) ], AuthenticationBar.prototype, "statusKnown"); Object.defineProperty(AuthenticationBar.prototype, "greetChanged", __decorate([ observe("greet"), __metadata('design:type', Function), __metadata('design:paramtypes', [String, String]), __metadata('design:returntype', void 0) ], AuthenticationBar.prototype, "greetChanged", Object.getOwnPropertyDescriptor(AuthenticationBar.prototype, "greetChanged"))); Object.defineProperty(AuthenticationBar.prototype, "userChanged", __decorate([ observe("user"), __metadata('design:type', Function), __metadata('design:paramtypes', [String, String]), __metadata('design:returntype', void 0) ], AuthenticationBar.prototype, "userChanged", Object.getOwnPropertyDescriptor(AuthenticationBar.prototype, "userChanged"))); Object.defineProperty(AuthenticationBar.prototype, "greetAll", __decorate([ computed(), __metadata('design:type', Function), __metadata('design:paramtypes', [String]), __metadata('design:returntype', String) ], AuthenticationBar.prototype, "greetAll", Object.getOwnPropertyDescriptor(AuthenticationBar.prototype, "greetAll"))); Object.defineProperty(AuthenticationBar.prototype, "onButtonWasClicked", __decorate([ listen("greet-event"), __metadata('design:type', Function), __metadata('design:paramtypes', [Event]), __metadata('design:returntype', void 0) ], AuthenticationBar.prototype, "onButtonWasClicked", Object.getOwnPropertyDescriptor(AuthenticationBar.prototype, "onButtonWasClicked"))); AuthenticationBar = __decorate([ /// <reference path="../..\..\bower_components/polymer-ts/polymer-ts.d.ts"/> component('authentication-bar'), __metadata('design:paramtypes', []) ], AuthenticationBar); return AuthenticationBar; })(polymer.Base); AuthenticationBar.register();
/* eslint-env mocha */ const levenshteindistance = require('../../../src').algorithms.string.levenshteindistance; const assert = require('assert'); describe('Levenshtein Distance', () => { it('should find levenshtein distance between two strings', () => { const stringA = 'sunday'; const stringB = 'saturday'; const distance = levenshteindistance(stringA, stringB); assert.equal(distance, 3); }); it('should return length of string A when B is empty', () => { const stringA = 'sunday'; const stringB = ''; const distance = levenshteindistance(stringA, stringB); assert.equal(distance, 6); }); it('should return length of string B when A is empty', () => { const stringA = ''; const stringB = 'saturday'; const distance = levenshteindistance(stringA, stringB); assert.equal(distance, 8); }); it('should return distance as 0 when no params are provided', () => { const distance = levenshteindistance(); assert.equal(distance, 0); }); });
const db = require('../db') const sequelize = require('sequelize'); const stpr = db.define("Order", { storageID: sequelize.INTEGER, productID: sequelize.INTEGER, total: sequelize.INTEGER }) db.sync() .then(()=>{ console.log("Create Order successfully...") }) module.exports = stpr
module.exports = { jwtSecret: process.env.JWT_SECRET || '8dc7dfb4-dd21-4916-b99a-b8bab0420974' };
/* eslint-disable @typescript-eslint/restrict-plus-operands */ /* eslint-disable @typescript-eslint/no-var-requires */ const path = require('path'); const mkdirp = require('mkdirp'); const fs = require('fs'); exports.onPreBootstrap = ({ store, reporter }) => { const { program } = store.getState(); const dirs = [path.join(program.directory, 'content')]; dirs.forEach(dir => { if (!fs.existsSync(dir)) { reporter.log(`creating the ${dir} directory`); mkdirp.sync(dir); } }); }; module.exports = { siteMetadata: { title: 'Ghost', description: 'The professional publishing platform', coverImage: 'img/blog-cover.jpg', logo: 'img/ghost-logo.png', lang: 'en', siteUrl: 'https://gatsby-casper.netlify.com', // full path to blog - no ending slash facebook: 'https://www.facebook.com/ghost', twitter: 'https://twitter.com/tryghost', showSubscribe: false, // subscribe button in site nav and home page mailchimpAction: '', // 'https://twitter.us19.list-manage.com/subscribe/post?u=a89b6987ac248c81b0b7f3a0f&amp;id=7d777b7d75', mailchimpName: '', // 'b_a89b6987ac248c81b0b7f3a0f_7d777b7d75', mailchimpEmailFieldName: '', // 'MERGE0', googleSiteVerification: '', // 'GoogleCode', footer: 'is based on Gatsby Casper', postsPerPage: 6, }, mapping: { 'MarkdownRemark.frontmatter.author': 'AuthorYaml', }, plugins: [ 'gatsby-plugin-sharp', { resolve: 'gatsby-source-filesystem', options: { name: 'content', path: path.join(process.cwd(), 'content'), }, }, { resolve: 'gatsby-transformer-remark', options: { plugins: [ { resolve: 'gatsby-remark-responsive-iframe', options: { wrapperStyle: 'margin-bottom: 1rem', }, }, 'gatsby-remark-prismjs', 'gatsby-remark-copy-linked-files', 'gatsby-remark-smartypants', 'gatsby-remark-abbr', { resolve: 'gatsby-remark-images', options: { maxWidth: 1170, quality: 90, }, }, ], }, }, 'gatsby-transformer-json', { resolve: 'gatsby-plugin-canonical-urls', options: { siteUrl: 'https://gatsby-casper.netlify.com', }, }, 'gatsby-plugin-emotion', 'gatsby-plugin-typescript', 'gatsby-transformer-sharp', 'gatsby-plugin-react-helmet', 'gatsby-transformer-yaml', 'gatsby-plugin-feed', { resolve: 'gatsby-plugin-postcss', options: { postCssPlugins: [require('postcss-color-function'), require('cssnano')()], }, }, ], };
import { OwcDemo } from './src/OwcDemo.js'; window.customElements.define('owc-demo', OwcDemo);
var currentYear = "2019"; //get xml data function loadStory(){ fetch('/data/storyData.xml').then((res) => { res.text().then((xml) => { let parser = new DOMParser(); let xmlDom = parser.parseFromString(xml, 'text/xml'); var eleList = xmlDom.getElementsByTagName('table'); var output = ''; for (let i = 0; i < eleList.length; i++) { var year = eleList[i].querySelector('[name="year"]').firstChild.nodeValue; var content_ = eleList[i].getElementsByTagName('content')[0].firstChild.wholeText; output += ` <a class="specialLink" href="#` + year + `" > <div class="timeline-item" id="` + year + `"> <span class="year_title">` + year + `</span> <h2 class="item_title">` + eleList[i].querySelector('[name="title"]').firstChild.nodeValue + ` </h2> <div class="innerContent"> `+ content_+` </div> </div> </a> `; } document.getElementsByClassName('container')[0].innerHTML = output; }); }); } //app obj for single page rounting function getCurrentPage(ev){ let result; let target = ev.target; let changeYear = ''; if (ev.target.tagName == "H2" || ev.target.tagName == "P" || ev.target.tagName == "SPAN" || ev.target.tagName == "IMG") { result = ev.target.parentElement.children[0].innerHTML; if (ev.target.parentElement.className == "innerContent") { result = ev.target.parentElement.parentElement.children[0].innerHTML; } target = ev.target.parentElement; } else if (ev.target.classList.contains('fa-times')){ result = "close" target = ev.target.parentElement; } else if (ev.target.classList.contains('fa-chevron-down') || ev.target.classList.contains('fa-chevron-up')) { result = "change" target = ev.target.parentElement; changeYear = ev.target.attributes[1].nodeValue; }else{ result = ev.target.children[0].innerHTML; } return [result, target, changeYear]; } const app = { pages: [], show: new Event('show'), init: function () { var promise = new Promise((resolve, reject) => { loadStory(); resolve(); }); promise.then((val) => { var inter = setInterval(() => { app.pages = document.querySelectorAll('.timeline-item'); if(app.pages.length != 1){ /* app.pages.forEach((pg) => { pg.addEventListener('show', app.pageShown); })*/ document.querySelectorAll('.timeline-item').forEach((link) => { link.addEventListener('click', app.nav); }) let hash = location.hash; if(hash.length != 0) { let newhash = location.hash.replace('#', ''); document.querySelector('.active').classList.remove('active'); document.getElementById(newhash).classList.add('active'); //window.scrollTo(0,parseInt(window.getComputedStyle(document.getElementById(newhash)). //transformOrigin.split('px')[1])); } clearInterval(inter); } }, 300); inter; }); }, nav: function (ev) { ev.preventDefault(); let resultList = getCurrentPage(ev); let currentPage = resultList[0]; try{ if (currentPage == "close") { currentPage = "mock" document.querySelector('.active').classList.remove('active'); document.getElementById(currentPage).classList.add('active'); history.pushState({}, currentPage, `#${''}`); document.getElementById(currentPage).dispatchEvent(app.show); } else if (currentPage == "change") { let changeYear = resultList[2]; document.querySelector('.active').classList.remove('active'); document.getElementById(changeYear).classList.add('active'); history.pushState({}, changeYear, `#${changeYear}`); document.getElementById(changeYear).dispatchEvent(app.show); } else { document.querySelector('.active').classList.remove('active'); document.getElementById(currentPage).classList.add('active'); history.pushState({}, currentPage, `#${currentPage}`); document.getElementById(currentPage).dispatchEvent(app.show); } }catch{ currentPage = "mock" document.getElementById(currentPage).classList.add('active'); history.pushState({}, currentPage, `#${''}`); document.getElementById(currentPage).dispatchEvent(app.show); } }, pageShown: function (ev) { console.log('Page', ev.target.id, 'just shown'); let h1 = ev.target.cl('h1'); h1.classList.add('big') } } function xmlMove(){ const scrollVal = window.scrollY; const xmlEle = document.getElementById('xml') const menuHeight = parseInt(window.getComputedStyle( document.getElementById('menu')).height); if (scrollVal > menuHeight) { xmlEle.style.position = "fixed"; xmlEle.style.top = "25px"; xmlEle.style.right = "15px"; } else { xmlEle.style.position = "absolute"; xmlEle.style.top = menuHeight + 15 + "px"; xmlEle.style.right = "10px"; } } xmlMove(); document.addEventListener('DOMContentLoaded', app.init); document.addEventListener('scroll', xmlMove); window.addEventListener('resize', xmlMove);
import React from 'react'; import cloneDeep from 'lodash/cloneDeep'; class CreateDocument extends React.Component { constructor(props) { super(props); this.state = { title: '', categoryId: '', url: '', file: null }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleFileSelect = this.handleFileSelect.bind(this); this.fileInput = null; } handleChange(event) { const state = cloneDeep(this.state); state[event.target.name] = event.target.value; this.setState(state); } handleFileSelect(event) { const state = cloneDeep(this.state); state.file = this.fileInput.files[0]; this.setState(state); } handleSubmit(event) { event.preventDefault(); if (this.state.url.length) { this.props.createLink( this.state.title, this.state.categoryId, this.state.url ); } else if (this.state.file) { this.props.upload( this.state.title, this.state.categoryId, this.state.file ); } } render() { return ( <div className="upload-file panel-item"> <form onSubmit={this.handleSubmit} name="uploadFile"> <div className="input-container"> <label>File Title:</label> <input type="text" name="title" onChange={this.handleChange} tabIndex="1" /> </div> <div className="input-container"> <label>Category:</label> <select name="categoryId" onChange={this.handleChange} tabIndex="2"> <option value={null}>Select Category</option> {this.props.categories.map(category => <option value={category.id} key={category.id}> {category.title} </option> )} </select> </div> <div className="input-container"> <label>URL:</label> <input type="url" name="url" onChange={this.handleChange} disabled={this.state.file} tabIndex="4" /> </div> <div className="input-container"> <label>Select File:</label> <input type="file" name="document" ref={(ref) => this.fileInput = ref} onChange={this.handleFileSelect} disabled={this.state.url.length} tabIndex="3" /> </div> <div className="button-container"> <button type="button" onClick={this.props.cancel} className="cancel"> Cancel </button> <button type="submit" disabled={ (!this.state.file && !this.state.url.length) || !this.state.categoryId.length || !this.state.title.length}> Create </button> </div> </form> </div> ); } } export default CreateDocument;
import React from 'react'; import { useRouter } from 'next/router'; import Query from 'components/query'; import PRODUCT_QUERY from 'apollo/queries/product/product'; import Wallet from 'components/svg/wallet'; import Truck from 'components/svg/truck'; import Warranty from 'components/svg/warranty'; const Forminfo = () => { const router = useRouter(); return ( <Query query={PRODUCT_QUERY} id={router.query.id}> {({ data: { product } }) => { return ( <div className="col-lg-4 col-md-5 col-12 offset-lg-1 offset-0"> <div className="form-info"> <div className="form-info__top"> <Wallet /> <h5 className="form-info__title">Заказ и Оплата</h5> </div> <div className="form-info__bottom"> <p className="form-info__desc">Полную информацию предоставит сотрудник колл-центра </p> </div> </div> <div className="form-info"> <div className="form-info__top"> <Truck /> <h5 className="form-info__title">Доставка</h5> </div> <div className="form-info__bottom"> <p className="form-info__desc" style={ product.fast_delivery ? { display: 'none' } : { display: 'block' } } >Ваш заказ будет доставлен на дом в течение 60 рабочих дней </p> <p className="form-info__desc" style={ product.fast_delivery ? { display: 'block' } : { display: 'none' } } >Ваш заказ будет доставлен на дом в течение 10 рабочих дней </p> <p className="form-info__desc">(стоимость 400 ₪)</p> </div> </div> <div className="form-info"> <div className="form-info__top"> <Warranty /> <h5 className="form-info__title">Гарантия</h5> </div> <div className="form-info__bottom"> <p className="form-info__desc">Срок гарантии - 12 месяцев со дня продажи изделия </p> </div> </div> </div> ); }} </Query> ); }; export default Forminfo;
var RowdyruffBoys = window.RowdyruffBoys || {}; RowdyruffBoys.map = RowdyruffBoys.map || {}; var data = { UserPoolId: _config.cognito.userPoolId, ClientId: _config.cognito.userPoolClientId }; var userPool = new AmazonCognitoIdentity.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); if (cognitoUser != null) { cognitoUser.getSession(function(err, session) { if (err) { alert(err); return; } console.log('session validity from recruiter.js: ' + session.isValid()); }); } (function rideScopeWrapper($) { var authToken; RowdyruffBoys.authToken.then(function setAuthToken(token) { if (token) { authToken = token; } else { window.location.href = 'signin.html'; } }).catch(function handleTokenError(error) { alert(error); window.location.href = '/signin.html'; }); $(function onDocReady() { $('#signOut').click(function() { cognitoUser.signOut(); alert("You have been signed out."); console.log("You have been signed out."); window.location = "signin.html"; }); $('#showUser').click(function() { cognitoUser.getUserAttributes(function(err, result) { if (err) { alert(err); return; } for (i = 0; i < result.length; i++) { console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue()); if(i == result.length - 2){ //alert('Your account status: ' + result[i].getName() + ' has value ' + result[i].getValue()); } if(i == result.length - 1){ alert('You are logged in on ' + result[i].getName() + ' which has value ' + result[i].getValue()); } } }); //alert(strInfoAccount); }); if (!_config.api.invokeUrl) { $('#noApiMessage').show(); } }); $('#deleteUser').click(function() { var r = confirm("Do you really want to delete Your actual account? \n This operation is not temporary."); if(r == true){ cognitoUser.deleteUser(function(err, result) { if (err) { alert(err.message || JSON.stringify(err)); return; } console.log('call result: ' + result); alert("Your account has been deleted . . . "); console.log("Your account has been deleted . . . ."); window.location = "signin.html"; }); } else { //alert("You canceled deleting your account."); console.log("You canceled deleting your account."); } }); $('#getAllUsers').click(function() { console.log("ShowAllUsers"); let url = "https://1mqghaecbc.execute-api.us-east-1.amazonaws.com/testGetAllUsers/getallusers"; $.ajax({ type:"GET", url: url, data: { 'Content-Type': 'application/json', 'Authorization': RowdyruffBoys.authToken }, crossDomain: true, success: function (data) { console.log("received: " + JSON.stringify(data)); }}); // $.getJSON(url, function(data) { // console.log("received: " + JSON.stringify(data)); // }); }); $('#createAJAX').click(function() { console.log("Deleting user from DynamoDB by AJAX"); let url = "https://54pvtn3r3g.execute-api.us-east-1.amazonaws.com/witamUser/users"; var text = '{ "userEmail":"kakuncio@gmail.com" }'; $.ajax({ headers: { 'Authorization': RowdyruffBoys.authToken, 'Accept': 'application/json', 'Content-Type': 'application/json' }, 'type': 'DELETE', 'url': url, 'data': text, 'dataType': 'json', crossDomain: true, success: function(resp) { console.log('good --> successfuly deleted user from DynamoDB'); }, error: function(resp, err) { console.log('fail deleteUser DynamoDB'); console.log(resp); console.log(err); } }); }); function displayUpdate(text) { $('#updates').append($('<li>' + text + '</li>')); } }(jQuery));
angular.module('esCore', []);
/** * Configurable authorizer, * Set the authorizer to a module relative to this module that handles validating * username and password. * * Authorizer modules must expose a function exports.authorize = function(username, password, cb) * * If the authorizer function has a function called init() it will be called. * */ var config = require('../util/config'); var hardcoded = require('./hardcoded-authorizer').authorize; var xml = require('./xml-authorizer').authorize; var pam = require('./pam-authorizer').authorize; var selector = hardcoded; swappable = function(username, password, cb) { return selector(username, password, cb); }; config.emitter.on('configReady', function() { if (config.configData.authorizer == 'hardcoded') { selector = hardcoded; } else if (config.configData.authorizer == 'pam') { selector = pam; } else if (config.configData.authorizer == 'xml') { selector = xml; } else { console.error("No authorizer configured! " + config.configData.authorizer); } if (selector.init) { selector.init(); } }); exports.authorize = swappable;
import React, { Component } from 'react' import { NavLink } from 'react-router-dom' import { Container } from 'semantic-ui-react' import { cookies } from '../../cookie' class AgeAllowance extends Component { handleClick = (res) => { if (res === 'Yes') { cookies.set('verification', 'yes', { path: '/' }); window.location.href = "/"; } else { cookies.set('verification', 'no', { path: '/' }); window.location.href = "https://google.com"; } } render() { return ( <Container className="full-size m-0 fade-in height-webkit-fill-available"> <section className="flex-display" style={{ flex: '1' }}> <div className="flex-space-end-between width-15"> <img className="full-image" src="/img/PaqueraMezcal_Entry_Ornament1.png" alt="" /> <img className="full-image" src="/img/PaqueraMezcal_Entry_Ornament2.png" alt="" /> <img className="full-image" src="/img/PaqueraMezcal_Entry_Ornament6.png" alt="" /> </div> <div className="flex-space-end-between width-70"> <img className="full-image-min-200 mt-20" src="/img/PaqueraMezcal_Entry_Ornament7.png" alt="" /> <section className="cookie-dialog-section"> <img className="width-50 top-left" src="/img/PaqueraMezcal_Story_TopLeft3.png" alt="" /> <img className="width-50 top-right" src="/img/PaqueraMezcal_Story_TopRight3.png" alt="" /> <img className="width-50 bottom-left" src="/img/PaqueraMezcal_Story_BottomLeft3.png" alt="" /> <img className="width-50 bottom-right" src="/img/PaqueraMezcal_Story_BottomRight3.png" alt="" /> <div className="cookie-alert-div"> <div className="title"> <h1>ARE YOU 21+</h1> <h1>YEARS OF AGE?</h1> </div> <div className="flex-space-around"> <button onClick={() => this.handleClick('Yes')}>YES</button> <button onClick={() => this.handleClick('No')}>NO</button> </div> <p> You must be of legal drinking age to enter this site. By entering you accept our <NavLink to={"/terms&condition"}>terms and conditions</NavLink> and <NavLink to={"/terms&condition"}>our privacy</NavLink> and <NavLink to={"/terms&condition"}>cookie policy</NavLink>.<br />We encourage drinking responsibly. </p> </div> </section> <img className="full-image-min-200 mb-20" src="/img/PaqueraMezcal_Entry_Ornament8.png" alt="" /> </div> <div className="flex-space-end-between width-15"> <img className="full-image" src="/img/PaqueraMezcal_Entry_Ornament4.png" alt="" /> <img className="full-image" src="/img/PaqueraMezcal_Entry_Ornament3.png" alt="" /> <img className="full-image" src="/img/PaqueraMezcal_Entry_Ornament5.png" alt="" /> </div> </section> </Container> ) } } export default AgeAllowance
import { all } from "redux-saga/effects"; import gistsSaga from "./gists"; import category from './category' export default function* () { yield all( [ category(), gistsSaga(), ] ); }
// console.log("app"); // alert();
$(function () { var total = $('#row_dates').val(); var selectedId; var dialog; var getLabel = function(label) { console.log(this); } $('#source_select, #month_value_select').select2(); //окно добавления записи $(document).on('click', '#create-user', function (e) { e.preventDefault(); console.log('testFunction'); $('#dialog-form .select-container').each(function(){ $("select", this).val($("select option:first", this).val()); switch($('button', this).attr('data-id')) { case 'consultations_select': $("button .filter-option", this).text('Выберите тип консультаций'); break; case 'print_select': $("button .filter-option", this).text('Выберите тип листов'); break; case 'book_loan_select': $("button .filter-option", this).text('Выберите тип эл. копий'); break; case 'denial_select': $("button .filter-option", this).text('Выберите тип отказа'); break; default: $("button .filter-option", this).text($('select',this).val()); } }); if($('#pam111').val()=='no_select') { alert('Выберите сотрудника'); } else { dialog = $("#dialog-form").dialog({ autoOpen: false, height: 800, width: 900, modal: true, buttons: { "добавить запись": function () { $('.ui-dialog-buttonset button:first-child').addClass('disabled'); addUser('library/selectphp.php'); }, "закрыть": function () { dialog.dialog("close"); } } }); dialog.dialog("open"); $('input[type="text"]').val(''); } }); //окно редактирования записи $(document).on('click', '.editButton', function () { selectedId = $(this).val(); $('#notes_select').val($(this).parent().siblings(".notesValue").text()); $('#page_value_select').val($(this).parent().siblings().find(".pcv").text()); $('#bbk_select').val($(this).parent().siblings(".bbkValue").text()); $('#request_select').val($(this).parent().siblings(".requestValue").text()); $('#username_select').val($(this).parent().siblings(".usernameValue").text()); $('#denial_select').val($(this).parent().siblings().find(".dcv").text()); $('#bookloan_select').val($(this).parent().siblings().find(".bcv").text()); if($(this).parent().siblings(".consultationsValue").text()!='') { $('#consultations_select option[value='+$(this).parent().siblings(".consultationsValue").text()+']').prop("selected", true); } else $('#consultations_select option:first').prop("selected", true); $('#authorization_select option[value='+$(this).parent().siblings(".authorizationValue").text()+']').prop("selected", true); $('#goal_select option[value='+$(this).parent().siblings(".targetValue").text()+']').prop("selected", true); $('#type_select option[value='+$(this).parent().siblings(".typeValue").text()+']').prop("selected", true); $('#bbk_select option[value='+$(this).parent().siblings(".bbkValue").text()+']').prop("selected", true); $('button').on('click',function(){ $('li').each(function(){ $(this).removeClass('selected'); /*$('select', this).change(function(){ var select = $(this).val(); var x = $('.dropdown-menu li:contains('+select+')'); x.addClass("selected"); });*/ }); }); $('#leftbar .select-container').each(function(){ $("button .filter-option", this).text($('select',this).val()); //alert($('select',this).val()); //$("button span", this).val($("select option:first", this).val()); /* x.addClass("selected"); x.css("border: 10px solid black!important;");*/ }); dialog = $("#dialog-form").dialog({ autoOpen: false, height: 800, width: 900, modal: true, buttons: { "отредактировать запись": function () { $('.ui-dialog-buttonset button:first-child').addClass('disabled'); addUser('library/edit.php'); }, "закрыть": function () { dialog.dialog("close"); } } }); dialog.dialog('open'); }); $(document).on('click', '#print-button', function () { dialog = $("#show_summary").dialog({ autoOpen: false, height: 550, width: 700, modal: true, buttons: { "закрыть": function () { dialog.dialog("close"); } } }); dialog.dialog('open'); }); $(document).on('click', '#add-button-event', function () { dialog = $("#add_event").dialog({ autoOpen: false, height: 550, width: 700, modal: true, buttons: { "Добавить запись": function () { addEvent('library/edit.php'); }, "закрыть": function () { dialog.dialog("close"); } } }); dialog.dialog('open'); }); // функция для добавления/редактирования записи в таблицу function addUser(action) { var date; var alert1 = action; date = new Date(); date = date.getUTCFullYear() + '-' + ('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' + ('00' + date.getUTCDate()).slice(-2) + ' '; var ajaxDate = date; var ajaxAuthorization = $("#authorization_select").val(); var ajaxUserName = $("#username_select").val(); var ajaxRequest = $("#request_select").val(); var ajaxTarget = $("#goal_select").val(); var ajaxSource = $("#source_select").val(); var ajaxType = $("#type_select").val(); var ajaxConsultations = $("#consultations_select").val(); var ajaxBBK = $("#bbk_select").val(); var ajaxNotes = $("#notes_select").val(); var ajaxPageCount = $("#print_value_select").val(); var ajaxPageType = $("#print_select").val(); var ajaxBookLoan = $("#book_loan_select").val(); var ajaxOperatorId = $("#pam111").val(); var ajaxDenial = $("#denial_select").val(); var ajaxDenialValue = $("#denial_value_select").val(); var ajaxBookloanValue = $("#book_loan_value_select").val(); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - // $.ajax({ url: alert1, type: "POST", dataType: "text", data: ( "ajaxDate=" + ajaxDate + "&ajaxAuthorization=" + ajaxAuthorization + "&ajaxUserName=" + ajaxUserName + "&ajaxRequest=" + ajaxRequest + "&ajaxTarget=" + ajaxTarget + "&ajaxSource=" + ajaxSource + "&ajaxType=" + ajaxType + "&ajaxConsultations=" + ajaxConsultations + "&ajaxBBK=" + ajaxBBK + "&ajaxNotes=" + ajaxNotes + "&ajaxPageCount=" + ajaxPageCount + "&ajaxPageType=" + ajaxPageType + "&ajaxBookLoan=" + ajaxBookLoan + "&ajaxOperatorId=" + ajaxOperatorId + "&ajaxDenial=" + ajaxDenial + "&ajaxDenialValue=" + ajaxDenialValue + "&ajaxBookloanValue=" + ajaxBookloanValue + "&ajaxSelectedId=" + selectedId ), beforeSend: function () { $('#dataTable').empty(); }, success: function (data) { $('#dataTable').load(' #dataTable table'); }, complete: function () { dialog.dialog('close'); $('input[type="text"]').val(''); $('.select-container').each(function () { $("select", this).val($("select option:first", this).val()); $('.select2-chosen', this).text($('select option:first', this).text()); }) } }); } function addEvent() { date = new Date(); date = date.getUTCFullYear() + '-' + ('00' + (date.getUTCMonth() + 1)).slice(-2) + '-' + ('00' + date.getUTCDate()).slice(-2) + ' '; var ajaxDate = date; var ajaxEventType = $("#event_type").val(); var ajaxEventName = $("#guest_name").val(); var ajaxEventNumber = $("#guest_number").val(); $.ajax({ url: "library/addEvent.php", type: "POST", dataType: "text", data: ( "ajaxEventType=" + ajaxEventType + "&ajaxEventName=" + ajaxEventName + "&ajaxEventNumber=" + ajaxEventNumber + "&ajaxDate=" + ajaxDate ), success: function (data) { eventform.dialog("close"); } }); } //Добавляем новую запись //показываем/скрываем поля с опциональными параметрамми в таблице $("#view-button").on("click", function () { $('#sidePanel').hide(); $(".optional_values").toggle(); if ($("#view-button").text() == "Скрыть доп.поля") { $("#view-button").text("Показать поля"); $('#sidePanel').show(); } else $("#view-button").text("Скрыть доп.поля"); }); //показываем/скрываем поля в модальной форме /*$("#optional").hide(); $('#show_optional').on("click",function(){ $("#optional").show(); $("#show_optional").hide(); }); $("#hide_optional").on("click", function(){ $("#optional").hide(); $("#show_optional").show(); });*/ //получаем id для редактирования записи в БД /*$.datepicker.setDefaults( $.extend( $.datepicker.regional['ru'] ) );*/ $("#time_start, #time_end").datepicker(); $("#filter_submit_btn").on("click", function (event) { //if ($("#month_value").val()==="выберите_месяц"){ //event.preventDefault(); // } }); $("#getMyNotesForToday").on('click', function () { if ($('#pam111').val() != "no_select") { $("#ajaxPagination").hide(); $('.ajax_loader').show(); $('#dataTable').css('position:absolute;') var WorkerId = $("#pam111").val(); $.ajax({ url: "getAjaxTable.php", type: "POST", data: ("WorkerId=" + WorkerId + "&getMyNotesForToday=" + '1'), beforeSend: function () { $('#dataTable').empty(); }, success: function (html) { setTimeout(function () { $('#dataTable').append(html); $('.ajax_loader').hide(); $('#dataTable').css('position:relative;') $('#backToMyNotes').show(); }, 2000); } }); } else { alert('выберите сотрудника!'); } }); $(document).on('click', '.pagination-css', function (e) { e.stopPropagation() var totalRecords = total; var page = parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); $.ajax({ url: "getAjaxTable.php", type: "post", data: ("page=" + page), beforeSend: function () { $('#dataTable').empty(); $('.ajax_loader').show(); }, success: function (html) { setTimeout(function () { $('#view-button').text('Показать поля'); $('#sidePanel').show(); $('#dataTable').empty(); $('#dataTable').append(html); $('.ajax_loader').hide(); $('#dataTable').css('position:relative;') }, 100); } }); $.ajax({ url: "ajaxPagination.php", type: "post", data: ("page=" + page + "&totalRecords=" + totalRecords), beforeSend: function () { $("#ajaxPagination").empty(); }, success: function (html) { $("#ajaxPagination").append(html); } }); }); }); $(document).on('keyup', function () { $('select').select2('close'); });
import { combineReducers, configureStore } from '@reduxjs/toolkit'; import { appSlice } from '../Pages/home/homeSlice'; import { listSlice } from '../Pages/list/listSlice'; const rootReducer = combineReducers({ details: appSlice.reducer, listdetails: listSlice.reducer, }); export const store = configureStore({ reducer: rootReducer, });
// This source file will have some operations. // 1. Create a valid group of elements // Let's say we have an array of arrays and we want the first and second element of each array. // e.g. [88, 99, 200] we want to have [88, 99], so we need to remove the third element in each array. // We want all the valid elements in one single array. const sample1 = [ [88, 99, 200], [12, 12, 200], [44, 99, 100], [88, 33, 100], [11, 90, 100], ]; const createValidArray = (sample) => { const flatArray = sample.flat(); var j = 0; var x = 0; for (i = 2; j < flatArray.length; i += 3) { flatArray.copyWithin(x, j, i); j = i + 1; x += 2; } return flatArray.splice(0, x); }; console.log(sample1); const validSample = createValidArray(sample1); console.log(validSample) // Output: [88, 99, 12, 12, 44, 99, 88, 33, 11, 90] // 2. To be continued...
import Carousel from 'react-bootstrap/Carousel' ; import {Row, Col} from 'react-bootstrap'; import "./Country.css"; import axios from 'axios'; import { useState, useEffect } from "react"; const Country = () => { const [userDatas, setUserDatas] = useState([]); useEffect(()=>{ axios.get('https://restcountries.com/v3/region/asia').then((res)=>{ const allTests = res.data; setUserDatas(allTests); }); },[userDatas]); return ( <div className="testimonial"> <Carousel> {userDatas.map((user)=>( <Carousel.Item> <img style={{'height':"300px"}} className="d-block w-100" src={'assets/img/R.jpeg'}/> <Carousel.Caption className="testimonialcaption"> <p><bold className="name">{user.name.common}</bold> <small className="location" style={{'color':'black'}}>{user.location}</small></p> <Row className="user" style={{'marginTop':'5vh'}}> <Col md={2}> <img className="flag" src={user.flags[1]}/> </Col> <Col md={6}> <div className="personalinfo"> <p><div className="rating">Capital: {user.capital}</div> <div className="rating">Region: {user.region}</div> <div className="rating">Sub Region: {user.subregion}</div></p> </div> </Col> </Row> <p className="message"> <i className="fas fa-quote-left"></i>{user.name.common} having an area of {user.area} is bordered by nations which include: {user.borders}.<br></br>The people here mostly speak {user.languages.key}<i className="fas fa-quote-right"></i></p> </Carousel.Caption> </Carousel.Item> ))} </Carousel> </div> ); } export default Country;
var slashcommand = require('./index'); var hemera = require('../hemera'); var whitelist = require('../utils/10amwhitelist'); var controller; /** * Responds to the 10AM slash command * @param {Object} bot * @param {Object} message */ module.exports = function (bot, message) { console.log('[HEMERA] Got a 10AM update'); console.log(message); controller = slashcommand.getController(); botHemera = hemera.getBot(); // Get the user object that is making the request controller.storage.users.get(message.user, function(err, user) { if (err) { bot.res.send('Ooops, there was an error. How embarassing. ' + err.toString()); console.trace(err); return; } if (!user || !user.slackUser) { botHemera.replyPrivate('I don\'t know you yet. Why don\'t you say "@hemera hi" and introduce yourself.'); return; } // Record the last time the user made an update and what that update was user.lastUpdate_at = new Date(); user.lastUpdate = message.text; controller.storage.users.save(user, function(err) { if (err) { console.trace(err); bot.res.send('Ooops, there was an error. How embarassing. ' + err.toString()); return; } // Send their update to our main 10AM channel var publicUpdate = '*' + user.slackUser.name + '\'s* plan for the day is: \n' + '>>> ' + message.text; botHemera.api.chat.postMessage({ channel: process.env.NODE_ENV === 'production' ? '10am' : '10amtest', text: publicUpdate, as_user: true }, function(err) { if (err) { console.trace(err); bot.res.send('Ooops, there was an error. How embarassing. ' + err.toString()); return; } // Respond to the API at this point so the rest is done after the request bot.res.send('OK, I will post your update!'); console.log('[HEMERA] posted 10am update to public slack channel'); // Now send a PM to each of our users with that update controller.storage.users.all(function(err, users) { if (err) { console.trace(err); return; } if (users && users.length) { for (var i = 0; i < users.length; i++) { var recipient = users[i]; if (recipient.slackUser && recipient.slackUser.is_bot) { console.log('[HEMERA] Not posting a message to another bot: %s', recipient.slackUser.name); continue; } // Only process our whitelist if (whitelist.indexOf(recipient.slackUser.name) === -1) { console.log('[HEMERA] Not posting a message to a user not in the beta: %s', recipient.slackUser.name); continue; } // Don't send a message to the user that's posting the update if (recipient.id === user.id) { console.log('[HEMERA] Not posting a message to myself: %s', user.slackUser.name); continue; } // Don't send a message to this person if they snoozed the user posting the update if (recipient.snooze && recipient.snooze.length && recipient.snooze.indexOf(user.slackUser.name) > -1) { console.log('[HEMERA] Not posting a message to %s because they are being snoozed by %s', user.slackUser.name, recipient.slackUser.name); continue; } // Open an IM channel and post to it console.log('[HEMERA] Posting a private message to: %s', recipient.slackUser.name); botHemera.api.im.open({ user: process.env.NODE_ENV === 'production' ? recipient.id : 'U03TC9WA9', }, function (err, res) { if (err) { console.trace(err); return; } console.log(res); var channelId = res.ok ? res.channel.id : null; if (channelId) { botHemera.api.chat.postMessage({ channel: channelId, text: publicUpdate, as_user: true }, function(err, res) { if (err) { return console.trace(err); } console.log(res); }); } }); } } }); }); }); }); };
let result = 0; const memo = []; function solution(user_id, banned_id) { const banned_list = banned_id.map(bannedId => bannedId.replace(/\*/g,'.')); const visit = [...user_id].fill(false); dfs(user_id, banned_list,0, 0, visit); return result; } function dfs(user_id, banned_id, idx, n, visit){ const visited = [...visit]; const regex = RegExp(`\^${banned_id[idx]}\$`); if(n === banned_id.length){ const temp = []; visited.forEach((v,i) => v && temp.push(user_id[i])); let cnt = 0; memo.forEach(array => { let flag; for(let i = 0 ; i < temp.length ; i++){ flag = array.some(element => element === temp[i]); if(!flag){ break; } } !flag && cnt++; }); if(cnt === memo.length){ memo.push(temp); result++; } return; } user_id.filter((id, index) => { if(regex.test(id)){ if(!visited[index]){ visited[index] = true; dfs(user_id, banned_id, idx+1, n+1, visited); visited[index] = false; } } }); } console.log(solution(["frodo", "fradi", "crodo", "abc123", "frodoc"],["fr*d*", "abc1**"]))
import React, { Fragment } from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import { Backdrop } from './Backdrop'; import CancelRequest from './CancelRequest'; import ErrorPrompt from './ErrorPrompt'; import ModalFooter from './ModalFooter'; import ModalHeader from './ModalHeader'; import ModalContent from './ModalContent'; import { serviceQuestions as questionnaire } from './Questionnaires/index'; const ModalBody = styled.div` position: absolute; display: flex; flex-direction: column; min-height: 320px; background: ${({ isBlue }) => (isBlue ? '#009fd9' : '#fafafa')}; top: 50%; left: 50%; transform: translate(-50%, -47%); width: 100%; z-index: 1100; min-width: 100%; height: 90%; @media (min-width: 601px) { min-width: 600px; width: 600px; } @media (min-width: 701px) { height: 70vh; } `; class Modal extends React.Component { state = { currentSlide: 0, currentType: null, answers: {}, validation: null, displayError: false, serviceQuestions: {}, }; componentWillMount() { window.onscroll = function() { window.scrollTo(0, 0); }; } componentDidMount() { const { whichService } = this.props; const validation = {}; const { currentSlide } = this.state; const currentType = questionnaire[whichService][currentSlide].type; const answerKeys = questionnaire[whichService] .filter(q => Object.prototype.hasOwnProperty.call(q, 'question')) .reduce((acc, curr) => { acc[curr.question] = null; validation[curr.question] = { isValid: false, }; return acc; }, {}); this.setState({ answers: answerKeys, validation, serviceQuestions: questionnaire[whichService], currentType, }); } componentWillUnmount() { window.onscroll = null; } updateTextFieldValueHandler = (question, e) => { const newInputValue = e.target.value; const { serviceQuestions } = this.state; const { answers, displayError, currentSlide, validation } = this.state; const { validation: typeOfSlideValidation } = serviceQuestions[currentSlide]; const isInputValid = this.validateTextInputs(newInputValue, typeOfSlideValidation); answers[question] = newInputValue; if (displayError && isInputValid) { const questionAnswerValid = { [question]: { isValid: true, }, }; this.setState({ displayError: false, validation: { ...validation, ...questionAnswerValid }, answers, }); } else { const questionAnswerValid = { [question]: { isValid: false, }, }; this.setState({ answers, validation: { ...validation, ...questionAnswerValid }, }); } this.setState({ answers, }); }; validateTextInputs = (input, validationType) => { switch (validationType) { case 'zipcode': return this.validateZipCode(input); case 'name': return this.validateName(input); case 'email': return this.validateEmail(input); default: return false; } }; validateZipCode = zipCode => /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipCode); validateEmail = email => /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email); validateName = name => name.trim().length >= 5; updateValueHandler = ([question, answer]) => { const { answers, currentType, validation } = this.state; const updatedAnswers = answers ? { ...answers } : {}; if (currentType !== 'multi') { updatedAnswers[question] = answer; } else { const answerList = updatedAnswers[question] ? [...updatedAnswers[question]] : []; if (answerList.includes(answer)) { updatedAnswers[question] = answerList.filter(a => a !== answer); } else { updatedAnswers[question] = [...answerList, answer]; } } const updatedValidation = { [question]: { isValid: true, wasTouched: true, }, }; this.setState({ answers: { ...updatedAnswers, }, validation: { ...validation, ...updatedValidation }, displayError: false, }); }; submitAnswers = () => { // const { answers } = this.state; }; nextSlide = e => { e.preventDefault(); const { currentSlide, currentType, validation, answers, serviceQuestions } = this.state; const { validation: typeOfSlideValidation } = serviceQuestions[currentSlide]; if (currentType === 'intro' || typeOfSlideValidation === '') { this.setState(prevState => ({ currentSlide: prevState.currentSlide + 1, currentType: serviceQuestions[prevState.currentSlide + 1].type, })); return; } const currentQuestion = serviceQuestions[currentSlide].question; let { isValid } = validation[currentQuestion]; if (['name', 'email', 'zipcode'].includes(typeOfSlideValidation)) { isValid = this.validateTextInputs(answers[currentQuestion], typeOfSlideValidation); } if (isValid) { this.setState(prevState => ({ currentSlide: prevState.currentSlide + 1, currentType: serviceQuestions[prevState.currentSlide + 1].type, displayError: false, })); } else { this.setState({ displayError: true }); } }; previousSlide = e => { e.preventDefault(); this.setState(prevState => ({ currentSlide: prevState.currentSlide - 1, currentType: prevState.serviceQuestions[prevState.currentSlide - 1].type, displayError: false, })); }; render() { const { closeModal, showCloseRequest, continueRequest, showCancelRequest } = this.props; const { currentSlide, answers, displayError, serviceQuestions } = this.state; const { type, question, options, professionalsToFind, nextButtons, validationMessage } = serviceQuestions[currentSlide] || {}; return ( <Fragment> <form> <ModalBody isBlue={type === 'intro'}> <ModalHeader isBlue={type === 'intro'} showCancelRequest={showCancelRequest} /> <ModalContent answers={answers[question]} type={type} question={question} options={options} updateValue={this.updateValueHandler} professionalsToFind={professionalsToFind} updateTextFieldValue={this.updateTextFieldValueHandler} /> {displayError ? <ErrorPrompt validationMessage={validationMessage} /> : null} <ModalFooter validationMessage={validationMessage} displayError={displayError} nextSlide={this.nextSlide} previousSlide={this.previousSlide} submitAnswers={this.submitAnswers} option={nextButtons} answers={answers[question]} isBlue={type === 'intro'} /> {showCloseRequest ? ( <CancelRequest percent={15} cancelRequest={closeModal} continueRequest={continueRequest} /> ) : null} </ModalBody> </form> <Backdrop /> </Fragment> ); } } Modal.propTypes = { closeModal: PropTypes.func.isRequired, continueRequest: PropTypes.func.isRequired, showCloseRequest: PropTypes.bool.isRequired, showCancelRequest: PropTypes.func.isRequired, }; export default Modal;
/*****************************************************************************/ /* MasterLayout: Event Handlers */ /*****************************************************************************/ Template.MasterLayout.events({ 'submit #search': function(event) { event.preventDefault(); var listOptions, value, userIds; listOptions = Session.get('listOptions'); //Search value value = $('[name=search]').val(); if (value.toLowerCase().startsWith('userid:') && value.split(':').length === 2) { delete listOptions.filters.$or; listOptions.filters.owner = value.split(':')[1].trim(); } else { delete listOptions.filters.owner; value = '.*' + common.escapeRegExp(value) + '.*'; //Searching value in users names userIds = _.pluck( Meteor.users.find({ $or: [{ 'profile.firstName': { $regex: value, $options: 'i' } }, { 'profile.lastName': { $regex: value, $options: 'i' } }] }, { fields: { _id: 1 } }).fetch(), '_id'); //Adding found users, name and description to the filter listOptions.filters['$or'] = [{ name: { $regex: value, $options: 'i' } }, { owner: { $in: userIds } }, { description: { $regex: value, $options: 'i' } }]; } Session.set('listOptions', listOptions); if (Router.current().route.getName() === 'home') { PublicationsPagination.set(Session.get('listOptions')); } else { Router.go('home'); } }, 'click #login-buttons-edit-profile': function() { Router.go('show_profile', { _id: Meteor.userId() }); } }); /*****************************************************************************/ /* MasterLayout: Lifecycle Hooks */ /*****************************************************************************/ Template.MasterLayout.onCreated(function() { if (!Session.get('listOptions')) { Session.set('listOptions', { sort: { createdAt: -1 }, filters: { } }); } });
// The main JavaScript file for the Child Flashcards Vue app // Define our routes const routes = [ { path: '/', component: VueCompEntryPage }, { path: '/num-0-100', component: VueCompNum0100 }, { path: '/num-tens', component: VueCompNumTens }, { path: '/letters-upper', component: VueCompLettersUpper }, { path: '/letters-lower', component: VueCompLettersLower }, { path: '/colors', component: VueCompColors }, { path: '/shapes', component: VueCompShapes }, { path: '/words', component: VueCompWords }, ] // Create our Vue router const router = new VueRouter({ routes: routes, // short for `routes: routes` mode: 'hash', // We use hash b/c to work in GitHub pages. History mode looks better if you can redirect 404 pages. }); const app = new Vue({ router, data: function () { return {}; }, }).$mount('#app')
import { Fragment } from "react"; import Head from "next/head"; import Link from "next/link"; import Blog from "../components/Blog"; import Projects from "../components/Projects"; import Language from "../components/Language"; import Buttons from "../components/ui/Buttons"; import Heading from "../components/ui/Heading"; import { dehydrate, QueryClient } from "react-query"; import { languageQuery, projectQuery, blogQuery, aboutQuery, } from "../utils/helpers/querys"; import { fetchQuery } from "../utils/functions/fetchQuery"; import { features } from "../utils/helpers/features"; import { BiFile } from "react-icons/bi"; import { useData } from "../context/DataContext"; import HorizontalRule from "../components/ui/HorizontalRule"; export default function Home() { const { projects } = useData(); return ( <main className=" overflow-hidden"> <Head> <title>Ashraf Chowdury | Front-End Developer</title> <meta name="description" content="Hi, I'm Ashraf Chowdury and I'm a Front-End Developer. I like to build excellent Web applications using Javascript and React.js. Currently, I am focused on empowering myself by learning some new technologies that will help me to better myself in my future journey." /> </Head> <header className=" relative flex flex-col-reverse lg:flex-row items-center justify-start lg:justify-between text-center lg:text-start mt-10 md:mt-20"> <section className=" xl:w-[800px] lg:w-[550px] mt-7 sm:mt-12 lg:mt-0 flex flex-col lg:items-start items-center"> <div className=" w-auto border border-hLight dark:border-hDark rounded-full pl-3 pr-5 py-2 flex items-center space-x-2 mb-4"> <span class="relative flex h-3 w-3"> <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span> <span class="relative inline-flex rounded-full h-3 w-3 bg-primary opacity-90"></span> </span> <p className="heading md:text-sm text-xs font-semibold uppercase"> Open To Work </p> </div> <h1 className=" capitalize text-3xl sm:text-[40px] md:text-5xl xl:text-6xl leading-[45px] sm:leading-[55px] md:leading-[65px] lg:leading-[68px] xl:leading-[80px] font-bold mb-2 sm:mb-3 md:mb-5 lg:mb-4 xl:mb-1"> Journey of a <span className="heading ">Front-End</span> Developer, </h1> <p className="custom_text w-[95%] sm:w-[78%] lg:w-[90%] text-sm md:text-[16px] xl:text-lg leading-6 md:leading-7 lg:leading-7 xl:leading-8 mx-auto lg:mx-0"> {"I'm"} Ashraf Chowdury, {"I've"} been learning the art of Frontend development by building things and contributing to open-source. </p> <div className="flex items-center justify-center lg:justify-start space-x-2 md:space-x-4 mt-8 sm:mt-12 lg:mt-16 mb-16 sm:mb-20 lg:mb-28"> <a href="resume_ashrafchowdury.pdf" download={true}> <Buttons style=" !bg-primary py-2 sm:!py-3 px-4 sm:!px-5 !text-light"> <BiFile className="mr-1 sm:mr-2 text-[16px] " /> Get Resume </Buttons> </a> <Buttons link="/contact" style=" !bg-transparent border border-hLight dark:border-hDark py-2 sm:!py-3 px-5 sm:!px-6" > Contact Me </Buttons> </div> <div className=" flex items-center justify-center lg:justify-start"> <p className="text-xs md:text-sm lg:text-[16px] "> Current Stack -{" "} </p> <img src="https://skillicons.dev/icons?i=typescript,nextjs,tailwind,appwrite,vscode,figma&theme=light" alt="tech" className=" hidden dark:block w-24 md:w-32 ml-3" loading="lazy" /> <img src="https://skillicons.dev/icons?i=typescript,nextjs,tailwind,appwrite,vscode,figma&theme=dark" alt="tech" className=" block dark:hidden w-24 md:w-32 ml-3" loading="lazy" /> </div> </section> <img src="./ashraf_chowdury_hero.png" alt="ashraf chowdury" className=" xl:w-[580px] lg:w-[500px] md:w-[550px] sm:w-[450px] w-full -mt-4 sm:-mt-5 md:-mt-8 lg:-mt-12 w-full rounded-xl hover:scale-105 duration-200" /> </header> <HorizontalRule /> <section className="relative flex flex-wrap items-center justify-center mt-20 mb-24"> <div className="gradiant lg:top-[20px] top-[0px] left-[55%] -translate-x-1/2 lg:w-[460px] w-[300px] lg:h-[460px] h-[300px] bg-[#B50121]"></div> <div className="gradiant lg:top-[-80px] top-[50px] left-[40%] -translate-x-1/2 lg:w-[400px] w-[250px] lg:h-[400px] h-[250px] bg-[#6016FC]"></div> {features.map((data) => { return ( <div className=" xl:w-[425px] lg:w-[320px] md:w-[320px] w-[90%] bg-hLight dark:bg-hDark xl:mx-3 lg:mx-2 lg:mt-0 m-2 rounded-lg xl:p-10 lg:p-7 md:p-8 sm:p-7 p-5" key={data.title} > <div className=" lg:w-[50px] lg:h-[50px] sm:w-[45px] sm:h-[45px] w-10 h-10 flex items-center text-dark dark:text-white justify-center rounded-lg lg:text-2xl sm:text-xl bg-hLight dark:bg-hDark"> <data.icon /> </div> <p className=" xl:text-lg sm:text-[16px] text-sm font-semibold lg:mt-6 sm:mt-4 mt-3 lg:mb-3 md:mb-2 sm:mb-4 mb-3"> {data.title} </p> <p className=" text-xs sm:text-sm lg:text-[16px] md:leading-6 font-light break-all leading-5 sm:leading-normal"> {data.about} </p> </div> ); })} </section> <Heading title="Recent Works" style=" mt-24 md:mt-32 lg:mt-52 mb-16 md:mb-20 lg:mb-28" about="Projects I had recently worked on" /> <section className="flex flex-col items-center"> {projects ?.filter((val) => val.project_id < 4) .map((value) => { return ( <Fragment key={value._id}> <Projects data={value} /> </Fragment> ); })} </section> <HorizontalRule /> <Heading title="My Ecosystem" style="mb-12 sm:mb-16 md:mb-20" about="I used these technologies to build my projects" /> <section className=" lg:w-[80%] xl:w-[70%] mx-auto relative "> <div className="gradiant lg:top-[-100px] left-[50px] lg:w-[520px] w-[300px] lg:h-[520px] h-[300px] bg-[#fca016]"></div> <div className="gradiant lg:top-[250px] left-1/2 lg:w-[400px] w-[250px] lg:h-[400px] h-[250px] bg-[#16fcd2]"></div> <Language /> </section> <HorizontalRule /> <Heading title="Latest Article" style="mb-12 sm:mb-16 md:mb-20" about="Latest articles I published on Hashnode" /> <article className=" flex flex-col space-y-4 items-center relative"> <div className="gradiant lg:top-[-100px] left-[50px] lg:w-[520px] w-[300px] lg:h-[520px] h-[300px] bg-[#fca016]"></div> <div className="gradiant lg:top-[250px] left-1/2 lg:w-[400px] w-[250px] lg:h-[400px] h-[250px] bg-[#16fcd2]"></div> <Blog /> </article> </main> ); } export async function getServerSideProps() { //setup the Query Client to fetch the data in sercer side const queryClient = new QueryClient(); //Requests for fetching author data for Sanity await fetchQuery(queryClient, "blog", blogQuery); await fetchQuery(queryClient, "language", languageQuery); await fetchQuery(queryClient, "project", projectQuery); await fetchQuery(queryClient, "about", aboutQuery); //dehydrate the setching data return { props: { dehydratedState: dehydrate(queryClient), }, }; }
import React, { Component, Fragment } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../store/actions/index'; import Toolbar from '../../components/Navigation/Toolbar/Toolbar'; import SideDrawer from '../../components/Navigation/SideDrawer/SideDrawer'; class Layout extends Component { state = { showSideDrawer: false, }; sideDrawerToggleHandler = _ => { this.setState(prevState => { return { showSideDrawer: !prevState.showSideDrawer }; }); }; sideDrawerClosedHandler = _ => { this.setState({ showSideDrawer: false }); }; render() { return ( <Fragment> <Toolbar toggleSideDrawer={this.sideDrawerToggleHandler} showSideDrawer={this.state.showSideDrawer} authenticated={this.props.authenticated} orderPosted={this.props.orderPosted} resetOrder={this.props.resetOrder} close={this.sideDrawerClosedHandler} /> <SideDrawer showSideDrawer={this.state.showSideDrawer} toggleSideDrawer={this.sideDrawerToggleHandler} close={this.sideDrawerClosedHandler} orderPosted={this.props.orderPosted} authenticated={this.props.authenticated} resetOrder={this.props.resetOrder} /> <div className='body'>{this.props.children}</div> </Fragment> ); } } const mapStateToProps = state => { return { authenticated: state.auth.tokenId, orderPosted: state.order.orderPosted, }; }; const mapDispatchToProp = dispatch => { return { resetOrder: _ => dispatch(actions.resetOrder()), }; }; export default connect(mapStateToProps, mapDispatchToProp)(Layout);
// import mongoose from 'mongoose'; const mongoose = require("mongoose"); var FeatureSchema = mongoose.Schema({ data: { geometry: { type: { type: String, default: "Point" }, coordinates: [Number] }, properties: { id: Number, price: Number, street: String, bedrooms: Number, bathrooms: Number, sq_ft: Number } } }); module.exports = mongoose.model('Feature', FeatureSchema);
import React from 'react' import ReactDOM from 'react-dom' import { createStore, combineReducers, compose } from 'redux' import { Provider } from 'react-redux' import ui from './ui/reducers' import auth from './auth/reducers' import App from './App' import 'babel-core/polyfill' import 'whatwg-fetch' import 'semantic-ui-css/semantic' import 'semantic-ui-css/semantic.css' import 'toastr/build/toastr.css' import 'react-datepicker/dist/react-datepicker.css' var devTools = null var finalCreateStore = createStore if (DEBUG) { let createDevTools = require('redux-devtools').createDevTools let LogMonitor = require('redux-devtools-log-monitor') let DockMonitor = require('redux-devtools-dock-monitor') devTools = (() => { let DevTools = createDevTools( <DockMonitor toggleVisibilityKey='H' changePositionKey='Q' defaultIsVisible={false}> <LogMonitor /> </DockMonitor> ) finalCreateStore = compose( DevTools.instrument() )(createStore) return <DevTools /> })() } let store = finalCreateStore(combineReducers({ ui, auth })) ReactDOM.render( <Provider store={store}> <div> {devTools} <App /> </div> </Provider>, document.getElementById('root') )
import { Header, Footer, Img } from "./Elements"; const HowItWorks = () => { return ( <div className="generic howItWorks"> <Header /> <div className="content"> <h1>How it Works</h1> <section> <Img src="/how_it_works.png" /> </section> </div> <Footer /> </div> ); }; export default HowItWorks;
/** * 1 页面加载的时候 * 1 从缓存中获取购物车的数据 渲染到页面中 * 这些数据,checked=true * 2 微信支付 * 1 哪些人 哪些账号 可以实现微信支付 * 1 企业账号 * 2 企业账号的小程序后台中,必须给开发者添加上白名单 * 1 一个AppId可以同时绑定多个开发者 * 2 这些开发者就可以公用这个AppId和他的开发权限 * 3 支付按钮 * 1 先判断缓存汇总有没有token * 2 没有,跳转到授权页面,进行获取token * 3 有token * 4 创建订单,获取订单编号 * 5 已经完成了微信支付 * 6 手动删除缓存中 已经被选中了的商品 * 7 删除后的购物车数据,填充回缓存 * 8 再跳转页面 */ //引入 用来发送请求的 方法 一定要把路径补全 //引入自定义的promise函数,request表示导入函数返回 import { getSetting,chooseAddress,openSetting,showModal,showToast,requestPayment} from "../../utils/asyncWx.js"; //引入⽀持es7的async语法 import regeneratorRuntime from '../../lib/runtime/runtime'; import {request} from "../../request/index.js"; Page({ data:{ address:{}, cart: [], totalPrice: 0, totalNum: 0 }, // 相对onload,常用的动作就用onShow onShow(){ // 1 获取缓存中的收货地址信息 const address = wx.getStorageSync("address"); // 1 获取缓存中的购物车数据,这个cart数据从哪来的??? 在商品详情goods_detail点击购物车时加入了缓存 // wx.getStorageSync("cart") || []:表示若wx.getStorageSync("cart")为空就等于[] let cart = wx.getStorageSync("cart") || []; // 过滤后的购物车数组 相对也结算页面最大的区别就在这 cart= cart.filter(v => v.checked) this.setData({address}); // 设置购物车状态同时,重新计算,底部工具栏的数据,全选,总价格,购买的数量 // 里面又调用setData // 总价格,总数量 let totalPrice = 0; let totalNum = 0; cart.forEach(v => { if(v.checked){ totalPrice += v.num * v.goods_price; totalNum += v.num; } }) this.setData({ cart, totalPrice, totalNum, address }); wx.setStorageSync("cart",cart); }, // 点击支付 async handleOrderPay(){ try { // 1 判断缓存中有没有token // const token = wx.getStorageSync("token"); // 在这里写假冒的token是可以的,注意这是假的!!! const token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo"; // 2 判断 if(!token){ wx.navigateTo({ url: '/pages/auth/index' }); return; } // 3 创建订单 // 3.1 准备请求头参数 // const header = {Authorization: token}; // 3.2 准备,请求体参数 const order_price = this.data.totalPrice; const consignee_addr = this.data.address.all; const cart = this.data.cart; let goods = []; cart.forEach(v => goods.push({ goods_id : v.goods_id, goods_number : v.num, goods_price : v.goods_price })) const orderParams = {order_price,consignee_addr,goods}; // 4 准备发送请求,创建订单,获取订单编号 // const order_number = await request({url:"/my/orders/create",method:"POST",data:orderParams}); // 上一行的变量order_number加上{ }有什么作用? const { order_number } = await request({ url: "/my/orders/create", method: "POST", data: orderParams }); //5 发起预支付接口 const {pay} =await request({url:"/my/orders/req_unifiedorder",method:"POST",data:{order_number}}) //6 进行微信扫码支付,这一步会弹出支付二维码,但是由于我的是假的token,所以这一步开始动不了了!!! await requestPayment(pay); // 7 查询后台 订单状态 const res = await request({ url: "/my/orders/chkOrder", method: "POST", data: { order_number }}); await showToast({ title: "支付成功" }); // 8 手动删除缓存中 已经支付了的商品,注意这里是先拿还没有过滤掉的cart购物车数据 let newCart=wx.getStorageSync("cart"); //过滤,留下来未被选中的 newCart=newCart.filter(v=>!v.checked); wx.setStorageSync("cart", newCart); // 8 支付成功了 跳转到订单页面 wx.navigateTo({ url: '/pages/order/index' }); } catch (error) { // await showToast({ title: "支付失败" }) const title = "支付失败,但既然给我了,那我就收下了: -" + this.data.totalPrice + "¥" await showToast({ title: title }) console.log(error); // 注意,这里主要是为了测试,所以支付失败也会跳转到成功页面!!!!! //============================================================================= // 8 手动删除缓存中 已经支付了的商品,注意这里是先拿还没有过滤掉的cart购物车数据 // let newCart=wx.getStorageSync("cart"); // //过滤,留下来未被选中的 // newCart=newCart.filter(v=>!v.checked); // wx.setStorageSync("cart", newCart); // // 8 支付成功了 跳转到订单页面 // wx.navigateTo({ // url: '/pages/order/index' // }); //============================================================================= } } })
import React from 'react'; import { storiesOf } from '@storybook/react'; import { select, text } from '@storybook/addon-knobs'; import TextOrInput from './index'; import Card from '../_storybookWrappers/Card'; const stories = storiesOf('Components|TextOrInput', module).addParameters({ component: TextOrInput, componentSubtitle: 'Displays a TextOrInput component', }); const typesSelect = (defaultValue = 'text') => select( 'type', { text: 'text', phone: 'phone', number: 'number', }, defaultValue, ); const canEditSelect = (defaultValue = true) => select( 'canEdit', { true: true, false: false, }, defaultValue, ); stories.add('default', () => { const value = text('value', 'TextOrInput content'); const placeholder = text('placeholder', 'Placeholder'); return ( <Card center> <TextOrInput type={typesSelect()} canEdit={canEditSelect()} placeholder={placeholder}> {value} </TextOrInput> </Card> ); }); stories.add('phone', () => { const value = text('value', '+7931341792'); const placeholder = text('placeholder', 'Placeholder'); return ( <Card center> <TextOrInput type="phone" placeholder={placeholder} canEdit={canEditSelect()}> {value} </TextOrInput> </Card> ); }); stories.add('email', () => ( <Card center> <TextOrInput type="email">vlad@email.com</TextOrInput> </Card> ));
(function($, ls) { "use strict"; /* * Only gets called when we're using $('$el').flightStatus format */ var FlightStatus = function(el, customOptions) { var _ = this; _.$el = $(el).addClass('flight-status'); _.defaults = defaults; document.body.addEventListener('flightQuerySuccess'); _.async(customOptions, _.makeWidget); }; /* * Default Values */ var defaults = { urls: { arriving: 'https://flysmartapp.com/***/flight/SearchNextArrivingFlights', departing: 'https://flysmartapp.com/***/flight/SearchNextDepartingFlights' }, airport: null, cacheTime: 30, count: 10, serverSideScript: 'curl.php' }; /* * Async calls to API, broadcast customEvent 'flightQuerySuccess' when completed */ FlightStatus.prototype.async = function(customOptions, callback) { // start requesting var _ = this, options = $.extend(defaults, customOptions); _.requests = { arriving: null, departing: null }; _.listen(callback); _.pollAPI(customOptions, _.broadcast, 'arriving'); _.pollAPI(customOptions, _.broadcast, 'departing'); }; /* * Listen for 'flightQuerySuccess' events. If we have successfully retrieved * data for each search term, make widget */ FlightStatus.prototype.listen = function(callback) { var _ = this; document.body.addEventListener('flightQuerySuccess', function() { var requestsComplete; for(var direction in _.requests) { if(_.requests.hasOwnProperty(direction)) { requestsComplete = _.requests[direction] ? true : false; } } if(requestsComplete) callback.call(_, _.requests); }); }; FlightStatus.prototype.broadcast = function() { document.body.dispatchEvent(new CustomEvent('flightQuerySuccess')); }; /* * Main API polling function */ FlightStatus.prototype.pollAPI = function(customOptions, callback, direction) { var _ = this, options = $.extend(defaults, customOptions), url = _.makeURL(options, direction), data = ls ? ls.get(url, options.cacheTime) : false; _.options = options; if(data) { _.requests[direction] = data; callback.call(_, data); return false; } try{ $.ajax({ url: options.serverSideScript, data: $.param({ url: url, type: 'json' }), success: function(data) { if(data.error) { console.log('Error querying API: ', data.error); return false; } data = JSON.parse(data); if(ls) ls.set(url, data); if(callback) { _.requests[direction] = data; callback.call(_, data); } }, error: function(e) { console.log(e); } }); } catch(e) { console.log(e); } }; FlightStatus.prototype.makeURL = function(options, direction) { return options.urls[direction].replace('***', options.airport); }; FlightStatus.prototype.makeWidget = function() { var _ = this, data = _.requests, $widget = $('<div></div>'), $header = $('<div class="toggles"></div>'); for(var direction in _.requests) { if(_.requests.hasOwnProperty(direction)) { var arriving = direction == 'arriving'; $header.append($('<span data-toggle="' + direction + '">' + direction + '</span>')); var $current = $('<div data-type="' + direction + '"></div>'); if (!data[direction]) return false; var flights = data[direction].List; for(var i = 0; i < _.options.count; i++) { var airport = !arriving ? flights[i].ArrivalAirportCode : flights[i].DepartureAirportCode, number = flights[i].FlightNumber, status = flights[i].Status == 'Delayed' ? 'delayed' : 'on-time', arr = flights[i].Time.split(':'), ampm = ' AM'; if(arr[0] > 12) { arr[0] = arr[0] - 12; ampm = ' PM'; } var time = arr.join(':') + ampm; $current .append($( '<div class="flight">' + '<span class="time">' + time + '</span>' + '<span class="number ' + status + '">' + number + '</span>' + '<span class="airport">' + airport + '</span>' + '</div>' )); } $widget.append($current); } } $header.prependTo($widget); $widget.find('[data-type]').eq(0).addClass('active'); $widget.find('[data-toggle]').eq(0).addClass('active'); $widget.find('[data-toggle]').click(function() { var $_ = $(this); $widget.find('.active').removeClass('active'); var toggle = $_.addClass('active').data('toggle'); $widget.find('[data-type="' + toggle + '"]').addClass('active'); }); _.$el.append('<p class="title">Flight Status</p>').append($widget); }; FlightStatus.prototype.poll = function(options, callback) { FlightStatus.prototype.async(options, callback); }; // Extend JQuery fn for $('$id').flightStatus() $.fn.flightStatus = function(options) { return this.each(function() { (new FlightStatus(this, options)); }); }; // Extend JQuery for $.flightStatus() // ONLY prototype(static) methods $.extend({ flightStatus: FlightStatus.prototype }); })(jQuery, typeof lsLite != 'undefined' ? lsLite : null);
class SleepRepository { constructor(sleepData, id) { this.sleepData = sleepData; this.id = id; this.user = this.getSleepData(); } getSleepData() { return this.sleepData.filter(user => user.userID === this.id); } getAllTimeAvg() { const totalHrs = this.user.reduce((totalHours, day) => { totalHours += day.hoursSlept; return totalHours; }, 0); return Math.round(totalHrs / this.user.length); } getQualitySleepAvg() { const sleepQualAvg = this.user.reduce((sleepQual, day) => { sleepQual += day.sleepQuality; return sleepQual; }, 0); return parseFloat((sleepQualAvg / this.user.length).toFixed(1)); } getDailySleepHours(date) { return this.user.find(day => day.date === date).hoursSlept; } weeklySleepData(date, user = this.user) { let i = user.findIndex(day => day.date === date); return this.user.slice(i - 6, i + 1); } getWeeklyHours(date) { return this.weeklySleepData(date).map(day => { return { date: day.date, hoursSlept: day.hoursSlept }; }); } getWeeklyQuality(date) { return this.weeklySleepData(date).map(day => { return { date: day.date, sleepQuality: day.sleepQuality }; }); } getAvgQuality() { const avgQual = this.sleepData.reduce((totalQual, day) => { totalQual += day.sleepQuality; return totalQual; }, 0); return parseFloat((avgQual / this.sleepData.length).toFixed(1)); } getAllIds() { return this.sleepData.reduce((idHolder, log) => { !idHolder.includes(log.userID) && idHolder.push(log.userID); return idHolder; }, []); } getBestSleepers(date) { let sorted = []; this.getAllIds().forEach(id => { let userLogs = this.sleepData.filter(log => log.userID === id); sorted.push(userLogs); }); let allWeeklyData = sorted.reduce((accumulator, user) => { let i = user.findIndex(log => log.date === date); accumulator.push(user.slice(i - 6, i + 1)); return accumulator; }, []); let allAverages = allWeeklyData.reduce((acc, user) => { let avgQual = user.reduce((totalQual, day) => { totalQual += day.sleepQuality; return totalQual; }, 0); acc.push( { id: acc.length + 1, avgQual: parseFloat((avgQual / 7).toFixed(1)) }); return acc; }, []); return allAverages.filter(user => user.avgQual > 3); } getMaxSleepers(date) { let specificDate = this.sleepData.filter(day => day.date === date); let maxSleepHours = Math.max.apply(Math, specificDate.map((log) => { return log.hoursSlept; })); return specificDate.filter(user => user.hoursSlept === maxSleepHours); } weeklyAvgHours(date) { let weeklySleep = this.weeklySleepData(date) let totalWeeklyHours = weeklySleep.reduce((totalHours, day) => { totalHours += day.hoursSlept; return totalHours; }, 0); return parseFloat((totalWeeklyHours / 7).toFixed(1)); } } if (typeof module !== 'undefined') { module.exports = SleepRepository; }
import React from 'react'; import {View, Text, StyleSheet} from 'react-native'; import Color from '../constants/color' import TitleText from '../components/TitleText' const Header = props => { return ( <View style={styles.header}> <TitleText style={styles.headerTitle}>{props.title}</TitleText> </View> ) }; const styles = StyleSheet.create({ header:{ width: '100%', height: 90, paddingTop:36, backgroundColor:Color.primary, alignItems: 'center', justifyContent:'center' } }) export default Header;
import React, { Component } from "react"; import { NavLink } from "react-router-dom"; import Logo from "../components/Logo"; import Button from "../components/Button"; import DropDown from "../components/DropDown"; const options = ["one", "two", "three"]; class Navigation extends Component { constructor(props) { super(props); this.state = { hide: false, nav: [ { name: "home", link: "/", }, { name: "features", link: "/features", }, { name: "getting started", link: "/getting_started", }, ], }; } handeleHide = () => { this.setState({ hide: !this.state.hide }); }; render() { const { nav, hide } = this.state; return ( <> <nav className="main-nav"> <i onClick={this.handeleHide} className="fas fa-bars"></i> <Logo /> <ul> {nav.map((nav, i) => ( <NavLink key={i} style={{ textDecoration: "none", color: "black" }} to={nav.link} activeClassName="active-nav" > <li>{nav.name}</li> </NavLink> ))} <DropDown /> </ul> <NavLink to="/demo" style={{ textDecoration: "none", color: "white" }} > <Button /> </NavLink> </nav> <ul className={hide === false ? "re-nav" : "drop"}> <div> <i style={{ top: "20px", left: "20px", position: "fixed", fontSize: "1.5rem", display: hide === false ? "none" : "block", }} onClick={this.handeleHide} className="fas fa-times" ></i> {nav.map((nav, i) => ( <NavLink key={i} style={{ textDecoration: "none", color: "black" }} to={nav.link} activeClassName="active-nav" > <li>{nav.name}</li> </NavLink> ))}{" "} <div style={{ margin: "20px auto" }}> <DropDown /> </div> </div> </ul> </> ); } } export default Navigation;
"use strict"; /** * This example shows how to define different authn/authz methods for different routes. * * Example: * * - Try to call /aaa/hello. It will call "aaaAuthn" and "aaaAuthz" methods * http://localhost:3000/aaa/hello * * - Try to call /bbb/hello. It will call "bbbAuthn" and "bbbAuthz" methods * http://localhost:3000/bbb/hello * * - Try to call /ccc/hello. It will call "authenticate" and "authorize" original methods * http://localhost:3000/ccc/hello * */ let path = require("path"); let { ServiceBroker } = require("moleculer"); let ApiGatewayService = require("../../index"); const { UnAuthorizedError, ERR_NO_TOKEN, ERR_INVALID_TOKEN } = require("../../src/errors"); // Create broker let broker = new ServiceBroker({ logger: console }); // Load other services broker.loadService(path.join(__dirname, "..", "test.service")); // Load API Gateway broker.createService({ mixins: ApiGatewayService, settings: { routes: [ { path: "/aaa", authentication: "aaaAuthn", authorization: "aaaAuthz", aliases: { "GET hello": "test.hello" } }, { path: "/bbb", authentication: "bbbAuthn", authorization: "bbbAuthz", aliases: { "GET hello": "test.hello" } }, { path: "/ccc", authentication: true, authorization: true, aliases: { "GET hello": "test.hello" } } ] }, methods: { aaaAuthn() { this.logger.info("Called 'aaaAuthn' method."); }, aaaAuthz() { this.logger.info("Called 'aaaAuthz' method."); }, bbbAuthn() { this.logger.info("Called 'bbbAuthn' method."); }, bbbAuthz() { this.logger.info("Called 'bbbAuthz' method."); }, authenticate() { this.logger.info("Called original 'authenticate' method."); }, authorize() { this.logger.info("Called original 'authorize' method."); } } }); // Start server broker.start();
const sendMail = require("../my_modules/sendMail.js"); process.on('message', function(megObj){ console.log('message from parent: ' + megObj.meg); sendMail({"to":"1533165085@qq.com","subject":"nodeApp-LayUI exit","html":megObj.meg},function(err, info){ if(err){ console.log(err); process.send({"meg": 'www_err发送邮件失败'}); return; } process.send({"meg": 'www_err发送邮件成功'}); }); });
/**A string S of lowercase English letters is * given. We want to partition this string * into as many parts as possible so that * each letter appears in at most one part, * and return a list of integers representing * the size of these parts. Example 1: Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. Note: S will have length in range [1, 500]. S will consist of lowercase English letters ('a' to 'z') only. */ var partitionLabels = function(S) { if(!S || S.length === 0){ return S; } let map = new Map(), len = 0, arr = []; for(let i=0; i<S.length; i++){ map.set(S[i], i); } while(len < S.length){ let start = len, s=""; let end = map.get(S[start]); while(start <= end){ s += S[start]; end = Math.max(map.get(S[end]),map.get(S[start])); len++; start++; } arr.push(s.length); } return arr; }; console.log(partitionLabels("ababcbacadefegdehijhklij")); // [9, 7, 8] // "ababcbaca", "defegde", "hijhklij"
class Cell{ constructor(pos){//X and Y will be row and column number this.pos = pos; this.x = pos % colsRows; this.y = Math.floor(pos / colsRows); this.isVisited = false; this.walls = [true, true];//Top, Right } getNeighbors(){ let neighbors = []; neighbors.push(cells[getIndex(this.x, this.y - 1)]); neighbors.push(cells[getIndex(this.x + 1, this.y)]); neighbors.push(cells[getIndex(this.x, this.y + 1)]); neighbors.push(cells[getIndex(this.x - 1, this.y)]); return(neighbors.filter(x => x && !x.isVisited)); } show(){ fill(0, 255, 0); rect(this.x * sizeOfCell, this.y * sizeOfCell, sizeOfCell, sizeOfCell); } static removeWall(cell1, cell2){ let xDiff = cell2.x - cell1.x; let yDiff = cell2.y - cell1.y; if(xDiff > 0){ cell2.walls[1] = false; } else if(xDiff < 0){ cell1.walls[1] = false; } else if(yDiff > 0){ cell2.walls[0] = false; } else if(yDiff < 0){ cell1.walls[0] = false; } } } function getIndex(x,y){ if(x < 0 || x > colsRows - 1 || y < 0 || y > colsRows - 1){ return(-1); } else{ return(x + y * colsRows); } }
import React, { useState } from 'react' import TextField from '@material-ui/core/TextField' import Button from '@material-ui/core/Button' import useStyles from './searchform.styles' const SearchForm = (props) => { const [pokemon, handlePokemon] = useState('') const { onSubmit } = props const classes = useStyles() const handleChange = (event) => { handlePokemon(event.target.value) } return ( <div> <div className={classes.searchForm}> <TextField id="filled-basic" label="Search Pokemon by name" variant="outlined" className={classes.textField} onChange={handleChange} color="primary" /> <Button onClick={() => onSubmit(pokemon)} className={classes.searchButton} variant="contained" > Search </Button> </div> </div> ) } export default SearchForm
import React from 'react' import { compose } from 'redux'; import { withAuthentication, withNav } from '../../hoc' import { Navagation } from '../index.js' import MapContainer from './mapContainer.js' import './map.scss' class Map extends React.Component { state = { rangeSliderValue: 4 } handleSliderChange = (e) => { e.preventDefault(); this.setState({ rangeSliderValue: e.target.value }) } render () { return ( <div className = 'mapPage'> <div className='mapContainer'> { /* <div className='rangeFilter'> <span>Range:</span> <input type="range" min="1" max="5" value={this.state.rangeSliderValue} onChange={this.handleSliderChange} /> >= {this.state.rangeSliderValue} </div> */ } <MapContainer ratingFilterNum={this.state.rangeSliderValue} /> </div> </div> ); } } export default compose( withNav )(Map);
import React, {useState, useEffect} from 'react'; import { doctorAPI } from '../../api'; import Spinner from '../Spinner'; const Doctor = (props) => { const [doctorInfo, setDoctorInfo] = useState(undefined); const [id, setId] = useState(undefined); const [loading, setLoading] = useState(true); useEffect( () => { async function getDoctorInfo() { setId(props.match.params.id); const doctor = await doctorAPI.getDoctorInfo(id); setDoctorInfo(doctor); setLoading(false); } getDoctorInfo(); }, [] ) return ( <> {loading && < Spinner/>} {!loading && <div> <h5>{doctorInfo.name}</h5> <img src={`/img/doctors/${id}.jpg`} alt='Картинка' /> <p>{doctorInfo.about}</p> </div>} </> ) } export default Doctor;
function Player() { this.pos = createVector(width/2, height/2); this.r = 20; this.moveSpeed = 5; this.stamina = 100; this.health = 100; this.bearing = PI / 2; this.dead = false; this.update = function() { this.bearing = PI / 2 + atan2(mouseY-this.pos.y, mouseX-this.pos.x); // Angle towards mouse position if (debug.stamina) { this.stamina = 100; // Infinite stamina } if (debug.health) { this.health = 100; // Infinite health } // Sprint Function if (keyIsDown(16)) { if (this.stamina > 0) { this.moveSpeed = 10; // Set sprint speed if (this.stamina > 5) { this.stamina -= 1; // Drain stamina } } else { this.moveSpeed = 5; // Set speed back to walk speed if stamina drained } } else { this.moveSpeed = 5; // Set speed back to walk speed when not holding sprint button if (this.stamina < 100) { this.stamina += 1; // Refill stamina } } // Walk up if (keyIsDown(87)) { if (dist(0, this.pos.y, 0, 0) > this.r) { this.pos.y -= this.moveSpeed; } } // Walk down if (keyIsDown(83)) { if (dist(0, this.pos.y, 0, height) > this.r) { this.pos.y += this.moveSpeed; } } // Walk right if (keyIsDown(68)) { if (dist(this.pos.x, 0, width, 0) > this.r) { this.pos.x += this.moveSpeed; } } // Walk left if (keyIsDown(65)) { if (dist(this.pos.x, 0, 0, 0) > this.r) { this.pos.x -= this.moveSpeed; } } } this.show = function() { // Main player push(); translate(this.pos.x, this.pos.y); rotate(this.bearing); if (debug.collider) { noFill(); ellipse(0, 0, this.r) // Sphere Collider } fill(255); triangle(0, -15, 15, 15, -15, 15); // Actaull player if (pistol.equipped) { if (pistol.equipped) { fill(60, 150, 50); } else { fill(60, 90, 255); } strokeWeight(1); rect(0, 5, 5, 20); // Weapon } pop(); // Ammo text push(); fill(0); textAlign(CENTER); textSize(15); textFont(myFont) text(pistol.ammoClip + " / " + pistol.ammoPool, 208, height-6); // Print out ammo pop(); // Health bar strokeWeight(0) fill(255, 50, 50); rectMode(CORNER); rect(7, height-110, this.health*1.6, 55); // Stamina bar strokeWeight(0); fill(0, 180, 200); rectMode(CORNER); rect(7, height-55, this.stamina*1.6, 55); rectMode(CENTER); // Draw pickup text and equip if (dist(this.pos.x, this.pos.y, pistol.pos.x, pistol.pos.y) < 15+this.r) { textAlign(CENTER); if (!pistol.equipped) { fill(0); text("Press F", this.pos.x, this.pos.y+35); // If player is near the gun show pickup text } fill(255); if (keyIsDown(70)) { pistol.equipped = true; } } strokeWeight(2); } }
let price_value = document.getElementById('price_addend'); let setMinPriceTags = document.getElementById('setMinPriceTags'); let setMinPriceCats = document.getElementById('setMinPriceCats'); let setMinRate = document.getElementById('setMinRate'); let setMidPriceTags = document.getElementById('setMidPriceTags'); let setMidPriceCats = document.getElementById('setMidPriceCats'); let setMidRate = document.getElementById('setMidRate'); let upMinPriceTags = document.getElementById('upMinPriceTags'); let upMidPriceTags = document.getElementById('upMidPriceTags'); let upMidRate = document.getElementById('upMidRate'); let upMinPriceCats = document.getElementById('upMinPriceCats'); let upMidPriceCats = document.getElementById('upMidPriceCats'); let setCurrPriceTags = document.getElementById('setCurrPriceTags'); let setCurrPriceCats = document.getElementById('setCurrPriceCats'); let setCurrRate = document.getElementById('setCurrRate'); let setCurrPriceBiglCats = document.getElementById('setCurrPriceBiglCats') let setCurrPriceBiglOther = document.getElementById('setCurrPriceBiglOther') chrome.cookies.get({url: 'https://my.prom.ua', name: 'lid'}, function(cookies) { uid = cookies.value.split('-')[2]; chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.executeScript( tabs[0].id, { code: 'user_id='+uid+'; localStorage.setItem("user_id", '+uid+');' } ) }); }); chrome.cookies.get({url: 'https://my.prom.ua', name: 'csrf_token'}, function(cookies) { token = cookies.value; chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.executeScript( tabs[0].id, { code: 'csrf_token="'+token+'";' } ) }); }); function run_func(func) { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.executeScript( tabs[0].id, { code: func } ) }); }; setMinPriceTags.onclick = function() { run_func('price_value = 0;'); run_func('set_min_price("others", true)'); }; setMinPriceCats.onclick = function() { run_func('price_value = 0;'); run_func('set_min_price("prom_catalog", true)'); }; setMinRate.onclick = function() { run_func('price_value = 0;'); run_func('set_min_rate("prom,group_bigl", true)'); }; setMidPriceTags.onclick = function() { run_func('price_value = 0;'); run_func('set_mid_price("others", true)'); }; setMidPriceCats.onclick = function() { run_func('price_value = 0;'); run_func('set_mid_price("prom_catalog", true)'); }; setMidRate.onclick = function() { run_func('price_value = 0;'); run_func('set_mid_rate("prom,group_bigl", true)'); }; upMinPriceCats.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('set_min_price("prom_catalog", true)'); }; upMidPriceCats.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('set_mid_price("prom_catalog", true)'); }; upMidRate.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('set_mid_rate("prom,group_bigl", true)'); }; upMinPriceTags.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('set_min_price("others", true)'); }; upMinRate.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('set_min_rate("prom,group_bigl", true)'); }; upMidPriceTags.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('set_mid_price("others", true)'); }; setCurrPriceTags.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('add_to_curr_price("others", false)'); }; setCurrPriceCats.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('add_to_curr_price("prom_catalog", false)'); }; setCurrPriceBiglCats.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('add_to_curr_price("bigl_catalog", false)'); }; setCurrPriceBiglOther.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('add_to_curr_price("bigl", false)'); }; setCurrRate.onclick = function() { run_func('price_value = ' + price_value.value + ';'); run_func('add_to_curr_rate("prom,group_bigl", false)'); };
const request = require('request'); var async = require("async"); const calls = ['activities/distance/date/today/7d.json', 'activities/steps/date/today/7d.json', 'activities/calories/date/today/7d.json', 'activities/date/today.json' ]; var token; var apiCallCount = 0; function init_api_calls(auth_token, cb) { token = auth_token; require('./fusioncharts_api').reset_data(); var i = 0, calls_size = calls.length; //using async.whilst for synchronous loop. async.whilst(function () { return i < calls_size; }, function (next) { request({ headers: { 'Authorization': 'Bearer ' + auth_token }, uri: 'https://api.fitbit.com/1/user/-/' + calls[i], method: 'GET' }, function (err, resp, object) { // console.log(object); require('./fusioncharts_api').set_data(object); i++; next(); }); }, function (err) { apiCallCount = apiCallCount + 4; cb(apiCallCount); }); } module.exports = { init_api_calls: init_api_calls, get_token: function () { return token; } }
import React, { useEffect } from "react"; import ScrollAnimation from "react-animate-on-scroll"; import Aos from "aos"; import "aos/dist/aos.css"; import EmailForm from "../components/EmailComp"; import New from "../components/NewBtn"; import Learn from "../components/Learn"; import Footer from "../components/Footer"; import "animate.css/animate.min.css"; import img from "../img/banner-img.png"; import why1 from "../img/why1.png"; import why2 from "../img/why2.png"; import why3 from "../img/why3.png"; import dots from "../img/dots.png"; import triangle from "../img/traingle.png"; import w1 from "../img/w1.png"; import w2 from "../img/w2.png"; import w3 from "../img/w3.png"; import h1 from "../img/h1.png"; import h2 from "../img/h2.png"; import h3 from "../img/h3.png"; import b1 from "../img/b1.png"; import b2 from "../img/b2.png"; import b3 from "../img/b3.png"; import b4 from "../img/b4.png"; import b5 from "../img/b5.png"; import oval from "../img/oval.png"; import d1 from "../img/f1.png"; const Home = () => { useEffect(() => { Aos.init({ duration: 2000 }); }, []); return ( <div className="home-cont"> {/* Banner sectiom */} <div className="banner"> <div className="banner-text"> <h1>Cloud assistant for schools</h1> <p> Edge LMS provides everything you need to plan, organize, manage, & <br /> finance your school, in one place. </p> <EmailForm /> </div> <div style={{ width: "70%", margin: "0px auto" }}> <img src={img} /> </div> </div> {/* WHy section */} <div className="why-cont"> <img className="dots" src={dots} /> <div className="why-section-cont"> <p className="sub-hd">why choose edge</p> <h1 className="hd"> Our aim is to solve the 3 fundamental <br /> drawbacks in Education </h1> <div className="why-text"> <div data-aos="fade-up" className="why-txt-cont"> <span> <img src={why1} /> <h4>Training</h4> </span> <p> Seamless training delivery. Edge LMS has simplified teaching for Instructors by provding tools that help in distributiing course materials while also monitoring students performance. </p> </div> <div data-aos="fade-down" className="why-txt-cont"> <span> <img src={why2} /> <h4>Learning</h4> </span> <p> Adaptive learning technology. Students can study better with interactive video sessions, online discussion boards, and their personalized learning schedule on Edge LMS. </p> </div> <div data-aos="fade-up" className="why-txt-cont"> <span> <img src={why3} /> <h4>Computer Testing</h4> </span> <p> Testing as a Service. Our robust Computer Based Testing service will ensure that Students can practice with various past exammination questions. </p> </div> </div> </div> <img className="triangle" src={triangle} /> </div> {/* work section */} <div className="works"> <div className="works-cont"> <h1 className="hd">How Edge LMS works?</h1> <p style={{ textTransform: "unset" }} className="sub-hd"> The unique thing about Edge LMS is its self-provisioning, unfettered interactivity and <br /> communication when delivering its services. </p> <div className="works-text"> <img data-aos="fade-up" src={w1} /> <div data-aos="fade-down"> <h2>For Learner</h2> <div className="dd"> <i className="fas fa-chevron-right"></i> <span>Access course materials both online and offline</span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span>Personalize their learning schedule and curriculum</span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span>Collaborate with other students on the platform</span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span> Measure their course competency via computer based <br /> {" "} {" "}tests and exams </span> </div> <New link={"See feature list >>"} /> </div> </div> </div> </div> <div className="works"> <div className="works-cont"> <div className="works-text"> <div data-aos="fade-up"> <h2>For Instructors</h2> <div className="dd"> <i className="fas fa-chevron-right"></i> <span> Create course structures and manage course content for <br /> students </span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span>Schedule Live classes in student’s calendar</span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span> Interact with students and send notifications of due <br /> assignments online </span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span> Monitor students performance on computer based tests </span> </div> <New link={"See feature list >>"} /> </div> <img data-aos="fade-down" src={w2} /> </div>{" "} </div> </div> <div className="works" style={{ paddingBottom: "100px" }}> <div className="works-cont"> <div className="works-text"> <img data-aos="fade-up" src={w3} /> <div data-aos="fade-down"> <h2>For Schools</h2> <div className="dd"> <i className="fas fa-chevron-right"></i> <span> Create course structures and manage course content for <br /> students </span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span>Schedule Live classes in student’s calendar</span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span> Interact with students and send notifications of due <br /> assignments online </span> </div> <div className="dd"> <i className="fas fa-chevron-right"></i> <span> Monitor students performance on computer based tests </span> </div> <New link={"See feature list >>"} /> </div> </div>{" "} </div> </div> {/* Good hand section */} <div className="hands"> <img className="oval" src={oval} /> <img className="dot" src={dots} /> <img className="line" src={d1} /> <div> <h1 className="hd">You’re in a good hands</h1> <p style={{ textTransform: "unset" }} className="sub-hd"> ST&T Regency International Schools uses Edge LMS to deliver an <br /> efficient blended learning environment. </p> <div className="hands-cont"> <div data-aos="fade-up" className="hands-text"> <p> Life before Company was very chaotic — we got a lot of phone calls, a lot of mistyped orders. So with Company, the ability to see the order directly from the customer makes it so streamlined. </p> <span className="hand-foot"> <img src={h1} /> <h5>Full Name, School Name</h5> </span> </div> <div data-aos="fade-down" className="hands-text"> <p> There’s no way we could have hired these many people and gotten so much business had we not had all of those back-office systems figured out. It’s been easier growing our company with a system that is so easy and scalable. </p> <span className="hand-foot"> <img src={h2} /> <h5>Full Name, School Name</h5> </span> </div> <div data-aos="fade-up" className="hands-text"> <p> Wow. I just updated my site and it was SO SIMPLE. I am blown away. You guys truly kick ass. Thanks for being so awesome. High fives! </p> <span className="hand-foot"> <img src={h3} /> <h5>Full Name, School Name</h5> </span> </div> </div>{" "} <div className="hnd-logo"> <img src={b1} /> <img src={b2} /> <img src={b3} /> <img src={b4} /> <img src={b5} /> </div> </div> </div> {/* learn section */} <Learn /> {/* footer section */} <Footer /> </div> ); }; export default Home;
const Request = require("../models/request"); const Archive = require("../models/archive"); const User = require("../models/user"); const Profile = require("../models/profile"); const Mailer = require("../mail/mailer"); const Sonarr = require("../services/sonarr"); const Radarr = require("../services/radarr"); const logger = require("../util/logger"); const filter = require("./filter"); const Discord = require("../notifications/discord"); const Telegram = require("../notifications/telegram"); const { showLookup } = require("../tmdb/show"); const fs = require("fs"); const path = require("path"); class processRequest { constructor(req = {}, usr = {}) { this.request = req; this.user = usr; } async new() { let out = {}; let quotaPass = await this.checkQuota(); if (quotaPass) { try { let existing = await Request.findOne({ requestId: this.request.id, }); if (existing) { out = await this.existing(); } else { out = await this.create(); } if (quotaPass !== "admin") { let updatedUser = await User.findOneAndUpdate( { id: this.user.id }, { $inc: { quotaCount: 1 } }, { new: true, useFindAndModify: false } ); out.quota = updatedUser.quotaCount; } this.mailRequest(); this.discordNotify(); } catch (err) { logger.log("error", "REQ: Error"); logger.log({ level: "error", message: err }); out = { message: "failed", error: true, user: this.user, request: this.request, }; } } else { out = { message: `You are over your quota. Quotas reset each week.`, error: true, user: this.user, request: this.request, }; } return out; } async existing() { let userDetails = await User.findOne({ id: this.user.id }); let profile = userDetails.profile ? await Profile.findById(this.user.profile) : false; let autoApprove = profile ? profile.autoApprove : false; let autoApproveTv = profile ? profile.autoApproveTv : false; if (userDetails.role === "admin") { autoApprove = true; autoApproveTv = true; } let requestDb = await Request.findOne({ requestId: this.request.id }); if (!requestDb.users.includes(this.user.id)) { requestDb.users.push(this.user.id); requestDb.markModified("users"); } if (this.request.type === "tv") { let existingSeasons = requestDb.seasons || {}; Object.keys(this.request.seasons).map((key) => { existingSeasons[key] = true; }); requestDb.seasons = existingSeasons; this.request.seasons = existingSeasons; requestDb.markModified("seasons"); } await requestDb.save(); if ( (this.request.type === "movie" && autoApprove) || (this.request.type === "tv" && autoApproveTv) ) { requestDb.approved = true; await requestDb.save(); this.sendToDvr(profile); } return { message: "request updated", user: this.user.title, request: this.request, }; } async create() { let userDetails = await User.findOne({ id: this.user.id }); let profile = userDetails.profile ? await Profile.findById(this.user.profile) : false; let autoApprove = profile ? this.request.type === "movie" ? profile.autoApprove : profile.autoApproveTv : false; if (userDetails.role === "admin") { autoApprove = true; } if (this.request.type === "tv" && !this.request.tvdb_id) { let lookup = await showLookup(this.request.id, true); this.request.tvdb_id = lookup.tvdb_id; } const newRequest = new Request({ requestId: this.request.id, type: this.request.type, title: this.request.title, thumb: this.request.thumb, users: [this.user.id], imdb_id: this.request.imdb_id, tmdb_id: this.request.tmdb_id, tvdb_id: this.request.tvdb_id, approved: autoApprove, timeStamp: new Date(), }); if (this.request.type === "tv") { newRequest.seasons = this.request.seasons; } try { await newRequest.save(); if (autoApprove) { this.sendToDvr(profile); } else { logger.info("REQ: Request requires approval, waiting"); this.pendingDefaults(profile); } } catch (err) { logger.log("error", `REQ: Unable to save request`); logger.log({ level: "error", message: err }); return { message: "failed", error: true, user: this.user, request: this.request, }; } return { message: "request added", user: this.user.title, request: this.request, }; } async pendingDefaults(profile) { let pending = {}; let filterMatch = await filter(this.request); if (filterMatch) { logger.log( "info", "REQ: Pending Request Matched on custom filter, setting default" ); for (let f = 0; f < filterMatch.length; f++) { let filter = filterMatch[f]; pending[filter.server] = { path: filter.path, profile: filter.profile, tag: filter.tag, }; } } else { let project_folder, configFile, configData, configParse; if (this.request.type === "movie") { if (process.pkg) { project_folder = path.dirname(process.execPath); configFile = path.join(project_folder, "./config/radarr.json"); } else { project_folder = __dirname; configFile = path.join(project_folder, "../config/radarr.json"); } configData = fs.readFileSync(configFile); configParse = JSON.parse(configData); for (let s in configParse) { let server = configParse[s]; if (profile.radarr && profile.radarr[server.uuid]) { pending[server.uuid] = { path: server.path_title, profile: server.profile, tag: false, }; } } } else { if (process.pkg) { project_folder = path.dirname(process.execPath); configFile = path.join(project_folder, "./config/sonarr.json"); } else { project_folder = __dirname; configFile = path.join(project_folder, "../config/sonarr.json"); } configData = fs.readFileSync(configFile); configParse = JSON.parse(configData); for (let s in configParse) { let server = configParse[s]; if (profile.sonarr && profile.sonarr[server.uuid]) { pending[server.uuid] = { path: server.path_title, profile: server.profile, tag: false, }; } } } } if (Object.keys(pending).length > 0) { await Request.updateOne( { requestId: this.request.id }, { $set: { pendingDefault: pending } } ); logger.log("info", "REQ: Pending Defaults set for later"); } else { logger.log("info", "REQ: No Pending Defaults to Set"); } } async sendToDvr(profile) { let filterMatch = await filter(this.request); if (filterMatch) { if (!Array.isArray(filterMatch)) filterMatch = [filterMatch]; logger.log( "info", "REQ: Matched on custom filter, sending to specified server" ); logger.log("info", "REQ: Sending to DVR"); if (this.request.type === "movie") { for (let i = 0; i < filterMatch.length; i++) { new Radarr(filterMatch[i].server).manualAdd( this.request, filterMatch[i] ); } } else { for (let i = 0; i < filterMatch.length; i++) { new Sonarr().addShow( { id: filterMatch[i].server }, this.request, filterMatch[i] ); } } return; } logger.log("info", "REQ: Sending to DVR"); // If profile is set use arrs from profile if (profile) { if (profile.radarr && this.request.type === "movie") { Object.keys(profile.radarr).map((r) => { let active = profile.radarr[r]; if (active) { new Radarr(r).processRequest(this.request.id); } }); } if (profile.sonarr && this.request.type === "tv") { Object.keys(profile.sonarr).map((s) => { let active = profile.sonarr[s]; if (active) { new Sonarr().addShow({ id: s }, this.request); } }); } } else { // No profile set send to all arrs logger.log("info", "REQ: No profile for DVR"); if (this.request.type === "tv") new Sonarr().addShow(false, this.request); if (this.request.type === "movie") new Radarr().processRequest(this.request.id); } } async removeFromDVR() { if (this.request) { if (this.request.radarrId.length > 0 && this.request.type === "movie") { for (let i = 0; i < Object.keys(this.request.radarrId).length; i++) { let radarrIds = this.request.radarrId[i]; let rId = radarrIds[Object.keys(radarrIds)[0]]; let serverUuid = Object.keys(radarrIds)[0]; let server = new Radarr(serverUuid); try { server.remove(rId); logger.log( "info", `REQ: ${this.request.title} removed from Radarr server - ${serverUuid}` ); } catch (err) { logger.log("error", `REQ: Error unable to remove from Radarr`, err); } } } if (this.request.sonarrId.length > 0 && this.request.type === "tv") { for (let i = 0; i < Object.keys(this.request.sonarrId).length; i++) { let sonarrIds = this.request.sonarrId[i]; let sId = sonarrIds[Object.keys(sonarrIds)[0]]; let serverUuid = Object.keys(sonarrIds)[0]; try { new Sonarr().remove(serverUuid, sId); logger.log( "info", `REQ: ${this.request.title} removed from Sonarr server - ${serverUuid}` ); } catch (err) { logger.log("error", `REQ: Error unable to remove from Sonarr`, err); } } } } } discordNotify() { let userData = this.user; const requestData = this.request; let type = requestData.type === "tv" ? "TV Show" : "Movie"; [new Discord(), new Telegram()].forEach((notification) => notification.send( "New Request", `A new request has been added for the ${type} "${requestData.title}"`, userData.title, `https://image.tmdb.org/t/p/w500${requestData.thumb}` ) ); } async mailRequest() { let userData = this.user; if (!userData.email) { logger.log("warn", "MAILER: No user email"); return; } const requestData = this.request; let type = requestData.type === "tv" ? "TV Show" : "Movie"; new Mailer().mail( `You've just requested a ${type}: ${requestData.title}`, `${type}: ${requestData.title}`, `Your request has been received and you'll receive an email once it has been added to Plex!`, `https://image.tmdb.org/t/p/w500${requestData.thumb}`, [userData.email], [userData.title] ); } async checkQuota() { let userDetails = await User.findOne({ id: this.user.id }); if (!userDetails) return false; if (userDetails.role === "admin") return "admin"; let userQuota = userDetails.quotaCount ? userDetails.quotaCount : 0; let profile = userDetails.profile ? await Profile.findById(this.user.profile) : false; let quotaCap = profile ? profile.quota : 0; if (quotaCap > 0 && userQuota >= quotaCap) { return false; } return true; } async archive(complete = Boolean, removed = Boolean, reason = false) { let oldReq = this.request; let archiveRequest = new Archive({ requestId: this.request.requestId, type: this.request.type, title: this.request.title, thumb: this.request.thumb, imdb_id: this.request.imdb_id, tmdb_id: this.request.tmdb_id, tvdb_id: this.request.tvdb_id, users: this.request.users, sonarrId: this.request.sonarrId, radarrId: this.request.radarrId, approved: this.request.approved, removed: removed ? true : false, removed_reason: reason, complete: complete ? true : false, timeStamp: this.request.timeStamp ? this.request.timeStamp : new Date(), }); await archiveRequest.save(); Request.findOneAndRemove( { requestId: this.request.requestId, }, { useFindAndModify: false }, function (err, data) { if (err) { logger.log("error", `REQ: Archive Error`); logger.log({ level: "error", message: err }); } else { logger.log("info", `REQ: Request ${oldReq.title} Archived!`); } } ); } } module.exports = processRequest;
/** * @param {number} n * @return {boolean} */ var isPowerOfThree = function(n) { if (n === 0) return false; var res = Math.round(Math.log(n) / Math.log(3)); return Math.pow(3, res) === n; }; console.log(isPowerOfThree(3)); console.log(isPowerOfThree(0)); console.log(isPowerOfThree(45));
/** * Created by Wujianxiong on 2016/12/19. */ var formidable = require('formidable'); var fs = require('fs'); var path = require('path'); var config = require('../../config'); function UploadService() { } /** * 上传文件(前端input的name="file") * @param req request * @param dir 文件保存目录 */ UploadService.upload = function (req, callback) { var dirs = path.join(config.root, 'public', 'images','photo') if (!fs.existsSync(dirs)) { fs.mkdirSync(dirs); } var timestamp = new Date().getTime(); fs.mkdirSync(path.join(dirs, timestamp.toString())); var form = new formidable.IncomingForm(); //创建上传表单 form.encoding = 'utf-8'; //设置编码 form.uploadDir = path.join(dirs, timestamp.toString()); //设置上传目录 form.keepExtensions = true; //保留后缀 form.maxFieldsSize = 3 * 1024 * 1024 * 1024; //文件大小 form.parse(req, function (err, fields, files) { if (err) { callback(err); return; } if (!files.file) { callback('请上传文件'); return; } fs.rename(files.file.path, path.join(dirs, timestamp.toString(), files.file.name), function (err) { if (err) { callback(err); return; } var ret = {}; ret.path = path.join(dirs, timestamp.toString(), files.file.name); ret.data = fields; callback(null, ret); }); }); } module.exports = UploadService;
"use strict"; (function () { /* Создайте массив объектов-стран. У страны есть название и список городов. У города есть название и численность населения */ var countries = [ { name: "Россия", cities: [ { name: "Москва", population: 12678079 }, { name: "Санкт-Петербург", population: 5398064 }, { name: "Новосибирск", population: 1625631 }, { name: "Екатеринбург", population: 1493749 }, { name: "Владивосток", population: 606561 } ] }, { name: "Германия", cities: [ { name: "Берлин", population: 12678079 }, { name: "Гамбург", population: 5398064 }, { name: "Мюнхен", population: 1625631 }, { name: "Кёльн", population: 1625631 } ] }, { name: "Франция", cities: [ { name: "Париж", population: 2138551 }, { name: "Марсель", population: 794811 }, { name: "Лион", population: 472317 }, { name: "Тулуза", population: 433055 }, { name: "Ницца", population: 338620 } ] } ]; console.log("Создали массив объектов-стран:"); console.log(countries); // Найдите страну/страны с максимальным количеством городов function getCountriesWithMaxCitiesCount() { var array = []; var maxCitiesCount = 0; countries.forEach(function (country) { if (country.cities.length > maxCitiesCount) { maxCitiesCount = country.cities.length; array = [country]; } else if (country.cities.length === maxCitiesCount) { array.push(country); } }); return array; } console.log("Нашли страну/страны с максимальным количеством городов:"); console.log(getCountriesWithMaxCitiesCount()); /* Получите объект с информацией по всем странам такого вида: ключ - название страны, значение - суммарная численность по стране */ function getTotalPopulationByCountries() { var object = {}; countries.forEach(function (country) { object[country.name] = country.cities.reduce(function (totalPopulation, city) { return totalPopulation + city.population; }, 0); }); return object; } console.log("Получили объект с информацией по странам (ключ - название страны, значение - численность населения):"); console.log(getTotalPopulationByCountries()); })();
var ntk = require('../lib'); ntk.createClient( (err, app) => { var wnd = app.createWindow({ width: 800, height: 600}); var ctx = wnd.getContext('2d'); var text = 'This is Test test'; var lastx = 0; var lasty = 0; wnd.on('expose', (ev) => { ctx.fillStyle = 'white'; ctx.fillRect(ev.x, ev.y, ev.width, ev.height, 1, 0.5, 0.5, 1); ctx.font = "50px 'Times New Roman'"; var w = ctx.measureText(text).width; ctx.fillStyle = ctx.createLinearGradient(0, 0, w, 100) .addColorStop(0, 'red') .addColorStop(1, 'blue'); ctx.fillStyle = 'red'; //'rgba(200, 200, 180, 0.7)'; ctx.fillText(text, 100, 100);// 750 - w, 250); }); var shift = 0; wnd.on('keydown', function(ev) { if (ev.codepoint == 8) text = text.slice(0, -1); else if (ev.codepoint) text = text + String.fromCodePoint(ev.codepoint); wnd.emit('expose', { x: 0, y: 0, width: 1000, height: 1000}); }); wnd.on('mousemove', function(ev) { lastx = ev.x; lasty = ev.y; wnd.emit('expose', { x: 0, y: 0, width: 1000, height: 1000}); }); wnd.map(); });
import * as f from './testFixtures.js'; import * as tmp from 'tmp'; import * as fs from 'fs'; import { execSync } from 'child_process'; const glob = require('glob'); describe('separate compilation using --es=es5 and --webpack', () => { const files = glob.sync('test/es5-mode/*.js'); for (const src of files) { if (src.endsWith('.forever.js')) { test(`${src} (may run forever)`, () => { const { name: dst } = tmp.fileSync({ dir: ".", postfix: '.js' }); execSync(`./bin/compile --webpack -t lazy --es=es5 ${src} ${dst}`); const r = execSync(`./bin/browser -t lazy --stop=5 --env=chrome -y 1 ${dst}`); fs.unlinkSync(dst); }); } else { test(src, () => { const { name: dst } = tmp.fileSync({ dir: ".", postfix: '.js' }); execSync(`./bin/compile --webpack -t lazy --es=es5 ${src} ${dst}`); const r = execSync(`./bin/browser -t lazy --env=chrome -y 1 ${dst}`); fs.unlinkSync(dst); }); } } });