text
stringlengths
7
3.69M
//'-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# //' Loja Exemplo Locaweb //' Versão: 6.2 //' Data: 12/09/06 //' Arquivo: funcoes_js.js //' Versão do arquivo: 0.2 //' Data da ultima atualização: 31/05/07 //' //'----------------------------------------------------------------------------- //' Licença Código Livre: http://comercio.locaweb.com.br/gpl/gpl.txt //'-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# //# FUNCOES CEP //################################################################################### function disable_form() { document.frm.cep.disabled = false; document.frm.cep.value = ''; } //################################################################################### function mostraiframe(linha) { var linha = document.getElementById(linha); if (linha.style.display=='none') { linha.style.display=''; } else { linha.style.display='none'; } } //################################################################################### function alteraiframe(linha,acao) { var linha = document.getElementById(linha); if (acao=='exibe') { linha.style.display=''; } else { linha.style.display='none'; } } //################################################################################### function enable_form() { document.frm.cep.disabled = false; } //################################################################################### function pesquisar_cep(pais,cep,pesofrete) { var tempIFrame=document.createElement('iframe'); tempIFrame.setAttribute('id','iframe_cep'); tempIFrame.setAttribute('name','iframe_cep'); tempIFrame.style.border = '0px'; tempIFrame.style.width = '0px'; tempIFrame.style.height = '0px'; tempIFrame.setAttribute('src','cep_frete.asp?pais='+pais+'&cep='+cep+'&pesofrete='+pesofrete); IFrameObj = document.body.appendChild(tempIFrame); } //################################################################################### function valida_pesquisar_cep() { // pais var DROPpais = document.frm.paises; var pais = DROPpais.options[DROPpais.selectedIndex].value; // cep var format_cep = document.frm.cep.value.replace("-", ""); if (pais == 'BR') { if (format_cep.length == 8){ executar_pesquisar_cep(); } else { alert(ValPesqCepALERTcepinvalido); document.frm.cep.focus(); } } else { executar_pesquisar_cep(); } } //################################################################################### function executar_pesquisar_cep() { // pais var DROPpais = document.frm.paises; var pais = DROPpais.options[DROPpais.selectedIndex].value; document.frmEditContact.pais_frete.value = pais; // cep var cep = document.frm.cep.value.replace("-", ""); //peso var peso = document.frm.pesofrete.value; pesquisar_cep(pais,cep,peso); } //################################################################################### function send_frete(string) { var vfrete = string.split('#'); SndFrtALERTopcaofrete = SndFrtALERTopcaofrete.replace("varOpcaoFrete", ""+vfrete[0])+""; SndFrtALERTopcaofrete = SndFrtALERTopcaofrete.replace("varValorFrete", ""+vfrete[1])+""; var conf_frete = confirm(SndFrtALERTopcaofrete) if (conf_frete==true) { document.frmEditContact.opcao_frete.value = vfrete[0]; document.frmEditContact.frete.value = vfrete[2]; document.frmEditContact.cep_frete.value = vfrete[3]; document.frmEditContact.submit(); } } //################################################################################### function handleResponse(informacoes) { ///////////////////// var tbl = document.getElementById('freteTable'); var lastRow = tbl.rows.length; if (lastRow > 0) tbl.deleteRow(lastRow - 1); if (informacoes != 0) { var verify_informacoes = informacoes.indexOf("#"); if (verify_informacoes>=0) { var CEP = document.frm.cep.value; var textoCEP = document.frm.textocep.value; var x=document.getElementById('freteTable').insertRow(0); var y=x.insertCell(0); y.innerHTML="<table id='"+ CEP +"' border='0' width='100%' cellpadding='0' cellspacing='2'></table>"; ///////////////////// var array_informacoes = informacoes.split("#"); var x=document.getElementById(CEP).insertRow(0); var y=x.insertCell(0); x.height="25" x.bgColor="#FEE247" y.innerHTML='<b>&nbsp;&nbsp;&nbsp;' + textoCEP + " " + CEP + ':</b>' ; var part_num=0; var count = 0; var mod = 0; var color; while (part_num < array_informacoes.length) { if (mod==0) { mod = 1; color = '#FFFFFF'; } else { mod = 0; color = '#F5F5F5'; } var array_frete = array_informacoes[part_num].split(":"); if (array_frete[2] != "ok") { // Insere o option na tabela var nRows=document.getElementById(CEP).rows.length var x=document.getElementById(CEP).insertRow(nRows) var y=x.insertCell(0) y.innerHTML= array_frete[0] + ": " + array_frete[2] count+=1; } else { if (array_frete[1] != "vazio") { //Trata o valor do frete conforme a moeda utilizada var verify_vlrFRETE = array_frete[1].indexOf("|"); if (verify_vlrFRETE>=0) { var vlrFRETE = array_frete[1].split("|"); var vlrFRETE_REAL = vlrFRETE[0]; var vlrFRETE_VIS = vlrFRETE[1]; } else { var vlrFRETE_REAL = array_frete[1]; var vlrFRETE_VIS = array_frete[1]; } // Insere o option na tabela var x=document.getElementById(CEP).insertRow(1) var y=x.insertCell(0) x.height="10" x.bgColor=color y.innerHTML="<input type='radio' name='opcao' value='"+ array_frete[0] + "#" + vlrFRETE_VIS + "#" + vlrFRETE_REAL + "#" + CEP + "' onclick='send_frete(this.value);'>" + array_frete[0] + " ( " + vlrFRETE_VIS + " )" count+=1; } } part_num+=1; } if (count == 0) { var x=document.getElementById('freteTable').insertRow(0) var y=x.insertCell(0) y.innerHTML=HndRespALERTsemfrete } enable_form(); } else { var vfrete = informacoes.split(":"); if (vfrete[2] != "ok") { var CEP = document.frm.cep.value; var textoCEP = document.frm.textocep.value; var x=document.getElementById('freteTable').insertRow(0); var y=x.insertCell(0); y.innerHTML="<table id='"+ CEP +"' border='0' width='100%' cellpadding='0' cellspacing='2'></table>"; var x=document.getElementById(CEP).insertRow(0); var y=x.insertCell(0); x.height="25" x.bgColor="#FEE247" y.innerHTML='<b>&nbsp;&nbsp;&nbsp;' + textoCEP + " " + CEP + ':</b>' ; // Insere o option na tabela var x=document.getElementById(CEP).insertRow(1) var y=x.insertCell(0) y.innerHTML= vfrete[0] + ": " + vfrete[2] count+=1; } else { //Trata o valor do frete conforme a moeda utilizada var verify_vlrFRETE = vfrete[1].indexOf("|"); if (verify_vlrFRETE>=0) { var vlrFRETE = vfrete[1].split("|"); var vlrFRETE_REAL = vlrFRETE[0]; var vlrFRETE_VIS = vlrFRETE[1]; } else { var vlrFRETE_REAL = vfrete[1]; var vlrFRETE_VIS = vfrete[1]; } document.frmEditContact.opcao_frete.value = vfrete[0]; document.frmEditContact.frete.value = vlrFRETE_REAL; document.frmEditContact.cep_frete.value = document.frm.cep.value; document.frmEditContact.submit(); } } } else { disable_form(); document.frm.cep.disabled = false; var x=document.getElementById('freteTable').insertRow(0) var y=x.insertCell(0) y.innerHTML=HndRespALERTsemfrete } } //################################################################################### function mostra_cep() { Form = document.carrinho; if ( (Form.cep1.value.length == 5) && (checatab) ) { Form.cep2.focus(); checatab=false; } } //################################################################################### /*VERIFICA*/ function cadastro_cep_verificar(cep){ if (!alterado_cep) { alterado_cep = true; document.all.cep.focus(); document.all.numero.value = ''; document.all.complemento.value = ''; } } //################################################################################### function check_meiopag(opcaopag){ var fr = document.OpcaoPag; for(a=0;a<fr.elements.length;a++){ if(fr.elements[a].value == opcaopag){ fr.elements[a].checked = true; } } } //# FUNCOES LOJA //################################################################################### var isNN = (navigator.appName.indexOf("Netscape")!=-1); function autoTab(input,len, e) { var keyCode = (isNN) ? e.which : e.keyCode; var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46]; if(input.value.length >= len && !containsElement(filter,keyCode)) { input.value = input.value.slice(0, len); input.form[(getIndex(input)+1) % input.form.length].focus(); } function containsElement(arr, ele) { var found = false, index = 0; while(!found && index < arr.length) if(arr[index] == ele) found = true; else index++; return found; } function getIndex(input) { var index = -1, i = 0, found = false; while (i < input.form.length && index == -1) if (input.form[i] == input)index = i; else i++; return index; } return true; } //################################################################################### function remover_produto(nome) { eval("document.carrinho."+nome+".value = 0"); // estamos zerando o carrinho. document.carrinho.submit (); } //################################################################################### function atualizar_carrinho() { var resposta, Form; Form = document.carrinho; resposta = true; if (Form.tipofrete.value == "SEDEX" && (Form.cep1.value.length != 0 || Form.cep2.value.length != 0)) { resposta = valida_cep(); } if (resposta == true) document.carrinho.submit (); } //################################################################################### function calcular_frete() { var resposta; resposta = valida_cep(); if (resposta == true) document.carrinho.submit (); } //################################################################################### function mostra_calculo_frete() { var Form; Form = document.pagamento; janela = window.open('calculo_frete.asp?valor=' + Form.subtotal.value + '&frete=' + Form.taxa_envio.value + '&cepdestino=' + Form.cep.value + '&peso=' + Form.peso.value + '&tipo_sedex=' + Form.tipo_sedex.value,'promocao','width=600,height=250,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes') if (janela != null) { janela.location.href ='calculo_frete.asp?valor=' + Form.subtotal.value + '&frete=' + Form.taxa_envio.value + '&cepdestino=' + Form.cep.value + '&peso=' + Form.peso.value + '&tipo_sedex=' + Form.tipo_sedex.value } } //################################################################################### function metodo_pagamento(nome) { var carteira, i, sel, num_pag, temp, metodo_pag, ssl, acao; var Form; Form = document.carrinho; num_pag = document.pagamento.num_pagamentos.value; if (document.pagamento.tipo.value == false) { alert(MtdPagALERTselpag); return false; } if (document.pagamento.taxa_envio.value == 0 && !document.carrinho.frete_teste) { alert(MtdPagALERTcalcfrete); return false; } else { if (num_pag == "1") { temp = document.pagamento.tipo.value; acao = document.pagamento.URL_Autentica.value + "?acao=login" + "&forma_pagamento=" + metodo_pag; eval("document.pagamento.action='" + acao + "'"); document.pagamento.submit(); } else { for (i=0; i<num_pag; i++) { if (document.pagamento.tipo.value == true) { sel = i; break; } } temp = document.pagamento.tipo.value; } // VISA1 // VISA - VisaNet, 1 - com SSL metodo_pag = temp.substring(0,temp.length-1); if (metodo_pag == "AMEX" || metodo_pag == "AMEXPOS"|| metodo_pag == "REDECARD" || metodo_pag == "RCARDPOS"|| metodo_pag == "VISA" || metodo_pag == "VISAPOS") metodo_pag = "CARTAO"; ssl = temp.substring(temp.length-1,temp.length); if (ssl == "0") { acao = document.pagamento.URL_Autentica.value + "?acao=login" + "&forma_pagamento=" + metodo_pag; } else { acao = document.pagamento.URL_Autentica_seguro.value + "?acao=login" + "&forma_pagamento=" + metodo_pag; } if (metodo_pag == "CARTAO") { acao = acao + "&cartao=" + temp.substring(0,temp.length-1); } eval("document.pagamento.action='" + acao + "'"); document.pagamento.submit(); } } //################################################################################### function valida_busca() { Form = document.busca; if (Form.produto.value.length == 0) { alert(VldBuscaALERTcampobusca); Form.produto.focus(); return false; } if (Form.produto.value.length < 3) { alert(VldBuscaALERTminbusca); Form.produto.focus(); return false; } if (!Form.codigo_categoria) { alert(VldBuscaALERTexistecatbusca); return false; } if (Form.codigo_categoria.value == '') { alert(VldBuscaALERTcatbusca); Form.codigo_categoria.focus(); return false; } } //################################################################################### function valida_cep() { Form = document.carrinho; if (Form.cep1.value.length == 0) { alert(VldCepALERTcampocep); Form.cep1.focus(); return false; } if (Form.cep2.value.length == 0) { alert(VldCepALERTcampocep); Form.cep2.focus(); return false; } s = limpa_string(Form.cep1.value); if (s.length != 5) { alert(VldCepALERTcaractcep); Form.cep1.focus(); return false; } s = limpa_string(Form.cep2.value); if (s.length != 3) { alert(VldCepALERTcaractcep); Form.cep2.focus(); return false; } return true; } //################################################################################### function limpa_string(S){ // Deixa so' os digitos no numero var Digitos = "0123456789"; var temp = ""; var digito = ""; for (var i=0; i<S.length; i++){ digito = S.charAt(i); if (Digitos.indexOf(digito)>=0){temp=temp+digito} } return temp } //################################################################################### function mostra_cep() { Form = document.carrinho; if ( (Form.cep1.value.length == 5) && (checatab) ) { Form.cep2.focus(); checatab=false; } } //################################################################################### function semtab() { checatab=false; } function comtab() { checatab=true; } checatab=true; //################################################################################### function mostra_cep() { Form = document.carrinho; if ( (Form.cep1.value.length == 5) && (checatab) ) { Form.cep2.focus(); checatab=false; } } //################################################################################### function menu_goto( menuform ) { selecteditem = menuform.local_frete_Exporta.selectedIndex ; local_frete_Exporta = menuform.local_frete_Exporta.options[ selecteditem ].value ; if (local_frete_Exporta.length != 0) { location.href = local_frete_Exporta ; } } //################################################################################### function valida_cadastro(formname,tipoverif,cep_frete) { var Form; Form = formname; if (cep_frete == 'SEM FRETE') { if (tipoverif == 'CadPedido') { if ((valida_endereco(Form,'CadPedido') == false) || (valida_password(Form) == false)) { return false; } } else if (tipoverif == 'CadUsuario') { if (valida_endereco(Form,'CadUsuario') == false) { return false; } } } else { if ((valida_endereco(Form,'CadPedido') == false) || (valida_password(Form) == false) || (verifica_cep(cep_frete) == false)) { return false; } } } //################################################################################### function valida_password(Form) { if (Form.tipo_login.value == "user_new") { if (Form.senha1.value.length == 0 || Form.senha2.value.length == 0) { alert(VldPwdALERTcamposenha); Form.senha1.focus(); return false; } if (Form.senha1.value != Form.senha2.value) { alert(VldPwdALERTsenhadif); Form.senha1.focus(); return false; } } } //################################################################################### function valida_trocapassword(Form) { if (Form.senha_atual.value.length == 0) { alert(VldTrocaPwdALERTcamposenhaatual); Form.senha_atual.focus(); return false; } if (Form.nova_senha.value.length == 0 || Form.confirma_senha.value.length == 0) { alert(VldTrocaPwdALERTcamposenha); Form.nova_senha.focus(); return false; } if (Form.nova_senha.value != Form.confirma_senha.value) { alert(VldTrocaPwdALERTsenhadif); Form.nova_senha.focus(); return false; } } //################################################################################### function valida_faleconosco(Form) { if (Form.nome.value.length == 0) { alert(VldFaleConALERTcmpnome); Form.nome.focus(); return false; } if (Form.email.value.length == 0) { alert(VldFaleConALERTcmpemail); Form.email.focus(); return false; } if (Form.email.value.indexOf('@', 0) == -1 || Form.email.value.indexOf('.', 0) == -1) { alert(VldFaleConALERTcmpemailinc); Form.email.focus(); return false; } if (Form.assunto.value.length == 0) { alert(VldFaleConALERTcmpassunto); Form.assunto.focus(); return false; } if (Form.comentarios.value.length == 0) { alert(VldFaleConALERTcmpcomentario); Form.comentarios.focus(); return false; } return true; } //################################################################################### function valida_newsletter(Form) { if (Form.nome.value.length == 0) { alert(VldNewsALERTcmpnome); Form.nome.focus(); return false; } if (Form.email.value.length == 0) { alert(VldNewsALERTcmpemail); Form.email.focus(); return false; } if (Form.email.value.indexOf('@', 0) == -1 || Form.email.value.indexOf('.', 0) == -1) { alert(VldNewsALERTcmpemailinc); Form.email.focus(); return false; } return true; } //################################################################################### function valida_endereco(Form,tipoverif) { var s; if ((Form.tipcliente[0].checked==false) && (Form.tipcliente[1].checked==false)) { alert(VldEndALERTcmpfisjur); return false; } //Dados Cobrança if (valida_dadosCobranca(Form) == false) { return false; } //Confirma o tipo de verificação if (tipoverif == 'CadPedido') { // Dados Entrega if (Form.cobranca_diferente.checked==true) { if (valida_dadosEntrega(Form) == false) { return false; } } } else if (tipoverif == 'CadUsuario') { // Dados Entrega if (valida_dadosEntrega(Form) == false) { return false; } } } //################################################################################### function valida_dadosCobranca(Form) { var s; if (Form.tipcliente[1].checked==true) { if (Form.razaosocial_cobranca.value.length == 0) { alert(VldEndALERTcmprazaosocial); Form.razaosocial_cobranca.focus(); return false; } if (Form.pais_cobranca.options[Form.pais_cobranca.selectedIndex].value == "BR") { var cnpj_cob = Form.cnpj_cobranca_b1.value + Form.cnpj_cobranca_b2.value + Form.cnpj_cobranca_b3.value + Form.cnpj_cobranca_b4.value + Form.cnpj_cobranca_b5.value; if (cnpj_cob.length == 0) { alert(VldEndALERTcmpcnpj); Form.cnpj_cobranca_b1.focus(); return false; } s = limpa_string(cnpj_cob); if (s.length == 14) { if (valida_CNPJ(cnpj_cob) == false ) { alert(VldEndALERTcmpcnpjinc); Form.cnpj_cobranca_b1.focus(); return false; } }else{ alert(VldEndALERTcmpcnpjinc); Form.cnpj_cobranca_b1.focus(); return false; } Form.cnpj_cobranca.value = cnpj_cob; } } if (Form.nome_cobranca.value.length == 0) { alert(VldEndALERTcmpnome); Form.nome_cobranca.focus(); return false; } if (Form.pais_cobranca.options[Form.pais_cobranca.selectedIndex].value == "BR") { var cpf_cob = Form.cpf_cobranca_b1.value + Form.cpf_cobranca_b2.value + Form.cpf_cobranca_b3.value + Form.cpf_cobranca_b4.value; if (cpf_cob.length == 0) { alert(VldEndALERTcmpcpf); Form.cpf_cobranca_b1.focus(); return false; } s = limpa_string(cpf_cob); if (s.length == 11) { if (valida_CPF(cpf_cob) == false ) { alert(VldEndALERTcmpcpfinc); Form.cpf_cobranca_b1.focus(); return false; } }else{ alert(VldEndALERTcmpcpfinc); Form.cpf_cobranca_b1.focus(); return false; } Form.cpf_cobranca.value = cpf_cob; var rg_cob = Form.rg_cobranca_b1.value + Form.rg_cobranca_b2.value + Form.rg_cobranca_b3.value + Form.rg_cobranca_b4.value; if (rg_cob.length == 0) { alert(VldEndALERTcmprg); Form.rg_cobranca_b1.focus(); return false; } if (rg_cob.length == 9) { Form.rg_cobranca.value = '0' + rg_cob; } else { Form.rg_cobranca.value = rg_cob; } } if (Form.logradouro_cobranca.value.length == 0) { alert(VldEndALERTcmpend); Form.logradouro_cobranca.focus(); return false; } if (Form.numero_cobranca.value.length == 0) { alert(VldEndALERTcmpnum); Form.numero_cobranca.focus(); return false; } if (Form.pais_cobranca.options[Form.pais_cobranca.selectedIndex].value == "BR") { var cep_cob = Form.cep_cobranca_b1.value + Form.cep_cobranca_b2.value; if (cep_cob.length == 0) { alert(VldEndALERTcmpcep); Form.cep_cobranca_b1.focus(); return false; } s = limpa_string(cep_cob); if (s.length != 8) { alert(VldEndALERTcmptamcep); Form.cep_cobranca_b1.focus(); return false; } Form.cep_cobranca.value = cep_cob; } if (Form.cidade_cobranca.value.length == 0) { alert(VldEndALERTcmpcidade); Form.cidade_cobranca.focus(); return false; } if (Form.pais_cobranca.options[Form.pais_cobranca.selectedIndex].value == "BR") { if (Form.ddd_cobranca.value.length == 0) { alert(VldEndALERTcmpddd); Form.ddd_cobranca.focus(); return false; } } if (Form.telefone_cobranca.value.length == 0) { alert(VldEndALERTcmptel); Form.telefone_cobranca.focus(); return false; } Form.data_nascimento_cobranca.value = Form.data_nascimento_cobranca_b1.value + Form.data_nascimento_cobranca_b2.value + Form.data_nascimento_cobranca_b3.value; } //################################################################################### function valida_dadosEntrega(Form) { var s; if (Form.tipcliente[1].checked==true) { if (Form.razaosocial_entrega.value.length == 0) { alert(VldEndALERTcmprazaosocial); Form.razaosocial_entrega.focus(); return false; } if (Form.pais_entrega.options[Form.pais_entrega.selectedIndex].value == "BR") { var cnpj_ent = Form.cnpj_entrega_b1.value + Form.cnpj_entrega_b2.value + Form.cnpj_entrega_b3.value + Form.cnpj_entrega_b4.value + Form.cnpj_entrega_b5.value; if (cnpj_ent.length == 0) { alert(VldEndALERTcmpcnpj); Form.cnpj_entrega_b1.focus(); return false; } s = limpa_string(cnpj_ent); if (s.length == 14) { if (valida_CNPJ(cnpj_ent) == false ) { alert(VldEndALERTcmpcnpjinc); Form.cnpj_entrega_b1.focus(); return false; } }else{ alert(VldEndALERTcmpcnpjinc); Form.cnpj_entrega_b1.focus(); return false; } Form.cnpj_entrega.value = cnpj_ent; } } if (Form.nome_entrega.value.length == 0) { alert(VldEndALERTcmpnome); Form.nome_entrega.focus(); return false; } if (Form.pais_entrega.options[Form.pais_entrega.selectedIndex].value == "BR") { var cpf_ent = Form.cpf_entrega_b1.value + Form.cpf_entrega_b2.value + Form.cpf_entrega_b3.value + Form.cpf_entrega_b4.value; if (cpf_ent.length == 0) { alert(VldEndALERTcmpcpf); Form.cpf_entrega_b1.focus(); return false; } s = limpa_string(cpf_ent); if (s.length == 11) { if (valida_CPF(cpf_ent) == false ) { alert(VldEndALERTcmpcpfinc); Form.cpf_entrega_b1.focus(); return false; } }else{ alert(VldEndALERTcmpcpfinc); Form.cpf_entrega_b1.focus(); return false; } Form.cpf_entrega.value = cpf_ent; var rg_ent = Form.rg_entrega_b1.value + Form.rg_entrega_b2.value + Form.rg_entrega_b3.value + Form.rg_entrega_b4.value; if (rg_ent.length == 0) { alert(VldEndALERTcmprg); Form.rg_entrega_b1.focus(); return false; } if (rg_ent.length == 9) { Form.rg_entrega.value = '0' + rg_ent; } else { Form.rg_entrega.value = rg_ent; } } if (Form.logradouro_entrega.value.length == 0) { alert(VldEndALERTcmpend); Form.logradouro_entrega.focus(); return false; } if (Form.numero_entrega.value.length == 0) { alert(VldEndALERTcmpnum); Form.numero_entrega.focus(); return false; } if (Form.pais_entrega.options[Form.pais_entrega.selectedIndex].value == "BR") { var cep_ent = Form.cep_entrega_b1.value + Form.cep_entrega_b2.value; if (cep_ent.length == 0) { alert(VldEndALERTcmpcep); Form.cep_entrega_b1.focus(); return false; } s = limpa_string(cep_ent); if (s.length != 8) { alert(VldEndALERTcmptamcep); Form.cep_entrega_b1.focus(); return false; } Form.cep_entrega.value = cep_ent; } if (Form.cidade_entrega.value.length == 0) { alert(VldEndALERTcmpcidade); Form.cidade_entrega.focus(); return false; } if (Form.telefone_entrega.value.length == 0) { alert(VldEndALERTcmptel); Form.telefone_entrega.focus(); return false; } if (Form.pais_entrega.options[Form.pais_entrega.selectedIndex].value == "BR") { if (Form.ddd_entrega.value.length == 0) { alert(VldEndALERTcmpddd); Form.ddd_entrega.focus(); return false; } } if (Form.email_entrega.value.length == 0) { alert(VldEndALERTcmpemail); Form.email_entrega.focus(); return false; } if (Form.email_entrega.value.indexOf('@', 0) == -1 || Form.email_entrega.value.indexOf('.', 0) == -1) { alert(VldEndALERTcmpemailinc); Form.email_entrega.focus(); return false; } Form.data_nascimento_entrega.value = Form.data_nascimento_entrega_b1.value + Form.data_nascimento_entrega_b2.value + Form.data_nascimento_entrega_b3.value; } //################################################################################### function valida_cartao(Form) { var s; s = limpa_string(Form.ccn.value); if (s.length != 16) { alert(VldCartaoALERTcmptamnumcartao); Form.ccn.focus(); return false; } if (Form.ccn.value.length == 0) { alert(VldCartaoALERTcmpnumcartao); Form.ccn.focus(); return false; } if (Form.exp.value.length == 0) { alert(VldCartaoALERTcmpdataval); Form.exp.focus(); return false; } if (Form.cvv2.value.length == 0) { alert(VldCartaoALERTcmpcodseg); Form.cvv2.focus(); return false; } return true; } //################################################################################### function valida_visa() { if (valida_endereco() == true) { document.Endereco.submit(); } else return; } //################################################################################### function limpa_string(S){ // Deixa so' os digitos no numero var Digitos = "0123456789"; var temp = ""; var digito = ""; for (var i=0; i<S.length; i++){ digito = S.charAt(i); if (Digitos.indexOf(digito)>=0){temp=temp+digito} } return temp } //################################################################################### function valida_CPF(s) { var i; s = limpa_string(s); var c = s.substr(0,9); var dv = s.substr(9,2); var d1 = 0; for (i = 0; i < 9; i++) { d1 += c.charAt(i)*(10-i); } if (d1 == 0) return false; d1 = 11 - (d1 % 11); if (d1 > 9) d1 = 0; if (dv.charAt(0) != d1) { return false; } d1 *= 2; for (i = 0; i < 9; i++) { d1 += c.charAt(i)*(11-i); } d1 = 11 - (d1 % 11); if (d1 > 9) d1 = 0; if (dv.charAt(1) != d1) { return false; } return true; } //################################################################################### function valida_CNPJ(s) { var i; s = limpa_string(s); var c = s.substr(0,12); var dv = s.substr(12,2); var d1 = 0; for (i = 0; i < 12; i++) { d1 += c.charAt(11-i)*(2+(i % 8)); } if (d1 == 0) return false; d1 = 11 - (d1 % 11); if (d1 > 9) d1 = 0; if (dv.charAt(0) != d1) { return false; } d1 *= 2; for (i = 0; i < 12; i++) { d1 += c.charAt(11-i)*(2+((i+1) % 8)); } d1 = 11 - (d1 % 11); if (d1 > 9) d1 = 0; if (dv.charAt(1) != d1) { return false; } return true; } //################################################################################### function valida_numeros(s) { var i; var dif = 0; for (i = 0; i < s.length; i++) { var c = s.charAt(i); if (!((c >= "0") && (c <= "9"))) { dif = 1; } } if (dif == 1) { return false; } return true; } //################################################################################### function copia_entrega(){ var n=''; var v=''; var s=''; var i=0; var form=document.Endereco; var x=form.length-1; if(form.cobranca_igual.checked){ for(var y = 0; y <= x; y++){ n=form.elements[y].name; if(n.substring(0,2)=='b_'){ s=n.substring(2,n.length); if(form.elements[s].type == "select-one"){ i=form.elements[s].selectedIndex; form.elements[n].selectedIndex=i; } else{ v=form.elements[s].value; form.elements[n].value=v; } } } } } //################################################################################### function mostradados(pri) { var element = document.getElementById(pri); if (element.style.display=='none') { element.style.display=''; } else { element.style.display='none' } } //################################################################################### function reenvio_pwd() { var fr = document.autent; if (fr.esquecisenha.checked == true) { fr.senha.disabled = true; fr.senha.value = ''; fr.enviar.value = RnvPwdALERTreenvsenha; } else { fr.senha.disabled = false; fr.enviar.value = RnvPwdALERTautentusuario; } } //################################################################################### function check_login() { var fr = document.autent; if (fr.user_id.value.length == 0) { alert(CkLoginALERTcmpemail); fr.user_id.focus(); return false; } if (fr.user_id.value.indexOf('@', 0) == -1 || fr.user_id.value.indexOf('.', 0) == -1) { alert(CkLoginALERTcmpemailinc); fr.user_id.focus(); return false; } if (fr.esquecisenha.checked == false) { if (fr.senha.value.length == 0) { alert(CkLoginALERTcmpsenha); fr.senha.focus(); return false; } } return true; } //################################################################################### function check_newlogin() { var fr = document.new_user; if (fr.user_id.value.length == 0) { alert(CkNwLoginALERTcmpemail); fr.user_id.focus(); return false; } if (fr.user_id.value.indexOf('@', 0) == -1 || fr.user_id.value.indexOf('.', 0) == -1) { alert(CkNwLoginALERTcmpemailinc); fr.user_id.focus(); return false; } return true; } //################################################################################### function alteraTipCad() { var tipCadTextCob = document.getElementById('tipCadTextJuridico_cobranca'); var tipCadInputCob = document.getElementById('tipCadInputJuridico_cobranca'); var tipCadTextEnt = document.getElementById('tipCadTextJuridico_entrega'); var tipCadInputEnt = document.getElementById('tipCadInputJuridico_entrega'); var tipCadTextCob2 = document.getElementById('tipCadTextJuridico2_cobranca'); var tipCadInputCob2 = document.getElementById('tipCadInputJuridico2_cobranca'); var tipCadTextEnt2 = document.getElementById('tipCadTextJuridico2_entrega'); var tipCadInputEnt2 = document.getElementById('tipCadInputJuridico2_entrega'); if (document.Endereco.tipcliente[0].checked == true) { tipCadTextCob.style.display='none'; tipCadInputCob.style.display='none'; tipCadTextEnt.style.display='none'; tipCadInputEnt.style.display='none'; tipCadTextCob2.style.display='none'; tipCadInputCob2.style.display='none'; tipCadTextEnt2.style.display='none'; tipCadInputEnt2.style.display='none'; document.getElementsByName('razaosocial_cobranca')[0].value =''; document.getElementsByName('cnpj_cobranca_b1')[0].value =''; document.getElementsByName('cnpj_cobranca_b2')[0].value =''; document.getElementsByName('cnpj_cobranca_b3')[0].value =''; document.getElementsByName('cnpj_cobranca_b4')[0].value =''; document.getElementsByName('cnpj_cobranca_b5')[0].value =''; document.getElementsByName('inscricaoestadual_cobranca')[0].value =''; document.getElementsByName('razaosocial_entrega')[0].value =''; document.getElementsByName('cnpj_entrega_b1')[0].value =''; document.getElementsByName('cnpj_entrega_b2')[0].value =''; document.getElementsByName('cnpj_entrega_b3')[0].value =''; document.getElementsByName('cnpj_entrega_b4')[0].value =''; document.getElementsByName('cnpj_entrega_b5')[0].value =''; document.getElementsByName('inscricaoestadual_entrega')[0].value =''; } else { tipCadTextCob.style.display=''; tipCadInputCob.style.display=''; tipCadTextEnt.style.display=''; tipCadInputEnt.style.display=''; tipCadTextCob2.style.display=''; tipCadInputCob2.style.display=''; tipCadTextEnt2.style.display=''; tipCadInputEnt2.style.display=''; } } //################################################################################### function checkTipCad(tipoEnd) { var verificacao; if (document.getElementsByName('razaosocial_'+tipoEnd)[0].value != '') { verificacao = true; } else { verificacao = false; } var tipCadText = document.getElementById('tipCadTextJuridico_'+tipoEnd); var tipCadInput = document.getElementById('tipCadInputJuridico_'+tipoEnd); var tipCadText2 = document.getElementById('tipCadTextJuridico2_'+tipoEnd); var tipCadInput2 = document.getElementById('tipCadInputJuridico2_'+tipoEnd); if (verificacao == false) { tipCadText.style.display='none'; tipCadInput.style.display='none'; tipCadText2.style.display='none'; tipCadInput2.style.display='none'; document.getElementsByName('razaosocial_'+tipoEnd)[0].value =''; document.getElementsByName('cnpj_'+tipoEnd+'_b1')[0].value =''; document.getElementsByName('cnpj_'+tipoEnd+'_b2')[0].value =''; document.getElementsByName('cnpj_'+tipoEnd+'_b3')[0].value =''; document.getElementsByName('cnpj_'+tipoEnd+'_b4')[0].value =''; document.getElementsByName('cnpj_'+tipoEnd+'_b5')[0].value =''; document.getElementsByName('inscricaoestadual_'+tipoEnd)[0].value =''; } else { tipCadText.style.display=''; tipCadInput.style.display=''; tipCadText2.style.display=''; tipCadInput2.style.display=''; } } //################################################################################### function verifica_cep(cep_frete){ if (document.Endereco.tipo_acesso.value != "conta"){ if (document.Endereco.cobranca_diferente.checked == true){ if (cep_frete != document.Endereco.cep_entrega.value) { resposta = confirm(VrfCepALERTcepentdif); if (resposta == false) { return false; } else { document.frmEditContact.mode.value='changeItem'; document.frmEditContact.cep_frete.value=document.Endereco.cep_entrega.value; document.frmEditContact.submit(); return false; } } } else { if (cep_frete != document.Endereco.cep_cobranca.value) { resposta = confirm(VrfCepALERTcepentcobdif); if (resposta == false) { return false; } else { document.frmEditContact.mode.value='changeItem'; document.frmEditContact.cep_frete.value=document.Endereco.cep_cobranca.value; document.frmEditContact.submit(); return false; } } } } } //################################################################################### function pagamento() { vpos=window.open('','vpos','toolbar=yes,menubar=yes,resizable=yes,status=no,scrollbars=yes,width=600,height=400'); document.pagamento.submit(); } //################################################################################### function JanelaNova(URLBoleto) { window.open(URLBoleto,'NOME','width=680,height=400,menubar,scrollbars,resizable'); } //################################################################################### function Start(VarForm,x,y) { vpos = window.open('','vpos','toolbar=no,menubar=no,resizable=yes,status=no,scrollbars=yes,width='+ x +',height='+ y +''); document.abnfinanc.submit(); } //################################################################################### function submit_bradesco(metodo_pag) { Form = document.Confirmacao; if (metodo_pag == "cc") { eval("Form.action='inicia_transacao.asp?metodo_pag=CC'"); } else if (metodo_pag == "transfer") { eval("Form.action='inicia_transacao.asp?metodo_pag=TRANSFER'"); } else if (metodo_pag == "financiamento") { eval("Form.action='inicia_transacao.asp?metodo_pag=FINANCIAMENTO'"); } document.Confirmacao.submit(); } //################################################################################### // formata data function formata_data(formato, keypress, objeto) { campo = eval (objeto); if (formato=='DATA'){ separador = '/'; conjunto1 = 2; conjunto2 = 5; } if (campo.value.length == conjunto1){ campo.value = campo.value + separador; } if (campo.value.length == conjunto2){ campo.value = campo.value + separador; } } //################################################################################### function mostraCarrinho(pri) { var textview = document.getElementById(pri); if (textview.style.display=='none') { textview.style.display=''; } else { textview.style.display='none'; } } //################################################################################### function PopUp(theURL,winName,features) { window.open(theURL,winName,features); } //################################################################################### function check_opcaopag() { var fr = document.OpcaoPag; var check = false; for(a=0;a<fr.elements.length;a++){ if(fr.elements[a].name == 'tipo'){ if (fr.elements[a].checked == true) { check = true; break; } } } if (check == false) { alert(CkOpPagALERTselpag); } else { fr.submit(); } } //################################################################################### function valida_VisaMoset(Form) { if (Form.ccn.value.length == 0) { alert(VldMosetALERTcmpnumcartao); Form.ccn.focus(); return false; } if (Form.email.value.length == 0) { alert(VldMosetALERTcmpemail); Form.email.focus(); return false; } if (Form.email.value.indexOf('@', 0) == -1 || Form.email.value.indexOf('.', 0) == -1) { alert(VldMosetALERTcmpemailinc); Form.email.focus(); return false; } if (Form.assunto.value.length == 0) { alert(VldMosetALERTcmpassunto); Form.assunto.focus(); return false; } if (Form.comentarios.value.length == 0) { alert(VldMosetALERTcmpcomentario); Form.comentarios.focus(); return false; } return true; } //################################################################################### function fncLimpaValue(objTexto, sString) { if (sString == objTexto.value) { objTexto.value = ''; } } //################################################################################### function fncPreencheValue(objTexto, sString) { if (objTexto.value == '') { objTexto.value = sString; } } //################################################################################### function atualiza_carrinho(tip) { var fr = document.frmEditContact; var qte_elements = 0; var liberado = true; var qte_escolhida, qte_atual, qte_maxima; var qte_diferenca; for (a=0;a<fr.elements.length;a++) { if(fr.elements[a].name == 'quantidade_produto') { qte_elements = qte_elements + 1; } } qte_elements = (qte_elements - 1); if (qte_elements>=1) { for (i=0;i<=qte_elements;i++) { qte_escolhida = fr.quantidade_produto[i].value; qte_atual = fr.quantidade_atual[i].value; qte_maxima = fr.quantidade_maxima[i].value qte_diferenca = qte_escolhida - qte_atual; var qte_tratada = String(qte_diferenca); if (qte_tratada.indexOf('-') == -1) { qte_tratada = Number(qte_tratada); if ((qte_tratada > qte_maxima) && (qte_maxima != 0)) { alert(AtzCarALERTqtdestoque); fr.quantidade_produto[i].focus(); liberado = false; break; } if ((qte_escolhida > qte_maxima) && (qte_maxima == 0) && (qte_tratada != 0)) { alert(AtzCarALERTqtdestoque); fr.quantidade_produto[i].focus(); liberado = false; break; } } } } else { qte_escolhida = fr.quantidade_produto.value; qte_atual = fr.quantidade_atual.value; qte_maxima = fr.quantidade_maxima.value qte_diferenca = qte_escolhida - qte_atual; var qte_tratada = String(qte_diferenca); if (qte_tratada.indexOf('-') == -1) { qte_tratada = Number(qte_tratada); if ((qte_tratada > qte_maxima) && (qte_maxima != 0)) { alert(AtzCarALERTqtdestoque); fr.quantidade_produto.focus(); liberado = false; } if ((qte_escolhida > qte_maxima) && (qte_maxima == 0) && (qte_tratada != 0)) { alert(AtzCarALERTqtdestoque); fr.quantidade_produto.focus(); liberado = false; } } } if (liberado == true) { if (tip == 'frete') { valida_pesquisar_cep(); } else { document.forms(2).submit(); } } } //################################################################################### function valida_indique() { Form = document.indique; if (Form.Nome_AmigoIndicador.value.length == 0) { alert(VldIndALERTcmpnome); Form.Nome_AmigoIndicador.focus(); return false; } if (Form.Email_AmigoIndicador.value.length == 0) { alert(VldIndALERTcmpemail); Form.Email_AmigoIndicador.focus(); return false; } if (Form.Email_AmigoIndicador.value.indexOf('@', 0) == -1 || Form.Email_AmigoIndicador.value.indexOf('.', 0) == -1) { alert(VldIndALERTcmpemailinc); Form.Email_AmigoIndicador.focus(); return false; } if (Form.Nome_AmigoIndicado.value.length == 0) { alert(VldIndALERTcmpnome); Form.Nome_AmigoIndicado.focus(); return false; } if (Form.Email_AmigoIndicado.value.length == 0) { alert(VldIndALERTcmpemail); Form.Email_AmigoIndicado.focus(); return false; } if (Form.Email_AmigoIndicado.value.indexOf('@', 0) == -1 || Form.Email_AmigoIndicado.value.indexOf('.', 0) == -1) { alert(VldIndALERTcmpemailinc); Form.Email_AmigoIndicado.focus(); return false; } if (Form.comentario.value.length == 0) { alert(VldIndALERTcmpcomentario); Form.comentario.focus(); return false; } return true; } //###################################################################################
exports = module.exports = require('./lib/DateFormat.js');
import React, {Component} from 'react'; import {firebase, firebaseJerseys} from "../../../firebase"; import {firebaseLooper,reverseArray} from '../../ui/misc'; import ProductCard from '../../ui/product_card'; import Slide from 'react-reveal/Slide'; import {Promise} from "core-js"; class Blocks extends Component { state = { jerseys:[] }; componentDidMount() { firebaseJerseys.limitToLast(15).once('value').then(snapshot => { const jerseys = firebaseLooper(snapshot); let promises = []; for(let key in jerseys){ promises.push( new Promise((resolve,reject) => { firebase.storage().ref('jerseys') .child(jerseys[key].image).getDownloadURL() .then(url => { jerseys[key].url = url; resolve() }) }) ) } Promise.all(promises).then(() => { this.setState({ jerseys: reverseArray(jerseys) }); }) }) } showJerseys = (jerseys) => ( jerseys ? jerseys.map((jersey) => ( <Slide bottom key={jersey.id}> <div className="item"> <div className="wrapper"> <ProductCard jersey={jersey} /> </div> </div> </Slide> )) :null ); render() { return ( <div className="home_matches"> {this.showJerseys(this.state.jerseys)} </div> ); } } export default Blocks;
const BaseXform = require('../base-xform'); class RPrXform extends BaseXform { get tag() { return 'a:rPr'; } render(xmlStream, model) { xmlStream.leafNode(this.tag, { sz: model.size ? Math.floor(model.size * 100) : undefined, b: model.bold ? 1 : 0, i: model.italic ? 1 : 0, u: RPrXform.UnderlineAttributes[model.underline], }); } parseOpen(node) {} parseText() {} parseClose() {} } RPrXform.UnderlineAttributes = { false: 'none', true: 'sng', none: 'none', single: 'sng', double: 'dbl', heavy: 'heavy', words: 'words', }; module.exports = RPrXform;
import ExpoPixi, { PIXI } from 'expo-pixi'; export default async context => { //http://pixijs.io/examples/#/basics/basic.js const app = ExpoPixi.application({ context, }); const bg = await ExpoPixi.spriteAsync(require('../../assets/pixi/depth_blur_BG.png')); bg.width = app.renderer.width; bg.height = app.renderer.height; app.stage.addChild(bg); const littleDudes = await ExpoPixi.spriteAsync(require('../../assets/pixi/depth_blur_dudes.png')); littleDudes.x = app.renderer.width / 2 - 315; littleDudes.y = 200; app.stage.addChild(littleDudes); const littleRobot = await ExpoPixi.spriteAsync(require('../../assets/pixi/depth_blur_moby.png')); littleRobot.x = app.renderer.width / 2 - 200; littleRobot.y = 100; app.stage.addChild(littleRobot); const blurFilter1 = new PIXI.filters.BlurFilter(); const blurFilter2 = new PIXI.filters.BlurFilter(); littleDudes.filters = [blurFilter1]; littleRobot.filters = [blurFilter2]; let count = 0; app.ticker.add(function() { count += 0.005; const blurAmount = Math.cos(count); const blurAmount2 = Math.sin(count); blurFilter1.blur = 20 * blurAmount; blurFilter2.blur = 20 * blurAmount2; }); };
$(document).ajaxStart(function () { $("#load").show(); }); $(document).ajaxStop(function () { $("#load").hide(); }); $('#Logout').click(function () { $.ajax({ type: "POST", url: '/Account/Logout', success: function (result) { debugger; window.location.href = '/Account/Login' }, }); });
/* * Implement all your JavaScript in this file! */ var result={final:0,temp:0,opclick:0,op:0,opop:0}; $('.number').click(function(){ if(result.opclick>0){ $('#display').val($(this).val()); result.opclick=0; } else{ $('#display').val($('#display').val() + $(this).val()); } result.temp=$('#display').val(); }); $('.operator').click(function(){ result.opclick++; if($(this).attr('id')=="equalsButton"){ if(result.opclick<2){ result.op=result.opop; result.opclick--;/*result.opclick=1;*/} /*result.opclick-=2;*/} else{ result.temp=$('#display').val(); result.opop=$(this).attr('value');} if(result.opclick>1){ result.op=$(this).attr('value'); } if(result.opclick<2){ if(result.op>0){ if(result.op==1){ result.final=Number(result.final)+Number(result.temp); } if(result.op==2){ result.final=Number(result.final)-Number(result.temp); } if(result.op==3){ result.final=Number(result.final)*Number(result.temp); } if(result.op==4){ result.final=Number(result.final)/Number(result.temp); } } else{ result.final=$('#display').val(); result.opop=$(this).attr('value'); result.opclick=1; } $('#display').val(result.final); result.op=$(this).attr('value'); } }); $('#clearButton').click(function(){ $('#display').val(''); result.final=0; result.temp=0; result.op=0; result.opclick=0; result.opop=0; });
import React from 'react'; import { mount } from 'enzyme'; import { injectIntl } from '../lib/index.es.js'; describe('injectIntl HOC', () => { it('injects intl into component', () => { const Component = jest.fn(() => null); const EnhancedComponent = injectIntl(Component); mount(<EnhancedComponent intl={{ locale: 'en' }} />); expect(Component.mock.calls[0][0]).toHaveProperty('intl'); }); });
var chai = require('chai'); var assert = chai.assert; var sumPrimes = require('../src/sumPrimes'); it('sumPrimes', function() { assert.deepEqual(typeof sumPrimes(10), 'number', 'sumPrimes(10) should return a number.'); assert.deepEqual(sumPrimes(10), 17, 'sumPrimes(10) should return 17.'); assert.deepEqual(sumPrimes(977), 73156, 'sumPrimes(977) should return 73156.'); });
/* * Copyright (C) 2009-2017 SAP SE or an SAP affiliate company. All rights reserved. */ sap.ui.define([ "fin/re/conmgmts1/controller/BaseController", "fin/re/conmgmts1/model/formatter" ], function(BaseController, formatter) { 'use strict'; return BaseController.extend('fin.re.conmgmts1.controller.reminderblocks.ReminderPopoverList', { formatter: formatter, onInit: function() { this._showCompletedReminders = false; }, onAfterRendering: function() { this._rebindTable(); }, _rebindTable: function() { var viewId = this.getView().getId(); var reminderList = sap.ui.getCore().byId(viewId + "--" + "reminderListPopover"); var filters; if (this._showCompletedReminders) { filters = []; } else { filters = [new sap.ui.model.Filter("Rsdone", sap.ui.model.FilterOperator.EQ, "false")]; } var oBinding = reminderList.getBinding("items"); oBinding.filter(filters); }, formatterForTranslatedReminderTitle: function(done, daysLeft) { var title = formatter.reminderTitle(done, daysLeft); return this.getModel("i18n").getResourceBundle().getText(title); }, onDoneButtonPressed: function(event) { event.preventDefault(); var id = event.getSource().getId(); sap.ui.getCore().byId(id.replace("doneButton", "commentDisplayArea")).setVisible(false); var editArea = sap.ui.getCore().byId(id.replace("doneButton", "editArea")); editArea.setVisible(true); }, enableDoneButton: function(done) { return !done; }, onSaveButtonPressed: function(event) { //event.preventDefault(); //event.getSource().getBindingContext().getObject.Rsdone = true;//('Rsdone', true); var that = this; var sPath = event.getSource().getBindingContext().sPath; var oData = event.getSource().getBindingContext().getObject(); oData.Rsdone = true; this.getView().getModel().update(sPath, oData, { merge: false, success: function() { that.getView().getModel().resetChanges(); } }); var id = event.getSource().getId(); var editArea = sap.ui.getCore().byId(id.replace("saveButton", "editArea")); editArea.setVisible(false); var commentDisplayArea = sap.ui.getCore().byId(id.replace("saveButton", "commentDisplayArea")); commentDisplayArea.setVisible(true); var doneButton = sap.ui.getCore().byId(id.replace("saveButton", "doneButton")); doneButton.setVisible(false); }, onCancelButtonPressed: function(event) { this.getView().getModel().resetChanges(); var id = event.getSource().getId(); var editArea = sap.ui.getCore().byId(id.replace("cancelButton", "editArea")); editArea.setVisible(false); var doneButton = sap.ui.getCore().byId(id.replace("cancelButton", "commentDisplayArea")); doneButton.setVisible(true); }, onReminderFilterSelection: function(oEvent) { var key = oEvent.getSource().getSelectedKey(); if (key === "all") { this._showCompletedReminders = true; } else { this._showCompletedReminders = false; } this._rebindTable(); } }); });
/*! * jQuery MediaElementJS Wrapper for RND15 * * @author Jeremy P. * @date 9 Jan 2015 */ ;(function ( $ ) { // Create the plugin name and defaults once var pluginName = "mediaVideo", defaults = { played : 0, type : 'inline', rowSelector : '.cr-content-region', mediaElementOptions: { // Always show controls even if cursor is not over video alwaysShowControls : false, // force iPad's native controls iPadUseNativeControls: true,     // force iPhone's native controls     iPhoneUseNativeControls: true,     // force Android's native controls     AndroidUseNativeControls: true, plugins : ['youtube'], // Prevent the video from looping loop: false, // These are the youtube player vars, specific vars we can pass into the iframe youTubePlayerVars : {autoplay: 1, loop: 0, modestbranding: 1, playsinline: 0, showinfo: 0} } }; // The actual plugin constructor function Plugin( element, options ) { this.$element = $(element); /** * jQuery has an extend method that merges the * contents of two or more objects, storing the * result in the first object. The first object * is generally empty because we don't want to alter * the default options for future instances of the plugin */ this.options = $.extend( {}, defaults, options) ; this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { /** * Initialization logic here * We have access to the DOM element and * the options via the instance, e.g. this.$element * and this.options * you can add more functions like the one below and * call them like so: this.yourOtherFunction(this.$element, this.options). */ init: function() { /** * Declare properties */ this.youTubeUrl = this.$element.attr('href'); this.videoId = this.youTubeUrl ? youtube_parser(this.youTubeUrl) : ''; this.cssRowId = 'media-video-' + this.videoId + '-' + Math.floor(Math.random() * 10000); /** * Cache the elements we need to use */ this.$videoElement = $('video', this.$element); /** * Remove controls from video tag and change height to fix iPad issue that 'steal' our click events */ if(this.$videoElement.length) { this.$videoElement.removeAttr('controls').height(0).attr('height','0'); } /** * Handle logic for different types of players */ switch (this.options.type) { case 'row': this.setupPlayerInRow(); break; case 'inline': this.$startFrame = $('span[data-picture]', this.$element); this.$playButton = $('.media-video__overlay-button', this.$element); break; } /** * Add our main click event handler that triggers the player */ this.$element.on('click', {plugin:this}, this.handleElementClick); }, /** * Initialise the player */ initPlayer: function() { var plugin = this; /** * Add attributes back in case we have removed them */ plugin.$videoElement.attr('controls', 'controls').height('100%').attr('height', '100%'); /** * Suppress any automatic interactions on the site to help performance */ plugin.suppressAutoInteractions(); /** * Handle logic for different types of players */ switch (plugin.options.type) { case 'inline': plugin.hideStartFrame(); break; case 'row': plugin.displayPlayerInRow(); break; } /** * Make sure we pass in the success handler to the MEJS options */ plugin.options.mediaElementOptions.success = plugin.mediaElementJsSuccess; /** * Instantiate the mediaelementplayer and assign to plugin.player if it does not exist */ if(typeof plugin.player == 'undefined') { plugin.$videoElement.mediaelementplayer(plugin.options.mediaElementOptions); plugin.player = plugin.$videoElement[0].player; } }, /** * MEJS Success Handler * Allows us to add custom 'fake' events as per MEJS scripts once player has initialised */ mediaElementJsSuccess: function (mediaElement, domObject) { /** * Specificlayly Track all the events so we can * pass them to GTM's dataLayer */ mediaElement.addEventListener('loadedmetadata', mediaTrackVideo, false); mediaElement.addEventListener('play', mediaTrackVideo, false); mediaElement.addEventListener('playing', mediaTrackVideo, false); mediaElement.addEventListener('pause', mediaTrackVideo, false); mediaElement.addEventListener('ended', mediaTrackVideo, false); mediaElement.addEventListener('timeupdate', mediaTrackVideo, false); }, /** * Suppress any automatic interactions on the site */ suppressAutoInteractions: function() { /** * Pauses all Flexslider Slideshows */ if(typeof Drupal.settings.flexslider !== 'undefined' && typeof Drupal.settings.flexslider.instances !== 'undefined') { /** * Loop through the instances and use the instance name + hash to find the flexslider and pause it */ for(var instanceName in Drupal.settings.flexslider.instances) { if (typeof $('#'+instanceName).flexslider == 'undefined') return; $('#'+instanceName).flexslider('pause'); } } }, /** * Helper functions for the player */ /** * Hide the start frame and it's play button */ hideStartFrame: function() { var plugin = this; /** * Hide the start frame if it exists */ if(plugin.$startFrame.length) { plugin.$startFrame.add(plugin.$playButton).hide(); } }, /** * Hide the start frame and it's play button */ setupPlayerInRow: function() { var plugin = this; /** * Check if we have an existing player, if not create one on the fly */ var $rows = plugin.$element.parents(plugin.options.rowSelector); plugin.$row = $($rows[$rows.length - 1]); /** * Get the YouTube URL */ var youTubeUrl = plugin.$element.attr('href'); var closeButton = '<button class="media-video-row__btn-close btn icon icon--large icon-close-cross"><span>Close</span></button>'; /** * We dynamically insert the markup to make our video work in the row */ var videoElement = '<div class="media-video">' + '<div class="media-video__content mejs-wrapper">' + closeButton + '<video width="100%" height="100%">' + '<source type="video/youtube" src="' + youTubeUrl + '">' + '</video>' + '</div></div>'; /** * Prepend the markup to the row */ plugin.$row .prepend('<div class="media-video-row__wrapper" id="' + plugin.cssRowId + '">' + '<div class="container media-video-row__container">' + '<div class="row media-video-row media-video-row--vertically-centred"><div class="col-xs-12 media-video-row__pane">' + videoElement + '</div></div>' + '</div>' + '<div class="media-video-row__bg"></div>' + '</div>'); /** * Cache the references so we can apply event handlers and further work with these elements */ plugin.$mediaVideoRowWrapper = $('#' + plugin.cssRowId + '.media-video-row__wrapper', plugin.$row); plugin.$videoElement = $('video', plugin.$mediaVideoRowWrapper); plugin.$mediaVideoRowBackground = $('.media-video-row__bg', plugin.$mediaVideoRowWrapper); plugin.$mediaVideoRowCloseButton = $('.media-video-row__btn-close', plugin.$mediaVideoRowWrapper); }, /** * Display the Player In Row */ displayPlayerInRow: function() { var plugin = this; /** * Ensure we suppress any auto playing of slideshows */ plugin.suppressAutoInteractions(); /** * Add class to show the background and video markup */ plugin.$mediaVideoRowWrapper.addClass('media-video-row__wrapper--visible'); /** * Add Event Handlers */ plugin.$mediaVideoRowBackground.on('click', {plugin:plugin}, plugin.handleBackgroundClick); plugin.$mediaVideoRowCloseButton.on('click', {plugin:plugin}, plugin.handleCloseButtonClick); $(document).on('mediaelementjs.before.enterfullscreen', plugin.handleMeJSEnterFullScreen); $(document).on('mediaelementjs.before.exitfullscreen', plugin.handleMeJSExitFullScreen); }, /** * Hide the start frame and it's play button */ hidePlayerInRow: function() { var plugin = this; /** * Remove class to show the background and video markup */ plugin.$mediaVideoRowWrapper.removeClass('media-video-row__wrapper--visible'); /** * Remove Event Handlers */ plugin.$mediaVideoRowBackground.off('click', plugin.handleBackgroundClick); plugin.$mediaVideoRowCloseButton.off('click', plugin.handleCloseButtonClick); $(document).off('mediaelementjs.before.enterfullscreen', plugin.handleMeJSEnterFullScreen); $(document).off('mediaelementjs.before.exitfullscreen', plugin.handleMeJSExitFullScreen); /** * Pause the Player */ plugin.player.pause(); }, /** * Event handler to respond to the click event on the element (Start frame or link) * @param {object} e [click event object] */ handleElementClick: function(e) { e.data.plugin.initPlayer(); e.preventDefault(); }, /** * Event handler for row background * @param {object} e [click event object] */ handleBackgroundClick: function(e) { e.data.plugin.hidePlayerInRow(); e.preventDefault(); }, /** * Event handler for row close button * @param {object} e [click event object] */ handleCloseButtonClick: function(e) { e.data.plugin.hidePlayerInRow(); e.preventDefault(); }, /** * Handles the MEJS enter fullscreen event * Fixes an issue that is caused by vertically centering the video * @param {[type]} e [description] */ handleMeJSEnterFullScreen: function(e) { if(typeof e.mejs == 'undefined') return; $(e.mejs.container) .parents('.media-video-row') .removeClass('media-video-row--vertically-centred'); }, /** * Handles the MEJS exit fullscreen event * Fixes an issue that is caused by vertically centering the video * @param {[type]} e [description] */ handleMeJSExitFullScreen: function(e) { if(typeof e.mejs == 'undefined') return; $(e.mejs.container) .parents('.media-video-row') .addClass('media-video-row--vertically-centred'); } }; /* * A really lightweight plugin wrapper around the constructor, * protecting against multiple instantiations */ $.fn[pluginName] = function ( options ) { return this.each(function () { if (typeof options === "string") { var args = Array.prototype.slice.call(arguments, 1), plugin = $.data(this, 'plugin_' + pluginName); plugin[options].apply(plugin, args); } else if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); } }); }; })( jQuery ); /** * Track Video Helper Function */ var mediaTrackVideo = function(e) { if (!dataLayer) return; var YT = e.target.pluginApi; // Youtube Object var video_data = YT["getVideoData"](); var label = video_data.video_id+':'+video_data.title; var action = e.type; switch(e.type) { /** * Track the play event */ case 'play': // Increment the playCount e.target.playCount = typeof e.target.playCount === 'undefined' ? 0 : e.target.playCount + 1; // Track the first time play was triggered if(e.target.playCount === 0) { action = 'playfirst'; } break; /** * Track when certain playtimes have been met * e.g. 0%, 25%, 50%, 75% and 100% */ case 'timeupdate': var t = YT["getDuration"]() - YT["getCurrentTime"]() <= 1.5 ? 1 : (Math.floor(YT["getCurrentTime"]() / YT["getDuration"]() * 4) / 4).toFixed(2); if (!YT["lastP"] || t > YT["lastP"]) { YT["lastP"] = t; action = t * 100 + "%"; } else { // Skip, if we have not met a major milestone return; } break; } var videoEvent = { event: "rnd15.video", label: label, action: action, mejs: e.target, youtubeObject: YT }; // Push the event object to the dataLayer dataLayer.push(videoEvent); }; /** * Helper function to get the YouTube Video ID * http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url */ function youtube_parser(url){ var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; var match = url.match(regExp); if (match&&match[7].length==11){ return match[7]; }else{ if(typeof console.log !== 'undefined') { console.log('Could not retrieve Video ID from YouTube URL'); } } }
 angular.module('ngApp.timezone').controller('TimeZoneController', function ($scope, $state, $window, $location, $filter, $translate, TimeZoneService, SessionService, $uibModal, $log, uiGridConstants, toaster, ModalService) { //Set Multilingual for Modal Popup var setModalOptions = function () { $translate(['Timezone', 'DeleteHeader', 'This', 'DeleteBody', 'Detail', 'FrayteError', 'FrayteInformation', 'ErrorDeletingRecord', 'ErrorGetting', 'SuccessfullyDelete', 'Timezone', 'The', 'information']).then(function (translations) { $scope.headerTextTimezone = translations.Timezone + " " + translations.DeleteHeader; $scope.bodyTextTimezone = translations.DeleteBody + " " + translations.This + " " + translations.Timezone + " " + translations.Detail; $scope.TitleFrayteError = translations.FrayteError; $scope.TitleFrayteInformation = translations.FrayteInformation; $scope.TextErrorDeletingRecord = translations.ErrorDeletingRecord; $scope.TextErrorGettingTimeZoneRecord = translations.ErrorGetting + " " + translations.Timezone + " " + translations.records; $scope.TextSuccessfullyDelete = translations.SuccessfullyDelete + " " + translations.The + " " + translations.Timezone + " " + translations.information; }); }; $scope.AddEditTimeZone = function (row) { var modalInstance = $uibModal.open({ animation: true, templateUrl: 'timezone/timezoneAddEdit.tpl.html', controller: 'TimeZoneAddEditController', windowClass: 'AddEditTimezone-Modal', size: 'lg', backdrop: 'static', resolve: { mode: function () { if (row === undefined) { return 'Add'; } else { return 'Modify'; } }, timezones: function () { return $scope.timezones; }, timezone: function () { if (row === undefined) { return { TimezoneId: 0, Name: '', Offset: '', OffsetShort: '' }; } else { return row.entity; } } } }); modalInstance.result.then(function (timezones) { //To Dos : Here we need to write the code to add/edit the existing scope $scope.timezones = timezones; }, function () { //User cancled the pop-up }); }; $scope.DeleteTimeZone = function (row) { var modalOptions = { headerText: $scope.headerTextTimezone, bodyText: $scope.bodyTextTimezone + '?' }; ModalService.Confirm({}, modalOptions).then(function (result) { TimeZoneService.DeleteTimeZone(row.entity.TimezoneId).then(function (response) { if (response.data.Status) { var index = $scope.gridOptions.data.indexOf(row.entity); $scope.gridOptions.data.splice(index, 1); toaster.pop({ type: 'success', title: $scope.TitleFrayteInformation, body: $scope.TextSuccessfullyDelete, showCloseButton: true }); } else { toaster.pop({ type: 'warning', title: $scope.TitleFrayteError, body: response.data.Errors[0], showCloseButton: true }); } }, function () { toaster.pop({ type: 'warning', title: $scope.TitleFrayteError, body: $scope.TextErrorDeletingRecord, showCloseButton: true }); }); }); }; $scope.SetGridOptions = function () { $scope.gridOptions = { showFooter: true, enableSorting: true, multiSelect: false, enableFiltering: true, enableRowSelection: true, enableSelectAll: false, enableRowHeaderSelection: false, selectionRowHeaderWidth: 35, noUnselect: true, enableGridMenu: false, enableColumnMenus: false, enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER, enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER, data: $scope.timezones, columnDefs: [ { name: 'Name', displayName: 'TimeZoneName', headerCellFilter: 'translate' }, { name: 'OffsetShort', displayName: 'Offset', headerCellFilter: 'translate' }, { name: 'Offset', displayName: 'OffsetDetail', headerCellFilter: 'translate' }, { name: 'Edit', displayName: "", enableFiltering: false, enableSorting: false, enableGridMenuenableRowSelection: false, noUnselect: false, cellTemplate: "timezone/timezoneEditButton.tpl.html", width: 65 } ] }; }; function init() { // set Multilingual Modal Popup Options setModalOptions(); $scope.gridheight = SessionService.getScreenHeight(); $scope.SetGridOptions(); TimeZoneService.GetTimeZoneList().then(function (response) { $scope.gridOptions.data = response.data; $scope.timezones = response.data; $scope.gridOptions.excessRows = $scope.gridOptions.data.length; }, function () { toaster.pop({ type: 'warning', title: $scope.TitleFrayteError, body: $scope.TextErrorGettingTimeZoneRecord, showCloseButton: true }); }); } init(); });
const ytdl = require('ytdl-core'); const ytdlDiscord = require('ytdl-core-discord'); function getDispatcher(message) { return message.guild.voiceConnection.dispatcher; } function getConnection(message) { return message.guild.voiceConnection; } async function getBotVoiceChannel(message) { return message.guild.voiceConnection.channel; } function inVoiceChannel(message) { return message.guild.voiceConnection ? true : false; } async function joinVoiceChannel(message) { try { return message.member.voiceChannel.join(); } catch(e) { console.error(`joinVoiceChannel ${e}`); } } async function leaveVoiceChannel(message) { return message.guild.voiceConnection.disconnect; } async function nowPlaying(message, url) { ytdl.getInfo(url) .then(info => message.channel.send( `:musical_note: ${info.title}\n:information_desk_person: ${info.author.name}` )) .catch(console.error); } async function playAudio(connection, url, volume) { const dispatcher = connection.playOpusStream( await ytdlDiscord(url, {filter: 'audioonly'}), // { type: 'opus', passes: 3 } { passes: 3 } ); dispatcher.on('error', error => console.error(error)); dispatcher.on('end', reason => { if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.'); else console.log(reason); }); dispatcher.setVolumeLogarithmic(1 / 5); } module.exports = { getDispatcher: getDispatcher, getConnection: getConnection, getBotVoiceChannel: getBotVoiceChannel, inVoiceChannel: inVoiceChannel, joinVoiceChannel: joinVoiceChannel, leaveVoiceChannel: leaveVoiceChannel, nowPlaying: nowPlaying, playAudio: playAudio }
function submitHandler(ev) { submitInfo(); // var submitBtn = getActivedObject(ev); ev.preventDefault(); var submitMark = false; var inputs = document.getElementById('buy').getElementsByTagName('input'); for(var i = 0; i < inputs.length; i ++) {//保证每个输入控件都有值; if(inputs[i].value == '') { alert("Please choose the " + inputs[i].name); return false; } } var submitMark = true; var buy = document.getElementById('buy'); if(submitMark) { buy.submit(); } }
function pushAlphabet(l) { l.append("a"); l.append("b"); l.append("c"); l.append("d"); l.append("e"); l.append("f"); l.append("g"); l.append("h"); l.append("i"); l.append("j"); l.append("k"); l.append("l"); l.append("m"); l.append("n"); l.append("o"); l.append("p"); l.append("q"); l.append("r"); l.append("s"); l.append("t"); l.append("u"); l.append("v"); l.append("w"); l.append("x"); l.append("y"); l.append("z"); } function List() { /* DON'T USE THESE TWO PROPERTIES IN YOUR PROGRAM Pretend these are private There is no error checking here, and you may find yourself out of bounds */ this.head = {next: null}; this.tail = null; //makeNode method takes the place of an explicit node declaration List._makeNode = function() { //this return is the object literal that is stored as a node return { data: null, prev: null, next: null }; } //doubles as an external iterator. //use "begin" to get first node //use "last" to get last node this.nodeAt = function(i) { if (typeof i === "string") { switch(i) { case "begin": return this.head; break; case "end": return this.tail; break; default: return false; } } var temp = this.head; temp = temp.next; for(var j = 0; j < i; j++) { temp = temp.next; } return temp; } this.append = function(data) { //list is empty if(this.head.next === null) { this.head.next = List._makeNode(); this.tail = this.head.next; } //list is not empty else { this.tail.next = List._makeNode(); //new node at the end this.tail.next.prev = this.tail; //gets the newly created node and sets prev to current tail this.tail = this.tail.next; //newly created node is now tail } this.tail.data = data; //sets the newly made tail node's data } this.insertBeforeX = function(data, i) { //need to push bounds checking var newNode = List._makeNode(); var ithNode = this._nodeAt(i); newNode.prev = ithNode.prev; ithNode.prev.next = newNode; newNode.next = ithNode; ithNode.prev = newNode; newNode.data = data; } this.insertAfterX = function(data, i) { var newNode = List._makeNode(); var ithNode = List._nodeAt(i); newNode.next = ithNode.next; thisithNode.next.prev = newNode; newNode.prev = ithNode; ithNode.next = newNode; newNode.data = data; } this.at = function(index) { var iteration = 0; var temp = this.head; temp = temp.next; for(var j = 0; j < index; j++) { temp = temp.next; } return temp.data; } this.pop = function() { this.tail = this.tail.prev; this.tail.next = null; } this.popFirst = function() { this.head.next = this.head.next.next; } this.popAt = function(i) { buff = this._nodeAt(i); buff.prev.next = buff.next; buff.next.prev = buff.prev; } //O(n). if used in for loop header, becomes O(n^2) this.length = function() { var temp = this.head; var count = 0; while(temp.next !== null) { count++; temp = temp.next; } return count; } this.getLast = function() { return this.tail.data; } this.getFirst = function() { return this.head.next.data; } } list = new List(); pushAlphabet(list); var node = list.nodeAt("begin"); var arr = Array(); while(node.next != null) { node = node.next; arr.push(node); console.log(node.data); }
import React from 'react'; import Routine from './routine'; import ChooseRoutine from './chooseRoutine'; const RoutineList = props => { const [editList, setEditList] = React.useState(''); let createList; if (props.view === 'userRoutineMain') { createList = createListRoutine(); } else { createList = createListChooseRoutine(); } function createListRoutine() { if (!props.routine) { return null; } else if (props.routine.length > 0) { const createList = props.routine.map(item => <Routine key={item.routineId} routineItem={item} editList={editList} setEditList={setEditList} routineId={item.routineId} userId={props.userId} setView={props.setView} setRoutine={props.setRoutine} routine={props.routine} />); return createList; } else { return <h2 className="p-3 text-secondary">add a routine</h2>; } } function createListChooseRoutine() { if (!props.routine) { return null; } else if (props.routine.length > 0) { const createList = props.routine.map(item => <ChooseRoutine addingInfo={props.addingInfo} key={item.routineId} routineItem={item} name={item.routineName} id={item.routineId} currentRoutine = {props.currentRoutine} changeView={props.changeView} findCurrentRoutine={props.findCurrentRoutine}/>); return createList; } else { return <h2 className="p-3 text-secondary">you have no routines</h2>; } } return ( <div>{createList}</div> ); }; export default RoutineList;
function data(){ var data = firebase.database().ref('userlist'); data.on('child_added', value); } var pwdref,outpwdref; var k,name,email,password,prevChild; function value(snapshot,prevChildKey){ var usrdata = snapshot.val(); var keys = Object.keys(usrdata); for(var i = 0; i<keys.length; i++){ k = keys[i]; name = usrdata[k].name; email = usrdata[k].email; password = usrdata[k].password; pwdref = password; for(i=1;i<keys.length;i++){ document.getElementById("p").innerHTML = '<ul><li>'+password[i]+'</li></ul>'; } console.log("inside for pwdref " + pwdref) console.log("inside for password " + password) prevKey = prevChildKey; } outpwdref = pwdref; console.log("outside for pwdref " + pwdref) console.log("outside for outpwdref " + outpwdref) console.log("outside for inside func " + password) call(); } console.log("outside everything " + outpwdref) var calling = outpwdref; function call(){ console.log("inside call() calling " + calling) } console.log(password)
import React, { useState } from 'react'; import styled from 'styled-components'; const Input = styled.input` height: 25px; width: 600px; `; const Button = styled.button` background: #6200ee; color: #fff; font-size: 16px; `; export default () => { const [value, setValue] = useState(); const onClick = ({ target: { value } }) => setValue(value); const onButtonClick = () => { const n = value .split(/\n/g) .map(d => d.split(',')) .map((d, k) => ({ id: k, name: d[0], url: d[1] })); setValue(n); console.log(n); }; return ( <div> <div> <textarea name="name" rows="20" cols="100" onChange={onClick} /> <textarea rows="20" cols="100" value={JSON.stringify(value)} style={{ display: value ? 'block' : 'none' }} ></textarea> </div> <Button onClick={onButtonClick}>submit</Button> </div> ); };
var Q = require('q'); var needle = require('needle'); var createLink = function(params, callback) { var deferred = Q.defer(); // Defaults to no custom and no private if (!params.custom) { params.custom = ''; } else if (!params.private) { params.private = false; } needle.post('https://api.waa.ai/shorten', params, function(err, response) { if (!err) { var link = response.body.data.url; deferred.resolve(link); } else { return false; } }); deferred.promise.nodeify(callback); return deferred.promise; } var getInfo = function(code, callback) { var deferred = Q.defer(); needle.get('https://api.waa.ai/info/' + code, function(err, response) { if (!err) { var info = response.body.data; deferred.resolve(info); } }); deferred.promise.nodeify(callback); return deferred.promise; } module.exports.link = createLink; module.exports.info = getInfo;
import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import './task.html'; Template.task.helpers({ isOwner() { return this.owner === Meteor.userId(); }, isLoggedIn() { return Meteor.userId(); }, }); Template.task.events({ 'click .toggle-checked'() { // Set the checked property to the opposite of its current value Meteor.call('tasks.setChecked', this._id, !this.checked); }, 'click .delete'() { Meteor.call('tasks.remove', this._id); }, 'click .toggle-private'() { Meteor.call('tasks.setPrivate', this._id, !this.private); }, }); Template.task.helpers({ is_today(date) { return date && date.toDateString() === new Date().toDateString(); } });
export default { recipes: { userRecipes: { newRecipes: [], cookedRecipes: [], totalRecipes: [] }, allRecipes: [] }, friends: [], potlucks: { potlucks: [], allPotluckRecipes: [] }, user: {}, session: !!sessionStorage.jwt }
/*global JSAV, window */ (function() { "use strict"; var av, // The JSAV object answerArr = [], // The (internal) array that stores the correct answer cloneArr = [], // Copy of (internal) array at start of exercise for reset jsavArr, // JSAV array that the user manipulates topArr, // JSAV array that holds value for top selectedIndex, // Array position that has been selected by user inValue; // insertion value // These are things that need to be accessed from the HTML file var astackPushPRO = { userInput: null, // Boolean: Tells if user ever did anything // Initialise the exercise initJSAV: function(max_size, curr_size, insertValue) { var i; //global variables selectedIndex = -1; inValue = insertValue; answerArr.length = 0; // Out with the old // Give random numbers in range 0..999 for (i = 0; i < curr_size; i++) { answerArr[i] = Math.floor(Math.random() * 1000); } for (i = 0; i < max_size - curr_size; i++) { answerArr.push([""]); } // Now make a copy cloneArr = answerArr.slice(0); reset(max_size, curr_size); // correct answer answerArr.splice(curr_size, 0, inValue); answerArr.splice(curr_size + 1, 1); // Set up handler for reset button $("#reset").click(function() { reset(max_size, curr_size); }); $("#insert").click(function() { insert(); }); $("#top").click(function() { settop(); }); }, // Check user's answer for correctness: User's array must match answer checkAnswer: function(max_size, curr_size) { if (topArr.value(0) !== (curr_size + 1)) { return false; } for (var i = 0; i < max_size; i++) { if (jsavArr.value(i) !== answerArr[i]) { return false; } } return true; } }; // reset function definition function reset(max_size, curr_size) { var leftMargin = 30, topMargin = 40; selectedIndex = -1; // Clear the old JSAV canvas. if ($("#AstackPushPRO")) { $("#AstackPushPRO").empty(); } // Set up the display av = new JSAV("AstackPushPRO"); topArr = av.ds.array([curr_size], {indexed: false, center: false, left: leftMargin, top: 0}); jsavArr = av.ds.array(cloneArr, {indexed: true, center: false, left: leftMargin, top: topMargin}); jsavArr.click(clickHandler); av.label("top:", {left: 0, top: 2}); av.displayInit(); av.recorded(); astackPushPRO.userInput = false; } // Click event handler on the array function clickHandler(index) { if (selectedIndex === -1) { // nothing currently selected // Selecting the current array index jsavArr.css(index, {"font-size": "110%"}); selectedIndex = index; jsavArr.highlight(index); } else { // Something is already selected if (selectedIndex !== index) { // He's swapping jsavArr.swap(selectedIndex, index); jsavArr.unhighlight(selectedIndex); jsavArr.css(selectedIndex, {"font-size": "100%"}); } jsavArr.css(index, {"font-size": "100%"}); jsavArr.unhighlight(index); selectedIndex = -1; // Reset to nothing selected } astackPushPRO.userInput = true; } // Handler for insert button function insert() { if (selectedIndex !== -1) { jsavArr.value(selectedIndex, inValue); jsavArr.css(selectedIndex, {"font-size": "100%"}); jsavArr.unhighlight(selectedIndex); selectedIndex = -1; astackPushPRO.userInput = true; } } // Handler for set top button function settop() { if (selectedIndex !== -1) { // Don't do anything if no index selected topArr.value(0, selectedIndex); jsavArr.css(selectedIndex, {"font-size": "100%"}); jsavArr.unhighlight(selectedIndex); selectedIndex = -1; } } window.astackPushPRO = window.astackPushPRO || astackPushPRO; }());
$(document).ready(function(){ $.bind_review_image($("#review_list")); $("img[lazy][!isload]").ui_lazy({placeholder:LOADER_IMG}); }); /** * 绑定图片事件 */ $.bind_review_image = function(dom){ var item_width = 100; var show_max = 6; var margin = 10; var border_width = 2; item_width+=(margin+border_width*2); $(dom).find(".review_pic").each(function(i,o){ //初始化 var img_count = $(o).find(".pic_box li").length; var current = 0; $(o).find(".over").width(show_max*item_width-margin); $(o).find(".pic_box").width(img_count*item_width); $(o).find("li").css("margin-right",margin); //绑定移上 $(o).find(".over").hover(function(){ $(o).oneTime(100,function(){ $(o).find(".pre").animate({left:2},{duration:100,queue:false}); $(o).find(".next").animate({right:2},{duration:100,queue:false}); }); },function(){ $(o).stopTime(); $(o).find(".pre").animate({left:-29},{duration:100,queue:false}); $(o).find(".next").animate({right:-29},{duration:100,queue:false}); }); //绑定点击箭头事件 $(o).find(".pre").bind("click",function(){ current = current-1<0?0:current-1; var left = current * item_width * -1; $(o).find(".pic_box").animate({left:left},{duration:100,queue:false}); }); $(o).find(".next").bind("click",function(){ current = current+1>img_count-show_max?img_count-show_max:current+1; var left = current * item_width * -1; $(o).find(".pic_box").animate({left:left},{duration:100,queue:false}); }); //绑定点击小图事件 var img_idx = -1; //当前图片的顺序idx $(o).find("li a").each(function(i,o){ $(o).attr("idx",i); //设置顺序 }); $(o).find("li a").bind("click",function(){ var big_img = $(this).attr("rel"); $(o).find("li a").removeClass("active"); if($(this).attr("is_active")=="active") { $(o).find("li a").removeAttr("is_active"); $(o).find(".big_img").hide(); img_idx = -1; } else { $(o).find("li a").removeAttr("is_active"); $(this).attr("is_active","active"); $(this).addClass("active"); $(o).find(".big_img").show(); $.do_load_big_img($(o).find(".big_img img"),big_img); img_idx = parseInt($(this).attr("idx")); $.do_init_arrow_ui(o,img_idx,img_count); } }); //绑定上下切换 $(o).find(".big_img a.bprev").bind("click",function(){ img_idx = img_idx-1<0?0:img_idx-1; var big_img = $(o).find("li a:eq("+img_idx+")").attr("rel"); $(o).find("li a").removeAttr("is_active"); $(o).find("li a").removeClass("active"); $(o).find("li a:eq("+img_idx+")").attr("is_active","active"); $(o).find("li a:eq("+img_idx+")").addClass("active"); $(o).find(".big_img").show(); $.do_load_big_img($(o).find(".big_img img"),big_img); $.do_init_arrow_ui(o,img_idx,img_count); if(img_count-img_idx>img_count-current) { $(o).find(".pre").trigger("click"); } }); $(o).find(".big_img a.bnext").bind("click",function(){ img_idx = img_idx+1>img_count-1?img_count-1:img_idx+1; var big_img = $(o).find("li a:eq("+img_idx+")").attr("rel"); $(o).find("li a").removeAttr("is_active"); $(o).find("li a").removeClass("active"); $(o).find("li a:eq("+img_idx+")").attr("is_active","active"); $(o).find("li a:eq("+img_idx+")").addClass("active"); $(o).find(".big_img").show(); $.do_load_big_img($(o).find(".big_img img"),big_img); $.do_init_arrow_ui(o,img_idx,img_count); if(img_idx>=current+show_max) { $(o).find(".next").trigger("click"); } }); }); }; //初始化大图上的ui箭头 $.do_init_arrow_ui = function(dom,img_idx,img_count){ if(img_idx==0) { $(dom).find(".big_img a.bprev").hide(); } else { $(dom).find(".big_img a.bprev").show(); } if(img_idx==img_count-1) { $(dom).find(".big_img a.bnext").hide(); } else { $(dom).find(".big_img a.bnext").show(); } //绑定大图切换与ui $(dom).find(".big_img a").css("width",$(dom).find(".big_img").width()/2); $(dom).find(".big_img a").css("height",$(dom).find(".big_img").height()); }; $.do_load_big_img = function(imgdom,src){ //$(imgdom).attr("src",src); //$(imgdom).attr("data-src",src); //$(imgdom).removeAttr("isload"); $(imgdom).ui_lazy({placeholder:LOADER_IMG,src:src,refresh:true}); };
import React from 'react'; import MealContainer from './components/MealContainer.js'; import IngredientListContainer from './components/IngredientListContainer.js'; function App() { return ( <div> <MealContainer /> {/* <IngredientListContainer /> */} </div> ); } export default App;
import ExpoPixi, { PIXI } from 'expo-pixi'; export default async context => { //http://pixijs.io/examples/#/basics/basic.js const app = ExpoPixi.application({ context, }); // holder to store the aliens var aliens = []; var totalDudes = 20; for (var i = 0; i < totalDudes; i++) { // create a new Sprite that uses the image name that we just generated as its source var dude = await ExpoPixi.spriteAsync(require('../../assets/pixi/eggHead.png')); // set the anchor point so the texture is centerd on the sprite dude.anchor.set(0.5); // set a random scale for the dude - no point them all being the same size! dude.scale.set(0.8 + Math.random() * 0.3); // finally lets set the dude to be at a random position.. dude.x = Math.random() * app.renderer.width; dude.y = Math.random() * app.renderer.height; dude.tint = Math.random() * 0xffffff; // create some extra properties that will control movement : // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees dude.direction = Math.random() * Math.PI * 2; // this number will be used to modify the direction of the dude over time dude.turningSpeed = Math.random() - 0.8; // create a random speed for the dude between 0 - 2 dude.speed = 2 + Math.random() * 2; // finally we push the dude into the aliens array so it it can be easily accessed later aliens.push(dude); app.stage.addChild(dude); } // create a bounding box for the little dudes var dudeBoundsPadding = 100; var dudeBounds = new PIXI.Rectangle( -dudeBoundsPadding, -dudeBoundsPadding, app.renderer.width + dudeBoundsPadding * 2, app.renderer.height + dudeBoundsPadding * 2 ); app.ticker.add(function() { // iterate through the dudes and update their position for (var i = 0; i < aliens.length; i++) { var dude = aliens[i]; dude.direction += dude.turningSpeed * 0.01; dude.x += Math.sin(dude.direction) * dude.speed; dude.y += Math.cos(dude.direction) * dude.speed; dude.rotation = -dude.direction - Math.PI / 2; // wrap the dudes by testing their bounds... if (dude.x < dudeBounds.x) { dude.x += dudeBounds.width; } else if (dude.x > dudeBounds.x + dudeBounds.width) { dude.x -= dudeBounds.width; } if (dude.y < dudeBounds.y) { dude.y += dudeBounds.height; } else if (dude.y > dudeBounds.y + dudeBounds.height) { dude.y -= dudeBounds.height; } } }); };
import { SET_RECIPE_FAMILIES_LIST } from "../actionTypes"; const initialState = { recipeFamiliesList: [] }; const recipeFamiliesReducer = (state = initialState, action) => { switch (action.type) { case SET_RECIPE_FAMILIES_LIST: return { ...state, recipeFamiliesList: action.payload.recipeFamiliesList }; default: return { ...state }; } }; export default recipeFamiliesReducer;
import React, { Component } from 'react'; import { graphql } from 'react-apollo'; import { Link, hashHistory } from 'react-router'; import gql from 'graphql-tag'; import fetchCustomer from '../queries/fetchCustomer'; import query from '../queries/fetchCustomers'; export class CustomerEdit extends Component { constructor(props) { super(props); this.state = { name: '', email: '', prime: false }; } componentWillReceiveProps(newProps) { if (newProps.data.customer) { const { customer } = newProps.data; this.setState({ name: customer.name, email: customer.email, prime: customer.prime }); } } onSubmit(event) { event.preventDefault(); this.props .mutate({ variables: { id: this.props.params.id, name: this.state.name, email: this.state.email, prime: this.state.prime }, refetchQueries: [ { query }, { query: fetchCustomer, variables: { id: this.props.params.id } } ] }) .then(() => hashHistory.push('/')); } render() { const { name, email, prime } = this.state; return ( <div className="wrapper"> <Link to="/">Back</Link> <h4>Edit Customer</h4> <form className="form"> <label>Name:</label> <input onChange={event => this.setState({ name: event.target.value })} value={name} /> <label>Email:</label> <input onChange={event => this.setState({ email: event.target.value })} value={email} /> <label>Prime Membership</label> <div className="switch"> <label> Off <input type="checkbox" id="mycheckbox" checked={prime} onChange={event => this.setState({ prime: event.target.checked }) } /> <span className="lever" /> On </label> </div> </form> <a onClick={this.onSubmit.bind(this)} className="waves-effect waves-light btn right" > Submit </a> </div> ); } } const mutation = gql` mutation updateCustomer( $id: ID $name: String $email: String $prime: Boolean ) { updateCustomer(id: $id, name: $name, email: $email, prime: $prime) { name email prime } } `; export default graphql(mutation)( graphql(fetchCustomer, { options: props => { return { variables: { id: props.params.id } }; } })(CustomerEdit) );
'use strict'; describe('alerts creation, listing', function () { var $scope, element, deferred, q, $routeParams, location, $httpBackend, alertFactory; beforeEach(module('myApp', function($provide) { alertFactory = { get: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, }; $provide.value("Alert", alertFactory); })); // beforeEach(module('components/locations/networks/alerts.html')); // beforeEach(module('components/alerts/form.html')); // beforeEach(module('components/alerts/details.html')); describe('alerts creation, listing', function () { beforeEach(inject(function($compile, $rootScope, $q, _$routeParams_, $injector) { $scope = $rootScope; $httpBackend = $injector.get('$httpBackend'); $httpBackend.whenGET('template/tooltip/tooltip-popup.html').respond(""); $httpBackend.whenGET('template/pagination/pagination.html').respond(""); $routeParams = _$routeParams_; $routeParams.location_id = 123123123; $scope.box = {}; q = $q; $scope.location = { slug: 456, id: 123 } element = angular.element('<list-alerts></list-alerts>'); $compile(element)($rootScope) element.scope().$digest(); })) it("should list the alerts for a user", function() { spyOn(alertFactory, 'get').andCallThrough(); expect(element.isolateScope().loading).toBe(true); var alert = { alerts: [ { alert_name: 'lobby'} ], _links: {} }; expect(element.isolateScope().loading).toBe(true) deferred.resolve(alert); $scope.$digest() expect(element.isolateScope().alerts[0].alert_name).toBe(alert.alerts[0].alert_name); expect(element.isolateScope()._links).toBe(alert._links); expect(element.isolateScope().loading).toBe(undefined); }) }) })
(function() { angular.module('imgApp',['ngResource']); })();
module.exports = { primary: "#4259df", secondary: "#ffffff" };
'use strict'; const path = require("path"), fs = require("fs"), RaspiCam = require('raspicam'), logger = require("./logger"); let _lastShoot = 0, _camera, _defaults = { interval: 1000, path: "./shoots/" }, _options = {}; function shoot() { const now = Date.now(), filename = `shoot_${now}.jpg`, fullpath = path.join(_options.path, filename), camera = new RaspiCam({ mode: 'photo', output: fullpath, width: 640, height: 480, timeout: 500, nopreview: true }); return new Promise(function (resolve, reject) { camera.on("exit", function () { resolve(fullpath); }); if (!camera.start()) { reject("unable to start camera engine"); } }); } module.exports.init = function (options) { _lastShoot = 0; _options = Object.assign({}, _defaults, options); if (!fs.existsSync(_options.path)) { fs.mkdirSync(_options.path); } } module.exports.shoot = function () { const now = Date.now(); if (now > _lastShoot + _options.interval) { _lastShoot = now; return shoot(); } return Promise.resolve(false); }
const FFT_MIN_LOG2 = 2; const FFT_MAX_LOG2 = 32; const FFT_MIN_SIZE = 1 << FFT_MIN_LOG2; const FFT_MAX_SIZE = 1 << FFT_MAX_LOG2; function logDualis(n) { let log2 = 0; for (let i = n >> 1; i; i >>= 1) log2++; return log2; } // tab = Float32Array(5 / 4 * fftSize + 1) // sine = tab + 0 // cosine = tab + fftSize / 4 function fillFiveQuarterSineTable(tab, fftSize) { const tab_size = 5 * fftSize / 4; let step = 2 * M_PI / fftSize; for (let i = 0; i <= tab_size; i++) tab[i] = Math.sin(i * step); return tab; } // tab = UInit32Array(fftSize) function fillBitreversedTable(tab, fftSize) { let log_size; for (log_size = -1, i = size; i; i >>= 1, log_size++) ; for (let i = 0; i < size; i++) { let idx = i; let xdi = 0; for (let j = 1; j < log_size; j++) { xdi += (idx & 1); xdi <<= 1; idx >>= 1; } tab[i] = xdi + (idx & 1); } return tab; } function isFftSize(n) { if (n < FFT_MIN_SIZE || n > FFT_MAX_SIZE) return false; /* power of 2? */ while ((n >>= 1) && !(n & 1)) ; return (n == 1); } function nextFftSize(n) { let fftSize = FFT_MIN_SIZE; for (let i = ((size - 1) >> FFT_MIN_LOG2); i > 0; i >>= 1) fftSize <<= 1; return fftSize; }
import React, { useContext } from 'react' import './discription.scss' import AudioPlayer from 'react-h5-audio-player'; import 'react-h5-audio-player/lib/styles.css'; import { BirdContext } from '../context/BirdContext' export const Discription = () => { const {state} = useContext(BirdContext) const renderData = state.answerId ? state.birdsList[ state.answerId - 1 ] : null; const renderInfo = ( <div className = 'discription'> <div className = 'conteiner'> <img alt={ state.currentBird.name } src={ state.currentBird.image } /> <div className = 'dop_discription'> <p>{state.currentBird.name} / {state.currentBird.species}</p> <AudioPlayer loop={false} autoPlayAfterSrcChange={false} src= { state.currentBird.audio } showJumpControls={false} customAdditionalControls={[]} /> </div> </div> <p> {state.currentBird.description} </p> </div> ) const defaultInfo = ( <div className='defaultInfo'> <span>Послушайте плеер.</span> <br/> <span>Выберите птицу.</span> </div> ); return ( <div className = 'discription_bird'> { renderData === null ? defaultInfo : renderInfo } </div> ); }
export { default } from './cookie'
var Util = { createIFrame: function(src){ var frm = $(document.createElement("iframe")); frm.css({ height: 100, width: 100, position: 'absolute', left: -150 }); frm.attr('src', src); document.body.appendChild(frm[0]); return frm[0]; }, // createDiv: function(src, callback){ // var div = $(document.createElement('div')); // div.css({ // height: 100, // width: 100, // position: 'absolute', // left: -150 // }); // $.get(src, function(data){ // div.html(data); // }); // }, // getBody: function(){ // }, getChartDataExample: function(){ return { chart: { type: 'line', zoomType: 'xy', height: 400 }, title: { text: 'actionLoginB 耗时', x: -20 //center }, xAxis: { categories: ['step-1', 'step-2', 'step-3'] }, yAxis: { title: { text: 'Time cost(ms)' } // plotLines: [{ // value: 2608, // width: 1, // color: '#808080', // label: { // text:'4.6版本' // } // }] }, credits: { text: '' }, tooltip: { valueSuffix: 'ms', }, // plotOptions: { // line: { // dataLabels: { // enabled: true // }, // enableMouseTracking: true // } // }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, // series: [{ // name: 'v123', // data: [{ // y : 4523, // events: { // click: function(){ // console.log(arguments); // debugger; // } // } // }, { // y : 4567 // }, { // y : 3546 // }] // }] series: [{ name: 'v123', data: [3345, 4567,3546] }, { name: 'v234', data: [2345,4534,2334] }, { name: 'v345', data: [3453,4444,5555] }, { name: 'v456', data: [4454,3866,4097] }] } }, avg: function(arr){ var num = 0; for(var i = 0; i < arr.length; i ++){ num += arr[i]; } return parseInt(num/arr.length); } };
var sql = require('mysql'); var Mysql = function () {}; Mysql.prototype.init = function (option) { this.sql = sql.createConnection({ host: option.host, user: option.user, password: option.password, database: option.database }); return this.sql; } module.exports = new Mysql();
import React from 'react'; document.getElementById('name').style.display = 'block'; document.getElementById('challenge').style.display = 'none'; document.getElementById('rating').style.display = 'none'; document.getElementById('feedback').style.display = 'none'; document.querySelector('#question2').onclick = function() { document.getElementById('name').style.display = 'none'; document.getElementById('challenge').style.display = 'block'; document.getElementById('rating').style.display = 'none'; document.getElementById('feedback').style.display = 'none'; }; document.querySelector('#question3').onclick = function() { document.getElementById('name').style.display = 'none'; document.getElementById('challenge').style.display = 'none'; document.getElementById('rating').style.display = 'block'; document.getElementById('feedback').style.display = 'none'; }; document.querySelector('#done').onclick = function() { document.getElementById('name').style.display = 'none'; document.getElementById('challenge').style.display = 'none'; document.getElementById('rating').style.display = 'none'; document.getElementById('feedback').style.display = 'block'; stream.stop(); };
import axios from 'axios' import fetchAllFixturesStart from './fetchAllFixturesStart' import fetchAllFixturesAck from './fetchAllFixturesAck' import fetchAllFixturesError from './fetchAllFixturesError' import endpoint from "../../const/endpoint"; import Cookies from "js-cookie"; const fetchAllFixtures = () => { return dispatch => { dispatch(fetchAllFixturesStart()); axios.get(endpoint + "/api/fixtures/all", { headers: { Authorization: `Bearer ${Cookies.get("authToken")}` } }) .then(response => dispatch(fetchAllFixturesAck(response))) .catch(error => dispatch(fetchAllFixturesError(error))) } } export default fetchAllFixtures;
window.MyRetirement_REMOTEAPI = { "url" : "/PlanningStation/extdirect/router", "type" : "remoting", "actions" : { "incomeService" : [ { "name" : "calcFullRetirementAgeMonthlyBenefit", "len" : 2 }, { "name" : "updateRetirementIncomeData", "len" : 2 }, { "name" : "getNoteAnnuityIncomeData", "len" : 1 }, { "name" : "getRetirementIncomeData", "len" : 1 }, { "name" : "deleteRetirementIncomeData", "len" : 2 }, { "name" : "createNoteAnnuityIncomeData", "len" : 2 }, { "name" : "calcFullRetirementAge", "len" : 2 }, { "name" : "updateSocialSecurityIncomeData", "len" : 2 }, { "name" : "createRetirementIncomeData", "len" : 2 }, { "name" : "calcMonthlyIncomeDuringRetirement", "len" : 1 }, { "name" : "deleteNoteAnnuityIncomeData", "len" : 2 }, { "name" : "updateNoteAnnuityIncomeData", "len" : 2 }, { "name" : "getSocialSecurityIncomeData", "len" : 1 } ], "whatIfService" : [ { "name" : "getAdditionalInvestingData", "len" : 1 }, { "name" : "getAdditionalInvestingWithSaveMore", "len" : 1 }, { "name" : "updateAdditionalInvestingWithSaveMore", "len" : 2 }, { "name" : "updateAdditionalInvestingData", "len" : 2 } ], "comparisonService" : [ { "name" : "updateBudgetData", "len" : 2 }, { "name" : "getTakeHomePayData", "len" : 1 }, { "name" : "getDefaultBudgetData", "len" : 1 }, { "name" : "updateTakeHomePayData", "len" : 2 }, { "name" : "getComparisonData", "len" : 1 }, { "name" : "getBudgetData", "len" : 1 } ], "enumerationService" : [ { "name" : "getEnumerations", "len" : 0 } ], "setupService" : [ { "name" : "getSetupInfo", "len" : 1 }, { "name" : "calcJointLifeExpectancy", "len" : 1 }, { "name" : "updateSetupInfo", "len" : 2 }, { "name" : "calcSingleLifeExpectancy", "len" : 2 }, { "name" : "updateClient", "len" : 2 }, { "name" : "getAssetAllocationPreRetirement", "len" : 2 }, { "name" : "getClient", "len" : 1 } ], "withdrawalRateService" : [ { "name" : "calcWithdrawalRateData", "len" : 2 }, { "name" : "getWithdrawalRateData", "len" : 1 }, { "name" : "getAssetAllocationAtRetirement", "len" : 2 } ], "planTrackUIService" : [ { "name" : "updatePlanTrackName", "len" : 2 }, { "name" : "getChartPresetView", "len" : 4 }, { "name" : "updatePlanTrackActiveMonitoring", "len" : 1 }, { "name" : "getPlanTrackGeneralInformation", "len" : 1 }, { "name" : "getPlanTrackTree", "len" : 1 }, { "name" : "updateActiveMonitoring", "len" : 2 }, { "name" : "updatePlanSelection", "len" : 2 }, { "name" : "getAnnualChartView", "len" : 2 }, { "name" : "deletePlanTracks", "len" : 1 }, { "name" : "getAccountBalanceMonthly", "len" : 1 }, { "name" : "isPlanTrackNameAlreadyInDb", "len" : 1 }, { "name" : "getChartForDateRangeView", "len" : 2 }, { "name" : "updatePlanTrackAccountsMonthlyCurrentBalance", "len" : 1 } ], "assetService" : [ { "name" : "deleteRetirementAssetData", "len" : 2 }, { "name" : "updateInvestmentAssetData", "len" : 2 }, { "name" : "deleteInvestmentAssetData", "len" : 2 }, { "name" : "calcAssetValuesAtRetirement", "len" : 1 }, { "name" : "getRetirementAssetData", "len" : 1 }, { "name" : "createRetirementAssetData", "len" : 2 }, { "name" : "calcAssetGrowth", "len" : 1 }, { "name" : "createInvestmentAssetData", "len" : 2 }, { "name" : "updateRetirementAssetData", "len" : 2 }, { "name" : "getInvestmentAssetData", "len" : 1 } ], "initializationService" : [ { "name" : "getModuleData", "len" : 1 } ] } };
import Head from "next/head"; import { useEffect, useState } from "react"; import Layout from "../../../components/Layout"; import { useRouter } from "next/router"; import Link from "next/link"; import { viewWorkOrder, cancelJob } from "../../../redux/actions/hires"; import { Button } from "@material-ui/core"; import PrivateRoute from "../../../hoc/PrivateRoute"; import { useSelector, useDispatch } from "react-redux"; import { format } from "date-fns"; import DashboardList from "../../../components/DashboardList"; import OrderStatusFlag from "../../../components/OrderStatusFlag"; import OrderStages from "../../../components/OrderStages"; const HireRequest = () => { const router = useRouter(); const dispatch = useDispatch(); const { id } = router.query; const userId = useSelector((state) => state.auth.uid); const workDetails = useSelector((state) => state.hire.workOrder); const [activeStep, setActiveStep] = useState(0); useEffect(() => { if (id) { dispatch(viewWorkOrder(id)); } }, [id]); useEffect(() => { if (workDetails.done) { setActiveStep(4); } else setActiveStep(workDetails.stage); }, [workDetails]); const cancel = async () => { try { await cancelJob(id); router.push("/poster/hires/pending"); } catch (error) { alert(error.message); } }; if (userId !== workDetails.customerId) return ( <Layout> <h1>Unauthorized</h1> </Layout> ); return ( <> <Head> <title>{workDetails.title} | Cloak.io</title> </Head> <Layout> <DashboardList state={2} /> <div className="flex p-3 flex-col md:flex-row min-h-screen"> <div className="flex-none px-3 md:flex-1"></div> <div className="flex-1 md:flex-2 lg:flex-3 h-full w-full border-solid border-gray-100 border-2"> <div className="w-full flex justify-between px-3 bg-gray-800"> <h1 className="text-sm font-semibold my-1 text-center text-white"> Hire Request {id} </h1> </div> <div className="p-5"> {/* <h1 className="text-2xl font-bold my-1 text-center text-gray-700"> Active Hire Request </h1> */} <div className="flex justify-between items-center flex-col md:flex-row"> <h1 className="text-2xl font-semibold my-1 text-center md:my-5"> {workDetails.title} </h1> <h5 className="text-3xl font-normal text-gray-800 mx-3"> ₦{workDetails.price} </h5> </div> <div className="flex justify-between items-center w-full"> {workDetails.completedDate && ( <h5 className="my-3 text-sm font-bold text-gray-800 cursor-pointer hover:underline"> Date Completed:{" "} {format( new Date(workDetails?.completedDate?.seconds * 1000), "MMMM dd, yyyy" )} </h5> )} {workDetails.cancelledDate && ( <h5 className="my-3 text-sm font-bold text-gray-800 cursor-pointer hover:underline"> Date Cancelled:{" "} {format( new Date(workDetails?.cancelledDate?.seconds * 1000), "MMMM dd, yyyy" )} </h5> )} <OrderStatusFlag cancelled={workDetails.cancelled} done={workDetails.done} /> </div> <div className="flex items-center my-3"> <h5 className="text-sm font-semibold text-gray-800"> Service Provider:{" "} </h5> <Link href={`/profile/${workDetails.userId}`}> <h5 className="text-sm font-bold text-gray-800 cursor-pointer hover:underline"> {workDetails.userId} </h5> </Link> </div> <Link href={`/search/${workDetails.posterId}`}> <a target="_blank"> <h1 className="font-bold text-gray-800 cursor-pointer hover:underline my-2"> View Poster </h1> </a> </Link> <hr /> <div className="mb-2"> <h1 className="font-bold text-lg my-5 text-gray-800"> Description </h1> {workDetails?.description?.map((text, index) => ( <p key={index} className="my-3 text-sm"> {text} </p> ))} </div> {/* Job Stages */} <OrderStages activeStep={activeStep} /> {!workDetails.done && !workDetails.cancelled && ( <div className="w-full flex justify-between"> <Button disabled={activeStep > 0} type="submit" variant="contained" color="secondary" margin="normal" // onClick={handleClose} onClick={cancel} > Cancel </Button> </div> )} </div> <div className="w-full flex justify-between px-3 bg-gray-800"> <h1 className="text-sm font-semibold my-1 text-center text-white"> Hire Request {id} </h1> </div> </div> <div className="flex-none px-3 md:flex-1"></div> </div> </Layout> </> ); }; export default PrivateRoute(HireRequest);
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var opencv4nodejs_1 = __importDefault(require("opencv4nodejs")); /** * returns an array of the 8 most dominant colors * * @param {Mat} image * @returns array of numbers: [number, number, number][] */ function dominantColor(image) { var resized = image.resize(1, 512 * 512); var data = resized.getDataAsArray(); var termCriteria = new opencv4nodejs_1.default.TermCriteria(1, 10, 3); // @ts-ignore var points = data[0].map(function (_a) { var b = _a[0], g = _a[1], r = _a[2]; return new opencv4nodejs_1.default.Point3(r, g, b); }); // @ts-ignore var results = opencv4nodejs_1.default.kmeans(points, 8, termCriteria, 1, 1); var centers = results.centers; // @ts-ignore return centers; } exports.default = dominantColor;
const onClickSave = async (place_id) => { try { const options = { url: '/place/bookmark/', method: 'POST', data: { place_id: place_id, } } const response = await axios(options) const responseOK = response && response.status === 200 && response.statusText === 'OK' if (responseOK) { const data = response.data //modify에서는 이미 뒤집힌 is_saved 값이 들어감! modifySave(data.place_id, data.is_bookmarked) } } catch (error) { console.log(error) } } const modifySave = (place_id, is_bookmarked) => { const save = document.querySelector(`.save-${place_id} i`); const save_content = document.querySelector(`.save-${place_id} .save__content`) const num = save_content.innerText; if (is_bookmarked === true) { save.className = "fas fa-bookmark"; const count = Number(num) + 1; save_content.innerHTML = count } else { save.className = "far fa-bookmark"; const count = Number(num) - 1; save_content.innerHTML = count } }
import {StyleSheet} from 'react-native'; const styles = StyleSheet.create({ container: { width: '100%', borderBottomWidth: 1, borderBottomColor: 'lightgrey', paddingBottom: 15, marginBottom: 5, }, view1: { flexDirection: 'row', paddingVertical: 10, alignItems: 'center', }, view2: { flexDirection: 'row', flex: 1, alignItems: 'center', }, view3: { flexDirection: 'row' }, view4: { flexDirection: 'row', flex: 1, }, image: { width: 30, height: 30, borderRadius: 15, marginLeft: 15, }, image2: { width: '100%', height: 350, }, image3: { width: 30, height: 30, borderRadius: 15, marginLeft: 15, }, text: { fontSize: 14, marginLeft: 15, fontWeight: 'bold', }, text2: { marginLeft: 15, fontSize: 15, fontWeight: 'bold' }, text3: { marginLeft: 15, fontSize: 15, }, text4: { marginLeft: 15, fontSize: 15, color: 'lightgray' }, text5: { marginTop: 15, marginLeft: 15, fontSize: 15, color: 'lightgray' }, button: { width: 40, }, button2: { width: 50, height: 50, justifyContent: 'center', alignItems: 'center', }, button3: { flexDirection: 'row', alignItems: 'center', marginTop: 15, }, }); export default styles;
require("../../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/packageB/plates/_components/dev" ], { "042ea": function(e, n, t) { var a = t("4474"); t.n(a).a; }, "0bb5": function(e, n, t) { t.r(n); var a = t("9cb7"), o = t.n(a); for (var c in a) [ "default" ].indexOf(c) < 0 && function(e) { t.d(n, e, function() { return a[e]; }); }(c); n.default = o.a; }, "164f": function(e, n, t) { t.r(n); var a = t("523a"), o = t("0bb5"); for (var c in o) [ "default" ].indexOf(c) < 0 && function(e) { t.d(n, e, function() { return o[e]; }); }(c); t("042ea"); var r = t("f0c5"), u = Object(r.a)(o.default, a.b, a.c, !1, null, "2f7ef0c4", null, !1, a.a, void 0); n.default = u.exports; }, 4474: function(e, n, t) {}, "523a": function(e, n, t) { t.d(n, "b", function() { return a; }), t.d(n, "c", function() { return o; }), t.d(n, "a", function() {}); var a = function() { var e = this; e.$createElement; e._self._c; }, o = []; }, "9cb7": function(e, n, t) { Object.defineProperty(n, "__esModule", { value: !0 }), n.default = void 0; var a = { props: { plate: { type: Object } }, components: { Stars: function() { t.e("pages/packageB/plates/_components/_stars").then(function() { return resolve(t("c81e")); }.bind(null, t)).catch(t.oe); }, Line3: function() { t.e("pages/packageB/plates/_components/_line_3").then(function() { return resolve(t("3f2c")); }.bind(null, t)).catch(t.oe); } }, data: function() { return {}; }, mounted: function() {}, methods: { preview: function(e) { wx.previewImage({ current: e, urls: [ e ] }); } } }; n.default = a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/packageB/plates/_components/dev-create-component", { "pages/packageB/plates/_components/dev-create-component": function(e, n, t) { t("543d").createComponent(t("164f")); } }, [ [ "pages/packageB/plates/_components/dev-create-component" ] ] ]);
const factorialDigitSum = input => { let product = input.toString().split("").map(el => Number(el)) let current = input-1 while(current > 1){ let multiplier = current.toString().split("").map(el => Number(el)) let sums = [] for(let i=multiplier.length-1; i>=0; i--){ let carry = 0 let sum = Array(multiplier.length-1-i).fill(0) for(let j=product.length-1; j>=0; j--){ let tempProduct = (multiplier[i]*product[j] + carry).toString().split("").map(el => Number(el)) sum.unshift(tempProduct.reverse()[0]) carry = tempProduct[1] ? tempProduct[1] : 0 } if(carry > 0){sum.unshift(carry)} sums.unshift(sum) } if(sums.length === 2){ while(sums[0].length > sums[1].length){ sums[1].unshift(0) } let answer = [] let carry = 0 for(let i = sums[1].length-1; i>=0; i--){ let tempSum = (sums[1][i] + sums[0][i] + carry).toString().split("").map(el => Number(el)) answer.unshift(tempSum.reverse()[0]) carry = tempSum[1] ? tempSum[1] : 0 } if(carry > 0){answer.unshift(carry)} product = answer } else { product = sums[0] } current = current - 1 } return product.reduce((a,b) => a+b) } console.log(factorialDigitSum(100)) //648
const { Command } = require('klasa'); const snekfetch = require('snekfetch'); module.exports = class extends Command { constructor(...args) { super(...args, { aliases: ['givepat'], description: 'Pat someone', usage: '<person:user>' }); } async run(msg, [person]) { const { body } = await snekfetch.get('https://nekos.life/api/v2/img/pat'); return msg.sendMessage(`✋ | ***${person}, You have recieved a pat from ${msg.author}!***`, { files: [body.url] }); } };
var setupModule = function (module) { controller = mozmill.getBrowserController(); }; var testAboutPage_WhenOpened_PageIsLoadedWithExpectedTitle = function () { const ABOUT_PAGE_URL = "about:pentadactyl"; const EXPECTED_TITLE = "About Pentadactyl"; const BLANK_PAGE_URL = "about:blank"; controller.open(BLANK_PAGE_URL); controller.waitForPageLoad(controller.tabs.activeTab); controller.open(ABOUT_PAGE_URL); controller.waitForPageLoad(controller.tabs.activeTab); controller.assert(function () controller.tabs.activeTab.title === EXPECTED_TITLE); }; // vim: sw=4 ts=8 et:
function filterTaskByCriteria(s) { $('#idTaskHiddenFilter').val(''); if(s.id=='idFilterTaskAll') { $('#idTaskHiddenFilter').val('all'); } else if(s.id=='idFilterTaskActive') { $('#idTaskHiddenFilter').val('active=true'); } else if(s.id=='idFilterTaskClosed') { $('#idTaskHiddenFilter').val('active=false'); } else if(s.id=='idFilterTaskClosed1WK') { $('#idTaskHiddenFilter').val('active=1'); } else if(s.id=='idFilterTaskClosed2WK') { $('#idTaskHiddenFilter').val('active=2'); } else if(s.id=='idFilterTaskClosedWK') { if($('#idnweeks').val()==null || $('#idnweeks').val()=='') { alert('Please enter a value for number of weeks'); return false; } else { var numWeeks = $('#idnweeks').val(); numWeeks = parseInt(numWeeks, 10); if(!numWeeks) { alert('Please enter a valid integer'); $('#idnweeks').val(''); return false; } } $('#idTaskHiddenFilter').val('active='+numWeeks); } $('#idFilterTaskSubmit').click(); } function selfUnjoin() { var dialogMessage=""; var checkedTaskNodeIds = []; var tOwner=""; $('input[id^="checkedTask_"]').each(function() { if(this.checked) { checkedTaskNodeIds.push($('#'+this.id).attr('catId')); tOwner = $('#'+this.id).attr('taskOwner'); } }); if(checkedTaskNodeIds.length > 1){ alert('Please select one task to unjoin yourself'); }else if(checkedTaskNodeIds.length ==0){ alert('Please select one task to unjoin yourself'); }else{ if(tOwner==$('#currentUser').val()){ dialogMessage = "As you are owner of the task ,So you are not authorized to self-unjoin"; } if(dialogMessage != ""){ alert(dialogMessage); checkedTaskNodeIds = []; }else { if(confirm('Are you sure you want to unjoin yourself from the task?')) { var userIds = []; userIds[0] = $('#currentUser').val(); var postData = { "taskIds" : checkedTaskNodeIds, "userIds" : userIds }; var postDataStr = JSON.stringify(postData); var searchText = $('#searchText').val(); var filterStatus = $('#filterStatus').val(); var filterClosedWeek = $('#filterClosedWeek').val(); $('#selfUnjoinPost').val(postDataStr); document.getElementById('selfunjoinform').action="userTaskAction.action?operationType=selfunjoinUserTask&searchText="+searchText+"&filterStatus="+filterStatus+"&filterClosedWeek="+filterClosedWeek; $('#selfunjoinSubmit').click(); } } } } function deleteTask() { // var checkCount = 0; var selected = ''; var checkedTaskNodeowner = ''; var dialogMessage=""; $('input[id^="checkedTask_"]').each(function() { if(this.checked) { selected += $('#'+this.id).attr('catId')+','; checkedTaskNodeowner += $(this).attr('taskOwner')+','; if($(this).attr('taskOwner')!=$('#currentUser').val()){ dialogMessage = "As you are not owner of atleast one task ,So you are not authorize to Delete"; } // checkCount++; } }); /* if(checkCount != 1) { alert('Please select one task to delete'); } else { */ var checkedTaskNodeIds = []; if(dialogMessage != ""){ alert(dialogMessage); checkedTaskNodeIds = []; }else { $(".case:checked").each(function() { checkedTaskNodeIds.push($(this).attr('catId')); }); if(checkedTaskNodeIds.length > 0){ if(confirm('Are you sure you want to delete the selected task?')) { var inputId = "input"; inputId = document.createElement("input"); inputId.type="hidden"; inputId.name = "defaultTaskId"; inputId.id = "defaultTaskId"; inputId.value = selected; var formSubmit = document.getElementById("idtaskoperationsform"); formSubmit.appendChild(inputId); prepareSearchAndSortSectionAndInsert("idtaskoperationsform",null); $('#idtaskoperationsform').attr('action', 'deleteTx'); $('#idsubmitoperation').click(); } }else{ alert("Please select a task to delete"); } } } function cancelTransferredTaskCommonView(s) { var id = ''; if(s.id=='idcncltransfrmview') { id = $('#taskIdTxt').val(); closeViewMyTask(); } else { id = $('#'+s.id).attr('itemId'); } $('#idtaskoperationsform').attr('action', 'canceltransfer'); $('#operationId').val(id); $('#idsubmitoperation').click(); } function cancelTransferredTaskFromView() { var checkedTaskIds = []; checkedTaskIds.push($('#taskIdTxt').val()); closeViewMyTask(); var postData = {"taskIds" : checkedTaskIds}; var form = document.getElementById('transferredNotMyTaskForm'); form.elements["taskData"].value = JSON.stringify(postData); form.elements["operationType"].value = "cancelTransferredTask"; form.action = "userTaskAction.action?searchTaskString="+$("#searchText").val()+"&taskStatus="+$("#filterStatus").val()+"&filterClosedWeek="+$("#filterClosedWeek").val()+"&notInMyTask=notInMyTask"; form.elements["transferredNotMyTaskFormSubmit"].click(); } function cancelSelectedTransferredTask() { var selected = ''; var count = 0; $('input[id^="checkedTask_"]').each(function() { if(this.checked) { selected += $('#'+this.id).attr('catId')+','; count++; } }); if(count == 0) { alert('Please select an outgoing task to cancel transfer.'); } else { $('#idtaskoperationsform').attr('action', 'canceltransfer'); $('#operationId').val(selected); $('#idsubmitoperation').click(); } }
function isEmpty(val) { return ((val !== "") || (val !== undefined) || (val.length > 0) || (val !== null)); } if (isEmpty(textInput)) { let defaultTxt = document.getElementsByClassName('defaultTxt'); for (var i = 0; i < defaultTxt.length; i++) { defaultTxt[i].innerHTML = 'Then came the night of the first falling star.'; } } //add text input functionality let input = document.getElementById('textInput'); let output = document.getElementsByClassName('outputText'); input.addEventListener('keyup', function() { for (var i = 0; i < output.length; i++) { output[i].innerHTML = input.value; } }); // add font size change functionality let size = document.querySelector('#fontSize'); let result = document.getElementsByClassName('sampleText'); size.addEventListener('change', function() { let resultFont = size.value; for (var i = 0; i < result.length; i++) { result[i].style.fontSize = resultFont; } }); //add reset button functionality const resetbtn = document.getElementById('reset'); resetbtn.addEventListener('click', function() { input.value = ''; size.value = '12px'; for (i = 0; i < output.length; i++) { output[i].innerHTML = 'Then came the night of the first falling star.'; } for (i = 0; i < result.length; i++) { result[i].style.fontSize = '14px'; } }); //add light/dark toggle let darkToggle = document.getElementById('dark'); let lightToggle = document.getElementById('light'); let body = document.querySelector('body'); darkToggle.addEventListener('click', function() { body.style.backgroundColor = '#545454'; body.style.color = '#efefef'; }); lightToggle.addEventListener('click', function() { body.style.backgroundColor = 'white'; body.style.color = 'black'; });
 Ext.onReady(function () { var filterPanel = Ext.create('Ext.form.Panel', { bodyPadding: 10, // Don't want content to crunch against the borders title: PAYEASY, items: [ { html: PAYEASYWARNING, border: 0, height: 40 }, { html: PAYEASYID, border:0, height:20 }, { xtype: 'numberfield', id: 'product_id', name: 'product_id', minValue: 1, fieldlabel: PRODUCTSTART }, { xtype: 'button', text: CONFIRM, handler: function () { //alert(Ext.getCmp('product_id').getValue()); window.open('/payeasy/outexcel?product_id=' + Ext.getCmp('product_id').getValue()); } }] // renderTo: Ext.getBody() }); var filterPanel2 = Ext.create('Ext.form.Panel', { bodyPadding: 10, // Don't want content to crunch against the borders title: PAYEASYEDIT, url: '/PayEasy/OutExcel2', items: [ { html: PAYEASYWARN, border: 0, height:40 }, { //專區Banner xtype: 'filefield', name: 'banner_image', id: 'banner_image', fieldLabel: UPPRODUCT, msgTarget: 'side', allowBlank: false, buttonText: SELECTEXC, fileUpload: true }, { xtype: 'button', text: CONFIRM, width: 50, handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ }); } } }] // renderTo: Ext.getBody() }); Ext.create('Ext.tab.Panel', { renderTo: Ext.getBody(), items: [filterPanel, filterPanel2 ] }); }); PayeaseCsv = function () { Ext.Ajax.request({ url: '/PayEasy/OutExcel3', method: 'post', params: { product_id: Ext.getCmp("product_id").getValue() }, failure: function () { Ext.Msg.alert("a", "操作失敗"); } }); }
import React from "react"; import StickyFooter from "../../reusableComponents/stickyFooter"; import "../Vaccine/vaccine.css"; import PromotionCard from "../../reusableComponents/PromotionCard"; import VaccineInfo from "./Vaccine-Info"; // Assets import RoundArrow from "../../../icons/Arrow.svg"; export const VaccinePage = () => { const paragraph = "In a country that is home to the world’s second-largest population when one of its largest enterprises providentially happens to be a philanthropic organisation, it raises hopes for a promising and sustainable future"; return ( <div id="Vaccine-Container" className="main-container"> <div id="content-container" className="container"> <div className="headerText"> <h1 id="content-container-heading"> HOME </h1> </div> <PromotionCard header="NBSC FOUNDATION" img={RoundArrow} paragraph={paragraph} /> <VaccineInfo /> </div> <StickyFooter /> </div> ); }; //<PromotionCard />
//bài 1 function func1(x) { return (x**2); } //bài 2 function func2(a,b,c) { let x=3*a+2*b-c; return func1(x); } //bài 3 function func3(str) { return str.substring(0, 10) + '...'; } //bài 4 function func4(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } //bài 5 function func5(number) { return Math.min.apply(null,number); } //bài 6 function bai6(arr) { //sắp xếp arr.sort(function(a,b){ return a.localeCompare(b); }); console.log('arr :', arr); //in từng phần tử ra màn hình for (let i=0; i<arr.length; i++){ document.write("phan tu "+ (i+1)+" la: "+arr[i]); } } function bai6nguoc(arr) { return arr.reverse(); } //bài 7 //vòng lặp //vl1 function vl1(a){ let giaithua = 1; for (var i = 1; i <=a; i++) { giaithua = giaithua * i; } return giaithua; } //vl2 function vl2(arr){ return arr.reverse(); }
let db = require('./dbRoutes'); let fs = require('fs'); module.exports = function (app) { app.get("/readDescription", function (req, res) { fs.readFile('./website-content/jeugdhuis-description.json', (err, data) => { if (err) throw err; let description = JSON.parse(data); res.json(description); }); }); app.post("/changeDescription", function (req, res, err) { console.log(req["body"]); let data = JSON.stringify(req["body"]); fs.writeFileSync('./website-content/jeugdhuis-description.json', data) }); app.get("/readAppDescription", function (req, res) { fs.readFile('./website-content/app-description.json', (err, data) => { if (err) throw err; let student = JSON.parse(data); res.json(student); console.log(student); }); }); app.post("/changeAppDescription", function (req, res, err) { console.log(req["body"]); let data = JSON.stringify(req["body"]); fs.writeFileSync('./website-content/app-description.json', data) }); app.get("/readMembers", function (req, res) { db.getAllMembers(result => { res.json(result); }) }); app.post("/addMember", function (req,res,err) { let memberToAdd = req["body"]; console.log("member: " + memberToAdd); db.addMember(memberToAdd,result => { res.json(result); }) }); app.post("/deleteMember", function (req, res, err) { let memberId = req["body"]; db.deleteMemberById(parseInt(memberId["id"]),result => { res.json(result); }) }); app.get("/readAboutUs", function (req,res,err){ fs.readFile('./website-content/about-us-description.json', (err, data) => { if (err) throw err; let description = JSON.parse(data); res.json(description); }); }); app.post("/changeAboutUs",function(req,res,err){ let data = JSON.stringify(req["body"]); fs.writeFileSync('./website-content/about-us-description.json', data) }); };
class ActiveEquation{ constructor(equation_obj, position_obj, id, jsavObject, globalPointerReference){ this.name=id; //console.log(this.name); this.equationObjectReference = equation_obj; this.selected = false; this.variables = {}; this.globalPointerReference = globalPointerReference; // members for visuals this.jsavequation = null; this.jsavObject = jsavObject; this.positionObj = position_obj; this.visualComponents = {}; this.createVisualEquation(position_obj, jsavObject); Window.jsavObject.logEvent({type: "deforms-equation-created", desc: this.name}); } getEquationSummary() { let equationSummary = { id: this.name, equation_template_id: this.equationObjectReference.id, variables: {} }; for(var i_var in this.variables) equationSummary.variables[i_var] = this.variables[i_var].getVariableSummary(); return equationSummary; } createVisualEquation(position_obj, jsavObject){ // Adding a tickmark object that indicates which equation is selected this.visualComponents["tickmark"] = jsavObject.label( //"OK", "&#x2610", { left: position_obj["POSITION_X"], top: position_obj["POSITION_Y"] } ).addClass("activeEqMenu"); this.visualComponents["tickmark"].element[0].dataset.selected="unselected"; this.visualComponents["tickmark"].element[0].addEventListener("click", e => { e.stopPropagation(); if(this.selected==true){ this.selected = false; this.visualComponents["tickmark"].element[0].innerHTML = "&#x2610"; this.visualComponents["tickmark"].element[0].dataset.selected="unselected"; // this.visualComponents["tickmark"].removeClass("tickselected"); Window.jsavObject.logEvent({type: "deforms-equation-unselected", desc: this.name}); } else{ this.selected = true; this.visualComponents["tickmark"].element[0].innerHTML = "&#x2611"; this.visualComponents["tickmark"].element[0].dataset.selected="selected"; // this.visualComponents["tickmark"].removeClass("tickunselected"); Window.jsavObject.logEvent({type: "deforms-equation-selected", desc: this.name}); } }); this.visualComponents["tickmark"].element[0] .setAttribute("title", "Click to select this equation and others to create a system, followed by clicking on Solve to solve the system."); // Delete button is added to remove the individual equation this.visualComponents["delete"] = jsavObject.label( "&#x2702", // "&#x1F5D1", { left: position_obj["POSITION_X"]+ this.visualComponents["tickmark"].element[0].offsetWidth+10, top: position_obj["POSITION_Y"], // left: 5, // top: 0, // relativeTo: this.visualComponents["tickmark"].element[0], // anchor: "right top", // myAnchor: "left top" } ).addClass("activeEqMenu"); this.visualComponents["delete"].element[0].dataset.id = this.name.split("_")[2]-1; this.visualComponents["delete"].element[0].dataset.wkid = this.name.split("_")[0].slice(2,); this.visualComponents["delete"].element[0].setAttribute("title", "Click to remove the equation, with values and associations."); // Adding a help button to provide instructions about the usage of how to use the equations. this.visualComponents["help"] = jsavObject.label( "&#xFFFD", { left: position_obj["POSITION_X"]+ this.visualComponents["tickmark"].element[0].offsetWidth+10+ this.visualComponents["delete"].element[0].offsetWidth+10, top: position_obj["POSITION_Y"] } ).addClass("activeEqMenu"); this.visualComponents["help"].element[0].dataset.id = this.name.split("_")[2]-1; this.visualComponents["help"].element[0].dataset.wkid = this.name.split("_")[0].slice(2,); this.visualComponents["help"].element[0].setAttribute("title", "Click here for help about the equations."); this.visualComponents["help"].element[0].addEventListener( "click", e=> { e.stopPropagation(); Window.jsavObject.logEvent({type: "deforms-equation-help-clicked", desc: this.name}); Window.showHelp("boxedEquation",e); }); // Adding a template text for the equation that was added, that shows the equation's subscripts // console.log(this.equationObjectReference) // Creating the visual elements. this.visualComponents["text"] = jsavObject.label( // katex.renderToString(this.name.split('_')[2]+": "+this.equationObjectReference["latex"]), katex.renderToString(this.equationObjectReference["latex"]), { left: position_obj["POSITION_X"]+ this.visualComponents["tickmark"].element[0].offsetWidth+10+ // Test if +5 or +13 works this.visualComponents["delete"].element[0].offsetWidth+10+ this.visualComponents["help"].element[0].offsetWidth+10, top: position_obj["POSITION_Y"]+3 } ).addClass("workspaceEquation"); this.visualComponents["text"].element[0].setAttribute("title", "Click to add a subscript to label this equation, or remove label."); this.visualComponents["text"].element[0].addEventListener("click", e=> { // Window.parentObject = this; e.stopPropagation(); this.subscriptizeEquationComponents(this); }); /** * Add code here to add an additional span class to every single box, * and associate a click handler with that span class container, so that * elements inside this span class are substituted out. * Look for this: <span class="mord amsrm">□</span> */ this.jsavequation = jsavObject.label( katex.renderToString(this.equationObjectReference["latex_boxes"]), { left: position_obj["POSITION_X"]+ this.visualComponents["tickmark"].element[0].offsetWidth+10+ // test if +5 or +13 helps this.visualComponents["delete"].element[0].offsetWidth+10+ this.visualComponents["help"].element[0].offsetWidth+10+ this.visualComponents["text"].element[0].offsetWidth+20, // test if +30 or +22 helps top: position_obj["POSITION_Y"] } ).addClass("boxedEquation"); // To be useful later. this.visualComponents["height"] = this.equationObjectReference.height; var boxList = this.jsavequation.element[0].childNodes[0].childNodes[1].childNodes[2] .querySelectorAll("span.mord.amsrm") //console.log(boxList); /** * Delegation: we handle the modification of the elements here, since we are * creating the boxes here. As for actually setting up the clickhandlers, * that is done in the call to createVariableBoxes(), so we change the query * for qSA to look for the container. */ for(var i=0; i<boxList.length; i++) { //var containerSpan = document.createElement("span"); boxList[i].className = "boxparam"; boxList[i].setAttribute("data-domain", "empty"); boxList[i].setAttribute("title", "Click to show menu."); //boxList[i].innerHTML = '<span class="mord amsrm">&#9634;</span>'; boxList[i].innerHTML = '<span class="mord value"></span><span class="mord unit"></span>'; } // setting an id for the main equation box element this.jsavequation.element[0].setAttribute("id",this.name); // Immediately create the variable boxes this.createVariableBoxes(); } createVariableBoxes(){ // This one is associated with creating Variable objects to go hand-in-hand with // box/parameter positions in the boxed representation var boxList = this.jsavequation.element[0].childNodes[0].childNodes[1].childNodes[2] .querySelectorAll("span.boxparam"); //console.log(boxList); for(var boxIndex=0; boxIndex<boxList.length; boxIndex++) { // add a line for a hidden non nodifiable variable for fixed constants var name = Window.getVarName(); var currentBox = boxList[boxIndex]; this.variables[this.equationObjectReference.params[boxIndex]] = new Variable( this.name+"_"+this.equationObjectReference.params[boxIndex], // name unique to workspace, equation, and parameter this.equationObjectReference.params[boxIndex], name, // actual variable name to be used everywhere else. this.equationObjectReference.variables[this.equationObjectReference.params[boxIndex]], this.equationObjectReference.domains[this.equationObjectReference.params[boxIndex]], currentBox, this.globalPointerReference, ) } } // oldCreateSolvableRepresentation(){ // // DEPRECATED: Features of Nerdamer+peculiarities required us to do things differently. // // Plus, this function is really messily written. // // TO WORK SPECIFICALLY ON THIS PART, TO CREATE THE SOLVABLE REPRESENTATION AND FINALLY, SOLUTION BOX // var splitString = this.equationObjectReference.template.split(" "); // for(var x=0; x<splitString.length; x++) // { // if(splitString[x], splitString[x] in this.variables) // { // if(this.variables[splitString[x]].value!=null) // splitString[x] = this.variables[splitString[x]].value; // else // { // // If this is called, there will be more than one unknown in the system. // // So, we need the current symbol, which would in turn be assigned by the // // corresponding Association object. // //splitString[x] = this.variables[splitString[x]].currentSymbol; // if(this.variables[splitString[x]].value == null){ // // Then this is probably a single equation solving scenario, use id. // splitString[x] = this.variables[splitString[x]].currentSymbol; // } // else if(this.variables[splitString[x]].valueType == "number"){ // splitString[x] = this.variables[splitString[x]].value; // } // else { // // it's an association, look up appropriate field. // //splitString[x] = this.variables[splitString[x]].value.varID; // } // } // } // } // return splitString.join(" "); // } createSolvableRepresentation(){ var unitEquationSet = []; var unknowns = {}; var knowns = {}; var splitString = this.equationObjectReference.template.split(" "); for(var x=0; x<splitString.length; x++) { // DEBUG: // console.log(splitString[x]); // if(splitString[x], splitString[x] in this.variables) if(splitString[x] in this.variables) { if(this.variables[splitString[x]].valueType=="number") { // Add the variable=value assignment separately, putting only // variables in the equation representation. var value = this.variables[splitString[x]].value; var varName = this.variables[splitString[x]].currentSymbol; var currentUnit = this.variables[splitString[x]].currentUnit; var source = this.variables[splitString[x]].valueSource; // stores where this value came from for graph creation. unitEquationSet.push(varName+"="+value); splitString[x] = varName; // this.variables[splitString[x]].currentSymbol; knowns[varName] = {"value":value, "unit": currentUnit, "source": source}; } else { // This just means that there is an association -> valueType="association" // Unlike the previous version, in our case, we will always have >1 equation. // So, we simply check for the term, and call on its representation variable. if(this.variables[splitString[x]].valueType=="association") { var ps = this.variables[splitString[x]].value.varDisplay; // splitString[x] = this.variables[splitString[x]].value.var; // unknowns[this.variables[splitString[x]].value.var] = ps; var subject = this.variables[splitString[x]].value.var; if(this.variables[splitString[x]].valueNegated) splitString[x] = "(-"+subject+")"; else splitString[x] = subject; unknowns[subject] = ps; } else { // OR it's a single unmarked, unconnected unknown var ps = this.variables[splitString[x]].parentSymbol; // splitString[x] = this.variables[splitString[x]].currentSymbol; // unknowns[splitString[x]] = ps; var subject = this.variables[splitString[x]].currentSymbol; if(this.variables[splitString[x]].valueNegated) splitString[x] = "(-"+subject+")"; else splitString[x] = subject; unknowns[subject] = ps; } } } } unitEquationSet.push(splitString.join(" ")); return { "equations": unitEquationSet, "unknowns": unknowns, "knowns": knowns }; } solve() { // Insert checking mechanism first, this is a complete functionality. //Then, solve it. var splitString = this.equationObjectReference.template.split(" "); var subject = null; for(var x=0; x<splitString.length; x++) { if(splitString[x] in this.variables) { if(this.variables[splitString[x]].valueType=="number") splitString[x] = this.variables[splitString[x]].value; else { // This just means that there is an association -> valueType="association" // Unlike the previous version, in our case, we will always have >1 equation. // So, we simply check for the term, and call on its representation variable. if(this.variables[splitString[x]].valueType=="association") { // var ps = this.variables[splitString[x]].value.varDisplay; splitString[x] = this.variables[splitString[x]].value.var; if(this.variables[splitString[x]].valueNegated) splitString[x] = "(-"+subject+")"; else splitString[x] = subject; } else { // OR it's a single unmarked, unconnected unknown // var ps = this.variables[splitString[x]].parentSymbol; subject = this.variables[splitString[x]].currentSymbol; if(this.variables[splitString[x]].valueNegated) splitString[x] = "(-"+subject+")"; else splitString[x] = subject; } } } } var solutions = nerdamer.solveEquations( [splitString.join(" "), subject+" = x + 1"] ); console.log(solutions); for(var i in solutions) { if(solutions[i][0] == subject) { return [solutions[i]]; } } //Substitute the random symbol name with the proper qualified variable name } subscriptizeEquationComponents(activeEqObject){ // Steps: // 1. Add subscripts to all the elements in the equation in the represented version // 2. Add subscripts to all the grayed out boxes in the boxed equation // 3. For all filled boxes with Association type objects, add subscripts // 4. For ALL of these cases, add subscripts to both the text representation as well as the visual representation. // console.log(this); var inputPromptHTML = '<h4>Enter a subscript name here.</h4>'+ '<input type="text" id="subscriptname" name="subscriptname" size="8" />'+ '<input type="button" id="submit" value="Set subscript"/>'; var inputBox = JSAV.utils.dialog(inputPromptHTML, {width: 150}); inputBox[0].style.top = event.pageY+5+"px"; inputBox[0].style.left = event.pageX+10+"px"; Window.box = inputBox; Window.showBlankPrompt = false; inputBox[0].addEventListener("click", e=> { e.stopPropagation(); }) inputBox[0].querySelector("#submit").addEventListener("click", e=> { e.stopPropagation(); // Window.parentObject.setSubscript( activeEqObject.setSubscript( e, Window.box[0].querySelector("#subscriptname").value, // Window.parentObject); activeEqObject); Window.box.close(); // Pushing event Window.jsavObject.logEvent({ type: "deforms-equation-subscripted", desc: { name: activeEqObject.name, subscript: Window.box[0].querySelector("#subscriptname").value } }); // Cleaning up delete Window.box; delete Window.parentObject; } ); } setSubscript(event, subscriptText, equationObject) { // var subscriptText = Window.box[0].querySelector("#subscriptname").value; // event.stopPropagation(); if(subscriptText == "") subscriptText = " "; // Step 1. equationObject.visualComponents["text"].text( katex.renderToString( // equationObject.name.split('_')[2]+": "+equationObject.equationObjectReference.latex.replace(new RegExp('_\{[A-Za-z0-9 ]+\}', 'g'),"_{"+subscriptText+"}") equationObject.equationObjectReference.latex.replace(new RegExp('_\{[A-Za-z0-9 ]+\}', 'g'),"_{"+subscriptText+"}") ) ); var assocVariables = []; for(var variable in equationObject.variables) { // Update the variable internal symbols for later associations and solving // This can be referenced from the current equation's equationRefObj and the variable's semantic name. // Update the current displayed boxes // Step 2. if (subscriptText == " ") equationObject.variables[variable].parentSymbol = equationObject.variables[variable].parentSymbolTemplate; else equationObject.variables[variable].parentSymbol = // equationObject.variables[variable].parentSymbolTemplate.replace( equationObject.variables[variable].parentSymbol.replace( new RegExp('_\{[A-Za-z0-9 ]+\}', 'g'),"_{"+subscriptText+"}"); // equationObject.variables[variable].subscript = subscriptText; // Not yet; we don't need this just yet. // Note: Expected behaviour with renaming variables explicitly for empty variable boxes - // Either the new variables will have empty subscripts, in which case the above will work just fine. // There will be empty { } groups in the parentSymbolTemplate which will be discovered and replaced // And when resetting, these will be used again. // However, if the variable does not have a { } group, then it won't get discovered, and it won't be replaced. if(equationObject.variables[variable].valueType != "number") { // Step 3. // else if(Window.parentObject.variables[variable].valueType == "association") if(equationObject.variables[variable].valueType == "association") { if(equationObject.variables[variable].value.startingAssocSubscriptEquationId == equationObject.name) // This part is debatable { // console.log(equationObject.variables[variable].value.startingAssocSubscriptEquationId); // console.log(equationObject.name); // equationObject.variables[variable].value.varDisplay = // equationObject.variables[variable].value.varDisplay // .replace(new RegExp('_\{[A-Za-z0-9 ]+\}', 'g'),"_{"+subscriptText+"}"); // equationObject.variables[variable].value.updateVarDisplay(); equationObject.variables[variable].value.setAssocVarDisplay("", subscriptText); } } else equationObject.variables[variable].grayOut(); } } // TODO: Can be shortened to make the calls from inside one another; makes the segment less complicated. // Adjusting the visuals of the equation var shiftChain = Window.windowManager.shiftRight(equationObject); // console.log(shiftChain); if(shiftChain == "shiftActiveEqDown") { // console.log(Window.parentObject); var extend = Window.windowManager.shiftActiveEqDown(equationObject.name); if(extend != null) { var split = equationObject.name.split("_"); var wkspaceNum = split[0].substring(2, split[0].length); Window.windowManager.shiftDown(extend, wkspaceNum); } } else if(shiftChain == "shiftActiveEqUp") { Window.windowManager.shiftActiveEqUp(equationObject.name); } // Window.box.close(); // delete Window.box; // delete Window.parentObject; } // OldgetUnitOfVariable(varName) // { // // Find the unknown variable - which can be an option later, if no parameter is passed. // // var varName = null; // // console.log("in getUnitOfVariable for"+varName); // // NOTES: In our observation, we can either have an unknown that has an association, or that does not (i.e. is null). // // If an unknown is associated, then it maybe difficult to compute its domain from inside // // especially if this equation contains atleast one unknown with a weird datatype. // // PLACEHOLDER FOR POTENTIAL HACK // // If an unknown is null (not associated), then we want to spend sometime computing its domain. // var splitString = this.equationObjectReference.template.split(" "); // for(var x=0; x<splitString.length; x++) // { // if(splitString[x] in this.variables) // { // if(this.variables[splitString[x]].value == null || this.variables[splitString[x]].valueType == "number") // { // // Single solver; one unknown, with // splitString[x] = this.variables[splitString[x]].currentSymbol; // } // else if(this.variables[splitString[x]].valueType == 'association') // { // // if there is an association, adds that automatically. // splitString[x] = this.variables[splitString[x]].value.var; // } // // No need for the numbers, we only need the variable symbols. // } // } // var equation = nerdamer(splitString.join(" ")); // var substituted = equation.solveFor(varName).toString() // Only reference of varName, used when the // var values = {}; // var flagIndeterminate = false; // for(var v in this.variables) // { // // This assumes that this is for a single variable solving scenario. // if(this.variables[v].valueType == "number") // { // values[this.variables[v].currentSymbol] = '1 '+this.variables[v].currentUnit; // } // else if(this.variables[v].valueType == "association") // { // // The domain is this case would obviously be unknown. // // For now, use the expected domain attribute of the variable to find the corresponding base unit // // console.log( // // "Can we find the right unit?", // // this.variables[v].value.domain, // // Window.defaultDomains[this.variables[v].value.domain], // // Window.defaultDomains[this.variables[v].value.domain][Window.unitFamily], // // ) // var unitName = Window.defaultDomains[this.variables[v].value.domain][Window.unitFamily]; // // values[this.variables[v].currentSymbol] = '1 '+ // values[this.variables[v].value.var] = '1 '+ // Window.UNIT_DB[this.variables[v].value.domain][unitName]['unit']; // // console.log("Did we find the right unit?",values[this.variables[v].currentSymbol]); // } // else if(this.variables[v].valueType == null) // { // // Probably the unknown we would calculate things for anyway; it hasn't been associated yet. // // Don't worry about it; this will certainly be the one we will be calculating the unit for. // // However, if we need the unit for this thing to infer the unit of something else, then enable this. // if (this.equationObjectReference.group == 'Arithmetic') { // // Special case, this is needed because everything else (mult, div, etc.) can fix itself (UPDATE: Maybe not) // // values[this.variables[v].currentSymbol] = ''; // Just leave it blank, let the rest of the units determine the rest. // // When it comes here, either this.variables[v] is the varName whose unit is requested, // // or this is the varName whose unit will be used for inference. // // For the first case, we can leave it blank. // if (varName == this.variables[v].currentSymbol) // It's not an assoc, otherwise it wouldn't be null // values[this.variables[v].currentSymbol] = ''; // // Else, we abort and directly return the expectedDomain and corresponding unit for the requested variable. // // We already have some info to go off of, we don't need to waste anymore time. // else { // flagIndeterminate = true; // } // } // else { // var unitName = Window.defaultDomains[this.variables[v].expectedDomain][Window.unitFamily]; // values[this.variables[v].currentSymbol] = '1 '+ Window.UNIT_DB[this.variables[v].expectedDomain][unitName]['unit']; // } // // Alternatively; try to find out what the unit for this thing should be, then use it for this one. // // values[this.variables[v].currentSymbol] = '1 '+ this.getUnitOfVariable(this.variables[v].currentSymbol)[1]; // } // } // // By this point, things have been calculated, and can be indexed by the proper variable name. // if(flagIndeterminate) { // var resultUnit = values[varName].split(" ")[1]; // if(resultUnit in Window.unitDomainMap) // var domain = Window.unitDomainMap[resultUnit]; // else // var domain = "unknown"; // temporary fix // return [varName, resultUnit, domain]; // } // // console.log(substituted); // // console.log(values); // for(var v in values) // { // substituted = substituted.replace(v,"("+values[v]+")"); // } // // console.log(substituted); // var resultUnit = mathjs.evaluate(substituted).toString().split(" ")[1]; // if(resultUnit in Window.unitDomainMap) // var domain = Window.unitDomainMap[resultUnit]; // else // var domain = "unknown"; // temporary fix // return [varName, resultUnit, domain]; // } // getUnitOfVariable(varName) // { // console.log("in getUnitOfVariable for"+varName); // // Create the representable version of the equation with only variable names. // // This will be placeholders for manipulation later. // var splitString = this.equationObjectReference.template.split(" "); // for(var x=0; x<splitString.length; x++) // { // if(splitString[x] in this.variables) // { // if(this.variables[splitString[x]].value == null || // this.variables[splitString[x]].valueType == "number") // { // splitString[x] = this.variables[splitString[x]].currentSymbol; // } // else if(this.variables[splitString[x]].valueType == 'association') // { // splitString[x] = this.variables[splitString[x]].value.var; // } // } // } // var equation = nerdamer(splitString.join(" ")); // var substituted = equation.solveFor(varName).toString() // Only reference of varName, used when the // // Now, assign the units to the variables // var values = {}; // var domains = {}; // var flagIndeterminate = false; // for(var v in this.variables) // { // if(this.variables[v].valueType == "number") // { // console.log("Inside number", this.variables[v]); // values[this.variables[v].currentSymbol] = '1 '+this.variables[v].currentUnit; // domains[this.variables[v].currentSymbol] = this.variables[v].currentDomain; // } // else if(this.variables[v].valueType == "association") // { // console.log("Domain of the current variable box", // this.variables[v].value.domain, // Window.UNIT_DB[this.variables[v].value.domain], // ) // var unitName = Window.defaultDomains[this.variables[v].value.domain][Window.unitFamily]; // // console.log(Window.UNIT_DB[this.variables[v].value.domain][unitName]); // // console.log(Window.UNIT_DB[this.variables[v].value.domain][unitName]['unit']); // values[this.variables[v].value.var] = '1 '+ // Window.UNIT_DB[this.variables[v].value.domain][unitName]['unit']; // domains[this.variables[v].value.var] = this.variables[v].value.domain; // console.log("Did we find the right unit?",values[this.variables[v].currentSymbol]); // } // else if(this.variables[v].valueType == null) // { // if(this.variables[v].expectedDomain != "free") // { // // Not a free domain, which means we know exactly what is supposed to be here. // console.log("Inside non free variale domain unknown non assoc", this.variables[v]); // var unitName = Window.defaultDomains[this.variables[v].expectedDomain][Window.unitFamily]; // values[this.variables[v].currentSymbol] = // '1 '+ Window.UNIT_DB[this.variables[v].expectedDomain][unitName]['unit']; // domains[this.variables[v].currentSymbol] = this.variables[v].expectedDomain; // } // else // { // // It is a free domain variable, but is it the subject of this call to getUnitOfVariable() ? // if (varName == this.variables[v].currentSymbol) // values[this.variables[v].currentSymbol] = ''; // We set it to nothing, since it doesn't matter; it won't be used. Alt: just "continue" // else { // flagIndeterminate = true; continue; // // We don't know what this unit is going to be. But we need it to guess the units of the other variables. // // The best we can do is guess it from the other units in this equation. // // TODO: Replace this with proper inference rules from other equations, since for each it would be specific. // // TODO: (contd.) It may even be coded in and accessed, if we don't want to write a whole function // // But, eg: c = a + b; the call to this wants the domain of a; given domain of b is known and c is null, unassoc. // // Since a is requested, it has to be an unknown; so it must be an assoc. So, we return the // // expected domain of the requested variable, and call it a day. // var resultUnit = Window.defaultDomains[this.variables[varName].expectedDomain][Window.unitFamily]; // if(resultUnit in Window.unitDomainMap) // return [varName, resultUnit, Window.unitDomainMap[resultUnit]]; // else // return [varName, "unit", "unknown"]; // } // } // } // } // if(flagIndeterminate) { // var resultUnit = values[varName].split(" ")[1];; // // if(resultUnit in Window.unitDomainMap) // if(resultUnit in Window.unitDomainMap) // return [varName, resultUnit, Window.unitDomainMap[resultUnit]]; // // if (domains[varName] in Window.UNIT_DB) // // return [varName, resultUnit, domains[varName]]; // else // return [varName, "", ["unknown", ""]]; // } // console.log(values); // for(var v in values) substituted = substituted.replace(new RegExp(v, 'g'),"("+values[v]+")"); // console.log(substituted); // // Now, evaluate the expression to find the units // // var resultUnit = mathjs.evaluate(substituted).toString().split(" ")[1]; // var result = mathjs.evaluate(substituted).toString().split(" "); // // Now, the main logic: is this unit legit, not, or just dimensionless? // if(result.length == 1) // { // // The quantity is dimensionless, in which case, we need to evaluate what // // the dimensions were to begin with. Just find the baseUnit for that variable, // // and send that over. Let the others handle this conversion. // // Go through the variables to find the correct variable name, and find its expectedDomain. // var expDom = domains[varName]; // var unitName = Window.defaultDomains[expDom][Window.unitFamily]; // return [ // varName, // Window.UNIT_DB[expDom][unitName]['unit'], // [expDom, Window.UNIT_DB[expDom][unitName]['unitDisp']] // ]; // } // else { // // It's not dimensionless, we just need to verify this thing is correct. // var resultUnit = (result.slice(1)).join(" "); // TODO: add parser to get proper symbols for all units // console.log(result); // var resultDomain = Window.unitDomainMap[resultUnit]; // if(resultDomain != null) { // return [ varName, resultUnit, resultDomain ]; // } // else { // console.log("Can't figure out the usual domain") // resultDomain = domains[varName]; // try{ // console.log(resultDomain); // console.log(Window.defaultDomains[resultDomain]); // var parentUnitName = Window.defaultDomains[resultDomain][Window.unitFamily]; // var parentUnit = Window.UNIT_DB[resultDomain][parentUnitName]['unit']; // console.log(parentUnit); // // If this throws an error, then we have an actual type mismatch // // Otherwise, it just means the units simplified to something else: eg: N.m and J // var number = mathjs.evaluate("number(1 "+resultUnit+", "+parentUnit+")"); // console.log(Window.unitDomainMap[parentUnit]); // return [varName, parentUnit, Window.unitDomainMap[parentUnit], number]; // } // catch(err) // { // return [varName, resultUnit, ["unknown", resultUnit]] // } // } // } // } } window.ActiveEquation = window.ActiveEquation || ActiveEquation
var app=require('express').(); //以下引入为为了能解析json请求参数 var bodyParser = require('body-parser'); var multer = require('multer'); var fs = require("fs"); //var adddatasuccess = ' { fieldCount: 0,affectedRows: 1,insertId: 6,serverStatus: 2,warningCount: 0,message: '',protocol41: true,changedRows: 0 }' app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded var MongoClient=require('mongodb').MongoClient; var DB_CONN_STR = 'mongodb://localhost:27017/runoob'; var insertData = function(db, callback) { //连接到表 site var collection = db.collection('site'); //插入数据 var data = [{"name":"菜鸟教程","url":"www.runoob.com"},{"name":"菜鸟工具","url":"c.runoob.com"}]; collection.insert(data, function(err, result) { if(err) { console.log('Error:'+ err); return; } callback(result); }); } MongoClient.connect(DB_CONN_STR, function(err, db) { console.log("连接成功!"); insertData(db, function(result) { console.log(result); db.close(); }); });
import React from 'react' import './Divbar.css' function Divbar() { return ( <div className="divbar"> </div> ) } export default Divbar
import React from 'react'; // import Header from './components/Header'; // import MainContent from './components/MainContent'; // import Arrow from './components/Arrow'; // import Footer from './components/Footer'; // import LearnProps from './components/LearnProps'; // import data from './data'; // import LearnState from './components/LearnState'; // import LearnEvents from './components/LearnEvents'; // import LearnLifecicle from './components/LearnLifecicle'; //import LearnFetch from './components/LearnFetch'; import LearnRouter from './components/LearnRouter'; class App extends React.Component { render(){ return ( <LearnRouter/> ); } } export default App;
import './Foot.css'; import './facebook-white.svg'; import { ReactComponent as Facebook } from '../../assets/social/facebook-white.svg'; import { ReactComponent as Twitter } from '../../assets/social/twitter-white.svg'; import { ReactComponent as Ig } from '../../assets/social/instagram-white.svg'; import { ReactComponent as Apple } from '../../assets/store/app-store.svg'; import { ReactComponent as Play } from '../../assets/store/play-store.svg'; import { ReactComponent as MS } from '../../assets/store/windows-store.svg'; const Foot = () => { return ( <footer className='footer'> <div className='foot-div'> <button className='foot-nav'> Home</button> <hr /> <button className='foot-nav'> Terms and Conditions</button> <hr /> <button className='foot-nav'> Privacy Policy</button> <hr /> <button className='foot-nav'> Collection Statement</button> <hr /> <button className='foot-nav'> Help</button> <hr /> <button className='foot-nav'> Manage Account</button> </div> <div className='copyright-cont'> <p>Copyright © 2016 DEMO Streaming. All Rights Reserved.</p> </div> <div className='svg-cont'> <span className='social-content'> <button> <Facebook className='social-svg' /> </button> <button> <Twitter className='social-svg' /> </button> <button> <Ig className='social-svg' /> </button> </span> <span className='store-cont'> <button> <Apple className='store-svg' /> </button> <button> <Play className='store-svg' /> </button> <button> <MS className='store-svg' /> </button> </span> </div> </footer> ); }; export default Foot;
(function () { 'use strict'; angular .module('myApp', []) .service('AuthenticationService', service); function service($http) { this.authenticate = function (username, password, callback) { this.username = "admin"; this.password = "pass"; var authenticationUrl = "http://10.10.10.27:8080/cal-repo-api/repo" + "user/login"; $http.post(authenticationUrl, { userName: username, password: password }).success(function (response) { callback(response); }).error(function (err, status) { callback({ success: false, data: {message: 'Server Error'} }) }); } } })();
const path = require('path') const {app, BrowserWindow, MenuItem} = require('electron') const config = require('./config') const labels = { selectall: 'Выделить всё', cut: 'Вырезать', copy: 'Копировать', paste: 'Вставить', } require('electron-context-menu')({ showInspectElement: config.dev, append() { return [new MenuItem({role: 'selectall', label: 'Выделить всё'})] }, labels }) /* switch (process.platform) { case 'darwin': config.window.icon = __dirname + '/images/bitcoin.icns' break; case 'win32': config.window.icon = __dirname + '/images/bitcoin.ico' break; } */ BrowserWindow.prototype.loadFile = function (path) { return this.loadURL(`file://${__dirname}${path}`, { userAgent: 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' }) } app.on('ready', function () { const win = new BrowserWindow(config.window) // if ('win32' === process.platform) { // win.setOverlayIcon(config.window.icon, 'Application') // } win.loadFile('/index.html') win.webContents.on('did-finish-load', function () { win.webContents.send('config', { userDataPath: app.getPath('userData') }) }) if (config.dev) { win.webContents.openDevTools() // BrowserWindow.addDevToolsExtension(__dirname + '/../extensions/react') // BrowserWindow.addDevToolsExtension(__dirname + '/../extensions/imacros') } }) app.on('window-all-closed', () => { app.quit() })
window.assert = chai.assert; window.expect = chai.expect; localStorage.clear(); mocha.ui('bdd');
import { useBrix } from 'react-brix' import { useFilters } from './useFilters' import { List } from 'immutable' jest.mock('react') jest.mock('react-brix') describe('useFilters', () => { describe('genre', () => { let useGenreMock beforeEach(() => { jest.clearAllMocks() // eslint-disable-next-line Array.prototype.get = jest.fn(x => 0) useGenreMock = [['tragedy'], jest.fn()] useBrix.mockReturnValue(useGenreMock) }) test('returns filters, hooks', () => { const [filters, { useGenre }] = useFilters() expect(filters).toMatchSnapshot() expect(useGenre).toEqual(useGenreMock) }) }) describe('play_id', () => { let usePlayIdMock beforeEach(() => { jest.clearAllMocks() // eslint-disable-next-line String.prototype.get = jest.fn(x => 0) usePlayIdMock = ['1', jest.fn()] useBrix.mockReturnValue(usePlayIdMock) }) test('returns filters, hooks', () => { const [filters, { usePlayId }] = useFilters() expect(filters).toMatchSnapshot() expect(usePlayId).toEqual(usePlayIdMock) }) }) describe('rating', () => { let useRatingMock beforeEach(() => { jest.clearAllMocks() useRatingMock = [List([1, 2]), jest.fn()] useBrix.mockReturnValue(useRatingMock) }) test('returns filters, hooks', () => { const [filters, { useRating }] = useFilters() const expected = JSON.stringify([[1, 2], jest.fn()]) const result = JSON.stringify(useRating) expect(filters).toMatchSnapshot() expect(result).toEqual(expected) }) }) })
const Engine = Matter.Engine; const World= Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint var engine, world; var office var shooter function preload() { office = loadImage("office1.jpg") } function setup(){ var canvas = createCanvas(1600,400); engine = Engine.create(); world = engine.world; ground = new Ground(800,390,1600,20) paper = new Paper(200,200) dustbin = new Dustbin(1000,290,200,20) shooter = new Shooter(paper.body,{x:200, y:100}) } function keyPressed (){ if (keyCode === UP_ARROW){ Matter.Body.applyForce(paper.body,paper.body.position,{x:1000,y:-1100}); } } function draw(){ background("red"); image(office,800,200,1600,500) Engine.update(engine); ground.display(); dustbin.display(); paper.display(); shooter.display(); //text("x: "+mouseX+" ,y: "+mouseY,mouseX,mouseY) } function mouseDragged(){ Matter.Body.setPosition(paper.body, {x: mouseX , y: mouseY}); } function mouseReleased(){ shooter.fly(); }
'use strict'; let result = 0; let welcome; let date = new Date(); let hour = date.getHours(); let minute = date.getMinutes(); let second = date.getSeconds(); if (minute < 10) { minute = '0' + minute; } if (second < 10) { second = '0' + second; } if (hour < 12) { welcome = 'good morning'; } else if (hour < 17) { welcome = 'good afternoon'; } else { welcome = 'good evening'; } alert(welcome+' WELCOME TO MY PAGE (ABOUT ME), YOU SHOULD ANSWER SOME QUESTION TO GET IN, THERE IS A HINT FOR THE ANSWER YOU CAN CHANGE IT, AND AFTER THAT I WILL ASK ALSO SOME QUESTION ABOUT YOU TO GET KNOW EACH OTHER.'); let n1 = prompt('Is My Name Rawan?').toUpperCase(); let n2 = prompt('Am I Currently Student?').toUpperCase(); let n3 = prompt('Is My Passion Programming?').toUpperCase(); let n4 = prompt('Is Iy Favorite Hobby Reading?').toUpperCase(); let n5 = prompt('is My Favorite Animal Dog').toUpperCase(); let number = 100; let counter = 0; const numGuess = function (num){ for (let i = 1; i<=4; i++){ let n6 = prompt('Enter Any Nmber Please'); if( parseInt(n6) > num ){ alert('Too High'); } else if( parseInt(n6) < num ){ alert('Too Low'); } else if(n6 === ''){ alert('You Must Enter A Number'); } else{ counter++; alert('Congrats You Enter The Exact Number Which Is '+num+', After Number Of Attempts Equal to '+counter); result++; break; } counter++; } alert('You Have Exceeded The Number Of Times Available To Enter The Correct Number Which Is '+counter+', And The Correct Number Is 100'); console.log('Your Guess Is '+num); }; numGuess(number); let i = 1; let MyArr = ['phone', 'tv', 'laptob', 'watch', 'airpods', 'ipad']; const smartDevice = function(a){ while (i <= 6) { let n7 = prompt('Please Enter The Smart Devices That You Have, HINT Use phone, tv, laptob, watch, airpods, ipad, Or Any Other Devices').toLowerCase(); for (let i1 = 0; i1 < MyArr.length; i1++) { if (n7 === MyArr[i1]) { alert('Your Guess Is True, Try Another One'); alert('Well Done, Correct Answer Which is '+ MyArr[i1] +'\n'); console.log('Your Answer About The devices is correct and its the same of mine which they are: ' + MyArr[i1]); result++; i = 9; break; }} if(i <= 6){ alert('You Entered A Wrong Answer'); } i++;} alert('Your Result Equal '+result); console.log(a); }; smartDevice(MyArr); const checkName = function(){ switch(n1){ case 'YES': alert('Thats Correct You Guess My Name'); console.log('Thats Correct You Guess My Name which is: '+'RAWAN'); result++; break; default: alert('Your Guess About My Name Not Correct!'); break; } console.log('Your Guess About My Name Is '+n1); }; checkName(); const student = function(){ switch(n2){ case 'NO': alert('Thats Correct, Your Guess That I Am Not Student Is True'); console.log('Thats Correct You Guess The Answer Which Is: I Am Not Student'); result++; break; default: alert('Your Guess About If I Am Not Currently A Student Is Not Correct!'); break; } console.log('Your Guess About If I Am Student Is '+n2); }; student(); const passion = function(){ switch(n3){ case 'YES': alert('Thats Correct, Your Guess Is Right About What Is My Passion'); console.log('Thats Correct, You Guessed What Is My Passion which is programming '); result++; break; default: alert('Your Guess About My Passion Not Correct!'); break; } console.log('Your Guess About My passion Is '+n3); }; passion(); const favHoppy = function(){ switch(n4){ case 'YES': alert('Thats Correct, Your Guess Is Right About My Favorite Hoppy'); console.log('Thats Correct, You Guessed What Is My Favorite Hoppy which is reading'); result++; break; default: alert('Your Guess About My Favorite Hoppy Not Correct!'); break; }console.log('Your Guess About My Favorite Hoppy Is '+n4); }; favHoppy(); const favAnimal = function(){ switch(n5){ case 'YES': alert('Thats Correct, Your Guess Is Right About My Favorite Animal'); console.log('Thats Correct, You Guessed What Is My Favorite Animal which is dog'); result++; break; default: alert('Your Guess About My Favorite Animal Not Correct!'); break; }console.log('Your Guess About My Favorite Animal Is '+n1); alert('THANKS FOR ANSWERING THE QUESTIONS I APPRECIATE THAT, NOW I WILL ASK YOU SOME QUESTIONS ABOUT YOUR SELF.'); let p1 = prompt('What Is Your Name?'); let p2 = prompt('What Is Your Favorite Sport?'); let p3 = prompt('What Is Your Favorite Sports Team?'); let p5 = prompt('What is Your favorite hobby?'); alert('HELLO ' + p1 + ' THANKS AGAIN FOR ANSWERING THE QUESTIONS, I APPRECIATE THAT, NICE TO MEET YOU.'); const count = function(r){ if (result > 4) { alert('Thank You ' + p1 + ' The Result Equal ' + r + ',your information about me very good'); } else { alert('Thank You ' + p1 + 'For Trying The Result Equal ' + r + ',you dont know me very well'); } console.log('Your total result equal to '+r); }; count(result); };
import React, { Component } from 'react' import {Body, Button, Container, Content, Text,} from 'native-base' import {View, Image} from 'react-native' import styles from './styles' import { compose } from "redux"; import _ from 'lodash' import { connect } from 'react-redux' import {SYSTEM_ROUTES} from "../../constants"; class PetAdoptedScreen extends Component { render() { const {navigation, handleSubmit, submitting, pristine} = this.props; return ( <Container> <Content> <View style={styles.container}> <Image source={require('../../../public/images/iconGreen.jpg')} style={styles.image} resizeMode="contain" /> <Text style={styles.textCongratulations}>Meus parabéns!</Text> <View style={styles.viewBody}> <Text style={styles.textBody}>Você acaba de adotar um pet e</Text> <Text style={styles.textBody}>a colaborar para um mundo melhor.</Text> </View> <View style={styles.viewBody}> <Text style={styles.textBody}>Estamos dando de presente para você</Text> <View style={styles.viewTextCupom}> <Text style={styles.textCupom}>20% DE DESCONTO </Text> <Text style={styles.textCupomCenter}>na</Text> <Text style={styles.textCupom}> GERAÇÃO PET</Text> </View> </View> <View style={styles.lastView}> <Text style={styles.textCupomCenter}>Na sua compra use o cupom </Text> <Text style={styles.textCupom}>GERACAOPET20</Text> </View> <Button full style={styles.buttonSubmit} //disabled={pristine || submitting} onPress={() => navigation.popToTop()} > <Text style={styles.textButtonSubmit}>Voltar ao menu</Text> </Button> </View> </Content> </Container> ) } } // const mapStateToProps = (state) => ({ // // }); PetAdoptedScreen = compose( connect(null, { }), )(PetAdoptedScreen); export { PetAdoptedScreen }
import { chevronIcon } from "../Icons"; import toggleCollapsibleContent from "./toggleCollapsibleContent"; /** * @function makeCollapsible * @param {HTMLElement} parentNode * @param {HTMLElement} contentNode * @param {HTMLElement} [togglerNode] */ const makeCollapsible = (parentNode, contentNode, togglerNode) => { parentNode.classList.add("o-collapsible"); contentNode.classList.add("o-collapsible__content"); contentNode.style.maxHeight = "100%"; if (togglerNode) { togglerNode.prepend(chevronIcon()); togglerNode.classList.add("o-collapsible__toggler"); togglerNode.addEventListener("click", (e) => { toggleCollapsibleContent(e.currentTarget); }); } else { const chevron = document.createElement("button"); chevron.classList.add("o-collapsible__toggler"); chevron.append(chevronIcon()); chevron.addEventListener("click", (e) => { toggleCollapsibleContent(e.currentTarget); }); parentNode.prepend(chevron); } }; export default makeCollapsible;
import { useState, useEffect, useLayoutEffect, useRef } from 'react'; const fetchData = (url, signal, setState) => { fetch(url, { signal }) .then(rsp => rsp.ok ? rsp : Promise.reject({ message: rsp.statusText, status: rsp.status }) ) .then(rsp => rsp.json()) .then(data => { setState(oldState => ({ ...oldState, data, loading: oldState.loading - 1 })); }) .catch(err => { const error = err.name !== 'AbortError' ? err : null; setState(oldState => ({ ...oldState, error, loading: oldState.loading - 1 })); }); }; const useAbortableFetch = url => { const [state, setState] = useState({ data: null, loading: 0, error: null, controller: null }); const isMounted = useRef(false); useLayoutEffect(() => { isMounted.current = true; return () => { isMounted.current = false; }; }, []); useEffect( () => { const controller = new AbortController(); setState(oldState => ({ data: null, loading: oldState.loading + 1, error: null, controller })); fetchData(url, controller.signal, state => { if (isMounted.current) { setState(state); } }); return () => controller.abort(); }, [url] ); return { data: state.data, loading: !!state.loading, error: state.error, abort: () => state.controller && state.controller.abort() }; }; export default useAbortableFetch;
export class Header extends Marionette.ItemView{ constructor (options) { super(options); this.text = options || ''; } get tagName () { return 'wood-header'; } get template () { return _.template('<%-text%>'); } templateHelpers () { return { text: this.options.text }; } } export {Header};
import * as actionTypes from "./constant"; import axios from "axios"; export const actGetUserPagingApi = (soTrang, soPhanTuTrenTrang, tuKhoa) => { return (dispatch) => { dispatch(actGetUserPagingRequest()); axios({ url: `https://movie0706.cybersoft.edu.vn/api/QuanLyNguoiDung/TimKiemNguoiDungPhanTrang`, method: "GET", params: { MaNhom: "GP09", soTrang, soPhanTuTrenTrang, tuKhoa, }, }) .then((result) => { dispatch(actGetUserPagingSuccess(result.data)); }) .catch((error) => { dispatch(actGetUserPagingFailed(error)); }); }; }; const actGetUserPagingRequest = () => { return { type: actionTypes.GET_USER_PAGING_REQUEST, }; }; const actGetUserPagingSuccess = (userPaging) => { return { type: actionTypes.GET_USER_PAGING_SUCCESS, payload: userPaging, }; }; const actGetUserPagingFailed = (error) => { return { type: actionTypes.GET_USER_PAGING_SUCCESS, payload: error, }; };
"use strict"; // Dependencies const express = require("express"); const mongoose = require("mongoose"); const router = express.Router(); const { Todo, validateTodo } = require("../models/todo"); const { messages, routes } = require("../constants/messages.json"); // Get all todos router.get(routes.getTodos, async (req, res) => { try { const todos = await Todo.find().sort("title"); res.json(todos); } catch (error) { res.status(400).send(error); } }); // Get todo by Id router.get(routes.getTodoById, async (req, res) => { const { id } = req.params; // validate that id has been passed as param if (!id) { return res.status(400).send(messages.missingId); } // Validate id matches mongoose type const isValidId = isValidObjectdId(id); if (!isValidId) { return res.status(400).send(messages.idFormat); } try { // search for todo by id in db const result = await Todo.findById(id); // todo not found if (!result) { return res.status(400).send(messages.recordNotFound); } res.json(result); } catch (error) { res.status(400).send(error); } }); // Create new todo router.post(routes.createTodo, async (req, res) => { // validate todo props const { error } = validateTodo(req.body); if (error) { return res.status(400).send(error.details[0].message); } // get todo prop values from request const { title, isCompleted } = req.body; console.log(title, isCompleted); // Check if todo is already in the db let todo = await Todo.findOne({ title: title }); if (todo) { return res.status(400).send(messages.recordAlreadyInDb); } // create todo obj for saving in db todo = new Todo({ title, isCompleted, }); try { // saving todo in db const { _id, title, isCompleted } = await todo.save(); const savedTodo = { _id, title, isCompleted, message: messages.recordAdded, }; // send message after saving successfully res.json(savedTodo); } catch (error) { res.status(400).send(error); } }); // Delete todo router.delete(routes.deleteTodo, async (req, res) => { const { id } = req.params; // validate that id has been passed as param if (!id) { return res.status(400).send(messages.missingId); } // Validate id matches mongoose type const isValidId = isValidObjectdId(id); if (!isValidId) { return res.status(400).send(messages.idFormat); } try { //find todo with the specific id and remove it from db const result = await Todo.findByIdAndRemove(id); // if id passed is not in db if (!result) { return res.status(400).send(messages.recordNotFound); } const deletedTodo = { _id: result._id, title: result.title, isCompleted: result.isCompleted, message: messages.recordDeleted, }; res.json(deletedTodo); } catch (error) { res.status(400).send(error); } }); // Update todo router.put(routes.updateTodo, async (req, res) => { // validate todo props const { error } = validateTodo(req.body); if (error) { return res.status(400).send(error.details[0].message); } try { const { id, title, isCompleted } = req.body; // look for todo in db and update const result = await Todo.findByIdAndUpdate(id, { title, isCompleted, }); // todo not found by id if (!result) { return res.status(400).send(messages.recordNotFound); } const updatedTodo = { _id: result._id, title: result.title, isCompleted: result.isCompleted, message: messages.recordUpdated, }; res.json(updatedTodo); } catch (error) { res.status(400).send(error); } }); // utils functions const isValidObjectdId = (id) => { return mongoose.Types.ObjectId.isValid(id); }; module.exports = router;
'use strict'; angular.module('vegewroApp') .factory('geoloc', ['googleMaps', function(googleMaps) { var lastGeoloc; function handleError(error, i18n) { var message; switch(error.code) { case error.PERMISSION_DENIED: message = i18n.gePermissionDenied; break; case error.POSITION_UNAVAILABLE: message = i18n.gePositionUnavailable; break; case error.TIMEOUT: message = i18n.geTimeout; break; case error.UNKNOWN_ERROR: message = i18n.geoerror + ': ' + i18n.geUnknownError; break; } console.log('Geolocation error occurred: ' + error); alert(message); } return { onGoogleMap : function(map, config, i18n) { if (navigator.geolocation) { var mapLocDiv = document.createElement('div'); window.locUser = function() { navigator.geolocation.getCurrentPosition(function(position) { if (lastGeoloc) { lastGeoloc.setMap(null); } var userCoords = googleMaps.newLatLng(position.coords.latitude, position.coords.longitude); googleMaps.setMapZoomIfSmallerThan(config.zoomWhenMarkerClicked); lastGeoloc = googleMaps.newMarker({ position: userCoords, map: map, title: i18n.youHere, icon: 'images/rabbit.png' }); map.panTo(userCoords); }, function(error) { handleError(error, i18n); }, config.geolocOptions); }; mapLocDiv.innerHTML = '<div class="map-loc"><img class="action" src="images/target.png" ' + 'onclick="window.locUser()"/></div>'; googleMaps.putOnMap(google.maps.ControlPosition.RIGHT_BOTTOM, mapLocDiv); } else { console.log('Geolocation is not supported'); } } }; }]);
const mongoose = require('mongoose'); const config = require('../config/baseConfig'); const logger = require('../common/logger') mongoose.connect(config.db, { poolSize: 20, useCreateIndex: true, useNewUrlParser: true }, (err) => { if(err){ logger.error('connect to %s error', config.db, err.message); process.exit(1); } console.log('connet to '+config.db); }) exports.User = require('./user');
var defines________________________________5________________8js________8js____8js__8js_8js = [ [ "defines________________5________8js____8js__8js_8js", "defines________________________________5________________8js________8js____8js__8js_8js.html#aabcca143c896fe50f41f780bbd91a5b1", null ] ];
//SETUP ROUTER var express = require("express"); var router = express.Router(); var mongoose = require("mongoose"); var resource = require("../models/resourceModel"); var user = require("../models/userModel"); var updateRating = require("./update-resource-rating"); var updateStatus = require("./update-resource-status"); var bodyParser = require("body-parser"); var categoryList = require("../models/categoryList.json"); var moment = require("moment"); router.use( bodyParser.urlencoded({ extended: true }) ); router.use(bodyParser.json()); router.get("/", function(req, res) { getAllPortfolios().then((response, error) => { if (req.isAuthenticated()) { // filter the resources returned from db to only include users ratings var resources = updateRating.filterOutCurrentUserRating( response, req.user.mongoID ); getUser(req.user.mongoID).then((response, error) => { // filter the resources returned from db to only include users status for (let i = 0; i < resources.length; i++) { resources[i].status = findResourceStatus( response, resources[i]["_id"] ); } // render page for authenticated user res.render("view-all-portfolios", { isUserAuthenticated: req.isAuthenticated(), resources: resources, categoryList: categoryList, moment: moment }); }); } else { // render page for un-authenticated user res.render("view-all-portfolios", { isUserAuthenticated: req.isAuthenticated(), resources: response, categoryList: categoryList, moment: moment }); } }); }); // register update to users rating router.post("/rate", function(req, res) { updateRating .updateResourceRating( req.body.resourceID, req.user.mongoID, req.body.resourceRating ) .then((response, error) => { res.redirect("back"); }); }); // register update to users status for the resource, not currently included on page router.post("/status", function(req, res) { var newResourceStatus = req.body.resourceStatus; getUserWithStatus( req.body.resourceID, req.user.mongoID ).then((response, error) => { var resourceStatus, dateField; if (newResourceStatus == "Completed") { resourceStatus = "resourcesCompleted"; dateField = "dateCompleted"; } else if (newResourceStatus == "Want To Do") { resourceStatus = "resourcesToDo"; dateField = "dateAdded"; } else if (newResourceStatus == "In Progress") { resourceStatus = "resourcesInProgress"; dateField = "dateStarted"; } if (response == "Not_Found") { updateStatus .pushResource( req.user.mongoID, resourceStatus, dateField, req.body.resourceID ) .then((response, error) => { res.redirect("back"); }); } else { var oldResourceStatus = findResourceStatusForPost( response, req.body.resourceID ); if (newResourceStatus == oldResourceStatus) { res.redirect("back"); } else { if (oldResourceStatus == "Completed") { oldResourceStatus = "resourcesCompleted"; } else if (oldResourceStatus == "Want To Do") { oldResourceStatus = "resourcesToDo"; } else if (oldResourceStatus == "In Progress") { oldResourceStatus = "resourcesInProgress"; } updateStatus .updateResourceStatus( req.user.mongoID, resourceStatus, oldResourceStatus, dateField, req.body.resourceID ) .then((response, error) => { res.redirect("back"); }); } } }); }); function findResourceStatusForPost(data, id) { for (let i = 0; i < data.resourcesCompleted.length; i++) { if (data.resourcesCompleted[i].resourceID == id) { return "Completed"; } } for (let i = 0; i < data.resourcesToDo.length; i++) { if (data.resourcesToDo[i].resourceID == id) { return "Want To Do"; } } for (let i = 0; i < data.resourcesInProgress.length; i++) { if (data.resourcesInProgress[i].resourceID == id) { return "In Progress"; } } } function findResourceStatus(data, id) { for (let i = 0; i < data.resourcesCompleted.length; i++) { if (data.resourcesCompleted[i].resourceID == id) { return ["Completed", "In Progress", "Want To Do"]; } } for (let i = 0; i < data.resourcesToDo.length; i++) { if (data.resourcesToDo[i].resourceID == id) { return ["Want To Do", "Completed", "In Progress"]; } } for (let i = 0; i < data.resourcesInProgress.length; i++) { if (data.resourcesInProgress[i].resourceID == id) { return ["In Progress", "Completed", "Want To Do"]; } } return ["Status", "Completed", "In Progress", "Want To Do"]; } function getResourceCategory(category, categoryQuery) { return new Promise(function(resolve, reject) { resource .find({ [categoryQuery]: category }) .exec(function(err, doc) { if (err) { console.log(err); reject(err); } else { resolve(doc); } }); }); } function getAllPortfolios() { return new Promise(function(resolve, reject) { resource.find({ resourceCategory: "Portfolio" }).exec(function(err, doc) { if (err) { console.log(err); reject(err); } else { resolve(doc); } }); }); } function getUser(userID) { return new Promise(function(resolve, reject) { user.findOne( { _id: userID }, function(err, doc) { if (err) { console.log(err); reject(err); } else { resolve(doc); } } ); }); } function getUserWithStatus(id, userID) { return new Promise(function(resolve, reject) { user.findOne( { _id: userID, $or: [ { "resourcesToDo.resourceID": id }, { "resourcesInProgress.resourceID": id }, { "resourcesCompleted.resourceID": id } ] }, function(err, doc) { if (err) { reject(err); } else if (doc) { resolve(doc); } else { resolve("Not_Found"); } } ); }); } module.exports = router;
const Lexer = require('./lexer'); describe("The lexer", () => { it("should parse text into tokens", () => { const lexer = new Lexer("1+3"); expect(lexer.next()).toEqual({ type: "NUMBER", value: 1 }); expect(lexer.next()).toEqual({ type: "ADD_OPERATOR", value: "+" }); expect(lexer.next()).toEqual({ type: "NUMBER", value: 3 }); expect(lexer.next()).toEqual({ type: "EOF", value: null }); }); it("should extract the required type", () => { const lexer = new Lexer("1+3"); expect(lexer.consume("NUMBER")).toEqual({ type: "NUMBER", value: 1 }); expect(lexer.consume("ADD_OPERATOR")).toEqual({ type: "ADD_OPERATOR", value: "+" }); expect(lexer.consume("NUMBER")).toEqual({ type: "NUMBER", value: 3 }); }); it("accepts numbers with more than one digit", () => { const lexer = new Lexer("12+3"); expect(lexer.consume("NUMBER")).toEqual({ type: "NUMBER", value: 12 }); expect(lexer.consume("ADD_OPERATOR")).toEqual({ type: "ADD_OPERATOR", value: "+" }); expect(lexer.consume("NUMBER")).toEqual({ type: "NUMBER", value: 3 }); }); it("should raise error for not expected type", () => { const lexer = new Lexer("1+3"); expect(() => lexer.consume("ADD_OPERATOR")).toThrow(); }) })
/* * @lc app=leetcode.cn id=40 lang=javascript * * [40] 组合总和 II */ // @lc code=start /** * @param {number[]} candidates * @param {number} target * @return {number[][]} */ var combinationSum2 = function(candidates, target) { let res = [], solution = []; candidates.sort((a, b) => a - b) let backTrack = (n, begin) => { if (n <= 0) { if (n === 0) { res.push([...solution]); } return; } else { for (let i = begin; i < candidates.length; i++) { if (i > begin && candidates[i] == candidates[i - 1]) continue; n = n - candidates[i]; solution.push(candidates[i]); backTrack(n, i + 1); let val = solution.pop(); n = n + val; } } } backTrack(target, 0); return res; }; // @lc code=end
import React, { useState, useEffect } from "react"; const Scores = ({getResults, deleteResult}) => { const [scores, setScores] = useState([]) useEffect(()=>{ getResults() .then((data)=>{ setScores(data) }) },[getResults]); const removeScore = (id) => { const temp = scores.map(s => s) const indexToDel = temp.map(s => s._id).indexOf(id); temp.splice(indexToDel, 1) setScores(temp) } const handleDelete = (id) => { deleteResult(id).then(() => { removeScore(id) }) } const headerRow = scores[0]?.results.map((result) => { return <th>{result.round}</th> }) const resultRows = scores?.map((score) => { const playerCell = <td>{score.name}</td> const resultCells = score.results.map((result) => { return <td class={result.winner ? "won" : "lost"}>{result.winner ? "Won" : "Lost"}</td> }) return ( <tr>{playerCell}{resultCells}<button onClick={() => handleDelete(score._id)}> Delete Score</button> </tr> ) }) return ( <div> <table id="scores-table"> <tr> <th>Player</th> {headerRow} </tr> {resultRows} </table> </div> ) } export default Scores
let carros = [ {nome: 'Fiat', modelo: 'Palio'}, {nome: 'Fiat', modelo: 'Uno'}, {nome: 'Toyota', modelo: 'Corolla'}, {nome: 'Ferrari', modelo: 'Spyder'} ] console.log(carros[2]); console.log(carros[2].modelo);
'use strict'; const copy = require('./utils').copyWithPattern; const debug = require('./utils').debug; const wrapAsync = require('./utils').wrapAsync; /** * @func copyFilesFromSourceToPublic * @desc Copies files from the source path to the public path. * @param {object} paths - The passed Pattern Lab config paths member. * @return {Array} */ const copyFilesFromSourceToPublic = paths => wrapAsync(function*() { // Copy files over const copiedFiles = [ copy(paths.source.styleguide, '*', paths.public.root), copy(paths.source.js, '**/*.js', paths.public.js), copy(paths.source.css, '*.css', paths.public.css), copy(paths.source.images, '*', paths.public.images), copy(paths.source.fonts, '*', paths.public.fonts), copy(paths.source.root, 'favicon.ico', paths.public.root), ]; debug(`build: Your files were copied over to ${paths.public.root}`); return yield Promise.all(copiedFiles); }); module.exports = copyFilesFromSourceToPublic;
import { Link } from "react-router-dom"; const Header = () => { return ( <> <h1>Shop Banner</h1> <ul className="nav"> <li> <Link to="/">Home</Link> </li> <li> <Link to="/login">Login</Link> </li> <li> <Link to="/register">Register</Link> </li> <li> <Link to="/cart">Cart</Link> </li> </ul> </> ); }; export default Header;
//"TaskId": "T_PRYCTGSQXNCGT_397"
import React from 'react'; import { NOTICES_TITLES } from '../../constants/notices'; import Icon from '../Icon'; import { StyledCard, StyledCardInner, Header, Content, Cross } from './styled'; const NOTICES_ICONS = { INFO: 'info', SUCCESS: 'circle-check-green', ERROR: 'error', WARNING: 'warning', }; const NoticeCard = ({ hideNotice, notice }) => { const iconName = NOTICES_ICONS[notice.type]; return ( <StyledCard> <StyledCardInner> {iconName && <Icon name={iconName} size={32} />} <div> <Header>{NOTICES_TITLES[notice.type] || ''}</Header> <Content>{notice.value}</Content> </div> </StyledCardInner> <Cross onClick={() => hideNotice(notice.id)} /> </StyledCard> ); }; export default NoticeCard;
import React, { Fragment, useEffect } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getGithubRepos } from '../../actions/profile'; import Spinner from '../../components/layouts/Spinner'; const Github = ({ getGithubRepos, profile: { profile, loading } }) => { useEffect(() => { getGithubRepos(); }, [getGithubRepos]); const { name, avatar_url, location, bio, blog, company, login, html_url } = profile; return loading ? ( <Spinner /> ) : ( <div className="card grid-2"> <div className="all-center"> <img src={avatar_url} className="round-img" alt="" /> <h5>{name}</h5> <p>Location: {location}</p> </div> <div> {bio && ( <Fragment> <h5>Bio</h5> <p>{bio}</p> </Fragment> )} <a href={html_url} className="btn btn-dark my-1"> Visit Github Profile </a> <ul> <li>{login && <Fragment><strong>Username: </strong> {login} </Fragment>}</li> <li>{company && <Fragment><strong>Company: </strong> {company} </Fragment>}</li> <li>{blog && <Fragment><strong>Website: </strong> {blog} </Fragment>}</li> </ul> </div> </div> ) } Github.propTypes = { getGithubRepos: PropTypes.func.isRequired } const mapStateToProps = state => ({ profile: state.profile }); export default connect(mapStateToProps, { getGithubRepos })(Github);
const axios = require('axios'); const Parallel = require("async-parallel"); const {aggregate, filter_issues, generate_url, validate} = require('../../helpers'); module.exports.controller = (app) => { /** * Retrieves an entity based on input parameters */ app.post('/query', async (req, res, next) => { const v = validate(req.body); if (!v.result) { return res.json({ "Success": false, "message": v.message }); } const url = req.body.repository; console.log(`Request to retrieve ${url}`); var array = url.split('/'); const owner = array[3]; const repo = array[4]; const issues = []; var page = 1; while (true) { const urls = [ generate_url(owner, repo, page++), generate_url(owner, repo, page++), generate_url(owner, repo, page++), generate_url(owner, repo, page), ]; console.log(urls); const subIssues = []; try { await Parallel.each(urls, function(url) { return axios.get(url).then(function(result) { subIssues.push(...filter_issues(result.data)); }); }); } catch (e) { console.log(e); return res.json({"Success": false, "message": "Unable to retrieve data"}); } if (subIssues.length == 0) break; issues.push(...subIssues); console.log(`Pulled out a total of ${issues.length} after page ${page}`); page++; } res.json({"Success": true, issues: aggregate(issues)}); }); };
import React, {Component} from 'react' import Axios from 'axios' class AllQuestion extends Component{ constructor(props){ super(props) this.state = { allQuestion : [] } } componentDidMount(){ Axios.get("http://localhost:5005/quora/question/").then(allQuest => { console.log(allQuest); this.setState({ allQuestion: allQuest.data }) }).catch(error => { console.log("Axios error") console.log(error) }) } Vote(event, id){ console.log(event.target.classList.add("abhishek")) console.log(id) Axios.post("http://localhost:5005/quora/like/5f3a6c1ec944801a08a6b2f1/question/"+id).then(result => { console.log(result); if(result.data == "upvote"){ console.log(event.target) event.target.classList.remove("text-info"); event.target.classList.add("text-warning"); } }).catch(error => { console.log("Axios Error"); console.log(error); }) } render(){ return( <div> {this.state.allQuestion.map((data, index) => { return( <div class="card my-2"> <div class="card-body"> <div className="d-flex align-items-baseline"> <h6 className="card-text mr-2">Nasim Shaikh</h6> <a href="#" class="bg-warning px-2 text-decoration-none text-white small rounded">JEE</a> </div> <h5 class="card-title"><a href="answer" className="text-decoration-none">{data.question}</a></h5> { data.images? <img class="card-img-top w-100" src={data.images} alt="alternate image"/>: "" } <div className="mt-3"> {data.tags.map((tag, index) => { return( <a href="#" class="badge badge-warning mr-2">{tag.toUpperCase()}</a> ) })} </div> </div> <div className="card-footer bg-white"> <div className="d-flex justify-content-between"> <div className="d-flex"> <div className="d-flex align-items-center pr-3"> <h5 className="vote-btn cursor-pointer" ><i class="far fa-arrow-alt-circle-up text-info" onClick={(e)=>this.Vote(e, data._id)}></i></h5> <h6 className="vote-counter pl-1 small">123</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="time-btn text-info cursor-pointer"><i class="far fa-clock"></i></h5> <h6 className="time-counter pl-1 small">10 hrs ago</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="views-btn text-info cursor-pointer"><i class="far fa-eye"></i></h5> <h6 className="views-counter pl-1 small">123</h6> </div> </div> <div className=""> <h5 className="dot-btn text-info cursor-pointer"><i class="fas fa-ellipsis-h"></i></h5> </div> </div> </div> </div> ) })} {/* <div class="card my-2"> <div class="card-body"> <div className="d-flex align-items-baseline"> <h6 className="card-text mr-2">Nasim Shaikh</h6> <a href="#" class="bg-warning px-2 text-decoration-none text-white small rounded">JEE</a> </div> <h5 class="card-title"><a href="answer" className="text-decoration-none">How much do web developers earn? What is their salary?</a></h5> <p class="card-text small text-muted">I am thinking of pursuing web developing as a career & was just wondering. I’ve heard that that location is a big factor when it comes to salary of web developers. Kindly state: 1) Country 2) Salary Monthly/Yearly 3) Years of experience. P.s) You can ...</p> <div> <a href="#" class="badge badge-warning mr-2">NEET</a> <a href="#" class="badge badge-warning mr-2">JEE</a> <a href="#" class="badge badge-warning mr-2">CET</a> <a href="#" class="badge badge-warning mr-2">MCA</a> </div> </div> <div className="card-footer bg-white"> <div className="d-flex justify-content-between"> <div className="d-flex"> <div className="d-flex align-items-center pr-3"> <h5 className="vote-btn text-info cursor-pointer" ><i class="far fa-arrow-alt-circle-up"></i></h5> <h6 className="vote-counter pl-1 small">123</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="time-btn text-info cursor-pointer"><i class="far fa-clock"></i></h5> <h6 className="time-counter pl-1 small">10 hrs ago</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="views-btn text-info cursor-pointer"><i class="far fa-eye"></i></h5> <h6 className="views-counter pl-1 small">123</h6> </div> </div> <div className=""> <h5 className="dot-btn text-info cursor-pointer"><i class="fas fa-ellipsis-h"></i></h5> </div> </div> </div> </div> <div class="card my-2"> <div class="card-body"> <div className="d-flex align-items-baseline"> <h6 className="card-text mr-2">Nasim Shaikh</h6> <a href="#" class="bg-warning px-2 text-decoration-none text-white small rounded">JEE</a> </div> <h5 class="card-title"><a href="answer" className="text-decoration-none">How much do web developers earn? What is their salary?</a></h5> <p class="card-text small text-muted">I am thinking of pursuing web developing as a career & was just wondering. I’ve heard that that location is a big factor when it comes to salary of web developers. Kindly state: 1) Country 2) Salary Monthly/Yearly 3) Years of experience. P.s) You can ...</p> <div> <a href="#" class="badge badge-warning mr-2">NEET</a> <a href="#" class="badge badge-warning mr-2">JEE</a> <a href="#" class="badge badge-warning mr-2">CET</a> <a href="#" class="badge badge-warning mr-2">MCA</a> </div> </div> <div className="card-footer bg-white"> <div className="d-flex justify-content-between"> <div className="d-flex"> <div className="d-flex align-items-center pr-3"> <h5 className="vote-btn text-info cursor-pointer" ><i class="far fa-arrow-alt-circle-up"></i></h5> <h6 className="vote-counter pl-1 small">123</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="time-btn text-info cursor-pointer"><i class="far fa-clock"></i></h5> <h6 className="time-counter pl-1 small">10 hrs ago</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="views-btn text-info cursor-pointer"><i class="far fa-eye"></i></h5> <h6 className="views-counter pl-1 small">123</h6> </div> </div> <div className=""> <h5 className="dot-btn text-info cursor-pointer"><i class="fas fa-ellipsis-h"></i></h5> </div> </div> </div> </div> <div class="card my-2"> <div class="card-body"> <div className="d-flex align-items-baseline"> <h6 className="card-text mr-2">Nasim Shaikh</h6> <a href="#" class="bg-warning px-2 text-decoration-none text-white small rounded">JEE</a> </div> <h5 class="card-title"><a href="answer" className="text-decoration-none">How much do web developers earn? What is their salary?</a></h5> <p class="card-text small text-muted">I am thinking of pursuing web developing as a career & was just wondering. I’ve heard that that location is a big factor when it comes to salary of web developers. Kindly state: 1) Country 2) Salary Monthly/Yearly 3) Years of experience. P.s) You can ...</p> <div> <a href="#" class="badge badge-warning mr-2">NEET</a> <a href="#" class="badge badge-warning mr-2">JEE</a> <a href="#" class="badge badge-warning mr-2">CET</a> <a href="#" class="badge badge-warning mr-2">MCA</a> </div> </div> <div className="card-footer bg-white"> <div className="d-flex justify-content-between"> <div className="d-flex"> <div className="d-flex align-items-center pr-3"> <h5 className="vote-btn text-info cursor-pointer" ><i class="far fa-arrow-alt-circle-up"></i></h5> <h6 className="vote-counter pl-1 small">123</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="time-btn text-info cursor-pointer"><i class="far fa-clock"></i></h5> <h6 className="time-counter pl-1 small">10 hrs ago</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="views-btn text-info cursor-pointer"><i class="far fa-eye"></i></h5> <h6 className="views-counter pl-1 small">123</h6> </div> </div> <div className=""> <h5 className="dot-btn text-info cursor-pointer"><i class="fas fa-ellipsis-h"></i></h5> </div> </div> </div> </div> <div class="card my-2"> <div class="card-body"> <div className="d-flex align-items-baseline"> <h6 className="card-text mr-2">Nasim Shaikh</h6> <a href="#" class="bg-warning px-2 text-decoration-none text-white small rounded">JEE</a> </div> <h5 class="card-title"><a href="answer" className="text-decoration-none">How much do web developers earn? What is their salary?</a></h5> <p class="card-text small text-muted">I am thinking of pursuing web developing as a career & was just wondering. I’ve heard that that location is a big factor when it comes to salary of web developers. Kindly state: 1) Country 2) Salary Monthly/Yearly 3) Years of experience. P.s) You can ...</p> <div> <a href="#" class="badge badge-warning mr-2">NEET</a> <a href="#" class="badge badge-warning mr-2">JEE</a> <a href="#" class="badge badge-warning mr-2">CET</a> <a href="#" class="badge badge-warning mr-2">MCA</a> </div> </div> <div className="card-footer bg-white"> <div className="d-flex justify-content-between"> <div className="d-flex"> <div className="d-flex align-items-center pr-3"> <h5 className="vote-btn text-info cursor-pointer" ><i class="far fa-arrow-alt-circle-up"></i></h5> <h6 className="vote-counter pl-1 small">123</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="time-btn text-info cursor-pointer"><i class="far fa-clock"></i></h5> <h6 className="time-counter pl-1 small">10 hrs ago</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="views-btn text-info cursor-pointer"><i class="far fa-eye"></i></h5> <h6 className="views-counter pl-1 small">123</h6> </div> </div> <div className=""> <h5 className="dot-btn text-info cursor-pointer"><i class="fas fa-ellipsis-h"></i></h5> </div> </div> </div> </div> <div class="card my-2"> <div class="card-body"> <div className="d-flex align-items-baseline"> <h6 className="card-text mr-2">Nasim Shaikh</h6> <a href="#" class="bg-warning px-2 text-decoration-none text-white small rounded">JEE</a> </div> <h5 class="card-title"><a href="answer" className="text-decoration-none">How much do web developers earn? What is their salary?</a></h5> <p class="card-text small text-muted">I am thinking of pursuing web developing as a career & was just wondering. I’ve heard that that location is a big factor when it comes to salary of web developers. Kindly state: 1) Country 2) Salary Monthly/Yearly 3) Years of experience. P.s) You can ...</p> <div> <a href="#" class="badge badge-warning mr-2">NEET</a> <a href="#" class="badge badge-warning mr-2">JEE</a> <a href="#" class="badge badge-warning mr-2">CET</a> <a href="#" class="badge badge-warning mr-2">MCA</a> </div> </div> <div className="card-footer bg-white"> <div className="d-flex justify-content-between"> <div className="d-flex"> <div className="d-flex align-items-center pr-3"> <h5 className="vote-btn text-info cursor-pointer" ><i class="far fa-arrow-alt-circle-up"></i></h5> <h6 className="vote-counter pl-1 small">123</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="time-btn text-info cursor-pointer"><i class="far fa-clock"></i></h5> <h6 className="time-counter pl-1 small">10 hrs ago</h6> </div> <div className="d-flex align-items-center pr-3"> <h5 className="views-btn text-info cursor-pointer"><i class="far fa-eye"></i></h5> <h6 className="views-counter pl-1 small">123</h6> </div> </div> <div className=""> <h5 className="dot-btn text-info cursor-pointer"><i class="fas fa-ellipsis-h"></i></h5> </div> </div> </div> </div> */} </div> ) } } export default AllQuestion;
import React from "react" import styled from "styled-components" import Image from "gatsby-image" import BaseButton from "../Shared/Buttons/BaseButtonOut" import { above } from "../../styles/Theme" const FreeGuidesSection = ({ cover1, cover2 }) => { return ( <GuidesContainer> <CoverWrapper> <Cover fluid={cover1} /> <BaseButton url="https://www.dropbox.com/s/15ejngnbah6husn/switch-2020.pdf"> Download </BaseButton> </CoverWrapper> <CoverWrapper> <Cover fluid={cover2} /> <BaseButton url="https://www.dropbox.com/s/0qsbs44v67ft1dh/top-5-pdf.pdf"> Download </BaseButton> </CoverWrapper> </GuidesContainer> ) } export default FreeGuidesSection const GuidesContainer = styled.div` display: grid; grid-template-columns: 1fr; gap: 20px; justify-items: center; ${above.mobile` grid-template-columns: 1fr 1fr; `} ` const CoverWrapper = styled.div` display: grid; grid-template-columns: 1fr; gap: 12px; justify-items: center; width: 240px; ` const Cover = styled(Image)` border-radius: 10px; width: 220px; `
import React, { useContext } from 'react'; import styled from 'styled-components'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { StyledButton } from '../../../molecules/AuthContent/styles'; import MainSocketContext from '../../../../providers/MainSocketContext'; import { NamespaceControllerContext } from '../context/NamespaceControllerContext'; import { ReactComponent as PasswordIcon } from '../../../../assets/icons/password.svg'; import { toggleCreateNamespace } from '../../../../actions/toggleActions'; const StyledNamespaceWrapper = styled.div` width: 100%; padding: 1rem 2rem; display: flex; flex-direction: row; justify-content: space-between; align-items: center; border-top: 1px solid #ccc; `; const StyledNamespaceName = styled.p` color: #222; `; const StyledPasswordIcon = styled(PasswordIcon)` width: 25px; height: 25px; fill: #ccc; margin-right: 1.5rem; `; const ButtonWrapper = styled.div` display: flex; flex-direction: row; align-items: center; `; const NamespaceJoinBox = ({ namespace, userID, toggleCreateNamespace }) => { const { socket } = useContext(MainSocketContext); const { changePage, setChosenNamespace } = useContext(NamespaceControllerContext); return ( <StyledNamespaceWrapper> <StyledNamespaceName>{namespace.name}</StyledNamespaceName> <ButtonWrapper> {namespace.password && <StyledPasswordIcon />} <StyledButton onClick={() => { if (namespace.password) { setChosenNamespace(namespace); changePage(4); } else { socket.emit('new_namespace_join', { userID, namespace }); toggleCreateNamespace(false); changePage(0); } }} > Join </StyledButton> </ButtonWrapper> </StyledNamespaceWrapper> ); }; NamespaceJoinBox.propTypes = { namespace: PropTypes.object.isRequired }; const mapStateToProps = ({ authenticationReducer: { userID } }) => { return { userID }; }; const mapDispatchToProps = dispatch => { return{ toggleCreateNamespace: isOpen => dispatch(toggleCreateNamespace(isOpen)), } } export default connect(mapStateToProps, mapDispatchToProps)(NamespaceJoinBox);
const axios = require("axios"); const Endpoints = require("./Endpoints"); const Player = require("./Classes/Player"); const Clan = require("./Classes/Clan"); const Cards = require("./Classes/Cards"); const Locations = require("./Classes/Locations"); const Location = require("./Classes/Location"); const UpcomingChests = require("./Classes/UpcomingChests"); const BattleLog = require("./Classes/BattleLog"); const Tournament = require("./Classes/Tournament"); class RoyaleJS { /** * * @param {string} apiToken Can be found at https://developer.clashroyale.com/#/account */ constructor(apiToken) { if (!apiToken) throw new Error("You need to provide an API token."); this._apiTOKEN = apiToken; this.header = { Accept: "application/json", Authorization: `Bearer ${this._apiTOKEN}` } } /** * * @description Queries the API for a full list of clans matching at least one filtering criteria * @returns Promise { object } */ /* async getClans() { let res; try { res = await axios({ method: "get", url: Endpoints.CLANS(), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } */ /** * * @param {string} clanTag * @description Get information of a specific clan * @returns Promise { object } */ async getClan(clanTag) { if (!clanTag) throw new Error("You need to provide a clan tag."); let res; try { res = await axios({ method: "get", url: Endpoints.CLAN(clanTag), headers: this.header }); let clan = new Clan(res.data); return clan; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} playerTag * @description Get information of a specific player * @returns Promise { object } */ async getPlayer(playerTag) { if (!playerTag) throw new Error("You need to provide a player tag."); let res; try { res = await axios({ method: "get", url: Endpoints.PLAYER(playerTag), headers: this.header }); let player = new Player(res.data); return player; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} playerTag * @description Get Upcoming Chests of a specific player * @returns Promise { object } */ async getPlayerUpcomingChests(playerTag) { if (!playerTag) throw new Error("You need to provide a player tag."); let res; try { res = await axios({ method: "get", url: Endpoints.PLAYER_UPCOMING_CHESTS(playerTag), headers: this.header }); let upcomingChests = new UpcomingChests(res.data); return upcomingChests; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} playerTag * @description Get Battle Log of a specific player * @returns Promise { object } */ async getPlayerBattleLog(playerTag) { if (!playerTag) throw new Error("You need to provide a player tag."); let res; try { res = await axios({ method: "get", url: Endpoints.PLAYER_BATTLE_LOG(playerTag), headers: this.header }); let battleLog = new BattleLog(res.data); return battleLog; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return console.log(error); return res; } } /** * * @description Get a full list and information of all existing cards * @returns Promise { object } */ async getCards() { let res; try { res = await axios({ method: "get", url: Endpoints.CARDS(), headers: this.header }); let cards = new Cards(res.data); return cards; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @description Queries the API for a full list of existing Tournaments * @returns Promise { object } */ /* async getTournaments() { if (!tournamentTag) throw new Error("You need to provide a tournament tag."); let res; try { res = await axios({ method: "get", url: Endpoints.TOURNAMENTS(), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } */ /** * * @param {string} tournamentTag * @description Get information of a specific tournament * @returns Promise { object } */ async getTournament(tournamentTag) { if (!tournamentTag) throw new Error("You need to provide a tournament tag."); let res; try { res = await axios({ method: "get", url: Endpoints.TOURNAMENT(tournamentTag), headers: this.header }); let tournament = new Tournament(res.data); return tournament; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @description Get a full list and information of all global tournaments * @returns Promise { object } */ async getGlobalTournaments() { let res; try { res = await axios({ method: "get", url: Endpoints.GLOBALTOURNAMENTS(), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @description Get a full list and information of all existing locations * @description Full list of location IDs can be found in https://docs.zloth.xyz/royalejs/documentation/reference * @returns Promise { object } */ async getLocations() { let res; try { res = await axios({ method: "get", url: Endpoints.LOCATIONS(), headers: this.header }); let locations = new Locations(res.data); return locations; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} locationID Location ID (e.g. "57000001" - North America]) * @description Get information of a specific location * @description Full list of location IDs can be found in https://docs.zloth.xyz/royalejs/documentation/reference * @returns Promise { object } */ async getLocation(locationID) { let res; if (!locationID) throw new Error("You need to provide a location ID."); try { res = await axios({ method: "get", url: Endpoints.LOCATION(locationID), headers: this.header }); let location = new Location(res.data); return location; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} locationID Location ID (e.g. "57000001" - North America]) * @description Get Player Rankings in a specific location * @description Full list of location IDs can be found in https://docs.zloth.xyz/royalejs/documentation/reference * @returns Promise { object } */ async getPlayerRankingsByLocation(locationID) { let res; if (!locationID) throw new Error("You need to provide a location ID."); try { res = await axios({ method: "get", url: Endpoints.PLAYER_RANKINGS_BY_LOCATION(locationID), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} locationID Location ID (e.g. "57000001" - North America]) * @description Get Clan Rankings in a specific location * @description Full list of location IDs can be found in https://docs.zloth.xyz/royalejs/documentation/reference * @returns Promise { object } */ async getClanRankingsByLocation(locationID) { if (!locationID) throw new Error("You need to provide a location ID."); let res; try { res = await axios({ method: "get", url: Endpoints.CLAN_RANKINGS_BY_LOCATION(locationID), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} locationID Location ID (e.g. "57000001" - North America]) * @description Get Clan War Rankings in a specific location * @description Full list of location IDs can be found in https://docs.zloth.xyz/royalejs/documentation/reference * @returns Promise { object } */ async getClanWarRankingsByLocation(locationID) { if (!locationID) throw new Error("You need to provide a location ID."); let res; try { res = await axios({ method: "get", url: Endpoints.CLAN_WAR_RANKINGS_BY_LOCATION(locationID), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @description Get full list and information of Top Player League seasons * @returns Promise { object } */ async getTopPlayerLeagueSeasons() { let res; try { res = await axios({ method: "get", url: Endpoints.TOP_PLAYER_LEAGUE_SEASONS(), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} seasonID Season ID * @description Get full list and information of Top Player Rankings in a specific season * @returns Promise { object } */ async getTopPlayerRankingsInSeason(seasonID) { if (!seasonID) throw new Error("You need to provide a season ID."); let res; try { res = await axios({ method: "get", url: Endpoints.TOP_PLAYER_RANKINGS_IN_SEASON(seasonID), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } /** * * @param {string} tournamentTag Tournament Tag * @description Get Global Tournament Ranking of a specific tournament * @returns Promise { object } */ async getGlobalTournamentRankingOfTournament(tournamentTag) { if (!tournamentTag) throw new Error("You need to provide a tournament tag."); let res; try { res = await axios({ method: "get", url: Endpoints.GLOBAL_TOURNAMENT_RANKINGS(tournamentTag), headers: this.header }); return res.data; } catch (error) { let err = error.toString().split(" "); let errCode = err[err.length - 1]; res = { status: errCode, error: err.join(" ") }; return res; } } } module.exports = RoyaleJS;
/** * Created by xiaocity on 18/1/20. */ function createHttpRequest() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; } function requestAddOrg(node) { var xmlhttp = createHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var data = xmlhttp.responseText; var treeData = '[' + data + ']'; treeData = JSON.parse(treeData); $("#aa").html(xmlhttp.responseText); //添加数的节点的子节点数据 $('#tt').tree('append', { parent:node.target, data:treeData }); //在treegrid表格后追加一行添加的信息 var gridData = JSON.parse(data); $('#dg').datagrid('appendRow', gridData); } }; var newOrgName = formaddneworg.name.value; if((newOrgName == null) || (newOrgName == "")){ alert("请输入组织名称"); } else { var orgLevel = node.organizationLevel; if (orgLevel == null){//表示是公司直接下属机构 orgLevel = 10000; }; var cpyId = node.cpyId; if(cpyId == null){ cpyId = node.objectId; }; var orgId = node.objectId; var url = "/todos/addorg?" + "uppername=" + node.name + "&name=" + newOrgName + "&orgid=" + orgId + "&cpyid=" + cpyId + "&orglevel=" + orgLevel; xmlhttp.open("GET",url,true); xmlhttp.send(); if(node.children == null){ cleanDatagrid(); } } } function removeChildNode(node) { var children = $('#tt').tree('getChildren', node.target);//子节点(市) if(children.length > 0){ children.forEach(function (child) {// $('#tt').tree('remove',child.target); }) } } function requestDelOrg(node) { var xmlhttp = createHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var data = xmlhttp.responseText; //$("#aa").html(xmlhttp.responseText); } }; var orgId = node.objectId; var url = "/todos/delorg?" + "orgid=" + orgId ; xmlhttp.open("GET",url,true); xmlhttp.send(); //update datagrid ui var rowIndex = $('#dg').datagrid('getRowIndex',node); $('#dg').datagrid('deleteRow',rowIndex); //update tree ui var treeNode = $('#tt').tree('find', node.id); if(treeNode){ $('#tt').tree('remove',treeNode.target); } var parent = $('#tt').tree('getParent',node.target); if (parent) { var jsonData = JSON.stringify(parent.children); jsonData = eval(jsonData); removeChildNode(parent); $('#tt').tree('reload', parent.target); $('#tt').tree('append', { parent:parent.target, data:jsonData }); $("#aa").html(JSON.stringify(parent)); } } function requestModifyOrg(node) { var curOrgName = formmdyorg.name.value; var upperOrgName = formmdyorg.uppername.value; curOrgName = curOrgName.trim(); upperOrgName = upperOrgName.trim(); var xmlhttp = createHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { $("#aa").html(xmlhttp.responseText); var data = xmlhttp.responseText; if(data.indexOf("cant not find org") != -1){ var msg = "找不到名称叫 " + upperOrgName +" 的组织"; alert(msg); } else { var sucIndex = data.indexOf("changeorgsuccess"); if(sucIndex != -1){ //仅是修改org名称成功 var strJson = data.substring(data.indexOf(":") + 1); var dataJson = JSON.parse(strJson); var treeNode = $('#tt').tree('find', dataJson.objectId); treeNode.name = dataJson.name; treeNode.text = dataJson.name; if (treeNode){ //update tree node $('#tt').tree('update', { target: treeNode.target, text: treeNode.text }); //update treegrid var data = $('#dg').datagrid('getData'); if(data){ if(data.rows.length > 0){ for(var i=0;i<data.rows.length;i++){ var dataRow = data.rows[i]; var resId = dataRow['id']; if(resId == dataJson.objectId){ $('#dg').datagrid('updateRow', { index: i, row: { "name": treeNode.name } }); break; } } } } } } else {//修改org的upper org 成功 var treeData = JSON.parse(data); //更新修改节点原父节点的信息 var node = $('#tt').tree('getSelected'); if(node){ node.ajaxed = false; updateTreeOrgInfo(node,true); } //更新修改节点新父节点的信息 node = $('#tt').tree('find', treeData.id); if(node){ node.ajaxed = false; updateTreeOrgInfo(node,true); $('#tt').tree('select', node.target); } } } } } if( (curOrgName == null) || (upperOrgName == null) || (curOrgName == "") || (upperOrgName == "")){ alert('请输入正确的名称或上级'); } else if(curOrgName == node.name && upperOrgName == node.upperOrganization){ // $.toaster('input info no change'); alert('input info no change'); return; } else { var newName = curOrgName; // if(curOrgName != node.name){ // newName = curOrgName; // } var newUpperName = "none"; if(upperOrgName != node.upperOrganization){ newUpperName = upperOrgName; } var orgId = node.objectId; var url = "/todos/mdyorg?" + "orgid=" + orgId + "&newname=" + newName + "&uppername=" + newUpperName; xmlhttp.open("GET",url,true); xmlhttp.send(); } } $(document).ready(function(){ }); function cleanDatagrid() { $('#dg').datagrid('loadData', { total: 0, rows: [] }); } function updateTreeOrgInfo(node,cleanChildren) { var orgId = node.objectId; if(node.ajaxed == false){ $.ajax({ method : 'get', url : '/todos/org?orgId=' + orgId, async : false, dataType : 'json', success : function(data) { if( cleanChildren == true) { if ($('#tt').tree('isLeaf', node.target)){ } else {//有子节点才做删除操作 removeChildNode(node); } } $('#tt').tree('append', { parent:node.target, data:data }); //====== $('#dg').datagrid('loadData', data); if(data.length == 0){ //如果市叶子节点则显示自己 cleanDatagrid(); $('#dg').datagrid('appendRow', node); } $("#aa").html(JSON.stringify(data)); }, error : function() { alert('error'); } }); node.ajaxed = true; } else { if(node.children == null){ cleanDatagrid(); $('#dg').datagrid('appendRow', node); } else { $('#dg').datagrid('loadData', node.children); } } } function requestOrgInfo() { $("#tt").tree({ onClick: function (node) { $("#aa").html(JSON.stringify(node)); updateTreeOrgInfo(node,false); } }); } function requestCompanyInfo() { $.ajax({ method: 'get', url: '/todos/cpy?id=5a60bc6d44d9040067c485a7', async: false, dataType: 'json', success: function (data) { $('#tt').tree('loadData', data); }, error: function (err) { alert(err); } }); } function btnClickLogic() { $('#btnAdd').click(function () { var node = $('#tt').tree('getSelected'); if (node) { $('#edit-add-org-upper').val(node.name); $('#edit-add-org-upper').attr("disabled", true); } }); $('#btnModify').click(function () { var row = $('#dg').datagrid('getSelected'); if (row) { $('#edit-mdy-org-upper').val(row.upperOrganization); $('#edit-mdy-org-name').val(row.name); } }); $('#btn-add-org-ok').click(function () { var node = $('#tt').tree('getSelected'); if (node) { requestAddOrg(node); } $('#dia-add-new').window('close'); }); $('#btn-mdy-org-ok').click(function () { var row = $('#dg').datagrid('getSelected'); if (row) { requestModifyOrg(row); } $('#dia-modify-org').window('close'); }); $('#btn-del-org-ok').click(function () { $('#dia-del-org').window('close'); var row = $('#dg').datagrid('getSelected'); if (row) { requestDelOrg(row); } }); }
const React = require('react'); const Navbar = require('../components/navigation/Navbar'); const Header = require('../components/header/Header'); const MainContent = require('../layouts/MainContent'); class CamerasPage extends React.Component { render () { return( <div className = 'dev-item'> <h1>Hello from page with devices list</h1> </div> ) } }; module.exports = CamerasPage;
import {customElement} from 'aurelia-framework'; @customElement('success-widget') export class SuccessWidget{ }
import React from 'react'; import MenuItem from '../menu-item/menu-item.component'; import './directory.styles.scss'; import image1 from '../../images/fotos_richi/DSC05965.jpg'; import image2 from '../../images/fotos_richi/DSC06663.jpg'; import image3 from '../../images/fotos_richi/DSC06439.jpg'; import image4 from '../../images/fotos_richi/DSC06595.jpg'; import image5 from '../../images/fotos_richi/DSC05899.jpg'; class Directory extends React.Component { constructor() { super(); this.state = { sections: [ { title: 'Madrid', imageUrl: image1, id: 1, linkUrl: '/madrid' }, { title: 'Barcelona', imageUrl: image2, id: 2, linkUrl: '/barcelona' }, { title: 'Málaga', imageUrl: image3, id: 3, linkUrl: '/malaga' }, { title: 'Eventos', imageUrl: image4, size: 'large', id: 4, linkUrl: '/eventos' }, { title: 'Historias', imageUrl: image5, size: 'large', id: 5, linkUrl: '/historias' } ] }; } render() { return ( <div className='directory-menu'> {this.state.sections.map(({ id, ...otherSectionProps }) => ( <MenuItem key={id} {...otherSectionProps} /> ))} </div> ); } } export default Directory;
import { connect } from 'react-redux'; import Toast from './toast.component'; import { hideToast } from './toaster.action'; const mapStateToProps = ({ toaster: { visible, content, variant, options } }) => ({ visible, content, variant, options, }); export default connect( mapStateToProps, { hideToast }, )(Toast);
function sortInt(payload, direction) { 'use strict'; var isAscending = (direction !== 'desc'); var l = payload.length; // loop through all items for (var x = l - 1; x >= 0; x--) { // original comparator value and position var origin = payload[x]; var position = x; // loop through precedents items for (var y = x - 1; y >= 0; y--) { var previous = payload[y]; if ((isAscending && previous > origin) || (!isAscending && previous < origin)) { // alright swap comparator origin = previous; position = y; } } // need swap? then swap between if (position !== x) { var t = payload[position]; payload[position] = payload[x]; payload[x] = t; } } return payload; } function sortIntAsc(payload) { return sortInt(payload, "asc") } function sortIntDesc(payload) { return sortInt(payload, "desc") } exports.sortIntAsc = sortIntAsc exports.sortIntDesc = sortIntDesc
define('isIt',function(){ return isIt = { pwd:function(str,intro){ //长度大于或等于6 var reg=/^[a-zA-Z]\w{5,17}$/; if(intro===undefined){ intro=""; } if(str.length < 6 || str.length > 16){ try{ tip.on(intro + "'" + str + "'" + " 不是正确的密码,因为长度小于6或者大于16",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的密码,因为长度小于6或者大于16"); } return false; } if(reg.test(str)){ // pass return true; } try{ tip.on("密码需以字母开头,长度在6~18之间,只能包含字符、数字和下划线",0,3000); }catch(err){ console.log("密码需以字母开头,长度在6~18之间,只能包含字符、数字和下划线"); } return false; }, number:function(str,intro){ //数字 // var reg = /^[0-9-][0-9.]+$/; //排除十六进制和未写整数部分的小数等情况 //上面这个有很大问题例如'2.2.2.2'也true var reg=/^[0-9]+(\.{0,1}[0-9]{1,3})|[0-9]*/; //Chris更改 整数或至多3位小数 if(intro===undefined){ intro=""; } if(reg.test(str)){ if(isNaN(str)){ try{ tip.on(intro + "'" + str + "'" + " 不是数字 ",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是数字 "); } return false; } //console.log("'" + str + "'" + " 是 " + intro ); return true; } try{ tip.on(intro + "'" + str + "'" + " 不是数字",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是数字 "); } return false; }, //正确格式:XXXX-XXXXXXX,XXXX-XXXXXXXX,XXX-XXXXXXX,XXX-XXXXXXXX,XXXXXXX,XXXXXXXX。 telephone:function(str,intro){ //座机!!(不确定有哪些严格字段) var reg = /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/;///^\d{3}-\d{8}|\d{4}-\d{7}$/;///([0-9]{3,4}-)?[0-9]{7,8}/;d{3}-d{8}|d{4}-d{7};^((d{3,4})|d{3,4}-)?d{7,8}$ if(intro===undefined){ intro=""; } if(reg.test(str)){ //console.log("'" + str + "'" + " 是 " + intro ); return true; } try{ tip.on(intro + "'" + str + "'" + " 不是正确的座机号码,请用‘-’分隔",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的座机号码,请用‘-’分隔"); } return false; }, //最新手机号段归属地数据库(2015年10月18日) /* 三大运营商最新号段 合作版 移动号段: 134 135 136 137 138 139 147 150 151 152 157 158 159 178(新) 182 183 184 187 188 联通号段: 130 131 132 145 155 156 175(新) 176(新) 185 186 电信号段: 133 153 177 180 181 189 虚拟运营商: 170 总结: 130-139/180-189 145 、147 150-153 、155-159 170 、175 、176 、177 、178 */ mobile:function(str,intro){ //手机 var reg = /^(1[38][0-9][0-9]{8})|(14[57][0-9]{8})|(15[012356789][0-9]{8})|(17[05678][0-9]{8})$/; if(intro===undefined){ intro=""; } if(reg.test(str)){ //console.log("'" + str + "'" + " 是 " + intro ); return true; } try{ tip.on(intro + "'" + str + "'" + " 不是正确的手机号码",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的手机号码"); } return false; }, tel: function (str, intro) { var p=/^(1[38][0-9][0-9]{8})|(14[57][0-9]{8})|(15[012356789][0-9]{8})|(17[05678][0-9]{8})$/; var t=/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/; if(intro===undefined){ intro=""; } if(p.test(str)||t.test(str)){ return true } try{ tip.on(intro + "'" + str + "'" + " 不是正确的电话号码",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的电话号码"); } return false; }, email:function(str,intro){ //电子邮箱(不太确定有哪些奇葩的邮箱) var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; if(intro===undefined){ intro=""; } if(reg.test(str)){ //console.log("'" + str + "'" + " 是 " + intro ); return true; } try{ tip.on(intro + "'" + str + "'" + " 不是正确的电子邮箱" ,0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的电子邮箱"); } return false; }, money:function(str,intro){ // 整数或只有2为小数的数值 var reg = /^[0-9]+(.[0-9]{1,2})?$/; if(intro===undefined){ intro=""; } if(reg.test(str)){ //console.log("'" + str + "'" + " 是 " + intro ); return true; } try{ tip.on(intro + "'" + str + "'" + " 不是正确的金额,金额为整数或只有两位小数",0,3000); billTip.on(intro + "'" + str + "'" + " 不是正确的金额,金额为整数或只有两位小数",0,3000) }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的金额,金额为整数或只有两位小数"); } return false; }, id:function(str,intro){ //身份证号码 var reg = /^\d{6}[12]\d{3}[01][0-9][0123][0-9]\d{3}[0-9xX]$/; if(intro===undefined){ intro=""; } if(reg.test(str)){ var yy = parseInt(str[6] + str[7] + str[8] + str[9]); var mm = parseInt(str[10] + str[11]); var dd = parseInt(str[12] + str[13]); var nowdate = new Date(); if(yy > nowdate.getFullYear()){ try{ tip.on(intro + "'" + str + "'" + " 不是正确的身份证号码,因为出生年份大于当前年份",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的身份证号码,因为出生年份大于当前年份"); } return false; } if(mm > 12 || mm == 0){ try{ tip.on(intro + "'" + str + "'" + " 不是正确的身份证号码,因为出生月份错误",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的身份证号码,因为出生月份错误"); } return false; } var day = [31,28,31,30,31,30,31,31,30,31,30,31]; if((yy % 400 == 0)||(yy / 4 == 0 && yy / 100 != 0)){ day[1] = 29; } if(dd > day[mm - 1] || dd == 0){ try{ tip.on(intro + "'" + str + "'" + " 不是正确的身份证号码,因为出生日期错误",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的身份证号码,因为出生日期错误"); } return false; } //console.log("'" + str + "'" + " 是 " + intro ); return true; } try{ tip.on(intro + "'" + str + "'" + " 不是正确的身份证号码",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的身份证号码"); } return false; }, //Chris 补充 /*(严格)匹配姓名: 要求:真实姓名可以是汉字,也可以是字母,但是不能两者都有,也不能包含任何符号和数字 注意:1.如果是英文名,可以允许英文名字中出现空格 2.英文名的空格可以是多个,但是不能连续出现多个 3.汉字不能出现空格[\u4e00-\u9fa5] */ name:function(str,intro){//匹配姓名 var reg=/^([\u4e00-\u9fa5]+|([a-zA-Z]+\s?)+)$/; if(intro===undefined){ intro=""; } if(reg.test(str)){ //console.log("'" + str + "'" + " 是 " + intro ); return true; } try{ tip.on(intro + "'" + str + "'" + " 不是正确的姓名格式",0,3000); }catch(err){ console.log(intro + "'" + str + "'" + " 不是正确的姓名格式"); } return false; } }; });
import React, { useState, memo } from 'react'; import { string, bool, func } from 'prop-types'; import { useUpdateEffect } from 'react-use'; import { useTranslation } from 'react-i18next'; import clsx from 'clsx'; import { makeStyles } from '@material-ui/styles'; import { fade } from '@material-ui/core/styles/colorManipulator'; import { CardMedia, IconButton } from '@material-ui/core'; import { AddAPhotoRounded, EditRounded } from '@material-ui/icons'; import useEvent from '../hooks/useEvent'; import Spinner from './Spinner'; const propTypes = { photo: string, canUpdate: bool, onChange: func.isRequired, }; const defaultProps = { photo: null, canUpdate: false, }; const useStyles = makeStyles(theme => ({ root: { filter: ({ sending }) => (sending ? 'opacity(0.5)' : 'none'), }, fullHeight: { height: '100%', }, button: { width: '100%', padding: 0, borderRadius: 0, opacity: ({ hasSource }) => (hasSource ? 0 : 1), transition: theme.transitions.create(['opacity']), '&:hover': { opacity: 1, }, }, buttonColor: ({ hasSource }) => hasSource && { color: theme.palette.common.white, '&:hover': { backgroundColor: fade( theme.palette.common.white, theme.palette.action.hoverOpacity, ), }, }, spinner: { position: 'absolute', top: 0, left: 0, }, padded: { paddingBottom: 62, // Lengend is 54px height + 2 * 4px margin }, })); const PointPopupPhoto = ({ photo, canUpdate, onChange }) => { const [source, setSource] = useState(photo); const [sending, setSending] = useState(false); const [loading, setLoading] = useState(false); useUpdateEffect(() => { // Uploaded photo variant received: // When the browser hits the variant URL, Active Storage will lazily transform the // original blob into the specified format and redirect to its new service location, // this could take some time. Here we set the component as loading to hold sending // state UI until the hoto is received and fully loaded. setLoading(true); }, [photo]); const classes = useStyles({ hasSource: !!source, sending }); const { t } = useTranslation(); const ActionIcon = !source ? AddAPhotoRounded : EditRounded; const createEvent = useEvent(); const createPhotoUploadEvent = () => { createEvent({ category: 'Reporting', action: 'Uploaded a photo', label: 'Report photo upload', }); }; const handleChange = event => { const file = event.target.files[0]; setSource(URL.createObjectURL(file)); setSending(true); onChange(file); createPhotoUploadEvent(); }; // Original blob transformation and loading completed, can show upload success. const handleUploadedPhotoLoad = () => { // Release preview object URL URL.revokeObjectURL(source); // Display uploaded photo variant setSource(photo); // Reset UI setSending(false); setLoading(false); }; return ( <> <CardMedia className={clsx(classes.root, classes.fullHeight)} image={source} > {canUpdate && !sending && ( <div className={classes.fullHeight}> <input id="add-a-photo" type="file" accept="image/*" onChange={handleChange} hidden /> <label htmlFor="add-a-photo" className={classes.fullHeight}> <IconButton component="div" color="primary" centerRipple={false} classes={{ root: clsx(classes.button, classes.fullHeight), label: classes.padded, colorPrimary: classes.buttonColor, }} aria-label={t('Add a photo')} > <ActionIcon /> </IconButton> </label> </div> )} </CardMedia> {sending && ( <Spinner variant="medium" delay={100} containerClassName={clsx(classes.spinner, classes.padded)} /> )} {loading && ( <img hidden alt="" src={photo} importance="high" onLoad={handleUploadedPhotoLoad} /> )} </> ); }; export default memo(PointPopupPhoto); PointPopupPhoto.propTypes = propTypes; PointPopupPhoto.defaultProps = defaultProps;
/* Theme Name: Mehr - Startup Landing page Author: Bighero Version : 1.0 */ jQuery(document).ready(function($) { "use strict"; new WOW().init(); // PRELOADER $(window).load(function() { $('#preloader').fadeOut('slow', function() { $(this).remove(); }); }); // Magnific Popup $('.popup-video').magnificPopup({ disableOn: 700, type: 'iframe', mainClass: 'mfp-fade', removalDelay: 160, preloader: false, fixedContentPos: false }); // Animated typing text // $(".animated-text").typed({ // strings: [ // "fully responsive", // "onepage template", // "mobile first", // "startup template" // ], // typeSpeed: 50, // loop: true, // }); // STICKY NAGIGATION $("#sticky-nav").sticky({ topSpacing: 0.2 }); // Smooth scroll var $root = $('html, body'); $('a').on('click', function() { $root.animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 1200, 'easeInOutCubic'); return false; }); // TESTIMONIALS SLIDER // $("#testimonials .slider").owlCarousel({ // navigation: false, // slideSpeed: 300, // paginationSpeed: 400, // singleItem: true // }); // CLIENTS SLIDER // $("#clients .slider").owlCarousel({ // navigation: false, // pagination: false, // autoPlay: 5000, / // items: 5, // }); $(window).scroll(function() { var scrollTop = $(window).scrollTop(); if (scrollTop > $("#sobre").offset().top) { $('.scroll-indicator').css('opacity', '1'); } else { $('.scroll-indicator').css('opacity', '0'); } }); // FORM VALIDATION // $(".subscribe-form input").jqBootstrapValidation({ // preventSubmit: true, // submitSuccess: function($form, event) { // event.preventDefault(); // prevent default submit behaviour // $.ajax({ // success: function() { // $('#subscribe-success').html("<div class='alert alert-success'>"); // $('#subscribe-success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") // .append("</button>"); // $('#subscribe-success > .alert-success') // .append("<strong>Your message has been sent. </strong>"); // $('#subscribe-success > .alert-success') // .append('</div>'); // } // }) // } // }); // CONTACT FORM // $("#contactForm input, #contactForm textarea").jqBootstrapValidation({ // preventSubmit: true, // submitError: function($form, event, errors) { // }, // submitSuccess: function($form, event) { // event.preventDefault(); // var name = $("input#name").val(); // var email = $("input#email").val(); // var message = $("textarea#message").val(); // var firstName = name; // if (firstName.indexOf(' ') >= 0) { // firstName = name.split(' ').slice(0, -1).join(' '); // } // $.ajax({ // url: "../mail/sendmail.php", // type: "POST", // data: { // name: name, // email: email, // message: message // }, // cache: false, // success: function() { // $('#success').html("<div class='alert alert-success'>"); // $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") // .append("</button>"); // $('#success > .alert-success') // .append("<strong>Your message has been sent. </strong>"); // $('#success > .alert-success') // .append('</div>'); // $('#contactForm').trigger("reset"); // }, // error: function() { // $('#success').html("<div class='alert alert-danger'>"); // $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") // .append("</button>"); // $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"); // $('#success > .alert-danger').append('</div>'); // $('#contactForm').trigger("reset"); // }, // }) // }, // filter: function() { // return $(this).is(":visible"); // }, // }); // GOOGLE MAP // $('#map').addClass('scrolloff'); // $('#overlay').on("mouseup", function() { // $('#map').addClass('scrolloff'); // }); // $('#overlay').on("mousedown", function() { // $('#map').removeClass('scrolloff'); // }); // $("#map").mouseleave(function() { // $('#map').addClass('scrolloff'); // }); });
function saveLocation() { var scroll = $(window).scrollTop(); localStorage.setItem('lastlocation', scroll); var lastChapter = document.getElementById('chapter-dropdown').value; var lastVerse = document.getElementById('verseList').value; localStorage.setItem('lastChapter', lastChapter); localStorage.setItem('lastVerse', lastVerse); } window.onbeforeunload = function() { saveLocation(); }; var x = 2 + 8; function goToPrevious() { var location = localStorage.getItem('lastlocation'); if (location != null) { scrollTo(0, location); } } console.log(x);
$(function(){ //添加主表 $("#addmaintable").click(function(){ $("#tablecolumn").html(""); $("#jointablelist").html(""); globaldata['tableinfo'] = {}; var maintable = $("#maintable").val(); var param = { 'maintable':maintable } $.loadajax({ url:baseurl+"m/Createtemp/getTablecolumn", data:param, success:function(res){ if(res.code!=1) { alertError(res.msg); return false; } var data = res.data; var maintablecolume = []; $("#tablecolumn").html(data['columnview']); $("#tablecolumn .maincolumevalue").each(function(){ maintablecolume.push($(this).val()); }) //用于表关联 globaldata['tableinfo'] = { //主表 'maintable':maintable, 'maintablecolume':maintablecolume, //关联表信息 'jointablelist':[ /* 数据结构 { jointable:'', jointablecolume:[] } */ ] } }, error:function(){ alertError(res.msg); return false; } }) }) $("#addjointable").click(function(){ if(!globaldata['tableinfo']||!globaldata['tableinfo']['maintable'] ){ alertError("请先选择主表"); return false; } var maintable = globaldata['tableinfo']['maintable']; var param = { 'maintable':maintable } $.loadajax({ url:baseurl+"m/Createtemp/getJoinTable", data:param, success:function(res){ if(res.code!=1) { alertError(res.msg); return false; } var data = res.data; var maintablecolume = []; $("#jointablelist").append(data['jointableview']); }, error:function(){ alertError(res.msg); } }) }) //清空联查表 $("#deletejointable").click(function(){ $("#jointablelist").html(""); globaldata['tableinfo']['jointablelist']=[]; }) //提交 $("#createtemp").click(function(){ $("#createfile").modal("show"); $("#createfile .save").off(); $("#createfile .save").on("click",function(){ $("#createfile").modal("hide"); var maintable = $("#maintable").val(); if(!maintable){ alertError("缺少主表"); return false; } var maintablecolume = []; $("#tablecolumn .maincolumevalue").each(function(){ var othis = $(this); if( !othis.is(":checked") ){ return true } var comment = othis.parent().parent().next().find(".maincolumecomment").val(); var search = 0; if(othis.parent().parent().next().find(".maincolumesearch").attr('checked')){ search = othis.parent().parent().next().find(".maincolumesearch").val(); } var odata = { 'k':othis.val(),//字段名 't':comment,//标题 's':search //搜索字段 } maintablecolume.push(odata); }) var joinlist = []; $("#jointablelist .jointablaname").each(function(){ var othis = $(this); var odata = { 'table':othis.val(), 'colume':[] } othis.parent().parent().next().find(".joincolumeinfolist").each(function(){ var jdata = $(this); if( !jdata.find(".joincolumevalue").is(":checked") ){ return true } var search = 0; if(jdata.find(".leftjoinolumesearch").attr('checked')){ search = jdata.find(".leftjoinolumesearch").val(); } var ocolume = { 'k':jdata.find(".joincolumevalue").val(), 't':jdata.find(".joincolumncomment").val(), //设为搜索项 's':search, //关联表名及字段 'l':jdata.find(".leftjoincolmunvalue").text(), }; odata['colume'].push(ocolume) }) joinlist.push(odata) }) var coldata = { 'maintable':maintable,//主表名 'maintablecolume':maintablecolume,//主表字段 'joinlist':[ /* { table:"", colume:[ { 'k':"", //字段 't':"", //标题 'f':"", //重命名 'l':"" //关联表名及字段 } ] } */ ], 'filename':$("#filename").val() }; coldata['joinlist']=joinlist; $.loadajax({ url:baseurl+"m/Createtemp/creater", type:"post", data:coldata, success:function(res){ if(res.code!=1) { alertError(res.msg); return false; } // var data = res.data; // var info = "<pre>"+ // "<button class='btn btn-success btn-xs'>添加为目录</button>"+ // " <button class='btn btn-danger btn-xs deletefile' aid='"+data['file_id']+"'>移除文件</button>"+ // "<br><br>创建时间:"+data['file_ctime']+"<br>"; // "</pre>"; // for(var i in data['file']){ // info+=data['file'][i]+"<br>"; // } // info+="</pre>"; // $(".rescreateinfo").prepend(info); // return true; location.reload(); }, error:function(){ alertError(res.msg); } }) }) }) //提交 $("#createtempsimp").click(function(){ $("#createfile").modal("show"); $("#createfile .save").off(); $("#createfile .save").on("click",function(){ $("#createfile").modal("hide"); if(!$("#filename").val()){ alertError("缺少文件名"); } var coldata = { 'filename':$("#filename").val() }; $.loadajax({ url:baseurl+"m/Createtemp/createrSimply", type:"post", data:coldata, success:function(res){ if(res.code!=1) { alertError(res.msg); return false; } location.reload(); }, error:function(){ alertError(res.msg); } }) }) }) $(".deletefile").on("click",function(){ var id = $(this).attr("aid"); var othis = $(this); $.loadajax({ confirm:"文件将被删除,请确认不是在使用中的目录!", url:baseurl+"m/Createtemp/deletefile?id="+id, success:function(res){ if(res.code == 1){ othis.parent().parent().remove(); alertSuccess(res.msg); }else{ alertError(res.msg); } }, error:function(){ alertError("操作失败"); } }) }) })
// // Collect the time from argv // // // Print stars in-line // // // Run a timer and remove stars //