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: locating element via selenium explicitly waiting and without gives 0 Using this url I want to locate div tags which has attribute data-asin . When I use //div[@data-asin] in Chrome Inspect mode it gives 21 elements. But while trying to get these elements via Selenium in both ways, explicit wait and direct length ...
locating element via selenium explicitly waiting and without gives 0
Using this url I want to locate div tags which has attribute data-asin . When I use //div[@data-asin] in Chrome Inspect mode it gives 21 elements. But while trying to get these elements via Selenium in both ways, explicit wait and direct length gives 0. As I guess Selenium remote browser is unable to get anyone of the...
[ "You have to mention XPATH not TAG_NAME:\ntry:\n x_index=wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//div[@data-asin]')))###Attention here\n print(len(x_index))\nexcept:\n y_index=driver.find_elements(By.XPATH,'//div[@data-asin]')###Anf attention here\n print(len(y_index))\n\n" ]
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074275526_python_selenium.txt
Q: why does this have a extra space after the '-' in 'I-'? I'm taking a class through zybooks, and the whitespace is a bit glitchy through here. I'm not sure what is causing this extra space, so any help would be appreciated. The instructions for this: Primary U.S. interstate highways are numbered 1-99. Odd numbers (...
why does this have a extra space after the '-' in 'I-'?
I'm taking a class through zybooks, and the whitespace is a bit glitchy through here. I'm not sure what is causing this extra space, so any help would be appreciated. The instructions for this: Primary U.S. interstate highways are numbered 1-99. Odd numbers (like the 5 or 95) go north/south, and evens (like the 10 or 9...
[ "That is how print works. It add space between every argument. That is why\nprint(1,2,3)\n\nprints 1 2 3 not 123.\nSo, most of the time, you want that behavior.\nThat being said, you can change it\nprint(1,2,3, sep='')\n\nprints 123\nIn your case (not yet the solution)\nprint(\"I-\", highway_number,\"is primary, go...
[ 6, 1, 1, 1 ]
[ "Python can be very confusing and sometimes the littlest things will change what it does. In this case, you have to change the comma next to the I- to a + sign. You then have to change the variable highway_number to a string. For example print('I-'+ str(highway_number) + \" is primary, going east/west.\")\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0074276204_python.txt
Q: Pythonic way to include imports in python package I am probably missing something obvious here: I am creating my own python package that I would like to import to PyPi. The modules Foo.py I have written look like this: import numpy as np import sklearn -------------- def Class(Foo): def function(a: int, b: int):...
Pythonic way to include imports in python package
I am probably missing something obvious here: I am creating my own python package that I would like to import to PyPi. The modules Foo.py I have written look like this: import numpy as np import sklearn -------------- def Class(Foo): def function(a: int, b: int): '''A class that uses numpy to do something with...
[ "Flit is a good and modern tool for the job.\nhttps://flit.pypa.io/en/stable/pyproject_toml.html#dependencies\nYou can specify the dependencies in the pyproject.toml file in the dependencies section as below:\ndependencies = [\n \"requests >=2.6\",\n \"configparser; python_version == '2.7'\",\n]\n\n" ]
[ 1 ]
[]
[]
[ "pip", "pypi", "python", "python_import", "python_packaging" ]
stackoverflow_0074260869_pip_pypi_python_python_import_python_packaging.txt
Q: Loop through a list with itertools.islice I'm trying to check the first 5 elements in a list, see if two or more are greater or equal to 5, and then check the next 5 elements with the same process. I have this working by creating a new list and appending the next 5 elements: from itertools import islice myList = ...
Loop through a list with itertools.islice
I'm trying to check the first 5 elements in a list, see if two or more are greater or equal to 5, and then check the next 5 elements with the same process. I have this working by creating a new list and appending the next 5 elements: from itertools import islice myList = [3, 7, 3, 1, 2, 3, 6, 75, 77, 4] print(sum(i>5 ...
[ "You can just use a range with step 5\nmyList = [3, 7, 3, 1, 2, 3, 6, 75, 77, 4]\n\nfor i in range(0, len(myList), 5):\n if sum(v > 5 for v in myList[i:i+5]) > 1:\n print(f'Chunk {i}->{i+5} has two or more values greater than 5')\n\nOutput:\nChunk 5->10 has two or more values greater than 5\n\n" ]
[ 1 ]
[]
[]
[ "list", "loops", "python", "python_itertools" ]
stackoverflow_0074276272_list_loops_python_python_itertools.txt
Q: How to extract lists in Python? ''' [[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]] find 1 ''' key = 1 x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]] #len(x) -> 1 Actually my question is simple, but i couldn't solve this problem... What should i use to solve it, i mean should i use re...
How to extract lists in Python?
''' [[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]] find 1 ''' key = 1 x = [[[[[[[[[[[[[[[[[[[[[[[[[[[[key]]]]]]]]]]]]]]]]]]]]]]]]]]]] #len(x) -> 1 Actually my question is simple, but i couldn't solve this problem... What should i use to solve it, i mean should i use recrusive functions or for loop ??? for...
[ "Here is a non-recursive approach for your current structure:\ndef extract_list(l: list):\n while True:\n l = l.pop()\n if not isinstance(l, list):\n return l\n\n\nx = [[[[[[[[[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]]]]]]]]]\nprint(extract_list(x)) # 1\n\n", "You can do that as follo...
[ 2, 2, 1, 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074276249_function_list_python.txt
Q: python: in my df, I need to add up a column until i hit a target, then change the data in a different column for each value that makes the target enter code hereI have a df like this : Project position emp hrs 0 A Burger flipper John 1.25 1 B cashier steve 2.25 2 C...
python: in my df, I need to add up a column until i hit a target, then change the data in a different column for each value that makes the target
enter code hereI have a df like this : Project position emp hrs 0 A Burger flipper John 1.25 1 B cashier steve 2.25 2 C cleaner Karen 0.25 3 A shift manager sally 0.25 4 C supervisor julie 1.25 5 A cleaner Karen 1.75**...
[ "df.loc[:, 'cumsum'] = df.groupby('emp')['hrs'].transform('cumsum')\n\nind = df[(df['emp'] == 'John') & (df['cumsum'] < 10)].index\ndf.loc[ind, 'position'] = 'Restaurant Manager'\n\nprint(df)\n\nOutput\n Project position emp hrs cumsum\n0 A Restaurant Manager John 1.25 1.25\n1 ...
[ 0 ]
[]
[]
[ "cumsum", "dataframe", "pandas", "python" ]
stackoverflow_0074267576_cumsum_dataframe_pandas_python.txt
Q: pd.to_datetime doesn't work on values similar to '10/30/2022 7:00:00 AM +01:00' I have a pandas dataframe with the following column: import pandas as pd df = pd.DataFrame(['10/30/2022 7:00:00 AM +01:00', '10/31/2022 12:00:00 AM +01:00', '10/30/2022 3:00:00 PM +01:00', '10/30/2022 9:00:00 PM +01:00', ...
pd.to_datetime doesn't work on values similar to '10/30/2022 7:00:00 AM +01:00'
I have a pandas dataframe with the following column: import pandas as pd df = pd.DataFrame(['10/30/2022 7:00:00 AM +01:00', '10/31/2022 12:00:00 AM +01:00', '10/30/2022 3:00:00 PM +01:00', '10/30/2022 9:00:00 PM +01:00', '10/30/2022 5:00:00 PM +01:00', '10/30/2022 10:00:00 PM +01:00', '10/30/2022 3...
[ "# convert to date \n# convert to your format\ndf['Date']=df['Date'].apply(pd.to_datetime).apply(lambda x: x.strftime('%Y-%m-%dT%H:%M:%S%z')) \n\n0 2022-10-30T07:00:00+0100\n1 2022-10-31T00:00:00+0100\n2 2022-10-30T15:00:00+0100\n3 2022-10-30T21:00:00+0100\n4 2022-10-30T17:00:00+0100\n5 2022...
[ 1, 1 ]
[]
[]
[ "datetime", "format", "pandas", "python", "strftime" ]
stackoverflow_0074276252_datetime_format_pandas_python_strftime.txt
Q: How to resolve TypeError: element_to_be_clickable() takes 1 positional argument? I'm getting the error TypeError: element_to_be_clickable() takes 1 positional argument but 2 were given when I run the following code: from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeD...
How to resolve TypeError: element_to_be_clickable() takes 1 positional argument?
I'm getting the error TypeError: element_to_be_clickable() takes 1 positional argument but 2 were given when I run the following code: from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.web...
[ "You do need both By and the value, but the function expects both values to be packed to one, in a tuple\nEC.element_to_be_clickable((By.CSS_SELECTOR, \"#add-flight-switch\"))\n\nIf you drill down the source code you will see element_to_be_clickable uses _find_element internally, this function unpack the tuple to b...
[ 4, 0 ]
[]
[]
[ "element", "python", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0069840450_element_python_selenium_selenium_chromedriver_web_scraping.txt
Q: How do i get rid of the degree sign from my integer when i want to convert it from a string in a dictionary? I have a dictionary as follows: Measurments = {'Kitchen': '22°', 'Master bedroom': '19°', 'Sitting room': '21°', 'Toilet': '24°', 'Guest bedroom': '18°', 'Garage': '15°', 'Outside': '12°'} and want to save...
How do i get rid of the degree sign from my integer when i want to convert it from a string in a dictionary?
I have a dictionary as follows: Measurments = {'Kitchen': '22°', 'Master bedroom': '19°', 'Sitting room': '21°', 'Toilet': '24°', 'Guest bedroom': '18°', 'Garage': '15°', 'Outside': '12°'} and want to save it in a new dictionary as follows: newDictionary = {'Kitchen': 22, 'Master bedroom': 19, 'Sitting room': 21, 'T...
[ "try something like this:\nnewDictionary = {key:int(value.replace('°', '')) for key,value in Measurments.items()}\n\nsince your values are all strings now, you can use replace method to remove the °, and then it will be able to convert it to int\n", "You can do it as follow by removing the unwanted character befo...
[ 0, 0 ]
[ "If you are sure if everything has a degree, you can simply do as below.\nmeasurements = {'Kitchen': '22°', 'Master bedroom': '19°', 'Sitting room': '21°', 'Toilet': '24°', 'Guest bedroom': '18°', 'Garage': '15°', 'Outside': '12°'}\n\nnewDictionary = {str(k):int(v[:-1]) for k,v in measurements.items()}\n\nprint(new...
[ -1 ]
[ "dictionary", "integer", "python", "string", "type_conversion" ]
stackoverflow_0074276409_dictionary_integer_python_string_type_conversion.txt
Q: Is there a C# equivalent to the Python := (an assignment expression)? Assignment expression Python 3.8 I like how it saves line. Example: for rule in rules: place = getPlace(rule) if place: print(f"Apply rule {rule.__name__} -> {place}") return place raise Exception('No rule found!') ↓↓ fo...
Is there a C# equivalent to the Python := (an assignment expression)?
Assignment expression Python 3.8 I like how it saves line. Example: for rule in rules: place = getPlace(rule) if place: print(f"Apply rule {rule.__name__} -> {place}") return place raise Exception('No rule found!') ↓↓ for rule in rules: if place:= getPlace(rule): print(f"Apply rule ...
[ "Well, there isn't a perfect 1:1 match, but in your case you could use\nforeach (var rule in rules)\n{\n string place;\n if ((place = GetPlace(rule)) != null)\n {\n Console.WriteLine($\"Found {place}\");\n return place;\n }\n}\n\nHere is a demo. The ((place = GetPlace(rule)) != null) is on...
[ 2 ]
[]
[]
[ "assignment_operator", "c#", "expression", "python" ]
stackoverflow_0074276338_assignment_operator_c#_expression_python.txt
Q: How to run Run only a Single test in Visual Studio Code and Python with output Does anyone know how to run only one python test with Test Explorer in Visual Studio Code? I have installed https://marketplace.visualstudio.com/items?itemName=LittleFoxTeam.vscode-python-test-adapter. I am using pytest. In the picture...
How to run Run only a Single test in Visual Studio Code and Python with output
Does anyone know how to run only one python test with Test Explorer in Visual Studio Code? I have installed https://marketplace.visualstudio.com/items?itemName=LittleFoxTeam.vscode-python-test-adapter. I am using pytest. In the picture below: If I press "Run Test" then only one test runs, but I do not see any log / o...
[ "I did not find one elegant way to just run one test and then see the correct sampled/collected output from that test, but I found a way to run only the test I was working on by tagging it with:\n@pytest.mark.run_this_test\n\nand hit F5 anywhere in VSCode to just run this test over and over again. The PyTest debug ...
[ 5, 2, 0 ]
[]
[]
[ "python", "test_explorer", "testing", "visual_studio_code" ]
stackoverflow_0059409834_python_test_explorer_testing_visual_studio_code.txt
Q: Why does python ElementTree parse and output (tostring) newlines and spaces? Given the following two sample XMLs: indented.xml: <RestInterface> <message id="9" timestamp="2022-10-30 20:54:27.493"> <response objectType="Org" id="Outlet.1"> <attr appId="APP1" name="timezone"> ...
Why does python ElementTree parse and output (tostring) newlines and spaces?
Given the following two sample XMLs: indented.xml: <RestInterface> <message id="9" timestamp="2022-10-30 20:54:27.493"> <response objectType="Org" id="Outlet.1"> <attr appId="APP1" name="timezone"> <value>Europe/Berlin</value> </attr> <attr appId="APP2" na...
[ "According to the documentation - https://docs.python.org/3/library/xml.etree.elementtree.html - the method canonicalize includes a parameter strip_text to control whitespace handling.\n\nstrip_text: set to true to strip whitespace before and after text content\n(default: false)\n\nprint(canonicalize(ET.tostring(ro...
[ 2 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0074276360_elementtree_python.txt
Q: Splitting on spaces, except between certain characters I am parsing a file that has lines such as type("book") title("golden apples") pages(10-35 70 200-234) comments("good read") And I want to split this into separate fields. In my example, there are four fields: type, title, pages, and comments. The desired re...
Splitting on spaces, except between certain characters
I am parsing a file that has lines such as type("book") title("golden apples") pages(10-35 70 200-234) comments("good read") And I want to split this into separate fields. In my example, there are four fields: type, title, pages, and comments. The desired result after splitting is ['type("book")', 'title("golden app...
[ "This regex should work for you \\s+(?=[^()]*(?:\\(|$))\nresult = re.split(r\"\\s+(?=[^()]*(?:\\(|$))\", subject)\n\nExplanation\nr\"\"\"\n\\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)\n + # Between one and unlimited times, as many times a...
[ 16, 3, 1, 1, 0 ]
[]
[]
[ "python", "string_parsing" ]
stackoverflow_0009644784_python_string_parsing.txt
Q: tkinter spinbox not int hey guys , i have problem i create a spinbox (Spinbox) but its not int! my code: def show(): if upper.get() > 1: print("hello") app = Tk() upper = Spinbox(app,fg="red" from_=0,to=100000000000000000000000) upper.pack() Button(app,text="show",command=show).pack() app.mainloop() ...
tkinter spinbox not int
hey guys , i have problem i create a spinbox (Spinbox) but its not int! my code: def show(): if upper.get() > 1: print("hello") app = Tk() upper = Spinbox(app,fg="red" from_=0,to=100000000000000000000000) upper.pack() Button(app,text="show",command=show).pack() app.mainloop() and my error: '>' not support...
[ "You need to use if int(upper.get()) > 1 to convert the value of upper.get() to an integer since Spinbox returns a string\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074276605_python_tkinter.txt
Q: pg_dump & pg_restore password using python module subprocess Problem: Use the PSQL pg_dump and pg_restore in a Python script and using the subprocess module. Background: I am using the following python 2.7 script from the localhost (i.e. Ubuntu 14.04.5 LTS) to create a backup of a table in a PSQL server (i.e. Post...
pg_dump & pg_restore password using python module subprocess
Problem: Use the PSQL pg_dump and pg_restore in a Python script and using the subprocess module. Background: I am using the following python 2.7 script from the localhost (i.e. Ubuntu 14.04.5 LTS) to create a backup of a table in a PSQL server (i.e. PostgreSQL 9.4.11) and restore it into the remote host (i.e. Ubuntu 16...
[ "The following works and the changes made are commented. \nI am not sure though why the pg_restore produces that password authentication error when using the full command (i.e. not split in the list) and using shell=True in Popen, but pg_dump on the other hand works fine using shell=True & the full command. Does < ...
[ 13, 12, 6, 0 ]
[]
[]
[ "pg_dump", "pg_restore", "psql", "python", "subprocess" ]
stackoverflow_0043380273_pg_dump_pg_restore_psql_python_subprocess.txt
Q: Jupyter error: "No module named jupyter_core.paths" Trying to open Jupyter Notebook (OSX 10.11.4) I get the following error: $ jupyter-notebook Traceback (most recent call last): File "/usr/local/bin/jupyter-notebook", line 7, in <module> from notebook.notebookapp import main File "/Users/geotheory/Library...
Jupyter error: "No module named jupyter_core.paths"
Trying to open Jupyter Notebook (OSX 10.11.4) I get the following error: $ jupyter-notebook Traceback (most recent call last): File "/usr/local/bin/jupyter-notebook", line 7, in <module> from notebook.notebookapp import main File "/Users/geotheory/Library/Python/2.7/lib/python/site-packages/notebook/__init__.py...
[ "I had the same issue, fixed by simply using pip install jupyter in the macOS terminal. \n", "I faced the same issue, and was able resolve with the following steps.\nconda create -n py36 python=3.6\nconda activate py36\nconda install notebook ipykernel jupyterlab\n\n\n", "I have encountered similar issue. Basic...
[ 10, 8, 3, 2, 1, 1, 1, 1, 0, 0 ]
[ "Got similar issue & Fixed after removing the user from the sudo group in ubuntu.\nsudo deluser my_user sudo\n\n" ]
[ -3 ]
[ "jupyter", "jupyter_notebook", "python" ]
stackoverflow_0036482850_jupyter_jupyter_notebook_python.txt
Q: Accessing specific key in list of dictionaries in Python I'm being asked to write a function which will accept a list of dictionary objects as input, and will return a list of values pertaining to a specific key in the dictionaries. An example of the function call: titles = getKeys( [book1, book2, book3] ) I made...
Accessing specific key in list of dictionaries in Python
I'm being asked to write a function which will accept a list of dictionary objects as input, and will return a list of values pertaining to a specific key in the dictionaries. An example of the function call: titles = getKeys( [book1, book2, book3] ) I made 3 dictionaries and then defined the function and passed a li...
[ "Based on the provided code, it seem you have not actually called the getKeys method, you've only defined it. Just because your list of dictionaries has the same name as the parameter of the getKeys method does not mean getKeys was ever called.\nbook1 = {\n \"Title\": \"ShowYourWork\",\n \"Price\": 2....
[ 0, 0 ]
[]
[]
[ "dictionary", "for_loop", "list", "python" ]
stackoverflow_0074237025_dictionary_for_loop_list_python.txt
Q: Python's equivalent of Typescript's Parameters utility type? Imagine a library like: class FooSdk: def __init__(config_a: something, config_b: something_else, **kwargs): pass # ... And you have your own utility function like: def do_something_with_foo(foo_config, another_argument: List): temp_foo = Fo...
Python's equivalent of Typescript's Parameters utility type?
Imagine a library like: class FooSdk: def __init__(config_a: something, config_b: something_else, **kwargs): pass # ... And you have your own utility function like: def do_something_with_foo(foo_config, another_argument: List): temp_foo = FooSdk(**foo_config) # ... do something with another_arguemnt an...
[ "Since Python 3.8, we have access to typing.TypedDict as proposed by PEP 589.\nfrom typing import TypedDict\n\nclass Foo:\n def __init__(self, a: int, b: str) -> None:\n pass\n\nclass FooInit(TypedDict):\n a: int\n b: str\n\ndef construct_foo(foo_init: FooInit) -> Foo:\n return Foo(**foo_init)\n\...
[ 0 ]
[]
[]
[ "python", "python_typing" ]
stackoverflow_0074275831_python_python_typing.txt
Q: Removing duplicates in lists How can I check if a list has any duplicates and return a new list without duplicates? A: The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct objects. To create a set from any iterable, you can simply pass it to the buil...
Removing duplicates in lists
How can I check if a list has any duplicates and return a new list without duplicates?
[ "The common approach to get a unique collection of items is to use a set. Sets are unordered collections of distinct objects. To create a set from any iterable, you can simply pass it to the built-in set() function. If you later need a real list again, you can similarly pass the set to the list() function.\nThe fol...
[ 2149, 477, 215, 117, 103, 48, 38, 34, 31, 31, 24, 22, 16, 13, 13, 10, 10, 10, 10, 8, 7, 7, 6, 6, 6, 5, 5, 5, 4, 4, 4, 4, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "list_with_unique_items = list(set(list_with_duplicates))\n\n", "Test = [1,8,2,7,3,4,5,1,2,3,6]\nTest.sort()\ni=1\nwhile i< len(Test):\n if Test[i] == Test[i-1]:\n Test.remove(Test[i])\n i= i+1\nprint(Test)\n\n", "Check for the string 'a' and 'b'\nclean_list = []\n for ele in raw_list:\n if 'b' i...
[ -1, -1, -1, -1, -2 ]
[ "algorithm", "duplicates", "intersection", "list", "python" ]
stackoverflow_0007961363_algorithm_duplicates_intersection_list_python.txt
Q: Pyautogui not properly moving the mouse in Roblox I'm writing code in python to help me accomplish something in a Roblox game. I won't go into too much detail, but basically, the objective is to automatically click at certain points in the screen. To try to accomplish this, I am using pyautogui.click(). So for ins...
Pyautogui not properly moving the mouse in Roblox
I'm writing code in python to help me accomplish something in a Roblox game. I won't go into too much detail, but basically, the objective is to automatically click at certain points in the screen. To try to accomplish this, I am using pyautogui.click(). So for instance if the point I needed to click at was (300, 500),...
[ "You have to use win32api and win32con for moving and clicking the mouse, as pyautogui is sometimes slow, so I am using win32api instead.\nThis is the code I used.\nfrom pyautogui import *\nimport pyautogui\nimport time\nimport win32api, win32con\n\ndef click(x,y):\n win32api.SetCursorPos((x,y)) \n win32api.m...
[ 0, 0, 0 ]
[]
[]
[ "mouse", "python", "roblox" ]
stackoverflow_0069080495_mouse_python_roblox.txt
Q: Can you safely read utf8 and latin1 files with a naïve try-except block? I believe that any valid latin1 character will either be interpreted correctly by Python's utf8 encoder or throw an error. I, therefore, claim that if you work with only either utf8 files or latin1 files, you can safely write the following co...
Can you safely read utf8 and latin1 files with a naïve try-except block?
I believe that any valid latin1 character will either be interpreted correctly by Python's utf8 encoder or throw an error. I, therefore, claim that if you work with only either utf8 files or latin1 files, you can safely write the following code to read those files, without ending up with Mojibake: from pathlib import P...
[ "Theoretically, there are valid Latin-1 sequences which are also valid UTF-8 sequences. In practice, these are very unlikely in any real-world textual data.\nYou can easily create a table of the possible combinations; here is a sample for tasting.\n>>> for x in \"\\u00a0\\u00a1\\u00a2\\u00ff\\u1234\\U00012345\":\n....
[ 3, 3, 3 ]
[]
[]
[ "iso_8859_1", "python", "utf_8" ]
stackoverflow_0074276512_iso_8859_1_python_utf_8.txt
Q: Inconsistent "OSError: [Errno 22] Invalid argument" error The add_to_log function defined in the following code is called thousands of times during the execution of a script: LOGFILENAME = 'N:\\Tools\\DelOldTempSave.log' def add_to_log(text): with open(LOGFILENAME, 'a') as logfile: now = str(datetime....
Inconsistent "OSError: [Errno 22] Invalid argument" error
The add_to_log function defined in the following code is called thousands of times during the execution of a script: LOGFILENAME = 'N:\\Tools\\DelOldTempSave.log' def add_to_log(text): with open(LOGFILENAME, 'a') as logfile: now = str(datetime.datetime.now().replace(microsecond=0)) logfile.write(no...
[ "\nAnd I can't trust python when writing to a text file?\n\n\nYes, it is a network drive. I want the log file to be visible to all computers.\n\nIt sounds more like you can't trust your network file system. Reliably appending to a file would require a (distributed network) lock to be taken out on the file, anyway, ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074268609_python.txt
Q: read_csv() got an unexpected keyword argument 'on_bad_lines' I am trying to read multiple dataframes in an list like the following: for i in excels: df2 = pd.read_csv(i, on_bad_lines='skip') dfs.append(df2) and it is working fine while running it locally but when on the deployement it shows the following ...
read_csv() got an unexpected keyword argument 'on_bad_lines'
I am trying to read multiple dataframes in an list like the following: for i in excels: df2 = pd.read_csv(i, on_bad_lines='skip') dfs.append(df2) and it is working fine while running it locally but when on the deployement it shows the following error: TypeError at /rfid-dumpdownload/ read_csv() got an unexpect...
[ "Reason is use older pandas version, under pandas 1.4.0:\n\non_bad_lines{‘error’, ‘warn’, ‘skip’} or callable, default ‘error’\n\nSpecifies what to do upon encountering a bad line (a line with too many fields). Allowed values are :\n\n ‘error’, raise an Exception when a bad line is encountered.\n\n ‘w...
[ 1 ]
[ "Use error_bad_lines argument instead of on_bad_lines.\nIn the newer version of pandas error_bad_lines is replaced by on_bad_lines\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0072210768_pandas_python.txt
Q: Python Mock: mock calls counted by call_count Is there a way to get the mock calls counted by call_count in this example: from mock import MagicMock mock = MagicMock() mock.get_query(arg=1).execute() mock.get_query(arg=2).execute() print('count:', mock.get_query.call_count) print('calls:', mock.get_query.mock_ca...
Python Mock: mock calls counted by call_count
Is there a way to get the mock calls counted by call_count in this example: from mock import MagicMock mock = MagicMock() mock.get_query(arg=1).execute() mock.get_query(arg=2).execute() print('count:', mock.get_query.call_count) print('calls:', mock.get_query.mock_calls) Actual result: count: 2 calls: [call(arg=1), ...
[ "It looks like you're looking for a list of call() objects corresponding to each call made to mock.get_query. I think that mock.get_query.call_args_list will give you what you want:\n>>> from mock import MagicMock\n>>> mock = MagicMock()\n>>> mock.get_query(arg=1).execute()\n<MagicMock name='mock.get_query().execut...
[ 1 ]
[]
[]
[ "python", "python_unittest", "python_unittest.mock", "unit_testing" ]
stackoverflow_0074266599_python_python_unittest_python_unittest.mock_unit_testing.txt
Q: Failed to call a function in Python, using Cocotb library I am using Cocotb to verify an RTL design. I have problem calling the multi() function in Python, see the code and the error I get below..... Code: @cocotb.test() async def test(dut) for i in range(10): #something for j i in range(10): ...
Failed to call a function in Python, using Cocotb library
I am using Cocotb to verify an RTL design. I have problem calling the multi() function in Python, see the code and the error I get below..... Code: @cocotb.test() async def test(dut) for i in range(10): #something for j i in range(10): #something #------------------ outpu...
[ "You have an obvious typo multi =( - remove the =.\nAlso, you most likely don't want to use asyncio.sleep but instead instruct the simulator to wait for a while using e.g. https://docs.cocotb.org/en/stable/triggers.html?highlight=timer#cocotb.triggers.Timer\n" ]
[ 1 ]
[]
[]
[ "cocotb", "python" ]
stackoverflow_0074274097_cocotb_python.txt
Q: A variable in a Python conditional statement A variable in a Python conditional statement. Hello my friends How can I define a condition with a variable in Python? One of my algorithms will have 1000 bets. I want to throw an expression in the loop and the indices of the variables will change. A: You can use := a...
A variable in a Python conditional statement
A variable in a Python conditional statement. Hello my friends How can I define a condition with a variable in Python? One of my algorithms will have 1000 bets. I want to throw an expression in the loop and the indices of the variables will change.
[ "You can use := as follow\n\nif (a := 1) == 1:\n print(\"True\") # True\n\nprint(a) # 1\n\n\n" ]
[ 1 ]
[]
[]
[ "conditional_statements", "if_statement", "python" ]
stackoverflow_0074276824_conditional_statements_if_statement_python.txt
Q: split a pandas column in to columns I want to get the area of the image as follows: labeled_mask, num_labels = ndimage.label(mask, structure=s) clusters = measure.regionprops(labeled_mask, image) propList = ['Area', 'MajorAxisLength', 'MinorAxisLength', 'Centroid'] output_file =...
split a pandas column in to columns
I want to get the area of the image as follows: labeled_mask, num_labels = ndimage.label(mask, structure=s) clusters = measure.regionprops(labeled_mask, image) propList = ['Area', 'MajorAxisLength', 'MinorAxisLength', 'Centroid'] output_file = open('draft_Stelle_measurements.csv', 'w...
[ "Instead of the measure.regionprops method, I used the measure.regionprops_table and produce the data in the correct format.\nprops = measure.regionprops_table(labeled_mask, image, properties=('area',\n 'axis_major_length',\n ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074275117_pandas_python.txt
Q: Can you explain me why outpot is so? if __name__ == '__main__': N = int(input()) lst = [] nums = [] for i in range(N): a = input() temp = a.split() if 'insert' in temp: lst.insert(int(temp[1]), int(temp[2])) elif 'print' in temp: nums...
Can you explain me why outpot is so?
if __name__ == '__main__': N = int(input()) lst = [] nums = [] for i in range(N): a = input() temp = a.split() if 'insert' in temp: lst.insert(int(temp[1]), int(temp[2])) elif 'print' in temp: nums.append(lst) elif 'remove' in tem...
[ "Two things that need to change:\n\nlst.reverse() instead of lst = lst.reverse()\nAs you are appending, removing etc. to lst, the list that you saved in nums will change with it. You need to use nums.append(lst.copy()) instead of nums.append(lst)\n\nThe full code becomes:\nif __name__ == '__main__':\n N = int(in...
[ -1 ]
[]
[]
[ "python" ]
stackoverflow_0074276662_python.txt
Q: Searching by both class and range in XPath I am currently doing a Google Play Store scraper that scrapes reviews from a particular app and writes the reviews to a file. To do that, I used Python Selenium to search for all the reviews here: https://play.google.com/store/apps/details?id=com.grabtaxi.passenger&showAl...
Searching by both class and range in XPath
I am currently doing a Google Play Store scraper that scrapes reviews from a particular app and writes the reviews to a file. To do that, I used Python Selenium to search for all the reviews here: https://play.google.com/store/apps/details?id=com.grabtaxi.passenger&showAllReviews=true, and thereafter extracted out all ...
[ "There are multiple different ways to improve on performance here:\n\nfirst scroll up until you got all the reviews (or a certain number) and only then extract them\nlet HTML parsers do the HTML parsing which would let you cut down on the number of JSON over HTTP selenium commands and other overhead of finding elem...
[ 3, 0 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0053112016_python_selenium_xpath.txt
Q: New to Python-My code to create a new duplicate free dictionary in Python is giving error Here is my code to create a dictionary with no duplicates. I am getting error AttributeError: 'dict' object has no attribute 'append'. Thank you for your help. mydict = {"c" : "2", "b" : "3", ...
New to Python-My code to create a new duplicate free dictionary in Python is giving error
Here is my code to create a dictionary with no duplicates. I am getting error AttributeError: 'dict' object has no attribute 'append'. Thank you for your help. mydict = {"c" : "2", "b" : "3", "a" : "4", "d" : "1", "e" : "1", "f" ...
[ "As the error says, dict has no append method. You are probably thinking of a list. Also, because python dicts cannot have duplicate keys, your dup_free dict will always be the same as your mydict.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074276883_python.txt
Q: IFFT of Hermitian matrix in numpy I read in a paper the IFFT of a Hermitian matrix is a matrix of all reals. But I'm not able to reproduce this in Python using numpy. # Hermitian matrix: https://en.wikipedia.org/wiki/Hermitian_matrix m = [[2 , 2 + 1j, 4 ], [2 - 1j, 3 , 0 + 1j], [4 , 0 -...
IFFT of Hermitian matrix in numpy
I read in a paper the IFFT of a Hermitian matrix is a matrix of all reals. But I'm not able to reproduce this in Python using numpy. # Hermitian matrix: https://en.wikipedia.org/wiki/Hermitian_matrix m = [[2 , 2 + 1j, 4 ], [2 - 1j, 3 , 0 + 1j], [4 , 0 - 1j, 1 ]] m = numpy.matrix(m) im =...
[ "I think the paper referred to something slightly different. A Hermitian matrix is one that that's equal to its complex conjugate transpose. However, the fft of real input is \"Hermite-symmetric\". It's equal to its complex conjugate, but not its complex conjugate transpose. \nOn a side note, I may be getting t...
[ 4, 0 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0032403461_matrix_numpy_python.txt
Q: How to invert a matrix with transfer functions in python? I know that in matlab I can do the following: s = tf('s') G11 = (s + 1)/(s + 2) G12 = 1/(2*s + 1) G21 = 1/(3*s + 1) G22 = 1/(4*s + 1) A = [G11 G12; G21, G22] Ai = inv(A) bode(A) and it will work just fine. In python, I tried to do something similar: impor...
How to invert a matrix with transfer functions in python?
I know that in matlab I can do the following: s = tf('s') G11 = (s + 1)/(s + 2) G12 = 1/(2*s + 1) G21 = 1/(3*s + 1) G22 = 1/(4*s + 1) A = [G11 G12; G21, G22] Ai = inv(A) bode(A) and it will work just fine. In python, I tried to do something similar: import control as co import numpy as np s = co.tf('s') G11 = (s + 1...
[ "Numpy (hint: it's right in the name) is a numerics library only; it does not do symbolic math. Sympy (also in the name) does symbolic math, so use it:\nimport sympy\n\ns = sympy.Symbol('s', imaginary=True)\ng11 = (s + 1)/(s + 2)\ng12 = 1/(2*s + 1)\ng21 = 1/(3*s + 1)\ng22 = 1/(4*s + 1)\nA = sympy.Matrix((\n (g11...
[ 4, 1 ]
[]
[]
[ "controls", "linear_algebra", "matlab", "numpy", "python" ]
stackoverflow_0074275353_controls_linear_algebra_matlab_numpy_python.txt
Q: How to give the data to serializer with JSONField I have model and serializer with JSONField class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) detail = models.JSONField(default=dict) def __str__(self): return self.user.username class ProfileSerializer(Mod...
How to give the data to serializer with JSONField
I have model and serializer with JSONField class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) detail = models.JSONField(default=dict) def __str__(self): return self.user.username class ProfileSerializer(ModelSerializer): class Meta: model = m.Profil...
[ "You are giving the data in right way, but as you are updating partially, you need to pass one more parameter:\nserializer = self.get_serializer(instance, data=data1, partial=True)\n\nTo debug the is_valid method, you can either throw exceptions from it like .is_valid(raise_exception=True); or in your code, print s...
[ 2 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074276799_django_django_rest_framework_python.txt
Q: How to store and load a big variable in python? My question is related with the storage and the loading of a big variable in python. Specifically, among other variables (v1, v2), I want to store a list of nested lists (v3)(bool type). v3 = [[[False] for x in range(6000)] for x in range(6000)] Then, I perform some...
How to store and load a big variable in python?
My question is related with the storage and the loading of a big variable in python. Specifically, among other variables (v1, v2), I want to store a list of nested lists (v3)(bool type). v3 = [[[False] for x in range(6000)] for x in range(6000)] Then, I perform some operation so I change some of the False values into ...
[ "If you are working with arrays, then I would suggest using numpy. One can use numpy.savez() to save multiple arrays into the same file.\nimport numpy as np\n\n# Create the data.\nv2 = np.full((6000, 6000, 1), fill_value=True)\nv3 = np.full((6000, 6000, 1), fill_value=False)\n\n# Save the data.\nnp.savez(\"data.npz...
[ 0 ]
[]
[]
[ "list", "pickle", "python" ]
stackoverflow_0074276295_list_pickle_python.txt
Q: Install TensorFlow latest build using Mamba I want to use mamba install to install the latest TensorFlow distribution (2.10 or 2.9.1 at least) with CUDA enabled. I tried the following: mamba install -c anaconda tensorflow==2.9.1=gpu_py310* mamba install -c anaconda tensorflow=2.9.1=gpu_py310* mamba install -c an...
Install TensorFlow latest build using Mamba
I want to use mamba install to install the latest TensorFlow distribution (2.10 or 2.9.1 at least) with CUDA enabled. I tried the following: mamba install -c anaconda tensorflow==2.9.1=gpu_py310* mamba install -c anaconda tensorflow=2.9.1=gpu_py310* mamba install -c anaconda tensorflow=2.9.1=gpu_py310 mamba install ...
[ "I figured it out, just had to use -c main instead of -c anaconda. The command is as follows:\nmamba install -c main tensorflow==2.9.1=gpu_py310*\n\nIt installs the desired version.\n" ]
[ 1 ]
[]
[]
[ "conda", "mamba", "python", "tensorflow" ]
stackoverflow_0074270621_conda_mamba_python_tensorflow.txt
Q: Finding specific array or list in a numpy array I have a list of numpy arrays, which consists of all possible configurations of 0 and 1 in a 10-pixel arrays. I'm trying to determine the number of arrays that have specific group of 1s for more than two 1s. For example, the array is [1,0,0,1,1,1,1,1,0,1]. I want to ...
Finding specific array or list in a numpy array
I have a list of numpy arrays, which consists of all possible configurations of 0 and 1 in a 10-pixel arrays. I'm trying to determine the number of arrays that have specific group of 1s for more than two 1s. For example, the array is [1,0,0,1,1,1,1,1,0,1]. I want to determine this array has five 1s as a block. Another ...
[ "convert the array to a string and check for membership along the lines of:\nstr_array = ''.join(my_array)\nreturn 5*'1' in str_array\n\n", "Try below approach.\nIts not very efficient, but it should work.\nfrom functools import reduce\nimport numpy as np\nfrom itertools import product\n\nn=int(input(\"How many 1...
[ 1, 1 ]
[]
[]
[ "arrays", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074276855_arrays_numpy_numpy_ndarray_python.txt
Q: Remove dictionaries from a list of dictionaries under certain conditions I have a very large list of dictionaries that looks like this (I show a simplified version): list_of_dicts: [{'ID': 1234, 'Name': 'Bobby', 'Animal': 'Dog', 'About': [{'ID': 5678, 'Food': 'Dog Food'}]}, {'ID': 5678, 'Food': 'Dog Food'},...
Remove dictionaries from a list of dictionaries under certain conditions
I have a very large list of dictionaries that looks like this (I show a simplified version): list_of_dicts: [{'ID': 1234, 'Name': 'Bobby', 'Animal': 'Dog', 'About': [{'ID': 5678, 'Food': 'Dog Food'}]}, {'ID': 5678, 'Food': 'Dog Food'}, {'ID': 91011, 'Name': 'Jack', 'Animal': 'Bird', 'About': [{'ID': 1996,...
[ "You can use a list comprehension:\ncleaned_list = [d for d in list_of_dicts if d['ID'] not in nested_ids]\n\n", "It is happening because we are modifying the dict while iterating it, So to avoid that we can copy the required values to a new dict as follow\nfiltered_dicts = []\nnested_ids = [5678, 1996, 2008]\nfo...
[ 3, 2, 1 ]
[]
[]
[ "dictionary", "list", "loops", "python" ]
stackoverflow_0074276961_dictionary_list_loops_python.txt
Q: Static files are not loading from Static folder I am Building a BlogApp and I am stuck on an Problem. The Problem Static Files are not loading from static folder. Some files are loading but some are not loading. What have i done ? urls.py I also put static url in urls.py , it also didn't work for me. urlpatterns +...
Static files are not loading from Static folder
I am Building a BlogApp and I am stuck on an Problem. The Problem Static Files are not loading from static folder. Some files are loading but some are not loading. What have i done ? urls.py I also put static url in urls.py , it also didn't work for me. urlpatterns += static(settings.STATIC_URL, document_root=settings....
[ "make sure that your settings.py has the following\nsettings.py\nfrom pathlib import Path\nimport os\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\nTEMPLATE_DIR = os.path.join(BASE_DIR,\"templates\")\nSTATIC_DIR = os.path.join(BASE_DIR,\"stati...
[ 1, 0 ]
[]
[]
[ "django", "django_settings", "django_urls", "python", "static" ]
stackoverflow_0066381380_django_django_settings_django_urls_python_static.txt
Q: DLL load failed while importing libtorrent: The specified module could not be found import libtorrent ImportError Traceback (most recent call last) Input In [2], in <cell line: 1>() ----> 1 import libtorrent ImportError: DLL load failed while importing libtorrent: The specified module could not be found. I am get...
DLL load failed while importing libtorrent: The specified module could not be found
import libtorrent ImportError Traceback (most recent call last) Input In [2], in <cell line: 1>() ----> 1 import libtorrent ImportError: DLL load failed while importing libtorrent: The specified module could not be found. I am getting this error while importing libtorrent.. plz someone help me to solve this issue
[ "You probably just need to install or reinstall libtorrent using pip.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074276726_python.txt
Q: How do I convert a string response size to MB in Python? I am doing a bit of a scraping project where I am scraping some data file information. The issue is that the response is a string that is sometimes in kB, MB, GB etc. What I need is to convert the response I get to MB and drop the text part eg. 290.5kB shoul...
How do I convert a string response size to MB in Python?
I am doing a bit of a scraping project where I am scraping some data file information. The issue is that the response is a string that is sometimes in kB, MB, GB etc. What I need is to convert the response I get to MB and drop the text part eg. 290.5kB should return 0.29 without MB at the end. The scraped section looks...
[ "You can do it by float(f_file_size[:-2]) as follow\nf_file_size = file_format.split('Format: ')[1].split(',')[1].strip(' ()')\n\n\noutput_dict['data_files'].append({'file_size': float(f_file_size[:-2])})\n\n", "We can use re.sub here with a callback function:\ndef repl(m):\n val = float(m.group(1))\n unit ...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0074276909_python.txt
Q: numpy standard deviation does not give the same result as scipy stats standard deviation Scipy and numpy standard deviation methods give slightly different results. I don't understand why. Can anyone explain that to me? Here is an example. import numpy as np import scipy.stats ar = np.arange(20) print(np.std(ar)) ...
numpy standard deviation does not give the same result as scipy stats standard deviation
Scipy and numpy standard deviation methods give slightly different results. I don't understand why. Can anyone explain that to me? Here is an example. import numpy as np import scipy.stats ar = np.arange(20) print(np.std(ar)) print(scipy.stats.tstd(ar)) returns 5.766281297335398 5.916079783099616
[ "It's in my mind a while ago..To get the same values\nimport numpy as np\nimport scipy.stats\nar = np.arange(20)\nprint(np.std(ar, ddof=1))\nprint(scipy.stats.tstd(ar))\n\noutput #\n5.916079783099616\n5.916079783099616\n\nMy mentor use to say\n\n-->ddof=1 if you're calculating np.std() for a sample taken from your ...
[ 3, 2 ]
[]
[]
[ "numpy", "python", "scipy", "statistics" ]
stackoverflow_0074276989_numpy_python_scipy_statistics.txt
Q: Can a large npy file be converted into small npy files? I have a large npy file with 33,696 lines of data. I would like to separate this into 18 small files with 1872 lines of data in each. I have tried to use the same codes for converting a large text file into small text files but I am not able to receive the ou...
Can a large npy file be converted into small npy files?
I have a large npy file with 33,696 lines of data. I would like to separate this into 18 small files with 1872 lines of data in each. I have tried to use the same codes for converting a large text file into small text files but I am not able to receive the output that I want. What alternative codes can be used to achie...
[ "A npy file is a binary format file that must be loaded as a whole. On the other hand, a text file should be read one line at a time. That means that you cannot expect that a code expecting text file to correctly process binary npy files.\nHere you should:\n\nload the npy file into a large numpy array (numpy.load)\...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074276451_arrays_numpy_python.txt
Q: I need to constantly move a character from the left to the right of the screen without touching anything In pygame. I need loop that does that I tried diferent technics but still don't get it. This function is in a class Player() so it moves the player from left to right automatically def move(self): d...
I need to constantly move a character from the left to the right of the screen without touching anything In pygame. I need loop that does that
I tried diferent technics but still don't get it. This function is in a class Player() so it moves the player from left to right automatically def move(self): dx = 0 dy = 0 # CHECKING THE RECT IF HAS HIT THE BORDERS if self.rect.left + dx < 0: pass # CHAN...
[ "You don't nee any extra loop. Use the application loop. Redraw the entire scene in each frame. Change the position of the object slightly in each frame. Since the object is drawn at a different position in each frame, the object appears to move smoothly. Limit frames per second to limit CPU usage and control the s...
[ 1, 0 ]
[]
[]
[ "loops", "pygame", "python" ]
stackoverflow_0074277026_loops_pygame_python.txt
Q: How to map color names with their HEX to make a conditionnal formating I have the dataframe below: import pandas as pd df = pd.DataFrame({'ID': ['ID001', 'ID002', 'ID003', 'ID004', 'ID005', 'ID006'], 'Color': ['Red', 'Green', 'Blue', 'Green', 'Yellow', 'Purple']}) ID Color 0 ID001 ...
How to map color names with their HEX to make a conditionnal formating
I have the dataframe below: import pandas as pd df = pd.DataFrame({'ID': ['ID001', 'ID002', 'ID003', 'ID004', 'ID005', 'ID006'], 'Color': ['Red', 'Green', 'Blue', 'Green', 'Yellow', 'Purple']}) ID Color 0 ID001 Red 1 ID002 Green 2 ID003 Blue 3 ID004 Green 4 ID005 Yellow 5 ...
[ "Matplotlib can convert color names to RGB and hex values for you\n>>> from matplotlib import colors\n>>> \n>>> colors.to_rgb('blue')\n(0.0, 0.0, 1.0)\n>>> \n>>> colors.to_hex('blue')\n'#0000ff'\n\n", "Thanks to @jprebys's answer above and @Sergey's here, I ended up with this code:\nimport pandas as pd\nfrom matp...
[ 2, 1 ]
[]
[]
[ "excel", "openpyxl", "pandas", "python", "xlsxwriter" ]
stackoverflow_0074276714_excel_openpyxl_pandas_python_xlsxwriter.txt
Q: How to use AWS Lambda synchronously with AWS Glue I have a lambda function that executes a crawler, SNS job and ETL. Is there any way to make the lambda function wait for the crawler to finish first before the SNS and ETL? Thanks I currently don't have the IAM access for step functions yet but still require this t...
How to use AWS Lambda synchronously with AWS Glue
I have a lambda function that executes a crawler, SNS job and ETL. Is there any way to make the lambda function wait for the crawler to finish first before the SNS and ETL? Thanks I currently don't have the IAM access for step functions yet but still require this to be done. Currently it just all executes in one go the...
[ "Either you can use this answer to do it really synchronous (waiting for Glue Crawler to finish inside the Lambda) or, if the Crawler takes to long and the Lambda times out, you create separate Lambdas for starting the crawler and ETL, and let the ETL Lambda be invoked by an EventBridge rule.\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "asynchronous", "aws_glue", "aws_lambda", "python" ]
stackoverflow_0074276859_amazon_web_services_asynchronous_aws_glue_aws_lambda_python.txt
Q: How to get pdf filename with Python requests? I'm using the Python requests library to get a PDF file from the web. This works fine, but I now also want the original filename. If I go to a PDF file in Firefox and click download it already has a filename defined to save the pdf. How do I get this filename? For exam...
How to get pdf filename with Python requests?
I'm using the Python requests library to get a PDF file from the web. This works fine, but I now also want the original filename. If I go to a PDF file in Firefox and click download it already has a filename defined to save the pdf. How do I get this filename? For example: import requests r = requests.get('http://www.r...
[ "It is specified in an http header content-disposition. So to extract the name you would do:\nimport re\nd = r.headers['content-disposition']\nfname = re.findall(\"filename=(.+)\", d)[0]\n\nName extracted from the string via regular expression (re module).\n", "Building on some of the other answers, here's how I ...
[ 94, 19, 12, 8, 5, 0, 0 ]
[]
[]
[ "filenames", "pdf", "python", "python_requests" ]
stackoverflow_0031804799_filenames_pdf_python_python_requests.txt
Q: Python cross-correlation not returning correct shift I'm learning about cross-correlation, and to do so I'm running scipy.signal.correlate on some simple examples. However, there are instances for which the maximum of the correlation function does not coincide with the input time shift (even though the correct tim...
Python cross-correlation not returning correct shift
I'm learning about cross-correlation, and to do so I'm running scipy.signal.correlate on some simple examples. However, there are instances for which the maximum of the correlation function does not coincide with the input time shift (even though the correct time shift IS present in dt). I suspect the issue lies in my ...
[ "The truncation effect for y2 leads to this result.\nif you set the t in wider range like:\nt = np.linspace(0.,20.*np.pi,100)\n\nyou can get the right results\n" ]
[ 0 ]
[]
[]
[ "cross_correlation", "python" ]
stackoverflow_0044013166_cross_correlation_python.txt
Q: How do I fix this guessing game of numbers 1 - 50? The following project requires: Your program should implement a simple guessing game with the following requirements: Generate a random number between 1 and 50 and then have the user guess the number. The program should tell the user whether they have guessed too ...
How do I fix this guessing game of numbers 1 - 50?
The following project requires: Your program should implement a simple guessing game with the following requirements: Generate a random number between 1 and 50 and then have the user guess the number. The program should tell the user whether they have guessed too high or too low and allow them to continue to guess unti...
[ "First issue is that your while cycle only lasts until a number is guessed. So that means after you guess the first random number, your program will finish.\nIn order to avoid that you should declare your $play = True$ boolean on top of the cycle so you can declare your while cycle something like this:\n play = ...
[ 1 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074269761_python_random.txt
Q: List comprehension correct format to include extended expression I ma trying to iterate through a list of numbers to calculate the largest number, using list comprehension, but the syntax seems to be evading me. Precisely, I am not able to figure out where to place the expression. I am trying to use a counter, and...
List comprehension correct format to include extended expression
I ma trying to iterate through a list of numbers to calculate the largest number, using list comprehension, but the syntax seems to be evading me. Precisely, I am not able to figure out where to place the expression. I am trying to use a counter, and store the largest number of the list in the counter. Is there a probl...
[ "List comprehensions are not built for this. You can make something work by using a helper function and a global variable. The result is a list of maxima so far. The last element is the global max.\nresult = float('-inf')\n\ndef check(n):\n global result\n if result < n:\n result = n\n return Tr...
[ 0 ]
[ "Easy way is to sort a/the list in place.\nExample in phyton:\n>>> a = [1,2,3,4,5,6,722,4,35,353,5,4634,64,64,634,4,3]\n>>> a.sort()\n>>> a\n[1, 2, 3, 3, 4, 4, 4, 5, 5, 6, 35, 64, 64, 353, 634, 722, 4634]\n>>> a[-1]\n4634\n>>> b = sorted(a, reverse=True)\n>>> b\n[4634, 722, 634, 353, 64, 64, 35, 6, 5, 5, 4, 4, 4, 3...
[ -1 ]
[ "python" ]
stackoverflow_0074277280_python.txt
Q: Python os.path.exists fails with relative path with multiple "..", but works with absolute path I am doing a simple os.path.exists() call but it's failing for a relative path with multiple .. while it succeeds with the absolute path. I've tested and found that the path is too long with the relative path. If I take...
Python os.path.exists fails with relative path with multiple "..", but works with absolute path
I am doing a simple os.path.exists() call but it's failing for a relative path with multiple .. while it succeeds with the absolute path. I've tested and found that the path is too long with the relative path. If I take off characters (extra in the example below) of the filename it works. The examples below aren't exac...
[ "I solved this issue by adding os.path.abspath in front of each relative path. I'm assuming each .. was being evaluated as a whole path.\nos.path.exists(os.path.abspath(r'..\\..\\..\\..\\folder1\\folder2\\folder3\\folder4\\myfilename_extra.txt')) # now succeeds\n" ]
[ 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0074277146_path_python.txt
Q: Python can't find module in the same folder My python somehow can't find any modules in the same directory. What am I doing wrong? (python2.7) So I have one directory '2014_07_13_test', with two files in it: test.py hello.py where hello.py: # !/usr/local/bin/python # -*- coding: utf-8 -*- def hello1(): pri...
Python can't find module in the same folder
My python somehow can't find any modules in the same directory. What am I doing wrong? (python2.7) So I have one directory '2014_07_13_test', with two files in it: test.py hello.py where hello.py: # !/usr/local/bin/python # -*- coding: utf-8 -*- def hello1(): print 'HelloWorld!' and test.py: # !/usr/local/bin/...
[ "Change your import in test.py to:\nfrom .hello import hello1\n\n", "Your code is fine, I suspect your problem is how you are launching it.\nYou need to launch python from your '2014_07_13_test' directory.\nOpen up a command prompt and 'cd' into your '2014_07_13_test' directory.\nFor instance:\n$ cd /path/to/2014...
[ 185, 111, 40, 35, 13, 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0024722212_module_python.txt
Q: Increasing the constant rows for a dataframe I have two datasets where the first dataset value is changing according to the number of objects I detected. My second dataset is a constant value where these columns should be joined with the first dataset. Now the problem is that if I have 50 rows in the first dataset...
Increasing the constant rows for a dataframe
I have two datasets where the first dataset value is changing according to the number of objects I detected. My second dataset is a constant value where these columns should be joined with the first dataset. Now the problem is that if I have 50 rows in the first dataset and 20 rows in the second dataset. How are the re...
[ "To fill constant values? You mean you need to fill that Extra Nan with constant values that are above?\nIf so\ndf_join=df_join.fillna(method='ffill')\ndf_join.head()\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074277377_pandas_python.txt
Q: I need to validate data is in JSON format in python I'm making a program that needs to validate that certain data is in json format. What's in the json does not mater and will change each time a user runs the program. Could anyone provide examples of ways to validate that data is in a json format? Currently attemp...
I need to validate data is in JSON format in python
I'm making a program that needs to validate that certain data is in json format. What's in the json does not mater and will change each time a user runs the program. Could anyone provide examples of ways to validate that data is in a json format? Currently attempting to use the jsonschema library.
[ "Use json.loads\n\nIf the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.\n\n", ">> f = open(\"data.json\")\n\n>> load_f = json.load(f)\n\n>> isinstance(load_f, dict)\n\n>> True\n\n", "import json\n\nvalid_json_example: str = '{\"example\":\"json_format\"}'\ninvalid_json_...
[ 0, 0, 0 ]
[]
[]
[ "automation", "json", "python", "python_3.x" ]
stackoverflow_0074277009_automation_json_python_python_3.x.txt
Q: Clean up irregularities in dictionary values using regex I need to create a dictionary from a text file that contains coordinates for named polygons. The output needs to be a dictionary where the polygon name is the key and corresponding x and y coordinates are the values. Most of the entries in the file follow a ...
Clean up irregularities in dictionary values using regex
I need to create a dictionary from a text file that contains coordinates for named polygons. The output needs to be a dictionary where the polygon name is the key and corresponding x and y coordinates are the values. Most of the entries in the file follow a standard layout as follows: Name of polygon (12.345, 1.2567) (...
[ "I think I've found a solution to my problem. I needed to account for multiple values per key in the loop and use re.findall() instead of re.split(). So my final loop looks like:\nfor key, *value in d.items():\n d[key] = re.findall(\"\\(.+\\)\", str(value))\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "loops", "python", "regex" ]
stackoverflow_0074275870_dictionary_loops_python_regex.txt
Q: ERROR: Could not build wheels for pandas, which is required to install pyproject.toml-based projects I'm trying to install pandas via pip install pandas on my laptop. Environment: Window 11 Pro Python 3.10.4 Pip version 22.0.4 Compatibility: Officially Python 3.8, 3.9 and 3.10. You must have pip>=19.3 to instal...
ERROR: Could not build wheels for pandas, which is required to install pyproject.toml-based projects
I'm trying to install pandas via pip install pandas on my laptop. Environment: Window 11 Pro Python 3.10.4 Pip version 22.0.4 Compatibility: Officially Python 3.8, 3.9 and 3.10. You must have pip>=19.3 to install from PyPI. C:\Users\PC>pip install pandas WARNING: Ignoring invalid distribution -ywin32 (c:\users\pc\...
[ "Pandas doesn't require Anaconda to work, but based on python310-32 in your output, you're using a 32-bit build of Python.\nPandas evidently does not ship 32-bit wheels for Python 3.10 (they do have win32 wheels for Python 3.8 and Python 3.9 though). (There could be alternate sources for pre-built 32-bit wheels, su...
[ 2, 0, 0 ]
[]
[]
[ "installation", "pandas", "pip", "python" ]
stackoverflow_0072401377_installation_pandas_pip_python.txt
Q: Count number of White Pixels per row of an image in Python I am stuck trying to count the number of white pixels per row in a image. i have tried this img = cv2.imread("11.jpg") # Its our Image object mask = np.uint8(np.where(img == 0, 1, 0)) row_counts = cv2.reduce(mask, 1, cv2.REDUCE_SUM, dtype=cv2.CV_32SC1) # ...
Count number of White Pixels per row of an image in Python
I am stuck trying to count the number of white pixels per row in a image. i have tried this img = cv2.imread("11.jpg") # Its our Image object mask = np.uint8(np.where(img == 0, 1, 0)) row_counts = cv2.reduce(mask, 1, cv2.REDUCE_SUM, dtype=cv2.CV_32SC1) # type: ignore #Data Collection White_row = 224- row_counts # 224 ...
[ "So i made my own loop algorithm that loops through every pixel and checks the pixel intensity. The image is converted into grey scale.\nimg = Image.open(\"11.jpg\")\nimg = img.convert(\"L\") # convert to grayscale\npix = img.load()\nwidth, height = img.size\nprint(width, height)\nprint(pix[91,134]) #Tester\nWhite...
[ 0 ]
[]
[]
[ "count", "opencv", "pixel", "python" ]
stackoverflow_0074276443_count_opencv_pixel_python.txt
Q: tensorflowjs output different result compared to python tensorflow Background: I'm trying to build a chrome extension that filter images on websites visited by user. The process basically is to get the image data, pass through my trained model (transfer learning from keras), and output the predicted class. In the ...
tensorflowjs output different result compared to python tensorflow
Background: I'm trying to build a chrome extension that filter images on websites visited by user. The process basically is to get the image data, pass through my trained model (transfer learning from keras), and output the predicted class. In the example, i want to check if the image belongs to dog or cat. Sample targ...
[ "I realise my main issue is that i skipped over the preprocessing_input portion in python.\nOriginal preprocessing code in python\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\ntest_image = preprocess_input(test_image)\n\nTake note that preprocessing in mobilenet_v2 is between -1 to 1. He...
[ 0 ]
[]
[]
[ "google_chrome", "google_chrome_extension", "python", "tensorflow", "tensorflow.js" ]
stackoverflow_0074272797_google_chrome_google_chrome_extension_python_tensorflow_tensorflow.js.txt
Q: Why is my recursion not working Selenium (python)? I'm new to Selenium, I'm trying to crawl into a website to index things, but my recursion is only giving me the first element of each categories : def crawl_table(driver, max_depths) : liste_lien = driver.find_elements(By .TAG_NAME, 'table') if (list...
Why is my recursion not working Selenium (python)?
I'm new to Selenium, I'm trying to crawl into a website to index things, but my recursion is only giving me the first element of each categories : def crawl_table(driver, max_depths) : liste_lien = driver.find_elements(By .TAG_NAME, 'table') if (liste_lien == "" or max_depths == 0): return get_fi...
[ "Actually the link were stored in one bloc so find_element was taking the element at the top and was done, I used the find_elements function and went through the links to do the recursion :\n\ndef crawl_table(driver, max_depths) : \n liste_lien = driver.find_elements(By .TAG_NAME, 'table')\n if (liste_lien ==...
[ 0 ]
[]
[]
[ "python", "recursion", "selenium" ]
stackoverflow_0074154151_python_recursion_selenium.txt
Q: Sympy relationals as_set within an interval As the title, I want to get intervals of sin(x) < 0 in [-5, 5] from sympy import Symbol, sin x = Symbol("x") y = sin(x) < 0 y.as_set() This will give an error because of periodic solutions, is there a way to do something like this? y.as_set([-5, 5]) # -> (-pi, 0) ∪ (p...
Sympy relationals as_set within an interval
As the title, I want to get intervals of sin(x) < 0 in [-5, 5] from sympy import Symbol, sin x = Symbol("x") y = sin(x) < 0 y.as_set() This will give an error because of periodic solutions, is there a way to do something like this? y.as_set([-5, 5]) # -> (-pi, 0) ∪ (pi, 5] Thank you!
[ "There is no built in method to do this, but you can write your own method to test the value of the function between the zeros and determine whether the interval satisfies the condition.\ndef posin(eq, r):\n assert isinstance(r, Interval)\n free = eq.free_symbols\n assert len(free) == 1 # univariate\n ...
[ 0 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0074271117_python_sympy.txt
Q: I cannot sort variables according to their given numbers (zebra problem) ` import itertools def imright(h1, h2): "House h1 is immediately right of h2 if h1-h2 == 1." return h1-h2 == 1 def nextto(h1, h2): "Two houses are next to each other if they differ by 1." return abs(h1-h2) == 1 def find_water...
I cannot sort variables according to their given numbers (zebra problem)
` import itertools def imright(h1, h2): "House h1 is immediately right of h2 if h1-h2 == 1." return h1-h2 == 1 def nextto(h1, h2): "Two houses are next to each other if they differ by 1." return abs(h1-h2) == 1 def find_water_zebra(): houses = [first,_,middle,_,_] = [1,2,3,4,5] orderings = list...
[ "Instead of using tuples, I edited your output such that is a dictionary, which makes it easier to get the right words as output. I created a function to get the right output from this dictionary:\ndef print_output(output, house):\n\n key_words = ['Nations', 'Colours', 'Drinks', 'Smokes', 'Pets']\n val_words ...
[ 0 ]
[]
[]
[ "constraints", "python", "sorting", "zebra_puzzle" ]
stackoverflow_0074275828_constraints_python_sorting_zebra_puzzle.txt
Q: How to find the root cause of "Element odoo has extra content: data" The error message "Element odoo has extra content: data" may be generated if an xml file such as a view fails to validate against the RELAXNG schema file odoo/odoo/import_xml.rng. Unforunately it isn't very specific. For example, this file: <?...
How to find the root cause of "Element odoo has extra content: data"
The error message "Element odoo has extra content: data" may be generated if an xml file such as a view fails to validate against the RELAXNG schema file odoo/odoo/import_xml.rng. Unforunately it isn't very specific. For example, this file: <?xml version="1.0" encoding="utf-8"?> <odoo> <data> <record id="reco...
[ "The error message, at least on Debian Linux, is produced by LXML's RelaxNG validator, which in turn relies on libxml2. We can see that xmllint, also based on libxml2, produces the same output:\nxmllint path/to/view.xml --relaxng ./odoo/odoo/import_xml.rng \n<snip xml file content/>\npath/to/view.xml:3: element d...
[ 1 ]
[]
[]
[ "odoo", "python", "relaxng", "xml" ]
stackoverflow_0074277606_odoo_python_relaxng_xml.txt
Q: Unable to pass CS50 check for scourgify problem set 6 I am unable to pass the test even though, my code works perfectly When I checked, Below is my code.. import sys import csv def main(): n, m = passing_arg() read_file(n, m) def passing_arg(): if len(sys.argv) > 3: sys.exit("Too many command...
Unable to pass CS50 check for scourgify problem set 6
I am unable to pass the test even though, my code works perfectly When I checked, Below is my code.. import sys import csv def main(): n, m = passing_arg() read_file(n, m) def passing_arg(): if len(sys.argv) > 3: sys.exit("Too many command-line arguments") elif len(sys.argv) < 3: sys....
[ "I ran your code with before.csv and I get this in after.csv:\nFirst,Last,House\nBlaise,Zabini,Slytherin\n\nI'm not sure if that's what the automatic checker is unhappy about, though:\n\n:( scourgify.py cleans short CSV file\n\nCause\nscourgify.py does not produce CSV with specified format\nLog\nrunning python3 sco...
[ 0, 0 ]
[]
[]
[ "cs50", "csv", "python", "python_3.x" ]
stackoverflow_0074267232_cs50_csv_python_python_3.x.txt
Q: How to independently iterate each elements of python list in parralel circle_elem = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy'] I want to simultaneously cycle/rotate each element of the above list in place somthing like: circle_elem = ['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu'] circle_elem = ['cdeab', 'hijfg'...
How to independently iterate each elements of python list in parralel
circle_elem = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy'] I want to simultaneously cycle/rotate each element of the above list in place somthing like: circle_elem = ['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu'] circle_elem = ['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv'] #etc........... The length of each elements i...
[ "You need a list comprehension that shifts each string individually.\n>>> def circular_shifts(elems, step=1):\n... return [e[step%len(e):] + e[:step%len(e)] for e in elems]\n...\n>>> circle_elem = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']\n>>> for i in range(5):\n... print(circular_shifts(circle_elem, i...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074277520_python.txt
Q: Program that reads a series of lines, each one with positive integers, and outputs the sum of the first line with even number of integers ending in 3 Write a program that reads a series of lines, each of them containing a sequence of non negative integers, and prints as output the value of the sum of the first lin...
Program that reads a series of lines, each one with positive integers, and outputs the sum of the first line with even number of integers ending in 3
Write a program that reads a series of lines, each of them containing a sequence of non negative integers, and prints as output the value of the sum of the first line that contains an even number of elements ending in 3. If there is no such line, the output will be -1. For instance, for the input: 23 12 4 25 44 43 23 3...
[ "OK, first you need to know what sys.stdin.read() type --> This is a string.\nRelated: What does sys.stdin read?\nsys.stdin is similar to a file reader.\nFor your problem, we can use\nlines = sys.stdin.readlines()\n\nThis will automatically split your input into a list of string.\nYou could also use:\nlines = sys.s...
[ 0, 0 ]
[]
[]
[ "math", "python", "python_3.x" ]
stackoverflow_0074276511_math_python_python_3.x.txt
Q: Is there a generic way to execute different python files, depending on sys.args? I would like to create a python file that can be run from the terminal - this file will be in charge of running various other python files depending on the functionality required along with their required arguments, respectively. For ...
Is there a generic way to execute different python files, depending on sys.args?
I would like to create a python file that can be run from the terminal - this file will be in charge of running various other python files depending on the functionality required along with their required arguments, respectively. For example, this is the main file: import sys from midi_to_audio import arguments, run ...
[ "Your runner could look like this, to load a module by name and check it has run, and check the arguments given on the command line, and finally dispatch to the module's run function.\nimport sys\nimport importlib\n\n\ndef main():\n args = sys.argv[1:]\n if len(args) < 1:\n raise Exception(\"No module ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074277576_python.txt
Q: Generating an MD5 checksum of a file Is there any simple way of generating (and checking) MD5 checksums of a list of files in Python? (I have a small program I'm working on, and I'd like to confirm the checksums of the files). A: You can use hashlib.md5() Note that sometimes you won't be able to fit the whole fi...
Generating an MD5 checksum of a file
Is there any simple way of generating (and checking) MD5 checksums of a list of files in Python? (I have a small program I'm working on, and I'd like to confirm the checksums of the files).
[ "You can use hashlib.md5()\nNote that sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the md5 method:\nimport hashlib\ndef md5(fname):\n hash_md5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chun...
[ 629, 328, 36, 30, 20, 2, 1, 0 ]
[ "change the file_path to your file\nimport hashlib\ndef getMd5(file_path):\n m = hashlib.md5()\n with open(file_path,'rb') as f:\n lines = f.read()\n m.update(lines)\n md5code = m.hexdigest()\n return md5code\n\n" ]
[ -1 ]
[ "checksum", "hashlib", "md5", "python" ]
stackoverflow_0003431825_checksum_hashlib_md5_python.txt
Q: Torch filter multidimensional tensor by start and end values I have a list of sentences and I am looking to extract contents between two items. If the start or end item does not exist, I want it to return a row with padding only. I already have the sentences tokenized and padded with 0 to a fixed length. I figured...
Torch filter multidimensional tensor by start and end values
I have a list of sentences and I am looking to extract contents between two items. If the start or end item does not exist, I want it to return a row with padding only. I already have the sentences tokenized and padded with 0 to a fixed length. I figured a way to do this using for loops, but it is extremely slow, so wo...
[ "A possible loop-free approach is this:\nimport torch\n\n# using the provided sample data\nstart_value, end_value = 4,9\ndata = torch.tensor([\n [3,4,7,8,9,2,0,0,0,0], \n [1,5,3,4,7,2,8,9,10,0],\n [3,4,7,8,10,0,0,0,0,0], # does not contain end value\n [3,7,5,9,2,0,0,0,0,0], # does not contain start valu...
[ 1, 1 ]
[]
[]
[ "nlp", "python", "pytorch", "tensor" ]
stackoverflow_0074198404_nlp_python_pytorch_tensor.txt
Q: Simple sine calculator doesn't return the right values The math.sine module seem to return wrong values. Where did I made a mistake ? import math A = float(input("Insert a number you want the sine of")) B = math.sin(math.radians(A)) print("sin of %.2f is %.6f" % (A, B)) The result for typing 45 is 0.707 instead...
Simple sine calculator doesn't return the right values
The math.sine module seem to return wrong values. Where did I made a mistake ? import math A = float(input("Insert a number you want the sine of")) B = math.sin(math.radians(A)) print("sin of %.2f is %.6f" % (A, B)) The result for typing 45 is 0.707 instead of 0.85 I was just getting back into Python. I can't see th...
[ "Be careful, there is difference between degrees and radians. You probably confused them with each other.\nCalculate with radians:\nimport math\n\nA = float(input(\"Insert a number you want the sine of\"))\n\nB = math.sin(math.radians(A))\nprint(\"sin of %.2f is %.6f\" % (A, B))\n\nCalculate with degrees:\nimport m...
[ 1 ]
[]
[]
[ "math", "python", "trigonometry" ]
stackoverflow_0074277704_math_python_trigonometry.txt
Q: Issue in using win32com to access Excel file everyone! I have been using the win32com.client module in Python to access cells of an Excel file containing VBA Macros. A statement in the code xl = win32com.client.gencache.EnsureDispatch("Excel.Application") has been throwing an error: AttributeError: module 'w...
Issue in using win32com to access Excel file
everyone! I have been using the win32com.client module in Python to access cells of an Excel file containing VBA Macros. A statement in the code xl = win32com.client.gencache.EnsureDispatch("Excel.Application") has been throwing an error: AttributeError: module 'win32com.gen_py.00020813-0000-0000-C000-00000000004...
[ "The main reason for this attribute error is because your COM-server has shifted from late-binding (dynamic) to early binding (static). \n\nIn Late Binding, whenever a method is called, the object is queried for the method and if it succeeds, then the call can be made. \nIn Early Binding, the information of the obj...
[ 10, 8, 5, 3, 2, 0, 0 ]
[]
[]
[ "excel", "python", "win32com" ]
stackoverflow_0047608506_excel_python_win32com.txt
Q: Reverse for ' error on Signup page I am trying to create a user account and all is well when I use the signup view and form to sign up on the signup HTML page below is some info but I get this error NoReverseMatch at /signup/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Met...
Reverse for ' error on Signup page
I am trying to create a user account and all is well when I use the signup view and form to sign up on the signup HTML page below is some info but I get this error NoReverseMatch at /signup/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0....
[ "you cant add html to redirect like that,\neither use render like this\nreturn render(request,'app/index.html')\n\nor \nreturn redirect('profile') #use name of a view declared in url to redirect to that specific page\n\n", "\nRemove the request argument inside the redirect function.\nThe redirect function is defi...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0055136043_django_python.txt
Q: How to find quartile value for every column in dataframe? I want to Find the Quartiles values for each and every column in my dataset in just one go with my dataset names as df4. How do I do that? I tried using For loop but didnt really got the expected output. A: You can use the np.percentile function with the ...
How to find quartile value for every column in dataframe?
I want to Find the Quartiles values for each and every column in my dataset in just one go with my dataset names as df4. How do I do that? I tried using For loop but didnt really got the expected output.
[ "You can use the np.percentile function with the required quartile/percentile values you need for each of the column and finally extract the values in the form of dictionary. You can refer to the code snippet\nimport numpy as np\n\ndf4 = pd.DataFrame({'col1': [1,2,3,4,5,6], 'col2': [4,5,6,7,8,9]})\nperc_df = {}\n\n...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074277693_pandas_python.txt
Q: Using params in flux queries with Python influxdb_client I am trying to update all of our influxdb python queries, so that they are not vulnerable to sql injections. To do this, I have read that you can use params with the query_api() and specifically with the query_data_frame() (https://medium.com/sekoia-io-blog/...
Using params in flux queries with Python influxdb_client
I am trying to update all of our influxdb python queries, so that they are not vulnerable to sql injections. To do this, I have read that you can use params with the query_api() and specifically with the query_data_frame() (https://medium.com/sekoia-io-blog/avoiding-injections-with-influxdb-bind-parameters-50f67e379abb...
[ "The issue is actually with the version of influxdb I was using (1.8.6). The query params is not a feature of Influxdb 1.8.6, and was only introduced into Influxdb 2.0.x\nSee the link below for a question opened with the Influxdb-python-client team.\nhttps://github.com/influxdata/influxdb-client-python/issues/285\n...
[ 1, 1, 0 ]
[]
[]
[ "flux_influxdb", "influxdb", "influxdb_python", "python", "sql_injection" ]
stackoverflow_0068385739_flux_influxdb_influxdb_influxdb_python_python_sql_injection.txt
Q: Tkinter Window: TypeError: can only concatenate str (not "int") to str I'm having trouble solving the Concatenate Error when it's present in a Tkinter Window. I tried using multiple methods but, they didn't work to well with what I'm trying to do. I'm trying to make it so where, at the click of a Tkinter button, i...
Tkinter Window: TypeError: can only concatenate str (not "int") to str
I'm having trouble solving the Concatenate Error when it's present in a Tkinter Window. I tried using multiple methods but, they didn't work to well with what I'm trying to do. I'm trying to make it so where, at the click of a Tkinter button, it would randomly choose a value between 0 and 100. If the random value is le...
[ "\ncan only concatenate str (not \"int\") to str\n\nis telling you exactly what the error is (and the traceback, which you should have added into your original question anyway, would have pinpointed exactly where).\nThe issue is you can't \"sum up\" a string and an integer. Instead, use string formatting:\n\"Goodgu...
[ 2, 0, 0 ]
[]
[]
[ "python", "random", "tkinter" ]
stackoverflow_0074276858_python_random_tkinter.txt
Q: Print only one result using for loop I am checking if each character within a string is alphanumeric and alphabetical. If all the characters within a string is alphanumeric/ alphabetical, I would print 'True', otherwise would print 'False'. My code is as below. s = 'a2' for i in s: if i.isalnum(): prin...
Print only one result using for loop
I am checking if each character within a string is alphanumeric and alphabetical. If all the characters within a string is alphanumeric/ alphabetical, I would print 'True', otherwise would print 'False'. My code is as below. s = 'a2' for i in s: if i.isalnum(): print('True') else: print('False')...
[ "You could do both functions isalnum() and isalpha() for the entire string\nprint(s.isalnum())\nprint(s.isaplha())\n\n", "All you have to do is combine your two if statements using the and operator, and you will get your expected output:\ns = 'a2'\nfor i in s:\n if i.isalnum() and i.isalpha():\n print('...
[ 0, 0 ]
[]
[]
[ "for_loop", "python", "string" ]
stackoverflow_0073890448_for_loop_python_string.txt
Q: Python, interleaving two or more linspace arrays I have three linspace arrays of equal length: a, b, and c. I want to interleave the arrays together in the following way. ([a[0], b[0], c[0]], [a[1], b[1], c[1]], [a[2], b[2], c[2]], . . . etc.) I've seen numerous examples of interleaving two or more arrays, but not...
Python, interleaving two or more linspace arrays
I have three linspace arrays of equal length: a, b, and c. I want to interleave the arrays together in the following way. ([a[0], b[0], c[0]], [a[1], b[1], c[1]], [a[2], b[2], c[2]], . . . etc.) I've seen numerous examples of interleaving two or more arrays, but nothing that groups associated values together. I need it...
[ "\nAdd a new axis of size 1 as the second axis for each array and concatenate them along the new axis.\n\nimport numpy as np\n\na, b, c = np.linspace(0, 4, 3), np.linspace(1, 5, 3), np.linspace(2, 6, 3)\nprint(a, b, c)\n# [0. 2. 4.] [1. 3. 5.] [2. 4. 6.]\n\nresult = np.concatenate([x.reshape(x.shape[0], 1, *(x.shap...
[ 1 ]
[]
[]
[ "arrays", "interleave", "linspace", "python" ]
stackoverflow_0074277754_arrays_interleave_linspace_python.txt
Q: Need Help about converting .py to .exe score = [] percent = [] add = [] print("Enter Grade") #getting input from user def multi_input(): try: while True: data=input() if not data: break yield data except KeyboardInterrupt: return data = list(multi_inp...
Need Help about converting .py to .exe
score = [] percent = [] add = [] print("Enter Grade") #getting input from user def multi_input(): try: while True: data=input() if not data: break yield data except KeyboardInterrupt: return data = list(multi_input()) #filter data into percent and score f...
[ "The .exe file runs your script, but after it runs it, nothing tells it to keep the window open, so it closes it.\nYou can try as a very quick solution to add\nk = input(\"press close to exit\")\n\nat the end of your script to prompt for input so it doesn't close.\nSee this or this\n" ]
[ 0 ]
[]
[]
[ "auto_py_to_exe", "exe", "pyinstaller", "python" ]
stackoverflow_0074251418_auto_py_to_exe_exe_pyinstaller_python.txt
Q: Code can't find keys in dictionary when prompted with string sequence Newbie at coding, doing this for university. I have written a dictionary which translates codons into single letter amino acids. However, my function can't find the keys in the dict and just adds an X to the list I've made. See code below: codon...
Code can't find keys in dictionary when prompted with string sequence
Newbie at coding, doing this for university. I have written a dictionary which translates codons into single letter amino acids. However, my function can't find the keys in the dict and just adds an X to the list I've made. See code below: codon_table = {('TTT', 'TTC'): 'F', ('TTA', 'TTG', 'CTT', 'CTC', ...
[ "You need a codon dictionary keyed on single codons.\nThen you need to iterate over the input sequence in groups of 3.\nYou also need to decide what the output should look like if a triplet is not found in your lookup dictionary.\nFor example:\nfrom functools import cache\n\ncodon_table = {('TTT', 'TTC'): 'F',\n ...
[ 1, 0 ]
[]
[]
[ "dictionary", "for_loop", "function", "key", "python" ]
stackoverflow_0074277818_dictionary_for_loop_function_key_python.txt
Q: How to draw a flat 3D rectangle in matplotlib? How do I draw a rectangle in 3D ? The code below works but it draws a triangle from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [0,1,1,0] y = [0,0,1,...
How to draw a flat 3D rectangle in matplotlib?
How do I draw a rectangle in 3D ? The code below works but it draws a triangle from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection import matplotlib.pyplot as plt fig = plt.figure() ax = Axes3D(fig) x = [0,1,1,0] y = [0,0,1,1] z = [0,1,0,1] verts = [list(zip(x,y,z))] ax.add_c...
[ "The Z axis is wrong should be [0,0,0,0], since each column is a point and the rectangle is on the 0 on Z axis.\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = Axes3D(fig)\nx = [0,1,1,0]\ny = [0,0,1,1]\nz = ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0067410270_python.txt
Q: How to scrape and concate text in tags with Beautiful Soup I want to scrape parts of this site: https://www.booklooker.de/B%C3%BCcher/Bastian-Sick+Der-Dativ-ist-dem-Genitiv-sein-Tod-Ein-Wegweiser-durch-den-Irrgarten-der-deutschen/id/A02ArCkS01ZZy More accurate this part: The html looks like this: I tried this, ...
How to scrape and concate text in tags with Beautiful Soup
I want to scrape parts of this site: https://www.booklooker.de/B%C3%BCcher/Bastian-Sick+Der-Dativ-ist-dem-Genitiv-sein-Tod-Ein-Wegweiser-durch-den-Irrgarten-der-deutschen/id/A02ArCkS01ZZy More accurate this part: The html looks like this: I tried this, but it doesn`t work: from bs4 import BeautifulSoup import ...
[ "You can just invoke the get_text() method to grab the entire description\nfrom bs4 import BeautifulSoup\nimport requests\npage = requests.get(\"https://www.booklooker.de/Bücher/Bastian-Sick+Der-Dativ-ist-dem-Genitiv-sein-Tod-Ein-Wegweiser-durch-den-Irrgarten-der-deutschen/id/A02ArCkS01ZZy\")\n \nsouped = Beauti...
[ 1, 1, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074264680_beautifulsoup_python.txt
Q: Compiler ERROR 'list' object is not callable What is causing this compiler error? How Could I fix this This works on online editor value = (10, 20, 30, 40, 50) my_tuple = list(value) print(my_tuple) A: My best guess is that you've shadowed the built-in function "list". This would mean that you might have used th...
Compiler ERROR 'list' object is not callable
What is causing this compiler error? How Could I fix this This works on online editor value = (10, 20, 30, 40, 50) my_tuple = list(value) print(my_tuple)
[ "My best guess is that you've shadowed the built-in function \"list\". This would mean that you might have used the word \"list\" as a variable somewhere in your code.\nFor example:\nlist = [1,232,3232]\nvalue = (10, 20, 30, 40, 50)\nmy_tuple = list(value)\nprint(my_tuple)\n\nI can see that you are using an .ipynb ...
[ 1 ]
[]
[]
[ "compiler_errors", "list", "python" ]
stackoverflow_0074277769_compiler_errors_list_python.txt
Q: adding rows based on values of other rows I have a list (in a dataframe) that looks like this: oddnum = [1, 3, 5, 7, 9, 11, 23] I want to create a new list that looks like this: newlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23] I want to test if the distance between two numbers is 2 (if oddnum[index+1]-oddnum[in...
adding rows based on values of other rows
I have a list (in a dataframe) that looks like this: oddnum = [1, 3, 5, 7, 9, 11, 23] I want to create a new list that looks like this: newlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23] I want to test if the distance between two numbers is 2 (if oddnum[index+1]-oddnum[index] == 2) If the distance is 2, then I want ...
[ "To pass errors, the best method is to use try and except conditions. Here's my code:\noddnum = [1, 3, 5, 7, 9, 11, 23]\nres = [] # The new list\nfor i in range(len(oddnum)):\n res.append(oddnum[i]) # Append the first value by default\n try: # Tries to run the code\n if oddnum[i] + 2 == oddnum[i+1]: r...
[ 1, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074277878_numpy_pandas_python.txt
Q: Find queryset where one field is greater than another one I have model Shop, I want to get all shops which time_open(opening time) is more than time_closed(closing time). For example 23:00:00 is more than 07:00:00 (Shop_2(Night shift shop)). class Shop(models.Model): time_open = models.TimeField() time_clo...
Find queryset where one field is greater than another one
I have model Shop, I want to get all shops which time_open(opening time) is more than time_closed(closing time). For example 23:00:00 is more than 07:00:00 (Shop_2(Night shift shop)). class Shop(models.Model): time_open = models.TimeField() time_closed = models.TimeField() for example i have two objects: shop_...
[ "You can take a look at django's F objects, it allows you to filter objects based on their field values.\nfrom django.db.models import F\nShop.objects.filter(time_open__gt=F('time_closed'))\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0074277905_django_django_models_django_orm_python.txt
Q: How to select a different webcam using cv2 in python I am trying to stream live video from an external camera using cv2. I was able to write the simple code to stitch the frames and stream it. But am struggling to find how to change the camera. I tried to run it after disabling the main webcam from the task manage...
How to select a different webcam using cv2 in python
I am trying to stream live video from an external camera using cv2. I was able to write the simple code to stitch the frames and stream it. But am struggling to find how to change the camera. I tried to run it after disabling the main webcam from the task manager, but it still did not work. So, if anyone can help me wi...
[ "Cameras are numbered for Windows. You can try a few indeces and check which camera index belongs to the camera you want.\ncapture = cv2.VideoCapture(index)\n\n" ]
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074277815_opencv_python.txt
Q: How can I compare values in a dataframe row and select one of them? I want to use Pandas to create a new column in a dataframe in which it compares 2 columns in a row in the df, if the values are different to choose an specific column, if the values are equal to chose any of them, if one of them in NaN, to choose ...
How can I compare values in a dataframe row and select one of them?
I want to use Pandas to create a new column in a dataframe in which it compares 2 columns in a row in the df, if the values are different to choose an specific column, if the values are equal to chose any of them, if one of them in NaN, to choose the other one (if both are NaN it will already be cover). I was using Num...
[ "np.nan != np.nan NaNs are never equal to each other so your logic is not doing what you think it is: df['col1'] != np.nan. Trying doing print(np.nan == np.nan) and it will always return False. You want to use df['col1'].isna() to find null values and df['col1'].notnull() to find non-null values.\nconditions = [\n ...
[ 1, 1, 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074277144_dataframe_numpy_pandas_python.txt
Q: Using two sets of coordinate points, find points that are closest to each other in python I have two DataFrames (df1, df2) with differing sizes, but the same overall columns. Both have time stamps and latitude and longitude points. The time stamps and coordinates are the same for many points because of the frequen...
Using two sets of coordinate points, find points that are closest to each other in python
I have two DataFrames (df1, df2) with differing sizes, but the same overall columns. Both have time stamps and latitude and longitude points. The time stamps and coordinates are the same for many points because of the frequency at which the data was collected. Here is an example of the DataFrame: time_local Lat Lon...
[ "Yes, what we require here is some math. The distance formula for coordinates would help us.\nFormula:1\n\nHere, x2 represents the second value and x1 the first. Same goes with y.\nPutting it in a code (Cartesian Plane):\npoints = [(37.1454, -85.0555), (37.1454, -85.0556), (37.1453, -85.0556)]\norigin = (37.1455, -...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074277966_numpy_pandas_python.txt
Q: Cannot locate any parts of the body of an element with selenium for python Life has been tough on me lately. I have tried to scrape a website (https://osf.io/preprints/discover?subject=bepress%7CSocial%20and%20Behavioral%20Sciences) with some of the HTML code below for a week now and have tried multiple things to ...
Cannot locate any parts of the body of an element with selenium for python
Life has been tough on me lately. I have tried to scrape a website (https://osf.io/preprints/discover?subject=bepress%7CSocial%20and%20Behavioral%20Sciences) with some of the HTML code below for a week now and have tried multiple things to get it to work. I need the div ID ember499 all the way at the bottom. This div i...
[ "You need to provide delay time.sleep()\ndriver.get('https://osf.io/preprints/discover?subject=bepress%7CSocial%20and%20Behavioral%20Sciences')\ntime.sleep(5)\nprint(len(driver.find_elements(By.CSS_SELECTOR,\".ember-application div\")))\nfor ele in driver.find_elements(By.CSS_SELECTOR,\".ember-application div\"):\n...
[ 0, 0 ]
[]
[]
[ "python", "screen_scraping", "selenium", "xpath" ]
stackoverflow_0074276900_python_screen_scraping_selenium_xpath.txt
Q: Find items containing the asked string in a dict of dicts python A collection of books and movies are already parsed and read into a dict of dicts. The program asks a user to enter a query string to search against multiple fields in the collection: title, author, and publisher. The search should perform partial st...
Find items containing the asked string in a dict of dicts python
A collection of books and movies are already parsed and read into a dict of dicts. The program asks a user to enter a query string to search against multiple fields in the collection: title, author, and publisher. The search should perform partial string matching and be case insensitive. All matching books should be di...
[ "This shows how you might navigate the nested dictionaries. Your could input for example 'river' or 'elisha'. You could simply extend it to deal with movies.\nquery = input('Please enter a query string to search: ').lower()\nfor key, value in library_collections.items():\n for x, y in value.items():\n if ...
[ 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074277401_dictionary_python.txt
Q: Python - getting src from a table cell I have a table as below for which I want to export the text OR the src to a *.csv file. <table class="GridView plm-table" id="pageLayout_projectTeamMembersGridView_gridView"> <tbody> <tr id="pageLayout_projectTeamMembersGridView_gridView_headerRow" class="GridViewHeaderRow"...
Python - getting src from a table cell
I have a table as below for which I want to export the text OR the src to a *.csv file. <table class="GridView plm-table" id="pageLayout_projectTeamMembersGridView_gridView"> <tbody> <tr id="pageLayout_projectTeamMembersGridView_gridView_headerRow" class="GridViewHeaderRow"> <th class="GridViewHeader" scope="col">A</...
[ "The problem in the following code\ndata = row.find_all('td')\nrow_data = [td.text.strip() for td in data]\nlength = len(df)\ndf.loc[length] = row_data\n\nis that td can have a text element, an img or some other element and you're not checking that.\nYou can do something like\nfor row in table1.find_all('tr')[1:]:\...
[ 0 ]
[]
[]
[ "html_table", "python", "screen_scraping", "src" ]
stackoverflow_0074271364_html_table_python_screen_scraping_src.txt
Q: XGBoost feature importance giving the results for 10 features I am trying to use XGBoost as a feature importance tool. However, out of 84 features, I got only results for only 10 of them and the for the rest of them prints zeros. Do you know how to fix it? This is my code and the results: import numpy as np from x...
XGBoost feature importance giving the results for 10 features
I am trying to use XGBoost as a feature importance tool. However, out of 84 features, I got only results for only 10 of them and the for the rest of them prints zeros. Do you know how to fix it? This is my code and the results: import numpy as np from xgboost import XGBClassifier from xgboost import plot_importance fro...
[ "Looks like your 'XYZ' feature is turning out to be the most important compared to others and as per the important values - it is suggested to drop the lower important features.\nYou can try with different feature combination, try some normalization on the existing feature or try with different feature important ty...
[ 0 ]
[]
[]
[ "data_preprocessing", "feature_selection", "python", "xgboost" ]
stackoverflow_0074277948_data_preprocessing_feature_selection_python_xgboost.txt
Q: Use Python's Numba library to calculate and iterate over the itertools.product of an array How would I go about doing this? I would like to be able to do this, but the itertools library doesn't work with Numba's njit. I have tried many answers from online, but they all throw errors I cannot seem to figure out (I'm...
Use Python's Numba library to calculate and iterate over the itertools.product of an array
How would I go about doing this? I would like to be able to do this, but the itertools library doesn't work with Numba's njit. I have tried many answers from online, but they all throw errors I cannot seem to figure out (I'm relatively new to Python). All help is appreciated, thanks! :)
[ "Why would you need to use itertools.product() together with numba?\nYou do not report to have large dataset so do not seem to be needing the speedup.\nIf you use numba njit, in general working with numerical data only, e.g. numpy arrays or doing for loops, works best. If this is the case for you, replace the itert...
[ 0 ]
[]
[]
[ "cartesian_product", "numba", "python" ]
stackoverflow_0074242410_cartesian_product_numba_python.txt
Q: Python Installation Problems I have installed python on my computer in the AppData\local\programs\python location on my computer. I got the installation file from the python website. I cannot use the installation packages from the Microsoft store due to an authorization error (even though I unchecked the boxes in ...
Python Installation Problems
I have installed python on my computer in the AppData\local\programs\python location on my computer. I got the installation file from the python website. I cannot use the installation packages from the Microsoft store due to an authorization error (even though I unchecked the boxes in the App Execution Aliases page in ...
[ "You must add python to global variables.\n" ]
[ -2 ]
[ "Try running just \"python\" in the command prompt. If it doesn't work just install it through https://www.python.org/downloads/.\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0074278160_python.txt
Q: How can I ensure that a certain string is not in my file? I'm trying to ask for students' IDs and save it to a file, and if a student inputs an ID number that already exists in the file, it will print an invalid message. I tried doing this by reading the file first and used if-else statement to check if the studen...
How can I ensure that a certain string is not in my file?
I'm trying to ask for students' IDs and save it to a file, and if a student inputs an ID number that already exists in the file, it will print an invalid message. I tried doing this by reading the file first and used if-else statement to check if the student ID is in the file or not. If it is, it will print the message...
[ "The open file handle file is an iterable, but when you iterate over it (which is what the in operator does) you receive a line at a time. Your code is thus checking whether the file contains a line which is equal to student_id, not whether the string contained in that variable is contained anywhere in the file. Th...
[ 3, 1 ]
[ "You opened the file but you haven't read the file,\nHence the if student_id in file reads the object but not the file contents\nUse this line\n#correct way to read file contents\nfile = open('testfile.txt', 'r').read()\n\nInsted of this line\n#incorrect way\nfile = open('testfile.text', 'r')\n\nUsing .read() gives...
[ -4 ]
[ "python" ]
stackoverflow_0074275639_python.txt
Q: MonkeyType: No traces found for module src.projectname.__main__ Context While trying to generate type hints for all python files in some project named projectname, I am experiencing some difficulties applying the stubs. The project directory is: projectname/ |-- src/ | |-- projectname/__main__.py | |-- project...
MonkeyType: No traces found for module src.projectname.__main__
Context While trying to generate type hints for all python files in some project named projectname, I am experiencing some difficulties applying the stubs. The project directory is: projectname/ |-- src/ | |-- projectname/__main__.py | |-- projectname/some_folder/some_script.py |-- tests/ | |-- projectname/test_s...
[ "Misunderstanding\nI think the key misunderstanding I had can be clarified with:\nMonkeyType currently does not automatically create typings for a Python project.\nIssue\nAs described in the issues and the readme, monkey type only generates type hints for the some.py files that a main.py file imports and uses. Even...
[ 0 ]
[]
[]
[ "python", "type_hinting" ]
stackoverflow_0074277935_python_type_hinting.txt
Q: ImportError: No module named google.oauth2 I wanted to add a google.cloud.storage dependency to my project so I tried to install this dependency with pip install --upgrade google-cloud-storage Running my app again with dev_appserver, it shows me that my gcloud components needed to be updated. Ok so, gcloud compone...
ImportError: No module named google.oauth2
I wanted to add a google.cloud.storage dependency to my project so I tried to install this dependency with pip install --upgrade google-cloud-storage Running my app again with dev_appserver, it shows me that my gcloud components needed to be updated. Ok so, gcloud components update And in my src/__init__.py file, I got...
[ "I've had this issue quite a bit. I uninstalled all Google packages from my local machine, deleted the lib folder in my GAE app folder, created it again then executed: \npip install -t lib google-auth google-auth-httplib2 google-api-python-client --upgrade\n\nThat should fix your problem.\n", "Just upgrading some...
[ 10, 5, 4, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_platform", "google_cloud_sdk", "python" ]
stackoverflow_0048792664_google_app_engine_google_cloud_platform_google_cloud_sdk_python.txt
Q: How to get the place values of numbers in a float? How can I get the place value of each number in a given float (ex: 32.578). This should output something like: tens: 3, ones: 2, tenth: 5 hundredth: 7 thousandth: 8 Is there any module that offers such a function? Thanks! A: The most efficient probably will lik...
How to get the place values of numbers in a float?
How can I get the place value of each number in a given float (ex: 32.578). This should output something like: tens: 3, ones: 2, tenth: 5 hundredth: 7 thousandth: 8 Is there any module that offers such a function? Thanks!
[ "The most efficient probably will likely be the string cast instead of algebraic modulos or logarithms.\nnumber = str(32.578)\nintegers, decimals = number.split(\".\")\n\nfor digit in integers[::-1]:\n # will iterate over\n # ones, tens, 100s, ...\n\nfor decimal in decimals:\n # iterates over your decimals...
[ 0 ]
[]
[]
[ "decimal", "python", "rounding" ]
stackoverflow_0074278142_decimal_python_rounding.txt
Q: How do I access command line arguments? I use python to create my project settings setup, but I need help getting the command line arguments. I tried this on the terminal: $python myfile.py var1 var2 var3 In my Python file, I want to use all variables that are input. A: Python tutorial explains it: import sys ...
How do I access command line arguments?
I use python to create my project settings setup, but I need help getting the command line arguments. I tried this on the terminal: $python myfile.py var1 var2 var3 In my Python file, I want to use all variables that are input.
[ "Python tutorial explains it:\nimport sys\n\nprint(sys.argv)\n\nMore specifically, if you run python example.py one two three:\n>>> import sys\n>>> print(sys.argv)\n['example.py', 'one', 'two', 'three']\n\n", "To get only the command line arguments\n(not including the name of the Python file)\nimport sys\n\nsys.a...
[ 722, 205, 195, 90, 29, 11, 7, 6, 5, 1, 0 ]
[]
[]
[ "command_line", "command_line_arguments", "python" ]
stackoverflow_0004033723_command_line_command_line_arguments_python.txt
Q: How to draw a line which cross two points but spans across the X direction using Plotly Python? I plotted a candlestick chart (X axis being timeseries, Y axis being stock prices) with a segment (the blue one) which started from a datapoint and ended with another datapoint import plotly.graph_objects as go import ...
How to draw a line which cross two points but spans across the X direction using Plotly Python?
I plotted a candlestick chart (X axis being timeseries, Y axis being stock prices) with a segment (the blue one) which started from a datapoint and ended with another datapoint import plotly.graph_objects as go import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-char...
[ "You can continue searching for a plug-and-play solution or you can create it yourself.\nA datetime is normally converted to an integer by your graphing tool. Most of the time it is \"seconds since Jan 1, 1970\". You can compute it with python datetime.datetime.timestamp().\nA straight line is defined by equation y...
[ 1 ]
[]
[]
[ "plotly_python", "python" ]
stackoverflow_0074276639_plotly_python_python.txt
Q: Regular Expression in Python by Matches I have a list of numbers that I am trying to pull out of text. Here is what I am working with: Expression = r"(\d+\.)?(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)" ExpressionResult = (re.findall(Expression, str(OriginalString))) print('original') print(str(OriginalString)) print('parse...
Regular Expression in Python by Matches
I have a list of numbers that I am trying to pull out of text. Here is what I am working with: Expression = r"(\d+\.)?(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)" ExpressionResult = (re.findall(Expression, str(OriginalString))) print('original') print(str(OriginalString)) print('parsed') print(str(ExpressionResult)) Here is my ...
[ "Not exactly sure why you are using regex?\nJust use list comprehension to create new list, and if needed join the list using the .join() function:\nOriginalString = ['', '', '7', '', '', '', '9.2', '', '', '', '9.1', '', '', '', '9.2', '', '', '', '9.5.5', '', '', '', '9.5', '', '', '', '10.1.1', '', '', '', '10.1...
[ 2 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074278112_list_python_string.txt
Q: Class method decorator with arguments So, here's a method: def evaluate(self): return self.left ** self.right And it can raise an OverflowError if the result is too big. To fix it (or convert to a different exception), you can e.g. decorate it: def overflow_adapter(method): def wrapper(self): try: ...
Class method decorator with arguments
So, here's a method: def evaluate(self): return self.left ** self.right And it can raise an OverflowError if the result is too big. To fix it (or convert to a different exception), you can e.g. decorate it: def overflow_adapter(method): def wrapper(self): try: return method(self) except...
[ "Something like this:\nfrom functools import wraps\n\n\ndef exception_adapter(\n aware: tuple[type[BaseException]],\n response: BaseException,\n):\n def decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n ...
[ 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0074278261_decorator_python.txt
Q: How to Trigger a DAG task by another task, regardless of the success of a previous task in Airflow using Python? Description How to run multiple ExternalPythonOperator (I need different packages / versions for different DAG tasks) after each other in serial without being dependent on the previous task's success "...
How to Trigger a DAG task by another task, regardless of the success of a previous task in Airflow using Python?
Description How to run multiple ExternalPythonOperator (I need different packages / versions for different DAG tasks) after each other in serial without being dependent on the previous task's success "upstream_fail". So it should just execute task after each other without caring about if any of them fails or succeeds....
[ "\ntrigger dag run operator https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/operators/trigger_dagrun/index.html\ntrigger rules https://airflow.apache.org/docs/apache-airflow/stable/concepts/dags.html#trigger-rules to get it to run even if upstream fails\nor\ndepends on past https://airflow.apache...
[ 1 ]
[]
[]
[ "airflow", "airflow_2.x", "docker", "python", "python_3.x" ]
stackoverflow_0074269959_airflow_airflow_2.x_docker_python_python_3.x.txt