text
stringlengths
7
3.69M
import React from 'react'; import { Popover, PopoverHeader, PopoverBody } from 'reactstrap'; import PropTypes from 'prop-types'; import Button from '../../common/Button'; import './styles/DeleteCardPopover.css'; const DeleteCardPopover = ({ card, authToken, deleteCard, isOpen, toggle }) => { return ( <Popover placement="bottom" target="PopoverDeleteCard" isOpen={isOpen} toggle={toggle}> <PopoverHeader>Are you sure you want to delete this card ?</PopoverHeader> <PopoverBody> <Button classes="btn btn-danger delete-card" title="Delete" id="PopoverDeleteCard" onClick={() => deleteCard(card.id, card.listId, authToken)} /> </PopoverBody> </Popover> ); }; DeleteCardPopover.propTypes = { authToken: PropTypes.string.isRequired, card: PropTypes.object.isRequired, isOpen: PropTypes.bool.isRequired, toggle: PropTypes.func.isRequired, deleteCard: PropTypes.func.isRequired }; export default DeleteCardPopover;
$(document).ready(function() { // automtically scrolls page so navbar is hidden $('html, body').animate({ 'scrollTop' : $("#events_title").position().top }); // shows tool tip when you hover over element $('[data-toggle="tooltip"]').tooltip(); // makes go to top button appear when user scrolls down the page $(window).scroll(function() { if ($(this).scrollTop() > 100) { $('#go-top').fadeIn(); } else { $('#go-top').fadeOut(); } }); // on button click, scroll to the top of the page $('#go-top').click(function() { $("html, body").animate({ scrollTop: 0 }, 300); return false; }); }); // removes bookmark from user function removebookmark(concertid) { $.get('/concert/removebookmark/', {concertid: concertid}); toastr.error('Bookmark removed!'); }; // fire when concert is deleted function deleteconcert() { toastr.error('Concert deleted!'); } function hideparent(elem, pretty) { if (pretty) { // if user has pretty view enabled // hides tile $(elem).parent().parent().parent().parent().parent().parent().hide(); } else { // hides table row $(elem).parent().parent().hide(); } }; // bookmark a concert function bookmark(concertid, pretty) { var $requesturl = document.getElementById("bookmarkButton").getAttribute('data-url'); $requesturl = $requesturl.replace('1',concertid); var $button; if (pretty) { $button = '<button class="btn btn-danger" onclick = "removebookmark(' +concertid+ ');hideparent(this, true);" >Remove Bookmark</button>'; } else { $button = '<button class="btn btn-danger" onclick = "removebookmark(' +concertid+ ');hideparent(this, false);" >Remove Bookmark</button>'; } //Now use AJAX to fetch the data for a the concert $.ajax({ url: $requesturl , type: 'GET', async: false, dataType: 'json', success: function(res){ //Depending on the date of the conert, append to appropiate table var $concerturl ='<a href="{% url "view" 1 %}">' $concerturl = $concerturl.replace('1',concertid); if (res[0].isfuture == "True") { $.each(res, function(i, item) { if (pretty) { // if user has pretty view enabled $('<div class="col-12 col-md-6 col-lg-4 mt">').append('<div class="tile-container"><div class="tile"><div class="tile-front" style="background-image: url( '+item.image+'); background-size: cover; background-position: center;"><div class="bottom-left"><p>'+item.artist+'<br>'+item.venuename+'</p></div></div><div class="tile-back" style=" background-image: url('+item.image+'); background-size: cover; background-position: center;"><div class ="center-white-bg tileback"> <div class ="center"><h6>'+item.artist+'<br>'+item.venuename+', '+item.location+'<br>'+item.date+'<br>'+item.starttime+' - '+item.endtime+'<br></h6> <br> ' + $concerturl + ' <button class="btn btn-outline-info">View</button></a> <button class="btn btn-danger" onclick = "removebookmark('+ concertid+');hideparent(this, true);" >Remove Bookmark</button></div></div></div></div></div>' ).appendTo('#futureevents'); } else { $('<tr>').append('<td>'+item.artist+'</td><td colspan="2">'+item.venuename+', '+item.location+'</td><td>'+item.date+'</td><td>'+item.starttime+' - '+item.endtime+'<td colspan="2">'+$concerturl+'<button class="btn btn-outline-info">View</button></a>&nbsp<button class="btn btn-danger" onclick = "removebookmark('+ concertid+');hideparent(this, false);">Remove Bookmark</button></td>' ).appendTo('#futureevents'); } }); } else { $.each(res, function(i, item) { if (pretty) { $('<div class="col-12 col-md-6 col-lg-4 mt">').append('<div class="tile-container"><div class="tile"><div class="tile-front" style="background-image: url( '+item.image+'); background-size: cover; background-position: center;"><div class="bottom-left"><p>'+item.artist+'<br>'+item.venuename+'</p></div></div><div class="tile-back" style=" background-image: url('+item.image+'); background-size: cover; background-position: center;"><div class ="center-white-bg tileback"> <div class ="center"><h6>'+item.artist+'<br>'+item.venuename+', '+item.location+'<br>'+item.date+'<br>'+item.starttime+' - '+item.endtime+'<br></h6> <br> ' + $concerturl + ' <button class="btn btn-outline-info">View</button></a> <button class="btn btn-danger" onclick = "removebookmark('+ concertid+');hideparent(this, true);" >Remove Bookmark</button></div></div></div></div></div>' ).appendTo('#pastevents'); } else { $('<tr>').append('<td>'+item.artist+'</td><td colspan="2">'+item.venuename+', '+item.location+'</td><td>'+item.date+'</td><td>'+item.starttime+' - '+item.endtime+'<td colspan="2">'+$concerturl+'<button class="btn btn-outline-info">View</button></a>&nbsp<button class="btn btn-danger" onclick = "removebookmark('+ concertid+');hideparent(this, false);">Remove Bookmark</button></td>' ).appendTo('#pastevents'); } }); } } }); $.get('/concert/bookmark/', {concertid: concertid}); toastr.success('Concert bookmarked!'); };
"use strict"; /// <reference path="../../scene/ComponentConfig.d.ts" /> Object.defineProperty(exports, "__esModule", { value: true }); const SpriteRendererConfig_1 = require("./SpriteRendererConfig"); SupCore.system.registerPlugin("componentConfigs", "SpriteRenderer", SpriteRendererConfig_1.default);
var controllers = require('./vue/controllers'); var components = require('./vue/components'); var attachedControllers = {}; var notify = require('./misc/notify'); var mountControllers = (selector) => { $(selector).each((i, el) => { var cName = $(el).attr('data-controller'); el.id = _.randomStr(); if (controllers[cName] === undefined) console.warn(`Controller ${cName} is not found`); attachedControllers[cName] = new controllers[cName]({el: `#${el.id}`}); }); }; var unmountControllers = (selector) => { $(selector).each((i, el) => { var cName = $(el).attr('data-controller'); if (attachedControllers[cName] !== undefined) { attachedControllers[cName].$destroy(true); } }); }; export default { libraries() { if (typeof window.Bugsnag !== 'undefined') { Bugsnag.releaseStage = CObj.environment; Bugsnag.notifyReleaseStages = ["production", "staging"]; } window.pusherSubscriptions = {}; window.placeholder = require('placeholder'); window._ = require('lodash'); require('./extensions/lodash'); window.moment = require('moment-business-days'); }, vue() { Vue.http.options.onComplete = (req) => { switch (req.status) { case 400: notify.error(JSON.parse(req.response).error); break; case 422: notify.validation(JSON.parse(req.response)); break; } } require('./vue/directives'); require('./vue/filters'); mountControllers("[data-controller]"); }, pjax() { $(document).pjax('a[data-pjax]', '#pjax-container', { timeout: 3000 }); $(document).pjax('a[data-pjax-full]', '#pjax-big-container', { timeout: 3000 }); $(document).on('pjax:clicked', () => { notify.loading(true); if ($('#navbar').hasClass('in')) { $('#navbar').collapse('toggle'); } if ($('#navbar-collapse-main').hasClass('in')) { $('#navbar-collapse-main').collapse('toggle'); } }); $(document).on('pjax:success', (e) => { mountControllers($(e.target).find("[data-controller]")); this.scripts(); notify.loading(false); $('.modal-backdrop').remove(); $(document).trigger('redraw.bs.charts'); $("a[data-pjax]").each(function (i, el) { var $parent = $($(el).parent()); if ($parent.is('li')) { $(el).attr('href') == window.location.href ? $parent.addClass('active') : $parent.removeClass('active'); } }); }); $(document).on('pjax:beforeReplace', (e) => { unmountControllers($(e.target).find("[data-controller]")); }); }, scripts() { $('.tooltipper').tooltip({ html: true }); } }
import myTaskApi from '@/api/myTask' import userApi from '@/api/user' export default { data () { return { isIndeterminate: true, mode: 'add', // 默认操作模式为新建 saved: false, // 界面的数据是否保存过 selectUsers: [], // 任务执行人集合 users: [], form: { id: null, taskTitle: '', taskContent: '', executeDate: '', executeUserName: '', executeRealName: '', finished: false, executeResult: '' }, rules: { taskTitle: [{ required: true, message: '任务标题必填', trigger: 'blur' }, { max: 100, message: '任务标题长度不能大于100个字符', trigger: 'blur' } ], taskContent: [{ required: true, message: '任务内容必填', trigger: 'blur' }, { max: 2000, message: '任务内容长度不能大于2000个字符', trigger: 'blur' } ], executeDate: [{ required: true, message: '执行日期必填', trigger: 'blur' }] } } }, methods: { // 是否显示更新按钮 showUpdateButton () { let loginInfo = JSON.parse(window.localStorage['loginInfo']) return this.mode === 'modify' && this.form.executeUserName === loginInfo.username }, // 处理全选事件 handleCheckAllChange (val) { this.selectUsers = val ? this.users : [] this.isIndeterminate = false }, // 取消 cancel () { if (typeof (this.$route.query.mode) !== 'undefined') { this.mode = this.$route.query.mode this.form = this.$route.query.task } else { this.form.id = null this.form.taskTitle = '' this.form.executeDate = '' this.form.taskContent = '' } }, // 保存 save () { this.$refs['form'].validate((valid) => { if (valid) { if (this.selectUsers.length === 0) { this.$message({ message: '请选择任务执行人!', type: 'warning', showClose: true }) return } // 如果校验通过就调用后端接口 for (let index in this.selectUsers) { let task = JSON.parse(JSON.stringify(this.form)) task.executeUserName = this.selectUsers[index]['username'] task.executeRealName = this.selectUsers[index]['realname'] myTaskApi.save(task).then( res => { if (res.status === 200) { this.$message({ message: '保存成功!', type: 'success', showClose: true }) } }) } // 修改保证状态标志 this.saved = true } else { // 如果检查不通过就给出提示 this.$message({ message: '有错误,请检查!', type: 'warning', showClose: true }) } }) }, // 更新 update () { if (this.form.executeResult === '') { this.$message({ message: '请输入执行结果!', type: 'warning', showClose: true }) return } let task = { 'id': this.form.id, 'finished': this.form.finished, 'executeResult': this.form.executeResult } myTaskApi.update(task).then( res => { if (res.status === 200) { this.$message({ message: '保存成功!', type: 'success', showClose: true }) } }) } }, computed: {}, created () { // 通过入参获取当前操作模式 if (typeof (this.$route.query.mode) !== 'undefined') { // 接收list传入的参数 this.mode = this.$route.query.mode this.form = this.$route.query.task } userApi.findAllEnabled().then(res => { if (res.status === 200) { this.users = res.data } }) } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ function obtener_login(){ var txt_usuario = $("#txt_usuario").val(); var txt_clave = $("#txt_clave").val(); var dataString='txt_usuario='+txt_usuario+'&txt_clave='+txt_clave; $.ajax({ type: "GET", dataType:"json", url: "/guayapp/data/login.php", data: dataString, success: function(data) { if(data.items!=null) window.location="/guayapp/ingreso.php"; else alert("Usuario o clave incorrecta"); } }); } $(document).ready(function(){ /*Validación del formulario login de la pagina index.php*/ $('#form_login').each (function(){ this.reset(); }); $("#submit").click( function(){ var indicar_foco=0; var entrar=true; if($("#txt_usuario").val()==""){ // mensaje_tooltip("#txt_usuario","Ingrese su usuario"); indicar_foco++; entrar=false; } if($("#txt_clave").val()==""){ $("#msj_login").toggle(200); //mensaje_tooltip("#txt_clave","Ingrese su clave"); indicar_foco++; entrar=false; } if(indicar_foco==2){ $("#txt_usuario").focus(); } if(entrar){ obtener_login(); } } ); });
function tableSer() { var i = 1; $(".ser-row").each(function () { $(this).text(i++); }); } $(document).ready(function () { $("#pcat").change(function () { $("#pscat").removeAttr("disabled"); var cat_id = $("select[name=pcat]").val(); $.ajax({ type: "POST", url: "assets/include/sub_categories.php", data: { id: cat_id }, success: function (sub_cat) { $("#pscat").html(sub_cat); }, }); }); }); $(document).ready(function () { $("#copy-product #pcat").change(function () { $("#copy-product #pscat").removeAttr("disabled"); var cat_id = $("#copy-product select[name=pcat]").val(); $.ajax({ type: "POST", url: "assets/include/sub_categories.php", data: { id: cat_id }, success: function (sub_cat) { $("#copy-product #pscat").html(sub_cat); }, }); }); }); $(document).ready(function () { $("#epcat").change(function () { $("#epscat").removeAttr("disabled"); var cat_id = $("select[name=epcat]").val(); $.ajax({ type: "POST", url: "assets/include/sub_categories.php", data: { id: cat_id }, success: function (sub_cat) { $("#epscat").html(sub_cat); }, }); }); }); $(document).ready(function () { $("#cpcat").change(function () { $("#cpscat").removeAttr("disabled"); var cat_id = $("select[name=cpcat]").val(); $.ajax({ type: "POST", url: "assets/include/sub_categories.php", data: { id: cat_id }, success: function (sub_cat) { $("#cpscat").html(sub_cat); }, }); }); }); $(document).ready(function () { $("form#add-product").submit(function (e) { e.preventDefault(); $("#save-p-btn").attr("disabled", "true"); $("#save-p-btn i").attr("class", "fas fa-spinner fa-spin ml-2 mr-2"); $.ajax({ url: "assets/include/add_product.php", type: "post", data: $(this).serialize(), success: function (data) { $("#add_product").modal("hide"); var id = data.trim(); var tableRow = ` <tr id = 'row-` + id + `'> <td class="ser-row"></td> <td id="name-` + id + `">` + $("input[name=pname]").val() + `</td> <td id="cat-` + id + `">` + $("#add_product select[name=pcat] option:checked").text() + `</td> <td id="subcat-` + id + `">` + $("#add_product select[name=pscat] option:checked").text() + `</td> <td id="quantity-` + id + `">` + $("input[name=pquan]").val() + `</td> <td id="price-`+id+`">`+$("input[name=price]").val()+`</td> <td><span id="status-`+id+`" class="badge badge-primary">Active</span></td> <td id="action-` + id + `"> <div class="dropdown"> <button type="button" class="btn btn-light dropdown-toggle w-100" data-toggle="dropdown"> Actions </button> <div class="dropdown-menu bg-dark text-center p-2 w-100"> <button class="btn btn-sm btn-info view-product" data-toggle="tooltip" data-placement="top" title="View" data-id="` + id + `"><i class="fas fa-eye"></i></button> <button class="btn btn-sm btn-success edit-product" data-toggle="tooltip" data-placement="top" title="Edit" data-id="` + id + `"><i class="fas fa-edit"></i></button> <button class="btn btn-sm btn-warning copy-product" data-toggle="tooltip" data-placement="top" title="Copy" data-id="` + id + `"><i class="fas fa-copy"></i></button> <button class="btn btn-sm btn-danger delete-product" data-toggle="tooltip" data-placement="top" title="Delet" data-id="` + id + `"><i class="fas fa-trash"></i></button> </div> </div></td> </tr> `; // $("") $("#main-table").prepend(tableRow); $("#bs-alert").toggle(); setTimeout(function () { $("#bs-alert").toggle(); }, 10000); tableSer(); $("#save-p-btn").attr("disabled", "false"); $("#save-p-btn i").attr("class", "fas fa-save ml-2 mr-2"); $("form#add-product")[0].reset(); }, }); }); }); $(document).ready(function () { $("form#copy-product").submit(function (e) { e.preventDefault(); $("#copy-p-btn").attr("disabled", "true"); $("#copy-p-btn i").attr("class", "fas fa-spinner fa-spin ml-2 mr-2"); $.ajax({ url: "assets/include/add_product.php", type: "post", data: $(this).serialize(), success: function (data) { var id = data.trim(); var tableRow = ` <tr id = 'row-` + id + `'> <td class="ser-row"></td> <td id="name-` + id + `">` + $("#copy_product input[name=pname]").val() + `</td> <td id="cat-` + id + `">` + $("#copy_product select[name=pcat] option:checked").text() + `</td> <td id="subcat-` + id + `">` + $( "#copy_product select[name=pscat] option:checked" ).text() + `</td> <td id="quantity-` + id + `">` + $("#copy_product input[name=pquan]").val() + `</td> <td id="price-`+id+`">`+$("#copy_product input[name=price]").val()+`</td> <td><span id="status-`+id+`" class="badge badge-primary">Active</span></td> <td id="action-` + id + `"> <div class="dropdown"> <button type="button" class="btn btn-light dropdown-toggle w-100" data-toggle="dropdown"> Actions </button> <div class="dropdown-menu bg-dark text-center p-2 w-100"> <button class="btn btn-sm btn-info view-product" data-toggle="tooltip" data-placement="top" title="View" data-id="` + id + `"><i class="fas fa-eye"></i></button> <button class="btn btn-sm btn-success edit-product" data-toggle="tooltip" data-placement="top" title="Edit" data-id="` + id + `"><i class="fas fa-edit"></i></button> <button class="btn btn-sm btn-warning copy-product" data-toggle="tooltip" data-placement="top" title="Copy" data-id="` + id + `"><i class="fas fa-copy"></i></button> <button class="btn btn-sm btn-danger delete-product" data-toggle="tooltip" data-placement="top" title="Delet" data-id="` + id + `"><i class="fas fa-trash"></i></button> </div> </div></td> </tr> `; $("#main-table").prepend(tableRow); $("#copy_product").modal("hide"); $("#bs-alert").css("display", "block"); setTimeout(function () { $("#bs-alert").css("display", "none"); }, 10000); tableSer(); $("#copy-p-btn").attr("disabled", "false"); $("#copy-p-btn i").attr("class", "fas fa-save ml-2 mr-2"); }, }); }); }); $(document).ready(function () { $("form#edit-product").submit(function (e) { var id = $("input[name=id]").val(); $("#edit-p-btn").removeAttr("disabled"); $("#edit-p-btn i").attr("class", "fas fa-spinner fa-spin ml-2 mr-2"); e.preventDefault(); $.ajax({ url: "assets/include/edit_products.php", type: "post", data: $(this).serialize(), success: function () {}, }); $("#edit-p-btn").removeAttr("disabled"); $("#edit-p-btn i").attr("class", "fas fa-save ml-2 mr-2"); $("#edit_product").modal("hide"); $("#name-" + id).text($("input[name=epname]").val()); $("#price-" + id).text($("input[name=eprice]").val()); $("#cat-" + id).text($("select[name=epcat] option:checked").text()); $("#subcat-" + id).text($("select[name=epscat] option:checked").text()); var status = $("select[name=status] option:checked").text(); $("#status-" + id).text(status); if (status=='Disabled') { $("#status-" + id).attr("class", "badge badge-danger"); } else { $("#status-" + id).attr("class", "badge badge-primary"); } $("#quantity-" + id).text($("input[name=epquan]").val()); }); }); $(document).on("click", ".delete-product", function () { var id = $(this).data("id"); swal({ title: "Are you sure?", text: "Once deleted the product will disappear!", icon: "warning", buttons: true, dangerMode: true, }).then((willDelete) => { if (willDelete) { $.ajax({ type: "POST", url: "assets/include/remove_products.php", data: { pid: id }, }); $("#status-" + id).attr("class", "badge badge-danger"); $("#status-" + id).text("Disabled"); tableSer(); swal("The Product has been deleted!", { icon: "success", }); } }); }); $(document).on("click", ".view-product", function () { var id = $(this).data("id"); $("#view_product").modal(); $("#product_name").text($("#name-" + id).text()); $("#product_cat").text($("#cat-" + id).text()); $("#product_subcat").text($("#subcat-" + id).text()); $("#product_quan").text($("#quantity-" + id).text()); }); $(document).on("click", ".edit-product", function () { $("#edit-product")[0].reset(); var id = $(this).data("id"); $("#edit_product").modal(); $("input[name=id]").val(id); $('select#epscat option:contains("' + $("#subcat-" + id).text() + '")').prop("selected", true); $('select#epcat option:contains("' + $("#cat-" + id).text() + '")').prop("selected",true); $('select#status option:contains("' + $("#status-" + id).text() + '")').prop("selected",true); $("input[name=epname]").val($("#name-" + id).text()); $("input[name=eprice]").val($("#price-" + id).text()); $("input[name=epquan]").val($("#quantity-" + id).text()); }); $(document).on("click", ".copy-product", function () { $("#copy-product")[0].reset(); var id = $(this).data("id"); $("#copy_product").modal(); $("input[name=id]").val(id); $("input[name=pname]").val($("#name-" + id).text()); $("input[name=pquan]").val($("#quantity-" + id).text()); $("input[name=price]").val($("#price-" + id).text()); $('#copy-product #pscat option:contains("' + $("#subcat-" + id).text() + '")').prop("selected", true); $('#copy-product #pcat option:contains("' + $("#cat-" + id).text() + '")').prop("selected", true); }); var session_items = sessionStorage.getItem("cart-items"); if (session_items==null) { sessionStorage.setItem("cart-items", 0); } $(document).ready(function () { $(".cart-items").text(sessionStorage.getItem("cart-items")); });
import React from 'react'; import {BackButton} from '../Styled'; import {Link} from 'react-router-dom'; const BackButtonComponent = ({backButtonUrl}) => { return( <Link to={backButtonUrl} className="link"> <BackButton> <span>Go Back</span> </BackButton> </Link> ) }; export default BackButtonComponent;
import React from "react"; import { Button } from "@mui/material"; import Box from "@material-ui/core/Box"; import GoogleIcon from "@mui/icons-material/Google"; const LoginForm = () => { return ( <div> <Box display="flex" justifyContent="center" alignItems="center" minHeight="100vh" component="div" > <a href="https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?redirect_uri=http://localhost:3000/profile&prompt=consent&response_type=code&client_id=410851594897-b3pab1hqinh5p6ojdssorppkhi3jv9nt.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive+https://www.googleapis.com/auth/userinfo.profile+https://www.google.com/m8/feeds/+https://www.googleapis.com/auth/userinfo.email&access_type=offline&flowName=GeneralOAuthFlow" target="_blank" rel="noreferrer" > <Button variant="outlined" color="error"> <GoogleIcon style={{ marginRight: ".6rem" }} /> LOGIN WITH GOOGLE{" "} </Button> </a> </Box> <p>locals{localStorage.getItem("code")}</p> </div> ); }; export default LoginForm;
"use-strict" var port = 8787; var express = require('express'); var app = express(); var twilio = require('twilio') var client = new twilio.RestClient('ACe2588f2e1e67751c38d432195e978b86', '1a6c19e4dae1567542bafca965bee23c'); var bodyParser = require('body-parser'); var firebase = require('firebase'); var ref = new firebase('https://skytextsupport.firebaseio.com/numbers'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); app.post('/support/messages', function(req, res){ console.log(req.body) client.messages.create({ to: req.body.num, from: "+17655873423", body: req.body.message }, function(err, message) { var phoneNums = ref.child(req.body.num) // var currentDate = new Date() phoneNums.push({ body: req.body.message, // date_sent: new Date(), from: "+17655873423", to: req.body.num }); res.send(req.body) }); }) app.listen(port);
class AppController{ constructor(utils){ 'ngInject'; this.foo = 'foo'; } } export default AppController;
var interface_c1_connector_get_user_contractors_response = [ [ "C1ConnectorGetUserContractorsBlock", "interface_c1_connector_get_user_contractors_response.html#aea5b6d894c855b7b0b0c5f7e846c9a2f", null ], [ "getGetUserContractorsResponsePublic", "interface_c1_connector_get_user_contractors_response.html#a1572353693e84641291006dea8a7d875", null ], [ "contractors", "interface_c1_connector_get_user_contractors_response.html#a108648a2d8150888cc0cb8b586310516", null ] ];
module.exports = { succeed, fail, repair, get, }; const item = { name: "marc", durability: 100, enhancement: 20 } function succeed(item) { if(item.enhancement < 20){ let enhance = ++item.enhancement return{...item, enhancement: enhance} } else if(item.enhancement == 20){ return item; } else{ let enhance = 20 return{...item, enhancement: enhance} } } function fail(item) { if(item.enhancement < 15){ let durab = item.durability - 5; console.log('durab fail', durab) return {...item, durability: durab} } else if (item.enhancement === 15){ let durab = item.durability - 10; console.log('durab fail', durab) return {...item, durability: durab} } else if (item.enhancement >= 16){ let enhance = item.enhancement - 1; let durab = item.durability - 10; console.log(enhance, durab) return {...item, enhancement: enhance, durability: durab} } else { return item; } } function repair(item) { if(item.durability < 100){ return { ...item, durability: 100 }; } else { let dura = 100 return {...item, durability: dura} } } function get(item) { if(item.enhancement === 0){ return item } else { let nameo = `[+${item.enhancement}] ${item.name}` return {...item, name: nameo} } }
import { helloworld } from './helloworld' document.write(helloworld())
module.exports = function (app) { app.get('/api/runner', findAllRunners); app.get('/api/runner/:runnerId', findUserById); app.post('/api/runner/register', createRunner); app.get('/api/profile', profile); app.get('/api/logout', logout); app.post('/api/login', login); app.put('/api/runner', updateRunner); app.get('/api/runner/:runnerId/runs', findAllRunsForRunner); var runnerModel = require('../models/runner/runner.model.server'); var runModel = require('../models/run/run.model.server'); function findUserById(req, res) { var id = req.params['runnerId']; runnerModel.findRunnerById(id) .then(function (user) { res.json(user); }) } function login(req, res) { var credentials = req.body; runnerModel .findRunnerByCredentials(credentials) .then(function(user) { console.log(user); req.session['currentUser'] = user; res.json(user); }) } function profile(req, res) { res.send(req.session['currentUser']); } function createRunner(req, res) { var user = req.body; runnerModel.createRunner(user) .then(function (user) { req.session['currentUser'] = user; res.json(user); }) } function findAllRunners(req, res) { runnerModel.findAllRunners() .then(function (users) { res.json(users); }) } function logout(req, res) { req.session.destroy(); res.send(200); } function updateRunner(req, res) { var runner = req.body; console.log(runner); runnerModel.updateRunner(runner) .then((runner) => res.json(runner)); } function findAllRunsForRunner(req, res) { console.log("Finding runs for runner."); var id = req.params.runnerId; console.log(id); runModel.findRunsForRunner(id) .then((runs) => res.json(runs)) } }
 const config = { apiKey: "AIzaSyCoKatVz8xlteNJGwY5hg_tDWEQ36foOGI", authDomain: "frontend-69cae.firebaseapp.com", databaseURL: "https://frontend-69cae.firebaseio.com", projectId: "frontend-69cae", storageBucket: "frontend-69cae.appspot.com", messagingSenderId: "574904259542" }; firebase.initializeApp(config);
import React from "react"; import './Jumbotrom.css'; function Jumbotrom (){ return( <div className="jumbotrom"> <h2 className="title">React Google Books</h2> </div> ) }; export default Jumbotrom;
import React from 'react'; import './TabsDoctors.css'; import PropTypes from 'prop-types'; import { makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import Typography from '@material-ui/core/Typography'; import Box from '@material-ui/core/Box'; import Personal from './Personal/Personal'; import ProfessionalDetails from './Professional/ProfessionalDetails'; import Clinic from './Clinic/Clinic'; import Hospital from './Hospital/Hospital'; import Procedures from './Procedures/Procedures'; function TabPanel(props) { const { children, value, index, ...other } = props; return ( <Typography component="div" role="tabpanel" hidden={value !== index} id={`nav-tabpanel-${index}`} aria-labelledby={`nav-tab-${index}`} {...other} > {value === index && <Box p={3}>{children}</Box>} </Typography> ); } TabPanel.propTypes = { children: PropTypes.node, index: PropTypes.any.isRequired, value: PropTypes.any.isRequired, }; function a11yProps(index) { return { id: `nav-tab-${index}`, 'aria-controls': `nav-tabpanel-${index}`, }; } function LinkTab(props) { return ( <Tab component="a" onClick={event => { event.preventDefault(); }} {...props} /> ); } const useStyles = makeStyles(theme => ({ root: { flexGrow: 1, backgroundColor: theme.palette.background.paper, }, })); export default function NavTabs() { const classes = useStyles(); const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <div className={classes.root}> <AppBar position="static"> <Tabs variant="fullWidth" value={value} onChange={handleChange} aria-label="nav tabs example" > <LinkTab label="Personal Details" href="/Personal" /> <LinkTab label="Professional Details" href="/Professional" /> <LinkTab label="Clinic" href="/Clinic" /> <LinkTab label="Hospital" href="/Hospital" /> <LinkTab label="Procedures" href="/Procedures" /> <LinkTab label="Social" href="/Social" /> <LinkTab label="Master Control" href="/MasterControl" /> </Tabs> </AppBar> <TabPanel value={value} index={0}> <Personal /> </TabPanel> <TabPanel value={value} index={1}> <ProfessionalDetails /> </TabPanel> <TabPanel value={value} index={2}> <Clinic /> </TabPanel> <TabPanel value={value} index={3}> <Hospital /> </TabPanel> <TabPanel value={value} index={4}> <Procedures /> </TabPanel> <TabPanel value={value} index={5}> Social page under construction </TabPanel> <TabPanel value={value} index={6}> Master Control page under construction </TabPanel> </div> ); }
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var models_1 = __importDefault(require("./models")); var graphql_yoga_1 = require("graphql-yoga"); var schema_1 = __importDefault(require("./schema")); var resolver_1 = __importDefault(require("./resolver")); var server = new graphql_yoga_1.GraphQLServer({ typeDefs: schema_1.default, resolvers: resolver_1.default }); models_1.default.sequelize.sync(); server.start(function () { return console.log('Server is running on localhost:4000'); });
var partition = function(s) { let ans = []; for (let i = 0; i < s.length; i++) { } }; function isPal(str) { if (str.length <1) {return false} if (str.length === 1) {return true} let start = 0 let end = str.length-1; while (start < end){ if (str[start] !== str[end]) { return false; } start++; end--; } return true; } // Iterate through console.log(('aab'))
const BrowserWaits = require('../../support/customWaits'); const ShareCaseData = require('../../utils/shareCaseData'); const CucumberReportLog = require("../../../codeceptCommon/reportLogger"); const { LOG_LEVELS } = require('../../support/constants'); class ShareCasePage { constructor() { this.backLink = $('.govuk-back-link'); this.shareCaseContainer = $('exui-case-share'); this.selectedCases = $$('xuilib-selected-case-list xuilib-selected-case'); this.continueButton = $("#share-case-nav button"); this.noCaseDisplay = $('#noCaseDisplay'); //User selection element this.userEmailInput = $('#add-user xuilib-user-select .govuk-input'); this.userFilterContainer = $('.mat-autocomplete-panel'); this.userFilterList = $$('.mat-autocomplete-panel .mat-option-text'); this.addUserBtn = $('#btn-add-user'); this.openCloseAll = $('.govuk-accordion__open-all'); this.testData_lastSelectedUser = ""; this.testData_lastAddedUser = ""; } async waitForPageToLoad(){ await BrowserWaits.waitForElement(this.shareCaseContainer); await BrowserWaits.waitForCondition(async () => { return await this.selectedCases.count() > 0; }); await browser.sleep(2); } async amOnPage() { await this.waitForPageToLoad(); await this.testData_storeCaseShareDataOnPage(); return await this.shareCaseContainer.isPresent(); } async testData_markUserWithEmailTobeAdded(email){ let casesCount = await this.casesCount(); for (let caseCounter = 1; caseCounter <= casesCount; caseCounter++) { let caseId = await this.getCaseSubtitle(caseCounter); ShareCaseData.MarkUserToShare(caseId,email); } } async testData_storeCaseShareDataOnPage(){ let casesCount = await this.casesCount(); for (let caseCounter = 1; caseCounter <= casesCount; caseCounter++){ let caseId = await this.getCaseSubtitle(caseCounter ); let sharedWith = []; let tobeAdded = []; let tobeRemoved= []; let usersCountInCase = await this.getUsersCount(caseCounter); for (let userCounter = 1; userCounter <= usersCountInCase; userCounter++){ let email = await this.getEmailForUserIncase(caseCounter, userCounter); let actionLinktext = await this.getActionLinkTextForUser(caseCounter, userCounter); if (actionLinktext === 'Cancel'){ let actionStatusLabel = await this.getActionLabelForUserWithEmail(caseCounter,email); if (actionStatusLabel.includes('added')){ tobeAdded.push(email); }else{ sharedWith.push(email); tobeRemoved.push(email); } }else{ sharedWith.push(email); } } ShareCaseData.AddCaseShareData(caseId,sharedWith,tobeAdded,tobeRemoved); CucumberReportLog.AddJson(ShareCaseData.getCaseWithId(caseId)); } } async clickBackLink(){ await this.backLink.click(); } async casesCount(){ await this.waitForPageToLoad(); return await this.selectedCases.count(); } async clickContinueButton(){ await this.continueButton.click(); } async enterUserEmailToSelect(emailText){ return await this.userEmailInput.sendKeys(emailText); } async getUserEmailText(emailText) { return await this.userEmailInput.getText(); } async getFilteredUsersCount(){ await BrowserWaits.waitForSeconds(2); return await this.userFilterList.count(); } async getFilteredUserEmails() { let userEmails = []; let usernameEmails = await this.getFilteredUserNameEmails(); for (let userCounter = 0; userCounter < usernameEmails.length; userCounter++ ){ let usernameEmailText = usernameEmails[userCounter]; let userEmail = usernameEmailText.split('-')[1].trim(); userEmails.push(userEmail); } return userEmails;s } async getFilteredUserNameEmails() { let userNameEmails = []; let usersCount = await this.getFilteredUsersCount(); for (let userCounter = 0; userCounter < usersCount; userCounter++) { let user = await this.userFilterList.get(userCounter); let usernameEmailText = await user.getText(); userNameEmails.push(usernameEmailText); } CucumberReportLog.AddMessage("Filtered Users : " + JSON.stringify(userNameEmails), LOG_LEVELS.Debug); return userNameEmails; } async selectUserFromFilteredList(userNum){ let userToSelect = await this.userFilterList.get(userNum - 1); CucumberReportLog.AddMessage("Selected User : "+await userToSelect.getText(),LOG_LEVELS.Debug); await userToSelect.click(); } async isAddButtonEnabled(){ return await this.addUserBtn.isEnabled(); } async clickAddUserbutton(){ await this.addUserBtn.click(); this.testData_lastAddedUser = this.testData_lastSelectedUser; this.testData_lastSelectedUser = ""; CucumberReportLog.AddMessage("Click Add with user selected : " + this.testData_lastAddedUser, LOG_LEVELS.Debug); await this.testData_markUserWithEmailTobeAdded(this.testData_lastAddedUser); } async getCaseTitle(caseNum){ let selectedCase = await this.selectedCases.get(caseNum - 1); return await selectedCase.$('.govuk-case-title').getText(); } async getCaseSubtitle(caseNum) { let selectedCase = await this.selectedCases.get(caseNum - 1); return await selectedCase.$('.govuk-case-sub-title').getText(); } async clickDeselectCase(caseNum){ let selectedCase = await this.selectedCases.get(caseNum - 1); CucumberReportLog.AddMessage("Deselecting Case " + await selectedCase.getText(), LOG_LEVELS.Debug); await selectedCase.$('#btn-deselect-case').click(); await BrowserWaits.waitForCondition(async () => { return !(await selectedCase.isPresent()); }); } async clickCaseDetailsExpandCollapseBtn(caseNum){ let selectedCase = await this.selectedCases.get(caseNum - 1); let button = await selectedCase.$('.govuk-accordion__section-button'); await BrowserWaits.waitForElement(button, "Expand/collapse icon not present"); await browser.sleep(1); await browser.executeScript('arguments[0].scrollIntoView()', button); await button.click(); } async isCaseContentDisplayed(caseNum){ let selectedCase = await this.selectedCases.get(caseNum - 1); return await selectedCase.$('.govuk-accordion__section--expanded').isPresent(); } async getUsersCount(caseNum){ let selectedCase = await this.selectedCases.get(caseNum - 1); return await selectedCase.$$('tbody tr').count(); } async getActionLinkForUser(caseNum, userNum){ let selectedCase = await this.selectedCases.get(caseNum - 1); let user = await selectedCase.$$('tbody tr').get(userNum - 1); return user.$('a'); } async getActionLinkTextForUser(caseNum, userNum){ let actionLink = await this.getActionLinkForUser(caseNum, userNum); let linkText = await browser.executeScript('return arguments[0].textContent', actionLink); return linkText; } async clickActionLinkForUser(caseNum,userNum){ let actionLink = await this.getActionLinkForUser(caseNum, userNum); let actionLinktext = await actionLink.getText(); let caseid = await this.getCaseSubtitle(caseNum); let userEmail = await this.getEmailForUserIncase(caseNum, userNum); let actionLinkLabel = await this.getActionLabelForUserWithEmail(caseNum,userEmail); await actionLink.click(); if (actionLinktext === "Remove"){ ShareCaseData.MarkUserToUnShare(caseid,userEmail); CucumberReportLog.AddMessage(caseid + " Case user uis marked for Unshare "+userEmail); console.log("*********** Marking to Remove " + caseid+" : email "+userEmail); } else if (actionLinkLabel.includes("added")){ ShareCaseData.CancelMarkedForShare(caseid, userEmail); CucumberReportLog.AddMessage(caseid + " Case user uis marked for Share " + userEmail); console.log("*********** Cancel to be Added " + caseId + " : email " + userEmail); }else{ ShareCaseData.CancelMarkedForUnShare(caseid, userEmail); CucumberReportLog.AddMessage(caseid + " canceled Marked or Unshare " + userEmail); console.log("*********** Cancel to be removed " + caseId + " : email " + userEmail); } } async getEmailForUserIncase(caseNum, userNum) { let selectedCase = await this.selectedCases.get(caseNum - 1); let userRow = await selectedCase.$$('tbody tr').get(userNum - 1); let email = await browser.executeScript('return arguments[0].textContent', userRow.$('td:nth-of-type(2)')); return email; } async getActionStatusLabelForUser(caseNum, userNum) { let selectedCase = await this.selectedCases.get(caseNum - 1); let user = await selectedCase.$$('tbody tr').get(userNum - 1); let actionLabelCol = user.$('td:nth-of-type(4)'); let actionLabel = await browser.executeScript('return arguments[0].textContent', actionLabelCol); return actionLabel; } async getUserRowInCase(caseNum, email){ let selectedCase = await this.selectedCases.get(caseNum - 1); let users = selectedCase.$$('tbody tr'); let userCount = await users.count(); for (let user = 0; user < userCount; user++) { let userRow = await users.get(user); let userEmail = await browser.executeScript('return arguments[0].textContent', userRow.$('td:nth-of-type(2)')); if (userEmail === email) { return userRow; } } return null; } async isUserWithEmailListedInCase(caseNum,email){ let userRow = await this.getUserRowInCase(caseNum, email); return userRow !== null; } async isUserWithEmailMarkedToBeAdded(caseNum, email) { let userRow = await this.getUserRowInCase(caseNum, email); let actionLabel = await browser.executeScript('return arguments[0].textContent', userRow.$('td:nth-of-type(4)')); return actionLabel.toLowerCase().includes("added"); } async isUserWithEmailMarkedToBeRemoved(caseNum, email) { let userRow = await this.getUserRowInCase(caseNum, email); let actionLabel = await browser.executeScript('return arguments[0].textContent', userRow.$('td:nth-of-type(4)')); return actionLabel.toLowerCase().includes("removed"); } async getActionLabelForUserWithEmail(caseNum,email){ let selectedCase = await this.selectedCases.get(caseNum - 1); let users = selectedCase.$$('tbody tr'); let userCount = await users.count(); for (let user = 0; user < userCount; user++) { let userRow = await users.get(user); let userEmail = await browser.executeScript('return arguments[0].textContent', userRow.$('td:nth-of-type(2)')); if (userEmail === email) { let actionLabel = await browser.executeScript('return arguments[0].textContent', userRow.$('td:nth-of-type(4)')); return actionLabel; } } return "user not listed" } async getMessageDisplayedInNoCasesDisplayed(){ return await this.noCaseDisplay.getText(); } async clickOpenOrCloseAllLink(){ await BrowserWaits.waitForElement(this.openCloseAll, "OpenAll/CloaseAll button not present"); await this.openCloseAll.click(); } async getLinkTextForOpenOrCloseAlllink(){ await BrowserWaits.waitForElement(this.openCloseAll, "OpenAll/CloaseAll button not present"); return await this.openCloseAll.getText(); } async isUserWithEmailNotSharedWithAtleastOneCase(email){ let totalCases = await this.casesCount(); for(let i = 1 ; i <= totalCases; i++){ if(!(await this.isUserWithEmailListedInCase(i,email))){ return i; } } return 0; } async isUserWithEmailSharedWithAtleastOneCase(email) { let totalCases = await this.casesCount(); for (let i = 1; i <= totalCases; i++) { if ((await this.isUserWithEmailListedInCase(i, email))) { return i; } } return 0; } async selectUserWithEmail_Not_SharedWithAtLeastOneCase(){ let useremails = await this.getFilteredUserEmails(); let userToSelect = 0; let email = ""; for(let i = 0; i < useremails.length; i++){ email = useremails[i]; let caseNum = await this.isUserWithEmailNotSharedWithAtleastOneCase(email); if (caseNum > 0){ userToSelect = i + 1; break; } } if (userToSelect > 0){ await this.selectUserFromFilteredList(userToSelect); this.testData_lastSelectedUser = email; CucumberReportLog.AddMessage("Selected a user not shared with any case : "+email); }else{ throw Error("AllUsers shared with all selected cases. cannot proceed with test step to select a user not shared with atleast one case"); } } async selectUserWithEmail_SharedWithAtLeastOneCase() { let useremails = await this.getFilteredUserEmails(); let userToSelect = 0; let email = ""; for (let i = 0; i < useremails.length; i++) { email = useremails[i]; let caseNum = await this.isUserWithEmailSharedWithAtleastOneCase(email); if (caseNum > 0) { userToSelect = i + 1; break; } } if (userToSelect > 0) { await this.selectUserFromFilteredList(userToSelect); this.testData_lastSelectedUser = email; CucumberReportLog.AddMessage("Selected a user shared with atleast one case : " + email); } else { throw Error("No user is list is shared with any case already. cannot proceed with test step to select a user not shared with atleast one case"); } } async isLastAddedUserListedInAllCases(){ let casesCount = await this.casesCount(); for(let i = 1; i<= casesCount; i++){ if(!(await this.isUserWithEmailListedInCase(i,this.testData_lastAddedUser))){ return false; } } return true; } async isLastAddedUserMarkedTobeAddedInAnyCase() { let casesCount = await this.casesCount(); for (let i = 1; i <= casesCount; i++) { if(await this.isUserWithEmailMarkedToBeAdded(i, this.testData_lastAddedUser)){ return true; } } return false; } async isAnyUserMarkedToBeRemoved() { let casesCount = await this.casesCount(); for (let i = 1; i <= casesCount; i++) { let usersCountInCase = await this.getUsersCount(i); for (let userCounter = 1; userCounter <= usersCountInCase; userCounter++) { let userActionLabel = await this.getActionStatusLabelForUser(i, userCounter); if (userActionLabel.toLowerCase().includes("remove")) { return true; } } } return false; } async clickRemoveForAUserInListedCases(){ let casesCount = await this.casesCount(); for (let caseCounter = 1; caseCounter <= casesCount; caseCounter++) { let usersCountInCase = await this.getUsersCount(caseCounter); for (let userCounter = 1; userCounter <= usersCountInCase; userCounter++ ){ let actionLinktext = await this.getActionLinkTextForUser(caseCounter, userCounter); if (actionLinktext.toLowerCase().includes("remove")){ if(!(await this.isCaseContentDisplayed(caseCounter))){ CucumberReportLog.AddMessage("Expanding Case at pos " + caseCounter); await this.clickCaseDetailsExpandCollapseBtn(caseCounter); } CucumberReportLog.AddMessage("Click Remove link for case pos" + caseCounter + " user pos " + userCounter); await this.clickActionLinkForUser(caseCounter, userCounter); return; } } } throw Error("No cases have cases already shared or not marked to be removed. Cannot proceed with scenario."); } async validateShareCaseChangesPersisted(){ let casesCount = await this.casesCount(); let issuesList = []; for (let caseCounter = 1; caseCounter <= casesCount; caseCounter++) { let caseId = await this.getCaseSubtitle(caseCounter); let caseShareData = ShareCaseData.getCaseWithId(caseId); CucumberReportLog.AddJson(caseShareData); for (let shareWithCounter = 0; shareWithCounter < caseShareData.sharedWith.length ; shareWithCounter++){ let email = caseShareData.sharedWith[shareWithCounter]; if(!(await this.isUserWithEmailListedInCase(caseCounter,email))){ issuesList.push(email + "already shared user is not listed for in case " + caseId); } } for (let shareWithCounter = 0; shareWithCounter < caseShareData.markedForShare.length; shareWithCounter++) { let email = caseShareData.markedForShare[shareWithCounter]; if (!(await this.isUserWithEmailMarkedToBeAdded(caseCounter, email))) { issuesList.push(email + "marked for added in not persisted " + caseId); } } for (let shareWithCounter = 0; shareWithCounter < caseShareData.markedForUnShare.length; shareWithCounter++) { let email = caseShareData.markedForUnShare[shareWithCounter]; if (!(await this.isUserWithEmailMarkedToBeRemoved(caseCounter, email))) { issuesList.push(email + "marked to remove in not persisted " + caseId); } } } return issuesList; } } module.exports = ShareCasePage;
// @flow import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import {createStore} from 'redux'; import registerServiceWorker from './registerServiceWorker'; import {counterReducer} from './counter'; import {ShowCurrentDate} from './show-date-inject-hoc-example'; import {Counter} from './counter'; const store = createStore( counterReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); const rootElement = document.getElementById('root'); if (!rootElement) { throw Error('no root element'); } ReactDOM.render( <Provider store={store}> <div> <ShowCurrentDate formatter={date => date.toString()}/> <ShowCurrentDate prefix='++' formatter={date => date.toString()}/> {/*<ShowCurrentDate prefix={3} formatter={date => date.toString()}/> wrong type*/} {/*<ShowCurrentDate /> prop missing*/} {/*<ShowCurrentDate formatter={() => ''} bla={3} /> unnecessary prop*/} <Counter prefix='>>> ' multiplicator={1} /> <Counter multiplicator={5} /> {/*<Counter /> prop missing*/} {/*<Counter multiplicator={5} bla={3} /> unnecessary prop*/} </div> </Provider>, rootElement ); registerServiceWorker();
var db = require('../db.js'); var _ = require('underscore'); module.exports.getWikiText = function(req, res) { var limit = Number(req.query.limit) || 10; var page = Number(req.query.page) || 1; var offset = (page - 1 ) * limit ; db.wikiText.findAll({ offset: offset, limit:limit, attributes : ['title', 'wikiTxt'] }).then(function(wiki){ if(wiki){ res.json(wiki); } else{ res.json("No wiki in DB"); } }); }; module.exports.getWikiTags = function(req, res) { var offset = req.query.offset || 0; var limit = req.query.limit || 10; db.wikiTags.findAll({ offset: offset, limit:limit, attributes : ['title', 'wikiTag'] }).then(function(wiki){ if(wiki){ res.json(wiki); } else{ res.json("No wiki in DB"); } }); };
[{"locale": "es"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Alfa"}}, "key": "1D6E2" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Beta"}}, "key": "1D6E3" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Gamma"}}, "key": "1D6E4" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Delta"}}, "key": "1D6E5" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Épsilon"}}, "key": "1D6E6" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Zeta"}}, "key": "1D6E7" }, {"category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Eta"}}, "key": "1D6E8"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Theta"}}, "key": "1D6E9" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Iota"}}, "key": "1D6EA" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Kappa"}}, "key": "1D6EB" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Lambda"}}, "key": "1D6EC" }, {"category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Mi"}}, "key": "1D6ED"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Ni"}}, "key": "1D6EE" }, {"category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Xi"}}, "key": "1D6EF"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Ómicron"}}, "key": "1D6F0" }, {"category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Pi"}}, "key": "1D6F1"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Rho"}}, "key": "1D6F2" }, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Sigma"}}, "key": "1D6F4" }, {"category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Tau"}}, "key": "1D6F5"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Ípsilon"}}, "key": "1D6F6" }, {"category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Phi"}}, "key": "1D6F7"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Ji"}}, "key": "1D6F8" }, {"category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Psi"}}, "key": "1D6F9"}, { "category": "Lu", "mappings": {"default": {"default": "cursiva mayúscula Omega"}}, "key": "1D6FA" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva alfa"}}, "key": "1D6FC"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva beta"}}, "key": "1D6FD" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva gamma"}}, "key": "1D6FE"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva delta"}}, "key": "1D6FF" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva épsilon"}}, "key": "1D700"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva zeta"}}, "key": "1D701" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva eta"}}, "key": "1D702"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva theta"}}, "key": "1D703" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva iota"}}, "key": "1D704"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva kappa"}}, "key": "1D705" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva lambda"}}, "key": "1D706"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva mi"}}, "key": "1D707" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva ni"}}, "key": "1D708"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva xi"}}, "key": "1D709" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva ómicron"}}, "key": "1D70A"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva pi"}}, "key": "1D70B" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva rho"}}, "key": "1D70C"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva final sigma"}}, "key": "1D70D" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva sigma"}}, "key": "1D70E"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva tau"}}, "key": "1D70F" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva ípsilon"}}, "key": "1D710"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva phi"}}, "key": "1D711" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva ji"}}, "key": "1D712"}, { "category": "Ll", "mappings": {"default": {"default": "cursiva psi"}}, "key": "1D713" }, {"category": "Ll", "mappings": {"default": {"default": "cursiva omega"}}, "key": "1D714"}]
import React, { Component } from "react"; import {Typography } from "components"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import {CopyText} from "../../copy"; import UserContext from "containers/App/UserContext"; import classNames from "classnames"; import Skeleton, { SkeletonTheme } from 'react-loading-skeleton'; import { getSkeletonColors, loadFakeBets, getApp } from "../../lib/helpers"; import delay from 'delay'; import "./index.css"; class TableDefault extends Component { intervalID = 0; static contextType = UserContext; static propTypes = { onHandleLoginOrRegister: PropTypes.func.isRequired }; constructor(props){ super(props); this.state = { rows : [], isLoadingRow : false }; } componentDidMount(){ this.projectData(this.props); const { showRealTimeLoading } = this.props; if(showRealTimeLoading) { this.intervalID = setInterval( async () => { this.setState({ isLoadingRow : false }); this.addRow(); }, 6000); } } componentWillReceiveProps(props){ this.projectData(props); } componentWillUnmount() { clearInterval(this.intervalID); } projectData = async (props) => { this.setState({ rows : props.rows}); } addRow = async () => { let { rows } = this.state; const { showRealTimeLoading, size, games } = this.props; if(showRealTimeLoading) { await delay(1000); rows = loadFakeBets(rows, games, size); this.setState({ rows, isLoadingRow : true }); } } createSkeletonRows = () => { let tabs = [] for (let i = 0; i < 10; i++) { tabs.push(<div styleName="skeleton-row"><Skeleton height={30} /></div>); } return tabs } getCurrencyImage(isCurrency, currencyId) { if(!isCurrency) return null; const currencies = getApp().currencies; const currency = (currencies.find(currency => currency._id == currencyId)); const appWallet = getApp().wallet.find(w => w.currency._id === currencyId); if(!currency) return null; return ( <img src={appWallet.image != null ? appWallet.image : currency.image} width={16} height={16}/> ) } renderGameColumn(row, background) { return ( <div styleName="image"> <div styleName="icon" style={{ background: background ? 'url('+background+') center center / cover no-repeat' : 'none'}}><img styleName='image-icon' src={row.image_url}/></div> <div styleName='image-name'><Typography variant='x-small-body' color={"grey"}> {row.name} </Typography></div> </div> ); } render() { let { isLoadingRow, rows } = this.state; let { titles, fields, isLoading, onTableDetails, tag, ln} = this.props; const copy = CopyText.tableIndex[ln]; const rowStyles = classNames("tr-row", { addRow: isLoadingRow }); return ( <div> {isLoading ? <SkeletonTheme color={ getSkeletonColors().color} highlightColor={ getSkeletonColors().highlightColor}> <div style={{opacity : '0.5'}}> {this.createSkeletonRows()} </div> </SkeletonTheme> : <div> <table styleName='table-row'> <thead styleName='table-head'> <tr styleName='tr-row'> {titles.map( text => <th styleName='th-row'> <Typography variant='x-small-body' color="grey" weight="bold"> {text} </Typography> </th> )} </tr> </thead> <tbody> { rows.map( (row) => <tr styleName={rowStyles}> {fields.map( (field, index) => { const styles = classNames("td-row", { 'td-row-img': field.image, 'td-row-currency': field.currency, 'td-row-state': field.isStatus }); const statusStyles = classNames("status"); if(field.dependentColor){ return ( <td styleName={styles} data-label={titles[index]}> {onTableDetails ? <a href="#" onClick={onTableDetails.bind(this, {titles, fields, row, tag})}> <Typography variant='x-small-body' color={ row[field.condition] ? 'green' : "grey"}> {row[field.value]} </Typography> {this.getCurrencyImage(field.currency, row['currency'])} </a> : <div> <Typography variant='x-small-body' color={ row[field.condition] ? 'green' : "grey"}> {row[field.value]} </Typography> {this.getCurrencyImage(field.currency, row['currency'])} </div> } </td> ) }else if(field.image){ const background = row[field.value].hasOwnProperty("background_url") ? row[field.value].background_url : null; return ( <td styleName={styles} data-label={titles[index]}> {onTableDetails ? <a href="#" onClick={onTableDetails.bind(this, {titles, fields, row, tag})}> {this.renderGameColumn(row[field.value], background)} </a> : this.renderGameColumn(row[field.value], background) } </td> ) }else if(field.isLink === true){ return ( <td styleName={styles} data-label={titles[index]}> <a href={row[field.linkField]} target={'_blank'}> <Typography variant={'x-small-body'} color='white'> {row[field.value]} </Typography> </a> </td> ) }else if(field.isStatus === true){ return ( <td styleName={styles} data-label={titles[index]}> <div styleName={statusStyles}> {onTableDetails ? <a href="#" onClick={onTableDetails.bind(this, {titles, fields, row, tag})}> <Typography variant='x-small-body' color={"fixedwhite"} weight={"bold"}> {row[field.value].text} </Typography> </a> : <div> <Typography variant='x-small-body' color={"fixedwhite"} weight={"bold"}> {row[field.value].text} </Typography> </div> } </div> </td> ) } else{ return ( // Normal <td styleName={styles} data-label={titles[index]}> {onTableDetails ? <a href="#" onClick={onTableDetails.bind(this, {titles, fields, row, tag})}> <Typography variant='x-small-body' color={"white"}> {row[field.value]} </Typography> {this.getCurrencyImage(field.currency, row['currency'])} </a> : <div> <Typography variant='x-small-body' color={"white"}> {row[field.value]} </Typography> {this.getCurrencyImage(field.currency, row['currency'])} </div> } </td> ) } })} </tr>) } </tbody> </table> { !rows.length ? <div styleName="no-info"> <Typography variant='small-body' color={"grey"}>{copy.TITLE}</Typography> </div> : null } </div> } </div> ); } } function mapStateToProps(state){ return { ln : state.language, }; } export default connect(mapStateToProps)(TableDefault);
export const lifecycleEquivalents = `// componentDidMount useEffect(() => { console.log('componentDidMount') }, []) // componentDidUpdate const isUpdate = useRef(false) useEffect(() => { if (isUpdate.current) { console.log('componentDidUpdate') } else { isUpdate.current = true } }) // componentWillUnmount useEffect(() => { return () => console.log('componentWillUnmount') }) `
import React from 'react'; import { connect } from 'react-redux'; import { LoggedOutCart} from '../Components/LoggedOutCart'; import CartItem from '../Components/CartItem'; import { checkoutCart } from '../Actions/ActiveCart'; import Payment from '../Components/stripe'; class Cart extends React.Component{ render() { window.scrollTo(0, 0); // ------------------------ Checks for User auth ----------------------------------------------------------------------------- const userLoggedIn = sessionStorage.getItem('Bearer'); // console.log('CART DATA', this.props.cart) // ---------------- Render LoggedOutCart if token is not available------------------------------------------------------ if(!userLoggedIn) { return(<LoggedOutCart />) } //----------------------------- function to multiply each item's price by it's quantity ------------------------------ let eachItemTotal = this.props.cart.map(i => i.price * i.quantity) //-------------------------- returns array of total price for each item --------------------------------------------------------------------- // console.log('eachItemTotal', eachItemTotal) //------------------------------------- if else function to join array total depending on the length of array ------------------------------------------------------------ const getGranTotal = (arr) => { if(arr.length === 0) { return '' } else if (arr.length === 1) { return arr.join('') } else if (arr.length > 1) { let sum = arr.reduce((acc, item) => { return acc + item }) return sum } } let cartTotal = getGranTotal(eachItemTotal); // console.log('TOTALLL', cartTotal) let totalItems = this.props.cart.length; // -------------------------------------- Conditional Rendering for whether Cart is empty or not ---------------------------------------------- if(this.props.cart.length === 0 && userLoggedIn) { return<div className="empty-cart"> <h4>Your Royal Bag is empty.</h4> </div> } else { return( <div className="cart-container"> <div className="items-container"> <p>Shopping Cart</p> {this.props.cart.map(i => { return <CartItem item={i}/> })} </div> <div className="total-container"> { totalItems > 1 ? <p>Items ({totalItems})</p> : <p>Item ({totalItems})</p> } <hr/> <p>Total ${cartTotal}</p> <div> <Payment total={cartTotal} items={this.props.cart} /> </div> </div> </div> ) } } } const mapStateToProps = state => ({ cart: state.cart.cartItems }); export default connect(mapStateToProps, { checkoutCart })(Cart);
export default { props: ['categories', 'mainCounter', 'mainCounterIdx', 'isHovered'], template: ` <aside @mouseover="toggleHover(true)" @mouseleave="toggleHover(false)" class="side-bar" > <div v-if="categories" v-for="(category,idx) in categories" @click="filterBy(category)" > <span class="side-bar-category"> <span class="main-counter" v-if="mainCounter && idx===mainCounterIdx" > {{mainCounter}} </span> <i :class="category.icon" class="side-bar-icons"> </i> <transition enter-active-class="animate__animated animate__backInLeft" leave-active-class="animate__animated animate__backOutLeft" > <span class="capitalize" v-if="hover"> {{categoryToShow(category)}}</span> </transition> </span> </div> </aside> `, data() { return { hover: false } }, methods: { filterBy(category) { this.$emit('setFilter', category.text) }, toggleHover(hovering) { if (!this.isHovered) { this.hover = true return } this.hover = hovering }, categoryToShow(category) { return category.text.split(':')[0] } }, computed: { }, created() { this.toggleHover() }, watch: { data: { immediate: true, deep: true, handler(newValue, oldValue) { } } }, }
// refer temperature formula for more info const ftoc = function (fTemp) { // refer code in the comment return Math.round((fTemp - 32) * (5 / 9) * 10) / 10; // let cResult = ((fTemp - 32) * 5) / 9; // let cRounded = Math.round(cResult * 10) / 10; // return cRounded; }; const ctof = function (cTemp) { // refer code in the comment return Math.round(((cTemp * 9) / 5 + 32) * 10) / 10; // let fResult = (cTemp * 9) / 5 + 32; // let fRounded = Math.round(fResult * 10) / 10; // return fRounded; }; module.exports = { ftoc, ctof, };
import CommentListPresenter from "./comment-list.js"; import MovieCardView from "../view/movie-card.js"; import MoviePopupView from "../view/movie-popup.js"; import CommetnsLoadingView from "../view/commetns-loading.js"; import {RenderPosition, replace, render, remove} from "../utils/render.js"; import {UserAction, UpdateType, Mode} from "../const.js"; export default class Movie { constructor(moviesListContainer, changeData, changeMode, moviesModel, commentsModel, api) { this._moviesListContainer = moviesListContainer; this._changeData = changeData; this._changeMode = changeMode; this._moviesModel = moviesModel; this._commentsModel = commentsModel; this._api = api; this._commetnsLoadingComponent = new CommetnsLoadingView(); this._movieComponent = null; this._moviePopupComponent = null; this._commentPresenter = null; this._mode = Mode.CLOSED; this._openMoviePopup = this._openMoviePopup.bind(this); this._handleWatchlistClick = this._handleWatchlistClick.bind(this); this._handleWatchedClick = this._handleWatchedClick.bind(this); this._handleFavoriteClick = this._handleFavoriteClick.bind(this); this._closeMoviePopup = this._closeMoviePopup.bind(this); this._onEscKeyDown = this._onEscKeyDown.bind(this); } init(movie) { this._movie = movie; this._renderMovieComponent(); if (this._mode === Mode.OPENED) { this._replaceMoviePopup(); } } resetView() { if (this._mode !== Mode.CLOSED) { this._closeMoviePopup(); } } _configMoviePopup() { this._moviePopupComponent = new MoviePopupView(this._movie); this._commentsContainer = this._moviePopupComponent.getElement().querySelector(`.form-details__bottom-container`); this._moviePopupComponent.setAddToWatchlistHandler(this._handleWatchlistClick); this._moviePopupComponent.setAlreadyWatchedHandler(this._handleWatchedClick); this._moviePopupComponent.setAddToFavoritsHandler(this._handleFavoriteClick); this._moviePopupComponent.setClosePopupHandler(this._closeMoviePopup); } _replaceMoviePopup() { const prevMoviePopupComponent = this._moviePopupComponent; this._configMoviePopup(); replace(this._moviePopupComponent, prevMoviePopupComponent); remove(prevMoviePopupComponent); this._renderComments(); } _renderMovieComponent() { const prevMovieComponent = this._movieComponent; this._movieComponent = new MovieCardView(this._movie); this._movieComponent.setShowPopupHandler(this._openMoviePopup); this._movieComponent.setAddToWatchlistHandler(this._handleWatchlistClick); this._movieComponent.setAlreadyWatchedHandler(this._handleWatchedClick); this._movieComponent.setAddToFavoritsHandler(this._handleFavoriteClick); if (prevMovieComponent === null) { render(this._moviesListContainer, this._movieComponent, RenderPosition.BEFOREEND); return; } replace(this._movieComponent, prevMovieComponent); remove(prevMovieComponent); } destroy() { if (this._movieComponent) { remove(this._movieComponent); } if (this._moviePopupComponent) { remove(this._moviePopupComponent); } } _onEscKeyDown(evt) { if (evt.key === `Escape` || evt.key === `Esc`) { evt.preventDefault(); this._closeMoviePopup(); document.removeEventListener(`keydown`, this._onEscKeyDown); } } _openMoviePopup() { this._configMoviePopup(); render(document.body, this._moviePopupComponent, RenderPosition.BEFOREEND); this._loadComments().then(() => this._renderComments()); document.addEventListener(`keydown`, this._onEscKeyDown); this._changeMode(); this._mode = Mode.OPENED; } _closeMoviePopup() { remove(this._moviePopupComponent); document.removeEventListener(`keydown`, this._onEscKeyDown); this._mode = Mode.CLOSED; } _renderComments() { if (this._commentListPresenter) { this._commentListPresenter.destroy(); this._commentListPresenter = null; } this._commentListPresenter = new CommentListPresenter(this._commentsContainer, this._movie, this._commentsModel, this._changeData, this._api); this._commentListPresenter.init(); } _loadComments() { render(this._commentsContainer, this._commetnsLoadingComponent); return this._api.getComments(this._movie) .then((comments) => { remove(this._commetnsLoadingComponent); this._commentsModel.setComments(comments); }); } _toggleMovieProperty(propertyName) { const update = Object.assign( {}, this._movie, { [propertyName]: !this._movie[propertyName] } ); this._api.updateMovies(update).then((updatedMovie) => { this._changeData( UserAction.UPDATE_MOVIE, UpdateType.MINOR, Object.assign( {}, updatedMovie ) ); }).catch(() => { this._movieComponent.shake(); }); } _handleWatchlistClick() { this._toggleMovieProperty(`isAddedInWachlist`); } _handleWatchedClick() { this._toggleMovieProperty(`isWatched`); } _handleFavoriteClick() { this._toggleMovieProperty(`isFavorite`); } }
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ layout_static = require('pixel.static') },{"pixel.static":2}],2:[function(require,module,exports){ module.exports = layout; function layout(graph, options) { options = options || {}; var initPos = typeof options.initPosition === 'function' ? options.initPosition : initPosDefault; var api = { step: function noop() { return true; }, /** * Gets position of a given node by its identifier. Required. * * @param {string} nodeId identifier of a node in question. * @returns {object} {x: number, y: number, z: number} coordinates of a node. */ getNodePosition: getNodePosition }; var positions = {}; graph.forEachNode(setInitialPosition); return api; function setInitialPosition(node) { positions[node.id] = initPos(node); } function getNodePosition(nodeId) { return positions[nodeId]; } function initPosDefault(node) { positions[node.id] = node.data; } } },{}]},{},[1]);
import KeyCodes from 'keycodes-enum'; import AccessibilityModule from '../../index'; describe('TabListData', () => { describe('register role', () => { let cjsTabList; let divEl; let shouldEnableKeyEvents; let levelVal; let isMultiselectable; let orientationVal; beforeEach(() => { cjsTabList = new createjs.Shape(); // dummy object shouldEnableKeyEvents = false; levelVal = 99; isMultiselectable = false; orientationVal = 'horizontal'; AccessibilityModule.register({ accessibleOptions: { enableKeyEvents: shouldEnableKeyEvents, level: levelVal, multiselectable: isMultiselectable, orientation: orientationVal, }, displayObject: cjsTabList, parent: container, role: AccessibilityModule.ROLES.TABLIST, }); stage.accessibilityTranslator.update(); divEl = parentEl.querySelector('div[role=tablist]'); }); describe('rendering', () => { it('creates div[role=tablist] element', () => { expect(divEl).not.toBeNull(); }); it('sets "aria-level" attribute', () => { expect(parseInt(divEl.getAttribute('aria-level'), 10)).toEqual( levelVal ); }); it('sets "aria-multiselectable" attribute', () => { const ariaMultiselectable = divEl.getAttribute('aria-multiselectable') === 'true'; expect(ariaMultiselectable).toEqual(isMultiselectable); }); it('sets "aria-orientation" attribute', () => { expect(divEl.getAttribute('aria-orientation')).toEqual(orientationVal); }); }); describe('accessible options getters and setters', () => { it('can read and set "level" property [for "aria-level"]', () => { expect(cjsTabList.accessible.level).toEqual(levelVal); const newVal = -1; cjsTabList.accessible.level = newVal; expect(cjsTabList.accessible.level).toEqual(newVal); }); it('can read and set "multiselectable" property [for "aria-multiselectable"]', () => { expect(cjsTabList.accessible.multiselectable).toEqual( isMultiselectable ); const newVal = true; cjsTabList.accessible.multiselectable = newVal; expect(cjsTabList.accessible.multiselectable).toEqual(newVal); }); it('can read and set "orientation" property [for "aria-orientation"]', () => { expect(cjsTabList.accessible.orientation).toEqual(orientationVal); const newVal = 'vertical'; cjsTabList.accessible.orientation = newVal; expect(cjsTabList.accessible.orientation).toEqual(newVal); }); }); describe('other options getters and setters', () => { it('can read and set "enableKeyEvents" property', () => { expect(cjsTabList.accessible.enableKeyEvents).toEqual( shouldEnableKeyEvents ); const newVal = true; cjsTabList.accessible.enableKeyEvents = newVal; expect(cjsTabList.accessible.enableKeyEvents).toEqual(newVal); }); }); describe('"onKeyDown" event listener', () => { let keyCode; let onKeyDown; beforeEach(() => { onKeyDown = jest.fn(); cjsTabList.on('keydown', onKeyDown); }); it('can dispatch "keyDown" event if "enableKeyEvents" is enabled', () => { keyCode = KeyCodes.down; divEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(onKeyDown).toBeCalledTimes(0); cjsTabList.accessible.enableKeyEvents = true; divEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(onKeyDown).toBeCalledTimes(1); }); it('can prevent default events if "defaultPrevented" is true', () => { keyCode = KeyCodes.down; cjsTabList.accessible.enableKeyEvents = true; const keydownEvent = new KeyboardEvent('keydown', { keyCode }); Object.defineProperty(keydownEvent, 'defaultPrevented', { value: true, }); divEl.dispatchEvent(keydownEvent); expect(onKeyDown).toBeCalledTimes(1); }); describe('can change active/selected child when proper key is pressed', () => { let cjsListItem1; // dummy child object let cjsListItem2; // dummy child object beforeEach(() => { cjsListItem1 = new createjs.Shape(); AccessibilityModule.register({ displayObject: cjsListItem1, role: AccessibilityModule.ROLES.SPAN, }); cjsTabList.accessible.addChild(cjsListItem1); cjsListItem2 = new createjs.Shape(); AccessibilityModule.register({ displayObject: cjsListItem2, role: AccessibilityModule.ROLES.SPAN, }); cjsTabList.accessible.addChild(cjsListItem2); stage.accessibilityTranslator.update(); cjsTabList.accessible.selected = cjsListItem2; cjsTabList.accessible.enableKeyEvents = true; }); it('UP AND DOWN', () => { cjsTabList.accessible.orientation = 'vertical'; keyCode = KeyCodes.up; divEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(onKeyDown).toBeCalledTimes(1); keyCode = KeyCodes.down; divEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(onKeyDown).toBeCalledTimes(2); }); it('LEFT AND RIGHT', () => { keyCode = KeyCodes.left; divEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(onKeyDown).toBeCalledTimes(1); keyCode = KeyCodes.right; divEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(onKeyDown).toBeCalledTimes(2); }); }); }); }); });
//load the things we need var mongoose = require('mongoose'); //define the schema for our user model var photoSchema = mongoose.Schema({ polishid: String, userid: String, location: String, creditname: String, creditlink: String, pendingdelete: Boolean, pendingreason: String, }); //create the model for users and expose it to our app module.exports = mongoose.model('Photo', photoSchema);
export const MANAGE_USERS_REQUEST = 'MANAGE_USERS_REQUEST'; export const MANAGE_USERS_SUCCESS = 'MANAGE_USERS_SUCCESS'; export const MANAGE_USERS_FAILURE = 'MANAGE_USERS_FAILURE'; export const ADD_USER_REQUEST = 'ADD_USER_REQUEST'; export const ADD_USER_SUCCESS = 'ADD_USER_SUCCESS'; export const ADD_USER_FAILURE = 'ADD_USER_FAILURE'; export const EDIT_USER_REQUEST = 'EDIT_USER_REQUEST'; export const EDIT_USER_SUCCESS = 'EDIT_USER_SUCCESS'; export const EDIT_USER_FAILURE = 'EDIT_USER_FAILURE'; export const GENERATE_PASSWORD_REQUEST = 'GENERATE_PASSWORD_REQUEST'; export const GENERATE_PASSWORD_SUCCESS = 'GENERATE_PASSWORD_SUCCESS'; export const GENERATE_PASSWORD_FAILURE = 'GENERATE_PASSWORD_FAILURE'; export const ROLE_LIST_REQUEST = 'ROLE_LIST_REQUEST'; export const rolesList = [ { name: 'user', value: 1 }, { name: 'admin', value: 2 }, ]; export const cityList = [ { label: 'Delhi', value: 1 }, { label: 'Chandigarh', value: 2 }, { label: 'Allahabad', value: 3 }, ]; export const manageUserFilters = [ { name: 'Name', placeholder: 'Rahul Kumar', type: 'text', }, { name: 'Mobile Number', placeholder: '9876543263', type: 'number', }, { name: 'Role', options: rolesList, type: 'select', }, // { // name: 'City', // options: cityList, // type: 'multiSelect', // }, { name: 'Date Created', type: 'dateRange', }, { name: 'Email', placeholder: 'admin@moneyloji.com', type: 'text', }, ];
const path = require('path'); const bcryptjs = require('bcryptjs'); const { Router } = require('express'); const { check, validationResult } = require('express-validator'); const { validarJWT } = require('../middlewares/validar_jwt'); const { generarJWT } = require('../helpers/generar_jwt'); const db = require('../db/connection.js'); const campos = ['id', 'email', 'encrypted_password', 'createdAt', 'updatedAt']; const __usuario = {email: '', password: ''}; const existeEmail = async (email) => { __usuario.email = email; try { const usuario = await db.Users.findOne({ where: { email } }); if (!usuario) { return Promise.reject( 'El usuario o la contraseña son incorrectos'); } } catch (error) { console.log(error); return Promise.reject('Tenemos algún problema con la identificación del usuario. Por favor, póngase en contacto con el administrador'); } }; const validarPassword = async (password) => { __usuario.password = password; try { const usuario = await db.Users.findOne({ where: { email: __usuario.email } }); const validPassword = bcryptjs.compareSync(password, usuario.encrypted_password); if (!validPassword) { return Promise.reject('El usuario o la contraseña son incorrectos'); } } catch (error) { console.log(error); return Promise.reject('El usuario no existe'); } }; const elEmailYaExiste = async (email) => { try { const usuario = await db.Users.findOne({ where: { email } }); if (usuario) { return Promise.reject('El email ya está siendo utilizado'); } } catch (error) { console.log(error); return Promise.reject('Tenemos algún problema con la identificación del usuario. Por favor, póngase en contacto con el administrador'); } }; const verificarLogin = [ check('email', 'El correo electrónico es obligatorio').isEmail(), check('password', 'La contraseña es obligatoria').not().isEmpty(), check('email').custom(existeEmail), check('password').custom(validarPassword), (req, res, next) => { const errors = validationResult(req); errors.array().map((elem) => { globalThis.arrayAlertaGlobal.push(elem.msg); globalThis.colorAlerta = 'danger'; }); if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() }); next(); }, ]; const verificarPreReset = [ validarJWT, (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() }); next(); }, ]; const verificarReset = [ validarJWT, check('password', 'Necesita aportar la contraseña').not().isEmpty(), check('repetir_password', 'Debe aportar la contraseña repetida').not().isEmpty(), check('password', 'El password debe de ser más de 6 letras').isLength({ min: 6, }), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() }); next(); }, ]; const verificarSingin = [ check('email', 'El correo electrónico es obligatorio').isEmail(), check('password', 'Necesita aportar la contraseña').not().isEmpty(), check('repetir_password', 'Debe aportar la contraseña repetida').not().isEmpty(), // check('repetir_password', 'Las contraseñas deben coincidir').custom(( value, { req } ) => { value === req.body.password}), check('email').custom(elEmailYaExiste), (req, res, next) => { const errors = validationResult(req); errors.array().map((elem) => { globalThis.arrayAlertaGlobal.push(elem.msg); globalThis.colorAlerta = 'danger'; }); if (!errors.isEmpty()) return res.status(422).json({ errors: errors.array() }); next(); }, ]; const crearUsuario = async (u) => { const nUsuario = { email: u.email, encrypted_password: bcryptjs.hashSync(u.password, 10), }; try { const contador = await db.Users.count({}); const usuario = await db.Users.create(nUsuario); let identificadorRol = 'Usuario'; if (contador === 0) identificadorRol = 'Administrador'; await db.UserRol.create({ user_id: usuario.dataValues.id, rol: identificadorRol }); } catch (error) { console.log(error); } }; module.exports = () => { const router = Router(); router .route('/') .get((req, res) => { res.status(200).render(path.join(__dirname, '../views/login/', 'login.hbs'), { alerta: globalThis.alertaGlobal, colorAlerta: globalThis.colorAlerta, a_alertas: globalThis.arrayAlertaGlobal, layout: '' }); globalThis.arrayAlertaGlobal = []; globalThis.alertaGlobal = ''; }) .post(verificarLogin, async (req, res) => { generarJWT(__usuario).then((token) => { res.status(200).json({ token }); }); }); router .route('/register') .get((req, res) => { res.status(200).render(path.join(__dirname, '../views/login/', 'registrar.hbs'), { alerta: globalThis.alertaGlobal, colorAlerta: globalThis.colorAlerta, a_alertas: globalThis.arrayAlertaGlobal, layout: '' }); globalThis.arrayAlertaGlobal = []; globalThis.alertaGlobal = ''; }) .post(verificarLogin, async (req, res) => { generarJWT(__usuario).then((token) => { res.status(200).json({ token }); }); }); router .route('/singin') .post(verificarSingin, async (req, res) => { const usuario = {email: req.body.email, password: req.body.password }; crearUsuario(usuario); generarJWT(usuario).then((token) => { res.status(200).json({ token }); }); }); router .route('/reset') .get(verificarPreReset, (req, res) => { if (req.usuario.email) res.status(200).render( path.join(__dirname, '../views/login/', 'reset.hbs'), { layout: '', token: req.query.tokenparam, email: req.usuario.email, }); else res.status(200).render(path.join(__dirname, '../views/login/', 'error.hbs'), { layout: '' }); }) .post(verificarReset, async (req, res) => { const { email } = req.usuario; const { password, repetir_password } = req.body; db.Users.findOne({ where: { email, }, attributes: campos, }).then((registro) => { if (!registro) throw new Error('Registro no encontrado'); if (password === repetir_password) { const valores = { encrypted_password: bcryptjs.hashSync(password, 10) }; registro.update(valores).then((actualizado) => { db.Tokens.create({ revocado: req.query.tokenparam }).then(() => { globalThis.alertaGlobal = 'Contraseña actualizada correctamente'; globalThis.colorAlerta = 'success'; console.log(`Contraseña actualizada correctamente ${JSON.stringify(actualizado, null, 2)}` ); res.redirect(`/login`); //globalThis.alertaGlobal = ''; }); }); } else { globalThis.alertaGlobal = 'ERROR: la nueva contraseña y la repetición de la misma debe coincidir, vuelva a intentarlo'; globalThis.colorAlerta = 'danger'; res.redirect(`/login/reset?tokenparam=${req.query.tokenparam}`); //globalThis.alertaGlobal = ''; } }).catch((error) => { globalThis.alertaGlobal = 'ERROR: no fue posible modificar el usuario correctamente, vuelva a intentarlo'; globalThis.colorAlerta = 'danger'; console.log(error); res.redirect(`/login?tokenparam=${req.query.tokenparam}`); //globalThis.alertaGlobal = ''; }); }); router .route('/forgot') .get((req, res) => { res.status(200).render(path.join(__dirname, '../views/login/', 'olvido.hbs'), { layout: '' }); }).post( (req, res) => { const usuario = {email: req.body.email, password: 'resetear' }; generarJWT(usuario, '10m').then((token) => { const email = require('../helpers/email.js'); email.enviarEmail(req.body.email, ` Buenos días, para realizar el cambio de contraseña, debe usted hacer clic sobre el siguiente enlace. El enlace caduca en 10 minutos. https://rotaciones.herokuapp.com/login/reset?tokenparam=${ token } Atentamente, El administrador del sistema. `, 'Recuperación de contraseña para la app Rotaciones' ); }); res.status(200).json({ msg: 'Este mensaje no sirve para nada, solo devolvemos algo a la función fetch del navegador' }); }); router .route('/email') .get((req, res) => { globalThis.alertaGlobal = 'Se le ha enviado un email con instrucciones para la recuperación de la contraseña'; globalThis.colorAlerta = 'success'; res.redirect(`/login`); //globalThis.alertaGlobal = ''; }); return router; };
var image = new Array (); for(var i = 0; i <= 15; i++){ image[i] = "/images/avatars/avatar" + (i + 1) + ".png"; } $( document ).ready(function() { $('.user').click(function(){ var firstName = $(this).data("firstname"); var lastName = $(this).data("lastname"); // set commentNamesInput so we know who the current loaded person is (to add comments to) $('#addCommentNames').data("firstname", firstName); $('#addCommentNames').data("lastname", lastName); loadComments(firstName, lastName); }); //detect enter key on from input $("#from").keypress(function( event ) { if (event.which == 13) { addComment(); } }); }); function addComment(){ var fromField = $('#from').val(); var honoreeFirst = $('#addCommentNames').data("firstName"); var honoreeLast = $('#addCommentNames').data("lastName"); var comment = $('#commentText').val(); if(typeof honoreeFirst === "undefined" || typeof honoreeLast === "undefined"){ $('#infoBox').text('Please select a name from the left column'); return; } // make sure the from field has input if(typeof fromField === "undefined" || fromField == ""){ $('#infoBox').text('Please say who you are!'); return; } // make sure the comment box has input if(comment.length === 0){ $('#infoBox').text('Please enter a comment!'); return; } $('#infoBox').empty().show(); $.ajax({ url: "/api/addComment", type: "POST", dataType: 'json', contentType: "application/x-www-form-urlencoded", data: { to: honoreeFirst+honoreeLast, from: fromField, msg: comment }, success: function(data){ $('#commentText').val(""); $("#infoBox").css('color','green'); $('#infoBox').text('Success!'); $("#infoBox").fadeOut(4000, function() { $("#infoBox").empty().show(); $("#infoBox").css('color','red'); }); loadComments(honoreeFirst, honoreeLast); }, error: function(err) { console.error("Error adding comment"); console.error(JSON.stringify(err)); } }); } function loadComments(firstName, lastName){ $.ajax({ url: "/api/getComments?name="+firstName+lastName, type: "GET", dataType: 'json', contentType: "application/x-www-form-urlencoded", success: function(data){ $('#titleName').html("<p id='congratsText'>Say Congratulations to " + firstName + " " + lastName + "!</p>"); $('#commentArea').html(''); for (index in data.msgs){ var commentHTML = "<div class='row'>"+ "<div class='large-2 columns small-3'>" + "<img src='"+getRandomAvatar()+"'/>" + "</div>"+ "<div class='large-10 columns'>"+ "<p>" + data.msgs[index].msg + "</p>" + "<p class='fromComment'><strong>-" + data.msgs[index].from + "</strong></p>" + "</div>" + "</div>" + "<hr/>"; $('#commentArea').append(commentHTML); } }, error: function(err) { console.error("failure to get comments"); console.error(JSON.stringify(err)); } }); } function getRandomAvatar(){ var size = image.length; var x = Math.floor(size*Math.random()); return image[x]; }
const axios = require('axios'); const env = process.env.TEST_ENV ? process.env.TEST_ENV : 'aat'; async function getS2SToken(){ const http = axios.create({ baseURL: `http://rpe-service-auth-provider-${env}.service.core-compute-${env}.internal`, timeout: 20000 }); const response = await http.post('/testing-support/lease', { 'microservice': 'xui_webapp' }, { headers: { 'accept': '*/*', 'Content-Type': 'application/json' } }); return response.data; } module.exports = { getS2SToken };
var count = 1 var countElement = document.querySelector("#count") function add1(){ count++; countElement.innerText = count + "Seahawks Lovers!"; console.log(count) }
const router = require('express').Router() const Actor = require('../models/actor') router .get('/', async (_req, res) => { const domains = await Actor.distinct('domains') const cleanedDomains = domains .filter(d => String(d) === d) .filter(d => d.length) .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())) res.send(cleanedDomains) }) module.exports = router
export default class UserService { constructor(userRepository) { this._userRepository = userRepository; } async execute() { return await this._userRepository.findAll() } }
import React from 'react'; import ReactDOM from 'react-dom'; import './Dial.css'; import 'tachyons'; import Indicator from './Indicator'; const Dial = () => { return( <div className='dial tc'> <div className='dial-inner'></div> </div> ) } export default Dial;
const How = (_ => { const init = _ => { // cache dom } return { init } })(); export default How;
X.define('model.quotationModel', function () { var api = X.config.quotation.api, model = X.model.create('model.quotationModel') model.submit = function(data, callback) { var options = { url: api.submit, data: data, type: 'POST', callback: callback } X.loadData(options) } var validate = { rules: { content: { required: true }, requestAdditionalAttachments: { required: false } }, messages: { content: { required: "Please enter the product name" }, requestAdditionalAttachments: { required: "Please enter the product name" } }, onfocusout: function (element) { $(element).valid() } } model.validate = validate return model })
function validate(){ var nombre,apellido,telefono,calle,entre_calle,ciudad_localidad,expresion nombre= document.getElementById ("nombre").value; apellido= document.getElementById ("apellido").value; telefono= document.getElementById ("telefono").value; calle= document.getElementById ("calle").value; entre_calle= document.getElementById ("entre_calle").value; ciudad_localidad= document.getElementById ("ciudad_localidad").value; /*expresion= / \w+@\w\.+[a-z]/; (expresion regular para evaluear correo electronico)*/ if(nombre==="" ||apellido==="" ||telefono==="" ||calle===""||entre_calle===""||ciudad_localidad===""){ alert("debe completar todos los campos") return false; }/* puede agregarse el correo electronico hay que usar la expresion regulara comentada mas arriba*/ else if(nombre.length>30||apellido.length>30 || telefono.length>20 ||calle.length>30||entre_calle.length>30||ciudad_localidad.length>30){ alert ("los valores son demasiado largos") return false; } else if(isNaN(telefono)){ alert("telefono debe ser un numero") return false } /* window.location.reload();*/ /*else if(!expresion.test(correo)){ alert("ingrese una direccion de correo valida") } evaluacion de expresion regular de correp electronico*/ /* agregar longitud maxima de los valores*/ }/*if(nombre===""){ alert("debe completar este campo") return false; } else if(telefono===""){ alert("debe completar este campo") return false; } else if(calles===""){ alert("debe completar este campo") return false; } else if(numero_puerta===""){ alert("debe completar este campo") return false; } else if(calles===""){ alert("debe completar este campo") return false; }*/
import React, { createRef } from 'react'; import { SafeAreaView, StyleSheet, ScrollView, TouchableOpacity, TextInput, View, Text, StatusBar, ImageBackground, } from 'react-native'; import { Image } from 'react-native'; import { Alert, Modal, Pressable } from "react-native"; import Feather from 'react-native-vector-icons/Feather'; import AntDesign from 'react-native-vector-icons/AntDesign'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import Foundation from 'react-native-vector-icons/Foundation'; import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'; import EvilIcons from 'react-native-vector-icons/EvilIcons'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import Entypo from 'react-native-vector-icons/Entypo'; import Popover from 'react-native-popover-view'; import { SliderBox } from "react-native-image-slider-box"; import moment from 'moment'; import ImagesSlider from '../QuestionAndAnswers/ImagesSlider'; import FireBaseFunctions from "../APIs/FireBaseFunctions"; import firestore from '@react-native-firebase/firestore'; class EventsList extends React.Component { services = new FireBaseFunctions(); constructor(props) { super(props); this.touchable = createRef(); this.state = { userProfileId: '918121702580', userName: 'Prem Kumar', userIcon: 'https://firebasestorage.googleapis.com/v0/b/app-visil.appspot.com/o/images%2Fpost_Images%2F918121702580%2F48.26998878368294%2Fdownload%20(4).jpg?alt=media&token=b48e5d49-91ab-45b1-9fb0-e54148780622', userIP: '103.117.238.130', showPopover: false, modalVisible: false, images: [ require('../Images/Flower1.jpg'), require('../Images/Flower2.jpg'), require('../Images/Flower3.jpg'), ] } } setModalVisible = (visible) => { this.setState({ modalVisible: visible }); this.setState({ showPopover: false }); } GotoCreateorEditEventPage = () => { this.props.navigation.navigate('CreateorEditEventPage'); } onLayout = e => { this.setState({ width: e.nativeEvent.layout.width }); }; GotoShareEventpage = () => { this.props.navigation.navigate('ShareEvent'); } MenuOpenClick = (item) => { // console.log(item) // item.showPopover = true; // console.log(item) this.setState({showPopover:item.Id}) //console.log("abc") // isVisible=true; console.log(item.Id); }; closePopover = (item) => { item.showPopover = false; } // MenuCloseClick = () => { // this.state.showPopover = false; // // isVisible=false; // }; followEventClick = async (item) => { console.log(item) this.setState({ userIP: await publicIp.v4() }) const likeId = this.services.getGuid(); var obj = { Id: likeId, Type: 'EVENTFOLLOW', ParentId: item.Id, EventId: item.Id, UserId: this.state.userProfileId, UserimageURL: this.state.userIcon || '', UserName: this.state.userName, Timestamp: new Date().toLocaleString(), UserIPAddress: this.state.userIP || '' } item.FollowList.push(obj.UserId); item.Count.followCount = item.Count.followCount + 1; item.TopFiveFollowList.push(this.userObj); await firestore().collection('Events').doc(item.Id).set(item); await firestore().collection('EventFollow').doc(obj.Id).set(obj); }; render() { let EventsGrids; if (this.props.eventList.length != undefined && this.props.eventList.length > 0) { EventsGrids = this.props.eventList.map((item, index) => (<View> <View style={styles.EventDisplayView}> <View style={{ flexDirection: "row", paddingBottom: 5 }}> <View> <Image source={require('../Images/user.jpg')} style={{ height: 50, width: 50, borderRadius: 50, }} /> </View> <View style={{ paddingLeft: 15 }}> <Text style={{ fontWeight: "bold", fontSize: 20, color: "black" }}>{item.UserName}</Text> <Text style={{ fontSize: 15, color: "black" }}>{item.CreatedTime}</Text> </View> </View> <View style={{ width: "100%" }} onLayout={this.onLayout}> <SliderBox images={item.Multimedia} sliderBoxHeight={200} nCurrentImagePressed={index => console.warn(`image ${index} pressed`)} autoplay circleLoop dotColor="#FFEE58" inactiveDotColor="#90A4AE" parentWidth={this.state.width} /> </View> <View style={{ flexDirection: "row", width: "100%", paddingTop: 20 }}> <View style={{ width: "15%", padding: 5 }}> <Text style={{ fontSize: 25, borderColor: "black", borderWidth: 1, borderRadius: 10, fontWeight: "bold", padding: 7, color: "black", textAlign: "center" }}>{moment(item.Dateofevent).format("D")}</Text> </View> <View style={{ width: "70%", padding: 10 }}> <Text style={{ fontSize: 20, fontWeight: "bold", color: "black", }}>{moment(item.Dateofevent).format("dddd")}, {moment(item.Dateofevent).format("LT")}</Text> <Text style={{ fontSize: 15, color: "black" }}>{moment(item.Dateofevent).format("MMMM")},{moment(item.Dateofevent).format("YYYY")}</Text> </View> <View style={{ width: "15%", padding: 15 }}> <TouchableOpacity ref={this.touchable} onPress={() => this.MenuOpenClick(item)}> <Text><Entypo name="dots-three-vertical" size={30} style={{ color: "black", textAlign: "center" }} /></Text> </TouchableOpacity> { (() => { if (this.state.showPopover == item.Id) { return ( <Popover //from={this.touchable} vc isVisible={true} // isVisible={this.state.showPopover} //isVisible={item.showPopover} //onRequestClose={() => this.closePopover(item)} onRequestClose={() => this.setState({ showPopover: false })} > <View style={{ padding: 10, width: 300 }}> <TouchableOpacity onPress={() => this.GotoCreateorEditEventPage()}> <View style={{ borderBottomWidth: 1, borderBottomColor: "thistle", }}> <Text style={{ fontSize: 22, textAlign: 'center', fontWeight: 'bold', padding: 10 }}>Edit this Event</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => this.GotoShareEventpage()}> <View style={{ borderBottomWidth: 1, borderBottomColor: "thistle", }}> <Text style={{ fontSize: 22, textAlign: 'center', fontWeight: 'bold', padding: 10 }}>Share this Event</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => this.setModalVisible(true)}> <View style={{ borderBottomWidth: 1, borderBottomColor: "thistle", }}> <Text style={{ fontSize: 22, textAlign: 'center', fontWeight: 'bold', padding: 10 }}>Delete this Event</Text> </View> </TouchableOpacity> <View> <Text style={{ textAlign: 'center', fontSize: 22, fontWeight: 'bold', padding: 10 }}>Report this Event</Text> </View> </View> </Popover> ) } })() } </View> </View> <View style={{ paddingTop: 10, paddingBottom: 5 }}> <Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>{item.Event}</Text> <Text style={{ fontSize: 17, color: "#a3a4a7", paddingTop: 5 }}>{item.Description}</Text> </View> <View style={{ flexDirection: "row", paddingBottom: 5 }}> <Text><Entypo name="location-pin" size={30} style={{ fontWeight: "bold", }} /></Text> <Text style={{ fontSize: 17, paddingBottom: 5 }}>{item.AddressLine1}, {item.AddressLine2}, {item.City}, {item.E_state}, {item.Country}, {item.Zipcode}</Text> </View> <View style={{ flexDirection: "row", width: "100%" }}> { (() => { if (item.Count.followCount > 0) { let likeDiv = <View> <TouchableOpacity style={{ flexDirection: "row", borderColor: "#53d769ff", borderWidth: 1, padding: 10, backgroundColor: "#53d769ff", borderRadius: 8 }} onPress={() => this.followEventClick(item)}> <Text><AntDesign name="check" size={30} style={{ color: "white", textAlign: "center", fontWeight: "bold", }} /></Text> <Text style={{ fontSize: 20, fontWeight: "bold", color: "white", paddingLeft: 5 }}>interested </Text> </TouchableOpacity> </View> item.FollowList.map(item => { if (item == this.state.userProfileId) { likeDiv = <View> <TouchableOpacity style={{ flexDirection: "row", borderColor: "#53d769ff", borderWidth: 1, padding: 10, backgroundColor: "#53d769ff", borderRadius: 8 }} onPress={() => this.unfollowEventClick(item)}> <Text><AntDesign name="check" size={30} style={{ color: "white", textAlign: "center", fontWeight: "bold", }} /></Text> <Text style={{ fontSize: 20, fontWeight: "bold", color: "white", paddingLeft: 5 }}>interested </Text> </TouchableOpacity> </View> } }) return likeDiv } else { return ( <View> <TouchableOpacity style={{ flexDirection: "row", borderColor: "#53d769ff", borderWidth: 1, padding: 10, backgroundColor: "#53d769ff", borderRadius: 8 }} onClick={() => this.followEventClick(item)}> <Text><AntDesign name="check" size={30} style={{ color: "white", textAlign: "center", fontWeight: "bold", }} /></Text> <Text style={{ fontSize: 20, fontWeight: "bold", color: "white", paddingLeft: 5 }}>interested </Text> </TouchableOpacity> </View> ) } })() } <View style={{ flexDirection: "row" }}> </View> </View> <View> <Text style={{ paddingTop: 10, fontSize: 20, color: "#a3a4a7" }}>{item.Count.followCount} more are participating</Text> </View> </View> </View>)) } else { EventsGrids = <View> <Text>No Events</Text> </View> } return ( <View style={{ height: "100%" }}> <ScrollView> {EventsGrids} </ScrollView> <View style={styles.centeredView}> <Modal animationType="slide" transparent={true} visible={this.state.modalVisible} onRequestClose={() => { Alert.alert("Modal has been closed."); this.setModalVisible(!modalVisible); }} > <View style={styles.centeredView}> <View style={styles.modalView}> <View style={{ padding: 10, textAlign: "center" }}> <Text style={{ fontWeight: "bold", fontSize: 20, textAlign: "center", paddingBottom: 10 }}>Confirm Deletion</Text> <Text style={{ fontWeight: "500", fontSize: 17, textAlign: "center" }}>Are you sure you want to delete this Event?</Text> </View> <View style={{ flexDirection: "row", padding: 20, alignItems: "flex-end", alignSelf: "flex-end" }}> <TouchableOpacity style={{ color: "#1e74f5", padding: 10 }}> <Text style={{ color: "#1e74f5", fontSize: 20 }}>DELETE</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.setModalVisible(!this.state.modalVisible)} style={{ color: "#1e74f5", padding: 10 }}> <Text style={{ color: "#1e74f5", fontSize: 20 }}>CANCEL</Text> </TouchableOpacity> </View> </View> </View> </Modal> </View> </View> ); }; } const styles = StyleSheet.create({ EventDisplayView: { margin: 10, backgroundColor: "white", padding: 20, borderRadius: 10, shadowColor: "#000", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.23, shadowRadius: 2.62, elevation: 4, }, centeredView: { flex: 1, justifyContent: "center", alignItems: "center", marginTop: 22, }, modalView: { margin: 20, backgroundColor: "white", borderRadius: 20, padding: 5, // alignItems: "center", shadowColor: "#000", shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.25, shadowRadius: 4, elevation: 5, width: "90%" }, modalText: { fontSize: 25, marginBottom: 15, // textAlign: "center" } }); export default EventsList;
(function(){ 'use strict' var ref = new Firebase("https://pocfirepoly.firebaseio.com/comment-list"); Polymer({ is:"comment-form", properties:{ name:String, comment:String, date:{ type:String, computed:'getDate()' }, img:String }, getDate :function(){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd } if(mm<10) { mm='0'+mm } today = mm+'/'+dd+'/'+yyyy; return today; }, sumbitComment: function() { var _name = document.querySelector('#name').value.trim(); var _comment = document.querySelector('#comment').value.trim(); var _date = document.querySelector('#date').value; if(_name==="" || _comment===""){ document.querySelector('#errTip').show(); }else{ // RANDOM IMAGE AND GENDER GENERATING var imgNo = Math.floor(Math.random() * (97)) + 1;//for image number randomly var gendeValue = imgNo%2//for selecting gender randomly var gender=null; (gendeValue===0)?(gender="women"):(gender="men"); var imgUrl="https://randomuser.me/api/portraits/thumb/"+gender+"/"+imgNo+".jpg"; // var imgUrl="https://randomuser.me/api/portraits/thumb/men/10.jpg"; ref.push({ "comment":_comment, "datetime":_date, "name":_name, "img":imgUrl }); document.querySelector('#toolTipAdd').show(); var _name = document.querySelector('#name').value=""; var _comment = document.querySelector('#comment').value=""; } } }); }());
// Create an Object let fridge = {}; fridge.eggs = 20; fridge.veg = 'Tomotos'; fridge.fruits = 'Mangos'; console.log(fridge); // Access the properties of an Object console.log(fridge.fruits); // Object with Data let mobile = { brand : 'Apple', color : 'silver', price : 35000, isInsured : true }; console.log(mobile); // Access the properties of an object console.log(`Brand : ${mobile.brand}`); // dot notation console.log(`Brand : ${mobile['brand']}`); // [] notation // Access non existing property console.log(mobile.ramCapacity); // undefined // Nested Objects let student = { name : 'Rajan', course : 'Engineering', age : 22, address : { city : 'Hyderabad', state : 'TS', country : 'India' } }; console.log(student); // Access the nested Objects console.log(`City : ${student.address.city}`); // Add properties to Object student.collegeName = 'IIT Mumbai'; console.log(student); // Add properties to nested Object console.log(student.address); student.address.street = 'Jubliee Hills'; console.log(student.address); // Delete properties from ab Object console.log(student); delete student.address; console.log(student);
import path from 'path' import fs from 'fs' export default class FileHelper { static getRoot() { return path.resolve('./') // return path.dirname(fileURLToPath(import.meta.url)) } static composePath(...paths) { return path.join(this.getRoot(), ...paths) } static clearDirectory(dirPath) { try { try { const stats = fs.statSync(dirPath) } catch (error) { fs.mkdirSync(dirPath, { recursive: true }) return true } fs.readdirSync(dirPath).forEach((file) => { fs.unlink(path.join(dirPath, file), (err) => { if (err) throw err }) }) } catch (error) { throw Error(`Не получилось создать директорию ${dirPath}: ${error}`) } } static isDirectory(path) { var stat = fs.lstatSync(path) return stat.isDirectory() } static isFileExists(path) { return fs.existsSync(path) } static deleteFile(path) { return fs.unlinkSync(path) } static getFileNameFromPath(filePath) { return path.basename(filePath) } static getJsonFromFile(filePath) { const content = fs.readFileSync(filePath, {encoding: 'utf8'}) return JSON.parse(content) } static textJson(json) { return JSON.stringify(json, null, 4) } static saveJsonToFileSync(json, filePath) { fs.writeFileSync(filePath, this.textJson(json), { encoding: 'UTF8', }) } static getFilesFromDir(dataDir, fileType = '.json') { let set = new Set() fs.readdirSync(dataDir).forEach((fileName) => { let filePath = path.join(dataDir, fileName) if (fileType === path.extname(filePath)) { set.add(filePath) } }) return set } }
'use strict'; angular.module('scrabble-ui') .directive('keyup', function($window){ return { restrict: 'A', link: function(scope, element, attrs){ var keyup = scope.$eval(attrs.keyup); init(); /** * */ function init(){ angular.element($window).on('keyup', onKeyup); scope.$on('$destroy', function(){ angular.element($window).off('keyup', onKeyup); }); } /** * * @param e */ function onKeyup(e){ var keyCode; var keyCodeString; for(keyCodeString in keyup){ keyCode = parseInt(keyCodeString, 10); if(keyCode === e.keyCode){ scope.$eval(keyup[keyCode]); } } } } } });
(function($) { /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ module('jQuery#bs3Alert', { // This will run before each test in this module. setup: function() { this.elems = $('#qunit-fixture').children(); } }); test('is chainable', function() { expect(1); // Not a bad test to run on collection methods. strictEqual(this.elems.bs3Alert(), this.elems, 'should be chainable'); }); asyncTest('produces a default alert', function() { expect(8); this.elems.bs3Alert(); $(document).trigger('show-alert', {message: 'hi there'}); var base = this; setTimeout(function() { start(); var alerts = $('DIV.alert'), firstAlert = alerts.first(), button = firstAlert.find('button'), title = firstAlert.find('strong').text(), html = firstAlert.html(); strictEqual( alerts.length, base.elems.length, "There should be one alert for each element" ); strictEqual( button.length, 1, 'expetced a close button'); equal( title, 'Error', 'expetced the title to be "Error"'); ok( html.indexOf('hi there') > 0, 'expetced the text to contain "hi there"'); ok( firstAlert.hasClass('alert-danger'), 'Expected the alert to have class "alert-danger"'); ok( firstAlert.hasClass('fade'), 'Expected the alert to have class "fade"'); ok( firstAlert.hasClass('in'), 'Expected the alert to have class "in"'); ok( firstAlert.hasClass('alert-dismissable'), 'Expected the alert to have class "alert-dismissable"'); }, 50); }); asyncTest('produces a non-dismissible alert', function() { expect(7); this.elems.bs3Alert({dismissable: false}); $(document).trigger('show-alert', {priority: 'warning', message: 'yo, way to go'}); setTimeout(function() { var firstAlert = $('DIV.alert').first(), button = firstAlert.find('button'), title = firstAlert.find('strong').text(), html = firstAlert.html(); strictEqual( button.length, 0, 'expetced no close button'); equal( title, 'Warning', 'expetced the title to be "Warning"'); ok( html.indexOf('yo, way to go') > 0, 'expetced the text to contain "yo, way to go"'); ok( firstAlert.hasClass('alert-warning'), 'Expected the alert to have class "alert-warning"'); ok( !firstAlert.hasClass('alert-dismissable'), 'Expected the alert not to have class "alert-dismissable"'); ok( !firstAlert.hasClass('fade'), 'Expected the alert not to have class "fade"'); ok( !firstAlert.hasClass('fade'), 'Expected the alert not to have class "in"'); start(); }, 50); }); asyncTest('produces a customised alert', function() { expect(7); this.elems.bs3Alert({fade: false, priority: 'success'}); $(document).trigger('show-alert', {message: 'yo, way to go'}); setTimeout(function() { var firstAlert = $('DIV.alert').first(), button = firstAlert.find('button'), title = firstAlert.find('strong').text(), html = firstAlert.html(); strictEqual( button.length, 1, 'expetced a close button'); equal( title, 'Success', 'expetced the title to be "Success"'); ok( html.indexOf('yo, way to go') > 0, 'expetced the text to contain "yo, way to go"'); ok( firstAlert.hasClass('alert-success'), 'Expected the alert to have class "alert-success"'); ok( firstAlert.hasClass('alert-dismissable'), 'Expected the alert to have class "alert-dismissable"'); ok( !firstAlert.hasClass('fade'), 'Expected the alert not to have class "fade"'); ok( !firstAlert.hasClass('fade'), 'Expected the alert not to have class "in"'); start(); }, 50); }); }(jQuery));
import electron from 'electron'; const remote = electron.remote; const Menu = remote.Menu; const templateForEditArea = [ { label: '撤消', role: 'undo' }, { label: '恢复', role: 'redo' }, { type: 'separator' }, { label: '剪切', role: 'cut' }, { label: '复制', role: 'copy' }, { label: '粘贴', role: 'paste' }, { type: 'separator' }, { label: '全选', role: 'selectall' } ]; const templateForCopyArea = [ { label: '复制', role: 'copy' } ]; const InputMenu = Menu.buildFromTemplate(templateForEditArea); const CopyMenu = Menu.buildFromTemplate(templateForCopyArea); function addListener() { document.body.addEventListener('contextmenu', (e) => { e.preventDefault(); e.stopPropagation(); let node = e.target; while (node) { // 节点是否可编辑 const isNodeEditable = node.nodeName.match(/^(input|textarea)$/i) || node.isContentEditable; // 是否有选中的文本 const hasSelectedText = window.getSelection().toString(); if (isNodeEditable || hasSelectedText) { (hasSelectedText && !isNodeEditable ? CopyMenu : InputMenu).popup(); break; } node = node.parentNode; } }); } function listenContextMenu() { if (document.body) { addListener(); } else { document.addEventListener('DOMContentLoaded', () => { addListener(); }); } } listenContextMenu();
const main = { primary: '#BD5D38', }; const defaults = { coal: { default: '#868E96', dark: '#343A40', }, silver: { default: '#F2F0F7', light: '#F9F7FC', dark: '#E8E6F0', }, }; const colors = { ...main, ...defaults, }; export default colors;
class Polygon_vertex2d extends Shape { constructor(vertex_array, color) { super(0, 0, color); this.vertex_array = vertex_array; this.midpoint = Vertex.midpoint(vertex_array); this.vertex_array_zero_based = []; for (let i = 0; i < vertex_array.length; i++) { this.vertex_array_zero_based[i] = vertex_array[i].shift(this.midpoint); } } draw(ctx) { ctx.beginPath(); { ctx.moveTo(this.vertex_array[0].x, this.vertex_array[0].y); for (let i = 1; i < this.vertex_array.length; i++) { ctx.fillStyle = this.getColor(); ctx.strokeStyle = this.getColor(); ctx.lineTo(this.vertex_array[i].x, this.vertex_array[i].y); ctx.stroke(); } ctx.fillStyle = this.getColor(); ctx.lineTo(this.vertex_array[0].x, this.vertex_array[0].y); ctx.stroke(); } } static clone(obj, color) // dependant on vertex.js { var vertex_array = []; for (var i = 0; i < obj.vertex_array.length; i++) { vertex_array[i] = new Vertex(obj.vertex_array[i].x, obj.vertex_array[i].y, 0); } var Polygon_vertex2dClone = new Polygon_vertex2d(vertex_array, color); return Polygon_vertex2dClone; } static monoscale(obj, x) // millegi pärast keerab rotX ja rotY pekki kui loop'ida koos { // uus idee Midpoint keerab nahka, kuna kokku pressituna raadius on väiksem ja theta hulk keeramisega vähendab iga korraga raadiust // lahendus, eraldi layer objekti reaalsete parameetrite hoidmiseks ja eraldi layer displaymine for (var i = 0; i < obj.vertex_array_zero_based.length; i++) { obj.vertex_array_zero_based[i].monoscale(x); } } static pan(obj, x, y) { for (var i = 0; i < obj.vertex_array.length; i++) { obj.vertex_array[i].pan(x, y, 0); obj.vertex_array_zero_based[i].pan(x, y, 0); // obj.vertex_array[i].add(x, y, 0); } } static mv(obj, objs_to_create) // input obj is Polygon_vertex2d object { var objs_to_create = 50; //wheels.splice(0, objs_to_create); // if (wheels.length != 0) { // wheels.splice(0, objs_to_create); // console.log(wheels); // } var obj_array = []; for (var i = 0; i < objs_to_create; i++) { obj.vertex_array[i].x = parseInt(r + Math.random() * (canvas.width - 2 * r)); // et pall tekiks canvase alass on vaja ruudu laius maha lahutada obj.vertex_array[i].y = parseInt(r + Math.random() * (canvas.height - 2 * r)); var MoveSpeed = 0.5 + parseInt(Math.random() * 0); //var direction = 360 * Math.random(); var Accel = Math.random() * 0.01; var ScaleChange = Math.random() * 1.3 - 1.4; obj_array[i] = (new Pol_ver_mv(x, y, MoveSpeed, ScaleChange, direction, Accel)); } wheels_set[wheels_set_counter] = wheels; wheels_set_counter++; } static rotX(obj, theta) { var shifted = [] for (let i = 0; i < obj.vertex_array_zero_based.length; i++) { obj.vertex_array_zero_based[i] = obj.vertex_array_zero_based[i].rotX(theta); obj.vertex_array[i] = obj.vertex_array_zero_based[i].shiftPlus(obj.midpoint); } } static rotY(obj, theta) { var shifted = [] for (let i = 0; i < obj.vertex_array_zero_based.length; i++) { obj.vertex_array_zero_based[i] = obj.vertex_array_zero_based[i].rotY(theta); obj.vertex_array[i] = obj.vertex_array_zero_based[i].shiftPlus(obj.midpoint); } } static rotZ(obj, theta) { var shifted = [] for (let i = 0; i < obj.vertex_array_zero_based.length; i++) { obj.vertex_array_zero_based[i] = obj.vertex_array_zero_based[i].rotZ(theta); obj.vertex_array[i] = obj.vertex_array_zero_based[i].shiftPlus(obj.midpoint); } } static midpoint(obj) { var vertex_array = []; for (var i = 0; i < obj.vertex_array.length; i++) { vertex_array[i] = new Vertex(obj.vertex_array[i].x, obj.vertex_array[i].y, 0); } return Vertex.midpoint(vertex_array); } static shift(obj, P) // P => point as vertex { var vertex_array = []; for (var i = 0; i < obj.vertex_array.length; i++) { vertex_array[i] = new Vertex(obj.vertex_array[i].x, obj.vertex_array[i].y, 0); obj.vertex_array[i] = vertex_array[i].shift(P); } } static pan_trail(stage, obj, objs_to_create, x_mult, y_mult, color) // vektor in degrees { var obj_array = []; for (let i = 0; i < objs_to_create; i++) { obj_array[i] = this.clone(obj, color); this.scalar(obj_array[i], i * x_mult, i * y_mult); stage.add(obj_array[i]); } } projection3d(obj, depth) { for(let i = 0; i < obj.vertex_array.length; i++) { cube_polygons[i] = obj.vertex_array[i].project(depth); } } }
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import FontAwesomeIcon from '@fortawesome/react-fontawesome' import faCheck from '@fortawesome/fontawesome-free-solid/faCheck'; import { palette } from '../../cssResources'; const CheckboxWrapper = styled.label` background-color: white; border: 3px solid ${palette.black}; border-radius: 3px; cursor: pointer; display: block; margin: 0 auto; width: 26px; height: 26px; `; const CheckboxInput = styled.input` display: none; ~ .Checkbox__input { color: ${palette.black}; transition: cubic-bezier(.7,-0.5,.3,1.5) .35s; transform: scale(0) translate3d(0,0,0); margin: 0; } :checked ~ .Checkbox__input { transform: scale(2) translate3d(0,0,0); } `; const Checkbox = ({ userType, bits, handleChange }) => { return ( <CheckboxWrapper> <CheckboxInput type="checkbox" value={bits} onChange={({ target }) => handleChange(userType, target.checked ? bits : -bits)} /> <FontAwesomeIcon className="Checkbox__input" icon={faCheck} /> </CheckboxWrapper> ) } Checkbox.propTypes = { userType: PropTypes.string.isRequired, bits: PropTypes.number.isRequired, handleChange: PropTypes.func.isRequired, }; export default Checkbox;
import React, { useState } from 'react'; import { Box, Grid, Typography, Button, makeStyles} from '@material-ui/core' import Details from "./pharmDetails.js" import pharmData from "./dummyData.js" const useStyles = makeStyles((theme) => ({ wrapper: { border: "1px solid #e8e8e8", }, companyName: { fontSize: "13.5px", backgroundColor: "#F5B7B1", padding: theme.spacing(0.75), borderRadius: "5px", display: "inline-block", fontWeight: 600, }, buttonStyle: { margin: theme.spacing(0.5), padding: theme.spacing(0.75), fontsize: "14.5px", borderRadius: "5px", transition: ".3s", //cursor: "pointer", fontWeight: 600, border: `1px solid ${theme.palette.secondary.main}`, color: theme.palette.secondary.main, cursor: "pointer", "&:hover": { backgroundColor: theme.palette.secondary.main, color: "#fff", } }, })); export default (props) => { const classes = useStyles(); const [newJobModal, setNewJobModal] = useState(false) return( <Box p={2} className={classes.wrapper}> {/* <Details closeModal={() => setNewJobModal(false)} newJobModal={newJobModal}/> */} <Grid container> <Grid item xs> <Typography className={classes.companyName} variant="subtitle1">{props.title}</Typography> </Grid> <Grid item container direction="column"xs> <Typography variant="subtitle1">{props.city}</Typography> </Grid> <Grid item container xs> <Button className={classes.buttonStyle} variant="outlined" onClick={()=>setNewJobModal(true)}>View</Button> </Grid> {pharmData.map(pharm => <Details key={pharm.id} {...pharm} closeModal={() => setNewJobModal(false)} newJobModal={newJobModal} />)} </Grid> </Box> ) }
import React, {Component} from "react"; import API from "../utils/API"; import PageTitle from "../components/PageTitle"; import Profile from "../components/Profile"; import Menu from "../components/Menu"; class PetProfile extends Component{ constructor (props) { super(props) this.state = { photo: require('../images/test.jpg'), pets: [], petName: "", petBirthday: 0, petType: "", breed: "", color: "", markings: "", weight: null, foodBrand: "", microchipNumber: 0, rabiesTagNumber: 0, insurance: "", medication: "", allergies: "", careNotes: "" }; } componentDidMount() { this.loadPets(); }; loadPets = () => { API.getAllPets() .then(res=> this.setState({pets: res.data})) .catch(err =>console.log(err)) }; render () { return ( <div> <Profile photo={this.state.photo} /> <Menu /> </div> ) } } export default PetProfile;
var api_url = "http://localhost:8080/"; jQuery.ajaxSetup({async:false}); var brands = []; var models = []; $(document).ready(function () { var d = new Date(); $("#date").html(d.toDateString()); setInterval(function() { d = new Date(); $("#time").html(d.toLocaleTimeString(navigator.language,{hour: "2-digit",minute:"2-digit"})); }); $("#sell-item").submit(function (e) { e.preventDefault(); var br = $.trim($("#brand").val()); var mo = $.trim($("#model").val()); var pro = $.trim($("#profit").val()); data = { "brand" : br, "model" : mo, "profit" : pro, "seller" : $("#seller").val(), "dt" : Math.floor(d.getTime()/1000) } $.post(api_url+"recordSell",data) .done(function(){alert("Rocorded!");}) .fail(function(){alert("Failed. Please try again");}); this.reset(); }); $("#brand").focusout(function() { data = { brand: $.trim(this.value) } $.post(api_url+"getModels",data,function(data,status,xhr) { if(status == "success") { modellist = JSON.parse(data); $("#model").autocomplete({ source: modellist, minLength: 0, select: function(e,ui) { if($("#brand").val()) { var data = { "brand":$("#brand").val(), "model": ui.item.value }; $.post(api_url+"getPrice",data,function(price,status) { $("#buyingprice").val(price); price = parseInt(price); if(price) { $("#sellingprice").val((price+(price*.1)).toFixed(0)); $("#profit").val((price*.1).toFixed(0)); $("#percent").val(10); } }); } return true; } }); } }); }); $.post(api_url+"getBrands",{},function(data,status) { if(status == "success") { brands = JSON.parse(data); $("#brand").autocomplete({ source: brands, minLength: 0, select: function(e,ui) { if($("#model").val()) { var item = { "brand" : ui.item.value, "model" : $("#model").val() }; $.post(api_url+"getPrice",item,function(price,status) { $("#buyingprice").val(price); price = parseInt(price); if(price) { $("#sellingprice").val((price+(price*.1)).toFixed(0)); $("#profit").val((price*.1).toFixed(0)); $("#percent").val(10); } }); } return true; } }); } }); $("#profit").on("change paste keyup",function() { pri = parseInt($("#buyingprice").val()); pro = parseInt($("#profit").val()); if(pri && pro) { per = (pro/pri*100).toFixed(1); spri = pri+pro; console.log(per,spri); $("#percent").val(per); $("#sellingprice").val(spri); } else if (pro == 0) { $("#percent").val(0); $("#sellingprice").val(pri); } }); $("#percent").on("change paste keyup",function() { pri = parseInt($("#buyingprice").val()); per = parseInt($("#percent").val()); if(pri && per) { pro = pri*per/100; spri = pri+pro; $("#profit").val(pro.toFixed(0)); $("#sellingprice").val(spri.toFixed(0)); } else if (per == 0) { $("#profit").val(0); $("#sellingprice").val(pri); } }); $("#sellingprice").on("change paste keyup",function() { pri = parseInt($("#buyingprice").val()); spri = parseInt($("#sellingprice").val()); if(pri && spri) { pro = spri - pri; per = pro/pri*100; $("#profit").val(pro.toFixed(0)); $("#percent").val(per.toFixed(1)); } else if(spri == 0) { $("#profit").val(0); $("#percent").val(0); } }); });
var app = angular.module('productApp',['ui.router','ngStorage']); app.constant('urls', { BASE: 'http://infracommerce.herokuapp.com/infracommerce', USER_SERVICE_API : 'http://infracommerce.herokuapp.com/infracommerce/api/product/' }); app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: 'partials/ManageProducts', controller:'ProductController', controllerAs:'ctrl', resolve: { products: function ($q, ProductService) { console.log('Carregando todos os produtos'); var deferred = $q.defer(); ProductService.loadAllProducts().then(deferred.resolve, deferred.resolve); return deferred.promise; } } }); $urlRouterProvider.otherwise('/'); }]);
module.exports = function (sequelize, DataTypes) { return sequelize.define("fix", { fix: { type: DataTypes.STRING, }, }); };
/*global WildRydes _config*/ (function timer($) { var countDownDate = new Date("Jan 20, 2021 24:00:00").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById("countdown").innerHTML = "<h1><p>Trump's Last Day Countdown: </br></p><p style=\"text-indent: 30px\">" + days + "d " + hours + "h " + minutes + "m " + seconds + "s</h1>"; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "<h1>Bye Bye...Mr. Ex President"; } }, 1000); }(jQuery));
angular.module("AppMod", ['ngRoute']) .factory("EditService",function() { var id = 100; return { getId: function() { return id; }, setId: function(val) { id=val; } }; }) .controller("AppCtrl", ["$http","$location","EditService", function($http,$location,EditService) { var self = this; self.goEdit = function(id) { EditService.setId(id); $location.path("/edit"); } self.changeAbout = function() { for (var std of self.students) { std.vis = true; } }; self.hideBySat = function(sat) { for (var std of self.students) { console.log("called function!"); if(std.sat>=sat) { std.show=true; } else { std.show=false; } } } self.refresh = function() { for(var std of self.students) { std.show = true; } $("#sat-filter").val(""); } $http.get("http://localhost:8080/student").then(function(resp) { self.students = resp.data; for (var std of self.students) { std.show = true; } }); self.deleteId = function(id) { $http({ url:"http://localhost:8080/student/delete/" + id, method: "DELETE", data: null, crossorigin: true, dataType: "json", contentType: "application/json", }).then(function(resp) { location.reload(true); }); } self.update = function() { var data = { id: $("#student-id").val(), firstName: $("#student-first-name").val(), lastName: $("#student-last-name").val(), gpa: $("#student-gpa").val(), sat: $("#student-sat").val() }; $http({ url:"http://localhost:8080/student/update", method: "PUT", data: JSON.stringify(data), crossorigin: true, dataType: "json", contentType: "application/json", }); } self.add = function() { var data = { firstName: $("#add-student-first-name").val(), lastName: $("#add-student-last-name").val(), gpa: $("#add-student-gpa").val(), sat: $("#add-student-sat").val() }; $http({ url:"http://localhost:8080/student/add", method: "POST", data: JSON.stringify(data), crossorigin: true, dataType: "json", contentType: "application/json", }).then(function(resp) { location.reload(true); }); } }]) .controller("EditCtrl", ["$http","EditService", function($http,EditService) { var self=this; self.editRecord = null; self.id = EditService.getId(); $http.get("http://localhost:8080/student/"+self.id).then(function(resp) { self.editRecord = resp.data; }); }]) .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/home.view.html' }).when('/student', { templateUrl: 'views/student.view.html', controller: 'AppCtrl', controllerAs: 'ctrl' }).when('/about', { templateUrl: 'views/about.view.html' }).when('/add', { templateUrl: 'views/add.view.html' }).when('/edit', { templateUrl: 'views/edit.view.html', controller: 'EditCtrl', controllerAs: 'Ectrl' }) .otherwise({redirectTo: '/'}); }]);
import React, { useState } from "react"; import { Link } from "react-router-dom"; import api from "../utils/api"; import InstrDash from "./Dashboards/InstrDash"; import StuDash from "./Dashboards/StuDash"; const Signin = props => { // make a post request to retrieve a token from the api // when you have handled the token, navigate to the BubblePage route const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(); const [data, setData] = useState({ username: "", password: "" }); const handleChange = e => { setData({ ...data, [e.target.name]: e.target.value }); }; const handleSubmit = e => { e.preventDefault(); setIsLoading(true); api() .post("/api/auth/login", data) .then( res => { if (res.data.user.roleId == 2) { //Set Token in Local Storage localStorage.setItem("token", res.data.token); //Set Username in Local Storage localStorage.setItem("username", res.data.user.username); //Set InstructorID in Local Storage localStorage.setItem("studentID", res.data.user.id); props.history.push("/student"); } else if (res.data.user.roleId == 1) { //Set Token in Local Storage localStorage.setItem("token", res.data.token); //Set Username in Local Storage localStorage.setItem("username", res.data.user.username); //Set InstructorID in Local Storage localStorage.setItem("instructorID", res.data.user.id); props.history.push("/instructor"); setIsLoading(true); if (res.data.user.roleId == 2) { console.log("Student"); props.history.push("/student"); } else if (res.data.user.roleId == 1) { props.history.push("/instructor"); } localStorage.setItem("token", res.data.token); setTimeout(function() { setIsLoading(false); }, 1000); } } // .catch(err => { // // setError(err.response.data.message) // console.log(err); // }); ); }; return ( <> {isLoading && <div>Loading... </div>} <div style={{ textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", marginTop: "30px", height: "150px" }} > <h1>Login</h1> <form onSubmit={handleSubmit} style={{ background: "#f1f1f1", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "space-around", padding: "30px 0px", width: "175px" }} > {error && <div className="error">{error}</div>} <input type="text" name="username" placeholder="Username" value={data.username} onChange={handleChange} /> <input type="password" name="password" placeholder="Password" value={data.password} onChange={handleChange} /> <button type="submit">Sign In</button> </form> </div> </> ); }; export default Signin;
import {createRouter, createWebHistory} from 'vue-router'; import Link from "../views/Link"; import CreatePoster from "../views/CreatePoster"; import OauthCallback from "../views/OauthCallback"; import {getSpotifyAccessToken} from "../assets/js/spotify-util"; const routes = [ { path: '/', name: 'createPoster', component: CreatePoster }, { path: '/link', name: 'link', component: Link }, { path: '/oauth-callback', name: 'oauthCallback', component: OauthCallback } ]; const router = createRouter({ history: createWebHistory(), routes }); // Controlling which routes users can access if they don't have an access token router.beforeResolve((to, from, next) => { // Checking if we have an access token stored in a cookie const cookieAccessToken = getSpotifyAccessToken(); if (cookieAccessToken === null) { // The access token has not yet been set, checking if we are on a whitelisted page const allowedNoAccessToken = ["oauthCallback", "link"]; if (allowedNoAccessToken.includes(to.name)) { next(); } else { // Trying to access page requiring access token with access token, redirect them next({name: "link"}); } return; } next(); }); export default router;
var express = require('express'); var bodyParser = require('body-parser'); var path = require('path'); var routes= require('./routes/index.js'); var mongo = require('mongodb'); var session = require('express-session'); var cookieParser = require('cookie-parser'); var mongoose = require('mongoose'); var passport = require('passport'); var cors = require('cors'); var LocalStrategy = require('passport-local').Strategy; mongoose.connect('mongodb://localhost/casetools'); var db = mongoose.connection; console.log('DB connected'); //init app var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); // Express Session app.use(session({ secret: 'secret', saveUninitialized: true, resave: true })); // Passport init app.use(passport.initialize()); app.use(passport.session()); app.use(cors()); // Global Vars app.use(function (req, res, next) { res.locals.user = req.user || null; next(); }); app.use(function (req, res, next) { res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate'); res.header('Expires', '-1'); res.header('Pragma', 'no-cache'); next(); }); app.use('/', routes); app.set('port', (process.env.PORT || 3000)); app.listen(app.get('port'), function(){ console.log('Server started on port '+app.get('port')); });
const Sequelize = require('sequelize'); const db = require('../db'); const Trips = db.define('trips', { route_id: { TYPE: Sequelize.STRING }, service_id: { TYPE: Sequelize.STRING }, trip_id: { TYPE: Sequelize.STRING }, trip_headsign: { TYPE: Sequelize.STRING }, direction_id: { TYPE: Sequelize.STRING }, block_id: { TYPE: Sequelize.STRING }, shape_id: { TYPE: Sequelize.STRING } }); module.exports = Trips;
(function () { 'use strict'; var kiosk = { 'el': document.getElementById('kiosk') }; // Save the previous state // kiosk.controller = function () { // var ctrl = this; // ctrl.data = {}; // kiosk.el.addEventListener('kiosk', function (event) { // ctrl.data = event.detail; // m.render(kiosk.el, kiosk.view(ctrl)); // }); // }; // kiosk.view = function (ctrl) { // if (Object.keys(ctrl.data).length === 0) { // return m('p', 'Waiting for data'); // } // return [ // m('pre', JSON.stringify(ctrl.data, null, ' ')) // ]; // }; // if (kiosk.el !== null) { // m.module(kiosk.el, kiosk); // } })(); var prevKiosk; clearKiosk(); // Define impress and get it to run var impKiosk = impress("kiosk"); var impressKiosk; var rKiosk = 0; function clearKiosk() { $.ajax({ method: 'GET', crossDomain: true, url: 'http://localhost:5000/kiosk', success: function (data, status, xhr) { var d = JSON.parse(data); var html = ''; $(d.data).each(function(i){ html += '<div class="step" data-y="'+ i*2000 +'">'+ d.data[i].content +'</div>'; // Clone the first slide to create a full circle if (i == d.data.length -1) { html += '<div class="step laststep" data-y="'+ (i+1)*2000 +'">'+ d.data[0].content +'</div>'; } }); if (html != prevKiosk) { prevKiosk = html; $('#kiosk').empty(); $('#kiosk').append(html); impressKiosk = impKiosk; impressKiosk.init(); impressKiosk.goto(0, 0); } }, error: function (xhr, status, error) { console.log(status.text); } }); } document.addEventListener('impress:stepenter', function(e){ if ($(e.target).hasClass('laststep')) { // Don't spam the API rKiosk++; if (rKiosk%2==1) { clearKiosk(); } } if (typeof timing !== 'undefined') clearInterval(timing); var duration = (e.target.getAttribute('data-transition-duration') ? e.target.getAttribute('data-transition-duration') : 2000); // use the set duration or fallback to 2000ms timing = setInterval(impressKiosk.next, duration); });
// Module dependencies. var application_root = __dirname, express = require('express'), // Web framework path = require('path'), // Utilities for dealing with file paths mongoose = require('mongoose'); //MongoDB integration // Create server var app = express(); // Configure server app.configure(function() { // parses request body and populates request.body app.use(express.bodyParser()); // checks request.body for http method overrides app.use(express.methodOverride()); // perform route lookup based on URL and HTTP method app.use(app.router); // where to serve static content app.use(express.static(path.join(application_root, '../'))); //show all errors in development app.use(express.errorHandler({dumpExceptions: true, showStack: true})); }); // Start server var port = 4712; app.listen(port, function() { console.log('Express server listening on port %d in %s node', port, app.settings.env); }); /** * BDD */ // Connect to database mongoose.connect('mongodb://localhost/docs_database'); // Schemas var Menu = new mongoose.Schema({ title: String, imgSrc: String, path: String }); var Article = new mongoose.Schema({ pid: String, title : String, text : String, created: Date, changed: Date }); // Models var MenuModel = mongoose.model('Menu', Menu); var ArticleModel = mongoose.model('Article', Article); /** * Routes */ // Example app.get('/api', function(request, response) { response.send('DOCS is running'); }); /** * Menus */ // Get a list of menu items app.get('/menus', function(request, response) { return MenuModel.find(function(err, menus) { if (!err) { return response.send(menus); } return console.log(err); }); }); // Insert a new menu item. app.post('/menus', function(request, response) { var menu = new MenuModel({ title: request.body.title, imgSrc: request.body.imgSrc, path: request.body.path }); menu.save(function(err){ if (!err) { return console.log('created menu item'); } return console.log(err); }); return response.send(menu); }); // jQuery.post('/menus', { // 'title': 'PHP', // 'imgSrc': 'images/menu/php.jpg', // 'path': 'php' // }, function(data, textStatus, jqXHR) { // console.log('POST response:'); // console.dir(data); // console.log(textStatus); // console.dir(jqXHR) // }); /** * Articles */ // Get a list of articles app.get('/articles', function(request, response) { return ArticleModel.find(function(err, articles) { if (!err) { return response.send(articles); } return console.log(err); }); }); // Insert a new article. app.post('/articles', function(request, response) { var article = new ArticleModel({ pid: request.body.pid, title: request.body.title, text: request.body.text, created: request.body.created, changed: request.body.changed }); article.save(function(err){ if (!err) { return console.log('created article'); } return console.log(err); }); return response.send(article); }); // jQuery.post('/articles', { // 'pid': "52151e31152118890b000001", // 'title': 'PHP 1', // 'text': 'PHP 1', // 'created': new Date(2013, 8, 21).getTime(), // 'changed': new Date(2013, 8, 21).getTime() // }, function(data, textStatus, jqXHR) { // console.log('POST response:'); // console.dir(data); // console.log(textStatus); // console.dir(jqXHR) // });
import React from 'react' import SelectField from 'material-ui/SelectField' import FormInput from './FormInput' const SelectInput = (props) => { const { label, children, ...rest } = props return ( <FormInput label={label}> <SelectField {...rest}> {children} </SelectField> </FormInput> ) } SelectInput.propTypes = { label: React.PropTypes.string, children: React.PropTypes.array, } export default SelectInput
import { forwardRef } from 'react'; import * as S from './styles'; const Input = forwardRef((props, ref) => { if (props.label) { return ( <S.Label> <div>{props.label}</div> <input {...props} ref={ref} /> </S.Label> ); } return <S.Input {...props} ref={ref} />; }); export default Input;
function recPermute(arr) { if (arr.length == 1) { return [arr]; } var perms = []; for (let i = 0; i < arr.length; i++) { var arr2 = []; for (let j = 0; j < arr.length; j++) { if (j != i) { arr2.push(arr[j]); } } var arr2perms = recPermute(arr2); for (let k = 0; k < arr2perms.length; k++) { let temp = arr2perms[k]; temp.push(arr[i]); perms.push(temp); } } return perms; } var seed = ['a','b','c','d']; var permutations = recPermute(seed); console.log('Generated ' + permutations.length + ' permutations of ' + seed); console.log(permutations);
export default /* glsl */` attribute vec3 vertex_position; attribute vec3 vertex_normal; attribute vec4 vertex_tangent; attribute vec2 vertex_texCoord0; attribute vec2 vertex_texCoord1; attribute vec4 vertex_color; uniform mat4 matrix_viewProjection; uniform mat4 matrix_model; uniform mat3 matrix_normal; vec3 dPositionW; mat4 dModelMatrix; mat3 dNormalMatrix; `;
const dbconnect = () => { const mongoose = require('mongoose'); const uri = "mongodb+srv://Ignacio-Merello:19Norelacional84!@cluster0.8wyqg.mongodb.net/clinicaMerello?retryWrites=true&w=majority"; mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }).then(() => { console.log('Connection Established') }) .catch(error => console.error('Error connecting' + error)); } module.exports = dbconnect;
import React, { Component } from 'react'; import './App.css'; import { Theme as UWPThemeProvider, getTheme } from "react-uwp/Theme"; import Button from "react-uwp/Button"; import TextBox from "react-uwp/TextBox"; import * as PropTypes from 'prop-types'; import PasswordBox from "react-uwp/PasswordBox"; import AutoSuggestBox from "react-uwp/AutoSuggestBox"; import {Switch} from 'react-router-dom'; import {Route, Link} from 'react-router-dom'; import NavigationView from "react-uwp/NavigationView"; import SplitViewCommand from "react-uwp/SplitViewCommand"; import Icon from "react-uwp/Icon"; import TreeView, { TreeItem } from "react-uwp/TreeView"; import CheckBox from "react-uwp/CheckBox"; import Toggle from "react-uwp/Toggle"; import Slider from "react-uwp/Slider"; import DropDownMenu from "react-uwp/DropDownMenu"; // import Content from "./components/Content"; import { FadeInOut, SlideInOut, ScaleInOut, CustomAnimate } from "react-uwp/Animate"; const baseStyle: React.CSSProperties = { margin: "10px 10px 10px 0" }; class ProjectOpened extends Component { static contextTypes = { theme: PropTypes.object }; handleClick() { console.log("HALO!"); } static contextTypes = { theme: PropTypes.object }; context: { theme: ReactUWP.ThemeType }; state: ProjectOpened = { showHeaderIcon: false, showItemIcon: false, iconDirection: "left", itemHeight: 32 }; render() { const { showHeaderIcon, showItemIcon, iconDirection, itemHeight } = this.state; const navigationTopNodes = [ <TreeView style={{ height: 640 }} iconDirection={iconDirection} itemHeight={itemHeight} headerIcon={showHeaderIcon && <Icon style={{ fontSize: itemHeight / 3 }}>FolderLegacy</Icon>} itemIcon={showItemIcon && <Icon style={{ fontSize: itemHeight / 3 }}>OpenFileLegacy</Icon>} listSource={[{ title: "Buscar", children: [{ title: "Imagenes", }] },{ title: "Mis Materiales", children: [] },{ title: "Color Fondo", children: [] }]} showFocus /> ]; const navigationBottomNode = [ <SplitViewCommand label="Cerrar Sesión" icon={"\uE7E8"} /> ]; const baseStyle: React.CSSProperties = { margin: 10 }; const defaultBtnStyle: React.CSSProperties = { margin: 4 }; const { theme } = this.context; const itemStyle = theme.prefixStyle({ color: theme.baseHigh, fontSize: 14, fontWeight: "lighter", textAlign: "center", width: "40%", height: "40%", margin: 10, outline: "none", overflow: "auto", position: "absolute", left: 0, right: 0, top: 0, bottom: 0, margin: "auto" }); return ( <div style={theme.prefixStyle({ display: "flex", flexDirection: "row", alignItems: "center", justifyContent: "center", flexWrap: "wrap", width: "100%", padding: "160px 0", background: theme.desktopBackground })} > <span style={{ ...itemStyle, background: theme.acrylicTexture40.background, "marginBottom": "0px", "width": "854px", "height": "480px", }}> <NavigationView style={{ ...baseStyle, "height": "480px", "margin": "0px", "overflow": "hidden" }} className="open-p-nav-view" pageTitle={<p style={{ fontSize: "16px" }}>José Sanchez</p>} displayMode="compact" autoResize={false} defaultExpanded background={theme.listLow} initWidth={48} navigationTopNodes={navigationTopNodes} navigationBottomNodes={navigationBottomNode} focusNavigationNodeIndex={3} isControlled > <div className="open-p-nav-view-content"> </div> </NavigationView> </span> </div> ); } } export default ProjectOpened;
import BinanceClient from './binance'; import WagerrClient from './wagerr'; import PostgresClient from './postgres'; export { BinanceClient, WagerrClient, PostgresClient };
const {shopCart, passengers} = require("./data"); const orderByTotalProducts = shopCart.sort((a,b) => b.quantity - a.quantity ); const orderByPassegerName = passengers.sort ((pa, pb)=>{ if (pa.name.toLowerCase () < pb.name.toLowerCase()) return -1; if (pa.name.toLowerCase () > pb.name.toLowerCase()) return 1; return 0; }); console.log (orderByPassegerName)
//订单 var Order = function() { this.products = []; //订单商品 this.discountAct = {}; //订单所参与的优惠活动 this.totalAmount = 0; //订单总额(优惠前) this.totalSaveMoney = 0; //订单优惠金额 } //打印订单 Order.prototype.print = function() { var self = this; var text = '***<没钱赚商店>购物清单***\n'; this.products.forEach(function(product) { var payment = product.payment(); self.totalSaveMoney += payment.saveMoney; self.totalAmount += payment.autoAmount; text += '名称 :' + product.name + ', '; text += '数量 :' + product.count + product.unit + ', '; text += '单价 :' + product.price / 100 + '(元), '; text += '小计 :' + payment.autoAmount + '(元)'; if (product.discount && !product.discount.free && payment.saveMoney) { text += ', 节省' + payment.saveMoney + '(元)'; } //输出订单优惠信息,注意此处只打印折扣类型的优惠信息,买X送X的优惠信息在总计中输出 if (product.discount && product.discount.free && payment.freeCount) { self.discountAct[product.discount.code].isActive = true; self.discountAct[product.discount.code].text += '名称: ' + product.name + ', 数量: ' + payment.freeCount + product.unit + '\n'; } text += '\n'; }) text += '----------------------\n'; //输出买X送X的优惠信息 for (var i in this.discountAct) { var discountAct = this.discountAct[i]; if (discountAct.isActive) { text += discountAct.text; text += '----------------------\n' } } //输出总计 text += '共计: ' + self.totalAmount.toFixed(2) + '(元)\n'; text += '节省: ' + self.totalSaveMoney.toFixed(2) + '(元)\n'; text += '**********************'; return text; } module.exports = Order;
// you can write to stdout for debugging purposes, e.g. // console.log('this is a debug message'); // BST function BST( data ){ var root, createNode; // Creates tree node createNode = function( data ){ return { left: null, data: data, right: null }; }; root = createNode( data ); // Inserts new node in tree, if it doesn't already exist this.insert = function( data ){ var node, next = root, newNode; // Traverse tree to find position for new node while ( next !== null ){ node = next; next = data < node.data ? node.left : node.right; if ( data === node.data ){ return -1; } } newNode = createNode( data ); if ( data < node.data ){ node.left = newNode; }else{ node.right = newNode; } return data; }; } function solution(A) { // write your code in JavaScript (Node.js 4.0.0) var tree, counter = 0, i; if ( A.length > 0 ){ tree = new BST( A[0] ); counter++; for ( i = 1; i < A.length; i++ ){ if ( tree.insert( A[i] ) === A[i] ){ counter++ } } } return counter; }
'use strict'; /* @author Rachel Carbone */ var app = angular.module('editor.modals', ['ui-bootstrap', 'datatables']); app.controller('inspectAnalystModalCtrl', function($rootScope, $scope, $modalInstance, $modal, UserRoleService, UserService, CommonMethods, modalSettings, notifications, AuthService) { $scope.restrictTo = "analystModal"; $scope.forms = {}; $scope.settings = { 'editMode' : (typeof modalSettings.editMode === 'undefined') ? false : modalSettings.editMode, 'newMode' : (typeof modalSettings.newMode === 'undefined') ? false : modalSettings.newMode, 'analystId' : modalSettings.analyst.id }; $scope.analyst = modalSettings.analyst; UserService.getUser(modalSettings.analyst.id) .then(function(result) { $scope.analyst = result.user; }); $scope.listof = {'userRoles' : [] }; UserRoleService.getRoles() .then(function(result) { $scope.listof.userRoles = result.roles; $scope.analyst.userRole_dd = CommonMethods.findOneInArray($scope.listof.userRoles, 'id', $scope.analyst.roleId); }); $scope.modalInEditMode = function(status) { $scope.settings.editMode = status; }; /* Used as a sub modal */ $scope.assignArticle = function(analystId) { var modalInstance = $modal.open({ templateUrl: 'js/app/modals/templates/inspectAssignmentModal.html', controller: 'inspectAssignmentModalCtrl', size: 'lg', backdrop: 'static', resolve: { modalSettings: function() { return { 'analystId' : modalSettings.analyst.id, 'assignment' : {}, 'editMode' : true, 'newMode' : true, 'admin' : true }; }, listof: function() { return $scope.listof; } } }); modalInstance.result.then(function(result) { }, function() { }); }; $scope.modalAddNew = function() { if ($scope.forms.analystForm.$valid) { $scope.analyst.roleId = $scope.analyst.userRole_dd.id; UserService.insertUser($scope.analyst) .then(function(result) { notifications.showSuccess(result); $modalInstance.close(true); }, function(error) { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': error, 'type' : 'danger' }); $scope.$broadcast('form-validate'); }); } else if(!$scope.forms.analystForm.email.$valid){ $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'Please enter a valid email.', 'type' : 'danger' }); $scope.$broadcast('form-validate'); } else { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'Please fill in all required fields.', 'type' : 'danger' }); $scope.$broadcast('form-validate'); } }; $scope.modalSave = function() { if ($scope.forms.analystForm.$valid) { $scope.analyst.roleId = $scope.analyst.userRole_dd.id; UserService.saveUser($scope.analyst, $scope.analyst.id) .then(function(result) { notifications.showSuccess(result); $modalInstance.close(true); }, function(error) { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': error, 'type' : 'danger' }); $scope.$broadcast('form-validate'); }); } else if(!$scope.forms.analystForm.email.$valid){ $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'Please enter a valid email.', 'type' : 'danger' }); $scope.$broadcast('form-validate'); } else { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'Please fill in all required fields.', 'type' : 'danger' }); $scope.$broadcast('form-validate'); } }; $scope.modalDelete = function() { if($scope.analyst.assignments.length > 0) { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'This analyst cannot be deleted because they have ' + $scope.analyst.assignments.length + ' assignment(s) associated with them.', 'type' : 'danger' }); } else { if (confirm('Are you sure you want to permanently delete this analyst? This action cannot be undone.')) { UserService.deleteUser($scope.analyst.id) .then(function(result) { notifications.showSuccess(result); $modalInstance.close(true); }, function(error) { notifications.showError(error); }); } else { $scope.modalInEditMode(false); } } }; $scope.modalRetire = function() { UserService.deactivateUser($scope.analyst.id) .then(function(result) { notifications.showSuccess(result); $modalInstance.close(true); }, function(error) { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'Please fill in all required fields.', 'type' : 'danger' }); }); }; $scope.modalReactivate = function() { UserService.reactivateUser($scope.analyst.id) .then(function(result) { notifications.showSuccess(result); $modalInstance.close(true); }, function(error) { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'Please fill in all required fields.', 'type' : 'danger' }); }); }; $scope.modalCancelEdit = function() { if($scope.settings.newMode) { $modalInstance.dismiss(false); } else { $scope.modalInEditMode(false); } }; $scope.modalClose = function() { $modalInstance.dismiss(false); }; $scope.sendResetEmail = function (email) { if (confirm('Would you like to send a password reset email to this user?')) { AuthService.forgotPasswordEmail(email).then(function (results) { notifications.showSuccess("Password reset instructions have been sent to " + email); }, function (error) { $rootScope.$broadcast('alertbar-add', { 'sender' : $scope.restrictTo, 'message': 'Please fill in all required fields.', 'type' : 'danger' }); }); } }; });
import React from 'react'; import { SafeAreaView, StyleSheet, ScrollView, TouchableOpacity, TextInput, View, Text, StatusBar, ImageBackground } from 'react-native'; import { Image } from 'react-native'; import Fontisto from 'react-native-vector-icons/Fontisto'; import AntDesign from 'react-native-vector-icons/AntDesign'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import Foundation from 'react-native-vector-icons/Foundation'; import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'; import EvilIcons from 'react-native-vector-icons/EvilIcons'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import Entypo from 'react-native-vector-icons/Entypo'; import FireBaseFunctions from "../APIs/FireBaseFunctions"; import firestore from '@react-native-firebase/firestore'; class SelectFriends extends React.Component { //services = services = new FireBaseFunctions(); userObj = {}; constructor(props) { super(props); console.log(props.route.params); this.userObj = props.route.params; this.state = { isloading: true, } } GoBack = () => { this.props.navigation.navigate('SelectAudience',this.userObj); } SaveFriends=()=>{ this.props.navigation.navigate('CreatPost',this.userObj); } render() { return ( <View style={styles.Friends}> <View style={styles.FriendsTop}> <View style={{ marginTop: 25, marginLeft: 5, alignItems: 'center', width: "10%" }}> <TouchableOpacity onPress={ () => this.GoBack() } style={{}}> <AntDesign name="arrowleft" size={30} style={{ color: "black" }} /> </TouchableOpacity> </View> <View style={{ marginTop: 25, marginLeft: 5, alignItems: 'center', width: "90%" }}> <Text style={{ fontWeight: "bold", fontSize: 20, marginLeft: -50, color: "black" }}>Select Friends</Text> </View> </View> <View style={styles.FriendsBottom}> <View style={styles.FriendsBottomCard}> <View style={{ flexDirection: "row" }}> <View style={{ flexDirection: "row", width: "80%", }}> <View style={{ width: "20%" }}> <Image source={require('../Images/user.jpg')} style={{ height: 50, width: 50, borderRadius: 10, margin: 10 }} /> </View> <View style={{ marginLeft: 10, width: "80%" }}> <Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>User Name</Text> <Text style={{ fontWeight: "bold", fontSize: 20, }}>USA</Text> </View> </View> <View style={{ width: "20%" }}> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{ borderColor: '#ea0f38', margin: 20, marginTop: 30, alignItems: 'center', }}> <Entypo name="circle" size={30} style={{ color: "black" }} /> <Text style={{ margin: 5, color: "#ea0f38", fontSize: 20, fontWeight: "bold", }}></Text> </TouchableOpacity> </View> </View> </View> <View style={styles.FriendsBottomCard}> <View style={{ flexDirection: "row" }}> <View style={{ flexDirection: "row", width: "80%", }}> <View style={{ width: "20%" }}> <Image source={require('../Images/user.jpg')} style={{ height: 50, width: 50, borderRadius: 10, margin: 10 }} /> </View> <View style={{ marginLeft: 10, width: "80%" }}> <Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>User Name</Text> <Text style={{ fontWeight: "bold", fontSize: 20, }}>USA</Text> </View> </View> <View style={{ width: "20%" }}> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{ borderColor: '#ea0f38', margin: 20, marginTop: 30, alignItems: 'center', }}> <Entypo name="circle" size={30} style={{ color: "black" }} /> <Text style={{ margin: 5, color: "#ea0f38", fontSize: 20, fontWeight: "bold", }}></Text> </TouchableOpacity> </View> </View> </View> </View> <View style={styles.FriendsFooter}> <View style={{ margin: 15, marginLeft: 20,width:"40%" }}> <TouchableOpacity onPress={ () => this.SaveFriends() } style={{ borderWidth: 1, borderRadius: 15,padding:10,alignItems:"center" }}> <Text style={{ margin: 5, color: "#ea0f38", fontSize: 20, fontWeight: "bold", }}> Save </Text> </TouchableOpacity> </View> <View style={{ margin: 15, marginLeft: 20,width:"40%" }}> <TouchableOpacity onPress={ () => this.GoBack() } style={{ borderWidth: 1, borderRadius: 15,padding:10,alignItems:"center" }}> <Text style={{ margin: 5, color: "#ea0f38", fontSize: 20, fontWeight: "bold", }}> Cancel </Text> </TouchableOpacity> </View> </View> </View> ); }; } const styles = StyleSheet.create({ Friends: { width: "100%", height: "100%", backgroundColor: "white" }, FriendsTop: { flexDirection: "row", width: "100%", height: "10%", borderBottomColor: "#1f1f21", borderBottomWidth: 1, backgroundColor: "white", }, FriendsBottom: { //flexDirection: "row", width: "100%", height: "80%", //margin: "5%", backgroundColor: "white", // borderTopRightRadius: 30, // borderTopLeftRadius: 30, }, FriendsBottomCard: { flexDirection: "row", //margin: "5%", width: "90%", }, FriendsFooter: { flexDirection: "row", width: "100%", height: "10%", borderTopColor: "#1f1f21", borderTopWidth: 1, }, }); export default SelectFriends;
const users = require('../models/users'); let id = 1; module.exports = { login: (req,res,next) => { const session = req.session; const {username, password} = req.body; const user = users.find( user => { return user.username === username && user.password===password}) console.log(user) if(user){ session.user.username = user.username; res.status(200).send(user) } else { res.status(401).send("user not found") } }, register: (req,res,next) => { const {session} = req; const {username,password} = req.body; let newUser = { id: id, username: username, password: password } id++ console.log(newUser) users.push(newUser) session.user.username = username; res.status(200).send(session.user) }, signout: (req,res,next) => { req.session.destroy(); console.log(req.session); res.status(200).send(req.session); }, getUser: (req,res,next) => { const {session} = req; console.log("getuser fired") console.log(session.user) res.status(200).send(session.user); } }
jQuery(document).ready(function($){ $(document).on('keyup', '.pt-four-0, .pt-four-1, .pt-four-2, .pt-four-3', function(){ var $this = $(this); var $parent = $this.closest('.pt-option-container'); var value = []; $parent.find('input[class^="pt-four-"]').each(function(){ if( $(this).val() !== "" ){ value.push( $(this).val() ); } }); if( value.length > 0 ){ $parent.find('input[class^="pt-four-"]').each(function(){ var key = $(this).attr('class').split('pt-four-')[1]; var $this = $(this) var val = $this.val() === "" ? 0 : $this.val(); val = /^\d+$/.test(val) === true ? val+'px' : val; value[key] = val; }); } $parent.find('.pt-option').val( value.join(',') ); }); });
import React, { Component } from 'react'; import './EventForm.scss'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import { connect } from 'react-redux'; import { Field, reduxForm } from 'redux-form' import MenuItem from '@material-ui/core/MenuItem'; import {createNewEvent, updateCurrentEvent} from '../../store/actions' import { REMOVE_CURRENT_EVENT, INIT_EVENTS_STATE, CLEAR_EVENTS_STATE } from '../../store/actionTypes' const validate = values => { const errors = {} const requiredFields = [ 'name', 'date', 'organizator', 'place', 'target_market' ] requiredFields.forEach(field => { if (!values[field]) { errors[field] = 'The field is required' } }) if(values.date && (+new Date(values.date) < +new Date())){ errors.date = 'Please shoose a future date' } return errors } class EventForm extends Component { state = { name: '', date: '', organizator: '', place: '', target_market: '', } renderTextField = ({ input, label, type, meta: { touched, error }, ...custom }) => { return <TextField label={label} helperText={touched && error} margin="dense" type={type} error={touched && error && true} fullWidth InputLabelProps={{ shrink: true }} {...input} {...custom} /> } renderSelectField = ({ input, label, type, children, meta: { touched, error }, ...custom }) => { return <TextField label={label} helperText={touched && error} margin="dense" type={type} select error={touched && error && true} fullWidth InputLabelProps={{ shrink: true }} children={children} {...input} {...custom} > </TextField> } renderFileField = ({ name, input, label, type, meta: { touched, error }, ...custom }) => { return <TextField label={label} helperText={touched && error} error={touched && error && true} margin="dense" type="file" fullWidth InputLabelProps={{ shrink: true }} onChange={this.handleChangeFile('img')} {...custom} /> } handleChange = name => event => { this.setState({ [name]: event.target.value, }); }; handleChangeFile = name => event => { if(event.target && event.target.files) { this.setState({ img: event.target.files[0], }); } }; updateFormHandler = (reset) => { reset() this.props.onClose() this.props.updateCurrentEvent(this.state, this.props.orgList) } createFormHandler = (reset) => { reset() this.props.onClose() this.props.createNewEvent(this.state, this.props.orgList) } componentDidMount = () => { if(this.props.currentEvent){ this.props.initEvent(this.props.currentEvent) this.setState({ ...this.props.currentEvent, organizator: this.props.currentEvent.organizator.id }) } } componentWillUnmount = () => { this.props.clearInitialState() if(this.props.currentEvent) { this.props.removeCurrentEvent() } } render() { const { pristine, reset, invalid,} = this.props return( <Dialog className='EventForm' open={this.props.open} onClose={this.props.onClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title">Add new event</DialogTitle> <DialogContent> <Field name="name" component={this.renderTextField} label="Event name" type='text' onChange={this.handleChange("name")} /> <Field name="date" component={this.renderTextField} label="Date" type='date' onChange={this.handleChange("date")} /> <Field name="organizator" component={this.renderSelectField} label="Oranizator" type='select' select onChange={this.handleChange("organizator")} > {this.props.orgList.map((item, i) => ( <MenuItem key={item.id} value={item.id}> {item.name} </MenuItem> ))} </Field> <Field name="place" component={this.renderTextField} label="Place" type='text' onChange={this.handleChange("place")} /> <Field name="target_market" component={this.renderTextField} label="Target market" type='test' onChange={this.handleChange("target_market")} /> <Field name="img" component={this.renderFileField} label="Image" type='file' /> </DialogContent> <DialogActions> <Button onClick={this.props.onClose} color="primary"> Cancel </Button> <Button disabled={pristine || invalid} onClick={this.props.currentEvent ? this.updateFormHandler.bind(this, reset) : this.createFormHandler.bind(this, reset)} color="primary"> Add </Button> </DialogActions> </Dialog> ) } } const mapStateToProps = state => { return { eventsList: state.events.eventsList, currentEvent: state.events.currentEvent, orgList: state.organizators.orgList, initialValues: state.eventFormInit.data } } const mapDispatchToProps = dispatch => { return { createNewEvent: (data, orgList) => dispatch(createNewEvent(data, orgList)), updateCurrentEvent: (data, orgList) => dispatch(updateCurrentEvent(data, orgList)), initEvent: (data) => (dispatch({type: INIT_EVENTS_STATE, data: data})), removeCurrentEvent: () => (dispatch({type: REMOVE_CURRENT_EVENT})), clearInitialState: () => (dispatch({type: CLEAR_EVENTS_STATE})), } } EventForm = reduxForm({ form: 'eventForm', validate, })(EventForm); export default connect(mapStateToProps, mapDispatchToProps)(EventForm)
module.exports = function(program) { 'use strict'; program .command('add-service <service>').alias('as') .description('add-service command <service>') .action(function(service, command) { console.log('Add ' + service); program.log(service); }); };
(function() { 'use strict'; function targetBlankAllLinks() { var i, links = document.getElementsByTagName('a'); for (i = 0; i < links.length; i++ ) { links[i].setAttribute('target', '_blank'); } } targetBlankAllLinks(); }());
var statisticsDetailHtml = { initSlide : function(data){ var data = { "changeTime":'30', "erjibiaozhun":"asc", "erjiyonghu":"asc" } $.ajax({ url :"/BZCX/statistics/More", type : "post", data : data, async : false, success : function(data){ TwoLevelQuantity = data.TwoLevelQuantity TwoLevelUser= data.TwoLevelUser } }); }, getQueryString : function(name) { var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } return null; }, chart1 : function(){ Highcharts.chart('container', { chart: { type: 'column' }, title: { text: '' }, subtitle: { text: '' }, xAxis: { categories: TwoLevelQuantity[0] }, yAxis: { labels: { x: -15 }, title: { text: '' } }, legend: { enabled: false }, credits: { text: '' }, series: [{ name: '标准数量', data: TwoLevelQuantity[1] }], responsive: { rules: [{ condition: { maxWidth: 500 }, // Make the labels less space demanding on mobile chartOptions: { xAxis: { labels: { formatter: function () { return this.value.replace('月', '') } } }, yAxis: { labels: { align: 'left', x: 0, y: -2 }, title: { text: '' } } } }] } }); }, chart2 : function(){ $('#container').highcharts({ chart: { type: 'bar' }, title: { text: '' }, subtitle: { text: '' }, xAxis: { categories: TwoLevelUser[0], title: { text: null } }, yAxis: { min: 0, title: { text: '用户数量', align: 'high' }, labels: { overflow: 'justify' } }, tooltip: { valueSuffix: ' ' }, plotOptions: { bar: { dataLabels: { enabled: true, allowOverlap: true } } }, legend: { enabled: false }, credits: { enabled: false }, series: [{ name: '用户数量', data: TwoLevelUser[1] }] }); }, chart3 : function(){ Highcharts.chart('container', { title: { text: '' }, subtitle: { text: '' }, yAxis: { title: { text: '' } }, xAxis: { categories: ['标准1', '标准1', '标准3', '标准4', '标准5', '标准6', '标准7', '标准8'] }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, credits: { enabled: false }, plotOptions: { series: { label: { connectorAllowed: false } } }, series: [{ name: '单位1', data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175] }, { name: '单位2', data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434] }, { name: '单位3', data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387] }, { name: '单位4', data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227] }, { name: '单位5', data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111] }], responsive: { rules: [{ condition: { maxWidth: 500 }, chartOptions: { legend: { layout: 'horizontal', align: 'center', verticalAlign: 'bottom' } } }] } }); } }; //确定当前展示哪个图表 var chart = statisticsDetailHtml.getQueryString("chart"); statisticsDetailHtml.initSlide(chart); switch(chart) { case "1": statisticsDetailHtml.chart1(); $(".chart-page").show(); break; case "2": statisticsDetailHtml.chart2(); break; case "3": statisticsDetailHtml.chart3(); break; }
// for user model we have username and password as attribute module.exports = { attributes : { username: 'STRING', password: 'STRING' } };
var app = getApp(); Page({ data: { yearList: [], oneClick: false }, //去选科首页 goElectiveIndex: function goElectiveIndex(e) { var year = e.currentTarget.dataset.year; app.globalData.chooseSubject.year = year; if (!app.checkOnce(this, "oneClick")) return; var chooseSubjectInfo = wx.getStorageSync("chooseSubjectInfo"); chooseSubjectInfo.year = year; wx.setStorageSync("chooseSubjectInfo", chooseSubjectInfo); if (this.share) { wx.redirectTo({ url: "../index/index?share=true" }); } else { wx.redirectTo({ url: "../index/index" }); } }, onLoad: function onLoad(options) { this.share = false; if (options && options.share) { this.share = true; } var yearList = JSON.parse(options.year); if (options.year) { this.setData({ yearList: yearList }); } }, onShow: function onShow() { app.resetOnce(this, "oneClick"); } });
import React from 'react'; import Repos from './Repos.jsx'; const RepoList = (props) => ( <div> <h4> RepoList </h4> {props.repos.map((repo) => <Repos oneRepo={repo}/> )} There are {props.repos.length} repos. </div> ) export default RepoList;
import Config from "../config/index"; import { message } from 'antd'; const getToken = () => { let loginInfo = localStorage.getItem("login_info"); let token = ""; if(loginInfo){ let a = JSON.parse(loginInfo); // console.log("去获取token信息",a); token = a.token.token; } return token; }; const encodeURLBody = (params) => { const encodedParams = Object.keys(params).map(key => ( `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}` )).join('&'); return encodedParams; }; //设置请求的超时时间 function timeoutFetch(promise, ms) { return new Promise((resolve, reject) => { const timer = setTimeout(() => { message.error('请求超时'); reject("fetch time out"); }, ms); //成功 promise.then( (res) => { clearTimeout(timer); resolve(res); }, //失败 (err) => { clearTimeout(timer); reject(err); } ); }) } function filterStatus(res) { if (res.ok) { return res; } else if(res.status == 403){ message.error('无操作权限'); return res; }else{ throw new Error('server handle error'); return {err_code: 502}; } } function toLoginPage(){ let a = window.location.origin + window.location.pathname; window.location = a + "#/login"; } //如果未登录,跳转到登录页面 function filterJSON(res) { res = JSON.parse(res); // console.log("filterJSON拿到的结果",res); if(res.errors){ if(res.errors[0].message.indexOf("Token无效") > -1){ console.log("token无效啦"); localStorage.removeItem(Config.loginInfoKey); toLoginPage(); return false; } } return res; } const timeout = 15000; const request = (params) => { //console.log('>>>>>>params', params); let netType = Config.netType.getInstance(); let name = netType.getName(); let uri = Config.apiDomain[name]; console.log("**********当前的公链网络是", name); let headers = { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }; let fetchOption = { method:'POST', headers:headers, body: JSON.stringify(params) }; //debugger; // 模拟数据 if(typeof params.interface_name !== 'undefined'){ }else if(params.indexOf('rap2api')>-1 || params.indexOf('http') > -1){ uri = params; headers = { Accept: 'application/json', }; fetchOption = { method:'GET', headers:headers, }; } return timeoutFetch(fetch(uri, fetchOption), timeout) .then(filterStatus) .then((response) => response.text()) .then(filterJSON) .catch((e) => { if(e !== "fetch time out"){ message.error("服务或者网络异常"); } if (e instanceof Array) { e.forEach(console.log); } else { console.log('服务或者网络异常: ',e); } return false; }); }; export default { exec:request };
/* 1 Cree un programa que muestre los números naturales de 1 a n. Use ciclo while */ let enterN = parseInt(prompt("Ingrese n")); showNaturalNumbers(enterN); function showNaturalNumbers(n) { let count = 1; while(count <= n){ console.log(count); count++; } }
#!/usr/bin/env node var Promise = require('bluebird'); var MongodbConnection = require('../lib/mongodb/connection'); var StreamPrinter = require('../lib/stream/printer'); var promisifyStream = require('../lib/stream/promisify'); var cli = require('../lib/cli'); var plot = require('../lib/plot').plot; var streamToArray = require('stream-to-array'); var mongo = new MongodbConnection('mongodb://localhost:27017/neurosky'); var timeMin = new Date('2015-05-07 21:26:00 +0200'); var timeMax = new Date('2015-05-07 21:36:00 +0200'); cli.observePromise('plotRaw', Promise.join( mongo.getReader('samples', { type: 'rawEeg', time: {$gte: timeMin, $lte: timeMax} }), function(reader) { var printer = new StreamPrinter(1); reader.pipe(printer); return streamToArray(reader).then(function(sampleList) { plot(sampleList); }); }) );
import { ListGroup, Form, Col, Row, ButtonGroup, Button, InputGroup, Toast } from "react-bootstrap" import { Link } from 'react-router-dom' import { useState, useEffect } from 'react' import { QuestionCardAdmin } from './QuestionCard.js' import { OpenedQuestionModal, ClosedQuestionModal } from "./Modal.js" import API from "./API.js" function NewSurvey(props) { const [show, setShow] = useState([false, false]) const [enable, setEnable] = useState(true) const [questions, setQuestions] = useState([]) const [title, setTitle] = useState("") const [description, setDescription] = useState("") const [message, setMessage] = useState('') const handleErrors = (err) => { setMessage({ msg: err.error, type: 'danger' }) } const handleTitle = (val) => { setTitle(val) } const handleDescription = (val) => { setDescription(val) } useEffect(() => { if (title.length > 0 && questions.length > 0) setEnable(false) else setEnable(true) }, [questions, title]) const handleSave = () => { let survey = { adminID: props.adminID, title: title, description: description } API.addSurvey(survey).then(sID => { questions.forEach((q, qID) => { let question = { sID: sID, qID: qID, title: q.title, open: q.open, min: q.min, max: q.max, answers: q.answers } API.addQuestion(question).then((questionID) => { q.answers.forEach((a, aID) => { let answer = { sID: sID, qID: questionID, aID: aID, text: a } API.addAnswer(answer).then((status) => { console.log(status) }).catch(e => handleErrors(e)) }) }).catch(e => handleErrors(e)) }) }).catch(e => handleErrors(e)) } return <Row className="d-flex flex-column mx-auto" style={{ width: "60%" }}> <Toast show={message !== ''} onClose={() => setMessage('')} delay={3000} autohide> <Toast.Body>{message?.msg}</Toast.Body> </Toast> <TitleAdmin title={title} handleTitle={handleTitle} description={description} handleDescription={handleDescription} /> <ListGroup> {questions.map((q) => <QuestionCardAdmin questions={questions} setQuestions={setQuestions} question={q} />)} </ListGroup> <OpenedQuestionModal questions={questions} setQuestions={setQuestions} show={show} setShow={setShow} /> <ClosedQuestionModal questions={questions} setQuestions={setQuestions} show={show} setShow={setShow} /> <Controls setShow={setShow} handleSave={handleSave} enable={enable} title={title} /> </Row> } function TitleAdmin(props) { return <Col md={12} className="mt-3"> <Form> <InputGroup id="title"> <Form.Control required size="lg" maxLength="32" type="text" placeholder="Your survey title" onChange={(e) => props.handleTitle(e.target.value)} /> <InputGroup.Append> <InputGroup.Text id="append">{props.title.length}/64</InputGroup.Text> </InputGroup.Append> </InputGroup> <InputGroup id="description"> <Form.Control required maxLength="64" type="text" placeholder="Your survey description" onChange={(e) => props.handleDescription(e.target.value)} /> <InputGroup.Append> <InputGroup.Text id="append">{props.description.length}/64</InputGroup.Text> </InputGroup.Append> </InputGroup> <h6 className="mandatory mt-4">Mandatory questions will be marked with</h6> </Form> </Col> } function Controls(props) { const handleShow = (n) => { let arr = [false, false] arr[n] = true props.setShow(arr) } return <Col className="d-flex flex-column mx-auto"> <ButtonGroup size="lg" className="mt-3 mb-3" style={{ width: "100%" }}> <Button id="btn-outlined" onClick={() => handleShow(0)}>New open-ended question</Button> <Button id="btn-outlined" onClick={() => handleShow(1)}>New close-ended question</Button> </ButtonGroup> <Link className="mx-auto mb-3" style={{ textDecoration: 'none' }} to={{ pathname: "/home" }}> <Button size="lg" disabled={props.enable} variant="outline-success" onClick={() => props.handleSave()}>Save</Button> </Link> </Col> } export default NewSurvey
'use strict' const Candidate = use('App/Models/Candidate') /** @typedef {import('@adonisjs/framework/src/Request')} Request */ /** @typedef {import('@adonisjs/framework/src/Response')} Response */ /** @typedef {import('@adonisjs/framework/src/View')} View */ class CandidateController { async index ({ request, response, view }) { try { const candidates = await Candidate.all() return candidates } catch (error) { return response.status(401).send({ error: error }); } } async store ({ request, response }) { const data = request.all(); try { const candidate = await Candidate.create(data); return candidate; } catch (error) { if (error.code === "23505") { return response.status(401).send({ error: "Usuário já cadastrado" }); } return response.status(401).send({ error: error }); } } async show ({ params, request, response, view }) { try { const candidate = await Candidate.findOrFail(params.id); return candidate; } catch (error) { return response.status(400).send({ "Erro": "Não encontramos o candidato com o id informado, por favor verifique o id e tente novamente" }); } } async update ({ params, request, response, view }) { try { const candidate = await Candidate.findOrFail(params.id); const data = request.all(); candidate.merge(data); await candidate.save(); return candidate; } catch (error) { if (error.code === "23505") { return response.status(401).send({ error: "Usuário já cadastrado" }); } return response.status(401).send({ error: error }); } } async destroy({ params, auth, response }) { try { const candidate = await Candidate.findOrFail(params.id); await candidate.delete(); return response .status(401) .send({ "Sucesso": "Usuário removido com sucesso" }); } catch (error) { return response.status(401).send({ error: error }); } } } module.exports = CandidateController
// HTTP request in Postman: // GET /jsonstore/bus/businfo/ HTTP/1.1 // Host: localhost:3030
import React from 'react'; import Cart from '../containers/CartContainer'; export default function (props) { return ( <div id="headerRow" className="row"> <div className="col-sm-6 col-xs-12"> <img className="cookieMonsterImg" src='/images/cookie-monster.jpg' /> <h1>Cookie Monsters</h1> <h3 className="subtitle">Home of the world's greatest cookies</h3> </div> <div id="cartRow" className="col-sm-6 col-xs-12"> <Cart /> </div> <br/> </div> ) }
module.exports = [ { _id: "acacadcxverwwacacaaf", content: "What is meant by Electromaganetic force?", comments: [ { _id: "khdckjkjnop", content: "The fundamental force associated with electric and magnetic fields. The electromagnetic force is carried by the photon and is responsible for atomic structure, chemical reactions, the attractive and repulsive forces associated with electrical charge and magnetism, and all other electromagnetic phenomena.", type: "answer", createdBy: { _id: "bcibiwbjn238u", name: "Teacher - Abinaya Sekar", date: "11/15/2019 3:32:45 PM", }, }, ], type: "clarify", createdBy: { _id: "bcibiwbjn238u", name: "Vanitha", date: "11/15/2019 3:32:45 PM", }, }, { _id: "yubvzjsio29jnjhc084b", content: "Give some examples of electromagnetic force?", comments: [ { _id: "tyr56vb789gdj", content: "light.", comments: [ { _id: "tyr56vb789gdj", content: "Generators.", type: "comment", createdBy: { _id: "bcibiwbjn238u", name: "Renukadevi", date: "11/16/2019 2:45:37 PM", }, }, { _id: "tyr56vb789gdj", content: "Generators.", type: "Agree", createdBy: { _id: "bcibiwbjn238u", name: "Vanitha", date: "11/16/2019 2:45:37 PM", }, }, ], type: "comment", createdBy: { _id: "bcibiwbjn238u", name: "Kowsalya Vijay", date: "11/15/2019 3:32:45 PM", }, }, { _id: "khdckjkjnsdxxop", content: "Both are correct. I explain you in a detailed manner. Light is an electromagnetic wave, where an oscillating electric field generates a changing magnetic field, which in turn creates an electric field, and so on. Electrical generators work by a spinning magnetic field creating a current in a nearby wire. Other example like Electromagnetism is also responsible for the electricity powering your screen and the device you're reading on, with the flow of electrons propelled energy.", type: "answer", comments: [ { _id: "tyr56vb789gdj", content: "Is there any difference between electromagnetic force & electromagnetism", type: "clarify", createdBy: { _id: "bcibiwbjnrgefef238u", name: "Jansirani", date: "11/16/2019 2:45:37 PM", }, }, { _id: "tyr56vssssb789gdj", content: "There is no difference between them", type: "comment", createdBy: { _id: "bcibiwbjnrgefef238u", name: "Vanitha", date: "11/16/2019 2:45:37 PM", }, }, { _id: "tyr56vrwsdsvsssb789gdj", content: "Jansirani answer is wrong. Electromagnetism is a branch of physics that involvesthe study of electromagnetic force. It is a type of interaction that occurs between electrically charged particles.", type: "answer", createdBy: { _id: "bcibiwbjn238u", name: "Teacher - Abinaya Sekar", date: "11/15/2019 3:32:45 PM", }, }, ], createdBy: { _id: "bcibiwbjn238u", name: "Teacher - Abinaya Sekar", date: "11/15/2019 3:32:45 PM", }, }, ], type: "clarify", createdBy: { _id: "jndckjnwck", name: "Jeeva", date: "11/15/2019 3:32:45 PM", }, }, ];
// Your code here. var name; var grade; var roster; var assign; function roster() { var roster = document.getElementById("roster").value; document.getElementById("roster").innerHTML = roster; } document.getElementById("roster").onclick = function(){ roster = document.getElementById("roster").value; document.getElementById("grade").onchange = function(){ grade = document.getElementById("grade").value; if (name >= 72) { message = "C-" } document.getElementById('roster').onclick = roster; }; // FREEBIES! Blank-out the inputs onfocus. document.getElementById("name").onfocus = clearName; document.getElementById("grade").onfocus = clearGrade; function clearName() { document.getElementById("name").value = ""; } function clearGrade() { document.getElementById("grade").value = ""; } document.getElementById("clickme").onfocus = result; if (name >= 72) { message = "c minus" } };
NanoStateDefaultClass.inheritsFrom(NanoStateClass); var NanoStateDefault = new NanoStateDefaultClass(); function NanoStateDefaultClass() { this.key = 'default'; //this.parent.constructor.call(this); this.key = this.key.toLowerCase(); NanoStateManager.addState(this); }
const tarjetas = document.querySelectorAll('.tarjeta'); const imagenes = document.querySelectorAll('.imagen'); tarjetas.forEach((tarjeta, i) => { const enlace = document.createElement('a'); enlace.classList.add('rutas-img'); tarjeta.appendChild(enlace); enlace.appendChild(imagenes[i]); }); const links = document.querySelectorAll('.rutas-img'); links.forEach((link,i) => { const urlImagen = prompt('Ingrese la url de la imagen ' + (i+1) + ' por favor'); link.setAttribute('href',urlImagen); link.setAttribute('target','_blank'); imagenes[i].setAttribute('src',urlImagen); imagenes[i].setAttribute('width','300px'); }); /* ETAPA 3 - Nodo padre: .contenedor - Nodo hijo repetitivo: .tarjeta - Hago un template con una función donde vaya creando todo lo que se repite, y pidiendo en cada vuelta el parámetro que se va modificando. Luego llamo a la función la cantidad de veces que sean necesarias. */ /* const contenedor = document.querySelector('.contenedor'); function crearImagen(){ const tarjeta = document.createElement("div"); tarjeta.setAttribute('class','tarjeta'); contenedor.appendChild(tarjeta); const enlace = document.createElement('a'); tarjeta.appendChild(enlace); const urlImagen = prompt('Ingrese la url de la imagen'); enlace.setAttribute('href',urlImagen); enlace.setAttribute('target','_blank'); const imagen = document.createElement('img'); imagen.setAttribute('src',urlImagen); imagen.setAttribute('width','400px'); enlace.appendChild(imagen); }; for (let i = 0; i < 4; i++) { crearImagen(); }; */ //También se puede hacer por un lado el template del html con la variable url y luego insertarla en otra función //que pide el url con un prompt /* const contenedor = document.querySelector('.contenedor'); function insertarImagen(urlImagen){ const template = `<div class = 'tarjeta'> <a href = '${urlImagen}' target= '_blank'> <img src = '${urlImagen}' class = 'imagen' width = '400px' > </a> </div> ` contenedor.innerHTML += template; } function pedirImagen(){ const urlImagen = prompt('Por favor, ingrese la url de la imagen'); insertarImagen(urlImagen); } for (let i = 0; i < 4; i++) { pedirImagen(); } */
window.onload = function(){ var oSet = document.getElementById("setting"); var aInput = oSet.getElementsByTagName("input"); var oBtn = document.getElementById("btn"); var oMsg = document.getElementById("msg"); oBtn.onclick = function() { var reg = /^((?!0)\d{1,2}|100)$/; if(!reg.test(aInput[0].value)){ alert("请输入正确的数值:\n\n行数范围【1-100】"); aInput[0].select(); return } else if(!reg.test(aInput[1].value)){ alert("请输入正确的数值:\n\n列数范围【1-100】"); aInput[1].select(); return } createTable(aInput[0].value,aInput[1].value); var oTab = document.getElementsByTagName("table")[0]; oTab.onclick = function(event){ var event = event || window.event; var oTarget = event.target || event.srcElement; if(oTarget.tagName.toUpperCase() === "TD") { oMsg.style.display = "block"; oMsg.innerHTML = ""; oMsg.innerHTML = "<span>您选择的区域数字是:"+oTarget.innerHTML+",颜色为:"+"</span><em style=\"background:"+oTarget.style.backgroundColor+";\"></em><span>"+oTarget.style.backgroundColor+"</span>"; } } } } function RandomColor(lower,upper){ return Math.floor(Math.random()*(upper - lower+1)+lower) } function getRanColor(){ var str = this.RandomColor(0, 0xF0F0F0).toString(16); while(str.length < 6) str = "0"+str; return "#" + str; } function createTable(row,col){ var aTable=document.getElementsByTagName('table'); if(aTable.length >= 1) { for(var i=0;i<aTable.length;i++){ document.body.removeChild(aTable[i]); } } var oTable = document.createElement("table"); for (var i = 0; i < row; i++) { var oTr = document.createElement("tr"); oTable.appendChild(oTr); for (var j = 0; j < col; j++) { var oTd = document.createElement("td"); oTd.style.background = getRanColor(); oTd.innerHTML = RandomColor(1,15); oTr.appendChild(oTd); }; }; document.body.appendChild(oTable); }