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: How to convert 2 lists into a dictionary WITH Column headers in python Although this seems a popular question, mine is different. I need the resulting dictionary to have headers: Here's what Im doing: list1 = [code_a, code_b, code_c] list2 = [name_a, name_b, name_c] to make this into a dictionary - we can use the...
How to convert 2 lists into a dictionary WITH Column headers in python
Although this seems a popular question, mine is different. I need the resulting dictionary to have headers: Here's what Im doing: list1 = [code_a, code_b, code_c] list2 = [name_a, name_b, name_c] to make this into a dictionary - we can use the zip function: res = dict(zip(list1, list2)) This will indeed produce for m...
[ "Hi i'm not very skilled at coding but in your combined_list you have duplicate keys so your goal isn't possible. I don't know what you're doing but i guess you could use a 2D datastructure. something like this:\ncombined_list = [('code_a', 'name_a'), ('code_b', 'name_b'), ('code_c', 'name_c')]\n\nyou cold generate...
[ 1 ]
[]
[]
[ "dictionary", "list", "python", "python_zip" ]
stackoverflow_0074380236_dictionary_list_python_python_zip.txt
Q: spark dataframe to csv in S3 I need to upload a spark dataframe as a csv to a path in S3. I'm having some trouble to find a solution whithout using some libraries. Due to client limitations, i cannot use pandas or s3fs. I can use boto3. Here's what a i have: import datetime as dt from pyspark.sql.functions import ...
spark dataframe to csv in S3
I need to upload a spark dataframe as a csv to a path in S3. I'm having some trouble to find a solution whithout using some libraries. Due to client limitations, i cannot use pandas or s3fs. I can use boto3. Here's what a i have: import datetime as dt from pyspark.sql.functions import * import boto3 MY_BUCKET = spark....
[ "You most probably need to two things. First, you have to save DataFrame into a single file, preferably to some temp location:\ntemp_location = MY_BUCKET+\"/folder/temp/\"\ndf.coalesce(1).write.csv(temp_location)\n\nThen, using Boto3, you have to extract this single CSV file from temp location into the preferred de...
[ 1 ]
[]
[]
[ "boto3", "pyspark", "python" ]
stackoverflow_0074380090_boto3_pyspark_python.txt
Q: How do I compare a text file that contains a router's running config with a live running config? Python, Linux Firsly, I am a beginner to this. I have to note that So I want to compare a router's running-config which I stored in a local machine in a text file to a current running-config that I want to print out in...
How do I compare a text file that contains a router's running config with a live running config? Python, Linux
Firsly, I am a beginner to this. I have to note that So I want to compare a router's running-config which I stored in a local machine in a text file to a current running-config that I want to print out in my linux terminal.. This is what I got so far. (THIS is written in VSCODE, so i can then open it via the linux term...
[ "you can try:\nwith open('running_config_copied.txt', 'r') as file1:\n diffs = difflib.ndiff(file1.readlines(),session.send_command('show running-config'))\n for diff in diffs:\n print(diff)\n\n" ]
[ 0 ]
[]
[]
[ "cisco", "config", "difflib", "linux", "python" ]
stackoverflow_0074380143_cisco_config_difflib_linux_python.txt
Q: Is there a way to handle dynamically loaded selectors with clicks on pages in scrapy-playwright? I have a use case like this. Suppose if I crawl a website abc.com using scrapy playwright the page it loads are of 3 different types of pages like page1->#selector1 page2->#selector2 page3->#selector3 and it changes...
Is there a way to handle dynamically loaded selectors with clicks on pages in scrapy-playwright?
I have a use case like this. Suppose if I crawl a website abc.com using scrapy playwright the page it loads are of 3 different types of pages like page1->#selector1 page2->#selector2 page3->#selector3 and it changes dynamically there is no guarantee which loads first. I want to click on the selector based on which i...
[ "Maybe you can check the selector is visible and then you can click it?\nif PageMethod(\"isVisible\",\"#selector1\"):\n PageMethod(\"click\",\"#selector1\") \nif PageMethod(\"isVisible\",\"#selector2\"):\n PageMethod(\"click\",\"#selector2\") \nif PageMethod(\"isVisible\",\"#selector3\"):\n PageMetho...
[ 0 ]
[]
[]
[ "playwright", "playwright_python", "python", "scrapy", "scrapyd" ]
stackoverflow_0074380158_playwright_playwright_python_python_scrapy_scrapyd.txt
Q: Correctly specify the types of unpacked `zip` I need to restructure some lists of tuples in python. I want to put the n-th value of each tuple in these lists into a separate tuple. The tuples in the lists are all similarly structured (e.g. position 1 is always an int) and I provided the respective type hints. Howe...
Correctly specify the types of unpacked `zip`
I need to restructure some lists of tuples in python. I want to put the n-th value of each tuple in these lists into a separate tuple. The tuples in the lists are all similarly structured (e.g. position 1 is always an int) and I provided the respective type hints. However, I unexpectedly receive an error message when I...
[ "I don't think the problem here is with Pylance or your code.\nzip accepts generic iterables\nThe problem is in the way that zip is designed/annotated. If we look at typeshed (always a great source for figuring out types of built-in functions), we can see that the the two-argument-overload looks something like this...
[ 0 ]
[]
[]
[ "pylance", "python", "python_typing", "type_hinting", "zip_operator" ]
stackoverflow_0074374059_pylance_python_python_typing_type_hinting_zip_operator.txt
Q: Python extend function not working - not sure why I have the following code where I want to add the string 'NSQscores' to the list of strings 'newlist'. However, the following code gives me a 'none'. columnlist = list(newdf.columns) newlist = columnlist[0:87] newlist2 = newlist.extend(['NSQscores']) print(newlist2...
Python extend function not working - not sure why
I have the following code where I want to add the string 'NSQscores' to the list of strings 'newlist'. However, the following code gives me a 'none'. columnlist = list(newdf.columns) newlist = columnlist[0:87] newlist2 = newlist.extend(['NSQscores']) print(newlist2) none Would be so grateful if anybody could give me ...
[ "x.extend modifies x in place and returns None. So you added an element to newlist and set newlist2 to None.\nTry newlist2 = newlist + ['NSQscores']. Or just use newlist instead of creating another one.\n", ".extend is a mutator, so it will modify newlist and not return anything.\nyou can just do newlist.extend([...
[ 1, 1 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074380418_dataframe_list_pandas_python.txt
Q: How to open url in incognito mode using requests (without selenium/playwright) I want to scrap following medium article: Link: article To get full content of the article It should be opened in incognito mode. So, when I use selenium/playwright with incognito mode for opening the url. It responds with full article....
How to open url in incognito mode using requests (without selenium/playwright)
I want to scrap following medium article: Link: article To get full content of the article It should be opened in incognito mode. So, when I use selenium/playwright with incognito mode for opening the url. It responds with full article. But with requests it responds only the half content. Is there any way to get incogn...
[ "To get full text of the article you have to make request to their GraphQL api:\nimport json\nimport requests\n\napi_url = \"https://duregger.medium.com/_/graphql\"\n\nquery = [\n {\n \"operationName\": \"PostViewerEdgeContentQuery\",\n \"query\": \"query PostViewerEdgeContentQuery($postId: ID!, $p...
[ 1 ]
[]
[]
[ "python", "python_3.x", "python_requests", "web_scraping" ]
stackoverflow_0074379397_python_python_3.x_python_requests_web_scraping.txt
Q: Python - Convert particular columns of data to integer I have a 2d array that is stored with NumPy. Is it possible to only convert the first and second columns to integers from float? This is my example of a 2d array. A: You can use asType() method import numpy as np arrayOfFloats = np.array( [ [1.2...
Python - Convert particular columns of data to integer
I have a 2d array that is stored with NumPy. Is it possible to only convert the first and second columns to integers from float? This is my example of a 2d array.
[ "You can use asType() method\nimport numpy as np\n\narrayOfFloats = np.array(\n [\n [1.2, 2.2, 3.2],\n [4.3, 5.4, 6.2]\n ]\n)\n\narrayOfFloats[0:1, 0:2] = arrayOfFloats[0:1, 0:2].astype(np.int64)\n\nprint(arrayOfFloats)\n\n" ]
[ 2 ]
[]
[]
[ "multidimensional_array", "numpy", "python" ]
stackoverflow_0074380334_multidimensional_array_numpy_python.txt
Q: Python JSON prints the same data twice (only in one case) A json prints the same data multiple times when called another time. It seems good on the first time but each next call makes it print only a part of JSON-contained string multiple times and only then the rest of it. Python code with open("src/pages/usergui...
Python JSON prints the same data twice (only in one case)
A json prints the same data multiple times when called another time. It seems good on the first time but each next call makes it print only a part of JSON-contained string multiple times and only then the rest of it. Python code with open("src/pages/userguide_sections.json", mode="rb") as f: userguide_sections = json.l...
[ "As it turnes out, the VS Code console is just unable to properly diplay anything that is too big for the console window. If you expand the terminal tab enough for the message to be displayed without vertical scroll tab appearing, you will gain consistent, good results. Also if you just use windows's cmd, you will ...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074374208_json_python.txt
Q: CS50P PSET3: Why is my code failing check50 for the grocery problem? The problem set I am trying to solve: CS50P 2022 psets/3/grocery/ The code I wrote: # Syntax of dict = {'key': value} mydict = {} # Infinite loop with break while True: try: item = input().upper() # Search if item matches a ...
CS50P PSET3: Why is my code failing check50 for the grocery problem?
The problem set I am trying to solve: CS50P 2022 psets/3/grocery/ The code I wrote: # Syntax of dict = {'key': value} mydict = {} # Infinite loop with break while True: try: item = input().upper() # Search if item matches a key inside the dict if item in mydict: mydict[item] = ...
[ "I do not find the exact problem of this code, but you can try to format your string before adding it to your dictionary. Python split method is really powerful for that. Maybe CS50 tries some weird combination to simulate a bad user.\nI would do something like that:\ns=input()\nt=s.split()\nret=\"\"\nn=len(t)\nfor...
[ 0, 0 ]
[]
[]
[ "cs50", "python" ]
stackoverflow_0074372158_cs50_python.txt
Q: Python like b-string concatenation in rust I am currently working on a side project where I am converting some code from python to rust. In python, we can do something like: Python code-> data = b'commit'+b' '+b'\x00' print(data) Output-> b'commit \x00' Is there any way to achieve this in rust? As I need to conc...
Python like b-string concatenation in rust
I am currently working on a side project where I am converting some code from python to rust. In python, we can do something like: Python code-> data = b'commit'+b' '+b'\x00' print(data) Output-> b'commit \x00' Is there any way to achieve this in rust? As I need to concatenate some b'' and store them in a file. Thank...
[ "You have a number of options for combining binary strings. However it sounds the best option for your use case is to use the write! macro. It lets you write bytes the same way you would use the format! and println! macros. This has the benefit of requiring no additional allocation. The write! macro uses UTF-8 enco...
[ 0 ]
[]
[]
[ "byte", "concatenation", "python", "rust" ]
stackoverflow_0074378958_byte_concatenation_python_rust.txt
Q: how to merge folders in python? How to remove part of a tree but keep the files and directories in python? I have paths like this: r"C:\User\Desktop\g1sr56g41f2d3s1gf\Document\A\file1.txt" r"C:\User\Desktop\g1sr56g41f2d3s1gf\Document\B\C\file2.txt" r"C:\User\Desktop\g1sr56g41f2d3s1gf\file3.txt" r"C:\User\Desktop\F...
how to merge folders in python?
How to remove part of a tree but keep the files and directories in python? I have paths like this: r"C:\User\Desktop\g1sr56g41f2d3s1gf\Document\A\file1.txt" r"C:\User\Desktop\g1sr56g41f2d3s1gf\Document\B\C\file2.txt" r"C:\User\Desktop\g1sr56g41f2d3s1gf\file3.txt" r"C:\User\Desktop\F2F31DS5FDSF1S2F3DS2F1D23\file4.txt" r...
[ "Here is my code:\n#!/usr/bin/python3\nimport os, shutil\n\nDST = 'Desktop'\n\ntoDel = []\nfor folder_name in os.listdir(DST):\n folder = os.path.join(DST, folder_name)\n if not os.path.isdir(folder):\n continue\n for path, _, files in os.walk(folder):\n relpath = os.path.join(DST, os.path.re...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074379577_python.txt
Q: Why doesn't `importlib.metadata.version` work on zip files? According to the documentation, importlib.metadata.version should work on dist-info folders in ZIP files. However, if you run pip install -t foo jedi-language-server (though you can use any package), zip -r foo.zip foo, PYTHONPATH=foo.zip/foo python -c "f...
Why doesn't `importlib.metadata.version` work on zip files?
According to the documentation, importlib.metadata.version should work on dist-info folders in ZIP files. However, if you run pip install -t foo jedi-language-server (though you can use any package), zip -r foo.zip foo, PYTHONPATH=foo.zip/foo python -c "from importlib.metadata import version; version('jedi-language-ser...
[ "Apparently, it only works if the metadata is in the top-level directory; that is, you have to do (cd foo; zip -r foo.zip .). It does not support nested directories.\n" ]
[ 0 ]
[]
[]
[ "python", "python_importlib" ]
stackoverflow_0074380541_python_python_importlib.txt
Q: Scraping website with selenium By css selector method gives errors I had a notebook for scraping Indiegogo website that was working perfectly, not I got errors as I see css selector method is now deprecated. I checked the website and nothing has changed, and I try to update my methods but still it does not work: i...
Scraping website with selenium By css selector method gives errors
I had a notebook for scraping Indiegogo website that was working perfectly, not I got errors as I see css selector method is now deprecated. I checked the website and nothing has changed, and I try to update my methods but still it does not work: import sys import logging from selenium.webdriver.remote.remote_connectio...
[ "I think you are missing this import:\nfrom selenium.webdriver.common.by import By\n\nBeside that, the locator looks not correct, with some small changes your code should be like this and it should do what you wanted:\nimport sys\nimport logging\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by imp...
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074380256_python_selenium.txt
Q: CS50 AI: Tic Tac Toe. Player X has 3 in a row, yet doesn't win, O picks next a 3rd one and wins I'm finishing AI50's tic tac toe, everything seems to be working, including the minimax algorithm but I came across a play (which almost always repeats itself), when the following steps occur as I am the X player: [2][2...
CS50 AI: Tic Tac Toe. Player X has 3 in a row, yet doesn't win, O picks next a 3rd one and wins
I'm finishing AI50's tic tac toe, everything seems to be working, including the minimax algorithm but I came across a play (which almost always repeats itself), when the following steps occur as I am the X player: [2][2] : X [0][0] : O [0][2] : X [2][0] : O At this point i place the final X between the previous two at ...
[ "The problem is in the winner function: it returns None when it finds a three-in-a-row of None values. This in itself may seem OK, but thereby it may miss a real three-in-a-row of X or O. This wrong assessment happens in the deeper state that arises from the board you described:\nO . X\n. . X\nO . X \n\nNow winner ...
[ 0 ]
[ "I believe your if conditions within the winner function need to be tweaked.\nThis is your current code.\ndef winner(board):\n \"\"\"\n Returns the winner of the game, if there is one.\n \"\"\" \n # Check horizontally and vertically\n for i in range(3):\n if board[i][0] == board[i][1] == b...
[ -2 ]
[ "cs50", "python", "tic_tac_toe" ]
stackoverflow_0074379382_cs50_python_tic_tac_toe.txt
Q: Return value of print statement in Python In one book I found thatprint(print("any text")) returns the size of text inside the function. i.e. 8 Here But in another book I found out that it returns None. So which answer is true? Or whether the 2nd answer is just an updated answer...? A: print() function doesn't r...
Return value of print statement in Python
In one book I found thatprint(print("any text")) returns the size of text inside the function. i.e. 8 Here But in another book I found out that it returns None. So which answer is true? Or whether the 2nd answer is just an updated answer...?
[ "print() function doesn't return anything (so it's None). When you're printing the output of a function which returns None, sure the output is None. So the 2nd book is correct.\n>>> print(print())\n\nNone\n\nIf you want get the length of a string, you should use len() function:\n>>> print(len(\"any text\"))\n8\n\n"...
[ 4, 1, 0 ]
[]
[]
[ "printing", "python", "return" ]
stackoverflow_0034836196_printing_python_return.txt
Q: convert python float to 32 bit object I'm trying to use python to investigate the effect of C++ truncating doubles to floats. In C++ I have relativistic energies and momenta which are cast to floats, and I'm trying to work out whether at these energies saving them as doubles would actually result in any improved p...
convert python float to 32 bit object
I'm trying to use python to investigate the effect of C++ truncating doubles to floats. In C++ I have relativistic energies and momenta which are cast to floats, and I'm trying to work out whether at these energies saving them as doubles would actually result in any improved precision in the difference between energy a...
[ "I'd suggest using Numpy as well. It exposes various data types including C style floats and doubles.\nOther useful tools are the C++17 style hex encoding and the decimal module for getting accurate decimal expansions.\nFor example:\nimport numpy as np\nfrom decimal import Decimal\n\nfor ftype in (np.float32, np.f...
[ 1 ]
[]
[]
[ "c++", "double", "floating_point", "python" ]
stackoverflow_0074376463_c++_double_floating_point_python.txt
Q: Extracting pmids from large xml file using iterparse I have a large xml file downloaded from pubmed central, I'm trying to extract all the PMID (around 3 million). I want to extract the elem.text (i.e., 34405992) for the corresponding element tag and attribute shown below, can someone advice on how to get all the ...
Extracting pmids from large xml file using iterparse
I have a large xml file downloaded from pubmed central, I'm trying to extract all the PMID (around 3 million). I want to extract the elem.text (i.e., 34405992) for the corresponding element tag and attribute shown below, can someone advice on how to get all the pmids using multiprocessing since there are 3 million reco...
[ "I was able to figure it out, though couldn't make use of multiprocessing.\ndata = []\n\nfor event, elem in ET.iterparse('my_file.xml'):\n if elem.tag == \"article-id\":\n contents = ET.tostring(elem)\n soup = BeautifulSoup(contents,'xml')\n input_tag = soup.find_all(attrs = {'pub-id-type':...
[ 0 ]
[]
[]
[ "iterparse", "python", "xml" ]
stackoverflow_0074306042_iterparse_python_xml.txt
Q: Using pandas to extract text between two words I am struggling to extract the text between two works. Specifically, I would like to extract the text between Example and Constraints. Here is a sample "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to t...
Using pandas to extract text between two words
I am struggling to extract the text between two works. Specifically, I would like to extract the text between Example and Constraints. Here is a sample "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nYou can return the answer in any order.\n Ex...
[ "Why don't you use python's native str.find method?\nsomething like s[s.find(\"Example\"):s.find(\"Constraints\")]\ncould work, perhaps with some trimming if you want to get rid of the word 'example' in the resultant string\nEDIT: Here's some sample code:\nexample = \"Given an array of integers nums and an integer ...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074380545_pandas_python.txt
Q: How to remove text from a string after a specific character? My program is like the command prompt (cmd) but much simpler. I am creating a command called, 'bd' which stands for back (one) directory. There is a path string: path = "C:/Program Files/node.js" and I want to remove the last directory '/node.js' but I d...
How to remove text from a string after a specific character?
My program is like the command prompt (cmd) but much simpler. I am creating a command called, 'bd' which stands for back (one) directory. There is a path string: path = "C:/Program Files/node.js" and I want to remove the last directory '/node.js' but I don't want to use indexing or slicing, because the path string will...
[ "the only way i can think of is to use path.split(/) and reassemble the string afterwards\nit would look something like this:\npath: str = \"C:/Program Files/node.js\"\nsplitup_path: list = path.split(\"/\")\nnew_path: str = \"\"\nfor i in range(path.count(\"/\")):\n new_path += f\"{splitup_path[i]}/\"\nprint(ne...
[ 1, 1 ]
[]
[]
[ "path", "python", "strip" ]
stackoverflow_0074380391_path_python_strip.txt
Q: Get content from class list I have 2 classes. AlchemicalStorage class is used to store the AlchemicalElement objects. class AlchemicalElement: def __init__(self, name: str): self.name = name def __repr__(self): return f'<AE: {self.name}>' class AlchemicalStorage: def __init__(self):...
Get content from class list
I have 2 classes. AlchemicalStorage class is used to store the AlchemicalElement objects. class AlchemicalElement: def __init__(self, name: str): self.name = name def __repr__(self): return f'<AE: {self.name}>' class AlchemicalStorage: def __init__(self): self.storage_list = [] ...
[ "it sounds kind of like you want printing out the AlchemicalStorage to have a specific format, so you could just create that format in a __str__ method:\nfrom collections import Counter\nclass AlchemicalStorage:\n def __str__(self):\n # a Counter will definitely be useful for what you are trying to do\n ...
[ 1 ]
[]
[]
[ "dictionary", "list", "oop", "python" ]
stackoverflow_0074380481_dictionary_list_oop_python.txt
Q: pass through variables from one file to another Im my program, In fileA i ask the user to enter there username and if they say yes itll save their username to a .env file if not i want it to only be saved until the program is either closed or stopped. Then the program in fileB runs a script. If theyve said yes to ...
pass through variables from one file to another
Im my program, In fileA i ask the user to enter there username and if they say yes itll save their username to a .env file if not i want it to only be saved until the program is either closed or stopped. Then the program in fileB runs a script. If theyve said yes to storing their password itll get it from the .env. if ...
[ "\nadd an extra field to the data you store in the file.\nuse the field to indicate whether the user wants it to be permanent\nalways store the info but periodically delete impermanent usernames.\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074380105_python.txt
Q: Reading and writing with multiple serial ports in PyQt5 I am developing a data monitor using PyQt5. I need to read from multiple sensors through serial ports. One or two of the sensors require different commands to send and then read the data, while the rest send data at a fixed speed. How can I monitor multiple p...
Reading and writing with multiple serial ports in PyQt5
I am developing a data monitor using PyQt5. I need to read from multiple sensors through serial ports. One or two of the sensors require different commands to send and then read the data, while the rest send data at a fixed speed. How can I monitor multiple ports without interrupting the UI? I don't know if I should us...
[ "Just as a real rough description:\nthreading maintains the same memory space as your main thread. This means that you can reference certain variables between threads.\nQthread is similar to normal threading, but it also includes the ability to restart the thread and can use slots/signals. If you're using PyQt5, I ...
[ 0 ]
[]
[]
[ "pyqt5", "pyserial", "python" ]
stackoverflow_0074364797_pyqt5_pyserial_python.txt
Q: Explode the contents of the cell in pandas dataframe into different rows I have a pandas dataframe in which multiple(3) column contains values corresponding to the next column. I want to split each row into multiple rows accordingly and create a new row per entry. For example, 'source' should become *source Time (...
Explode the contents of the cell in pandas dataframe into different rows
I have a pandas dataframe in which multiple(3) column contains values corresponding to the next column. I want to split each row into multiple rows accordingly and create a new row per entry. For example, 'source' should become *source Time (magazine) WarnerMedia WarnerMedia WarnerMedia U.S. Securities and Exchange Com...
[ "You can pass a list to pandas.DataFrame.explode:\nexploded = df.explode([\"source\", \"target\", \"type\"])\n\nTo explode multiple columns, each list within each cell must have an identical length to the lists in the other cells in the row.\n" ]
[ 2 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074380470_csv_dataframe_pandas_python.txt
Q: Partially coloring text of QTreeWidgetItem I am trying to get part of the text of a QTreeWidgetItem to be set to red and have found a few examples, namely how to set the background color of part of the text in qtreewidgetitem and is it possible to partially italicize the text of a qtreewidgetitem, but they are in ...
Partially coloring text of QTreeWidgetItem
I am trying to get part of the text of a QTreeWidgetItem to be set to red and have found a few examples, namely how to set the background color of part of the text in qtreewidgetitem and is it possible to partially italicize the text of a qtreewidgetitem, but they are in C++ so I'm not following them. I get that they'r...
[ "QLabel does not support ANSI color commands. You should use Qt's HTML subset (rich text) instead:\nmixedLabel.setText(\"I AM <span style='color: red'>CHILD</span>\")\n\nDocumentation for the capabilities of their HTML subset can be found here: https://doc.qt.io/qt-6/richtext-html-subset.html\n" ]
[ 0 ]
[]
[]
[ "pyqt5", "python", "qtreewidget", "qtreewidgetitem" ]
stackoverflow_0074380440_pyqt5_python_qtreewidget_qtreewidgetitem.txt
Q: getting results from a doubled nest JSON into a pandas df if there I am trying to get facebook data for a business I run, and put it into a pandas dataframe. Some posts have comments and others do not, and I am trying to get a dataframe from it. The JSON I have is this: {'data': [{'id': 'user_id_post_id1'}, {'id...
getting results from a doubled nest JSON into a pandas df if there
I am trying to get facebook data for a business I run, and put it into a pandas dataframe. Some posts have comments and others do not, and I am trying to get a dataframe from it. The JSON I have is this: {'data': [{'id': 'user_id_post_id1'}, {'id': 'user_id_post_id2'}, {'id': 'user_id_post_id3'}, {'comments': {'d...
[ "Try:\ndata = {\n \"data\": [\n {\"id\": \"user_id_post_id1\"},\n {\"id\": \"user_id_post_id2\"},\n {\"id\": \"user_id_post_id3\"},\n {\n \"comments\": {\n \"data\": [\n {\n \"created_time\": \"2022-11-09T00:15:29+000...
[ 1 ]
[]
[]
[ "dataframe", "json", "pandas", "python" ]
stackoverflow_0074380588_dataframe_json_pandas_python.txt
Q: Writing a .bat file to run a .py file in the Python interpreter In general, the problem is that I use Anaconda and, unlike IDLE, you can’t just associate .py files with the Python interpreter there, since many environments are used there and the necessary environment must be activated before running the .py file. ...
Writing a .bat file to run a .py file in the Python interpreter
In general, the problem is that I use Anaconda and, unlike IDLE, you can’t just associate .py files with the Python interpreter there, since many environments are used there and the necessary environment must be activated before running the .py file. You can't do without writing a .bat file. I've never done this and do...
[ "I found the Bat_To_Exe_Converter program, which converts .bat files to .exe. It also allows you to hide the command line when starting a .py file, set an icon for the resulting .exe file. The program allows you to associate .py files with the resulting .exe file, thereby allowing you to run .py files in the desire...
[ 0 ]
[]
[]
[ "anaconda", "batch_file", "cmd", "python", "windows" ]
stackoverflow_0074371867_anaconda_batch_file_cmd_python_windows.txt
Q: Programatically edit Helm templates? Let's say I have a large set of Helm charts, in which I want to edit every deployment.yaml file in the templates directory of each chart, which doing manually is a tedious task. I've tried to use Python's pyyaml and benedict to do something like this: content = read_file() # re...
Programatically edit Helm templates?
Let's say I have a large set of Helm charts, in which I want to edit every deployment.yaml file in the templates directory of each chart, which doing manually is a tedious task. I've tried to use Python's pyyaml and benedict to do something like this: content = read_file() # reads the deployment.yaml file deployment = ...
[ "Helm templates are just Go templates. The work on text. You can, theoretically, parse them into a syntax tree representing the Go template syntax, but that's not what you want.\nOnly after template processing will the input become a valid YAML structure. Therefore, you generally cannot make code comprehend the str...
[ 0, 0 ]
[]
[]
[ "kubernetes_helm", "python", "yaml" ]
stackoverflow_0074375075_kubernetes_helm_python_yaml.txt
Q: Python argparse, handle either several positional arguments OR optional argument I have the following code: parser = argparse.ArgumentParser(description='') parser.add_argument('-l', '--login', action='store_true') parser.add_argument('FILTER1') parser.add_argument('FILTER2') parser.add_argument('FILTER3') I'd l...
Python argparse, handle either several positional arguments OR optional argument
I have the following code: parser = argparse.ArgumentParser(description='') parser.add_argument('-l', '--login', action='store_true') parser.add_argument('FILTER1') parser.add_argument('FILTER2') parser.add_argument('FILTER3') I'd like "--login" to be mutually exclusive from FILTER1, FILTER2, FILTER3. Also, FILTER1, ...
[ "The most straightforward way to do this with argparse is to make the filters into an optional argument followed by nargs=3 in a mutually exclusive group with \"login\". Otherwise, you could do your own parsing and make each filter an optional positional.\nFilters as optional\nimport argparse\n\nparser = argparse.A...
[ 2, 0 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0074380157_argparse_python.txt
Q: Python 3.9 - Improper Installation, Cannot Import SSL I am attempting to install the Azure CLI on my Fedora 35 machine using this guide. When installing the RHEL 9 RPM using DNF (step 2 of that guide), Python 3.9 is installed along with Azure (Azure is dependent on 3.9). The installation of both applications appea...
Python 3.9 - Improper Installation, Cannot Import SSL
I am attempting to install the Azure CLI on my Fedora 35 machine using this guide. When installing the RHEL 9 RPM using DNF (step 2 of that guide), Python 3.9 is installed along with Azure (Azure is dependent on 3.9). The installation of both applications appears to succeed until I run az --version, at which point I ge...
[ "Try building with the argument of --with-ssl and make sure that openssl is downloaded.\n", "I managed to resolve this by uninstalling python3.9 and the Azure CLI, then using whereis to properly remove my broken source installation:\nsudo dnf remove azure-cli-2.42.0-1.el9.x86_64\nwhereis python3.9\nsudo rm -rf /...
[ 0, 0 ]
[]
[]
[ "azure", "fedora", "installation", "python", "python_3.x" ]
stackoverflow_0074294628_azure_fedora_installation_python_python_3.x.txt
Q: python and calculating the power of a number I was asked to calculate the cubed root of a number in python3 and used the following code: import numpy as np # numerical routines def myfunct(x): return np.power(x,3./2.) xStar = 4 print('Exact value at',xStar,' is in myfunc ',myfunct(xStar)) This is fi...
python and calculating the power of a number
I was asked to calculate the cubed root of a number in python3 and used the following code: import numpy as np # numerical routines def myfunct(x): return np.power(x,3./2.) xStar = 4 print('Exact value at',xStar,' is in myfunc ',myfunct(xStar)) This is fine, however by accident I found the following work...
[ "prehaps take a look at the documentation for both:\n\nbuilt in pow\n\n\nThe arguments must have numeric types. With mixed operand types, the\ncoercion rules for binary arithmetic operators apply.\n\n\nnp.power\n\n\nRaise each base in x1 to the positionally-corresponding power in x2.\nx1 and x2 must be broadcastabl...
[ 1 ]
[]
[]
[ "numpy", "python", "python_3.x" ]
stackoverflow_0074380766_numpy_python_python_3.x.txt
Q: Python: Convert bytes to json im having this byte class b'ToCountry=US&ToState=WA&SmsMessageSid=SM2c04173b9a5f684be8019e177978c791&NumMedia=0&ToCity=&FromZip=&SmsSid=SM2c04173b9a5f684be8019e177978c791&FromState=&SmsStatus=received&FromCity=&Body=Bbjhggggggg&FromCountry=EE&To=%2B15095121752&ToZip=&NumSegments=1&Ref...
Python: Convert bytes to json
im having this byte class b'ToCountry=US&ToState=WA&SmsMessageSid=SM2c04173b9a5f684be8019e177978c791&NumMedia=0&ToCity=&FromZip=&SmsSid=SM2c04173b9a5f684be8019e177978c791&FromState=&SmsStatus=received&FromCity=&Body=Bbjhggggggg&FromCountry=EE&To=%2B15095121752&ToZip=&NumSegments=1&ReferralNumMedia=0&MessageSid=SM2c0417...
[ "One line solution\na = b'ToCountry=US&ToState=WA&SmsMessageSid=SM2c04173b9a5f684be8019e177978c791&NumMedia=0&ToCity=&FromZip=&SmsSid=SM2c04173b9a5f684be8019e177978c791&FromState=&SmsStatus=received&FromCity=&Body=Bbjhggggggg&FromCountry=EE&To=%2B15095121752&ToZip=&NumSegments=1&ReferralNumMedia=0&MessageSid=SM2c04...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074375608_python.txt
Q: PyDrake ImportError: cannot import name 'DiscreteContactSolver' from 'pydrake.all' Trying to follow the Force Control examples from the Manipulation textbook however I'm running into this issue at the beginning: ImportError: cannot import name 'DiscreteContactSolver' from 'pydrake.all' I've checked my installati...
PyDrake ImportError: cannot import name 'DiscreteContactSolver' from 'pydrake.all'
Trying to follow the Force Control examples from the Manipulation textbook however I'm running into this issue at the beginning: ImportError: cannot import name 'DiscreteContactSolver' from 'pydrake.all' I've checked my installation and I'm at drake 1.9.0. The online pydrake documentation says that the DiscreteContac...
[ "Drake v1.9.0 does not contain python bindings for DiscreteContactSolver. The website API documentation current reflects the nightly build, not the stable release.\nThe pydrake bindings for DiscreteContactSolver were added in #18214 on October 30th. The pydrake release 1.9.0 was approximately three weeks prior, on...
[ 1 ]
[]
[]
[ "drake", "python" ]
stackoverflow_0074379319_drake_python.txt
Q: loop over two variables to create multiple year columns If I have table |a | b | c| |"hello"|"world"| 1| and the variables start =2000 end =2015 How do I in pyspark add 15 cols with 1st column m2000 and second m2001 etc and all these new cols have 0 so new dataframe is |a | b | c|m2000 | m2001...
loop over two variables to create multiple year columns
If I have table |a | b | c| |"hello"|"world"| 1| and the variables start =2000 end =2015 How do I in pyspark add 15 cols with 1st column m2000 and second m2001 etc and all these new cols have 0 so new dataframe is |a | b | c|m2000 | m2001 | m2002 | ... | m2015| |"hello"|"world"| 1| 0 | 0 | 0...
[ "You can simply use withColumn to add relevant columns.\nfrom pyspark.sql.functions import col,lit\n\ndf = spark.createDataFrame(data=[(\"hello\",\"world\",1)],schema=[\"a\",\"b\",\"c\"])\n\ndf.show()\n\n+-----+-----+---+\n| a| b| c|\n+-----+-----+---+\n|hello|world| 1|\n+-----+-----+---+\n\nfor i in range(...
[ 1, 1, 0, 0 ]
[]
[]
[ "apache_spark", "dataframe", "pyspark", "python" ]
stackoverflow_0074374409_apache_spark_dataframe_pyspark_python.txt
Q: Plot the deformed shape using python, how can i use paython to Plot the deformed shape using the nodal solutions (from part b) with the Hermite cubic interpolation functions in the same graph. when i have solution for b: Plot the deformed shape with the Hermite cubic interpolation functions in the same graph. pyt...
Plot the deformed shape using python,
how can i use paython to Plot the deformed shape using the nodal solutions (from part b) with the Hermite cubic interpolation functions in the same graph. when i have solution for b: Plot the deformed shape with the Hermite cubic interpolation functions in the same graph. python
[ "You can use scipy.interpolate.CubicHermiteSpline to interpolate values at any desired points between the fixed and free end of the beam.\nSo to plot your values you can interpolate over your desired positions and compute the corresponding deflections\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074380476_python.txt
Q: Initialize class more efficiently in Python I have this code in which I initialize a class (Adapter) by the name I get from the request. It seems to be a bit clumsy, and I'm sure there's a better/cleaner way of doing it. from adapters.gofirst_adapter import GoFirstAdapter from adapters.spicejet_adapter import Spic...
Initialize class more efficiently in Python
I have this code in which I initialize a class (Adapter) by the name I get from the request. It seems to be a bit clumsy, and I'm sure there's a better/cleaner way of doing it. from adapters.gofirst_adapter import GoFirstAdapter from adapters.spicejet_adapter import SpiceJetAdapter from adapters.airasia_adapter import ...
[ "You can use a dict to map the parameter to the specific class:\nfrom adapters.gofirst_adapter import GoFirstAdapter\nfrom adapters.spicejet_adapter import SpiceJetAdapter\nfrom adapters.airasia_adapter import AirAsiaAdapter\n\nclass Adapter():\n adapters = {'goFirst':GoFirstAdapter, 'spiceJet':SpiceJetAdapter, ...
[ 2, 1 ]
[]
[]
[ "python", "python_class" ]
stackoverflow_0074380821_python_python_class.txt
Q: Determining average values over irregular number of rows in a csv file I have a csv file with days of the year in one column and temperature in another. The days are split into sections and I want to find the average temperature over each day.Eg day 0,1,2,3 etc The measurements of temperatures has been taken irreg...
Determining average values over irregular number of rows in a csv file
I have a csv file with days of the year in one column and temperature in another. The days are split into sections and I want to find the average temperature over each day.Eg day 0,1,2,3 etc The measurements of temperatures has been taken irregularly meaning there are different numbers of measurements at certain times ...
[ "You could convert Days to an integer and use that to group.\n>>> df.groupby(df[\"Days\"].astype(int)).mean()\n Days Temp\nDays \n0 0.775 18.500000\n1 1.400 18.333333\n3 3.525 19.500000\n4 4.500 20.000000\n\n" ]
[ 1 ]
[]
[]
[ "average", "csv", "dataframe", "python" ]
stackoverflow_0074380732_average_csv_dataframe_python.txt
Q: How to replace ones with the values present in x? In place of 1 , x values should be filled according to the index. My code is : x = [0.5697071 0.47144773 0.45310486] z_prime= [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1]] flatten_matrix = [val for val in z_prime ] for val in flatten_matrix: for j in val: if(j!=0):...
How to replace ones with the values present in x?
In place of 1 , x values should be filled according to the index. My code is : x = [0.5697071 0.47144773 0.45310486] z_prime= [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1]] flatten_matrix = [val for val in z_prime ] for val in flatten_matrix: for j in val: if(j!=0): z= x else: z = 0 print(z) This gives the output as: 0 ...
[ "Try this:\nflatten_matrix = [[x[idx] if elm[idx] == 1 else 0 for idx in range(len(elm))] for elm in z_prime]\n\nAs a sidenote: I'd recommend breaking this up into a standalone function, because if you ever come back to this list comprehension it'll be incomprehensible.\nConsider something like this (which may be s...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074380830_python.txt
Q: Weird error when trying to optimize my game in pygame So I'm making a game in PyGame and I made a system that spawns a bunch of trees and rocks. These are objects that call an update() function where some necessary calculations for their position are made and they get blited to the screen. I'm trying to make a pro...
Weird error when trying to optimize my game in pygame
So I'm making a game in PyGame and I made a system that spawns a bunch of trees and rocks. These are objects that call an update() function where some necessary calculations for their position are made and they get blited to the screen. I'm trying to make a program that only really updates a foliage object when its vis...
[ "The main issue is that your code is using time.time() which has a granularity of decimal seconds. It is multiplied by 300, but this looks like a fudge to speed it up??\nIt's better to use the PyGame function pygame.time.get_ticks() for all in-game times. This function returns the number of milliseconds since you...
[ 0 ]
[]
[]
[ "optimization", "performance", "pygame", "python" ]
stackoverflow_0074380404_optimization_performance_pygame_python.txt
Q: Python Tkinter count-down GUI crashing when i start the Count-Down with a button. (app not answering) I am making a count-down GUI with Tkinter in Python 3.10 and I'm making a slider that sets the minutes, 2 labels that display the minutes and seconds and a button to start the timer. The problem is that it crashes...
Python Tkinter count-down GUI crashing when i start the Count-Down with a button. (app not answering)
I am making a count-down GUI with Tkinter in Python 3.10 and I'm making a slider that sets the minutes, 2 labels that display the minutes and seconds and a button to start the timer. The problem is that it crashes when I click the start timer button, The strange thing is that it doesn't give me any error messages it ju...
[ "As JRiggles mentioned sleep and tkinter do not go well. This is because sleep() blocks the main loop of tkinter.\nThe most common way to solve this issue is to use after() to manage these kind of loops.\nHere is a paired down version of your code that uses a combination of after() and a refactored function.\nimpor...
[ 1 ]
[]
[]
[ "crash", "python", "python_3.x", "timer", "tkinter" ]
stackoverflow_0074380568_crash_python_python_3.x_timer_tkinter.txt
Q: What is the purpose of the "~" symbol in Python and how would it alter .isnull()? this will be my first query as I'm pretty new to understanding Python and its intricacies, especially all the symbols. In my attempt to understand the ~ (grave?) symbol I know it's related to binary output. However, I ran into this p...
What is the purpose of the "~" symbol in Python and how would it alter .isnull()?
this will be my first query as I'm pretty new to understanding Python and its intricacies, especially all the symbols. In my attempt to understand the ~ (grave?) symbol I know it's related to binary output. However, I ran into this predicament in a Data Camp practice session. So here's my question: What is the "~" symb...
[ "~x is implemented using the __invert__ method. For example, int.__invert__ swaps 0s for 1s and vice versa in the twos'-complement binary representation of an integer.\n>>> ~8\n-9\n>>> ~-9\n8\n\nOther types can define __invert__ to mean something different. Many libraries use ~, &, and | as operators equivalent to ...
[ 1 ]
[]
[]
[ "isnull", "python", "symbols" ]
stackoverflow_0074380969_isnull_python_symbols.txt
Q: Iterate through dataframe, capturing substring and creating new column I have a dataframe that contains multiple columns. The one relevant for this problem is the group_email. From this group email I need to parse out a specific substring from it to get a group_code. I have created two different regex patterns to ...
Iterate through dataframe, capturing substring and creating new column
I have a dataframe that contains multiple columns. The one relevant for this problem is the group_email. From this group email I need to parse out a specific substring from it to get a group_code. I have created two different regex patterns to capture the substring based on the starting. If the email starts with "gcp" ...
[ "You could use np.select() to put all your conditions into one line.\ncondlist = [group_member_df['group_email'].astype(str).str.startswith('gcp'), group_member_df['group_email'].astype(str).str.startswith('irm')]\n\nchoicelist = [group_member_df['group_email'].str.extract('(?:prod-)(.*)-'), group_member_df['group_...
[ 0 ]
[]
[]
[ "dataframe", "iterator", "loops", "pandas", "python" ]
stackoverflow_0074380577_dataframe_iterator_loops_pandas_python.txt
Q: Divide chocolate bar with if/elif/else I've been having problem with this simple question. was able to solve it with for loop, but not only if/elif/else. Any suggestion on how to tackle this? Question: Chocolate bar has the form of a rectangle divided into n×m portions. Chocolate bar can be split into two rect...
Divide chocolate bar with if/elif/else
I've been having problem with this simple question. was able to solve it with for loop, but not only if/elif/else. Any suggestion on how to tackle this? Question: Chocolate bar has the form of a rectangle divided into n×m portions. Chocolate bar can be split into two rectangular parts by breaking it along a selec...
[ "So the question is basically asking:\n\nFor a given n, m and k, does there exist two numbers, a and b, such that a * b = k, where either a = n and b < m or a = m and b < n.\n\nYou can solve that with this condition:\nn = int(input())\nm = int(input())\nk = int(input())\n\nif (k % n == 0 and k / n < m) or (k % m ==...
[ 6, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0044572283_if_statement_python.txt
Q: Escape all characters in a string MarkdownV2 (python) I happen to have trouble with a name "x" that has some special characters in it, now, this name shall be sent in a text with more stuff which uses MarkdownV2, however, this name "x" isn't avaiable for me, I dont know it, and I can't manually change it. Then, ho...
Escape all characters in a string MarkdownV2 (python)
I happen to have trouble with a name "x" that has some special characters in it, now, this name shall be sent in a text with more stuff which uses MarkdownV2, however, this name "x" isn't avaiable for me, I dont know it, and I can't manually change it. Then, how can I escape all special characters in a string? """NAME:...
[ "to escape every character you put an r in front of the str to escape one character use a backslash\n" ]
[ 0 ]
[]
[]
[ "markdown", "python" ]
stackoverflow_0074381077_markdown_python.txt
Q: Replace character to "@" in string Why python does not replace last character for @? str_manip = input("Enter a sentence ") last_char = str_manip[-1] print(last_char) change_char = str_manip.replace("last_char", "@") print(change_char) It comes up as exactly the same sentence as I enter, unchanged. I have read a ...
Replace character to "@" in string
Why python does not replace last character for @? str_manip = input("Enter a sentence ") last_char = str_manip[-1] print(last_char) change_char = str_manip.replace("last_char", "@") print(change_char) It comes up as exactly the same sentence as I enter, unchanged. I have read a few websites and still do not understand...
[ "Try this\nstr_manip = input(\"Enter a sentence \")\nlast_char = str_manip[-1]\nprint(last_char)\nchange_char = str_manip.replace(last_char, \"@\")\nprint(change_char)\n\n", "Replace\nchange_char = str_manip.replace(\"last_char\", \"@\")\n\nby\nchange_char = str_manip.replace(last_char, \"@\")\n\n" ]
[ 2, 1 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0074381035_python_replace.txt
Q: Can not import a module when run the flask server using the flask run command I'm new to flask framework and I want to write a simple flask app that uses another python module (librosa package). I have successfully installed librosa in the same virtual environment that I have installed flask and I can easily impor...
Can not import a module when run the flask server using the flask run command
I'm new to flask framework and I want to write a simple flask app that uses another python module (librosa package). I have successfully installed librosa in the same virtual environment that I have installed flask and I can easily import it in the python interpreter. Here is the python script. # app.py from flask impo...
[ "if you are using an IDE such as pycharm, then you may need to install it from the terminal in the IDE itself, not cmd\n", "This may be the solution to your problem:\npython -m flask run\n\nThe reason is that flask run may use the python executable somewhere else, not the virtual environment you created for the p...
[ 1, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0064910508_flask_python.txt
Q: Problem scraping title, price and date from a site using selenium Hi guuys Im trying to scrape some information about a shoe of zalando and save the price, the title, the day and the hour in differents variables using Seleinum webdriver.This is my code: from selenium import webdriver from selenium.webdriver.common...
Problem scraping title, price and date from a site using selenium
Hi guuys Im trying to scrape some information about a shoe of zalando and save the price, the title, the day and the hour in differents variables using Seleinum webdriver.This is my code: from selenium import webdriver from selenium.webdriver.common.by import By import csv DRIVER_PATH = 'C:\chromedriver.exe' driver = ...
[ "One idea is to take a look at the variable, element_text, for many different products, and decide a different way to split the text - the split method can take in a smaller string to split the longer string by.\nIf that doesnt work, you can also iterate through the element_text_split variable (which is just a list...
[ 1, 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0074379742_python_selenium_selenium_chromedriver_web_scraping.txt
Q: How to best check if Enum type is IntEnum or IntFlag My project has many Enums that follow a certain Naming convention. I have a general method that converts a string into an Enum value. I want to convert Enum Attribute Names to Enums ( I got this handled ). Also I want to convert an int value passed in a string t...
How to best check if Enum type is IntEnum or IntFlag
My project has many Enums that follow a certain Naming convention. I have a general method that converts a string into an Enum value. I want to convert Enum Attribute Names to Enums ( I got this handled ). Also I want to convert an int value passed in a string to an Enum if the enum inherits from IntEnum or IntFlag. My...
[ "I think you just want:\nif issubclass(ec, (enum.IntEnum, enum.IntFlag)):\n # handle IntEnum or IntFlag case\n\n", "I don't understand the entirety of your use-case, but here are some built-in enum capabilities:\nfrom enum import IntEnum\n\nclass LayoutKind(IntEnum):\n TITLE_SUB = 0\n TITLE_BULLETS = 1\n...
[ 2, 0 ]
[]
[]
[ "enums", "python", "python_3.x" ]
stackoverflow_0074380303_enums_python_python_3.x.txt
Q: Mypy error while calling functions dynamically Trying to type check this code (which works perfectly fine): x = list(range(10)) for func in min, max, len: print(func(x)) results in the following error: main.py:3: error: Cannot call function of unknown type How should this be handled? A: You can try defini...
Mypy error while calling functions dynamically
Trying to type check this code (which works perfectly fine): x = list(range(10)) for func in min, max, len: print(func(x)) results in the following error: main.py:3: error: Cannot call function of unknown type How should this be handled?
[ "You can try defining your sequence of functions before the loop. This runs fine with mypy:\nfrom typing import Callable, Sequence\n\nx = list(range(10))\nfuncs: Sequence[Callable] = min, max, len\nfor func in funcs:\n print(func(x))\n\n", "If you know your argument to each of those functions will be of type l...
[ 1, 1 ]
[]
[]
[ "mypy", "python", "python_typing" ]
stackoverflow_0074376797_mypy_python_python_typing.txt
Q: Stacking column indices on top of one another using Pandas I'm looking to stack the indices of some columns on top of one another, this is what I currently have: Buy Buy Currency Sell Sell Currency Date 2013-12-31 100 CAD 1...
Stacking column indices on top of one another using Pandas
I'm looking to stack the indices of some columns on top of one another, this is what I currently have: Buy Buy Currency Sell Sell Currency Date 2013-12-31 100 CAD 100 USD 2014-01-02 200 USD 200 CAD 2014...
[ "using concat\nimport pandas as pd\n\n\nprint(pd.concat(\n [df['Buy'], df['sell']], axis=1\n).stack().reset_index(1, drop=True).rename(index='buy/sell')\n)\n\noutput:\n0 100\n0 100\n1 200\n1 200\n2 300\n2 300\n3 400\n3 400\n\n", "# assuming that your data has date as index.\ndf.set_inde...
[ 0, 0, 0 ]
[]
[]
[ "indices", "pandas", "python", "stack" ]
stackoverflow_0074379162_indices_pandas_python_stack.txt
Q: Django How to get sum of column after doing subtraction on each row? For example, I have an item where the "soldprice" price was 10, the "paid" was 2 and the "shipcost" was 2. I am currently doing as follows: @property def profit(self): if self.soldprice is not None and self.paid is not None and self.s...
Django How to get sum of column after doing subtraction on each row?
For example, I have an item where the "soldprice" price was 10, the "paid" was 2 and the "shipcost" was 2. I am currently doing as follows: @property def profit(self): if self.soldprice is not None and self.paid is not None and self.shipcost is not None: return self.soldprice - self.paid - self....
[ "Because profit is not stored in the database, you can't aggragate it in your ORM query.\nYou can, however, quite easily loop through it in your view and add it to context for your template, assuming inventory is a recordset:\nrunning_total = 0\nfor i in inventory:\n running_total += i.profit\n\ncontext['total_p...
[ 3 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0074380555_django_postgresql_python.txt
Q: Extracting lists from tuple with a condition I've been trying to extracting from this tuples E=tuple([random.randint(0,10) for x in range(10)]) Let's say the result is (3,4,5,0,0,3,4,2,2,4) . I want to extract from this tuple lists of numbers is ascending order without sorting the tuple or anything. Example : [[3...
Extracting lists from tuple with a condition
I've been trying to extracting from this tuples E=tuple([random.randint(0,10) for x in range(10)]) Let's say the result is (3,4,5,0,0,3,4,2,2,4) . I want to extract from this tuple lists of numbers is ascending order without sorting the tuple or anything. Example : [[3,4,5],[0,0,3,4],[2,2,4]]
[ "You can create a custom function (generator in my example) to group ascending elements:\ndef get_ascending(itr):\n lst = []\n for v in itr:\n if not lst:\n lst = [v]\n elif v < lst[-1]:\n yield lst\n lst = [v]\n else:\n lst.append(v)\n yield...
[ 1 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074381003_list_python_tuples.txt
Q: Python Requests Get State Trying to use the requests package to login to https://apps.kbnfinans.kommunalbanken.no/access/ When accessing this page I need to get the "state" and "auth0Client". Look at the picture below. When opening the webpage above - javascript opens different pages. How do I grab this GET reques...
Python Requests Get State
Trying to use the requests package to login to https://apps.kbnfinans.kommunalbanken.no/access/ When accessing this page I need to get the "state" and "auth0Client". Look at the picture below. When opening the webpage above - javascript opens different pages. How do I grab this GET request with Python Requests? This au...
[ "You should use something like Selenium with headless chrome browser to emulate users behaviour and render javascript if site doesn't provide an API to do that.\nIn case parameters are known just append it as headers or as a query string\n" ]
[ 0 ]
[]
[]
[ "auth0", "authentication", "python", "python_requests" ]
stackoverflow_0074381231_auth0_authentication_python_python_requests.txt
Q: Nested list with python basic Given the names and grades for each student in a class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each ...
Nested list with python basic
Given the names and grades for each student in a class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line. Example reords...
[ "The algorithm is:\n\nAdd all students with their marks to list reords\nSort list with unique marks (using set)\nFilter list to get a student with the second min mark\nPrint name for each filtered student\n\nTested here:\nif __name__ == '__main__':\n reords = []\n \n for _ in range(int(input())):\n ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0067162145_python.txt
Q: Can't calculate the total cost in my restaurant menu program So I am making a restaurant menu in Python, I got everything to work besides the program keeping track of the total cost. I've tried a few different things but no luck so far. It's probably something super simple but I can't figure it out. P.S. I'm a Pyt...
Can't calculate the total cost in my restaurant menu program
So I am making a restaurant menu in Python, I got everything to work besides the program keeping track of the total cost. I've tried a few different things but no luck so far. It's probably something super simple but I can't figure it out. P.S. I'm a Python beginner so I'm still trying to get used to and learn this lan...
[ "Only a litle mistake: the variable totalPrice must be initialized outside of the loop.\nSee the code below:\nprint(\"1. Cheeseburger: $3.50\")\nprint(\"2. Gyro: $6.00\")\nprint(\"3. Chicken Sandwich: $2.50\")\nprint(\"4. Burrito: $7.00\")\nprint(\"5. Fries: $1.50\")\nprint(\"6. Exit\")\n\ntotalPrice = 0 # <--- he...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074381049_python.txt
Q: Why isn't it possible to use backslashes in f-strings? In Python >=3.6, f-strings can be used as a replacement for the str.format method. As a simple example, these are equivalent: '{} {}'.format(2+2, "hey") f'{2+2} {"hey"}' Disregarding format specifiers, I can basically move the positional arguments of str.form...
Why isn't it possible to use backslashes in f-strings?
In Python >=3.6, f-strings can be used as a replacement for the str.format method. As a simple example, these are equivalent: '{} {}'.format(2+2, "hey") f'{2+2} {"hey"}' Disregarding format specifiers, I can basically move the positional arguments of str.format inside braces in an f-string. Note specifically that I am...
[ "You seem to expect\n'{}'.format(\"new\\nline\")\n\nand\nf'{\"new\\nline\"}'\n\nto be equivalent. That's not what I would expect, and it's not how backslashes in f-strings worked back in the pre-release versions of Python 3.6 where backslashes between the braces were allowed. Back then, you'd get an error because\n...
[ 13, 9, 4, 0 ]
[]
[]
[ "backslash", "f_string", "python", "python_3.x", "string_formatting" ]
stackoverflow_0051775950_backslash_f_string_python_python_3.x_string_formatting.txt
Q: How to get the return value of a function passed to multiprocessing.Process? In the example code below, I'd like to get the return value of the function worker. How can I go about doing this? Where is this value stored? Example Code: import multiprocessing def worker(procnum): '''worker function''' prin...
How to get the return value of a function passed to multiprocessing.Process?
In the example code below, I'd like to get the return value of the function worker. How can I go about doing this? Where is this value stored? Example Code: import multiprocessing def worker(procnum): '''worker function''' print str(procnum) + ' represent!' return procnum if __name__ == '__main__': ...
[ "Use shared variable to communicate. For example like this:\nimport multiprocessing\n\n\ndef worker(procnum, return_dict):\n \"\"\"worker function\"\"\"\n print(str(procnum) + \" represent!\")\n return_dict[procnum] = procnum\n\n\nif __name__ == \"__main__\":\n manager = multiprocessing.Manager()\n r...
[ 320, 85, 59, 44, 39, 17, 16, 11, 11, 2, 2, 0, 0 ]
[]
[]
[ "multiprocessing", "python", "python_multiprocessing", "return_value" ]
stackoverflow_0010415028_multiprocessing_python_python_multiprocessing_return_value.txt
Q: Page not found at /polls I am a total beginner in "django" so I'm following some tutorials currently I' am watching https://youtu.be/JT80XhYJdBw Clever Programmer's tutorial which he follows django tutorial Everything was cool until making a polls url Code of views.py: from django.shortcuts import render from dja...
Page not found at /polls
I am a total beginner in "django" so I'm following some tutorials currently I' am watching https://youtu.be/JT80XhYJdBw Clever Programmer's tutorial which he follows django tutorial Everything was cool until making a polls url Code of views.py: from django.shortcuts import render from django.http import HttpResponse ...
[ "Page not found (404)\nRequest Method: GET\nRequest URL: http://127.0.0.1:8000/polls/\nUsing the URLconf defined in Mypr.urls, Django tried these URL patterns, in this order:\n\nadmin/\nThe current path, polls/, didn't match any of these.\n\nYou're seeing this error because you have DEBUG = True in your Django s...
[ 0, 0, 0 ]
[]
[]
[ "django", "error_handling", "pycharm", "python" ]
stackoverflow_0065124975_django_error_handling_pycharm_python.txt
Q: python bytes array display is different to element value I have a bytes array returned from a hardware module, the len is: len(a) 51 when I display it in vscode or terminal, it shows: b'>128 143 134 135 141 139 134 120 137 135 132 143 \r\n' when I try to convert it to list: s = list(a.strip()) s[0] 62 s[1]...
python bytes array display is different to element value
I have a bytes array returned from a hardware module, the len is: len(a) 51 when I display it in vscode or terminal, it shows: b'>128 143 134 135 141 139 134 120 137 135 132 143 \r\n' when I try to convert it to list: s = list(a.strip()) s[0] 62 s[1] 49 s[2] 50 s[3] 56 how could I convert list s to 12 integers...
[ "That's a bytes string. You could use strip to get rid of the \\r\\n on the end, then slice 1: to get rid of the > at the front. Then, split on spaces to get a list of strings and convert those to integers.\ntest = b'>128 143 134 135 141 139 134 120 137 135 132 143 \\r\\n'\nl = [int(val) for val in a.strip()[1:].s...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074380658_python.txt
Q: Pytest --doctest-modules executes scripts I have this MRE: . └── tests └── notest.py The notest.py just do a sys.exit(1): When I run pytest --doctest-modules I get this error: ERROR collecting tests/notest.py tests/notest.py:4: in <module> sys.exit(1) E SystemExit: 1 So the --doctest-modules would try ...
Pytest --doctest-modules executes scripts
I have this MRE: . └── tests └── notest.py The notest.py just do a sys.exit(1): When I run pytest --doctest-modules I get this error: ERROR collecting tests/notest.py tests/notest.py:4: in <module> sys.exit(1) E SystemExit: 1 So the --doctest-modules would try to execute my script which is not a test. Is th...
[ "\nIs that normal behaviour?\n\nYes. Passing --doctest-modules will activate a special doctest collector that is not restricted to globs specified by python_files (test_*.py and *_test.py by default). Instead, it will find and collect any python module that is not __init__.py or __main__.py. Afterwards, doctest wil...
[ 1 ]
[]
[]
[ "pytest", "python", "testing" ]
stackoverflow_0074360037_pytest_python_testing.txt
Q: Plotting circles around points in animation plot I'm plotting some points moving in a 2D space and I want to add circles around them. I have all the x,y coordinates for the points around which the circles are supposed to be plotted, but I am unsure how to add this into the animate function. Any help would be appre...
Plotting circles around points in animation plot
I'm plotting some points moving in a 2D space and I want to add circles around them. I have all the x,y coordinates for the points around which the circles are supposed to be plotted, but I am unsure how to add this into the animate function. Any help would be appreciated! import matplotlib.pyplot as plt from launcher ...
[ "Instead of plt.circle (which seems to me is not supported in Matplotlib v3.5.1), please use matplotlib.patches.Circle to draw circles.\nplt.subplots draws a figure and returns an array of Axes objects. By default, the function call returns one Axes object, which is referred here as ax.\nAt the beginning of every f...
[ 0 ]
[]
[]
[ "animation", "matplotlib", "python" ]
stackoverflow_0074337370_animation_matplotlib_python.txt
Q: Duck Typing in Python (in order to mimic a String) Duck Typing in general is explained here: https://stackoverflow.com/a/4205163/19446851. What does Duck Typing mean in Python? Is it really possible to make one type look like another type. Can I have an own class that "looks and quacks" like a string? See the foll...
Duck Typing in Python (in order to mimic a String)
Duck Typing in general is explained here: https://stackoverflow.com/a/4205163/19446851. What does Duck Typing mean in Python? Is it really possible to make one type look like another type. Can I have an own class that "looks and quacks" like a string? See the following example: from dataclasses import dataclass @datac...
[ "\nIs it really possible to make one type look like another type?\n\nThis is quite typical of people who come from a statically typed language to interpret duck typing but it misses a significant aspect of the whole deal: it isn't that you are faking another type it is that your code relies on behaviour instead of ...
[ 0 ]
[]
[]
[ "duck_typing", "elementtree", "python", "string" ]
stackoverflow_0072926900_duck_typing_elementtree_python_string.txt
Q: Avoid DataFrame.resample to change the hour I am trying to extract the minimum value for each day in a dataset containing hourly prices. This I want to do for every hour separately since I later want to add other information to each hour, before combining the dataset again (which is why I want to keep the hour in ...
Avoid DataFrame.resample to change the hour
I am trying to extract the minimum value for each day in a dataset containing hourly prices. This I want to do for every hour separately since I later want to add other information to each hour, before combining the dataset again (which is why I want to keep the hour in datetime). This is my data: ...
[ "I did not find a nice solution to this problem, I managed to get where I want though with this method:\nt = datetime.timedelta(hours=1)\n\ndf_min = df_min.reset_index()\n\ndf_min['date'] = df_min['date'] + t\n\ndf_min.set_index('date', inplace = True)\n\ndf_hour_1 = pd.concat([df_hour_1, df_min], axis=1)\n\nThat i...
[ 0 ]
[]
[]
[ "pandas_resample", "python" ]
stackoverflow_0074377674_pandas_resample_python.txt
Q: Loop through each pixel of a raster stack and return a time series of pixels using Python I'm new to Python language and I'm trying to loop through a rasterstack and store pixels in a time-series manner. For example, suppose I have three rasters of three dates, for 2020, 2021, 2022: A = array([[[0.2, 0.3, 0.4, 0....
Loop through each pixel of a raster stack and return a time series of pixels using Python
I'm new to Python language and I'm trying to loop through a rasterstack and store pixels in a time-series manner. For example, suppose I have three rasters of three dates, for 2020, 2021, 2022: A = array([[[0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]], [[1.0, 1.1, 1.2, 1.3, 1.4, 1.5...
[ "You can transpose the original array with the code below, I resize after the transpose to get rid of the extra dimension but depending on your actual data you might not need/want it.\narr = np.array([\n [[0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]],\n [[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7]],\n [[1.8, 1.9,...
[ 0 ]
[]
[]
[ "numpy", "python", "raster", "rasterio" ]
stackoverflow_0074369591_numpy_python_raster_rasterio.txt
Q: How to avoid memory errors when creating large numpy arrays? I would like to create a 4D array meant to store a 3D vector field like U = np.array((3,N,N,N), dtype = float) where N = 2^n with n = 0,1,2,3,4,... To do this I tried U = np.array(np.meshgrid(Ux, Uy, Uz, indexing='ij'), dtype=float) where Ux, Uy, Uz ar...
How to avoid memory errors when creating large numpy arrays?
I would like to create a 4D array meant to store a 3D vector field like U = np.array((3,N,N,N), dtype = float) where N = 2^n with n = 0,1,2,3,4,... To do this I tried U = np.array(np.meshgrid(Ux, Uy, Uz, indexing='ij'), dtype=float) where Ux, Uy, Uz are the three components of a vector generated using list comprehens...
[ "With N=4:\nIn [131]: N=4; Ux = np.arange(N**3) \nIn [132]: Ux.shape\nOut[132]: (64,)\n\nThe 2nd way of combining 3 arrays of this shape:\nIn [133]: np.array((Ux,Ux,Ux)).shape\nOut[133]: (3, 64) \nIn [134]: np.array((Ux,Ux,Ux)).reshape(3,N,N,N).shape\nOut[134]: (3, 4, 4, 4)\n\nThe meshgrid shape is much bigge...
[ 0 ]
[]
[]
[ "arrays", "memory", "numpy", "python" ]
stackoverflow_0074377821_arrays_memory_numpy_python.txt
Q: Can I Access Specific Memory Addresses Manually Via Python I am working on a project where I am interfacing(?) with another program. This other program has no way for me to interface with it, so, I need to pull values out of memory. I have already found the addresses where these values are stored relative to the M...
Can I Access Specific Memory Addresses Manually Via Python
I am working on a project where I am interfacing(?) with another program. This other program has no way for me to interface with it, so, I need to pull values out of memory. I have already found the addresses where these values are stored relative to the MZ Start address listed in the programs PE header. I simply need ...
[ "Yes, this is possible. But, I will warn you that reading and writing to specific memory addresses is the wrong tool to solve this problem. The right tool is probably ctypes or SWIG. In particular, that would save you from needing to figure out what the right offsets are.\nI figure you're going to ignore that advic...
[ 1, 0 ]
[]
[]
[ "memory", "memory_address", "python", "ram" ]
stackoverflow_0074381153_memory_memory_address_python_ram.txt
Q: Selenium / Python - Fill in the login in a pop-up window I want to fill in the login of this page with selenium: https://influence.co/go/location-search/top-nl-influencers/city/amsterdam. But it is not sending the keys. Send_keys try: email = driver.find_element(By.CSS_SELECTOR, "#user_email") self.asser...
Selenium / Python - Fill in the login in a pop-up window
I want to fill in the login of this page with selenium: https://influence.co/go/location-search/top-nl-influencers/city/amsterdam. But it is not sending the keys. Send_keys try: email = driver.find_element(By.CSS_SELECTOR, "#user_email") self.assertTrue(email.is_enabled) driver.execute_script("arguments[...
[ "There is more than one match for that locator. Email field is the second one, so you have to mention like this:\ndriver.find_element(By.XPATH, \"(.//*[@id='user_email'])[2]\").send_keys(\"email@gmail.com\")\n\n", "I count four elements with id of user_email on the page. One approach is to wait until the modal d...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074327634_beautifulsoup_python_selenium_selenium_webdriver_web_scraping.txt
Q: Possible approaches for iteration over multiple lists using python dataframe or any library I want to write a Python program which iterates multiple lists and gets all the possible combinations of each element. I will illustrate the idea in greater detail below. I have three lists as following: list_01=['A','B','C...
Possible approaches for iteration over multiple lists using python dataframe or any library
I want to write a Python program which iterates multiple lists and gets all the possible combinations of each element. I will illustrate the idea in greater detail below. I have three lists as following: list_01=['A','B','C','D'] list_02=[2, 2.5, 3, 3.5] list_03=['2003','2004','2005','2006','2007','2008'] And I would ...
[ "3 nested loops\nYou can use the code below:\nlist_01=['A','B','C','D']\nlist_02=[2, 2.5, 3, 3.5]\nlist_03=['2003','2004','2005','2006','2007','2008']\n\nfor k in list_01:\n for j in list_02:\n for i in list_03:\n print(k+','+str(j) + ',' + i)\n\nIn the code the instruction: print(k+','+str(j) ...
[ 0, 0 ]
[]
[]
[ "iteration", "list", "python" ]
stackoverflow_0074381295_iteration_list_python.txt
Q: python a faster method of finding indexes in a list of 2million+ data that match string condition ##Mock Data## my_list = list(range(1700)) import itertools cross_product = list(itertools.product(my_list,my_list)) station_combinations = ["_".join([str(i),str(b)]) for i,b in cross_product if i != b] #############...
python a faster method of finding indexes in a list of 2million+ data that match string condition
##Mock Data## my_list = list(range(1700)) import itertools cross_product = list(itertools.product(my_list,my_list)) station_combinations = ["_".join([str(i),str(b)]) for i,b in cross_product if i != b] ############### from time import time,sleep station_name = "5" start = time() for h in range(10): reverse_ind...
[ "One solution can be using indexes, in this case two indexes for a and b. For example:\nmy_list = list(range(1700))\n\nimport itertools\n\ncross_product = list(itertools.product(my_list, my_list))\nstation_combinations = [\n \"_\".join([str(i), str(b)]) for i, b in cross_product if i != b\n]\n\n# precompute inde...
[ 1 ]
[]
[]
[ "list_comprehension", "numba", "python", "string" ]
stackoverflow_0074381265_list_comprehension_numba_python_string.txt
Q: Download PDF from link that auto generates it in Python I've been trying to make a program that downloads pdfs from links that "auto generates" them and to rename these files but i fail miserably. eg. link "https://checkaproduct.se.com/DistantRequestDispatcher.aspx?action=export&pid=62035238&lang=en_us" When you ...
Download PDF from link that auto generates it in Python
I've been trying to make a program that downloads pdfs from links that "auto generates" them and to rename these files but i fail miserably. eg. link "https://checkaproduct.se.com/DistantRequestDispatcher.aspx?action=export&pid=62035238&lang=en_us" When you enter it your browser (chrome - auto downloads with some stup...
[ "You will need to write your own os or python curl calls but that type of link can be captured in a short-term window, NOTE the pdf is auto generated with today's date thus it is NOT a stored pdf but a fresh Date: Wednesday, November 9, 2022 generation.\nBasically you call first reference to respond with the Locat...
[ 0 ]
[]
[]
[ "download", "pdf", "python" ]
stackoverflow_0074375403_download_pdf_python.txt
Q: Update plotly chart in jupyter notebook I'm creating a plotly chart in jupyter notebook. Because I'm testing some algorithm I want to add data after the initial fig2.show(). But when I update the data and call fig2.show again a new chart is being rendered. How can I update the chart instead of creating a new chart...
Update plotly chart in jupyter notebook
I'm creating a plotly chart in jupyter notebook. Because I'm testing some algorithm I want to add data after the initial fig2.show(). But when I update the data and call fig2.show again a new chart is being rendered. How can I update the chart instead of creating a new chart? This should be an easy task - but it's way ...
[ "This answer worked for me, and seems like the ideal answer to this question as well. I've voted to mark this as a duplicate.\nTo summarize: by wrapping the Figure in a FigureWidget, we can now do exactly what the OP wanted. Although on Colab I did have to give some extra permission by calling the following:\nfrom ...
[ 0 ]
[]
[]
[ "jupyter_notebook", "plotly", "plotly_python", "python" ]
stackoverflow_0062485380_jupyter_notebook_plotly_plotly_python_python.txt
Q: Is there any way to get Network Address with subnet mask with python? I am trying to scan my local area network information with python. Is there any way to get Network Address with subnet mask information to python? I want to get the Network Address (local network) and subnet mask information in the variables But...
Is there any way to get Network Address with subnet mask with python?
I am trying to scan my local area network information with python. Is there any way to get Network Address with subnet mask information to python? I want to get the Network Address (local network) and subnet mask information in the variables But when I searched on google, seems like there is no relevant information Tha...
[ "I think this will be helpful to get local network information in your case this might be os dependent.\nimport netifaces\nnetifaces.interfaces()\n#>>['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']\nnetifaces.ifaddresses('lo0')\n#>>{18: [{'addr': ''}], 2: [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0...
[ 0 ]
[]
[]
[ "networking", "python", "subnet" ]
stackoverflow_0074381254_networking_python_subnet.txt
Q: Fill column value based on join in Pyspark dataframe I have a dataframe using the code df = sc.parallelize([ (123, 2345,25,""), (123, 2345,29,"NY"), (123,5422,67,"NY"),(123,9422,67,"NY"),(123,3581,98,"NY"),(231, 4322,77,""),(231,4322,99,"Paris"),(231,8342,45,"Paris") ]).toDF(["userid", "transactiontime","zip",...
Fill column value based on join in Pyspark dataframe
I have a dataframe using the code df = sc.parallelize([ (123, 2345,25,""), (123, 2345,29,"NY"), (123,5422,67,"NY"),(123,9422,67,"NY"),(123,3581,98,"NY"),(231, 4322,77,""),(231,4322,99,"Paris"),(231,8342,45,"Paris") ]).toDF(["userid", "transactiontime","zip","location"]) +------+---------------+---+--------+ |useri...
[ "The first and last windowing functions accept an optional ignorenulls parameter which may be helpful in this case.\nHowever in your example you actually don't have null values but empty strings, which is different.\nw = Window.partitionBy('userid', 'transactiontime')\n\ndf_new = df \\\n .withColumn(\"fixedLoc\"...
[ 1 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python" ]
stackoverflow_0074381069_apache_spark_apache_spark_sql_pyspark_python.txt
Q: Pytest tries to collect wrong classes I have a Python module: . ├── module │ ├── __init__.py │ ├── __main__.py │ └── suite.py ├── docs ├── pyproject.toml ├── pytest.ini ├── setup.cfg ├── setup.py ├── tests │ ├── test_config.py │ ├── test_description.py │ ├── test_id.py │ ├── foo.py │ └── test_schem...
Pytest tries to collect wrong classes
I have a Python module: . ├── module │ ├── __init__.py │ ├── __main__.py │ └── suite.py ├── docs ├── pyproject.toml ├── pytest.ini ├── setup.cfg ├── setup.py ├── tests │ ├── test_config.py │ ├── test_description.py │ ├── test_id.py │ ├── foo.py │ └── test_schema.py └── tox.ini When I run pytest with t...
[ "I usually set the magic __test__ attribute to False on all classes that pytest should skip for any reason, including the ones that clash with the naming rules from python_classes. Example: create a conftest.py in your project's root directory with the contents\nfrom module.suite import TestSuite\n\nTestSuite.__tes...
[ 1 ]
[]
[]
[ "pytest", "python", "testing" ]
stackoverflow_0074359710_pytest_python_testing.txt
Q: Creating a relative symlink in python without using os.chdir() Say I have a path to a file: /path/to/some/directory/file.ext In python, I'd like to create a symlink in the same directory as the file, that points to the file. I'd like to end up with this: /path/to/some/directory/symlink -> file.ext I can do this...
Creating a relative symlink in python without using os.chdir()
Say I have a path to a file: /path/to/some/directory/file.ext In python, I'd like to create a symlink in the same directory as the file, that points to the file. I'd like to end up with this: /path/to/some/directory/symlink -> file.ext I can do this fairly easily using os.chdir() to cd into the directory and create ...
[ "You can also use os.path.relpath() so that you can use symlinks with relative paths. Say your script is in a directory foo/ and this directory has subdirectories src/ and dst/, and you want to create relative symlinks in dst/ to point to the files in src/. To do so, you can do:\nimport os\nfrom glob import glob\nf...
[ 31, 16, 0, 0 ]
[]
[]
[ "multithreading", "python", "symlink" ]
stackoverflow_0009793631_multithreading_python_symlink.txt
Q: sort G.nodes case insensitive I want to sort the nodes in my G.nodes with G=nx.Graph case insensitive. My code is H=nx.Graph() H.add_nodes_from(sorted(G.nodes(data=True), key=str.lower)) H.add_edges_from(G.edges(data=True)) But this leads to: descriptor 'lower' for 'str' objects doesn't apply to a 'tuple' object ...
sort G.nodes case insensitive
I want to sort the nodes in my G.nodes with G=nx.Graph case insensitive. My code is H=nx.Graph() H.add_nodes_from(sorted(G.nodes(data=True), key=str.lower)) H.add_edges_from(G.edges(data=True)) But this leads to: descriptor 'lower' for 'str' objects doesn't apply to a 'tuple' object How can I sort case insensitive in ...
[ "Oh I found the answer. It's\nH = nx.MultiDiGraph()\nH.add_nodes_from(sorted(G.nodes(data=True), key=lambda a: (a[0].lower())))\nH.add_edges_from(G.edges(data=True))\n\n" ]
[ 0 ]
[]
[]
[ "case_insensitive", "networkx", "python", "sorting" ]
stackoverflow_0074380922_case_insensitive_networkx_python_sorting.txt
Q: CryptoJS decrypt AES (CBC) with salt to Python Crypto I have this code on javascript. I want to rewrite this code on python but when i try to use salt with key i get wrong decrypted string, what i do wrong (how to use salt with key as it use in CryptoJS)? (I can't change type of encryption, but i need to decrypt e...
CryptoJS decrypt AES (CBC) with salt to Python Crypto
I have this code on javascript. I want to rewrite this code on python but when i try to use salt with key i get wrong decrypted string, what i do wrong (how to use salt with key as it use in CryptoJS)? (I can't change type of encryption, but i need to decrypt existing string) Code in js // y is array with all data var...
[ "The posted codes use different key derivation functions: The JavaScript code implicitly applies EVP_BytesToKey(), the Python code explicitly uses PBKDF2.\nNote that the IV specified in the JavaScript object is ignored. Instead, the IV determined via key derivation is used. This can be easily proven by using a rand...
[ 1 ]
[]
[]
[ "cryptography", "cryptojs", "javascript", "python" ]
stackoverflow_0074377121_cryptography_cryptojs_javascript_python.txt
Q: Class attributes dependent on other class attributes I want to create a class attribute, that are dependent to another class attribute (and I tell class attribute, not instance attribute). When this class attribute is a string, as in this topic, the proposed solution class A: foo = "foo" bar = foo[::-1] p...
Class attributes dependent on other class attributes
I want to create a class attribute, that are dependent to another class attribute (and I tell class attribute, not instance attribute). When this class attribute is a string, as in this topic, the proposed solution class A: foo = "foo" bar = foo[::-1] print(A.bar) works fine. But when the class attribute is a...
[ "Python is trying to look up remove in the global scope, but it doesn't exist there. x, on the other hand, is looked up in the enclosing (class) scope.\nSee the documentation:\nResolution of names\n\nClass definition blocks and arguments to exec() and eval() are special in the context of name resolution. A class de...
[ 5 ]
[]
[]
[ "class_attributes", "python" ]
stackoverflow_0074377678_class_attributes_python.txt
Q: How to utilise ffmpeg to to extract key frames from a video stream and only print the labels present within these frames? So a bit of context, I'm using the TensorFlow object detection API for a project, and I've modified the visualization_utils file to print any present class labels to the terminal and then write...
How to utilise ffmpeg to to extract key frames from a video stream and only print the labels present within these frames?
So a bit of context, I'm using the TensorFlow object detection API for a project, and I've modified the visualization_utils file to print any present class labels to the terminal and then write them to a .txt file. From a bit of research I've come across FFmpeg, I'm wondering if there is a function I can use in FFmpeg ...
[ "Thought I'd just follow up on this, I ended up using ffmpeg mpdecimate and setpts filters to remove duplicate and similar frames.\nffmpeg -i example.mp4 -vf mpdecimate=frac=1,setpts=N/FRAME_RATE/TB example_decimated.mp4\n\nThis however didn't solve the problem of duplicates within the file I was writing the label...
[ 0, 0 ]
[]
[]
[ "ffmpeg", "object_detection", "python", "tensorflow", "video" ]
stackoverflow_0065924019_ffmpeg_object_detection_python_tensorflow_video.txt
Q: Complement a DataFrame with empty columns if it has a columns total lower than desired There are some methods already published here to manually add a column, but my need is to add an amount that is still unknown. So I currently use this method (the example, the total number of columns I need to have is 10, so it ...
Complement a DataFrame with empty columns if it has a columns total lower than desired
There are some methods already published here to manually add a column, but my need is to add an amount that is still unknown. So I currently use this method (the example, the total number of columns I need to have is 10, so it analyzes if there are 10 columns and if there are less than 10, it adds the rest needed): im...
[ "Does the column name need to be an empty string?, you could just do it in alphabetical format if you require always 10 columns.\nimport pandas as pd\nimport string\n\ndf = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})\nalpha_list = list(string.ascii_lowercase[len(df.columns):10])\ndf[[alpha_list]] = None\n\nprint(df)\n\...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074381467_dataframe_pandas_python.txt
Q: 'UpdateMany' Mongo/PyMongo Bulkwrite deprecated? I am looking to update approximately 3000K entries their distance field, with 4000 values through PyMongo bulkwrite(), as update_many single is too slow. My practice: operations = [] for i in data: operations.append(updateMany({'location.zip':i['_id']}, {"$set":...
'UpdateMany' Mongo/PyMongo Bulkwrite deprecated?
I am looking to update approximately 3000K entries their distance field, with 4000 values through PyMongo bulkwrite(), as update_many single is too slow. My practice: operations = [] for i in data: operations.append(updateMany({'location.zip':i['_id']}, {"$set":{'calculations.distance':i['distance']}}, upsert=True)...
[ "You don't need to guess; just read the documentation.\nTry:\nfrom pymongo import MongoClient, UpdateMany\n\ndb = MongoClient()['mydatabase']\n\ncollection = db['collection']\n\ndata = [{'_id': 'postal', 'distance': 298.5}]\n\noperations = []\nfor i in data:\n operations.append(\n UpdateMany({'location.zi...
[ 1 ]
[]
[]
[ "mongodb", "pymongo", "python", "python_3.x" ]
stackoverflow_0074362417_mongodb_pymongo_python_python_3.x.txt
Q: How can I paginate the attributes from a model? I have a single for each series, but I want to paginate inside this page. I want to paginate the episodes because some series have more than 100 episodes and it is too much for a single page. class SerieDetailedView(DetailView): template_name = "tailwind/series_d...
How can I paginate the attributes from a model?
I have a single for each series, but I want to paginate inside this page. I want to paginate the episodes because some series have more than 100 episodes and it is too much for a single page. class SerieDetailedView(DetailView): template_name = "tailwind/series_detail.html" model = Serie slug_url_kwarg = "s...
[ "I think you did not understand the concept of relationnal database. In your case, you should split your data into two distinct tables :\nclass Serie(models.Model):\n name = models.CharField(max_length=150, unique=True)\n finished = models.BooleanField(default=False)\n published_at = models.DateTimeField(a...
[ 0 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0074379845_django_pagination_python.txt
Q: Value switcher for groups in Python/Numpy I have a list: groups = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'] I need to map each value to have an output like this, independently from the numbers of groups and elements inside: [0,0,0,1,1,0,0,1] The values in output should switch every time when the group is changing...
Value switcher for groups in Python/Numpy
I have a list: groups = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D'] I need to map each value to have an output like this, independently from the numbers of groups and elements inside: [0,0,0,1,1,0,0,1] The values in output should switch every time when the group is changing.
[ "Using python\nWith a list comprehension and the walrus operator of python 3.8+:\ngroups = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']\n\nflag = 0\n\nout = [flag if a==b else (flag:=1-flag) for a, b in zip(groups, groups[:1]+groups)]\n\nOr itertools:\nfrom itertools import groupby, chain\n\nout = list(chain.from_itera...
[ 1, 0 ]
[]
[]
[ "list_comprehension", "numpy", "python" ]
stackoverflow_0074381415_list_comprehension_numpy_python.txt
Q: WebRTC build fails with find_depot_tools error I am trying to compile WebRTC Framework. I cloned the repositories from here and here Prior cloning the repositories I installed depot_tools by following the instructions mentioned here However, when I try to compile it resulted in following error rk@180 src % ./tool...
WebRTC build fails with find_depot_tools error
I am trying to compile WebRTC Framework. I cloned the repositories from here and here Prior cloning the repositories I installed depot_tools by following the instructions mentioned here However, when I try to compile it resulted in following error rk@180 src % ./tools_webrtc/ios/build_ios_libs.sh ...
[ "I managed to solve the problem, this works for me\ncd src\ngit checkout main\ngit pull origin main\ntools_webrtc/ios/build_ios_libs.py\n\nMost likely the local version of the src cloned by you really does not contain find_depot_tools, unlike the origin/main branch\n" ]
[ 0 ]
[]
[]
[ "python", "webrtc" ]
stackoverflow_0070802435_python_webrtc.txt
Q: How can I convert a string into a tuple in python? My problem is that I want to convert this type of pieces of string into tuples. But I want the word to be a string and the number to be an integer. Is there some simple solution for this problem? mystring = "(Ilioupoli,2)" The output should be: ("Ilioupoli", 2) ...
How can I convert a string into a tuple in python?
My problem is that I want to convert this type of pieces of string into tuples. But I want the word to be a string and the number to be an integer. Is there some simple solution for this problem? mystring = "(Ilioupoli,2)" The output should be: ("Ilioupoli", 2) I've been looking for some solutions but didn't find the...
[ "Remove the () around it, use split() to split it at the comma, then convert the second element to an integer.\nmystring = \"(Ilioupoli,2)\"\nfields = mystring.strip(\"()\").split(',')\nmytuple = (fields[0], int(fields[1]))\n\n", "Remove the () using .replace() and split the string using .split() at the comma to ...
[ 1, 0 ]
[ "Use string replace to replace the ( and ) with nothing. Split the string on the ',' using string.split. Take the first element as a string, and convert the second using int or float. Then construct your tuple.\n" ]
[ -1 ]
[ "integer", "python", "string", "tuples" ]
stackoverflow_0074381725_integer_python_string_tuples.txt
Q: How to remove integers but keep the floats from a dictionary? I have a dictionary shaped like this: {'Afghanistan': 0.0, 'Albania': 0, 'Algeria': 50.0, 'Angola': 51.85185185185185 'Vietnam': 48.333333333333336, 'Yemen': 25.0, 'Zambia': -105.55555555555556, 'Zimbabwe': -570.0, 'Global': -24.358974358974358}...
How to remove integers but keep the floats from a dictionary?
I have a dictionary shaped like this: {'Afghanistan': 0.0, 'Albania': 0, 'Algeria': 50.0, 'Angola': 51.85185185185185 'Vietnam': 48.333333333333336, 'Yemen': 25.0, 'Zambia': -105.55555555555556, 'Zimbabwe': -570.0, 'Global': -24.358974358974358} As you can see some values are 0 where some are 0.0. I need to re...
[ "You don't need nested loops, just one loop. The value of the dictionary element would be dictionary[y].\nAnd I'm not sure what you mean by y[x]. y is a dictionary key, x is an integer, so y[x] is one of the characters in the country name; this will get an error is x is more than the length of the country.\nYou sho...
[ 1 ]
[]
[]
[ "dictionary", "floating_point", "integer", "python", "types" ]
stackoverflow_0074381738_dictionary_floating_point_integer_python_types.txt
Q: ipyleaflet map not rendering in jupyter notebook on install Running the following inside the notebook: !pip install ipyleaflet !jupyter nbextension enable --py --sys-prefix ipyleaflet Successfully registers ipyleaflet extension: Enabling notebook extension jupyter-leaflet/extension... - Validating: ok Howe...
ipyleaflet map not rendering in jupyter notebook on install
Running the following inside the notebook: !pip install ipyleaflet !jupyter nbextension enable --py --sys-prefix ipyleaflet Successfully registers ipyleaflet extension: Enabling notebook extension jupyter-leaflet/extension... - Validating: ok However rendering the map within the same notebook does not work: fro...
[ "I received the same error while running Jupyter Notebook but restarting the kernel, and closing and reopening that file worked for me.\n" ]
[ 0 ]
[]
[]
[ "ipyleaflet", "jupyter_notebook", "python", "python_3.x" ]
stackoverflow_0074287757_ipyleaflet_jupyter_notebook_python_python_3.x.txt
Q: Django - How to add a comment limit of 1 I currently have a comment functionality and I want to add a limit of one comment for each user but don't know how to do that. I tought on making a 'posted' field in the user model which would be true when the user posted a comment but I don't know how to do that and most i...
Django - How to add a comment limit of 1
I currently have a comment functionality and I want to add a limit of one comment for each user but don't know how to do that. I tought on making a 'posted' field in the user model which would be true when the user posted a comment but I don't know how to do that and most importantly if that is the better way of doing ...
[ "If you are really sure a user should post one and only one comment, you should use a OneToOneField. This way, the unique constraint shall be be automatically generated and the object easier to manage.\nclass Comment(models.Model):\n service = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null...
[ 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074381396_django_django_views_python.txt
Q: memory_profiler %mprun with imported function works but don't display the profiler as a table, how to fix that? I'm studying memory_profiler with a function i made just for practice purposes, and the memory_profiler doesn't display the memory usage as a table. The function file (FuncExamples.py) is in the same fol...
memory_profiler %mprun with imported function works but don't display the profiler as a table, how to fix that?
I'm studying memory_profiler with a function i made just for practice purposes, and the memory_profiler doesn't display the memory usage as a table. The function file (FuncExamples.py) is in the same folder as the jupyter notebook. The code is running inside vscode with the jupyter notebook extension. If i run in an an...
[ "The message you are getting is not an error but rather telling you that the extension you are trying to use is already loaded \"%load_ext memory_profiler.\" You could get rid of this message by separating the line: %load_ext memory_profiler into its own cell in your jupyter notebook and then each time you want to ...
[ 0 ]
[]
[]
[ "jupyter_notebook", "memory_profiling", "python" ]
stackoverflow_0072418230_jupyter_notebook_memory_profiling_python.txt
Q: Why does python pandas need fix infront of ax to draw a graph? I was learning how to make graphs with python pandas. But I couldn't understand how this code works. fig , ax = plt.subplots( ) ax = tips[['total_bill','tip']].plot.hist(alpha=0.5, bins=20, ax=ax) I couldn't understand why the code words only when ther...
Why does python pandas need fix infront of ax to draw a graph?
I was learning how to make graphs with python pandas. But I couldn't understand how this code works. fig , ax = plt.subplots( ) ax = tips[['total_bill','tip']].plot.hist(alpha=0.5, bins=20, ax=ax) I couldn't understand why the code words only when there is fig infront of ax. Also I have no idea what 'ax=ax' means. I fo...
[ "Pandas is using the library matplotlib to do the plotting. Try to read up a bit about how matploltib works, it will help you understand this code a bit.\nGenerally, plotting with matplotlib involves a figure and one or more axes. A figure can be thought of as a frame where multiple plots can be created inside. Eac...
[ 0 ]
[]
[]
[ "dataframe", "graph", "pandas", "python", "series" ]
stackoverflow_0074381751_dataframe_graph_pandas_python_series.txt
Q: How do I read an mp4 file directly into moviepy from S3? Any idea how to read an S3 mp4 file directly into moviepy? I have tried, import boto3 from io import BytesIO from moviepy.editor import * client = boto3.client('s3') obj = client.get_object(Bucket='some-bucket', Key='some-file') VideoFileClip(BytesIO(obj['...
How do I read an mp4 file directly into moviepy from S3?
Any idea how to read an S3 mp4 file directly into moviepy? I have tried, import boto3 from io import BytesIO from moviepy.editor import * client = boto3.client('s3') obj = client.get_object(Bucket='some-bucket', Key='some-file') VideoFileClip(BytesIO(obj['Body'].read())) but I am getting, Traceback (most recent cal...
[ "This is an old question, apologies in advance for the delay, but for anyone in the future looking for a potential solution, you can load videos with direct urls into VideoFileClip.\nFirst, you'll need to generate a presigned url of the object in the bucket:\nimport boto3\nimport logging\ndef create_presigned_url(b...
[ 0 ]
[]
[]
[ "amazon_s3", "ffmpeg", "moviepy", "python" ]
stackoverflow_0055593404_amazon_s3_ffmpeg_moviepy_python.txt
Q: How to compare Cisco software versions in Python I need to compare software versions for Cisco devices in Python, but unfortunately packaging.version doesn't support this format when 3rd and 4th indexes are joined by letters. Maybe someone knows a package that can compare the following versioning format "15.2.7E7"...
How to compare Cisco software versions in Python
I need to compare software versions for Cisco devices in Python, but unfortunately packaging.version doesn't support this format when 3rd and 4th indexes are joined by letters. Maybe someone knows a package that can compare the following versioning format "15.2.7E7" from packaging.version import Version # working if V...
[ "swversion package can parse and compare Cisco software versions, as in the following example\nimport re\nfrom swversion import SwVersion\n\ntext = \"Cisco IOS Software, C2960X Software (C2960X-UNIVERSALK9-M), Version 15.2(4)E10, ...\"\ntext = re.search(r\"Version (\\S+),\", text)[1]\n\nversion1 = SwVersion(text) ...
[ 0 ]
[]
[]
[ "cisco", "cisco_ios", "networking", "python", "version" ]
stackoverflow_0074336469_cisco_cisco_ios_networking_python_version.txt
Q: pandas: Rolling correlation with fixed patch for pattern-matching Happy New Year. I am looking for a way to compute the correlation of a rolling window and a fixed window ('patch') with pandas. The ultimate objective is to do pattern matching. From what I read on the docs, AND HOPEFULLY I MISSED SOMETHING, corr() ...
pandas: Rolling correlation with fixed patch for pattern-matching
Happy New Year. I am looking for a way to compute the correlation of a rolling window and a fixed window ('patch') with pandas. The ultimate objective is to do pattern matching. From what I read on the docs, AND HOPEFULLY I MISSED SOMETHING, corr() or corrwith() do not allow you to lock one of the Series / DataFrames. ...
[ "Clearly, the copious use of reset_index is a signal that we are fighting with Panda's indexing and automatic alignment. Oh, how much easier things would be if we could just forget about the index!\nIndeed, that is what NumPy is for. (Generally speaking, use Pandas when you need alignment or grouping by index, use ...
[ 2 ]
[ "There is a mistake here because len(df) - len(patch) is not equal to len(correl).\nlen(df) = 10\nlen(patch) = 4\n\nSo technically we should have 6 values for the correl. But len(correl)=7\nNot sure where the issue comes from\n" ]
[ -1 ]
[ "correlation", "numpy", "pandas", "pattern_matching", "python" ]
stackoverflow_0027733482_correlation_numpy_pandas_pattern_matching_python.txt
Q: Iterating through a dictionary, and getting max, min, and average values from the value For the get_gc_stats( ) function: The first value in the returned list will be the minimum GC value in the dictionary The second value in the returned list will be the maximum GC value in the dictionary The third value in the r...
Iterating through a dictionary, and getting max, min, and average values from the value
For the get_gc_stats( ) function: The first value in the returned list will be the minimum GC value in the dictionary The second value in the returned list will be the maximum GC value in the dictionary The third value in the returned list will be the average GC value from the dictionary Assuming the dictionary is: dna...
[ "You can use make a long list of all the \"GC\" values and then the use min(), max(), and divide the sum of all values by the length of the list to get the values you would like.\ndna_stats = {\n 'TAGC' : [0.5, 4], \n 'ACGTATGC' : [0.5, 8],\n 'ATG' : [0.3333333333333333, 3],\n 'ACGGCTAG' : [0.625, 8]\n}\n\ndef ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074381654_python.txt
Q: FastAI Multilayer LSTM not learning, accuracy decreases while training I'm following Chapter 12 on RNNs/LSTMs from scratch in the fastai book, but getting stuck trying to train a custom built LSTM from scratch. Here is my code This is the boilerplate bit (following the examples in the book) from fastai.text.all im...
FastAI Multilayer LSTM not learning, accuracy decreases while training
I'm following Chapter 12 on RNNs/LSTMs from scratch in the fastai book, but getting stuck trying to train a custom built LSTM from scratch. Here is my code This is the boilerplate bit (following the examples in the book) from fastai.text.all import * path = untar_data(URLs.HUMAN_NUMBERS) lines = L() with open(path/'tr...
[ "After some playing around I was able to figure it out. The issue was the way I was initialising the list of cells. In MyModule.__init__ I only needed to change the line to\nself.cells = nn.ModuleList([LSTMCell(bs, n_hidden) for _ in range(sl)])\n\nThe reason it was broken was that by initialising the Modules in a ...
[ 0 ]
[]
[]
[ "deep_learning", "fast_ai", "lstm", "python", "pytorch" ]
stackoverflow_0074316188_deep_learning_fast_ai_lstm_python_pytorch.txt
Q: How to give an error output when there's not enough values given to input in Python? There's a part of my schoolwork. I need to give an error output when user doesn't give an second input, but as you know python gives an error itself when you don't give the second output. Is there any way to do that or do I have t...
How to give an error output when there's not enough values given to input in Python?
There's a part of my schoolwork. I need to give an error output when user doesn't give an second input, but as you know python gives an error itself when you don't give the second output. Is there any way to do that or do I have to change my implementation? I have to check the second argument that's why I am getting th...
[ "How about this? Treat the \"rest\" part as a list and check if its length is zero.\noption, *person = input(\"Choose an option and person: \").split()\nif len(person) == 0:\n print(\"Missing argument\")\n\n", "either wrap the line that throws an error in a try: except block or don't do the tuple unpacking on th...
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074381574_python.txt
Q: Run python script at the click of an html button (Flask/Django) I have a very simple python code that retrieves the share price of some stocks. I have managed to include that in Django/Flask so I can see this in a html page. I would like to create an html button that when I click on it it runs the python script an...
Run python script at the click of an html button (Flask/Django)
I have a very simple python code that retrieves the share price of some stocks. I have managed to include that in Django/Flask so I can see this in a html page. I would like to create an html button that when I click on it it runs the python script and the share prices refresh (and remain on the same html page e.g. ind...
[ "If you have written a class, or a method, then you can just call it an store the returned value in a variable and pass it to the html file using jinja2.\nwould be something like:\nreturn render_template(\"index.html\", parameter1 = returned_value)\n\nand in your html file:\n<p>{{ parameter1 }}</p>\n\nTake a look:\...
[ 0, 0 ]
[]
[]
[ "django", "flask", "python" ]
stackoverflow_0074381889_django_flask_python.txt
Q: Multi-file archive format supporting iteration in python I recently realized that neither .tar.gz nor .zip archive file enable quick iteration over the files they contain in python. Let me elaborate. I have a large collection of files. The statistics are the following: Number of files: 4'810'289 Number of directo...
Multi-file archive format supporting iteration in python
I recently realized that neither .tar.gz nor .zip archive file enable quick iteration over the files they contain in python. Let me elaborate. I have a large collection of files. The statistics are the following: Number of files: 4'810'289 Number of directories: 402'212 The tar.gz archive is 9GB. The .zip archive file...
[ "I am not seeing that ZipFile behavior. This is on a 16 GB zip file with about 11,000 entries. The memory usage is nowhere near the size of the zip file:\nPython 3.9.6 (default, Sep 26 2022, 11:37:49) \n[Clang 14.0.0 (clang-1400.0.29.202)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more...
[ 1 ]
[]
[]
[ "archive", "compression", "iteration", "python" ]
stackoverflow_0074380295_archive_compression_iteration_python.txt
Q: InvalidArgumentError : input depth must be evenly divisible by filter depth: 4 vs 3 I'm a beginner. I tried Image Classification by Tensorflow, and got the following error. I found the similar issue on web, but I couldn't understand. What does the error mean? How should I do for it? Please give me some advice. I u...
InvalidArgumentError : input depth must be evenly divisible by filter depth: 4 vs 3
I'm a beginner. I tried Image Classification by Tensorflow, and got the following error. I found the similar issue on web, but I couldn't understand. What does the error mean? How should I do for it? Please give me some advice. I use 100 files(png/15pix, 15pix) like a sample image. Tensorflow ver.2.0.0 / python ver.3.8...
[ "If your model looks like this:\nmodel = tf.keras.Sequential([\ntf.keras.layers.Conv2D(16, (3, 3), activation = 'relu', input_shape = (150, 150, 3)),\ntf.keras.layers.MaxPooling2D(2, 2),\ntf.keras.layers.Conv2D(32, (3, 3), activation = 'relu'),\ntf.keras.layers.MaxPooling2D(2, 2),\ntf.keras.layers.Flatten(),\ntf.ke...
[ 10, 5, 4, 4, 3, 1, 0 ]
[]
[]
[ "error_handling", "image_comparison", "python", "tensorflow" ]
stackoverflow_0060174964_error_handling_image_comparison_python_tensorflow.txt
Q: Unexpected output of bash 'ps -p $$' command returned by 'subprocess.run()' I am running Linux Mint 18.1 and Python 3.9. To find out which shell is executing shell commands I have started to use ps -p $$ which is expected to return the info about the shell as value of CMD. When using subprocess.run() in Python not...
Unexpected output of bash 'ps -p $$' command returned by 'subprocess.run()'
I am running Linux Mint 18.1 and Python 3.9. To find out which shell is executing shell commands I have started to use ps -p $$ which is expected to return the info about the shell as value of CMD. When using subprocess.run() in Python not specifying the shell or specifying the shell as executable='sh' the CMD value is...
[ "This is a bash optimization. If the command line is just a single command, it's is implemented by simply calling execv() rather than forking a child to execute the command. This replaces the shell process with the ps program, keeping the same PID. It's as if you executed.\nprint(run('exec ps -p $$', ...))\n\nYou d...
[ 3 ]
[]
[]
[ "bash", "linux", "python", "shell" ]
stackoverflow_0074381947_bash_linux_python_shell.txt