Skip to main content

Posts

Showing posts from January, 2023

Trying to make a scrollable table with tkinter [duplicate]

I'm trying to make a scrollable grid table. I had a look at some answers and it seems the way is to make a Frame , then put a Canvas and a Scrollbar next to eachother and apply some commands for scrolling. I have this code here, but I can't figure out what is wrong with this. import tkinter as tk class Test: def __init__(self): self.root = tk.Tk() table_and_scrollbar_frame = tk.Frame(self.root) table_frame = tk.Canvas(table_and_scrollbar_frame) table_frame.grid(row=0, column=0) self.table_headers = ["header_1", "header_2", "header_3", "header_4"] for test_row in range(0,100): for header_to_create in self.table_headers: current_entry = tk.Entry(table_frame, width=25, justify='center') current_entry.insert(0, header_to_create + " " + str(test_row)) current_entry.configure(state='disable...

Selectize.js adds item immediately after removal

I want an element to be removed from the list by clicking on it in the selectize-dropdown-content So that the elements do not disappear after adding from the list, I used hideSelected: false, The click event doesn't work on this elements, I can't catch it The problem is that after my code works and the element is removed, onItemAdd immediately works and it is added to the list again) I have this code: $(document).on('mousedown',function (e){ if ($(e.target).hasClass('option') && $(e.target).hasClass('selected')){ var value = $(e.target).attr("data-value"); var control = $(e.target).parents('.selectize-control').siblings('.selectized')[0].selectize; control.removeItem(value); control.refreshItems(); control.refreshOptions(); } }); i tried to catch click events or something but they don't apply to these elements Via Active questions ta...

How to implement a while loop into this code

I'm currently trying to code this area calulator but I'm having a hard time understanding how to implement a while loop, any help would be appreciated. I have tried looking into loops but I'm not quite understanding how to write them even after watching some YouTube videos. def calculate_square_area(side:float): return side * side def calculate_rectangele_area(length:float, width:float): return length * width def calculate_circle_area(radius:float): pi = 3.14 return pi * radius **2 def calculate_rhombus_area(p: float, q: float): return p*q/2 print(""" --------------- Area Calculator --------------- """) selection = input("""\t 'S' - Square \t 'R'- Rectangle \t 'C'- Circle \t 'H'- Rhombus """) def calculate_area(selection): area = 0 if selection == "S": side =input("Enter The Side:") area = calculate_square_area(f...

OpenCV Python remove object/pattern from images

I have been facing this problem from some days: i need to remove this image/pattern from images like this or this using OpenCV. I know that the problem is a Template Matching problem and I have to use filters (like canny) and and "slide" the template over the image, once this has been transformed by the filters. I tried some solutions like this or this , but i had poor results, for example applying the second method I obtain this images 1 2 this is my code import cv2 import numpy as np # Resizes a image and maintains aspect ratio def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA): # Grab the image size and initialize dimensions dim = None (h, w) = image.shape[:2] # Return original image if no need to resize if width is None and height is None: return image # We are resizing height if width is none if width is None: # Calculate the ratio of the height and construct the dimensions ...

how can i hide an element on screen with reactjs

I would like a text to be displayed on the screen and only be hidden when pressing a button, but I don't know how. I thought of using useState like this: const [textVisibility, setTextVisibility] = useState(true) <button onClick={() => setTextVisibility(false)} /> the problem I found is that when clicking on the button the page will be rendered again and the visibility value will be the default value (true). How can I do that? Via Active questions tagged javascript - Stack Overflow https://ift.tt/8jkC3iR

How to make sticky image swap text look better on mobile view?

I am a beginner and want to make this sticky image look better on mobile. As you scroll, the image is in a fixed position and changes once it reaches a certain point and correlates with the related text. However, it look good on desktop as a two column layout, but I want the text to span wider than it is on mobile. Any help appreciated, thanks https://jsfiddle.net/g67j5nLm <div class="locker"> <div class="locker__image"> <div class="locker__container"> <img class="image image--1" src="https://assets.codepen.io/325536/placeimg_480_720_tech.jpg"> <img class="image image--2" src="https://assets.codepen.io/325536/tech.jpeg"> </div> </div> <div class="locker__content"> <div class="locker__section locker__section--1 cb" data-swap="image--1"> <h3>01</h3> <p>Lorem ipsum dolor sit...

AWS lambda stuck importing library

I am trying to deploy my ECR image to aws lambda. The image works fine locally, but on aws, it gets stuck importing this library https://github.com/jianfch/stable-ts . import json import boto3 import requests import numpy print("All imports ok 1 ...") from stable_whisper import load_model print("All imports ok 2 ...") The first statement is printed but it gets stuck on importing and the second statement never got printed until it timed out. Docker File: # Build FFmpeg FROM public.ecr.aws/lambda/python:3.8 as lambda-base COPY requirements.txt ./ COPY myfunction.py ./ RUN pip3 install -r requirements.txt WORKDIR /ffmpeg_sources RUN yum install autoconf automake bzip2 bzip2-devel cmake libxcb libxcb-devel \ freetype-devel gcc gcc-c++ git libtool make pkgconfig zlib-devel -y -q # Compile NASM assembler RUN curl -OL https://www.nasm.us/pub/nasm/releasebuilds/2.15.05/nasm-2.15.05.tar.bz2 RUN tar xjvf nasm-2.15.05.tar.bz2 RUN cd nasm-2.15.05 && sh aut...

Getting Nuxt error handling function with Apache

Try to learn Nuxt, some wine and some water as a Swedish proverb says. I got som problem with the error handling, when I build app (no problem in dev). Looks like it do not live so good with Apache and its htaccess file. This is my htaccess: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> The basic error handling function (error.vue in site root), for an example if I go to http://nuxtshop.localhost/xyz/zyz , it triggers. But its the error with createError function that do not trigger right, it just redirect to home and then I get a blank page (actually the default.vue layout, no slot populated). For an example I have a product page with this code, were I try to handle if the product do not exist (url, i.e. params do not exist). Script: <script setup> const { id } = useRoute().params; const runtimeConfig = use...

Why is my Node.js api not added to swagger?

I'm trying to add Swagger to my apis in my Node.js project. I have the following project structure: ▼ src ▼ app ▼ api ▼ routes GroupsRoutes.js main.js My main.js file is inside the src folder on the same level as the app folder. The GroupsRoutes.js file looks like this: const express = require('express'); const { default: mongoose } = require('mongoose'); const router = express.Router(); const Groups = require('../../models/group'); const Devices = require('../../models/device'); const Applications = require('../../models/application'); /** * @swagger * /api/organizations/:orgId/groups: * get: * description: Get all groups * responses: * 200: * description: Success */ router.get('/organizations/:orgId/groups', async (req, res) => { try { const orgId = req.params.orgId; let groups; groups = await Groups.find({ orgId: orgId }); ...

Create non strait forawrd SqlAlchemi relationship

I have 2 SqlAlchemy entities: study and series with 1 to many relation (study has many series). I crearted a relationship that way: class SeriesDBModel(Base): __tablename__ = "series" series_uid = Column(String, primary_key=True) study_uid = Column(String, ForeignKey(StudyDBModel.study_uid)) study = relationship("StudyDBModel", lazy="subquery", cascade="all") class StudyDBModel(Base): __tablename__ = "study" study_uid = Column(String, primary_key=True) My question is: Do I have to create the entities like this: series = SeriesDBModel() study = StudyDBModel() series.study = study Or Can I just create both entities independently but with the same study_uid? I'm asking because the second way i how I save my entities but using series.study returns None . BTW, it's not a "sessio.commit()" issue. I'm verifing both entities exist in the DB before trying series.study.. I tried to fetch se...

Handle re-calling a function inside useEffect when "Back Button" clicked from a user in React

I'm trying to not call loadUserPosts() function again if the user clicks the 'back button' on his browser. I think this is because of the isLogged useState because is changing when clicking the back button. The loadUserPosts function is inside an useEffect only if the user is logged, so I have this: In Posts.js component I have this: import { useState, useEffect } from "react"; import { AuthUseContext } from '../context/AuthContext'; import Axios from 'axios'; function Posts() { const [posts, setPosts] = useState([]); const { isLogged, setIsLogged, userData, setUserData } = AuthUseContext(); useEffect(() => { if(isLogged) { loadUserPosts(); } }, [isLogged]); // my API request to load all user posts function loadUserPosts() { Axios.post('/posts/load', { user: userData.id }).then((response) => { if(response.data.status === "su...

mock a service with Jest

Trying to write a test to provide code coverage for the following code : note : there are other functions in the service but just listing one for brevity. export const service = { getById: async (id) => { const url = `/api/customers/${id}/names` const {data} = await axios.get(url, axiosOptions); return data; } I'm attempting to simply provide code coverage with this test: note : I have attempted to use require instead of import but that does not seem to work. import {service} from './requests'; it("mocks the getById function", () => { service.getById = jest.fn(); expect(service.getById.mock).toBeTruthy(); } This test passes however seems to provide no code coverage. I've attempted to mock out the axios call but I seem to get nowhere as examples I've found of implementations are not working for me currently. Does anyone have ideas and an example how I could provide code coverage for the service please? Update ...

python property class namespace confusion

I am confused about use of property class with regard to references to the fset/fget/fdel functions and in which namespaces they live. The behavior is different depending on whether I use property as a decorator or a helper function. Why do duplicate vars in class and instance namespaces impact one example but not the other? When using property as a decorator shown here I must hide the var name in __dict__ with a leading underscore to prevent preempting the property functions. If not I'll see a recursion loop. class setget(): """Play with setters and getters""" @property def x(self): print('getting x') return self._x @x.setter def x(self, x): print('setting x') self._x = x @x.deleter def x(self): print('deleting x') del self._x and I can see _x as an instance property and x as a class property: >>> sg = setget() >>> sg.x = 1 settin...

how to comparing two slightly different strings and return Percent likeness between the two strings

I need to comparing two slightly different strings and return Percent likeness between the two strings This could have been easier for two strings of same length. But what if the length is different? For Example : I like to help everybody Hi I would like to help every coder A simple logic would be to compare each word in first sentence with same position word of different sentence. But in this case the length is different. So how do I proceed? Any help would be appreciated. Via Active questions tagged javascript - Stack Overflow https://ift.tt/FTH1t2w

How to properly organize mobx data structure in react app with complex hierarchy

I'm writing an app with react framework, mobx state manager and using typescript. The application includes a left menu and a workspace in the form of tabs. As in the picture below. Visual representation of the application Each tab contains its own content. As in any browser.Tabs can be created by clicking on the menu button, as well as by clicking on the button from the content of the tab itself. For example, we open the first tab. Its content is a table that contains information about some list of elements. We can edit each element by clicking on the "Edit" button, this should open a new tab. Table with editable data Thus we get a hierarchical structure. Also, the same tabs should manage one global storage. What MobX data structure would you suggest to use for such an application? At the moment, I came up with the following data structure Based on the MVVM pattern. There is a global tab manager which has the following methods: add tab, remove tab and set current open ...

Can only get one single document by id in a Firestore collection

I am stuck with a very strange bug and I can't understand why it is happening. I have a collection in the Google Firestore called previews , in the collection, I have 4 documents that I manually inserted into the Firestore with automatically generated ids. When I try to get the documents by id, only one of them is retrievable from the JavaScript side. I've been able to reproduce the problem with the query builder of the Firestore: You can clearly see the documents here with their ids. When I query BEOEGqnl7wBXCB6G4RLP , it works: But when I query any other document, I get no result, even though they do exist! I tried to change the properties of the documents, I also thought it may be some invisible space, but I checked that too. I don't see any difference between the documents, except for the data that's in them. Any idea of what could be wrong? Thank you! Via Active questions tagged javascript - Stack Overflow https://ift.tt/FTH1t2w

is there away to convert the relative path for image to a local host URL using parcel?

I 'm using parcel to bundle my project, the src attribute need to be converted from relative path to local host path by parcel. so I 'm looking for a solution for this problem. class SectionResoursesView { generateMarkup(data) { let markup = ``; data.map(res => { markup += ` <div class="col-4"> <div class="resource"> <a href="${res.url}" target="_blank" class="resource__link" > <img src="../img/logos/codepen.png" alt="${res.logo.alt}" class="resource__image" /> <span class="resource__title">${res.name}</span> </a> </div> </div> `; }); return markup; } } export default new SectionResoursesView(); I expected that I can find away to achieve this problem, and I can convert relative path ...

Giving Multiple Buttons an EventListener

I'm making a website that includes carousels and buttons. When you click the buttons it moves the carousel to the left or right to see more or previous content. I made it at first by creating two functions, one for the button that goes back and one for the button that goes forward. It worked, but I realized that I needed to make it for All of the buttons since I had multiple carousels. var nextButton = document.querySelectorAll('.button-forward'); var backButton = document.querySelectorAll('.button-back'); nextButton.addEventListener('click', function() { itemContainer.style.transform = 'translateX(-40%)'; }); backButton.addEventListener('click', function() { itemContainer.style.transform = 'translateX(10%)'; }); I tried storing all the forward and backward buttons with document.querySelectorAll and gave them a forEach method where in it is the event listener for them. The other two carousel buttons still weren't working, ...

Running pyinstaller on code containing relative paths

I have a large python codebase developed inside PyCharm. I want to use PyInstaller for obvious reasons; however, I'm struggling with relative paths for data files due to the project code file hierarchy. The file hierarchy was a usual top-down structure, i.e., the point of execution is within a file found in the project root folder, with the additional python files stored in a sensible folder, (please pay particular attention to the version.txt file on the same level as the Main.py file) e.g., Project/ --Main.py --version.txt --Engines/ ----somefile.py --Controllers/ ----somefile.py --Entities/ ----somefile.py A year ago, I built a GUI front end whilst maintaining the console-based point of execution. The GUI point of execution is within MainGUI.py. But that file is not at the project root. It looks a bit like this: Project/ --Main.py --version.txt --GUI/ ----MainGUI.py --Engines/ ----somefile.py --Controllers/ ----somefile.py --Entities/ ----somefile.py Inside MainGUI.py, I h...

BingX api how to trade order in perpetual swap api v2?

I'm trying to place a new order using BingX API in python but I get this response: {"code":100001,"msg":"","success":false,"timestamp":1674818924644} I use the following code to trade a new order: import urllib.request import json import base64 import hmac import time import json APIURL = "https://open-api.bingx.com" APIKEY = "MyApiKEY" SECRETKEY = "MySecretKey" def genSignature(paramsStr): return hmac.new(SECRETKEY.encode("utf-8"), paramsStr.encode("utf-8"), digestmod="sha256").digest() def post(url, body): req = urllib.request.Request(url, headers={ 'User-Agent': 'Mozilla/5.0', 'X-BX-APIKEY': APIKEY, }, method="POST") return urllib.request.urlopen(req).read() def tradeOrder(symbol, side, tradeType): paramsMap = { "symbol": symbol, "side": side, ...

Python Tkinter dialing functionality

I am creating a GUI application using Tkinter that has a number pad and output of dialed numbers after pushing respective buttons. I've searched a little on Tkinter labels and appending them but I can't seem to find anything that works for what I need. I made a function called AppendDialEntry() and assigned that function to each button with the symbol as a passed parameter to append what is already in the label. Here is a sample of the Append function: def AppenddialEntry(string): dialInput = dialEntry.cget("text") + string dialEntry.config(text=dialInput) dialEntry = tk.Label(root, text="") dialEntry.grid(row=0, column=4) And here is one of the buttons: number_3 = tk.Button(root, text="3", command=AppendDialEntry("3")) I am also attaching the GUI to show what I am getting. source https://stackoverflow.com/questions/75268763/python-tkinter-dialing-functionality

How to shuffle cards - JavaScript

I'm trying to make a card matching game in JavaScript where every time the user starts the game, the cards shuffle. If they flip two of the same cards the get a point added to their score. I have the card matching aspect working using a data framework on each card div, but this immediately invoked shuffle card function I've added isn't working. Thank you in advance! JavaScript of Shuffling the Cards: const cards = document.querySelectorAll(".the-card"); (function shuffle() { cards.forEach(card => { let randomPos = Math.floor(Math.random() * 12); card.style.order = randomPos; }); })(); HTML of Each Card(16 in total): <div class="main-card-container"> <div class="the-card" data-framework="twoofhearts"> <div class="the-back card-face"> <img src="./images/cardback.png" class="flipped-card" </div> <div class="the-front card-face"> ...

Unexpected Characters During Reading a WAVE File

I've started to design an audio signal analyser and at first, I wanted to start from the basics. One of those first steps is to plot audio samples versus time. I've written the code below to show whole data inside (both file format and audio data) a voice recording of a WAVE file. That 5-second long audio file is created by using 44.1 kHz of sampling frequency, 16-bit integers to represent samples, 1024 frames and two channels (i.e., stereo). import sys import wave import pyaudio with wave.open("Recording-1.wav", "rb") as file: f = pyaudio.PyAudio(); FRAMES = 1024; # Frames are used to fit in them file information without loading up all of them onto a single variable and possibly exceeding a pre-specified memory allocation of it. whole_data = wf.readframes(FRAMES); print(whole_data); wf.close(); After running the script, I've gathered an output which includes characters in hexadecimal numbers that ...

How to use class based views in FastAPI?

I am trying to use class based views in my FastApi project to reduce redundancy of code. Basically I need CRUD functionality for all of my models and therefor would have to write the same routes over and over again. I created a small example project to display my progress so far, but I ran into some issues. I know there is this Fastapi-utils but as far as I understand only reduces the number of Dependencies to call and is no longer maintained properly (last commit was March 2020). I have some arbitrary pydantic Schema/Model. The SQLAlchemy models and DB connection are irrelevant for now. from typing import Optional from pydantic import BaseModel class ObjBase(BaseModel): name: Optional[str] class ObjCreate(ObjBase): pass class ObjUpdate(ObjBase): pass class Obj(ObjBase): id: int A BaseService class is used to implement DB access. To simplify this there is no DB access right now and only get (by id) and list (all) is implemented. from typing import Any, Generic...

In Pygame, when building a character, why are we using x,y when we are already giving the width and height?

the pygame code I am not understanding why we are putting x,y when we already have width and height for the character. Just wanted to know what's the use of x,y in here? source https://stackoverflow.com/questions/75258780/in-pygame-when-building-a-character-why-are-we-using-x-y-when-we-are-already-g

'form.save(commit=True)' not saving to database

I am trying to use a ModelForm to create a new model in my database. The thing is, it's not saving it to there when I call form.save(commit=True) . I am using Elastic Beanstalk (the free tier) to host my website. I feel like this has something to do with the problem. This is my forms.py : from datetime import date from .models import Itinerary class CreateItinerary(forms.ModelForm): class Meta: model = Itinerary exclude = ["sights"] destination = forms.CharField(max_length=100) start = forms.DateField(widget=forms.NumberInput(attrs={'type': 'date'}), initial=date.today) end = forms.DateField(widget=forms.NumberInput(attrs={'type': 'date'})) class FindPlaces(forms.Form): types = ((1, "restaurants"), (2, "attractions"), (3, "parks"), (4, "national parks"), (5, "clothing stores"), (6, "malls"), (7, "departme...

Creating a Binary Search Tree visualizer using javascript css and Html

I was looking to create a binary search tree visualizer, like in visualalgo.net in which I generate 10 random elements in javascript and those elements get used as values for the nodes to create a binary search tree. My problem is I am not able to figure out the logic for correctly positioning the elements so that it looks like a bst. For example a value smaller than the root must be placed to the left, a little to the bottom as compared to the root, wheras a larger value must be placed to the right and so on using CSS Using javascript I created 10 random elements and created as many division HTML elements, using Javascript's method of createElement(), as the number of random Elements. The divs innerText was set to the random values by iterating through a loop. HTML: <div class="elements"> </div> JavaScript let nodeElements = document.querySelector(".elements") const randomArr = []; for (let i = 0; i < 10; i++) { let randomValue = Math.fl...

Discord.js : Trying to export client from ./index.js, but it keeps saying client is undefined

I'm currently coding a discord bot using node.js, I wanted to create a command that sends a dm to a certain user, but I can't get my client variable into the needed file. Here's my code in index.js // my index.js file client.login(token) module.exports = client; // my sendMessage.js file const bot = require("../index"); module.exports = { data: new SlashCommandBuilder() .setName('new-command') .setDescription('some description'), async execute(interaction) { // interaction.guild is the object representing the Guild in which the command was run bot.users.cache.get('439484647022526465').send("test"); } }; Via Active questions tagged javascript - Stack Overflow https://ift.tt/W9ytHld

How can I give discord users with a specific role limitations?

I want to limit the actions of users on a discord server that are interacting with a discord bot for a specific time. As an example: The user with the role "user" can only press a button 10 times in a day (24h). A other user with the role "user2" can press the button 20 times in a day. After that the user gets a message that he reached the daily limit. How can I do that in js? I couldn't find anything about the topic. Via Active questions tagged javascript - Stack Overflow https://ift.tt/W9ytHld

How to randomly pick key from dict and change value?How to randomly pick key and change value?

I want to randomly select an animal and if there is no value 0 then decrease the value by 1. I want to repeat the action twice. Try: animals = { "pets": {"dog": 2, "cat": 1, "mouse": 0}} a = random.choice(list(animals["pets"])) but this only displays the name of the animal. I would like to get a result like this: dog 1, cat 0, mouse 0 How to do it? Thank you and best regards. source https://stackoverflow.com/questions/75251242/how-to-randomly-pick-key-from-dict-and-change-valuehow-to-randomly-pick-key-and

Random image load works fine offline, but not on website

This code works perfectly fine by itself but as soon as I embed it into a website it no longer loads an image on page load. Why? How can it be improved? My guess is the susceptible windowon.load . Maybe it can be substituted? //$(document).ready(function(){choosePic;} //alert(window.onload); //https://stackoverflow.com/questions/2810825/javascript-event-window-onload-not-triggered; window.onload = choosePic; var onloadd = window.onload; var myPix = new Array( "https://m.box.com/file/903146245504/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png", "https://m.box.com/file/1055524661946/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png", "https://m.box.com/file/896387464705/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png" ); function choosePic() { var randomNum = Math.floor(Math.random() * myPix.length); document.getElementById("myPic...

DataFrame and multiprocessing in python

I had done a exercise in python and came across with the following problem: enter image description here And this is my code: enter image description here Someone can me help with this? I used jupyter-notebook, pandas and multiprocessing in python. I tried to change the number of wokers, but even though didn't work. I expected that the function populate the new_df with the informations that I requested. source https://stackoverflow.com/questions/75250631/dataframe-and-multiprocessing-in-python

Cannot assign to global variable in on_ready()

I am trying to code a discord bot that simultaneously prints new messages and sends user input from console to a selected channel. Here is what I have so far: import discord from threading import Thread from asyncio import run intents = discord.Intents.all() intents.members = True client = discord.Client(intents=intents,chunk_guilds_at_startup=False) main_channel = int(input('Enter channel ID you want to chat in: ')) channel = 613 @client.event async def on_ready(): global channel channel = await client.fetch_channel(main_channel) async def send(): while True: await channel.send(input('Send a message: ')) z = Thread(target=lambda:run(send())) z.start() try: client.run('##########################') except discord.errors.HTTPException: from os import system system('kill 1') I get TypeError: 'int' object has no attribute 'send' on line 42. Why is the global variable not getting assigned to in on_ready()? source...

I want to a create a moving label

import tkinter as tk from tkinter import * import keyboard import time a = 120 root = tk.Tk() root.state('zoomed') root.configure(bg='white') root.resizable(False, False) a = 30 x = 0 def increase(): global a a += 10 def ar(): for i in range(50): labele1.place(x=120, y=a) root.after(1000, increase) c1 = Canvas(root, width=700, height=700, bg='gray95') c1.place(x=450, y=60) labele1 = tk.Label(c1, text='_______', font='Calibri 20') startbutton = tk.Button(text='BaÅŸla', command=ar) startbutton.pack() root.mainloop() I want to create a moving label which moves per second. Everything looks clear but it doesn't work well. I want to make a car race app but first the walls should move back and it exit the project source https://stackoverflow.com/questions/75238632/i-want-to-a-create-a-moving-label

Javascript how to redirect to another website and send the JWT as bearer token as well

I need to redirect to another website and send the JWT as a bearer token as well. Can I use fetch to do it? Something like this: $( document ).ready( function() { document.getElementById('Aother-Website-Link').addEventListener('click', event => { event.preventDefault(); fetch('Aother-Website-Link', { mode: "cors", method: "GET", headers: { 'Authorization': `Bearer ${jwt}` } }) .then(() => { window.location.href = 'Aother-Website-Link'; }) .catch(error => { console.error(error); }); }); Via Active questions tagged javascript - Stack Overflow https://ift.tt/1xz7Tfd

Python Pandas Extract text between words and symbols with regex

I am trying to extract certain words between some text and symbol using regex in Python Pandas. The problem is that sometimes there are non-characters after the word I want to extract, and sometimes there is nothing. Here is the input table. Here is the expected output. I've tried this str.extract(r'[a-zA-Z\W]+\s+Reason to buy:([a-zA-Z\s]+)[a-zA-Z\W]+\s+') but does not work. Any advice is appreciated. Thanks. source https://stackoverflow.com/questions/75238599/python-pandas-extract-text-between-words-and-symbols-with-regex

Library Client side test with local web server

I'm starting in JavaScript test environment. There are a lot of tools out there and I don't really know what to chose for my needs. I'm creating a library to download/upload files from browser with encryption feature. I'll the example of the upload test here. I need to test the upload function with a local server to upload the file then compare this file to the original one / decrypt it if the file is encrypted during the process to compare hashes. I couldn't find a simple way to actually run browser test and nodejs tests within the same test. I came to the solution of running my server before launching the client and then send the results through http requests. Is it a good test architecture or is there any better solution? Thank you for your attention Via Active questions tagged javascript - Stack Overflow https://ift.tt/1xz7Tfd

Why is my insertRow method adding blank cells to my table?

I am trying to add the results from a fetch request into a new row in a table. However, When I run the function to do that, the first click adds a blank row instead of adding my desired data. Additionally, the data that I would have liked to add gets added the next time the function is ran. I have no idea what is wrong and I have tried so many things. I believe this problem is causing my other function called "total()" to return an error as the first cell is undefined instead of containing a value. Here is my javascript: document.getElementById('getFood').addEventListener('click', getFood); document.getElementById('getFood').addEventListener('click', total); /*function getText() { $.ajax({ method: 'GET', url: 'https://api.api-ninjas.com/v1/nutrition?query=' + document.getElementById('foodInput'), headers: { 'X-Api-Key': 'vrtwcc/pVgAr2o/a4dEyYA==hR1m7lLVdU4ho4hW' }, contentT...

How to assign values a backshifted array inside np.where?

I'm trying to write a values from other arrays without using for and if s. Say we got multiple arrays, want to check condition and later assign values to new array. Better explained in code. What I want to do so this for and ifs but in np.where way import numpy as np arr = np.array([np.nan, np.nan, 30, 60, 5, 10, 55]) up_arr = np.array([np.nan, np.nan, 100, 110, 120, 130, 140]) down_arr = np.array([np.nan, np.nan, 90, 100, 110, 120, 130]) result = np.full_like(arr, np.nan, dtype=float) result2 = np.full_like(arr, np.nan, dtype=float) for i in range(1, len(arr)): if arr[i] >= 50: if up_arr[i] < result[i - 1]: result[i] = result[i - 1] else: result[i] = up_arr[i] else: if down_arr[i] > result[i - 1]: result[i] = result[i - 1] else: result[i] = down_arr[i] result2[i] = result[i - 2] print(result) print(result2) Listing 1: For-if code output is: [ nan nan 90. 110. 1...

Mapping array inside another array using spread operator

I'm testing spread operator inside array to map another array values. Unfortunately, I have come up with weird behavior or I did it wrong. When I return 2 objects using map inside the array, it's only returning the last object. Code below: const cats = ["Tom", "Ginger", "Angela"]; const array = [ // { // name: "Ben", // sex: "male" // }, ...cats.map((element, index, array) => { return ( { name: element, sex: element !== "Angela" ? "male" : "female" }, { age: element !== "Angela" ? "20" : "18", color: element === "Tom" ? "black" : element === "Ginger" ? "orange" : "white" } ); }) ]; console.log(array); In console: [{"age":"20","color":"black...

Creating a new Awkward array from indices

The problem I am facing is to create a new array from a set of indices. Namely, I have a set of particles and jets, for each jet there is a list of indices of which particles belong to the given jet. import awkward as ak import vector particles = ak.Array({ "mass": ak.Array([1, 2, 3, 4, 5]), "px": ak.Array([1, 2, 3, 4, 5]), "py": ak.Array([1, 2, 3, 4, 5]), "pz": ak.Array([1, 2, 3, 4, 5]), }) particles_p4 = vector.awk(ak.zip({ "mass": particles["mass"], "x": particles["px"], "y": particles["py"], "z": particles["pz"] })) jet = ak.Array({ "constituents": ak.Array([[1, 2, 4, 5], [3]]), "energy": ak.Array([1.2, 3.4]) }) What I would like to get is for each jet the particle_p4 values in a new array like so: <Array [[{x: 1, y: 1, z: 1,...

How can i delete this collection in firebase? [duplicate]

i recently began to use firebase and i ran into a problem, to get it straight, i want to make a e-commerce site, ofcourse it has cart, i used firebase for my back-end, for every user, i create a document in "users" collection, each user's document id is the uid of that given user. On every document, i have a cart, and in the cart, the products, on my cart page, i want to have a "Empty Cart" that deletes all the products, meaning it deletes "cart" collection. How can i do that? I have left some photos below that will probably explain the problem better. Image of the firebase tree I tried this and it did not work! const deleteCart = async () => { const cartDoc = `users/${user.uid}/cart` await deleteDoc(db, cartDoc) } i get this error : " TypeError: Cannot use 'in' operator to search for '_delegate' in undefined " Via Active questions tagged javascript - Stack Overflow https://ift.tt/MSBcpkj

How to use Peer.js in Next.js with TypeScript?

Next.js runs on server side also, so Peer.js raise error when using Next.js. Here one says: https://stackoverflow.com/a/66292100/239219 this is probably because peer js is performing some side effect during import. He propose this: useEffect(() => { import('peerjs').then(({ default: Peer }) => { // Do your stuff here }); }, []) But I need DataConnection as using Typescript, and also asign it to a useState. would you show an example how? This is what I put togeter, but TypesScript raise errors: useEffect(() => { import('peerjs').then(({ default: Peer, DataConnection }) => { const peer = new Peer(localStorage.token) peer.on('connection', (conn: DataConnection) => { console.log('Connected to peer:', conn) conn.on('data', (data) => { console.log('Received data:', data) }) }) retu...

Can't train model from checkpoint on Google Colab because those all deleted after a few hours

I'm using Google Colab for finetuning a pre-trained model. I successfully preprocessed a dataset and created an instance of the Seq2SeqTrainer class: trainer = Seq2SeqTrainer( model, args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], data_collator=data_collator, tokenizer=tokenizer, compute_metrics=compute_metrics ) But the problem is training it from last checkpoint after the session is over. If I run trainer.train() it runs well. As it takes long time I came back to Colab tab after a few hours. I know that if session got crashed I can continue training from last checkpoint like this: trainer.train("checkpoint-5500") But the problem is that those checkpoint data no longer exist on Google Colab if I came back too late, so even though I know till what point training has been done, I will have to start all over again? Is there any way to solve this problem? source https://...

Barista BOT functioning from my mobile but not from else's mobile [closed]

I have created a Barista BOT. Further, I have set up the function in BOT to 'Log Incoming Text Messages in Google Sheets'. When I use my mobile number to send message to Twilio number to operate the BOT, I get all response from BOT and also storage of chosen drink in google sheet. But when I use some one else's mobile to send message to Twilio number, I get no response from BOT. When I check the 'Executions' under Logs for BOT, I see that the BOT is under execution. I stop it manually by pressing the 'Stop Execution' option. The Error logs under monitoring in Console gives 'Error - 81002'- Message Unexpected event Error Description An unexpected event was received while processing a widget. Studio ignored this event and did not transition to another widget because there was no matching transition available to handle the event. Note: If the Execution ended correctly, this warning can be ignored. The function that I am using is as below - const...

Complete In-Depth Reading/Tutorials/Guide for Full-Stack Development? [closed]

Are there any resources out there that really get in depth about a true full-stack for building web or mobile applications? I know about MERN/MEAN stack which includes: M - MongoDB - used to host your data E - Express - middleware to spin up a server R/A - React/Angular - used to build the front-end through components (Made up of HTML, CSS, JS) N - Node - I think of it as an easy way to keep track of and download dependencies instead of going through one by one. It makes it easier for multiple people to use and start working locally. An index in a ways to your project. However, this doesn't really cover anything like testing, CI/CD, Docker, Kubernetes, pipelines(yml), Schemas, version control hosting(GitHub/GitLab/Bitbucket), git vs yarn, etc. Maybe this is what DevOps is? I am sure I am missing a few things, but is there anything like that out there, or do I just have to piece it together as I do my own research? It would also be good to know alternatives, like git vs yarn, Mon...

How can I bucket/bin a dataframe in python based on the year?

Let's say I have a very simple dataframe with one column, year. There would be 14 distinct years, from 2010 to 2023. I would need to bin/bucket these years into three categories, 'old', 'medium', and 'new' where new would be the 3 most recent years (2023,2022,2021), medium would be 2015-2020, and old would be 2010-2014. How would I do this? source https://stackoverflow.com/questions/75203610/how-can-i-bucket-bin-a-dataframe-in-python-based-on-the-year

Extended FastAPI OAuth2PasswordRequestForm

So, to register a user, I needed some additional fields that were not in the standard form: @router.post("/sign-up/", response_model=TokensScheme) async def sign_up(form_data: OAuth2PasswordRequestForm = Depends(), email: str = Body(), first_name: str | None = Body(default=None), second_name: str | None = Body(default=None), session: Session = Depends(get_db)): repository = UsersRepository(session) repository.create( User( email=email, username=form_data.username, password=get_password_hash(form_data.password), first_name=first_name, second_name=second_name, is_active=False, ) ) return sign_in(form_data, session) This route successfully fulfills its task, however, I did not really like adding fields in this way and I decided to extend the standard form as follows: class UserBaseScheme(BaseModel): ...