Skip to main content

Posts

Showing posts from November, 2022

Convert Playwright DOMSnapshot.captureSnapshot to javascript native code

I'm trying to convert the following code snippet: self.client = self.page.context.new_cdp_session(self.page) self.client.send( "DOMSnapshot.captureSnapshot", {"computedStyles": [], "includeDOMRects": True, "includePaintOrder": True}, ) Into native javascript that I could run within a chrome extension. How would I do that? For added context, I will need to be able to index into the results like so: strings = tree["strings"] document = tree["documents"][0] nodes = document["nodes"] backend_node_id = nodes["backendNodeId"] attributes = nodes["attributes"] node_value = nodes["nodeValue"] parent = nodes["parentIndex"] node_types = nodes["nodeType"] node_names = nodes["nodeName"] is_clickable = set(nodes["isClickable"]["index"]) text_value =

Comma separated number after specific substring in middle of string

I need to extract a sequence of coma separated numbers after specific substring. When the substring is in the beginning of the string it works fine, but not when its in the middle. The regex 'Port':\ .([0-9]+) works fine with the example below to get the value 2 . String example: {'Port': '2', 'Array': '[0, 0]', 'Field': '[2,2]', 'foo': '[0, 0]' , 'bar': '[9, 9]'} But i need to get Field value, I dont care if its '[2,2]' or 2,2 (string or number) I tried various attempts with regex calculator, but couldnt find a solution to return the value after string in middle of the text. Any ideas? Please help. Thanks ahead, Nir source https://stackoverflow.com/questions/74632019/comma-separated-number-after-specific-substring-in-middle-of-string

@event bloque ma commande en python

Bonjour à tous ! Je débute en python et j'essaye actuellement de m'entrainer à faire un petit bot discord. Cependant je suis confronté à un problème que je n'arrive pas à résoudre. J'ai créer un @event afin d'envoyer un message lorsque l'on mentionne quelqu'un sur discord et j'ai également créer un @commands qui me permet de faire un !rm pour supprimer des messages d'une conversation. Malheureusement quand je lance mon code ma commande rm ne fonctionne plus alors que mon event lui fonctionne encore. Quand je commente mon event la commande rm fonctionne. Pouvez vous m'aider s'il vous plait ? Merci d'avance :) Code : # -*- coding: UTF-8 -*- import os import discord import random import message_by_name from discord.ext import commands from discord import message bot = commands.Bot(intents=discord.Intents.all(), command_prefix = "!", description = "couteau suisse") @bot.event async def on_ready(): print("Le

'RecursionError' in a for loop

I have tried to implement a flatten function to even flatten strings but got an error for Recursion. Could someone help resolve this puzzle? def flatten(items): for x in items: if isinstance(x, Iterable): yield from flatten(x) else: yield x items = [2, [3, 4, [5, 6], 7], 8, 'abc'] for x in flatten(items): print(x) I was expecting to print '2, 3, 4, 5, 6, 7, 8, a, b, c'; but instead, I got '2, 3, 4, 5, 6, 7, 8 and a RecursionError. I think the 'abc' is also 'Iterable', so why the code doesn't work? Thank you! source https://stackoverflow.com/questions/74633320/recursionerror-in-a-for-loop

I want to use google cloud firestore for my html website

I am new to web development and I want to use firestore in a seperate js file. I kept searching for answers everywhere, and after almost 2 hours, my frustration led me to write this question. Here's the situation: I'm using a simple html/css/js format for my website, no webpack stuff. Just a html file, a linked css file and a linked javascript file. How do I use firestore? I'm tired and frustrated and absolutely blank at this point, so absolute details will be appreciated. Thanks. Via Active questions tagged javascript - Stack Overflow https://ift.tt/olcwuUG

Having issues with collisions, I think the problem is 'for' loops

I have 2 objects in a list and the collision is supposed to start an action but it only works with the first object in the list. https://imgur.com/a/oJn1GKf In the imgur link, the first video is the feature that I'm making where when you collide with one of the power up tiles, time slows and you get a choice between speed, an extra jump, and something else I haven't decided yet. But you can see it only activates with the one on the right which is the first object in the list, which I am assuming is an issue with me using a for loop but I'm not sure. This is all of the stuff in the event: for i in p_up_rects: pygame.Rect.move_ip(i, - scroll[0], - scroll[1]) DISPLAYSURF.blit(p_up_sprite, i) if moves.square.colliderect(i): p_up_coll = True time_slow += (time_slow_target - time_slow) / 50 if abs(time_slow_target - time_slow)*100 <= 5: time_slow = .005 if time_slow <= .005: #math if p_u

Unsure where to place the Google Maps Autocomplete country restriction [duplicate]

I'm working on the following code and I'm completely baffled as to where to place the Google Maps Autocomplete country restriction. function addMarker(map, features){ var infowindow = new google.maps.InfoWindow(); for (var i = 0, feature; feature = features[i]; i++) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(feature.latitude, feature.longitude), icon: feature.icon !== undefined ? feature.icon : undefined, map: map, title: feature.title !== undefined? feature.title : undefined, content: feature.content !== undefined? feature.content : undefined, }); google.maps.event.addListener(marker, 'click', function () { if(this.content){ infowindow.setContent(this.content); infowindow.open(map, this); } }); } } function is

How to create a loop to calculate MSE?

I have a problem where I need to calculate MSE and MAE. I want to create a loop where: (Test 1) Input 1-15, predict next 15 mins. (Test 2) Input 2-16, predict next 15 mins. (Test 3) Input 3-17, predict next 15 mins. ... and so on, until the end of my inputs. For each of Test 1, 2, 3 etc, find the MSE and MAE. Then, I want to calculate the average MSE and MAE. These are the examples of my predicted and original data frames that I want to use. combined_original_df combined_predicted_df I've tried splitting the dfs into chunks using def split_pred_dataframe(combined_pred_df, chunk_size = 15): chunks = list() num_chunks = len(combined_pred_df) // chunk_size + (1 if len(combined_pred_df) % chunk_size else 0) for i in range(num_chunks): chunks.append(combined_pred_df[i*chunk_size:(i+1)*chunk_size]) return chunks def split_original_dataframe(combined_original_df, chunk_size = 15): chunks = list() num_chunks = len(combined_original_df) // c

Changing image that opens when you click on dropdown

I made the changing picture that opens when I click on the dropdown. But when I copy this dropdown more than once, the changed image does not work. const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function clickToChange() { let imgsrc = this.getAttribute("data-value"); console.log(imgsrc); image.src = imgsrc; } checkbox.forEach(check => check.addEventListener('click', clickToChange)); <div class="custom_select custom-select1"> <a class="image_swap image"> <img id="imageToSwap" class="item__img" src="https://via.placeholder.com/350x150"> </a> <div class="select"> <div class="selectBtn" data-type="firstOption">test</div> <div class="selectDropdown mm-dropdown"> <div class="option imgOption" data-type="

Constructing a Mathematical Equation for Image Bands in Google Earth Engine

I am struggling with an equation, getting some syntax error in it, The equation is following: formula : (K2 / ln ((K1/TOA_band10)+1)) - 273.15 I am trying to do operation on image bands, but not being able to construct the right code. I have used this instead, var BT = band_10.expression((1329.2405 1.0/((799.0284 1.0/TOA_B10)+1).log10())-273.15); but it did not work. A general hint about constructing an equation in earth engine - javascript. Via Active questions tagged javascript - Stack Overflow https://ift.tt/3Im2Ejx

tkinter button color won't change (non-click event)

I created a program to move a knight around a chess board touching every square without touching the same one twice, starting from a random location. I am attempting to show this action using tkinter by changing the color of the square (which is a button) to red as the knight moves. The Chess Board is made of tkinter buttons and they relate to the "Square" class. The program sets the correct colors when creating the grid, but won't change them during execution. Here is the reduced code (as instructed to provide). from tkinter import * from tkmacosx import Button import random import sys WIDTH = 800 HEIGHT = 1000 GRID_SIZE = 8 class Square: board = [] def __init__(self, x, y, touched=False): self.touched = touched self.board_btn_object = None self.x = x self.y = y def create_btn_object(self, location): btn = Button ( locati

Why I can not send messages with telethon, An Invalid Peer was used

I'm trying to send some messages with telethon client API, I have scraped users from groups and have them all in a .csv. It works well with my API credentials, although, I'm getting an error when using a different account with different API credentials [!] Error: An invalid Peer was used. Make sure to pass the right peer type and that the value is valid (for instance, bots cannot start conversations) (caused by SendMessageRequest) Here is the code https://gist.github.com/Raduc4/fd62662cd602db60ca4311af3608a6b2 Personal opinion: I think there is an error because I have scraped with an account and trying to send with a different one. source https://stackoverflow.com/questions/74605988/why-i-can-not-send-messages-with-telethon-an-invalid-peer-was-used

A faster solution for Project Euler question 10

I have solved the question 10 regarding sum of all primes under 2 million, however my code takes over a few minutes to calculate the result. I was just wondering if there is any way to optimise it to make it run faster ? The code takes an upper limit Generates an array Iterates through it and removes multiples of a number, replacing it with 0 Takes that filtered array and loops through the next non zero number Increases this number till it is sqrt of the limit. Prints out what is left. import numpy as np def sievePrime(n): array = np.arange(2, n) tempSieve = [2] for value in range(2, int(np.floor(np.sqrt(n)))): if tempSieve[value - 2] != value: continue else: for x in range(len(array)): if array[x] % value == 0 and array[x] != value: array[x] = 0 tempSieve = array return sum(array) print(sievePrime(2000000)) Thank you for your time. source https://stackov

How to use ArrayFire batched 2D convolution

Reading through ArrayFire documentation, I noticed that the library supports batched operations when using 2D convolution. Therefore, I need to apply N filters to an image using the C++ API. For easy testing, I decided to create a simple Python script to assert the convolution results. However, I couldn't get proper results when using >1 filters and comparing them to OpenCV's 2D convolution separately. Following is my Python script: import arrayfire as af import cv2 import numpy as np np.random.seed(1) np.set_printoptions(precision=3) af.set_backend('cuda') n_kernels = 2 image = np.random.randn(512,512).astype(np.float32) kernels_list = [np.random.randn(7,7).astype(np.float32) for _ in range(n_kernels)] conv_cv_list = [cv2.filter2D(image, -1, cv2.flip(kernel,-1), borderType=cv2.BORDER_CONSTANT) for kernel in kernels_list] image_gpu = af.array.Array(image.ctypes.data, image.shape, image.dtype.char) kernels = np.stack(kernels_list, axis=-1) if n_kerne

Trying to write values to serial port in python and read them from arduino simultaneoulsy

I want to send some constantly changing values from my Python code in Visual studio to my arduino IDE (mac user by the way). I want the arduino code to read the values as they are being sent, instead of having to run the code in python, close the window, and then open up the arduino IDE after. Essentially, I want Visual Studio to write to the serial port whilst Arduino is reading from it. At the moment, the python side is working fully- I'm using pyserial and when I ask my python code to read me the values it has written to the serial port, it works. However, when I try to open up the arduino IDE and run the code, it says 'port busy'. I can't run the python code if the arduino IDE is open either, it returns the same sort of error message. Does anyone know how I can solve this? Thanks Python code: import serial #arduinostuff import time arduino = serial.Serial(port='/dev/cu.usbmodem14101', baudrate=115200, timeout=.1) # Project: Object Tracking # Author: Ad

WebGL: INVALID_VALUE: texImage2D: invalid internalformat - depthTexture in webgl2

const depthTextures = gl => { const depthTexture = gl.createTexture(); const depthTextureSize = 512; gl.bindTexture(gl.TEXTURE_2D, depthTexture); gl.texImage2D(gl.TEXTURE_2D, // target 0, // mip level gl.DEPTH_COMPONENT, // internal format depthTextureSize, // width depthTextureSize, // height 0, // border gl.DEPTH_COMPONENT, // format gl.UNSIGNED_INT, // type null); // data gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); const depthFramebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, depthFramebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, // target gl.DEPTH_ATTACHMENT, // attachment point gl.TEXTURE_2D, // texture target depthTexture, // texture 0); // mip level // create a color texture

Indent created Elements in javascript

So I've used javascript to build up an HTML markup for a component (accordion) const accordItem = document.createElement("div"); const accordTitle = document.createElement("p"); const accordContent = document.createElement("div"); const accordContentParagraph = document.createElement("p"); All the elements are appended to a container container.append(accordItem); accordItem.append(accordTitle, accordContent); accordContent.append(accordContentParagraph); In the code, I populate the divs and paragraphs with content. So, an accordion generator of a sort. So the imaginary user can see a preview of how it would look. And also download a text file. But if I copy the code from developers' tools. Or write it in the file; I see this mess of a markup. Everything is in one line. <div class="accordionItem"><p class="accordionTitle">This is some content</p><div class="accordionContent"><p

AxisError: axis 4 is out of bounds for array of dimension 4

t0=time.time() hist_vanilla = model_vanilla.fit_generator( SeismicSequence( labeled_data, train_data["Xline"].values, train_data["Time"].values, train_data["Class"].values, patch_size, batch_size, 1), steps_per_epoch=steps, validation_data = SeismicSequence( labeled_data, test_data["Xline"].values, test_data["Time"].values, test_data["Class"].values, patch_size, batch_size, 1), validation_steps = len(test_samples)//batch_size, epochs = epochs, verbose = 0, callbacks = callbacklist) print('--> Training for Waldeland CNN took {:.1f} sec'.format(time.time()-t0)) #Thanks to aadm AxisError Traceback (most recent call last) <ipython-input-52-8828ecedd241> in <module> 22 epochs = epochs, 23 verbose = 0, ---> 24

Phaser play animations at the same time

I currently have a group of sprites that the player can add to when they click. I want to find a way to make it so that they play the animation at the same time (which is important since otherwise the conveyor belts will be out of sync). I've tried to do conveyors.playAnimation() every time it adds something new, but that resulted in it "skipping" frames every time I add a new one. Is there a method I could use so that the new one starts at the same frame as the others? Via Active questions tagged javascript - Stack Overflow https://ift.tt/14HfyEx

Issues Creating a 3D Renderer in JavaScript

I am trying to make my own 3D renderer in JavaScript using raycasting, but despite checking over the math and the code countless times, it still does not seem to be working. I've tried everything I possibly could to get this thing to work and it won't, so I'm hoping someone else can figure it out. My code runs an Update method every frame, increasing the yaw (Camera.Rot.Yaw) by 0.1 radians every iteration, but it ends up looking weird and unrealistic, and I can't figure out why. Sorry if it's confusing and long, I can't really think of a way to make a minimal reproducible example of this. This is the Update method: Update(Canvas, Ctx, Map, Camera) { var id = Ctx.getImageData(0, 0, Canvas.width, Canvas.height); var Pixels = id.data; //Distance of projection plane from camera //It should be behind I think var PlaneDist = 64; //Divides the second slopes by this so each ray goes a shorter //distance each iteration, effectively increas

Starting a python script from another before it crashes

I'm trying to make some project code I have written, more resilient to crashes, except the circumstances of my previous crashes have all been different. So that I do not have to try and account for every single one, I thought I'd try to get my code to either restart, or execute a copy of itself in place of it and then close itself down gracefully, meaning its replacement, because it's coded identically, would in essence be the same as restarting from the beginning again. The desired result for me would be that while the error resulting circumstances are present, my code would be in a program swap out, or restart loop until such time as it can execute its code normally again....until the next time it faces a similar situation. To experiment with, I've written two programs. I'm hoping from these examples someone will understand what I am trying to achieve. I want the first script to execute, then start the execute process for the second (in a new terminal) before clo

JavaScript regular expression is inconsistent after passing once [duplicate]

I have a regular expression check to determine if the input is valid or not. It returns false for all expected wrong inputs. However, after passing the input check successfully once, there is an odd situation where an input (I only found one so far) that should fail will now pass until I refresh the page and start over. let tstr = '^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])'; let treg = new RegExp(tstr); console.log(treg.test(*input value*)); The input that I noticed acting strange is Testword If I put the string above as an input before any checks pass, then it will fail. If at any point of testing a valid input passes the check, ex 'Wordword1', then I can reenter 'Testword' and it will pass even though it should fail. I can't understand the reason for this inconsistency. Why is this happening and how can I prevent this? Via Active questions tagged javascript - Stack Overflow https://ift.tt/14HfyEx

Python Socket Not Reading UDP Packets on Jetson Hardware

II have UDP packets that are being sent to my device via an Ethernet connection. I am attempting to read them data using the socket library in Python (version 3.8.10); however, despite them being displayed on the device when I run tcpdump , my Python program never receives the data, and I'm not sure why. I want to receive the data from my local port 2368 ; however, it is not working. I will provide more information below. Here is the code that I'm using to read data from the socket that I'm interested in. import socket with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as soc: soc.bind(("", 2368)) data = soc.recv(2000) # I'm using an arbitrary buffer size print("Received Data!", data) Main Issue : The hardware that I'm having trouble with running this code on is a Jetson Xavier with Ubuntu 20.04.5 LTS and Gnome 3.36.8 (I'm not exactly too sure what Gnome is). When I try to run the Python code above on this hardware, the

Parsing JSON formatted in JS file within page package source

I successfully managed to scrap a dynamic.js file I was looking for because it contains a JSON variable I want to extract. Within the ChromeDev source tab, I was able to identify the file containing the JSON variable, however, I am not able to understand which formatting it is and how to parse it. Here's what it looks like: app = {};app["last_change"] = "11491620393";app["last_change_as_of"] = 1668773511284;app["generation_fiber_id"] = "1668773511072x153651415292286300";app["_id"] = "prellomaster1028";app["app_version"] = "live";app["_index"] = {};app["_index"]["id_to_path"] = {};app["_index"]["id_to_path"]["bTHlK"] = "%ed.bTHli.%el.cmQru"; I tried importing this variable "app" on different JSON parser and tweaking a few formatting settings but none of them worked. Any hints? Thanks Via Active questions tagge

Update value in a dictionnary with React Hooks/ JS

I have a dictionnary in which I want to re-format some data because when I receive them from my database, they are not formatted correctly. To do that, I store them in a dictionnary like so when the page is opened: const [data, setData] = useState([]); db.collection('users').doc(auth.currentUser.uid).get().then((response)=> {setData(response.data().appointments)}) and then I try to call a function to update the startDate and endDate keys' value automatically everytime the page is opened: // This function re-formats and will be used in the next one function toDateTime(secs){ var t = new Date(1970, 0, 1); // Epoch t.setSeconds(secs); //console.log(t) return t } // This function has to update the value function pwease(datis){ var secondo = datis['startDate']['seconds'] var secondu = datis['endDate']['seconds'] var upDatis = { ...datis, endDate : toDateTime(secondu),

Im trying to do some code in python that reads a text file and picks out the 5 lines with the highest number and prints them

i have an assignment coming up in which i have to code a dice game . its multiplayer random luck with gambling points and etc one of the things its asking for though is to save the winning players name and their score into a text file and at the end print the five highest scores in the text file with the five players names, ive got the code so that it saves the players name and score along with some text but have absolutely no idea on how to read the whole text file and and pick out lines that have the 5 largest integers and print them ` name = str(input("Player 1 name")) name2 = str(input("Player 2 name")) score = str(input("Player 1 score")) score2 = str(input("Player 2 score")) text_file = open("CH30.txt", "r+") if score > score2: content = text_file.readlines(30) if len(content) > 0 : text_file.write("\n") text_file.write(name) text_file.write (" wins with ") text_fi

How to update array object value in angular

Trying to update array object value but not working. I am trying to update item value from an array But not updating. How to resolve this issue. ngOnInit() { this.arr = [ { lable: 'test1', item: 'Row6', }, { lable: 'test2', item: 'Row9', }, { lable: 'test3', item: 'Row4', }, ]; } updateVal() { this.arr = this.arr[0].item = 'Row9'; console.log(this.arr); } Demo: https://stackblitz.com/edit/angular-ivy-srsirm?file=src%2Fapp%2Farrcom%2Farrcom.component.ts Via Active questions tagged javascript - Stack Overflow https://ift.tt/ADiX0Ms

How can I get an array of objects containing a certain property value that are nested in another object in JavaScript? [closed]

I have an object with a bunch of nested objects, some of which have their own nested objects. I need to write a function that accepts the outermost object and returns an array of all objects that are nested inside it that satisfy a given condition. I've been banging my head against the desk for an hour with only vague ideas but at this point I just don't know how to solve this. Via Active questions tagged javascript - Stack Overflow https://ift.tt/dvVfGw8

I just deployed my web app to firebase, see what i'm getting

See what i'm getting after dploying my app to firebase. I already did firebase hosting, but the web content is still not showing Via Active questions tagged javascript - Stack Overflow https://ift.tt/dvVfGw8

How to checkin list of divs if there is a span within with class 'new'

In Beautifulsoup i receive a list of divs . Each of these divs has an span included: <div role="news_item" class="ni_nav_9tg"> <span class="nav_element_new_S5g">Germany vs. Japan</span> </div> ... <div role="news_item" class="ni_nav_9tg"> <span class="nav_element_new_S5g">Brasil vs. Serbia</span> </div> What i want is to check if in this list of div a span exist whose class contains string "new". Just true or false as result. Of course i could iterate through each item div in list and get span item after this check if class contains string "new", but i am not sure if this is the right approach. source https://stackoverflow.com/questions/74576984/how-to-checkin-list-of-divs-if-there-is-a-span-within-with-class-new

Firebase returns undefined when it comes to snapshot.val() [duplicate]

I use NextJS const db = getDatabase() const getTeamData = (teamName: string) => { onValue(ref(db, teamName), snapshot => { return snapshot.val() }) } console.log(getTeamData('exampleTeam')) I do have this exampleTeam in the database; however, it returns undefined anyway. But why? I have tried this: let ret: any[] = [] onValue(ref(db, teamName), snapshot => { ret.push(snapshot.val()) }) return ret[0] } But it still returns undefined. Also, if I change something in the code so that it does a fast reload, then all of the correct data is printed and it works good. Via Active questions tagged javascript - Stack Overflow https://ift.tt/dvVfGw8

Translating latitude and longitude into x,y grid on webpage

I am trying to take latitude and longitude values from different people's location into a gridlike 2D display where y= longitude and x = latitude 2D. How can I do that using html, css, java? I just found from a different question, maybe I could use ArcGis Api to translate the values to X and Y. But then how would I place them on the screen, so that they have the correct location? I have this code for the latitude and longitude: const getLocation = document.getElementById("btn"); getLocation.addEventListener("click", evt=> { if("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(position=> { let latitude = position.coords.latitude; let longitude = position.coords.longitude; console.log(latitude,longitude); },error=>{ console.log(error.code); }); }else { console.log("not supported") } }); Via Active questions tagged java

Convert strConflictedYesReviewers data into a single object which is group by ownerid and make array of opportunityid

I get a dynamic string(strConflictedYesReviewers) which contains multiple user recordswhere each record is separated by semicolon and then each record represents ownerid and opportunityid separated by asterisk. I have done it but looking for a better approach or code review. const strConflictedYesReviewers = "88639280*198719943;88642547*198721749;88627345*198721749;88664734*198721749;88686221*198721749;88676217*198721749;88664734*198721749;88686221*198721749;88676217*198721749;" .split(";") .map(item => item.split("*")) .filter(item => !!item[0]) .map(item => ({ownerid: item[0], opportunityid: item[1]})) .reduce(function(acc, curr) { (acc[curr["ownerid"]] = acc[curr["ownerid"]] || []).push(curr["opportunityid"]); return acc; }, {}); console.log(strConflictedYesReviewers); Via Active questions tagged javascript - Stack Overflow https://ift.tt/dvVfGw8

Pandas: How to Squash Multiple Rows into One Row with More Columns

I'm looking for a way to convert 5 rows in a pandas dataframe into one row with 5 times the amount of columns (so I have the same information, just squashed into one row). Let me explain: I'm working with hockey game statistics. Currently, there are 5 rows representing the same game in different situations , each with 111 columns. I want to convert these 5 rows into one row (so that one game is represented by one row) but keep the information contained in the different situations. In other words, I want to convert 5 rows, each with 111 columns into one row with 554 columns (554=111*5 minus one since we're joining on gameId ). Here is my DF head: So, as an example, we can see the first 5 rows have gameId = 2008020001 , but each have a different situation (i.e. other , all , 5on5 , 4on5 , and 5on4 ). I'd like these 5 rows to be converted into one row with gameId = 2008020001 , and with columns labelled according to their situation. For example, I want columns for all

'Content-Length' Header affecting parsing of request Gin Gonic

I am making an app where an image is taken by the user then sent to the backend as json with some other keys as base64 data. When I try to send the content from my frontend (sveltekit) it doesn't work and Gin gives me either invalid character 'o' looking for beginning of value // or EOF depending on whether I send the Content-Length header with the request. When I send the same request from postman (which autosets the Content-Length header) it works. I tried implementing the content-length header in my frontend - see below. dataurl is a b64 string from canvas.toDataURL() const uploadImage = () => { // console.log(dataURL); let frdurl = dataURL.toString(); frdurl = frdurl.split(",", 2); let tos = frdurl[1]; console.log(typeof(tos)); console.log(tos) let b = { data: tos, User: "test2" } fetch("http://localhost:8080/uploaddaily", {

Pandas apply works as inplace true

I'm trying to change a new data frame's column using apply function to another df, but both data frames' columns changes. df = pd.DataFrame([['x1','x2'],['y1','y2']],columns=['A','B']) A B x1 x2 y1 y2 lst = [] def getbinary(x): if x not in lst: lst.append(x) return lst.index(x) modeldf = df modeldf['A'] = df['A'].apply(getbinary) modeldf and df after this code: A B 0 x2 1 y2 source https://stackoverflow.com/questions/74565374/pandas-apply-works-as-inplace-true

async function returning a promise and not a value [duplicate]

I am fetching data from an API to get the number of likes. this is the function to get all the data ` const getLikes = async () => { const response = await fetch(`https://us-central1-involvement-api.cloudfunctions.net/capstoneApi/apps/${apiKey}/likes`) const likeData = await response.json(); return likeData; } `then I want to store info in a variable so I wrote this other function ` const likesObj = async ()=> { const getLike = await getLikes() return getLike; } ` when I console.log the const getLike it does print an Array of objects with every item and the number of likes it has. but when I return getLikes it returns a promise, how can I return the result and not the promise I tried with .then() but I get the same result Via Active questions tagged javascript - Stack Overflow https://ift.tt/iKLH3bx

Reference this for member functions in literal objects [duplicate]

Here is the modular way of js literal object. In the 'display' function, 'this' refers normally. But in 'addEvent' this refers to something else. Since the object where the click event occurred becomes 'this', this pointing to a member function cannot be used. How can I solve this problem? let s_text = {}; var currentPanel = function(){ var prefix = ''; var subtext = ''; return { setText: function(text){ subtext = text; }, getText: function(){ return subtext; }, display: function(text){ this.setText(text); return '<span>'+subtext+'</span>' }, addEvent: function(){ document.getElementById('canvas'+id).onclick = function(){ let args = {}; var id = $(this).attr('data-root'); arg

Unable to import dbutils in my python file

I am trying to fetch secret_id and client_id in my python notebook in vscode. CLIENT_SECRET = dbutils.secrets.get(scope="abc", key ="SERVICE-PRINICIPAL-CLIENT-SECRET") CLIENT_ID = dbutils.secrets.get(scope="abc", key ="SERVICE-PRINICIPAL-CLIENT-ID") But how do I import dbutils in my python class? source https://stackoverflow.com/questions/74552521/unable-to-import-dbutils-in-my-python-file

how to generate the minimum distance in this function

this function classify the elements of a list into clusters .the elements of eatch cluster the distance between theme is <= (max(distance)+min(disatnce))/2 , distance is a list of distances between one element and all the rest of theme. i want to generate this criteria inside the function because in this function the minimum distance is given by me. the data : PLAYER,Mat.x,Inns.x,NO,Runs.x,HS,Avg.x,BF,SR.x AB de Villiers,12,11,2,480,90,53.33,275,174.54 Quinton de Kock,8,8,0,201,53,25.12,162,124.07 Ankit Sharma,0,0,0,0,0,0,0,0 Anureet Singh,0,0,0,0,0,0,0,0 def clustering(groups, min_dist, data, i): distance = [] for g in range(0,len(groups)): somme = 0 # jusqu'a la fin des nombre de colomne for j in range(0,len(list(data.iloc[i, :]))): # difference between the 1st elt in the cluster and the elts not yet clustered diff = dif(groups[g][0][j], data.iloc[i, j]) somme = somme+diff distance.append(somme)

How to add data in array in form state in React

Problem Screenshot I am trying to use the form to add data to the form data I want the question to go into question as shown in the form data then I want the options to go into the options array as ` { letter: "A", answer: "", isTrue: false }, { letter: "B", answer: "", isTrue: false }, { letter: "C", answer: "", isTrue: false }, { letter: "D", answer: "", isTrue: false }, ` but I am finding difficult The questions can be added and dynamically and changing just the questions works individually but I can't get to do the same for the options Please help me achieve this, even if it can be done in another totally different way const [questionId, setQuestionId] = useState(0); const [questions, setQuestions] = useState({}); const [form, setForm] = useState([]); const [opt, setOpt] = useState([]); const opts = ["A", "B", "C", "D"]; co

FFmpeg not splitting videos precisely

I was trying to use FFmpeg to split videos into 30s segments, here is the full code: from tkinter import filedialog, Tk import subprocess import os Tk().withdraw() path_to_video = filedialog.askopenfilename() print(f"Path to video is: {path_to_video}") segment_duration = input("Enter each segment duration in second: ") os.chdir(os.path.dirname(__file__)) print(f"-i \"{path_to_video}\" -c copy -map 0 -segment_time {segment_duration} -f segment -reset_timestamps 1 Output_%03d.mp4") subprocess.run([ "E:\\Programs\\FFmpeg\\ffmpeg-master-latest-win64-gpl\\bin\\ffmpeg.exe", "-i", path_to_video, "-c:", "copy", "-map", "0", "-segment_time", segment_duration, "-f", "segment", "-reset_timestamps", "1", "Output_%03d.mp4"]) But it actually splits it into videos with really low precision, how can I f

Select during vs. after insert produces different results

My database is written to every second during certain hours. It's also read from during same hours, every minute. The read outputs different values during operational hours vs. after hours. Might be data is not written when I read. How to fix this or make sure data for last minute is complete before reading? Would a different database do better? How I am reading: conn = sqlite3.connect(f'{loc_tick}/tick.db', detect_types=sqlite3.PARSE_DECLTYPES, timeout=20, isolation_level=None) select_statement = f"select * from symfut WHERE timestamp >= date('now', '-10 days')" m1df = pd.read_sql(select_statement, conn) Write: conn = sqlite3.connect('tick.db', detect_types=sqlite3.PARSE_DECLTYPES, timeout=20,isolation_level=None) c = conn.cursor() c.execute('PRAGMA journal_mode=wal') c.execute('PRAGMA wal_autocheckpoint = 100') c.execute('INSERT INTO symfut (timestamp, c, b, a) VALUES (?,?,?,?)', (times

Script for calculation the best segments combination [closed]

I need help. I need a script that will accept the length of segments in millimeters and the number of segments of that length. Segments can be of any length up to 1500 mm. What is the point of the script? It is necessary that he calculates combinations of segments so that their sum is equal to 1500 mm. The sum of the segments can exceed 1500 mm only by 100mm, but cannot be less than 1500mm. Also, the number of segments on one interval should not exceed 10 pieces. The script must find the most profitable solution, so that the surplus is minimal, and even better, it would be equal to 0. For example: We have 5 pieces 205mm long, 6 pieces 230mm long and 10 pieces 195mm long. It is necessary to combine them so that their total would be 1500 + - 100 mm. Conventionally, 205mm x 3 + 230mm x 3 + 195mm x 1 = 1500mm, this is how the script should calculate the moves. I depend on your help, because all the nuances do not fit in my head. For myself, I now realized that it will look like a

How to skip a tag when using Beautifulsoup find_all?

I want to edit an HTML document and parse some text using Beautifulsoup. I'm interested in <span> tags but the ones that are NOT inside a <table> element. I want to skip all tables when finding the <span> elements. I've tried to find all <span> elements first and then filter out the ones that have <table> in any parent level. Here is the code. But this is too slow. for tag in soup.find_all('span'): ancestor_tables = [x for x in tag.find_all_previous(name='table')] if len(ancestor_tables) > 0: continue text = tag.text Is there a more efficient alternative? Is it possible to 'hide' / skip tags while searching for <span> in find_all method? source https://stackoverflow.com/questions/74538402/how-to-skip-a-tag-when-using-beautifulsoup-find-all

SVG dynamic positioning and dimensions

I have a web app that renders svg elements from cartesian points (lines, paths, etc) that come from a database. I have a requirement that an end user can upload an svg file (icons) and drag the icon to fit within specific bounds of the points already defined and rendered in the app. For example (see snippet), a user can upload the 'x' icon and drag it near the green line defined by two points, which should result in the icon being snapped and resized to the line - the upper left corner snapped to the line start point, and the width of the icon extending to the line end point. Same is true for the file icon being snapped to the red line. This is done dynamically during drag with js. I have omitted the js from the snippet to keep things simple, as I am confident that the answer lies with svg attributes and or style that I can set with js, but the svg properties/values are what I cannot pin down. What I have tried - everything, I think. Given that I am nesting svg elements, I t

movieReviewsApp: How to get the value (actual written text) from an input into a variable and display it somewhere else?

I made a html/javaScript app that get movie data from an API and displays it (index.html), when someone click the "see details" link from any movieCard theyre redirected to a new page (singleMovieView.html). I want to be able to write in an input/textarea, click a button and then, with createdElemenst of div, paragraps, h, etc, upload it into an empty div I made specially just for the reviews. The singleMovieView.html display info of the particular movie and then, below, there are two divs; one for writing the review (textArea/input and button)and below that another div to display the pastReviews. Heres the code: index.html: <!DOCTYPE html> <html> <head> <title>Movies Site</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="topnav"> <a class="active" href="#">Movies Site</a> <div class="searc