Google App Engine Node app not sending cookies in header

I have a Node app that I’ve deployed in Google App Engine. I am utilizing sessions in the back end to handle authorization to access certain features.

I’m using connect-pg-simple to handle my postgres datastore, and I can see in the database that sessions are being stored in it.

// Connect to DB
const pool = new Pool({ connectionString });

// Create store
const store = new (require('connect-pg-simple')(session))({pool: pool});

// Set up sessions
app.use(session({
    name: "recipebook-session",
    secret: process.env.SESSION_SECRET,
    cookie: {
        maxAge: 2592000000, // 30 days
        secure: true,
        sameSite: 'none'
    },
    saveUninitialized: false,
    store: store,
    resave: false
}));

During the login process, I save a cookie with a CSRF Token to compare with later and send the cookie back to the host:

// Generate tokens
let tokens = auth.generateTokens();

// Save CSRF to user session
req.session.csrf = tokens['CSRF'];

// Return tokens to webapp
res.send(tokens);

Client then sends back token:

// Send response to server
let data = await fetch(`https://backend.jeffreycarr.dev/auth/google/verify_login?csrf=${csrf}&code=${code}&scope=${scope}`, {credentials: 'include'});

This all works great locally, but trying to do it deployed in App Engine results in the cookie never getting set (and never being told to be set)
enter image description here

I have a feeling it has to do with the cookie needing to be secure, but I’m using a custom domain with Google and the Google managed certificates are in place. I can access any endpoints on the backend, the cookies just aren’t being set.

Best approach for utility functions import [closed]

I have some utility functions that exported in from each corresponding module:

// utility-foo.js
export function utilityFoo() {
  // some stuff
}
// utility-bar.js
export function utilityBar() {
  // some stuff
}

in order to import both functions we can use two approaches:

  1. import each function separately:
import { utilityFoo } from './utility-foo';
import { utilityBar } from './utility-bar';
  1. use utils.js module:
// utils.js
export { utilityFoo } from './utility-foo';
export { utilityBar } from './utility-bar';

and then:

import { utilityFoo, utilityBar } from './utils';

Which approach is better?

async function is looping infinitely when I try to pass its value inside a express.js router

I have a async function that gets data from an API when i try to use the function in the router it seems to loop infinitely until it exceeds the request limit to the API. also something interesting is when I try to use the same function in the same way in different router it seems to work.

problematic router:

const router=express.Router()
const getProfileData=require('../middleware/summonerData')

router.route('/').get((req,res)=>{
    res.send("ji")
}).post((req,res)=>{
    res.redirect('/summoner/'+req.body.name)
})

router.route('/:name').get(async(req,res)=>{
    const data=await getProfileData("pridestalker")
    res.render("profile",{data:data})
})

module.exports=router

getProfileData:

const key="RGAPI-234c4b58-cfc7-464e-a139-925595108827"

async function getSummonerData(Summoner){
    const response = await fetch('https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+Summoner+'?api_key='+key);
    var data = await response.json();
    return data;
    }

    async function getMatchIds(puuid){
    const response = await fetch('https://europe.api.riotgames.com/lol/match/v5/matches/by-puuid/'+puuid+'/ids?start=0&count=20&api_key='+key);
    var data = await response.json();
    return data;
    }

    async function getMatchData(matchId,puuid){    
    const response = await fetch(`https://europe.api.riotgames.com/lol/match/v5/matches/${matchId}?api_key=`+key);    
    var data = await response.json();
    let myIndex=data.info.participants.findIndex((element) => element.puuid == puuid)
    
    let matchData= {
        mystats:{victory:  data.info.participants[myIndex].win,
            champ: data.info.participants[myIndex].championName,
            champIcon: data.info.participants[myIndex].championName + '_0.jpg',
            summoner: data.info.participants[myIndex].summonerName,
            level: data.info.participants[myIndex].champLevel,
            build: { item1: data.info.participants[myIndex].item1, item2: data.info.participants[myIndex].item2, item3: data.info.participants[myIndex].item3, item4: data.info.participants[myIndex].item4, item5: data.info.participants[myIndex].item5, item6: data.info.participants[myIndex].item6, item0: data.info.participants[myIndex].item0 },
            kills: data.info.participants[myIndex].kills,
            deaths: data.info.participants[myIndex].deaths,
            assists: data.info.participants[myIndex].assists,
            kda: (data.info.participants[myIndex].kills + data.info.participants[myIndex].assists) / data.info.participants[myIndex].deaths,
            cs: data.info.participants[myIndex].totalMinionsKilled + data.info.participants[myIndex].neutralMinionsKilled
        },
        players: data.info.participants.map(element => obj =
             { team: element.teamId,
                champ: element.championName,
                champIcon: element.championName + '_0.jpg', 
                summoner: element.summonerName, 
                level: element.champLevel, 
                build: { item1: element.item1, item2: element.item2, item3: element.item3, item4: element.item4, item5: element.item5, item6: element.item6, item0: element.item0 }, 
                kills: element.kills, 
                deaths: element.deaths, 
                assists: element.assists, 
                kda: (element.kills + element.assists) / element.deaths, 
                cs: element.totalMinionsKilled + element.neutralMinionsKilled
            })
    }
   return matchData;
}

async function getProfileData(sumName){
    let summonerData = await getSummonerData(sumName);
    let puuid = summonerData.puuid;
    console.log(puuid)
    let matches = await getMatchIds(puuid);
    console.log(matches[1])
    let matchHistoryData=[];
    for(let match of matches){
        const matchData=await getMatchData(match,puuid)
        matchHistoryData.push(matchData)   
    }
    const ProfileData={
        SummonerData:summonerData,
        matchHistoryData:matchHistoryData
    }
    return ProfileData
}

module.exports=getProfileData;

index.js(server):

const express=require("express")
const app=express()

app.use(express.urlencoded({extended:true}))

app.set("view engine","ejs")
app.use(express.static(__dirname + '/public'));
app.get('/',(req,res)=>{
    res.render('home.ejs')
})

const tierListRouter=require('./routes/tierlist')
app.use("/tierlist",tierListRouter)
const summonersRouter=require('./routes/summoner')
app.use('/summoner',summonersRouter)

app.listen(3000)

working router:

const express=require('express')
const router=express.Router()
const getProfileData=require('../middleware/summonerData')

router.route('/').get(async(req,res)=>{
    const data=await getProfileData("pride")
    res.render("tier-list",{data:JSON.stringify(data)})
})
module.exports=router

bower fails with Repository not found

In the project there is package.json and bower.json with this content:

{
  "name": "project-name",
  "dependencies": {
    "paho-mqtt": "*"
  }
}

There is also ember-cli-build.js with:

app.import('bower_components/paho-mqtt/src/mqttws31.js');

When I run yarn I get the following error:

bower paho-mqtt#* ECMDERR Failed to execute "git ls-remote --tags --heads https://github.com/larrytin/paho.mqtt.javascript.git",
exit code of #128 remote: Repository not found. fatal: Authentication failed for 'https://github.com/larrytin/paho.mqtt.javascript.git/'

There is no such repository or is private: https://github.com/larrytin?tab=repositories

However, npm points to https://github.com/eclipse/paho.mqtt.javascript

Output of bower search paho.mqtt:

    paho-mqtt https://github.com/larrytin/paho.mqtt.javascript.git
    paho-mqtt-cli-js https://github.com/jgsantos/paho-mqtt.git
    bower-paho-mqtt https://github.com/larrytin/paho.mqtt.javascript.git
    paho.mqtt.js https://github.com/huangguozhen/paho.mqtt.js.git
    paho-mqtt-js https://github.com/StickmanVentures/paho-mqtt-js.git
    eclipse-paho-mqtt-js http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.javascript.git
    mqtt https://github.com/mqttjs/MQTT.js.git
    angular-paho https://github.com/bipolalam/angular-paho.git
    tsante-mqtt https://github.com/telecomsante/tsante-mqtt.git
    mqtt-wildcard https://github.com/hobbyquaker/mqtt-wildcard.git
    mqtt-q https://github.com/quentinlampin/mqtt-q.git
    mqtt-elements https://github.com/mqttjs/mqtt-elements.git
    mqtt-client https://github.com/centamiv/mqtt-client.git
    MQTT-bootstrap https://github.com/PCaponetti/MQTT-bootstrap.git
    mqtt-angularjs https://github.com/truongducanhskt/mqtt-angularjs.git
    angular-mqtt https://github.com/shellus/angular-MQTT.git
    angularjs-mqtt https://github.com/thanhson1085/angularjs-mqtt.git
    mqtt-connection https://github.com/sandro-k/mqtt-connection.git
    mqtt-elements-2 https://github.com/mozeal/mqtt-elements.git
    io-angular-mqtt https://github.com/jledun/angular-mqtt.git
    web-mqtt-client https://github.com/orbitbot/web-mqtt-client.git
    mqtt-browser-ws https://github.com/chenhuang511/mqtt-browser-ws.git
    aws-mqtt-browser https://github.com/komushi/aws-mqtt-browser.git
    simple-js-mqtt-client https://github.com/tebemis/simple-js-mqtt-client.git
    anh-mqtt-service-ws https://github.com/truongducanhskt/anh-mqtt-service-ws.git
    ng-mqtt https://github.com/vasco-santos/ngmqtt.git
    mqtt-browser https://github.com/sadeqzadeh/mqttjs-browser.git
    aws-iot-mqtt-websocket-sdk-js https://github.com/tapasbose/aws-iot-mqtt-websocket-sdk-js.git
    paho-script-only https://github.com/EMNico/mqttws31.git

There is no https://github.com/eclipse/paho.mqtt.javascript.git on this list above.

I removed paho-mqtt from bower.json and executed: npm i paho-mqtt --save-dev.

Then when I ran yarn start I got this error:

ENOENT: no such file or directory, open '/var/folders/58/4d0cprgn18b8v9yptpgnrk1r0000gp/T/broccoli-44755Swg20IggAAbv/out-272-broccoli_debug_debug_2_vendor_js/bower_components/paho-mqtt/src/mqttws31.js'

Any suggestion how to fix this problem?

Does the return statement work differently when the function is called outside the app server in Node.js/Express [duplicate]

So I have this function I am calling outside of my app.js, it’s another JavaScript file

const Lodash = require("lodash")
module.exports.postExist = function(posts, req) {
  let postValue = []
  posts.forEach(post => {
      if (Lodash.lowerCase(req.params.postName.toLowerCase()) === Lodash.lowerCase(post.title.toLowerCase())) {
        postValue = post;
        console.log(postValue + "inside");
        return true;
      }
    }
  );

  console.log("outside");
  return false
}

Console log

[object Object]inside
outside

The return value of this function is giving me false which I don’t understand because the if statement is executed at some point from what I’m getting from the console log [object Object]inside, why isn’t my function returning true and exiting the function. Why is it continuing the execution to my other return value?

mathjs intellisense does not work in vscode

I have just installed nodejs.

I want to calculate an average so i have required mathjs. I know i can use other methods, but this is convenient.

const mathjs = require('mathjs')

Unlike other modules (builtin modules or my user defined modules), i do not see the intellisense pop up, which rather bothers me as i cannot see all the methods available.

Things i have tried:

  1. closing and reopening vscode
  2. npm install mathjs (local install)
  3. npm -g install mathjs (global install)
  4. restarting windows

I have tried to tinker with the vscode settings, but since it works for everything else, i am averse to making too many random guesses.

I have visited the official page (https://www.npmjs.com/package/mathjs) but do not see anything that gives me a better clue. So now i am stuck.

How can i get the intellisense working for this module (assuming that it is possible) ?

TypeError: ProductManager is not a constructor

i have a file in JS where i define a constructor and some methods ( add, get, etc)
when i try to call it from another JS file i receive the message from the title: TypeError: ProductManager is not a constructor

const fs = require('fs')
const filename = './productos.json'

class ProductManager {
    products

    constructor() {
        this.products = []
    }

    #generateID = () => {
        if (this.products.length === 0) return 1
        return this.products[this.products.length - 1].id + 1
    }

    addProduct(title, description, price, image, code, stock) {
        const id = this.#generateID()
        const product = {id, title, description, price, image, code, stock}

        // Valido que el producto tenga todos los campos
        if (!title || !description || !price || !image || !code || !stock) {
            return console.log('Error: Todos los campos son obligatorios')
        }

        //Valido que el producto ingresado no exista
        const productExists = this.products.some((product) => product.code === code)
        if (productExists) {
            return console.log('Error: El producto ya existe')
        } else {
            this.products.push(product)
            fs.writeFileSync(filename, JSON.stringify(this.products, null, 't'))
        }
    }

    getProducts() {

        // return this.#products

        const contenido = JSON.parse(fs.readFileSync(filename, 'utf-8'))
        console.log(" Muestro el contenido del archivo Productos", contenido)
    }

The second file where i call this JS is:

const express = require('express');

const app = express();

const ProductManager = require('./productos.js');

app.get('/', (request, response) => {
    response.send('<h1 style="color:goldenrod">Bienvenidos a la pagina de productos!!</h1>');
})

app.get('/products', (request, response) => {
    const productManager = new ProductManager()
    productManager.getProducts()
    response.send({
        message: "success",
        data: productManager.getProducts()
    })
})


app.listen(8080, () => {
    console.log("Servidor corriendo en http://localhost:8080");
})

the error is on the line const productManager = new ProductManager()

i don’t know where to start.

Remove Hash # from Js file

iam new at wordpress World and iam using Plugin to add product to my Blog,
this plugin use Tabs to show up the product,
but when i press Tabs (Overview-Specs-Reviews),
The URL becomes: https://telfonak.com/clon0ed-infinix-hot-10s/#aps-specs
https://telfonak.com/clon0ed-infinix-hot-10s/#aps-overview

i want to remover # from URL But keep everything work as normal, i contact the develpoder of plugin and he told me to edit aps-main-script-min.js to remove it ,iam sorry i have 0 knowlagde of JS..
so i need any help
here is the file:

/* APS Products JavaScripts /
!function(t){“use strict”;var a=”rtl”==t(“html”).attr(“dir”)?”rtl”:”ltr”;function e(t){return t?aps_vars.comp_link+function(t){if(t)return new Hashids(aps_vars.comp_cn,10).encode(t)}(t)+”/”:aps_vars.comp_link}function s(a,e,s){if(“success”==a)var i=”+e+””;else if(“error”==a)i=”+e+””;else i=e;t(“body”).append(”+i+””);var n=t(“.aps-res-msg”),r=t(“.aps-msg-overlay”),o=n.outerHeight()/2,p=n.outerWidth()/2;function l(){n.fadeOut(“slow”,function(){t(this).remove(),r.fadeOut(“fast”,function(){t(this).remove()})})}n.css({marginTop:”-“+o+”px”,marginLeft:”-“+p+”px”}),r.fadeIn(200),n.fadeIn(300),s&&setTimeout(l,3e3),t(“.aps-close-box”).click(l)}function i(e){if(aps_vars.show_panel){var s=t.cookie(aps_vars.comp_cn);if((s?s.split(“,”):[]).length>0){t(“.aps-comps-overlay”).length||t(“body”).append(”),t(“.aps-comps-overlay”).addClass(“aps-comps-loading”);var i={action:”aps-comps”,pos:s,active:t(“.aps-comps-list.active-list”).data(“id”)};t.ajax({url:aps_vars.ajaxurl,type:”GET”,data:i,beforeSend:function(){1==e&&(“rtl”==a?t(“.aps-comps-overlay”).animate({left:”-262px”},200):t(“.aps-comps-overlay”).animate({right:”-262px”},200))},success:function(a){a&&t(“.aps-comps-overlay”).html(a)},complete:function(){1==e&&(t(“.aps-comps-handle”).addClass(“opened”),”rtl”==a?t(“.aps-comps-overlay”).animate({left:”0″},300):t(“.aps-comps-overlay”).animate({right:”0″},300)),t(“.aps-comps-overlay”).removeClass(“aps-comps-loading”)}})}else”rtl”==a?t(“.aps-comps-overlay”).animate({left:”-262px”},300,function(){t(this).remove()}):t(“.aps-comps-overlay”).animate({right:”-262px”},300,function(){t(this).remove()})}}t(window).on(“load scroll rating”,function(){t(‘[data-bar=”true”]’).each(function(){t(this).apsAnimateBar(3e3)}),t(‘[data-bar=”false”]’).each(function(){var a=t(this).find(‘[data-type=”bar”]’),e=a.data(“width”);a.css(“width”,e)})}),t(“.aps-tooltip”).on({mouseenter:function(){var e=t(this).next(“.aps-tooltip-data”).html(),s=t(“.aps-tooltip-display”);t(“body”).append(”+e+””).show(300),t(document).on(“mousemove”,function(e){var i=e.pageY+20,n=e.pageX+15;if(“rtl”==a){var r=t(window).width()-n;s.css({top:i,right:r})}else s.css({top:i,left:n})})},mouseleave:function(){t(“.aps-tooltip-display”).hide(50,function(){t(this).remove()})}}),t.fn.apsIsVisible=function(){var a=t(window),e={top:a.scrollTop(),left:a.scrollLeft()};if(e.right=e.left+a.width(),e.bottom=e.top+a.height(),this.is(“:visible”)){var s=this.offset();return s.right=s.left+this.outerWidth(),s.bottom=s.top+this.outerHeight(),!(e.right<s.left||e.left>s.right||e.bottom<s.top||e.top>s.bottom)}},t.fn.apsAnimateBar=function(a){var e=this.find(‘[data-type=”num”]’),s=this.find(‘[data-type=”bar”]’),i=this.data(“rating”),n={num:i,wid:10
i};s.apsIsVisible(!0)&&!this.hasClass(“aps-animated”)&&(this.addClass(“aps-animated”),t({num:0,wid:0}).animate(n,{duration:a,step:function(){e.html(Number(this.num.toFixed(1))),s.css(“width”,this.wid+”%”)}}))},t.cookie=function(t,a,e){if(arguments.length>1&&(null===a||”object”!=typeof a)){e=jQuery.extend({},e);if(null===a&&(e.expires=-1),”number”==typeof e.expires){var s=e.expires,i=e.expires=new Date;i.setDate(i.getDate()+s)}return document.cookie=[encodeURIComponent(t),”=”,e.raw?String(a):encodeURIComponent(String(a)),e.expires?”; expires=”+e.expires.toUTCString():””,e.path?”; path=”+e.path:””,e.domain?”; domain=”+e.domain:””,e.secure?”; secure”:””].join(“”)}var n,r=(e=a||{}).raw?function(t){return t}:decodeURIComponent;return(n=new RegExp(“(?:^|; )”+encodeURIComponent(t)+”=([^;])”).exec(document.cookie))?r(n[1]):null},t(document).on(“change”,”.aps-compare-cb”,function(a){var e=t(this),s=e.val().toString(),n=e.data(“ctd”).toString(),r=e.parent(“.aps-compare-btn”);r.data(“title”);e.is(“:checked”)?(t.apsAddToCompare(s,n),setTimeout(function(){r.find(“.aps-compare-txt”).text(aps_vars.comp_rem)},500)):(t.apsRemoveFrmCompare(s,n),setTimeout(function(){r.find(“.aps-compare-txt”).text(aps_vars.comp_add)},500)),i(!0)}),t(document).on(“click”,”.aps-add-compare”,function(a){a.preventDefault();var s=t(this),i=s.data(“pid”).toString(),n=s.data(“ctd”).toString(),r=s.data(“reload”),o=(s.data(“title”),t.apsAddToCompare(i,n));void 0!==r&&1==r&&setTimeout(function(){location=e(o)},1e3)}),t(document).on(“click”,”.aps-remove-compare”,function(a){a.preventDefault();var s=t(this),n=s.data(“pid”).toString(),r=s.data(“ctd”).toString(),o=s.data(“load”),p=t.apsRemoveFrmCompare(n,r);if(void 0!==o&&1==o)setTimeout(function(){location=e(p)},1e3);else{var l=t(“input[name=’compare-id-“+n+”‘]:checkbox”),c=l.parent(“.aps-compare-btn”);l.prop(“checked”,!1),setTimeout(function(){c.find(“.aps-compare-txt”).text(aps_vars.comp_add)},500),i(!0)}}),t.apsAddToCompare=function(a,e){var s=””,i=t.cookie(aps_vars.comp_cn);if(i){for(var n=””,r=i.split(“,”),o=(r=t.grep(r,function(t){return t}),0);o<r.length;o++){var p=r[o],l=p.split(““);if(l[0]===e){s=l[1];n=p}}if(s=s.split(“-“),s=t.grep(s,function(t){return t}),t.inArray(a,s)<0){s.push(a);var c=s.join(“-“);c=(c=[e,c]).join(““),s.length>1?r[r.indexOf(n)]=c:r.push(c),h=(r=t.grep(r,function(t){return t})).join(“,”),t.cookie(aps_vars.comp_cn,h,{expires:7,path:”/”})}}else{s=a;var h=e+”“+a;t.cookie(aps_vars.comp_cn,h,{expires:7,path:”/”})}return s},t.apsRemoveFrmCompare=function(a,e){for(var s=t.cookie(aps_vars.comp_cn).split(“,”),i=(s=t.grep(s,function(t){return t}),””),n=””,r=0;r<s.length;r++){var o=s[r].split(““);o[0]===e&&(i=o[1],n=o)}i=i.split(“-“),(i=t.grep(i,function(t){return t})).splice(t.inArray(a,i),1);var p=i.length>0?e+”“+i.join(“-“):””;s[s.indexOf(n.join(““))]=p;var l=(s=t.grep(s,function(t){return t})).join(“,”);return t.cookie(aps_vars.comp_cn,l,{expires:7,path:”/”}),i},t(document).on(“mouseenter touchstart”,”.aps-dropdown”,function(){t(this).find(“ul”).stop().slideDown()}),t(document).on(“mouseleave touchend”,”.aps-dropdown”,function(){t(this).find(“ul”).stop().slideUp()}),t(document).on(“click”,”.aps-display-controls li a”,function(a){var e=t(“.aps-products”);t(“.aps-display-controls li a”).removeClass(“selected”),t(this).addClass(“selected”),t(this).hasClass(“aps-display-list”)?(e.removeClass(“aps-products-grid”).addClass(“aps-products-list”),t.cookie(“aps_display”,”list”,{expires:30,path:”/”})):(e.removeClass(“aps-products-list”).addClass(“aps-products-grid”),t.cookie(“aps_display”,”grid”,{expires:30,path:”/”})),a.preventDefault()}),t(document).on(“submit”,”#apsReviewForm”,function(a){var e=t(this),i=e.find(“.aps-button”),n=e.serialize();t.ajax({url:aps_vars.ajaxurl,type:”POST”,data:n,dataType:”json”,beforeSend:function(){i.hide(),i.after(”)},success:function(t){t.success?(s(“success”,t.success,!0),e.trigger(“reset”)):s(“error”,t.error,!0)},complete:function(){i.next(“.aps-loading”).remove(),i.show()}}),a.preventDefault()}),t(document).on(“click”,”.aps-comps-handle”,function(){t(this).hasClass(“opened”)?(t(this).removeClass(“opened”),”rtl”==a?t(this).parent().animate({left:”-262px”},200):t(this).parent().animate({right:”-262px”},200)):(t(this).addClass(“opened”),”rtl”==a?t(this).parent().animate({left:”0″},300):t(this).parent().animate({right:”0″},300))}),t(window).on(“load”,function(){i(!1)}),t(document).on(“click”,”.aps-comps-nav span”,function(a){var e=t(this),s=t(“.aps-comps-list.active-list”);s.removeClass(“active-list”),e.hasClass(“aps-comps-next”)?s.next(“.aps-comps-list”).length>0?s.next(“.aps-comps-list”).addClass(“active-list”):t(“.aps-comps-list:first”).addClass(“active-list”):e.hasClass(“aps-comps-prev”)&&(s.prev(“.aps-comps-list”).length>0?s.prev(“.aps-comps-list”).addClass(“active-list”):t(“.aps-comps-list:last”).addClass(“active-list”))}),t(document).on(“click”,”.aps-table-fold”,function(a){var e=t(this),s=e.find(“.aps-tb-fold-open”),i=e.find(“.aps-tb-fold-close”),n=e.parent().find(“.aps-attr-infold”);n.hasClass(“aps-attr-exfold”)?(n.removeClass(“aps-attr-exfold”),s.css(“display”,”block”),i.css(“display”,”none”)):(n.addClass(“aps-attr-exfold”),s.css(“display”,”none”),i.css(“display”,”block”)),a.preventDefault()})}(jQuery),jQuery(document).ready(function(t){“use strict”;if(t(“.aps-tab-container”).hasClass(“aps-tabs-init”)){var a=window.location.hash;a?(t(a).show(),t(“.aps-tabs li[data-id='”+a+”‘]”).addClass(“active”)):(t(“.aps-tab-content:first”).show(),t(“.aps-tabs li:first”).addClass(“active”),t(“.aps-tabs-bottom li:first”).addClass(“active”)),t(“ul.aps-tabs li”).on(“click”,function(a){var e=t(this),s=e.data(“id”);t(“ul.aps-tabs li”).removeClass(“active”),t(“.aps-tabs li[data-id='”+s+”‘]”).addClass(“active”);var i=e.find(“a”).attr(“href”);t(i).fadeIn(300),t(“.aps-tab-content”).not(i).hide(),t(“html, body”).animate({scrollTop:t(i).offset().top-80},500),history.pushState?history.pushState(null,null,i):window.location.hash=i,t(window).trigger(“rating”),a.preventDefault()})}if(t(“.aps-main-image”).hasClass(“aps-main-img-zoom”)){var e=ImageViewer();t(“.aps-main-image”).on(“click”,function(){var a=t(this).find(“.aps-image-zoom”),s=a.attr(“src”),i=a.data(“src”);e.show(s,i)})}t(‘[data-carousel=”1″]’).each(function(){var a=t(this),e={items:a.data(“items”)?a.data(“items”):4,autoplay:1===a.data(“auto”),autoplayTimeout:a.data(“timeout”)?1e3a.data(“timeout”):5e3,autoplayHoverPause:1===a.data(“hover”),loop:1===a.data(“loop”),nav:1===a.data(“nav”),margin:a.data(“margin”)?a.data(“margin”):10,rtl:”rtl”==t(“html”).attr(“dir”),navText:a.data(“navtext”)?a.data(“navtext”):[“‹”,”›”],responsive:a.data(“responsive”)?a.data(“responsive”):{0:{items:3},768:{items:4}}};a.owlCarousel(e)});var s=[];t(“.aps-image-gallery”).on(“click”,”img”,function(a){var e=t(this),i=t(“.aps-img-loader”),n=t(“.aps-image-zoom”),r=n.attr(“src”),o=e.data(“src”);if(t.inArray(r,s)<0&&s.push(r),n.data(“src”)!=o){n.data(“src”,o).attr(“src”,o);o.match(/./(.)$/)[1];t.inArray(o,s)<0&&(i.fadeIn(50),n.on(“load”,function(){i.fadeOut(300)})),t(“.aps-thumb-item”).removeClass(“active-thumb”),e.parent().addClass(“active-thumb”)}});var i=t(“.aps-product-videos”);if(1===i.data(“enable”)){var n=i.data(“effect”),r=1===i.data(“nav”),o=1===i.data(“close”);t(“.aps-lightbox”).nivoLightbox({effect:n,keyboardNav:r,clickOverlayToClose:o})}var p=function(a){var e=a.parent().attr(“id”),s=parseInt(a.val()),i=parseInt(a.attr(“max”)),n=parseInt(a.data(“min”)),r=t(“#apsReviewForm”).data(“color”),o=”rtl”==t(“html”).attr(“dir”)?”left”:”right”;if(s<n){a.val(n).trigger(“change”);var p=100n/i}else p=100s/i;var l=”#”+e+” input::-webkit-slider-runnable-track {background: linear-gradient(to “+o+”, “+r+” 0%, “+r+” “+p+”%, #e5e6e7 “+p+”%, #e5e6e7 100%);}”;if(t(“#style-“+e).length>0)document.getElementById(“style-“+e).textContent=l;else{var c=document.createElement(“style”);c.setAttribute(“id”,”style-“+e),document.body.appendChild(c),c.textContent=l}};t(“.aps-range-slider-range”).each(function(){var a=t(this),e=parseInt(a.val());a.next().html(e),p(a),a.on(“input change”,function(){var a=t(this),e=0,s=0,i=parseInt(a.val());a.next().html(i),p(a),t(“.aps-range-slider-range”).each(function(){e+=Number(t(this).val()),s++});var n=(e/s).toFixed(1).replace(/.0$/,””);t(“.aps-total-score”).text(n)})})}),function(t,a){if(“function”==typeof define&&define.amd)define([“module”,”exports”],a);else if(“undefined”!=typeof exports)a(module,exports);else{var e={exports:{}};a(e,e.exports),t.Hashids=e.exports}}(this,function(t,a){“use strict”;Object.defineProperty(a,”__esModule”,{value:!0});var e=function(){function t(t,a){for(var e=0;e<a.length;e++){var s=a[e];s.enumerable=s.enumerable||!1,s.configurable=!0,”value”in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(a,e,s){return e&&t(a.prototype,e),s&&t(a,s),a}}(),s=function(){function t(){var a=arguments.length<=0||void 0===arguments[0]?””:arguments[0],e=arguments.length<=1||void 0===arguments[1]?0:arguments[1],s=arguments.length<=2||void 0===arguments[2]?”abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890″:arguments[2];!function(t,a){if(!(t instanceof a))throw new TypeError(“Cannot call a class as a function”)}(this,t);var i=””,n=void 0,r=void 0;this.escapeRegExp=function(t){return t.replace(/[-[]{}()*+?.,^$|#s]/g,”$&”)},this.parseInt=function(t,a){return/^(-|+)?([0-9]+|Infinity)$/.test(t)?parseInt(t,a):NaN},this.seps=”cfhistuCFHISTU”,this.minLength=parseInt(e,10)>0?e:0,this.salt=”string”==typeof a?a:””,”string”==typeof s&&(this.alphabet=s);for(var o=0;o!==this.alphabet.length;o++)-1===i.indexOf(this.alphabet.charAt(o))&&(i+=this.alphabet.charAt(o));if(this.alphabet=i,this.alphabet.length<16)throw”error: alphabet must contain at least X unique characters”.replace(“X”,16);if(-1!==this.alphabet.search(” “))throw”error: alphabet cannot contain spaces”;for(var p=0;p!==this.seps.length;p++){var l=this.alphabet.indexOf(this.seps.charAt(p));-1===l?this.seps=this.seps.substr(0,p)+” “+this.seps.substr(p+1):this.alphabet=this.alphabet.substr(0,l)+” “+this.alphabet.substr(l+1)}this.alphabet=this.alphabet.replace(/ /g,””),this.seps=this.seps.replace(/ /g,””),this.seps=this._shuffle(this.seps,this.salt),(!this.seps.length||this.alphabet.length/this.seps.length>3.5)&&(n=Math.ceil(this.alphabet.length/3.5))>this.seps.length&&(r=n-this.seps.length,this.seps+=this.alphabet.substr(0,r),this.alphabet=this.alphabet.substr(r)),this.alphabet=this._shuffle(this.alphabet,this.salt);var c=Math.ceil(this.alphabet.length/12);this.alphabet.length<3?(this.guards=this.seps.substr(0,c),this.seps=this.seps.substr(c)):(this.guards=this.alphabet.substr(0,c),this.alphabet=this.alphabet.substr(c))}return e(t,[{key:”encode”,value:function(){for(var t=arguments.length,a=Array(t),e=0;e<t;e++)a[e]=arguments[e];if(!a.length)return””;if(a[0]&&a[0].constructor===Array&&!(a=a[0]).length)return””;for(var s=0;s!==a.length;s++)if(a[s]=this.parseInt(a[s],10),!(a[s]>=0))return””;return this._encode(a)}},{key:”decode”,value:function(t){return t&&t.length&&”string”==typeof t?this._decode(t,this.alphabet):[]}},{key:”encodeHex”,value:function(t){if(t=t.toString(),!/^[0-9a-fA-F]+$/.test(t))return””;for(var a=t.match(/[wW]{1,12}/g),e=0;e!==a.length;e++)a[e]=parseInt(“1″+a[e],16);return this.encode.apply(this,a)}},{key:”decodeHex”,value:function(t){for(var a=[],e=this.decode(t),s=0;s!==e.length;s++)a+=e[s].toString(16).substr(1);return a}},{key:”_encode”,value:function(t){for(var a=void 0,e=this.alphabet,s=0,i=0;i!==t.length;i++)s+=t[i]%(i+100);for(var n=a=e.charAt(s%e.length),r=0;r!==t.length;r++){var o=t[r],p=n+this.salt+e;e=this._shuffle(e,p.substr(0,e.length));var l=this._toAlphabet(o,e);if(a+=l,r+1<t.length){var c=(o%=l.charCodeAt(0)+r)%this.seps.length;a+=this.seps.charAt(c)}}if(a.length<this.minLength){var h=(s+a[0].charCodeAt(0))%this.guards.length,d=this.guards[h];(a=d+a).length<this.minLength&&(h=(s+a[2].charCodeAt(0))%this.guards.length,a+=d=this.guards[h])}for(var u=parseInt(e.length/2,10);a.length<this.minLength;){var f=(a=(e=this._shuffle(e,e)).substr(u)+a+e.substr(0,u)).length-this.minLength;f>0&&(a=a.substr(f/2,this.minLength))}return a}},{key:”_decode”,value:function(t,a){var e=[],s=0,i=new RegExp(“[“+this.escapeRegExp(this.guards)+”]”,”g”),n=t.replace(i,” “),r=n.split(” “);if(3!==r.length&&2!==r.length||(s=1),void 0!==(n=r[s])[0]){var o=n[0];n=n.substr(1),i=new RegExp(“[“+this.escapeRegExp(this.seps)+”]”,”g”),r=(n=n.replace(i,” “)).split(” “);for(var p=0;p!==r.length;p++){var l=r[p],c=o+this.salt+a;a=this._shuffle(a,c.substr(0,a.length)),e.push(this._fromAlphabet(l,a))}this._encode(e)!==t&&(e=[])}return e}},{key:”_shuffle”,value:function(t,a){var e=void 0;if(!a.length)return t;for(var s=t.length-1,i=0,n=0,r=0;s>0;s–,i++){i%=a.length,n+=e=a.charAt(i).charCodeAt(0);var o=t[r=(e+i+n)%s];t=(t=t.substr(0,r)+t.charAt(s)+t.substr(r+1)).substr(0,s)+o+t.substr(s+1)}return t}},{key:”_toAlphabet”,value:function(t,a){var e=””;do{e=a.charAt(t%a.length)+e,t=parseInt(t/a.length,10)}while(t);return e}},{key:”_fromAlphabet”,value:function(t,a){for(var e=0,s=0;s<t.length;s++){e+=a.indexOf(t[s])*Math.pow(a.length,t.length-s-1)}return e}}]),t}();a.default=s,t.exports=a.default});

How would I calculate the broadcast week of a given date within Javascript

I am working on a program that needs to calculate the broadcast week of a given date in order to extract information from an API. Broadcast week calculation is a little different than week numbers, the 1st of January is always in week 1, and then the calendar iterates from there.

Here is a link to the broadcast calendar for 2023 and 2022 respectively, they are a little funky:
https://www.rab.com/public/reports/2023.pdf

https://www.rab.com/public/reports/2022.pdf

I have tried using various formulas, however nothing seems to be working. Has anyone else tried to calculate this, and if so what was your approach?

Any help is greatly appreciated.

I want animate scrollleft += a variable but i cant seem to make it work without a specific number

pls help.

right now I have a button that scrolls a div 500 and sets the current position to 500. I need to replace the 500 by a variable number. so += a variable number. Any help would be much appreciated.

$('#button').click(function() {
  $('#row_01').animate({
    scrollLeft: '+=500'
  }, 1000);
});

$('#button_alt').click(function() {
  $('#row_01').animate({
    scrollLeft: '-=500'
  }, 1000);
});

I want to scroll the div a percentage distance on click.

server and web client by websocket

Hello I have a server code in python and a web client in js. I am trying to use secure websocket. But I cannot make them connected. Do I miss some configuration here? Is it because I am doing ssl? Because I am asked to use secure websocket so I have to add it.
My server code:

import asyncio, websockets, functools, ssl, logging
from dotenv import dotenv_values
from server_func import handle_question_wrapper
import nest_asyncio

nest_asyncio.apply()


def initialize():
    config = dotenv_values("../.env")
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ssl_context.load_cert_chain("../server.crt", "../server.key")

    config["ssl_context"] = ssl_context

    return config


async def run(config):
    start_server = websockets.serve(
        functools.partial(handle_question_wrapper, config=config),
        "localhost",
        443,
        ssl=config["ssl_context"],
        ping_interval=None
    )

    start_server.ws_server.check_origin = True
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()


if __name__ == "__main__":
    logger = logging.getLogger("websocket_server")
    logging.basicConfig(
        format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S"
    )
    config = initialize()

    asyncio.run(run(config))

My web client code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Websocket Client</title>
    <script>
      var ws;

      function connect() {
        ws = new WebSocket("wss://127.0.0.1:443");
        ws.onopen = function () {
          console.log("Websocket connected!");
        };
        ws.onmessage = function (event) {
          console.log("Received message: ", event.data);
        };
      }

      function sendMessage() {
        var message = document.getElementById("message").value;
        ws.send(message);
        console.log("Sent message: ", message);
      }
    </script>
  </head>
  <body onload="connect()">
    <input type="text" id="message" />
    <button onclick="sendMessage()">Send</button>
  </body>
</html>

Would you mind giving some advice?

Authorization token not being sent to backend

I am trying to create a store, and I’m currently working on the front end wishlist, using redux. I am trying to configure the add to wishlist, but for some reason, I keep getting the error that I did not give it a token. Everything else works the way it should.

Here is my add to wishlist service:

const addWishItem = async (id, token) => {
  const config = {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  };

  const response = await axios.post(`${wishData}/add-wish/${id}`, config);

  return response.data;
};

and this is my add to wishlist slice:

export const addToWishlist = createAsyncThunk(
  "wish/addWishItem",
  async (id, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return wishService.addWishItem(id, token);
    } catch (error) {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message;
      return thunkAPI.rejectWithValue(message);
    }
  }
);

Class attribute becoming undefined after javascript

class MyQueue {
    contructor() {
        this.inputStack = new MyStack();
        this.outputStack = new MyStack();
    }

    push(val) {
        this.inputStack.push(val);
    }

    pop() {
        if(this.outputStack.empty()) {
            const { inputStack, outputStack} = moveInputToOutput(
                this.inputStack,
                this.outputStack,
            );
            this.inputStack = inputStack;
            this.outputStack  = outputStack;
        }   
       return this.outputStack.pop();
    }

    peek() {
        if(this.outputStack.empty()) {
            const { inputStack, outputStack} = moveInputToOutput(
                this.inputStack,
                this.outputStack,
            );
            this.inputStack = inputStack;
            this.outputStack  = outputStack;
        }   
       return this.outputStack.top();
    }

    empty() {
        return this.inputStack.empty() && this.outputStack.empty();
    }

}

const moveInputToOutput = (inputStack, outputStack) => {
    while(!inputStack.empty()) {
        const inputvalue = inputStack.pop();
        outputStack.push(inputvalue);
    }
    return {
        inputStack,
        outputStack,
    };
 }


class MyStack {
    constructor() {
        this.first = null;
        this.size = 0;
    }

    push(value) {    
        const node = new Node(value);
        node.next = this.first;
        this.first = node;
        this.size++;
    }
    
    pop() {
        const node = this.first;
        this.first = this.first?.next ? this.first.next: null;
        this.size = this.size == 0 ? 0 : --this.size;
        return node?.value
    }
    
    empty() {
        return this.first === null;
    }

    top() {
        const node = this.first;
        return node?.value;
    }
}

class Node {
    constructor(value){
        this.value = value;
        this.next = null;
    }
}

Getting an error of

Line 9 in solution.js
        this.inputStack.push(val);
                        ^
TypeError: Cannot read properties of undefined (reading 'push')
    Line 9: Char 25 in solution.js (MyQueue.push)
    Line 105: Char 26 in solution.js (helper_select_method)
    Line 169: Char 22 in solution.js (Object.<anonymous>)
    Line 16: Char 8 in runner.js (Object.runner)
    Line 100: Char 26 in solution.js (Object.<anonymous>)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)

I am calling myQueue class to create an object to make the object, but when calling the push function from the stack class, it is making the this variable a undefined, trying to understand why, can anybody help me on this, looks like maybe a very minor issue, not able to find for hours

How can i make the window.print() function look “prettier” in my html page?

I was trying to print a table i created using pandas in my html page, so i used the window.print() function, the problem is that it doesn’t have neither the bottom line nor the middle line between all the rows of the table.

The code i’m using to generate the table in my python script is:
` df = pd.DataFrame({‘Nome’: lnome, ‘CEP’: lcep, ‘CPF / CNPJ’: lcpfcnpj, ‘Status’:lstatus, ‘Estado’:lestado, ‘Cidade’:lcidade})
#alf / lcl / cep
if ordem == “alf”:
df = df.sort_values(by=[‘Nome’, ‘Estado’, ‘Cidade’, ‘Status’])
elif ordem == “lcl”:
df = df.sort_values(by=[‘Estado’, ‘Cidade’, ‘Nome’, ‘Status’])

global finaltable
finaltable = df.to_html(classes='table', index=False)`

And the code i’m using in html to print is:
` function imprimir() {
// Hide the top bar
document.getElementsByClassName(‘bar’)[0].style.display = ‘none’;

        window.print()
        document.getElementsByClassName('bar')[0].style.display = 'flex';
    }`

But when i try to print it turns from this: How it looks like on my html page

To this: How it looks like after i use window.print()

I tried looking for diferent ways to print my html page but none of them were less “bugged”

Note that i DON’T want to adjust the font, the font color or anything, just the “bars” or “lines” that were supposed to be between the rows and at the bottom of the table (my main problem is the bottom)

Thanks in advice

How can I get all values from a specific key in mongoose?

I got a few documents in mongoose that looks something like this:

[
    {
        _id = "...",
        name = "abc123",
        colors = [1, 2, 3]
    },
    {
        _id = "...",
        name = "def431",
        colors = [4, 2, 1]
    },
    {
        _id = "...",
        name = "htl534",
        colors = [3, 5, 7]
    },
    {
        _id = "...",
        name = "lwq154",
        colors = [9, 1, 4]
    }
]

From these documents I’d like to get an array with all the values from the keys named name, it would look something like this: ["abc123", "def431", "lwq154"]. How could I achive this? I thought about using some sort of querys or some find function, but I can’t seem to figure it out.