Skip to main content

Posts

Showing posts from May, 2023

Promised Streaming to Base64 not concatenating full response

I'm trying to download a potentially large file by streaming. It must be accumulated into memory because the API I'm using requires a base64 upload. However, I'm thinking a stream might still be necessary because the implementation would be in a web server and I don't want to block the event loop. Any ideas on why this code might not be working? It seems like the chunks aren't being concatenated because I'm getting only the first piece of the response body when I debug. import { Transform } from "stream"; import axios from "axios"; import fs from "fs/promises"; class Base64EncodeStream extends Transform { private completePromise: Promise<string>; constructor() { super({ transform: (chunk, encoding, callback) => { this.push(chunk.toString("base64")); callback(); }, }); this.completePromise = new Promise((resolve, reject) => { let data = ""; t

AWS API gateway to pass file through lambda to s3 bucket

I am trying to build an API with API gateway to accept a file upload. I am going through lambda so that I can manipulate the file name before passing it on to S3 bucket In the event body i can see the file contents but can't seem to access the file name. Right now Im not implementing anything to move file to S3 because I haven't been able to access the file name. the code is as follows import sys import os import boto3 import json def lambda_handler(event,context): eventBody = json.dumps(event['body']) return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, 'body': eventBody, 'isBase64Encoded': False } the event body looks as follows "----------------------------210938299122441198584130\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r\nContent-Type: text/plain\r\n\r\nthis is a test f

How to set the response time from the bot

I am writing my bot in python, the user writes a message, the bot answers, so far without a break, how to make it so that a day has not passed since his answer, he wrote, the day has not yet passed, come back the next day source https://stackoverflow.com/questions/76376901/how-to-set-the-response-time-from-the-bot

How to maintain CSS styles while printing from a specific part of a webpage

I am trying to print a specific part of my page and also maintain its style. currently when I press print all my CSS styles are stripped away. Here is my HTML document. const button = document.createElement('button') //this is the print button button.classList.add('printButton') button.textContent = 'Print' const entryContainer = document.getElementById('container') const card = document.createElement('div') //this will be the card to print card.classList.add('card') card.setAttribute('id', 'printcard') card.textContent = 'I failed the first quarter of a class in middle school, so I made a fake report card. I did this every quarter that year. I forgot that they mail home the end-of-year cards, and my mom got it before I could intercept with my fake. She was PISSED—at the school for their error. The teacher also retired that year and had already thrown out his records, so they had to take my mother’s “proof” (the fa

How can I render a div that has its visibility:'hidden'? in PDFjs

So I'm implementing a feature in my react web app, and in one of the Views, I have a button that takes 2 HTMLElements and display them in 2 pages in a PDF, but I would like one of them to stay hidden. The problem is that while hidden, PDFjs does not render it. Same happens when trying to set it to position:'absolute' and smth like '-999999px'. This is the piece of code responsible for capturing and saving: const downloadIt = () => { const blackboard = document.getElementById('blackboard') as HTMLElement; const descriptionList = document.getElementById('elementDescriptions') as HTMLElement; const width = blackboard.offsetWidth; const height = blackboard.offsetHeight; const aspectRatio = width / height; html2canvas(blackboard).then((canvas) => { const pdf = new jsPDF(); const imageData = canvas.toDataURL('image/png'); const pdfHeight = pdf.internal.pageSize.getWidth() * (1 / aspectRatio);

Slice two datetime objects with Python

I have two date time objects in Python 2.7. The first looks like this: 2018-09-22 00:00:00 and the second looks like this: 1899-12-30 17:20:59 I would like to end up with the dates from the first datetime object and the time from the second datetime object. 2018-09-22 17:20:59 Unfortunately I am coding for some old GIS software and compelled to use 2.7 Any help is appreciated. source https://stackoverflow.com/questions/76376535/slice-two-datetime-objects-with-python

plt graphic test and train accuracy doesnt see

I couldn’t visualize the test and train data on the graph plane in any way. My test, train, and loss values are clear, but I can’t draw a suitable graph for them. I shared the image below. Can you please help me? I also added the code I wrote below. #%% Saving Training Model torch.save(net.state_dict(), 'trained_model.pth') print("Trained model saved.") #%% print("Loss list: ", loss_list) print("Test accuracy: ", test_acc) print("Train accuracy: ", train_acc) #%% visualize fig, ax1 = plt.subplots() ax1.plot(loss_list, label="Loss", color="black") ax1.set_xlabel('Epoch') ax1.set_ylabel('Loss') ax2 = ax1.twinx() ax2.plot(range(len(test_acc)), np.array(test_acc) / 100, label="Test Acc", color="red") ax2.plot(range(len(train_acc)), np.array(train_acc) / 100, label="Train Acc", color="blue") ax2.set_ylabel('Accuracy') ax1.legend(loc='upper left')

file upload won't upload .Json file

I'm working on my first react project and I have an upload button through which the user can upload a set of files. I noticed that the file upload works perfectly for all file extensions, except for .json files. I'm not quite sure why that is, can anyone take a look at my addFile function? openUploadStream is the function given by mongoDB for GridFS storage of files. const addFile = async (req, res) => { const { filename } = req.body const path = "cache\\" + filename //all files are stored in the cache folder const uploadStream = fs.createReadStream(path). pipe(bucket.openUploadStream(filename)) //store the file as the filename} res.status(200).json({id : uploadStream.id}) //return unique id of file in the db } and in the frontend I call the API using axios await axios.post('/api/filesRoute/fs', { filename : filename }) .then((json) => { console.log('Success uploading', filename) raws.push(jso

Correctly configure IP network when using Python socket library

I have Python code like the following that makes a TCP connection over Wifi to a Linux microcomputer from my personal laptop. This works when I connected to the Wifi network of the microcomputer from my personal laptop. However, if I'm also connected to another network over ethernet, this does not work. import socket PORT = 65432 HOST = "192.168.6.2" socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket creation socket.connect((HOST, PORT)) # socket connection To address this problem of being connected to Ethernet: when connecting via ssh, I use the following: ssh -B en0 username@192.168.1.1 . Please see this post for details on the network. I basically want to to tell the Python socket library to include the -B en0 option, but am not sure how to do this. source https://stackoverflow.com/questions/76367840/correctly-configure-ip-network-when-using-python-socket-library

How can I make parent categories bold in a product table with Woocommerce?

I am using a table products to filter categories. What I need is to make only the parent categories bold. In this search result e.g.: https://demo.motorocker.gr/?swoof=1&antalaktika=scooter we need to bold only parent categories I am attaching a pic ( https://i.stack.imgur.com/oYEcR.png ) I tried to make it through CSS but it didn't work. I tried e.g. this class li#select2-wcpt_filter_product_cat-zx-result-ac7d-elastika but I see that every time each category comes out with a separate ID. Any advice? Via Active questions tagged javascript - Stack Overflow https://ift.tt/rey8tLS

Angular Dynamic Add rows with custom components

I am trying to add rows for search/filter requirement. There are 100s of fields to filter. Do my boss decided to keep them in a dropdown (here in this example I kept Manager, City and Name). When user selects one from the drop down, (lets say, City), the next box should display another drop down with all cities. If user selects Name, the next box should display a Text Box. And user can add as many rows (filters). I tried and was able to dynamic add rows and display text box or drop down (based on inputType). But my problem is when I change from manager to Name, then it changes all boxes in right side to Text box. And when Add a new row/filer, it automatically displays previous selected drop down or Test. That means what I want is the right side dropdown or text box should appear only when user selects a value from the left side. I am not sure I am explaining it well or not. But please feel free to ask questions. Below is the example I have done so far. Thanks in advance for your hel

How do I compare two columns in a Pandas DataFrame and output values from other columns based on the match?

So I have a pandas dataframe. A: 3, 4, 1, 2, 1, B 1, 2, 3, 4 C Red, Blue, Yellow, Green D Yes, No, Maybe, True what I want to be able to do is sequentially check column A against column B, if there is a match then output C and D relative to B. For example the data frame above would be converted into A Yellow, Green, Red, Blue, Red B Maybe, True, Yes, No, Yes I am rather new to python and pandas so I might be missing something simple here but I cannot think of solutions for this problem and am unsure where to start to find an answer. Any help would be appreciated -Smoggs Many various ideas. I know I should be using iloc to target the value in the cell, but I am unsure how to output the result next to it. I'm really at a loss here source https://stackoverflow.com/questions/76360074/how-do-i-compare-two-columns-in-a-pandas-dataframe-and-output-values-from-other

Why previous page only works if there's 2 pages (Google Drive API)

I've encountered a problem, probably it's not something huge. So basically I'm using Google Drive API to retrieve files from drive and I want to make pagination, I managed to do next page just fine, but the problem rised when I tried implementing Previous Page button. Imanaged to make it work, but now if there's 2 pages it works just fine, but if there's more than 2, for example, if there are 3 pages, if I go to 3rd page, click Previous Page button, it takes me to 2nd page, but then there's no "previousPageToken" so button is not appearing at all. Should I store tokens in an array or something like that? Here is the code: let currentPageToken = null; let previousPageToken = null; async function listFiles(folderId, pageToken = null) { $('#table_content').empty(); $('#table_content').remove(); isListFilesInProgress = true; // Set the flag to indicate listFiles() is in progress // Disable the button during listFiles() execut

Getting text attributes from different elements on a website using Python

I am attempting to scrape text from different elements within a website. I have had no luck scraping any text so far. attached is the HTML and a picture of the exact elements I would like to extract from the website. I want to scrape the date/time, the name of the teams "Juventus - AC Milan", and the odds. I am not asking for it to be done for me I just don't know why my code isn't getting text from the buttons. HTML Website I'm using urllib3 and beautifulsoup4. I got the header from a forum and just changed the chrome version to mine. How do I know what needs to be inside my header? Attached is the code I have tried: import urllib3 from bs4 import BeautifulSoup url = "https://beta.goal3.xyz/sports/soccer" # Define the headers headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/113.0.5672.127 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,applicatio

Google app script passing of variables into a trigger function

Google app script creating a trigger and passing variables to it My code creates google forms and I want it so that everytime a form is submitted a email is sent to me, if I initialise it like my createformtrigger in the loop, it will just send me an email even though there have been no responses to my form yet Everytime the onFormSubmit trigger triggers, the variables return as undefined here is my code below function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } function sendEmailNotification4(formName, responseSheetUrl) { const targetEmail = "aldenrequeza@gmail.com"; const emailSubject = formName + " New Form Response"; const emailBody = "A new response has been submitted. Link to response: " + responseSheetUrl; MailApp.sendEmail(targetEmail, emailSubject, emailBody); } function createFormTrigger(formId, formNam

cant use the AutoTyping.js library in vercel (Reactjs)

hi im new to react and im using a library which is called AutoTyping.js which you may know so when im using it in my localhost everything seems fine but when i push it to vercel its not working and i dont know why can anyone help ? I just want the vercel to somehow recognizes the library. Via Active questions tagged javascript - Stack Overflow https://ift.tt/wV9MoZg

'Property doesn't exist' error with imported module in Svelte

I want to use big.js or decimal.js to perform accurate calculations of decimal numbers in my basic Svelte app. To test it, I have imported the module in my App.svelte file: import Decimal from "../node_modules/decimal.js/decimal.mjs"; import Big from "../node_modules/big.js/big.mjs"; However, when I create a Big object and use its built-in functions, I get an error in my IDE (Visual Studio Code), but the code works as expected in the console: let myNumber = 3.2; let secondNumber = new Big(myNumber).div(2); Error: Property 'div' does not exist on type 'Big' How can I get my IDE to recognise imported objects from modules? To clarify, I am not using typescript. Via Active questions tagged javascript - Stack Overflow https://ift.tt/R5uPKkB

Can't Receive Data from RoboClaw Encoders While Using Python Code In Raspberry Pi 3

We are working on a project that uses 2x15A Roboclaw Motor drivers. We are trying to extract the encoder value from roboclaw while using a Raspberry Pi 3. The python code always prints the values of encoders as [0, 0] whatever we try. Rewiring also didn't work. We are able to see data when using basicmicro motion studio tool to access the roboclaw product directly from a computer. But we can not get a reading while using python code and Roboclaw library. Python code we use is from basicmicro's "Using RoboClaw Encoders" tutorial. We are also not receiving any errors in python, the code is able to utilize the motors with the same python code but not capable getting any data feedback from the encoders, all the returned values from the encoders are (0,0). Example of the code can be seen Below: from roboclaw import Roboclaw from time import sleep roboclaw = Roboclaw("/dev/ttyS0", 38400) roboclaw.Open() motor_1_count = roboclaw.ReadEncM1(0x80) print "Ori

Paste a image to the canvas for full size

I have 640x692 jpg (Emperor_Penguin_Manchot_empereur.jpg). and I want to paste this in canvas. So, I made the canvas const canvasRef = useRef(); useEffect(() =>{ var chara= new Image(); chara.src = "http://localhost:8021/Emperor_Penguin_Manchot_empereur.jpg"; chara.onload = () => { var ctx = canvasRef.current.getContext('2d'); ctx.drawImage(chara,0,0,640,692,0,0,640,692);// paste the image as the same size. } return <canvas ref={canvasRef} style=></canvas> this is the picture, result However with this script, it shows the only the part of this picture (left top). I set the size of canvas and jpg as the same size. Where am I wrong?? Via Active questions tagged javascript - Stack Overflow https://ift.tt/R5uPKkB

Regular expression that matches only the letters in a given word

I am trying to create a regex expression which will allow the test string to match with the following conditions: The test string can be any length and contain any letters. ALL characters in the regex must be matched. All letters in regex must be matched ONLY the number of times they are repeated in the regex expression. If a letter is repeated more than once in the regex it can be consecutive in the test string or separated by other letters. The letters in the test string don't have to be in the same order as the regex. So if: TEST STRING = polymmorphiiic the following regex would match ppy ooyc ciii whereas the following would fail: pmy iy yrz Your help appreciated as I can get all the above satisfied. I have tried breaking down all the requirements and creating regex string for each but I can't get over string that will cover all. source https://stackoverflow.com/questions/76349191/regular-expression-that-matches-only-the-letters-in-a-given-word

Calculate difference between two times on Qualtrics

Respondents record a start time (time to bed) and and end time (time out of bed) in separate questions using flatpickr’s time picker. The responses are recorded in the format, for example, 11:00 PM and 8:00 AM, for start time and end time respectively. I need to calculate time in bed = (time out of bed - time to bed) in minutes. To calculate time in bed, I attempted the following: Qualtrics.SurveyEngine.addOnload(function() { /*Place your JavaScript here to run when the page loads*/ }); Qualtrics.SurveyEngine.addOnReady(function() { // get the values of the start and end time questions var timeToBed = "${q://QID4/ChoiceTextEntryValue}"; var timeOutOfBed = "${q://QID12/ChoiceTextEntryValue}"; // create Date objects for the start and end times var timeToBedDate = new Date("1/1/2000 " + timeToBed); var timeOutOfBedDate = new Date("1/1/2000 " + timeOutOfBed); // check if the end time is before the start

Generate HTML file with Spring that execute AngularJS scripts

I have an HTML page that displays information on a given country. I would like now to generate this HTML with Java, so that then I can reuse the code for another HTML page and don't duplicate it. I created this GET mapping in my controller @RequestMapping(path = "/region/{regionId:[\\d]+}", produces = MediaType.TEXT_HTML_VALUE) @ResponseBody public String regionPage(@PathVariable int regionId) { return pageService.getRegionPage(regionId); } And the pageService.getRegionPage returns for example the following String (that I formatted) <!doctype html> <html> <head> <title>Bhutan</title> <script src="/angular/angular.min.js"></script> <script src="/angular/angular-animate.js"></script> <script src="/angular/angular-route.js"></script> <script src="/angular/angular-cookies.js"></script> <script src=&quo

d3 polygon and trash icon on edge

I want to render polygon shapes in d3.js -- but on the edge of each polygon provide a trash icon so the polygon itself can be removed. Then keep a track of remaining polygons. 1 - how do you append circles/trash icons to the edge of polygon boundaries - near the top of the shape? 2 - how do you make/render trash icons -- a png image or another svg shape that gets attached http://jsfiddle.net/o9t6ardh/ <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script> $(document).ready(function() { var vis = d3.select("body").append("svg") .attr("width", 1000) .attr("height", 667); var scaleX = d3.scale.linear() .domain([-30, 30]) .range([0, 600]); var scaleY = d3.scale.linear() .domain([0, 50]) .range([500, 0]); var data = [ {

Python - Selenium: How can I upload File without Type: File

I´m trying currently upload a picture with Selenium to a site.I have tried sendkeys(doesnt work because Type: File is missing), autoit(work but I cannot change the Code and Fileurl in Python) and some other but nothing work for me. This is the Html-Code from the button: <div class="Polaris-Page-Header__RightAlign_1ok1p"><div class="Polaris-Page-Header__PrimaryActionWrapper_w8or9"><div class="Polaris-Box_375yx Polaris-Box--printHidden_15ag0"><button class="Polaris-Button_r99lw Polaris-Button--primary_7k9zs" type="button"><span class="Polaris-Button__Content_xd1mk"><span class="Polaris-Button__Text_yj3uv">Dateien hochladen</span></span></button></div></div></div> What can I use in this case or can I use Sendkey somehow? Thank you. source https://stackoverflow.com/questions/76348606/python-selenium-how-can-i-upload-file-without-type-file

Binding variable in loop changes it's type

I'm trying to make some order in a script that uses nicegui. I'm using a dictionary to store all button labels and the pages they will redirect to. I'm iterating over all keys in pages dictionary and calling ui.button for each of them. from nicegui import ui pages = {'page_one':'Page','page_two':'Page 2','page_three':'Page 3'} for page in pages: ui.button(pages[page], on_click=lambda page: ui.open(page)) when binding page it becomes a completely different type nicegui.events.ClickEventArguments instead of a normal string not binding page causes all buttons to redirect to page_three ui.button(pages[page], on_click=lambda: ui.open(page)) I feel like I completely misunderstand what actually binding is and how lambdas operate. Why is the page variable changing type when bound to function in this context? source https://stackoverflow.com/questions/76348605/binding-variable-in-loop-changes-its-type

Group element in list based on conditions and indexes

I have a set of lists composed of names and role. However, there is no real logic between how the list are organized. For instance, I have this list : l = ['john', 'owner', 'mark', 'manager', 'alex', 'steve', 'employee', 'manager'] #the last role shouldn't be assigned to anyone I want to assign each person the role that is located next to it in the list or the closest one from left to right. The desired output should be something like : output = [['john', 'owner'], ['mark', 'manager'], ['alex', 'employee'], ['steve', 'employee']] My guess was to add indexes to the list elements, and than check which element based on a set of condition was closest to the list element I was looking at. This is part of my script : parties_role = [(idx, item) for idx,item in enumerate(l)] for item in parties_role: if "owner" not in str(item[1])

Tensorflow simple cumulative sum of product rnn cell

Hello i am trying to build a tensorflow model that calculates a cumulative sum of products of two of the input features, ie predicting on only (1,2) should return 2, and then predicting on (2,2) should give 6=(1 * 2) + (2 * 2) model.predict([1,2]) >>> 2 model.predict([2,2]) >>> 6 model.reset_states() model.predict([2,2]) >>> 4 i have tried the following: import numpy as np import tensorflow as tf class MinimalRNNCell(tf.keras.layers.Layer): def __init__(self, units, **kwargs): self.states = np.array([0]) self.state = np.array([0]) self.units = units self.state_size = units super(MinimalRNNCell, self).__init__(**kwargs) def call(self, inputs, states): prev_output = states[0] output = tf.math.add(prev_output,inputs) return output, [output] # Define model #input inp = tf.keras.layers.Input(shape=(2,)) #split input x1,x2 = tf.split(inp, num_or_size_splits=2, axis=1) #c

How to plot a 3D bar chart with categorical variable

today I have tried to plot a 3D bar chart with python. For that I used my dataset containing 3 numeric variables and convert 2 in categorical variable, 'fibrinogen' and 'RR__root_mean_square' (by interval; 4 in total) with pd.cut() . An example of the first row of my dataset: Fibrinogen RR__root_mean_square Weight gain 2 5.15 26.255383 -2.0 3 0.99 20.934106 0.5 7 2.12 24.252434 -1.0 11 1.64 17.004289 3.0 12 3.06 21.201716 0.0 This is my own code : from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import pandas as pd # sample data data = {'Fibrinogen': [5.15, 0.99, 2.12, 1.64, 3.06], 'RR__root_mean_square': [26.255383, 20.934106, 24.252434, 17.004289, 21.201716], 'Weight gain': [-2.0, 0.5, -1.0, 3.0, 0.0]} X_success = pd.DataFrame(data) x1

Adding a child element to a container resets any ongoing css property transitions in other child elements

I have a script that creates a <span> every 1,000 ms, adding it to a <p> element through its appendChild function. The transition for opacity for these spans is set at 3,000 ms, and I have a setTimeout that changes the opacity from its initial value of 0.3 to 1.0 after 10 ms, i.e., right after the element is added it begins transitioning. The issue I'm having is that once a new <span> is added to the <p> any currently animating element skips its transition til its end, suddenly arriving at the final 1.0 value. Why is this happening? Can't I add an element to a container without messing with currently running transitions? const text = `This is just an example`; const words = text.replace(/\n/g, ` `).split(` `).filter(i => i); let i = 0; function add() { const container = document.getElementById('container'), span = document.createElement('span'), id = `s${i}`; span.innerText = words[i % words.length]; span

How to add a drop down list on this stamp I have in blue beam Revu Example would like a drop down on location with options like Edmonton, Calgary ETC

var builder = { // These map to Text Fields in the Stamp textBoxes : [ { field:"Location", description:"Location lsd:", default:function() { return ""; } }, { field:"WBS", description:"WBS Code:", default:function() { return ""; } }, { field:"BusinessUnit", description:"Buisness Unit Name:", default:function() { return ""; } }, { field:"GL Number", description:"GL Number Code:", default:function() { return ""; } }, { field:"Amount", description:"Amount Number:", default:function() { return ""; } } ] } help Via Active questions tagged javascript - Stack Overflow https://ift.tt/eM5WYGC

firebase function v2 trigger for realtimedatabase using a python script is not working for me

I am trying to use python with firebase functions. I already have a function running for my webhooks. but I tried to add another function to run when a new record is created on RealtimeDatabase, without success. I tried using the CLI at first, following the steps and using this code from the quickstart : from typing import Any # The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers. from firebase_functions import db_fn # The Firebase Admin SDK to access the Firebase Realtime Database. from firebase_admin import initialize_app, db app = initialize_app() @db_fn.on_value_written(reference="/Stores/{storeID}") def onwrittenfunctiondefault(event: db_fn.Event[db_fn.Change]) -> None: print(event.data) You can see I switched to on_value_written to catch any change on the path Stores/{storeID} I don't know what am i missing.. I also tried to create the function from google cloud console, created the eventarc trigger and it was deployed s

Swiper instance not yet available on window.load

I need to setup the click event on an Elementor carousel widget, which is swiper.js 8 under the hood. Problem is, depending on the page (same code works elsewhere), not even when window.load executes the swiper instance is available to work with: jQuery(window).on('load', function(){ const swiperTarget = jQuery('#dp-neighborhoods .swiper'); const swiperNeigh = swiperTarget.data('swiper'); if (swiperNeigh) { alert('found it'); //it doesn't swiperNeigh.on('click', clickSwiper); } function clickSwiper(swiper, event) {...} I can only get this to work if I call the function from a button, which is not ideal. A delay (Promise(resolve => setTimeout(resolve, time)) doesn't help either. Would there be another way to make this work? Via Active questions tagged javascript - Stack Overflow https://ift.tt/eM5WYGC

Why is Pyodide giving me a 'File is not a zip file' error when I try to install a .whl package using micropip?

I'm trying to import a .whl package using micropip into pyodide for use in an html file, but am getting an error about "must be a zip file"? Based on the documentation of micropip here , I assume the micropip.install() should be linked to a .whl file and not .zip. I used python3 -m build to create the .whl file, and then uploaded it to github. This is the error code: pyodide.asm.js:14 Uncaught (in promise) PythonError: Traceback (most recent call last): File "/lib/python3.10/asyncio/futures.py", line 201, in result raise self._exception File "/lib/python3.10/asyncio/tasks.py", line 234, in __step result = coro.throw(exc) File "/lib/python3.10/site-packages/micropip/_micropip.py", line 183, in install transaction = await self.gather_requirements(requirements, ctx, keep_going) File "/lib/python3.10/site-packages/micropip/_micropip.py", line 173, in gather_requirements await gather(*requirement_promises)

ScrollTop jerky in Chrome

I have this code and I am unable to achieve a fluid movement using Scroll-to-top function and Cubic bezier / 'easeInOutCubic' at lower speed (e.g 4000-6000). I've tried different alternatives with no luck. Would you please advise? Thanks. $(window).scroll(function() { if ($(this).scrollTop() > 350) { $('#scrlTop').fadeIn(); } else { $('#scrlTop').fadeOut(); } }); $('#scrlTop').click(function () { $('html, body').animate({ scrollTop: '0px' }, 4800, 'easeInOutCubic'); return false; }); #scrlTop { position: fixed; bottom: 16.6px; right: 18px; width: 57px; height: 57px; border-radius: 0%; background-color: black; display: none; backface-visibility: hidden; transform: translateZ(0); } /* Extra Things */ body{background-image: url(https://images.unsplash.com/photo-1484542603127-984f4f7d14cb?ixlib=rb-4.0.3&ixid

How to fix an Axios network error in a React Native fetch to a python Flask API?

I have this simple API from flask import Flask, request from flask_restful import Api, Resource from flask_cors import CORS from usingSavedModel import testImage app = Flask(__name__) CORS(app) api = Api(app) class Mushrooms(Resource): def post(self): image_url = request.json.get("image_url") #probabilities = testImage(image_url) return {"probabilities": "chicken"} api.add_resource(Mushrooms, "/mushrooms") if __name__ == "__main__": app.run(debug=True) And I am trying to access this API from a react native file: useEffect(() => { const sendRequest = async () => { url = "http://127.0.0.1:5000/mushrooms"; try { const response = await axios.post(url, { image_url: "aa" }); console.log(response.data); } catch (error) { console.log(error); } }; sendRequest(); }); No matter what I do I keep getting: {

django can you filter for different value for each object in one query

how to filter for different value for each object and is there is a better way to validate that amount of sales items wont be bigger than purchases items here is what I think is wrong in SaleItemListSerializer I am making a for loop and for each item I get its medicine and expiry date then finding sum by making 2 subquery and a query so if I have 15 item there will be 15 query on the database the total response time is in average about 0.8 s in sqlite but in mysql it grows to 1.5 ( still i want to add retrived items and disposed items in the supquery so it will grow bigger ) so is there is a way to annotate all medicine that are in items each with its expiry date ( which is stored in sale items and purchase items ) in one database query ? I think I am making alot of mistakes I am still new to django any help will be appreciated class SaleAddSerializer(serializers.ModelSerializer): items = serializers.ListField(child=serializers.DictField(),write_only=True,min_length=1) clas

Hovering over a thumbnail triggers audio but not video using the YouTube API in JavaScript - how can I fix this?

I am trying to make a YouTube video play when I hover on a thumbnail But it only plays the audio, I can't see the video and it doesn't stop playing when I stop hovering. Here is the code HTML <div class="thumbnail" data-video-id="D9N7QaIOkG8"> <img src="assets\meyra.jpg" alt="Thumbnail 1"> <div class="video-overlay"></div> </div> <script> function onYouTubeIframeAPIReady() { const thumbnails = document.querySelectorAll(".thumbnail"); thumbnails.forEach(function(thumbnail) { const videoOverlay = thumbnail.querySelector(".video-overlay"); const videoId = thumbnail.dataset.videoId; thumbnail.addEventListener("mouseenter", function() { const player = new YT.Player(videoOverlay, { videoId: videoId, width: "100%", height: "100%", playerVars: { autopl

Fetch multiple folders data into dataframe for given dates

I have storage container where data is in multiple folders with date appended at the end. (below) "dbfs:/mnt/input/raw/extract/pro_2023-01-01/parquet files here" "dbfs:/mnt/input/raw/extract/pro_2023-01-02/parquet files here" "dbfs:/mnt/input/raw/extract/pro_2023-01-03/parquet files here" "dbfs:/mnt/input/raw/extract/pro_2023-01-04/parquet files here" "dbfs:/mnt/input/raw/extract/pro_2023-01-05/parquet files here" It works fine with good performance if I try to read the data from one folder. example: df = spark.read.parquet("dbfs:/mnt/input/raw/extract/pro_2023-01-05/") But I have situation when I need to load the data for multiple days into dataframe (mostly weekly basis). For that I pull all data and then use temp view to filter based on folderLoadDate which one of the column in parquet files. In that case, it works but takes forever to run while it scans all the folder and do transformations, I think

AppState event persists across all app screens even when cleaned

I use the AppState API listener to run a function when the app comes from background to active state. I remove it on the useEffect cleanup, but it is still being called on the other screens like it was never cleaned. const MyRoute = ({ navigation, route }) => { const appStateRef = useRef(AppState.currentState); useEffect(() => { getUserData(); function updateRouteData(nextAppState) { if (appStateRef.current.match(/inactive|background/) && nextAppState === 'active') { getRoutes(); // <-- } appStateRef.current = nextAppState; } AppState.addEventListener('change', updateRouteData); return () => { AppState.removeEventListener('change', updateRouteData); }; }, []); // ... } The AppState event listener persists on the other screens. react-native: "0.64.4" Via Active questions tagged javascript - Stack Overflow https://ift.tt/oRDvpgH

update multiple fields in django

I have Inventory and Product Classes in models - The Product class have Inventory.item as ManyToManyField I can select items and save them in Product.items from Inventory.item. I try to get quantity from request.POST.getlist() and submit request when I submit the request I want the Inventory.quantity to by subtract automatically whatever gets values as list from request.POST.getlist() after subtract Inventory.quantity model will update the items quantity by update this my codes. I am not sure if I make correctly update I still get AttributeError: 'list' object has no attribute 'split' models.py class Inventory(models.Model): stock_transaction_numbers = models.PositiveBigIntegerField(null=True, blank=True, unique=True,) item = models.CharField(max_length=700,null=True, blank=True) unit = models.CharField(max_length=100,null=True, blank=True) quantity = models.IntegerField(null=True, default=0, blank=True) class Product(models.Model):

Setting React state from JSON data in useEffect

I need to fetch json data and iterate over it, fetching some more json data later, and finally setting React states. I'd like to use a general function to handle all file requests. I'd also like to handle different types of errors ( 404 and json parsing, mostly). I've read How to use async functions in useEffect and several other relevant articles, but whatever I try to do outside of my fetchData function, I keep getting only Promises instead of data. Also, this only needs to be done once, when the main App.js load. Is it good practice to use an Effect for that, or should it be done at the top of the file, before the App component itself (which needs the data)? useEffect(() => { async function fetchData(url) { const response = await fetch(url, { headers : { 'Content-Type': 'application/json', 'Accept': 'application/json' } }) if (!response.ok) { return Promis

Trouble tracing source of queries in a dynamically generated table from a GET request in JavaScript

I have this URL , and when it opens it loads up a table dinamically using JavaScript. I looked into the network tab while the page is loading, and found out that there is a GET request to get a JSON file for the table, which pings the /fnet/publico/pesquisarGerenciadorDocumentosDados route with some extra queries. Most of them are the same for any cnpjFundo , but there are two queries I'm having trouble finding where they come from: administrador and _ . Is there a way I can find where the website is pulling these values from? I've tried looking through some of the js scripts, but I can't make sense of anything. Via Active questions tagged javascript - Stack Overflow https://ift.tt/oRDvpgH

Json data extraction using python

I have this python script that gives me results from an API query: import requests import json url = 'https://zabbix.enterprise.net/zabbix/api_jsonrpc.php' token = '6e..5d' headers = {'Content-Type': 'application/json'} get_hosts_payload = { 'jsonrpc': '2.0', 'method': 'host.get', 'params': { 'output': 'extend', 'selectTags': 'extend' }, 'auth': token, 'id': 1 } response = requests.post(url, data=json.dumps(get_hosts_payload), headers=headers) # Process response if response.status_code == 200: result = response.json()['result'] for host in result: print(host) print('Host Name:', host['name']) print('Description:', host['description']) #??? print('Tag:', host['tags': {'tag': 'parent'}]) else: print('Request fa

If statement running every second

This is a really simple question, I'm building a timer in React JS and I want to know if this is right. There is a setInterval() on my app that every second decreases 1 to my "seconds" state, which is this one: const [seconds, setSeconds] = useState(0) const [minutes, setMinutes] = useState(0) const [isPaused, setIsPaused] = useState(true) timerId.current = setInterval(() => { setSeconds(prev => prev - 1) }, 1000); And this useEffect checks EVERY SECOND if the timer is running AND if seconds is < than 0, to increase minutes and adds 59 more seconds. useEffect(() => { // if timer isn't running return if (isPaused) { return } // reset seconds and decrease minutes if (seconds < 0) { setSeconds(59) setMinutes(prev => prev - 1) } }, [seconds]) My question here is, isn't it bad for the useEffect to run two if statements every second? Like, wouldn't it be bad for performance? And if it reall

How can I generate T1-T14 values in a new column by comparing dates in a pandas dataframe?

I am trying to compare column values to the actual dates and based on the create a new column where it measures the difference between the dates as T1-T14(T1 being the one difference between actual date and column date) I tried to use where condition where we compare the actual date to the column date and output the result to a new column based on the difference between those two. But unable to achieve the same. Actual Data: Actual Data Desired Output: Output Data source https://stackoverflow.com/questions/76318302/how-can-i-generate-t1-t14-values-in-a-new-column-by-comparing-dates-in-a-pandas

how to rewrite logics without using arrow functions

How to rewrite logics for saving state of component without using arrow functions in Nextjs code? import { useState, createContext, useContext } from "react"; export const FormContext = createContext(); export default function FormProvider({ children }) { const [data, setData] = useState({}); const setFormValues = (values) => { setData((prevValues) => ({ ...prevValues, ...values, })); }; return ( <FormContext.Provider value=> {children} </FormContext.Provider> ); } export const useFormData = () => useContext(FormContext); Via Active questions tagged javascript - Stack Overflow https://ift.tt/zP4yRmk

Python: remove duplicates in a dictionary list based on 2 values,

I have this dictionaries list: [{'emailAddress':'user1@test.com','role':'writer','displayName':'USER1','type':'user','resultRole':'writer'}, {'emailAddress':'user2@test.com','role':'owner','displayName':'USER2','type':'user','resultRole':'owner'}, {'emailAddress':'user1@test.com','role':'writer','displayName':'USER1','type':'user','resultRole':'multiplex'}, {'emailAddress':'user2@test.com','role':'owner','displayName':'USER2','type':'user','resultRole':'owner'}, {'emailAddress':'user3@test.com','role':'commenter','displayName':'USER3','type':'user','resultRole':'multiplex'}] I want to remove

How can I type in the terminal after the process of "yarn start"?

I am building a Node chat app and I want to type in the terminal something but I can't type anymore after I enter the "yarn start" I am following a tutorial and he can type in his terminal after he enter the "yarn start" but in my case I can't Via Active questions tagged javascript - Stack Overflow https://ift.tt/IR32a6p

Astropy weighted circular mean with numpy ndarrays, encountering TypeError: only integer scalar arrays can be converted to a scalar index

Hello all and thank you for any assistance in advance. I am using the astropy circmean function ( https://docs.astropy.org/en/stable/api/astropy.stats.circmean.html ) to evaluate the weighted circular mean of an array of angles. The function takes a numpy ndarray for the angles in radians and another ndarray for the weights. I am getting a type error when trying to input a numpy array for the weights. I can reproduce the error with this code: import numpy as np from astropy.stats import circmean circmean(np.array([.05, -np.pi/2, np.pi]), np.array([1, 1, 10])) Error: TypeError: only integer scalar arrays can be converted to a scalar index I tried checking that the arrays were the required data type and changing the data type of the weights entries. The function works without the weights, but I need to use the weighting. I was expecting the function to work and calculate the desired weighted mean. source https://stackoverflow.com/questions/76309526/astropy-weighted-circular-mea

how to view all items mat-select multiple

I'm using Angular Material and I would like to know if it is possible to automatically increase the size of mat-select when I select several security groups, because today when I select several, it can only visualize the groups that fit in the mat-select space. I wanted to be able to view all security groups. Selected Groups - Mat-Select HTML: <mat-form-field class="matfield" appearance="outline" required> <mat-label>Secure Group</mat-label> <mat-select class="mat-select-securegroup" [formControl]="secureGroups" multiple> <mat-option *ngFor="let secureGroups of secureGroupsList" [value]="secureGroups"></mat-option> </mat-select> </mat-form-field> COMPONENT.TS: secureGroups = new FormControl(''); secureGroupsList: string[] = ['Secure Group 1', 'Secure Group 2', 'Secure Group 3', 'Secure Group

How to eliminate nested arrays to create a "clean" 2d array

I have the below function, but it is not returning the desired result. How can I change this so it returns the desired output? function convertArr () { const separateNestedArrays = function (arr) { return arr.flatMap((element) => { if (Array.isArray(element)) { return element; } else { return [element]; } }); }; const twoDimensionalArray = [ [1, 2, 3, 4], [[5, 6], [9, 10]], [5, 6, 7] ]; const modifiedArray = separateNestedArrays(twoDimensionalArray); console.log(modifiedArray); // Desired Output: [[1, 2, 3, 4], [5, 6], [9, 10], [5, 6, 7]] // Current Output: [ 1, 2, 3, 4, [ 5, 6 ], [ 9, 10 ], 5, 6, 7 ] }; Via Active questions tagged javascript - Stack Overflow https://ift.tt/IR32a6p

Why use var or let [duplicate]

I am learning javascript. I find that variables can be declared using var or let . However, I also find that the code works well even if variables are used without any of these 2 keywords. Hence, I can use any of following: name = ""; var name = ""; let name = ""; Why should I use var or let if they are not essential? Thanks for your insight. Via Active questions tagged javascript - Stack Overflow https://ift.tt/IR32a6p

Pandas UDF Error: AttributeError: 'NoneType' object has no attribute '_jvm' [duplicate]

I have a pyspark dataframe like this: +-------+-------+ | level | value | +-------+-------+ | 1 | 4 | | 1 | 5 | | 2 | 2 | | 2 | 6 | | 2 | 3 | +-------+-------+ I have to create a value for every group in level column and save this in lable column. This value for every group must be unique, so I use ObjectId Mongo function to create that. Next dataframe is like this: +-------+--------+-------+ | level | lable| value | +-------+--------+-------+ | 1 | bb76 | 4 | | 1 | bb76 | 5 | | 2 | cv86 | 2 | | 2 | cv86 | 6 | | 2 | cv86 | 3 | +-------+--------+-------+ Then I must create a dataframe as following: +-------+-------+ | lable | value | +-------+-------+ | bb76 | 9 | | cv86 | 11 | +-------+-------+ To do that, first I used spark groupby : def create_objectid(): a = str(ObjectId()) return a def add_lable(df): df = df.cache() df.count() grou

I get http://localhost:3000/api/auth/error?error=AccessDenied in my NextJs application using google signin. Why?

Pleas Help me To solve this problem. http://localhost:3000/api/auth/error?error=AccessDenied in my NextJs application using google signin. Why? Here is my [...nextauth] file ... Here is my Nav component where I want to pass the signin function... When I click on it, it returns a 404 response yet I am supposed to see this below: How I Sove It? Via Active questions tagged javascript - Stack Overflow https://ift.tt/f0PSIYB

How to get button to display happy/sad emoji, temp and city?

Could I get some help with this project. it's for shecodes, I need it to ask what city and temp when clicking the button and also add a smile or frowny face if temp above 0 and for below 0. Thanks in advance for the help! <button>Change city</button> <script> function changeCity() { let city = prompt("What city do you live in?"); let temp = prompt("What temperature is it?"); let h1 = document.querySelector("h1"); h1.innerHTML = "Currently " + temp + " in " + city + if (temp > 0) ("😍") else ("😭") ; } let weatherButton = document.querySelector("button"); weatherButton.addEventListener("click", changeCity); Via Active questions tagged javascript - Stack Overflow https://ift.tt/f0PSIYB

Pandas issue pulling a number from a string input from a CSV file

I have a csv file with the contents: StrainMax 0.125 StrainMin -0.125 cycles_sec 10 time_percent 50 I read it in with: df = pd.read_csv('Strains_SI.csv', index_col=None, header=None) Then this: StrainMax = df.iat[0,0] StrainMin = df.iat[1,0] cycles_sec = df.iat[2,0] time_percent = df.iat[3,0] print(StrainMax) print(StrainMin) print(cycles_sec) print(time_percent) And what I get is this (I believe these are strings): StrainMax 0.125 StrainMin -0.125 cycles_sec 10 time_percent 50 But what I want is this: 0.125 (I want an float here) -0.125 (I want an float here) 10 (I want an integer here) 50 (I want an integer here) Is this possible? I tried numerous Pandas commands and can't get it. I am expecting floats and integers of the numbers only. source https://stackoverflow.com/questions/76301629/pandas-issue-pulling-a-number-from-a-string-input-from-a-csv-file

python ValueError 'input contains NaN'

This is the code cell from my program where I am facing an error. Dataset used for the program is twitter.csv. x = np.array(df["tweet"]) y = np.array(df["labels"]) cv = CountVectorizer() x = cv.fit_transform(x) x_train, x_test, y_train, y_test = train_test_split(x,y, test_size= 0.25, random_state= 42) clf = DecisionTreeClassifier() clf.fit(x_train,y_train) Error occured is: ValueError Traceback (most recent call last) Cell In[52], line 8 6 x_train, x_test, y_train, y_test = train_test_split(x,y, test_size= 0.25, random_state= 42) 7 clf = DecisionTreeClassifier() ----> 8 clf.fit(x_train,y_train) File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\sklearn\tree\_classes.py:889, in DecisionTreeClassifier.fit(self, X, y, sample_weight, check_input) 859 def fit(self, X, y, sample_weight=None, check_input=True): 860 ""&quo