text
stringlengths
7
3.69M
import React from 'react'; import styles from './styles.module.css'; import Modal from '../../elements/Modal'; import Button from '../../elements/Button'; export default function ModalSuccess(props) { const { onClose, open, message, action } = props; return ( <Modal onClose={onClose} open={open}> <section className={styles['success-root']}> <h2>{message}</h2> <Button handleClick={action} variant="primary"> Tutup </Button> </section> </Modal> ); }
var CaseManager = require("./common/CaseManager"); var CcdFields = require("./common/ccdFields"); var BrowserWaits = require('../../support/customWaits'); class IACCase { constructor() { this.caseManager = new CaseManager(); this.ccdField = new CcdFields(); this.continueBtn = element(by.xpath('//button[contains(text(),\'Continue\')]')); this.validationError = $(".validation-error"); this.addNewBtn = element(by.xpath('//button[contains(text(),\'Add new\')]')); this.docUploadField = $("#uploadTheNoticeOfDecisionDocs_0_document"); this.findAddressBtn = element(by.xpath('//button[contains(text(),\'Find address\')]')); this.firstOption = element(by.xpath('//option[@value=\'1: Object\']')); this.clientDetentionCheckbox = $("#checklist_checklist2-isNotDetained"); this.clientEUDecisionCheckbox = $("#checklist_checklist7-isNotEUDecision"); this.yesAppellantUK = element(by.xpath('//input[@id=\'appellantInUk_Yes\']')); this.HORefferenceField = $("#homeOfficeReferenceNumber"); this.dayField = $("#homeOfficeDecisionDate-day"); this.monthField = $("#homeOfficeDecisionDate-month"); this.yearField = $("#homeOfficeDecisionDate-year"); this.appelantTitle = $("#appellantTitle"); this.appelantFirstName = $("#appellantGivenNames"); this.appelantLastName = $("#appellantFamilyName"); this.dayOfBirth = $("#appellantDateOfBirth-day"); this.monthOfBirth = $("#appellantDateOfBirth-month"); this.yearOfBirth = $("#appellantDateOfBirth-year"); this.isStateless = $("#appellantStateless-isStateless"); this.contacEmail = element(by.xpath('//input[@id=\'contactPreference-wantsEmail\']')); this.emailField = $("#email"); this.appealType = $("#appealType-revocationOfProtection"); this.appealGrounds = $("#appealGroundsRevocation_values-revocationRefugeeConvention"); this.noDeportation = $("#deportationOrderOptions_No"); this.noNewMatters = $("#hasNewMatters_No"); this.otherAppeals = $("#hasOtherAppeals"); this.legalRepName = $("#legalRepName"); this.legalRepRef = $("#legalRepReferenceNumber"); this.yesFixedAddress = $("#appellantHasFixedAddress_Yes"); } async createCase(isAccessibilityTest) { var caseData = { "Home Office Reference/Case ID" : "012345678", "Appeal number[0]." : "IA123451234", "Other appeals" : "No", "Has your client appealed against any other UK immigration decisions?": "No", }; await this.caseManager.createCase(caseData, isAccessibilityTest); } async getErrorMessageMandatoryField(){ await this.continueBtn.click(); await BrowserWaits.waitForElement(this.validationError); return this.validationError.getText(); } async tellUsAboutYourClientPage(){ await this.clientDetentionCheckbox.click(); await this.clientEUDecisionCheckbox.click(); await BrowserWaits.waitForSeconds(3); await this.continueBtn.click(); } async locationPage(){ await BrowserWaits.waitForPresenceOfElement(this.yesAppellantUK); await this.yesAppellantUK.click(); await this.continueBtn.click(); } async homeOfficeDetailsPage(){ await BrowserWaits.waitForPresenceOfElement(this.HORefferenceField); await this.HORefferenceField.sendKeys('012345678'); await this.dayField.sendKeys('01'); await this.monthField.sendKeys('01'); await this.yearField.sendKeys('2021'); await this.continueBtn.click(); } async noticeOfDecisionPage(){ await BrowserWaits.waitForPresenceOfElement(this.addNewBtn); await this.addNewBtn.click(); await this.ccdField.docUpload(); await this.ccdField.docDescriptionField(); await BrowserWaits.waitForSeconds(3); await this.continueBtn.click(); } async basicDetailsPage(){ await BrowserWaits.waitForPresenceOfElement(this.appelantTitle); await this.appelantTitle.sendKeys('Miss'); await this.appelantFirstName.sendKeys('Jane'); await this.appelantLastName.sendKeys('Doe'); await this.dayOfBirth.sendKeys('1'); await this.monthOfBirth.sendKeys('1'); await this.yearOfBirth.sendKeys('1990'); await this.continueBtn.click(); } async nationalityPage(){ await BrowserWaits.waitForPresenceOfElement(this.isStateless); await this.isStateless.click(); await this.continueBtn.click(); } async addressPage(){ await BrowserWaits.waitForPresenceOfElement(this.yesFixedAddress); await this.yesFixedAddress.click(); await this.ccdField.postcodeLookup(); await BrowserWaits.waitForSeconds(3); await BrowserWaits.waitForElementClickable(this.continueBtn); await this.continueBtn.click(); } async contactPage(){ await BrowserWaits.waitForPresenceOfElement(this.contacEmail); await this.contacEmail.click(); await BrowserWaits.waitForSeconds(3); await BrowserWaits.waitForPresenceOfElement(this.emailField); await this.emailField.sendKeys('test@test.com') await this.continueBtn.click(); } async appealTypePage(){ await BrowserWaits.waitForPresenceOfElement(this.appealType); await this.appealType.click(); await BrowserWaits.waitForSeconds(3); await this.continueBtn.click(); } async appealGroundsPage(){ await BrowserWaits.waitForPresenceOfElement(this.appealGrounds); await this.appealGrounds.click(); await BrowserWaits.waitForElementClickable(this.continueBtn); await this.continueBtn.click(); } async deportationOrderPage(){ await BrowserWaits.waitForPresenceOfElement(this.noDeportation); await this.noDeportation.click(); await this.continueBtn.click(); } async newMattersPage(){ await BrowserWaits.waitForPresenceOfElement(this.noNewMatters); await this.noNewMatters.click(); await this.continueBtn.click(); } async appealAgainstOtherDecisionsPage(){ await BrowserWaits.waitForPresenceOfElement(this.otherAppeals); await this.otherAppeals.click(); await element(by.xpath('//option[contains(text(),\'No\')]')).click(); await this.continueBtn.click(); } async legalRepDetailsPage(){ await BrowserWaits.waitForPresenceOfElement(this.legalRepName); await this.legalRepName.sendKeys('John Doe'); await this.legalRepRef.sendKeys('101010'); await this.continueBtn.click(); await BrowserWaits.waitForSeconds(3); } } module.exports = IACCase;
import { getElement } from '../utils.js'; import display from '../displayProducts.js'; const setupSearch = (store) => { const form = getElement('.input-form') const name = getElement('.search-input') form.addEventListener('keyup',()=>{ const value = name.value; if(value){ let newStore = store.filter((product)=>{ let {name} =product; name = name.toLowerCase(); if(name.startsWith(value)){ return product } }) display(newStore,getElement('.products-container')) if(newStore.length<1){ const products = getElement('.products-container') products.innerHTML = `<h3 class="filter-error">Sorry, no product matched your search</h3>` } }else{ display(store,getElement('.products-container')) } }) }; export default setupSearch;
/* al presionar el botón mostrar 10 repeticiones con números ASCENDENTE, desde el 1 al 10. */ function mostrar() { var i; for(i = 0; i < 10 ; i++){ document.write(i + "<br>"); } }
class MAttribute{ constructor(){ this.whole = true; this.fraction = false; this.decimal = false; this.degree = false; this.negative = false; }; };
import Component from '@glimmer/component'; import debugLogger from 'ember-debug-logger'; import { action } from '@ember/object'; import { htmlSafe } from '@ember/template'; import { supportsPassiveEventListeners } from 'twyr-dsl/utils/browser-features'; import { tracked } from '@glimmer/tracking'; export default class TwyrTooltipComponent extends Component { // #region Private Attributes debug = debugLogger('twyr-tooltip'); _element = null; // #endregion // #region Tracked Attributes @tracked _renderTooltip = false; @tracked _hideTooltip = true; // #endregion // #region Constructor constructor() { super(...arguments); this.debug(`constructor`); this.enterEventHandler = this._enterEventHandler.bind(this); this.leaveEventHandler = this._leaveEventHandler.bind(this); window.addEventListener('blur', this.leaveEventHandler); window.addEventListener('orientationchange', this.leaveEventHandler); window.addEventListener('scroll', this.leaveEventHandler); window.addEventListener('resize', this.leaveEventHandler); } // #endregion // #region Lifecycle Hooks @action didInsert(element) { this._renderTooltip = false; this._element = element.parentNode; this.debug(`didInsert: `, this._element); const anchorElem = this.anchorElement; if(!anchorElem) return; anchorElem.addEventListener('focus', this.enterEventHandler); anchorElem.addEventListener('mouseenter', this.enterEventHandler); anchorElem.addEventListener('touchstart', this.enterEventHandler, supportsPassiveEventListeners ? { passive: true } : false); } willDestroy() { this.debug(`willDestroy`); super.willDestroy(...arguments); const anchorElem = this.anchorElement; if(!anchorElem) return; anchorElem.removeEventListener('touchstart', this.enterEventHandler, supportsPassiveEventListeners ? { passive: true } : false); anchorElem.removeEventListener('mouseenter', this.enterEventHandler); anchorElem.removeEventListener('focus', this.enterEventHandler); window.removeEventListener('scroll', this.leaveEventHandler); window.removeEventListener('resize', this.leaveEventHandler); window.removeEventListener('orientationchange', this.leaveEventHandler); window.removeEventListener('blur', this.leaveEventHandler); } // #endregion // #region DOM Event Handlers _enterEventHandler() { this.debug(`_enterEvent`); if(this.isDestroying || this.isDestroyed) return; const anchorElem = this.anchorElement; if(!anchorElem) return; anchorElem.addEventListener('blur', this.leaveEventHandler); anchorElem.addEventListener('mouseleave', this.leaveEventHandler); anchorElem.addEventListener('touchcancel', this.leaveEventHandler); this._renderTooltip = true; this._hideTooltip = false; } _leaveEventHandler() { this.debug(`_leaveEvent`); if(this.isDestroying || this.isDestroyed) return; const anchorElem = this.anchorElement; if(!anchorElem) return; anchorElem.removeEventListener('blur', this.leaveEventHandler); anchorElem.removeEventListener('mouseleave', this.leaveEventHandler); anchorElem.removeEventListener('touchcancel', this.leaveEventHandler); this._renderTooltip = false; this._hideTooltip = true; } // #endregion // #region Computed Properties get anchorElement() { this.debug(`anchorElement`); let anchorElem = null; if(this.args.attachTo && (typeof this.args.attachTo === 'string')) { anchorElem = document.querySelector(this.args.attachTo); } anchorElem = anchorElem || this._element; this.debug(`anchorElement: `, anchorElem); return anchorElem; } get defaultedParent() { this.debug(`defaultedParent: `, (this.args.parent || '#twyr-wormhole')); return this.args.parent || '#twyr-wormhole'; } get destinationId() { const destination = this.defaultedParent; const destinationElement = (typeof destination === 'string') ? document.querySelector(destination) : destination; if((typeof destinationElement === 'string') && (destinationElement.charAt(0) === '#')) { this.debug(`destinationId: `, `#${destinationElement.substring(1)}`); return `#${destinationElement.substring(1)}`; } let id = destinationElement.getAttribute('id'); if(id) { this.debug(`destinationId: `, `#${id}`); return `#${id}`; } id = (this._element) ? `${this._element.getAttribute('id')}-parent` : 'parent'; destinationElement.setAttribute('id', id); this.debug(`destinationId: `, id); return id; } get destinationElement() { const destElem = document.querySelector(this.destinationId); this.debug(`destinationElement: `, destElem); return destElem; } get position() { this.debug(`position: `, (this.args.position || 'bottom')); return this.args.position || 'bottom'; } get zIndex() { this.debug(`z-index: `, (this.args.zIndex || 100)); return this.args.zIndex || 100; } get containerStyle() { const contStyle = htmlSafe(`pointer-events:none; z-index:${this.zIndex};`); this.debug(`containerStyle: `, contStyle); return contStyle; } // #endregion // #region Actions @action updateHideTooltip(hideTooltip) { this._hideTooltip = hideTooltip; } // #endregion }
var app = app || {}; // The Application // Our overall **AppView** is the top-level piece of UI app.AppView = Backbone.View.extend({ el: '#todoapp', events: { 'keypress #new-todo': 'createOnEnter', 'click #toggle-all': 'toggleAllToComplete' }, initialize: function(){ var todos = app.Todos todos.fetch({data: {user_id: sessionStorage.getItem('user_id')}}); this.$input = this.$('#new-todo'); this.listenTo(app.Todos, 'add', this.addOne) this.listenTo(app.Todos, 'reset', this.addAll); this.listenTo(app.Todos, 'all', this.render); // this.listenTo(app.Todos, '') }, render: function() { // var numberCompleted = app.Todos.completed().length // numberCompleted = { completed: numberCompleted, poop: "Poop Yo!" } // if (app.Todos.length) { // this.$('.todo-footer').html(this.footerTemplate(numberCompleted)) // } this.checkIfAllTodosAreCompleted(); return this // need to finish render function }, newAttributes: function(){ return { description: this.$input.val().trim(), done: false, user_id: sessionStorage.getItem('user_id') }; }, showAllAreCompleted: function(){ this.$el.find('#toggle-all').removeClass('fa-circle-o').addClass('fa-bullseye'); }, toggleAllToComplete: function(){ var todos = app.Todos.models if (this.checkIfAllTodosAreCompleted() === true) { todos.forEach(function (todo){ todo.set({'done': false}) todo.save(); // it is making another model here I believe within the database... I need to fix this // rails does not recognize that backbone model for new todos is the same. Instead it thinks it is a new one everytime // something is saved }) this.showAllAreActive(); }else { todos.forEach(function (todo){ todo.set({'done': true}); todo.save() }) this.showAllAreCompleted(); } }, checkIfAllTodosAreCompleted: function() { var todos = app.Todos var completed = todos.completed().length if (todos.length === completed && todos.length !== 0) { this.showAllAreCompleted(); return true; } else { this.showAllAreActive(); return false; } }, showAllAreActive: function(){ this.$el.find('#toggle-all').removeClass('fa-bullseye').addClass('fa-circle-o'); }, // add a single todo item to the list by creating a view // appending its element to the div todo-list-items addOne: function(todo){ var todoView = new app.TodoView({ model : todo }); $('#todo-list-items').append( todoView.render().el ); if (todoView.model.get('done')) { todoView.makeCompleted() } }, addAll: function(){ this.$('#todo-list-items').html(''); app.Todos.fetch({data: {user_id: sessionStorage.getItem('user_id')}}) app.Todos.each(this.addOne, this); }, createOnEnter: function(event){ if (event.which === 13) { var newTodo = app.Todos.create( this.newAttributes() ); console.log('created') } else { return; } this.$input.val(''); } })
import { Layout } from "antd"; import React, { Component } from "react"; import "./style.css"; export default class Header extends Component { render() { return ( <Layout.Header className="header"> <img alt="logo" src="/static/img/logo.jpg" /> <span>weekendfuelbag</span> </Layout.Header> ); } }
var cadastroAluno; var cadastroFuncionario; var cadastroAgenda; var cadastroAtividadeExtraCurricular; var cadastroCaracteristicaSaude; var cadastroCargoFuncionario; var cadastroCronograma; var cadastroGrauEscolar; var cadastroItensDeCronograma; var cadastroItensPorCronograma; var cadastroMatricula; var cadastroPeriodo; var cadastroProntuarioAluno; var cadastroResponsavel; var cadastroTipoUsuario; var cadastroTurma; /*Edicao*/ var edicaoAluno; var edicaoFuncionario; var edicaoAgenda; var edicaoAtividadeExtraCurricular; var edicaoCaracteristicaSaude; var edicaoCargoFuncionario; var edicaoCronograma; var edicaoGrauEscolar; var edicaoItensDeCronograma; var edicaoItensPorCronograma; var edicaoMatricula; var edicaoPeriodo; var edicaoProntuarioAluno; var edicaoResponsavel; var edicaoTipoUsuario; var edicaoTurma; window.onload = function () { cadastroAluno = document.getElementById("cadastroAluno"); cadastroFuncionario = document.getElementById("cadastroFuncionario"); cadastroAgenda = document.getElementById("cadastroAgenda"); cadastroAtividadeExtraCurricular = document.getElementById("cadastroAtividadeExtraCurricular"); cadastroCaracteristicaSaude = document.getElementById("cadastroCaracteristicaSaude"); cadastroCargoFuncionario = document.getElementById("cadastroCargoFuncionario"); cadastroCronograma = document.getElementById("cadastroCronograma"); cadastroGrauEscolar = document.getElementById("cadastroGrauEscolar"); cadastroItensDeCronograma = document.getElementById("cadastroItensDeCronograma"); cadastroItensPorCronograma = document.getElementById("cadastroItensPorCronograma"); cadastroMatricula = document.getElementById("cadastroMatricula"); cadastroPeriodo = document.getElementById("cadastroPeriodo"); cadastroProntuarioAluno = document.getElementById("cadastroProntuarioAluno"); cadastroResponsavel = document.getElementById("cadastroResponsavel"); cadastroTipoUsuario = document.getElementById("cadastroTipoUsuario"); cadastroTurma = document.getElementById("cadastroTurma"); /*edicao*/ edicaoAluno = document.getElementById("edicaoAluno"); edicaoFuncionario = document.getElementById("edicaoFuncionario"); edicaoAgenda = document.getElementById("edicaoAgenda"); edicaoAtividadeExtraCurricular = document.getElementById("edicaoAtividadeExtraCurricular"); edicaoCaracteristicaSaude = document.getElementById("edicaoCaracteristicaSaude"); edicaoCargoFuncionario = document.getElementById("edicaoCargoFuncionario"); edicaoCronograma = document.getElementById("edicaoCronograma"); edicaoGrauEscolar = document.getElementById("edicaoGrauEscolar"); edicaoItensDeCronograma = document.getElementById("edicaoItensDeCronograma"); edicaoItensPorCronograma = document.getElementById("edicaoItensPorCronograma"); edicaoMatricula = document.getElementById("edicaoMatricula"); edicaoPeriodo = document.getElementById("edicaoPeriodo"); edicaoProntuarioAluno = document.getElementById("edicaoProntuarioAluno"); edicaoResponsavel = document.getElementById("edicaoResponsavel"); edicaoTipoUsuario = document.getElementById("edicaoTipoUsuario"); edicaoTurma = document.getElementById("edicaoTurma"); /*------*/ var btnCadastroAluno = document.getElementById("btnCadastroAluno"); btnCadastroAluno.onclick = mostraCadastroAluno; var btnCadastroFuncionario = document.getElementById("btnCadastroFuncionario"); btnCadastroFuncionario.onclick = mostraCadastroFuncionario; var btnCadastroAgenda = document.getElementById("btnCadastroAgenda"); btnCadastroAgenda.onclick = mostraCadastroAgenda; var btnCadastroAtividadeExtraCurricular = document.getElementById("btnCadastroAtividadeExtraCurricular"); btnCadastroAtividadeExtraCurricular.onclick = mostraCadastroAtividadeExtraCurricular; var btnCaracteristicaSaúde = document.getElementById("btnCaracteristicaSaúde"); btnCaracteristicaSaúde.onclick = mostraCaracteristicaSaúde; var btnCargoFuncionario = document.getElementById("btnCargoFuncionario"); btnCargoFuncionario.onclick = mostraCargoFuncionario; var btnCronograma = document.getElementById("btnCronograma"); btnCronograma.onclick = mostraCronograma; var btnGrauEscolar = document.getElementById("btnGrauEscolar"); btnGrauEscolar.onclick = mostraGrauEscolar; var btnItensDoCronograma = document.getElementById("btnItensDoCronograma"); btnItensDoCronograma.onclick = mostraItensDoCronograma; var btnItensPorCronograma = document.getElementById("btnItensPorCronograma"); btnItensPorCronograma.onclick = mostraItensPorCronograma; var btnMatricula = document.getElementById("btnMatricula"); btnMatricula.onclick = mostraMatricula; var btnPeriodo = document.getElementById("btnPeriodo"); btnPeriodo.onclick = mostraPeriodo; var btnProntuarioAluno = document.getElementById("btnProntuarioAluno"); btnProntuarioAluno.onclick = mostraProntuarioAluno; var btnResponsavel = document.getElementById("btnResponsavel"); btnResponsavel.onclick = mostraResponsavel; var btnTipoUsuario = document.getElementById("btnTipoUsuario"); btnTipoUsuario.onclick = mostraTipoUsuario; var btnTurma = document.getElementById("btnTurma"); btnTurma.onclick = mostrabtnTurma; /*edicao*/ var btnEdicaoAluno = document.getElementById("btnEdicaoAluno"); btnEdicaoAluno.onclick = mostraEdicaoAluno; var btnEditarFuncionario = document.getElementById("btnEditarFuncionario"); btnEditarFuncionario.onclick = mostraEdicaoFuncionario; var btnEditarAgenda = document.getElementById("btnEditarAgenda"); btnEditarAgenda.onclick = mostraEdicaoAgenda; var btnEditarAtividadeExtraCurricular = document.getElementById("btnEditarAtividadeExtraCurricular"); btnEditarAtividadeExtraCurricular.onclick = mostraEdicaoAtividadeExtraCurricular; var btnEditarCaractSaude = document.getElementById("btnEditarCaractSaude"); btnEditarCaractSaude.onclick = mostraEdicaoCaractSaude; var btnEditarCargoFuncionario = document.getElementById("btnEditarCargoFuncionario"); btnEditarCargoFuncionario.onclick = mostraEdicaoCargoFuncionario; var btnEditarCronograma = document.getElementById("btnEditarCronograma"); btnEditarCronograma.onclick = mostraEdicaoCronograma; var btnEditarGrauEscolar = document.getElementById("btnEditarGrauEscolar"); btnEditarGrauEscolar.onclick = mostraEdicaoGrauEscolar; var btnEditarItensCronograma = document.getElementById("btnEditarItensCronograma"); btnEditarItensCronograma.onclick = mostraEdicaoItensCronograma; var btnEditarItensPorCronograma = document.getElementById("btnEditarItensPorCronograma"); btnEditarItensPorCronograma.onclick = mostraEdicaoItensPorCronograma; var btnEditarMatricula = document.getElementById("btnEditarMatricula"); btnEditarMatricula.onclick = mostraEdicaoMatricula; var btnEditarPeriodo = document.getElementById("btnEditarPeriodo"); btnEditarPeriodo.onclick = mostraEdicaoPeriodo; var btnEditarProntuarioAluno = document.getElementById("btnEditarProntuarioAluno"); btnEditarProntuarioAluno.onclick = mostraEdicaoProntuarioAluno; var btnEditarResponsavel = document.getElementById("btnEditarResponsavel"); btnEditarResponsavel.onclick = mostraEdicaoResponsavel; var btnEditarTipoUsuario = document.getElementById("btnEditarTipoUsuario"); btnEditarTipoUsuario.onclick = mostraEdicaoTipoUsuario; var btnEditarTurma = document.getElementById("btnEditarTurma"); btnEditarTurma.onclick = mostraEdicaoTurma; /*------*/ cadastroAluno.classList.add("escondido"); cadastroFuncionario.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); /*edicao*/ edicaoAluno.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); /*------*/ } function mostraCadastroAluno() { cadastroAluno.classList.remove("escondido"); cadastroFuncionario.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraCadastroFuncionario() { cadastroFuncionario.classList.remove("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraCadastroAgenda(){ cadastroAgenda.classList.remove("escondido"); cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraCadastroAtividadeExtraCurricular(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.remove("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraCaracteristicaSaúde(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.remove("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraCargoFuncionario(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.remove("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraCronograma(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.remove("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraGrauEscolar(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.remove("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraItensDoCronograma(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.remove("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraItensPorCronograma(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.remove("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraMatricula(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.remove("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraPeriodo(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.remove("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraProntuarioAluno(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.remove("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraResponsavel(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.remove("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostraTipoUsuario(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.remove("escondido"); cadastroTurma.classList.add("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTurma.classList.add("escondido"); } function mostrabtnTurma(){ cadastroFuncionario.classList.add("escondido"); cadastroAluno.classList.add("escondido"); cadastroAgenda.classList.add("escondido"); cadastroAtividadeExtraCurricular.classList.add("escondido"); cadastroCaracteristicaSaude.classList.add("escondido"); cadastroCargoFuncionario.classList.add("escondido"); cadastroCronograma.classList.add("escondido"); cadastroGrauEscolar.classList.add("escondido"); cadastroItensDeCronograma.classList.add("escondido"); cadastroItensPorCronograma.classList.add("escondido"); cadastroMatricula.classList.add("escondido"); cadastroPeriodo.classList.add("escondido"); cadastroProntuarioAluno.classList.add("escondido"); cadastroResponsavel.classList.add("escondido"); cadastroTipoUsuario.classList.add("escondido"); cadastroTurma.classList.remove("escondido"); edicaoFuncionario.classList.add("escondido"); edicaoAluno.classList.add("escondido"); edicaoAgenda.classList.add("escondido"); edicaoAtividadeExtraCurricular.classList.add("escondido"); edicaoCaracteristicaSaude.classList.add("escondido"); edicaoCargoFuncionario.classList.add("escondido"); edicaoCronograma.classList.add("escondido"); edicaoGrauEscolar.classList.add("escondido"); edicaoItensDeCronograma.classList.add("escondido"); edicaoItensPorCronograma.classList.add("escondido"); edicaoMatricula.classList.add("escondido"); edicaoPeriodo.classList.add("escondido"); edicaoProntuarioAluno.classList.add("escondido"); edicaoResponsavel.classList.add("escondido"); edicaoTipoUsuario.classList.add("escondido"); } /*edicao*/ function mostraEdicaoAluno() { edicaoAluno.classList.remove("escondido"); } function mostraEdicaoFuncionario() { edicaoFuncionario.classList.remove("escondido"); } function mostraEdicaoAgenda() { edicaoAgenda.classList.remove("escondido"); } function mostraEdicaoAtividadeExtraCurricular() { edicaoAtividadeExtraCurricular.classList.remove("escondido"); } function mostraEdicaoCaractSaude(){ edicaoCaracteristicaSaude.classList.remove("escondido"); } function mostraEdicaoCargoFuncionario(){ edicaoCargoFuncionario.classList.remove("escondido"); } function mostraEdicaoCronograma(){ edicaoCronograma.classList.remove("escondido"); } function mostraEdicaoGrauEscolar(){ edicaoGrauEscolar.classList.remove("escondido"); } function mostraEdicaoItensCronograma(){ edicaoItensDeCronograma.classList.remove("escondido"); } function mostraEdicaoItensPorCronograma(){ edicaoItensPorCronograma.classList.remove("escondido"); } function mostraEdicaoMatricula(){ edicaoMatricula.classList.remove("escondido"); } function mostraEdicaoPeriodo(){ edicaoPeriodo.classList.remove("escondido"); } function mostraEdicaoProntuarioAluno(){ edicaoProntuarioAluno.classList.remove("escondido"); } function mostraEdicaoResponsavel(){ edicaoResponsavel.classList.remove("escondido"); } function mostraEdicaoTipoUsuario(){ edicaoTipoUsuario.classList.remove("escondido"); } function mostraEdicaoTurma(){ edicaoTurma.classList.remove("escondido"); } /*-----*/
export default function Jobs() { let jobs = []; let handlers = []; this.add = function (handler, timeout) { handlers.push( { handler: handler, timeout: timeout } ); } this.run = function () { for (let i = 0; i < handlers.length; i++) { jobs[i] = window.setInterval(handlers[i].handler, handlers[i].timeout); } } this.stopAll = function () { for (let i = 0; i < jobs.length; i++) { window.clearInterval(jobs[i]); } jobs = []; } }
import Component from '@glimmer/component'; import debugLogger from 'ember-debug-logger'; export default class TwyrCardTitleComponent extends Component { // #region Private Attributes debug = debugLogger('twyr-card-title'); // #endregion // #region Yielded Sub-components subComponents = { 'media': 'twyr-card/title/media', 'text': 'twyr-card/title/text' }; // #endregion // #region Constructor constructor() { super(...arguments); this.debug(`constructor`); } // #endregion }
/* @flow */ /* ********************************************************** * File: types/functionTypes.js * * Brief: Types for functions * * Authors: Craig Cheney * * 2017.09.10 CC - Document created * ********************************************************* */ /* Return type of a redux-thunk */ export type thunkType = (dispatch: () => void, getState: () => *) => void; /* [] - END OF FILE */
function TreeNode(val) { this.val = val; this.left = this.right = null; }; function sortedArrayToBST(nums) { return sortedArrayToBSTRecursive(nums, 0, nums.length); }; function sortedArrayToBSTRecursive(nums, startIndex, length) { // Base case if (length === 1) { return new TreeNode(nums[startIndex]); } // The midpoint is the startIndex + length/2 const mid = Math.floor(startIndex + length/2); // Construct midNode const midNode = new TreeNode(nums[mid]); // Connect the left and right children midNode.left = sortedArrayToBSTRecursive( nums, startIndex, mid - startIndex ); midNode.right = sortedArrayToBSTRecursive( nums, mid + 1, length - 1 - mid, ); return midNode; }
const db = require("../models"); const MalwareURL = db.DevDB.malware; const Op = db.DevDB.Sequelize.Op; const { validationResult } = require('express-validator'); /** * * @param {Object} req * @param {Object} res * @returns create a new records in the database and returns a responed */ exports.create = (req, res) => { const errors = validationResult(req); if(!errors.isEmpty()){ return res.status(422).jsonp(errors.array()); }else { let url = { address: req.body.address } MalwareURL.create(url) .then(data => { res.send(data); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating the Tutorial." }); }); } }; /** * @deprecated takes a request and returns a responed * @param {Object} req * @param {Object} res * @param {Object} next */ exports.findURL = (req, res, next) => { let hostname = req.params.hostname; if (hostname.includes(":")) { let hostAndPortArray = hostname.split(':'); hostname = hostAndPortArray[0]; port = hostAndPortArray[1]; } /** * @deprecated queries database to find hostname */ MalwareURL.findOne({ where: { address: hostname} }) .then(data => { let port = ''; let url = req.originalUrl.replace('/urlinfo/1/', ''); let path = req.params[0] ? req.params[0] : ''; let queryString = (req.query && Object.keys(req.query).length > 0) ? req.query : ''; let host = req.get('host'); let resObject = {}; if(data != null){ resObject = { message: 'URL is not safe to visit', hostname: hostname, port: port, path: path, url: url, queryString: { ...queryString }, serverHost: host, }; }else { resObject = { message: 'URL is safe to be visit', hostname: hostname, port: port, path: path, url: url, queryString: { ...queryString }, serverHost: host, }; } res.json(resObject); }).catch(err => { next(err) }) }
class Component extends HTMLElement { constructor(props) { super(); this._innerHtml = props._innerHtml; this._type = props._type || "anon"; this.attachShadow({ mode: "open" }); this.__attachContent(); } __attachContent = () => { this.shadowRoot.innerHTML = this._innerHtml; }; } export default Component;
import React from 'react' import Showtime from './Showtime.js' import $ from 'jquery' var imageURL, vote_average; var Listing = React.createClass({ getInitialState: function() { return ({imageURL: ''}); }, componentDidMount: function() { var movieDBURL = 'https://api.themoviedb.org/3/search/movie?api_key=aadd317edcf7fded06137442eb497be2&query='; var movieDBImageURL = 'https://image.tmdb.org/t/p/w500/'; var searchString = this.props.title; if (searchString.includes("IMAX")) { var len = searchString.length - 24; searchString = searchString.substr(0, len); } if (searchString.includes("3D")) { var len = searchString.length - 3; searchString = searchString.substr(0, len); } var url = movieDBURL + searchString; $.get(url).then((data) => { imageURL = movieDBImageURL + data.results[0].poster_path; vote_average = data.results[0].vote_average; this.setState({imageURL: imageURL,vote_average:vote_average}); }) }, update:function(event){ var time = event.target.id; var title = this.props.title; this.props.window.time = time; this.props.window.title = title; this.props.window.imgURL = this.state.imageURL; this.props.addEvent(); }, render:function(){ return( <ul className='collection with-header'> <li className="collection-header"><h4>{this.props.title}</h4> <img className="listingImg" src={this.state.imageURL} /> <p id='vote_average'>Vote Average: {this.state.vote_average}</p> </li> {this.props.showtimes.map((time,i)=><Showtime key={'showtime-' + i} timeClick={this.update} time={time}/>)} </ul> ) } }) export default Listing
var $grid = $('.row').isotope({ // options itemSelector: '.col-md-4', layoutMode: 'fitRows' }); $('.filter button').on("click",function(){ var value = $(this).attr('data-name'); $grid.isotope({ filter:value }) })
import Ember from 'ember'; export function dollarFormat(params, namedArgs) { var formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, }); return formatter.format(params[0]); } export default Ember.Helper.helper(dollarFormat);
import Api from '@/services/Api' export default { allquizzes(auth) { return Api().get('allquizzes', auth) }, questions(quiz,auth) { return Api().get(`questions/${quiz}`, auth) }, takequiz(candidate,quiz,auth){ return Api().get(`takequiz/${candidate}/${quiz}`,auth) }, postanswer(instance,auth){ return Api().post('postanswer',instance, auth) }, score(candidate,quiz,auth){ return Api().get(`score/${candidate}/${quiz}`, auth) }, taken(candidate,auth){ return Api().get(`taken/${candidate}`, auth) }, updaterandomquiz(randomquizid, questions, auth) { return Api().patch(`updaterandquiz/${randomquizid} `, questions, auth) }, }
require('dotenv').config() const fs = require('fs'); const exec = require('child_process').exec; const express = require('express'); const bodyParser = require('body-parser'); const request = require('request'); const app = express(); const { createEventAdapter } = require('@slack/events-api'); const slackSigningSecret = process.env.SLACK_SIGNING_SECRET; const slackEvents = createEventAdapter(slackSigningSecret, { waitForResponse: true, }); const os = require('os'); const platform = os.platform(); if (platform === 'win32') { const winsay = require('winsay'); } slackEvents.on('reaction_added', (event, respond, error) => { // console.log('Reaction event received', event); if (event.type === 'reaction_added') { const emoticonText = event.text; var outputDevice = ''; var player = 'afplay '; if (emoticonText) { //pick output device 1 = headphones, 2 = speakers (default) - windows only if (platform === 'win32') { player = 'mplayer '; const hasTest = message.text.indexOf("test"); if (hasTest > -1) { //test was included, so play through device 1 (headphones) outputDevice = '-ao dsound:device=1 '; } else { //test not included so play through device 2 (speakers) outputDevice = '-ao dsound:device=2 '; } } else { outputDevice = ''; } respond.status(200).send(); }; }; const emoticon = event.reaction; if (emoticon !== undefined) { const emoticonMp3 = `approved-sounds/${emoticon}.mp3`; fs.exists(emoticonMp3, function (existsMp3) { if (existsMp3) { exec(`${player}${outputDevice} ${emoticonMp3}`); console.log(`playing: ${emoticonMp3}`); } }); respond.status(200).send(); } else { return console.log(error.name); } }); slackEvents.on('error', (error) => { return console.log(`${error.name}: ${error}`); }); app.listen(process.env.PORT,`Listening for events on ${process.env.PORT}` ) (async (req, res) => { const server = await slackEvents.start(process.env.PORT); console.log(`Listening for events on ${server.address().process.env.PORT}`); respond.status(200).send(); })();
import app from '../../src/app'; import chai from 'chai'; import request from 'supertest'; import Bluebird from 'bluebird'; import { loadFixtures, createAuthorization } from '../helpers'; import { TOKEN, MODERATOR, ADMINISTRATOR, HIERARCHY, AUTH_NAMES } from '../../src/auth/constants'; chai.should(); function checkAuthorization( auth, httpVerb, controller, shouldBeAuthenticatedForLevel ) { return new Bluebird(resolve => { request(app) [httpVerb.toLowerCase()](controller) .set('Authorization', createAuthorization(auth)) .end((err, res) => { if (shouldBeAuthenticatedForLevel) { chai.assert.notEqual( res.status, 401, `${httpVerb} ${controller} should be allowed with ${ AUTH_NAMES[auth] }` ); } else { chai.assert.equal( res.status, 401, `${httpVerb} ${controller} should not be allowed with ${ AUTH_NAMES[auth] }` ); } resolve(); }); }); } function testSecurity(controller, httpVerb, authId) { it(`${controller} should be ${authId} authenticated for ${httpVerb}`, done => { let shouldBeAuthenticatedForLevel = false; Bluebird.each(HIERARCHY, auth => { if (auth === authId) { // we have iterated to the correct level, it should be authenticated // for all levels and up shouldBeAuthenticatedForLevel = true; } return checkAuthorization( auth, httpVerb, controller, shouldBeAuthenticatedForLevel ); }).nodeify(done); }); } describe('Security', () => { beforeEach(() => loadFixtures(['api-tokens.json'])); describe('Auth API', () => { testSecurity('/authenticate/reset', 'POST', MODERATOR); testSecurity('/authenticate/invite', 'GET', MODERATOR); testSecurity('/authenticate/invite', 'POST', MODERATOR); }); describe('API Token API', () => { testSecurity('/api-tokens', 'GET', MODERATOR); testSecurity('/api-tokens', 'POST', MODERATOR); testSecurity('/api-tokens', 'DELETE', MODERATOR); }); describe('Customer Roles API', () => { testSecurity('/roles', 'GET', MODERATOR); testSecurity('/roles', 'POST', MODERATOR); testSecurity('/roles', 'PUT', MODERATOR); testSecurity('/roles', 'DELETE', MODERATOR); }); describe('Customer API', () => { testSecurity('/customers', 'GET', TOKEN); testSecurity('/customers/1', 'GET', TOKEN); testSecurity('/customers', 'POST', TOKEN); testSecurity('/customers/1', 'PUT', TOKEN); testSecurity('/customers/1', 'DELETE', MODERATOR); }); describe('Nerd API', () => { testSecurity('/nerd', 'GET', TOKEN); testSecurity('/nerd/username', 'GET', TOKEN); }); describe('Products API', () => { testSecurity('/products', 'GET', TOKEN); testSecurity('/products/1', 'GET', TOKEN); testSecurity('/products', 'POST', MODERATOR); testSecurity('/products/1', 'DELETE', MODERATOR); }); describe('Transaction API', () => { testSecurity('/transactions', 'GET', MODERATOR); testSecurity('/transactions/1', 'GET', MODERATOR); testSecurity('/transactions', 'POST', TOKEN); }); describe('Users API', () => { testSecurity('/users', 'GET', MODERATOR); testSecurity('/users/1', 'GET', MODERATOR); testSecurity('/users', 'GET', MODERATOR); testSecurity('/users/1', 'PUT', MODERATOR); testSecurity('/users/1', 'DELETE', MODERATOR); }); });
import styled from "styled-components"; export const Ranking = styled.section` height: 700px; margin-bottom: var(--marginbottom); `; export const More = styled.div` width: 100%; height:55px; text-align: right; border-top: 1px solid var(--corborda); padding:.8rem; a { color: #9fa9ba; font-size:.9rem; } a:hover { color: var(--textcolor); } `; export const UsersContainer = styled.div` height: calc(86% - 55px); width: 100%; padding: 0 1.5rem; `; export const Top = styled.div` display: flex; justify-content: space-around; align-items: center; width: 100%; padding: 0.5rem 0; border-bottom: 1px solid var(--corborda); p { font-size: 0.9rem; margin-bottom: 0; color: var(--textcolor); } span { font-size: 0.8rem; color: #9fa9ba; } span:last-child { margin-bottom: 0; } img { width: 47px; height: 47px; background: #dedede; } @media (min-width: 992px) and (max-width: 1199px) { .top { padding: 0.6rem; } } `; export const GrupoLegendas = styled.div` width: 100%; .descricao-legendas { display: flex; justify-content: space-between; margin-top: 0.3rem; } `;
import React, {Component} from "react"; import Child from "./Child"; class ComponentLifecycle extends Component{ constructor(props) { super(props); console.log("Demo3.Parent: execute constructor"); this.state = { msg: 'this is parent component.' }; } static getDerivedStateFromProps(props, state){ console.log("Demo3.Parent: execute getDerivedStateFromProps"); return state; } componentDidMount() { console.log("Demo3.Parent: execute componentDidMount"); } render() { console.log("Demo3.Parent: execute render"); return ( <div> <h3>{this.state.msg}</h3> <Child /> </div> ); } } export default ComponentLifecycle;
import React from 'react'; import ReactDOM from 'react-dom'; import AutoSuggest from './Autosuggest'; const suggestions = ['C', 'C++', 'Python', 'Java', 'Javascript', 'PHP']; const handleSelect = selection => alert(`You selected ${selection}`); ReactDOM.render(<AutoSuggest suggestions={suggestions} onSelect={handleSelect}/>, document.getElementById('app'));
const webpack = require('webpack') const path = require('path') const pkg = require('./package.json') const compress = require('compression') const BrowserSyncPlugin = require('browser-sync-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const year = new Date().getFullYear() const contribs = ([pkg.author].concat(pkg.contributors || [])).map(c => c.name || '').join(', ') const banner = `${pkg.name} - v${pkg.version}\n${pkg.homepage}\nCopyright (c) ${year} ${contribs}\nLicensed under the ${pkg.license}` let bSync = new BrowserSyncPlugin({ host: 'localhost', port: 3000, server: { baseDir: ['.'], middleware: [compress()] }, files: ['demo/*.*', 'src/*.*'], notify: false, startPath: '/demo' }) let outputFile module.exports = env => { let mode = env.prod ? 'production' : 'development' let plugins = [] if (env.prod) { outputFile = '[name].min.js' plugins.push(new webpack.BannerPlugin(banner)) const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') .BundleAnalyzerPlugin plugins.push(new BundleAnalyzerPlugin()) } else { outputFile = '[name].js' plugins.push(bSync) } plugins.push( new MiniCssExtractPlugin({ filename: '[name].css', chunkFilename: '[name].[id].css' }) ) plugins.push( new webpack.DefinePlugin({ PRODUCTION: JSON.stringify(env.prod), LOG: JSON.stringify(!env.prod) }) ) plugins.push( new webpack.ProvidePlugin({ $: 'jquery' }) ) let devtool = env.prod ? {} : { devtool: 'cheap-module-eval-source-map' } let publicPath = '/build/' let config = { entry: { 'calendarium': './src/js/calendarium.js' }, output: { path: path.resolve(__dirname, 'dist/'), publicPath, filename: outputFile, chunkFilename: env.prod ? 'calendarium.[name].min.js' : 'calendarium.[name].js', sourceMapFilename: '[file].map', libraryTarget: 'umd', umdNamedDefine: true }, module: { rules: [ { test: /(\.jsx|\.js)$/, use: { loader: 'babel-loader', options: { presets: [['@babel/preset-env', { useBuiltIns: 'usage', corejs: 3 }]], plugins: [ '@babel/plugin-transform-runtime' ] } }, exclude: /(node_modules|bower_components)/ }, { test: /(\.jsx|\.js)$/, loader: 'eslint-loader', exclude: /node_modules/ }, { test: /\.(sa|sc|c)ss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', { loader: 'sass-loader', options: { outputStyle: 'compressed', omitSourceMapUrl: true } } ] }, { test: /\.(jpe?g|png|ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, use: 'base64-inline-loader?limit=1000&name=[name].[ext]' } ] }, resolve: { modules: [path.resolve('./node_modules'), path.resolve('./src')], extensions: ['.json', '.js', '.css'], mainFiles: ['index'] }, plugins: plugins, mode: mode, optimization: { usedExports: true }, externals: { jquery: 'jQuery' } } return env.prod ? config : { ...config, ...devtool } }
// This [js] object folds an incoming midi-note to a range set within lowOctave and highOctave // For Example is lowOctave = 3, and highOctave = 5 and a note of octave 1 comes in, it is folded to octave 5 // An incoming octave of 0 is folded to 6, which is then folded to 4 inlets = 1; outlets = 1; var lowOctave = 0; var highOctave = 10; function setLowOctave(l) { if (l < highOctave) { lowOctave = l; } } function setHighOctave(h) { if (h > lowOctave) { highOctave = h; } } function list(a) { var incNote = arguments[0]; var incVel = arguments[1]; var outNote = inNote; var outVel = incVel; var incOct = Math.floor(incNote / 12); var outOct = getNewOctave(incOct); outNote = (incNote % 12) + 12 * outOct; outlet(0,[outNote,outVel]); } function getNewOctave(oct) { var retOct = oct; while (retOct < lowOctave || retOct > highOctave) { if (oct < lowOctave) { retOct = lowOctave + (lowOctave - oct) } else if (oct > highOctave) { retOct = highOctave - (oct - highOctave) } } return retOct; }
import React, { Component } from 'react'; import Projects from './Projects'; import AboutMe from './AboutMe'; import Navbar from './NavBar'; import Info from './info'; import Photos from './Photos'; import '../style/style.css'; // Main component which displays content. class Main extends Component { state = { section: "Projects" } // Renders content based on state. Default is projects. renderModels = () => { if (this.state.section === "Projects") { return <Projects /> } if (this.state.section === "About Me") { return <AboutMe /> } if (this.state.section === "Photos") { return <Photos /> } } // Sets the section state based on nav bar selection. Projects is default. setSection = (state) => { this.setState({section: state}); } render() { return ( <div id="mainPage"> <Navbar setSection={this.setSection}/> <h2 style={{"color": "blue", "text-align": "center", "text-shadow": "2px 2px red"}} > {this.state.section} </h2> <div> {this.renderModels()} </div> <Info /> </div> ) } } export default Main;
import _ from 'lodash'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { ListView, View, Text } from 'react-native'; import { employeesFetch, loginUser } from '../actions'; import AvailableListItem from './AvailableListItem'; import { Button, CardSection } from './common'; class AvailableList extends Component { state={ order: 1, priceSum: 0, bagSum: 0, allBags: 0 }; componentWillMount() { //this.props.loginUser(); this.props.employeesFetch(); this.createDataSource(this.props); } componentWillReceiveProps(nextProps) { // nextProps are the next set of props that this component // will be rendered with // this.props is still the old set of props this.createDataSource(nextProps); } createDataSource({ employees }) { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.dataSource = ds.cloneWithRows(employees.sort((a, b) => { if (a.buyInDate < b.buyInDate) { return this.state.order * -1; } if (a.buyInDate > b.buyInDate) { return this.state.order; } return 0; })); this.sumPrices({ employees }); } dateOrder() { this.setState({ order: -1 * this.state.order }, () => this.createDataSource(this.props)); } sumPrices({ employees }) { let priceTotal = 0; let bagTotal = 0; let all = 0; employees.forEach(element => { all++; if (element.isSold === false && element.isCosign !== true) { priceTotal += Number(element.buyInPrice); bagTotal++; } }); this.setState({ priceSum: priceTotal, bagSum: bagTotal, allBags: all }); } renderRow(employee) { return <AvailableListItem employee={employee} />; } render() { return ( <View style={{ flex: 1 }}> <CardSection> <Text style={{ flex: 2, fontSize: 18 }}>Total Price:{'\n'}US$ {this.state.priceSum} </Text> <Text style={{ flex: 2, fontSize: 18 }}>Total Bags:{'\n'}{this.state.bagSum} </Text> <Button onPress={this.dateOrder.bind(this)} style={{ flex: 1 }}>Date</Button> </CardSection> <ListView enableEmptySections dataSource={this.dataSource} renderRow={this.renderRow} initialListSize={this.state.allBags} /> </View> ); } } const mapStateToProps = state => { const employees = _.map(state.employees, (val, uid) => { return { ...val, uid }; }); return { employees }; }; export default connect(mapStateToProps, { employeesFetch, loginUser })(AvailableList);
/* * ecommerceTaskDetailController.js * * Copyright (c) 2017 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * Component of eCommerce task summary. Used to fetch and display list of eCommerce task only. This component does not * show details of any particular task. * * @author vn40486 * @since 2.14.0 */ (function () { angular.module('productMaintenanceUiApp').controller('EcommerceTaskDetailController',ecommerceTaskDetailController); ecommerceTaskDetailController.$inject = ['$rootScope', '$scope','EcommerceTaskApi', 'ngTableParams', '$stateParams', 'ImageApi', 'DownloadService','urlBase', 'ProductSearchService', '$state', 'appConstants', 'productGroupApi', 'ECommerceViewApi', 'ProductSearchApi', '$filter', '$timeout','DownloadImageService','taskService']; function ecommerceTaskDetailController($rootScope, $scope, ecommerceTaskApi, ngTableParams, $stateParams, imageApi, downloadService, urlBase, productSearchService, $state, appConstants, productGroupApi, eCommerceViewApi, productSearchApi, $filter, $timeout, downloadImageService,taskService) { var self = this; /** * Hierarchy context code for eCommerce * @type {string} */ self.hierarchyContextCode = 'CUST'; self.showEcommerceTaskSummary = false; /** * Max time to wait for excel download. * * @type {number} */ self.WAIT_TIME = 1200; /** * Tracks whether or not the user is waiting for a download. * * @type {boolean} */ self.downloading = false; /** * Denotes whether back end should fetch total counts or not. Accordingly server side will decide on executing * additional logic to fetch count information. * * @type {boolean} */ self.includeCounts = false; /** * The number of rows per page constant. * @type {int} */ self.DEFAULT_PAGE_SIZE = 25; /** * The number of rows per page constant when navigate to Home page. * @type {int} */ self.NAVIGATE_PAGE_SIZE = 100; /** * The total number of records in the report. * @type {int} */ self.totalRecordCount = null; /** * The parameters passed to the application from ng-tables getData method. These need to be stored * until all the data are fetched from the backend. * * @type {null} */ self.dataResolvingParams = null; /** * The promise given to the ng-tables getData method. It should be called after data is fetched. * * @type {null} */ self.defer = null; /** * The data being shown in the report. * @type {Array} */ $scope.data = null; /** * The message to display about the number of records viewing and total (eg. Result 1-100 of 130). * @type {String} */ self.resultMessage = null; /** * maintains state of data call. * @type {boolean} */ self.firstFetch = true; /** * Represents the currently selected work request referenced task. * @type {null} */ self.selectedWorkRequest = null; /** * Map of task type and description. * @type {{MYTSK: string}} */ self.taskTypeMap = {'MYTSK':'Ecommerce View'}; /** * Map of task status code and it's description. * @type {{ACTIV: string, CLOSD: string}} */ self.taskStatusMap = {'ACTIV':'Active', 'CLOSD':'Closed'}; /** * Represents the task currently displayed on screen. * @type {{}} */ self.task = {}; /** * Represents the task currently displayed on screen. * @type {{}} */ self.taskOrg = {}; /** * Logical attribute id of PDP template. * @type {number} */ const LOGICAL_ATTR_PDP_TEMPLATE = 515; /** * Sales channel of HEB.Com * @type {string} */ const SALES_CHANNEL_HEB_COM = '01'; /** * This message will show when there is no any Show On Site options are select. * @type {string} */ const EMPTY_SHOW_ON_SITE = "Please select at least one Show On Site."; /** * No image url constant. * @type {string} */ self.NO_IMAGE_URL = 'images/no_image.png'; /** * Represents the supported imaged response data uri's mime and charset part. The <img> tags data uri * representation generally looks like "data:[<mime type>][;charset=<charset>][;base64],<encoded data>". The * "<ecoded data>" part represents the binary data expected from the server. * @type {string} */ const RESP_IMAGE_DATA_TYPE = 'data:image/png;base64,'; /** * Thumbnail Image height constant. * @type {number} */ const IMAGE_THUMBNAIL_HEIGHT = 40; /** * Thumbnail Image width constant. * @type {number} */ const IMAGE_THUMBNAIL_WIDTH = 40; /** * Constant for NO_CHANGE_UPDATE_MESSAGE * @type {string} */ const NO_CHANGE_UPDATE_MESSAGE = "There are no changes on this page to be saved. Please make any changes to update."; /** * Search criteria used during Add Products to Task. */ self.searchCriteria; /** * Keeps track of selected selected products/Rows. * @type {Array} */ self.selectedWorkRequests = []; /** * Keeps track of excluded products/Rows when "Select All" is checked. * @type {Array} */ self.excludedWorkRequests = []; /** * Represents state of Select-All check box. */ self.allWorkRequests = false; /** * Defaul user. Load all user's data. * @type {{uid: string, fullName: string}} */ self.defaultUser = {uid:'',fullName:'All'}; /** * Currently logged in user. * @type {{uid, fullName}} */ self.currentUser = {uid:$rootScope.currentUser.id, fullName: $rootScope.currentUser.name}; /** * Currently selected user/assignee initialized with the logged in user name. * @type {{uid, fullName}} */ self.assignedTo = self.currentUser; /** * List of assignee of products in the displayed task. * @type {Array} */ self.assignedToUsers = []; /** * Represents the task edit status. * @type {boolean} */ self.isEditingTask =false; /** * Represents the task delete status. * @type {boolean} */ self.isDeletingTask = false; /** * Search type product for ecommerce view * @type {String} */ const SEARCH_TYPE = "basicSearch"; /** * Selection type product for ecommerce view * @type {String} */ const SELECTION_TYPE = "Product ID"; /** * Ecommerce view tab * @type {String} */ const ECOMMERCE_VIEW_TAB = 'ecommerceViewTab'; /** * Code table of show on site filter option. * @type {[*]} */ self.showOnSiteOptions = [ {code:'Y', desc:'Yes', checked: true}, {code:'N', desc:'No', checked: true} ]; /** * Currently displayed show on site user selection. * @type {*} */ self.displayShowOnSiteOptions = angular.copy(self.showOnSiteOptions); /** * Keeps track of user's show on site selection. * @type {*} */ self.selectedShowOnSiteOptions = angular.copy(self.showOnSiteOptions); /** * Currently selected image. * @type {ProductScanImageURI} */ self.selectedImage = ''; /** * image downloading status. * @type {boolean} */ self.isImageDownloading = false; /** * Constant. */ const SPACE_STRING = ' '; const KEY_YES_STRING = 'Y'; const KEY_NO_STRING = 'N'; const ACTION_TYPE_PUBLISH = 4; /** * The saleschannel. * @type {Object} */ self.salesChannel; /** * The list of channels. * @type {Array} */ self.salesChannels=[]; /** * The pdf templates. * @type {Object} */ self.pdpTemplate; /** * The list of pdf templates. * @type {Array} */ self.pdpTemplates = []; /** * The list of fulfillmentProgram selected. * @type {Array} */ self.fulfillmentProgramsSelected = []; /** * List of FulfillmentPrograms of one channel. * @type {Array} */ self.fulfillmentPrograms=[]; /** * Holds the list of FulfillmentPrograms of all channels. * @type {Array} */ self.allFulfillmentPrograms=[]; /** * The showOnsite. * @type {Object} */ self.showOnSite; /** * The showOnsite select. * @type {Array} */ self.showOnSiteSelect; /** * The tomorrow date. * @type {Object} */ self.tomorrow; /** * Options for datepicker. */ self.options = { minDate: new Date(), maxDate: new Date("12/31/9999") }; /** * The effectiveDate. * @type {Object} */ self.effectiveDate; /** * The expirationDate. * @type {Object} */ self.expirationDate; /** * Flag for show on site start date open date picker * @type {boolean} */ self.showOnSiteStartDateOpen = false; /** * Flag for show on site end date open date picker * @type {boolean} */ self.showOnSiteEndDateOpen = false; /** * The object default select. */ self.objectSelectTemp = { id : null, description : "--Select--" }; /** * The list of work request selected. * @type {Array} */ self.workRequestSelectedList = []; /** * The search criteria. */ self.dataSearch = {}; /** * Setting for dropdown multiple select. */ $scope.dropdownMultiselectSettings = { showCheckAll: false, showUncheckAll: false, smartButtonMaxItems: 5, scrollableHeight: '250px', scrollable: true, checkBoxes: true }; /** * Text default for dropdown multiple select. */ $scope.projectText = { buttonDefaultText: "--Select--" }; /** * When click open date picker for anther attribute, store current status for date picker. */ self.openDatePicker = function (fieldName) { switch (fieldName) { case "showOnSiteStartDate": self.showOnSiteStartDateOpen = true; break; case "showOnSiteEndDate": self.showOnSiteEndDateOpen = true; break; default: break; } self.options = { minDate: new Date(), maxDate: new Date("12/31/9999") }; }; /** * The description for mass fill data. * @type {String} */ self.massFillDescription = ''; /** * List work request mass fill. * @type {Array} */ self.workRequestMassFillList = []; /** * The data mass fill for select all product. * @type {Object} */ self.dataMassFillAllProduct = {}; /** * The product selected * @type {number} */ self.productIdSelected = 0; /** * Assign to BDM flag * @type {Boolean} */ self.isAssignToBDM = false; /** * Assign to EBM flag * @type {Boolean} */ self.isAssignToEBM = false; /** * Remove all flag * @type {Boolean} */ self.isRemoveAll = false; /** * Task is deleted * @type {boolean} */ self.isDeletedTask = false; /** * The constant for message when remove all successfully. * @type {string} */ const REMOVE_ALL_SUCCESS_MESSAGE = "Delete products request submitted Successfully"; /** * The constant for message and refresh when remove all successfully. * @type {string} */ const REMOVE_ALL_SUCCESS_AND_REFRESH_MESSAGE = "Delete products request submitted Successfully. Please refresh after few seconds to see the change."; /** * This message will show when there is no any Sales Channel options are select. * @type {string} */ const EMPTY_SALES_CHANNEL_FILTER_MESSAGE = "Please select at least one Sales Channel."; /** * Constant for sales channels. */ const STORE_CODE = '02'; const DINNER_TONIGHT_CODE = '07'; const CENTRAL_MARKET_CODE = '06'; const CENTRAL_MARKET_PREFIX = 'CM-'; const HEB_TO_YOU_CODE = '03'; const HEB_TO_YOU_PREFIX = '2U-'; const EMPTY_STRING = ""; /** * The list sales channels filter. * @type {Array} */ self.salesChannelsFilter =[]; /** * The list sales channels filter org. * @type {Array} */ self.salesChannelsFilterOrg =[]; /** * Flag for check all Sales Channels. * @type {boolean} */ self.allSalesChannels = true; /** * Init function called during loading of this controller. */ self.init = function () { self.getTaskInfo($stateParams.taskId); self.getDataForMassFill(); self.tomorrow = new Date(); self.tomorrow.setDate(new Date().getDate() + 1); }; /** * Fetches high level Task info. * @param taskId task id. */ self.getTaskInfo = function(taskId) { ecommerceTaskApi.getTaskInfo( { taskId: taskId}, function(result) { if(result.alertHideSw === KEY_YES_STRING){ self.isDeletedTask = true; } else { self.isDeletedTask = false; } self.task = result; self.taskOrg = angular.copy(self.task); self.tableParams = self.buildTable(); self.fetchProductsAssignee(self.task); }, self.handleError ); }; /** * Constructs the ng-table based data table. */ self.buildTable = function () { return new ngTableParams( { page: 1, count: self.DEFAULT_PAGE_SIZE }, { counts: [25,50,100], getData: function ($defer, params) { self.isWaiting = true; self.isNoRecordsFound = false; self.defer = $defer; self.dataResolvingParams = params; self.includeCounts = false; if (self.firstFetch) { self.includeCounts = true; } self.getTaskDetail(params.page() - 1); } } ) }; /** * get product list to show on header product detail page. * @param productId the product id. * @param productPosition the current position of product on grid. */ self.getProductToNavigate = function(productId, productPosition){ //Set search condition productSearchService.setSearchType(SEARCH_TYPE); productSearchService.setSelectionType(SELECTION_TYPE); productSearchService.setSearchSelection(productId); productSearchService.setListOfProducts($scope.data); productSearchService.setAlertId($stateParams.taskId); taskService.setTaskId($stateParams.taskId); //Set selected tab is ecommerceViewTab tab to navigate ecommerce view page productSearchService.setSelectedTab(ECOMMERCE_VIEW_TAB); //productGroupService.setProductGroupId(self.cusProductGroup.customerProductGroup.custProductGroupId); //Set from page navigated to productSearchService.setFromPage(appConstants.ECOMMERCE_TASK); productSearchService.setDisableReturnToList(false); productSearchService.productUpdatesTaskCriteria = {}; productSearchService.productUpdatesTaskCriteria.trackingId = self.task.alertKey.trim(); productSearchService.productUpdatesTaskCriteria.assignee = self.assignedTo.uid; productSearchService.productUpdatesTaskCriteria.showOnSite = self.getSelectedShowOnSite(); productSearchService.productUpdatesTaskCriteria.salesChannelsFilter = self.getSelectedSalesChannelsFilter() productSearchService.productUpdatesTaskCriteria.pageIndex = self.convertPagePerCurrentPageSizeToPagePerOneHundred(productPosition); productSearchService.productUpdatesTaskCriteria.pageSize = self.NAVIGATE_PAGE_SIZE; $state.go(appConstants.HOME_STATE); }; /** * Convert page per current page size to page per one hundred. * @param productPosition the position of product on grid table. * @returns {number} the position of product per one hundred. */ self.convertPagePerCurrentPageSizeToPagePerOneHundred = function(productPosition){ var productPositionInDataBase = (self.tableParams.page()-1) * self.tableParams.count() + productPosition; return Math.floor(productPositionInDataBase/self.NAVIGATE_PAGE_SIZE) + 1; } /** * search product to show on header product detail * @param results */ self.searchProductToNavigate = function(results){ var lstProducts=[]; results.data.forEach(function(item){ item.productMaster.alertId= self.task.alertID; }); self.isWaiting = false; self.navigateToEcommerView(self.productIdSelected,results.data); }; /** * Fetches details of the task displayed on screen from database with pagination. * @param page selected page number. */ self.getTaskDetail = function(page) { self.clearMessage(); self.dataSearch ={ trackingId: self.task.alertKey.trim(), assignee: self.assignedTo.uid, showOnSite: self.getSelectedShowOnSite(), salesChannelsFilter : self.getSelectedSalesChannelsFilter(), includeCounts: self.includeCounts, page : page, pageSize : self.tableParams.count() }; ecommerceTaskApi.getTaskDetail(self.dataSearch, self.loadData,self.handleError); }; /** * Callback for a successful call to get data from the backend. * * @param results The data returned by the backend. */ self.loadData = function (results) { // Update message in the case remove all if(self.isRemoveAll){ self.isRemoveAll = false; if(results.data.length === 0){ self.message = REMOVE_ALL_SUCCESS_MESSAGE; }else{ self.message = REMOVE_ALL_SUCCESS_AND_REFRESH_MESSAGE; } } // If this was the fist page, it includes record count and total pages. if (results.complete) { self.totalRecordCount = results.recordCount; self.dataResolvingParams.total(self.totalRecordCount); self.firstFetch = false; } self.resultMessage = self.getResultMessage(results.data.length, self.tableParams.page() -1); self.renderUserSelection(results.data, self.allWorkRequests, self.selectedWorkRequests, self.excludedWorkRequests); $scope.data = results.data; self.defer.resolve(results.data); if (results.data && results.data.length === 0) { self.isNoRecordsFound = true; } self.fetchProductImages(results.data); if (self.allWorkRequests) { self.selectedWorkRequests = []; $scope.data.forEach(function(item){ var hasExist = false; self.excludedWorkRequests.forEach(function(workRequest){ if(item.workRequestId == workRequest.workRequestId){ hasExist = true; } }); if(!hasExist){ self.selectedWorkRequests.push(item); } }); } self.convertWorkRequesToWorkRequestMassFill(); self.isWaiting = false; if(results.data == null || results.data == undefined || results.data.length == 0){ self.isDeletingTask = true; } else { self.isDeletingTask = false; } }; /** * Convert workRequest data to workRequestMassFill data. */ self.convertWorkRequesToWorkRequestMassFill = function(){ $scope.data.forEach(function(item){ if(self.dataMassFillAllProduct.isMassFillAllProduct){ var hasExist = false; var workRequestMassFill = self.getWorkRequestMassFill(item, self.dataMassFillAllProduct.salesChannel, self.dataMassFillAllProduct.lstFulfillmentChannel, self.dataMassFillAllProduct.showOnSite?1:0, self.dataMassFillAllProduct.effectiveDate, self.dataMassFillAllProduct.expirationDate, self.dataMassFillAllProduct.pdpTemplate); self.workRequestMassFillList.forEach(function(workRequestMassFillOld){ if(workRequestMassFillOld.workRequestId == item.workRequestId){ hasExist = true; } }); var hasExistExcludedWorkRequests = false; self.dataMassFillAllProduct.excludedAlerts.forEach(function(excludedAlerts){ if(excludedAlerts == item.productId){ hasExistExcludedWorkRequests = true; } }); if(!hasExist && !hasExistExcludedWorkRequests){ self.workRequestMassFillList.push(workRequestMassFill); } } self.workRequestMassFillList.forEach(function(workRequestMassFill){ if(item.workRequestId == workRequestMassFill.workRequestId){ self.mapDataMassFill(item, workRequestMassFill); item.isMassFill = true; } }) }) }; /** * Used to reload table data. */ self.refreshTable = function (page, clearMsg) { if(clearMsg) { self.clearMessage(); self.salesChannel = angular.copy(self.objectSelectTemp); self.pdpTemplate = angular.copy(self.objectSelectTemp); self.showOnSite = angular.copy(self.objectSelectTemp); self.fulfillmentProgramsSelected = []; self.effectiveDate = null; self.expirationDate = null; } self.firstFetch = true; self.resetWorkRequestsSelection(true); self.tableParams.page(page); self.tableParams.reload(); self.massFillDescription = ''; self.workRequestMassFillList = []; self.selectedWorkRequests = []; self.excludedWorkRequests = []; self.dataMassFillAllProduct = {}; self.allWorkRequests = false; }; /** * Return of back end after a user removes an alert. Based on the size of totalRecordCount, * this method will either: * --reset view to initial state * --re-issue call to back end to update information displayed * * @param results Results from back end. */ self.handleSuccess = function(resp){ self.refreshTable(1, false); self.displayMessage(resp.message, false); }; /** * Callback that will respond to errors sent from the backend. * * @param error The object with error information. */ self.handleError = function(error){ if (error && error.data && error.data.message) { self.displayMessage(error.data.message, true); } else if(error && error.data && error.data.statusText) { self.displayMessage(error.data.statusText, true); } else { self.displayMessage("An unknown error occurred.", true); } self.isWaiting = false; }; /** * Generates the message that shows how many records and pages there are and what page the user is currently * on. * * @param dataLength The number of records there are. * @param currentPage The current page showing. * @returns {string} The message. */ self.getResultMessage = function(dataLength, currentPage){ return "" + (self.tableParams.count() * currentPage + 1) + " - " + (self.tableParams.count() * currentPage + dataLength) + " of " + self.totalRecordCount.toLocaleString(); }; /** * Used to reload table data. */ self.reloadTable = function (page, clearMsg) { if(clearMsg) {self.clearMessage();} self.firstFetch = true; self.tableParams.page(page); self.tableParams.reload(); }; /** * Used to display any success of failure messages above the data table. * @param message message to be displayed. * @param isError is error or not; True - message displayed in red. False- message get displayed in blue. */ self.displayMessage = function(message, isError) { self.isError = isError; if(self.isRemoveAll){ self.message = ""; }else{ self.message = message; } }; /** * Used to display any success of failure messages for the task * @param message message to be displayed. * @param isError is error or not; True - message displayed in red. False- message get displayed in blue. */ self.displayMessageTask = function(message, isError) { self.isErrorTask = isError; self.messageTask = message; }; /** * Used to clear any success/failure message displayed as result of last action by the user. */ self.clearMessage = function() { self.isError = false; self.message = ''; self.isErrorMassFillData = false; self.isErrorRequireMess = null; self.errorMassFillDataLst = []; }; /** * Used to display fulfillment Channel description as a comma separated values. * @param productFullfilmentChanels * @returns {string} */ self.displayFulfilmentChannels = function(productFullfilmentChanels) { var fulfillmentChannelNames = []; _.forEach(productFullfilmentChanels, function (o) { var saleChannelPrefix = EMPTY_STRING; switch (o.key.salesChanelCode.trim()) { case CENTRAL_MARKET_CODE: saleChannelPrefix = CENTRAL_MARKET_PREFIX; break; case HEB_TO_YOU_CODE: saleChannelPrefix = HEB_TO_YOU_PREFIX; } fulfillmentChannelNames.push(SPACE_STRING + saleChannelPrefix + o.fulfillmentChannel.description.trim()); }); if(fulfillmentChannelNames.length >0){ if(productFullfilmentChanels[0].hasMassFill){ return productFullfilmentChanels[0].fulfillmentChannel.salesChannel.description.trim() + " - " + fulfillmentChannelNames.join(); } } return fulfillmentChannelNames.join(); }; /** * Used to pull out PDP attribute info out of all the attribute information of a particular product. * @param masterDataExtensionAttributes * @returns {string} */ self.displayPDPTemplate = function (masterDataExtensionAttributes) { return _.pluck(_.filter(masterDataExtensionAttributes, {key :{'attributeId': LOGICAL_ATTR_PDP_TEMPLATE}}), 'attributeValueText').join(); }; /** * Used to show the status of show on site based on the show on site data for HEB.Com. It is assumed the default * sales channel for Ecommerce Task screen is HEB.com * @param productOnlines * @returns {*} */ self.displayShowOnSite = function (productOnlines) { var tempArray = _.filter(productOnlines,{key :{'saleChannelCode': SALES_CHANNEL_HEB_COM}}); tempArray.sort(function(date1, date2){ return new Date(date2.key.effectiveDate) - new Date(date1.key.effectiveDate); }); return _.pluck(tempArray, 'showOnSiteByExpirationDate')[0]; }; /** * Used to fetch primary image of product referenced by the work request. * @param workRequests */ self.fetchProductImages = function (workRequests) { if (workRequests) { _.forEach(workRequests, function (wrkRqst) { self.fetchProductImage(wrkRqst.productMaster); }); } }; /** * Used to fetch primary image of product referenced by the Product Master. * @param productMaster */ self.fetchProductImage = function (productMaster) { imageApi.getPrimaryImageByProductId( { productId : productMaster.prodId, salesChannelCode : SALES_CHANNEL_HEB_COM, width: IMAGE_THUMBNAIL_WIDTH, height: IMAGE_THUMBNAIL_HEIGHT }, function(result) { if(result.data && result.data.image && result.data.image.length>0) { productMaster.image = RESP_IMAGE_DATA_TYPE+result.data.image; } else { productMaster.image = self.NO_IMAGE_URL; } }, function(error) { productMaster.image = self.NO_IMAGE_URL; } ); }; /** * Used to fetch notes/comments of the selected work request (product). * @param workRequestId */ self.getProductNotes = function(workRequestId) { ecommerceTaskApi.getProductNotes( {workRequestId : workRequestId}, function(result) { console.log(result); }, self.handleError ); }; /** * Used to launch and display the product notes modal/pop-up screen. * @param workRequest */ self.displayTaskNotes = function(task) { $rootScope.$broadcast('resetTaskNotes'); $('#taskNotesModal').modal('show'); }; /** * Used to launch and display the product notes modal/pop-up screen. * @param workRequest */ self.displayProductNotes = function(workRequest) { self.selectedWorkRequest = workRequest; $timeout( function(){ $rootScope.$broadcast('openProductNotes'); }, 300); }; /** * Used to display Add products modal. */ self.addProducts = function() { self.searchCriteria = null;//clear any previously searched criteria. $rootScope.$broadcast('resetProductSearch'); $('#addProductsModal').modal('show'); }; /** * called by product-search-criteria when search button pressed * @param searchCriteria */ self.updateSearchCriteria = function(searchCriteria) { self.searchCriteria = searchCriteria; }; /** * called by product-search-selection when select button pressed * @param productSelection */ self.updateSearchSelection = function(selectedProducts) { if(!self.searchCriteria.isSelectAll){ var productIds = []; angular.forEach(selectedProducts, function (selectedProduct) { if (productIds.indexOf(selectedProduct.prodId) == -1) { productIds.push(selectedProduct.prodId); } }); self.searchCriteria.productIds = productIds.toString(); self.searchCriteria.excludedProducts = null; } self.submitAddProducts(); }; /** * Handles submit of add products. On click of submit, this method collects and sends all the selected products * (and any exclusions) to the backend service to be added to this task. */ self.submitAddProducts = function() { self.searchCriteria.trackingId = self.task.alertKey.trim(); ecommerceTaskApi.addProducts( self.searchCriteria, function(result) { self.displayMessage(result.message, false); $('#addProductsModal').modal("hide"); }, function(error) { self.handleError(error); $('#addProductsModal').modal("hide"); } ); }; /** * Resets all previous row selections when "Select All" is checked/unchecked. */ self.resetWorkRequestsSelection = function(includeSelectAll) { if (includeSelectAll) { self.allWorkRequests = false; } self.selectedWorkRequests = []; self.excludedWorkRequests = []; if(self.allWorkRequests){ $scope.data.forEach(function(workRequest){ self.selectedWorkRequests.push(workRequest) }); self.dataMassFillAllProduct.isSelectedAllProduct = true; }else { self.dataMassFillAllProduct.isSelectedAllProduct = false; } }; /** * Keeps track of row selection and exclusions in consideration to the state of "Select All" option. * * @param alertChecked selected row state. True/False. * @param alert data (Alert) object of the row that was modified. */ self.toggleProductSelection = function(workRequest) { if (self.allWorkRequests) {//checking if "Select All" is checked? !workRequest.checked ? self.excludedWorkRequests.push(workRequest) : _.remove(self.excludedWorkRequests, function(o) { var check = o.workRequestId == workRequest.workRequestId; return check; }); } workRequest.checked ? self.selectedWorkRequests.push(workRequest) : _.remove(self.selectedWorkRequests, function(o) { var check = o.workRequestId == workRequest.workRequestId; return check; }); }; /** * Used to send selected products to back end to be deleted. If select-all is chosen, then it displays the * remove-all confirmation modal for user to confirm his action, otherwise it just proceeds with sending the * selected products and tracking id (task id) to the backend service for removal from the task. */ self.removeProducts = function(){ self.clearMessage(); if(self.allWorkRequests || (self.selectedWorkRequests != null && self.selectedWorkRequests.length > 0)){ $('#removeAllProductsModal').modal("show"); }else { self.confirmSelectProductsModalContent = "Please select at least one Product to remove."; $('#confirmSelectProductsModal').modal({ backdrop: 'static', keyboard: true }); } }; /** * Handles removing all the products from the task. The backend service implementaion for this is a Batch handling, * hence this method's service callback does not wait for all products to be removed and so simply confirms on * successful submit of the batch. */ self.removeAllProducts = function() { if (self.allWorkRequests) { var data = { trackingId : self.task.alertKey.trim(), assignee: self.assignedTo.uid, showOnSite: self.getSelectedShowOnSite(), salesChannelsFilter : self.getSelectedSalesChannelsFilter(), productIds : self.getProducts(self.excludedWorkRequests)}; self.isRemoveAll = true; ecommerceTaskApi.removeAllProducts(data,self.handleSuccess,self.handleError); } else { var data = {trackingId: self.task.alertKey.trim(), productIds: self.getProducts(self.selectedWorkRequests)}; ecommerceTaskApi.removeProducts(data,self.handleSuccess,self.handleError); } }; /** * Utility function - used to collect product-ids from the given work requests. * @param workRqstArr array of work requests. * @returns {Array} array of product Ids. */ self.getProducts = function(workRqstArr) { var productIds = []; _.forEach(workRqstArr, function (o) { productIds.push(o.productId); }); return productIds; }; /** * Used to maintain the state of previous row selections by the user. Checks/Unchecks rows during data-loading (as * result of refresh or pagination). * * @param workRqstDataArr new list of data fetched from backend. * @param allWorkRqstChecked is select all checked; true/false. * @param selectedAlerts list of selected work requests/products. * @param excludedWorkRqst list of excluded work requests/products. */ self.renderUserSelection = function(workRqstDataArr, allWorkRqstChecked, selectedWorkRqst, excludedWorkRqst) { if (allWorkRqstChecked) { _.forEach(workRqstDataArr, function (workRqst) { var index = _.findIndex(excludedWorkRqst, function(o) { return o.workRequestId == workRqst.workRequestId;}); workRqst.checked = !(index > -1); /*if (index > -1) { workRqst.checked = false; } else { workRqst.checked = true; }*/ }); } else { _.forEach(workRqstDataArr, function (workRqst) { var index = _.findIndex(selectedWorkRqst, function(o) { return o.workRequestId == workRqst.workRequestId;}); workRqst.checked = index > -1; /*if (index > -1) { workRqst.checked = true; } else { workRqst.checked = false; }*/ }); } }; /** * Fetch list of users to whom the products in the task has been assgined to. * @param task */ self.fetchProductsAssignee = function(task) { ecommerceTaskApi.getProductsAssignee( {trackingId : task.alertKey.trim()}, function(result) { self.assignedToUsers = result; }, self.handleError ); }; /** * Handle change to assignee from the drop down. On change of user, this function sets the selected assignee * and kick starts refresh of the table with newly changed assingee name. * @param user selected user/assignee. */ self.toggleAssignee = function(user) { self.assignedTo = user; self.refreshTable(1, true); }; /** * Handles loading the currently logged in user's task information(products). */ self.loadMyTask = function () { self.toggleAssignee(self.currentUser); }; /** * Used to undo any task info modifications. */ self.resetTask = function () { self.task = angular.copy(self.taskOrg); self.isEditingTask = false; self.messageTask = null; self.isErrorTask = false; }; /** * Check if has changed data * @returns {boolean} */ self.hasDataChanged = function(){ return !(JSON.stringify( angular.copy(self.taskOrg)) === JSON.stringify(angular.copy(self.task))) }; /** * The funtion is used to update task. */ self.updateTask = function() { if(self.hasDataChanged()) { ecommerceTaskApi.updateTask( {taskId: self.task.alertID}, self.task, function (response) { self.displayMessageTask(response.message, false); self.isEditingTask = false; self.taskOrg = angular.copy(self.task); }, self.handleError ); }else { self.messageTask = NO_CHANGE_UPDATE_MESSAGE; self.isErrorTask = true; } }; self.deleteTask = function() { ecommerceTaskApi.deleteTask( self.task, function (results) { taskService.setReturnToEcommerceTaskList(true); taskService.setAlertDataTxt(self.task.alertDataTxt); $state.go(appConstants.HOME_STATE); }, self.handleError ); }; /** * Initiates a download of all the records. */ self.export = function() { var encodedUri = self.generateExportUrl(); if(encodedUri !== self.EMPTY_STRING) { self.downloading = true; downloadService.export(encodedUri, 'eCommerceTaskDetails.csv', self.WAIT_TIME, function () { self.downloading = false; }); } }; /** * Generates the URL to ask for the export. * * @returns {string} The URL to ask for the export. */ self.generateExportUrl = function() { var showOnSite = self.getSelectedShowOnSite(); if (showOnSite === null) { showOnSite = ''; } var salesChannelsFilter = self.getSelectedSalesChannelsFilter(); if (salesChannelsFilter === null) { salesChannelsFilter = ''; } return urlBase + '/pm/task/ecommerceTask/exportTaskDetailToCsv?' + 'trackingId=' + self.task.alertKey.trim() + '&assignee=' + self.assignedTo.uid + '&showOnSite=' + showOnSite + '&salesChannelsFilter=' + salesChannelsFilter; }; /** * Called from child component eCommerceTaskHierarchyAssignment when the assignment changes are saved */ self.updateAssignment = function() { self.refreshTable(); }; /** * Backup search condition product for ecommerce View */ self.navigateToEcommerView = function(productId,products) { //Set search condition productSearchService.setSearchType(SEARCH_TYPE); productSearchService.setSelectionType(SELECTION_TYPE); productSearchService.setSearchSelection(productId); productSearchService.setListOfProducts(products); productSearchService.setAlertId($stateParams.taskId); taskService.setTaskId($stateParams.taskId); //Set selected tab is ecommerceViewTab tab to navigate ecommerce view page productSearchService.setSelectedTab(ECOMMERCE_VIEW_TAB); //productGroupService.setProductGroupId(self.cusProductGroup.customerProductGroup.custProductGroupId); //Set from page navigated to productSearchService.setFromPage(appConstants.ECOMMERCE_TASK); productSearchService.setDisableReturnToList(false); $state.go(appConstants.HOME_STATE); }; /** * Handles applying filter change for update reason. Eventually tiggeres reloading of data table based on user selection. */ self.applyFilterShowOnSite = function() { self.selectedShowOnSiteOptions = angular.copy(self.displayShowOnSiteOptions); var optionsSelected = _.pluck(_.filter(self.selectedShowOnSiteOptions, function(o){ return o.checked == true;}),'code'); if(optionsSelected.length > 0){ self.refreshTable(1, true); $('#showOnSiteFilter').removeClass("open"); } else { self.isError = true; self.message = EMPTY_SHOW_ON_SITE; } }; /** * Resets show on site selections to initial state. */ self.resetFilterShowOnSite = function() { self.displayShowOnSiteOptions = angular.copy(self.showOnSiteOptions); self.selectedShowOnSiteOptions = angular.copy(self.showOnSiteOptions); }; /** * Cancels users selection. Changes displayed options state to previously saved state. */ self.cancelFilterShowOnSite = function() { self.displayShowOnSiteOptions = angular.copy(self.selectedShowOnSiteOptions); $('#showOnSiteFilter').removeClass("open"); }; /** * Used to show on site status of Y/N based on user selection. Returns null if both options are selected or * unselected, meaning to fetch all records. * @returns {null} */ self.getSelectedShowOnSite = function() { var optionsSelected = _.pluck(_.filter(self.selectedShowOnSiteOptions, function(o){ return o.checked == true;}),'code'); return (optionsSelected.length == 1) ? optionsSelected[0] : null; }; /** * Show full primary image, and allow user download */ self.showFullImage = function (prodId) { $('#imageModal').modal({backdrop: 'static', keyboard: true}); self.fetchProductFullImage(prodId); }; /** * Used to fetch primary image of product referenced by the product id. * @param productMaster */ self.fetchProductFullImage = function (prodId) { self.selectedImage = null; self.isImageDownloading = true; imageApi.getPrimaryImageByProductId( { productId : prodId, salesChannelCode : SALES_CHANNEL_HEB_COM }, function(result) { self.isImageDownloading = false; if(result.data) { self.selectedImage = result.data; } }, function(error) { self.isImageDownloading = false; } ); }; /** * Download current image. */ self.downloadImage = function () { if(self.selectedImage != null){ var imageFormat = (self.selectedImage.imageFormat=='' ? 'png' : self.selectedImage.imageFormat).trim(); var imageBytes = self.selectedImage.image; downloadImageService.download(imageBytes, imageFormat); } }; /** * Get data for mass fill. */ self.getDataForMassFill = function(){ self.salesChannel = angular.copy(self.objectSelectTemp); self.pdpTemplate = angular.copy(self.objectSelectTemp); self.showOnSite = angular.copy(self.objectSelectTemp); self.fulfillmentProgramsSelected = []; self.effectiveDate = null; self.expirationDate = null; self.showOnSiteSelects = [ { id : null, description : "--Select--" }, { id : 1, description : "Yes" }, { id : 0, description : "No" } ]; self.loadPDPTemplates(); self.loadFulfillmentPrograms(); $scope.handleEventSelectDropdown = { onSelectionChanged: function() { if(self.fulfillmentProgramsSelected == null || self.fulfillmentProgramsSelected.length ==0){ self.showOnSite = angular.copy(self.objectSelectTemp); self.effectiveDate = null; self.expirationDate = null; self.fulfillmentPrograms.forEach(function(fulfillmentProgram){ fulfillmentProgram.disabled = false; }); }else{ var fulfillmentProgramTemp = self.fulfillmentProgramsSelected[self.fulfillmentProgramsSelected.length-1]; if(fulfillmentProgramTemp.abbreviation.trim() == 'Dsply'){ self.fulfillmentPrograms.forEach(function(fulfillmentProgram){ if(fulfillmentProgram.abbreviation.trim() != 'Dsply'){ fulfillmentProgram.disabled = true; } }); self.fulfillmentProgramsSelected = [fulfillmentProgramTemp]; }else{ self.fulfillmentPrograms.forEach(function(fulfillmentProgram){ fulfillmentProgram.disabled = false; }); } } } }; }; /** * Load the list of channels from api. */ self.loadSalesChannels = function(){ productGroupApi.findAllSaleChanel( //success function (results) { self.salesChannels = []; self.salesChannels.push(self.salesChannel); self.salesChannelsFilter = []; _.forEach(results, function (salesChannel) { if (salesChannel.id !== STORE_CODE && salesChannel.id !== DINNER_TONIGHT_CODE) { self.salesChannels.push(angular.copy(salesChannel)); salesChannel.checked = true; self.salesChannelsFilter.push(salesChannel); } }); self.salesChannelsFilterOrg = angular.copy(self.salesChannelsFilter); self.selectedSalesChannelsFilter = angular.copy(self.salesChannelsFilter); }, self.handleError ); }; /** * Load the list of pdf templates from api. */ self.loadPDPTemplates = function () { eCommerceViewApi.findAllPDPTemplate( //success function (results) { self.pdpTemplates.push(self.pdpTemplate); self.pdpTemplates = self.pdpTemplates.concat(results); } ,self.handleError ); }; /** * Load the list of fulfillments for all sales channels from api. */ self.loadFulfillmentPrograms = function(){ productSearchApi.queryFulfilmentChannels(function(results){ self.allFulfillmentPrograms = results; self.loadSalesChannels(); }, self.handleError); }; /** * Get the list of FulfillmentPrograms by sales channel id. * * @return the list of FulfillmentPrograms. */ self.getFulfillmentPrograms = function(channelId){ var results = []; self.allFulfillmentPrograms.forEach(function(item, index){ if(item.salesChannel.id == channelId){ item.id = index; item.label = item.description.trim(); results.push(item); } } ); results.sort(); results.reverse(); return results; }; /** * Handle data when change sale channel. */ self.handleChangeSalesChannel = function(){ self.fulfillmentProgramsSelected = []; self.showOnSite = angular.copy(self.objectSelectTemp); self.effectiveDate = null; self.expirationDate = null; self.fulfillmentPrograms = self.getFulfillmentPrograms(self.salesChannel.id); }; /** * Handle data show on site date. */ self.handleShowOnSiteDate = function() { if(self.showOnSite == null || self.showOnSite.id == null || self.showOnSite.id == 0){ self.effectiveDate = null; self.expirationDate = null; }else{ self.effectiveDate = self.tomorrow; self.expirationDate = new Date("12/31/9999"); } }; /** * Mass fill data with product. */ self.massFillDataWithProduct = function(){ self.clearMessage(); if(!self.validateMassFillData()){ if((self.selectedWorkRequests != null && self.selectedWorkRequests.length > 0) || (self.allWorkRequests && self.excludedWorkRequests.length<self.totalRecordCount)){ self.isWaiting = true; if(self.dataMassFillAllProduct.isSelectedAllProduct){ var workRequestMassFillListTemp = []; if(self.excludedWorkRequests != undefined && self.excludedWorkRequests != null && self.excludedWorkRequests.length >0 ){ self.workRequestMassFillList.forEach(function(workRequestMassFillOld,index){ self.excludedWorkRequests.forEach(function(workRequest){ if(workRequestMassFillOld.workRequestId == workRequest.workRequestId){ workRequestMassFillListTemp.push(workRequestMassFillOld); } }); }) } self.workRequestMassFillList = workRequestMassFillListTemp; self.setDataMassFillAllProduct(); } self.selectedWorkRequests.forEach(function(workRequest){ var workRequestMassFill = self.getWorkRequestMassFill(workRequest, self.salesChannel, self.fulfillmentProgramsSelected, self.showOnSite, self.effectiveDate, self.expirationDate, self.pdpTemplate); var hasExist = false; $scope.data.forEach(function(item){ if(item.workRequestId == workRequest.workRequestId){ self.mapDataMassFill(item, workRequestMassFill); item.isMassFill = true; } }); self.workRequestMassFillList.forEach(function(workRequestMassFillOld){ if(workRequestMassFillOld.workRequestId == workRequest.workRequestId){ self.mapDataMassFill(workRequestMassFillOld, workRequestMassFill); hasExist = true; } }); if(!hasExist){ self.workRequestMassFillList.push(workRequestMassFill); } }); $timeout(function() { self.isWaiting = false; }, 1500); }else { self.confirmSelectProductsModalContent = "Please select at least one Product to Mass Fill."; $('#confirmSelectProductsModal').modal({ backdrop: 'static', keyboard: true }); } } }; /** * Mapp data between two workRequest. */ self.mapDataMassFill = function(workRequestMap, workRequestMassFill){ workRequestMap.pdpTemplate = angular.copy(workRequestMassFill.pdpTemplate); workRequestMap.productMaster = angular.copy(workRequestMassFill.productMaster); workRequestMap.candidateFulfillmentChannels = angular.copy(workRequestMassFill.candidateFulfillmentChannels); }; /** * Set data mass fill when check all data. */ self.setDataMassFillAllProduct = function(){ self.dataMassFillAllProduct.isMassFillAllProduct = true; var excludedAlerts = []; self.excludedWorkRequests.forEach(function(item){ excludedAlerts.push(item.productId); }); self.dataMassFillAllProduct.pdpTemplate = angular.copy(self.pdpTemplate); self.dataMassFillAllProduct.lstFulfillmentChannel = angular.copy(self.fulfillmentProgramsSelected); self.dataMassFillAllProduct.salesChannel = angular.copy(self.salesChannel); if(self.showOnSite != null && self.showOnSite.id == 1){ self.dataMassFillAllProduct.isShowOnSite = true; self.dataMassFillAllProduct.effectiveDate = self.convertDateToStringWithYYYYMMDD(self.effectiveDate); self.dataMassFillAllProduct.expirationDate = self.convertDateToStringWithYYYYMMDD(self.expirationDate); }else{ self.dataMassFillAllProduct.isShowOnSite = false; self.dataMassFillAllProduct.effectiveDate = null; self.dataMassFillAllProduct.expirationDate = null; } self.dataMassFillAllProduct.excludedAlerts = excludedAlerts; }; /** * Get WorkRequest when mass fill. */ self.getWorkRequestMassFill = function (workRequest, salesChannel, fulfillmentProgramsSelected, showOnSite, effectiveDate, expirationDate, pdpTemplate){ var workRequestMassFill = angular.copy(workRequest); var productFullfilmentChanels = self.getFullfilmentChanelsMassFill(true, salesChannel, fulfillmentProgramsSelected, showOnSite, effectiveDate, expirationDate); var candidateFulfillmentChannels = self.getFullfilmentChanelsMassFill(false, salesChannel, fulfillmentProgramsSelected, showOnSite, effectiveDate, expirationDate); workRequestMassFill.isMassFill = true; if(pdpTemplate != null && pdpTemplate.id != null){ var isMassFillPdpTemplateSuccess = false; workRequestMassFill.pdpTemplate = angular.copy(pdpTemplate); workRequestMassFill.productMaster.masterDataExtensionAttributes.forEach(function(masterDataExtensionAttribute, index){ if(masterDataExtensionAttribute.key.attributeId == LOGICAL_ATTR_PDP_TEMPLATE){ masterDataExtensionAttribute.attributeValueText = pdpTemplate.description; isMassFillPdpTemplateSuccess = true; } }); if(!isMassFillPdpTemplateSuccess){ var masterDataExtensionAttribute = { key : {attributeId : LOGICAL_ATTR_PDP_TEMPLATE}, attributeValueText : pdpTemplate.description, } workRequestMassFill.productMaster.masterDataExtensionAttributes.push(masterDataExtensionAttribute); } } if(productFullfilmentChanels.length > 0){ productFullfilmentChanels.forEach(function(productFullfilmentChanel, index){ productFullfilmentChanel.key.productId = workRequestMassFill.productId; }); workRequestMassFill.productMaster.productFullfilmentChanels = angular.copy(productFullfilmentChanels); workRequestMassFill.candidateFulfillmentChannels = angular.copy(candidateFulfillmentChannels); } return workRequestMassFill; }; /** * Get fullfilmentChanels mass fill */ self.getFullfilmentChanelsMassFill =function(isProduct, salesChannel, fulfillmentProgramsSelected, showOnSite, effectiveDate, expirationDate){ var fullfilmentChanels = []; if(salesChannel != null && salesChannel.id != null && fulfillmentProgramsSelected != null && fulfillmentProgramsSelected.length > 0){ fulfillmentProgramsSelected.forEach(function(fulfillmentChannelSelected, index){ var fullfilmentChanel; if(isProduct){ fullfilmentChanel = { key :{ salesChanelCode : fulfillmentChannelSelected.key.salesChannelCode, fullfillmentChanelCode : fulfillmentChannelSelected.key.fulfillmentChannelCode }, fulfillmentChannel : fulfillmentChannelSelected } if(showOnSite != null && showOnSite.id == 1){ fullfilmentChanel.effectDate = self.convertDateToStringWithYYYYMMDD(effectiveDate); fullfilmentChanel.expirationDate = self.convertDateToStringWithYYYYMMDD(expirationDate); }else{ fullfilmentChanel.effectDate = null; fullfilmentChanel.expirationDate = null; } }else{ fullfilmentChanel = { key :{ salesChannelCode : fulfillmentChannelSelected.key.salesChannelCode, fulfillmentChannelCode : fulfillmentChannelSelected.key.fulfillmentChannelCode }, } if(self.showOnSite != null && self.showOnSite.id == 1){ fullfilmentChanel.newData = KEY_YES_STRING; fullfilmentChanel.effectiveDate = self.convertDateToStringWithYYYYMMDD(effectiveDate); fullfilmentChanel.expirationDate = self.convertDateToStringWithYYYYMMDD(expirationDate); }else{ fullfilmentChanel.newData = KEY_NO_STRING; fullfilmentChanel.effectiveDate = null; fullfilmentChanel.expirationDate = null; } } fullfilmentChanel.hasMassFill = true; fullfilmentChanels.push(fullfilmentChanel); }); } return fullfilmentChanels; }; /** * Validate data mass fill. */ self.validateMassFillData = function(){ self.isErrorMassFillData = false; self.isErrorRequireMess = null; self.errorMassFillDataLst = []; if((self.pdpTemplate == null || self.pdpTemplate.id == null) && (self.salesChannel == null || self.salesChannel.id == null || self.fulfillmentProgramsSelected == null || self.fulfillmentProgramsSelected.length == 0)){ self.isErrorMassFillData = true; self.isErrorRequireMess = "Please select value for Mass Fill." }else if(self.salesChannel != null && self.salesChannel.id != null && self.fulfillmentProgramsSelected != null && self.fulfillmentProgramsSelected.length > 0){ if(self.showOnSite == null || self.showOnSite.id == null){ self.isErrorMassFillData = true; self.errorMassFillDataLst.push("Fulfillment Program Value is a mandatory field."); }else if(self.showOnSite.id == 1){ if (self.isDate1GreaterThanDate2(self.tomorrow, self.effectiveDate)) { self.errorMassFillDataLst.push("Start Date must be greater than Current Date."); self.isErrorMassFillData = true; } if(!self.isDate1GreaterThanDate2(self.expirationDate, self.effectiveDate)) { self.isErrorMassFillData = true; if (!self.isDate1GreaterThanDate2(self.tomorrow, self.effectiveDate)) { self.errorMassFillDataLst.push("Effective Date must be less than End Date."); } self.errorMassFillDataLst.push("End Date must be greater than Effective Date and less than 12/31/9999."); } } } return self.isErrorMassFillData; }; /** * Handle click button save mass fill. */ self.saveDataMassFill = function (){ if(self.workRequestMassFillList == null || self.workRequestMassFillList.length == 0){ self.isErrorMassFillData = true; self.isErrorRequireMess = NO_CHANGE_UPDATE_MESSAGE; }else { self.massFillDescription = ''; $('#confirmSaveMassFill').modal({ backdrop: 'static', keyboard: true }); } }; /** * Do save data mass fill. */ self.doSaveDataMassFill = function(){ self.isWaiting = true; var massUpdateTaskRequest = { isSelectAll : self.dataMassFillAllProduct.isMassFillAllProduct, excludedAlerts : self.dataMassFillAllProduct.excludedAlerts, selectedCandidateWorkRequests : self.workRequestMassFillList, salesChannel : self.dataMassFillAllProduct.salesChannel, lstFulfillmentChannel : self.dataMassFillAllProduct.lstFulfillmentChannel, isShowOnSite : self.dataMassFillAllProduct.isShowOnSite==null || self.dataMassFillAllProduct.isShowOnSite==undefined || !self.dataMassFillAllProduct.isShowOnSite?KEY_NO_STRING:KEY_YES_STRING, effectiveDate : self.dataMassFillAllProduct.effectiveDate, expirationDate : self.dataMassFillAllProduct.expirationDate, pdpTemplate : self.dataMassFillAllProduct.pdpTemplate==null || self.dataMassFillAllProduct.pdpTemplate==undefined || self.dataMassFillAllProduct.pdpTemplate.id==null?null:self.dataMassFillAllProduct.pdpTemplate, trackingId: self.task.alertKey.trim(), assigneeId: self.assignedTo.uid, showOnSiteFilter: self.getSelectedShowOnSite(), salesChannelsFilter : self.getSelectedSalesChannelsFilter(), description : self.massFillDescription } ecommerceTaskApi.updateMassFillToProduct(massUpdateTaskRequest,self.massUpdateTaskRequestSuccess, self.handleError); }; /** * Handle data when save mass fill success. */ self.massUpdateTaskRequestSuccess = function (response) { self.isWaiting = false; self.trackingId = response.data; $('#confirmSaveSuccessMassFill').modal({ backdrop: 'static', keyboard: true }); }; /** * Go to check status page when click button check status in popup. */ self.goToCheckStatusPage = function() { $('#confirmSaveSuccessMassFill').modal("hide"); $('#confirmSaveSuccessMassFill').on('hidden.bs.modal', function () { $state.go(appConstants.CHECK_STATUS,{trackingId:self.trackingId}); }); }; /** * Get total record mass fill. */ self.getTotalRecordMassFill = function() { if(self.dataMassFillAllProduct.isMassFillAllProduct && self.dataMassFillAllProduct.excludedAlerts != null && self.dataMassFillAllProduct.excludedAlerts != undefined){ var total = self.totalRecordCount; self.dataMassFillAllProduct.excludedAlerts.forEach(function(excludedWorkRequest){ var hasExist = false; self.workRequestMassFillList.forEach(function(workRequestMassFill){ if(excludedWorkRequest == workRequestMassFill.productId){ hasExist = true; } }); if(!hasExist){ total = total - 1; } }); return total; }else{ return self.workRequestMassFillList.length; } }; /** * Get title for FufillmentProgram select dropdown. */ self.getTitleForFulfillmentProgram = function() { var fulfillmentChannelNames = []; _.forEach(self.fulfillmentProgramsSelected, function (o) { fulfillmentChannelNames.push(SPACE_STRING + o.description.trim()); }); return fulfillmentChannelNames.join(); }; /** * Compare the date is greater than date 2 or not. * * @param date1 the date. * @param date2 the date. * @returns {boolean} true if the date1 is greater than date 2 or false. */ self.isDate1GreaterThanDate2 = function (date1, date2) { if ((new Date(self.convertDateToStringWithYYYYMMDD(date1)).getTime() > new Date(self.convertDateToStringWithYYYYMMDD(date2)).getTime())) { return true; } return false; }; /** * Convert the date to string with format: yyyy-MM-dd. * @param date the date object. * @returns {*} string */ self.convertDateToStringWithYYYYMMDD = function (date) { return $filter('date')(date, 'yyyy-MM-dd'); }; /** * Show modal when click button assign task to BDM. */ self.assignToBDM = function(){ self.isAssignToBDM = true; self.isAssignToEBM = false; if(self.allWorkRequests || (self.selectedWorkRequests != null && self.selectedWorkRequests.length > 0)){ self.confirmAssignTaskContent = "Are you sure you want to assign to BDM the selected Product?"; $('#confirmAssignTask').modal({ backdrop: 'static', keyboard: true }); }else { self.confirmSelectProductsModalContent = "Please select at least one Product to assign to BDM"; $('#confirmSelectProductsModal').modal({ backdrop: 'static', keyboard: true }); } }; /** * Do assign task to BDM. */ self.doAssignToBDM = function(){ var excludedAlerts = []; self.excludedWorkRequests.forEach(function(item){ excludedAlerts.push(item.productId); }); var massUpdateTaskRequest = { isSelectAll : self.allWorkRequests, excludedAlerts : excludedAlerts, selectedCandidateWorkRequests : self.selectedWorkRequests, trackingId: self.task.alertKey.trim(), assigneeId: self.assignedTo.uid, alertId: self.task.alertID } ecommerceTaskApi.assignToBDM(massUpdateTaskRequest,self.assignToBDMSuccess, self.handleError); }; /** * Handle data when assign task TO BDM success. */ self.assignToBDMSuccess = function(response) { self.refreshTable(1,true); self.confirmAssignTaskSuccessContent = "The product(s) have been assigned to the BDM(s) successfully."; $('#confirmAssignTaskSuccess').modal({ backdrop: 'static', keyboard: true }); }; /** * Show modal when click button assign task to EBM. */ self.assignToEBM = function(){ self.isAssignToBDM = false; self.isAssignToEBM = true; if(self.allWorkRequests || (self.selectedWorkRequests != null && self.selectedWorkRequests.length > 0)){ self.confirmAssignTaskContent = "Are you sure you want to assign to eBM the selected Product?"; $('#confirmAssignTask').modal({ backdrop: 'static', keyboard: true }); }else { self.confirmSelectProductsModalContent = "Please select at least one Product to assign to eBM"; $('#confirmSelectProductsModal').modal({ backdrop: 'static', keyboard: true }); } }; /** * Do assign task to EBM. */ self.doAssignToEBM = function(){ var excludedAlerts = []; self.excludedWorkRequests.forEach(function(item){ excludedAlerts.push(item.productId); }); var massUpdateTaskRequest = { isSelectAll : self.allWorkRequests, excludedAlerts : excludedAlerts, selectedCandidateWorkRequests : self.selectedWorkRequests, trackingId: self.task.alertKey.trim(), assigneeId: self.assignedTo.uid, alertId: self.task.alertID, role: "BDM" } ecommerceTaskApi.assignToEBM(massUpdateTaskRequest,self.assignToEBMSuccess, self.handleError); }; /** * Handle data when assign task to EBM success. */ self.assignToEBMSuccess = function(response) { self.refreshTable(1,true); self.confirmAssignTaskSuccessContent = "The product(s) have been assigned to the eBM(s) successfully."; $('#confirmAssignTaskSuccess').modal({ backdrop: 'static', keyboard: true }); }; /** * Handle reset button. */ self.onReset = function(){ if(self.task){ self.fetchProductsAssignee(self.task); } self.assignedTo = self.currentUser; self.resetFilterShowOnSite(); self.resetFilterFulfillmentChannel(true); self.refreshTable(1,true); }; /** * Check data before publish. */ self.publish = function () { if(self.allWorkRequests || (self.selectedWorkRequests !== null && self.selectedWorkRequests.length > 0)){ $('#confirmatioPublishProductModal').modal("show"); }else { self.confirmSelectProductsModalContent = "Please select at least one product to Publish"; $('#confirmSelectProductsModal').modal({backdrop: 'static', keyboard: true}); } }; /** * Publish product. */ self.publishProduct = function () { var excludedAlerts = []; self.excludedWorkRequests.forEach(function (item) { excludedAlerts.push(item.productId); }); var massUpdateTaskRequest = { isSelectAll: self.allWorkRequests, selectedCandidateWorkRequests: self.selectedWorkRequests, alertType: 'MYTSK', trackingId: self.task.alertKey.trim(), effectiveDate: self.dataMassFillAllProduct.effectiveDate, expirationDate: self.dataMassFillAllProduct.expirationDate, assigneeId: self.assignedTo.uid, attributes: _.trim(self.dataMassFillAllProduct.attributes) === '' ? null : _.trim(self.dataMassFillAllProduct.attributes).split(","), excludedAlerts: excludedAlerts, actionType: ACTION_TYPE_PUBLISH, alertId:$stateParams.taskId }; self.isWaiting = true; ecommerceTaskApi.publishProduct(massUpdateTaskRequest, function (response) { self.isWaiting = false; self.trackingId = response.data; $('#confirmSaveSuccessMassFill').modal("show"); }, self.handleError) }; /** * Return to list ecommerce task in home page. */ self.returnToEcommerceTaskList = function () { taskService.setReturnToEcommerceTaskList(true); $state.go(appConstants.HOME_STATE); } /** * Handles applying filter change for Fulfillment Channel. Eventually tiggeres reloading of data table based on user selection. */ self.applyFilteFulfillmentChannel = function() { self.selectedSalesChannelsFilter = angular.copy(self.salesChannelsFilter); var selectedSalesChannels = _.pluck(_.filter(self.selectedSalesChannelsFilter, function(o){ return o.checked == true;}),'id'); if(selectedSalesChannels.length > 0){ self.refreshTable(1, true); $('#fulfillmentChannelFilter').removeClass("open"); }else { self.isError = true; self.message = EMPTY_SALES_CHANNEL_FILTER_MESSAGE ; } }; /** * Resets Fulfillment Channel selections to initial state. */ self.resetFilterFulfillmentChannel = function(resetAllData) { self.salesChannelsFilter = angular.copy(self.salesChannelsFilterOrg); self.allSalesChannels = true; if(resetAllData) self.selectedSalesChannelsFilter = angular.copy(self.salesChannelsFilterOrg); }; /** * Cancels users selection. Changes displayed options state to previously saved state. */ self.cancelFilterFulfillmentChannel = function() { self.salesChannelsFilter = angular.copy(self.selectedSalesChannelsFilter); self.setSelectAllSalesChannels(); $('#fulfillmentChannelFilter').removeClass("open"); }; /** * Used to build list Sales Channel code/numbers based on the user selection. If user havent made any selection, * it returns null instead of sending all the default-selected attributes code. This is done to save query fetch performance. */ self.getSelectedSalesChannelsFilter = function() { var selectedSalesChannels = _.pluck(_.filter(self.selectedSalesChannelsFilter, function(o){ return o.checked == true;}),'id'); return (selectedSalesChannels.length != self.salesChannelsFilterOrg.length) ? selectedSalesChannels.join(): null; }; /** * Set flag select all Sales Channel or not when user selected Sales Channel */ self.setSelectAllSalesChannels = function () { var selectedSalesChannels = _.filter(self.salesChannelsFilter, function (o) { return o.checked == true; }); self.allSalesChannels = selectedSalesChannels.length == self.salesChannelsFilterOrg.length ? true : false; } /** * Set check/uncheck Sales Channel when user select all/unselect all Sales Channel */ self.setSelectedForAllSalesChannels = function () { _.map(self.salesChannelsFilter, function (o) { return o.checked = self.allSalesChannels; }); } } })();
import * as fc from 'fast-check'; const alphaNumericString = fc.asciiString({ minLength: 1 }).map((str) => str.replace(/[^a-zA-Z0-9]/g, 'a')); export default alphaNumericString;
'use strict'; const pkg = require( '../../package' ); const _Config=require('../../utils/config')( pkg.name ).load(require('../../config/app'),{}); const Config = require( '../../utils/config' )( pkg.name ).current; const mongojs = require( '../../utils/mongojs' ); const collection = mongojs( Config().services.db.mongodb.uri, [ 'specimens' ] ).specimens; const newFormat = { "photos": { "main": "", "all": [] }, "physical_dimensions": { "weight": null, "length": null, "width": null, "height": null, "main_crystal": null }, "species": { "main": "", "additional": [] }, "discovery_location": { "stope": "", "level": "", "mine": "", "district": "", "state": "", "country": "" }, "analysis": { "analyzed": false, "by": "", "method": "" }, "acquired": { "date": null, "paid": null, "from": "", "where": "" }, "states": { "old_label": false, "repair": false, "story": false, "figured": false }, "storage_location": { "exhibit": false, "inside": false, "outside": false, "loan": false, "details": "" }, "geology": { "metamorphic": false, "pegmatite": false, "porphyry": false, "crd_skarn": false, "epithermal_vein": false, "volcanic_related": false, "exhalite": false, "mvt": false, "evaporite": false, "other": "" }, "exhibit_history": [], "features": { "twinned": false, "pseudomorph": false, "inclusions": false, "photosensitive": false }, "fluorescence": { "sw": false, "sw_details": "", "lw": false, "lw_details": "" }, "quality": { "exceptional": false, "exhibit": false, "locality": false, "study": false }, "locality": { "type_locality": false, "self_collected": false, "when": null }, "photographed": { "photographed": false, "by": "", "photo_file_number": "", "files": [] }, "provenance": { "old_labels": false, "prior_labels": false, "former_owners": [], "prior_catalog_number": null, "label": false, "label_files": [], "miguel_romero": false, "miguel_romero_number": null }, "comments": "", "story": "", "figured": "", "repair_history": "", "analysis_history": "", "specimen_location": "", "documents": [] }; console.log( '[!] Updating specimen objects.' ); collection.find( {}, function ( err, result ) { if ( err ) { console.error( err ); process.exit( 1 ); } const next = function ( files, i, done ) { if ( i >= files.length ) { done(); } if ( i % 100 === 0 ) { console.log( '\t[!] ' + i + ' of ' + files.length + '.' ); } update( files[ i ], function ( err ) { if ( err ) { return done( err ); } next( files, ++i, done ); } ); }; next( result, 0, function ( err ) { if ( err ) { console.error( err ); process.exit( 1 ); } console.log( '[!] Updated ' + result.length + ' files.' ); console.log( '[ALL DONE!!!]' ); process.exit( 0 ); } ); } ); function update( specimen, done ) { collection.update( { _id: specimen._id }, Object.assign( {}, newFormat, specimen ), {}, function ( err ) { return done( err ); } ); }
var DoublyLinkedList = function() { var list = {}; var Node = function(value) { node = {}; node.value = value; return node; } list.head = null; list.tail = null; list.addToHead = function(value) { var newNode = Node(value); newNode.previous = null; if (list.head === null) { list.head = newNode; list.tail = newNode; } else { list.head.previous = newNode; newNode.next = list.head; list.head = newNode; } } list.addToTail = function(value) { var newNode = Node(value); newNode.next = null; //if there are no values in the list if (list.head === null) { //set head and tail to value list.head = newNode; list.tail = newNode; //else } else { //set last node to point to value list.tail.next = newNode; //set new node to point to previous node newNode.previous = list.tail; //and set tail to point to value list.tail = newNode; } } list.removeHead = function() { var previousHead = list.head; if (list.head.next) { list.head = list.head.next; } list.head.previous = null; return previousHead.value; } list.removeTail = function() { var previousTail = list.tail; if (list.tail.previous) { list.tail = list.tail.previous; } list.tail.next = null; return previousTail.value; } list.contains = function(value) { var found = false; var check = function(node, value) { if (node.value === value) { found = true; } else if (node.next !== null) { check(node.next, value); } return found; } return check(list.head, value); } return list; }
(function ($p) { var routePrefix = $p.baseUrl + '/venues'; $p.venueService = { getByVenueId: function (venueId) { return $p.httpGet(routePrefix + '/' + venueId); } }; })($paramount)
define(['views/index', 'views/register', 'views/login', 'views/forgotpassword', 'views/profile', 'views/contact/contacts', 'views/contact/addcontact','views/invitation/invitations', 'models/Account', 'models/PostsCollection', 'models/ContactCollection','models/InvitationCollection','models/ProfileHeader'], function(IndexView, RegisterView, LoginView, ForgotPasswordView, ProfileView, ContactsView, AddContactView, InvitationView, Account, PostsCollection, ContactCollection,InvitationCollection,ProfileModel) { var SocialRouter = Backbone.Router.extend({ currentView: null, socketEvents: _.extend({}, Backbone.Events), routes: { 'addcontact': 'addcontact', 'invitation/:id' : 'invitation', 'index/:id': 'index', 'login': 'login', 'register': 'register', 'forgotpassword': 'forgotpassword', 'profile/:id': 'profile', 'contacts/:id': 'contacts' }, changeView: function(view) { if ( null != this.currentView ) { this.currentView.undelegateEvents(); } this.currentView = view; this.currentView.render(); }, index: function(id) { var contactId = id ? id : 'me'; if(contactId!=undefined){ $('#loginForm').hide(); $('#main').show(); var postCollection = new PostsCollection(); postCollection.url = '/accounts/'+contactId+'/posts'; this.changeView(new IndexView({ collection: postCollection , socketEvents: this.socketEvents })); postCollection.fetch(); } }, addcontact: function() { this.changeView(new AddContactView()); }, login: function() { this.changeView(new LoginView( { socketEvents:this.socketEvents })); }, forgotpassword: function() { this.changeView(new ForgotPasswordView()); }, register: function() { this.changeView(new RegisterView()); }, profile: function(id) { var profile = new ProfileModel(); profile.url = '/accounts/'+id+'/getinfoheader'; this.changeView(new ProfileView({model:profile, socketEvents:this.socketEvents})); profile.fetch(); }, contacts: function(id) { var contactId = id ? id : 'me'; var contactsCollection = new ContactCollection(); contactsCollection.url = '/accounts/' + id + '/contacts'; this.changeView(new ContactsView({ collection: contactsCollection })); contactsCollection.fetch(); }, invitation: function(id){ var contactId = id ? id : 'me'; var invitationCollection = new InvitationCollection(); invitationCollection.url = '/accounts/' + contactId + '/invitations'; this.changeView(new InvitationView({ accountId: 0, collection: invitationCollection, socketEvents:this.socketEvents })); invitationCollection.fetch(); } }); return new SocialRouter(); });
const geoJsonSimple = { "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { "gid": "20", "name": "gfbfgbfgb", "videosrc": "xvbxcvb", "addtime": "2021-01-13 12:50:33", "id": "6", "calarea": "0" }, "geometry": { "type": "Point", "coordinates": [110.797727, 41.911865] } }, { "type": "Feature", "properties": { "gid": "19", "name": "dfgdfg", "videosrc": "dfgxzcvdf", "addtime": "2021-01-13 12:50:23", "id": "5", "calarea": "0" }, "geometry": { "type": "Point", "coordinates": [111.25766, 41.422131] } }, { "type": "Feature", "properties": { "gid": "17", "name": "testx", "videosrc": "adfasdf", "addtime": "2021-01-13 12:46:56", "id": "3", "calarea": "0" }, "geometry": { "type": "Point", "coordinates": [110.383788, 42.438739] } }, { "type": "Feature", "properties": { "gid": "16", "name": "test", "videosrc": "asdfasdf", "addtime": "2021-01-13 12:31:05", "id": "2", "calarea": "0" }, "geometry": { "type": "Point", "coordinates": [110.282603, 41.774292] } }] }; const wktSimple="POINT(110.282603 41.774292)"; class pointWkt { value constructor(string) { this.value=string; } get value(){ return this.value; } toGeoJSON() { } } pointWkt.fromGeoJSON=function(GeoJSON) { let coordinate=NaN; const handDict={ "FeatureCollection":a=>a.features[0].geometry.coordinates, "Feature":a=>a.geometry.coordinates, "Point":a=>a.coordinates, } GeoJSON= GeoJSON instanceof Object?GeoJSON:JSON.parse(GeoJSON); coordinate=handDict[GeoJSON.type](GeoJSON); this.value=`POINT(${coordinate[0]} ${coordinate[1]})`; return this; } let a=pointWkt.fromGeoJSON(geoJsonSimple); console.log(a.value)
$('.multiple-items').slick({ infinite: true, slidesToShow: 3, speed: 300, slidesToScroll: 3, autoplaySpeed :300, draggable: true, autoplay: true, /* this is the new line */ autoplaySpeed: 2000, touchThreshold: 1000, dots: false, prevArrow: false, nextArrow: false }); $(".page").hide(); $('.page').click(function() { $('body,html').animate({ scrollTop: 0 }) }); $(window).scroll(function () { var e = $(window).scrollTop(); if (e > 300) { $(".page").show(); } else { $(".page").hide(); } }); $('body .d-product-img-more').on('click', function(event) { $('.d-product-img-more').css('border', 'none'); $(this).css('border', '2px solid var(--primary)'); $('.img_pro--main').attr('src', $(this).attr('src')); }); // $('body .d-product-img-more').on('click', function(event) { // }); // var elements = document.getElementsByClassName("d-product-img-more"); // var myFunction = function() { // var newSrc = this.getAttribute("src"); // this.style.border = "2px solid var(--primary)"; // document.getElementsByClassName("d-product-main-img")[0].setAttribute('src', newSrc); // }; // for (var i = 0; i < elements.length; i++) { // elements[i].addEventListener('click', myFunction, false); // } $('.d-product-img-more').eq(0).click();
// The config for the webserver module.exports = { // [string] The URL the webserver is hosted on (e.g. https://webhooks.example.com/) // The base MUST END WITH A SLASH base: "" };
(function(){ 'use strict'; angular .module('everycent.setup.institutions') .factory('InstitutionsService', InstitutionsService); InstitutionsService.$inject = ['$http', 'Restangular']; function InstitutionsService($http, Restangular){ var service = { getInstitutions: getInstitutions, addInstitution: addInstitution }; var baseAll = Restangular.all('institutions'); return service; function getInstitutions(){ return baseAll.getList(); } function addInstitution(institution){ return baseAll.post(institution); } } })();
import React from 'react' import './login-btn.sass' export default class LoginBtn extends React.Component { render() { return( <button type="button" class="login-btn" onClick={ this.props.loggedIn ? this.props.logout : this.props._toggleSignInBox } > { this.props.loggedIn ? 'Log Out' : 'Log In' } </button> ) } }
import { call, put, takeEvery } from 'redux-saga/effects'; import HttpHelper from '../../utils/http-helper'; import { recentActivityUrl } from '../../utils/urls'; import { RECENT_ACTIVITY_REQUEST } from './dashboard-constants'; import { recentActivitySuccess, recentActivityFailure, } from './recent-activity-action'; const { getRequest } = new HttpHelper(); export function* recentActivity(action) { try { const response = yield call(getRequest, { url: recentActivityUrl(action.urlParams), }); yield put(recentActivitySuccess(response.data)); } catch (error) { yield put(recentActivityFailure()); } } export function* watchRecentActivity() { yield takeEvery(RECENT_ACTIVITY_REQUEST, recentActivity); }
export default class UpdateMenuAddOnUseCase { constructor({database, logger, config}) { this.config = config; this.menuAddOnDao = database.menuAddOnDao(); this.logger = logger; } async execute(param) { return await this.menuAddOnDao.updateMenuAddOn(param.id, param.data) } }
/** * 对两个不定长的数组进行相加 * 给 [1,2,3] [4,2] 返回 [1,6,5] */ function add(arr1, arr2) { const arr = arr1.length > arr2.length ? arr2 : arr1; const arr3 = arr1.length > arr2.length ? arr1 : arr2; const result = []; while (arr.length) { const a = arr.pop(); const b = arr3.pop(); const res = a + b; result.unshift(res); } return arr3.concat(result); } console.log(add([1, 2, 3, 4], [7, 9, 1])); /** * [ { id: 1, pid: 0, name: 'body' }, { id: 2, pid: 1, name: 'title' }, { id: 3, pid: 2, name: 'div' }, { id: 4, pid: 0, name: 'div' }, { id: 9, pid: 4, name: 'div' } ] * 扁平化数组转树结构 */ function toTree(list) { const map = {}; const result = []; list.forEach((item) => { if (!map[item.id]) { map[item.id] = item; } }); list.forEach((item) => { const p = map[item.pid]; if (p) { if (!p.children) p.children = []; p.children.push(item); } else { result.push(item); } }); return result; } toTree([ { id: 1, pid: 0, name: 'body' }, { id: 2, pid: 1, name: 'title' }, { id: 3, pid: 2, name: 'div' }, { id: 4, pid: 0, name: 'div' }, { id: 9, pid: 4, name: 'div' } ]);
function solve(input){ let heroes = []; for (let i = 0; i < input.length; i++) { let tokens = input[i].split(' / '); let heroName = tokens[0]; let level = Number(tokens[1]); let items = tokens.slice(2)[0].split(', '); heroes.push({Hero: heroName, level, items}); } heroes.sort((a, b) => a.level - b.level); for (const hero of heroes) { let entries = Object.entries(hero); let items = entries[2][1].sort((a,b) => a.localeCompare(b)); console.log(`${entries[0][0]}: ${entries[0][1]}`); console.log(`${entries[1][0]} => ${entries[1][1]}`); console.log(`${entries[2][0]} => ${items.join(', ')}`); } } solve([ "Isacc / 25 / Apple, GravityGun", "Derek / 12 / BarrelVest, DestructionSword", "Hes / 1 / Desolator, Sentinel, Antara" ]);
// 'data-height': 400, // 'data-theme-id': 0, // 'data-default-tab': 'result', // 'data-slug-hash': 'amgpKB', // 'data-pen-title': 'Codepen', // 'data-user': 'robert77', // 'placeholder': 'Unable to load Codepen', // 'data-border' : '', // 'data-border-color': '', // 'data-link-logo-color': '' // data-tab-bar-color // data-tab-link-color // data-active-tab-color // data-active-link-color // data-embed-version
/* global define, Promise */ 'use strict'; define([ 'lodash', 'lru-cache', 'immutable', 'url-parse', 'rethinkdb', '-/logger/index.js' ], (_, lru, { Map }, parse, r, logger) => { let feeds = Map({}); const max = !_.isNaN(parseInt(process.env.MVP_STORE_LRU_MAXSIZE, 10)) ? parseInt(process.env.MVP_STORE_LRU_MAXSIZE, 10) : 500; const maxAge = !_.isNaN(parseInt(process.env.MVP_STORE_LRU_MAXAGE, 10)) ? parseInt(process.env.MVP_STORE_LRU_MAXAGE, 10) : 1000 * 60 * 60; const cache = lru({ max, maxAge, dispose(key) { (feeds.get(key) || { close: _.noop }).close(); }, noDisposeOnSet: true }); let conn; const plugin = { async connect(options) { const settings = _.defaultsDeep(options, { storeUri: 'rethinkdb://admin@127.0.0.1:28015' }); const defaults = { protocol: 'rethinkdb', hostname: '127.0.0.1', port: 28015, username: 'admin' }; const { protocol, hostname: host, port, username: user, password } = _.defaultsDeep(parse(settings.storeUri), defaults); if (protocol !== 'rethinkdb:') { throw new Error('Unsupported store protocol'); } logger.debug('store setings:', settings); conn = await r.connect({ host, port, user, password }); return { success: true }; }, browse({ type, where, skip, limit }) { let q = r.table(type); if (_.isObject(where)) { let tmp = q; _.each(_.keys(where), key => { tmp = q.getAll(where[key]); }); q = tmp; } if (_.isInteger(skip)) { q = q.skip(skip); } if (_.isInteger(limit)) { q = q.limit(limit); } return q.run(conn); }, read({ type, id }) { const key = `${type}/${id}`; const value = cache.get(key); return value ? Promise.resolve(value) : new Promise((resolve, reject) => { r.table(type) .get(id) .changes({ includeInitial: true, squash: true }) .run(conn, (err, feed) => { if (err) { return reject(err); } feeds = feeds.set(key, feed); let unresolved = true; return feed.each((eachErr, row) => { const { new_val: v } = row || {}; // eslint-disable-line camelcase cache.set(key, v); if (unresolved) { unresolved = false; resolve(v); } }); }); }); }, edit({ type, object }) { return r.table(type) .get(object.id) .replace(doc => ( (object.version > (doc.version || 0)) ? object : doc )) .run(conn); }, add({ type, objects }) { r.table(type) .insert(objects) .run(conn); }, delete({ type, selection }) { return r.table(type) .getAll(r.args(selection)) .delete() .run(conn); } }; return plugin; });
X.define('modules.credit.creditDetail', ['model.creditModel', 'data.currencyEntireData', 'data.countryData'], function(model, currencyData, countryData) { var view = X.view.newOne({ el: $(".xbn-content"), url: X.config.credit.tpl.creditDetail }) var ctrl = X.controller.newOne({ view: view }) var events = { changeValue: function(data) { $('[data-control-type]', view.el).each(function(i, item) { var ele = $(item) switch (ele.attr('data-control-type')) { case 'ComboBox': var name = ele.attr('name'), source = eval(name + 'Data'), index = parseInt(data[name]) ele.html(source.source[index].value) break case 'WebUpload': //var file = data[ele.attr('name')] //ele.html('<span>'+ file.filename +'</span>') var file = data[ele.attr('name')], newFile = { filename: file.filename, href: X.config.PATH_FILE.path.rootUploadUrl + '?fileType=1&filePath='+ file.filePath +'&fileName='+ file.filename } ele.loadTemplate($('#creditDetailFiles', view.el), [newFile]) break } }) this.addProducts(data.productInfoList) }, addProducts: function(data) { var html = '' for (var i in data) { var pro = data[i] html += [ '<div class="'+ (i % 2? 'even-row': '') +'">', '<span>'+ (parseInt(i) + 1)+'</span>', '<span>'+ pro.nameCn +'</span>', //'<span class="deleteProduct curp">删除</span>', '</div>' ].join('') } $('#productsHtmlList').html(html) } } ctrl.load = function(para) { model.getCredit(para.id, function(result) { var data = result.data[0] view.render(data, function() { if (!model.creditStatus) $('.original-input', view.el).addClass('none') events.changeValue(data) }) }) } return ctrl })
// @flow import React, { Component } from 'react'; type APropsType = {}; class A extends Component<APropsType> { render() { return <h2>A</h2>; } } export default A;
const express= require ("express"); const router= express.Router(); const registerController= require ("../controllers/registerController.js") router.get ("/", registerController.entrarRegister); module.exports = router;
import React from 'react' import { StyleSheet } from 'quantum' const styles = StyleSheet.create({ self: { display: 'flex', flexDirection: 'row', width: '100%', '& strong': { color: '#000000', flexBasis: '40px', display: 'inline-flex', flexShrink: 0, }, '& span': { display: 'inline-flex', flexShrink: 1, }, }, }) const Title = ({ active, index, children }) => ( <span className={styles()}> <strong> {active}.{index + 1} </strong> <span> {children} </span> </span> ) export default Title
import { lang, MTURK } from '../config/main' import { getUserId, getTurkUniqueId } from '../lib/utils' import { baseStimulus } from '../lib/markup/stimuli' const userId = () => { if (MTURK) { return { type: 'html_keyboard_response', stimulus: baseStimulus(`<h1>${lang.userid.set}</h1>`, true), response_ends_trial: false, trial_duration: 800, on_finish: (data) => { const uniqueId = getTurkUniqueId() console.log(uniqueId) } } } else { const ipcRenderer = window.require('electron').ipcRenderer; const envPatientId = ipcRenderer.sendSync('syncPatientId') return { type: 'survey_text', questions: [{ prompt: baseStimulus(`<h1>${lang.userid.set}</h1>`, true), value: envPatientId }], on_finish: (data) => { getUserId(data) } } } } export default userId
'use strict' class DeviceFeed { get rules () { return { // validation rules data: 'required|databodyExists' } } get validateAll () { return true } get messages () { return { 'data.required': 'You must provide a data array.', 'data.databodyExists': 'You must provide a valid data properties.' } } async fails (errorMessages) { return this.ctx.response.status(422).send(errorMessages) } } module.exports = DeviceFeed
import { isArray } from 'lodash' import {buildUrl} from '../url-utils' export const transformFromApi = (data, transformFunc) => { let ret = data if (data) { if (isArray(data.content)) { data = data.content } // cette partie supporte deux types de retour, soit un retour sous forme d'array d'entités, et le format object // contenant une propriété "content" qui est un array d'entité. Dans les deux cas, on garde la référence obtenue // de l'api car elle n'est certainement pas référencée dans le state. if (isArray(data)) { for (let i = 0; i < data.length; i++) { data[i] = transformFunc(data[i]) } } else { ret = transformFunc(data) } return ret } } // fromApiTransformer: fonction qui modifie l'instance reçue de l'api pour ajuster sa structure pour le reducer // toApiTransformer : fonction qui transforme la donnée prise du state pour le serveur. Doit retourner un NOUVEL objet export default class RestService { constructor (route, apiClient, fromApiTransformer = null, toApiTransformer = null) { this.route = route this.apiClient = apiClient this.fromApiTransformer = fromApiTransformer this.toApiTransformer = toApiTransformer this.get = this.get.bind(this) this.save = this.save.bind(this) this.delete = this.delete.bind(this) this.archive = this.archive.bind(this) this.restore = this.restore.bind(this) this.patch = this.patch.bind(this) this.list = this.list.bind(this) } get (id) { const transform = this.fromApiTransformer return this.apiClient.get(this.route, id) .then((data) => { const transformedData = transform ? transformFromApi(data, transform) : data return transformedData }) } list (filtersMap) { const transform = this.fromApiTransformer const route = buildUrl(this.route, filtersMap) return this.apiClient.get(route) .then((data) => { const transformedData = transform ? transformFromApi(data, transform) : data return transformedData }) } save (entity, requestHeaders) { const id = entity.id const transformedData = this.toApiTransformer ? this.toApiTransformer(entity) : entity const transform = this.fromApiTransformer let promise if (id) { promise = this.apiClient.put(this.route, transformedData, id, requestHeaders) } else { promise = this.apiClient.post(this.route, transformedData, requestHeaders) } return promise.then((data) => { const transformedData = transform ? transformFromApi(data, transform) : data return transformedData }) } patch (entity, id, requestHeaders) { const transform = this.fromApiTransformer return this.apiClient.patch(this.route, entity, id, requestHeaders) .then((data) => { const transformedData = transform ? transformFromApi(data, transform) : data return transformedData }) } delete (ids, requestHeaders) { return this.apiClient.delete(this.route, ids, requestHeaders) } archive (ids, requestHeaders) { const url = this.route + '/archive' return this.apiClient.post(url, ids, requestHeaders) } restore (ids, requestHeaders) { const url = this.route + '/restore' return this.apiClient.post(url, ids, requestHeaders) } }
import Component from '@glimmer/component'; import debugLogger from 'ember-debug-logger'; import { action } from '@ember/object'; import { htmlSafe } from '@ember/template'; import { tracked } from '@glimmer/tracking'; export default class TwyrTabsTabComponent extends Component { // #region Private Attributes debug = debugLogger('twyr-tabs-tab'); _element = null; // #endregion // #region Tracked Attributes @tracked left = 0; @tracked width = 0; // #endregion // #region Constructor constructor() { super(...arguments); this.debug(`constructor`); } // #endregion // #region Lifecycle Hooks @action didInsert(element) { this.debug(`didInsert`); this._element = element; if(this.args.registerWithParent && (typeof this.args.registerWithParent === 'function')) this.args.registerWithParent(this, true); } willDestroy() { this.debug(`willDestroy`); if(this.args.registerWithParent && (typeof this.args.registerWithParent === 'function')) this.args.registerWithParent(this, false); super.willDestroy(...arguments); } // #endregion // #region DOM Event Handlers @action handleClick(event) { if(!this._element || this._element.hasAttribute('disabled')) { this.debug(`handleClick::disabled`); return; } if(this.args.onClick && (typeof this.args.onClick === 'function')) { this.debug(`handleClick::onClick::event: `, event); this.args.onClick(event); } if(this.isSelected) return; if(this.args.onSelect && (typeof this.args.onSelect === 'function')) { this.debug(`handleClick::onSelect: `, this); this.args.onSelect(this); } } // #endregion // #region Public Methods called only by the parent _updateDimensions() { // this is the true current width // it is used to calculate the ink bar position & pagination offset this.left = this._element.offsetLeft; this.width = this._element.offsetWidth; } // #endregion // #region Computed Properties get computedStyle() { if(!this.args.href) return undefined; return htmlSafe('text-decoration:none; border:none;'); } get isHref() { if(this.args.href && this._element && !this._element.hasAttribute('disabled')) return this.args.href; return undefined; } get isSelected() { this.debug(`isSelected? ${(this.args.value === this.args.selected)}`); return (this.args.value === this.args.selected); } // #endregion }
import gen from '../helpers/idGenerator' export default { Query: { categories: (root,args,{models})=>{ return models.Category.findAll() } }, Category:{ news: (category)=>{ return category.getNews() } }, Mutation: { addCategory: async (root,args,{models})=>{ const newCategory = await models.Category.create({id:gen(),name:args.name}) return newCategory } }, };
class UserLst { constructor(total, userLst) { this.total = total; this.userLst = userLst; } applyData(json) { Object.assign(this, json); } } module.exports = UserLst;
// Values and Sum var testArr = [6, 3, 5, 1, 2, 4]; var sum = 0; for (var i = 0; i < testArr.length; i++) { console.log("Num: " + testArr[i]); sum = sum + testArr[i]; console.log("Sum: " + sum); } // Value and Position var testArr = [6, 3, 5, 1, 2, 4]; for (var i = 0; i < testArr.length; i++) { console.log(i * testArr[i]); }
// Build a function that takes two parameters (two binary trees data structures) and validate they are twins // If they are twins then return true, else return false const sameTree = (tree1, tree2) => { // Code here } module.exports = sameTree
import React from 'react' import './Sidebar.css' // React icons import { AiFillHome } from 'react-icons/ai'; import { FaBox } from 'react-icons/fa'; import { GiMagnifyingGlass } from 'react-icons/gi'; import { MdPermContactCalendar } from 'react-icons/md'; import { FaUsers } from 'react-icons/fa'; import { AiOutlineTransaction } from 'react-icons/ai'; import { HiOutlineDocumentReport } from 'react-icons/hi'; import { RiArrowDropDownLine } from 'react-icons/ri'; export default function Sidebar() { return ( <div className='sidebar' > <div className='sidebarWrapper'> <div className='sidebarMenu'> <h3 className='sidebarTitle'>Dashboard</h3> <ul className='sidebarList'> <li className='sidebarListItem'> <AiFillHome style={{ marginRight: '5px' }}/> Home <RiArrowDropDownLine style={{ marginLeft: '111px' }} /> </li> <li className='sidebarListItem'> <FaBox style={{ marginRight: '5px' }}/> Products <RiArrowDropDownLine style={{ marginLeft: '91px' }} /> </li> <li className='sidebarListItem'> <GiMagnifyingGlass style={{ marginRight: '5px' }}/> Explore <RiArrowDropDownLine style={{ marginLeft: '100px' }} /> </li> <li className='sidebarListItem'> <MdPermContactCalendar style={{ marginRight: '5px' }}/> Contact <RiArrowDropDownLine style={{ marginLeft: '100px' }} /> </li> </ul> <h3 className="sidebarTitle">Quick Menu</h3> <ul className="sidebarList"> <li className="sidebarListItem"> <FaUsers style={{ marginRight: '5px' }}/> Users <RiArrowDropDownLine style={{ marginLeft: '114px' }} /> </li> <li className="sidebarListItem"> <AiOutlineTransaction style={{ marginRight: '5px' }}/> Transactions <RiArrowDropDownLine style={{ marginLeft: '65px' }} /> </li> <li className="sidebarListItem"> <HiOutlineDocumentReport style={{ marginRight: '5px'}}/> Reports <li> <RiArrowDropDownLine style={{ marginLeft: '92px' }}/> </li> </li> </ul> </div> </div> </div> ) }
module.exports = { jwtSecret: process.env.JWT_SECRET || '27ddee8d-6c5a-4dae-ba1d-b91bfe67fcb9' };
const yargs = require('yargs') const notes = require('./utilitis.js') const pieces = require('./mongodb.js') yargs.command({ command:'search', description:'Searching Subject', builder:{ search:{ describe: 'Searching on Web', demandOption:true, type:'string' } }, handler: function(argv){ notes.search(argv.search) } }) yargs.command({ command:'write', description:'Searching Subject', builder:{ write:{ describe: 'Searching on Web', demandOption:true, type:'string' } }, handler: function(argv){ pieces.writing(argv.write) } }) yargs.parse()
import {Component} from "react"; import { Card, Col, Form, Row} from "react-bootstrap"; class Payment extends Component{ state = { amount : 1000 } componentDidMount = () => { if(sessionStorage.token) { this.setState({amount:0}); } } render() { return( <> <div style={{backgroundColor:'white' }}> <Card style={{ boxShadow: "0 1rem 2rem rgba(0,0,0,0.2)"}}> <Card.Header className="text-center" as="h5">Payment to Add Credits</Card.Header> <Card.Body> <div className='container'> <Form > <p></p> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Control type="number" placeholder="Amount to be Add to Account" name="university" value={this.state.amount} /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Control type="text" placeholder="Card Holder Name ex: john" name="university" /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Control type="text" placeholder="Card Number ex: 2222-2222-2222-2222" name="university" /> </Form.Group> <Row> <Col sm='7'> <Form.Control placeholder="Expire Date" type="date" name="firstname" /> </Col> <Col sm='5'> <Form.Control placeholder="CVC ex: 890" type="number" name="lastname" /> </Col> </Row> </Form> </div> </Card.Body> </Card> </div> </> ) } } export default Payment;
function capturar(){ //uso del archivo JS //console.log("Capturar") function Persona(nombre,edad){ this.nombre = nombre; this.edad = edad; } var nombreCapturar = document.getElementById("nombre").value; // testeamos la captura de lña primer variable // console.log(nombreCaptura); var edadCapturar = document.getElementById("edad").value; // hacemos uso de la variable local nuevoNombre //var nuevoNombre = new Persona(nombreCapturar, edadCapturar); // para que responda mi funcion externa pasamos la variable local a global quitando var nuevoNombre = new Persona(nombreCapturar, edadCapturar); // testeamos el contructor con el nuevo objeto console.log(nuevoNombre); // ejecutamos la función agregar(); } var nombresListados = []; function agregar () { nombresListados.push(nuevoNombre); console.log(nombresListados); document.getElementById("tabla").innerHTML += '<tbody><td>'+nuevoNombre.nombre+'</td><td>'+nuevoNombre.edad+'</td></tbody>'; };
//index.js //获取应用实例 const app = getApp() Page({ data: { count: 5, currentIndex: 0, items: [], animationData: {}, images: [ 'https://lg-7d7cxgzy-1251232205.cos.ap-shanghai.myqcloud.com/0.jpg', 'https://lg-7d7cxgzy-1251232205.cos.ap-shanghai.myqcloud.com/1.jpg' ] }, onShareAppMessage: function() { return { title: '一刀的小程序', path: '/pages/index/index' } }, //事件处理函数 bindViewTap: function() { wx.navigateTo({ url: '../logs/logs' }) }, getRandomImage: function() { const index = Math.floor(Math.random() * this.data.images.length) return this.data.images[index] }, getRandomLeft: function() { return Math.floor(Math.random() * 4) * 200 }, getRandomTop: function() { return Math.floor(Math.random() * 5) * 200 }, onLoad: function() { this.showAnimation(0) }, onShow: function() { }, showAnimation: function(index) { setTimeout(function() { let result = this.data.items.slice() const image = this.getRandomImage() const left = this.getRandomLeft() const top = this.getRandomTop() result.push({ image, left, top }); let animation = wx.createAnimation({ duration: 1000, timingFunction: 'ease' }) this.animation = animation animation.rotate(360).scale(1.1, 1.1).step() this.setData({ animationData: this.animation.export(), currentIndex: index, items: result }) if (index < this.data.count - 1) { this.showAnimation(index + 1) } }.bind(this), 1500) } })
/* eslint-disable quotes */ const { connect, disconnect } = require("mongoose"); const { dbUrl, options } = require("./options"); const connectToDB = () => connect(dbUrl, options); const disconnectDB = () => disconnect(); module.exports = { connectToDB, disconnectDB };
import React from "react" import ReactDOM from "react-dom" import App from "./App" import Child from "./Child" import { isChild } from "./utils" if (!isChild()) { ReactDOM.render(<App />, document.getElementById("root")) } else { ReactDOM.render(<Child />, document.getElementById("root")) }
import React, { Component } from 'react'; /** * @extends {Component} */ class Arrow extends Component { constructor(props) { super(props); } render() { return ( <defs> <marker id="end-arrow" viewBox="0 -5 10 10" strokeWidth="1px" refX="32" markerWidth="3.5" markerHeight="3.5" orient="auto"> <path xmlns="http://www.w3.org/2000/svg" d="M0,-5L10,0L0,5" /> </marker> <marker xmlns="http://www.w3.org/2000/svg" strokeWidth="1px" id="triangle" viewBox="0 0 10 10" refX="0" refY="5" markerUnits="strokeWidth" markerWidth="4" markerHeight="3" orient="auto"> <path d="M 0 0 L 10 5 L 0 10 z" /> </marker> </defs> ); } } export default Arrow; /** <marker id="mark-end-arrow" viewBox="0 -5 10 10" refX="7" markerWidth="3.5" markerHeight="3.5" orient="auto"> <path d="M0,-5 L10,0 L0,5"></path> </marker> <marker id="test-arrow" markerWidth="10" markerHeight="10" refX="0" refY="3" orient="auto" markerUnits="strokeWidth" viewBox="0 0 20 20"> <path d="M0,0 L0,6 L9,3 z" fill="#f00" /> </marker> <marker id="markerCircle" markerWidth="8" markerHeight="8" refX="5" refY="5"> <circle cx="5" cy="5" r="3" style={{stroke: "none", fill:"#000000"}}/> </marker> <marker id="markerArrow" strokeWidth="1px" markerWidth="17" markerHeight="13" refX="2" refY="6" orient="auto"> { //<path d="M2,2 L2,11 L10,6 L2,2" style={{fill: "#000000"}} /> } <path d="M2,2 L2,11 L10,6 L2,2" style={{fill: "#000000"}} /> </marker> */
var EvalEnv = require('../evalEnv.js'); var util = require('../util.js'); var assert = require('assert'); var HashDB = require('../hashDB.js'); var DummyKVS = require('../keyvalue.js'); describe('EvalEnv', function(){ var hashDB; var kvs; beforeEach(function() { kvs = new DummyKVS(); hashDB = new HashDB(kvs); }); describe('init(evaluator, args, cb(err, h0))', function(){ it('should return a hash to an object constructed by the evaluator\'s init() method', function(done){ var evaluators = {foo: { init: function(args, ctx) { ctx.ret({bar: args.bar, baz: 2}); } }}; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {bar: 3}, _.to('h0')); }, function(_) { assert(this.h0.$hash$, 'h0 must be a hash'); hashDB.unhash(this.h0, _.to('s0')); }, function(_) { assert.deepEqual(this.s0, {_type: 'foo', bar: 3, baz: 2}); _(); }, ], done)(); }); it('should pass the evaluator as the "this" of the called method', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val: this.def}); }, def: 100, }, }; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('s0')); }, function(_) { hashDB.unhash(this.s0, _.to('s0')); }, function(_) { assert.equal(this.s0.val, 100); _(); }, ], done)(); }); }); describe('apply(s1, patch, unapply, cb(err, s2, res, eff, conf))', function(){ it('should apply patch to s1 by invoking the evaluator\'s apply method, to retrieve s2 and res', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:0}); }, apply: function(s1, patch, unapply, ctx) { assert.equal(patch._type, 'bar'); var old = s1.val; s1.val += patch.amount; ctx.ret(s1, old); }, }}; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('h0')); }, function(_) { evalEnv.apply(this.h0, {_type: 'bar', amount: 2}, false, _.to('h1', 'res')); }, function(_) { hashDB.unhash(this.h1, _.to('s1')); }, function(_) { assert.deepEqual(this.s1, {_type: 'foo', val: 2}); assert.equal(this.res, 0); _();}, ], done)(); }); it('should use the patch evaluator if one exists for the patch type', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:0}); }, apply: function(s1, patch, unapply, ctx) { var old = s1.val; s1.val += patch.amount; ctx.ret(s1, old); }, }, bar: { apply: function(s1, patch, unapply, ctx) { var old = s1.val; s1.val -= patch.amount; // Does the opposite ctx.ret(s1, old); } }, }; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('h0')); }, function(_) { evalEnv.apply(this.h0, {_type: 'bar', amount: 2}, false, _.to('h1', 'res')); }, function(_) { hashDB.unhash(this.h1, _.to('s1')); }, function(_) { assert.deepEqual(this.s1, {_type: 'foo', val: -2}); assert.equal(this.res, 0); _();}, ], done)(); }); it('should pass the evaluator as the "this" of the called method', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val: 0}); }, apply: function(s1, patch, unapply, ctx) { s1.val += this.amount; ctx.ret(s1); }, amount: 50, }, }; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('s0')); }, function(_) { evalEnv.apply(this.s0, {}, false, _.to('s1')); }, function(_) { hashDB.unhash(this.s1, _.to('s1')); }, function(_) { assert.equal(this.s1.val, 50); _(); }, ], done)(); }); it('should report a conflict if a propagated patch conflicted', function(done){ var evaluators = { atom: require('../atom.js'), dir: require('../dir.js'), comp: require('../composite.js'), }; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('dir', {}, _.to('s0')); }, function(_) { evalEnv.trans(this.s0, {_type: 'comp', patches: [ {_type: 'create', _path: ['foo'], evalType: 'atom', args: {val: 'bar'}}, {_type: 'set', _path: ['foo'], from: 'baz', to: 'bat'}, // This is conflicting ]}, _.to('s1', 'res', 'eff', 'conf')); }, function(_) { assert(this.conf, 'should be conflicting'); _(); }, ], done)(); }); it('should collect effect patches from the application of the given patch', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val: 0}); }, apply: function(s1, patch, unapply, ctx) { s1.val += patch.amount * (unapply ? -1 : 1); ctx.effect({_type: 'bar', val: s1.val}); ctx.ret(s1); }, }, }; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('s0')); }, function(_) { evalEnv.apply(this.s0, {_type: 'baz', amount: 10}, false, _.to('s1', 'res', 'eff')); }, function(_) { assert.deepEqual(this.eff, [{_type: 'bar', val: 10}]); _(); }, ], done)(); }); it('should accumulate effects of underlying patches', function(done){ var evaluators = { dir: require('../dir.js'), comp: require('../composite.js'), foo: { init: function(args, ctx) { ctx.ret({val: 0}); }, apply: function(s1, patch, unapply, ctx) { s1.val += patch.amount * (unapply ? -1 : 1); ctx.effect({_type: 'bar', val: s1.val}); ctx.ret(s1); }, }, }; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('dir', {}, _.to('s0')); }, function(_) { evalEnv.apply(this.s0, {_type: 'comp', patches: [ {_type: 'create', _path: ['a'], evalType: 'foo', args: {}}, {_type: 'create', _path: ['b'], evalType: 'foo', args: {}}, {_type: 'baz', _path: ['a'], amount: 5}, {_type: 'baz', _path: ['b'], amount: 7}, ]}, false, _.to('s1', 'res', 'eff')); }, function(_) { assert.deepEqual(this.eff, [{_type: 'bar', val: 5}, {_type: 'bar', val: 7}]); _(); }, ], done)(); }); }); describe('trans(h1, patch, cb(err, h2, res, eff, conf))', function(){ it('should apply the patch', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:0}); }, apply: function(s1, patch, unapply, ctx) { var old = s1.val; s1.val += patch.amount; ctx.ret(s1, old); }, }}; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('h0')); }, function(_) { evalEnv.trans(this.h0, {_type: 'bar', amount: 2}, _.to('h1', 'res')); }, function(_) { hashDB.unhash(this.h1, _.to('s1')); }, function(_) { assert.deepEqual(this.s1, {_type: 'foo', val: 2}); assert.equal(this.res, 0); _();}, ], done)(); }); it('should avoid repeating calculations already done', function(done){ var count = 0; var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:0}); }, apply: function(s1, patch, unapply, ctx) { s1.val += patch.amount; count++; // Side effect: count the number of calls ctx.ret(s1); }, }}; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('h0')); }, function(_) { evalEnv.trans(this.h0, {_type: 'bar', amount: 2}, _.to('h1')); }, function(_) { evalEnv.trans(this.h1, {_type: 'bar', amount: -2}, _.to('h2')); }, function(_) { evalEnv.trans(this.h2, {_type: 'bar', amount: 2}, _.to('h3')); }, function(_) { evalEnv.trans(this.h3, {_type: 'bar', amount: -2}, _.to('h4')); }, function(_) { evalEnv.trans(this.h4, {_type: 'bar', amount: 2}, _.to('h5')); }, function(_) { evalEnv.trans(this.h5, {_type: 'bar', amount: -2}, _.to('h6')); }, function(_) { evalEnv.trans(this.h6, {_type: 'bar', amount: 2}, _.to('h7')); }, function(_) { evalEnv.trans(this.h7, {_type: 'bar', amount: -2}, _.to('h8')); }, function(_) { assert.equal(count, 2); _(); }, ], done)(); }); }); describe('query(s, q, cb(err, res))', function(){ it('should apply query patch q to object with state s, emitting res', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:args.val}); }, apply: function(s, query, unapply, ctx) { if(query._type == 'get') { ctx.ret(s, s.val); } }, }}; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {val:7}, _.to('h0')); }, function(_) { evalEnv.query(this.h0, {_type: 'get'}, _.to('res')); }, function(_) { assert.equal(this.res, 7); _();}, ], done)(); }); it('should emit an error if the query changes the state', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:0}); }, apply: function(s1, patch, unapply, ctx) { var old = s1.val; s1.val += patch.amount; ctx.ret(s1, old); }, }}; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); util.seq([ function(_) { evalEnv.init('foo', {}, _.to('h0')); }, function(_) { evalEnv.query(this.h0, {_type: 'bar', amount: 2}, _); }, ], function(err) { if(!err) { done(new Error('Error not emitted')); } else if(err.message == 'Query patch bar changed object state') { done(); } else { done(err); } })(); }); it('should do the opposite of applying patch to s1. Applying patch to s2 should result in s1, given that conf is false', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:0}); }, apply: function(s1, patch, unapply, ctx) { var old = s1.val; if(!unapply) { s1.val += patch.amount; } else { s1.val -= patch.amount; } ctx.ret(s1, old); }, }}; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); var patch = {_type: 'bar', amount: 2}; util.seq([ function(_) { evalEnv.init('foo', {}, _.to('h0')); }, function(_) { evalEnv.apply(this.h0, patch, false, _.to('h1')); }, function(_) { evalEnv.apply(this.h1, patch, true, _.to('h2')); }, function(_) { hashDB.hash(this.h2, _.to('h2')); }, function(_) { assert.equal(this.h2.$hash$, this.h0.$hash$); _(); }, ], done)(); }); it('should use the unpatch evaluator if one exists for the patch type', function(done){ var evaluators = { foo: { init: function(args, ctx) { ctx.ret({val:0}); }, apply: function(s1, patch, unapply, ctx) { var old = s1.val; if(!unapply) { s1.val += patch.amount; } else { s1.val -= patch.amount; } ctx.ret(s1, old); } }, bar: { apply: function(s1, patch, unapply, ctx) { var old = s1.val; if(!unapply) { s1.val += patch.amount * 2; } else { s1.val -= patch.amount * 2; } ctx.ret(s1, old); } }, }; var evalEnv = new EvalEnv(hashDB, kvs, evaluators); var patch = {_type: 'bar', amount: 2}; util.seq([ function(_) { evalEnv.init('foo', {}, _.to('h0')); }, // 0 function(_) { evalEnv.apply(this.h0, patch, true, _.to('h1')); }, // -4 function(_) { hashDB.unhash(this.h1, _.to('s1')); }, function(_) { assert.equal(this.s1.val, -4); _(); }, ], done)(); }); }); });
'use strict'; window.Resources = (function(){ /** * All of the resources loaded into the system * * @type Array */ var data = []; /** * Gets a specific resource for the user. * * @param string key The key to look for * @param object replacements The values to replace * @return mixed The resource value with any replacements completed. */ var get = function(key, replacements) { var resource = baseResource(key); return replacePlaceholders(resource, replacements); }; /** * Helper to derive the resource name * * @param string key The key * @return mixed The resource value, or the key if not found. */ var baseResource = function(key) { var resource = findResource(key, Resources.data); return resource === undefined ? key : resource; }; /** * Recursively finds the resource related to the data provided. * * @param {string} key The key * @param {<type>} data The data * @return {<type>} { description_of_the_return_value } */ var findResource = function (key, data) { // Is there a '.'? if(key.indexOf('.') == -1) { // There isn't, so return the value return data[key]; } // Split the string up around the first '.'' var attribute = key.substring(0, key.indexOf('.')); var remainder = key.substring(key.indexOf('.') + 1); // Either recursively find the resoruce, or the data. return typeof(data[attribute]) == 'object' ? findResource(remainder, data[attribute]) : data[attribute]; } /** * Replaces any placeholders in the text with the requested replacements. * * @param mixed resource The resource * @param object replacements The replacements * @return {Function} { description_of_the_return_value } */ var replacePlaceholders = function(resource, replacements) { if(typeof(resource) == 'object') { return resource; } for(var index in replacements) { resource = replaceAll(resource, ':' + index, replacements[index]); }; return resource; }; /** * Replaces all instances of an key with the related value * * @param string resource The resource * @param stiring expression The expression to replace * @param string value The value to replace it with * @return {string} { description_of_the_return_value } */ var replaceAll = function(resource, expression, value) { return resource.replace(new RegExp(expression.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"), 'g'), value); } return { data: data, get: get }; })();
export class ScalingMath { //linear scaling of knob position in degrees, 0 being straight up; 'amp' represents amplitude linScale(knobPosition, amp){ return this.scaleRound(amp*(knobPosition + 150)/300, amp); } revLinScale(paramval, amp) { return this.scaleRound(300/amp*paramval - 150, amp); } expScale(knobPosition, amp, curveShape){ return this.scaleRound(amp*(Math.exp(curveShape*(knobPosition+150) / 300)-1) / (Math.exp(curveShape)-1), amp); } revExpScale(paramval, amp, curveShape){ return this.scaleRound(300 / curveShape * Math.log(paramval / amp*(Math.exp(curveShape)-1)+1) - 150, amp); } binScale(knobPosition, base, ex){ return Math.round( base*(Math.pow(2, ex*(knobPosition+150) / 300)-1)); } revBinScale(knobPosition, base, ex){ return Math.round(300*Math.log2(knobPosition/base + 1)/ex - 150); } noteToTone(note) { return 16.35*Math.pow(2, (note/125)); } scaleRound(val, a){ if(a>=100) return Math.round(val); else if(a<100&&a>=10) return Math.round(val*10)/10; else return Math.round(val*100)/100; } }
module.exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions let { data } = await graphql(` query { allMarkdownRemark { edges { node { fields { slug } } } } } `) data.allMarkdownRemark.edges.forEach(edge => { createPage({ path: edge.node.fields.slug, component: `${__dirname}/src/templates/singleBlog.js`, context: { slug: edge.node.fields.slug, }, }) }) } module.exports.onCreateNode = ({ node, actions }) => { const { createNodeField } = actions /** * Add slug field to article node */ if (node.internal.type === 'MarkdownRemark') { let arr = node.fileAbsolutePath.split('/') let articleDirName = arr[arr.length - 2] let articleSlug = articleDirName .split(' ') .map(word => word.toLowerCase()) .join('-') let slug = `/articles/${articleSlug}` createNodeField({ node, name: 'slug', value: slug, }) } }
/**Query database every 24hours and notify user if time is up to returned borrowed books */ let path = require('path'); const tempdir = path.join(__dirname, './template/reminder.ejs'); const sendEmail = require('./sendMail').sendEmail; const Borrowed = require('../models').Borrowed; const User = require('../models').User; const Book = require('../models').Book; //check database every 24 hours let refresh = 24 * 60 * 60 * 1000; function sendReminder() { setInterval(loop, refresh); } function loop() { //query database to get all unreturned books return Borrowed.findAll({ where: { returned: false } }).then(borrow => { return borrow.map(function(borrow) { let userId = borrow.userId; let bookId = borrow.bookId; let updatedAt = borrow.updatedAt; let now = new Date(); let duration = now - updatedAt; let expire = 7 * refresh; //user has 7 days to return //get user details where book ought to have been returned but still with the user if (duration >= expire) { return User.findById(userId).then(user => { let username = user.username; return Book.findById(bookId).then(book => { let userEmail = user.email; let bookTitle = book.title; let data = { user: username, book: bookTitle, date: updatedAt }; if (duration >= expire) { sendEmail(userEmail, tempdir, data, 'Return Book'); } }); }); } }); }); } exports.sendReminder = sendReminder;
import Vue from 'vue' import Router from 'vue-router' import Register from '@/components/Register' import Login from '@/components/Login' import Vote from '@/components/Vote' import RequestService from '../services/RequestService' Vue.use(Router) const router = new Router({ routes: [ { path: '/', redirect: '/login' }, { path: '/register', name: 'register', component: Register }, { path: '/login', name: 'login', component: Login }, { path: '/vote', name: 'vote', component: Vote, meta: { requiresAuth: true } } ], methods: { redirect (target) { this.$router.push(target) } } }) router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { verify().then(function (autherised) { if (autherised !== false) { next() } else { next({path: '/login'}) } }) } else { next() } }) async function verify () { try { const response = await RequestService.verifyToken({ token: Vue.cookies.get('token') }) return response } catch (error) { return false } } export default router
/** * window.c.projectReportNoRewardReceived component * Render project report form * */ import m from 'mithril'; import prop from 'mithril/stream'; import h from '../h'; import _ from 'underscore'; import ownerMessageContent from './owner-message-content'; import modalBox from './modal-box'; const projectReportNoRewardReceived = { oninit: function(vnode) { const formName = 'report-no-reward-received'; const displayModal = h.toggleProp(false, true); const storeId = 'send-message'; const sendMessage = () => { if (!h.getUser()) { h.storeAction(storeId, vnode.attrs.project.project_id); return h.navigateToDevise(`?redirect_to=/projects/${vnode.attrs.project.project_id}`); } displayModal(true); }; if (h.callStoredAction(storeId) == vnode.attrs.project().project_id) { displayModal(true); } vnode.state = { displayModal, sendMessage, formName: vnode.attrs.formName || formName }; }, view: function({state, attrs}) { const contactModalC = [ownerMessageContent, prop(_.extend(attrs.user, { project_id: attrs.project().id }))]; return m('.card.u-radius.u-margintop-20', [ (state.displayModal() ? m(modalBox, { displayModal: state.displayModal, content: contactModalC }) : ''), m('.w-form', m('form', [ m('.report-option.w-radio', [ m('input.w-radio-input[type=\'radio\']', { value: state.formName, checked: attrs.displayFormWithName() === state.formName, onchange: m.withAttr('value', attrs.displayFormWithName) }), m('label.fontsize-small.fontweight-semibold.w-form-label', { onclick: _ => attrs.displayFormWithName(state.formName) }, 'Apoiei este projeto e ainda não recebi a recompensa') ] ), m('.u-margintop-30', { style: { display: attrs.displayFormWithName() === state.formName ? 'block' : 'none' } }, m('.fontsize-small', [ 'Para saber sobre a de entrega da sua recompensa, você pode enviar uma', m('a.alt-link', { style: { cursor: 'pointer' }, onclick: h.analytics.event({ cat: 'project_view', act: 'project_creator_sendmsg', lbl: attrs.user.id, project: attrs.project() }, state.sendMessage), text: ' mensagem diretamente para o(a) Realizador(a)' }), '.', m('br'), m('br'), 'Veja', m('a.alt-link', { href: 'https://suporte.catarse.me/hc/pt-br/articles/360000149946-Ainda-n%C3%A3o-recebi-minha-recompensa-E-agora-', target: '_blank' }, ' aqui '), 'outras dicas sobre como acompanhar essa entrega.' ] ) ) ] ) ) ]); } }; export default projectReportNoRewardReceived;
import React, { Component} from 'react'; import HoleTriangle from './holes/HoleTriangle'; import HoleSquare from './holes/HoleSquare'; import HoleCircle from './holes/HoleCircle'; class HolePanel extends Component { render() { return ( <div style={styles.panelStyle}> <HoleTriangle /> <HoleCircle /> <HoleSquare /> </div> ); } } const styles = { panelStyle: { height: 300, width: 800, backgroundColor: 'saddlebrown', borderRadius: 20, display: 'flex', justifyContent: 'space-evenly', alignItems: 'center', margin: 'auto' } } export default HolePanel;
import { hostname, tokenHeader } from '../../config/settings' import { port } from '../../config/constants' import makeRequest from './makeRequest' const get = (endpoint) => { console.log(endpoint) let options = { hostname, port, method: 'GET', path: endpoint, headers: {} } if (tokenHeader) { options.headers['Authorization'] = tokenHeader } return makeRequest(options) } export default get
import Toolbar from './Toolbar' export { Toolbar, }
import 'bootstrap'; import {DataCache} from 'dataCache'; import {Plugin1} from 'Plugin1'; import {Plugin2} from 'Plugin2'; export function configure(aurelia) { let cache = new DataCache(); cache.data.push('1'); cache.data.push('2'); cache.data.push('3'); aurelia.use.instance("apiRoot", "http://brianapidemos.azurewebsites.net/CommunityAPI/") aurelia.use.globalResources('converters/dateFormatValueConverter'); // avoids need for <require/> elements in templates aurelia.use.globalResources('validation/validation-summary.html'); aurelia.use.transient("SuperPlugIn", Plugin1); aurelia.use.transient("SuperPlugIn", Plugin2); aurelia.use.instance("Cache", cache); aurelia.use .standardConfiguration() .developmentLogging() .plugin("aurelia-dialog") .plugin("aurelia-validation"); aurelia.start().then(a => a.setRoot("shell")); }
import { Group } from 'models/models' class GroupRepository { getGroupsWithCriteria = search => { return Group.find(search, '_id name pictureUrl owner moderators') .populate('owner moderators', '_id info.fullName info.link') .lean() } } export default GroupRepository
(function(){ let customers = []; let index = 0; function Customer(id,name,text){ this.id = id; this.name = name; this.text = text; } function createCustomer(id,name,text){ let fullImg = `img/customer-${id}.jpg`; const customer = new Customer(fullImg,name,text); customers.push(customer); } createCustomer(1,"Kemal Sunal",`Ben bir balon değilim. Öyle çıkanlar var ve ayakta kalmak için her gün TV’de görünmek zorundalar. Ama benim böyle bir şeye ihtiyacım yok çünkü ben sırtımı halka dayamışım.`) createCustomer(2,"Cüneyt Arkın",`Bugün sabah olana kadar şu kollarımın ucuna iki tane arslan pençesi yapacaksın.`) createCustomer(3,"Filiz Akın",`İstemyerek sarf ettiğim acı sözleri şimdi geri alıyorum.`) document.querySelectorAll('.btn').forEach(function (item) { item.addEventListener('click', function (event) { event.preventDefault(); if (event.target.parentElement.classList.contains('prevBtn') || event.target.classList.contains('prevBtn')) { if (index === 0) { index = customers.length; console.log(index) } index--; document.getElementById('customer-img').src = customers[index].id; document.getElementById('customer-name').textContent = customers[index].name; document.getElementById('customer-text').textContent = customers[index].text; } if (event.target.parentElement.classList.contains('nextBtn') || event.target.classList.contains('nextBtn')) { if (index === (customers.length)) { index = 0; } document.getElementById('customer-img').src = customers[index].id; document.getElementById('customer-name').textContent = customers[index].name; document.getElementById('customer-text').textContent = customers[index].text; index++; } }); }); })();
/* ************************************************************ title : Scroll Bar ver 0.01 date : 2016.12 author : Heowongeun ************************************************************ */ var DragAndDrop = require('./DragAndDrop'); var Bind = require('../util/Bind'); var windowSize = require('../util/WindowSize'); var throttle = require('throttle-debounce/throttle'); function ScrollBar($btn,$wrap,option){ this.btn = $btn; this.wrap = $wrap; this.isDrag = false; this.isMoving = false; this.config = { direction : 'x', bounceFriction : 0.2, dragSpeed : 0.2, update : function(){}, end : function(){} }; $.extend(this.config,option); this.drag = {x:0,y:0,vf:0,old:{x:0,y:0}}; this.position = {x:0,y:0,oldX:0,normal:{x:0,y:0}}; this.fakePosition = {x:0,y:0,oldX:0}; var $fakeBtn; var $win = $(window); var maxWidth = 0, maxHeight = 0; var ticking = false; function setup(){ onDragStart = Bind(onDragStart,this); onDragMove = Bind(onDragMove,this); onDragStop = Bind(onDragStop,this); barClick = Bind(barClick,this); update = Bind(update,this); onResize = Bind(onResize,this); // $fakeBtn = $('<figure></figure>'); // $btn.after($fakeBtn); // $fakeBtn.css({ // position:'absolute', // background:'red', // left:$btn.css('left'), // top:$btn.css('top'), // marginLeft:$btn.css('marginLeft'), // marginTop:$btn.css('marginTop'), // cursor:'pointer', // zIndex:10 // }); $win.on('resize',throttle(10,onResize,false)); // this.wrap.on('click',this.barClick); onResize(); new DragAndDrop($btn,{ onStart:onDragStart, onMove:onDragMove, onEnd:onDragStop }); } function onDragStart(e){ this.btn.addClass('scrollHover'); this.drag.old.x = this.drag.x; this.isDrag = true; if(!ticking){ requestAnimationFrame(update); ticking = true; } } function onDragMove(e){ this.isMoving = true; this.drag.x = -e.distance.x+this.drag.old.x; } function onDragStop(e){ this.isDrag = false; this.isMoving = false; this.btn.removeClass('scrollHover'); console.log('stop'); } function barClick(e){ this.drag.x = e.offsetX; } function onResize(){ maxWidth = this.wrap.width()-$btn.width(); maxHeight = this.wrap.height(); // $fakeBtn.css({width:$btn.width(),height:$btn.height()}); } function update(){ this.fakePosition.x = this.drag.x; if(this.fakePosition.x < 0)this.fakePosition.x = 0; if(this.fakePosition.x > maxWidth)this.fakePosition.x = maxWidth; // TweenLite.set($fakeBtn,{x:this.fakePosition.x,y:this.fakePosition.y}); this.position.x += (this.fakePosition.x-this.position.x)*this.config.dragSpeed; // this.position.y += (this.fakePosition.y-this.position.y)*this.config.dragSpeed; this.btn[0].style.transform = this.transition(this.position.x,0,0); var distance = Math.abs(this.position.x-this.fakePosition.x); this.position.normal.x = this.position.x/maxWidth; // this.position.normal.y = this.position.y/maxHeight; this.config.update(this.position); if(distance<0.01 && !this.isDrag){ ticking = false; this.config.end(); }else{ requestAnimationFrame(update); } } this.transition = function(x,y,z){ return 'translate3d('+x+'px,'+y+'px,'+z+'px)'; } this.setX = function(normal){ this.fakePosition.x = this.position.x = normal*maxWidth; this.position.normal.x = normal; this.drag.x = normal*maxWidth; TweenLite.set(this.btn,{x:this.position.x,y:this.position.y}); // onRender(); } setup.call(this); return this; }; module.exports = ScrollBar;
"use strict"; const bench = require("./src/index"); const AlminVersions = { current: require("./almin-current"), "0.12": require("./almin-0.12"), "0.9": require("./almin-0.9") }; bench(AlminVersions, benchmark => { console.log(benchmark.join("\n")); console.log("Fastest is " + benchmark.filter("fastest").map("name")); });
/** * 图片墙 * * @param imgs 图片的src 数组 * @param container 放置图片的容器 * @param containerWidth 容器的宽度 * @param rowHeight 行的高度 */ function imagewall(imgs, container, containerWidth, rowHeight) { calcImageSizes(imgs).done(function(sizes) { var newSizes = resizeTo(sizes, rowHeight); var rows = toRows(newSizes, containerWidth); calcFinalSize(newSizes, rows, containerWidth, rowHeight); var $imgContainer = renderRows(imgs, newSizes, rows); $imgContainer.appendTo(container); }); } /** * 获取图片的原始大小 * * @param imgs 图片的src 数组 * @returns 图片的原始大小数组 */ function calcImageSizes(imgs) { var sizes = []; var deferred = $.Deferred(); var resolveCount = 0; function calc(index) { var imgObj = new Image(); imgObj.src = imgs[index]; // var deferred = $.Deferred(); $(imgObj).on("load", function() { sizes[index] = { width : imgObj.width, height : imgObj.height } resolveCount++; if (resolveCount == imgs.length) { deferred.resolve(sizes); } }); } for ( var index = 0; index < imgs.length; index++) { calc(index); } return deferred; } /** * 根据指定的高度, 对图片进行缩放 * * @param sizes 图片原始大小数组 * @param height 指定的高度 * @returns {Array} 图片缩放后的大小数组 */ function resizeTo(sizes, height) { var newSizes = []; $.each(sizes, function(index, size) { // 宽度 = (指定高度 / 图片高度) * 图片宽度 var rate = size.width / size.height; newSizes[index] = { width : height * rate, height : height } }); return newSizes; } /** * 根据缩放后的大小, 将图片划分的多行 * * @param newSizes 缩放后的图片大小 * @param containerWidth 容器的宽度 * @returns {Array} 每一个元素是一行的开始和结束序号, 已经总的图片的宽度 */ function toRows(newSizes, containerWidth) { var rows = []; var indexMark = 0; var rowWidth = 0; function addRow(start, end, width) { rows.push({ start : start, end : end, width : width }); } // 计算每一行的图片 // 1. 将图片的宽度依次相加 // 2. 如果当前一行的宽度加上当前这一个图片的宽度 小于 容器的宽度, 则继续相加 // 3. 如果是等于, 则是刚刚好了, 不用管了 // 4. 如果是大于, 则根据加上这一张图片后的宽度, 比不加上的宽度, 那一个和容器宽度比较接近. for ( var index = 0; index < newSizes.length; index++) { var w = rowWidth + newSizes[index].width; if (w < containerWidth) { // 如果当前一行的宽度加上当前这一个图片的宽度 小于 容器的宽度 rowWidth = w; } else if (w == containerWidth) { // 重新开始一行了. addRow(indexMark, index, w); indexMark = index + 1; rowWidth = 0; } else { // w > containerWidth if (containerWidth - rowWidth <= w - containerWidth) { // 不加上这张图片比较适合 // 这一张图片是下一行的了 addRow(indexMark, index - 1, rowWidth); indexMark = index; rowWidth = newSizes[index].width; } else { // 这一张图片是当前行的 addRow(indexMark, index, w); indexMark = index + 1; rowWidth = 0; } } } if (indexMark < newSizes.length) { addRow(indexMark, newSizes.length - 1, rowWidth); } return rows; } /** * 根据分的行, 重新计算每一行的每一个图片的高度 * * @param newSizes 缩放后的图片大小, 重新计算后的大小会更新到这个数组 * @param rows 每一行的开始/结束序号 * @param containerWidth 容器的宽度 * @param rowHeight 每一行默认的高度, 在这个高度上进行调整 */ function calcFinalSize(newSizes, rows, containerWidth, rowHeight) { function calc(row, newHeight, dHeight) { for ( var index = row.start; index <= row.end; index++) { var size = newSizes[index]; newSizes[index] = { width : size.width * dHeight, height : newHeight } } } $.each(rows, function(rowIndex, row) { var rowWidth = row.width; if (rowWidth != containerWidth) { var newHeight = containerWidth * rowHeight / rowWidth; var dHeight = newHeight / rowHeight; if (rowIndex == rows.length - 1 && dHeight > 1.5) { // 最后一行可能没那么多图片了, 则不放到最大, 只按照一定的比例就可以 dHeight = 1.5; newHeight = dHeight * rowHeight; } calc(row, newHeight, dHeight); } }); } /** * 生成行以及图片 * * @param imgs 图片src 数组 * @param newSizes 每一个图片的大小 * @param rows 每一行的开始/结束序号 * @returns 生成的所有图片, 这里是一个jQuery 对象 */ function renderRows(imgs, newSizes, rows) { var $container = $("<div></div>"); $.each(rows, function(rowIndex, row) { var $row = $("<div style='overflow: hidden; white-space: nowrap;'></div>").appendTo($container); for ( var index = row.start; index <= row.end; index++) { var $img = $("<img/>").attr("src", imgs[index]).css(newSizes[index]); $img.css({ "margin" : "3px", }).appendTo($row); } }); return $container; }
// crossbrowser event adding function addEvent(event, func) { if (window.addEventListener) window.addEventListener(event, func, false); else if (window.attachEvent) window.attachEvent('on' + event, func); }; // detect if element is a link function isLink(element) { if (element.tagName === 'A') return true; return (element.parentNode) ? isLink(element.parentNode) : false; }; // load remote content function loadURL(url, callback) { var request = createXMLHTTPObject(); if (!request) return; request.open('GET', url, true); request.onreadystatechange = function () { if (request.readyState != 4) return; if (request.status != 200 && request.status != 304) { console.log('HTTP error ' + request.status); return; } callback(request); } if (request.readyState == 4) return; request.send(); } // returns xmlhttp object function createXMLHTTPObject() { var xmlhttp = false, XMLHttpFactories = [ function () { return new XMLHttpRequest() }, function () { return new ActiveXObject("Msxml2.XMLHTTP") }, function () { return new ActiveXObject("Msxml3.XMLHTTP") }, function () { return new ActiveXObject("Microsoft.XMLHTTP") } ]; for (var i=0; i<XMLHttpFactories.length; i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; }
import { expect, sinon } from '../test-helper' import mailJet from '../../src/infrastructure/mailing/mailjet' import NotifyTheme from '../../src/use_cases/notify-theme' describe('Unit | Service | NotifyTheme', () => { const theme = { previousTheme: 'new', newTheme: 'dark', } beforeEach(() => { sinon.stub(mailJet, 'sendEmail') }) afterEach(() => { mailJet.sendEmail.restore() }) describe('#notifyThemeEmail', () => { it('should send an email with correct data', () => { // given mailJet.sendEmail.resolves() // when const promise = NotifyTheme.notifyTheme(theme) // then return promise.then(result => { expect(result).to.equal(theme) expect(mailJet.sendEmail).to.have.been.calledWithExactly({ from: 'contact-localhost@recontact.me', to: ['contact-localhost@recontact.me'], fromName: 'RecontactMe', subject: '[RecontactMe] Un thème a été choisi : dark!', template: '<p>Le thème a été changé :</p>\n' + '<p>C\'était : new</p>\n' + '<p>C\'est : dark</p>', }) }) }) it('should throw error when mailJet rejects', () => { // given mailJet.sendEmail.rejects(new Error('error')) // when const promise = NotifyTheme.notifyTheme(theme) // then return promise.catch(err => { expect(err.message).to.equal('error') }) }) }) })
export class WeatherData{ constructor(cityName, description,humidity){ this.cityName = cityName; this.description = description; this.temperature = ''; this.humidity = humidity; } } export const WeatherProxyHandler = { get: function(target, property){ return Reflect.get(target,property); }, set: function(target,property, value){ // const newValue = (value * 1.8 + 32).toFixed(2)+ 'F.'; const newValue = value + 'C.'; return Reflect.set(target,property,newValue); } };
Accounts.config({sendVerificationEmail: true, restrictCreationByEmailDomain: 'zenbanx.com'});
'use strict'; /** * Module dependencies. */ const Koa = require('koa'); const request = require('supertest'); const requestId = require('..'); /** * Uuid regex. */ const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}/; /** * Test `koa-requestid`. */ describe('koa-requestid', () => { let app; let server; beforeEach(() => { app = new Koa(); server = app.listen(); }); afterEach(() => server.close()); it('should expose a named function', () => { expect(requestId().name).toEqual('requestId'); }); it('should add a request id to `ctx.state` by default', () => { app.use(requestId()); app.use(ctx => { ctx.body = ctx.state.id; }); return request(server) .get('/') .expect(uuid); }); for (const option of ['expose', 'header', 'query']) { it(`should throw an error if \`${option}\` option is invalid`, () => { try { requestId({ [option]: 123 }); fail(); } catch (e) { expect(e.message).toEqual(`Option \`${option}\` requires a boolean or a string`); } }); } it('should not check the querystring if `query` is false', () => { app.use(requestId({ query: false })); app.use(ctx => { ctx.body = ctx.state.id; }); return request(server) .get('/?requestId=foobar') .expect(uuid); }); it('should not check the header if `header` is false', () => { app.use(requestId({ header: false })); app.use(ctx => { ctx.body = ctx.state.id; }); return request(server) .get('/') .set('request-id', 'foobar') .expect(uuid); }); it('should not expose the header if `header` is false', () => { app.use(requestId({ expose: false })); app.use(ctx => { ctx.body = ctx.state.id; }); return request(server) .get('/') .set('request-id', 'foobar') .expect({}); }); it('should check the `requestId` querystring by default', () => { app.use(requestId()); app.use(ctx => { ctx.body = ctx.state.id; }); return request(server) .get('/?requestId=foobar') .expect('foobar'); }); it('should check the `request-id` header by default', () => { app.use(requestId()); app.use(ctx => { ctx.body = ctx.state.id; }); return request(server) .get('/') .set('request-id', 'foobar') .expect('foobar'); }); it('should expose the `request-id` by default', () => { app.use(requestId()); app.use(ctx => { ctx.body = ctx.response.header['request-id']; }); return request(server) .get('/') .set('request-id', 'foobar') .expect('foobar'); }); it('should expose request id in a custom header if `expose` is set', () => { app.use(requestId({ expose: 'x-request-id' })); app.use(ctx => { ctx.body = ctx.response.header['x-request-id']; }); return request(server) .get('/') .set('request-id', 'foobar') .expect('foobar'); }); });
/* Project Euler: Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. */ var i = 0; var multiplesArray = []; while(i<1000){ if(i%3 === 0 || i%5 === 0){ multiplesArray.push(i); } i++; } var sum = multiplesArray.reduce(function(sum,value){ return sum + value; }) // console.log(multiplesArray); console.log("The sum is: " + sum);
const CronJob = require('cron').CronJob; const Console = require('./Console'); const tradeManager = require('./TradeManager'); var browserManager; const everyMinute = new CronJob('* * * * *', async () => { let minute = new Date().getMinutes(); let trades = tradeManager.getTradesByMinute(minute % 15); if(trades.length > 0){ Console.log(`Bumpeando ${trades.length} ${trades.length == 1 ? 'anuncio' : 'anuncios'}`); let bumpTrades = await browserManager.bump(trades); tradeManager.update(bumpTrades); }else{ Console.log('...'); } }); module.exports = async function(){ browserManager = await require('./BrowserManager')(); everyMinute.start(); }
(function(){ angular.module('QforQuants') .factory('userRoleService',function($http,$q){ var modelName = 'userrole'; var apiUrl = '/api/userrole'; var getAll = function(){ var defered = $q.defer(); $http({ method : 'GET', url : modelName + apiUrl }).success(function(result){ defered.resolve(result); }).error(function(error){ defered.reject(error); }); return defered.promise; }; var save = function(userRole){ var defered = $q.defer(); $http({ method : 'POST', data : userRole, url : modelName + apiUrl }).success(function(result){ defered.resolve(result); }).error(function(error){ defered.reject(error); }); return defered.promise; }; var update = function(data,id){ var defered = $q.defer(); $http({ method : 'PUT', data : {update : data}, url : modelName + apiUrl +'/'+id }).success(function(result){ defered.resolve(result); }).error(function(error){ defered.reject(error); }); return defered.promise; }; var delet = function(id){ var defered = $q.defer(); $http({ method : 'DELETE', url : modelName + apiUrl +'/'+id }).success(function(result){ defered.resolve(result); }).error(function(error){ defered.reject(error); }); return defered.promise; }; return { GetAllRoles : getAll, SaveRole : save, UpdateRole : update, DeleteRole : delet }; }); })();
import React from 'react' import { Title } from '../Title' import { ResumeWrapper, ResumeContent, ResumeItem, ResumeTitle, ResumeValue } from './style' function Resume({ data, children }) { const { subTotal, total, shippingTotal, discount } = data; return ( <ResumeWrapper> <Title> Resumo do pedido </Title> <ResumeContent> <ResumeItem> <ResumeTitle> Produtos </ResumeTitle> <ResumeValue> {subTotal?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || ""} </ResumeValue> </ResumeItem> <ResumeItem> <ResumeTitle> Frete </ResumeTitle> <ResumeValue> {shippingTotal?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || ""} </ResumeValue> </ResumeItem> <ResumeItem color={'primary'}> <ResumeTitle > Desconto </ResumeTitle> <ResumeValue> -{discount?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || ""} </ResumeValue> </ResumeItem> <ResumeItem color={'darkest'} weight={'700'}> <ResumeTitle> Total </ResumeTitle> <ResumeValue> {total?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || ""} </ResumeValue> </ResumeItem> </ResumeContent> {children} </ResumeWrapper> ) } export default Resume
var setZeroes = function(matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; m = matrix.lenght, n = matrix[0].length; var rowZero = false, colZero = false; for (let j = 0; j < n; ++j) { if (matrix[0][j] == 0) { rowZero = true; break; } } for (let i = 0; i < m; ++i) { if (matrix[i][0] == 0) { colZero = true; break; } } for (let i = 1; i < m; ++i) { for (let j = 1; j < n; ++j) { if (matrix[i][j] == 0) { matrix[0][j] = 0; matrix[i][0] = 0; } } } for (let i = 1; i < m; ++i) { for (let j = 1; j < n; ++j) { if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; } } if (rowZero) { for (let j = 0; j < n; ++j) matrix[0][j] = 0; } if (colZero) { for (let i = 0; i < m; ++i) matrix[i][0] = 0; } };
!function () { 'use strict'; function Controller($scope, dataService, $location, info) { $scope.target = {}; $scope.status = info.ContractStatus; dataService.contract .query({maxCount: 5, showLatest: true}).$promise .then(function (response) { $scope.contracts = response; }); dataService.general .recentForms({ maxCount: 5 }).$promise .then(function (response) { $scope.forms = response; }); $scope.getSelectOptions = function (category) { function selectTemplate(item) { var result; if (item.category) { if(item.category == 'Contract') { item.category = 'Activity'; } result = '<div class="row"><p class="col-md-9">' + item.name + '</p><p class="col-md-3 text-right">' + item.category + '</p></div>'; } else if (item.customerName) { result = item.customerName; } else { result = item.name; } return result; } return { formatResult: selectTemplate, formatSelection: selectTemplate, containerCssClass: 'form-control', minimumInputLength: 1, query: function (query) { $scope.$apply(function () { dataService[category] .query({ name: query.term }).$promise .then(function (response) { query.callback({ results: response }); }); }); } }; }; $scope.view = function () { var target = $scope.target, category = target.category ? target.category.toLowerCase() : $scope.category; if (category == 'activity') { category = 'contract'; } $location.path('/' + category + '/info/' + target.id); }; }; angular.module('DNNT') .controller('controller.dashboard', Controller); }();
function sumar() { var num1 = parseInt(document.getElementById('a').value); var num2 = parseInt(document.getElementById('b').value); var suma =num1 + num2; alert('La suma es: '+ suma); } function restar() { var num1 = parseInt(document.getElementById('a').value); var num2 = parseInt(document.getElementById('b').value); var resta =num1 - num2; alert('La Resta es: '+ resta); } function multiplicar() { var num1 = parseInt(document.getElementById('a').value); var num2 = parseInt(document.getElementById('b').value); var multiplicar = num1 * num2; alert('La suma es: '+ multiplicar); } function dividir() { var num1 = parseInt(document.getElementById('a').value); var num2 = parseInt(document.getElementById('b').value); var dividir =num1 / num2; alert('La suma es: '+ dividir); }
import React from 'react'; import {Button,Checkbox,Select,Radio,Switch,Form,Row,Col,Icon,Modal,Input,InputNumber,Cascader,Tooltip } from 'antd'; const FormItem = Form.Item; const RadioGroup = Radio.Group; const Option = Select.Option; import {FetchUtil} from '../../utils/fetchUtil'; import {trim} from '../../utils/validateUtil'; export default class EditDataListRecord extends React.Component{ constructor(props){ super(props); this.state={ visible:false, dataRecord:this.props.row.dataRecord, fieldNum:this.props.metaList.length } } handleChange=(index,e)=>{ var value=e.target.value; var valueArr=this.state.dataRecord.split(','); if(valueArr.length<this.state.fieldNum){ var newArr=new Array(this.state.fieldNum); for(var i=0;i<this.state.fieldNum;i++){ newArr[i]=valueArr[i]!=undefined?valueArr[i]:''; } valueArr=newArr; } valueArr[index]=trim(value); this.setState({ dataRecord:valueArr.join(',') }); } handleSelect=(name,value)=>{ var state = this.state; state[name] = trim(value); this.setState(state); } showModal=()=>{ this.setState({ visible:true }) } handleSubmit=()=>{ var param={}; param.id=this.props.row.id; param.dataListId=this.props.dataListId; param.dataRecord=this.state.dataRecord; FetchUtil('/datalistrecord/','PUT',JSON.stringify(param), (data) => { this.setState({ visible:false }); this.props.reload(); }); } handleCancel=()=>{ this.setState({ visible:false }) } render(){ const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 16 }, }; let valueArr=this.state.dataRecord.split(','); return ( <span> <Tooltip title="编辑" onClick={this.showModal}><a>编辑</a></Tooltip> <Modal title="编辑记录" visible={this.state.visible} onOk={this.handleSubmit} onCancel={this.handleCancel}> <Form horizontal form={this.props.form}> {this.props.metaList.map(function(info,i){ return ( <FormItem {...formItemLayout} key={'meta'+info.id} label={info.label}> <Input type="text" value={valueArr[i]} onChange={this.handleChange.bind(this,i)}/> </FormItem> ); }.bind(this))} </Form> </Modal> </span> ); } }
process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', function(chuck) { process.stdout.write('Data entered: ' + chuck); }); process.stdin.on('end', function() { process.stderr.write('Stream end.\n'); }); process.on('SIGTERM', function() { process.stderr.write("Terminating process..."); }); console.log("PID: #" + process.pid);
// For an introduction to the Blank template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkID=397704 // To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints, // and then run "window.location.reload()" in the JavaScript Console. (function () { "use strict"; document.addEventListener('deviceready', onDeviceReady.bind(this), false); function onDeviceReady() { // Handle the Cordova pause and resume events document.addEventListener('pause', onPause.bind(this), false); document.addEventListener('resume', onResume.bind(this), false); bootstrapApplication(); // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here. }; function onPause() { // TODO: This application has been suspended. Save application state here. }; function onResume() { // TODO: This application has been reactivated. Restore application state here. }; function bootstrapApplication() { //resolve dependencies var EventBus = _.extend({}, Backbone.Events); CollectionService = CollectionService(); //setup autoRefresh broadcast setInterval(function () { EventBus.trigger('autoRefresh'); }, 5000) //Compose views var messageListView = new MessageListView({ eventBus: EventBus, collectionService: CollectionService }); var inputView = new InputView({ eventBus: EventBus }); }; })();
/** * Created by root on 15.06.17. */ function initMap() { var latitude = 59.990147, longitude = 30.159004, map_zoom = 15; var style = [{ featureType: 'all', stylers: [ {saturation: 0}] }, { featureType: 'water', skylers: [ {saturation: 1}] }]; var map_options = { center: new google.maps.LatLng(latitude, longitude), zoom: map_zoom, panControl: false, zoomControl: false, mapTypeControl: false, streetViewControl: false, mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: true }; var map = new google.maps.Map(document.getElementById('map'), map_options); var image = '/wp-content/themes/kids/assets/images/map_marker.png'; var beachMarker = new google.maps.Marker({ position: new google.maps.LatLng(latitude, longitude), map: map, icon: image }); map.getStreetView().setOptions({ adressControlOptions: { position: google.maps.ControlPosition.BOTTOM } }); } /* var panorama = map.getStreetView(); panorama.setPosition({ lat: latitude, lng: longitude }); panorama.setPov({ heading: 265, pitch: 0 }); panorama.setVisible(true); map.setStreetView(panorama); function toggleStreetView() { var toggle = panorama.getVisible(); if (toggle === false) { panorama.setVisible(true); } else { panorama.setVisible(false); } } } */
const methodHandlers = {} const requestHandlers = [] const registerMethodHandler = (method, handler) => { methodHandlers[method] = handler } const registerRequestHandler = (requestHandler) => { requestHandlers.push(requestHandler) } const parseBody = (req, callback) => { const chunks = [] req.on('data', (chunk) => chunks.push(chunk)) req.on('end', () => callback(null, Buffer.concat(chunks))) req.on('error', callback) } const sendResult = (res, result) => { res.setHeader('Content-Type', 'application/octet-stream') res.end(encode(result)) } let encode = (payload) => { return new Buffer(JSON.stringify(payload)).toString('base64') } registerEncode = (_encode) => encode = _encode let decode = (payload) => { return JSON.parse(Buffer.from(payload.toString(), 'base64').toString()) } registerDecode = (_decode) => decode = _decode registerRequestHandler((req, res, next) => { if (req.method !== 'POST' || req.url !== '/api') { next() return } parseBody(req, (err, buffer) => { if (err) { console.error('err', err) res.statusCode = 500 res.end() return } const {method, params} = decode(buffer) const methodHandler = methodHandlers[method] if (typeof methodHandler === 'function') { methodHandler(params, (err, result) => { const status = err ? err.message : 'ok' sendResult(res, {method, params, status, result}) }) } else { sendResult(res, {method, params, status: 'method not found', result: null}) } }) }) const httpRequestHandler = (req, res, index = 0) => { if (index >= requestHandlers.length) { res.statusCode = 404 res.end() return } requestHandlers[index](req, res, () => httpRequestHandler(req, res, index + 1)) } module.exports = { registerEncode, registerDecode, registerMethodHandler, registerRequestHandler, httpRequestHandler }
/* eslint-disable react/jsx-no-target-blank */ /* eslint-disable jsx-a11y/anchor-is-valid */ /* eslint-disable jsx-a11y/alt-text */ import React, { Component } from 'react'; import './Project.css' export default class Project5 extends Component { render () { const props = this.props return ( <div className="container-fluid text-center"> <div className="card card-inverse view overlay animatedLoad" style={{animationDelay: '1.75s'}}> <img className="card-img card-img-top" src={props.imgUrl} style={{width:' 154%', marginLeft: '-32%'}} /> <div className="card-img-overlay" style={{backgroundColor: '#2beeb6'}}> <div className="vertical-align-center"> <h2 className="text-center display-4 project-name">{props.projectName}</h2> <p className="text-center lead project-about">{props.aboutProject}</p> <div className="buttons"> <a className="button" target="_blank" href={props.projectSource}>SOURCE</a> <a className="button" target="_blank" href={props.projectDemo}>DEMO</a> </div> </div> </div> </div> </div> ) } }