content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Is it possible in Python to capture individual parts of a URL with constant structure? If my question is vague, I apologize, it's a difficult question to put to words. If, for example, I needed parts of this URL: https://stackoverflow.com/questions/449775/how-can-i-split-a-url-string-up-into-separate-parts-in-pyt...
Is it possible in Python to capture individual parts of a URL with constant structure?
If my question is vague, I apologize, it's a difficult question to put to words. If, for example, I needed parts of this URL: https://stackoverflow.com/questions/449775/how-can-i-split-a-url-string-up-into-separate-parts-in-python I needed the question number, and the question title, and let's assume the title is foll...
[ "Let's take the link of this question which is\nhttps://stackoverflow.com/questions/74119810/is-it-possible-in-python-to-capture-individual-parts-of-a-url-with-constant-stru\n\nNow, if you see the pattern, after https://(just ignore it), we have 2 \"/\". So we can split it based on these.\nIn [1]: link = \"https://...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074119810_python.txt
Q: NoSuchElementException: Message: no such element: Unable to locate element: Error trying to scrape data from dynamic website using selenium Ive been working on the following code in which i try to scrape data from a dynamic website(constantly live changing herokuapp website which displays data taken from a sensor)...
NoSuchElementException: Message: no such element: Unable to locate element: Error trying to scrape data from dynamic website using selenium
Ive been working on the following code in which i try to scrape data from a dynamic website(constantly live changing herokuapp website which displays data taken from a sensor). While looking for some information i try to use selenium but i doesnt seem to work for me. The following part of the code works well: from sele...
[ "You are using the class name MuiTypography-root MuiTypography-h4 css-2voflx which has multiple spaces in it,however in Selenium spaces are not allowed in the class name, you can convert this to CSS selector like below:\nelement = driver.find_element(By.CSS_SELECTOR, \".MuiTypography-root.MuiTypography-h4.css-2vofl...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074119484_python_selenium_selenium_webdriver_web_scraping.txt
Q: Web scraping stats from basketball reference game-by-game I am trying to get the basic and advanced stats from basketball reference for each team in a game...by game, month, and season. I am confident in the loops that I have in place to cycle through months and seasons, but I am struggling to retrieve the specifi...
Web scraping stats from basketball reference game-by-game
I am trying to get the basic and advanced stats from basketball reference for each team in a game...by game, month, and season. I am confident in the loops that I have in place to cycle through months and seasons, but I am struggling to retrieve the specific stats that I want from the html for each game/box score. I ha...
[ "It seems to me like your code works just fine, but the issue is that you are not importing the packages before using them. Here is your fix:\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas\n\nstats_basic = ['FG', 'FGA', 'FG%', '3P', '3PA', '3P%', 'FT', 'FTA', 'FT%', 'ORB', 'DRB', 'TRB', 'AST', 'STL'...
[ 1 ]
[]
[]
[ "html", "python", "tags", "web_scraping" ]
stackoverflow_0074118255_html_python_tags_web_scraping.txt
Q: How can I reverse the value of the output? Let's put int 5 as a sample input; in my code its expressed as this: n = int(input()) for i in range(0, n): n = n - 1 print(n**2) I get an output as: 16 9 4 1 0 Instead I want to reverse the result to: 0 1 4 9 16 How do you go about solving this problem? A: Th...
How can I reverse the value of the output?
Let's put int 5 as a sample input; in my code its expressed as this: n = int(input()) for i in range(0, n): n = n - 1 print(n**2) I get an output as: 16 9 4 1 0 Instead I want to reverse the result to: 0 1 4 9 16 How do you go about solving this problem?
[ "The following will reverse the output:\nn = int(input())\nfor i in range(0,n):\n print(i**2)\n\nIt will loop from 0 to your inputted n value, printing it's square at each iteration. This also negates the need for the n = n - 1 line.\nOutput:\n0 ** 2\n1 ** 2\n.\n.\n.\nn ** 2\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074119850_python.txt
Q: Issue between number of classes and shape of inputs in metric collection torch I have a problem because I want to calculate some metrics in torchmetrics. but there is a problem: ValueError: The implied number of classes (from shape of inputs) does not match num_classes. The output is from UNet and the loss functi...
Issue between number of classes and shape of inputs in metric collection torch
I have a problem because I want to calculate some metrics in torchmetrics. but there is a problem: ValueError: The implied number of classes (from shape of inputs) does not match num_classes. The output is from UNet and the loss function is BCEWithLogitsLoss (binary segmentation) channels = 1 because of grayscale img ...
[ "It seems that torchmetrics expects different shape. Try to flatten both output and labels:\nprec = torchmetrics.Precision(num_classes=1)(outputs.view(-1), labels.type(torch.int32).view(-1))\n\n", "I was using the torchmetrics library for calculating F1 score, Precision and Recall for segmentation task; I was try...
[ 2, 0 ]
[]
[]
[ "deep_learning", "python", "pytorch" ]
stackoverflow_0072928902_deep_learning_python_pytorch.txt
Q: why does my code appear as a black screen on pygame? I am new at coding. I have been trying to load a picture to modify it as a tutorial and it keeps appearing as a black screen. I do not know where is problem, and what I'm missing, so any advice on that would be appreciated as well. import sys import pygame imp...
why does my code appear as a black screen on pygame?
I am new at coding. I have been trying to load a picture to modify it as a tutorial and it keeps appearing as a black screen. I do not know where is problem, and what I'm missing, so any advice on that would be appreciated as well. import sys import pygame import random command = sys.argv[1] img = pygame.image.load...
[ "You have to blit the image (ìmg) on the display (new_img). The display is new_imgnotimg`.\nimg.blit (new_img,(0,0))\nnew_img.blit(img, (0, 0))\n\nI recommend to change the name of the display Surface:\nimport sys\nimport pygame\nimport random\n\ncommand = sys.argv[1]\nimg = pygame.image.load(command)\n(wid, hgt) =...
[ 2 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0074119661_pygame_python_python_3.x.txt
Q: Python HTML parsing getting only first element without childs So basically I'm trying to parse a website and the result is not the whole html, just some elements. The webpage I'm trying to parse to practice is https://dre.pt/dre/detalhe/anuncio-concurso-urgente/491-2022-201313437 (inspect webpage to check html). A...
Python HTML parsing getting only first element without childs
So basically I'm trying to parse a website and the result is not the whole html, just some elements. The webpage I'm trying to parse to practice is https://dre.pt/dre/detalhe/anuncio-concurso-urgente/491-2022-201313437 (inspect webpage to check html). At first, tried parsing with BeatifulSoup4, but since I was not gett...
[ "If you're willing to give selenium another try, I use this function in several of my scraping projects:\n# from selenium import webdriver\n# from selenium.webdriver.common.by import By\n# from selenium.webdriver.support.ui import WebDriverWait\n# from selenium.webdriver.support import expected_conditions as EC\n\n...
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_requests" ]
stackoverflow_0074108012_beautifulsoup_html_python_python_requests.txt
Q: React Component not Refreshing Django REST everyone ! I'm learning React by myself, and I'm stuck here where I'm doing a REST API for a Chat APP, when I POST a new message, the component don't refresh by itself, I have to refresh the page. I managed to refresh it putting the idmessage and vmessage in the useEffect...
React Component not Refreshing Django REST
everyone ! I'm learning React by myself, and I'm stuck here where I'm doing a REST API for a Chat APP, when I POST a new message, the component don't refresh by itself, I have to refresh the page. I managed to refresh it putting the idmessage and vmessage in the useEffect array, but it kept hitting the API, and I'm pre...
[ "If you want to make real time messages system without hitting the database each time, you should read about WebSocket in a simple word it is opening pool connection between multiple devices to send and receive data without closing the connection after send for example like http request and this data will always pa...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "reactjs" ]
stackoverflow_0074118126_django_django_rest_framework_python_reactjs.txt
Q: Split a long byte array into numpy array of strings Usually, when creating an numpy array of strings, we can do something like import numpy as np np.array(["Hello world!", "good bye world!", "whatever world"]) >>> array(['Hello world!', 'good bye world!', 'whatever world'], dtype='<U15') Now the question is, I am...
Split a long byte array into numpy array of strings
Usually, when creating an numpy array of strings, we can do something like import numpy as np np.array(["Hello world!", "good bye world!", "whatever world"]) >>> array(['Hello world!', 'good bye world!', 'whatever world'], dtype='<U15') Now the question is, I am given a long bytearray from a foreign C function like th...
[ "If you can zero out the data on the C side, then you can use np.frombuffer and it will be about as efficient as you can reasonably expect:\nSo, if you can zero out the data, then this can be read using numpy.frombuffer and it will probably be as efficient as you can reasonably expect to get:\n>>> raw = b'hello wor...
[ 1 ]
[]
[]
[ "c", "numpy", "python" ]
stackoverflow_0074119847_c_numpy_python.txt
Q: How to store passwords in the database (Python) While making my first major project, I have encountered a problem. I need to store passwords in a database. I know about hashing using bcrypt and salting, but I don't know how to properly store them in the database (what type of data to use). Should I use BINARY, BLO...
How to store passwords in the database (Python)
While making my first major project, I have encountered a problem. I need to store passwords in a database. I know about hashing using bcrypt and salting, but I don't know how to properly store them in the database (what type of data to use). Should I use BINARY, BLOB or VARCHAR? After hashing I have both password hash...
[ "From the Bcrypt wikipedia page the output is 59 or 60 depending on the cost. output is in a radix-64 with $ as separators.\nLike Nick ODell said the comments VARBINARY(60) keeps the simple format easily. A VARCHAR(60) is also an ok choice with ascii or latin1 as a character set.\nDue to the variable length a VARCH...
[ 1 ]
[]
[]
[ "mariadb", "mariadb_10.4", "python", "python_3.x" ]
stackoverflow_0074058610_mariadb_mariadb_10.4_python_python_3.x.txt
Q: Pandas get ratio of a value from another df I have a dataframe df1 user_id 0 101 1 102 2 103 3 101 and another df2 user_id type 0 101 cash 1 101 card 2 102 card 3 102 card 4 103 cash 5 103 cash 6 103 card There are more than 2 types. I want to...
Pandas get ratio of a value from another df
I have a dataframe df1 user_id 0 101 1 102 2 103 3 101 and another df2 user_id type 0 101 cash 1 101 card 2 102 card 3 102 card 4 103 cash 5 103 cash 6 103 card There are more than 2 types. I want to add a columns to df1 that is the ratio of each t...
[ "Use crosstab with normalize parameter, rename columns names by DataFrame.add_suffix and add DataFrame.round, add to df1 by DataFrame.join:\ndf = (df1.join(pd.crosstab(df2['user_id'], df2['type'], normalize='index')\n .add_suffix('_pct').round(2), on='user_id'))\nprint (df)\n user_id card_pct cas...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074120047_pandas_python.txt
Q: VSCode -- how to set working directory for debugging a Python program How do I run a Python program under debug and set the working directory for the run? A: @SpeedCoder5's comment deserves to be an answer. In launch.json, specify a dynamic working directory (i.e. the directory where the currently-open Python fi...
VSCode -- how to set working directory for debugging a Python program
How do I run a Python program under debug and set the working directory for the run?
[ "@SpeedCoder5's comment deserves to be an answer.\nIn launch.json, specify a dynamic working directory (i.e. the directory where the currently-open Python file is located) using:\n\"cwd\": \"${fileDirname}\"\n\nThis takes advantage of the \"variables reference\" feature in VS Code, and the predefined variable fileD...
[ 344, 57, 33, 24, 6, 3, 2, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0038623138_python_visual_studio_code.txt
Q: This model has not yet been built error on model.summary() I've keras model defined as follow class ConvLayer(Layer) : def __init__(self, nf, ks=3, s=2, **kwargs): self.nf = nf self.grelu = GeneralReLU(leak=0.01) self.conv = (Conv2D(filters = nf, kernel_s...
This model has not yet been built error on model.summary()
I've keras model defined as follow class ConvLayer(Layer) : def __init__(self, nf, ks=3, s=2, **kwargs): self.nf = nf self.grelu = GeneralReLU(leak=0.01) self.conv = (Conv2D(filters = nf, kernel_size = ks, strides = s, ...
[ "The error says what to do:\n\nThis model has not yet been built. Build the model first by calling build()\n\nmodel.build(input_shape) # `input_shape` is the shape of the input data\n # e.g. input_shape = (None, 32, 32, 3)\nmodel.summary()\n\n", "There is a very big difference between kera...
[ 67, 30, 11, 2, 2, 1, 0 ]
[ "I was also facing same error, so I have removed model.summary(). Then issue is resolved. As it arises if model of summary is defined before the model is built.\nHere is the LINK for description which states that\nRaises:\n ValueError: if `summary()` is called before the model is built.**\n\n" ]
[ -3 ]
[ "keras", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0055908188_keras_python_tensorflow_tensorflow2.0.txt
Q: using f-string sql query in python Say I have a function that returns a pandas read sql call: def recommendations_for_user(user_id, threshold=4.5): # Join with the courses table query = """ SELECT title, rating FROM recommendations INNER JOIN courses ON courses.course_id = recommendations.course_id...
using f-string sql query in python
Say I have a function that returns a pandas read sql call: def recommendations_for_user(user_id, threshold=4.5): # Join with the courses table query = """ SELECT title, rating FROM recommendations INNER JOIN courses ON courses.course_id = recommendations.course_id WHERE user_id=%(user_id)s AND ratin...
[]
[]
[ "I use f strings all the time for SQL queries. Redshift, RDS, MySql, Sqlite no issues.\nMy guess is user is a string so it needs single quotes. If it is indeed a long or int then it must be some other issue.\nquery = f\"\"\"\n SELECT title, rating FROM recommendations\n INNER JOIN courses ON courses.course_id...
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074120022_pandas_python.txt
Q: Scraping Data from Table with Multiple Pages I am trying to scrape data from AGMARKNET website. The tables are split into 11 pages but all of the pages use the same url. I am very new to webscraping (or python in general), but AGMARKNET does not have a public API so scraping the page seems to be my only option. I ...
Scraping Data from Table with Multiple Pages
I am trying to scrape data from AGMARKNET website. The tables are split into 11 pages but all of the pages use the same url. I am very new to webscraping (or python in general), but AGMARKNET does not have a public API so scraping the page seems to be my only option. I am currently using BeautifulSoup to parse the HTML...
[ "The website you linked to seems to be using JavaScript to navigate to the next page. The requests and BeautifulSoup libraries are only for parsing static HTML pages, so they can't run JavaScript.\nInstead of using them, you should try something like Selenium that actually simulates a full browser environment (incl...
[ 0 ]
[]
[]
[ "data_extraction", "python", "web_scraping" ]
stackoverflow_0074115910_data_extraction_python_web_scraping.txt
Q: Python UpSetPlot returning error: 'RangeIndex' object has no attribute 'levels' I have been trying to get an UpSetPlot to work and have not been having much luck. My code is quite simple, I have already shaped the data in a CSV. Below is what I have been trying to run. import pandas as pd from matplotlib import py...
Python UpSetPlot returning error: 'RangeIndex' object has no attribute 'levels'
I have been trying to get an UpSetPlot to work and have not been having much luck. My code is quite simple, I have already shaped the data in a CSV. Below is what I have been trying to run. import pandas as pd from matplotlib import pyplot as plt from upsetplot import UpSet upset = pd.read_csv ("upset.csv") plot(upset)...
[ "I think you are missing a step here. After reading the data, you need to convert it to a Upset-compatible format. You can read more about it here.\nBased on the steps mentioned, you can to use from_memberships() to convert it before plotting. This will convert the data to a series with multiple indices which is re...
[ 1 ]
[]
[]
[ "matplotlib", "python", "upsetplot" ]
stackoverflow_0074119911_matplotlib_python_upsetplot.txt
Q: RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 1 I have read other people's questions for similar issues, but can't figure it out in my case. My code is below, how do I fix this? Thank you. data = ImageFolder(data_dir, transform=transforms.Compose([transforms.Res...
RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 1
I have read other people's questions for similar issues, but can't figure it out in my case. My code is below, how do I fix this? Thank you. data = ImageFolder(data_dir, transform=transforms.Compose([transforms.Resize((224,224)),transforms.ToTensor()])) trainloader = torch.utils.data.DataLoader(data, batch_size=3600, ...
[ "Your input to the network is a 2D image. That is a tensor with 4 dimensions: batch, channel, height and width.\nHowever, you treat the 2D input as a 1D signal by applying nn.Linear layers to its width dimension only, resulting with an output of shape batchchannelheight*output_dim. In contrast, the nn.CrossEntropyL...
[ 1 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074119363_python_pytorch.txt
Q: Using KerasTensor elements from previous layer to populate matrices in next layer I'm building a neural network using TensorFlow and I'm running into an error I was hoping to get some help with. I'm trying to take the output of a Dense layer and map its individual elements to a matrix in a subclassed layer. A simp...
Using KerasTensor elements from previous layer to populate matrices in next layer
I'm building a neural network using TensorFlow and I'm running into an error I was hoping to get some help with. I'm trying to take the output of a Dense layer and map its individual elements to a matrix in a subclassed layer. A simple example of what I'm trying to do is as follows: # ----------------------------------...
[ "Not sure if this is what you're after, but the theta variables are not single elements like you're probably expecting, but rather tf.strided_slice tensors with shape (5,), even though your inputs tensor is the output from your Dense layer, with shape (5,). If you try to get an element of the strided slice tensor, ...
[ 0 ]
[]
[]
[ "keras", "numpy", "python", "tensorflow" ]
stackoverflow_0074105552_keras_numpy_python_tensorflow.txt
Q: (ERROR) Python: ValueError: not enough values to unpack (expected 2, got 1) I am trying to compare two excel files and I am getting the ValueError. Here is a log of the error I get. This should compare two excel files which I have imported into the project. I am using the pandas library and numpy. This worked when...
(ERROR) Python: ValueError: not enough values to unpack (expected 2, got 1)
I am trying to compare two excel files and I am getting the ValueError. Here is a log of the error I get. This should compare two excel files which I have imported into the project. I am using the pandas library and numpy. This worked when I tried comparing a smaller data set but not for a much larger excel file. Any s...
[ "Problem is not same number of rows / columns in both DataFrames, so warning for compare numpy arrays and error in numpy.where.\nYou can check it:\nprint (len(dfnew))\nprint (len(dfold))\n\nprint (len(dfnew.columns))\nprint (len(dfold.columns))\n\nFor same index and columns in both DataFrames use:\nidx = dfnew.inde...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074120114_numpy_pandas_python.txt
Q: FastAPI is not quitting when pressing Ctr+c I am finding a difficulty with quitting FastAPI. Ctr+c does not work. Here is my pyproject.toml [tool.pyright] exclude = ["app/worker"] ignore = ["app/worker"] [tool.poetry] name = "api" version = "0.1.0" description = "" authors = ["SamiAlsubhi <sami@alsubhi.me>"] [to...
FastAPI is not quitting when pressing Ctr+c
I am finding a difficulty with quitting FastAPI. Ctr+c does not work. Here is my pyproject.toml [tool.pyright] exclude = ["app/worker"] ignore = ["app/worker"] [tool.poetry] name = "api" version = "0.1.0" description = "" authors = ["SamiAlsubhi <sami@alsubhi.me>"] [tool.poetry.dependencies] python = ">=3.8,<3.9" fas...
[ "I've read about this problem in using uvicorn and I found the below code snippet to resolve that:\n# Add the below code snippet to your app.py module after the app initialization.\n\n\ndef receive_signal(signalNumber, frame):\n print('Received:', signalNumber)\n sys.exit()\n\n\n@app.on_event(\"startup\")\nas...
[ 0, 0 ]
[]
[]
[ "asgi", "fastapi", "python", "uvicorn" ]
stackoverflow_0074116435_asgi_fastapi_python_uvicorn.txt
Q: How to add values in an empty numpy array? I created an array using numpy.empty(). Now I want to add new values to that array based on the if-else condition. I wrote a for loop for that with the if-else condition inside. I only want to add values to the columns belonging to the first row. But after running the cod...
How to add values in an empty numpy array?
I created an array using numpy.empty(). Now I want to add new values to that array based on the if-else condition. I wrote a for loop for that with the if-else condition inside. I only want to add values to the columns belonging to the first row. But after running the code I've written below, I'm getting some random va...
[ "Use np.zeros or np.ones, np.empty initialises with random numbers\nnumber_rows = 16\nnumber_cols = 10\nasr = np.zeros((number_rows, number_cols)) #np.zeros instead\n \nfor i in range(10): \n if prediction[i] == check_keep[i]:\n asr.iloc[0, i] = 1 #also it is better to use np indexing here\n else:\n asr.ilo...
[ 1 ]
[]
[]
[ "list", "matrix", "numpy", "python" ]
stackoverflow_0074120105_list_matrix_numpy_python.txt
Q: Checking and finding duplicate values I have a table: Key Sequence Longitude Latitude 1001 1 18.2 14.2 1001 2 18.2 14.2 1001 3 18.2 14.2 2001 1 25.6 22.8 2001 2 25.6 22.8 2001 3 25.6 22.8 5004 1 25.6 22.8 5004 2 25.6 22.8 5004 3 25.6 22.8 6895 1 36.2 17.4 6895 2 36.2 17.4 6895 3 36.2 17.4 6650 1 18.2...
Checking and finding duplicate values
I have a table: Key Sequence Longitude Latitude 1001 1 18.2 14.2 1001 2 18.2 14.2 1001 3 18.2 14.2 2001 1 25.6 22.8 2001 2 25.6 22.8 2001 3 25.6 22.8 5004 1 25.6 22.8 5004 2 25.6 22.8 5004 3 25.6 22.8 6895 1 36.2 17.4 6895 2 36.2 17.4 6895 3 36.2 17.4 6650 1 18.2 14.2 6650 2 18.2 14.2 ...
[ "First remove the duplicates per key, then check what is still duplicated between keys:\n# get example of duplicated rows\ns = (df\n .drop_duplicates(subset=['Key', 'Longitude', 'Latitude'])\n .duplicated(['Longitude', 'Latitude'])\n )\n\n# extract the original keys and mark all matching rows\ndf['Duplicate'] = np....
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074119472_pandas_python.txt
Q: I'm trying to import user input variables to call upon them in another module but keep receiving an error import math def area(radius): return (math.pi * radius**2) def circumference(radius): return (2 * math.pi * radius) def main(): radius = float(input('Enter radius of circle: ')) ar = area(radiu...
I'm trying to import user input variables to call upon them in another module but keep receiving an error
import math def area(radius): return (math.pi * radius**2) def circumference(radius): return (2 * math.pi * radius) def main(): radius = float(input('Enter radius of circle: ')) ar = area(radius) cir = circumference(radius) print(f'The area of a circle with radius {radius:.2f} is {cir:.3f}') ...
[ "Functions with the module prefix are called without the radius parameter:\nprogram5_2.area()\nprogram5_2.circumference()\n\nYou should not \"import\" the input values into the module, but pass them there. And I would recommend against variable names such as cir : 6 months from now you won't remember if is was cir,...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074120123_python.txt
Q: Sorting class instances in a List How do I sort class instances in the list based on the length of the pool? Example: Current value in dictionary: {"Metal":[['A', 20, 50, 'Wide']], "Wood":[['B', 50, 20, 'Thin'], ['C', 30, 30, 'Wide']] Sorted value in dictionary: {"Metal":[['A', 20, 50, 'Wide']], "Wood":[['C', 30...
Sorting class instances in a List
How do I sort class instances in the list based on the length of the pool? Example: Current value in dictionary: {"Metal":[['A', 20, 50, 'Wide']], "Wood":[['B', 50, 20, 'Thin'], ['C', 30, 30, 'Wide']] Sorted value in dictionary: {"Metal":[['A', 20, 50, 'Wide']], "Wood":[['C', 30, 30, 'Wide'], ['B', 50, 20, 'Thin']] ...
[ "Both list.sort() for in-place sorting and sorted for returning a new list accept a key= callable argument that accepts the object to be sorted and should return its \"sort key\".\nself._pools[\"Metal\"].sort(key=lambda pool: pool.length)\n\n" ]
[ 4 ]
[]
[]
[ "class", "oop", "python" ]
stackoverflow_0074120271_class_oop_python.txt
Q: How do I check which version of Python is running my script? How do I check which version of the Python interpreter is running my script? A: This information is available in the sys.version string in the sys module: >>> import sys Human readable: >>> print(sys.version) # parentheses necessary in python 3. ...
How do I check which version of Python is running my script?
How do I check which version of the Python interpreter is running my script?
[ "This information is available in the sys.version string in the sys module:\n>>> import sys\n\nHuman readable:\n>>> print(sys.version) # parentheses necessary in python 3. \n2.5.2 (r252:60911, Jul 31 2008, 17:28:52) \n[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]\n\nFor further processing, use sys.version_info or sys....
[ 1628, 417, 103, 99, 71, 49, 31, 14, 8, 5, 4, 3, 3, 3, 2, 2, 1, 1, 1, 0, 0, 0 ]
[ "If you are working on linux just give command python output will be like this\n\nPython 2.4.3 (#1, Jun 11 2009, 14:09:37)\n[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more\n information.\n\n", "For windows, Go to command prompt and type this c...
[ -1, -1, -3 ]
[ "python", "version" ]
stackoverflow_0001093322_python_version.txt
Q: Kernel dies while trying to save a mathplotlib figure Before my question, that's the setup: MacBook Air (M2, 2022) macOS Monterey 12.5.1 Visual Studio Code 1.72.2 Python 3.8.9 I am trying to create multiple figures in a for-loop using mathplotlib. I've uploaded some testable code for the project here: https://onec...
Kernel dies while trying to save a mathplotlib figure
Before my question, that's the setup: MacBook Air (M2, 2022) macOS Monterey 12.5.1 Visual Studio Code 1.72.2 Python 3.8.9 I am trying to create multiple figures in a for-loop using mathplotlib. I've uploaded some testable code for the project here: https://onecompiler.com/python/3ykd8g2hs The creation works and noteboo...
[ "Try to install a lower version of pyzmq with the following command\npython -m pip install pyzmq==19.0.2 --force-reinstall\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "matplotlib", "python", "visual_studio_code" ]
stackoverflow_0074116581_jupyter_notebook_matplotlib_python_visual_studio_code.txt
Q: pandas appending excel(xlsx) file gives attribute.error Getting trouble with either of errors ; writer.book=book AttributeError: can't set attribute 'book' or BadZipFile for code not giving badzipfile error I put code line which writes excel file first, dataOutput=pd.DataFrame(dictDataOutput,index=[0]) but, even t...
pandas appending excel(xlsx) file gives attribute.error
Getting trouble with either of errors ; writer.book=book AttributeError: can't set attribute 'book' or BadZipFile for code not giving badzipfile error I put code line which writes excel file first, dataOutput=pd.DataFrame(dictDataOutput,index=[0]) but, even though I cannot get rid of writer.book = book AttributeError: ...
[ "There are a few things that are unclear about your question, but I'll do my best to try and answer what I think you're trying to do.\nFirst off, things that won't work:\n\nFrom the to_excel docs, \"If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object\", so w...
[ 2 ]
[]
[]
[ "attributeerror", "openpyxl", "pandas", "python" ]
stackoverflow_0074085655_attributeerror_openpyxl_pandas_python.txt
Q: Accessing text file created within a function inside another function I have a function setup in the following manner: @MyClass def func1(): #runs a bash script subprocess.call(shlex.split('./fedora.sh ./all_packages.txt')) #creates a text file called log.txt #class method def func2(): #How t...
Accessing text file created within a function inside another function
I have a function setup in the following manner: @MyClass def func1(): #runs a bash script subprocess.call(shlex.split('./fedora.sh ./all_packages.txt')) #creates a text file called log.txt #class method def func2(): #How to access log.txt within this class method here? with open('./log.t...
[ "Found one way of accessing the newly created file:\nimport os\nos.listdir(), key=lambda t: -os.stat(t).st_mtime)[0]\n#sorts the files created in desccending order and take the newly created file\n\n" ]
[ 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074120179_file_python.txt
Q: how to make a form field not part of the submitted form I have an extra field in a django form that triggers javascript to change the fields in other forms: class MyForm(forms.ModelForm): my_extra_form_field = forms.ChoiceField() class Meta: model = MyModel fields = ["field1", "field2"] ...
how to make a form field not part of the submitted form
I have an extra field in a django form that triggers javascript to change the fields in other forms: class MyForm(forms.ModelForm): my_extra_form_field = forms.ChoiceField() class Meta: model = MyModel fields = ["field1", "field2"] field_order = ["field1", "my_extra_form_field", "field2"] ...
[ "Just add this to your javascript in template:\n// jQuery\n$('#my_extra_form_field').removeAttr('name');\n\n// Javascript\ndocument.getElementById('my_extra_form_field').removeAttribute('name');\n\n", "adding to NixionSparrow's answer:\nYou may need to add the attribute required as mentioned in the docs here\nmy_...
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074120182_django_python.txt
Q: convert text to csv with python pandas I want to convert text file to csv file import pandas as pd readfile = pd.read_csv(r'text.txt') readfile.to_csv(r'CSV.csv, index=None) my text file format: the result: In the red circle it's add a decimal number follow the data it's duplicate I don't want it to...
convert text to csv with python pandas
I want to convert text file to csv file import pandas as pd readfile = pd.read_csv(r'text.txt') readfile.to_csv(r'CSV.csv, index=None) my text file format: the result: In the red circle it's add a decimal number follow the data it's duplicate I don't want it to add a decimal number please suggestion me w...
[ "#just add header = None, since first line of txt is considered header that's why it is managing duplicate column names.\nimport pandas as pd\nreadfile = pd.read_csv(r'text.txt',header=None)\nreadfile.to_csv(r'CSV.csv, index=None)\n\n#sample example output of readfile\n 0 1 2 3 4 5 6 7 8\n ...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074119285_csv_pandas_python.txt
Q: Yolov5s on Openvino I have trained a model using yolov5 and it is working just fine: My ultimate goal is to use a model that I have trained on custom data (to detect the hook and bucket) in the Openvino framework. To achieve this, I first exported the best version of the model to the appropriate Openvino format, ...
Yolov5s on Openvino
I have trained a model using yolov5 and it is working just fine: My ultimate goal is to use a model that I have trained on custom data (to detect the hook and bucket) in the Openvino framework. To achieve this, I first exported the best version of the model to the appropriate Openvino format, using the following comma...
[ "This error is expected as the model contains a dynamic shape. This model can be executed using the ov::Core:compile_model API in OpenVINO 2022.1.\nYou can refer to class ov::CompiledModel and Dynamic Shape for more information.\n", "You use API 1.0 that does not support dynamic shapes.\nYou need to use API 2.0 f...
[ 2, 1, 0 ]
[]
[]
[ "computer_vision", "intel", "openvino", "python", "yolov5" ]
stackoverflow_0071970869_computer_vision_intel_openvino_python_yolov5.txt
Q: Building wheel for tokenizers (pyproject.toml) did not run successfully - Python 3.9.9 - Windows 10 Yes there are several other questions like this but no solution provided I am trying to install and run this project https://github.com/xashru/punctuation-restoration I have cloned the github repository Installed ru...
Building wheel for tokenizers (pyproject.toml) did not run successfully - Python 3.9.9 - Windows 10
Yes there are several other questions like this but no solution provided I am trying to install and run this project https://github.com/xashru/punctuation-restoration I have cloned the github repository Installed rust from here downloading x64 : https://www.rust-lang.org/tools/install I am using Python 3.9.9 (tags/v3.9...
[ "As far as I can see it comes down to a version conflict.\nThe versions of transformers and tokenizers are severly out of date.\nOn the rust side, that means that a rust feature (const_fn) tokenizers is using, is by now part of rust and not a nightly feature anymore (this is what the error output shows the compiler...
[ 1 ]
[]
[]
[ "huggingface_tokenizers", "python", "rust" ]
stackoverflow_0074117990_huggingface_tokenizers_python_rust.txt
Q: Open a Toplevel by pressing a butten with functools.partial I'm openng a Toplevel window by pressing a butten with command=lambda: PasswordWindow(self).grab_set() but i want to use functools.partial to do this. Is there a way to do this? A: functools.partial requires a callable, so you can't have it both create...
Open a Toplevel by pressing a butten with functools.partial
I'm openng a Toplevel window by pressing a butten with command=lambda: PasswordWindow(self).grab_set() but i want to use functools.partial to do this. Is there a way to do this?
[ "functools.partial requires a callable, so you can't have it both create an instance of PasswordWindow and call a method on that object. You'll either need to move the call to grab_set inside PasswordWindow.__init__, or create a separate function that does what you want. Though, if you create a separate function, t...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074120373_python_tkinter.txt
Q: Resizing binary mask stored in numpy array I have got numpy arrays consisting of only 0s and 1s. They are supposed to be the target for an Image Segmentation Model, so I am trying to resize them all so they have the same dimensions. The problem is that when resizing with the code below, the image is not being kept...
Resizing binary mask stored in numpy array
I have got numpy arrays consisting of only 0s and 1s. They are supposed to be the target for an Image Segmentation Model, so I am trying to resize them all so they have the same dimensions. The problem is that when resizing with the code below, the image is not being kept as a binary. Instead, I get a lot of float valu...
[ "Use preserve_range=True as well:\nnew_label_data = st.resize(label_data, (1024, 1024), order=0, preserve_range=True, anti_aliasing=False)\n\nSee st.resize for more details.\n" ]
[ 0 ]
[]
[]
[ "image_segmentation", "python", "scikit_image", "semantic_segmentation" ]
stackoverflow_0074110716_image_segmentation_python_scikit_image_semantic_segmentation.txt
Q: Trying to run OpenVINO inference kit with an OpenCV version of 4.5.1, while reporting error The error that I have gotten is: cv2.error: OpenCV(4.5.1) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-yaf6rry6/opencv/modules/dnn/src/dnn.cpp:3901: error: (-2:Unspecified error) Build OpenCV with ...
Trying to run OpenVINO inference kit with an OpenCV version of 4.5.1, while reporting error
The error that I have gotten is: cv2.error: OpenCV(4.5.1) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-yaf6rry6/opencv/modules/dnn/src/dnn.cpp:3901: error: (-2:Unspecified error) Build OpenCV with Inference Engine to enable loading models from Model Optimizer. in function 'readFromModelOptimiz...
[ "How have you installed OpenCV (and OpenVINO) on your machine?\nHave you built OpenCV from source-code or installed a pre-built, pre-packaged version?\nYou might want to check e.g. this post: OpenVINO: How to build OpenCV with Inference Engine to enable loading models from Model Optimizer\nFew options:\n\nbuild Ope...
[ 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0073367614_opencv_python.txt
Q: BeautifulSoup to find a HTML tag that contains tags with specific class How to find all tags that include tags with certain class? The data is: <tr> <td class="TDo1" width=17%>Tournament</td> <td class="TDo2" width=8%>Date</td> <td class="TDo2" width=6%>Pts.</td> <td class="TDo2" width=34%>Pos. Player (team)</td> ...
BeautifulSoup to find a HTML tag that contains tags with specific class
How to find all tags that include tags with certain class? The data is: <tr> <td class="TDo1" width=17%>Tournament</td> <td class="TDo2" width=8%>Date</td> <td class="TDo2" width=6%>Pts.</td> <td class="TDo2" width=34%>Pos. Player (team)</td> <td class="TDo5" width=35%>Pos. Opponent (team)</td> </tr> <tr> <td class=TD...
[ "I suppose you want to find all <tr> that contains any tag with class TD<any character>3:\nimport re\n\n# `html` contains your html from the question\nsoup = BeautifulSoup(html, \"html.parser\")\npat = re.compile(r\"TD.3\")\n\nfor tr in soup.find_all(\n lambda tag: tag.name == \"tr\"\n and tag.find(class_=lam...
[ 1, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "findall", "python" ]
stackoverflow_0074117210_beautifulsoup_findall_python.txt
Q: How to sort the list value of a defaultdict(list)? from collections import defaultdict d=defaultdict(list) d['A']=[('a',20,30), ('b', 13, 1)] d['B']=[('c',2,1), ('b', 3, 21)] for k, v in d.items(): d[k] = sorted(v, key=lambda tup: (tup[1], tup[2]), reverse=True) print(d) defaultdict(<class 'list'>, {'A': [('...
How to sort the list value of a defaultdict(list)?
from collections import defaultdict d=defaultdict(list) d['A']=[('a',20,30), ('b', 13, 1)] d['B']=[('c',2,1), ('b', 3, 21)] for k, v in d.items(): d[k] = sorted(v, key=lambda tup: (tup[1], tup[2]), reverse=True) print(d) defaultdict(<class 'list'>, {'A': [('a', 20, 30), ('b', 13, 1)], 'B': [('b', 3, 21), ('c', 2,...
[ "Your defaultdict's default type only takes effect when the key doesn't yet exist, which is useful for things like appending to a collection without KeyError for fresh keys!\nIf you have mixed types and are trying to sort 'em, just create a custom class which does what you want\nYou could also add a comparator (onl...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074120259_python.txt
Q: Form returning not valid in django In my django app I have a User model that has a Boolean field of is_manager. User model in models.py: class User(AbstractUser): name = models.CharField(max_length=15, null=True, blank=True) last_name = models.CharField(max_length=15, null=True, blank=True) title = mod...
Form returning not valid in django
In my django app I have a User model that has a Boolean field of is_manager. User model in models.py: class User(AbstractUser): name = models.CharField(max_length=15, null=True, blank=True) last_name = models.CharField(max_length=15, null=True, blank=True) title = models.CharField(max_length=50, null=True, ...
[ "\" Oh! I completely missed that. I think the *args is required because that's how you pass in the request.POST. if you would have an explicit key like myform(data=request.POST) it would have worked because it would be in the *kwargs .. So it was basically failing cause it was acting like you were just initiating a...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074114441_django_python.txt
Q: with and pmin from R to Python I have troubles when writing small part of R code into Python. Here is the R code: W <- expand.grid(list(A = 1:10, C = 1:15)) W$B <- 40 - rowSums(W) GC <- with( W, pmin(floor(53*C - 0.9*C^2), pmin(floor(52*B - 1.1*B^2), pmin(62*A, 614))) ) I need it to rewrite it into Python. T...
with and pmin from R to Python
I have troubles when writing small part of R code into Python. Here is the R code: W <- expand.grid(list(A = 1:10, C = 1:15)) W$B <- 40 - rowSums(W) GC <- with( W, pmin(floor(53*C - 0.9*C^2), pmin(floor(52*B - 1.1*B^2), pmin(62*A, 614))) ) I need it to rewrite it into Python. This is what I have until now: import...
[ "The equivalent would be assign:\ndf.assign(B=40 - df['A'] - df['C'])\n\nIf you want to have a reference relative to the object itself, use a callable:\ndf.assign(B=lambda d: 40 - d['A'] - d['C'])\n\nIf you want to use a name with special characters or spaces:\ndf.assign(**{'B': lambda d: 40 - d['A'] - d['C'])})\n\...
[ 1 ]
[]
[]
[ "python", "r" ]
stackoverflow_0074120577_python_r.txt
Q: VScode Python "Run Cell" does nothing I'm using VScode on mac and configured an anaconda environment. When I insert # %% and hit "Run Cell", nothing happens at all. How can I fix this? EDIT: the solution was simply to reboot my machine :) A: When I insert and hit "Run Cell", nothing happens at all If you can cr...
VScode Python "Run Cell" does nothing
I'm using VScode on mac and configured an anaconda environment. When I insert # %% and hit "Run Cell", nothing happens at all. How can I fix this? EDIT: the solution was simply to reboot my machine :)
[ "\nWhen I insert and hit \"Run Cell\", nothing happens at all\n\nIf you can create .ipynb file which can be successfully run, there should be no problem.\nTry reload window and give the interactive window more time to load:\n\n\n" ]
[ 0 ]
[]
[]
[ "anaconda", "python", "visual_studio_code" ]
stackoverflow_0074115967_anaconda_python_visual_studio_code.txt
Q: Scraping a table that uses a firebase database I am trying to scrape data for a project from this website, specifically the table under the "Matchups" tab. I'm brand new to web scraping so I did some digging through inspect element, but as far as I can tell the table is loaded dynamically, so none of the data can ...
Scraping a table that uses a firebase database
I am trying to scrape data for a project from this website, specifically the table under the "Matchups" tab. I'm brand new to web scraping so I did some digging through inspect element, but as far as I can tell the table is loaded dynamically, so none of the data can be found in the source. I looked in dev tools and I...
[ "It seems like the developer of the app you are scraping has disabled unauthenticated access to their Firestore database. Bypassing Firebase authentication is nearly impossible. So my suggestion for you is to invest your resources in either building a JavaScript capable web scraper, or to use an external web scrapi...
[ 0 ]
[]
[]
[ "firebase", "python", "web_scraping" ]
stackoverflow_0074103627_firebase_python_web_scraping.txt
Q: Open-Closed Principle in Python OOD I am designing a parking lot. Now I have three kinds of parking spots. I want to initialize my parking lot like this: Building({Size.SMALL: 5, Size.MEDIUM: 6, Size.LARGE: 7}) This means this parking lot has 5 small spots, 6 medium spots and 7 large spots. And below is my code...
Open-Closed Principle in Python OOD
I am designing a parking lot. Now I have three kinds of parking spots. I want to initialize my parking lot like this: Building({Size.SMALL: 5, Size.MEDIUM: 6, Size.LARGE: 7}) This means this parking lot has 5 small spots, 6 medium spots and 7 large spots. And below is my code for spots and the parking lot (i.e., Bui...
[ "I assume that when you say \"new kinds of vehicles added\" you mean new additions to your size enum:\nfrom enum import Enum\n\nclass Size(Enum):\n SMALL = 1\n MEDIUM = 2\n LARGE = 3\n\nrather than inherit the base parking spot class, you could just include the Size enum as a property of the spot. Therefor...
[ 2 ]
[]
[]
[ "object_oriented_analysis", "open_closed_principle", "python", "solid_principles" ]
stackoverflow_0074118882_object_oriented_analysis_open_closed_principle_python_solid_principles.txt
Q: what module will help me to analyze this data? I have a csv file which holds many records and there are many other csv files which holds the same records but with their different values. I want to analyze and to get some useful information from these csv files but do not know how to do it? How to do it? csv file i...
what module will help me to analyze this data?
I have a csv file which holds many records and there are many other csv files which holds the same records but with their different values. I want to analyze and to get some useful information from these csv files but do not know how to do it? How to do it? csv file is like Compony name,DCP,OpenMarket,HIGH,LOW,CURRENT_...
[ "using pandas, if you want to diff cell by cell, and assuming the 2 files have the same number of rows / columns, I would do the following:\nimport pandas as pd\n\ndf1 = pd.read_csv('file1.csv')\ndf2 = pd.read_csv('file2.csv')\n\n# join the 2 dataframes to get a single dataframe\ndf = df1.join(df2, rsuffix='_2')\n#...
[ 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074119152_csv_python.txt
Q: How to melt 2 level of columns in pandas without providing the name of columns? I would like a support on doing melt without providing all the column names. I have a dataframe with 5000+ columns and it is quite dynamic. Hence, would like to see if there is any way to do melt without providing columns (using df.col...
How to melt 2 level of columns in pandas without providing the name of columns?
I would like a support on doing melt without providing all the column names. I have a dataframe with 5000+ columns and it is quite dynamic. Hence, would like to see if there is any way to do melt without providing columns (using df.columns). # Sample df #| sub1 sub2 subN #| Stud...
[ "Nevermind. Found out just using melt() without any arguments did the trick\n", "It depends of data:\nprint (df)\n sub1 sub2 subN \n Student max min mean max min mean max min mean\n0 Joy 7 2 0 8 3 1 7 2 0\n1 Red 9 2 5 8 3 4 ...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074120524_pandas_python.txt
Q: My Dash tutorials look way different than in the docs. Should they? I'm a seasoned back-end engineer, but I'm a newbie with browser-based GUI design (HTML, CSS, etc.). I need to build a dashboard and have found Dash. I'm just starting to work through the examples. When I run the examples, my results look nothing...
My Dash tutorials look way different than in the docs. Should they?
I'm a seasoned back-end engineer, but I'm a newbie with browser-based GUI design (HTML, CSS, etc.). I need to build a dashboard and have found Dash. I'm just starting to work through the examples. When I run the examples, my results look nothing like what is shown in the documentation. The documentation states that ...
[ "I encourage you to use Dash Bootstrap Components to get style your table easily, and I re-write your example with this library and I get the desired output you want:\nfrom dash import Dash, html, dcc\nimport pandas as pd\nimport dash_bootstrap_components as dbc\n\napp = Dash(external_stylesheets=[dbc.themes.BOOTST...
[ 1 ]
[]
[]
[ "css", "html", "plotly_dash", "python" ]
stackoverflow_0074119729_css_html_plotly_dash_python.txt
Q: Adding Lat long Cordinates to a GeoTiff file I have a Satellite Image of a Terrain, and I have the Latitude and Longitude measures of the four cordinates of the file. How can I add the following data to the GeoTiff file, using Python or Matlab A: You can open the file in update-mode and set the geotransform. It ...
Adding Lat long Cordinates to a GeoTiff file
I have a Satellite Image of a Terrain, and I have the Latitude and Longitude measures of the four cordinates of the file. How can I add the following data to the GeoTiff file, using Python or Matlab
[ "You can open the file in update-mode and set the geotransform.\nIt does require your image to be a regular grid, and often the assumption is that it isn't rotated (which you can tell of you know all four corner coordinates).\nThe geotransform also requires the x/y size in pixels, which you can calculate from the i...
[ 0 ]
[]
[]
[ "gdal", "gis", "python", "sar" ]
stackoverflow_0074119873_gdal_gis_python_sar.txt
Q: Data Classes vs Dictionaries I've been learning about dataclasses, and was reworking an old project trying to integrate a dataclass into the program in place of a dictionary system I was using. The code blocks below are essentially the respective new and old methods being used to build a dataframe of several thous...
Data Classes vs Dictionaries
I've been learning about dataclasses, and was reworking an old project trying to integrate a dataclass into the program in place of a dictionary system I was using. The code blocks below are essentially the respective new and old methods being used to build a dataframe of several thousand items. My problem is I don't u...
[ "As discussed in the comments, there is a lot of discussion (and opinions) regarding this particular comparison. After doing several hours of research, there are a few main points I'd like to lay out for anyone else who may have this question in the future.\n1. In regard to efficiency\nDictionaries are simpler data...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074117873_dictionary_python.txt
Q: How can I check if an object is in another object (defined by my class)? How can I check if an object is in another object? So say I have the following defined: class Container: def __init__(self): self.a = ['x','y','z'] and I want to be able to make the following work: 'x' in Container() # True My ...
How can I check if an object is in another object (defined by my class)?
How can I check if an object is in another object? So say I have the following defined: class Container: def __init__(self): self.a = ['x','y','z'] and I want to be able to make the following work: 'x' in Container() # True My attempt/guess was that there was some type of dunder method for in like so: cl...
[ "In this case, the in operator relies on the object being iterable. So the solution would be to define the dunder method for __iter__ as follows:\ndef __iter__(self, item):\n return iter(self.a)\n\nFor the final product to be:\nclass Container:\n def __init__(self):\n self.a = ['x','y','z']\n def __...
[ -1 ]
[]
[]
[ "python" ]
stackoverflow_0074120722_python.txt
Q: Filter resultSet stored inside dictionary I have a dictionary where each key is a string and value is Pandas's resultSet. I know how to write a list comprehension for it, for example: myDict = {k: v for k,v in myDict.items() if len(v)>0 } But what I need to do is to apply some filter not to resultSet itself, but ...
Filter resultSet stored inside dictionary
I have a dictionary where each key is a string and value is Pandas's resultSet. I know how to write a list comprehension for it, for example: myDict = {k: v for k,v in myDict.items() if len(v)>0 } But what I need to do is to apply some filter not to resultSet itself, but to its elements. I.e. I want to write a compreh...
[ "Use nested list comprehension for filter nested dicts:\nmyDict = {\n\"key1\": [{\"a\":1,\"b\":-2,\"c\":-3}, {\"a\":1,\"b\":-2,\"c\":3}], \n\"key2\": [{\"a\":1,\"b\":2,\"c\":3},{\"a\":51,\"b\":-42,\"c\":43}] \n}\n\nmyDict = {k: [x for x in v if x['c'] > 0] for k,v in myDict.items()}\n\n#MYousefi super comment - if ...
[ 1 ]
[]
[]
[ "dictionary_comprehension", "list_comprehension", "pandas", "python" ]
stackoverflow_0074120685_dictionary_comprehension_list_comprehension_pandas_python.txt
Q: (Pymongo) return Json data result, after interact MongoDB I want to return Json result like below, contains is it successfully functioning (use 0/1) , modified contents and modified data count Json result: {"ok" : 1, "msg" : [{ "name" : "Moma", "Age" : 33} , { "name" : "Kara", "Age" : 44} ], "count": 2 } The ...
(Pymongo) return Json data result, after interact MongoDB
I want to return Json result like below, contains is it successfully functioning (use 0/1) , modified contents and modified data count Json result: {"ok" : 1, "msg" : [{ "name" : "Moma", "Age" : 33} , { "name" : "Kara", "Age" : 44} ], "count": 2 } The tried code below: I tried to use .inserted_count and .upserted_...
[ "the .modified_count and for modified_data in mycol.find().sort(\"_id\", -1).limit(#num): are the key\nsee below, I'm pretty close, here is what I solve\nimport pymongo\nimport datetime\nimport json\ndef init_db(ip, db, coll):\n myclient = pymongo.MongoClient('mongodb://' + ip + '/')\n mydb = myclient[db]\n ...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0074108321_mongodb_pymongo_python.txt
Q: Sum all diagonals in feature maps in parallel in PyTorch Let's say I have a tensor shaped (1, 64, 128, 128) and I want to create a tensor of shape (1, 64, 255) holding the sums of all diagonals for every (128, 128) matrix (there are 1 main, 127 below, 127 above diagonals so in total 255). What I am currently doing...
Sum all diagonals in feature maps in parallel in PyTorch
Let's say I have a tensor shaped (1, 64, 128, 128) and I want to create a tensor of shape (1, 64, 255) holding the sums of all diagonals for every (128, 128) matrix (there are 1 main, 127 below, 127 above diagonals so in total 255). What I am currently doing is the following: x = torch.rand(1, 64, 128, 128) diag_s...
[ "Have you considered using torch.nn.functional.conv2d?\nYou can sum the diagonals with a diagonal filter sliding across the tensor with appropriate zero padding.\nimport torch\nimport torch.nn.functional as nnf\n\n# construct a diagonal filter using `eye` function, shape it appropriately\nf = torch.eye(x.shape[2])[...
[ 1, 1, 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0057347896_python_pytorch.txt
Q: Selenium package - StateElementReferenceException I’ve got this part code in my script: elements = driver.find_elements(By.TAG_NAME, 'p') for e in elements: if e.text not in elenco: print(e.text) elenco.append(e.text) if ("Denis" in e.text): print("Find Denis") Many time...
Selenium package - StateElementReferenceException
I’ve got this part code in my script: elements = driver.find_elements(By.TAG_NAME, 'p') for e in elements: if e.text not in elenco: print(e.text) elenco.append(e.text) if ("Denis" in e.text): print("Find Denis") Many times the script break in these rows with this message: sel...
[ "For the first error message:\nIn short, the message is saying that the element you're looking for is no longer in the DOM, or it changed.\nYou may be able to try something like below to help\n# Add some items to your import statements, to help handle exceptions\nfrom selenium.common.exceptions import NoSuchElement...
[ 0 ]
[]
[]
[ "python", "runtime_error", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074120456_python_runtime_error_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Read a Kubernetes Deployment with specific label with python kubernetes client I am looking for the python Kubernetes client equivalent for kubectl get deploy -n app -l team=blue I'm aware of this function deployment = api.read_namespaced_deployment(name='foo', namespace='bar') but how can I have same thing with ...
Read a Kubernetes Deployment with specific label with python kubernetes client
I am looking for the python Kubernetes client equivalent for kubectl get deploy -n app -l team=blue I'm aware of this function deployment = api.read_namespaced_deployment(name='foo', namespace='bar') but how can I have same thing with label?
[ "read_namespaced_deployment expects deployment name, which does not make sense of using label, you should use list_namespaced_deployment\nyou can use label_selector\n\n:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.\n\nfrom kubernetes import cl...
[ 1 ]
[]
[]
[ "kubernetes", "python" ]
stackoverflow_0074120339_kubernetes_python.txt
Q: How to get current timestamp in AWS Lambda? I am trying to query a group of IDs created in the last 30 days in an AWS Lambda function written in python. I need the lambda to be able to generate a current timestamp in this format: 2021-05-22T00:00:00. How can I get this timestamp? A: >>> from datetime import dat...
How to get current timestamp in AWS Lambda?
I am trying to query a group of IDs created in the last 30 days in an AWS Lambda function written in python. I need the lambda to be able to generate a current timestamp in this format: 2021-05-22T00:00:00. How can I get this timestamp?
[ ">>> from datetime import datetime\n>>> datetime.now().isoformat(timespec='seconds')\n'2021-06-23T17:19:53'\n\n", "You can also get the lambda request time epoch in requestTimeEpoch. Just take care, the value is in milliseconds.\ndatetime.fromtimestamp(event['requestContext']['requestTimeEpoch'] / 1000)\n\n" ]
[ 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "python", "timestamp" ]
stackoverflow_0068106455_amazon_web_services_aws_lambda_python_timestamp.txt
Q: Field 'id' expected a number but got 'pk' I'm writing some simple unit tests for my class based views. I've completed the tests for urls in which I've used args = ['pk'] for urls that had pks. However, when doing similar tests to views, ones with pks ends with the error Field 'id' expected a number but got 'pk' '....
Field 'id' expected a number but got 'pk'
I'm writing some simple unit tests for my class based views. I've completed the tests for urls in which I've used args = ['pk'] for urls that had pks. However, when doing similar tests to views, ones with pks ends with the error Field 'id' expected a number but got 'pk' '. Here's the working URL test: url = rev...
[ "path('user/<int:pk>/', GetUser.as_view(), name='user'),\npath('update/<int:pk>/', UpdateUser.as_view(), name='update-user'),\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_class_based_views", "django_rest_framework", "python", "unit_testing" ]
stackoverflow_0074120655_django_django_class_based_views_django_rest_framework_python_unit_testing.txt
Q: Error object has no attribute in Paint app This is the code, I got it from here https://www.youtube.com/watch?v=uW-NLL9dlBs After many attempts, I solved some issues, but I still couldnt get it to work. Its supposed to be an app for painting. I wanted it to have very large pixels with invisible grid too, so painti...
Error object has no attribute in Paint app
This is the code, I got it from here https://www.youtube.com/watch?v=uW-NLL9dlBs After many attempts, I solved some issues, but I still couldnt get it to work. Its supposed to be an app for painting. I wanted it to have very large pixels with invisible grid too, so painting in it would create low resolution pixel art, ...
[ "In order to get your paint program working, the following bugs need to be addressed.\nThe self.canvas_color_button command has a bug. Just remove the parens to make it work.\nThere's a problem with color selection methods.\nHere is the solution.\ndef select_color(self,col):\n self.pen_color = col\n\n\ndef erase...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074108987_python_tkinter.txt
Q: ModuleNotFoundError: No module names libcloud.utils Using python 3.7.9, apache-libcloud 3.6.0 It was working fine on Ubuntu however error arose when replicating on Windows therefore guessing it is OS problem however cannot find any reference online. When I call get_driver() method from libcloud.storage.providers i...
ModuleNotFoundError: No module names libcloud.utils
Using python 3.7.9, apache-libcloud 3.6.0 It was working fine on Ubuntu however error arose when replicating on Windows therefore guessing it is OS problem however cannot find any reference online. When I call get_driver() method from libcloud.storage.providers it attempts and fails to import libcloud.utils from libclo...
[ "Install dj-libcloud from terminal using pip.\nThe command:\npip install dj-libcloud\n\nThen try:\nimport libcloud.utils\n\n" ]
[ 0 ]
[]
[]
[ "libcloud", "linux", "operating_system", "python", "windows" ]
stackoverflow_0074120023_libcloud_linux_operating_system_python_windows.txt
Q: unable to perform min I have a following dataframe: import pandas as pd import itertools d = {'A': range(1, 11), 'C': range(1, 16)} df = pd.DataFrame(itertools.product(*d.values()),columns=d.keys()) I would like to add new column Gc which will take a value of two nested min: df.assign(Gc=min(53*df["C"] - 0.9*d...
unable to perform min
I have a following dataframe: import pandas as pd import itertools d = {'A': range(1, 11), 'C': range(1, 16)} df = pd.DataFrame(itertools.product(*d.values()),columns=d.keys()) I would like to add new column Gc which will take a value of two nested min: df.assign(Gc=min(53*df["C"] - 0.9*df["C"]**2, min(62*df["A"] -...
[ "The issue is that min is a python function, which only works with scalar (not vectors).\nYou can use numpy:\nimport numpy as np\n\ndf.assign(Gc=np.minimum(53*df[\"C\"] - 0.9*df[\"C\"]**2,\n np.minimum(62*df[\"A\"] - 1.5*df[\"A\"]**2, 15)))\n\noutput:\n A C Gc\n0 1 1 15.0\n1 ...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074120923_pandas_python.txt
Q: Using regex to get multiple number in string in python I have 3 strings "1:1 (1 stock – 1 voting right)" "1 stock – 1 voting right" "01 stock – 01 voting right" How can i get all the numbers in string and return it to format "num:num" when I use regex in Python. Can you give me a general regex to process all cas...
Using regex to get multiple number in string in python
I have 3 strings "1:1 (1 stock – 1 voting right)" "1 stock – 1 voting right" "01 stock – 01 voting right" How can i get all the numbers in string and return it to format "num:num" when I use regex in Python. Can you give me a general regex to process all case? Example: If case is first string, it will return 1:1 beca...
[ "My two cents assuming:\n\nAt least two integers seperated by at least a single non-number;\nOrder of appearance of these integers is kept as input for 1st:2nd integer in final format;\nRemove possible leading zeros from integers.\n\nTry:\n^\\D*0*(\\d+)\\D+0*(\\d+).*$\n\nReplace with \\1:\\2. See an online demo\n\n...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074120666_python_regex.txt
Q: Backfill a list with preceding list items Say I have a list containing the values 1, 0 and -1. I am trying to find a method of creating a new list so that the preceding values determine the current values. So that for every zero that appears, if a positive number was the last seen in the list, it should become 1. ...
Backfill a list with preceding list items
Say I have a list containing the values 1, 0 and -1. I am trying to find a method of creating a new list so that the preceding values determine the current values. So that for every zero that appears, if a positive number was the last seen in the list, it should become 1. Similarly, with negative numbers. #Example: x ...
[ "Using a simple loop:\nx = [1, 1, 1, 0, 0, -1, -1, 1, 0, 1, 0, 0, 0, -1, -1, 0, 0, 1, 1, 1, 1]\n\nout = []\nprev = 1 # default value\nfor i in x:\n if i == 0:\n out.append(prev)\n else:\n out.append(i)\n prev = i\n\noutput:\n[1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, ...
[ 1 ]
[]
[]
[ "list", "python", "python_2.7" ]
stackoverflow_0074120828_list_python_python_2.7.txt
Q: AzureML: msrest.serialization:Ran into a deserialization error following AutoMLStep run I am running an automated ML training notebook which is basically replicating a MS tutorial notebook (https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/machine-learning-pipelines/intro-to-pipeline...
AzureML: msrest.serialization:Ran into a deserialization error following AutoMLStep run
I am running an automated ML training notebook which is basically replicating a MS tutorial notebook (https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-with-automated-machine-learning-step.ipynb). After running the pipeline to co...
[ "I tried to reproduce the issue and worked for me. The warning is regarding the deserialization and the dependency is notified in conda environment. To avoid the warning and achieve the prediction and get the result. It is suggested to use the AutoML notebook.\n# Retrieve best model from Pipeline Run\nbest_model_ou...
[ 0 ]
[]
[]
[ "azure_machine_learning_service", "azure_ml_pipelines", "azureml_python_sdk", "python" ]
stackoverflow_0074105623_azure_machine_learning_service_azure_ml_pipelines_azureml_python_sdk_python.txt
Q: How to drop all columns with null values in a PySpark DataFrame? I have a large dataset of which I would like to drop columns that contain null values and return a new dataframe. How can I do that? The following only drops a single column or rows containing null. df.where(col("dt_mvmt").isNull()) #doesnt work beca...
How to drop all columns with null values in a PySpark DataFrame?
I have a large dataset of which I would like to drop columns that contain null values and return a new dataframe. How can I do that? The following only drops a single column or rows containing null. df.where(col("dt_mvmt").isNull()) #doesnt work because I do not have all the columns names or for 1000's of columns df.fi...
[ "Here is one possible approach for dropping all columns that have NULL values: See here for the source on the code of counting NULL values per column.\nimport pyspark.sql.functions as F\n\n# Sample data\ndf = pd.DataFrame({'x1': ['a', '1', '2'],\n 'x2': ['b', None, '2'],\n 'x3': ...
[ 14, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python" ]
stackoverflow_0051322445_apache_spark_apache_spark_sql_pyspark_python.txt
Q: Efficient way to find a substring in a string, but the superstring contains brackets I am doing constituency parsing. I have a larger string, and this string contains brackets. Example: "The [quick brown fox] [jumps over] [the lazy dog]." I have a smaller substring, but this string does not contain brackets: "quic...
Efficient way to find a substring in a string, but the superstring contains brackets
I am doing constituency parsing. I have a larger string, and this string contains brackets. Example: "The [quick brown fox] [jumps over] [the lazy dog]." I have a smaller substring, but this string does not contain brackets: "quick brown fox jumps over" I want to find the version of the smaller substring in the larger ...
[ "One approach that can achieve this in linear time complexity would be to create lists of indices at which left brackets and right brackets should be inserted in the larger sentence that's stripped of the brackets.\nThen, find the indices of the leftmost left bracket and of the rightmost right bracket within where ...
[ 0 ]
[]
[]
[ "performance", "python", "search", "string" ]
stackoverflow_0074108429_performance_python_search_string.txt
Q: How to train Numpy-based data on GPU? Because of the huge amount of data, I want to train my data on GPU. My model is also based on Numpy. How can I modify the data and model to speed up my calculation? A: Numpy does not have native support GPU. However, you can use library like Numba, which is utilized for big ...
How to train Numpy-based data on GPU?
Because of the huge amount of data, I want to train my data on GPU. My model is also based on Numpy. How can I modify the data and model to speed up my calculation?
[ "Numpy does not have native support GPU. However, you can use library like Numba, which is utilized for big datasets and GPU usage.\n" ]
[ 0 ]
[]
[]
[ "gpu", "machine_learning", "python" ]
stackoverflow_0074121033_gpu_machine_learning_python.txt
Q: Hosting webhook target GCP Cloud Function I am very new to GCP, my plan is create a webhook target on GCP to listen for events on a thirdparty application, kick off scripts to download files from webhook event and push to JIRA/Github. During my research read alot about cloud functions, but there were also cloud ru...
Hosting webhook target GCP Cloud Function
I am very new to GCP, my plan is create a webhook target on GCP to listen for events on a thirdparty application, kick off scripts to download files from webhook event and push to JIRA/Github. During my research read alot about cloud functions, but there were also cloud run, app engine and PubSub. Any suggestions on wh...
[ "There are use cases in which Cloud Functions, Cloud Run and App Engine can be used indistinctively (not Pubsub as it is a messaging service). There are however use cases that do not fit some of them properly.\nCloudFunctions must be triggered and each execution is (should be) isolated, that implies you can not exp...
[ 1 ]
[]
[]
[ "cloud", "google_cloud_functions", "google_cloud_platform", "python" ]
stackoverflow_0074119702_cloud_google_cloud_functions_google_cloud_platform_python.txt
Q: How to match string from regex in column? I have a data frame with two columns name and regex. And mystring = 'abc xy 123 main st' ---name----regex--- ---123 Main Street----\d+\s*main\s*st(reet)?--- ---123 Middle Street----\d+\s*middle\s*st(reet)?--- --------------------------------------------------- Now I want ...
How to match string from regex in column?
I have a data frame with two columns name and regex. And mystring = 'abc xy 123 main st' ---name----regex--- ---123 Main Street----\d+\s*main\s*st(reet)?--- ---123 Middle Street----\d+\s*middle\s*st(reet)?--- --------------------------------------------------- Now I want to get the names regex frame whose regex grant ...
[ "You can match the string to each regex using the map function that applies a lambda to each row:\nimport re\ndf[df['regex'].map(lambda r: re.search(r, mystring)).astype(bool)]\n# name regex\n#0 123 Main Street \\d+\\s*main\\s*st(reet)?\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "regex" ]
stackoverflow_0074120978_dataframe_pandas_python_regex.txt
Q: How to edit size of axes text size on SHAP depedence plot in Python I have used this code: for i in range(len(col_list)): shap.dependence_plot(i, shap_values, X.values, feature_names=X.columns, dot_size=10, interaction_index=None, x_jitter=-0.5) to generate the following SHAP dependence plot: Does anyone kno...
How to edit size of axes text size on SHAP depedence plot in Python
I have used this code: for i in range(len(col_list)): shap.dependence_plot(i, shap_values, X.values, feature_names=X.columns, dot_size=10, interaction_index=None, x_jitter=-0.5) to generate the following SHAP dependence plot: Does anyone know how to modify the size of the text in the x-axis so that it becomes sma...
[ "I'm not familiar with SHAP, but my guess is it looks like it returns a matplotlib Figure object. In that case, the following should work\nshap_figure = shap.dependence_plot(i, shap_values, X.values, feature_names=X.columns, dot_size=10, interaction_index=None, x_jitter=-0.5)\n\nax_list = shap_figure .axes # see ht...
[ 1 ]
[]
[]
[ "plot", "python", "shap", "text" ]
stackoverflow_0074121149_plot_python_shap_text.txt
Q: Send myself an email using win32com.client I have a template from code I've gathered from different places to send emails in various of my scripts: import win32com.client ################################################## ################################################## #########################################...
Send myself an email using win32com.client
I have a template from code I've gathered from different places to send emails in various of my scripts: import win32com.client ################################################## ################################################## ################################################## ######################################...
[ "The CurrentUser property of the Namespace or Account class allows to get the display name of the currently logged-on user as a Recipient object. The Recipient class provides the Address property which returns a string representing the e-mail address of the Recipient. \nIn case of Exchange server you may need to ca...
[ 1, 0 ]
[]
[]
[ "outlook", "python", "win32com" ]
stackoverflow_0031280228_outlook_python_win32com.txt
Q: Saving an image after tf.image.resize I am trying to resize some images using tensorflows image resizing method. I have a loop where I load in the image, resize and then try to write it back out using cv2.imwrite(). However, it continues to error out, does this not output an image? Here's my code: j=0 for i in ima...
Saving an image after tf.image.resize
I am trying to resize some images using tensorflows image resizing method. I have a loop where I load in the image, resize and then try to write it back out using cv2.imwrite(). However, it continues to error out, does this not output an image? Here's my code: j=0 for i in images: skyr_img = imread(my_data_dir+'/'+st...
[ "If you are using colab you can mount your drive to colab using\nfrom google.colab import drive\ndrive.mount('/content/drive', force_remount=True)\n\nYou can save images to your drive using\nimg = cv2.imread('/content/gold.jpeg')\nresized_img = tf.image.resize(img, (1050, 1610)).numpy()\npath ='/content/drive/MyDri...
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0073626489_python_tensorflow.txt
Q: Error loading MySQLdb module: No module named 'MySQLdb' I have tried a lot to solve this issue but I did not solve it. I have searched a lot on google and stackoverflow, no option is working for me. Please help me. Thanks in advance. I am using django 1.10, python 3.4. I have tried : pip install mysqldb. pip inst...
Error loading MySQLdb module: No module named 'MySQLdb'
I have tried a lot to solve this issue but I did not solve it. I have searched a lot on google and stackoverflow, no option is working for me. Please help me. Thanks in advance. I am using django 1.10, python 3.4. I have tried : pip install mysqldb. pip install mysql. pip install mysql-python. pip install MySQL-python...
[ "MySQLdb is the interface to MySQL database. As mentioned by other posts, MySQLdb doesn't support Python 3.x. I used PyMySQL as the replacement. You need to install it first:\npip install PyMySQL\n\nThe next step is to replace 'MySQLdb' with 'pymysql' in all the codes, which is intimidating. Luckily, PyMySQL can be...
[ 42, 13, 12, 3, 2, 1, 0, 0 ]
[]
[]
[ "django", "mysql", "python", "python_3.x" ]
stackoverflow_0039574813_django_mysql_python_python_3.x.txt
Q: Manually Edit cells in pandas data frame on a condition We have the following dummy data frame that collects counts of warnings (based on a reason) for a given date: temp = pd.DataFrame(np.array([['2022-10-13','one',123],['2022-10-13','two',77123], ['2022-10-13','three',451], ['2022-1...
Manually Edit cells in pandas data frame on a condition
We have the following dummy data frame that collects counts of warnings (based on a reason) for a given date: temp = pd.DataFrame(np.array([['2022-10-13','one',123],['2022-10-13','two',77123], ['2022-10-13','three',451], ['2022-10-13','three',77]]), columns = ['...
[ "First make sure the column count are integers (or floats), then use .loc[] and select the rows you wish to adapt (temp.reason != 'two') and make the change (temp['count'] * 100):\ntemp['count'] = temp['count'].astype(int)\ntemp.loc[temp.reason != 'two', 'count'] = temp['count'] * 100\nprint(temp)\n\nOutput\n ...
[ 3, 3, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074121264_numpy_pandas_python.txt
Q: Selenium with firefox-geckodriver on Raspbian 64bit? is possible to run automatic scripts (Python + Selenium) with firefox-esr browser on Rasberry Pi OS (Raspbian) 64 bit? In the past I used Ubuntu XFCE on my Raspberrypi Pi 4 and there was possible to install geckodriver (like sudo apt install firefox-geckodriver)...
Selenium with firefox-geckodriver on Raspbian 64bit?
is possible to run automatic scripts (Python + Selenium) with firefox-esr browser on Rasberry Pi OS (Raspbian) 64 bit? In the past I used Ubuntu XFCE on my Raspberrypi Pi 4 and there was possible to install geckodriver (like sudo apt install firefox-geckodriver). When comes official 64 bit Raspbian I removed Ubuntu and...
[ "Mozilla finally releases Geckodriver 0.32 for AArch64 which works on Raspbian 64bit (Debian based).\n" ]
[ 0 ]
[]
[]
[ "geckodriver", "python", "raspberry_pi", "raspbian", "selenium" ]
stackoverflow_0072367038_geckodriver_python_raspberry_pi_raspbian_selenium.txt
Q: Binary representation of float in Python (bits not hex) How to get the string as binary IEEE 754 representation of a 32 bit float? Example 1.00 -> '00111111100000000000000000000000' A: You can do that with the struct package: import struct def binary(num): return ''.join('{:0>8b}'.format(c) for c in struct.p...
Binary representation of float in Python (bits not hex)
How to get the string as binary IEEE 754 representation of a 32 bit float? Example 1.00 -> '00111111100000000000000000000000'
[ "You can do that with the struct package:\nimport struct\ndef binary(num):\n return ''.join('{:0>8b}'.format(c) for c in struct.pack('!f', num))\n\nThat packs it as a network byte-ordered float, and then converts each of the resulting bytes into an 8-bit binary representation and concatenates them out:\n>>> bina...
[ 90, 41, 31, 15, 10, 9, 5, 2, 2, 1, 0, 0, 0 ]
[ "You can use the .format for the easiest representation of bits in my opinion:\nmy code would look something like:\ndef fto32b(flt):\n# is given a 32 bit float value and converts it to a binary string\nif isinstance(flt,float):\n # THE FOLLOWING IS AN EXPANDED REPRESENTATION OF THE ONE LINE RETURN\n #...
[ -1 ]
[ "binary", "floating_point", "python" ]
stackoverflow_0016444726_binary_floating_point_python.txt
Q: Global Max Pooling in Pytorch: RuntimeError: mat1 and mat2 shapes cannot be multiplied (128x2048 and 128x1024) In the model I'm building I'm trying to improve performance by replacing the Flatten layer with global max pooling. To check that shapes are in order I ran a single random sample through the net: test = t...
Global Max Pooling in Pytorch: RuntimeError: mat1 and mat2 shapes cannot be multiplied (128x2048 and 128x1024)
In the model I'm building I'm trying to improve performance by replacing the Flatten layer with global max pooling. To check that shapes are in order I ran a single random sample through the net: test = torch.rand((1, 3, 224, 224)) # [N, C, H, W] foo = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, pad...
[ "Use Flatten() in the layers instead of view(). So your linear layer should look like this:\n self.linear = nn.Sequential(\n nn.Flatten(),\n nn.Dropout(0.5),\n nn.Linear(128, 1024),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(1024, 10)\n )\n\nAnd your forward functio...
[ 1 ]
[]
[]
[ "conv_neural_network", "python", "pytorch" ]
stackoverflow_0074120641_conv_neural_network_python_pytorch.txt
Q: How to stream video/images from python app to a remote ReactJS webpage I have been searching for this solution but not sure of the direction to go. I have a python app using OpenCV to stream realtime video cameras (CCTV). So when I sit on the pc itself where the app is running I can open the cameras in the app and...
How to stream video/images from python app to a remote ReactJS webpage
I have been searching for this solution but not sure of the direction to go. I have a python app using OpenCV to stream realtime video cameras (CCTV). So when I sit on the pc itself where the app is running I can open the cameras in the app and see the videos playing (using cv2.imshow). However I now am looking to view...
[ "To establish the flask/opencv connection you do something like the following. In your flask you setup a function:\ndef webcam():\n camera = cv2.VideoCapture(0)\n\n while True:\n success, frame = camera.read()\n if success:\n \n ret, buffer = cv2.imencode('.jpg', frame)\n ...
[ 0 ]
[]
[]
[ "python", "reactjs", "video_streaming" ]
stackoverflow_0074090972_python_reactjs_video_streaming.txt
Q: How to modify the Dataframe I have dataframe like this Keyword devops aws ec2 python java dotnet optional/mandatory optional mandatory mandatory optional optional mandatory Candidate Name User1 ...
How to modify the Dataframe
I have dataframe like this Keyword devops aws ec2 python java dotnet optional/mandatory optional mandatory mandatory optional optional mandatory Candidate Name User1 1 1 1 ...
[ "Instead calculate_skill_coverage_percent use mean by all rows - it is sum divided by length with set 0 if mean of mandatory is less like 1 by Series.mask:\ns = df.xs('mandatory', level=0, axis=1).mean(axis=1)\ndf['Percent_Match'] = df.mean(axis=1).mask(s.lt(1), 0)\n\nprint(df)\n mandatory ...
[ 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074121139_dataframe_numpy_pandas_python.txt
Q: Asking for Big Query code for the below mentioned SAS-SQL code Suppose I have a table name customer which is having cust_id(customer ID) and purchase date columns. I need to know the Big query code of below mentioned SAS-SQL code. proc sql; select * from customer where cust_id <>. ; quit; What would be the Big q...
Asking for Big Query code for the below mentioned SAS-SQL code
Suppose I have a table name customer which is having cust_id(customer ID) and purchase date columns. I need to know the Big query code of below mentioned SAS-SQL code. proc sql; select * from customer where cust_id <>. ; quit; What would be the Big query code (specifically 3rd line of the code) of this piece of code?...
[ "I would propose the following:\nselect * \nfrom customer \nwhere cust_id IS NOT NULL \n\n", "In SAS SQL, period(.) is used to define missing values which are equal to null and <> denotes not equal if used with WHERE statement. For your requirement, a BigQuery IS operator can be used. The third statement can be...
[ 1, 0 ]
[]
[]
[ "google_bigquery", "python", "sas", "sql" ]
stackoverflow_0074109628_google_bigquery_python_sas_sql.txt
Q: Concatenate list element of three different based on index into one list I have the following three lists of which I'd like to combine each list element by index creating a new list. Before: list_numbers = [55900, 44560, 49510, 49509, 49519, 49556, 49586] list_names = ['Richard White', 'Susan Pierce', 'Kim Note',...
Concatenate list element of three different based on index into one list
I have the following three lists of which I'd like to combine each list element by index creating a new list. Before: list_numbers = [55900, 44560, 49510, 49509, 49519, 49556, 49586] list_names = ['Richard White', 'Susan Pierce', 'Kim Note', 'John Lee', 'Jennifer Six', 'Maria Cruz', 'Martin Lewis'] list_grades = ['10...
[ "You can try to run loop and concatenate all values as single string as below:\n[f'{list_numbers[l]} {list_names[l]} {list_grades[l]}' for l in range(len(list_grades))]\n\nOr\n[' '.join(map(str, z)) for z in zip(list_numbers,list_names, list_grades )]\n\nOutput:\n['55900 Richard White 100',\n'44560 Susan Pierce 46'...
[ 1, 0 ]
[]
[]
[ "concatenation", "list", "python", "sorting" ]
stackoverflow_0074121406_concatenation_list_python_sorting.txt
Q: How to use a python application (tkinter).exe to open a text file im a beginner at python and im trying to created a program using tkinter that view and edit text. i used pyinstaller to make an .exe file to view text, but when i used "open with" to a text file and select my text viewer program nothing shows. then ...
How to use a python application (tkinter).exe to open a text file
im a beginner at python and im trying to created a program using tkinter that view and edit text. i used pyinstaller to make an .exe file to view text, but when i used "open with" to a text file and select my text viewer program nothing shows. then i noticed that how is my program supposed to open the file and display ...
[ "Not sure if I understood your question well. Do you need to know the path of the file you are opening?\n from os.path import split\n\n textname=filedialog.askopenfilename(title=\"Open File\", filetypes=((\"Text\", \"*.txt\"), (\"Python\", \"*.py\"), (\"Html\", \"*.html\"), (\"All Files\", \"*.*\")))\n pat...
[ 0 ]
[]
[]
[ "python", "tkinter", "windows" ]
stackoverflow_0074120852_python_tkinter_windows.txt
Q: Converting text file to json I have text file and I want to convert it to JSON: red|2022-09-29|03:15:00|info 1 blue|2022-09-29|10:50:00| yellow|2022-09-29|07:15:00|info 2 so i type a script to convert this file into JSON: import json filename = 'input_file.txt' dict1 = {} fields =['name', 'date', 'time', '...
Converting text file to json
I have text file and I want to convert it to JSON: red|2022-09-29|03:15:00|info 1 blue|2022-09-29|10:50:00| yellow|2022-09-29|07:15:00|info 2 so i type a script to convert this file into JSON: import json filename = 'input_file.txt' dict1 = {} fields =['name', 'date', 'time', 'info'] with open(filename) as fh...
[ "If you see your required json output, it is a list and not a dict like you have right now. So using a list(data) instead of dict(dict1) should give the correct output.\nFollowing updated code should generate the json data in required format -\nimport json\n\nfilename = 'input_file.txt' \ndata = []\nfields =['name'...
[ 1, 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074121481_json_python.txt
Q: List combination based on value of each index in another list I have the following two lists list_1 = [3, 5, 7, 2] list_2 = [ '1-CHA', '2-NOF', '3-INC', '4-CHA', '5-NOF', '6-NOF', '7-INC', '8-INC', '9-INC', '10-INC', '11-CHA', '12-NOF', '13-CHA', '14-CHA', '15-INC', '16-IN...
List combination based on value of each index in another list
I have the following two lists list_1 = [3, 5, 7, 2] list_2 = [ '1-CHA', '2-NOF', '3-INC', '4-CHA', '5-NOF', '6-NOF', '7-INC', '8-INC', '9-INC', '10-INC', '11-CHA', '12-NOF', '13-CHA', '14-CHA', '15-INC', '16-INC', '17-INC' ] I want to combine the two lists in the fol...
[ "You can create an iterator from list_2 so that you can fetch items from the list for the number of times specified in list_1 by calling next on the iterator:\nseq = iter(list_2)\nfinal_list = ['|'.join(next(seq) for _ in range(n)) for n in list_1]\n\nYou can also use itertools.islice instead to avoid repeated call...
[ 5, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0074121490_list_list_comprehension_python.txt
Q: how to show the combinaton too in this code? This is my code to exchange a bank note to smaller coines and notes.it shows the number of combination but not the combination themselves. how should I modify the code? def exchange(a,coins): if a==0: return 1 elif a<0 or len(coins)==0: return 0 ...
how to show the combinaton too in this code?
This is my code to exchange a bank note to smaller coines and notes.it shows the number of combination but not the combination themselves. how should I modify the code? def exchange(a,coins): if a==0: return 1 elif a<0 or len(coins)==0: return 0 else: return exchange(a,coins[1:])+exc...
[ "Right now, the base cases of your recursive function only return numbers. If you want your result to be a list of combinations, you need to at least return lists from your base cases.\n" ]
[ 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074110459_python_recursion.txt
Q: how to round-off the value of the x-axis in python line chart how to round off the value of the x-axis in this graph as it's very long number 6000000 and not looking good. and also how can I make this graph more good-looking and presentable here is my code import pandas as pd import matplotlib.pyplot as plt import...
how to round-off the value of the x-axis in python line chart
how to round off the value of the x-axis in this graph as it's very long number 6000000 and not looking good. and also how can I make this graph more good-looking and presentable here is my code import pandas as pd import matplotlib.pyplot as plt import pandas as pd import matplotlib.ticker as mticker import numpy as n...
[ "\nUse ax.ticklabel_format\n...\nfig, ax = plt.subplots()\n# set the format BEFORE putting \"ink\" in the figure\nax.ticklabel_format(axis='y', scilimits=(4,4), useMathText=True)\nax.set_ylim((57800,62200))\n...\n\n\nThis is exactly (oh well! almost...) the first diagram in question, but with the y-axis labels as i...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074120029_matplotlib_python.txt
Q: What does the PyTables warning "a closed node found in the registry" mean? When using pandas.to_hdf function to save data to a HDF5 file, I'm getting the following warning: C:\{my path to conda environment}\lib\site-packages\tables\file.py:426: UserWarning: a closed node found in the registry: ``/{my object key}/...
What does the PyTables warning "a closed node found in the registry" mean?
When using pandas.to_hdf function to save data to a HDF5 file, I'm getting the following warning: C:\{my path to conda environment}\lib\site-packages\tables\file.py:426: UserWarning: a closed node found in the registry: ``/{my object key}/meta/{my column name}/meta/_i_table`` warnings.warn("a closed node found in th...
[ "For all its worth i managed to overcome the warning by installing tables 3.6.1 from:\nhttps://www.lfd.uci.edu/~gohlke/pythonlibs/#pytables\nusing the +gpl version for python 3.9.\nNever the less i do not know the details of this choice and i cannot justify why it is working.\n", "I observed the same issue. For m...
[ 0, 0 ]
[]
[]
[ "hdf5", "pandas", "pytables", "python", "warnings" ]
stackoverflow_0061801207_hdf5_pandas_pytables_python_warnings.txt
Q: how to solve winerror 5 in python? my code is this but for some reason its not working? # opening an image from the source path img = Image.open('text1.png') # describes image format in the output print(img) # path where the tesseract module is installed pytesseract.pytesseract.tesseract_cmd = ( r'C:\Users\Sa...
how to solve winerror 5 in python?
my code is this but for some reason its not working? # opening an image from the source path img = Image.open('text1.png') # describes image format in the output print(img) # path where the tesseract module is installed pytesseract.pytesseract.tesseract_cmd = ( r'C:\Users\Sayan Dutta Gupta\AppData\Local\Programs\P...
[ "I've run into this as well, solution is usually to be sure to run the program as an administrator (right click, run as administrator.)\n" ]
[ 0 ]
[]
[]
[ "python", "python_tesseract" ]
stackoverflow_0074121648_python_python_tesseract.txt
Q: figuring out action performed based on date column for pandas dataframe Existing Dataframe : Id sms_sent_date sms_number Action_date action_performed A 21-11-2021 1 21-11-2021 opened A 22-11-2021 2 22-...
figuring out action performed based on date column for pandas dataframe
Existing Dataframe : Id sms_sent_date sms_number Action_date action_performed A 21-11-2021 1 21-11-2021 opened A 22-11-2021 2 22-11-2021 clicked A 23-11-2021 3 ...
[ "Filter rows by maximal sms_sent_date per groups by GroupBy.transform and then get first row by Id by DataFrame.drop_duplicates:\ndf1 = (df[df['sms_sent_date'].eq(df.groupby(['Id'])['sms_sent_date'].transform('max'))]\n .drop_duplicates('Id'))\nprint (df1)\n Id sms_sent_date sms_number Action_date action_...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074121645_pandas_python.txt
Q: Pyautogui locate functions in a minimized window I am developing a code using pyautogui where i detect an event in the window "A" and them, with alt+tab, execute an action in the window "B". I would like to know if it is possible to do this, but with the window "A" minimized, so it doesnt have to alt+tab all the t...
Pyautogui locate functions in a minimized window
I am developing a code using pyautogui where i detect an event in the window "A" and them, with alt+tab, execute an action in the window "B". I would like to know if it is possible to do this, but with the window "A" minimized, so it doesnt have to alt+tab all the time (the solution doesnt necessary has to be with pyau...
[ "If you intended to use the locate function with pyautogui, whether or not it's LocateAll or just locate, it has to see that same matching image on screen first then you can adjust the confident to your needs. What you're asking is really hard to answer without knowing what you wanted to do, for example if you wann...
[ 0 ]
[]
[]
[ "automation", "pyautogui", "python", "screenshot", "windows" ]
stackoverflow_0074114378_automation_pyautogui_python_screenshot_windows.txt
Q: TypeError: Parameter to MergeFrom() must be instance of same class: expected google.datastore.v1.Key.PathElement got PathElement I am trying to push the data to GCP DataStore, The below code snippet works fine in Jupyter Notebook but it is throwing error in VS Code. def load_data_json(self, kind_name, data_with_q...
TypeError: Parameter to MergeFrom() must be instance of same class: expected google.datastore.v1.Key.PathElement got PathElement
I am trying to push the data to GCP DataStore, The below code snippet works fine in Jupyter Notebook but it is throwing error in VS Code. def load_data_json(self, kind_name, data_with_qp_ID, qp_id): #Load the data in JSON format to upload into the DataStore data_with_qp_ID_as_JSON = self.convert_DF_t...
[ "I was able to clear this error. It was an issue with Protobuf library that my environment was using. I downgraded the version of protobuf from 4.x.x to 3.20.1 and it worked.\n" ]
[ 0 ]
[]
[]
[ "datastore", "google_cloud_platform", "python" ]
stackoverflow_0074101113_datastore_google_cloud_platform_python.txt
Q: Run Python script multiple times at the same time? Hey I have the following "problem". I am currently writing a python script that checks certificates for CRL. You give this script the certificate in the command line and it checks it. This script should now be started several times in the Linux terminal at the sam...
Run Python script multiple times at the same time?
Hey I have the following "problem". I am currently writing a python script that checks certificates for CRL. You give this script the certificate in the command line and it checks it. This script should now be started several times in the Linux terminal at the same time. Does this work with a normal script without mult...
[ "you can run multiple shell commands by using & between commands to run them in parallel:\ncmd arg1 & cmd arg2 & cmd arg3\n\nfor example\n", "There are several way to do this.\nUsing only bash, See Here\nUsing Parallel package, See Here\nInstall parallel before using it with sudo apt install parallel -y.\n" ]
[ 2, 0 ]
[]
[]
[ "linux", "multithreading", "python", "python_3.x" ]
stackoverflow_0074121529_linux_multithreading_python_python_3.x.txt
Q: How to substract two dates based on filter of two other columns I am new in Python and I am struggling to reshape my dataFrame. For a particular client (contact_id), I want to add an new date column that actually substracts the DTHR_OPERATION date for a 'TYPE_OPER_VALIDATION = 3' minus the DTHR_OPERATION date for ...
How to substract two dates based on filter of two other columns
I am new in Python and I am struggling to reshape my dataFrame. For a particular client (contact_id), I want to add an new date column that actually substracts the DTHR_OPERATION date for a 'TYPE_OPER_VALIDATION = 3' minus the DTHR_OPERATION date for a 'TYPE_OPER_VALIDATION = 1'. If the 'TYPE_OPER_VALIDATION' is equal ...
[ "Hello Nicolas and welcome to Stack Overflow. Please remember to always include sample data to reproduce your issue. Here is sample data to reproduce part of your dataframe:\ndf = pd.DataFrame({'Id contact':['cf2e79bc-8cac-ec11-9840-000d3ab078e6']*12+['865c5edf-c7ac-ec11-9840-000d3ab078e6']*10,\n 'DTHR OPERAT...
[ 1, 0 ]
[]
[]
[ "datetime", "numpy", "pandas", "python", "series" ]
stackoverflow_0074089068_datetime_numpy_pandas_python_series.txt
Q: Using a single websocket for a multiple clients I've never used before websockets neither web workers and everything around that. Obviously, I'm lost and I don't know how to make it properly. I've learned how to make a websocket and leave it working in a server port successfully. As well, load a web worker (but th...
Using a single websocket for a multiple clients
I've never used before websockets neither web workers and everything around that. Obviously, I'm lost and I don't know how to make it properly. I've learned how to make a websocket and leave it working in a server port successfully. As well, load a web worker (but this one can't refresh the website straight). When a us...
[ "SOLVED!\nJust I generate a number assigned to each client (can be different device between each other) and I send the random number generated by server to each connection!\nBefore \"connection\" you shoul add:\nconst WS = require('ws');\nconst WS_PORT = 8081\nconst express = require('express');\nconst app = expres...
[ 0 ]
[]
[]
[ "node.js", "php", "python", "web_worker", "websocket" ]
stackoverflow_0074084913_node.js_php_python_web_worker_websocket.txt
Q: Python Logging module not working in Google Colab I will start by saying the I found a similar question and none of the suggested solutions worked for me at the end of 2022. I do not manage to do simple things like changing the severity level of the logging on Colab: Or writing the logs to a file: import logging ...
Python Logging module not working in Google Colab
I will start by saying the I found a similar question and none of the suggested solutions worked for me at the end of 2022. I do not manage to do simple things like changing the severity level of the logging on Colab: Or writing the logs to a file: import logging logging.basicConfig(filename='app.log', filemode='w', ...
[ "For the first problem, the debug message does not print because the lowest severity of the root logger is set to WARNING. You can change it to DEBUG with\nimport logging\n\nlogging.getLogger('RootLogger').setLevel(logging.DEBUG)\n\n\nFor the second problem, as Colab is still on Python 3.7 and not 3.8, the force= p...
[ 2 ]
[]
[]
[ "google_colaboratory", "python", "python_3.x", "python_logging" ]
stackoverflow_0074117246_google_colaboratory_python_python_3.x_python_logging.txt
Q: Append 0 after specific element in the same list by updating the length using python I have a problem which is similar to this. Here I am trying to append 0 after every 5 in the list. The below code does not update the length of the list and the output I get is [1,4,5,0,2,7,5,0,5] while desired output is [1,4,5,0,...
Append 0 after specific element in the same list by updating the length using python
I have a problem which is similar to this. Here I am trying to append 0 after every 5 in the list. The below code does not update the length of the list and the output I get is [1,4,5,0,2,7,5,0,5] while desired output is [1,4,5,0,2,7,5,0,5,0] mylist1 = [1,4,5,2,7,5,5] for i in range(len(mylist1)): if mylist1[i] ==...
[ "Try this :\nmylist1 = [1,4,5,2,7,5,5]\n\nfor i, value in enumerate(mylist1):\n if value == 5:\n mylist1.insert(i+1, 0)\nprint(f'output: {mylist1}')\n\n", "Problem is when you insert an item into list, the list length changed. So your loop not iterate all items.\nTry this:\nmylist1 = [1, 4, 5, 2, 7, 5,...
[ 0, 0, 0, 0 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0074121528_append_list_python.txt
Q: Passing screenshot from selenium into Pillow without saving to disk I'm trying to take multiple screenshots using Selenium and need to do some basic image processing on each image and I'm using Pillow for this task. I'm trying to reduce the number of read and writes so would like to pass the png straight from sele...
Passing screenshot from selenium into Pillow without saving to disk
I'm trying to take multiple screenshots using Selenium and need to do some basic image processing on each image and I'm using Pillow for this task. I'm trying to reduce the number of read and writes so would like to pass the png straight from selenium into Pillow without saving it to disk first. Below is a rudimentary ...
[ "First, get_screenshot_as_png is not a method so no need to call it.\nSecond, The documentation for Image.open says that it can accept a file-like object, so you should be able to pass in a io.BytesIO object created from the bytes object containing the encoded image:\nSo you can use this code to read the image:\nfr...
[ 1 ]
[]
[]
[ "python", "python_imaging_library", "selenium" ]
stackoverflow_0071547773_python_python_imaging_library_selenium.txt
Q: Cannot get count() of PySpark dataframe after filtering I have two pyspark.sql.dataframe.DataFrame objects that are initialized as so (generalized example) df = spark.table(path) filtered_df = df.filter(df[col1].contains(value)) I can run the following code to determine the number of rows in df: print(df.count())...
Cannot get count() of PySpark dataframe after filtering
I have two pyspark.sql.dataframe.DataFrame objects that are initialized as so (generalized example) df = spark.table(path) filtered_df = df.filter(df[col1].contains(value)) I can run the following code to determine the number of rows in df: print(df.count()) This is successful. I can attempt to do the same for filter...
[ "Answer:\nNOTE: The above code works for me on Databricks with following assumption i.e., value is a single string or number.\nYou can try below two routes to filter dataframe element for a specific column.\nSolution 1:\nReplace this section of your code:\nfiltered_df = df.filter(df[col1].contains(value))\nwith the...
[ 1 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074121733_pyspark_python.txt
Q: Is it possible to add a dimension to a numpy.ndarray that its shape becomes (n,m,1)? For example: xlist = [(1, 2, 3, 4), (5, 6, 7, 8)] xarr = np.array(xlist) The shape of xarr is (2,4). Is it possible to reshape it to (2,4,1), so that I can use xarr[i][j][0] to get an element? A: There are several ways: xnew = ...
Is it possible to add a dimension to a numpy.ndarray that its shape becomes (n,m,1)?
For example: xlist = [(1, 2, 3, 4), (5, 6, 7, 8)] xarr = np.array(xlist) The shape of xarr is (2,4). Is it possible to reshape it to (2,4,1), so that I can use xarr[i][j][0] to get an element?
[ "There are several ways:\nxnew = np.rehshape(xnew, (2, 4, 1)) # slow but can handle non numpy\nxnew = xarr.reshape((2, 4, 1)) # can create a VIEW\nxarr[:,:,np.newaxis] # (2, 4, 1) # create a VIEW\nxarr.shape = (2, 4, 1) # fast, changes original array\n\n\nSome performance test, all operations a...
[ 2, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074117119_numpy_python.txt
Q: splitting the address column in pandas I have a pandas dataset like this: import pandas as pd data = {'id': ['001', '002', '003','004'], 'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA", "W...
splitting the address column in pandas
I have a pandas dataset like this: import pandas as pd data = {'id': ['001', '002', '003','004'], 'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA", "1180 Shelard Tower\\nMinneapolis, MN 55426\\nUSA", "William N. Barnard\\n145 S. Durbin\\nCasper, ...
[ "Here is an approach using extract instead of split and update in place:\ndf.update(df['address'].str.extract(r'([^,]+)(?:,\\s(\\w+)\\s*(\\d+)\\\\n(\\w+))?$')\n .set_axis([\"address\", \"region\", \"Zipcode\", \"Country\"], axis=1) \n )\n\ndf['name'] = pd.NA\n\ndf.update(df['address'].str.extract(r'(?:(.*?)\\\\n)?(...
[ 1, 0 ]
[]
[]
[ "dataframe", "delimiter", "pandas", "python", "split" ]
stackoverflow_0074121651_dataframe_delimiter_pandas_python_split.txt
Q: filtering a column list from a term starting from the back I have this dataset: emails1 = ['abc@gmail.com', "ddd@hotmail.com", "www@outlook.com"] emails2 = ['data@hello.com', "abc@gmail.com", 'data@gmail.com', "abc@gmail.com"] emails3 = ["abc@gmail.com", 'lll@hello.com'] terms = ['@gmail.com', 'data', 'ddd@'] d...
filtering a column list from a term starting from the back
I have this dataset: emails1 = ['abc@gmail.com', "ddd@hotmail.com", "www@outlook.com"] emails2 = ['data@hello.com', "abc@gmail.com", 'data@gmail.com', "abc@gmail.com"] emails3 = ["abc@gmail.com", 'lll@hello.com'] terms = ['@gmail.com', 'data', 'ddd@'] df = pd.DataFrame([emails1, emails2, emails3]) df["emails"] = df...
[ "The exact logic is unclear, but you need a list comprehension:\nimport re\nregex = re.compile('|'.join(map(re.escape, terms)))\n# r'@gmail\\.com|data|ddd@'\n\ndf['wanted'] = [next((x for x in l[::-1] if x and regex.search(x)), None)\n for l in df['emails']]\n\noutput:\n ...
[ 1 ]
[]
[]
[ "arrays", "dataframe", "pandas", "python" ]
stackoverflow_0074121923_arrays_dataframe_pandas_python.txt
Q: Confusion matrix problem; Result show only 0 and 1 I have the same problem, always the same. When I run a confusion matrix its results display only 0s & 1s. It is not suppose to go like this, here's the problem. It suppose to go between 0 and 20 but it's not. What I done wrong? and how can I fix this. Here's the...
Confusion matrix problem; Result show only 0 and 1
I have the same problem, always the same. When I run a confusion matrix its results display only 0s & 1s. It is not suppose to go like this, here's the problem. It suppose to go between 0 and 20 but it's not. What I done wrong? and how can I fix this. Here's the code I used from tensorflow import keras from keras.pre...
[ "Your predictions match the true labels. Thus, you perform a perfect classification with 100 % accuracy.\nMake sure to obtain the predictions from model i.e., model.predict(), which is currently not used. Exclude the subtotals from crosstab with margins=False, otherweise you include the subtotals in the confusion m...
[ 0 ]
[]
[]
[ "confusion_matrix", "keras", "python", "tensorflow" ]
stackoverflow_0074120954_confusion_matrix_keras_python_tensorflow.txt
Q: Python 3: ImportError "No Module named Setuptools" I'm having troubles with installing packages in Python 3. I have always installed packages with setup.py install. But now, when I try to install the ansicolors package I get: importerror "No Module named Setuptools" I have no idea what to do because I didn't have...
Python 3: ImportError "No Module named Setuptools"
I'm having troubles with installing packages in Python 3. I have always installed packages with setup.py install. But now, when I try to install the ansicolors package I get: importerror "No Module named Setuptools" I have no idea what to do because I didn't have setuptools installed in the past. Still, I was able to ...
[ "Your setup.py file needs setuptools. Some Python packages used to use distutils for distribution, but most now use setuptools, a more complete package. Here is a question about the differences between them.\nTo install setuptools on Debian:\nsudo apt-get install python3-setuptools\n\nFor an older version of Python...
[ 687, 173, 53, 36, 32, 31, 16, 12, 12, 5, 4, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "module", "package", "python", "python_3.3", "setup.py" ]
stackoverflow_0014426491_module_package_python_python_3.3_setup.py.txt