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: Python to exe - hydra: No module named 'hydra._internal.core_plugins' I have a Python script (3.9.8) which work fine in the cli (on Win11). Now I want to take my python script and generate a .exe. I did it once with hydra without any problems. Now after the convert I do get this error message from Hydra (1.2.0). T...
Python to exe - hydra: No module named 'hydra._internal.core_plugins'
I have a Python script (3.9.8) which work fine in the cli (on Win11). Now I want to take my python script and generate a .exe. I did it once with hydra without any problems. Now after the convert I do get this error message from Hydra (1.2.0). Traceback (most recent call last): File "src\main.py", line 19, in <module...
[ "I suspect that there's a bug in auto-py-to-exe that is incompatible with Python's importlib.import_module function.\nLooking at the stacktrace you posted, I see File \"hydra\\core\\plugins.py\", line 58, in _initialize. Looking at line 58 hydra/core/plugins.py in the Hydra source repo, I see there's a call to impo...
[ 0 ]
[]
[]
[ "auto_py_to_exe", "hydra", "python" ]
stackoverflow_0074306775_auto_py_to_exe_hydra_python.txt
Q: How to extract strings on Python list? I'm a newbie to python and I would like to take strings per each element in a Python list. So the elements in my list look like "name", "id": 1, "localized_name", ... And I would like to have only "name", and delete all the strings, "id": 1, "localized_name", ... for i in ra...
How to extract strings on Python list?
I'm a newbie to python and I would like to take strings per each element in a Python list. So the elements in my list look like "name", "id": 1, "localized_name", ... And I would like to have only "name", and delete all the strings, "id": 1, "localized_name", ... for i in range(113): dota2_hero[i].rstrip('''"id": ...
[ "If l is the list containing your data you can do as follow:\nnames = [x.split(\",\")[0] for x in l]\n" ]
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074324849_list_python_python_3.x.txt
Q: plotly round decimals and add commas in figure_factory tables I've created a table in pandas and would like to display it with plotly. However I want to do my number formatting with plotly instead of pandas. How can I do this? import pandas as pd import numpy as np import plotly.figure_factory as ff df = pd.DataF...
plotly round decimals and add commas in figure_factory tables
I've created a table in pandas and would like to display it with plotly. However I want to do my number formatting with plotly instead of pandas. How can I do this? import pandas as pd import numpy as np import plotly.figure_factory as ff df = pd.DataFrame({'num': [1, 2, 3], 'sqrt': pd.Series([1, 2,...
[ "I tried to update the annotations for figure_factory because the table contents are text, but an error occurred, so I used a graph object. The format can be set in the cells of the graph object, so specify it there. However, to change the display format for each individual cell, you need to list the appropriate fo...
[ 1 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074324218_plotly_python.txt
Q: Pandas exercise: Group by two values and find the mean I am currently working on this pandas exercise: https://github.com/guipsamora/pandas_exercises/blob/master/03_Grouping/Occupation/Exercises_with_solutions.ipynb The dataframe I am working with has an age, gender and occupation column. The question asks for eac...
Pandas exercise: Group by two values and find the mean
I am currently working on this pandas exercise: https://github.com/guipsamora/pandas_exercises/blob/master/03_Grouping/Occupation/Exercises_with_solutions.ipynb The dataframe I am working with has an age, gender and occupation column. The question asks for each combination of occupation and gender, calculate the mean a...
[ "My solution was correct. Silly me. I was looking at the answer for the following question.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074324979_pandas_python.txt
Q: How does inheritance of class variables work in Python? I'm trying to get back to Python but I don't get why the following code doesn't work as intended. class Cat: age = 0 class Dog(Cat): pass Dog.age = 1 Cat.age = 2 print(Dog.age, Cat.age) My output is: 1 2 But why doesn't Dog.age equals 2? Dog is a...
How does inheritance of class variables work in Python?
I'm trying to get back to Python but I don't get why the following code doesn't work as intended. class Cat: age = 0 class Dog(Cat): pass Dog.age = 1 Cat.age = 2 print(Dog.age, Cat.age) My output is: 1 2 But why doesn't Dog.age equals 2? Dog is a subclass of Cat and modifying the class variable of the su...
[ "Any property of Dog will override a property inherited from Cat. You can re-define a value in Cat, but it won't matter because it has already been overridden by the child. For example:\nclass Cat:\n age = 0 # Cat.age = 0\n\n\nclass Dog(Cat):\n pass # Dog.age = Cat.age = 0\n\n\nDog.age=1 # Dog.age = 1, and...
[ 2, 0 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0074324901_inheritance_python.txt
Q: How can I make python script show an error when user inputs same file name with this piece of code? I was creating a note taking program, using the user voice command. When the file already exists, I want to show an error. It runs smoothly when the file name is different though. When the file already exists, I hav...
How can I make python script show an error when user inputs same file name with this piece of code?
I was creating a note taking program, using the user voice command. When the file already exists, I want to show an error. It runs smoothly when the file name is different though. When the file already exists, I have coded to open in the writing mode. It would erase the earlier file, and write new instead of adding in ...
[ "You'd want to check if the file exists after they input it, which can be done using \"os.path.exists\" as also suggested by Tim Roberts. Here's code that should work for you:\nelif 'note' in query:\n try:\n Looper = True # Added a loop so it can repeatedly ask the user until they give a valid ans...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074324942_python_python_3.x.txt
Q: How do I search a pandas dataframe to get the row with a cell matching a specified value? I have a dataframe that might look like this: print(df_selection_names) name 0 fatty red meat, like prime rib 0 grilled I have another dataframe, df_everything, with col...
How do I search a pandas dataframe to get the row with a cell matching a specified value?
I have a dataframe that might look like this: print(df_selection_names) name 0 fatty red meat, like prime rib 0 grilled I have another dataframe, df_everything, with columns called name, suggestion and a lot of other columns. I want to find all the rows in df_ever...
[ "https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html?highlight=isin#pandas.Series.isin\ndf_everything[df_everything['name'].isin(df_selection_names[\"name\"])]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074324980_dataframe_pandas_python.txt
Q: How to write multiple strings in one line? I've started to learn Python with LPTHW and I've gotten to exercise 16: http://learnpythonthehardway.org/book/ex16.html And feel like an idiot because I can't figure out one of the seemingly simple "extra credit" assignments that wants the following: target.write(line1) t...
How to write multiple strings in one line?
I've started to learn Python with LPTHW and I've gotten to exercise 16: http://learnpythonthehardway.org/book/ex16.html And feel like an idiot because I can't figure out one of the seemingly simple "extra credit" assignments that wants the following: target.write(line1) target.write('\n') target.write(line2) target.wri...
[ "target.write(line1 \\n, line2 \\n, line3 \\n)\n\n'\\n' only make sense inside a string literal. Without the quotes, you don't have string literals.\ntarget.write('line1 \\n, line2 \\n, line3 \\n')\n\nOk, now everything is a string literal. But you want line1, line2, line3 to not be string literals. You need those ...
[ 51, 7, 4, 2, 2, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0008691311_python_string.txt
Q: Why doesn’t my Python code show output in Visual Studio Code? import random from words import words import string def get_valid_word(word): word = random.choice(words) while '-' in word or ' ' in word: word = random.choice(words) return word def hangman(): word = get_valid_word(words...
Why doesn’t my Python code show output in Visual Studio Code?
import random from words import words import string def get_valid_word(word): word = random.choice(words) while '-' in word or ' ' in word: word = random.choice(words) return word def hangman(): word = get_valid_word(words) word_letters = set(word) # letters in word alphabet = se...
[ "Because you never called hangman():\nIf you are using a script try this at the end of script:\nif __name__ = \"__main__\":\n hangman()\n\nOtherwise, just call hangman() at the end.\n" ]
[ 1 ]
[ "A function is a block of code that will only run when it has been called upon. You have declared two functions but never called them, therefore they cannot run. To fix this, simply call the functions like this:\nhangman()\nget_valid_word()\n\nAdd this to the very bottom of your code without an indent so that the c...
[ -1 ]
[ "python" ]
stackoverflow_0074324937_python.txt
Q: Mouse scroll wheel with selenium webdriver, on element without scrollbar? I'm trying to drive part of a web map akin to Google Maps, where zoom in/out is done by scrolling while moused over. Ideally, I'd like to be able to do something like this: someElement.scroll(-50) The closest methods I saw in the documentat...
Mouse scroll wheel with selenium webdriver, on element without scrollbar?
I'm trying to drive part of a web map akin to Google Maps, where zoom in/out is done by scrolling while moused over. Ideally, I'd like to be able to do something like this: someElement.scroll(-50) The closest methods I saw in the documentation were click and send_keys, but neither of those do scrolling. I've also trie...
[ "To reproduce/test a mouse wheel, you'll have to emit the mouseover, mousemove and wheel events to the top element with a script injection.\nHere's a working example with Google Map:\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException\n\ndef wheel_element(element, deltaY = 120...
[ 29, 1, 1, 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0047274852_python_selenium_selenium_webdriver.txt
Q: Use to_json but with overall data name I'm trying to use to_json to create a json file with python. I have it working so far to produce the following sort of output: [ { "Country": "A", "Title": "B", "Category": "C" }, { "Country": "D", "Title": "E", "Cat...
Use to_json but with overall data name
I'm trying to use to_json to create a json file with python. I have it working so far to produce the following sort of output: [ { "Country": "A", "Title": "B", "Category": "C" }, { "Country": "D", "Title": "E", "Category": "F" } ] But I need it to create...
[ "I don't think .to_json() can do this by itself. Use df.to_dict('records') to create the list of dictionaries, then put that list inside another dictionary and write that JSON to the file.\nd = {\"data\": df.to_dict('records')}\nwith open(\"file.json\", \"w\") as f:\n json.dump(d, f)\n\n", "why don't you just ...
[ 2, 0 ]
[ "\norient str \nIndication of expected JSON string format.\n‘records’ : list like [{column -> value}, … , {column -> value}]\n\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html?highlight=to_json#pandas.DataFrame.to_json\ndf.to_json(....., orient='records')\n\n" ]
[ -1 ]
[ "arrays", "json", "pandas", "python", "to_json" ]
stackoverflow_0074325068_arrays_json_pandas_python_to_json.txt
Q: How to define __new__ for Enum subclasses? I have a case where I have digit-only code values and some associated standard text. I have a number of fixed code sets I would like to define as enumerations where I can reuse the __new__ method that attaches the associated text to the members (I am using json to dump th...
How to define __new__ for Enum subclasses?
I have a case where I have digit-only code values and some associated standard text. I have a number of fixed code sets I would like to define as enumerations where I can reuse the __new__ method that attaches the associated text to the members (I am using json to dump these, so want the serialization to reflect the va...
[ "The proper definition for CodeEnum is:\nclass CodeEnum(Code, enum.Enum):\n def __new__(cls, code: str, text: str) -> None:\n obj = super().__new__(cls, code)\n obj._value_ = Code(code)\n obj.text = text\n return obj\n\nThe major difference is using super(). _value_ is a Code instead...
[ 1 ]
[]
[]
[ "enums", "python", "python_3.x" ]
stackoverflow_0074324527_enums_python_python_3.x.txt
Q: Python requests - cannot understand how the argument is passed I am using this code to get data from Twitter API. The code works, but I cannot understand how. Specifically, I cannot understand how the auth=bearer_oauth argument works, since I am passing a function. And how the function works, since I am calling it...
Python requests - cannot understand how the argument is passed
I am using this code to get data from Twitter API. The code works, but I cannot understand how. Specifically, I cannot understand how the auth=bearer_oauth argument works, since I am passing a function. And how the function works, since I am calling it without its argument. Sorry if this is too basic, but I could not f...
[ "The bearer_oauth function is just setting the request's authorization header to the bearer token before the request is sent.\nThe code you provided essentially has the same functionality as this:\nheaders = {\"Authorization\": f\"Bearer {bearer_token}\"\nrequests.get(url, headers=headers)\n\nAfter you send the req...
[ 1 ]
[]
[]
[ "arguments", "function", "python", "python_requests" ]
stackoverflow_0074316385_arguments_function_python_python_requests.txt
Q: Find out the widget, which is in nth position of the QGridlayout in PyqQt5? My intention is to find out the widget's "n"th position in QGridlayout. In My code, I have three QGridlayout. First QGirdlayout has 4 widgets, the second QGridlayout has 5 widgets and the third QGridlayout has also 5 Widgets. In each QGrid...
Find out the widget, which is in nth position of the QGridlayout in PyqQt5?
My intention is to find out the widget's "n"th position in QGridlayout. In My code, I have three QGridlayout. First QGirdlayout has 4 widgets, the second QGridlayout has 5 widgets and the third QGridlayout has also 5 Widgets. In each QGridlayout, widgets are placed in various positions. How to find out the widget posit...
[ "Layout items are always stored internally in a one-dimensional array. They can be accessed using itemAt(), no matter the way the manager lays out its items.\nFor one dimensional layouts (QBoxLayout, QStackedLayout), though, the order of those items is always consistent with the visual representation; using insertW...
[ 1 ]
[]
[]
[ "pyqt", "pyqt5", "python" ]
stackoverflow_0074324534_pyqt_pyqt5_python.txt
Q: Assigning mongodb array element in a variable in pymongo i am making a self-project for practice but i am stuck at a point. I am not able to store the value of an element of an array of mongodb in a variable. server = pymongo.MongoClient(url) pokemon_python = server.pokemon_python gonestarter = pokemon_python.gone...
Assigning mongodb array element in a variable in pymongo
i am making a self-project for practice but i am stuck at a point. I am not able to store the value of an element of an array of mongodb in a variable. server = pymongo.MongoClient(url) pokemon_python = server.pokemon_python gonestarter = pokemon_python.gonestarter bulba_health = gonestarter.find_one({"stats":{"$elem...
[ "Given your current python code, you can access the value you want with:\nbulba_health[\"stats\"][0][\"health\"]\n\nbulba_health[\"stats\"] retrieves the array values of the \"stats\" field:\n[{\"health\": 15}, ...]\n\nbulba_health[\"stats\"][0] retrieves the first element in the array:\n{\"health\": 15}\n\nbulba_h...
[ 1 ]
[]
[]
[ "database", "pymongo", "python" ]
stackoverflow_0074315679_database_pymongo_python.txt
Q: pytest profiling mostly reporting on pytest functions In order to profile my code, I've installed pytest-profiling and run $ pytest --profile However, almost all of the results in the summary are related to functions in pytest itself: ncalls tottime percall cumtime percall filename:lineno(function) 1...
pytest profiling mostly reporting on pytest functions
In order to profile my code, I've installed pytest-profiling and run $ pytest --profile However, almost all of the results in the summary are related to functions in pytest itself: ncalls tottime percall cumtime percall filename:lineno(function) 159 0.001 0.000 0.170 0.001 runner.py:108(pytest...
[ "There currently appears to be no option in the plugin to cutomize which function calls are shown (source: plugin repo).\nHowever, you could write a custom script to display only the profiling results you're interested in (which is saved at ./prof/combined.prof).\nimport pstats\n\nstats = pstats.Stats('./prof/combi...
[ 1 ]
[]
[]
[ "profiling", "pytest", "python" ]
stackoverflow_0074198259_profiling_pytest_python.txt
Q: How to iterate through all python objects from a c extension? I'm working on a python memory profiler where I collect the size of python objects with the following method: sum(map(sys.getsizeof, gc.get_objects())) This is significantly the slowest part of the code - especially gc.get_objects - so I decided to spe...
How to iterate through all python objects from a c extension?
I'm working on a python memory profiler where I collect the size of python objects with the following method: sum(map(sys.getsizeof, gc.get_objects())) This is significantly the slowest part of the code - especially gc.get_objects - so I decided to speed it up and rewrite it as a c extension. The problem is that the p...
[ "Here is code I found on GitHub\nhttps://github.com/crazyguitar/pysheeet/blob/master/docs/notes/python-c-extensions.rst#iterate-a-list\n#include <Python.h>\n\n#define PY_PRINTF(o) \\\n PyObject_Print(o, stdout, 0); printf(\"\\n\");\n\nstatic PyObject *\niter_list(PyObject *self, PyObject *args)\n{\n PyObject ...
[ 0 ]
[]
[]
[ "python", "python_c_api", "python_internals" ]
stackoverflow_0032756506_python_python_c_api_python_internals.txt
Q: Keras2 ImageDataGenerator or TensorFlow tf.data? With Keras2 being implemented into TensorFlow and TensorFlow 2.0 on the horizon, should you use Keras ImageDataGenerator with e.g, flow_from_directory or tf.data from TensorFlow which also can be used with fit_genearator of Keras now? Will both methods will have t...
Keras2 ImageDataGenerator or TensorFlow tf.data?
With Keras2 being implemented into TensorFlow and TensorFlow 2.0 on the horizon, should you use Keras ImageDataGenerator with e.g, flow_from_directory or tf.data from TensorFlow which also can be used with fit_genearator of Keras now? Will both methods will have their place by serving a different purpose or will tf.d...
[ "Alongside custom defined Python generators, you can wrap the ImageDataGenerator from Keras inside tf.data.\nTensorFlow >= 2.10 (it's all about tf.data.Dataset())\n # Treat it as a normal tf.data.Dataset()\n dataset = tf.keras.utils.image_dataset_from_directory (...)\n # Or any other augmentation\n normaliz...
[ 14, 10, 2, 1 ]
[]
[]
[ "keras", "keras_2", "python", "tensorflow" ]
stackoverflow_0055627995_keras_keras_2_python_tensorflow.txt
Q: Print summary of frequency of one column that requires two other columns in order to figure out? I had other issues that I resolved but this problem here has set me back a little bit. I have the following columns (there's 50,000 total data in my actual file): Area Date SpeedOver Risk Accid...
Print summary of frequency of one column that requires two other columns in order to figure out?
I had other issues that I resolved but this problem here has set me back a little bit. I have the following columns (there's 50,000 total data in my actual file): Area Date SpeedOver Risk Accident Wendly 8/8/2010 15 L No Wendly 2/9/2010 35 ...
[ "You first need to aggregate the number of accidents:\n# select rows of 2010\n# the original method can be used here\nm1 = df['Date'].str.endswith('2010')\n# m1 = df.index.year==2010\n\n# identify rows with accidents\nm2 = df['Accident'].eq('Yes')\n\n# count the accidents of 2010\n# keep the top 3\nm2[m1].groupby(d...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074325110_dataframe_pandas_python_python_3.x.txt
Q: Can I set the index value of a list to a changing variable in this example? I am a total beginner to Python and recently had a question while experimenting with lists. I have a for loop that increases a variable 'x' and generates a random number every time. I want to add this random number to a list, but when I tr...
Can I set the index value of a list to a changing variable in this example?
I am a total beginner to Python and recently had a question while experimenting with lists. I have a for loop that increases a variable 'x' and generates a random number every time. I want to add this random number to a list, but when I try assigning the index value of the random number to x, I get this error message: ...
[ "import random as number\n\nvalues = [number.randint(1,91) for _ in range(9)]\n\n", "Lists do not have infinite memory, you must tell Python how many elements there are if you are going to add values at arbitrary indexes. However, you can also add or delete elements, so it is very common to start with an empty li...
[ 3, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074324986_list_python.txt
Q: how to print 3x3 array in python? I need to print a 3 x 3 array for a game called TicTackToe.py. I know we can print stuff from a list in a horizontal or vertical way by using listA=['a','b','c','d','e','f','g','h','i','j'] # VERTICAL PRINTING for item in listA: print item Output: a b c or # HORIZONTAL...
how to print 3x3 array in python?
I need to print a 3 x 3 array for a game called TicTackToe.py. I know we can print stuff from a list in a horizontal or vertical way by using listA=['a','b','c','d','e','f','g','h','i','j'] # VERTICAL PRINTING for item in listA: print item Output: a b c or # HORIZONTAL PRINTING for item in listA: p...
[ "You can enumerate the items, and print a newline only every third item:\nfor index, item in enumerate('abcdefghij', start=1):\n print item,\n if not index % 3:\n print\n\nOutput:\na b c\nd e f\ng h i\nj\n\nenumerate starts counting from zero by default, so I set start=1.\nAs @arekolek comments, if you...
[ 23, 11, 8, 5, 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0035903828_python.txt
Q: Match, update and replace values from one dataset to another in Pandas I have two datasets, one has old data and one has updated data. I'd like to create a new dataset by updating values based on if the area, date and column values match. Data df1 area date aa bb cc japan 10/1/2027 1 0 0 u...
Match, update and replace values from one dataset to another in Pandas
I have two datasets, one has old data and one has updated data. I'd like to create a new dataset by updating values based on if the area, date and column values match. Data df1 area date aa bb cc japan 10/1/2027 1 0 0 us 1/1/2022 5 5 5 fiji 11/2/2026 1 1 1 ...
[ "You can merge and combine_first:\ncols = ['area', 'date']\nout = (df2[cols].merge(df1, on=cols, how='left')\n .combine_first(df2)[df2.columns]\n )\n\noutput:\n area date aa bb cc stat\n0 japan 10/1/2027 1 0 0 yes\n1 fiji 11/2/2026 1 1 1 no\n\n", "Using .merge and making...
[ 3, 1, 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074324785_numpy_pandas_python.txt
Q: How do I choose a row based off the index in python/pandas? I have a row in my csv file here: 0 1 2 3 4 5 0 I 55 A 2018-03-10 00:00:00.000 username_in_current_row 2012-01-24 00:00:00.000 I want to write s...
How do I choose a row based off the index in python/pandas?
I have a row in my csv file here: 0 1 2 3 4 5 0 I 55 A 2018-03-10 00:00:00.000 username_in_current_row 2012-01-24 00:00:00.000 I want to write something in python where it only selects rows that have "I" at th...
[ "It sounds like you're saying you want to do filter the dataframe. If you want to find where there's an \"I\" at the index of zero and then print the length, you can do this:\nfiltered_df = df[df.loc[0, 0]==\"I\"]\nprint(f\"{len(filtered_df)} records had an \"I\" at index 0 for column 0.\")\n\nThe thing is, only th...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074324269_pandas_python.txt
Q: How to make a Disnake Slash Command private My Code: import disnake from disnake.ext import commands intents = disnake.Intents.default() intents.members = True intents.message_content = True bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), intents=intents) @bot.slash_command() async def genera...
How to make a Disnake Slash Command private
My Code: import disnake from disnake.ext import commands intents = disnake.Intents.default() intents.members = True intents.message_content = True bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), intents=intents) @bot.slash_command() async def generate_password(inter): await inter.response.se...
[ "Oh, i Get what you Mean,Those are Called Ephemeral Messages, And You can easy make them By:\n@bot.slash_command()\nasync def generate_password(interaction):\n await interaction.response.send_message(\"password\", ephemeral=True)\n\n" ]
[ 1 ]
[]
[]
[ "discord.py", "disnake", "python" ]
stackoverflow_0074320407_discord.py_disnake_python.txt
Q: How to get a value from a web table using Python Selenium? I can access to the page. I can go to the location of the table using Selenium xpath. driver.find_elements('xpath', "/html/body/div/div/div[1]/div[2]/div[3]/div/div[4]/div[2]/div/div[2]/div/table/tbody/tr[2]/td[3]") The question is how I can get the value...
How to get a value from a web table using Python Selenium?
I can access to the page. I can go to the location of the table using Selenium xpath. driver.find_elements('xpath', "/html/body/div/div/div[1]/div[2]/div[3]/div/div[4]/div[2]/div/div[2]/div/table/tbody/tr[2]/td[3]") The question is how I can get the value inside the cell?
[ "You need to assign the result of your expression to a variable which will be an array of element objects. Since you are directly referencing a td element, the array will only have one element, which should be the value you are looking for. To get this value, use element[0].text.\nelement = driver.find_elements('xp...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074325138_python_selenium.txt
Q: how can i filter a python get request response to only show specific data I get stats from opensea.io, but om only interested in the floor price. I have tried adding payload to my requests.get but im still given the same response. below is my code and below that is my response import requests headers = {"accept": ...
how can i filter a python get request response to only show specific data
I get stats from opensea.io, but om only interested in the floor price. I have tried adding payload to my requests.get but im still given the same response. below is my code and below that is my response import requests headers = {"accept": "application/json"} slug = 'doodles-official' baseurl = 'https://api.opensea.io...
[ "Even though it looks you already got it working, there's still some room for improvement.\n\nNo need to include the headers - the requests library will automatically include them for you.\nNo need to import the json library either, you can just call the json() method on the response object itself, which automatica...
[ 0 ]
[]
[]
[ "api", "opensea", "python", "python_requests" ]
stackoverflow_0074305098_api_opensea_python_python_requests.txt
Q: How to find last value of a List in file.txt if first value match the entered data I am writing a simple car rental system to check price of a car. This is the Available Vehicles.txt In which the 3rd row is the car price. RegNumber | Car Name | Price | Transmission Type H4E-11,Toyota,66,Automatic Transmission X11...
How to find last value of a List in file.txt if first value match the entered data
I am writing a simple car rental system to check price of a car. This is the Available Vehicles.txt In which the 3rd row is the car price. RegNumber | Car Name | Price | Transmission Type H4E-11,Toyota,66,Automatic Transmission X11-11,Volkswagen,62,Automatic Transmission JBA-123,Ibiza,65,Automatic Transmission MDZ-A1A...
[ "Don't parse manually csv files, use the csv module:\nimport csv\n\nregNumber = input(\"Please enter Registration Number of Car: \")\n\nwith open('AvailableVehicles.txt') as f:\n # load file lazily\n data = csv.reader(f)\n\n # let's use a generator to stop on the first match\n price = next((row[2] for r...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074325246_python_python_3.x.txt
Q: how to open a dir which i just created in python few lines above(used current date and time to create the folder)? datestring = datetime.datetime.now().strftime("%Y-%m-%d") print(datestring) os.mkdir(datestring) (now i need to open this folder and create a csv file name as attendance) f = open(datestring,'Attendan...
how to open a dir which i just created in python few lines above(used current date and time to create the folder)?
datestring = datetime.datetime.now().strftime("%Y-%m-%d") print(datestring) os.mkdir(datestring) (now i need to open this folder and create a csv file name as attendance) f = open(datestring,'Attendance.csv', 'r+') writer = csv.writer(f)
[ "The simplest way is to use relative path to file. Also, I think you should use with statement while operating with files.\ndatestring = datetime.datetime.now().strftime(\"%Y-%m-%d\")\nprint(datestring)\nos.mkdir(datestring)\n\nwith open(datestring + '/Attendance.csv', 'r+') as f:\n writer = csv.writer(f)\n #...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074325193_python.txt
Q: Trying to run my python script in terminal I'm new to Python and trying to automate a process on my computer, but I'm having trouble. I've already written my Python script with what I want to print, but I'd like to have my own code to press enter after that. I tried "keyboard.press(Key.enter)," but my code does no...
Trying to run my python script in terminal
I'm new to Python and trying to automate a process on my computer, but I'm having trouble. I've already written my Python script with what I want to print, but I'd like to have my own code to press enter after that. I tried "keyboard.press(Key.enter)," but my code does not run on the terminal. Here is the code: from py...
[ "I understood your problem, don't print those commands, instead go to the CLI tab and type them.\nimport pyautogui as gui\nimport time\n\ntime.sleep(5) # Time you should take to switch to the command line tab on foreground\n\ngui.write(\"export SPOTIPY_CLIENT_ID='123'\")\ngui.write(\"export SPOTIPY_CLIENT_SECRET='1...
[ 1 ]
[]
[]
[ "enter", "python" ]
stackoverflow_0074325277_enter_python.txt
Q: How to read _io.TextIOWrapper multiple times? I have the code below: >>> from pathlib import Path >>> path = Path(r"C:\Users\slash\test.txt") >>> f = path.open(encoding="utf-8") >>> f <_io.TextIOWrapper name="C:\\Users\\slash\\test.txt" mode='r' encoding='utf-8'> >>> f.read() 'Test line 1\nTest line 2\nTest line 3...
How to read _io.TextIOWrapper multiple times?
I have the code below: >>> from pathlib import Path >>> path = Path(r"C:\Users\slash\test.txt") >>> f = path.open(encoding="utf-8") >>> f <_io.TextIOWrapper name="C:\\Users\\slash\\test.txt" mode='r' encoding='utf-8'> >>> f.read() 'Test line 1\nTest line 2\nTest line 3\n' >>> f.read() '' Can you guys explain to me the...
[ ">>> f.read()\n'Test line 1\\nTest line 2\\nTest line 3\\n'\n>>> f.read()\n''\n\nImagine your f object is nothing but a cursor.\nOnce the cursor has ended readinig the file, you have to retake it to the beginning.\nYou can do this using the method seek with arguments (0, 0).\n>>> f.read()\n'Test line 1\\nTest line ...
[ 1 ]
[]
[]
[ "path", "pathlib", "python" ]
stackoverflow_0074325131_path_pathlib_python.txt
Q: taking an input from a user, adding elements of the string together so I take a user input in a loop seen below mail_list = [] x = 0 while x >= 0: user_input = input('enter first name, last name, ID, and email domain: ') mail_list.append(user_input) if user_input == 'done': break so it is supp...
taking an input from a user, adding elements of the string together
so I take a user input in a loop seen below mail_list = [] x = 0 while x >= 0: user_input = input('enter first name, last name, ID, and email domain: ') mail_list.append(user_input) if user_input == 'done': break so it is supposed to add the first name, last name, and email domain together to make ...
[ "\nAre you expecting something like email = first_name + '.' + last_name + '@gmail.' + domain\n\nI'll suppose this comment by Gautam Chettiar is right.\n\nAt this point you have mail_list which contains all the parts of the email address, you can join this manually.\nemail = mail_list[0] + '.' + mail_list[1] + '@gm...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074325280_python.txt
Q: Python virtual environment not installing packages in correct directory (python) I have set up a virtual environment correctly have activated it and when I do "which python" it tells me the correct directory, but when I do pip install in the venv it installs the package in the default directory of the mac and not ...
Python virtual environment not installing packages in correct directory (python)
I have set up a virtual environment correctly have activated it and when I do "which python" it tells me the correct directory, but when I do pip install in the venv it installs the package in the default directory of the mac and not in my venv. I have tried using pycharm and installing packages with that, but it happe...
[]
[]
[ "Follow these steps in order -\nIn your current working directory :\npython3 -m venv venv\nsource venv/bin/activate\n(venv) pip3 install library_name\n\nTo check if libraries were properly installed or not :\n(venv) pip3 freeze\n\nand check if your installed libraries is displayed on the terminal screen or not.\nTo...
[ -1, -1 ]
[ "module", "pycharm", "python", "python_venv", "pyvenv" ]
stackoverflow_0070983330_module_pycharm_python_python_venv_pyvenv.txt
Q: Getting reCaptcha in python requests I am using python module requests to send some requests to google but after some requests, a reCaptcha pops up.I am using user agent but it still pops up! What should I do? I used user agent, it did change the browser looks but it did no effect on the Captcha problem user_agent...
Getting reCaptcha in python requests
I am using python module requests to send some requests to google but after some requests, a reCaptcha pops up.I am using user agent but it still pops up! What should I do? I used user agent, it did change the browser looks but it did no effect on the Captcha problem user_agent = 'Mozilla/5.0 (Windows NT 6.3; Win64; x6...
[ "That’s kind of the entire point of captchas. They help deter against bots and spammers. Most captchas can’t be bypassed easily, so just changing the user agent won’t make the captcha go away. Since it sounds like the captchas only appear after a certain number of requests, you could use rotating residential proxie...
[ 1 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074224533_python_python_requests.txt
Q: How could I create a one click hyperlink for websites like https://www.integral-calculator.com/ that automatically pastes into the Javascript box? My web app generates Calculus I problems in Latex and non-Latex form. I use these two websites to check my answers: https://www.derivative-calculator.net/ https://www.i...
How could I create a one click hyperlink for websites like https://www.integral-calculator.com/ that automatically pastes into the Javascript box?
My web app generates Calculus I problems in Latex and non-Latex form. I use these two websites to check my answers: https://www.derivative-calculator.net/ https://www.integral-calculator.com/ E.g., I copy/paste the non-Latex form of the math problem log(v)/v**4 and put it into the Integral calculator website to underst...
[ "You are correct in that, as these websites do not use URL parameters, you will not be able to generate a URL from within your app that auto-populates the required fields. Additionally, these websites do not appear to use any sort of publicly accessible API (they take form data and process the results on the server...
[ 0 ]
[]
[]
[ "hyperlink", "javascript", "mathjax", "python" ]
stackoverflow_0074325137_hyperlink_javascript_mathjax_python.txt
Q: Problem installing mysqlclient for a website hosted on namecheap shared hosting plan I have my small Django website hosted on namecheap. I want to migrate from sqlite3 database to MySQL but when I try to run the pip install mysqlclient command, I get the following error: (majestylink:3.7)[majeaozd@server255 majest...
Problem installing mysqlclient for a website hosted on namecheap shared hosting plan
I have my small Django website hosted on namecheap. I want to migrate from sqlite3 database to MySQL but when I try to run the pip install mysqlclient command, I get the following error: (majestylink:3.7)[majeaozd@server255 majestylink]$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.ta...
[ "error: command 'gcc' failed with exit status 1 in namecheap, the problem is on shared hosting, because the root acces is limited.\nYou need to contact support, they will temporary enable compiler for your account so that you will be able install it.\nhttps://www.namecheap.com/support/knowledgebase/article.aspx/983...
[ 4, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0062243451_django_python.txt
Q: Function to set axis labels only partially works, how do I get the axis labels to display as a function I want to write a function that will print the title and x and y labels. I managed to get the title to display but my code does not display the axis labels. def title(t, y, x): return ax.set_title(t) ax...
Function to set axis labels only partially works, how do I get the axis labels to display as a function
I want to write a function that will print the title and x and y labels. I managed to get the title to display but my code does not display the axis labels. def title(t, y, x): return ax.set_title(t) ax.set_ylabel(y) ax.set_xlabel(x) I expect the code to display the Title, y-axis label, and x-axis label ...
[ "You were only returning set_title as a result the labels were not displaying.\nReturn all configs like this:\ndef title(t, y, x):\n return ax.set_title(t), ax.set_ylabel(y), ax.set_xlabel(x)\n\n", "In function title you have used return statement only for ax.set_title. The function is not considering the last...
[ 0, 0 ]
[]
[]
[ "jupyter", "pandas", "python" ]
stackoverflow_0074325199_jupyter_pandas_python.txt
Q: Replacing ' ' with '\ ' for use in subprocess processes I'm attempting to build a script to batch process and rename videos according to their content, and am attempting to call ffprobe from python in order to do so. For filenames that have spaces, ffprobe is OK with either giving them a '' or putting the whole st...
Replacing ' ' with '\ ' for use in subprocess processes
I'm attempting to build a script to batch process and rename videos according to their content, and am attempting to call ffprobe from python in order to do so. For filenames that have spaces, ffprobe is OK with either giving them a '' or putting the whole string in ' ' . At the terminal command line both of the follow...
[ "\nProviding a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed ...
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0074325025_python_subprocess.txt
Q: running multiple processes simultaneously I am attempting to create a program in python that runs multiple instances (15) of a function simultaneously over different processors. I have been researching this, and have the below program set up using the Process tool from multiprocessing. Unfortunately, the program e...
running multiple processes simultaneously
I am attempting to create a program in python that runs multiple instances (15) of a function simultaneously over different processors. I have been researching this, and have the below program set up using the Process tool from multiprocessing. Unfortunately, the program executes each instance of the function sequentia...
[ "I think what is happening is that you are not doing enough in some_function to observe work happening in parallel. It spawns a process, and it completes before the next one gets spawned. If you introduce a random sleep time into some_function, you'll see that they are in fact running in parallel.\nfrom multiproc...
[ 23, 3, 0 ]
[]
[]
[ "python", "python_multiprocessing" ]
stackoverflow_0022700164_python_python_multiprocessing.txt
Q: Python multiple turtle.ondrag not working I have been writing program about dragging turtles to different designated position. However, turtle.ondrag(turtle.goto) nor at[i].ondrag(at[i].goto) does not work. I've been amended with the solution from here Python turtle.ondrag not working @ Jellominer, but that's seem...
Python multiple turtle.ondrag not working
I have been writing program about dragging turtles to different designated position. However, turtle.ondrag(turtle.goto) nor at[i].ondrag(at[i].goto) does not work. I've been amended with the solution from here Python turtle.ondrag not working @ Jellominer, but that's seems not working for my case (with multiple turtle...
[ "There are two problems with your code, the first is how the lambda is setup. The second is that you use two different ways to set the ondrag:\nat[i].ondrag(lambda x, y: handler(x, y, i))\n\ncurTurtle.ondrag(handler)\n\nSo even if your lambda was correct, you'd wipe it out on the first drag event. Here's a lambda...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "python_turtle", "turtle_graphics" ]
stackoverflow_0074324995_python_python_3.x_python_turtle_turtle_graphics.txt
Q: why there is no error for a= [10,] but error for [10,,] in python? why is there no error for a = [10,] but error for [10,,] in Python ? what is interpreter expecting from comma/s in both the cases? I understand it's more of a syntax error but there has to rationale/logical explanation of this. A: Of course the...
why there is no error for a= [10,] but error for [10,,] in python?
why is there no error for a = [10,] but error for [10,,] in Python ? what is interpreter expecting from comma/s in both the cases? I understand it's more of a syntax error but there has to rationale/logical explanation of this.
[ "Of course there is a logical explanation.\nMany people, when writing a list, leave in the extra final comma, as in\nlst = [1,2,3,4,]\n\nSo, Python allows that and ignores a final comma. But you can't have an empty entry in the MIDDLE of a list.\n", "In python list we cannot have an empty entry in middle of two v...
[ 1, 0 ]
[]
[]
[ "list", "python", "syntax", "syntax_error" ]
stackoverflow_0074324961_list_python_syntax_syntax_error.txt
Q: Python web crawling code with CSS seletor import urllib.request from bs4 import BeautifulSoup import time link_list = list() header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'} url = "https://www.musinsa.com/brands/poloralphla...
Python web crawling code with CSS seletor
import urllib.request from bs4 import BeautifulSoup import time link_list = list() header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'} url = "https://www.musinsa.com/brands/poloralphlauren" req = urllib.request.Request(url=url, hea...
[ "The tag(s) your are looking for aren't contained in the HTML source code of the site but rather are rendered dynamically with Javascript.\nTry this instead to get all links for items:\nimport requests\nfrom bs4 import BeautifulSoup\nurl = \"https://www.musinsa.com/brands/poloralphlauren\"\nres = requests.get(url)\...
[ 1 ]
[]
[]
[ "beautifulsoup", "css", "html", "python" ]
stackoverflow_0074325363_beautifulsoup_css_html_python.txt
Q: How to limit docker container running time in python? I am still new to python. I would like to run a container with limited time (5min) and also keep the try-except in case the container failed to finish running. For example: import docker client = docker.from_env() try: # how to limit the running time to 5 m...
How to limit docker container running time in python?
I am still new to python. I would like to run a container with limited time (5min) and also keep the try-except in case the container failed to finish running. For example: import docker client = docker.from_env() try: # how to limit the running time to 5 min, if exceeds 5 min, kill the container anyways contai...
[ "If you mean by waiting for 5 minutes and then killing the process, then write on top of the script:\nimport time\nThen, under the cont.stop() code, type in time.sleep(300)\n(300 seconds is 5 mins, according to a calculator.)\n" ]
[ 0 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0074325525_docker_python.txt
Q: Multiple async requests simultaneously I'm trying to call ~ 300 API calls at the same time, so that I would get the results in a couple of seconds max. My pseudo-code looks like this: def function_1(): colors = ['yellow', 'green', 'blue', + ~300 other ones] loop = asyncio.new_event_loop() asyncio.set_e...
Multiple async requests simultaneously
I'm trying to call ~ 300 API calls at the same time, so that I would get the results in a couple of seconds max. My pseudo-code looks like this: def function_1(): colors = ['yellow', 'green', 'blue', + ~300 other ones] loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) res = loop.run_until_com...
[ "aiohttp with Native Coroutines (async/await)\nHere is a typical pattern that accomplishes what you're trying to do. (Python 3.7+.)\nOne major change is that you will need to move from requests, which is built for synchronous IO, to a package such as aiohttp that is built specifically to work with async/await (nat...
[ 51, 0 ]
[]
[]
[ "python", "python_3.x", "python_asyncio", "python_requests" ]
stackoverflow_0053021448_python_python_3.x_python_asyncio_python_requests.txt
Q: Call Matlab function from Python script: "not enough values to unpack" ValueError I called a Matlab function from Python, the function has 3 outputs. Python gives ValueError: not enough values to unpack (expected 3, got 2). Here's the Matlab function testCalledByPython: function [otpt1, otpt2, otpt3] = testCalledB...
Call Matlab function from Python script: "not enough values to unpack" ValueError
I called a Matlab function from Python, the function has 3 outputs. Python gives ValueError: not enough values to unpack (expected 3, got 2). Here's the Matlab function testCalledByPython: function [otpt1, otpt2, otpt3] = testCalledByPython(inpt) otpt1 = rand(inpt, inpt); otpt2 = magic(inpt); otpt3 = zeros(inpt, inpt);...
[ "I found the solution myself. It's actually explained in Matlab Documentation:\nhttps://uk.mathworks.com/help/matlab/matlab_external/call-matlab-functions-from-python.html\nSo knowing there are 3 outputs, the way to do it is changing last line of Python script to: \notpt1, otpt2, otpt3 = eng.testCalledByPython(2, n...
[ 2, 0 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0053066901_matlab_python.txt
Q: How to plot several data frames in one figure? I have a program which outputs between 1 to 4 pandas data frames, each with the structure below: a b time 2008 11.61 11.99 2009 12.54 10.66 2010 13.64 12.34 2011 14.02 13.20 In each case the rows may increase if I add years and column...
How to plot several data frames in one figure?
I have a program which outputs between 1 to 4 pandas data frames, each with the structure below: a b time 2008 11.61 11.99 2009 12.54 10.66 2010 13.64 12.34 2011 14.02 13.20 In each case the rows may increase if I add years and columns may increase if I add cities but in each of the fo...
[ "One way to do this is using Pandas MultIndex to assemble each frame into a single \"multi-dimensional\" dataframe. Another way would be to collect these frames into a Python list.\nSeeing and using the pattern as you've done is a great idea. However, using exec is almost always a bad idea; you need to write code...
[ 0 ]
[]
[]
[ "dataframe", "exec", "matplotlib", "pandas", "python" ]
stackoverflow_0074325410_dataframe_exec_matplotlib_pandas_python.txt
Q: Define css class in django Forms Assume I have a form class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) Is there a way for me to define css classes on each field such that I can then use jQuery based on cl...
Define css class in django Forms
Assume I have a form class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping ...
[ "Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: django-widget-tweaks. Hope somebody will find it useful.\n", "Answered my own question. Sigh\nhttp://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs\nI di...
[ 191, 96, 84, 49, 34, 33, 22, 17, 6, 5, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000401025_django_django_forms_python.txt
Q: Why is my isColliding function not working? When my turtle moves forward, it should check if it is within the desired area, but it isn't working. I tried checking the specific coordinates of the box, but that did not work. In the isColliding function, it should just be checking if my turtle is within the topLeft x...
Why is my isColliding function not working?
When my turtle moves forward, it should check if it is within the desired area, but it isn't working. I tried checking the specific coordinates of the box, but that did not work. In the isColliding function, it should just be checking if my turtle is within the topLeft x and bottomRight x and within the topLeft y and b...
[ "I believe your primary issue is that you have the Y comparison in isColliding backward. Your secondary issue is you're doing unnecessary type coercions. My rework of your code that I believe works as you describe:\nfrom turtle import Screen, Turtle\n\nallObs = {\n \"testBox\": {\n \"topLeft\": (100, 10...
[ 0 ]
[]
[]
[ "python", "python_turtle" ]
stackoverflow_0074318837_python_python_turtle.txt
Q: How to remove every first word from .txt file? Sample data: Apple iPhone 14 Samsung Galaxy S22 Xiaomi Redmi 9 John Doe Desired output: iPhone 14 Galaxy S22 Redmi 9 Doe I'd like open a .txt file. How do I remove every first word from every line when file looks similar like there? On Notepad, I can use CTRL A > F...
How to remove every first word from .txt file?
Sample data: Apple iPhone 14 Samsung Galaxy S22 Xiaomi Redmi 9 John Doe Desired output: iPhone 14 Galaxy S22 Redmi 9 Doe I'd like open a .txt file. How do I remove every first word from every line when file looks similar like there? On Notepad, I can use CTRL A > Find and replace > "First_Name " > "" > And I got a l...
[ "This works for me:\nwith open(\"sample.txt\", \"r\", encoding=\"utf8\") as f:\n for line in f:\n separate_words = line.split(\" \")\n new_line = \" \".join(separate_words[1:])\n print(new_line, end=\"\")\n\nOutput:\n$ python test.py\niPhone 14\nGalaxy S22\nRedmi 9\nDoe\n\n", "This is conc...
[ 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074322588_csv_python.txt
Q: Loading a tmx file with import pytmx in python I have made a map in the tiled editor and intend to use it in a game using pygame. I imported pytmx to help with this process but when I use load_pygame("directory of file") it give out this error Traceback (most recent call last): File "D:\Coder man\code\GUI\game ...
Loading a tmx file with import pytmx in python
I have made a map in the tiled editor and intend to use it in a game using pygame. I imported pytmx to help with this process but when I use load_pygame("directory of file") it give out this error Traceback (most recent call last): File "D:\Coder man\code\GUI\game map\showing map.py", line 7, in <module> tmx_dat...
[ "The error message is clearly saying what's wrong.\nCannot find tileset file :/automap-tiles.tsx ... at D:\\Tile sheet\\:\\automap-tiles.tsx\n\nYour tile map is referencing an external tile set file(*.tsx), and its file path is specified by a full path without a drive letter, defined by Microsoft, which I'll call a...
[ 0, 0 ]
[]
[]
[ "python", "pytmx", "tmx" ]
stackoverflow_0074324034_python_pytmx_tmx.txt
Q: Extract value from dictionary in dataframe column I have a DataFrame with a column with dictionaries. I need to extract a value from the dictionary. df = pd.DataFrame (x.edges (data=True), columns = ['emp1','emp2','weight']) emp1 emp2 weight 0 Joan Lee {'weight': 3} 1 Joan ...
Extract value from dictionary in dataframe column
I have a DataFrame with a column with dictionaries. I need to extract a value from the dictionary. df = pd.DataFrame (x.edges (data=True), columns = ['emp1','emp2','weight']) emp1 emp2 weight 0 Joan Lee {'weight': 3} 1 Joan Andy {'weight': 1} 2 Vincent Frida {'weight': ...
[ "figured it out.\ndf['newweight'] = df.weight.apply(lambda x: x['weight'])\n\n", "You can also use .str[]\ndf.weight.str['weight']\n\n", "x.get ('value') would look for the key called 'value', but your dictionary has only one key called 'weight'.\ndict.get is specifically designed to return None when you attemp...
[ 2, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0065674646_dataframe_pandas_python.txt
Q: How to avoid this column so that I only get a remaining data in csv and not the Unamed: 0 column when I save the dataframe as new csv file I have a dataframe and I converted it into a new csv file but when I read this new csv file I get a ' Unamed: 0 ' column which has row index's. I need to avoid this column. I e...
How to avoid this column so that I only get a remaining data in csv and not the Unamed: 0 column when I save the dataframe as new csv file
I have a dataframe and I converted it into a new csv file but when I read this new csv file I get a ' Unamed: 0 ' column which has row index's. I need to avoid this column. I even tried to delete the this column and save this dataframe into new csv file but still after that I get the same Unamed: 0 column in next new c...
[ "When writing to csv, use index=False to avoid including the index.\ndf.to_csv(\"data.csv\", index=False)\n\nWhen reading the csv file, you can use index_col to specify the column to use as an index:\ndf = pd.read_csv(\"data.csv\", index_col=0) # Use 1st column as index\n\nYou can also use usecols to specify the c...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074325734_python.txt
Q: Vectorizing theano/aesara variable operations I am trying to compute the function below with theano/aesara in an preferably vectorized manner: ![image|620x182](upload://9Px5wAGjZdkBXVBg4fqmuSPorPr.png) The solution i have is not vectorized and therefore way too slow: def apply_adstock_with_lag(x, L, P, D): """...
Vectorizing theano/aesara variable operations
I am trying to compute the function below with theano/aesara in an preferably vectorized manner: ![image|620x182](upload://9Px5wAGjZdkBXVBg4fqmuSPorPr.png) The solution i have is not vectorized and therefore way too slow: def apply_adstock_with_lag(x, L, P, D): """ params: x: original array L: length ...
[ "Have you tried:\ndef apply_adstock_with_lag(x, L, P, D):\n adstocked_x = np.convolve(x, D**((np.arange(0, L, 1) - P)**2))[:-(L-1)] / sum(D**((np.arange(0, L, 1) - P)**2))\n adstocked_x = at.as_tensor_variable(adstocked_x)\n return adstocked_x\n\nThis should work\n" ]
[ 0 ]
[]
[]
[ "pymc", "pymc3", "python", "theano", "vectorization" ]
stackoverflow_0073620582_pymc_pymc3_python_theano_vectorization.txt
Q: Multiple crop sections with loop in opencv and mouse clicks I have obtained region of interests through mouse clicks with OpenCV as roi = [[(276, 756), (940, 828), 'text', 'name'], [(1572, 764), (2332, 824), 'text', 'cnic'], [(1996, 692), (2052, 752), 'box', 'corporate'], [(2300, 692), (2356, ...
Multiple crop sections with loop in opencv and mouse clicks
I have obtained region of interests through mouse clicks with OpenCV as roi = [[(276, 756), (940, 828), 'text', 'name'], [(1572, 764), (2332, 824), 'text', 'cnic'], [(1996, 692), (2052, 752), 'box', 'corporate'], [(2300, 692), (2356, 756), 'box', 'individual']] where each tuple is obtained from mo...
[ "for pt1, pt2, _, _ in roi:\n cropped = img[pt1[1]:pt2[1], pt1[0]:pt2[0]]\n\n" ]
[ 0 ]
[]
[]
[ "loops", "numpy", "python" ]
stackoverflow_0074325503_loops_numpy_python.txt
Q: Unsafe redirect to URL with protocol django rest framework When the user completes the registration process, I want to redirect her to the login page, where I get the following error. Unsafe redirect to URL with protocol 'accounts' What method should I use to solve this error? class RegisterUser(APIView): seri...
Unsafe redirect to URL with protocol django rest framework
When the user completes the registration process, I want to redirect her to the login page, where I get the following error. Unsafe redirect to URL with protocol 'accounts' What method should I use to solve this error? class RegisterUser(APIView): serializer_class = RegisterSerializer def post(self, request): ...
[ "Simply you can try this way:\nChange this:\nreturn HttpResponseRedirect('accounts:login')\n\nTo:\nreturn HttpResponseRedirec('/accounts/login/')\n\nTry and see if it solves the error\n", "It should be either:\nreturn redirect('accounts:login')\n\nor:\nreturn HttpResponseRedirect(reverse('accounts:login'))\n\n" ]
[ 2, 1 ]
[]
[]
[ "django", "django_rest_framework", "django_serializer", "django_views", "python" ]
stackoverflow_0074325609_django_django_rest_framework_django_serializer_django_views_python.txt
Q: Sequentially update DataFrame value based on previous row's value Not sure if there is a more elegant way to do what I want to do. Basically, I need to determine the current row's "position" value based on the "factor" value and the previous row's "position" value. I tried to loop through the DataFrame and use som...
Sequentially update DataFrame value based on previous row's value
Not sure if there is a more elegant way to do what I want to do. Basically, I need to determine the current row's "position" value based on the "factor" value and the previous row's "position" value. I tried to loop through the DataFrame and use some if else statements to update the value, but it is very clumpy and the...
[ "IIUC, you can use this vectorial alternative:\nthreshold_2 = 0.7\nthreshold_1 = 0.35\n\nm1 = df['factor'].gt(threshold_2)\n\ngroup = m1.cumsum()\n\nm2 = df.loc[group>0, 'factor'].gt(threshold_1).groupby(group).cummin()\n\ndf['position'] = (m1|df.index.isin(m2[m2].index)).astype(int)\n\noutput:\n ...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074325624_dataframe_pandas_python.txt
Q: input() :: Using Backspace And Arrow Keys I have a python script that takes information from the user through the built in input() function. My question is why do the backspace and arrow keys not function correctly and how can I fix it so they function as intended. A simple example of the problem I am having... #!...
input() :: Using Backspace And Arrow Keys
I have a python script that takes information from the user through the built in input() function. My question is why do the backspace and arrow keys not function correctly and how can I fix it so they function as intended. A simple example of the problem I am having... #!/usr/bin/env python3 while 1: x=input("enter ...
[ "Import the readline module from the standard library.\nIt automatically wraps stdin.\n", "Look into the tkinter library:\nhttp://wiki.python.org/moin/TkInter\nThere's also a good discussion of the library here on SO:\nArrow key input code not working in tkinter\n", "To add to the answer from @t-8ch, here is an...
[ 24, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0014796323_python_python_3.x.txt
Q: Telegram bot convert mp4 to mp3 i am currently trying to create a telegram bot which can convert mp4 to mp3. The bot needs to receive the videos sent by users and then send back an audio file to them after converting the mp4 to mp3. However, the problem im facing now is that the videos sent by users cant be read b...
Telegram bot convert mp4 to mp3
i am currently trying to create a telegram bot which can convert mp4 to mp3. The bot needs to receive the videos sent by users and then send back an audio file to them after converting the mp4 to mp3. However, the problem im facing now is that the videos sent by users cant be read by my bot. Do any of you know how to s...
[ "Here's my code (thanks to @Daweo How to convert MP4 to MP3:\nimport os\nvideo = moviepy.editor.VideoFileClip(os.path.join(\"path\",\"to\",\"movie.mp4\"))\nvideo.audio.write_audiofile(os.path.join(\"path\",\"to\",\"movie_sound.mp3\"))\n\nYou simply need to change the file type or to be precise the path.\n" ]
[ 0 ]
[]
[]
[ "audio", "bots", "python", "telegram", "video" ]
stackoverflow_0074325678_audio_bots_python_telegram_video.txt
Q: Alexa Skill python not working properly with NoIntent I am a basic dev with Alexa Skill, and with Python, but cannot understand where is the problem. This skill ask the start and the end of a shower, to calculate expenses and energy consumption. When user finish the shower, I ask "Alexa take the shower" than Alexa...
Alexa Skill python not working properly with NoIntent
I am a basic dev with Alexa Skill, and with Python, but cannot understand where is the problem. This skill ask the start and the end of a shower, to calculate expenses and energy consumption. When user finish the shower, I ask "Alexa take the shower" than Alexa asks: Have you finished the shower? ("YES") Have you used...
[]
[]
[ "logger.info(\"inside YesIntentHandler()\") \n# type: (HandlerInput) -&gt; Response \npersistent_attributes = handler_input.attributes_manager.persistent_attributes\nif 'total_minutes' in persistent_attributes:\n # dryer is used \n minutes = persistent_attributes['total_minutes'] \n # calculation\n tota...
[ -1 ]
[ "alexa", "alexa_skill", "python" ]
stackoverflow_0074321396_alexa_alexa_skill_python.txt
Q: How to convert a byte type data to UUID in python I am reading the UUID from my board as b"\x93S4E2\x8d\x9e\x8f\xe9\x11\xc1z\xd0U\x95'" How to convert or format this to obtain a 128-bit UUID that reads [279555d0-7ac1-11e9-8f93-8d3245345393] A: The Python UUID library will normally cover most of the situations th...
How to convert a byte type data to UUID in python
I am reading the UUID from my board as b"\x93S4E2\x8d\x9e\x8f\xe9\x11\xc1z\xd0U\x95'" How to convert or format this to obtain a 128-bit UUID that reads [279555d0-7ac1-11e9-8f93-8d3245345393]
[ "The Python UUID library will normally cover most of the situations that you need for UUIDs.\nhttps://docs.python.org/3/library/uuid.html\nThe result I'm get doesn't match your expected output 100% but I wonder if you have a typo in your question.\nThis is what I did:\nimport uuid\n\nraw_id = b\"\\x93S4E2\\x8d\\x9e...
[ 0 ]
[]
[]
[ "python", "uuid" ]
stackoverflow_0074324693_python_uuid.txt
Q: django query with manytomany as list I'm working with django (4.1) and I have a problem with a QuerySet. models.py class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model...
django query with manytomany as list
I'm working with django (4.1) and I have a problem with a QuerySet. models.py class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_le...
[ "You can define related_name to easily access related model through the implicit relation.\nTo be clearer if you define related_name=\"articles\" inside your M2M field publications, you'll be able to access articles related to publication by calling my_publication.articles.all()\nTo return titles associated with pu...
[ 0 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0074321486_django_orm_python.txt
Q: How to merge/join consecutive lines How do I merge every single batch of consecutive lines in a .txt file? Example: Turn this: User#0001 Hello Whats Up User#0002 Hi ... into this: User#0001 Hello Whats Up User#0002 Hi ... I want to merge all of the lines because when I've tried doing this: pattern = r'([a-zA-Z...
How to merge/join consecutive lines
How do I merge every single batch of consecutive lines in a .txt file? Example: Turn this: User#0001 Hello Whats Up User#0002 Hi ... into this: User#0001 Hello Whats Up User#0002 Hi ... I want to merge all of the lines because when I've tried doing this: pattern = r'([a-zA-Z]+#[0-9]+.)(.+?(?:^$|\Z))' data = { ...
[ "I would phrase your requirement using re.sub:\ninp = \"\"\"User#0001\nHello\nWhats Up\n\n\nUser#0002\nHi\"\"\"\n\noutput = re.sub(r'(?<!\\n)\\n(?=\\S)', ' ', inp)\nprint(output)\n\nThis prints:\nUser#0001 Hello Whats Up\n\n\nUser#0002 Hi\n\nThe regex used here says to match:\n\n(?<!\\n) assert that newline does no...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074324234_python_regex.txt
Q: How to go about data modelling? I've spent the last 2 hours or so figuring out how to apply it to my two variables. I am supposed to demonstrate/explain how I would handle the relationship of the two following variables in data modelling: Pressure24h DangerLevel24h 1000.2 45 ...
How to go about data modelling?
I've spent the last 2 hours or so figuring out how to apply it to my two variables. I am supposed to demonstrate/explain how I would handle the relationship of the two following variables in data modelling: Pressure24h DangerLevel24h 1000.2 45 1014.8 90 990.8 ...
[ "Here's my code as discussed in the comments:\ndef lobf(*cords):\n cords = cords[0]\n print(cords)\n x_mean, y_mean = 0, 0\n print(cords)\n for x, y in cords:\n x_mean += x # get x sum\n y_mean += y # get y sum\n x_mean /= len(cords) # get x mean\n y_mean /= len(cords) # get y mea...
[ 0 ]
[]
[]
[ "data_modeling", "python", "python_3.x" ]
stackoverflow_0074325667_data_modeling_python_python_3.x.txt
Q: Two keypresses processed in each frame (pygame snake game) I am making a snake game, and I want to make sure that if you want to turn twice (for example a 180 degree turn), if both keys are pressed in the same frame, the next key press will be processed in the next frame, so that the snake actually turns twice ove...
Two keypresses processed in each frame (pygame snake game)
I am making a snake game, and I want to make sure that if you want to turn twice (for example a 180 degree turn), if both keys are pressed in the same frame, the next key press will be processed in the next frame, so that the snake actually turns twice over two frames instead of changing direction twice in the same fra...
[ "Store the keys pressed in a queue:\ndirection_queue = []\n\nif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_a:\n direction_queue.append('L')\n if event.key == pygame.K_d:\n direction_queue.append('R')\n if event.key == pygame.K_w:\n direction_queue.append('U')\n if even...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074249252_pygame_python.txt
Q: Retrieving Index from Linked List I am wanting to iterate through my linked list and only retrieve the value at a specific index. I have written a very slow way of accomplishing this: ` def get_index(self, data): if self.head is None: raise Exception("List is empty") reg_list = [] ...
Retrieving Index from Linked List
I am wanting to iterate through my linked list and only retrieve the value at a specific index. I have written a very slow way of accomplishing this: ` def get_index(self, data): if self.head is None: raise Exception("List is empty") reg_list = [] for i in self: reg...
[ "It is confusing that your code names the argument data while it is supposed to be an index, and then names the loop variable i, which is supposed to be a node. Why not choose names that actually say what it is? Like index and node?\nYou can change the given code to the following:\n def get_index(self, index):\n...
[ 1 ]
[]
[]
[ "linked_list", "python", "python_3.x" ]
stackoverflow_0074324925_linked_list_python_python_3.x.txt
Q: Unsupported operand type(s) for 'X': 'NoneType' and 'NoneType' I'm currently working on a code and I'm getting this error. Please explain what am I doing wrong in a simple way...help! s=int(input('input random seed:')) a=print('The first number is',format(random(50,56))) b=print('The second number is',format(rando...
Unsupported operand type(s) for 'X': 'NoneType' and 'NoneType'
I'm currently working on a code and I'm getting this error. Please explain what am I doing wrong in a simple way...help! s=int(input('input random seed:')) a=print('The first number is',format(random(50,56))) b=print('The second number is',format(random(50,56))) if (a*b)==c: print('Your answer is correct.')
[ "The problem is with these lines.\na = print('The first number is',format(random.randint(1,9)))\nb = print('The second number is',format(random.randint(1,9)))\n\nprint function is used to print the values to the stdout and it does not return any value. A function in python that has no return value will implicitly r...
[ 0, 0, 0 ]
[ "Problem is you are assigning with print statement that will return None in python\n\na=print('The first number is',format(random.randint(1,9)))\n\ntry this:\nimport random\ns=int(input('input random seed:'))\nrandom.seed(s)\na=format(random.randint(1,9))\nb=format(random.randint(1,9))\nprint('The first number is',...
[ -1 ]
[ "non_type", "python" ]
stackoverflow_0074326106_non_type_python.txt
Q: np.select not working with datetime64[ns] I have a series with datetime values, with timezone. If i use np.select to: if hour after 12 -> return next day if hour before 11 -> return same day else return np.nan With the datetime values with timezones, it works. However, if I use np.select after removing timezones...
np.select not working with datetime64[ns]
I have a series with datetime values, with timezone. If i use np.select to: if hour after 12 -> return next day if hour before 11 -> return same day else return np.nan With the datetime values with timezones, it works. However, if I use np.select after removing timezones, it gives me the following error: TypeError: C...
[ "Use a suitable default to avoid the error; here you can use pandas' not-a-time value:\nimport pandas as pd\nimport numpy as np\n\ndatetime_series = pd.Series(\n [\n \"2022-09-24 22:00:00+02:00\",\n \"2022-09-04 11:30:00+02:00\",\n \"2022-11-11 02:20:30+02:00\",\n \"2022-11-12 03:20:3...
[ 2 ]
[]
[]
[ "datetime", "numpy", "pandas", "python", "timezone" ]
stackoverflow_0074323074_datetime_numpy_pandas_python_timezone.txt
Q: Call nested function from another function in python? I have a function inside inside another and a third function. How can I call my nested function inside of my third function? Is there any special libraries I can use? I am not allowed to edit a() or b(), only c(). def a(): def b(): print("hi") def ...
Call nested function from another function in python?
I have a function inside inside another and a third function. How can I call my nested function inside of my third function? Is there any special libraries I can use? I am not allowed to edit a() or b(), only c(). def a(): def b(): print("hi") def c(): # code only here to call b() to print
[ "When you do this, function b is defined locally within a. This means that it cannot be accessed by default outside of a. There are two main ways to solve this, but both involve modifying a:\n\nThe global keyword (not recommended)\ndef a():\n global b\n def b():\n print(\"hi\")\n\nHere the global keywo...
[ 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0050786308_python.txt
Q: TypeError: can only concatenate str (not "relativedelta") to str i'm trying to get next month from selected date. if i using datetime.date.today() its ok. but i need working with request date. how can i solve it.Thanks date = request.form['date'] print(date) // 2022-11-05 // nextmonth = datetime.date.today() + rel...
TypeError: can only concatenate str (not "relativedelta") to str
i'm trying to get next month from selected date. if i using datetime.date.today() its ok. but i need working with request date. how can i solve it.Thanks date = request.form['date'] print(date) // 2022-11-05 // nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1) nextmonth = date + relativedelta.re...
[ "You have to convert str to date and then use relativedelta.relativedelta.\nNot sure what format the date is, I am assuming it is YYYY-MM-DD.\nYou can change the day and month format as per what you want.\nimport datetime\nfrom dateutil import relativedelta\ndate = '2022-11-05'\ndate = datetime.datetime.strptime(da...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074326030_python.txt
Q: Flask-Admin: How to prevent deletion of inline_models? I'm trying to prevent the deletion of certain entries in the inline model views with flask-admin: The respective inline model code looks like this: class ModelCategoryValueInline(InlineFormAdmin): form_columns = ('id', 'display_name', 'name') form_edi...
Flask-Admin: How to prevent deletion of inline_models?
I'm trying to prevent the deletion of certain entries in the inline model views with flask-admin: The respective inline model code looks like this: class ModelCategoryValueInline(InlineFormAdmin): form_columns = ('id', 'display_name', 'name') form_edit_columns = ('id', 'display_name') can_delete = False ...
[ "Even though this is not an ideal solution I've managed to achieve the desired behaviour by editing the inline_list_base.html template:\n{% macro render_inline_fields(field, template, render, check=None) %}\n<div class=\"inline-field\" id=\"{{ field.id }}\">\n {# existing inline form fields #}\n <div class=\"...
[ 0, 0 ]
[]
[]
[ "flask", "flask_admin", "flask_wtforms", "python" ]
stackoverflow_0074136227_flask_flask_admin_flask_wtforms_python.txt
Q: sqlite3: Incorrect number of bindings supplied Here is my code: def update(id, title, author, year, isbn): conn = sqlite3.connect("books.db") cur = conn.cursor() cur.execute("UPDATE book SET title=?, author=?, year=? WHERE id=?", (title, author, year, isbn, id)) conn.commit() conn.close Gettin...
sqlite3: Incorrect number of bindings supplied
Here is my code: def update(id, title, author, year, isbn): conn = sqlite3.connect("books.db") cur = conn.cursor() cur.execute("UPDATE book SET title=?, author=?, year=? WHERE id=?", (title, author, year, isbn, id)) conn.commit() conn.close Getting the following error: Incorrect number of bindings ...
[ "cur.execute(\"UPDATE book SET title=?, author=?, year=? WHERE id=?\", (title, author, year, id))\n" ]
[ 0 ]
[]
[]
[ "binding", "python", "sql", "sqlite" ]
stackoverflow_0062265284_binding_python_sql_sqlite.txt
Q: Extract value from list inside JSON dictionary (Python) I need to extract a value from a dictionary, inside a list, inside a dictionary. The value I'm tryng to get is dealId inside affectedDeals. (highlighted with ^) data = {'date': '2022-11-04T12:36:57.016', 'status': 'OPEN', 'reason': 'SUCCESS', 'dealStatus': '...
Extract value from list inside JSON dictionary (Python)
I need to extract a value from a dictionary, inside a list, inside a dictionary. The value I'm tryng to get is dealId inside affectedDeals. (highlighted with ^) data = {'date': '2022-11-04T12:36:57.016', 'status': 'OPEN', 'reason': 'SUCCESS', 'dealStatus': 'ACCEPTED', 'epic': 'SILVER', 'dealReference': 'o_0bc30104-8dd...
[ "May be this could help you to get the output as expected in question\nCode:\ndata = {\n \"date\": \"2022-11-04T12:36:57.016\",\n \"status\": \"OPEN\",\n \"reason\": \"SUCCESS\",\n \"dealStatus\": \"ACCEPTED\",\n \"epic\": \"SILVER\",\n \"dealReference\": \"o_0bc30104-8ddf-4d67-9daa-e7d878a8cad9\"...
[ 0, 0 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0074326207_dictionary_json_python.txt
Q: Checking conditionals Python Hi I am stuck on a question. I am new to coding and in order to attend a bootcamp I need to answer some questions. Nothing I write works, I always get a syntax error. This is the question: At your school, the front gate is locked at night for safety. You often need to study late on cam...
Checking conditionals Python
Hi I am stuck on a question. I am new to coding and in order to attend a bootcamp I need to answer some questions. Nothing I write works, I always get a syntax error. This is the question: At your school, the front gate is locked at night for safety. You often need to study late on campus. There is sometimes a night gu...
[ "There's a lot of mistakes there, on your first code, you forgot : after if and else, then inside the if statement, you forgot the hour variable that compares to 17, then your guard variable assignment inside the if and else block should use = instead of ==, finally on the last if statement, you should use the comp...
[ 0, 0, 0, 0 ]
[]
[]
[ "conditional_statements", "if_statement", "python", "syntax_error" ]
stackoverflow_0074326214_conditional_statements_if_statement_python_syntax_error.txt
Q: what does 'elem' means in 'for elem in smiles'? Can somebody please tell me that what elem means in for elem in smiles? I am learning programming by all my own and I have this problem. A: You have an object that contains other objects, probably an Array. In your example, this is called smiles. for elem in smiles...
what does 'elem' means in 'for elem in smiles'?
Can somebody please tell me that what elem means in for elem in smiles? I am learning programming by all my own and I have this problem.
[ "You have an object that contains other objects, probably an Array.\nIn your example, this is called smiles.\nfor elem in smiles will loop over each item in this array and assign the value of the current item to elem.\nSo imagine smiles is build up like this: [1,2,3], then the loop will run 3 times. Elem will be 1 ...
[ 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074326208_for_loop_python.txt
Q: Fastest way to generate random bits for Brownian Motion simulation with Python TL;DR: I try to generate large amounts of random numbers from a set of [-1, 1] I found out that np.random.Generator.choice is the worst method while the best one is to use np.random.Generator.random and move from boolean and to integer....
Fastest way to generate random bits for Brownian Motion simulation with Python
TL;DR: I try to generate large amounts of random numbers from a set of [-1, 1] I found out that np.random.Generator.choice is the worst method while the best one is to use np.random.Generator.random and move from boolean and to integer. Is there a better way to generate such random numbers in large amounts? I want to s...
[ "It will be a lot faster to generate 32 bit unsigned integers, and extract 32 random bits from each integer. By asking for a full range, I believe that avoids any scaling or conversion overhead from manipulating the words pulled from the rng, so it should be the most efficient (eg, calling rng.bytes uses this meth...
[ 3, 1 ]
[]
[]
[ "numpy", "python", "random" ]
stackoverflow_0074324633_numpy_python_random.txt
Q: python recursive pascal triangle After completing an assignment to create pascal's triangle using an iterative function, I have attempted to recreate it using a recursive function. I have gotten to the point where I can get it to produce the individual row corresponding to the number passed in as an argument. But ...
python recursive pascal triangle
After completing an assignment to create pascal's triangle using an iterative function, I have attempted to recreate it using a recursive function. I have gotten to the point where I can get it to produce the individual row corresponding to the number passed in as an argument. But several attempts to have it produce th...
[ "You just need to pass a list of lists through the recursion, and pick off the last element of the list (i.e. the last row of the triangle) to build your new row. Like so:\ndef triangle(n):\n if n == 0:\n return []\n elif n == 1:\n return [[1]]\n else:\n new_row = [1]\n result ...
[ 13, 4, 0 ]
[ "Yes, as Karl Knechtel also showed, recursive Pascal Triangle can go this way :\nP=lambda h:(lambda x:x+[[x+y for x,y in zip(x[-1]+[0],[0]+x[-1])]])(P(h-1))if h>1 else[[1]]\nprint(P(10))\n\n" ]
[ -1 ]
[ "pascals_triangle", "python", "recursion" ]
stackoverflow_0010628788_pascals_triangle_python_recursion.txt
Q: Substitute Regex pattern with another pattern dynamically I am trying to do the following in python, where I have a long pattern where I need to substitute a portion of the pattern dynamically substitutions = [rgx1, rgx2] pattern = start_pattern<dynamic_substitution>end_pattern for substitution in substitutions: ...
Substitute Regex pattern with another pattern dynamically
I am trying to do the following in python, where I have a long pattern where I need to substitute a portion of the pattern dynamically substitutions = [rgx1, rgx2] pattern = start_pattern<dynamic_substitution>end_pattern for substitution in substitutions: newpattern = start_pattern<substitution>end_pattern Is ther...
[ "I think this may be what you are wanting to do... or at least this is the way that I would do it.\n\ncompile the regex patterns that you need\nadd them to a list\niterate through the list as required\nuse the regex function that is appropriate for your needs eg. findall, search, match etc.\n\nimport re\n\nrgx1 = r...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074323724_python_regex.txt
Q: Get Web data with images for HTML table I am trying to extract the article body with images from this link, so that using the extracted article body I can make a HTML table. So, I have tried using BeautifulSoup. t_link = 'https://www.cnbc.com/2022/01/03/5-ways-to-reset-your-retirement-savings-and-save-more-money-i...
Get Web data with images for HTML table
I am trying to extract the article body with images from this link, so that using the extracted article body I can make a HTML table. So, I have tried using BeautifulSoup. t_link = 'https://www.cnbc.com/2022/01/03/5-ways-to-reset-your-retirement-savings-and-save-more-money-in-2022.html' page = requests.get(t_link) soup...
[ "I didn't quite understand your goal, so mine is probably not the answer you want.\nIn the html source of that page you have all inside the script you at the bottom.\n\nIt has inside the content of the page in JSON format.\nIf you simply use grep and jq (a great JSON cli utility), you can run\ncurl -kL \"https://ww...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074284673_beautifulsoup_python_web_scraping.txt
Q: ValueError: time data '2022-07-25 15:35:50.717 +0530' does not match format '%Y-%m-%d,%H%M%S%f%z' I need to print a specific date along with time in the format yyyy/mm/dd HH/MM/SS when the input is given in the format yyyy/mm/dd HH/MM/SS/%f/%z I tried this code: import datetime print(datetime.datetime.strptime("2...
ValueError: time data '2022-07-25 15:35:50.717 +0530' does not match format '%Y-%m-%d,%H%M%S%f%z'
I need to print a specific date along with time in the format yyyy/mm/dd HH/MM/SS when the input is given in the format yyyy/mm/dd HH/MM/SS/%f/%z I tried this code: import datetime print(datetime.datetime.strptime("2022-07-25 15:35:50.717 +0530", "%Y-%m-%d %H%M%S%f%z").strftime("%m/%d/%Y %H%M%S")) and was expecting a...
[ "You forgot about : in between hour, minute, second.\nimport datetime\n\nprint(datetime.datetime.strptime(\"2022-07-25 15:35:50.717 +0530\", \"%Y-%m-%d %H:%M:%S.%f %z\").strftime(\"%m/%d/%Y %H:%M:%S\"))\n>>> 07/25/2022 15:35:50\n\n" ]
[ 1 ]
[]
[]
[ "datetime_format", "python" ]
stackoverflow_0074326332_datetime_format_python.txt
Q: Django's dumpdata only dumping auth permission and contenttypes data I use local Postgres on the dev environment and deployed my app to Heroku with Postgres as well. I migrated my database, and now I want to load my data. The app works fine on Heroku, but without data. I have different settings files for dev and p...
Django's dumpdata only dumping auth permission and contenttypes data
I use local Postgres on the dev environment and deployed my app to Heroku with Postgres as well. I migrated my database, and now I want to load my data. The app works fine on Heroku, but without data. I have different settings files for dev and prod - with local Postgres and Postgres on Heroku correspondingly. I have m...
[ "Simply you can try this command:\nheroku run python manage.py dumpdata --natural -- > data.json\n\n" ]
[ 0 ]
[]
[]
[ "django", "dumpdata", "loaddata", "postgresql", "python" ]
stackoverflow_0074326021_django_dumpdata_loaddata_postgresql_python.txt
Q: Pygame not updating dialogue within a sprite group I have an issue with my dialogue index updating but not updating the text drawn to the screen. If the player is within distance of the npc the space button should update the dialogue. Currently it does draw the first index of dialogue if the player collides with t...
Pygame not updating dialogue within a sprite group
I have an issue with my dialogue index updating but not updating the text drawn to the screen. If the player is within distance of the npc the space button should update the dialogue. Currently it does draw the first index of dialogue if the player collides with the npc but moving away doesn't change anything as well a...
[ "The list of size tuples is self.dialog.sizes, not self.dialog.size:\nif self.dialog.index < len(self.dialog.size)-1:\nif self.dialog.index < len(self.dialog.sizes)-1:\n\n" ]
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074145151_pygame_python.txt
Q: Player sprite not behind isometric tiles I am currently trying to learn how to use isometric maps in a game environment. I'm using Tiled Map Editor to create a map and PyTMX and Pygame to read and use the information. I am currently making the maps in layers and treating them as big Sprites. This way I can use '''...
Player sprite not behind isometric tiles
I am currently trying to learn how to use isometric maps in a game environment. I'm using Tiled Map Editor to create a map and PyTMX and Pygame to read and use the information. I am currently making the maps in layers and treating them as big Sprites. This way I can use ''' pygame.sprites.LayerUpdates ''' Doing this a...
[ "You have to draw the the objects in the correct order:\n\ndraw the isometric map\n\nSort the objects (player, strair, etc.) by their lower y-coordinate and render them from bottom to top\n\n\n" ]
[ 1 ]
[]
[]
[ "isometric", "pygame", "python", "pytmx", "tiled" ]
stackoverflow_0073800057_isometric_pygame_python_pytmx_tiled.txt
Q: Issue connecting to the Kernel in Jupyter notebook I have just installed my Jupyter notebook to run Python . I have an active internet connection and python installed . I am getting an error saying "A connection to the notebook server could not be established. The notebook will continue trying to reconnect. Check...
Issue connecting to the Kernel in Jupyter notebook
I have just installed my Jupyter notebook to run Python . I have an active internet connection and python installed . I am getting an error saying "A connection to the notebook server could not be established. The notebook will continue trying to reconnect. Check your network connection or notebook server configuratio...
[ "I think you may have too many variables affecting your install to be able to determine exactly what is wrong. I would recommend starting with a fresh install of Python use either 3.10.8 or 3.11.0:\nhttps://www.python.org/ftp/python/3.10.8/python-3.10.8-amd64.exe\nhttps://www.python.org/ftp/python/3.11.0/python-3.1...
[ 1 ]
[]
[]
[ "anaconda", "anaconda3", "jupyter_notebook", "pycharm", "python" ]
stackoverflow_0074326053_anaconda_anaconda3_jupyter_notebook_pycharm_python.txt
Q: Have function loop n times, or until the end I have a class I use for scraping a site. It uses the requests library sessions and looks something like this: class Scraper: def scrape_page(self): """Scrapes the current page""" # do something self.request_next_page() def request_next...
Have function loop n times, or until the end
I have a class I use for scraping a site. It uses the requests library sessions and looks something like this: class Scraper: def scrape_page(self): """Scrapes the current page""" # do something self.request_next_page() def request_next_page(self): """ Finds the 'next' link if ...
[ "This funtionality can be implemented using either a while-loop or recursion. While-loops tend to be more efficient and easier to read. Also, recursion can raise errors when the number of nested calls is too large.\nFor the main loop in scrape_pages I would do something like this:\ndef scrape_pages(self, num):\n ...
[ 0 ]
[]
[]
[ "loops", "methods", "python", "python_3.x", "python_class" ]
stackoverflow_0074326405_loops_methods_python_python_3.x_python_class.txt
Q: python multiline regex with intricated or intexmixed results ; is it possible to match all result in a single pattern? exemple of text to illustrate what i want to do : i want to match all files xxx.txt found and processed : texte=""" ..................................................................... ... ... fo...
python multiline regex with intricated or intexmixed results ; is it possible to match all result in a single pattern?
exemple of text to illustrate what i want to do : i want to match all files xxx.txt found and processed : texte=""" ..................................................................... ... ... found: a_dir/a_sub_dir/aaa.txt ..................................................................... ... ... found: a_dir/a_...
[ "It is easy to do it line by line because each tag (found, startprocess, endprocess) is followed by the filename.\nAnd so more faster than trying to match all tags in multiline mode.\n(thanks to Tim Roberts)\nPython script with the solution line by line :\n#!/usr/bin/python\n\nimport re\n\n# input string\ninput_str...
[ 0 ]
[]
[]
[ "multiline", "python", "regex" ]
stackoverflow_0074306264_multiline_python_regex.txt
Q: Cannot open Local Terminal Failed to start [cmd.exe] in C:/Users/Home/PycharmProjects/untitled in PyCharm i can't use terminal in PyCharm, i saw a lot of submissions about this problem but there's no clear answer, and most of them are "your antivirus's blocking cmd for PyCharm" (or something like that), but i don'...
Cannot open Local Terminal Failed to start [cmd.exe] in C:/Users/Home/PycharmProjects/untitled in PyCharm
i can't use terminal in PyCharm, i saw a lot of submissions about this problem but there's no clear answer, and most of them are "your antivirus's blocking cmd for PyCharm" (or something like that), but i don't use any. also i'm on Windows 7 i don't know if that's the problem.
[ "Go to File > Settings > Terminal and change shell path from powershell.exe to C:\\Windows\\System32\\cmd.exe.\nThis fixed the issue.\n" ]
[ 1 ]
[]
[]
[ "pycharm", "python", "python_3.x" ]
stackoverflow_0059089910_pycharm_python_python_3.x.txt
Q: Access variables from main program in python I'm new to this website, may I have some help on the following? I have a main.py program that contains the dictionary loaddict. I have a module outside of the main program that contains multiple functions which all of them requires the dictionary loaddict from the main ...
Access variables from main program in python
I'm new to this website, may I have some help on the following? I have a main.py program that contains the dictionary loaddict. I have a module outside of the main program that contains multiple functions which all of them requires the dictionary loaddict from the main program. Is there a way to access the dictionary l...
[ "Your mistake\nIn my opinion your mistake is only the import instruction, so in your code it is necessary only a correct import:\nfrom main import loaddict\n\nBelow I show you the 2 files that I have created in my system (both file are in the same folder /home/frank/stackoverflow).\nmain.py\nloaddict = {'key1': 'va...
[ 2 ]
[]
[]
[ "module", "python", "variables" ]
stackoverflow_0074326299_module_python_variables.txt
Q: Import Library failed but resource succeeded in Robotframework Imported a resource succeeded with no error but the libraries show path error as it has no such path. The code is below as a part of the project of Robotframework. All other testcases share the same issues. The code with error is \*\*\* Settings \*\*\...
Import Library failed but resource succeeded in Robotframework
Imported a resource succeeded with no error but the libraries show path error as it has no such path. The code is below as a part of the project of Robotframework. All other testcases share the same issues. The code with error is \*\*\* Settings \*\*\* Documentation Library ../lib/ue/SparkLibrary/common.py Lib...
[ "It seems to me that content inside your common.py is having error.\n\nImporting library 'common' failed: ModuleNotFoundError: No module named 'flexbot'\n\nSo in above error line it is saying that you don't have flexbot library installed. So Try to install this library and then run your robot script again.\nNOTE- I...
[ 0 ]
[]
[]
[ "python", "robotframework", "visual_studio_code" ]
stackoverflow_0074311848_python_robotframework_visual_studio_code.txt
Q: Piping in Python like R - adding rank I have a dataframe like so: Feature RFI col1 1.8 col2 1.1 col3 2.1 col4 2.8 col5 0.3 How can I get the following output in one line? Rank Feature RFI 3 col1 1.8 4 col2 1.1 2 col3 2.1 1 col4 2.8 5 col5 0.3 I have the following code...
Piping in Python like R - adding rank
I have a dataframe like so: Feature RFI col1 1.8 col2 1.1 col3 2.1 col4 2.8 col5 0.3 How can I get the following output in one line? Rank Feature RFI 3 col1 1.8 4 col2 1.1 2 col3 2.1 1 col4 2.8 5 col5 0.3 I have the following code to sort: df.sort_values('RFI', ascending =...
[ "With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"Feature\": [\"col1\", \"col2\", \"col3\", \"col4\", \"col5\"],\n \"RFI\": [1.8, 1.1, 2.1, 2.8, 0.3],\n }\n)\n\nHere is one way to do it:\ndf[\"Rank\"] = (\n df.sort_values(\"RFI\", ascending=False)\n .rese...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074290849_pandas_python.txt
Q: Django - Static Files from App Directories In a development environment, I'd like to use static files from the app directories. #settings.py SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATIC_ROOT = (os.path.join(SITE_ROOT, 'static_files/')) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(...
Django - Static Files from App Directories
In a development environment, I'd like to use static files from the app directories. #settings.py SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATIC_ROOT = (os.path.join(SITE_ROOT, 'static_files/')) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(SITE_ROOT, 'static/'), ) STATICFILES_FINDERS = (...
[ "Ok I found the problem, I made an oversight that was not visible in my question. I was searching into in static/js, static/flash, static/css, static/images and put the files directly into app/static so they were not found.\n", "Check the value of STATIC_ROOT and STATICFILES_DIRS.\nAdd a print in your setting fi...
[ 3, 1, 0 ]
[]
[]
[ "django", "django_settings", "python", "static_files" ]
stackoverflow_0006409920_django_django_settings_python_static_files.txt
Q: Get mean based on the other columns Suppose I've a dataset which has 2 columns named : 'rate' 'rest_type' and they have values like : rate rest_type 3.4 dining 4 casual 3 cafe 3.4 delivery 4 mexian 3 italian 4.4 indian 4 south_indian 3 cafe Now I want to calculate the m...
Get mean based on the other columns
Suppose I've a dataset which has 2 columns named : 'rate' 'rest_type' and they have values like : rate rest_type 3.4 dining 4 casual 3 cafe 3.4 delivery 4 mexian 3 italian 4.4 indian 4 south_indian 3 cafe Now I want to calculate the mean of only the rate which has correspond...
[ "Use boolean indexing:\nout = df.loc[df['rest_type'].isin(['cafe', 'dining']), 'rate'].mean()\n\noutput: 3.1333333333333333\nIntermediate:\ndf.loc[df['rest_type'].isin(['cafe', 'dining']), 'rate']\n\n0 3.4\n2 3.0\n8 3.0\nName: rate, dtype: float64\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074326654_dataframe_pandas_python.txt
Q: Finding Root of a Scatter Plot (Python) I am currently plotting a hysterisis, out of a data set. It has following form: Image of Hysterisis The data looks like this: B(mT) U (V) std (V) direction loop -599.9600 0.2104 0.0019 1.0000 1.0000 -594.9676 0.1994 0.0011 1.0000 1.0000 Now I am trying...
Finding Root of a Scatter Plot (Python)
I am currently plotting a hysterisis, out of a data set. It has following form: Image of Hysterisis The data looks like this: B(mT) U (V) std (V) direction loop -599.9600 0.2104 0.0019 1.0000 1.0000 -594.9676 0.1994 0.0011 1.0000 1.0000 Now I am trying to find the point of the curve going upwards...
[ "You can easily find the roots using scipy.interp1d:\n# [x,y] is one of the plotted curves.\ni = np.argmin(np.fabs(y)) # find point closest to the root\nx, y = x[i-3:i+4], y[i-3:i+4] # make sub-arrays near the root\nx_root = scipy.interp1d(y, x, kind='linear')(0)\n\nBasically, we interpolate a multi-linear curv...
[ 0 ]
[]
[]
[ "plot", "python", "root", "scatter_plot" ]
stackoverflow_0074326634_plot_python_root_scatter_plot.txt
Q: Is there a way to click on a checkbox to make a list item active? I want to check a checkbox and a class will be added to a list item that will reduce the opacity and also line-through the list item to show completion of task. This is what I did but it is not working. var btn = document.querySelector('.btn') v...
Is there a way to click on a checkbox to make a list item active?
I want to check a checkbox and a class will be added to a list item that will reduce the opacity and also line-through the list item to show completion of task. This is what I did but it is not working. var btn = document.querySelector('.btn') var inputValue = document.querySelector('input'); var ulContainer = doc...
[ "I think you want to do something like this:\n\n\nlet list = document.querySelector('ul');\nlist.addEventListener('click', function(ev) {\n if (ev.target.tagName === 'LI') {\n ev.target.classList.toggle('checked');\n }\n}, false);\n* {\n box-sizing: border-box;\n}\n\nul {\n margin: 0;\n padding: 0;\n}\n\nul...
[ 1 ]
[]
[]
[ "javascript", "list", "python", "todo", "todoist" ]
stackoverflow_0074326408_javascript_list_python_todo_todoist.txt
Q: How to initialize a datetime.time object from a string? Is there a method like datetime.datetime.strptime(), that accepts a string like '16:00' and returns a datetime.time(16,0) object (i.e., an object that holds only time, not date)? Edit: I could use datetime.datetime.strptime(), but it would return a datetime.d...
How to initialize a datetime.time object from a string?
Is there a method like datetime.datetime.strptime(), that accepts a string like '16:00' and returns a datetime.time(16,0) object (i.e., an object that holds only time, not date)? Edit: I could use datetime.datetime.strptime(), but it would return a datetime.datetime, and I want only time, not a date.
[ "import time\ntime.strptime(\"16:00\", \"%H:%M\")\n\n", "import datetime\nimport time\ndef datetimestrptime(time_string,time_fmt):\n t = time.strptime(time_string,time_fmt)\n return datetime.time(hour=t.tm_hour,minute=t.tm_min,second=t.tm_sec)\nprint datetimestrptime(\"16:00\",\"%H:%M\")\n16:00:00\n\n", ...
[ 5, 3, 0 ]
[]
[]
[ "datetime", "python", "strptime", "time" ]
stackoverflow_0012554774_datetime_python_strptime_time.txt
Q: Bar Chart of sleep time duration I have the foloowing dataset: user_id: name of user - eg: 'user1' start: when user started sleeping - eg: '2022-09-24 22:00:00+02:00' stop: when user stopped sleeping - eg: '2022-09-25 04:30:00+02:00' Desired output: I would like to plot a bar/line chart with: x axis: time of c...
Bar Chart of sleep time duration
I have the foloowing dataset: user_id: name of user - eg: 'user1' start: when user started sleeping - eg: '2022-09-24 22:00:00+02:00' stop: when user stopped sleeping - eg: '2022-09-25 04:30:00+02:00' Desired output: I would like to plot a bar/line chart with: x axis: time of clock (0 to 24 hours) y axis: user_id ...
[ "I think what you're looking for is a gantt chart. See the following example:\nimport pandas as pd\nimport numpy as np\nimport plotly.graph_objs as go\nfrom datetime import timedelta\nfrom datetime import datetime\nimport plotly.figure_factory as ff\nfrom dateutil.parser import parse\n\ndf = pd.DataFrame({'Task': ...
[ 2 ]
[]
[]
[ "datetime", "duration", "pandas", "plot", "python" ]
stackoverflow_0074322509_datetime_duration_pandas_plot_python.txt
Q: How to show matching rows of two columns in a multi index dataframe? I want to show the matching rows from sub_col1 and sub_col2 having a multi index dataframe. How can I do so? Here is my dataframe import pandas as pd multi_index = pd.MultiIndex.from_tuples( [("r0", "rA"), ("r1", "rB"), ("r4", "rB")], names=...
How to show matching rows of two columns in a multi index dataframe?
I want to show the matching rows from sub_col1 and sub_col2 having a multi index dataframe. How can I do so? Here is my dataframe import pandas as pd multi_index = pd.MultiIndex.from_tuples( [("r0", "rA"), ("r1", "rB"), ("r4", "rB")], names=["Courses", "Fee"] ) cols = pd.MultiIndex.from_tuples([("col1", "sub_col1"...
[ "Here is one way to do it using Pandas apply and concat:\n# Check for corresponding values\ndf[(\"col2\", \"sub_col2\")] = df.apply(\n lambda x: x[(\"col1\", \"sub_col1\")]\n if x[(\"col1\", \"sub_col1\")] in df[(\"col2\", \"sub_col2\")].tolist()\n else x[(\"col2\", \"sub_col2\")],\n axis=1,\n)\n\n# Reo...
[ 1 ]
[]
[]
[ "comparison", "dataframe", "multi_index", "pandas", "python" ]
stackoverflow_0074290356_comparison_dataframe_multi_index_pandas_python.txt
Q: How do I check if a rectangle can fit into a bounding area? I wrote a function that generates a lot of things like this: [ (0, 619.5312394955338, 337.573529597446, 1080), (619.5312394955338, 1544.7619727875272, 0, 310.3079296654736), (619.5312394955338, 1544.7619727875272, 310.3079296654736...
How do I check if a rectangle can fit into a bounding area?
I wrote a function that generates a lot of things like this: [ (0, 619.5312394955338, 337.573529597446, 1080), (619.5312394955338, 1544.7619727875272, 0, 310.3079296654736), (619.5312394955338, 1544.7619727875272, 310.3079296654736, 337.573529597446), (1544.7619727875272, 1920, 0, 310.30...
[ "IMHO, this is an instance of the bin packing problem, resp. the sub-type of rectangle packing. Simplified, this means, in general, there is not better/faster solution than really trying every possible combination to find the matches.\nWikipedia links two different possible approaches with a little improved runtime...
[ 1, 1, 0 ]
[]
[]
[ "algorithm", "python", "python_3.x" ]
stackoverflow_0072569297_algorithm_python_python_3.x.txt
Q: How to add or sum multiple variables and return an int I seem to have a problem with converting types properly in general. This is just my most recent example. I want to take the variables b, w, r, u, g, and colorless, add their values together, and return an int. I'm posting the entire created class because it...
How to add or sum multiple variables and return an int
I seem to have a problem with converting types properly in general. This is just my most recent example. I want to take the variables b, w, r, u, g, and colorless, add their values together, and return an int. I'm posting the entire created class because its entirely likely that I have more than one problem here. im...
[ "I figured out the answer to my own problem. I was making this more complicated than I needed to. Instead of trying to count each occurence of b, w, r, u, g I should have just used the len() function.\nclass MTG_card:\n\ndef __init__(self, card_type, rarity, mana_cost, modifier_1=None, modifier_2=None, modifier_3...
[ 0 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0074325651_class_methods_python.txt
Q: No module named when using PyInstaller I try to compile a Python project under Windows 7 using PyInstaller. The project works fine, there are no issues, however when I try to compile it the result doesn't work. Though I get no warnings during compilation there are many in the warnmain.txt file in the build directo...
No module named when using PyInstaller
I try to compile a Python project under Windows 7 using PyInstaller. The project works fine, there are no issues, however when I try to compile it the result doesn't work. Though I get no warnings during compilation there are many in the warnmain.txt file in the build directory: warnmain.txt I don't really understand t...
[ "Had a similar problem with no module named FileDialog. Discovered that with version 3.2, I could use \npyinstaller --hidden-import FileDialog ... \ninstead of modifying my main script.\n", "Pyinstaller won't see second level imports. So if you import module A, pyinstaller sees this. But any additional module th...
[ 31, 24, 14, 11, 4, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "matplotlib", "numpy", "pyinstaller", "pyqt4", "python" ]
stackoverflow_0025733467_matplotlib_numpy_pyinstaller_pyqt4_python.txt
Q: Python file not getting imported from different directory in robot framework Hi I am trying to import python file in my robot code using library function like this. Library /Users/test/Desktop/bb/src/json.py Library /Users/test/Desktop/bb/src/csv.py I have another python file in same directory that is working. ...
Python file not getting imported from different directory in robot framework
Hi I am trying to import python file in my robot code using library function like this. Library /Users/test/Desktop/bb/src/json.py Library /Users/test/Desktop/bb/src/csv.py I have another python file in same directory that is working. I imported like this. Library ./API.py But those two files not getting imported....
[ "I'm not familiar with the 'Library' command, but if it follows the same logic as 'import', then the following can help:\nLet's say I have a python file 'module_test.py' located in 'C:/Users/Public/'\n, and I'm coding in a different directory. Then to import this file, I should add it to the path list before import...
[ 0, 0 ]
[]
[]
[ "pycharm", "python", "python_3.x", "robotframework" ]
stackoverflow_0074307890_pycharm_python_python_3.x_robotframework.txt
Q: call a nested function (function inside another function) I have a function like def mode1(): #some code def form_fill(): #some code def error(): #some other code and in somewhere else in the code, I want to call the form_fill() only what I've already tried is event, value = window.read() if even...
call a nested function (function inside another function)
I have a function like def mode1(): #some code def form_fill(): #some code def error(): #some other code and in somewhere else in the code, I want to call the form_fill() only what I've already tried is event, value = window.read() if event == 'Mode 1': mode1_submit() mode1() if event == 'Mode...
[ "THIS IS NOT SOMETHING YOU SHOULD DO, but you could create a nested function attribute like so:\ndef foo():\n # for closures or strictly local function\n # then this is useful!\n # ugly hack other wise to try and create methods.\n def bar():\n print('bar') \n \n # if there are multiple f...
[ 4, 0, 0 ]
[ "You should probably use a class for this problem, but if you really want to use a nested loop you could do something like this:\ndef mode1(function_to_call=None):\n print(\"mode1\")\n\n def form_fill():\n print(\"form_fill\")\n\n def error():\n print(\"error\")\n\n possibles = locals().co...
[ -1 ]
[ "python" ]
stackoverflow_0068553220_python.txt