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:
small project that is a phone book first for loop its dosent work and in need
phone_book = {1111111111:"amal",
2222222222:"Mohammed",
3333333333:"Khadijah",
4444444444:"Abdullah",
5555555555:"Rawan",
6666666666:"Fai... | small project that is a phone book first for loop its dosent work and in need | phone_book = {1111111111:"amal",
2222222222:"Mohammed",
3333333333:"Khadijah",
4444444444:"Abdullah",
5555555555:"Rawan",
6666666666:"Faisal",
7777777777:"Layla"}
xx = int(input('Enter the number : ')... | [
"I dind't understand the second part but try it like this:\ncode:\nphone_book = {1111111111:\"amal\",\n 2222222222:\"Mohammed\",\n 3333333333:\"Khadijah\",\n 4444444444:\"Abdullah\",\n 5555555555:\"Rawan\",\n 6666666666:\... | [
0
] | [] | [] | [
"dictionary",
"for_loop",
"function",
"python"
] | stackoverflow_0074668930_dictionary_for_loop_function_python.txt |
Q:
cant add lowercase text discord bot in python
I have a small code to use it in discord created in python and I have a small problem
The command is currently written in uppercase text and I would like it to be written in lowercase, if it is not written in lowercase the bot does not send the images to discord
he com... | cant add lowercase text discord bot in python | I have a small code to use it in discord created in python and I have a small problem
The command is currently written in uppercase text and I would like it to be written in lowercase, if it is not written in lowercase the bot does not send the images to discord
he command is used:
!ubi ESTABLO ELEVADO
Should be used:... | [
"this is what you are looking for!\n@bot.command()\n async def ubi(ctx, *, args):\n response = requests.get('https://jose89fcb.es/apifortnite/api.io.php')\n data = response.json()\n for api in data['list']:\n if args in api[\"name\"].lower():\n \n awai... | [
0
] | [] | [] | [
"discord",
"python"
] | stackoverflow_0074669087_discord_python.txt |
Q:
Assign data in JSON file to a variable based on condition python
I am trying to grab data from JSON file based on what quarter the dates represent. My goal is to assign the data to a variable so I should have Q1, Q2, Q3, Q4 variables holding the data inside. Below is the JSON:
{
"lastDate":{
"0":"2022Q... | Assign data in JSON file to a variable based on condition python | I am trying to grab data from JSON file based on what quarter the dates represent. My goal is to assign the data to a variable so I should have Q1, Q2, Q3, Q4 variables holding the data inside. Below is the JSON:
{
"lastDate":{
"0":"2022Q4",
"1":"2022Q4",
"2":"2022Q4",
"7":"2022Q4",
... | [
"With pandas you can read this nested dictionary a transform it to a table representation. Then the aggregation you are required becomes quite natural.\nimport pandas as pd \n\nsample_dict = {\n \"lastDate\":{\n \"0\":\"2022Q4\",\n \"1\":\"2022Q4\",\n \"2\":\"2022Q4\",\n \"7\":\"2022Q... | [
1,
1,
0
] | [] | [] | [
"for_loop",
"json",
"python"
] | stackoverflow_0074666206_for_loop_json_python.txt |
Q:
Why won't list memorize previous inputs and sum them?
With each iteration the list only presents the last appended input and not the sum of the last input + previous appended inputs.
def main_program():
n = []
n.append(int(input("insert:\n")))
print(sum(n))
while True:
main_program()
if input("... | Why won't list memorize previous inputs and sum them? | With each iteration the list only presents the last appended input and not the sum of the last input + previous appended inputs.
def main_program():
n = []
n.append(int(input("insert:\n")))
print(sum(n))
while True:
main_program()
if input("Add another number? (Y/N):\n") == "N":
break
I'm t... | [
"Define n just once.\ndef main_program():\n n.append(int(input(\"insert:\\n\")))\n print(sum(n))\n\nn = []\nwhile True:\n main_program()\n if input(\"Add another number? (Y/N):\\n\") == \"N\":\n break\n\nPassing the list as parameter in the function main_program also works, since lists are call-b... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074669171_python_python_3.x.txt |
Q:
Tabula-py: specify parameters for tabula.io.build_options
I am trying to understand how the build_options function defined in tabula.io module and the java_options in function convert_into work.
To understand it I wrote my code with just the page options specified:
import tabula
options = tabula.io.build_options(p... | Tabula-py: specify parameters for tabula.io.build_options | I am trying to understand how the build_options function defined in tabula.io module and the java_options in function convert_into work.
To understand it I wrote my code with just the page options specified:
import tabula
options = tabula.io.build_options(pages="all")
dfs = tabula.io.convert_into('input.pdf',"output.cs... | [
"java_options expects list of string.\ntabula.convert_into('input.pdf',\"output.csv\",output_format=\"csv\", pages=\"all\")\n\nYou don't have to use build_options.\nSee also:\nhttps://tabula-py.readthedocs.io/en/latest/tabula.html#tabula.io.convert_into\n"
] | [
0
] | [] | [] | [
"python",
"tabula_py"
] | stackoverflow_0072317873_python_tabula_py.txt |
Q:
Incompatible shapes Mean Squared Error Keras
I want to train a RNN with Keras, the shape for the X is (4413, 71, 19) while for y is (4413,2)
Code
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, retur... | Incompatible shapes Mean Squared Error Keras | I want to train a RNN with Keras, the shape for the X is (4413, 71, 19) while for y is (4413,2)
Code
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.add(Dropout(.2))
model.add(BatchNormalization())
model.add(LSTM(128, return_sequences=True, input_shape=(None,19)))
model.ad... | [
"Try setting the parameter return_sequences of the last LSTM layer to False:\nmodel = Sequential()\nmodel.add(LSTM(128, return_sequences=True, input_shape=(None,19)))\nmodel.add(Dropout(.2))\nmodel.add(BatchNormalization())\n\nmodel.add(LSTM(128, return_sequences=True))\nmodel.add(Dropout(.2))\nmodel.add(BatchNorma... | [
1
] | [] | [] | [
"keras",
"lstm",
"python",
"tensorflow"
] | stackoverflow_0074669249_keras_lstm_python_tensorflow.txt |
Q:
Unable to load tables with "Load more" options in a website using Python
Need to scrape the full table from this site with "Load more" option.
As of now when I`m scraping , I only get the one that shows up by default on when loading the page.
import pandas as pd
import requests
from six.moves import urllib
URL2 =... | Unable to load tables with "Load more" options in a website using Python | Need to scrape the full table from this site with "Load more" option.
As of now when I`m scraping , I only get the one that shows up by default on when loading the page.
import pandas as pd
import requests
from six.moves import urllib
URL2 = "https://www.mykhel.com/football/indian-super-league-player-stats-l750/"
head... | [
"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0'\n}\n\n\ndef main(url):\n params = {\n \"action\": \"stats\",\n \"league_id\": \"750\",\n \"limit\": \"300\... | [
3,
0
] | [] | [] | [
"beautifulsoup",
"dataframe",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074668149_beautifulsoup_dataframe_pandas_python_web_scraping.txt |
Q:
How can i have two not arguments in an if statement
I want to check if the following value is not a digit and is not "a" or "b" but I'm met with a syntax error. It says it expect ":" after not in the second argument.
if not char.isdigit() and not in ('a', 'b'):
I don't know what I can try to fix this. I could nest... | How can i have two not arguments in an if statement | I want to check if the following value is not a digit and is not "a" or "b" but I'm met with a syntax error. It says it expect ":" after not in the second argument.
if not char.isdigit() and not in ('a', 'b'):
I don't know what I can try to fix this. I could nest the if statement but that leads to bad code and I know t... | [
"The line should be:\nif not char.isdigit() and char not in ('a', 'b'):\n\nYou have to declare what variable is not in ('a', 'b')\nFurthermore, I would take a look at how to structure questions on StackOverflow.\n"
] | [
2
] | [] | [] | [
"python",
"python_3.x",
"string"
] | stackoverflow_0074669271_python_python_3.x_string.txt |
Q:
Create a weighted graph from an adjacency matrix in graph-tool, python interface
How should I create a graph using graph-tool in python, out of an adjacency matrix?
Assume we have adj matrix as the adjacency matrix.
What I do now is like this:
g = graph_tool.Graph(directed = False)
g.add_vertex(len... | Create a weighted graph from an adjacency matrix in graph-tool, python interface | How should I create a graph using graph-tool in python, out of an adjacency matrix?
Assume we have adj matrix as the adjacency matrix.
What I do now is like this:
g = graph_tool.Graph(directed = False)
g.add_vertex(len(adj))
edge_weights = g.new_edge_property('double')
for i in range(adj... | [
"Graph-tool now includes a function to add a list of edges to the graph. You can now do, for instance:\nimport graph_tool as gt\nimport numpy as np\ng = gt.Graph(directed=False)\nadj = np.random.randint(0, 2, (100, 100))\ng.add_edge_list(np.transpose(adj.nonzero()))\n\n",
"this is the extension of Tiago's answer ... | [
13,
4,
2,
0
] | [] | [] | [
"graph",
"graph_tool",
"python"
] | stackoverflow_0023288661_graph_graph_tool_python.txt |
Q:
Append row to DataFrame in Pandas and putting it on bottom
I want to add a row to a multi-index dataframe and I want to group it in its outer index where the alphabetical order is important, i.e, I can't use df.sort_index().
Here is the problem.
Code:
import pandas as pd
import numpy as np
categories = {"A":["c",... | Append row to DataFrame in Pandas and putting it on bottom | I want to add a row to a multi-index dataframe and I want to group it in its outer index where the alphabetical order is important, i.e, I can't use df.sort_index().
Here is the problem.
Code:
import pandas as pd
import numpy as np
categories = {"A":["c", "b", "a"] , "B": ["a", "b", "c"], "C": ["a", "b", "d"] }
array ... | [
"df.loc[['A', 'B', 'C']]\n\noutput:\nA c 0.887137\n b -0.105262\n a -0.180093\n d 2.000000\nB a -0.687134\n b -1.120895\n c 2.398962\nC a -2.226126\n b -0.203238\n d 0.036068\ndtype: float64\n\nif you want get ['A', 'B', 'C'] by code, use following\nidx0 = df.index.get_level... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074669264_dataframe_pandas_python_python_2.7_python_3.x.txt |
Q:
When I append a path, python gives an error
I tried to add a directory path to sys.path, but it gives me an error:
import sys
sys.path.append("C:\Users\tamer\Desktop\code\python\modules")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
A:
This s... | When I append a path, python gives an error | I tried to add a directory path to sys.path, but it gives me an error:
import sys
sys.path.append("C:\Users\tamer\Desktop\code\python\modules")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
| [
"This should do it:\nsys.path.append(\"C:\\\\Users\\\\tamer\\\\Desktop\\\\code\\\\python\\\\modules\")\n",
"Another approach is to use raw string, basically r is prefixed.\nFor this use case it should be.\nsys.path.append(r\"C:\\Users\\tamer\\Desktop\\code\\python\\modules\")\n\n"
] | [
0,
0
] | [] | [] | [
"python",
"sys",
"sys.path",
"windows"
] | stackoverflow_0074667805_python_sys_sys.path_windows.txt |
Q:
Stable Diffusion (Wheel 'torch' located at ___ is invalid.)
I have been attempting to install stable diffusion and have run into this error that I have no idea how to fix. When attempting to run the webui-user i receive this message
venv "C:\Users\___\Desktop\AI\stable-diffusion-webui\venv\Scripts\Python.exe"
Pyt... | Stable Diffusion (Wheel 'torch' located at ___ is invalid.) | I have been attempting to install stable diffusion and have run into this error that I have no idea how to fix. When attempting to run the webui-user i receive this message
venv "C:\Users\___\Desktop\AI\stable-diffusion-webui\venv\Scripts\Python.exe"
Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.... | [] | [] | [
"Automatic1111 is easier to install from scratch and has a nice user interface.\nYou'll have to provide the instructions you're following for us to help troubleshoot your particular method.\n"
] | [
-1
] | [
"python",
"stable_diffusion"
] | stackoverflow_0074665626_python_stable_diffusion.txt |
Q:
how to call a dictionary key that is inside another dict
Have a little problem with a simple function that need solving
would like to be able to edit a dict with the update() but the problem is that I want to update it using its value and not its key
here is my code:
contacts = {"Mohamed": {"name": "Mohamed Sayed"... | how to call a dictionary key that is inside another dict | Have a little problem with a simple function that need solving
would like to be able to edit a dict with the update() but the problem is that I want to update it using its value and not its key
here is my code:
contacts = {"Mohamed": {"name": "Mohamed Sayed", "number": "0123565665", "birthday": "24.11.1990", "address":... | [
"If they enter the first name, then the sub-dictionary is simply contacts[name]. You don't need to loop over the whole contacts dictionary.\ndef edit_contact():\n name = input(\"Please enter the first name of the contact you want to edit: \")\n if name in contacts:\n print(contacts[name])\n else:\n... | [
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074669223_dictionary_list_python.txt |
Q:
Postponing the release of an element from resource when the next queue is full
I used some inputs that I got from this forum and got quite far while using simpy for the first time in my life for university. Now my question remains:
I can see that the customer/entity goes through process0 and the process1_broker b... | Postponing the release of an element from resource when the next queue is full | I used some inputs that I got from this forum and got quite far while using simpy for the first time in my life for university. Now my question remains:
I can see that the customer/entity goes through process0 and the process1_broker but gets stuck right after entering process1. It never comes out. What am I doing wro... | [
"I used a store with a capacity to act as a blocking queue\nProcess 1 will not release its process 1 resource until the entity can be put into the store. If the store is at capacity, it will block the put until process 2 pulls a entity from the store.\nTo manage the store, I have a broker process that matches enti... | [
0
] | [] | [] | [
"python",
"simpy",
"while_loop"
] | stackoverflow_0074667274_python_simpy_while_loop.txt |
Q:
Split Pandas dataframe by a specific custom parameter
I have a sample pandas dataframe as below:
What I want to do is to write a function to split this dataframe by its time value. The function returns a list of dataframes.
I used the below function to split the dataframe.
def split_dataframe(df, chunk_size=20):
... | Split Pandas dataframe by a specific custom parameter | I have a sample pandas dataframe as below:
What I want to do is to write a function to split this dataframe by its time value. The function returns a list of dataframes.
I used the below function to split the dataframe.
def split_dataframe(df, chunk_size=20):
chunks = list()
num_chunks = len(df) // chunk_size ... | [
"With the following toy dataframe:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"id\": [1, 1, 1, 2, 2, 3, 4, 4, 5, 5],\n \"sample_val\": [10, 11, 10, 12, 22, 22, 23, 23, 24, 24],\n \"time\": [300, 301, 301, 302, 302, 304, 311, 308, 309, 305],\n }\n)\n\nHere is one way to do it:\nN = ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074631375_dataframe_pandas_python.txt |
Q:
Splitting string, ignoring brackets including nested brackets
I would like to split a string at spaces (and colons), except inside curly brackets and rounded brackets. Similar questions have been asked, but the answers fail with nested brackets.
Here is an example of a string to split:
p1: I/out p2: (('mean', 5)... | Splitting string, ignoring brackets including nested brackets | I would like to split a string at spaces (and colons), except inside curly brackets and rounded brackets. Similar questions have been asked, but the answers fail with nested brackets.
Here is an example of a string to split:
p1: I/out p2: (('mean', 5), 0.0, ('std', 2)) p3: 7 p4: {'name': 'check', 'value': 80.0}
... | [
"You can use the following PCRE/Python PyPi regex compliant pattern:\n(?:(\\((?:[^()]++|(?1))*\\))|(\\{(?:[^{}]++|(?2))*})|[^\\s:])+\n\nSee the regex demo.\nIt matches\n\n(?: - start of a container non-capturing group:\n\n(\\((?:[^()]++|(?1))*\\)) - Group 1: a substring between two nested round brackets\n| - or\n(\... | [
3
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0074668806_python_regex_split.txt |
Q:
Python modules I've just installed in my virtual env, are not found
I'm using Ubuntu 20.04.5 LTS. Output of python3 --version command: Python 3.8.10
When I type pip in terminal and press TAB, it responds with the following options: pip, pip3, pip3.10 and pip3.8
But, when I use any of then with the --version flag, ... | Python modules I've just installed in my virtual env, are not found | I'm using Ubuntu 20.04.5 LTS. Output of python3 --version command: Python 3.8.10
When I type pip in terminal and press TAB, it responds with the following options: pip, pip3, pip3.10 and pip3.8
But, when I use any of then with the --version flag, it all prints the same output, which is: pip 22.3.1 from /home/myuser/.lo... | [
"Looks ok to me.\nIf your environment is activated try to just run\npython kmeans3.py\n\nor\npython3 kmeans3.py\n\n",
"I don't know why is that, but I solved this problem installing \"scikit-learn\" package before install \"sklearn\"\n"
] | [
0,
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"scikit_learn",
"virtualenv"
] | stackoverflow_0074632110_pip_python_python_3.x_scikit_learn_virtualenv.txt |
Q:
pow large numbers in Python
How can I raise large numbers to a power in python?
a = 62608558862573792084872798679396455703616395237802859621162736207631538899993
b = 93910650126758265671774994856253142403789359314618444886584691522424141933664
c = pow(a, b)
It is impossible to get an answer that way. Are there an... | pow large numbers in Python | How can I raise large numbers to a power in python?
a = 62608558862573792084872798679396455703616395237802859621162736207631538899993
b = 93910650126758265671774994856253142403789359314618444886584691522424141933664
c = pow(a, b)
It is impossible to get an answer that way. Are there any ways to raise large numbers to ... | [
"If you calculate the result to all digits, it has 10^78 digits. That's more than will fit into any RAM of any computer in the world today.\n\nIt is impossible to get an answer that way.\n\nIt will be impossible to get a precise answer for a long time, given that Earth only has ~10^50 atoms.\nThe number 62608558862... | [
3
] | [] | [] | [
"largenumber",
"pow",
"python"
] | stackoverflow_0074669402_largenumber_pow_python.txt |
Q:
User defined function through inputs in Python
I wish to create a custom calculator where the user defines two parameters and a function using a GUI and when they click on calculate it executes their user defined function passing the two parameters.
argument1 = IntSlider( … )
argument2 = IntSlider( … )
userDefined... | User defined function through inputs in Python | I wish to create a custom calculator where the user defines two parameters and a function using a GUI and when they click on calculate it executes their user defined function passing the two parameters.
argument1 = IntSlider( … )
argument2 = IntSlider( … )
userDefinedFunction = TextArea( … )
calculateButton = Button ( ... | [
"I'd probably go with something more limiting than a full function definition. Having the user create the function signature is going to add complications as you cannot eval it, you would have to exec it instead. Then finding out the method name would be complex, and it would allow the user to overwrite local varia... | [
1,
1
] | [] | [] | [
"ipywidgets",
"panel_pyviz",
"python"
] | stackoverflow_0074668885_ipywidgets_panel_pyviz_python.txt |
Q:
Python function about chemical formulas
I have a CSV file that contains chemical matter names and some info.What I need to do is add new columns and write their formulas, molecular weights and count H,C,N,O,S atom numbers in each formula.I am stuck with the counting atom numbers part.I have the function related i... | Python function about chemical formulas | I have a CSV file that contains chemical matter names and some info.What I need to do is add new columns and write their formulas, molecular weights and count H,C,N,O,S atom numbers in each formula.I am stuck with the counting atom numbers part.I have the function related it but I don't know how to merge it and make c... | [
"If I understand correctly, you should be able to use str.extract here:\ndf[\"H\"] = df[\"Formula\"].str.extract(r'H(\\d+)')\ndf[\"C\"] = df[\"Formula\"].str.extract(r'C(\\d+)')\ndf[\"N\"] = df[\"Formula\"].str.extract(r'N(\\d+)')\ndf[\"O\"] = df[\"Formula\"].str.extract(r'O(\\d+)')\ndf[\"S\"] = df[\"Formula\"].str... | [
1,
1
] | [] | [] | [
"chemistry",
"csv",
"python",
"python_3.x"
] | stackoverflow_0074668631_chemistry_csv_python_python_3.x.txt |
Q:
Python: Extract keywords from string
Hey Guys I am searching for a fast/efficient way to extract keywords (defined in a list) from a String (in a Dataframe) without being case sensitive or dependent on " " chars:
keys = ['I', 'love', 'Cookies']
String from df= "xxxxxxxxIxx xx cookies"
result should by either ['I']... | Python: Extract keywords from string | Hey Guys I am searching for a fast/efficient way to extract keywords (defined in a list) from a String (in a Dataframe) without being case sensitive or dependent on " " chars:
keys = ['I', 'love', 'Cookies']
String from df= "xxxxxxxxIxx xx cookies"
result should by either ['I'] or ['I', 'Cookies']
I am currently using ... | [
"Working code as per your inputs:\nmy_str =\"xxxxxxxixxx xx cookhes\"\nmy_list = [\"I\", \"love\", \"Cookies\"]\nif any(substring.casefold() in my_str.casefold() for substring in my_list):\n print('Contains element')\nelse:\n print('Not contain any element.')\n\nMore info on the following answer from StackOve... | [
0
] | [] | [] | [
"dataframe",
"python",
"string",
"substring"
] | stackoverflow_0074669279_dataframe_python_string_substring.txt |
Q:
hi why does my else in while loop is not working?
I wanted to select two numbers and when I run the program it will start form the lower one and will print me numbers one after one till the big number.
the loop in the while is working but the else doesnt work...
num1= int(input('enter first number'))
num2= int... | hi why does my else in while loop is not working? | I wanted to select two numbers and when I run the program it will start form the lower one and will print me numbers one after one till the big number.
the loop in the while is working but the else doesnt work...
num1= int(input('enter first number'))
num2= int (input('enter second number'))
while num1 > num2 :
... | [] | [] | [
"You haven't written If statement in your code that,s why its not working\n"
] | [
-1
] | [
"python",
"while_loop"
] | stackoverflow_0074669439_python_while_loop.txt |
Q:
Trying to get historical data for multiple securities using python and IB API - df not clearing between loops
I'm trying to get historical data for several products through the IB API, and store each product in a dataframe (which I need to save in separate csv files).
This is my code, the main issue is that the da... | Trying to get historical data for multiple securities using python and IB API - df not clearing between loops | I'm trying to get historical data for several products through the IB API, and store each product in a dataframe (which I need to save in separate csv files).
This is my code, the main issue is that the dataframe isn't clearing between loops, when moving onto the second loop the df contains data for 2 products, the thi... | [
"create a dictionary and append the app.data as a key value pair in the historicaldata callback. Then you can access them separately - in fact converting a dict to multi-level dataframe is also possible\n"
] | [
0
] | [] | [] | [
"ib_api",
"interactive_brokers",
"pandas",
"python",
"tws"
] | stackoverflow_0073211491_ib_api_interactive_brokers_pandas_python_tws.txt |
Q:
Create a link to a specific word count position such as bookmark in docx
How this project works:
Searches external docx / OCR data for a keyword
Builds a context of 100 words surrounding the keyword
Builds a docx to store the passage with a hyperlink posted under each completed search
What is missing:
A way to l... | Create a link to a specific word count position such as bookmark in docx | How this project works:
Searches external docx / OCR data for a keyword
Builds a context of 100 words surrounding the keyword
Builds a docx to store the passage with a hyperlink posted under each completed search
What is missing:
A way to link to the passage to its source from the external document in Word, so you ca... | [
"To build a system that searches for a keyword in external documents, extracts a context of 100 words surrounding the keyword, and creates a new document with hyperlinks to the passages in the original document. The problem you are facing is that the OCR documents do not have headings or bookmarks, so it is difficu... | [
0
] | [] | [] | [
"hyperlink",
"ms_word",
"python"
] | stackoverflow_0074669471_hyperlink_ms_word_python.txt |
Q:
Is it possible in Python to call a child from parent class without initialize the child?
I want to know if is it possible to create a parent class to handle some common logic, but have some specific logic in child classes and run it without initialize the child as it's in abstraction.
For example:
class Person:
... | Is it possible in Python to call a child from parent class without initialize the child? | I want to know if is it possible to create a parent class to handle some common logic, but have some specific logic in child classes and run it without initialize the child as it's in abstraction.
For example:
class Person:
def __init__(self, fname, lname, country):
self.firstname = fname
self.lastname = lnam... | [] | [] | [
"Yes, it is possible to create a parent class that has some common logic and child classes that have specific logic, and to call the child class methods without initializing an instance of the child class. However, the code you have provided will not work as you expect it to because it contains some errors and logi... | [
-1
] | [
"abstract_class",
"class_hierarchy",
"python",
"python_3.x"
] | stackoverflow_0074669535_abstract_class_class_hierarchy_python_python_3.x.txt |
Q:
Plotting Scatter plot with different lines
Please I am trying to plot a scatter plot as shown in the attached image.
I have tried the below code but it is not working. This is in python by the way.
hours = [n / 3600 for n in seconds]
fig, ax = plt.subplots(figsize=(8, 6))
## Your code here
ax.plot(hours, fish_coun... | Plotting Scatter plot with different lines | Please I am trying to plot a scatter plot as shown in the attached image.
I have tried the below code but it is not working. This is in python by the way.
hours = [n / 3600 for n in seconds]
fig, ax = plt.subplots(figsize=(8, 6))
## Your code here
ax.plot(hours, fish_counts, marker="x")
ax.set_xlabel("Hours since low t... | [
"To plot a scatter plot with the data you provided, you can use the scatter method instead of the plot method. Here is an example of how you could do this:\n# import the necessary packages\nimport matplotlib.pyplot as plt\n\n# define the data\nhours = [n / 3600 for n in seconds]\nfish_counts = [10, 12, 8, 11, 9, 15... | [
0,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074668688_matplotlib_python.txt |
Q:
Django - How do you create several model instances at the same time because they are connected
I want to create a user profile and the user profile has a location (address). I need to create the profile first and location second, and then match the profile and the location using a third model called ProfileLocatio... | Django - How do you create several model instances at the same time because they are connected | I want to create a user profile and the user profile has a location (address). I need to create the profile first and location second, and then match the profile and the location using a third model called ProfileLocation. I want to do this using one api call, because all the data comes from one form and the location d... | [
"your procedure is perfect, just need to override the create method of the serializer\ndef create(self, validated_data):\n # for better understand print or log the validated_data\n location_data = validated_data.pop('location') # all location data will be poped from the validated data as a dict\n ... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074668588_django_django_rest_framework_python.txt |
Q:
discord.py interaction error message not working
I'm trying to make an error handler with a command and it gives the user an ephermal message saying Invalid language but I get the following traceback (Below the code). I might be doing something wrong in the interaction argument (I'm new to the whole interaction th... | discord.py interaction error message not working | I'm trying to make an error handler with a command and it gives the user an ephermal message saying Invalid language but I get the following traceback (Below the code). I might be doing something wrong in the interaction argument (I'm new to the whole interaction thing and I'm trying it out)
@client.hybrid_command(name... | [
"You cannot have both ctx and interaction in hybrid command callback, you can only have ctx, which is a Context object.\nYou can fix this by removing the interaction from the callback argument.\nasync def translate(ctx, language, *, message):\n\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074669450_discord_discord.py_python.txt |
Q:
giving precedence to arithmetic operators in python3
I am implementing a simple arithmetic calculation on a server which includes add, sub, mul and Div, for the simplicity purposes no other operations are being done and also no parentheses "()" to change the precedence. The input I will have for the client is some... | giving precedence to arithmetic operators in python3 | I am implementing a simple arithmetic calculation on a server which includes add, sub, mul and Div, for the simplicity purposes no other operations are being done and also no parentheses "()" to change the precedence. The input I will have for the client is something like "1-2.1+3.6*5+10/2"(no dot product, 2.1 or 3.6 i... | [
"Recursively split the expression according to operator precedence:\ndef do_calc(num1, op, num2):\n # Stub to represent the server call that performs one operation.\n # Note that actually using eval() in your backend is REALLY BAD.\n expr = f\"{num1} {op} {num2}\" \n res = str(eval(expr))\n print(exp... | [
1,
1,
1
] | [] | [] | [
"list",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074668808_list_python_python_3.x_sorting.txt |
Q:
python sql table with paramter to json
Good Day!
I am trying to conver sql query into json with python, but getting an error when try to use sql query with a paramater:
sql syntax error: incorrect syntax near "%"
it works ok without setting paramater
My db is hana and module is hdbcli
my code
def db(db_name="xxx"... | python sql table with paramter to json | Good Day!
I am trying to conver sql query into json with python, but getting an error when try to use sql query with a paramater:
sql syntax error: incorrect syntax near "%"
it works ok without setting paramater
My db is hana and module is hdbcli
my code
def db(db_name="xxx"):
return dbapi.connect(address=db_name,... | [
"hana with hdbdcli uses :placeholder for prepared statements\nsome mpre infrmation can be found\nmy_query = query_db(\"select bname, name_text from addrs where num=:num\", {\"num\": 100})\n\nyou use for two parameter\nwhere id=:id and c2= :c2\n{\"id\": id, \"c2\": c2}\n\n"
] | [
0
] | [] | [] | [
"django",
"hana",
"json",
"python",
"sql"
] | stackoverflow_0074669302_django_hana_json_python_sql.txt |
Q:
Discord py 2.0 interaction option
Discord 2.0 Py\
@bot.tree.command()
@app_commands.describe(amount="Please give amount")
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.send_message(f"You clean {amount} message", ephemeral=True)
await interaction.channel.purge(li... | Discord py 2.0 interaction option | Discord 2.0 Py\
@bot.tree.command()
@app_commands.describe(amount="Please give amount")
async def clear(interaction: discord.Interaction, amount: int):
await interaction.response.send_message(f"You clean {amount} message", ephemeral=True)
await interaction.channel.purge(limit=amount)
Hello this is my code. All... | [
"You can make the option not required by setting a default value for it, and the library will make it optional for you.\n# set the default value for the \"amount\" argument to 1; if the user doesn't input the option, the argument will be 1.\nasync def clear(interaction: discord.Interaction, amount: int = 1):\n\nYou... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074669206_discord_discord.py_python.txt |
Q:
Visual Studio Code Jupyter not recognising conda kernel
I created a new conda environment named 'ct' and installed Python 3.10.6, Jupyter Lab, matplotlib and numpy. Also the ipykernel is installed.
VS Code lets me select Python 3.10.6 from 'ct' as interpreter without issues.
VS Code select interpreter
But I cannot... | Visual Studio Code Jupyter not recognising conda kernel | I created a new conda environment named 'ct' and installed Python 3.10.6, Jupyter Lab, matplotlib and numpy. Also the ipykernel is installed.
VS Code lets me select Python 3.10.6 from 'ct' as interpreter without issues.
VS Code select interpreter
But I cannot choose 'ct' as kernel as VS Code only suggests the 'base' ke... | [
"What finally worked out for me was closing VS Code entirely, recreating the environment and creating a new blank notebook in VS Code. Now the kernel shows up and is surprisingly available for all new and old notebooks.\nI also found this option in the Jupyter settings in VS Code: https://i.stack.imgur.com/rcJU6.pn... | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"conda",
"jupyter",
"kernel",
"python",
"visual_studio_code"
] | stackoverflow_0074028297_conda_jupyter_kernel_python_visual_studio_code.txt |
Q:
Change model representation in Flask-Admin without modifying model
I have a model with a __repr__ method, which is used for display in Flask-Admin. I want to display a different value, but don't want to change the model. I found this answer, but that still requires modifying the model. How can I specify a separ... | Change model representation in Flask-Admin without modifying model | I have a model with a __repr__ method, which is used for display in Flask-Admin. I want to display a different value, but don't want to change the model. I found this answer, but that still requires modifying the model. How can I specify a separate representation for Flask-Admin?
class MyModel(db.Model):
data = ... | [
"The following answers have helped me to solve my issue:\n\nHow to tell flask-admin to use alternative representation when displaying Foreign Key Fields?\nFlask-admin, editing relationship giving me object representation of Foreign Key object\nFlask-Admin Many-to-Many field display\n\nThe cause was in that I tried ... | [
1,
0,
0
] | [] | [] | [
"flask",
"flask_admin",
"python"
] | stackoverflow_0037031399_flask_flask_admin_python.txt |
Q:
Python Quandl giving me error
So I have a bit of code in python which tries to get home prices from zillow. I am following the documentation exactly but I still get errors. The code:
import quandl
quandl.ApiConfig.api_key = "I have a key here in the code"
data = quandl.get("http://www.quandl.com/api/v3/datasets/... | Python Quandl giving me error | So I have a bit of code in python which tries to get home prices from zillow. I am following the documentation exactly but I still get errors. The code:
import quandl
quandl.ApiConfig.api_key = "I have a key here in the code"
data = quandl.get("http://www.quandl.com/api/v3/datasets/ZILL/S00022_A.csv", returns="numpy"... | [
"The code quandl.get() goes with the installed csv file and not an URL. So please import a dataset code and try to import it in your code by\nquandl.get('WIKI/GOOGL')\n\nHere, I have imported a dataset for stock prediction of Google\n"
] | [
0
] | [] | [] | [
"database",
"python",
"python_3.x",
"quandl",
"zillow"
] | stackoverflow_0046900561_database_python_python_3.x_quandl_zillow.txt |
Q:
How to show category names from a mysql database table in the dropdown list of django form
I am working on a article management platform webapp using django. I have created a registration form using the django form where I want to show category names from the category table.
This is the code to create category tab... | How to show category names from a mysql database table in the dropdown list of django form | I am working on a article management platform webapp using django. I have created a registration form using the django form where I want to show category names from the category table.
This is the code to create category table where I have two column. One is cid which is ID and another one is category_name. Here the ca... | [
"First of all, category needs to be a field, not a class. Use ModelChoiceField for this.\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"mysql",
"python"
] | stackoverflow_0074669516_django_django_forms_django_models_mysql_python.txt |
Q:
Error While Using Multiprocessing Library in Python
I am getting an error on Python when using the Multiprocessing library.
I have a list of 18,000 ids to collect via a GET from an external API (function update_events()) and then save each json file to blob storage in Azure . This would take a long time in a singl... | Error While Using Multiprocessing Library in Python | I am getting an error on Python when using the Multiprocessing library.
I have a list of 18,000 ids to collect via a GET from an external API (function update_events()) and then save each json file to blob storage in Azure . This would take a long time in a single-threaded environment so I decided to use a thread pool.... | [
"Thanks @Axe319 for the solution, it looks like I need to initialize file_name before everything else, as in here:\ndef update_events(id:int):\n try: \n ### Initialize first to ensure it's defined for error log\n file_name = str(id) + '.json' \n\n ### If get_events errors out now, Exception... | [
1
] | [] | [] | [
"concurrency",
"multithreading",
"python",
"python_logging",
"python_multiprocessing"
] | stackoverflow_0074659662_concurrency_multithreading_python_python_logging_python_multiprocessing.txt |
Q:
input unicode character string ('u+2022') and output character
I have a Python program that uses a dictionary with Unicode number strings in it, then prints out the actual character. My code looks like this:
unicodeChars = {'bullet': 'u+2022'}
print(chr(unicodeChars['bullet']))
But I am receiving the following e... | input unicode character string ('u+2022') and output character | I have a Python program that uses a dictionary with Unicode number strings in it, then prints out the actual character. My code looks like this:
unicodeChars = {'bullet': 'u+2022'}
print(chr(unicodeChars['bullet']))
But I am receiving the following error:
TypeError: 'str' object cannot be interpreted as an integer
C... | [
"Take a look at the Unicode HOWTO. You will see that you really are looking for this instead:\nunicodeChars = {'bullet': '\\u2022'}\nprint(unicodeChars['bullet'])\n\n"
] | [
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"python_unicode"
] | stackoverflow_0074669668_list_python_python_3.x_python_unicode.txt |
Q:
Adding new points to point cloud in real time - Open3D
I am using Open3D to visualize point clouds in Python. Essentially, what I want to do is add another point to the point cloud programmatically and then render it in real time.
This is what I have so far. I could not find any solution to this.
In the code below... | Adding new points to point cloud in real time - Open3D | I am using Open3D to visualize point clouds in Python. Essentially, what I want to do is add another point to the point cloud programmatically and then render it in real time.
This is what I have so far. I could not find any solution to this.
In the code below, I show one possible solution, but it is not effective. The... | [
"In below page, it explains how to update visualizer without close the window.\nhttp://www.open3d.org/docs/release/tutorial/visualization/non_blocking_visualization.html\nCode may look like below:\n// set up an new empty pcd\n// init visualizer\n// for loop :\n//add new points into pcd\n\n//visualizer update as sam... | [
0,
0
] | [] | [] | [
"numpy",
"open3d",
"python"
] | stackoverflow_0065774814_numpy_open3d_python.txt |
Q:
how do I overwrite text I've already written to the console?
I am trying to get this to
Read the text from screen #Working
Output the text #Working
Delete Output #Not working
Replace with Output every 5 second. #Not working as depended on prior
Can someone help... | how do I overwrite text I've already written to the console? | I am trying to get this to
Read the text from screen #Working
Output the text #Working
Delete Output #Not working
Replace with Output every 5 second. #Not working as depended on prior
Can someone help?
I am trying to get this algo to read the screen every 5 seconds,... | [
"So, your question really is \"how to I overwrite text I've already written to the console?\" There are two ways.\nIf there is only one line of text, just write a carriage return at the end instead of a newline. For example:\n print(text, end='\\r')\n\nIf there are multiple lines of text, you can clear the sc... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074646615_python.txt |
Q:
Snake Algorithm (active contour) in python
Find contour on the right side of the chest image as indicated with red circle and by using Python and scikit-image package for the image below
this is the image i have to process
to make it like this result:
the result must be like this
I don't know a lot of python thats... | Snake Algorithm (active contour) in python | Find contour on the right side of the chest image as indicated with red circle and by using Python and scikit-image package for the image below
this is the image i have to process
to make it like this result:
the result must be like this
I don't know a lot of python thats why I need to know what I have to do
| [
"To find the contour on the right side of the chest image, you can use the find_contours function from the scikit-image package. This function takes an image as input and returns a list of all the contours in the image.\nHere is an example of how you can use this function to find the contour on the right side of th... | [
1
] | [] | [] | [
"computer_vision",
"image_processing",
"python"
] | stackoverflow_0074669771_computer_vision_image_processing_python.txt |
Q:
How to find a random number in python
I have a random number and I want to create a bot that find it automatically but I'm stuck. Can you help me pls
I have these two variables:
a = random.randint(0,50)
b = 50
I want to make the bot find a using b.
I tried this but it's too long to make:
if b != a:
b = statis... | How to find a random number in python | I have a random number and I want to create a bot that find it automatically but I'm stuck. Can you help me pls
I have these two variables:
a = random.randint(0,50)
b = 50
I want to make the bot find a using b.
I tried this but it's too long to make:
if b != a:
b = statistics.mean(0,b)
if b > a:
b = st... | [
"import random\na = random.randint(0,50)\nb = 50\ni = b//2\nwhile b!=a:\n if b<a:\n b+=i\n elif b>a:\n b-=i \n if i>1:\n i//=2\nprint(a,b)\n\n"
] | [
2
] | [] | [] | [
"bots",
"python",
"random"
] | stackoverflow_0074669751_bots_python_random.txt |
Q:
A Python program to print the longest consecutive chain of words of the same length from a sentence
I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is "To be or not to be", the output should be "To, be,... | A Python program to print the longest consecutive chain of words of the same length from a sentence | I got tasked with writing a Python script that would output the longest chain of consecutive words of the same length from a sentence. For example, if the input is "To be or not to be", the output should be "To, be, or".
text = input("Enter text: ")
words = text.replace(",", " ").replace(".", " ").split()
x = 0
same = ... | [
"using groupby you can get the result as\nfrom itertools import groupby\nstring = \"To be or not to be\"\nsol = ', '.join(max([list(b) for a, b in groupby(string.split(), key=len)], key=len))\nprint(sol)\n# 'To, be, or'\n\n",
"len() function takes a string as an argument, for instance here in this code according ... | [
2,
0
] | [] | [] | [
"for_loop",
"list",
"python",
"string"
] | stackoverflow_0074669723_for_loop_list_python_string.txt |
Q:
Can't open label file. (This can be normal only if you use MSCOCO) YoloV4
I'm working with YoloV4 model object detection. I'm trying to train the custom dataset but I'm constantly getting this error line:
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8... | Can't open label file. (This can be normal only if you use MSCOCO) YoloV4 | I'm working with YoloV4 model object detection. I'm trying to train the custom dataset but I'm constantly getting this error line:
Can't open label file. (This can be normal only if you use MSCOCO): data/obj/13_PNG.rf.c87d3ef90086ec0d21254a8a7c97147a.txt
Can't open label file. (This can be normal only if you use MSCOC... | [
"Make sure that your labels(annotations) and the training image names are the same. If there is a difference between labels and image names, then it will cause this particular error. I had the same error when working with annotation files. For me, it happened when I had to convert from .png to .jpg and that changed... | [
0
] | [] | [] | [
"google_colaboratory",
"neural_network",
"python"
] | stackoverflow_0073652439_google_colaboratory_neural_network_python.txt |
Q:
Parenthesis in a recursive way (Python)
def paren(s, cnt=0):
if s == '':
return True
if s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
return cnt == 0
So this code works for all cases if there is the same number of "(" and ")".
Bu... | Parenthesis in a recursive way (Python) | def paren(s, cnt=0):
if s == '':
return True
if s[0] == '(':
return paren(s[1:], cnt + 1)
elif s[0] == ')':
return paren(s[1:], cnt - 1)
return cnt == 0
So this code works for all cases if there is the same number of "(" and ")".
But for example it doesn't work for "))(( ".
ho... | [
"def paren(s):\n _s = s.replace('()','')\n if not _s:\n return True\n elif _s==s:\n return False\n return paren(_s)\n\nprint(paren(')()('))\n\n",
"Check if at any point c < 0, and fix the return for when s == ''\ndef paren(s, cnt=0):\n if c < 0: return False\n elif s == '': return ... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074669803_python_python_3.x.txt |
Q:
Implementing an interface in python
I am pretty new to Python and couldn't understand the origin of this problem.
I'm trying to implement an interface, I have downloaded the zope.interface package, and imported it in my file like this
import zope.interface
Now when I write
class MyInterface(zope.interface.Interf... | Implementing an interface in python | I am pretty new to Python and couldn't understand the origin of this problem.
I'm trying to implement an interface, I have downloaded the zope.interface package, and imported it in my file like this
import zope.interface
Now when I write
class MyInterface(zope.interface.Interface)
I get this error:
"message": "Inhe... | [
"I am new to python too, but I will try to help using the little knowledge I have.\nActually I tested your code, and it works for me, it doesn't give me that error message. But concerning the difference between both statements, I wrote the following code to figure out the difference:\n import zope.interface\n ... | [
0,
0,
0
] | [] | [] | [
"python",
"zope",
"zope.interface"
] | stackoverflow_0074665243_python_zope_zope.interface.txt |
Q:
Im trying to build an Installer for some packages that my programm needs. I also want to have a Status bar which shows the current progress
import tkinter as tk
import multiprocessing
from tkinter import messagebox
def installPackages_1(self):
self.t = ""
label = tk.Label(fenster, text="Checking for packa... | Im trying to build an Installer for some packages that my programm needs. I also want to have a Status bar which shows the current progress | import tkinter as tk
import multiprocessing
from tkinter import messagebox
def installPackages_1(self):
self.t = ""
label = tk.Label(fenster, text="Checking for packages...").place(x=60, y=100)
pb = ttk.Progressbar(fenster, orient='horizontal', mode='determinate', length=280)
pb.place(x=180, y=100)
... | [
"Pyinstaller already bundles the libraries with your executable, you don't need to check for them.\nchecking for libraries and installing them is completely unnecessary (and isn't as simple as you expect), don't call either functions inside your executable and your app will work just fine, as you don't need to call... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"subprocess",
"tkinter"
] | stackoverflow_0074669815_multiprocessing_python_subprocess_tkinter.txt |
Q:
How do you pull specific information out of a text file? Python
Here is an example of some of the information in the text file:
Ticker : Ticker representing the company | Company: Name | Title: Position of trader | Trade Type: Buy or sell | Value: Monetary value
Ticker : AKUS | Company: Akouos, Inc. | Title: 10% ... | How do you pull specific information out of a text file? Python | Here is an example of some of the information in the text file:
Ticker : Ticker representing the company | Company: Name | Title: Position of trader | Trade Type: Buy or sell | Value: Monetary value
Ticker : AKUS | Company: Akouos, Inc. | Title: 10% | Trade Type: P - Purchase | Value: +$374,908,350
Ticker : HHC | Com... | [
"The best way I can think of is to import into a dataframe (df), and then convert to a dictionary (if that is what you really want).\n\nFirstly import the data into a pandas dataframe:\nimport pandas as pd\n\nfilename = 'file1.txt'\n\ndf = pd.read_csv(filename,\n sep = ':\\s+|\\s\\|',\n ... | [
2,
1
] | [] | [] | [
"python",
"txt"
] | stackoverflow_0074669178_python_txt.txt |
Q:
Advice on how to debug python code using Pycharm
I am a relatively new python user, and wanted advice on how best to debug my code.
Currently, I have a script (main.py), that I run in debug mode using PyCharm. This file is quite short, as most of my functions are contained within another module I have written (i.e... | Advice on how to debug python code using Pycharm | I am a relatively new python user, and wanted advice on how best to debug my code.
Currently, I have a script (main.py), that I run in debug mode using PyCharm. This file is quite short, as most of my functions are contained within another module I have written (i.e. functionsmodule.py). If I put breakpoints in the fun... | [
"You can specify a breakpoint in the code directly using the built-in breakpoint()function, which might help in a case like this.\nSee PEP-553 for more details.\n"
] | [
1
] | [] | [] | [
"debugging",
"pycharm",
"python"
] | stackoverflow_0074669843_debugging_pycharm_python.txt |
Q:
Django form with multi input from loop save only last record to database
I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is ... | Django form with multi input from loop save only last record to database | I have a problem with saving data from a form in django. Only the last record is saved. I generate a list of dates (days of the month) in the view and display it in the form in templates along with the fields next to the type. Everything is displayed correctly in templates, but when I submit to, only the last record f... | [
"You need to pass the form to the template. Now this is OK in your code. But I thing the problem come with the way you manage your form lifecycle.\nIf I understand your code the workflow is the following:\n\nA GET REQUEST Initialize to form with the current states\nYou use several GET requests (buttons) to update s... | [
1,
0,
0
] | [] | [] | [
"django",
"forms",
"html",
"python"
] | stackoverflow_0074615371_django_forms_html_python.txt |
Q:
Extracting information from a list of json Python
Identifier Properties
1 [{"$id":"2","SMName":"pia.redoabs.com","Type":"sms"},{"$id":"3","Name":"_18_Lucene41_0.doc","Type":"file"}]
2 [{"$id":"2","SMName":"pred.redocad.com","Type":"sms"},{"$id":"3","Name":"_18_Nil41_0.doc","Type":"file"}]
3 ... | Extracting information from a list of json Python | Identifier Properties
1 [{"$id":"2","SMName":"pia.redoabs.com","Type":"sms"},{"$id":"3","Name":"_18_Lucene41_0.doc","Type":"file"}]
2 [{"$id":"2","SMName":"pred.redocad.com","Type":"sms"},{"$id":"3","Name":"_18_Nil41_0.doc","Type":"file"}]
3 [{"$id":"2","SMName":"promomaster.com","Type":"sms... | [
"You can try:\nimport json\n\ndf[\"Properties\"] = df[\"Properties\"].apply(\n lambda x: {\n d[\"Type\"]: (d[\"SMName\"] if d[\"Type\"] == \"sms\" else d[\"Name\"])\n for d in json.loads(x)\n }\n)\n\ndf = pd.concat([df, df.pop(\"Properties\").apply(pd.Series)], axis=1)\n\nprint(df)\n\nPrints:\n ... | [
0
] | [] | [] | [
"json",
"list",
"python"
] | stackoverflow_0074669506_json_list_python.txt |
Q:
Attempting to install Stable Diffusion via Python
I've trawled through stack overflow, several youtube videos and can't for the life of me work this out.
I've unpackaged and pulled from git, all files are where they need to be as far as the installation for Stable Diffusion goes - but when I go to run I get two er... | Attempting to install Stable Diffusion via Python | I've trawled through stack overflow, several youtube videos and can't for the life of me work this out.
I've unpackaged and pulled from git, all files are where they need to be as far as the installation for Stable Diffusion goes - but when I go to run I get two errors, one being the pip version. I upgraded via 'pip in... | [
"One of the easiest methods to install SD is with Automatic1111\nhttps://github.com/AUTOMATIC1111/stable-diffusion-webui\nInstructions on this page in a section titled \"Automatic Installation on Windows\" (since you're using windows paths in your post)\n\nInstall Python 3.10.6, checking \"Add Python to PATH\" Inst... | [
0
] | [] | [] | [
"pip",
"python",
"stable_diffusion"
] | stackoverflow_0074313444_pip_python_stable_diffusion.txt |
Q:
TypeError converting fahrenheit to celsius in python
my code:
temperature_f = input('Please enter the temperature :')
print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')
run code:
Please enter the temperature :50
Traceback (most recent call last):
File "c:\Users\Aryan\.vscode\py\test1.py", li... | TypeError converting fahrenheit to celsius in python | my code:
temperature_f = input('Please enter the temperature :')
print('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')
run code:
Please enter the temperature :50
Traceback (most recent call last):
File "c:\Users\Aryan\.vscode\py\test1.py", line 2, in <module>
print('The temperature is' , 1.8 / (... | [
"You have to type cast your input\ntemperature_f = input(int('Please enter the temperature :'))\n\n",
"type cast temperature string into float.\ntemperature_f = float(input('Please enter the temperature :'))\nprint('The temperature is' , 1.8 / (temperature_f - 32) ,'centigrade')\n\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074669949_python.txt |
Q:
openAI DALL-E ModuleNotFoundError
I installed DALL-E following the instructions on https://github.com/openai/DALL-E
and got :
---> 10 from dall_e import map_pixels, unmap_pixels, load_model
11 from IPython.display import display, display_markdown
12
ModuleNotFoundError: No module named 'dall_e'
A:
I fou... | openAI DALL-E ModuleNotFoundError | I installed DALL-E following the instructions on https://github.com/openai/DALL-E
and got :
---> 10 from dall_e import map_pixels, unmap_pixels, load_model
11 from IPython.display import display, display_markdown
12
ModuleNotFoundError: No module named 'dall_e'
| [
"I found that it helped when I changed which Python version I was using.\nIt fixed my issue when I changed mine from 3.7.- to 3.10.7.\n"
] | [
1
] | [] | [] | [
"openai",
"python",
"pytorch"
] | stackoverflow_0072078830_openai_python_pytorch.txt |
Q:
planets created from 1d perlin noise terrain look weird
i am trying to make planets using pyglet but they end up looking like stars result
here is my code
also i need a way to convert a batch to a sprite (to move it easily)
import pyglet
from pyglet import shapes
import opensimplex
import math
import time
brtd = ... | planets created from 1d perlin noise terrain look weird | i am trying to make planets using pyglet but they end up looking like stars result
here is my code
also i need a way to convert a batch to a sprite (to move it easily)
import pyglet
from pyglet import shapes
import opensimplex
import math
import time
brtd = 0
######## planets###########
class planetobj():
def __i... | [
"OK, I've corrected your trigonometry, but there are some other issues. The random values you get back from the noise generator are between -1 and 1. You are then multiplying that by the planet size, which gives you wild variations from wedge to wedge. What you want is to have a basic wedge size, which you use t... | [
0
] | [] | [] | [
"procedural_generation",
"pyglet",
"python"
] | stackoverflow_0074664055_procedural_generation_pyglet_python.txt |
Q:
launch URL in Flet
I'm using Flet and I want for my app to launch a link when clicking on a button.
According to the docs, I can use launch_url method. But when I tried, I got the following error:
Exception in thread Thread-6 (open_repo):
Traceback (most recent call last):
File "C:\Users\Iqmal\AppData\Local\Prog... | launch URL in Flet | I'm using Flet and I want for my app to launch a link when clicking on a button.
According to the docs, I can use launch_url method. But when I tried, I got the following error:
Exception in thread Thread-6 (open_repo):
Traceback (most recent call last):
File "C:\Users\Iqmal\AppData\Local\Programs\Python\Python311\Li... | [
"To fix the error you're getting, you need to import the page module from the flet library and then create an instance of the page class. Then, you can call the launch_url method on that instance to open a URL in the default web browser.\nHere's how you might update your code to do that:\nimport flet as ft\nImport ... | [
0,
0
] | [] | [] | [
"flet",
"flutter",
"python"
] | stackoverflow_0074661326_flet_flutter_python.txt |
Q:
How to crop square inscribed in partial circle?
I have frames of a video taken from a microscope. I need to crop them to a square inscribed to the circle but the issue is that the circle isn't whole (like in the following image). How can I do it?
My idea was to use contour finding to get the center of the circle ... | How to crop square inscribed in partial circle? | I have frames of a video taken from a microscope. I need to crop them to a square inscribed to the circle but the issue is that the circle isn't whole (like in the following image). How can I do it?
My idea was to use contour finding to get the center of the circle and then find the distance from each point over the w... | [
"This may not be adequate in terms of centered at center of circle, but using my iterative processing, one can crop to an approximation of the largest rectangle inside your circle area.\nInput:\n\nimport cv2\nimport numpy as np\n\n# read image\nimg = cv2.imread('img.jpg')\nh, w = img.shape[:2]\n\n# threshold so bor... | [
6,
4,
1,
0
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074645811_image_processing_opencv_python.txt |
Q:
Passing a function's output as a parameter of another function
I'm having a hard time figuring out how to pass a function's return as a parameter to another function. I've searched a lot of threads that are deviations of this problem but I can't think of a solution from them. My code isn't good yet, but I just nee... | Passing a function's output as a parameter of another function | I'm having a hard time figuring out how to pass a function's return as a parameter to another function. I've searched a lot of threads that are deviations of this problem but I can't think of a solution from them. My code isn't good yet, but I just need help on the line where the error is occurring to start with.
Instr... | [
"You can't use a function as a parameter, I think what you want to do is use it as an argument. You can do it like this:\nimport datetime as dt\n\ndef func1():\n bd = input(\"When is your birthday? \")\n try:\n dt.datetime.strptime(bd, \"%m/%d/%Y\")\n except ValueError as e:\n print(\"There i... | [
0,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074663224_function_python.txt |
Q:
How can I turn a xy-meshgrid and a 1D array into a contour?
So I have a csv file (which I have read with pandas), which has 3 columns the first column corresponds to the x-axis, the second column the y-axis and the third column is the value for the free energy, we can interpret that as the z-axis or the height of ... | How can I turn a xy-meshgrid and a 1D array into a contour? | So I have a csv file (which I have read with pandas), which has 3 columns the first column corresponds to the x-axis, the second column the y-axis and the third column is the value for the free energy, we can interpret that as the z-axis or the height of the xy-plane. I have create a meshgrid with my x,y colums which h... | [
"Use the contour() function from the matplotlib library. This function takes in three arguments: x,y,z.\nYou can reshape your z array to be the same size as your X and Y arrays using the reshape() method. Then, you can pass all three arrays to the contour() function to generate your desired contour plot.\nimport ma... | [
0
] | [] | [] | [
"3d",
"contour",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074670095_3d_contour_matplotlib_numpy_python.txt |
Q:
How to find if elements of a column in a data frame are string-contained by the elements of a column of another data frame?
I have a data frame tweets_df that looks like this:
sentiment id date text
0 0 15020713601... | How to find if elements of a column in a data frame are string-contained by the elements of a column of another data frame? | I have a data frame tweets_df that looks like this:
sentiment id date text
0 0 1502071360117424136 2022-03-10 23:58:14+00:00 AngelaRaeBoon1 Same Alabama Republicans charge...
1 0 1502070916318121994 2022-0... | [
"Convert country and region values to a list and use str.contains to filter out rows that do not contain these values.\n#with case insensitive\nvals=globe_df.stack().to_list()\n\ntweets_df = tweets_df[tweets_df ['text'].str.contains('|'.join(vals), regex=True, case=False)]\n\nor (with case insensitive)\nvals=\"({})... | [
0
] | [
"You can try using pandas.Series.str.contains to find the values.\ntweets_df[tweets_df['text'].contains('{}|{}'.format(entry['Country'],entry['Region'])]\n\nAnd after creating a new column with boolean values, you can remove rows with the value True.\n",
"# Import data\nglobe_df = pd.read_csv('countriesAndRegions... | [
-1,
-1
] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074669715_dataframe_pandas_python.txt |
Q:
Simple question, Finding word count within file trouble
I've looked up a simple way to file word count for a file but it keeps giving me zero
output
script
A:
This should hopefully solve your problem. The split is only set to count words separated by spaces. Hope this helps!
fileName = input('Enter File Name: ')... | Simple question, Finding word count within file trouble | I've looked up a simple way to file word count for a file but it keeps giving me zero
output
script
| [
"This should hopefully solve your problem. The split is only set to count words separated by spaces. Hope this helps!\nfileName = input('Enter File Name: ')\nwith open(fileName,'r') as file:\n lineCnt = 0\n wordCnt = 0\n for i in file:\n lineCnt += 1\n for j in i.split():\n wordCnt... | [
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074670150_file_python.txt |
Q:
python selenium alternative for web actions
I am constantly waiting for the page to load in web actions. Is there a way to do web actions faster without waiting for the page to load ?
When working with Selenium, it takes time to navigate from page to page.
A:
If your use case does not require opening an actual b... | python selenium alternative for web actions | I am constantly waiting for the page to load in web actions. Is there a way to do web actions faster without waiting for the page to load ?
When working with Selenium, it takes time to navigate from page to page.
| [
"If your use case does not require opening an actual browser and interacting with the webpage through simulated user input, then you can use HTTP requests to extract/manipulate data from the page. Popular modules for this are Requests and BeautifulSoup.\n"
] | [
0
] | [] | [] | [
"automation",
"bots",
"javascript",
"python",
"selenium"
] | stackoverflow_0074669684_automation_bots_javascript_python_selenium.txt |
Q:
Transform For loop into while loop
s=0
for i in range(3,20,2):
if i>10:
break
else:
s=s+i
print(s)
how can i transform this code into a while loop?
I don't know how to include the step.
A:
s = 0
i = 3
while i<10:
s+=i
i+=2
print(s)
A:
If you want to break the loop when i>... | Transform For loop into while loop | s=0
for i in range(3,20,2):
if i>10:
break
else:
s=s+i
print(s)
how can i transform this code into a while loop?
I don't know how to include the step.
| [
"s = 0\ni = 3\nwhile i<10:\n s+=i\n i+=2\nprint(s)\n\n",
"If you want to break the loop when i>10, then why you're running the loop till 20? Any way you can try this\ns,i=0,3\nwhile i<=20:\n if i>10:\n break\n else:\n s=s+i\n i+=2\nprint(s)\n\n",
"Here's how you can transform the fo... | [
1,
0,
0,
0
] | [] | [] | [
"for_loop",
"python",
"while_loop"
] | stackoverflow_0074669923_for_loop_python_while_loop.txt |
Q:
Check for None in pandas dataframe
I would like to find where None is found in the dataframe.
pd.DataFrame([None,np.nan]).isnull()
OUT:
0
0 True
1 True
isnull() finds both numpy Nan and None values.
I only want the None values and not numpy Nan. Is there an easier way to do that without looping through t... | Check for None in pandas dataframe | I would like to find where None is found in the dataframe.
pd.DataFrame([None,np.nan]).isnull()
OUT:
0
0 True
1 True
isnull() finds both numpy Nan and None values.
I only want the None values and not numpy Nan. Is there an easier way to do that without looping through the dataframe?
Edit:
After reading the co... | [
"If you want to get True/False for each line, you can use the following code. Here is an example as a result for the following DataFrame:\ndf = pd.DataFrame([[None, 3], [\"\", np.nan]])\n\ndf\n# 0 1\n#0 None 3.0\n#1 NaN\n\nHow to check None\nAvailable: .isnull()\n>>> df[0].isnull()\n0 Tru... | [
13,
8,
0
] | [] | [] | [
"nan",
"numpy",
"pandas",
"python"
] | stackoverflow_0045271309_nan_numpy_pandas_python.txt |
Q:
How do I pass in a 1d array to sklearn's LabelEncoder?
I'm following along an Uber-Lyft price prediction notebook on Kaggle, but I'm trying to use the Polars module.
In cell 43 where they use sklearn's LabelEncoder, they have the following loop that appears to loop through each feature, except for price, and encod... | How do I pass in a 1d array to sklearn's LabelEncoder? | I'm following along an Uber-Lyft price prediction notebook on Kaggle, but I'm trying to use the Polars module.
In cell 43 where they use sklearn's LabelEncoder, they have the following loop that appears to loop through each feature, except for price, and encodes it:
from sklearn import preprocessing
le = preprocessing.... | [
"It looks like this encoding is the equivalent of a \"dense\" ranking.\n>>> df_cat_encode\n source destination cab_type name short_summary icon price\n0 0 0 0 3 1 1 5.0\n1 0 0 0 0 2 2 11.0\n2 0 ... | [
0
] | [] | [] | [
"arrays",
"python",
"python_polars",
"scikit_learn"
] | stackoverflow_0074669199_arrays_python_python_polars_scikit_learn.txt |
Q:
getting timers to print values from bubblesort, wont print my last value unless I lower it?
import sys
import time
from random import randint
import numpy as np
sys.setrecursionlimit(6000)
nums = [10, 50, 100, 500, 1000, 5000]
def bubble(A, n):
for i in range(n - 1):
if A[i] > A[i + 1]:
A... | getting timers to print values from bubblesort, wont print my last value unless I lower it? | import sys
import time
from random import randint
import numpy as np
sys.setrecursionlimit(6000)
nums = [10, 50, 100, 500, 1000, 5000]
def bubble(A, n):
for i in range(n - 1):
if A[i] > A[i + 1]:
A[i], A[i + 1] = A[i + 1], A[i]
if n - 1 > 1:
bubble(A, n - 1)
def time_by_bubble_sor... | [
"According to sys.setrecursionlimit, emphasis mine:\n\nThe highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a cr... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074635282_python.txt |
Q:
General way of filtering by IDs with DRF
Is there a generic way that I can filter by an array of IDs when using DRF?
For example, if I wanted to return all images with the following IDs, I would do this:
/images/?ids=1,2,3,4
My current implementation is to do the following:
# filter
class ProjectImageFilter(djang... | General way of filtering by IDs with DRF | Is there a generic way that I can filter by an array of IDs when using DRF?
For example, if I wanted to return all images with the following IDs, I would do this:
/images/?ids=1,2,3,4
My current implementation is to do the following:
# filter
class ProjectImageFilter(django_filters.FilterSet):
"""
Filter on ex... | [
"One solution without django-filters is to just super() override get_queryset. Here is an example:\nclass MyViewSet(view.ViewSet):\n\n # your code\n\n def get_queryset(self):\n queryset = super(MyViewSet, self).get_queryset()\n\n ids = self.request.query_params.get('ids', None)\n if ids:\... | [
1,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"python_2.7"
] | stackoverflow_0036851257_django_django_rest_framework_python_python_2.7.txt |
Q:
Joblib UserWarning while trying to cache results
I get the following UserWarning when trying to cache results using joblib:
import numpy
from tempfile import mkdtemp
cachedir = mkdtemp()
from joblib import Memory
memory = Memory(cachedir=cachedir, verbose=0)
@memory.cache
def get_nc_var3d(path_nc, var, year):
... | Joblib UserWarning while trying to cache results | I get the following UserWarning when trying to cache results using joblib:
import numpy
from tempfile import mkdtemp
cachedir = mkdtemp()
from joblib import Memory
memory = Memory(cachedir=cachedir, verbose=0)
@memory.cache
def get_nc_var3d(path_nc, var, year):
"""
Get value from netcdf for variable var for ye... | [
"I don't have an answer to the \"why doesn't this work?\" portion of the question. However to simply ignore the warning you can use warnings.catch_warnings with warnings.simplefilter as seen here.\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n your_code()\n\n\nObviously,... | [
0,
0,
0
] | [] | [] | [
"joblib",
"netcdf",
"numpy",
"python"
] | stackoverflow_0037129754_joblib_netcdf_numpy_python.txt |
Q:
Converting week numbers to dates
Say I have a week number of a given year (e.g. week number 6 of 2014).
How can I convert this to the date of the Monday that starts that week?
One brute force solution I thought of would be to go through all Mondays of the year:
date1 = datetime.date(1,1,2014)
date2 = datetime.dat... | Converting week numbers to dates | Say I have a week number of a given year (e.g. week number 6 of 2014).
How can I convert this to the date of the Monday that starts that week?
One brute force solution I thought of would be to go through all Mondays of the year:
date1 = datetime.date(1,1,2014)
date2 = datetime.date(12,31,2014)
def monday_range(date1,d... | [
"You could just feed the data into time.asctime(). \n>>> import time\n>>> week = 6\n>>> year = 2014\n>>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))\n>>> atime\n'Mon Feb 10 00:00:00 2014'\n\n\nEDIT:\nTo convert this to a datetime.date object:\n>>> datetime.datetime.fromtimestamp(ti... | [
6,
5,
4,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0022789198_datetime_python.txt |
Q:
discord.py temprole command
First of all i dont really know why its not working properly. Its not returning any errors, messages etc., the code is running properly. Can somebody help me fix my issue?
EDIT1: Just want to add that im noob in coding and ive spent about 1 hour trying to solve the problem
import discor... | discord.py temprole command | First of all i dont really know why its not working properly. Its not returning any errors, messages etc., the code is running properly. Can somebody help me fix my issue?
EDIT1: Just want to add that im noob in coding and ive spent about 1 hour trying to solve the problem
import discord
from discord.ext import command... | [
"as I can see you have a warning so you there are some missing intents\nchange this\nbot = discord.ext.commands.Bot(command_prefix = \"$\", intents=discord.Intents.default()) \nto\nbot = discord.ext.commands.Bot(command_prefix = \"$\", intents=discord.Intents.all())\n\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074668821_discord_discord.py_python.txt |
Q:
How can I make permanent changes to a list using a function in python tkinter?
I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns "[]" and never the updated li... | How can I make permanent changes to a list using a function in python tkinter? | I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns "[]" and never the updated list. Is there a way I can do this?
I have tested and there are no issues involving ex... | [
"It is printing an empty list because the list is empty. You are not printing after appending\nfrom tkinter import *\n\nwindow = Tk()\n\nnames = []\n\nent = Entry(window) ent.pack()\n\ndef change():\n names.append(ent.get())\n print(names)\n\nbtn = Button (window, command = change ) btn.pack()\n\n#print(names... | [
1,
0
] | [] | [] | [
"list",
"python",
"tkinter"
] | stackoverflow_0074670268_list_python_tkinter.txt |
Q:
Django rest framework CORS( Cross Origin Resource Sharing) is not working
I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file,
INSTALLED_APPS = [
'corsheaders',
'django.con... | Django rest framework CORS( Cross Origin Resource Sharing) is not working | I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file,
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
... | [
"use this setting for your app. This happened because of the fact that you are using HTTPS over HTTP.\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n"
] | [
0
] | [
"According to docs for CORS_ALLOW_ALL_ORIGINS\n\nIf True, all origins will be allowed. Other settings restricting\nallowed origins will be ignored. Defaults to False.\n\nSo it looks like your CORS_ALLOWED_ORIGINS is ignored because CORS_ALLOW_ALL_ORIGINS is explicitly set to False forbidding all origins.\n"
] | [
-1
] | [
"django",
"django_cors_headers",
"django_rest_framework",
"python"
] | stackoverflow_0063626757_django_django_cors_headers_django_rest_framework_python.txt |
Q:
Django Crispy Form doesn't add or update database
Hello, I am writing a small project about a car shop and this is the problem I came up with.
I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without ad... | Django Crispy Form doesn't add or update database | Hello, I am writing a small project about a car shop and this is the problem I came up with.
I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without adding a new car to the database.
Here is the code.
views... | [
"Try rewriting your form like this:\nclass ManipulateProductForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(ManipulateProductForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.helper.form_action = 'Submit'\n self.helper.add_input(Submit... | [
1
] | [] | [] | [
"backend",
"django",
"django_crispy_forms",
"python"
] | stackoverflow_0074670091_backend_django_django_crispy_forms_python.txt |
Q:
CSV file data to Excel (Remove csv file after workbook save not working)
I'm having trouble removing the csv file after the data is integrated into the workbook. I'm getting a message
The process cannot access the file because it is being used by another process!
and I tried closing the file before I am applying ... | CSV file data to Excel (Remove csv file after workbook save not working) | I'm having trouble removing the csv file after the data is integrated into the workbook. I'm getting a message
The process cannot access the file because it is being used by another process!
and I tried closing the file before I am applying the os.remove syntax to my code. I am curretly stuck in what I should do. I've... | [
"Using pathlib.glob to find all files, concatenate the csv files with a generator to excel. Finally delete csv files.\nimport contextlib\nfrom pathlib import Path\n\nimport pandas as pd\n\n\ndef concatenate_csvs(path: str) -> None:\n pd.concat(\n (pd.read_csv(x) for x in Path(f\"{path}/\").glob(\"SearchRe... | [
0,
0
] | [] | [] | [
"operating_system",
"pandas",
"permissions",
"python"
] | stackoverflow_0074670286_operating_system_pandas_permissions_python.txt |
Q:
httpx.RemoteProtocolError: peer closed connection without sending complete message body
I am getting the above error despite setting the timeout to None for the httpx call. I am not sure what I am doing wrong.
from httpx import stream
with stream("GET", url, params=url_parameters, headers=headers, timeout=None) a... | httpx.RemoteProtocolError: peer closed connection without sending complete message body | I am getting the above error despite setting the timeout to None for the httpx call. I am not sure what I am doing wrong.
from httpx import stream
with stream("GET", url, params=url_parameters, headers=headers, timeout=None) as streamed_response:
| [
"I've got the same error when using httpx via openapi-client autogenerated client\nresponse = httpx.request(verify=client.verify_ssl,**kwargs,)\n\nIt turned out in kwargs parameter headers contained wrong authorization token.\nSo basically in my case that error meant \"authorization error\".\nYou might want to chec... | [
0
] | [] | [] | [
"httpx",
"python"
] | stackoverflow_0074153345_httpx_python.txt |
Q:
IF ELSE in robot framework [Keyword as a condition]
I just can't figure out how to map a keyword as a condition.
@keyword("Is the Closed Message Page Present")
def check_closedMsg_page(self):
result = self.CLOSED_TEXT.is_displayed
self.LOG(f"It returns {self.CLOSED_TEXT.is_displayed}")
... | IF ELSE in robot framework [Keyword as a condition] | I just can't figure out how to map a keyword as a condition.
@keyword("Is the Closed Message Page Present")
def check_closedMsg_page(self):
result = self.CLOSED_TEXT.is_displayed
self.LOG(f"It returns {self.CLOSED_TEXT.is_displayed}")
return result
The above function returns a bool valu... | [
"I'm still new to the framework, but the only simple method I found is to store the keyword return value to a local variable and use that in the IF statement.\n*** Settings ***\nLibrary SeleniumLibrary\nLibrary ../stackoverflow.py\n\n*** Test Cases ***\nrobot Example\n\n ${value} Is the Closed Message Page Pres... | [
0
] | [] | [] | [
"python",
"robot",
"selenium"
] | stackoverflow_0074657581_python_robot_selenium.txt |
Q:
Not able to access a variable (created in a child frame) from the root window
I am trying to create an application where the user enters a directory name and it gets printed in the console. For this I have created 2 classes:
class FolderInputFrame(tk.Frame):
## child frame class
def __init__(self, parent):... | Not able to access a variable (created in a child frame) from the root window | I am trying to create an application where the user enters a directory name and it gets printed in the console. For this I have created 2 classes:
class FolderInputFrame(tk.Frame):
## child frame class
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self._widgets()
self.pack(... | [
"You need to access the data from the instance of the FolderInputFrame since that is the class that created the variable:\nprint(self.folder_input_container.directory.get())\n\nYou need to make sure you do this after the user has clicked the button. In your example you're attempting to print the value immediately a... | [
0
] | [] | [] | [
"oop",
"python",
"tkinter"
] | stackoverflow_0074669692_oop_python_tkinter.txt |
Q:
Iterate over list selecting multiple elements at a time in Python
I have a list, from which I would like to iterate over slices of a certain length, overlapping each other by the largest amount possible, for example:
>>> seq = 'ABCDEF'
>>> [''.join(x) for x in zip(seq, seq[1:], seq[2:])]
['ABC', 'BCD', 'CDE', 'DEF... | Iterate over list selecting multiple elements at a time in Python | I have a list, from which I would like to iterate over slices of a certain length, overlapping each other by the largest amount possible, for example:
>>> seq = 'ABCDEF'
>>> [''.join(x) for x in zip(seq, seq[1:], seq[2:])]
['ABC', 'BCD', 'CDE', 'DEF']
In other words, is there a shorthand for zip(seq, seq[1:], seq[2:])... | [
"Not an elegant solution, but this works:\nseq = 'ABCDEF'\nn=3\n[seq[i:i+n] for i in range(0, len(seq)+1-n)]\n\n",
"[seq[i:i+3] for i in range(len(seq)-2)] is the Python code for something similar.\nThe far more elegant and recommended version of this is to use the itertools library from Python (seriously, why do... | [
4,
1,
0
] | [] | [] | [
"iteration",
"list",
"python",
"python_3.x",
"sequence"
] | stackoverflow_0044765896_iteration_list_python_python_3.x_sequence.txt |
Q:
Python how to read N number of lines at a time
I am writing a code to take an enormous textfile (several GB) N lines at a time, process that batch, and move onto the next N lines until I have completed the entire file. (I don't care if the last batch isn't the perfect size).
I have been reading about using iterto... | Python how to read N number of lines at a time | I am writing a code to take an enormous textfile (several GB) N lines at a time, process that batch, and move onto the next N lines until I have completed the entire file. (I don't care if the last batch isn't the perfect size).
I have been reading about using itertools islice for this operation. I think I am halfway... | [
"islice() can be used to get the next n items of an iterator. Thus, list(islice(f, n)) will return a list of the next n lines of the file f. Using this inside a loop will give you the file in chunks of n lines. At the end of the file, the list might be shorter, and finally the call will return an empty list.\nfr... | [
76,
9,
3,
2,
1,
0,
0
] | [] | [] | [
"lines",
"python",
"python_itertools"
] | stackoverflow_0006335839_lines_python_python_itertools.txt |
Q:
How to re-apply all previous calculations in a pandas data frame on append
Let's say I have this data frame:
df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6]})
And let's say I define a new column like this:
df["C"] = df["A"] + df["B"]
then the C column will have the values [5, 7, 9].
However, let's say I append a new ... | How to re-apply all previous calculations in a pandas data frame on append | Let's say I have this data frame:
df = pd.DataFrame({"A":[1,2,3],"B":[4,5,6]})
And let's say I define a new column like this:
df["C"] = df["A"] + df["B"]
then the C column will have the values [5, 7, 9].
However, let's say I append a new row with the values 4 for A and 7 for B, then the C column will have the values ... | [
"What distinguish Python from other programming languages is that it is interpreted rather than compiled. It means that the code is executed line by line.\nSo, in your case when you'll add a row at the end of the df, there will be no re-calculation.\ndf[\"C\"] = df[\"A\"] + df[\"B\"] #executed firstly\n\ndf.loc[len... | [
0
] | [] | [] | [
"append",
"apply",
"pandas",
"python"
] | stackoverflow_0074670547_append_apply_pandas_python.txt |
Q:
Using lambda to define a function based on another: How do I keep my code generic?
I have some python code that defines a new function based on an old one. It looks like this
def myFunction(a: int, b: int, c: int):
# Do stuff
myNewFunction = lambda a, b: myFunction(a, b, 0)
My new function is the same as the... | Using lambda to define a function based on another: How do I keep my code generic? | I have some python code that defines a new function based on an old one. It looks like this
def myFunction(a: int, b: int, c: int):
# Do stuff
myNewFunction = lambda a, b: myFunction(a, b, 0)
My new function is the same as the old function, but sets the last argument to 0.
My question: Say I did not know the func... | [
"You're almost correct, you can use functools.partial this way(instead of lambda):\nfrom functools import partial\n\ndef myFunction(a: int, b: int, c: int):\n print(a, b, c)\n\nlast_param_name = myFunction.__code__.co_varnames[-1]\nnew_func = partial(myFunction, **{last_param_name: 0})\n\nnew_func(10, 20)\n\nTec... | [
1
] | [] | [] | [
"lambda",
"python",
"python_3.x"
] | stackoverflow_0074670410_lambda_python_python_3.x.txt |
Q:
Why is Flask making me put @app.route("/interior.html") in route instead of @app.route("/interior")
I am building a website with a booking page that requires me to put the data into a database so I am using python Flask app.
I know that in the @app.route I am only supposed to put @app.route("/exterior") however, w... | Why is Flask making me put @app.route("/interior.html") in route instead of @app.route("/interior") | I am building a website with a booking page that requires me to put the data into a database so I am using python Flask app.
I know that in the @app.route I am only supposed to put @app.route("/exterior") however, whenever I try it using this method I get 404 Page Not Found. Instead I have to put @app.route("/exterior... | [
"I copied your code and made some minor syntax fixes. below is working as normal. perhaps you could copy this and start adding back some of your functionality and see where it goes wrong.\nhere is the directory structure:\ntest_app/\n app.py\n templates/\n interior.html\n exterior.html\n ... | [
0
] | [] | [] | [
"flask",
"html",
"python"
] | stackoverflow_0074499442_flask_html_python.txt |
Q:
How to delete a django JWT token?
I am using the Django rest framework JSON Web token API that is found here on github (https://github.com/GetBlimp/django-rest-framework-jwt/tree/master/).
I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like... | How to delete a django JWT token? | I am using the Django rest framework JSON Web token API that is found here on github (https://github.com/GetBlimp/django-rest-framework-jwt/tree/master/).
I can successfully create tokens and use them to call protected REST APis. However, there are certain cases where I would like to delete a specific token before its ... | [
"The biggest disadvantage of JWT is that because the server does not save the session state, it is not possible to abolish a token or change the token's permissions during use. That is, once the JWT is signed, it will remain in effect until it expires, unless the server deploys additional logic. \n So, you cannot ... | [
9,
7,
2,
0
] | [] | [] | [
"django",
"jwt",
"python",
"rest"
] | stackoverflow_0040604877_django_jwt_python_rest.txt |
Q:
set df to value between tuple
i would like to set a df value between two values x_lim(0,2) to True.
I would like to get a df that looks like this:
x | y | z
0 | 7 | True
1 | 3 | True
2 | 4 | True
3 | 8 | False
i tried :
def set_label(df, x_lim, y_lim, variable):
for index, row in df.iterrows():
for i ... | set df to value between tuple | i would like to set a df value between two values x_lim(0,2) to True.
I would like to get a df that looks like this:
x | y | z
0 | 7 | True
1 | 3 | True
2 | 4 | True
3 | 8 | False
i tried :
def set_label(df, x_lim, y_lim, variable):
for index, row in df.iterrows():
for i in range(x_lim[0],x_lim[1]):
... | [
"Here is one way to do it:\nimport pandas as pd\n\n# Create a dataframe with sample data\ndf = pd.DataFrame({'x': [0, 1, 2, 3], 'y': [7, 3, 4, 8]})\n\n# Set the 'z' column to True if the value of 'x' is between 0 and 2 (inclusive)\ndf['z'] = df['x'].between(0, 2, inclusive=True)\n\n# Print the resulting dataframe\n... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074670641_pandas_python.txt |
Q:
Bot is not waiting for the message
I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
if type == "netflix":
c.execute("SELECT price FRO... | Bot is not waiting for the message | I'm trying to make the bot wait for a specific message(from a specific author and some specific things) But the bot is just waiting for any message and it makes the command.
Here's the function:
async def check(message):
if type == "netflix":
c.execute("SELECT price FROM netflix")
neprice = c.fetchall()... | [
"In your code, you wrote await message.respond(...).\nThere isn't a respond() function in both discord.py and pycord, as far as I know. Try changing it to reply(...) and see if it works.\n",
"async def buy(message, type: str, amount:Optional[int]):\n #type here the stuff that u want make before the check\n ... | [
0,
0
] | [] | [] | [
"discord.py",
"pycord",
"python"
] | stackoverflow_0074659035_discord.py_pycord_python.txt |
Q:
How do I make it stop storing everything in the first element of the list?
I am trying to have each line be stored in a different element of the list. The text file is as follows...
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display... | How do I make it stop storing everything in the first element of the list? | I am trying to have each line be stored in a different element of the list. The text file is as follows...
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
I am trying to have 2... | [
"In the code you've provided, you're overwriting the inventory_dict parameter with an empty dictionary on the second line of the process_inventory function. This means that the dictionary that you pass to the function as an argument won't be used or updated in the function.\nTo fix this, you should remove the line ... | [
0
] | [] | [] | [
"dictionary",
"file",
"list",
"python"
] | stackoverflow_0074670666_dictionary_file_list_python.txt |
Q:
JavaScript is not executed in tracking form
I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and p... | JavaScript is not executed in tracking form | I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and put it in json format.
However in my html file the... | [
"There are a few potential issues with your code:\nYou are not rendering the JSON data in the HTML template, so the information from the database is not being displayed on the page. You will need to pass the data from the database to the HTML template and then use it to populate the elements on the page.\nThe JavaS... | [
0
] | [] | [] | [
"ajax",
"javascript",
"jquery",
"python"
] | stackoverflow_0074667191_ajax_javascript_jquery_python.txt |
Q:
How to convert uint8 in brackets to (r, g, b) value
Hey guys i found my self stuck on this. I am making an obs spotify app that shows you album cover, name of the artist, and now i would like to add average color output but i need it in rgb.
this is the average code with this output: [112.62674316 103.23660889 98... | How to convert uint8 in brackets to (r, g, b) value | Hey guys i found my self stuck on this. I am making an obs spotify app that shows you album cover, name of the artist, and now i would like to add average color output but i need it in rgb.
this is the average code with this output: [112.62674316 103.23660889 98.91593262]
src_img = cv2.imread('icon.jpeg')
average_colo... | [
"It looks like the code you posted is using the NumPy library to calculate the average color of an image. The output you're seeing, [112.62674316 103.23660889 98.91593262], is an array of floating point values representing the average values of the red, green, and blue channels of the image, respectively.\nTo conve... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074670693_numpy_python.txt |
Q:
How can i use .kv file in different folders?
I don't know how to use .kv file so i just want to summary example. For example let we have 2 folders.
These folders: src and design.
src folder contain: main.py
design folder contain: main.kv
I want to know just simple example in this situation. How can i access from m... | How can i use .kv file in different folders? | I don't know how to use .kv file so i just want to summary example. For example let we have 2 folders.
These folders: src and design.
src folder contain: main.py
design folder contain: main.kv
I want to know just simple example in this situation. How can i access from main.py file to main.kv file. I researched but i di... | [
"you can use the Builder object to load all of the .kv files you want.\n # useful for creating paths from multiple parts\n from pathlib import Path, PurePath\n #\n from kivy.lang import Builder\n # load_file can be called multiple times\n Builder.load_file(str(PurePath(\"c:/\", \"users\", \"public\", \"... | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"python"
] | stackoverflow_0074667825_kivy_kivy_language_python.txt |
Q:
Clean way to send data struct from python to arduino?
I'm working on a robot and I'd like to somehow send a command using pySerial to the arduino.
The command would look like {MOVE, 60, 70} or {REQUEST_DATA}, where I'd have the arduino read in the first value, if it's "MOVE" then it drives some motors with speed 6... | Clean way to send data struct from python to arduino? | I'm working on a robot and I'd like to somehow send a command using pySerial to the arduino.
The command would look like {MOVE, 60, 70} or {REQUEST_DATA}, where I'd have the arduino read in the first value, if it's "MOVE" then it drives some motors with speed 60 and 70, and if it's "REQUEST_DATA" it would respond with... | [
"There are a number of ways to tackle this problem, and the best solution depends on exactly what data you're sending back and forth.\nThe simplest solution is to represent commands a single bytes (e.g., M for MOVE or R for REQUEST_DATA), because this way you only need to read a single byte on the arduino side to d... | [
1
] | [] | [] | [
"arduino",
"pyserial",
"python",
"serial_communication"
] | stackoverflow_0074669524_arduino_pyserial_python_serial_communication.txt |
Q:
How can I make the user input another password if it's not strong enough?
Right now with what I have, even if the password meets all the criteria it prints "Weak password try again!". It allows for another user input but it doesn't break and print "Strong password" if it is strong.
Code:
if (l>= and u>=1 and p>=1 ... | How can I make the user input another password if it's not strong enough? | Right now with what I have, even if the password meets all the criteria it prints "Weak password try again!". It allows for another user input but it doesn't break and print "Strong password" if it is strong.
Code:
if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):
break
print("Strong password")
else:
... | [
"while True:\n passwordName = input(\"Password ? \")\n if (l>= and u>=1 and p>=1 and d>=1 and l+u+p+d==len(s)):\n print(\"Strong password\")\n break\n\n else:\n print(\"Weak password, try again\")\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074670610_python.txt |
Q:
Custom Sorting gglot2 in python
I am working on ggplt visualization, which plotting countries total expenditure from the highest to the lowest. Since there are many small values, I am aggregating several small categories into the "other" category. I am having trouble finding a way to move the "Other" Category to t... | Custom Sorting gglot2 in python | I am working on ggplt visualization, which plotting countries total expenditure from the highest to the lowest. Since there are many small values, I am aggregating several small categories into the "other" category. I am having trouble finding a way to move the "Other" Category to the end and keeping the rest sorted fr... | [
"In general, you can custom sort your dataframe outside ggplot (just using some pandas) and no reordering inside the plot aesthetics will be necessary.\nThe code below demonstrates this for the diamonds dataset that comes with plotline, where one factor level ('Premium') is moved to the bottom while all others rema... | [
0
] | [] | [] | [
"ggplot2",
"plotnine",
"python"
] | stackoverflow_0074668827_ggplot2_plotnine_python.txt |
Q:
meaning of double star in pandas dataframe construstor
I want to know what is the meaning of double star in the following pandas dataframe constructor '
If i delete it, then complier raises an error:
Mixing dicts with non-Series may lead to ambiguous ordering.
bus_summary = pd.DataFrame(**{'columns': ['business i... | meaning of double star in pandas dataframe construstor | I want to know what is the meaning of double star in the following pandas dataframe constructor '
If i delete it, then complier raises an error:
Mixing dicts with non-Series may lead to ambiguous ordering.
bus_summary = pd.DataFrame(**{'columns': ['business id column', 'latitude', 'longitude'],
'data': {'business id ... | [
"The double star (**) is used in the pandas dataframe constructor to indicate that the argument being passed is a dictionary containing key-value pairs. This is commonly used as a shorthand way to pass a dictionary as an argument to a function or method. In this case, the double star allows the dictionary containin... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074670749_pandas_python.txt |
Q:
Matplotlib in Rmarkdown/RStudio fails when calling LaTeX on `\$` with Anaconda
Problem description
I am having to use Anaconda on Windows, and am trying to write an RMarkdown document, knitted into a pdf, where within the RMarkdown I am using some Python snippets. However, when I try make matplotlib use LaTeX (wit... | Matplotlib in Rmarkdown/RStudio fails when calling LaTeX on `\$` with Anaconda | Problem description
I am having to use Anaconda on Windows, and am trying to write an RMarkdown document, knitted into a pdf, where within the RMarkdown I am using some Python snippets. However, when I try make matplotlib use LaTeX (with the rc.params) I find it does not render but hits an error I cannot understand nor... | [
"It looks like the error is occurring when matplotlib is trying to save the figure as a pdf. The specific error is a KeyError with the key b'tcrm1200', which is related to the font matplotlib is trying to use for rendering the LaTeX text. The b prefix indicates that the key is a byte string, rather than a regular s... | [
0
] | [
"Just remove the backslash! The string is already protected in single quote format.\nplt.title(r'Some Latex with symbol $')\n\n",
"I think u should type in text in 'markdown' section of JupyterNotebook in Ananconda, type the python code in the 'codes' section of the notebook too and finally save it as PDF via LaT... | [
-2,
-4
] | [
"latex",
"matplotlib",
"python",
"r",
"r_markdown"
] | stackoverflow_0058502671_latex_matplotlib_python_r_r_markdown.txt |
Q:
Why do i keep getting an undefined variable error message in python?
So I keep getting error messages for cost_delivery not being defined, but the rest of the cost__ variables are ok, and theres no difference to how I've coded them? I am including my code below - any help would be appreciated!
price = float(input(... | Why do i keep getting an undefined variable error message in python? | So I keep getting error messages for cost_delivery not being defined, but the rest of the cost__ variables are ok, and theres no difference to how I've coded them? I am including my code below - any help would be appreciated!
price = float(input("Please enter the price of the package: "))
distance = float(input("Please... | [
"in below section\ndelivery = input(\"Would you like priority or standard delivery?\")\nif delivery == 'priority':\n cost_delivery == priority_delivery\nelif delivery == 'standard':\n cost_delivery == standard_delivery\n\n\n== is used to check if two object have same value.\nsince cost_delivery is not defined... | [
1
] | [] | [] | [
"python",
"python_3.x",
"undefined"
] | stackoverflow_0074670753_python_python_3.x_undefined.txt |
Q:
Django add element to dynamic form
Is there a way to add image element for each input in form?
I need to have an image alongside each input from form. I created this sample form and model that works the same way as in my code. The result I'd like to get is this.
Sample form code
class CreateProfileForm(forms.Model... | Django add element to dynamic form | Is there a way to add image element for each input in form?
I need to have an image alongside each input from form. I created this sample form and model that works the same way as in my code. The result I'd like to get is this.
Sample form code
class CreateProfileForm(forms.ModelForm):
fieldsets = [
("Field... | [
"To add an image element for each input in a form, you can use the as_table method on the form in your template to render the form fields as an HTML table. Each input will be rendered as a table row, and you can add an img element to each row to display the image.\nHere is an example of how you could do this in you... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_templates",
"python"
] | stackoverflow_0074670825_django_django_forms_django_models_django_templates_python.txt |
Q:
get my instagram follower list with selenium
I'm beginner on programming. I trying get my Instagram follower list but i have just 12 follower. I tried firstly click to box and scroll down but it didn't work.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.com... | get my instagram follower list with selenium | I'm beginner on programming. I trying get my Instagram follower list but i have just 12 follower. I tried firstly click to box and scroll down but it didn't work.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
from selenium.common.... | [
"You can select multiple elements with this.\n#get all followers\nfollowers = driver.find_elements(By.CSS_SELECTOR, \"._ab8y._ab94._ab97._ab9f._ab9k._ab9p._abcm\")\n# loop each follower\nfor user in followers:\n #do something here.\n\nUsing css selectors, in my opinion, is much easier.\nAlso note I used find_ele... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074670747_python_selenium.txt |
Q:
Python and Pandas - Distances with latitude and longitude
I am trying compare distances between points (in this case fake people) in longitudes and latitudes.
I can import the data, then convert the lat and long data to radians and get the following output with pandas:
lat long
name ... | Python and Pandas - Distances with latitude and longitude | I am trying compare distances between points (in this case fake people) in longitudes and latitudes.
I can import the data, then convert the lat and long data to radians and get the following output with pandas:
lat long
name
Veronica Session 0.200081 0.246723
L... | [
"I used the function in the answer you linked and it worked fine. Can't confirm that the distance is in the unit you need though.\ndf['dist'] = \\\nhaversine(df.lat.shift(), df.long.shift(),\n df.loc[1:, 'lat'], df.loc[1:, 'long'], to_radians=False)\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>... | [
1
] | [] | [] | [
"pandas",
"python",
"traveling_salesman"
] | stackoverflow_0074670372_pandas_python_traveling_salesman.txt |
Q:
How do i have the if statement become effective after the 30 seconds
I want the if statement working after the 30 seconds but that isn't the case right now. I heard people recommend threading but that's just way too complicated for me.
import os
import time
print('your computer will be shutdown if you dont play m... | How do i have the if statement become effective after the 30 seconds | I want the if statement working after the 30 seconds but that isn't the case right now. I heard people recommend threading but that's just way too complicated for me.
import os
import time
print('your computer will be shutdown if you dont play my game or if you lose it')
shutdown = input("What is 12 times 13? you hav... | [
"I recommend to use threads because it makes the thing much easier here. Try this:\nimport threading\nimport time\n\nuser_input = \"\"\nANSWER_TIME = 30\n\ndef time_over():\n match user_input:\n case '156':\n exit(0)\n case '':\n print('you didnt even try')\n os.sys... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0074670704_python.txt |
Q:
python datetime.time extract from DB
i've got data extracted by pandas d=pd.read_sql(query, conn)
from DB which looks like this:
day
start
stop
2022-01-01
06:45:27
14:34:24
when i want to import it to array
start=np.asarray(d['start'])
it looks like this:
array([datetime.time(6, 45, 27)])
i want it to look it l... | python datetime.time extract from DB | i've got data extracted by pandas d=pd.read_sql(query, conn)
from DB which looks like this:
day
start
stop
2022-01-01
06:45:27
14:34:24
when i want to import it to array
start=np.asarray(d['start'])
it looks like this:
array([datetime.time(6, 45, 27)])
i want it to look it like
array([06:45:27])
is there a ... | [
"You can use the strftime method to convert the time objects to strings with a specific format. For example, to convert the time object to a string in the format \"HH:MM:SS\", you can do the following:\nimport numpy as np\n# Create a sample array of datetime.time objects\ntime_array = np.array([datetime.time(6, 45,... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074670821_numpy_pandas_python.txt |
Q:
how to specify log format for supervisor stdout log?
I have a process configured in supervisor as below. The module itself have its own logger in code. Normally we do not care the stdout_logfile.
But today I found there are some exception info in stdout_logfile (not captured by the logger in code). I want to know ... | how to specify log format for supervisor stdout log? | I have a process configured in supervisor as below. The module itself have its own logger in code. Normally we do not care the stdout_logfile.
But today I found there are some exception info in stdout_logfile (not captured by the logger in code). I want to know when did those exception happened. But the stdout_logfile ... | [
"in my case i solved this problem by using\nstderr_logfile=/home/root/project/logfile_err.log\n\nthis scripts\n"
] | [
0
] | [] | [] | [
"python",
"supervisord"
] | stackoverflow_0070705507_python_supervisord.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.