Skip to main content

Posts

Showing posts from April, 2022

Ebay API "The ISBN field is missing. Please add ISBN to the listing and try again." but its there

Hopefully you can help as not even the ebay dev forums seem to be able too :S So i am uploading books, out of 90,000 only 12,000 has listed and i always get this error "The ISBN field is missing. Please add ISBN to the listing and try again." When i print the data being uploaded i get this :- {'availability': {'shipToLocationAvailability': {'quantity': 0}}, 'condition': 'NEW', 'product': {'title': 'Niteblessings : Meditations to close the day', 'description': '', 'aspects': {'format': ['294g'], 'format_title': ['Hardback 208 pages'], 'pagination': ['Hardback 208 pages'], 'imprint': ['Lion Books'], 'edition': ['New ed'], 'ISBN': ['0745981550'], 'published': ['22 Oct 2021'], 'classifications': ['22 Oct 2021'], 'readership': ['22 Oct 2021'], 'di...

How to interpret this strange Python routine coding format

I came across a strange format of Python code about routine. What is the actual meaning? def get_values() -> list: query = "select value from table" result = db.execute(query) return [ value[0] for value in result ] I think the -> list means this routine returns data type list but I don't understand how the return (build a list)? Why it is value[0] ? source https://stackoverflow.com/questions/72069885/how-to-interpret-this-strange-python-routine-coding-format

Python - Checking for common cooardinate between 3D ndarray and 2D ndarray without using loops! (Numpy)

Im trying to solve a problem in which I am given 2 ndarray of booleans . one of shape (n,m,z), denote as A, and the other (n,m), denote as B. If I am thinking of the 3D array as an array of 'z' 2D arrays, I would like to check if for every i between 0 and z, there is at least one coordinate [x,y] that: A[x,y,i] == B[x,y] == 1. for example: let A be np.array([[[1,0,0], [0,1,0], [0,0,1]] , [[0,1,0], [0,1,0], [0,1,0]], [[1,0,0], [0,1,0], [0,0,1]]]) and B be: > [[1,0,0], [0,1,0], [0,0,1]]) The function should return True! I need to solve it without any loops (just numpy tools)! Thank you in advance. source https://stackoverflow.com/questions/72071507/python-checking-for-common-cooardinate-between-3d-ndarray-and-2d-ndarray-witho

How to force Python to reinstall utilities package when python can't figure out the version to install - versions: none

I'm trying to install the utilities package for python 3.10, but when I run pip3 install --upgrade --force-reinstall utilities , I just get an error as shown below. What is wrong here? How can I get this package installed? (venv_3.10) brad:integration-testing$ python3 QA/lib/framework/cpap/launcher.py ... Traceback (most recent call last): File "/home/brad/Development/integration-testing/integration-testing/QA/lib/framework/cpap/launcher.py", line 22, in <module> from utilities import get_logger, logging ModuleNotFoundError: No module named 'utilities' (venv_3.10) brad:integration-testing$ pip3 install utilities ERROR: Could not find a version that satisfies the requirement utilities (from versions: none) ERROR: No matching distribution found for utilities (venv_3.10) brad:integration-testing$ pip3 install --upgrade --force-reinstall utilities ERROR: Could not find a version that satisfies the requirement utilities (from versions: none) ERROR: No matc...

tkinter: How to start a new line after opening parenthesis?

I have a program with my code, the idea is: I have a textbox, I put a text in it and with I button I need to create a new line after any open parenthesis. I have little experience with tkinter and I don't even know where to start to do this, I also went to do further research but found no documentation. source https://stackoverflow.com/questions/72071493/tkinter-how-to-start-a-new-line-after-opening-parenthesis

Using Angular Material Button by itself in a Stackblitz?

I use Angular Material all the time on Stackblitz, and usually I import a kitchen sink module, and everything just works. Now I'm trying to just import the Angular Material Button Module, and I get the error: Error in src/app/app.component.ts (8:14) Unable to import component MatButton. The symbol is not exported from /turbo_modules/@angular/material@13.3.5/button/button-module.d.ts (module '@angular/material/button/button-module'). This is the Stackblitz: https://stackblitz.com/edit/angular-ivy-wxvebj?file=src%2Fapp%2Fapp.module.ts Any ideas? Via Active questions tagged javascript - Stack Overflow https://ift.tt/ygT7oqd

client disconnect after one message in mqtt

import time client = mqtt.Client() client.connect("test.mosquitto.org", 1883) def on_connect(client, userdata, flags, rc): print("Conectando al Servidor - " + str(rc)) client.subscribe("Valve_OC") client.subscribe("Medir") def on_message(client, userdata, message): # The callback for when a PUBLISH message is received from the server. global message_received time.sleep(1) message_received=str(message.payload.decode("utf-8")) print("received message =", message_received) valor_mensaje= int(float(message_received)) #el potenciometro va de 0 a 1023, simulamos que es el sensor de temperatura if (valor_mensaje<=300): #apertura 100% print("abrir completamente la valvula") client.publish("Valve_OC", "Abrir,100") print("valor publicado en topic Valve_OC") time.sleep(3) client.disconnect() elif (valor_me...

Linear mixed models with one predictor depending on another in Python

I've recently started analysing the data for a project using linear mixed models but am not sure how to deal with a predictor that depends on another. In my study, each participant reported two events (Event: A & B) and whether they discussed each event with someone else (Status: shared or not shared). In other words, besides event which was a within subjects predictor, I also have two responses from each participant regarding status for each event. A participant can have discussed Event A but not Event B (or the vice versa), both events, or neither of the events. The dependent variable is perceived emotional change. I initially structured the model in this way: mod = smf.mixedlm("emotion_change ~ Event * Status", data, groups=data["participant"]).fit() However, I realised that the model should probably be hierarchical because each Status response was specifically for one of the events, so I created two variables instead: Status_PE and Status_NS, and the...

Linux Python how to use libraries from an IDE

I have installed tensorflow and OpenCV in a virtual environment (located pi/projects/env) In terminal I can access the environment then run "python3" to test if tensorflow is working. But I don't know how I can use tensorflow/opencv from an IDE (importing the libraries doesn't work) and gives an error saying the module has not been found. So how do I add the path to the libraries to my IDE so it compilies the libraries? *I am currently using Geany IDE on a raspberry pi 4 source https://stackoverflow.com/questions/72059544/linux-python-how-to-use-libraries-from-an-ide

Segmentation for calculating Average speed for electric vehicle

I am trying to calculate average energy consumption of electric vehicles. For calculating that, I am using speed parameter from the dataset. Trying to segment the speed based on time per second. Need python coding for machine learning to segment speed profile for every 120 seconds and then to calcuate average speed from start to end of the segment. I am having 10000 records in my dataset with 40 columns. The coding I used for plotting is import matplotlib as pyplot ax=df['speed'].plot(figsize=(12,6), fontsize=10) plt.xlabel('time in sec', fontsize=20) plt.ylabel('Speed') The above displays a simple graph of speed profile. Need help on segmentation based on time . source https://stackoverflow.com/questions/72062750/segmentation-for-calculating-average-speed-for-electric-vehicle

Vaex expression to select all rows

In Vaex, what expression can be used as a filter to select all rows? I wish to create a filter as a variable and pass that to a function. filter = True if x > 5: filter = y > 20 df['new_col'] = filter & z < 10 My wish is that if x <= 5 it will ignore the filter (thus I'm trying to use True as a value). Doing it this way gives the error 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' What expression will select all rows? source https://stackoverflow.com/questions/72062845/vaex-expression-to-select-all-rows

Show and hide with CSS animation

My goal is to create an animation when showing and hiding an HTML element. The show and hide is triggered by a button that toggles a class hide. Here is my code: const button = document.querySelector('button'); const box = document.querySelector('.box'); button.addEventListener('click', () => { box.classList.toggle('hide'); }) .box { width:200px; height: 200px; border: 1px solid #000; background-color: gray; margin: 0 auto; opacity: 1; display: block; } .hide { display: none; transition: all 1s ease-out; opacity: 0; } <button>Show / Hide</button> <div class="box hide"></div> Via Active questions tagged javascript - Stack Overflow https://ift.tt/YxEfMja

In Python, If there is a duplicate, use the date column to choose the what duplicate to use

I have code that runs 16 test cases against a CSV, checking for anomalies from poor data entry. A new column, 'Test case failed,' is created. A number corresponding to which test it failed is added to this column when a row fails a test. These failed rows are separated from the passed rows; then, they are sent back to be corrected before they are uploaded into a database. There are duplicates in my data, and I would like to add code to check for duplicates, then decide what field to use based on the date, selecting the most updated fields. Here is my data with two duplicate IDs, with the first row having the most recent Address while the second row has the most recent name. ID MnLast MnFist MnDead? MnInactive? SpLast SpFirst SPInactive? SpDead Addee Sal Address NameChanged AddrChange 123 Doe John No No Doe Jane No No Mr. John Doe Mr. John 123 place 05/01/2022 11/22/2022 123 Doe Dan No No Doe Jane No No Mr. John Doe Mr. John 78...

Why this function in tkinter doesn't work?

I have this simple program just for understand and you can run for trying it, when I enter with the ,ouse in the Entry/text box the button "Nome utente" get eliminate in the "distruggi_pulsante" function. When I leave the text area the button is recreated in the "crea pulsante" function, but why does it work only once? The first enter-leave cycle works but in the second the button doesn't get destroyed. Here is my code : from tkinter import * def distruggi_pulsante(e): bottone_nome_trasparente.destroy() def crea_pulsante(e): bottone_nome_trasparente = Button(window, text="Nome utente", bg="white", fg="grey", relief="sunken", bd=0) bottone_nome_trasparente.configure(activebackground="white") bottone_nome_trasparente.configure(activeforeground="grey") bottone_nome_trasparente.place(x=802, y=201) window = Tk() window.state('zoomed') window.title("Facebook"...

Is this structures of SQL models okay? (Flask)

I am creating a chat application in flask where you can create users and chat with others. I am storing all the information in SQLAlchemy. I was wondering if this structure for my models is okay. I am still a beginner with Flask and SQLAlchemy so I may have errors. from . import db from flask_login import UserMixin user_chat = db.Table("user_chat", db.Column("user_id", db.Integer, db.ForeignKey("user.id")), db.Column("chat_id", db.Integer, db.ForeignKey("chat.id")) ) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(150), unique=True) username = db.Column(db.String(150), unique=True) password = db.Column(db.String(150)) firstName = db.Column(db.String(150)) lastName = db.Column(db.String(150)) birthday=db.Column(db.String(150)) sport = db.Column(db.String(150)) bio = db.Column(db.String(150)) chats = db.relationship("Chat...

BabylonJS Lathe Shape Update

Has anyone come across a method to update the shape and/or other options in a lathe mesh? Currently I'm just redrawing them, but every update called on it just creates a new one, and disposing it is not working. What I want to do is basically just: this.lathe.shape = pointArray; But I don't think there is any way to access it or set it. I have tried this method of disposing and building a new mesh and it doesn't work and is not ideal for what I'm trying to do: this.lathe.dispose(); this.lathe = BABYLON.MeshBuilder.CreateLathe(...); Via Active questions tagged javascript - Stack Overflow https://ift.tt/8u6HOro

Why does a browser apply CSS styles first before deciding what onclick event handler to call?

I have a single div on a page. It has an onclick event handler. When the user clicks on that div I expect that the event handler will be called. But there is this CSS rule as well: when that div has a focus, it will be moved 50 pixels to the right (away from the mouse pointer). As a result of this the onclick event handler is not called, even though the user clearly clicked on that div at the beginning. It's as if the browser first applies CSS and only after that decides, what did the user clicked on. I made a simple demo here: https://jsbin.com/yalazam/edit?html,css,console,output Click on the yellow square (that is the div ) in the fourth column and see the console in the third column. Only a message "focus square" will appear, but not a "click square" . Does this behavior makes any sense? Is there any case when it is useful? Or should I just accept it as a weird behavior of the browser? Via Active questions tagged javascript - Stack Overflow https...

How to remove keys and lift props up?

Given the following object: { __proxy: { state: { count: 0 items: { __proxy: { state: { amount: 0 } } } } } } I'd like to convert it to: { count: 0, items: { amount: 0 } } So, as you can see, I'm doing a few things: Removing __proxy and bringing its content up Removing state and bringing its content up All of the above recursively. I've tried something like the snippet below: const removeKeys = (obj, keys) => obj !== Object(obj) ? obj : Array.isArray(obj) ? obj.map((item) => removeKeys(item, keys)) : Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k))); removeKeys(myObj, ['__proxy', 'state']) However, it completely removes __proxy and/or state - and I want to preserve their content. That said, do you know any existing solution for that? A NPM library, perhaps? Or a lodash function? Thanks! Via Acti...

Javascript event when first accessing the website

this is a pretty simple question in theory, but i can't seem to find an answer: is there such a thing as an event for when a user first accesses a website ? something like onload , but for the whole website, not for a single page. basically i'm writing a website in Python Flask with Jinja. part of the website retrieves information from wikipedia, which slows the website a lot. so i added a toggle switch to activate / deactivate the wikipedia bit. however, i can't seem to find a consistent way to define a default value for the button (when accessing the website, wikipedia enhancements are activated) while also keeping the button's value when navigating through the website (the button's value doesn't change unless you tell it to). everything else works fine: toggling wikipedia enhancements on and off... i'm using Flask and Jinja, so if you have an idea using that, it's fine to ! here's the html button: <label class="toggle" id="...

Need to hide js file or minify it from the web browser after prod build in React

After using npm run build cmd with the following script in package.json file in my React App, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false' && react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, FYI: I am using windows machine. The js code is not hiding from the browser stil I can see from the browser sources tab. I am using spring application as backend. Can anyone tell me how can I do hide js file or minify it after prod build. Via Active questions tagged javascript - Stack Overflow https://ift.tt/8u6HOro

Is it normal Redux removes a local state in this situation?

I'm struggling to understand Redux and am loosing a local state upon hitting a button on a React page. The situation is as follows: Suppose you are on a React page, which has a local state: {"player": "PersonA"} There's also a button on the same React page. Pushing the button triggers a Redux action. The associated controller method returns: return res.status(200).json({ statusCode: 200, success: true, payment: {"amount": "3", "currency": "EUR"}, }); And the reducer: case APPLY_SUCCESS: console.log(...state); // returns undefined return { ...state, paymentData: action.payload.payment }; After hitting the button on the React page, the local state only contains paymentData . So player is gone from the local state. I thought ...state in the reducer should ensure maintaining the existing local state that is unaffected by the action. So it would just append paymentData to the local state and al...

Using complete dataset for future prediction in Azure Machine Learning Studio [closed]

I am developing an automated machine learning mechanism. I am using Azure machine learning studio. During development, I got the requirement to use the complete dataset for training. Now my point is to find, is there any such mechanism to use the complete dataset for training without using it for testing. How do I use the current prediction model to identify future predictions from the current data? source https://stackoverflow.com/questions/72033872/using-complete-dataset-for-future-prediction-in-azure-machine-learning-studio

How to track rows between two specific occurrences in a column?

I have a following dataframe: How to keep track of occurrences when a specific user is working on a specific tab in a way as shown on the following image? For example: In the first row, user A opened a "Tab Alpha" and I would like to store the value "Tab Alpha" in a newly generated column "User A" in each row until the value "Tab Alpha closed by User A". Expected output: Link to dataframe: https://docs.google.com/spreadsheets/d/1vt5TgYRwMTA8X26S7BtjrXudM_Vih4BUT0AzfQJbO_I/edit?usp=sharing source https://stackoverflow.com/questions/72027479/how-to-track-rows-between-two-specific-occurrences-in-a-column

How to combine spaxels together within an area of a fits file?

I have a fits file that I have open and closed and then produced a spectrum of one single spot within this image. I now need to create a loop and add the spaxels within some area together to produce a stacked spectrum. Any ideas of how I would do this? hdul=fits.open('ADP.2016-09-08T02:00:17.312.fits') hdul.info() cube=hdul[1].data print(np.shape(cube)) #cube[:. iy, ix] header=hdul[1].header wave=header['CRVAL3']+np.arange(header['NAXIS3'])*header['CD3_3'] print(wave) hdul.close plt.close('all') fig=plt.figure() ax=fig.add_subplot(111) fig.set_figwidth(15) ax.set_ylim(1,1e4) ax.set_yscale('log') ax.set_xlim(4800,6900) ax.plot(wave,cube[:, 53-1,237-1],linewidth=0.75) fig.tight_layout() source https://stackoverflow.com/questions/72034891/how-to-combine-spaxels-together-within-an-area-of-a-fits-file

semicolon insertion puzzlement in front of [] [duplicate]

Why did I need a semicolon at }) right before [inTitle line ? I spend whole bunch of time troubleshooting this and saw that the reason it wasn't working because I omitted semicolon. And I know now it works this way and I assume it has to do w/ what comes up next but I just cannot figure out the documentation that has this info. Can someone please point me to right direction? btnAddNote.addEventListener('click', () => { this.onNoteAdd() }); [inpTitle, inpBody].forEach(inputField => { inputField.addEventListener("blur", () => { const updatedTitle = inpTitle.value.trim() const updatedBody = inpBody.value.trim() this.onNoteEdit(updatedTitle, updatedBody) }) }) Via Active questions tagged javascript - Stack Overflow https://ift.tt/8u6HOro

GAN generator loss is 0 from the start

I need data augmentation for network traffic and I'm following an article in which the structure of the discriminator and generator are both specified. My input data is a collection of pcap files, each having 10 packets with 250 bytes. They are then transformed into a (10, 250) array and all the bytes are cast into float64. def Byte_p_to_float(byte_p): float_b = [] for byte in byte_p: float_b.append(float(str(byte))) return float_b Xtrain = [] a = [] for i in range(len(Dataset)): for p in range(10): a.append(Byte_p_to_float(raw(Dataset[i][p]))) # packets transform to byte, and the float64 Xtrain.append(a) a = [] Xtrain = np.asarray(Xtrain) Xtrain = Xtrain / 127.5 - 1.0 # normalizing. I then go on training the model but the generator loss is always 0 from start! batch_size = 128 interval = 5 iterations = 2000 real = [] # a list of all 1s for true data label for i in range (batch_size): real.append(1) fake = [] # a list of all 1s ...

Call function multiple time nodejs

I have following code, to insert passwords on a website. require('chromedriver'); var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder() .forBrowser('chrome') .build(); driver.get('https://junusergin.github.io/hack-mich/login.html'); let dictionary = [123456, 123456789, 12345, "qwerty", "password", 12345678, 111111, 123123, 1234567890, 1234567, "qwerty123", "000000", "1q2w3e", "aa12345678", "abc123"]; function tryCombinations(combinations) { let index = 0; inputField = driver.findElement(webdriver.By.id('username')); driver.executeScript("arguments[0].setAttribute('value', 'test')", inputField); inputField = driver.findElement(webdriver.By.id('password')); driver.executeScript("arguments[0].setAttribute('value', '" + combinations[index] +...

TypeError: Cannot read properties of undefined (reading '0') in NodeJS

I have the TypeError: Cannot read properties of undefined (reading '0') with game_id: result.data[0].game_id, warning in my terminal, What is weird is that the console.log("result ", result); shows me what I need, but below I can't access result.data[0].game_id Code return promise1.then((result) => { console.log("result ", result); <-- ALL GOOD HERE if (!result && !result.data && !result.data[0]) return; Stream.findOne({}).then((stream) => { if (!stream) { let streamInfos = new Stream({ game_id: result.data[0].game_id, <-- ISSUE HERE Output of the console.log("result ", result); {"data": [{ "id":"45300981596", "user_id":"90849777", "user_login":"versifixion", "user_name":"VersifiXion", "game_id":"21779", "game_name":"League of Legends...

Load large files without killing process python - memory management

I am creating a compression algorithm using python - however, when loading large files and datasets (usually 1 or 2 gb+), the process is killed do to running out of RAM. What tools and methods are available to allow saving memory, while also having the entire file available to access and iterate too. The current code is right here (dev branch). source https://stackoverflow.com/questions/72020651/load-large-files-without-killing-process-python-memory-management

Is my for-loop that iterates through a list of strings and function correct? [closed]

I am trying to iterate through a data frame that has these columns as the names. Is this correct? For context, The lists above are the column names, and the newel_var is the new columns I am creating as a result. This is what I Have #Difference between home and away variabls to also help visualize and create #curvefit lines #must create columns in data frame that include these stats_by_yr.keys() ##lists holding the column names for each column based on home or away home_var = [ "PTS_home","FG_PCT_home", 'FT_PCT_home', 'FG3_PCT_home', 'AST_home', 'REB_home', "HOME_WIN_PCT" ] away_var = [ "PTS_away","FG_PCT_away", 'FT_PCT_away', 'FG3_PCT_away', 'AST_away', 'REB_away', "AWAY_WIN_PCT"] newcol_var = ["PTS_dif","FG_PCT_dif", 'FT_PCT_dif', 'FG3_PCT_dif', 'AST_dif', 'REB_d...

How do I iterate the price in parentheses and add it to the total price, My code doesn't seem to work

I've found this on google and gave it a go. But it seems as if its not doing anything. it isn't updating the price total area at all, nor is it adding or subtracting. <script type="text/javascript"> function doMath() { // Capture the entered values of two input boxes var my_input1 = document.getElementsByName("case").value; var my_input2 = document.getElementsByName("cpu").value; var my_input3 = document.getElementsByName("cooling").value; var my_input4 = document.getElementsByName("ram").value; var my_input5 = document.getElementsByName("gpuchoice").value; var my_input6 = document.getElementsByName("storage").value; var my_input7 = document.getElementsByName("storage1").value; var my_input8 = document.getElementsByName("storage2").value; var my_input9 = document.getElementsByName("powersupchoic...

Using base_score with XGBClassifier to provide initial priors for each target class

When using XGBRegressor, it's possible to use the base_score setting to set the initial prediction value for all data points. Typically that value would be set to the mean of the observed value in the training set. Is it possible to achieve a similar thing using XGBClassifier, by specifying a value for every target class, when the objective parameter is set to multi:softproba ? E.g. computing the sum of each occurrence for each target class in the training set and normalizing by percentage of total would give us: class pct_total -------------------- blue 0.57 red 0.22 green 0.16 black 0.05 So that when beginning its first iteration, XGBClassifier would start with these per-class values for every data point, instead of simply starting with 1 / num_classes for all classes. Is it possible to achieve this? source https://stackoverflow.com/questions/72013683/using-base-score-with-xgbclassifier-to-provide-initial-priors-for-each-target-cl

change value of tom select after rendering it

I'm working on an update function that uses tom-select ( https://tom-select.js.org/ ). The process goes as follows: 1- the user clicks on the edit button 2- a bootstrap modal will open and the data of the selected row will show so he can update them. the problem: after rendering the selector I want to change it's value to select the value of the selected item, I tried this code: $('#select-beast-update').val(response.data.book.author_id).change() but it's not working, then I tried using the onInitialize:function() -refer to this link at the callbacks section to get more details https://tom-select.js.org/docs/ - and it also did not work. this is my AJAX function : $.ajax({ url: "".replace('%book%',id), type: "GET", success: (response)=>{ $('#book-id-update').val(response.data.book.id) $('#book-name-update').val(resp...

How to implement queue.Queue.peek()

(I didn't find similar questions, please help combine this question if you find one) The queue class doesn't have a peek() method. (Offical document link: https://docs.python.org/3/library/queue.html?highlight=queue#queue.PriorityQueue ) I'm just curious how can I implement a peek() if I use it like this: import queue myqueue = queue.Queue() myqueue.put(1) myqueue.peek() #it doesn't have peek() method I'm also curious that isn't peek() a "standard" operation for queue data structure? Why Python official queue class doesn't provide it? Thank you very much ~ source https://stackoverflow.com/questions/72005326/how-to-implement-queue-queue-peek

Why is not the following 3D polar plot of Array Factor being plotted?

import numpy as np import math as mt import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as axes3d #################################################################################### fig = plt.figure() ax = fig.gca(projection='3d') #fig.add_subplot(1,1,1, projection='3d') #################################################################################### freq = 30e+6 # in Hz # 30 MHz lam = 3e+8/freq # in m k_o = 2*np.pi/lam theta = np.linspace(0, np.pi, 100) # in radians phi = np.linspace(0, 2*np.pi, 100) # in radians ############################################################################################################################### N_E = 6 # number of elements # positions on the vertices of a pentagon ############################################################################################################################### D_XY = 3.5 # in m R_XY = 1.7*D_XY C1 = 0.309 C2 = 0.809 S1 = 0.951 S2 = 0.5878 XY = np....

I want to access the "TO" field in the email object in python which appears at the end of a failed-email notification

---------- Forwarded message ---------- From: test email val1testemail@gmail.com To: no_such_email@gmail.com Cc: Bcc: Date: Mon, 25 Apr 2022 09:06:05 -0400 Subject: test test # select specific mails _, selected_mails = mail.search(None, '(FROM "mailer-daemon@googlemail.com")') #total number of mails from specific user print("Total Messages from :mailer-daemon@googlemail.com" , len(selected_mails[0].split())) #print(_,selected_mails[0].split()) for num in selected_mails[0].split(): _, data = mail.fetch(num , '(RFC822)') _, bytes_data = data[0] #convert the byte data to message email_message = email.message_from_bytes(bytes_data) print("\n===========================================") #access data print("Subject: ",email_message["subject"]) print("To:", email_message["to"]) print("From: ",email_message["from"]) print("Date: ",email_messag...

executing script on remote server

I have a python script and input data that the python script takes. I want to execute the python script on remote server without copying python script and data to the remote server. Can this kind of cases be possible to solve. At first i activate the virtual environment and entered to the /home/dong/fold where python script present in the local machine script.py should be executed. I used the script ssh dong@182.27.35.xxx "conda activate env; cd /home/dong/fold" It doesn't execute the script instead it shows error no script.py present source https://stackoverflow.com/questions/72004991/executing-script-on-remote-server

Calculate Input Fields while user is filling data in form - Django Model Form

I have a user form through which I can save data to the database. I want certain fields to be auto calculated while I am filling the the form. For e.g. Net Weight = Gross Weight - Tier Weight and stuff like that. I also want to add RADIO BUTTONS for fields like LOADING , UNLOADING , DEDUCTION , etc. where values will be calculated when user selects one of the option given. Design of the type of form I want, I just don't know how to make that using Django: I am using Django Model Form. Models.py class PaddyPurchase(models.Model): ref_no = models.IntegerField(primary_key='true') token_no = models.CharField(max_length=20, unique='true') agent_name = models.CharField(max_length=20) trip_no = models.IntegerField() date = models.DateField() vehicle_no = models.CharField(max_length=10) bora = models.IntegerField() katta = models.IntegerField() plastic = models.IntegerField() farmer_name = models.CharField(max_length=30) ...

What is the correct way of embedding tweets using twitter api

I am working on a website where I want to show the most recent 3 tweets from my Twitter profile. There is a way to embed the tweets by using the publish.twitter.com URL, the problem with this method is that I cannot style my embedded tweets and it doesn't even show the number of likes and retweets. I want to get the recent tweets using the Twitter API where I am in control of the embedded tweets and can style them. here is what I am using to embed tweets on my website. <div class="twitter-feed" style="display:flex; align-items:center; justify-content:center;"> <a class="twitter-timeline" href="https://twitter.com/dev_taimoor?ref_src=twsrc%5Etfw">Tweets by dev_taimoor</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </div> I need to know a way of using Twitter API through javascript so that I can fetch tweets. I did some research but none of...

Return list of words with match score > x in fuzzywuzzy Python

I'm working on a client-side web application and I want to retrieve an answer for a trivia question from the user, but I want to deem it a correct answer even if the spelling is slightly off. I'm wondering if there is a good way of using fuzzywuzzy (when I wrangle the data originally in python) to return a list of words that would have a matching score greater than .9, for instance. So, if I pass "chicken" and .9 to the function, it returns all words that have a similarity score of over .9 for "chicken" ("chickenn, "chiken", etc.). Any thoughts would be helpful, thank you! source https://stackoverflow.com/questions/71992025/return-list-of-words-with-match-score-x-in-fuzzywuzzy-python

Why does slicing lazy-loaded AudioIOTensor fail with stereo FLAC?

TensorFlow tutorial on audio data preparation ( https://www.tensorflow.org/io/tutorials/audio ) provides the following example: import tensorflow as tf import tensorflow_io as tfio audio = tfio.audio.AudioIOTensor('gs://cloud-samples-tests/speech/brooklyn.flac') print(audio) ...and then states "The content of the audio clip will only be read as needed, either by converting AudioIOTensor to Tensor through to_tensor() , or though slicing (emphasis added). Slicing is especially useful when only a small portion of a large audio clip is needed:" audio_slice = audio[100:] # remove last dimension audio_tensor = tf.squeeze(audio_slice, axis=[-1]) print(audio_tensor) This works as advertised, and it prints: <AudioIOTensor: shape=[28979 1], dtype=<dtype: 'int16'>, rate=16000> tf.Tensor([16 39 66 ... 56 81 83], shape=(28879,), dtype=int16) So far, so good. Now I try this with a stereo FLAC: audio = tfio.audio.AudioIOTensor('./audio/stereo_fi...

How to convert pandas dataframe max index values into string?

I am working with a pandas dataframe consisting of "recipients" on the y axis and "donors" on the x. Donor1 Donor2 Donor3 Donor4 Donor5 Donor6 Recipient1 0 4 1 4 7 6 Recipient2 6 0 9 8 5 8 Recipient3 5 3 5 0 9 3 Recipient4 9 2 1 8 0 5 Recipient5 4 5 5 9 4 2 Recipient6 5 4 2 8 5 6 The maxValueIndex code maxValueIndex = df_test_bid.idxmax(axis = 1) print(str(maxValueIndex)) produces: (index of max value in that row) Recipient1 Donor5 Recipient2 Donor3 Recipient3 Donor5 Recipient4 Donor1 Recipient5 Donor4 Recipient6 Donor4 dtype: object How can I convert each recipient/donor pair into a single string? In other words, how can I iterate through each recipient/donor pair? Trying to iterate with a for loop only gets me ...

Hangman, replace blanks with word. How would I do it?

This is my current code, Im looking for any help as to how to replace the blanks with the letter/word. I am new to coding and this seems to be one issue I have been having. I have tried to look up and see different answers for this question before but I can't find a solution that I myself can understand. #import-statements# import random import turtle as hangman import time #game-configuration# words_list = ["aardvark","special","mathematics","tabletop","dog","crazy","stop"] background = hangman.Screen() background.setup(400,450) background.bgcolor("lightblue") font_setup = ("Arial", 20, "Normal") hangman.penup() #functions# def description_name(): print("Welcome to hangman. Your goal is to guess the word. You may guess words or letters, just remember you have six tries.") print("======================================") name = input("Enter a username ...

MockServerWorker is not handling responses when using fecth in react

I'm doing test driven development in react course - I'm trying to development test for post request. Below is by react code. import React from "react"; import axios from "axios"; class SignUpPage extends React.Component { state = { } onChange = (event) => { const {id, value} = event.target; this.setState({ [id]:value }) }; onChangeUsername = (event) => { const currentValue = event.target.value; this.setState({ username: currentValue, // disabled: currentValue !== this.state.confirmPassword }); }; onChangeEmail = (event) => { const currentValue = event.target.value; this.setState({ email: currentValue, // disabled: currentValue !== this.state.confirmPassword }); }; onChangePassword= (event) => { const currentValue = event.target.value; this.setState({ ...

Incorrect path of executable file in Linux

I need to run an exe file in Linux which has the Python code: import os dirname = os.path.normpath(os.getcwd()) print(dirname) When I run the code with the command python code.py , it runs fine and gives me the output : \root\path\to\file . But when I try to run the exe file with the command wine64 code.exe , which has the same python code, It gives me the output : Z:\root\path\to\file . I tried to fix it by adding dirname = dirname.replace('Z:', '') , but it doesn't work, How to do this? source https://stackoverflow.com/questions/71991561/incorrect-path-of-executable-file-in-linux

two lists, one is list of names and the other one is list of ages in python [closed]

let me describe my program, I have two lists one is list of name and the other one is list of ages, and I am to check name from the console while trying to match corresponding age to the name I got from the user or the console. Pleas help !![This is my code][1] [1]: https://ift.tt/Jwxg74o source https://stackoverflow.com/questions/71981971/two-lists-one-is-list-of-names-and-the-other-one-is-list-of-ages-in-python

Mypy does not warn when breaking the abstract methods type specification in subtype's method [closed]

After running mypy against the above code, mypy does not warn anything. However, I think it should warn about type signature of AppleJuiceFactorty.__call__ method, because AppleJuiceFactory inherits from JuiceFactory[Apple, AppleJuice] therefore FluitT and FruitJuiceT are narrowed down to Apple and AppleJuice respectively. Could you tell me what's the problem? And is it in my side or mypy side? from abc import ABC, abstractmethod from typing import Generic, TypeVar, Type class Fruit: pass class Apple(Fruit): pass class Orange(Fruit): pass FruitT = TypeVar('FruitT', bound=Fruit) class FruitJuice: pass class AppleJuice(FruitJuice): pass class OrangeJuice(FruitJuice): pass FruitJuiceT = TypeVar('FruitJuiceT', bound=FruitJuice) JuiceFactoryT = TypeVar('JuiceFactoryT', bound='JuiceFactory') class JuiceFactory(ABC, Generic[FruitT, FruitJuiceT]): @abstractmethod def __cal__(self, inp: FruitT) -> FruitJuiceT: pass class AppleJuiceFact...

Adding a button that can allow the user to create editable draggable boxes for the user and/or redirect to a form

My goal is to create a bunch of sectioned off containers that a card into said containers. Its similar to how some Kanban Boards work. However, for the moment I wish to be able to allow the user to create these cards and drag and edit them whenever they want. HTML <div class="container"> <h3>Unscheduled Projects</h3> <p class="draggable" draggable="true" contenteditable="true">1</p> </div> <div class="container"> <h3>Ready To Be Developed</h3> <p class="draggable" draggable="true" contenteditable="true">2</p> </div> <div class="container"> <h3>In Development</h3> <p class="draggable" draggable="true" contenteditable="true">3</p> </div> <div class="container"> ...

Can you average a machine learning model's predictions from prior three years to predict next year?

This is a hypothetical question. If I built a machine learning regression model, let's say KNN, or Random Forest, and used the data from the previous three years to predict revenue. And then wanted to predict revenue for the next year, let's say 2023. Could I just take the average of the prior three years to predict the future year? source https://stackoverflow.com/questions/71982870/can-you-average-a-machine-learning-models-predictions-from-prior-three-years-to

Resampling or backfilling for a Pandas MultiIndex (to higher freq)

I would like to modify a dataframe of hourly stock prices that has a datetime column with hourly frequencies and missing values. Below is a min example: date_times =['2020-12-30 14:30:00+00:00', '2022-03-20 20:00:00+00:00' ] prices =[25.60, 21.40 ] stock_names =['AAPL', 'MSFT' ] df = pd.DataFrame({'date_time':date_times, 'stock_name':prices, 'price':stock_names}) df.date_time = pd.to_datetime(df.date_time, utc = True ) I would like to bfill or resample this in such a way that it becomes and hourly data for each stock and for the missing values uses the next available one. Whatever the easiest way is. Maybe recreate a new dataframe with this index and merge? Not sure what the easiest solution is. source https://stackoverflow.com/questions/71982865/resampling-or-backfilling-for-a-pandas-multiindex-to-higher-freq

How do I add a break line to this object literal in react?

I have a Column Component, and I'm trying to display these two data points with a break line, please help. right now the result is: BusinessName UserName I'd like: BusinessName UserName <Column calculateCellValue={(cellData: { BusinessName: string; UserName: string }) => `${cellData.BusinessName} ${cellData.UserName}`} /> Via Active questions tagged javascript - Stack Overflow https://ift.tt/2gmsECD

enable the track in the player through the playlist

I want to add a small player to my site to listen to music. I found a beautiful example that I liked and want to change and finish it a little. There's a button down here, it opens the playlist. And I want that when I click on any track from the playlist, it will play in the player. I manually added the tracks to the playlist, gave them the same ID and different values: <div id="track" value="0" class="trackName">qwe asd — bensound summer</div> <div id="track" value="1" class="trackName">zxc — bensound anewbeginning</div> Next, I try to get all these IDs with values: var track = document.getElementById("track").getAttribute("value"); And now somehow make it so that when I click on one of the tracks, the currentSong variable is set to the value of the selected track. But it doesn't work for me, my variable var track always has the first value, i.e. 0. What am I doin...