language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | displayNoneInlineButton(accion){
/** Se valida si se obtuvo informacion o no */
if(this.state.objConfiguracion.id > 0){
/** se valida si se esta realizando un guardado o edicion */
if(accion === 'Guardar'){
document.getElementById("btnGuardar").style.display = "none";
document.getElementById("btnEditar").style.display = "inline";
}else{
document.getElementById("btnGuardar").style.display = "inline";
document.getElementById("btnEditar").style.display = "none";
}
}
} | displayNoneInlineButton(accion){
/** Se valida si se obtuvo informacion o no */
if(this.state.objConfiguracion.id > 0){
/** se valida si se esta realizando un guardado o edicion */
if(accion === 'Guardar'){
document.getElementById("btnGuardar").style.display = "none";
document.getElementById("btnEditar").style.display = "inline";
}else{
document.getElementById("btnGuardar").style.display = "inline";
document.getElementById("btnEditar").style.display = "none";
}
}
} |
JavaScript | limpiarStateValues(){
this.asignarValorState('tasafinanciamiento',0,'objConfiguracion');
this.asignarValorState('porcientoenganche',0,'objConfiguracion');
this.asignarValorState('plazomaximo',0,'objConfiguracion');
} | limpiarStateValues(){
this.asignarValorState('tasafinanciamiento',0,'objConfiguracion');
this.asignarValorState('porcientoenganche',0,'objConfiguracion');
this.asignarValorState('plazomaximo',0,'objConfiguracion');
} |
JavaScript | obtieneConfiguracion(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Configuracion/getConfiguracion',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Validacion para determinar si trae informacion el objeto o no */
if(Respuesta.objConfiguracion !== null){
/** Se asignan los valores al state normal */
this.asignarValorState('id',Respuesta.objConfiguracion.id,'objConfiguracion');
this.asignarValorState('tasafinanciamiento',Respuesta.objConfiguracion.tasafinanciamiento,'objConfiguracion');
this.asignarValorState('porcientoenganche',Respuesta.objConfiguracion.porcientoenganche,'objConfiguracion');
this.asignarValorState('plazomaximo',Respuesta.objConfiguracion.plazomaximo,'objConfiguracion');
/** Se asignan los valores al state de editar */
this.asignarValorState('id',Respuesta.objConfiguracion.id,'objConfEditar');
this.asignarValorState('tasafinanciamiento',Respuesta.objConfiguracion.tasafinanciamiento,'objConfEditar');
this.asignarValorState('porcientoenganche',Respuesta.objConfiguracion.porcientoenganche,'objConfEditar');
this.asignarValorState('plazomaximo',Respuesta.objConfiguracion.plazomaximo,'objConfEditar');
/** Se llama el metodo que deshabilita el boton */
this.displayNoneInlineButton('Guardar');
/** Se llama el metodo que deshabilita los inputs */
this.deshabilitarHabilitarInputs(true);
}
})
} | obtieneConfiguracion(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Configuracion/getConfiguracion',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Validacion para determinar si trae informacion el objeto o no */
if(Respuesta.objConfiguracion !== null){
/** Se asignan los valores al state normal */
this.asignarValorState('id',Respuesta.objConfiguracion.id,'objConfiguracion');
this.asignarValorState('tasafinanciamiento',Respuesta.objConfiguracion.tasafinanciamiento,'objConfiguracion');
this.asignarValorState('porcientoenganche',Respuesta.objConfiguracion.porcientoenganche,'objConfiguracion');
this.asignarValorState('plazomaximo',Respuesta.objConfiguracion.plazomaximo,'objConfiguracion');
/** Se asignan los valores al state de editar */
this.asignarValorState('id',Respuesta.objConfiguracion.id,'objConfEditar');
this.asignarValorState('tasafinanciamiento',Respuesta.objConfiguracion.tasafinanciamiento,'objConfEditar');
this.asignarValorState('porcientoenganche',Respuesta.objConfiguracion.porcientoenganche,'objConfEditar');
this.asignarValorState('plazomaximo',Respuesta.objConfiguracion.plazomaximo,'objConfEditar');
/** Se llama el metodo que deshabilita el boton */
this.displayNoneInlineButton('Guardar');
/** Se llama el metodo que deshabilita los inputs */
this.deshabilitarHabilitarInputs(true);
}
})
} |
JavaScript | onChangeSelectCliente(s){
if(s.length > 0){
/** Se agrega el nombre a la propiedad del state */
this.asignarValorState('nombrecliente',s[0].nombre,'opcionesSeleccionadas');
this.asignarValorState('clavecliente',s[0].clavecliente,'opcionesSeleccionadas');
this.asignarValorState('rfccliente',s[0].rfc,'opcionesSeleccionadas');
/** se muestra el div donde se encuentra el rfc */
document.getElementById("divRfc").style.display="inline";
}else{
/** Se limpia el nombre y clave a la propiedad del state */
this.asignarValorState('nombrecliente','','opcionesSeleccionadas');
this.asignarValorState('clavecliente','','opcionesSeleccionadas');
this.asignarValorState('rfccliente','','opcionesSeleccionadas');
/** se oculta el div donde se encuentra el rfc */
document.getElementById("divRfc").style.display="none";
}
} | onChangeSelectCliente(s){
if(s.length > 0){
/** Se agrega el nombre a la propiedad del state */
this.asignarValorState('nombrecliente',s[0].nombre,'opcionesSeleccionadas');
this.asignarValorState('clavecliente',s[0].clavecliente,'opcionesSeleccionadas');
this.asignarValorState('rfccliente',s[0].rfc,'opcionesSeleccionadas');
/** se muestra el div donde se encuentra el rfc */
document.getElementById("divRfc").style.display="inline";
}else{
/** Se limpia el nombre y clave a la propiedad del state */
this.asignarValorState('nombrecliente','','opcionesSeleccionadas');
this.asignarValorState('clavecliente','','opcionesSeleccionadas');
this.asignarValorState('rfccliente','','opcionesSeleccionadas');
/** se oculta el div donde se encuentra el rfc */
document.getElementById("divRfc").style.display="none";
}
} |
JavaScript | calcularInfTotalEngancheBonificacion(){
/** Variables para calcular el porcentaje de enganche, Bonificacion de enganche y el total */
var porcentajeEnganche = parseFloat(0);
var bonificacionEnganche = parseFloat(0);
var totalAdeudo = parseFloat(0);
/** Se recorre el arreglo */
for(var i = 0; i < this.state.articulosCalculaInformacion.length;i++){
/** Se obtiene el objeto en la posicion del arreglo */
var object = this.state.articulosCalculaInformacion[i];
/** Se calcula el iva del producto */
var precioiva = (parseFloat(object.precio) * (1 + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(this.props.objConfiguracion.plazomaximo)) / parseFloat(100)))).toFixed(2);
/** Se calcula el importe del producto */
var importeproducto = precioiva * parseInt(object.cantidad);
/** Se calcula el porcentaje enganche */
var enganche = ((parseFloat(this.props.objConfiguracion.porcientoenganche)/parseInt(100)) * importeproducto).toFixed(2);
/** Se calcula la bonificacion del enganche */
var boniEnganche = (enganche * ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseFloat(this.props.objConfiguracion.plazomaximo)) / parseInt(100))).toFixed(2);
/** Se calcula el total */
var total = (parseFloat(importeproducto) - parseFloat(enganche) - parseFloat(boniEnganche)).toFixed(2);
/** Se asignan los valores a las variables necesarias para llevar el conteo */
porcentajeEnganche = parseFloat(parseFloat(porcentajeEnganche) + parseFloat(enganche)).toFixed(2);
bonificacionEnganche = parseFloat(parseFloat(bonificacionEnganche) + parseFloat(boniEnganche)).toFixed(2);
totalAdeudo = parseFloat(parseFloat(totalAdeudo) + parseFloat(total)).toFixed(2);
}
/** Se asigna la informacion al state */
this.asignarValorState('enganche',parseFloat(porcentajeEnganche).toFixed(2),'informacionTotal');
this.asignarValorState('bonificacionenganche',parseFloat(bonificacionEnganche).toFixed(2),'informacionTotal');
this.asignarValorState('total',parseFloat(totalAdeudo).toFixed(2),'informacionTotal');
} | calcularInfTotalEngancheBonificacion(){
/** Variables para calcular el porcentaje de enganche, Bonificacion de enganche y el total */
var porcentajeEnganche = parseFloat(0);
var bonificacionEnganche = parseFloat(0);
var totalAdeudo = parseFloat(0);
/** Se recorre el arreglo */
for(var i = 0; i < this.state.articulosCalculaInformacion.length;i++){
/** Se obtiene el objeto en la posicion del arreglo */
var object = this.state.articulosCalculaInformacion[i];
/** Se calcula el iva del producto */
var precioiva = (parseFloat(object.precio) * (1 + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(this.props.objConfiguracion.plazomaximo)) / parseFloat(100)))).toFixed(2);
/** Se calcula el importe del producto */
var importeproducto = precioiva * parseInt(object.cantidad);
/** Se calcula el porcentaje enganche */
var enganche = ((parseFloat(this.props.objConfiguracion.porcientoenganche)/parseInt(100)) * importeproducto).toFixed(2);
/** Se calcula la bonificacion del enganche */
var boniEnganche = (enganche * ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseFloat(this.props.objConfiguracion.plazomaximo)) / parseInt(100))).toFixed(2);
/** Se calcula el total */
var total = (parseFloat(importeproducto) - parseFloat(enganche) - parseFloat(boniEnganche)).toFixed(2);
/** Se asignan los valores a las variables necesarias para llevar el conteo */
porcentajeEnganche = parseFloat(parseFloat(porcentajeEnganche) + parseFloat(enganche)).toFixed(2);
bonificacionEnganche = parseFloat(parseFloat(bonificacionEnganche) + parseFloat(boniEnganche)).toFixed(2);
totalAdeudo = parseFloat(parseFloat(totalAdeudo) + parseFloat(total)).toFixed(2);
}
/** Se asigna la informacion al state */
this.asignarValorState('enganche',parseFloat(porcentajeEnganche).toFixed(2),'informacionTotal');
this.asignarValorState('bonificacionenganche',parseFloat(bonificacionEnganche).toFixed(2),'informacionTotal');
this.asignarValorState('total',parseFloat(totalAdeudo).toFixed(2),'informacionTotal');
} |
JavaScript | onClickAgregarArticulo(){
/** Validacion para determinar si se agregara el elemento seleccionado al listado */
if(this.state.opcionArticulo.id > 0){
/** Se crea un objeto para asignar la informacion */
var objArt = {
clavearticulo:this.state.opcionArticulo.clavearticulo,
descripcion:this.state.opcionArticulo.descripcion,
existencia:this.state.opcionArticulo.existencia,
//id:this.state.opcionArticulo.id,
modelo:this.state.opcionArticulo.modelo,
precio:this.state.opcionArticulo.precio,
cantidad:this.state.opcionArticulo.cantidad
};
/** Se agrega el articulo al listado */
this.state.listadoArticulosSeleccionados.push(objArt);
/** Prueba de error */
this.onChangeSelectArticulo(this.state.listadoArticulosSeleccionados);
}
/** Se limpia el typeahead */
this._Typeahead.clear();
} | onClickAgregarArticulo(){
/** Validacion para determinar si se agregara el elemento seleccionado al listado */
if(this.state.opcionArticulo.id > 0){
/** Se crea un objeto para asignar la informacion */
var objArt = {
clavearticulo:this.state.opcionArticulo.clavearticulo,
descripcion:this.state.opcionArticulo.descripcion,
existencia:this.state.opcionArticulo.existencia,
//id:this.state.opcionArticulo.id,
modelo:this.state.opcionArticulo.modelo,
precio:this.state.opcionArticulo.precio,
cantidad:this.state.opcionArticulo.cantidad
};
/** Se agrega el articulo al listado */
this.state.listadoArticulosSeleccionados.push(objArt);
/** Prueba de error */
this.onChangeSelectArticulo(this.state.listadoArticulosSeleccionados);
}
/** Se limpia el typeahead */
this._Typeahead.clear();
} |
JavaScript | validarInformacion(){
/** Se valida que se haya seleccionado un cliente */
if(this.state.opcionesSeleccionadas.clavecliente !== ''){
/** Se valida que se haya seleccionado un articulo */
if(this.state.opcionArticulo.clavearticulo !== '' && this.state.opcionArticulo.id > 0){
/** Se valida que al menos haya seleccionado un articulo */
if(this.state.informacionArticulo.cantidad > 0){
/** Se asigna el valor para mostrar la seccion de pagos */
this.asignarValorState('showSeccionPagos',true,'mostrarVentanaPagos');
/** Se deshabilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="none";
/** Se hablita el boton de guardar */
document.getElementById("btnGuardar").style.display="inline";
}else{
/** Mensaje de error de que debe seleccionar el articulo */
this.mostrarControlMensaje('Se debe agregar un artículo a la tabla','danger','showMensaje');
/** Se deshablita el boton de guardar */
document.getElementById("btnGuardar").style.display="none";
/** Se habilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="inline";
}
}else{
/** Mensaje de error de que debe seleccionar el articulo */
this.mostrarControlMensaje('Se debe seleccionar un artículo','danger','showMensaje');
/** Se deshablita el boton de guardar */
document.getElementById("btnGuardar").style.display="none";
/** Se habilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="inline";
}
}else{
/** Mensaje de error de que debe seleccionar el cliente */
this.mostrarControlMensaje('Se debe seleccionar un cliente','danger','showMensaje');
/** Se deshablita el boton de guardar */
document.getElementById("btnGuardar").style.display="none";
/** Se habilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="inline";
}
} | validarInformacion(){
/** Se valida que se haya seleccionado un cliente */
if(this.state.opcionesSeleccionadas.clavecliente !== ''){
/** Se valida que se haya seleccionado un articulo */
if(this.state.opcionArticulo.clavearticulo !== '' && this.state.opcionArticulo.id > 0){
/** Se valida que al menos haya seleccionado un articulo */
if(this.state.informacionArticulo.cantidad > 0){
/** Se asigna el valor para mostrar la seccion de pagos */
this.asignarValorState('showSeccionPagos',true,'mostrarVentanaPagos');
/** Se deshabilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="none";
/** Se hablita el boton de guardar */
document.getElementById("btnGuardar").style.display="inline";
}else{
/** Mensaje de error de que debe seleccionar el articulo */
this.mostrarControlMensaje('Se debe agregar un artículo a la tabla','danger','showMensaje');
/** Se deshablita el boton de guardar */
document.getElementById("btnGuardar").style.display="none";
/** Se habilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="inline";
}
}else{
/** Mensaje de error de que debe seleccionar el articulo */
this.mostrarControlMensaje('Se debe seleccionar un artículo','danger','showMensaje');
/** Se deshablita el boton de guardar */
document.getElementById("btnGuardar").style.display="none";
/** Se habilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="inline";
}
}else{
/** Mensaje de error de que debe seleccionar el cliente */
this.mostrarControlMensaje('Se debe seleccionar un cliente','danger','showMensaje');
/** Se deshablita el boton de guardar */
document.getElementById("btnGuardar").style.display="none";
/** Se habilita el boton de siguiente */
document.getElementById("btnSiguiente").style.display="inline";
}
} |
JavaScript | guardarVenta(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Ventas/guardarVenta',{
method:'POST',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
},body:JSON.stringify(this.state.objVenta)
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna la informacion del modal para ocultarlo */
this.asignarValorState('mensaje','','modalCargando');
this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se valida para determinar si se realizo el guardado correctamnte o no */
if(Respuesta.objetoStatus.codigoError.split(" ")[0] === "201"){
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'success','showMensaje');
}else{
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'danger','showMensaje');
}
})
} | guardarVenta(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Ventas/guardarVenta',{
method:'POST',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
},body:JSON.stringify(this.state.objVenta)
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna la informacion del modal para ocultarlo */
this.asignarValorState('mensaje','','modalCargando');
this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se valida para determinar si se realizo el guardado correctamnte o no */
if(Respuesta.objetoStatus.codigoError.split(" ")[0] === "201"){
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'success','showMensaje');
}else{
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'danger','showMensaje');
}
})
} |
JavaScript | componentWillMount(){
this.asignarValorState('id',this.props.objArticulo.id,'objArticulo');
if(this.props.objArticulo.clavearticulo === ''){
this.asignarValorState('clavearticulo',this.props.claveArticulo,'objArticulo');
}else{
this.asignarValorState('clavearticulo',this.props.objArticulo.clavearticulo,'objArticulo');
}
this.asignarValorState('descripcion',this.props.objArticulo.descripcion,'objArticulo');
this.asignarValorState('modelo',this.props.objArticulo.modelo,'objArticulo');
this.asignarValorState('precio',this.props.objArticulo.precio,'objArticulo');
this.asignarValorState('existencia',this.props.objArticulo.existencia,'objArticulo');
} | componentWillMount(){
this.asignarValorState('id',this.props.objArticulo.id,'objArticulo');
if(this.props.objArticulo.clavearticulo === ''){
this.asignarValorState('clavearticulo',this.props.claveArticulo,'objArticulo');
}else{
this.asignarValorState('clavearticulo',this.props.objArticulo.clavearticulo,'objArticulo');
}
this.asignarValorState('descripcion',this.props.objArticulo.descripcion,'objArticulo');
this.asignarValorState('modelo',this.props.objArticulo.modelo,'objArticulo');
this.asignarValorState('precio',this.props.objArticulo.precio,'objArticulo');
this.asignarValorState('existencia',this.props.objArticulo.existencia,'objArticulo');
} |
JavaScript | onChange(target,propiedad,objeto){
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
if(propiedad === 'descripcion' || propiedad === 'modelo'){
valorPattern = obtenerRegexPattern("nombres");
}else{
if(propiedad === 'precio'){
valorPattern = obtenerRegexPattern("precio");
}else{
valorPattern = obtenerRegexPattern("numero");
}
}
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
} | onChange(target,propiedad,objeto){
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
if(propiedad === 'descripcion' || propiedad === 'modelo'){
valorPattern = obtenerRegexPattern("nombres");
}else{
if(propiedad === 'precio'){
valorPattern = obtenerRegexPattern("precio");
}else{
valorPattern = obtenerRegexPattern("numero");
}
}
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
} |
JavaScript | validarInformacion(){
if(this.generaValidacionControles() === 0){
/** Se valida si se realizara un guardado o una actualizacion */
if(this.state.objArticulo.id === 0){
/** Se realizara un guardado */
return true;
}else{
/** Se llama el metodo que se encargara de indicar si se modifico algo o no */
if(validaStateVsPropObj(this.state.objArticulo,this.props.objArticulo,'articulos')){
return true;
}else{
/** Se asignan los valores del mensaje */
this.mostrarControlMensaje("Se debe modificar al menos un campo para poder actualizar.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
}
}else{
this.mostrarControlMensaje("Debe proporcionar toda la información.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
} | validarInformacion(){
if(this.generaValidacionControles() === 0){
/** Se valida si se realizara un guardado o una actualizacion */
if(this.state.objArticulo.id === 0){
/** Se realizara un guardado */
return true;
}else{
/** Se llama el metodo que se encargara de indicar si se modifico algo o no */
if(validaStateVsPropObj(this.state.objArticulo,this.props.objArticulo,'articulos')){
return true;
}else{
/** Se asignan los valores del mensaje */
this.mostrarControlMensaje("Se debe modificar al menos un campo para poder actualizar.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
}
}else{
this.mostrarControlMensaje("Debe proporcionar toda la información.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
} |
JavaScript | generaValidacionControles(){
let validacion = 0;
validacion = aplicaValidacion("txtDescripcion",this.state.objArticulo.descripcion,false);
validacion = aplicaValidacion("txtModelo",this.state.objArticulo.modelo,false);
validacion = aplicaValidacion("txtPrecio",this.state.objArticulo.precio,true);
validacion = aplicaValidacion("txtExistencia",this.state.objArticulo.existencia,true);
return validacion;
} | generaValidacionControles(){
let validacion = 0;
validacion = aplicaValidacion("txtDescripcion",this.state.objArticulo.descripcion,false);
validacion = aplicaValidacion("txtModelo",this.state.objArticulo.modelo,false);
validacion = aplicaValidacion("txtPrecio",this.state.objArticulo.precio,true);
validacion = aplicaValidacion("txtExistencia",this.state.objArticulo.existencia,true);
return validacion;
} |
JavaScript | async resetCheckbox() {
// replacing the checked rebase prompt with unchecked one
const updatedBody = this.pr_body.replace(
this.checkedRegex,
this.uncheckedString
);
const params = {
owner: this.repo_data.owner,
repo: this.repo_data.repo,
pull_number: this.pr_number,
body: updatedBody,
};
await this.octokit.pulls.update(params);
core.info("Unchecked the rebase flag in PR description");
} | async resetCheckbox() {
// replacing the checked rebase prompt with unchecked one
const updatedBody = this.pr_body.replace(
this.checkedRegex,
this.uncheckedString
);
const params = {
owner: this.repo_data.owner,
repo: this.repo_data.repo,
pull_number: this.pr_number,
body: updatedBody,
};
await this.octokit.pulls.update(params);
core.info("Unchecked the rebase flag in PR description");
} |
JavaScript | async doesPrNeedsUpdate() {
if (this.pr_data.merged === true) {
core.warning("Skipping pull request, already merged.");
return false;
}
if (this.pr_data.state !== "open") {
core.warning(
`Skipping pull request, no longer open (current state: ${this.pr_data.state}).`
);
return false;
}
if (!this.pr_data.head.repo) {
core.warning(`Skipping pull request, fork appears to have been deleted.`);
return false;
}
const { data: comparison } = await this.octokit.repos.compareCommits({
owner: this.pr_data.head.repo.owner.login,
repo: this.pr_data.head.repo.name,
base: this.pr_data.base.label,
head: this.pr_data.head.label,
});
if (comparison.behind_by === 0) {
core.info("Skipping pull request, up-to-date with base branch.");
return false;
}
core.info(
`Master is ahead of ${this.pr_data.head.ref} by ${comparison.behind_by} commits`
);
return true;
} | async doesPrNeedsUpdate() {
if (this.pr_data.merged === true) {
core.warning("Skipping pull request, already merged.");
return false;
}
if (this.pr_data.state !== "open") {
core.warning(
`Skipping pull request, no longer open (current state: ${this.pr_data.state}).`
);
return false;
}
if (!this.pr_data.head.repo) {
core.warning(`Skipping pull request, fork appears to have been deleted.`);
return false;
}
const { data: comparison } = await this.octokit.repos.compareCommits({
owner: this.pr_data.head.repo.owner.login,
repo: this.pr_data.head.repo.name,
base: this.pr_data.base.label,
head: this.pr_data.head.label,
});
if (comparison.behind_by === 0) {
core.info("Skipping pull request, up-to-date with base branch.");
return false;
}
core.info(
`Master is ahead of ${this.pr_data.head.ref} by ${comparison.behind_by} commits`
);
return true;
} |
JavaScript | async run() {
if (!this.pr_data) {
core.setFailed("No PR data available!");
}
if (!this.pr_number) {
core.setFailed("No PR number available!");
}
core.info(`PR Number is ${this.pr_number}`);
if (!this.pr_body) {
core.setFailed("No PR body available!");
}
const regexTest = new RegExp(this.checkedRegex);
const isRebaseAllowed = regexTest.test(this.pr_body);
if (!isRebaseAllowed) {
core.info("Rebase is not allowed since it is unchecked");
} else {
core.info(
"Flag is checked, rebase is allowed. Proceeding with the merge"
);
const prNeedsUpdate = await this.doesPrNeedsUpdate();
if (prNeedsUpdate) {
core.info("PR branch is behind master. Updating now....");
await this.rebase();
} else {
core.warning(
"PR branch is up-to-date with master. Not proceeding with merge"
);
}
await this.resetCheckbox();
}
} | async run() {
if (!this.pr_data) {
core.setFailed("No PR data available!");
}
if (!this.pr_number) {
core.setFailed("No PR number available!");
}
core.info(`PR Number is ${this.pr_number}`);
if (!this.pr_body) {
core.setFailed("No PR body available!");
}
const regexTest = new RegExp(this.checkedRegex);
const isRebaseAllowed = regexTest.test(this.pr_body);
if (!isRebaseAllowed) {
core.info("Rebase is not allowed since it is unchecked");
} else {
core.info(
"Flag is checked, rebase is allowed. Proceeding with the merge"
);
const prNeedsUpdate = await this.doesPrNeedsUpdate();
if (prNeedsUpdate) {
core.info("PR branch is behind master. Updating now....");
await this.rebase();
} else {
core.warning(
"PR branch is up-to-date with master. Not proceeding with merge"
);
}
await this.resetCheckbox();
}
} |
JavaScript | function s_date( seconds ){
let dt = new Date()
dt.setSeconds( seconds )
return dt.toISOString()
} | function s_date( seconds ){
let dt = new Date()
dt.setSeconds( seconds )
return dt.toISOString()
} |
JavaScript | async function authenticate(){
// return the cached token
if( auth_token ){
return auth_token
}
try {
// note, hardcoded to API version 1
var auth = await post(false)( `${restURL}/v1/auth`, {username:username, password:password})
if( auth && auth["authToken"] ){
authentication_attempts = 0 // a good authToken indicates success
auth_token = auth["authToken"]
}
return auth_token
} catch( e ){
// TODO: switch on each bad status code; probably factor out that part
auth_token = ""
if( e.response ) handleHTTPError( e.response, authenticate )
console.log( e.responseBody )
}
} | async function authenticate(){
// return the cached token
if( auth_token ){
return auth_token
}
try {
// note, hardcoded to API version 1
var auth = await post(false)( `${restURL}/v1/auth`, {username:username, password:password})
if( auth && auth["authToken"] ){
authentication_attempts = 0 // a good authToken indicates success
auth_token = auth["authToken"]
}
return auth_token
} catch( e ){
// TODO: switch on each bad status code; probably factor out that part
auth_token = ""
if( e.response ) handleHTTPError( e.response, authenticate )
console.log( e.responseBody )
}
} |
JavaScript | function post( getToken = true, method = "POST" ){
return async function post_vals( url, post_object ){
let headers = {"x-cassandra-request-id": uuidv4()}
if( getToken ) headers["x-cassandra-token"] = await authenticate()
try {
const response = await got(url,
{ method,
headers,
json: post_object,
responseType: 'json'})
if( response && response.body ){
body = response.body
if( body && body.errors && body.errors.length ) throw new Error( body.errors[0].message )
return body
} else if( response.statusCode >= 200 && response.statusCode <= 304 ) {
return { statusCode:response.statusCode }
} else {
return response
}
// GQL API may return an HTTP success but embed errors into the response
// throw an exception with the message
} catch(e) {
console.log( e );
if( e && e.response ) handleHTTPError( e.response, ()=> post.apply( arguments ))
}
}
} | function post( getToken = true, method = "POST" ){
return async function post_vals( url, post_object ){
let headers = {"x-cassandra-request-id": uuidv4()}
if( getToken ) headers["x-cassandra-token"] = await authenticate()
try {
const response = await got(url,
{ method,
headers,
json: post_object,
responseType: 'json'})
if( response && response.body ){
body = response.body
if( body && body.errors && body.errors.length ) throw new Error( body.errors[0].message )
return body
} else if( response.statusCode >= 200 && response.statusCode <= 304 ) {
return { statusCode:response.statusCode }
} else {
return response
}
// GQL API may return an HTTP success but embed errors into the response
// throw an exception with the message
} catch(e) {
console.log( e );
if( e && e.response ) handleHTTPError( e.response, ()=> post.apply( arguments ))
}
}
} |
JavaScript | function handleHTTPError( response, retry_function ){
function log(code, message){ console.log(`--------------------- Encountered HTTP Code ${code}: ${message} ---------------------`); }
switch ( response.statusCode ) {
case 304: // Not Modified
log(304, "Not Modified")
break;
case 400: // Bad Request
log( 400, "Bad Request")
break;
case 401: // Unauthorized
if( authentication_attempts++ < 2 ){ // retry
retry_function()
}
log( 401, `Unauthorized (${authentication_attempts} failed login attempts)`)
break;
case 403: // Forbidden
log( 403, "Forbidden")
break;
case 404: // Not Found
log( 404, "Not Found")
break;
case 500: // Internal Server Error
log( 500, "Internal Server Error")
break;
case 501: // Not Implemented
log( 501, "Not Implemented")
break;
case 502: // Bad Gateway
log( 502, "Bad Gateway")
break;
case 503: // Service Unavailable
log( 503, "Service Unavailable")
break;
case 504: // Gateway Timeout
log( 504, "Gateway Timeout")
break;
default:
log( response.statusCode, "CURRENTLY UNHANDLED CODE - SHOULD IMPLEMENT")
break;
}
} | function handleHTTPError( response, retry_function ){
function log(code, message){ console.log(`--------------------- Encountered HTTP Code ${code}: ${message} ---------------------`); }
switch ( response.statusCode ) {
case 304: // Not Modified
log(304, "Not Modified")
break;
case 400: // Bad Request
log( 400, "Bad Request")
break;
case 401: // Unauthorized
if( authentication_attempts++ < 2 ){ // retry
retry_function()
}
log( 401, `Unauthorized (${authentication_attempts} failed login attempts)`)
break;
case 403: // Forbidden
log( 403, "Forbidden")
break;
case 404: // Not Found
log( 404, "Not Found")
break;
case 500: // Internal Server Error
log( 500, "Internal Server Error")
break;
case 501: // Not Implemented
log( 501, "Not Implemented")
break;
case 502: // Bad Gateway
log( 502, "Bad Gateway")
break;
case 503: // Service Unavailable
log( 503, "Service Unavailable")
break;
case 504: // Gateway Timeout
log( 504, "Gateway Timeout")
break;
default:
log( response.statusCode, "CURRENTLY UNHANDLED CODE - SHOULD IMPLEMENT")
break;
}
} |
JavaScript | function check_required_field( property_name, property_obj ){
if( property_obj === undefined || !property_obj[property_name] || property_obj[property_name] === undefined || property_obj[property_name] === "" ){
throw new Error("userid is a required field for user changes")
}
return true;
} | function check_required_field( property_name, property_obj ){
if( property_obj === undefined || !property_obj[property_name] || property_obj[property_name] === undefined || property_obj[property_name] === "" ){
throw new Error("userid is a required field for user changes")
}
return true;
} |
JavaScript | function make_special_json( obj ){
let json = JSON.stringify( obj )
json.replace(/\\"/g,"\uFFFF");
json = json.replace(/"([^"]+)":/g, '$1:').replace(/\uFFFF/g, '\\\"');
return json
} | function make_special_json( obj ){
let json = JSON.stringify( obj )
json.replace(/\\"/g,"\uFFFF");
json = json.replace(/"([^"]+)":/g, '$1:').replace(/\uFFFF/g, '\\\"');
return json
} |
JavaScript | function useScrollConstraints(ref, measureConstraints) {
const [constraints, setConstraints] = useState({
top: 0,
bottom: 0
});
useEffect(() => {
if (!measureConstraints) return;
const element = ref.current;
const viewportHeight = window.innerHeight;
const contentTop = element.offsetTop;
const contentHeight = element.offsetHeight;
const scrollableViewport = viewportHeight - contentTop * 2;
const top = Math.min(scrollableViewport - contentHeight, 0);
setConstraints({ top, bottom: 0 });
}, [measureConstraints]);
return constraints;
} | function useScrollConstraints(ref, measureConstraints) {
const [constraints, setConstraints] = useState({
top: 0,
bottom: 0
});
useEffect(() => {
if (!measureConstraints) return;
const element = ref.current;
const viewportHeight = window.innerHeight;
const contentTop = element.offsetTop;
const contentHeight = element.offsetHeight;
const scrollableViewport = viewportHeight - contentTop * 2;
const top = Math.min(scrollableViewport - contentHeight, 0);
setConstraints({ top, bottom: 0 });
}, [measureConstraints]);
return constraints;
} |
JavaScript | function isFunction(functionToCheck) {
// https://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
} | function isFunction(functionToCheck) {
// https://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
} |
JavaScript | function showBannerIfConsentNotSet (consentProvidedCallback = () => {}) {
const consentCookieNotSet = !Cookies.get(GOVUK_PAY_ANALYTICS_CONSENT_COOKIE_NAME)
const banner = document.querySelector(`#${ANALYTICS_CONSENT_BANNER_ID}`)
if (consentCookieNotSet && !banner) {
const banner = createBannerHTMLElement(consentProvidedCallback)
document.body.prepend(banner)
}
} | function showBannerIfConsentNotSet (consentProvidedCallback = () => {}) {
const consentCookieNotSet = !Cookies.get(GOVUK_PAY_ANALYTICS_CONSENT_COOKIE_NAME)
const banner = document.querySelector(`#${ANALYTICS_CONSENT_BANNER_ID}`)
if (consentCookieNotSet && !banner) {
const banner = createBannerHTMLElement(consentProvidedCallback)
document.body.prepend(banner)
}
} |
JavaScript | function toggleHidness(toHide, toShow) {
if (toHide != "") {
$(toHide).hide();
}
if (toShow != "") {
if ($(toShow).hasClass("hide")) {
$(toShow).removeClass("hide");
} else {
$(toShow).show();
}
}
} | function toggleHidness(toHide, toShow) {
if (toHide != "") {
$(toHide).hide();
}
if (toShow != "") {
if ($(toShow).hasClass("hide")) {
$(toShow).removeClass("hide");
} else {
$(toShow).show();
}
}
} |
JavaScript | function showItems() {
connection.query("SELECT * FROM `products`", function (err, res) {
if (err) throw err;
// Loop through database and show items
for (var i = 0; i < res.length; i++) {
console.log("ID " + res[i].itemId + "|", "Product " + res[i].productName + "|", "Price $" + res[i].price);
console.log("\n--------------------------------------\n");
};
inquiries();
})} | function showItems() {
connection.query("SELECT * FROM `products`", function (err, res) {
if (err) throw err;
// Loop through database and show items
for (var i = 0; i < res.length; i++) {
console.log("ID " + res[i].itemId + "|", "Product " + res[i].productName + "|", "Price $" + res[i].price);
console.log("\n--------------------------------------\n");
};
inquiries();
})} |
JavaScript | function inquiries() {
inquirer.prompt([{
//The first should ask them the ID of the product they would like to buy.
type: 'input',
name: 'itemId',
message: 'Please enter the Item ID of an item you would like to buy.'
},
{
//The second message should ask how many units of the product they would like to buy.
type: 'input',
name: 'quantity',
message: 'How many would you like?',
validate: function (value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
}
]).then(function (input) {
var item = parseInt(input.itemId);
var inputQuantity = parseInt(input.quantity);
checkout(item, inputQuantity);
});
function checkout(ID, qty) {
// Once the customer has placed the order, check if store has enough of the product to meet the request
connection.query("SELECT * FROM `products` WHERE `itemId` = ?" + ID, function (err, results, fields) {
if (err) throw err;
if (qty <= results[0].stock) {
// calculate cost of the transaction.
var custTotal = results[0].price * qty;
console.log("The total cost of this purchase is $" +custTotal);
// Update mySQL database with reduced inventory
connection.query("UPDATE `products` SET `stock` = `stock` - " + qty + " WHERE `itemId` = " + ID);
console.log('\nTransaction Completed. Thank you!')
connection.end(); // end the script/connection
} else {
// Insufficient inventory
console.log("Sorry, that item is not in stock.");
inquiries();
}
});
}
} | function inquiries() {
inquirer.prompt([{
//The first should ask them the ID of the product they would like to buy.
type: 'input',
name: 'itemId',
message: 'Please enter the Item ID of an item you would like to buy.'
},
{
//The second message should ask how many units of the product they would like to buy.
type: 'input',
name: 'quantity',
message: 'How many would you like?',
validate: function (value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
}
]).then(function (input) {
var item = parseInt(input.itemId);
var inputQuantity = parseInt(input.quantity);
checkout(item, inputQuantity);
});
function checkout(ID, qty) {
// Once the customer has placed the order, check if store has enough of the product to meet the request
connection.query("SELECT * FROM `products` WHERE `itemId` = ?" + ID, function (err, results, fields) {
if (err) throw err;
if (qty <= results[0].stock) {
// calculate cost of the transaction.
var custTotal = results[0].price * qty;
console.log("The total cost of this purchase is $" +custTotal);
// Update mySQL database with reduced inventory
connection.query("UPDATE `products` SET `stock` = `stock` - " + qty + " WHERE `itemId` = " + ID);
console.log('\nTransaction Completed. Thank you!')
connection.end(); // end the script/connection
} else {
// Insufficient inventory
console.log("Sorry, that item is not in stock.");
inquiries();
}
});
}
} |
JavaScript | function createBadgeFallback(el, binding) {
// Create a new style tag
let style = document.createElement('style');
// Generate the content of Badge
const content = Number.isInteger(binding.value) ? binding.value : binding.value.value;
// Get the CSS attributes to use in style
const styleString = generateStyle(content, binding);
// Generate a timestamp to avoid style collisions with another badges
const timestamp = (new Date().getTime() / 1000).toString().replace('.', '');
// Set our attr name
const attrName = `badge-${timestamp}`;
// Now the element have the attrName
// ex: <input badge-36297362 />
el.setAttribute(attrName, '');
// Finally, create the final CSS class with a pseudo-element
style.innerHTML = `.vue-shadow-badge[${attrName}]::after {
${styleString}
}`;
// Append our newly created class to the head of document
document.getElementsByTagName('head')[0].appendChild(style);
// Append the class to the element class list
el.className = `${el.className} vue-shadow-badge`;
} | function createBadgeFallback(el, binding) {
// Create a new style tag
let style = document.createElement('style');
// Generate the content of Badge
const content = Number.isInteger(binding.value) ? binding.value : binding.value.value;
// Get the CSS attributes to use in style
const styleString = generateStyle(content, binding);
// Generate a timestamp to avoid style collisions with another badges
const timestamp = (new Date().getTime() / 1000).toString().replace('.', '');
// Set our attr name
const attrName = `badge-${timestamp}`;
// Now the element have the attrName
// ex: <input badge-36297362 />
el.setAttribute(attrName, '');
// Finally, create the final CSS class with a pseudo-element
style.innerHTML = `.vue-shadow-badge[${attrName}]::after {
${styleString}
}`;
// Append our newly created class to the head of document
document.getElementsByTagName('head')[0].appendChild(style);
// Append the class to the element class list
el.className = `${el.className} vue-shadow-badge`;
} |
JavaScript | function showTab(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
} | function showTab(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
} |
JavaScript | updateOne(table, objColVals, condition, cb) {
let queryString = `UPDATE ${table}`;
queryString += ' SET ';
queryString += objToSql(objColVals);
queryString += ' WHERE ';
queryString += condition;
console.log(queryString);
connection.query(queryString, (err, result) => {
if (err) {
throw err;
}
cb(result);
});
} | updateOne(table, objColVals, condition, cb) {
let queryString = `UPDATE ${table}`;
queryString += ' SET ';
queryString += objToSql(objColVals);
queryString += ' WHERE ';
queryString += condition;
console.log(queryString);
connection.query(queryString, (err, result) => {
if (err) {
throw err;
}
cb(result);
});
} |
JavaScript | function renderLicenseBadge(license) {
if (license != "") {
return `
[<img src="https://img.shields.io/badge/license-${license}-COLOR.svg?logo=LOGO">](<https://opensource.org/licenses/${license}>)`
} else {
return ""
}
} | function renderLicenseBadge(license) {
if (license != "") {
return `
[<img src="https://img.shields.io/badge/license-${license}-COLOR.svg?logo=LOGO">](<https://opensource.org/licenses/${license}>)`
} else {
return ""
}
} |
JavaScript | function renderLicenseLink(license) {
if (license != "") {
return `
* [License](#license)`
} else {
return ""
}
} | function renderLicenseLink(license) {
if (license != "") {
return `
* [License](#license)`
} else {
return ""
}
} |
JavaScript | function renderLicenseSection(license) {
if (license != "") {
return `
## License
This application is covered under the ${license} license.`
} else {
return ""
}
} | function renderLicenseSection(license) {
if (license != "") {
return `
## License
This application is covered under the ${license} license.`
} else {
return ""
}
} |
JavaScript | function generateMarkdown(data) {
return `# ${data.title}
${renderLicenseBadge(data.license)}
## Description
${data.description}
## Table of Contents
If your README is long, add a table of contents to make it easy for users to find what they need.
- [Installation](#installation)
- [Usage](#usage)
${renderLicenseLink(data.license)}
- [Credits](#contribution)
## Installation
${data.installation}
## Usage
${data.usage}
## License
${data.license}
## Contribution
${data.contribution}
## Tests
${data.test}
## Questions
<a href="https://github.com/${data.github}">github profile</a>
<a href="mailto:${data.email}">Contact me</a>
`;
} | function generateMarkdown(data) {
return `# ${data.title}
${renderLicenseBadge(data.license)}
## Description
${data.description}
## Table of Contents
If your README is long, add a table of contents to make it easy for users to find what they need.
- [Installation](#installation)
- [Usage](#usage)
${renderLicenseLink(data.license)}
- [Credits](#contribution)
## Installation
${data.installation}
## Usage
${data.usage}
## License
${data.license}
## Contribution
${data.contribution}
## Tests
${data.test}
## Questions
<a href="https://github.com/${data.github}">github profile</a>
<a href="mailto:${data.email}">Contact me</a>
`;
} |
JavaScript | function init() {
inquirer.prompt(questions).then(function(response){
fs.writeFileSync("./README.md", generateMarkdown(response))
})
} | function init() {
inquirer.prompt(questions).then(function(response){
fs.writeFileSync("./README.md", generateMarkdown(response))
})
} |
JavaScript | move() {
// if the sprite has no next cell and no trailing cell on the board and the sprite has already moved
if (!this.type.$nextCell && !this.type.$trailingCell && !this.type.firstMove) {
// then it's time to delete the sprite, so we set its offBoard property so that a later method can remove it
this.offBoard = true;
}
// swapCells method does the actual moving of the sprite's divs
this.swapCells();
// updateObject method sets the new column numbers of the sprite, then...
this.updateObject();
// ...we update the cellsTakenUp array to hold the new divs
this.cellsTakenUp = this.getCellElems();
// also set the firstMove property to false, because the sprite just went through a move
this.type.firstMove = false;
} | move() {
// if the sprite has no next cell and no trailing cell on the board and the sprite has already moved
if (!this.type.$nextCell && !this.type.$trailingCell && !this.type.firstMove) {
// then it's time to delete the sprite, so we set its offBoard property so that a later method can remove it
this.offBoard = true;
}
// swapCells method does the actual moving of the sprite's divs
this.swapCells();
// updateObject method sets the new column numbers of the sprite, then...
this.updateObject();
// ...we update the cellsTakenUp array to hold the new divs
this.cellsTakenUp = this.getCellElems();
// also set the firstMove property to false, because the sprite just went through a move
this.type.firstMove = false;
} |
JavaScript | updateObject() {
// check for the direction that the sprite is moving in first
if (this.type.direction == 'neg') {
this.type.rightColNum--;
}
if (this.type.direction == 'pos') {
this.type.rightColNum++;
}
this.type.leftColNum = this.type.rightColNum - this.type.spriteLength;
} | updateObject() {
// check for the direction that the sprite is moving in first
if (this.type.direction == 'neg') {
this.type.rightColNum--;
}
if (this.type.direction == 'pos') {
this.type.rightColNum++;
}
this.type.leftColNum = this.type.rightColNum - this.type.spriteLength;
} |
JavaScript | swapCells() {
// first we loop through the sprite's divs and check if any of them have a frogger id; i.e. frogger is 'on' them
var $cellWithFrogger = null;
var $nextCellForFrogger = null;
for (var i = 0; i < this.cellsTakenUp.length; i++) {
// checks existence of the current element, since it can be null
var id = this.cellsTakenUp[i] ? this.cellsTakenUp[i].getAttribute('id'):null;
// checks if the element has an id and if it contains 'frogger'
if (id && id.includes('frogger')) {
// if it does, store the element in a variable to be utilized later
$cellWithFrogger = this.cellsTakenUp[i];
// determine the next place the frogger should be moved based on the sprite's motion
if (this.type.direction == 'neg') {
$nextCellForFrogger = this.cellsTakenUp[i - 1];
}
if (this.type.direction == 'pos') {
$nextCellForFrogger = this.cellsTakenUp[i + 1];
}
}
}
// nice variables to shorten the code
var $next = this.type.$nextCell;
var $remove = this.type.$trailingCell;
var $leading = this.type.$leadingCell;
// does the sprite have a target destination? does it have at least one div on the board?
if (!$next && !$leading && !$remove) {
// if it doesn't, then it does not exist on the playing field
this.offBoard = true;
// does the sprite have at least a trailing div on the board, even if it doesn't have a destination?
} else if ((!$next && !$leading && $remove) || (!$next && $leading && $remove)) {
// if it does, then we want to remove the trailing div, since the sprite is almost off the board
this.offBoard = false;
// remove the type's class from the current div
var nextClass = $remove.getAttribute('class');
var newClass = nextClass.replace((' ' + this.type.typeClass), '');
$remove.setAttribute('class', newClass);
// flip the isallowed attribute to the opposite of what it was
$remove.dataset.isallowed = this.type.canBePlacedOn;
// does the sprite have a destination even if it's missing a first and/or last div?
} else if (($next && !$leading && !$remove) || ($next && $leading && !$remove)) {
// if it does, then we want to add a new trailing div, since the sprite is just getting on the board
this.offBoard = false;
// add the type's class to the new div
var nextClass = $next.getAttribute('class');
$next.setAttribute('class', (nextClass + ' ' + this.type.typeClass));
// set the isallowed attribute to what the type says it should be
$next.dataset.isallowed = this.type.canHoldFrogger;
// do all the sprites elements exist? aka is the sprite entirely on the board and not approaching the board's end?
} else if ($next && $leading && $remove) {
this.offBoard = false;
// do a full move
// get rid of remove
var nextClass = $remove.getAttribute('class');
var newClass = nextClass.replace((' ' + this.type.typeClass), '');
$remove.setAttribute('class', newClass);
$remove.dataset.isallowed = this.type.canBePlacedOn;
// move leading to next
var nextClass = $next.getAttribute('class');
$next.setAttribute('class', (nextClass + ' ' + this.type.typeClass));
$next.dataset.isallowed = this.type.canHoldFrogger;
}
// is the frogger on the current sprite and does it have somewhere to go?
if ($cellWithFrogger && $nextCellForFrogger) {
// if so, move it to the next one
$cellWithFrogger.setAttribute('id', '');
$nextCellForFrogger.setAttribute('id', 'frogger');
}
// the last if statement allows the frogger to be moved with the sprite, so that it will be moved with, for example,
// the log that it's on. it's important to note two things here:
// 1) if the frog reaches the end of the board while on a log, it will slip off the log into the river when the log
// disappears, 'killing' the frog
// 2) if, by some miracle, the user manages to get the frog on a truck, it will still move with the truck because of
// the way we determined that the frog is there
} | swapCells() {
// first we loop through the sprite's divs and check if any of them have a frogger id; i.e. frogger is 'on' them
var $cellWithFrogger = null;
var $nextCellForFrogger = null;
for (var i = 0; i < this.cellsTakenUp.length; i++) {
// checks existence of the current element, since it can be null
var id = this.cellsTakenUp[i] ? this.cellsTakenUp[i].getAttribute('id'):null;
// checks if the element has an id and if it contains 'frogger'
if (id && id.includes('frogger')) {
// if it does, store the element in a variable to be utilized later
$cellWithFrogger = this.cellsTakenUp[i];
// determine the next place the frogger should be moved based on the sprite's motion
if (this.type.direction == 'neg') {
$nextCellForFrogger = this.cellsTakenUp[i - 1];
}
if (this.type.direction == 'pos') {
$nextCellForFrogger = this.cellsTakenUp[i + 1];
}
}
}
// nice variables to shorten the code
var $next = this.type.$nextCell;
var $remove = this.type.$trailingCell;
var $leading = this.type.$leadingCell;
// does the sprite have a target destination? does it have at least one div on the board?
if (!$next && !$leading && !$remove) {
// if it doesn't, then it does not exist on the playing field
this.offBoard = true;
// does the sprite have at least a trailing div on the board, even if it doesn't have a destination?
} else if ((!$next && !$leading && $remove) || (!$next && $leading && $remove)) {
// if it does, then we want to remove the trailing div, since the sprite is almost off the board
this.offBoard = false;
// remove the type's class from the current div
var nextClass = $remove.getAttribute('class');
var newClass = nextClass.replace((' ' + this.type.typeClass), '');
$remove.setAttribute('class', newClass);
// flip the isallowed attribute to the opposite of what it was
$remove.dataset.isallowed = this.type.canBePlacedOn;
// does the sprite have a destination even if it's missing a first and/or last div?
} else if (($next && !$leading && !$remove) || ($next && $leading && !$remove)) {
// if it does, then we want to add a new trailing div, since the sprite is just getting on the board
this.offBoard = false;
// add the type's class to the new div
var nextClass = $next.getAttribute('class');
$next.setAttribute('class', (nextClass + ' ' + this.type.typeClass));
// set the isallowed attribute to what the type says it should be
$next.dataset.isallowed = this.type.canHoldFrogger;
// do all the sprites elements exist? aka is the sprite entirely on the board and not approaching the board's end?
} else if ($next && $leading && $remove) {
this.offBoard = false;
// do a full move
// get rid of remove
var nextClass = $remove.getAttribute('class');
var newClass = nextClass.replace((' ' + this.type.typeClass), '');
$remove.setAttribute('class', newClass);
$remove.dataset.isallowed = this.type.canBePlacedOn;
// move leading to next
var nextClass = $next.getAttribute('class');
$next.setAttribute('class', (nextClass + ' ' + this.type.typeClass));
$next.dataset.isallowed = this.type.canHoldFrogger;
}
// is the frogger on the current sprite and does it have somewhere to go?
if ($cellWithFrogger && $nextCellForFrogger) {
// if so, move it to the next one
$cellWithFrogger.setAttribute('id', '');
$nextCellForFrogger.setAttribute('id', 'frogger');
}
// the last if statement allows the frogger to be moved with the sprite, so that it will be moved with, for example,
// the log that it's on. it's important to note two things here:
// 1) if the frog reaches the end of the board while on a log, it will slip off the log into the river when the log
// disappears, 'killing' the frog
// 2) if, by some miracle, the user manages to get the frog on a truck, it will still move with the truck because of
// the way we determined that the frog is there
} |
JavaScript | function confirmar(id_cont) {
let resposta = confirm("Confirma a exclusão deste container? " + id_cont)
if (resposta === true) {
window.location.href = "delete_cont?id_cont=" + id_cont
}
} | function confirmar(id_cont) {
let resposta = confirm("Confirma a exclusão deste container? " + id_cont)
if (resposta === true) {
window.location.href = "delete_cont?id_cont=" + id_cont
}
} |
JavaScript | function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
prototype[method] = function (arg) {
return this._invoke(method, arg);
};
});
} | function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
prototype[method] = function (arg) {
return this._invoke(method, arg);
};
});
} |
JavaScript | function invoke(method, arg) {
var result = generator[method](arg);
var value = result.value;
return value instanceof AwaitArgument ? Promise.resolve(value.arg).then(invokeNext, invokeThrow) : Promise.resolve(value).then(function (unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
return result;
});
} | function invoke(method, arg) {
var result = generator[method](arg);
var value = result.value;
return value instanceof AwaitArgument ? Promise.resolve(value.arg).then(invokeNext, invokeThrow) : Promise.resolve(value).then(function (unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
return result;
});
} |
JavaScript | function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
} | function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
} |
JavaScript | function initialize(window) {
$document = window.document;
$location = window.location;
$cancelAnimationFrame = window.cancelAnimationFrame || window.clearTimeout;
$requestAnimationFrame = window.requestAnimationFrame || window.setTimeout;
} | function initialize(window) {
$document = window.document;
$location = window.location;
$cancelAnimationFrame = window.cancelAnimationFrame || window.clearTimeout;
$requestAnimationFrame = window.requestAnimationFrame || window.setTimeout;
} |
JavaScript | function injectTextNode(parentElement, first, index, data) {
try {
insertNode(parentElement, first, index);
first.nodeValue = data;
} catch (e) {} //IE erroneously throws error when appending an empty text node after a null
} | function injectTextNode(parentElement, first, index, data) {
try {
insertNode(parentElement, first, index);
first.nodeValue = data;
} catch (e) {} //IE erroneously throws error when appending an empty text node after a null
} |
JavaScript | function Deferred(successCallback, failureCallback) {
var RESOLVING = 1,
REJECTING = 2,
RESOLVED = 3,
REJECTED = 4;
var self = this,
state = 0,
promiseValue = 0,
next = [];
self.promise = {};
self.resolve = function (value) {
if (!state) {
promiseValue = value;
state = RESOLVING;
fire();
}
return this;
};
self.reject = function (value) {
if (!state) {
promiseValue = value;
state = REJECTING;
fire();
}
return this;
};
self.promise.then = function (successCallback, failureCallback) {
var deferred = new Deferred(successCallback, failureCallback);
if (state === RESOLVED) {
deferred.resolve(promiseValue);
} else if (state === REJECTED) {
deferred.reject(promiseValue);
} else {
next.push(deferred);
}
return deferred.promise;
};
function finish(type) {
state = type || REJECTED;
next.map(function (deferred) {
state === RESOLVED ? deferred.resolve(promiseValue) : deferred.reject(promiseValue);
});
}
function thennable(then, successCallback, failureCallback, notThennableCallback) {
if ((promiseValue != null && isObject(promiseValue) || isFunction(promiseValue)) && isFunction(then)) {
try {
// count protects against abuse calls from spec checker
var count = 0;
then.call(promiseValue, function (value) {
if (count++) return;
promiseValue = value;
successCallback();
}, function (value) {
if (count++) return;
promiseValue = value;
failureCallback();
});
} catch (e) {
m.deferred.onerror(e);
promiseValue = e;
failureCallback();
}
} else {
notThennableCallback();
}
}
function fire() {
// check if it's a thenable
var then;
try {
then = promiseValue && promiseValue.then;
} catch (e) {
m.deferred.onerror(e);
promiseValue = e;
state = REJECTING;
return fire();
}
if (state === REJECTING) {
m.deferred.onerror(promiseValue);
}
thennable(then, function () {
state = RESOLVING;
fire();
}, function () {
state = REJECTING;
fire();
}, function () {
try {
if (state === RESOLVING && isFunction(successCallback)) {
promiseValue = successCallback(promiseValue);
} else if (state === REJECTING && isFunction(failureCallback)) {
promiseValue = failureCallback(promiseValue);
state = RESOLVING;
}
} catch (e) {
m.deferred.onerror(e);
promiseValue = e;
return finish();
}
if (promiseValue === self) {
promiseValue = TypeError();
finish();
} else {
thennable(then, function () {
finish(RESOLVED);
}, finish, function () {
finish(state === RESOLVING && RESOLVED);
});
}
});
}
} | function Deferred(successCallback, failureCallback) {
var RESOLVING = 1,
REJECTING = 2,
RESOLVED = 3,
REJECTED = 4;
var self = this,
state = 0,
promiseValue = 0,
next = [];
self.promise = {};
self.resolve = function (value) {
if (!state) {
promiseValue = value;
state = RESOLVING;
fire();
}
return this;
};
self.reject = function (value) {
if (!state) {
promiseValue = value;
state = REJECTING;
fire();
}
return this;
};
self.promise.then = function (successCallback, failureCallback) {
var deferred = new Deferred(successCallback, failureCallback);
if (state === RESOLVED) {
deferred.resolve(promiseValue);
} else if (state === REJECTED) {
deferred.reject(promiseValue);
} else {
next.push(deferred);
}
return deferred.promise;
};
function finish(type) {
state = type || REJECTED;
next.map(function (deferred) {
state === RESOLVED ? deferred.resolve(promiseValue) : deferred.reject(promiseValue);
});
}
function thennable(then, successCallback, failureCallback, notThennableCallback) {
if ((promiseValue != null && isObject(promiseValue) || isFunction(promiseValue)) && isFunction(then)) {
try {
// count protects against abuse calls from spec checker
var count = 0;
then.call(promiseValue, function (value) {
if (count++) return;
promiseValue = value;
successCallback();
}, function (value) {
if (count++) return;
promiseValue = value;
failureCallback();
});
} catch (e) {
m.deferred.onerror(e);
promiseValue = e;
failureCallback();
}
} else {
notThennableCallback();
}
}
function fire() {
// check if it's a thenable
var then;
try {
then = promiseValue && promiseValue.then;
} catch (e) {
m.deferred.onerror(e);
promiseValue = e;
state = REJECTING;
return fire();
}
if (state === REJECTING) {
m.deferred.onerror(promiseValue);
}
thennable(then, function () {
state = RESOLVING;
fire();
}, function () {
state = REJECTING;
fire();
}, function () {
try {
if (state === RESOLVING && isFunction(successCallback)) {
promiseValue = successCallback(promiseValue);
} else if (state === REJECTING && isFunction(failureCallback)) {
promiseValue = failureCallback(promiseValue);
state = RESOLVING;
}
} catch (e) {
m.deferred.onerror(e);
promiseValue = e;
return finish();
}
if (promiseValue === self) {
promiseValue = TypeError();
finish();
} else {
thennable(then, function () {
finish(RESOLVED);
}, finish, function () {
finish(state === RESOLVING && RESOLVED);
});
}
});
}
} |
JavaScript | addToFavs(name, iconUrl, url, channelId, guildId){
this.setState({
favs: [...this.state.favs, {name, iconUrl, url, channelId, guildId}]
}, this.props.plugin.saveSettings);
} | addToFavs(name, iconUrl, url, channelId, guildId){
this.setState({
favs: [...this.state.favs, {name, iconUrl, url, channelId, guildId}]
}, this.props.plugin.saveSettings);
} |
JavaScript | function pipeMessage(client, inputName, msg) {
client.complete(msg, printResultFor('Receiving message'));
var json = JSON.parse(msg.getBytes().toString('utf8'));
// Convert msg to IOTDT bridge message structure
var req = {
device: {
deviceId: inputName
},
measurements: {
},
timestamp: json.timeCreated
}
req.measurements[inputName + '_machine_temperature'] = json.machine.temperature;
req.measurements[inputName + '_machine_pressure'] = json.machine.pressure;
req.measurements[inputName + '_ambient_temperature'] = json.ambient.temperature;
req.measurements[inputName + '_ambient_humidity'] = json.ambient.humidity;
var message = JSON.stringify(req);
console.log('[JSON] ' + message);
if (message) {
var outputMsg = new Message(message);
client.sendOutputEvent('output', outputMsg, printResultFor('Sending transformed message'));
}
} | function pipeMessage(client, inputName, msg) {
client.complete(msg, printResultFor('Receiving message'));
var json = JSON.parse(msg.getBytes().toString('utf8'));
// Convert msg to IOTDT bridge message structure
var req = {
device: {
deviceId: inputName
},
measurements: {
},
timestamp: json.timeCreated
}
req.measurements[inputName + '_machine_temperature'] = json.machine.temperature;
req.measurements[inputName + '_machine_pressure'] = json.machine.pressure;
req.measurements[inputName + '_ambient_temperature'] = json.ambient.temperature;
req.measurements[inputName + '_ambient_humidity'] = json.ambient.humidity;
var message = JSON.stringify(req);
console.log('[JSON] ' + message);
if (message) {
var outputMsg = new Message(message);
client.sendOutputEvent('output', outputMsg, printResultFor('Sending transformed message'));
}
} |
JavaScript | function publishData(){//post to HTML:
$('tbody').append('<tr><td class="name" data-key =' + FBkeyValue + '>'
+ FBname
+ '</td><td>'
+ FBadd
+ '</td><td>'
+ FBpost
+ '</td><td>'
+ FBemail
+ '</td><td>'
+ FBdate
+ '</td><td>'
+ FBtime
+ '</td><td>'
+ FBtel
+ '</td><td>'
// + '<span class="glyphicon glyphicon-remove" aria-hidden="true" data-key =' + FBkeyValue + '></span>'
+ '</td><td>'
+ '<button type="submit" class="btn btn-success btn-xs update" data-key =' + FBkeyValue + '>Update'
+ '</td></tr>')
} | function publishData(){//post to HTML:
$('tbody').append('<tr><td class="name" data-key =' + FBkeyValue + '>'
+ FBname
+ '</td><td>'
+ FBadd
+ '</td><td>'
+ FBpost
+ '</td><td>'
+ FBemail
+ '</td><td>'
+ FBdate
+ '</td><td>'
+ FBtime
+ '</td><td>'
+ FBtel
+ '</td><td>'
// + '<span class="glyphicon glyphicon-remove" aria-hidden="true" data-key =' + FBkeyValue + '></span>'
+ '</td><td>'
+ '<button type="submit" class="btn btn-success btn-xs update" data-key =' + FBkeyValue + '>Update'
+ '</td></tr>')
} |
JavaScript | function publishData(){//post to HTML:
$('tbody').append('<tr><td class="name" data-key =' + FBkeyValue + '>'
+ FBname
+ '</td><td>'
+ FBadd
+ '</td><td>'
+ FBpost
+ '</td><td>'
+ FBemail
+ '</td><td>'
+ FBdate
+ '</td><td>'
+ FBtime
+ '</td><td>'
+ FBtel
+ '</td><td>'
//+ '<span class="glyphicon glyphicon-remove" aria-hidden="true" data-key =' + FBkeyValue + '></span>'
+ '</td><td>'
+ '<button type="submit" class="btn btn-success btn-xs update" data-key =' + FBkeyValue + '>Update'
+ '</td></tr>')
} | function publishData(){//post to HTML:
$('tbody').append('<tr><td class="name" data-key =' + FBkeyValue + '>'
+ FBname
+ '</td><td>'
+ FBadd
+ '</td><td>'
+ FBpost
+ '</td><td>'
+ FBemail
+ '</td><td>'
+ FBdate
+ '</td><td>'
+ FBtime
+ '</td><td>'
+ FBtel
+ '</td><td>'
//+ '<span class="glyphicon glyphicon-remove" aria-hidden="true" data-key =' + FBkeyValue + '></span>'
+ '</td><td>'
+ '<button type="submit" class="btn btn-success btn-xs update" data-key =' + FBkeyValue + '>Update'
+ '</td></tr>')
} |
JavaScript | function sendEmailVerification() {
// [START sendemailverification]
firebase.auth().currentUser.sendEmailVerification().then(function() {
// Email Verification sent!
// [START_EXCLUDE]
tellAppInventor('Email Verification Sent!');
// [END_EXCLUDE]
});
// [END sendemailverification]
} | function sendEmailVerification() {
// [START sendemailverification]
firebase.auth().currentUser.sendEmailVerification().then(function() {
// Email Verification sent!
// [START_EXCLUDE]
tellAppInventor('Email Verification Sent!');
// [END_EXCLUDE]
});
// [END sendemailverification]
} |
JavaScript | function manipulationTarget( elem, content ) {
if ( nodeName( elem, "table" ) &&
nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return jQuery( ">tbody", elem )[ 0 ] || elem;
}
return elem;
} | function manipulationTarget( elem, content ) {
if ( nodeName( elem, "table" ) &&
nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return jQuery( ">tbody", elem )[ 0 ] || elem;
}
return elem;
} |
JavaScript | function waitUntilReady(componentBeingObserved, component, callback) {
if (!componentBeingObserved.__x) {
window.requestAnimationFrame(function () {
return component.__x.updateElements(component);
});
return getNoopProxy();
}
return callback();
} | function waitUntilReady(componentBeingObserved, component, callback) {
if (!componentBeingObserved.__x) {
window.requestAnimationFrame(function () {
return component.__x.updateElements(component);
});
return getNoopProxy();
}
return callback();
} |
JavaScript | function hardWait(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
} | function hardWait(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
} |
JavaScript | static isP1 (port) {
if (
(port.vendorId === '0403' && port.productId === '6001') ||
(port.vendorId === '067b' && port.productId === '2303') // Issue #7
) {
return true
}
return false
} | static isP1 (port) {
if (
(port.vendorId === '0403' && port.productId === '6001') ||
(port.vendorId === '067b' && port.productId === '2303') // Issue #7
) {
return true
}
return false
} |
JavaScript | async _findPort () {
if (this._options.serialPort != null) {
return this._options.serialPort
}
const ports = await P1Client.findPorts()
/** Emitted when serial port devices are discovered.
* @event P1Client#ports
* @param {Object[]} ports - The discovered serial ports.
*/
this.emit('ports', ports)
for (const port of ports) {
if (P1Client.isP1(port)) {
return port.path
}
}
throw new Error('USB P1 converter cable not found')
} | async _findPort () {
if (this._options.serialPort != null) {
return this._options.serialPort
}
const ports = await P1Client.findPorts()
/** Emitted when serial port devices are discovered.
* @event P1Client#ports
* @param {Object[]} ports - The discovered serial ports.
*/
this.emit('ports', ports)
for (const port of ports) {
if (P1Client.isP1(port)) {
return port.path
}
}
throw new Error('USB P1 converter cable not found')
} |
JavaScript | async open () {
const serialPort = this._options.serialPort != null
? this._options.serialPort
: await this._findPort()
return new Promise((resolve, reject) => {
const { hostname, port } = this._toHost(serialPort)
if (hostname != null && port != null) {
this.p1 = net.connect(port, hostname, () => {
this.emit('open', serialPort)
this._setTimeout()
resolve(serialPort)
})
this.p1.close = this.p1.destroy
} else {
const options = this._options.dsmr22
? { baudRate: 9600, dataBits: 7, parity: 'even' } // 9600 7E1
: { baudRate: 115200 } // 115200 8N1
this.p1 = new SerialPort(serialPort, options, (error) => {
if (error) {
// this.emit('error', error)
return reject(error)
}
/** Emitted when the connection to the serial port is opened.
* @event P1Client#open
* @param {string} serialPort
*/
this.emit('open', serialPort)
this._setTimeout()
resolve(serialPort)
})
}
this.p1
.on('data', () => { this._setTimeout() })
.on('close', () => {
this.p1.unpipe(this.parser)
this.p1.removeAllListeners()
delete this.p1
/** Emitted when the connection to the serial port is closed.
* @event P1Client#close
* @param {string} serialPort
*/
this.emit('close', serialPort)
})
.on('error', (error) => {
/** Emitted when an error occurs.
* @event P1Client#error
* @param {Error} error
*/
this.emit('error', error)
})
.pipe(this.parser)
})
} | async open () {
const serialPort = this._options.serialPort != null
? this._options.serialPort
: await this._findPort()
return new Promise((resolve, reject) => {
const { hostname, port } = this._toHost(serialPort)
if (hostname != null && port != null) {
this.p1 = net.connect(port, hostname, () => {
this.emit('open', serialPort)
this._setTimeout()
resolve(serialPort)
})
this.p1.close = this.p1.destroy
} else {
const options = this._options.dsmr22
? { baudRate: 9600, dataBits: 7, parity: 'even' } // 9600 7E1
: { baudRate: 115200 } // 115200 8N1
this.p1 = new SerialPort(serialPort, options, (error) => {
if (error) {
// this.emit('error', error)
return reject(error)
}
/** Emitted when the connection to the serial port is opened.
* @event P1Client#open
* @param {string} serialPort
*/
this.emit('open', serialPort)
this._setTimeout()
resolve(serialPort)
})
}
this.p1
.on('data', () => { this._setTimeout() })
.on('close', () => {
this.p1.unpipe(this.parser)
this.p1.removeAllListeners()
delete this.p1
/** Emitted when the connection to the serial port is closed.
* @event P1Client#close
* @param {string} serialPort
*/
this.emit('close', serialPort)
})
.on('error', (error) => {
/** Emitted when an error occurs.
* @event P1Client#error
* @param {Error} error
*/
this.emit('error', error)
})
.pipe(this.parser)
})
} |
JavaScript | async close () {
if (this.p1 != null) {
this.p1.close()
}
} | async close () {
if (this.p1 != null) {
this.p1.close()
}
} |
JavaScript | _setTimeout () {
if (this.timeout != null) {
clearTimeout(this.timeout)
}
this.timeout = setTimeout(() => {
if (this.p1 != null) {
this.emit(
'error', new Error(`no data received in ${this._options.timeout}s`)
)
this.p1.close()
}
}, this._options.timeout * 1000)
} | _setTimeout () {
if (this.timeout != null) {
clearTimeout(this.timeout)
}
this.timeout = setTimeout(() => {
if (this.p1 != null) {
this.emit(
'error', new Error(`no data received in ${this._options.timeout}s`)
)
this.p1.close()
}
}, this._options.timeout * 1000)
} |
JavaScript | parseTelegram (telegram) {
try {
// Validate telegram.
if (telegram == null || typeof telegram !== 'string') {
this.emit('warning', 'ignoring unsupported telegram')
return
}
const header = telegram.match(/(.+)\r\n\r\n/)
const footer = telegram.match(/(!)([0-9A-F]{4})?\r\n/)
if (header == null || footer == null) {
this.emit('warning', 'ignoring invalid telegram')
return
}
if (footer[2] != null) {
const checksum = parseInt(footer[2], 16)
const crc = this.crc16('/' + telegram.slice(0, -6))
if (checksum !== crc) {
this.emit('warning', 'ignoring telegram with crc error')
return
}
}
/** Emitted when a telegram has been validated.
* @event P1Client#telegram
* @param {string} telegram - The validated telegram.
*/
this.emit('telegram', telegram)
// Convert telegram into a raw object.
const obj = { type: header[1], checksum: footer[2] }
const lines = telegram.match(/\d+-\d+:\d+\.\d+\.\d+(\(.*\)\r?\n?)+\r\n/g)
for (const line of lines) {
const keys = line.match(/\d+-\d+:\d+\.\d+\.\d+/)
const values = line.match(/\([^)]*\)/g)
const a = p1Keys[keys[0]]
if (a == null) {
/** Emitted when the telegram contains an unknown key.
* @event P1Client#warning
* @param {string} message - The warning message.
*/
this.emit('warning', `${keys[0]}: ignoring unknown key`)
continue
}
for (const id in a) {
if (a[id].key != null) {
try {
obj[a[id].key] = a[id].f(a[id].allValues ? values : values[id])
} catch (error) {
const value = a[id].allValues ? values.join('') : values[id]
this.emit(
'warning', `${keys[0]}: ignoring unknown value ${value}`
)
}
}
}
}
/** Emitted when a telegram has been parsed.
* @event P1Client#rawData
* @param {Object} rawData - The telegram converted 1:1 to a flat obect.
*/
this.emit('rawData', obj)
// Convert the flat object into a cooked object.
const be = obj.version_be != null
const low = be ? 2 : 1
const normal = be ? 1 : 2
const tariff = obj.tariff === low ? 'low' : 'normal'
const result = {
type: obj.type,
version: be ? obj.version_be : obj.version == null ? '2.2' : obj.version,
msg_text: obj.msg_text,
msg_num: obj.msg_num,
electricity: {
id: obj.id.trim(),
lastupdated: obj.lastupdated,
tariff: tariff,
consumption: {
low: obj['consumption_t' + low],
normal: obj['consumption_t' + normal]
},
power: obj.power,
failures: {
short: obj.failures_short,
long: obj.failures_long,
log: obj.log
},
l1: {
voltage: obj.l1_voltage,
sags: obj.l1_sags,
swells: obj.l1_swells,
current: obj.l1_current,
power: obj.l1_power
}
},
electricityBack: {
id: obj.id.trim() + 'B',
lastupdated: obj.lastupdated,
tariff: tariff,
consumption: {
low: obj['consumption_back_t' + low],
normal: obj['consumption_back_t' + normal]
},
power: obj.power_back,
l1: { power: obj.l1_power_back }
}
}
if (obj.l2_voltage != null) {
result.electricity.l2 = {
voltage: obj.l2_voltage,
sags: obj.l2_sags,
swells: obj.l2_swells,
current: obj.l2_current,
power: obj.l2_power
}
result.electricityBack.l2 = { power: obj.l2_power_back }
result.electricity.l3 = {
voltage: obj.l3_voltage,
sags: obj.l3_sags,
swells: obj.l3_swells,
current: obj.l3_current,
power: obj.l3_power
}
result.electricityBack.l3 = { power: obj.l3_power_back }
}
if (obj.d1_type != null) {
result[obj.d1_type] = {
id: obj.d1_id.trim(),
lastupdated: obj.d1_lastupdated,
consumption: obj.d1_consumption
}
}
if (obj.d2_type != null) {
result[obj.d2_type] = {
id: obj.d2_id.trim(),
lastupdated: obj.d2_lastupdated,
consumption: obj.d2_consumption
}
}
if (obj.d3_type != null) {
result[obj.d3_type] = {
id: obj.d3_id.trim(),
lastupdated: obj.d3_lastupdated,
consumption: obj.d3_consumption
}
}
if (obj.d4_type != null) {
result[obj.d4_type] = {
id: obj.d4_id.trim(),
lastupdated: obj.d4_lastupdated,
consumption: obj.d4_consumption
}
}
/** Emitted when a telegram has been parsed.
* @event P1Client#data
* @param {Object} data - The telegram converted an object with
* nested objects.
*/
this.emit('data', result)
} catch (error) {
this.emit('error', error)
}
} | parseTelegram (telegram) {
try {
// Validate telegram.
if (telegram == null || typeof telegram !== 'string') {
this.emit('warning', 'ignoring unsupported telegram')
return
}
const header = telegram.match(/(.+)\r\n\r\n/)
const footer = telegram.match(/(!)([0-9A-F]{4})?\r\n/)
if (header == null || footer == null) {
this.emit('warning', 'ignoring invalid telegram')
return
}
if (footer[2] != null) {
const checksum = parseInt(footer[2], 16)
const crc = this.crc16('/' + telegram.slice(0, -6))
if (checksum !== crc) {
this.emit('warning', 'ignoring telegram with crc error')
return
}
}
/** Emitted when a telegram has been validated.
* @event P1Client#telegram
* @param {string} telegram - The validated telegram.
*/
this.emit('telegram', telegram)
// Convert telegram into a raw object.
const obj = { type: header[1], checksum: footer[2] }
const lines = telegram.match(/\d+-\d+:\d+\.\d+\.\d+(\(.*\)\r?\n?)+\r\n/g)
for (const line of lines) {
const keys = line.match(/\d+-\d+:\d+\.\d+\.\d+/)
const values = line.match(/\([^)]*\)/g)
const a = p1Keys[keys[0]]
if (a == null) {
/** Emitted when the telegram contains an unknown key.
* @event P1Client#warning
* @param {string} message - The warning message.
*/
this.emit('warning', `${keys[0]}: ignoring unknown key`)
continue
}
for (const id in a) {
if (a[id].key != null) {
try {
obj[a[id].key] = a[id].f(a[id].allValues ? values : values[id])
} catch (error) {
const value = a[id].allValues ? values.join('') : values[id]
this.emit(
'warning', `${keys[0]}: ignoring unknown value ${value}`
)
}
}
}
}
/** Emitted when a telegram has been parsed.
* @event P1Client#rawData
* @param {Object} rawData - The telegram converted 1:1 to a flat obect.
*/
this.emit('rawData', obj)
// Convert the flat object into a cooked object.
const be = obj.version_be != null
const low = be ? 2 : 1
const normal = be ? 1 : 2
const tariff = obj.tariff === low ? 'low' : 'normal'
const result = {
type: obj.type,
version: be ? obj.version_be : obj.version == null ? '2.2' : obj.version,
msg_text: obj.msg_text,
msg_num: obj.msg_num,
electricity: {
id: obj.id.trim(),
lastupdated: obj.lastupdated,
tariff: tariff,
consumption: {
low: obj['consumption_t' + low],
normal: obj['consumption_t' + normal]
},
power: obj.power,
failures: {
short: obj.failures_short,
long: obj.failures_long,
log: obj.log
},
l1: {
voltage: obj.l1_voltage,
sags: obj.l1_sags,
swells: obj.l1_swells,
current: obj.l1_current,
power: obj.l1_power
}
},
electricityBack: {
id: obj.id.trim() + 'B',
lastupdated: obj.lastupdated,
tariff: tariff,
consumption: {
low: obj['consumption_back_t' + low],
normal: obj['consumption_back_t' + normal]
},
power: obj.power_back,
l1: { power: obj.l1_power_back }
}
}
if (obj.l2_voltage != null) {
result.electricity.l2 = {
voltage: obj.l2_voltage,
sags: obj.l2_sags,
swells: obj.l2_swells,
current: obj.l2_current,
power: obj.l2_power
}
result.electricityBack.l2 = { power: obj.l2_power_back }
result.electricity.l3 = {
voltage: obj.l3_voltage,
sags: obj.l3_sags,
swells: obj.l3_swells,
current: obj.l3_current,
power: obj.l3_power
}
result.electricityBack.l3 = { power: obj.l3_power_back }
}
if (obj.d1_type != null) {
result[obj.d1_type] = {
id: obj.d1_id.trim(),
lastupdated: obj.d1_lastupdated,
consumption: obj.d1_consumption
}
}
if (obj.d2_type != null) {
result[obj.d2_type] = {
id: obj.d2_id.trim(),
lastupdated: obj.d2_lastupdated,
consumption: obj.d2_consumption
}
}
if (obj.d3_type != null) {
result[obj.d3_type] = {
id: obj.d3_id.trim(),
lastupdated: obj.d3_lastupdated,
consumption: obj.d3_consumption
}
}
if (obj.d4_type != null) {
result[obj.d4_type] = {
id: obj.d4_id.trim(),
lastupdated: obj.d4_lastupdated,
consumption: obj.d4_consumption
}
}
/** Emitted when a telegram has been parsed.
* @event P1Client#data
* @param {Object} data - The telegram converted an object with
* nested objects.
*/
this.emit('data', result)
} catch (error) {
this.emit('error', error)
}
} |
JavaScript | async function fetchDatasets(type, variables) {
function changeKeyName(key) {
if (key == 'size') return 'rows';
else if (key == 'from') return 'start';
else return key;
}
variables.fq
? (variables.fq = variables.fq.concat(
` AND private:false AND type:${type}`
))
: (variables.fq = `private:false AND type:${type}`);
// creating a string of parameter from object of variables for CKAN API use
const varArray = Object.keys(variables).map((key) => {
return `${changeKeyName(key)}=${variables[key]}`;
});
const varString =
varArray.length > 0
? varArray.join('&')
: `fq=private:false AND type:${type}`;
const response = await fetch(
`http://15.206.122.72/api/3/action/package_search?${varString}`
);
const data = await response.json();
return data;
} | async function fetchDatasets(type, variables) {
function changeKeyName(key) {
if (key == 'size') return 'rows';
else if (key == 'from') return 'start';
else return key;
}
variables.fq
? (variables.fq = variables.fq.concat(
` AND private:false AND type:${type}`
))
: (variables.fq = `private:false AND type:${type}`);
// creating a string of parameter from object of variables for CKAN API use
const varArray = Object.keys(variables).map((key) => {
return `${changeKeyName(key)}=${variables[key]}`;
});
const varString =
varArray.length > 0
? varArray.join('&')
: `fq=private:false AND type:${type}`;
const response = await fetch(
`http://15.206.122.72/api/3/action/package_search?${varString}`
);
const data = await response.json();
return data;
} |
JavaScript | function findFileByPath(dataSet,filePath){
for(var file of dataSet){
if(file.filePath == filePath){
return file;
}
}
console.log("cannot find file");
} | function findFileByPath(dataSet,filePath){
for(var file of dataSet){
if(file.filePath == filePath){
return file;
}
}
console.log("cannot find file");
} |
JavaScript | function preview(checkboxs,file){
var preview = [];
if(typeof file == 'undefined'){
return preview;
}
var columns = file.columnList;
for(var i =0 ;i < checkboxs.length;i++){
if(checkboxs[i].status == true){
preview.push(columns[checkboxs[i].index]);
}
}
return preview;
} | function preview(checkboxs,file){
var preview = [];
if(typeof file == 'undefined'){
return preview;
}
var columns = file.columnList;
for(var i =0 ;i < checkboxs.length;i++){
if(checkboxs[i].status == true){
preview.push(columns[checkboxs[i].index]);
}
}
return preview;
} |
JavaScript | function handlelines(configObj, newHandlers) {
let propsToAdd = configObj.propsToAdd;
// handleLine could be the only needed piece to be replaced for most gulp-etl plugins
const defaultHandleLine = (lineObj) => {
for (let propName in propsToAdd) {
lineObj[propName] = propsToAdd[propName];
}
return lineObj;
};
const defaultFinishHandler = (context, file) => {
log.info("The handler for " + file.basename + " has officially ended!");
};
const defaultStartHandler = (context, file) => {
log.info("The handler for " + file.basename + " has officially started!");
};
const handleLine = newHandlers && newHandlers.transformCallback ? newHandlers.transformCallback : defaultHandleLine;
const finishHandler = newHandlers && newHandlers.finishCallback ? newHandlers.finishCallback : defaultFinishHandler;
let startHandler = newHandlers && newHandlers.startCallback ? newHandlers.startCallback : defaultStartHandler;
function StreamPush(transformer, handledLine) {
if (transformer._onFirstLine) {
transformer._onFirstLine = false;
}
else {
handledLine = '\n' + handledLine;
}
log.debug(handledLine);
transformer.push(handledLine);
}
function newTransformer(context, file) {
let transformer = through2.obj(); // new transform stream, in object mode
transformer._onFirstLine = true; // we have to handle the first line differently, so we set a flag
// since we're counting on split to have already been called upstream, dataLine will be a single line at a time
transformer._transform = function (dataLine, encoding, callback) {
let returnErr = null;
try {
let dataObj;
let handledObj;
if (dataLine.trim() != "") {
dataObj = JSON.parse(dataLine);
handledObj = handleLine(dataObj, context, file);
}
if (handledObj) {
if (Array.isArray(handledObj)) {
for (var i = 0; i < handledObj.length; i++) {
let handledLine = JSON.stringify(handledObj[i]);
StreamPush(this, handledLine);
}
}
else {
let handledLine = JSON.stringify(handledObj);
StreamPush(this, handledLine);
}
}
}
catch (err) {
returnErr = new PluginError(PLUGIN_NAME, err);
}
callback(returnErr);
};
return transformer;
}
// creating a stream through which each file will pass
// see https://stackoverflow.com/a/52432089/5578474 for a note on the "this" param
const strm = through2.obj(function (file, encoding, cb) {
const self = this;
let returnErr = null;
// initialize a context object if needed; attached to the file.data object (compatible with gulp-data)
if (file && !file.data)
file.data = {};
if (!file.data.context)
file.data.context = {};
startHandler(file.data.context, file);
if (file.isNull()) {
// return empty file
return cb(returnErr, file);
}
else if (file.isBuffer()) {
// strArray will hold file.contents, split into lines
const strArray = file.contents.toString().split(/\r?\n/);
let tempLine;
let resultArray = [];
// we'll call handleLine on each line
for (let dataIdx in strArray) {
try {
let lineObj;
let tempLine;
if (strArray[dataIdx].trim() != "") {
lineObj = JSON.parse(strArray[dataIdx]);
tempLine = handleLine(lineObj, file.data.context, file);
// add newline before every line execept the first
if (dataIdx != "0") {
resultArray.push('\n');
}
if (tempLine) {
if (Array.isArray(tempLine)) {
for (var i = 0; i < tempLine.length; i++) {
resultArray.push(JSON.stringify(tempLine[i]));
if (i != tempLine.length - 1) {
resultArray.push('\n');
}
}
}
else {
resultArray.push(JSON.stringify(tempLine));
}
}
}
}
catch (err) {
returnErr = new PluginError(PLUGIN_NAME, err);
}
}
let data = resultArray.join('');
log.debug(data);
file.contents = Buffer.from(data);
finishHandler(file.data.context, file);
// send the transformed file through to the next gulp plugin, and tell the stream engine that we're done with this file
cb(returnErr, file);
}
else if (file.isStream()) {
try {
file.contents = file.contents
// split plugin will split the file into lines
.pipe(split())
.pipe(newTransformer(file.data.context, file))
.on('finish', function () {
// using finish event here instead of end since this is a Transform stream https://nodejs.org/api/stream.html#stream_events_finish_and_end
//the 'finish' event is emitted after stream.end() is called and all chunks have been processed by stream._transform()
//this is when we want to pass the file along
log.debug('finished');
finishHandler(file.data.context, file);
})
.on('error', function (err) {
log.error(err);
self.emit('error', new PluginError(PLUGIN_NAME, err));
});
// after our stream is set up (not necesarily finished) we call the callback
log.debug('calling callback');
cb(returnErr, file);
}
catch (err) {
log.error(err);
self.emit('error', new PluginError(PLUGIN_NAME, err));
}
}
});
return strm;
} | function handlelines(configObj, newHandlers) {
let propsToAdd = configObj.propsToAdd;
// handleLine could be the only needed piece to be replaced for most gulp-etl plugins
const defaultHandleLine = (lineObj) => {
for (let propName in propsToAdd) {
lineObj[propName] = propsToAdd[propName];
}
return lineObj;
};
const defaultFinishHandler = (context, file) => {
log.info("The handler for " + file.basename + " has officially ended!");
};
const defaultStartHandler = (context, file) => {
log.info("The handler for " + file.basename + " has officially started!");
};
const handleLine = newHandlers && newHandlers.transformCallback ? newHandlers.transformCallback : defaultHandleLine;
const finishHandler = newHandlers && newHandlers.finishCallback ? newHandlers.finishCallback : defaultFinishHandler;
let startHandler = newHandlers && newHandlers.startCallback ? newHandlers.startCallback : defaultStartHandler;
function StreamPush(transformer, handledLine) {
if (transformer._onFirstLine) {
transformer._onFirstLine = false;
}
else {
handledLine = '\n' + handledLine;
}
log.debug(handledLine);
transformer.push(handledLine);
}
function newTransformer(context, file) {
let transformer = through2.obj(); // new transform stream, in object mode
transformer._onFirstLine = true; // we have to handle the first line differently, so we set a flag
// since we're counting on split to have already been called upstream, dataLine will be a single line at a time
transformer._transform = function (dataLine, encoding, callback) {
let returnErr = null;
try {
let dataObj;
let handledObj;
if (dataLine.trim() != "") {
dataObj = JSON.parse(dataLine);
handledObj = handleLine(dataObj, context, file);
}
if (handledObj) {
if (Array.isArray(handledObj)) {
for (var i = 0; i < handledObj.length; i++) {
let handledLine = JSON.stringify(handledObj[i]);
StreamPush(this, handledLine);
}
}
else {
let handledLine = JSON.stringify(handledObj);
StreamPush(this, handledLine);
}
}
}
catch (err) {
returnErr = new PluginError(PLUGIN_NAME, err);
}
callback(returnErr);
};
return transformer;
}
// creating a stream through which each file will pass
// see https://stackoverflow.com/a/52432089/5578474 for a note on the "this" param
const strm = through2.obj(function (file, encoding, cb) {
const self = this;
let returnErr = null;
// initialize a context object if needed; attached to the file.data object (compatible with gulp-data)
if (file && !file.data)
file.data = {};
if (!file.data.context)
file.data.context = {};
startHandler(file.data.context, file);
if (file.isNull()) {
// return empty file
return cb(returnErr, file);
}
else if (file.isBuffer()) {
// strArray will hold file.contents, split into lines
const strArray = file.contents.toString().split(/\r?\n/);
let tempLine;
let resultArray = [];
// we'll call handleLine on each line
for (let dataIdx in strArray) {
try {
let lineObj;
let tempLine;
if (strArray[dataIdx].trim() != "") {
lineObj = JSON.parse(strArray[dataIdx]);
tempLine = handleLine(lineObj, file.data.context, file);
// add newline before every line execept the first
if (dataIdx != "0") {
resultArray.push('\n');
}
if (tempLine) {
if (Array.isArray(tempLine)) {
for (var i = 0; i < tempLine.length; i++) {
resultArray.push(JSON.stringify(tempLine[i]));
if (i != tempLine.length - 1) {
resultArray.push('\n');
}
}
}
else {
resultArray.push(JSON.stringify(tempLine));
}
}
}
}
catch (err) {
returnErr = new PluginError(PLUGIN_NAME, err);
}
}
let data = resultArray.join('');
log.debug(data);
file.contents = Buffer.from(data);
finishHandler(file.data.context, file);
// send the transformed file through to the next gulp plugin, and tell the stream engine that we're done with this file
cb(returnErr, file);
}
else if (file.isStream()) {
try {
file.contents = file.contents
// split plugin will split the file into lines
.pipe(split())
.pipe(newTransformer(file.data.context, file))
.on('finish', function () {
// using finish event here instead of end since this is a Transform stream https://nodejs.org/api/stream.html#stream_events_finish_and_end
//the 'finish' event is emitted after stream.end() is called and all chunks have been processed by stream._transform()
//this is when we want to pass the file along
log.debug('finished');
finishHandler(file.data.context, file);
})
.on('error', function (err) {
log.error(err);
self.emit('error', new PluginError(PLUGIN_NAME, err));
});
// after our stream is set up (not necesarily finished) we call the callback
log.debug('calling callback');
cb(returnErr, file);
}
catch (err) {
log.error(err);
self.emit('error', new PluginError(PLUGIN_NAME, err));
}
}
});
return strm;
} |
JavaScript | normalizingParameters(obj) {
const selfParameters = ['signKey', 'env', 'passpfx']
selfParameters.forEach((key)=>{
delete obj[key]
})
return obj
} | normalizingParameters(obj) {
const selfParameters = ['signKey', 'env', 'passpfx']
selfParameters.forEach((key)=>{
delete obj[key]
})
return obj
} |
JavaScript | sandboxKey() {
const sandboxSignKeyUrl = 'https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey'
const options = {
mch_id: this.mch_id,
nonce_str: utils.nonceStr(),
}
options.sign = utils.sign(options, this.signKey)
return request.post(sandboxSignKeyUrl)
.type('xml')
.send(utils.json2xml(options))
.then((_)=>{
return utils.buildResponse(_)
})
.then((response)=>{
this.signKey = response.sandbox_signkey
return response.sandbox_signkey
})
} | sandboxKey() {
const sandboxSignKeyUrl = 'https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey'
const options = {
mch_id: this.mch_id,
nonce_str: utils.nonceStr(),
}
options.sign = utils.sign(options, this.signKey)
return request.post(sandboxSignKeyUrl)
.type('xml')
.send(utils.json2xml(options))
.then((_)=>{
return utils.buildResponse(_)
})
.then((response)=>{
this.signKey = response.sandbox_signkey
return response.sandbox_signkey
})
} |
JavaScript | makeRequest(method, path, body, qs) {
// Return a promise to allow developers to appropriately handle API responses.
return new Promise((resolve, reject) => {
request({
method,
qs,
body,
json: true,
url: `${this.base}/${path}`,
headers: {
'Authorization': `Bearer ${this.jwt}`
}
}, (error, response, responseBody) => {
// If there is a request error, reject the Promise.
if (error) {
return reject(error);
}
// If there is an error on the response body, reject the Promise.
if (responseBody && responseBody.error) {
return reject(responseBody.error);
}
// If we receive a status code other than 2XX range, reject the Promise.
if (response.statusCode < 200 || response.statusCode > 299) {
return reject(`Error encountered during request to StreamElements. Status Code: ${response.statusCode}`);
}
// If no errors have been encountered, resolve the Promise with the response body.
return resolve(responseBody);
});
});
} | makeRequest(method, path, body, qs) {
// Return a promise to allow developers to appropriately handle API responses.
return new Promise((resolve, reject) => {
request({
method,
qs,
body,
json: true,
url: `${this.base}/${path}`,
headers: {
'Authorization': `Bearer ${this.jwt}`
}
}, (error, response, responseBody) => {
// If there is a request error, reject the Promise.
if (error) {
return reject(error);
}
// If there is an error on the response body, reject the Promise.
if (responseBody && responseBody.error) {
return reject(responseBody.error);
}
// If we receive a status code other than 2XX range, reject the Promise.
if (response.statusCode < 200 || response.statusCode > 299) {
return reject(`Error encountered during request to StreamElements. Status Code: ${response.statusCode}`);
}
// If no errors have been encountered, resolve the Promise with the response body.
return resolve(responseBody);
});
});
} |
JavaScript | function showEvents() {
theYear = -1, theMonth = -1, theDay = -1;
for (i = 0; i < data.years.length; i++) {
if (calendar.date.getFullYear() == data.years[i].int) {
theYear = i;
break;
}
}
for (i = 0; i < data.years[theYear].months.length; i++) {
if ((calendar.date.getMonth() + 1) == data.years[theYear].months[i].int) {
theMonth = i;
break;
}
}
for (i = 0; i < data.years[theYear].months[theMonth].days.length; i++) {
if (calendar.date.getDate() == data.years[theYear].months[theMonth].days[i].int) {
theDay = i;
break;
}
}
theEvents = data.years[theYear].months[theMonth].days[theDay].events;
organizer.list(theEvents); // what's responsible for listing
_events = [];
} | function showEvents() {
theYear = -1, theMonth = -1, theDay = -1;
for (i = 0; i < data.years.length; i++) {
if (calendar.date.getFullYear() == data.years[i].int) {
theYear = i;
break;
}
}
for (i = 0; i < data.years[theYear].months.length; i++) {
if ((calendar.date.getMonth() + 1) == data.years[theYear].months[i].int) {
theMonth = i;
break;
}
}
for (i = 0; i < data.years[theYear].months[theMonth].days.length; i++) {
if (calendar.date.getDate() == data.years[theYear].months[theMonth].days[i].int) {
theDay = i;
break;
}
}
theEvents = data.years[theYear].months[theMonth].days[theDay].events;
organizer.list(theEvents); // what's responsible for listing
_events = [];
} |
JavaScript | function wrapText(tokens, needle, wrapper, getMatchParts = defaultMatchParts) {
const results = [];
tokens.forEach((token) => {
if (token.type === 0 /* text */) {
let remaining = token.text;
while (remaining.length > 0) {
const m = remaining.match(needle);
if (m === null) {
results.push(newTextToken(remaining));
return;
}
const mp = getMatchParts(m);
const offset = remaining.indexOf(mp.fullMatch);
const preOffset = offset + mp.prefix.length;
if (preOffset > 0) {
results.push(newTextToken(remaining.substr(0, preOffset)));
}
results.push(newElementTokenWithText(wrapper, mp.wrapped));
if (mp.postfix) {
results.push(newTextToken(mp.postfix));
}
remaining = remaining.substr(offset + mp.fullMatch.length);
}
}
else if (token.type === 1 /* element */) {
results.push(newElementToken(token.refElement, wrapText(token.children, needle, wrapper, getMatchParts)));
}
});
return results;
} | function wrapText(tokens, needle, wrapper, getMatchParts = defaultMatchParts) {
const results = [];
tokens.forEach((token) => {
if (token.type === 0 /* text */) {
let remaining = token.text;
while (remaining.length > 0) {
const m = remaining.match(needle);
if (m === null) {
results.push(newTextToken(remaining));
return;
}
const mp = getMatchParts(m);
const offset = remaining.indexOf(mp.fullMatch);
const preOffset = offset + mp.prefix.length;
if (preOffset > 0) {
results.push(newTextToken(remaining.substr(0, preOffset)));
}
results.push(newElementTokenWithText(wrapper, mp.wrapped));
if (mp.postfix) {
results.push(newTextToken(mp.postfix));
}
remaining = remaining.substr(offset + mp.fullMatch.length);
}
}
else if (token.type === 1 /* element */) {
results.push(newElementToken(token.refElement, wrapText(token.children, needle, wrapper, getMatchParts)));
}
});
return results;
} |
JavaScript | function applyWrapMultipleCaps(tokens, wrapElement, minLength) {
if (minLength <= 1) {
return wrapText(tokens, /\b[A-Z]\b/, wrapElement);
}
const needle = new RegExp(`\\b(\\d[A-Z][A-Z\\d]{${minLength - 2},}|[A-Z][A-Z\\d]{${minLength
- 1},})\\b`);
return wrapText(tokens, needle, wrapElement);
} | function applyWrapMultipleCaps(tokens, wrapElement, minLength) {
if (minLength <= 1) {
return wrapText(tokens, /\b[A-Z]\b/, wrapElement);
}
const needle = new RegExp(`\\b(\\d[A-Z][A-Z\\d]{${minLength - 2},}|[A-Z][A-Z\\d]{${minLength
- 1},})\\b`);
return wrapText(tokens, needle, wrapElement);
} |
JavaScript | function ordinalMatchParts(matches) {
return {
prefix: matches[1],
wrapped: matches[2],
postfix: '',
fullMatch: matches[0],
};
} | function ordinalMatchParts(matches) {
return {
prefix: matches[1],
wrapped: matches[2],
postfix: '',
fullMatch: matches[0],
};
} |
JavaScript | function applyWrapQuotes(tokens, wrapElements) {
let t = tokens;
// double
t = wrapText(t, LEFT_DOBULE_QUOTE_REGEX, wrapElements.leftDouble);
t = wrapText(t, RIGHT_DOUBLE_QUOTE_REGEX, wrapElements.rightDouble);
// single
t = wrapText(t, LEFT_SINGLE_QUOTE_REGEX, wrapElements.leftSingle);
t = wrapText(t, RIGHT_SINGLE_QUOTE_REGEX, wrapElements.rightSingle);
t = wrapText(t, APOSTROPHE_REGEX, wrapElements.apostrophe);
// non-curly
t = wrapText(t, DOUBLE_QUOTE_REGEX, wrapElements.double);
t = wrapText(t, SINGLE_QUOTE_REGEX, wrapElements.single);
return t;
} | function applyWrapQuotes(tokens, wrapElements) {
let t = tokens;
// double
t = wrapText(t, LEFT_DOBULE_QUOTE_REGEX, wrapElements.leftDouble);
t = wrapText(t, RIGHT_DOUBLE_QUOTE_REGEX, wrapElements.rightDouble);
// single
t = wrapText(t, LEFT_SINGLE_QUOTE_REGEX, wrapElements.leftSingle);
t = wrapText(t, RIGHT_SINGLE_QUOTE_REGEX, wrapElements.rightSingle);
t = wrapText(t, APOSTROPHE_REGEX, wrapElements.apostrophe);
// non-curly
t = wrapText(t, DOUBLE_QUOTE_REGEX, wrapElements.double);
t = wrapText(t, SINGLE_QUOTE_REGEX, wrapElements.single);
return t;
} |
JavaScript | function request(gql) {
// const defaultOptions = {
// credentials: 'include',
// };
// const newOptions = { ...defaultOptions, ...options };
// if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
// if (!(newOptions.body instanceof FormData)) {
// newOptions.headers = {
// Accept: 'application/json',
// 'Content-Type': 'application/json; charset=utf-8',
// ...newOptions.headers,
// };
// newOptions.body = JSON.stringify(newOptions.body);
// } else {
// // newOptions.body is FormData
// newOptions.headers = {
// Accept: 'application/json',
// 'Content-Type': 'multipart/form-data',
// ...newOptions.headers,
// };
// }
// }
// return fetch(url, newOptions)
// .then(checkStatus)
// .then(response => {
// if (newOptions.method === 'DELETE' || response.status === 204) {
// return response.text();
// }
// return response.json();
// })
// .catch(e => {
// const { dispatch } = store;
// const status = e.name;
// if (status === 401) {
// dispatch({
// type: 'login/logout',
// });
// return;
// }
// if (status === 403) {
// dispatch(routerRedux.push('/exception/403'));
// return;
// }
// if (status <= 504 && status >= 500) {
// dispatch(routerRedux.push('/exception/500'));
// return;
// }
// if (status >= 404 && status < 422) {
// dispatch(routerRedux.push('/exception/404'));
// }
// });
return client.query({
query: gql,
});
// return fetch(url, newOptions)
// .then(checkStatus)
// .then(response => {
// if (newOptions.method === 'DELETE' || response.status === 204) {
// return response.text();
// }
// return response.json();
// })
// .catch(e => {
// const { dispatch } = store;
// const status = e.name;
// if (status === 401) {
// dispatch({
// type: 'login/logout',
// });
// return;
// }
// if (status === 403) {
// dispatch(routerRedux.push('/exception/403'));
// return;
// }
// if (status <= 504 && status >= 500) {
// dispatch(routerRedux.push('/exception/500'));
// return;
// }
// if (status >= 404 && status < 422) {
// dispatch(routerRedux.push('/exception/404'));
// }
// });
} | function request(gql) {
// const defaultOptions = {
// credentials: 'include',
// };
// const newOptions = { ...defaultOptions, ...options };
// if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
// if (!(newOptions.body instanceof FormData)) {
// newOptions.headers = {
// Accept: 'application/json',
// 'Content-Type': 'application/json; charset=utf-8',
// ...newOptions.headers,
// };
// newOptions.body = JSON.stringify(newOptions.body);
// } else {
// // newOptions.body is FormData
// newOptions.headers = {
// Accept: 'application/json',
// 'Content-Type': 'multipart/form-data',
// ...newOptions.headers,
// };
// }
// }
// return fetch(url, newOptions)
// .then(checkStatus)
// .then(response => {
// if (newOptions.method === 'DELETE' || response.status === 204) {
// return response.text();
// }
// return response.json();
// })
// .catch(e => {
// const { dispatch } = store;
// const status = e.name;
// if (status === 401) {
// dispatch({
// type: 'login/logout',
// });
// return;
// }
// if (status === 403) {
// dispatch(routerRedux.push('/exception/403'));
// return;
// }
// if (status <= 504 && status >= 500) {
// dispatch(routerRedux.push('/exception/500'));
// return;
// }
// if (status >= 404 && status < 422) {
// dispatch(routerRedux.push('/exception/404'));
// }
// });
return client.query({
query: gql,
});
// return fetch(url, newOptions)
// .then(checkStatus)
// .then(response => {
// if (newOptions.method === 'DELETE' || response.status === 204) {
// return response.text();
// }
// return response.json();
// })
// .catch(e => {
// const { dispatch } = store;
// const status = e.name;
// if (status === 401) {
// dispatch({
// type: 'login/logout',
// });
// return;
// }
// if (status === 403) {
// dispatch(routerRedux.push('/exception/403'));
// return;
// }
// if (status <= 504 && status >= 500) {
// dispatch(routerRedux.push('/exception/500'));
// return;
// }
// if (status >= 404 && status < 422) {
// dispatch(routerRedux.push('/exception/404'));
// }
// });
} |
JavaScript | function bootstrap() {
const channel = new MessageChannel();
ghostWindow.postMessage('ghostframe', '*', [channel.port2]);
// listen to URL changes
channel.port1.onmessage = (evt) => {
let data;
try {
data = JSON.parse(evt.data);
} catch (err) {
console.warn(`ghostframe received data that is not JSON: ${evt.data}`);
return;
}
const { location, title } = data;
const match = location.match(/\w+:\/\/[^/]+\/([^?#]*)(.*)/);
if (!match) {
console.warn(`ghostframe received data that is not a URL: "${evt.data}"`);
return;
}
const path = match[1];
const queryAndHash = match[2];
document.title = title;
window.history.pushState(path, title, `/${path}${queryAndHash}`);
}; // channel.port1.onmessage
} // bootstrap | function bootstrap() {
const channel = new MessageChannel();
ghostWindow.postMessage('ghostframe', '*', [channel.port2]);
// listen to URL changes
channel.port1.onmessage = (evt) => {
let data;
try {
data = JSON.parse(evt.data);
} catch (err) {
console.warn(`ghostframe received data that is not JSON: ${evt.data}`);
return;
}
const { location, title } = data;
const match = location.match(/\w+:\/\/[^/]+\/([^?#]*)(.*)/);
if (!match) {
console.warn(`ghostframe received data that is not a URL: "${evt.data}"`);
return;
}
const path = match[1];
const queryAndHash = match[2];
document.title = title;
window.history.pushState(path, title, `/${path}${queryAndHash}`);
}; // channel.port1.onmessage
} // bootstrap |
JavaScript | function transMsg(msgToTrans, sender, lang, destChannel) {
// Just some basic logging in json format.
console.log(`{
Translation Task: {
"sender": ${sender.username},
"message": ${msgToTrans},
"sentLanguage": ${lang},
"destChannel": ${destChannel}
}
}`)
// Translation Magic 🦄 - Send the message off to the DeepL API for translation.
translate({
text: msgToTrans,
target_lang: lang,
auth_key: process.env.deepLKey,
// All optional DeepL parameters available in the official documentation can be defined here as well.
})
.then(result => {
// Send the translated version of the message to the appropriate Discord channel :)
eval(destChannel).send(result.data.translations[0].text, {
username: sender.username,
avatarURL: `https://cdn.discordapp.com/avatars/${sender.id}/${sender.avatar}.jpeg`,
});
})
// Catch Errors. But of course, I never make mistakes, so this is a useless line *kappa*
.catch(error => {
console.error(error)
})
} | function transMsg(msgToTrans, sender, lang, destChannel) {
// Just some basic logging in json format.
console.log(`{
Translation Task: {
"sender": ${sender.username},
"message": ${msgToTrans},
"sentLanguage": ${lang},
"destChannel": ${destChannel}
}
}`)
// Translation Magic 🦄 - Send the message off to the DeepL API for translation.
translate({
text: msgToTrans,
target_lang: lang,
auth_key: process.env.deepLKey,
// All optional DeepL parameters available in the official documentation can be defined here as well.
})
.then(result => {
// Send the translated version of the message to the appropriate Discord channel :)
eval(destChannel).send(result.data.translations[0].text, {
username: sender.username,
avatarURL: `https://cdn.discordapp.com/avatars/${sender.id}/${sender.avatar}.jpeg`,
});
})
// Catch Errors. But of course, I never make mistakes, so this is a useless line *kappa*
.catch(error => {
console.error(error)
})
} |
JavaScript | function proxyMsg(msgToTrans, sender, lang, destChannel) {
console.log(`{
Proxy Task: {
"sender": ${sender.username},
"message": ${msgToTrans},
"sentLanguage": ${lang},
"destChannel": ${destChannel}
}
}`)
eval(destChannel).send(msgToTrans, {
username: sender.username,
avatarURL: `https://cdn.discordapp.com/avatars/${sender.id}/${sender.avatar}.jpeg`,
})
} | function proxyMsg(msgToTrans, sender, lang, destChannel) {
console.log(`{
Proxy Task: {
"sender": ${sender.username},
"message": ${msgToTrans},
"sentLanguage": ${lang},
"destChannel": ${destChannel}
}
}`)
eval(destChannel).send(msgToTrans, {
username: sender.username,
avatarURL: `https://cdn.discordapp.com/avatars/${sender.id}/${sender.avatar}.jpeg`,
})
} |
JavaScript | function resolveValue(value, targetStack, envName, params) {
const dict = {
stack: targetStack,
env: envName,
...params
};
if (typeof value === "function") {
return value(targetStack, envName, dict);
}
if (typeof value === "string") {
return format(value, dict);
}
return value;
} | function resolveValue(value, targetStack, envName, params) {
const dict = {
stack: targetStack,
env: envName,
...params
};
if (typeof value === "function") {
return value(targetStack, envName, dict);
}
if (typeof value === "string") {
return format(value, dict);
}
return value;
} |
JavaScript | async execute(command, options = {}) {
try {
const result = await justRunIt(command, {
...options,
env: {
AWS_PROFILE: this.role,
...options.env
},
dryRun: options.dryRun || this.dryRun
});
return result;
} catch (error) {
const errorMessage = `An error occurred running a ${
command[0]
} command: ${options.quiet ? `${error.stderr}\n\n` : ""}${
error.message
}`;
const ce = new CallerError(errorMessage);
ce.stack = error.stack;
ce.command = command;
throw ce;
}
} | async execute(command, options = {}) {
try {
const result = await justRunIt(command, {
...options,
env: {
AWS_PROFILE: this.role,
...options.env
},
dryRun: options.dryRun || this.dryRun
});
return result;
} catch (error) {
const errorMessage = `An error occurred running a ${
command[0]
} command: ${options.quiet ? `${error.stderr}\n\n` : ""}${
error.message
}`;
const ce = new CallerError(errorMessage);
ce.stack = error.stack;
ce.command = command;
throw ce;
}
} |
JavaScript | async authenticate() {
if (this.authenticationCommand) {
if (typeof this.authenticationCommand === "function") {
await this.authenticationCommand(
this.targetStack,
this.envName,
{
execute: this.execute.bind(this),
role: this.role,
dryRun: this.dryRun
}
);
} else if (Array.isArray(this.authenticationCommand)) {
await this.execute(this.authenticationCommand);
} else {
await this.execute([this.authenticationCommand]);
}
}
} | async authenticate() {
if (this.authenticationCommand) {
if (typeof this.authenticationCommand === "function") {
await this.authenticationCommand(
this.targetStack,
this.envName,
{
execute: this.execute.bind(this),
role: this.role,
dryRun: this.dryRun
}
);
} else if (Array.isArray(this.authenticationCommand)) {
await this.execute(this.authenticationCommand);
} else {
await this.execute([this.authenticationCommand]);
}
}
} |
JavaScript | function serialize (item, module = null) {
const moduleId = module ? module.id : null
const isChild = item.category === 'Child'
const anchor = isChild ? item.anchor : ''
const category = isChild ? 'Child' : item.category
const description = isChild ? moduleId : null
const label = item.label || null
const link = `${yard_kit_relative_url_path}${isChild ? module.url : item.element.url}${isChild ? `#${item.anchor}` : ''}`
return {
link: link, // Link to the result. Used in the 'href' tag.
title: item.match, // Main text displayed for each autocomplete result.
description: description, // Displayed under the title.
label: label, // 'Callback' or 'Type' - if set it will be displayed next to the title.
matchQuality: item.matchQuality, // 0..1 - How well result matches the search term. Higher is better.
category: category
// 'Module', 'Mix Task' or 'Child'.
// Used to sort the results according to the 'sortingPriority'.
// 'Child' means an item that belongs to a module (like Function, Callback or Type).
}
} | function serialize (item, module = null) {
const moduleId = module ? module.id : null
const isChild = item.category === 'Child'
const anchor = isChild ? item.anchor : ''
const category = isChild ? 'Child' : item.category
const description = isChild ? moduleId : null
const label = item.label || null
const link = `${yard_kit_relative_url_path}${isChild ? module.url : item.element.url}${isChild ? `#${item.anchor}` : ''}`
return {
link: link, // Link to the result. Used in the 'href' tag.
title: item.match, // Main text displayed for each autocomplete result.
description: description, // Displayed under the title.
label: label, // 'Callback' or 'Type' - if set it will be displayed next to the title.
matchQuality: item.matchQuality, // 0..1 - How well result matches the search term. Higher is better.
category: category
// 'Module', 'Mix Task' or 'Child'.
// Used to sort the results according to the 'sortingPriority'.
// 'Child' means an item that belongs to a module (like Function, Callback or Type).
}
} |
JavaScript | function findMatchingChildren (elements, parentId, term, key) {
const regExp = new RegExp(helpers.escapeText(term), 'i')
return (elements || []).reduce((acc, element) => {
if (acc[key + element.id]) { return acc }
// Match "Module.funcion" format.
const fullTitle = `${parentId}.${element.id}`
const fullTitleMatch = !(parentId + '.').match(regExp) && fullTitle.match(regExp)
const match = element.id && element.id.match(regExp)
let result = JSON.parse(JSON.stringify(element))
if (match) {
result.match = highlight(match)
result.matchQuality = matchQuality(match)
} else if (fullTitleMatch) {
// When match spans both module and function name (i.e. ">Map.fe<tch")
// let's return just ">fe<tch" as the title. Module will already be displayed under the title.
const lastSegment = term.split('.').pop()
const lastSegmentMatcher = new RegExp(helpers.escapeText(lastSegment), 'i')
const lastSegmentMatch = element.id.match(lastSegmentMatcher)
result.matchQuality = matchQuality(lastSegmentMatch)
result.match = highlight(lastSegmentMatch)
result.element = element
} else {
return acc
}
acc[key + result.id] = result
return acc
}, {})
} | function findMatchingChildren (elements, parentId, term, key) {
const regExp = new RegExp(helpers.escapeText(term), 'i')
return (elements || []).reduce((acc, element) => {
if (acc[key + element.id]) { return acc }
// Match "Module.funcion" format.
const fullTitle = `${parentId}.${element.id}`
const fullTitleMatch = !(parentId + '.').match(regExp) && fullTitle.match(regExp)
const match = element.id && element.id.match(regExp)
let result = JSON.parse(JSON.stringify(element))
if (match) {
result.match = highlight(match)
result.matchQuality = matchQuality(match)
} else if (fullTitleMatch) {
// When match spans both module and function name (i.e. ">Map.fe<tch")
// let's return just ">fe<tch" as the title. Module will already be displayed under the title.
const lastSegment = term.split('.').pop()
const lastSegmentMatcher = new RegExp(helpers.escapeText(lastSegment), 'i')
const lastSegmentMatch = element.id.match(lastSegmentMatcher)
result.matchQuality = matchQuality(lastSegmentMatch)
result.match = highlight(lastSegmentMatch)
result.element = element
} else {
return acc
}
acc[key + result.id] = result
return acc
}, {})
} |
JavaScript | function moveNode(source) {
scale = zoomListener.scale();
children = source.children[0];
x = -children.y0;
y = -source.x0;
x = x * scale + 40;
y = y * scale + viewerHeight / 2;
d3.select('g').transition()
.duration(duration)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")");
zoomListener.scale(scale);
zoomListener.translate([x, y]);
} | function moveNode(source) {
scale = zoomListener.scale();
children = source.children[0];
x = -children.y0;
y = -source.x0;
x = x * scale + 40;
y = y * scale + viewerHeight / 2;
d3.select('g').transition()
.duration(duration)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")");
zoomListener.scale(scale);
zoomListener.translate([x, y]);
} |
JavaScript | function updateSuggestions (term) {
const results = getSuggestions(term)
const relative_url_path = yard_kit_relative_url_path || ''
const template = autocompleteResultsTemplate({
empty: results.length === 0,
results: results,
term: term,
relative_url_path: relative_url_path,
})
autocompleteElement.html(template)
} | function updateSuggestions (term) {
const results = getSuggestions(term)
const relative_url_path = yard_kit_relative_url_path || ''
const template = autocompleteResultsTemplate({
empty: results.length === 0,
results: results,
term: term,
relative_url_path: relative_url_path,
})
autocompleteElement.html(template)
} |
JavaScript | function selectedElement () {
const currentlySelectedElement = $('.autocomplete-suggestion.selected')
if (currentlySelectedElement.length === 0) {
return null
}
if (currentlySelectedElement.attr('data-index') === '-1') {
// -1 marks the deafult 'Search for "phrase"...' element
return null
}
return currentlySelectedElement
} | function selectedElement () {
const currentlySelectedElement = $('.autocomplete-suggestion.selected')
if (currentlySelectedElement.length === 0) {
return null
}
if (currentlySelectedElement.attr('data-index') === '-1') {
// -1 marks the deafult 'Search for "phrase"...' element
return null
}
return currentlySelectedElement
} |
JavaScript | function moveSelection (direction) {
const currentlySelectedElement = $('.autocomplete-suggestion.selected')
let indexToSelect = -1
if (currentlySelectedElement.length) {
indexToSelect = parseInt(currentlySelectedElement.attr('data-index')) + direction
}
let elementToSelect = $(`.autocomplete-suggestion[data-index="${indexToSelect}"]`)
if (!elementToSelect.length) {
if (indexToSelect < 0) {
elementToSelect = $('.autocomplete-suggestion:last')
} else {
elementToSelect = $('.autocomplete-suggestion:first')
}
}
$('.autocomplete-suggestion').each(function () {
$(this).toggleClass('selected', $(this).is(elementToSelect))
})
} | function moveSelection (direction) {
const currentlySelectedElement = $('.autocomplete-suggestion.selected')
let indexToSelect = -1
if (currentlySelectedElement.length) {
indexToSelect = parseInt(currentlySelectedElement.attr('data-index')) + direction
}
let elementToSelect = $(`.autocomplete-suggestion[data-index="${indexToSelect}"]`)
if (!elementToSelect.length) {
if (indexToSelect < 0) {
elementToSelect = $('.autocomplete-suggestion:last')
} else {
elementToSelect = $('.autocomplete-suggestion:first')
}
}
$('.autocomplete-suggestion').each(function () {
$(this).toggleClass('selected', $(this).is(elementToSelect))
})
} |
JavaScript | function fillSidebarWithNodes (nodes, filter) {
const moduleType = helpers.getModuleType()
filter = filter || moduleType
var filtered = nodes[filter] || []
var fullList = $('#full-list')
const relative_url_path = yard_kit_relative_url_path || '';
fullList.replaceWith(sidebarItemsTemplate({'nodes': filtered, 'group': '', 'relative_url_path': relative_url_path}))
setupSelected(['#', filter, '-list'].join(''))
$('#full-list').attr('data-filter-type', filter)
$('#full-list li a').on('click', e => {
var $target = $(e.target)
// the user might have clicked on the nesting indicator
var linkTag = $target.is('a') ? $target : $target.closest('a')
if (linkTag.hasClass('expand') && !$target.is('span') && !e.shiftKey) {
e.preventDefault()
$(e.target).closest('li').toggleClass('open')
} else {
$('#full-list li.current-page li.current-hash').removeClass('current-hash')
$(e.target).closest('li').addClass('current-hash')
}
})
} | function fillSidebarWithNodes (nodes, filter) {
const moduleType = helpers.getModuleType()
filter = filter || moduleType
var filtered = nodes[filter] || []
var fullList = $('#full-list')
const relative_url_path = yard_kit_relative_url_path || '';
fullList.replaceWith(sidebarItemsTemplate({'nodes': filtered, 'group': '', 'relative_url_path': relative_url_path}))
setupSelected(['#', filter, '-list'].join(''))
$('#full-list').attr('data-filter-type', filter)
$('#full-list li a').on('click', e => {
var $target = $(e.target)
// the user might have clicked on the nesting indicator
var linkTag = $target.is('a') ? $target : $target.closest('a')
if (linkTag.hasClass('expand') && !$target.is('span') && !e.shiftKey) {
e.preventDefault()
$(e.target).closest('li').toggleClass('open')
} else {
$('#full-list li.current-page li.current-hash').removeClass('current-hash')
$(e.target).closest('li').addClass('current-hash')
}
})
} |
JavaScript | function load (location) {
var required = requireAll(location)
var config = {}
for (var key in required) {
config[key.replace(/^array\./, 'array:')] = required[key]
}
var konsole = createConsole(config)
return konsole
} | function load (location) {
var required = requireAll(location)
var config = {}
for (var key in required) {
config[key.replace(/^array\./, 'array:')] = required[key]
}
var konsole = createConsole(config)
return konsole
} |
JavaScript | function combine () {
var config = {}
Array.prototype.forEach.call(arguments, function (tconsoleInstance) {
mergeObject(config, tconsoleInstance._tconsoleConfig)
})
return createConsole(config)
} | function combine () {
var config = {}
Array.prototype.forEach.call(arguments, function (tconsoleInstance) {
mergeObject(config, tconsoleInstance._tconsoleConfig)
})
return createConsole(config)
} |
JavaScript | register(item) {
if ( ! ( item.prototype instanceof Extension ) ) {
throw 'Extension Error: Only Extensions can be registered';
}
var extension = new item(this[loggerSymbol]);
if ( typeof extension.name !== 'string' ) {
throw 'Extension Error: Extension to register must serve a name';
}
if ( typeof extension.name.length === 0 ) {
throw 'Extension Error: Extension name can not be empty';
}
if ( extension.name in this[extensionsSymbol] ) {
throw 'Extension Error: Extension name does already exists';
}
this[extensionsSymbol][extension.name] = {
class: item,
extension: extension,
booted: false,
autoDiscover: extension.autoDiscover,
};
if ( extension.autoDiscover ) {
this.discover(extension.name);
}
} | register(item) {
if ( ! ( item.prototype instanceof Extension ) ) {
throw 'Extension Error: Only Extensions can be registered';
}
var extension = new item(this[loggerSymbol]);
if ( typeof extension.name !== 'string' ) {
throw 'Extension Error: Extension to register must serve a name';
}
if ( typeof extension.name.length === 0 ) {
throw 'Extension Error: Extension name can not be empty';
}
if ( extension.name in this[extensionsSymbol] ) {
throw 'Extension Error: Extension name does already exists';
}
this[extensionsSymbol][extension.name] = {
class: item,
extension: extension,
booted: false,
autoDiscover: extension.autoDiscover,
};
if ( extension.autoDiscover ) {
this.discover(extension.name);
}
} |
JavaScript | discover(extension) {
if ( ! ( extension in this[extensionsSymbol] ) ) {
this[loggerSymbol].warn(
'Extensions Manager: Unknown extension ' + extension
);
return false;
}
var meta = this[extensionsSymbol][extension];
if ( meta.booted === true ) {
return true;
}
if ( ! ( Array.isArray(meta.extension.dependencies) ) ) {
throw 'Extensions Error: dependencies must be served as an array of extension names';
}
var manager = this;
var dependenciesMet = 0;
meta.extension.dependencies.forEach(function(extension) {
if ( typeof extension !== 'string' ) {
throw 'Extension Error: A dependency must be given as a string based name';
}
if ( manager.discover(extension) ) {
dependenciesMet++;
}
});
if ( dependenciesMet < meta.extension.dependencies.length ) {
console.log(this[extensionsSymbol]);
throw 'Extension Error: Can not resolve ' + ( meta.extension.dependencies.length - dependenciesMet ) +
' dependencies required for ' + extension
;
}
meta.extension.factorize(this[extensibleObjectsSymbol]);
this.globalize(meta.extension);
meta.booted = true;
this[loggerSymbol].debug(
'Extensions Manager: Extension discovered -> ' + meta.extension.name
);
return true;
} | discover(extension) {
if ( ! ( extension in this[extensionsSymbol] ) ) {
this[loggerSymbol].warn(
'Extensions Manager: Unknown extension ' + extension
);
return false;
}
var meta = this[extensionsSymbol][extension];
if ( meta.booted === true ) {
return true;
}
if ( ! ( Array.isArray(meta.extension.dependencies) ) ) {
throw 'Extensions Error: dependencies must be served as an array of extension names';
}
var manager = this;
var dependenciesMet = 0;
meta.extension.dependencies.forEach(function(extension) {
if ( typeof extension !== 'string' ) {
throw 'Extension Error: A dependency must be given as a string based name';
}
if ( manager.discover(extension) ) {
dependenciesMet++;
}
});
if ( dependenciesMet < meta.extension.dependencies.length ) {
console.log(this[extensionsSymbol]);
throw 'Extension Error: Can not resolve ' + ( meta.extension.dependencies.length - dependenciesMet ) +
' dependencies required for ' + extension
;
}
meta.extension.factorize(this[extensibleObjectsSymbol]);
this.globalize(meta.extension);
meta.booted = true;
this[loggerSymbol].debug(
'Extensions Manager: Extension discovered -> ' + meta.extension.name
);
return true;
} |
JavaScript | globalize(extension) {
if ( ! ( extension instanceof Extension ) ) {
throw 'Extension Error: globalize parameter must be instance of Extension';
}
var items = extension.globals(this[extensibleObjectsSymbol]);
for ( var key in items ) {
this[globalsSymbol][key] = items[key];
this[loggerSymbol].debug(
'Extensions Manager: Global "' + key + '" engaged'
);
}
} | globalize(extension) {
if ( ! ( extension instanceof Extension ) ) {
throw 'Extension Error: globalize parameter must be instance of Extension';
}
var items = extension.globals(this[extensibleObjectsSymbol]);
for ( var key in items ) {
this[globalsSymbol][key] = items[key];
this[loggerSymbol].debug(
'Extensions Manager: Global "' + key + '" engaged'
);
}
} |
JavaScript | extendClass(object, extensions) {
if ( typeof object !== 'object' ) {
throw 'Extension Error: object parameter must be an object';
}
if ( typeof extensions !== 'object' ) {
throw 'Extension Error: extensions parameter must be an object';
}
for ( var current in extensions ) {
object.prototype[current] = extensions[current];
}
} | extendClass(object, extensions) {
if ( typeof object !== 'object' ) {
throw 'Extension Error: object parameter must be an object';
}
if ( typeof extensions !== 'object' ) {
throw 'Extension Error: extensions parameter must be an object';
}
for ( var current in extensions ) {
object.prototype[current] = extensions[current];
}
} |
JavaScript | componentDidUpdate() {
if (
this.props.match.params.query !== this.state.query ||
this.props.match.params.page !== this.state.page
) {
this.updatePage()
}
} | componentDidUpdate() {
if (
this.props.match.params.query !== this.state.query ||
this.props.match.params.page !== this.state.page
) {
this.updatePage()
}
} |
JavaScript | render() {
const photos = this.props.images.map((image) => {
return (
<li key={image.id}>
<Photo src={image.src} alt="Photo pulled from the Flickr API" />
</li>
)
})
if (photos.length < 1 && !this.props.loading) {
return <NoResults />
}
return (
<div className="photo-container">
{this.props.loading ? <h3>Loading...</h3> : <ul>{photos}</ul>}
<Pagination pages={this.props.pages} match={this.props.match} />
</div>
)
} | render() {
const photos = this.props.images.map((image) => {
return (
<li key={image.id}>
<Photo src={image.src} alt="Photo pulled from the Flickr API" />
</li>
)
})
if (photos.length < 1 && !this.props.loading) {
return <NoResults />
}
return (
<div className="photo-container">
{this.props.loading ? <h3>Loading...</h3> : <ul>{photos}</ul>}
<Pagination pages={this.props.pages} match={this.props.match} />
</div>
)
} |
JavaScript | function parseJSON(json, debug) {
let parsed;
try {
parsed = JSON.parse(json);
} catch (err) {
if (debug) console.log('Cannot parse file contents');
throw err;
}
return parsed;
} | function parseJSON(json, debug) {
let parsed;
try {
parsed = JSON.parse(json);
} catch (err) {
if (debug) console.log('Cannot parse file contents');
throw err;
}
return parsed;
} |
JavaScript | function HeyzapAds_start(publisherId, options) {
if (typeof(publisherId) !== "string") {
throw new TypeError('"publisherId" must be a string');
}
if (typeof(options) !== 'undefined' && !(options instanceof HeyzapAds.Options)) {
throw new TypeError('"Options" must be an instance of HeyzapAds.Options');
}
return Common.exec(SERVICE, 'start', publisherId, options);
} | function HeyzapAds_start(publisherId, options) {
if (typeof(publisherId) !== "string") {
throw new TypeError('"publisherId" must be a string');
}
if (typeof(options) !== 'undefined' && !(options instanceof HeyzapAds.Options)) {
throw new TypeError('"Options" must be an instance of HeyzapAds.Options');
}
return Common.exec(SERVICE, 'start', publisherId, options);
} |
JavaScript | function HeyzapAds_onIAPComplete(productId, productName, price) {
if (typeof(productId) !== 'string') {
throw new TypeError('"productId" must be a string.');
}
if (typeof(productName) !== 'string') {
throw new TypeError('"productName" must be a string.');
}
if (typeof(price) !== 'number') {
throw new TypeError('"price" must be a number.');
}
return Common.exec(SERVICE, 'onIAPComplete', productId, productName, price);
} | function HeyzapAds_onIAPComplete(productId, productName, price) {
if (typeof(productId) !== 'string') {
throw new TypeError('"productId" must be a string.');
}
if (typeof(productName) !== 'string') {
throw new TypeError('"productName" must be a string.');
}
if (typeof(price) !== 'number') {
throw new TypeError('"price" must be a number.');
}
return Common.exec(SERVICE, 'onIAPComplete', productId, productName, price);
} |
JavaScript | componentDidMount() {
let myMap = L.map("leaflet-map").setView(this.props.coordinate, 16)
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(myMap);
/* The marker got error by default because it cannot detect marker images' path
* so we need to explicitly redefine it like this. Ref:
* https://leafletjs.com/examples/custom-icons/*/
L.Marker.prototype.options.icon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow,
iconSize: [24,41],
iconAnchor: [12,41],
popupAnchor: [0, -30]
});
let marker = L.marker(this.props.coordinate).addTo(myMap)
marker.bindPopup(this.props.popUpText)
/* To make sure the div is rendered before the map, otherwise the map will not
* fully rendered. If the map still not fully rendered, increase timeout. Ref:
* https://github.com/Leaflet/Leaflet/issues/4835 */
setTimeout(function(){ myMap.invalidateSize()}, 100);
} | componentDidMount() {
let myMap = L.map("leaflet-map").setView(this.props.coordinate, 16)
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(myMap);
/* The marker got error by default because it cannot detect marker images' path
* so we need to explicitly redefine it like this. Ref:
* https://leafletjs.com/examples/custom-icons/*/
L.Marker.prototype.options.icon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow,
iconSize: [24,41],
iconAnchor: [12,41],
popupAnchor: [0, -30]
});
let marker = L.marker(this.props.coordinate).addTo(myMap)
marker.bindPopup(this.props.popUpText)
/* To make sure the div is rendered before the map, otherwise the map will not
* fully rendered. If the map still not fully rendered, increase timeout. Ref:
* https://github.com/Leaflet/Leaflet/issues/4835 */
setTimeout(function(){ myMap.invalidateSize()}, 100);
} |
JavaScript | function LoginController($scope, $rootScope, $location, $http, LoginService) {
$scope.login = function() {
delete $rootScope.error;
$http({
method: 'POST',
url: 'api/auth/v1/users/signin',
headers : {'Content-Type': 'application/json', 'Authorization':'Basic ' + btoa($scope.username+':'+$scope.password)},
data: {'email':$scope.username}
}).success(function(user) {
if($rootScope.isAdmin(user)){
$rootScope.username = $scope.username;
$rootScope.password = $scope.password;
$rootScope.user = user;
$location.path("/admin/0");
} else {
$rootScope.error = "Not admin";
}
}).error(function(data, status) {
$rootScope.error = "Bad credentials";
if (status === 400){
} else if (status === 401) {
//Unauthorized - Bad credentials
} else if (status === 409) {
} else {
}
$location.path("/login");
});
};
} | function LoginController($scope, $rootScope, $location, $http, LoginService) {
$scope.login = function() {
delete $rootScope.error;
$http({
method: 'POST',
url: 'api/auth/v1/users/signin',
headers : {'Content-Type': 'application/json', 'Authorization':'Basic ' + btoa($scope.username+':'+$scope.password)},
data: {'email':$scope.username}
}).success(function(user) {
if($rootScope.isAdmin(user)){
$rootScope.username = $scope.username;
$rootScope.password = $scope.password;
$rootScope.user = user;
$location.path("/admin/0");
} else {
$rootScope.error = "Not admin";
}
}).error(function(data, status) {
$rootScope.error = "Bad credentials";
if (status === 400){
} else if (status === 401) {
//Unauthorized - Bad credentials
} else if (status === 409) {
} else {
}
$location.path("/login");
});
};
} |
JavaScript | addMenuItemLogo({logo, url, app, version, title, text, style}) {
this.addMenuItemBtn({
type:'logo',
url:url,
mode: logo,
custom: {
content:{
version:app+' '+version
}
},
text: text, //app+' '+version+' '+text,
title:title,
style:style
});
} | addMenuItemLogo({logo, url, app, version, title, text, style}) {
this.addMenuItemBtn({
type:'logo',
url:url,
mode: logo,
custom: {
content:{
version:app+' '+version
}
},
text: text, //app+' '+version+' '+text,
title:title,
style:style
});
} |
JavaScript | showMenuBar(holder,where) {
let h=document.getElementById(holder);
h.className='navbar '+where||'top';
h.appendChild(this.menu);
return h;
} | showMenuBar(holder,where) {
let h=document.getElementById(holder);
h.className='navbar '+where||'top';
h.appendChild(this.menu);
return h;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.