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:
RandomizedSearchCV - Sample from a grid that doesn't fit into int limit
When running the .fit method from RandomizedSearchCV, one of the operations is to check the length of the parameters.
For some of my tests, the size of this grid is bigger than the parameter size.
Is there a way to avoid this behaviour?
--> 33... | RandomizedSearchCV - Sample from a grid that doesn't fit into int limit | When running the .fit method from RandomizedSearchCV, one of the operations is to check the length of the parameters.
For some of my tests, the size of this grid is bigger than the parameter size.
Is there a way to avoid this behaviour?
--> 332 grid_size = len(ParameterGrid(self.param_distributions))
333 re... | [
"Looking at the code surrounding the snippet from your traceback, we can see that the full ParameterGrid is created when the param_distributions consists entirely of lists instead of scipy(-compatible) distributions. So an easy workaround is to just use a scipy distribution for at least one of your parameters (may... | [
0
] | [] | [] | [
"integer",
"python",
"scikit_learn",
"types"
] | stackoverflow_0074332734_integer_python_scikit_learn_types.txt |
Q:
activate venv with pyenv
I followed this guide to install pyenv in order to manage all python versions I have installed on my Mac. However, it is not clear to me what the pyenv global 3.7.3 command does and how I can activate a venv that uses python 3.7. If I type:
$ pyenv version
3.7.3
But apparently this is not... | activate venv with pyenv | I followed this guide to install pyenv in order to manage all python versions I have installed on my Mac. However, it is not clear to me what the pyenv global 3.7.3 command does and how I can activate a venv that uses python 3.7. If I type:
$ pyenv version
3.7.3
But apparently this is not enough to activate the venv?
| [
"list python versions in terminal:\n $ pyenv install --list | grep \" 3\\.[678]\"\nInstall Python version if not in list:\n $ pyenv install 3.8.6\nCreate virtual env with python version:\n $ pyenv virtualenv 3.8.6 project1\nList versions of virtual environments:\n$ pyenv versions\nActivate a virtual version:\npye... | [
12,
7,
1,
0
] | [] | [] | [
"macos",
"pyenv",
"python",
"python_venv"
] | stackoverflow_0062841295_macos_pyenv_python_python_venv.txt |
Q:
Adding a column with no header to a dataframe
How can I add an empty column to my dataframe without introducing a header to it?
I am using pandas to work on a dataframe where I need to add an empty column without any header. I know that by using
df["New_Column_Name"] = ""
(where df is my dataframe) would add an ... | Adding a column with no header to a dataframe | How can I add an empty column to my dataframe without introducing a header to it?
I am using pandas to work on a dataframe where I need to add an empty column without any header. I know that by using
df["New_Column_Name"] = ""
(where df is my dataframe) would add an empty column to the df. But, in my case I don't wan... | [
"data = {'Name': ['Rob', 'Bob', 'Tob'],\n 'Age': [20, 21, 19]}\ndf = pd.DataFrame(data)\ndf[''] = ''\nprint(df.columns)\n\noutput:\nIndex(['Name', 'Age', ''], dtype='object')\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074336879_dataframe_pandas_python.txt |
Q:
Image upload leads to Server Error (500) Django app deployed on railway.app
I have deployed a django app on railway.app. In development I can upload images but when I go to deployed app and click on upload it leads me to Server Error (500).
following is my settings.py code
STATIC_URL = 'static/'
# STATIC_ROOT = BA... | Image upload leads to Server Error (500) Django app deployed on railway.app | I have deployed a django app on railway.app. In development I can upload images but when I go to deployed app and click on upload it leads me to Server Error (500).
following is my settings.py code
STATIC_URL = 'static/'
# STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STA... | [
"I have solved this issue. I changed debug to true in production and which lead me to the the exact error which was actually in view logic.\nI was getting absolute path of the image which was throwing this error so I changed this logic to get relative path which solved this issue.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074307325_django_python.txt |
Q:
How to telnet checkpoint firewalls using python?
I want to check whether the console for the checkpoint firewalls is working or not which python Library should I use and how to use?
I tried telnetlib but was unable to find the correct output
A:
I don't know if that can helps you but maybe you can try pwntools or... | How to telnet checkpoint firewalls using python? | I want to check whether the console for the checkpoint firewalls is working or not which python Library should I use and how to use?
I tried telnetlib but was unable to find the correct output
| [
"I don't know if that can helps you but maybe you can try pwntools or use directly socket module.\npwntools (you can connect to an endpoint using ssh or telnet and then run an interactive shell) :\n\nhttps://pypi.org/project/pwntools/\nhttps://docs.pwntools.com/en/stable/install.html\n\nsocket :\n\nhttps://docs.pyt... | [
0,
0
] | [] | [] | [
"automation",
"networking",
"python"
] | stackoverflow_0074293999_automation_networking_python.txt |
Q:
How to assign a new column to a dataframe based on comparison between other columns?
In my one sheet Excel file that I created through my SQL, I have 3 columns that represent letter ratings. The rating values may differ between ratings 1, 2, and 3, but they can still be ranked with the same value.
I am trying to c... | How to assign a new column to a dataframe based on comparison between other columns? | In my one sheet Excel file that I created through my SQL, I have 3 columns that represent letter ratings. The rating values may differ between ratings 1, 2, and 3, but they can still be ranked with the same value.
I am trying to create a new column in my Excel file that can take these 3 letter ratings and pull the midd... | [
"With the fowllowing toy dataframe:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"Rating_1\": [\"A+\", \"Cc\", \"Aa\"],\n \"Rating_2\": [\"AA\", \"Cc\", \"Aa\"],\n \"Rating_3\": [\"BB\", \"Cc\", \"Bb\"],\n }\n)\n\nprint(df)\n# Output\n Rating_1 Rating_2 Rating_3\n0 A+ AA... | [
0
] | [] | [] | [
"conditional_statements",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074267915_conditional_statements_dataframe_pandas_python.txt |
Q:
Pandas - Group by multiple columns and datetime
I have a df of tennis results and I would like to be able to see how many days its been since each player last won a game.
This is what my df looks like
Player 1
Player 2
Date
p1_win
p2_win
Murray
Nadal
2022-05-16
1
0
Nadal
Murray
2022-05-25
1
0
and this is what ... | Pandas - Group by multiple columns and datetime | I have a df of tennis results and I would like to be able to see how many days its been since each player last won a game.
This is what my df looks like
Player 1
Player 2
Date
p1_win
p2_win
Murray
Nadal
2022-05-16
1
0
Nadal
Murray
2022-05-25
1
0
and this is what I want it to look like
Player 1
Player ... | [
"I leveraged pd.merge_asof to find the latest win, and then did a merge to the relevant index.\n df = pd.DataFrame({'Player 1': {0: 'Murray', 1: 'Nadal', 2: 'Murray', 3: 'Nadal', 4: 'Murray', 5: 'Nadal', 6: 'Murray'}, 'Player 2': {0: 'Nadal', 1: 'Murray', 2: 'Nadal', 3: 'Murray', 4: 'Nadal', 5: 'Murray', 6: 'Nad... | [
0
] | [] | [] | [
"datetime",
"group_by",
"pandas",
"python"
] | stackoverflow_0074335578_datetime_group_by_pandas_python.txt |
Q:
Why does my code to find a cycle in a DG not work correctly?
I have the following task about finding a cycle in a directed graph.
https://www.eolymp.com/en/problems/2270
Here is my code, it passes 82%. Where can there be inaccuracies here? I did exactly according to the instructions for describing the algorithms.
... | Why does my code to find a cycle in a DG not work correctly? | I have the following task about finding a cycle in a directed graph.
https://www.eolymp.com/en/problems/2270
Here is my code, it passes 82%. Where can there be inaccuracies here? I did exactly according to the instructions for describing the algorithms.
def dfs(start_v, G, Color, path, result):
Color[start_v] = 1
... | [
"The problem is that your code will print \"NO\" before having iterated all the nodes of the graph. This should not happen within the loop, but after. This is important in cases where the first DFS traversal does not reach all nodes, and there is a cycle in the nodes that it did not reach yet. So the cycle will onl... | [
0
] | [] | [] | [
"algorithm",
"directed_graph",
"python"
] | stackoverflow_0074336824_algorithm_directed_graph_python.txt |
Q:
Openpyxl - Remove duplicates when copy and pasting data between workbooks
My script copies from one workbook to another and sorts them based on value. I'm trying to find a way to remove duplicates. I tried to use an if statement to check if the data already exists in the destination workbook, but it is not working... | Openpyxl - Remove duplicates when copy and pasting data between workbooks | My script copies from one workbook to another and sorts them based on value. I'm trying to find a way to remove duplicates. I tried to use an if statement to check if the data already exists in the destination workbook, but it is not working correctly. Where am I going wrong?
from openpyxl import load_workbook
from op... | [
"I don't see the pandas tag in your question but in case you're interested, you can use some of this library functions to avoid loops, speed up your transformation and get the same result you're looking for.\nimport pandas as pd\n\ncols_template= [\"A\", \"B\", \"C\"]\n\ndef concat_missingvals(df):\n out = pd.co... | [
1
] | [] | [] | [
"for_loop",
"loops",
"openpyxl",
"python"
] | stackoverflow_0074332546_for_loop_loops_openpyxl_python.txt |
Q:
AttributeError: 'Dash' object has no attribute 'run' in Python/Plotly-DASH
I am new in python and dashboard building so I am trying to print a phylogenetic tree with dash. But I encounter the following problem AttributeError: 'Dash' object has no attribute 'run' as soon as I try to run the app. I know my code pro... | AttributeError: 'Dash' object has no attribute 'run' in Python/Plotly-DASH | I am new in python and dashboard building so I am trying to print a phylogenetic tree with dash. But I encounter the following problem AttributeError: 'Dash' object has no attribute 'run' as soon as I try to run the app. I know my code probably is problematic but this error in this case seems that dash is not capable ... | [
"It should be one method, run_server:\nif __name__ == '__main__':\n app.run_server(debug=True)\n\n"
] | [
0
] | [] | [] | [
"dashboard",
"plotly_dash",
"python"
] | stackoverflow_0074331179_dashboard_plotly_dash_python.txt |
Q:
Python: Working on arrays need assistance in setting a range so the user cannot enter an input over 100
This is a snippet of the code I am working on
mark =[]
totMark1 = 0
# Set the value for pre_class_activity and determine the weight of pre-class activities
pre_class_activity = 4
weight1 = pre_class... | Python: Working on arrays need assistance in setting a range so the user cannot enter an input over 100 | This is a snippet of the code I am working on
mark =[]
totMark1 = 0
# Set the value for pre_class_activity and determine the weight of pre-class activities
pre_class_activity = 4
weight1 = pre_class_activity * 4
try:
# ask the user to enter their marks they got in the pre class activity store them in ... | [
"for i in range(pre_class_activity):\n marks = -1\n while marks not in range(101):\n marks = int(input())\n \n if marks not in range(101):\n print(\"Marks should be between 0 and 100\")\n\n mark.append(marks)\n\nIt runs a loop, so in case if the input is not in range 0 - 100... | [
-1
] | [
"mark =[]\ntotMark1 = 0\n\npre_class_activity = 4\nweight1 = pre_class_activity * 4\n\ntry:\n\n print(\"Please enter the marks you have obtained in the \" + str(pre_class_activity) + \" pre-class activities in numeric values: \")\n\n for i in range(pre_class_activity):\n marks = -1\n while marks... | [
-1
] | [
"python"
] | stackoverflow_0074336854_python.txt |
Q:
PySimpleGUI listboxes and double-key problem
Working with PySimpleGUI a while before, I found a problem related to how I wanted to handle my program.
I wanted my app to have language system, which worked on key system - it simply checked the language in settings file, and headed to respective language file with ke... | PySimpleGUI listboxes and double-key problem | Working with PySimpleGUI a while before, I found a problem related to how I wanted to handle my program.
I wanted my app to have language system, which worked on key system - it simply checked the language in settings file, and headed to respective language file with key provided. In such manner:
EN file:
{
"text_fie... | [
"You have two ways of getting the values from a Listbox\n\nusing values['-Listbox-'] for getting the actual value\nusing sg.Listbox().get_indexes() for getting the index of the selection\n\nThe implementation of get_indexes() looks like this\nimport PySimpleGUI as sg\n\nvalue_list = ['something', 'something else', ... | [
0,
0,
0
] | [] | [] | [
"listbox",
"pysimplegui",
"python"
] | stackoverflow_0074288080_listbox_pysimplegui_python.txt |
Q:
How to use user input date as a positional argument for a class?
import datetime
class JoiningDetails:
Name = str(input("Enter the name : "))
def __init__(self,x):
self.x = x
def output(self):
print (Name.x)
def getDoJ(self):
Name.x = input("Enter the... | How to use user input date as a positional argument for a class? | import datetime
class JoiningDetails:
Name = str(input("Enter the name : "))
def __init__(self,x):
self.x = x
def output(self):
print (Name.x)
def getDoJ(self):
Name.x = input("Enter the date of Joining of the employee in YYYY/MM/DD format\t:\t")
... | [
"You have to write a function inside the class and then you can pass it as a positional argument while creating the object.\nI'll give you a simple example to understand, you could possibly can refactor it according to your needs.\nfrom datetime import datetime\n\n\nclass JoiningDetails:\n def __init__(self, joi... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074337036_python.txt |
Q:
Recursion output isn't printing
I'm new to python and trying to understand recursion. I'm trying to write a code where someone inputs 2 numbers (Num1, Num2). A calculation will take place until Num1 is greater than Num 2. The result of the calculation's final value should then be outputted.
This is my code:
def Re... | Recursion output isn't printing | I'm new to python and trying to understand recursion. I'm trying to write a code where someone inputs 2 numbers (Num1, Num2). A calculation will take place until Num1 is greater than Num 2. The result of the calculation's final value should then be outputted.
This is my code:
def Recursive(Num1, Num2):
if Num1 > Nu... | [
"def Recursive(Num1, Num2):\n if Num1 > Num2:\n return 10\n if Num1 == Num2:\n return Num1\n print(Num1, Num2)\n return Num1 + Recursive(Num1 * 2, Num2)\n\nNum1=int(input(\"Enter number 1: \"))\nNum2=int(input(\"Enter number 2: \"))\nprint(\"Final value: \", Recursive(Num1, Num2))\n\nThis ... | [
2
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074336930_python_recursion.txt |
Q:
append elements from specific positions of a list to another lists in one line function
I need to generate M lists from another list with N=a*M elements (a>=1), so the nth element of i partition is added to the the nth position of the i new list (i=1..M, so the original list is splitted in equal parts of N/M lengt... | append elements from specific positions of a list to another lists in one line function | I need to generate M lists from another list with N=a*M elements (a>=1), so the nth element of i partition is added to the the nth position of the i new list (i=1..M, so the original list is splitted in equal parts of N/M length).
With an example is a lot easier to understand:
so supose that I have this list lg=[1,2,3,... | [
"You can do this with a simple slice operation:\n>>> lg=[1,2,3,4,5,6,7,8,9]\n>>> [lg[i::3] for i in range(3)]\n[[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n\nThe third part of the slice is the \"step\" between each element in the slice; it defaults to 1, but setting it to M makes it take every Mth element.\n"
] | [
2
] | [] | [] | [
"iterable",
"list",
"python"
] | stackoverflow_0074337178_iterable_list_python.txt |
Q:
Clicking on button in windows 10 via python
I used win32com to read and send an outlook mail, but when i do it creates a pop up which asks me to deny or allow the program to do so, there is a python module which will allow me to press "allow for 10 minutes," and then click allow?
Just wanted to know if there a mod... | Clicking on button in windows 10 via python | I used win32com to read and send an outlook mail, but when i do it creates a pop up which asks me to deny or allow the program to do so, there is a python module which will allow me to press "allow for 10 minutes," and then click allow?
Just wanted to know if there a module which is able to do so similar to what seleni... | [
"Yes.\nIt's called pywinauto and it does Native GUI automation for Windows.\nTo get the id's of the UI you're trying to automate, use what Microsoft recommends: Accessiblity Insights.\n",
"You get a standard security prompt in Outlook.\nThere are several ways for suppressing such prompts:\n\nUse a third-party com... | [
0,
0
] | [] | [] | [
"office_automation",
"outlook",
"python",
"win32com"
] | stackoverflow_0074334802_office_automation_outlook_python_win32com.txt |
Q:
OSError: [Errno 97] when trying to run locust in Linux RHEL
I did locust complete installation using pip3 install locust, wrote a small script to test it and I'm getting the following stack:
[2022-11-06 12:02:03,635] acabista.remote.csb/INFO/locust.main: Starting Locust 2.13.0
Traceback (most recent call last):
... | OSError: [Errno 97] when trying to run locust in Linux RHEL | I did locust complete installation using pip3 install locust, wrote a small script to test it and I'm getting the following stack:
[2022-11-06 12:02:03,635] acabista.remote.csb/INFO/locust.main: Starting Locust 2.13.0
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 908, in gevent._gevent_cgreen... | [
"I just found out the answer for it in here: https://github.com/locustio/locust/issues/1770\nTo make locust run in the http://localhost:8089/ I needed to run the command as\nlocust -f first_locust_file.py --web-host localhost\n"
] | [
0
] | [] | [] | [
"locust",
"python",
"python_3.x"
] | stackoverflow_0074337071_locust_python_python_3.x.txt |
Q:
Getting Flask JSON response as an HTML Table?
I was wondering if there might be a way to return my Flask app's response as an HTML table populated by the JSON response key value pairs instead of merely having the entire JSON string on the HTML page?
Below is the code that i have:
from flask import Flask
import jso... | Getting Flask JSON response as an HTML Table? | I was wondering if there might be a way to return my Flask app's response as an HTML table populated by the JSON response key value pairs instead of merely having the entire JSON string on the HTML page?
Below is the code that i have:
from flask import Flask
import json, pandas as pd
app = Flask(__name__)
@app.route(... | [
"You should write a template for it like Alex Hall said.\nIt won't be hardcoded if you loop through column names.\nFirstly, you should import render_template.\nfrom flask import Flask, render_template\n\nThen, you need to change your request handler. This allows to render a template 'record.html' with injecting two... | [
9,
4,
0
] | [] | [] | [
"csv",
"flask",
"html_table",
"json",
"python"
] | stackoverflow_0049964340_csv_flask_html_table_json_python.txt |
Q:
How to create an array from selected csv values?
array = []
for vid in account:
vid_shares = (df.loc[df['account'] == '123', 'shares'])
array.append(vid_shares)
print(array)
This produces something in the following format.
1 10.0
2 15.0
3 0.0
4 12.0
5 17.0
6 0.0
7 9... | How to create an array from selected csv values? |
array = []
for vid in account:
vid_shares = (df.loc[df['account'] == '123', 'shares'])
array.append(vid_shares)
print(array)
This produces something in the following format.
1 10.0
2 15.0
3 0.0
4 12.0
5 17.0
6 0.0
7 9.0
8 12.0
9 13.0
10 8.0
11 30.0
1... | [
"If you just want the sum.\ntotal = df[\"shares\"].sum()\n\nIf you want a list.\nshares = df[\"shares\"].tolist()\n\nIf you want an array.\narr = df[\"shares\"].to_numpy()\n\n",
"The sum of all the values is calculated with array.sum()\ne.g. in your case :\n>>> array.sum()\n142.0\n\n"
] | [
0,
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074336996_csv_dataframe_pandas_python.txt |
Q:
How to use sync_to_async() in Django template?
I am trying to make the Django tutorial codes polls into async with uvicorn async view.
ORM query works with async view by wrapping in sync_to_async() as such.
question = await sync_to_async(Question.objects.get, thread_sensitive=True)(pk=question_id)
But I have no i... | How to use sync_to_async() in Django template? | I am trying to make the Django tutorial codes polls into async with uvicorn async view.
ORM query works with async view by wrapping in sync_to_async() as such.
question = await sync_to_async(Question.objects.get, thread_sensitive=True)(pk=question_id)
But I have no idea how to apply sync_to_async or thread inside Djan... | [
"I have found several solutions for that:\nIt's not safe. In your settings.py add:\nimport os\nos.environ[\"DJANGO_ALLOW_ASYNC_UNSAFE\"] = \"true\"\n\nOr get your Question object in separate function:\n@sync_to_async\ndef get_question(question_id):\n return get_object_or_404(Question, pk=question_id)\n\nquestion... | [
1
] | [] | [] | [
"asynchronous",
"django",
"python"
] | stackoverflow_0072394322_asynchronous_django_python.txt |
Q:
Calculating precision, recall and F1 score per class in a multilabel classification problem
I'm trying to calculate the precision, the recall and the F1-Score per class in my multilabel classification problem. However, I think I'm doing something wrong, because I am getting really high values, and the F1 Score for... | Calculating precision, recall and F1 score per class in a multilabel classification problem | I'm trying to calculate the precision, the recall and the F1-Score per class in my multilabel classification problem. However, I think I'm doing something wrong, because I am getting really high values, and the F1 Score for the whole problem is 0.66. However, I'm getting +0.8 f1-score in the individual classes.
This is... | [
"You could use the classification_report function from sklearn:\nfrom sklearn.metrics import classification_report\n\nlabels = [[0, 1, 1], [1, 0, 0], [1, 0, 1]]\npredictions = [[[0, 0, 1], [1, 0, 0], [1, 1, 1]]\n\nreport = classification_report(labels, predictions)\nprint(report)\n\nWhich outputs:\n pr... | [
1
] | [] | [] | [
"machine_learning",
"multilabel_classification",
"precision_recall",
"python",
"scikit_learn"
] | stackoverflow_0074336968_machine_learning_multilabel_classification_precision_recall_python_scikit_learn.txt |
Q:
Is there a Python function I can use for a condition like "If condition is still true after (3) seconds then dosomething"(
I am running a opencv through django and trying to save the data in sqlite.
I tried to use the sleep() in library time, but it only prevents my web app from running.
color = (0, 0, 255)
time.... | Is there a Python function I can use for a condition like "If condition is still true after (3) seconds then dosomething"( | I am running a opencv through django and trying to save the data in sqlite.
I tried to use the sleep() in library time, but it only prevents my web app from running.
color = (0, 0, 255)
time.sleep(3)
if color == (0, 0, 255):
save time
| [
"You have more options to solve this, here and here are some examples.\nExample with time and while loop:\nimport time\n\ndef your_func():\n #your code:\n #if color == (0, 0, 255):\n #save time\n\nmax_wait_time = 3.0 #the time you want in seconds\nstart_time = time.time()\nwhile True:\n if (time.time() ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074336978_django_python.txt |
Q:
Adding datetime by 1 hour implementation to existing dataset with (dumb question)
I have 3 columns in the dataset to which I wanna add dates
Date
temperature
humidity
2015-01-01 00:00:00
5.9
NA
2015-01-01 01:00:00
5.5
NA
⋮
⋮
⋮
2015-01-01 23:00:00
7
NA
I wanna add 2 months like from 1st may to 31 july to Date... | Adding datetime by 1 hour implementation to existing dataset with (dumb question) | I have 3 columns in the dataset to which I wanna add dates
Date
temperature
humidity
2015-01-01 00:00:00
5.9
NA
2015-01-01 01:00:00
5.5
NA
⋮
⋮
⋮
2015-01-01 23:00:00
7
NA
I wanna add 2 months like from 1st may to 31 july to Date column
with hour implementation it will be smth like this
Date
tempera... | [
"Well, you have a start with the iteration from datetime.datetime and datetime.timedelta\nYou need to accumulate those in a list, rather than printing them\nlistofdates=[]\ndate = datetime.datetime(2015,3,31,23,0,0)\nfor i in range(32): \n date += datetime.timedelta(hours=1)\n listofdates.append(date)\n\nAnd ... | [
0
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074336756_dataframe_datetime_pandas_python.txt |
Q:
Normalizing a list of strings Python
I have a very large list of strings which each words in the list are unnormalized, for instance:
word_list = ["Alzheimer", "Alzheimer's", "Alzheimer.", "Alzheimer?","Cognition.", "Cognition's", "Cognitions", "Cognition"] # and the list goes on
As you can see,there are many ide... | Normalizing a list of strings Python | I have a very large list of strings which each words in the list are unnormalized, for instance:
word_list = ["Alzheimer", "Alzheimer's", "Alzheimer.", "Alzheimer?","Cognition.", "Cognition's", "Cognitions", "Cognition"] # and the list goes on
As you can see,there are many identical terms in the list but some of them ... | [
"You can try to use this function, I tried this, it removes all the special characters (All non letters/digits) and punctuations and gets the statement to lower case letters\nimport re\ndef word_normalizer(word): \n word = re.sub('[^A-Za-z0-9]+', '', word)\n return word.lower()\n\n",
"The standard string mo... | [
0,
0,
0
] | [
"You can also use str.translate and str.maketrans with punctuation from string module to remove punctuation:\nword_list = [\"Alzheimer\", \"Alzheimer's\", \"Alzheimer.\", \"Alzheimer?\",\"Cognition.\", \"Cognition's\", \"Cognitions\", \"Cognition\"]\n\ndef word_normalizer(word):\n from string import punctuation\... | [
-1
] | [
"data_cleaning",
"normalization",
"python",
"string"
] | stackoverflow_0074336544_data_cleaning_normalization_python_string.txt |
Q:
Find out if and how a chess game was finished
I'm using Stockfish 15 and Python 3.10 to build a browser chessgame.
Now I'm struggling to figure out if a game is over (win, lose, draw).
I have now searched for hours in forums etc. for an answer and found none. Can anyone help me further?
A:
The python-chess packa... | Find out if and how a chess game was finished | I'm using Stockfish 15 and Python 3.10 to build a browser chessgame.
Now I'm struggling to figure out if a game is over (win, lose, draw).
I have now searched for hours in forums etc. for an answer and found none. Can anyone help me further?
| [
"The python-chess package has a board.is_checkmate() option:\npython-chess.readthedocs.io/en/latest\nAny game that is not a checkmate can be a draw by repetition, so having the history of the moves in the game is necessary. Knowing the history of the game, python-chess can also look for draws, stalemates, general o... | [
0
] | [] | [] | [
"chess",
"python",
"python_3.x",
"stockfish"
] | stackoverflow_0074335118_chess_python_python_3.x_stockfish.txt |
Q:
Python TCP sockets headers
I need to create a communication between a client and a server with TCP. But I'd like to send and work with "headers". So from the client I'd like to send a header "COMMAND1" and the server returns me something.
I have the following code:
Server
import socket
import threading
bind_ip = ... | Python TCP sockets headers | I need to create a communication between a client and a server with TCP. But I'd like to send and work with "headers". So from the client I'd like to send a header "COMMAND1" and the server returns me something.
I have the following code:
Server
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9998
serv... | [
"If you want to add your own header, you just have to:\n\nMake sure your programm finds the start of your message (like, every message beginns \"!?&\")\nSend your own header-data just after the start-symbol of your message.\nMaybe mark the end of your message with something or pass a length in your header.\nSince T... | [
0,
0
] | [] | [] | [
"python",
"sockets",
"tcp",
"tcpclient"
] | stackoverflow_0048522920_python_sockets_tcp_tcpclient.txt |
Q:
How to scrape info from table with beautifulsoup?
In the following kind of HTML table's columns, I can't get the numeric values under the quotation marks with the find_all('td')[i].text command. Python returns me blank values instead of 3.03, 1.21, etc...
Please can someone help me catching those values?
<td class... | How to scrape info from table with beautifulsoup? | In the following kind of HTML table's columns, I can't get the numeric values under the quotation marks with the find_all('td')[i].text command. Python returns me blank values instead of 3.03, 1.21, etc...
Please can someone help me catching those values?
<td class="table-main__odds colored" data-oid="5lmp0xv464x0xf55p... | [
".text won't work cause, the expected values are no texts. Select all the elements by its attribute (data-odd) and extract the value:\nfor e in soup.select('[data-odd]'):\n print(e.get('data-odd'))\n\n-> 3.03\n 1.21\n 3.23\n\nor only from <span>\nfor e in soup.select('span[data-odd]'):\n print(e.get('data... | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074337407_beautifulsoup_html_python_web_scraping.txt |
Q:
Creating one csv file containing data from many csv files
I have a folder full of csv files that contain results for different participants in an experiment. I'm trying to create one large csv file containing all the csv files in the directory. I'm using listdir() to create a list of all the files but I haven't be... | Creating one csv file containing data from many csv files | I have a folder full of csv files that contain results for different participants in an experiment. I'm trying to create one large csv file containing all the csv files in the directory. I'm using listdir() to create a list of all the files but I haven't been able to open the individual files in this list. I think I ne... | [
"Your issue is that listdir() returns the filenames without their path information, so you need to append the filename to the path.\nimport os\n...\n\nfor file in files:\n participant = open(os.join(path, file), \"r\"):\n ...\n\nOther details:\nf\"{file}\" is the same thing as just file. I.e., open(file, \"r\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074337084_python.txt |
Q:
How to sort a list alphabetically taken from a DataFrame
I have following df....
symbol changeInOI latestOI prevOI volume underlyingValue
ULTRACEMCO 2189 31832 29643 83044 6894
DRREDDY 1399 32838 31439 25451 4520
BAJFINANCE 1305 69772 68467... | How to sort a list alphabetically taken from a DataFrame | I have following df....
symbol changeInOI latestOI prevOI volume underlyingValue
ULTRACEMCO 2189 31832 29643 83044 6894
DRREDDY 1399 32838 31439 25451 4520
BAJFINANCE 1305 69772 68467 73528 7212
MARUTI 987 81983 8... | [
"Read the Python documentation of the sort method of a list. Check the contents of a after calling .sort().\n\nsort(*, key: None = ..., reverse: bool = ...) -> None\nsort(*, key: (int) -> SupportsRichComparison, reverse: bool = ...) -> None\n\nSort the list in ascending order and return None.\n\nThe sort is in-plac... | [
0
] | [] | [] | [
"dataframe",
"python",
"sorting"
] | stackoverflow_0074337439_dataframe_python_sorting.txt |
Q:
Can I have env vars in the python string for file path
I'd like to add a folder to PATH on Windows with this call:
sys.path.append(r'C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python37\Lib\site-packages')
However my interpreter gives me a bunch of errors (py 3.7.13).
Is there a way I can have Windows env v... | Can I have env vars in the python string for file path | I'd like to add a folder to PATH on Windows with this call:
sys.path.append(r'C:\Users\%USERNAME%\AppData\Local\Programs\Python\Python37\Lib\site-packages')
However my interpreter gives me a bunch of errors (py 3.7.13).
Is there a way I can have Windows env vars in the path string referenced in such exotic manner?
| [
"I've ended with a solution like this\nsys.path.append(f'C:\\\\Users\\\\{os.environ.get(\"USERNAME\")}\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\Lib\\\\site-packages')\n\nI had to change '\\' to '\\\\' because I use formatted output f'' to insert username into the string.\n"
] | [
0
] | [] | [] | [
"environment_variables",
"python",
"python_3.x"
] | stackoverflow_0074319158_environment_variables_python_python_3.x.txt |
Q:
local variable 'sbang' referenced before assignment
I am trying to return an array that has 1 added to the value represented by the array given the array of any length but I get this error once I execute my code:
UnboundLocalError: local variable 'sbang' referenced before assignment
My code is :
def up_array(arr)... | local variable 'sbang' referenced before assignment | I am trying to return an array that has 1 added to the value represented by the array given the array of any length but I get this error once I execute my code:
UnboundLocalError: local variable 'sbang' referenced before assignment
My code is :
def up_array(arr):
for i in arr:
if i < 0:
re... | [
"In your code if arr is empty then the for loop will not be executed and sbang will never be initialized. You can fix it by doing:\ndef up_array(arr):\n\n for i in arr:\n if i < 0:\n return None\n if i > 9:\n return None\n sbang = \"\".join(map(str, arr))\n a = \"0\" + s... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074337398_python.txt |
Q:
How to split some text to another column from pandas dataframe
Let's say I have below dataframe
ID EQ Type
0 P-456 BSD500,BSD300,GHF20e,GHF20g
1 P-460 BSD500,BSD300,GHF20e
2 P-462 GHF20e,GHF20g,GHF20h
I want to take some text of EQ Type's row then ins... | How to split some text to another column from pandas dataframe | Let's say I have below dataframe
ID EQ Type
0 P-456 BSD500,BSD300,GHF20e,GHF20g
1 P-460 BSD500,BSD300,GHF20e
2 P-462 GHF20e,GHF20g,GHF20h
I want to take some text of EQ Type's row then insert it to another column, the expected result is as below
... | [
"I hope I've understood you correctly, you want to extract every GHF20* value into a separate column:\ndf = df.assign(tmp=df[\"EQ Type\"].str.split(\",\")).explode(\"tmp\")\ndf[\"\"] = np.where(df[\"tmp\"].str.startswith(\"GHF20\"), \"EQ Type_1\", \"EQ Type\")\n\nprint(\n df.pivot_table(\n index=[df.inde... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"split"
] | stackoverflow_0074337380_dataframe_pandas_python_split.txt |
Q:
WinError 5:Access denied PyTesseract
I know this question has already been answered on this site, however, none of the solutions I looke up the internet seemed to work. Here's what I tried:
Giving all permissions to my python file
Changing PATH variable to point to my tesseract folder
Running IDLE as administrato... | WinError 5:Access denied PyTesseract | I know this question has already been answered on this site, however, none of the solutions I looke up the internet seemed to work. Here's what I tried:
Giving all permissions to my python file
Changing PATH variable to point to my tesseract folder
Running IDLE as administrator and then executing the file from there
... | [
"I suspect a few things, not sure about any though.\nFirst and the most obvious, the path to Tesseract is not complete. It should be something like:\ntesseract_cmd = 'C:\\\\Program Files (x86)\\\\Tesseract-OCR\\\\tesseract'\n\nI believe your path points to a directory/folder and not an executable, though only you c... | [
18,
18,
5,
1,
0
] | [
"Install the tesseract exe in a directory inside your project. I did the above and it worked fine, without giving Win 5 error.\n"
] | [
-1
] | [
"error_handling",
"ocr",
"python",
"python_tesseract",
"windows"
] | stackoverflow_0046004859_error_handling_ocr_python_python_tesseract_windows.txt |
Q:
Django - show bootstrap modal after successful save data to db
I'm new to Django and at this point , I set up a very simple post article page, I hope that when I successfully save the article, it will show the message of the bootstrap modal style.
model.py
from django.db import models
from django.utils import time... | Django - show bootstrap modal after successful save data to db | I'm new to Django and at this point , I set up a very simple post article page, I hope that when I successfully save the article, it will show the message of the bootstrap modal style.
model.py
from django.db import models
from django.utils import timezone
class Article(models.Model):
title = models.CharField(max_... | [
"The problem is with modal itself, whenever you are submitting the form the form gets submitted but when it comes with saved=True then also there is a need for clicking the button of modal to display the message saved successfully which is not possible. So the other alternative is to use alert classes of boostrap (... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074337042_django_django_forms_django_templates_django_views_python.txt |
Q:
does an instance of a Ray actor run in only one process?
Can the methods of a Ray actor be called in parallel on a single remote instance? it seems i have to create a new instance of the actor, then call the method on that instance in order to achieve parallelization. See the code and out put below
@ray.remote
cla... | does an instance of a Ray actor run in only one process? | Can the methods of a Ray actor be called in parallel on a single remote instance? it seems i have to create a new instance of the actor, then call the method on that instance in order to achieve parallelization. See the code and out put below
@ray.remote
class ActorTest:
def __init__(self) -> None:
self.fac... | [
"It is possible to call the methods of a single actor in parallel either via asyncio or threading: https://docs.ray.io/en/latest/ray-core/actors/async_api.html\nAs stated in the docs neither bypasses the Gil\n"
] | [
2
] | [] | [] | [
"multiprocessing",
"parallel_processing",
"python",
"ray"
] | stackoverflow_0074334814_multiprocessing_parallel_processing_python_ray.txt |
Q:
How to get activation values of a layer in pytorch
I have a pytorch-lightning model that has a dense layer like so:
def __init__(...)
...
self.dense = nn.Linear(channels[-1], 64, bias=True)
...
for my project, I need to get the activation values of this layer as a list
I have tried this code which I found on the ... | How to get activation values of a layer in pytorch | I have a pytorch-lightning model that has a dense layer like so:
def __init__(...)
...
self.dense = nn.Linear(channels[-1], 64, bias=True)
...
for my project, I need to get the activation values of this layer as a list
I have tried this code which I found on the pytorch discussion forum:
activation = {}
def get_activ... | [
"It seems like you model does not have 'dense' layer, only 'fc'.\nTry:\nmodelftr.fc.register_forward_hook(get_activation('fc'))\n\n"
] | [
1
] | [] | [] | [
"python",
"pytorch",
"pytorch_lightning"
] | stackoverflow_0074337447_python_pytorch_pytorch_lightning.txt |
Q:
Python dynamic alias for an object attribute rather than get just a value of attribute (get actual dict key value)
I have the next code:
current_money = my_dict[long_key_1][long_key_2]...[users][user][one_more_long_key][current_money]
I want to access current_money without typing this long line every time,
but cu... | Python dynamic alias for an object attribute rather than get just a value of attribute (get actual dict key value) | I have the next code:
current_money = my_dict[long_key_1][long_key_2]...[users][user][one_more_long_key][current_money]
I want to access current_money without typing this long line every time,
but current_money is immutable int, saving it to variable will not hold an actual value.
How I can easy create alias to acces... | [
"You're right, the full expression you gave will not allow you to update the value. But you could stop one level short:\nuser_alias = my_dict[long_key_1][long_key_2]...[users][user]\nuser_alias[current_money] = new_value\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074337556_python.txt |
Q:
win32com MSProject find value and related Unique ID
writing python extension using win32com module to connect to MSProject. The tasks in the project have been 'dispatched' or not. If the task was not dispatched, the date is NULL. SO I iterate through the tasks and find those with 'dispatch date' == NULL, and pl... | win32com MSProject find value and related Unique ID | writing python extension using win32com module to connect to MSProject. The tasks in the project have been 'dispatched' or not. If the task was not dispatched, the date is NULL. SO I iterate through the tasks and find those with 'dispatch date' == NULL, and place them in a temp list, easy.
local_temp_list = []
for t... | [
"Use the UniqueID property of the Tasks object to reference a task by its UID.\nTry something like this:\nfor uid in local_temp_list:\n task = MSProject.Tasks.UniqueID(uid)\n\n"
] | [
0
] | [] | [] | [
"ms_project",
"python",
"win32com"
] | stackoverflow_0074332138_ms_project_python_win32com.txt |
Q:
How to get credentials for getting user email after OAUTH with Google API Python Client
I'm trying to get user's email after OAUTH.
I have already found this code:
def get_user_info(credentials):
"""Send a request to the UserInfo API to retrieve the user's information.
Args:
credentials: oauth2client.clie... | How to get credentials for getting user email after OAUTH with Google API Python Client | I'm trying to get user's email after OAUTH.
I have already found this code:
def get_user_info(credentials):
"""Send a request to the UserInfo API to retrieve the user's information.
Args:
credentials: oauth2client.client.OAuth2Credentials instance to authorize the
request.
Returns:
User ... | [
"Credentials in this case will come from a combination of the info you got from the Google Dev portal and the http redirect to Google for the user to give your app permission the required permissions.\nBuild the credentials object separately and then pass it through to \"build()\" as the arguement for credentials.\... | [
0
] | [] | [] | [
"google_api",
"python"
] | stackoverflow_0074335701_google_api_python.txt |
Q:
How to set col and rows in add_subplot?
I am trying to generate 16 subgraphs, My end goal is to have an 8 x 2 size for the final graph, My code looks like this:
def visualize_t2t(token_dict, scores):
fig = plt.figure(figsize=(50, 50))
for idx, scores in enumerate(scores):
scores_np = np.array(scores)
... | How to set col and rows in add_subplot? | I am trying to generate 16 subgraphs, My end goal is to have an 8 x 2 size for the final graph, My code looks like this:
def visualize_t2t(token_dict, scores):
fig = plt.figure(figsize=(50, 50))
for idx, scores in enumerate(scores):
scores_np = np.array(scores)
ax = fig.add_subplot(12, 12, idx+1)
... | [
"Just replace ax = fig.add_subplot(12, 12, idx+1) with ax = fig.add_subplot(2, 8, idx+1).\n"
] | [
1
] | [] | [] | [
"matplotlib",
"plot",
"python",
"python_3.x"
] | stackoverflow_0074336861_matplotlib_plot_python_python_3.x.txt |
Q:
Replace text in PDF with Python
I am trying to replace text strings in a PDF file using the Python code below.
import PyPDF2
reader = PyPDF2.PdfFileReader('document.pdf', strict=True, warndest=None, overwriteWarnings=True)
writer = PyPDF2.PdfFileWriter()
replacements = {'old' : 'new'}
P = reader.getNumPages()
for... | Replace text in PDF with Python | I am trying to replace text strings in a PDF file using the Python code below.
import PyPDF2
reader = PyPDF2.PdfFileReader('document.pdf', strict=True, warndest=None, overwriteWarnings=True)
writer = PyPDF2.PdfFileWriter()
replacements = {'old' : 'new'}
P = reader.getNumPages()
for p in range(P):
page = reader.get... | [
"As explained here, this isn't a good idea.\nYou might consider building an HTML of the page you want, then use wkhtmltopdf to convert it into PDF\n"
] | [
0
] | [] | [] | [
"pdf",
"pypdf2",
"python",
"replace",
"string"
] | stackoverflow_0065597812_pdf_pypdf2_python_replace_string.txt |
Q:
matplotlib: combine different figures and put them in a single subplot sharing a common legend
We have a code that creates figures from input.txt files. We need to combine 2 of these figures in a single subplot. The data from figure1 will be plotted in the left subplot and from figure2 in the right subplot, sharin... | matplotlib: combine different figures and put them in a single subplot sharing a common legend | We have a code that creates figures from input.txt files. We need to combine 2 of these figures in a single subplot. The data from figure1 will be plotted in the left subplot and from figure2 in the right subplot, sharing the same legend and witht he same scale in axes x and y:
Here there is some example data:
x = [ ... | [
"Does this solve your problem?\nx = [ 1, 2, 3, 5, 10, 100, 1000 ]\ny1 = [ 1, 0.822, 0.763, 0.715, 0.680, 0.648, 0.645 ]\ny2 = [ 1, 0.859, 0.812, 0.774, 0.746, 0.721, 0.718 ]\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.transforms import BlendedGenericTransform\n# mode 01 from one case\nfig1 = plt.figure()\n... | [
15,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0016748577_matplotlib_python.txt |
Q:
VSCode: Intellisense has stopped suggesting imports in Python from my own code
Within a Python file in vscode, I have imported a constant called MONSTER_1_SET. The import source also has other constant variables named MONSTER_2_SET, all the way up to MONSTER_8_SET.
Before, once I would start typing the name of one... | VSCode: Intellisense has stopped suggesting imports in Python from my own code | Within a Python file in vscode, I have imported a constant called MONSTER_1_SET. The import source also has other constant variables named MONSTER_2_SET, all the way up to MONSTER_8_SET.
Before, once I would start typing the name of one of these constants anywhere within my .py file, VSCode would suggest the names of a... | [
"I figured it out, this Pylance setting somehow became disabled and I needed to re-enable it.\n"
] | [
1
] | [] | [] | [
"intellisense",
"python",
"visual_studio_code"
] | stackoverflow_0074337369_intellisense_python_visual_studio_code.txt |
Q:
Match ip address using regex
I'm trying to match a simplified version of IP addresses (I believe this pattern should match all IP addresses and then some things that aren't IP addresses, but that's not really important.) I'm using this syntax in Python:
'([0-9]{1,3}\.){3}[0-9]{1,3}'
This, however, matches "127.",... | Match ip address using regex | I'm trying to match a simplified version of IP addresses (I believe this pattern should match all IP addresses and then some things that aren't IP addresses, but that's not really important.) I'm using this syntax in Python:
'([0-9]{1,3}\.){3}[0-9]{1,3}'
This, however, matches "127.", for example. As far as I can tell... | [
"Quick answer, use this instead:\n(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\n\nLong answer:\nUsing 127.0.0.1 as an example, the regex you posted will only match \"0.\" rather than the full address. The parentheses you're using creates a matching group, which tells the parser to ensure that the entire pattern is found, but onl... | [
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006043714_python_regex.txt |
Q:
How to skip some iterations inside bs4 tags?
I am trying to scrap data (thumbnail image link) from this site.
The problem is, when it's getting the data it takes three tags, but the onle first tag has that thumbnail link, other two are not important. So, I need to skip those two tags and move to the fourth tag. ... | How to skip some iterations inside bs4 tags? | I am trying to scrap data (thumbnail image link) from this site.
The problem is, when it's getting the data it takes three tags, but the onle first tag has that thumbnail link, other two are not important. So, I need to skip those two tags and move to the fourth tag. For example,
0 <li> #contains the thumbnail link
1... | [
"Use enumerate and skip every 2 items and only continue (not to be confused with continue) with code for every 3rd item.\nfor index, item in enumerate(items):\n if index % 3 != 0:\n continue\n \n ...\n\nIf the issue is that .find returns None at some point you can use a try/except:\nfor item in item... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x",
"web_scraping"
] | stackoverflow_0074337703_beautifulsoup_python_python_3.x_web_scraping.txt |
Q:
How To Jira Resolution IDs from with Python Jira Library?
Right now I'm trying to get all the resoultion ids for a given project. I'm using the jira python library found here: https://jira.readthedocs.io/ and a longer version of the documentation here: https://buildmedia.readthedocs.org/media/pdf/jira/latest/jira.... | How To Jira Resolution IDs from with Python Jira Library? | Right now I'm trying to get all the resoultion ids for a given project. I'm using the jira python library found here: https://jira.readthedocs.io/ and a longer version of the documentation here: https://buildmedia.readthedocs.org/media/pdf/jira/latest/jira.pdf
The code is as follows:
option: {
'server': url
}
jira... | [
"Hey @outsideyam are you using Jira Cloud?\nIf so the following will give you what you want:\nimport requests\nfrom requests.auth import HTTPBasicAuth\nimport json\n\nurl = \"https://your-domain.atlassian.net/rest/api/3/resolution\"\n\nauth = HTTPBasicAuth(\"email@example.com\", \"<api_token>\")\n\nheaders = {\n ... | [
0
] | [] | [] | [
"jira",
"python"
] | stackoverflow_0074295112_jira_python.txt |
Q:
How to add multihreading to a continuous Python function?
I have an infinite loop Python function for measuring how fast are SECP256K1 public Keys are generated.
The script:
from time import time
a = 0
b = 7
n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
gx = 0x79be667ef9dcbbac55a06295ce87... | How to add multihreading to a continuous Python function? | I have an infinite loop Python function for measuring how fast are SECP256K1 public Keys are generated.
The script:
from time import time
a = 0
b = 7
n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
gy = 0x483ada7726a3c4655da... | [
"You can use the package gmpy2 for that and it is 10 times faster (on my machine) by just changing the beginning of the code to:\nimport gmpy2\n\na = gmpy2.mpz(0)\nb = gmpy2.mpz(7)\nn = gmpy2.mpz(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141)\ngx = gmpy2.mpz(0x79be667ef9dcbbac55a06295ce870b0702... | [
1,
0
] | [] | [] | [
"cpu_usage",
"cryptography",
"multithreading",
"optimization",
"python"
] | stackoverflow_0074334381_cpu_usage_cryptography_multithreading_optimization_python.txt |
Q:
Nightmare of installing and running Tensorflow in R Studio on windows 10
Please, I have been having trouble for weeks now trying to install and run tensorflow and keras in R Studio. I have tried everything I can find online to no avail. I have anaconda installed on my system, do I need to uninstall it? After runni... | Nightmare of installing and running Tensorflow in R Studio on windows 10 | Please, I have been having trouble for weeks now trying to install and run tensorflow and keras in R Studio. I have tried everything I can find online to no avail. I have anaconda installed on my system, do I need to uninstall it? After running this line of code:
install_tensorflow(method = "conda",version = "default",... | [
"there have been significant changes to the installation pathway in the R package recently. Can you please try the following (in a fresh R session):\ninstall.packages(\"keras\")\nreticulate::install_miniconda()\nkeras::install_keras()\n\nIf the above doesn't work, can you please file an issue: https://github.com/rs... | [
2,
0
] | [] | [] | [
"python",
"r",
"tensorflow",
"windows"
] | stackoverflow_0068069190_python_r_tensorflow_windows.txt |
Q:
How to loop over a RDD by index in Pyspark and replace column values?
I am trying to accompany the following I have done with a regular df in pandas with a RDD or Spark DF in pyspark.
I was trying to solve it with the foreach() function, but I have failed at all attempts. Has somebody got a neat solution for it?
f... | How to loop over a RDD by index in Pyspark and replace column values? | I am trying to accompany the following I have done with a regular df in pandas with a RDD or Spark DF in pyspark.
I was trying to solve it with the foreach() function, but I have failed at all attempts. Has somebody got a neat solution for it?
for i in range(len(all_songs)):
if all_songs['loudness'][i] >0:
... | [
"I am not sure if pure DataFrame API solution is valid for your case, but I would achieve what you have described with the following code:\nfrom pyspark.sql.functions import when, col\n\n# Assume that `df` is your DataFrame\nreplaced_df = df.withColumn(\"loudness\", when(col(\"loudness\") > 0, col(\"loudness\") * ... | [
1
] | [] | [] | [
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0074337044_apache_spark_pyspark_python.txt |
Q:
cannot add % sign to show on the pie
enter image description hereIm plotting Pie with values shown as % but values appear without "%" sign, I,m trying to add it("%") as string but says format is incomplete, when i remove it, it prints values without sign
I m using:
df['Sold Contract'].value_counts().plot(kind='pie... | cannot add % sign to show on the pie | enter image description hereIm plotting Pie with values shown as % but values appear without "%" sign, I,m trying to add it("%") as string but says format is incomplete, when i remove it, it prints values without sign
I m using:
df['Sold Contract'].value_counts().plot(kind='pie', figsize=(5,5), legend= True, autopct ="... | [
"Actually, that is a very good question.\nThe main reason is that normally when you want to use a special character inside a string as a character(\", ', ) you use the backslash(/) before that character(\", ', \\).\nIn the case of the % sign, you use two signs(so %%) inside your string to print one percent sign\nSo... | [
1
] | [] | [] | [
"pandas",
"pie_chart",
"plot",
"python"
] | stackoverflow_0074337752_pandas_pie_chart_plot_python.txt |
Q:
How to include external Spark library while using PySpark in Jupyter notebook
I am trying to run the following PySpark-Kafka streaming example in a Jupyter Notebook. Here is the first part of the code I am using in my notebook:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from py... | How to include external Spark library while using PySpark in Jupyter notebook | I am trying to run the following PySpark-Kafka streaming example in a Jupyter Notebook. Here is the first part of the code I am using in my notebook:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
sc = pyspark.SparkContext(master='local[*]... | [
"There are at least two ways of doing so, corresponding roughly to the two options suggested in the error message:\nThe first way is to update accordingly your respective Jupyter kernel (if you are not already using Jupyter kernels, you should - see this answer for the detailed generalities of using kernels in Jupy... | [
2,
0
] | [] | [] | [
"apache_spark",
"jupyter",
"jupyter_notebook",
"pyspark",
"python"
] | stackoverflow_0051105475_apache_spark_jupyter_jupyter_notebook_pyspark_python.txt |
Q:
Replace df data with other df data
I'm generating some counts with this code:
df1 = (df.loc[df['Are you okay?']== 'No', 'Are yu sad?']
.value_counts()
.rename_axis('Vals')
.reset_index(name='Count'))
So I'm obtaining the Yes and No Counts, but this is for 3 diferent columns and the only count that ... | Replace df data with other df data | I'm generating some counts with this code:
df1 = (df.loc[df['Are you okay?']== 'No', 'Are yu sad?']
.value_counts()
.rename_axis('Vals')
.reset_index(name='Count'))
So I'm obtaining the Yes and No Counts, but this is for 3 diferent columns and the only count that I need is Yes this is what I got:
Va... | [
"df_all_rows = pd.concat([df1, df2, df3], ignore_index=True)\n\n"
] | [
0
] | [] | [] | [
"google_colaboratory",
"pandas",
"python",
"replace",
"row"
] | stackoverflow_0074322228_google_colaboratory_pandas_python_replace_row.txt |
Q:
Hospital management system binary file giving error
I am making a hospital management system in which there is a specific function readpatientrec in which it takes in a number and checks if the number matches the patient number and displays the record corresponding to the patient number.
I wrote an if condition fo... | Hospital management system binary file giving error | I am making a hospital management system in which there is a specific function readpatientrec in which it takes in a number and checks if the number matches the patient number and displays the record corresponding to the patient number.
I wrote an if condition for it and the patient number and inputted number matches b... | [] | [] | [
"as Klaus D. said, you could try the following code, to catch the exception and find the solution\ndef searchpatientrec(p_no):\nf = open(\"patient.dat\", \"rb\")\nflag = False\ntry:\n rec = pickle.load(f)\n print(rec[0])\n print(p_no)\n if rec[0] == p_no:\n p_no = rec[0]\n p_name = rec[1]\... | [
-1
] | [
"binary",
"if_statement",
"list",
"python",
"python_3.x"
] | stackoverflow_0074337795_binary_if_statement_list_python_python_3.x.txt |
Q:
Python Multiprocessing, Pytest, and Windows: How to perform pytest live-logging when using multiprocessing in a cross-platform setting?
I created a Github repo with all the code necessary to test the issue. For the sake of consistency and ease of search, I pasted most of the repo's README.md below.
NOTE: This que... | Python Multiprocessing, Pytest, and Windows: How to perform pytest live-logging when using multiprocessing in a cross-platform setting? | I created a Github repo with all the code necessary to test the issue. For the sake of consistency and ease of search, I pasted most of the repo's README.md below.
NOTE: This question requires Linux or a system that can (preferably a combination of Windows+Linux) support "spawn" and "fork" multiprocessing contexts.
S... | [
"After experimenting, I determined that indeed pytestwas the culprit responsible for not showing the child processes' logs in sys.stdout. With this, I found a GitHub issue from PyTest and used a proposed solution to achieve my requirements.\nI extended the solution and added more tests to verify that the solution w... | [
0
] | [] | [] | [
"linux",
"multiprocessing",
"pytest",
"python",
"windows"
] | stackoverflow_0074258805_linux_multiprocessing_pytest_python_windows.txt |
Q:
How to validate fields with foreign keys in serializers context?
I'm working on some validations, and I want to check whether the requesterid entered is referencing to a userroleid value of "3" from userTable model. If it doesn't meet the criteria, it will raise a validation error. How can I access a field from a ... | How to validate fields with foreign keys in serializers context? | I'm working on some validations, and I want to check whether the requesterid entered is referencing to a userroleid value of "3" from userTable model. If it doesn't meet the criteria, it will raise a validation error. How can I access a field from a referenced table?
What I have tried is something like request = self.c... | [
"Solved it using this code:\ndef validate(self, data):\n if data['requesterid'].userroleid_id != 3:\n raise serializers.ValidationError(\"Sorry! You entered a user with no requester permissions.\")\n return data\n\n"
] | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"django_views",
"python"
] | stackoverflow_0074337087_django_django_rest_framework_django_serializer_django_views_python.txt |
Q:
How to do recursive vectorized calculations in pandas DataFrame via columns?
Edit: I have altered the sample data so that the 5th row is now gone due to an error in the sample.
Assume that we a directed graph G = (V, E) of edges E and vertices V. Assume that we have a Pandas DataFrame describing which nodes (u, v)... | How to do recursive vectorized calculations in pandas DataFrame via columns? | Edit: I have altered the sample data so that the 5th row is now gone due to an error in the sample.
Assume that we a directed graph G = (V, E) of edges E and vertices V. Assume that we have a Pandas DataFrame describing which nodes (u, v)are connected to each other and the value/weight of the corresponding edge e. Let ... | [
"There is some issue with your dataset. I re-create another example here:\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'from':[0,2,3,1,0],\n 'to':[1,2,4,4,2],\n 'val':[10,20,30,40,50]})\n\nHere if you do not have to groupby, then it is easier to exact series out... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"recursion",
"vectorization"
] | stackoverflow_0074337363_dataframe_pandas_python_recursion_vectorization.txt |
Q:
Avoid emptying dictionary recursively
I am trying to create a dictionary from a list recursively and my code only works when there is only one item in the list. It fails for multiple items and I suspect that this is because the dictionary is being recreated through each instance of the recursion instead of adding ... | Avoid emptying dictionary recursively | I am trying to create a dictionary from a list recursively and my code only works when there is only one item in the list. It fails for multiple items and I suspect that this is because the dictionary is being recreated through each instance of the recursion instead of adding to it after the first instance. How can I a... | [
"You have the edge condition, so you need to define what to do when you have more than one. Here you just take the first tuple, make a dict, and then add the results of recursion into that dict:\nrestaurantChoice = [(\"Paige\", \"Dancing Goats\"), (\"Fareeda\", \"Botiwala\"),\n (\"Ramya\", \"Mine... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"recursion"
] | stackoverflow_0074337686_dictionary_list_python_recursion.txt |
Q:
Issues with installing python libraries on Windows : CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/win-64
I'd like to install the pymongo library but I'm getting the following error:
(C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
conda insta... | Issues with installing python libraries on Windows : CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/anaconda/win-64 | I'd like to install the pymongo library but I'm getting the following error:
(C:\Users\xxxxxxx\AppData\Local\Continuum\anaconda3) C:\Users\xxxxxxx>
conda install -c anaconda pymongo
Fetching package metadata ...
CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/a
nacond... | [
"This works a charm:-\nJust copy these:-\n\nlibcrypto-1_1-x64.dll\n\nlibssl-1_1-x64.dll\n\n\nfrom D:\\Anaconda3\\Library\\bin to D:\\Anaconda3\\DLLs.\n",
"Execute the following command in the cmd prompt/terminal:\nconda config --set ssl_verify no \n",
"I try to create a virtual env with python 2.7 with anaconda... | [
165,
84,
34,
18,
9,
8,
4,
3,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"anaconda",
"conda",
"https",
"python",
"ssl"
] | stackoverflow_0050125472_anaconda_conda_https_python_ssl.txt |
Q:
Using python how to display dns
Using Python, is there a way using psutil or something else to return the output of "ipconfig /displaydns" or something similar?
Spawning a cmd process and running the command is not an option.
A:
To execute a command, you can use the os library. Executing the command you've shown... | Using python how to display dns | Using Python, is there a way using psutil or something else to return the output of "ipconfig /displaydns" or something similar?
Spawning a cmd process and running the command is not an option.
| [
"To execute a command, you can use the os library. Executing the command you've shown above is as simple as:\nimport os\nos.system('ipconfig /displaydns')\n\nIf you want to store the output of a command in a variable, you can use:\nx = os.popen('ipconfig /displaydns')\n\n",
"You can try using dnspython's resolver... | [
0,
0,
0
] | [] | [] | [
"psutil",
"python",
"python_2.7"
] | stackoverflow_0049058273_psutil_python_python_2.7.txt |
Q:
How to pair values from a list
I am trying to pair the first and last values together from a list, the second and the 2nd last number and so on. I can do it manually:
list = [ slist[0], slist[-1] ]
list1 = [ slist[1], slist[-2] ]
but the problem for me here is that I am taking an input for the number of students ... | How to pair values from a list | I am trying to pair the first and last values together from a list, the second and the 2nd last number and so on. I can do it manually:
list = [ slist[0], slist[-1] ]
list1 = [ slist[1], slist[-2] ]
but the problem for me here is that I am taking an input for the number of students and I dont know how many values the ... | [
"I'm not sure if your question has any bearing on the problem you're trying to solve -- but to pair the first and last element, second and second last, etc, you can slice the list in two and zip the first half with the reversed second half:\n>>> slist = list(range(10))\n>>> slist\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>... | [
1,
1
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0074337246_list_python_sorting.txt |
Q:
How do I use pydantic to standardise import of different formats of the same information?
I have data from a web API request that can return one of two different dictionaries:
Wh version: [{'energy_wh': int, 'month': int, 'year': int}]
kWh version: [{'energy': float, 'month': int, 'year': int}]
I only know which... | How do I use pydantic to standardise import of different formats of the same information? | I have data from a web API request that can return one of two different dictionaries:
Wh version: [{'energy_wh': int, 'month': int, 'year': int}]
kWh version: [{'energy': float, 'month': int, 'year': int}]
I only know which format by checking for the presence of the corresponding key.
I'd like to create class with th... | [
"Pydantic has the concept of validation for things like that. You can use a root_validator to write out the logic that ensures correct conversion before the values are passed to the individual field validators by using the pre=True setting.\nIf you want this validation to also occur every time values are assigned t... | [
1
] | [] | [] | [
"pydantic",
"python",
"python_3.x"
] | stackoverflow_0074337602_pydantic_python_python_3.x.txt |
Q:
How to use ceasar cipher with dictionaries?
How would I cipher the following dictionary?:
('', '', 'newpwd', 'gdfhjhgdfhgdf', '11A7AC66816E87CF0AE7AE1891DA159095A1049A96B3A8546C8A51B381F568D8705811BBDD2B89385ACE8DF1B12C2B8CA17524E4C7F79354D8C4025316FCD13C0CDD87C455B99B0AB647DD5A134BF675AE0EA08D3D997518FF065510FC49... | How to use ceasar cipher with dictionaries? | How would I cipher the following dictionary?:
('', '', 'newpwd', 'gdfhjhgdfhgdf', '11A7AC66816E87CF0AE7AE1891DA159095A1049A96B3A8546C8A51B381F568D8705811BBDD2B89385ACE8DF1B12C2B8CA17524E4C7F79354D8C4025316FCD13C0CDD87C455B99B0AB647DD5A134BF675AE0EA08D3D997518FF065510FC497F780B43D05F', 'e=10001;m=d0fa1d37fa0bb621a8cbb66... | [
"Your function encrypt() by its parameters seems to want to accept a text string as the first parameter and not a collection of strings.\nThe loop inside the function seems to be accessing individual characters of the string parameter given the name char and the use of ord(char).\nThe reason for the error is that i... | [
0
] | [] | [] | [
"cryptography",
"encryption",
"python"
] | stackoverflow_0074337620_cryptography_encryption_python.txt |
Q:
Filter Django query by week of month?
In a Django query, how would you filter by a timestamp's week within a month?
There's a built-in week accessor, but that refers to week-of-the-year, e.g. 1-52. As far as I can tell, there's no other built-in option.
The only way I see to do this is to calculate the start and ... | Filter Django query by week of month? | In a Django query, how would you filter by a timestamp's week within a month?
There's a built-in week accessor, but that refers to week-of-the-year, e.g. 1-52. As far as I can tell, there's no other built-in option.
The only way I see to do this is to calculate the start and end date range for the week, and then filte... | [
"The easiest way to do this using datetime objects is to quite simply subtract the current date weekly year value, with the yearly week value for the 1st day (or 1st week) of the month.\nYou can use the .isocalendar() function to achieve this:\ndt.isocalendar[1] - dt.replace(day=1).isocalendar()[1] + 1\n\nBasically... | [
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0074337575_django_django_queryset_python.txt |
Q:
convert days to weeks in python
On the first line, ask the user how many days they've been driving for and declare the user input. It's an integer, so cast the string.
Then calculate the number of years in that set of days.
Next, convert the remaining days that weren't converted to years into weeks.
Then, get any ... | convert days to weeks in python | On the first line, ask the user how many days they've been driving for and declare the user input. It's an integer, so cast the string.
Then calculate the number of years in that set of days.
Next, convert the remaining days that weren't converted to years into weeks.
Then, get any remaining days that weren't converted... | [
"Your calculation is wrong.\ndays = int(input(\"Days you have been driving: \"))\nyears=days//365\nweeks=days//7\nconsDays=days%7\nprint(\"You have been driving for:\")\nprint(\"Years:\" , years)\nprint(\"Weeks:\" , weeks)\nprint(\"Days:\" , consDays)\n\n\nOUTPUT (for input 1000)\nYou have been driving for:\nYears:... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074338007_python.txt |
Q:
csv package parses each char as a row
According to this answer it seems I can parse each row of a CSV file with csv.reader(data, delimiter=",", quotechar='"'), so I made the following MWE (Minimal Working Example):
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
data = """\
1,"A towel,",1.0
42," it say... | csv package parses each char as a row | According to this answer it seems I can parse each row of a CSV file with csv.reader(data, delimiter=",", quotechar='"'), so I made the following MWE (Minimal Working Example):
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
data = """\
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massi... | [
"From csv:\n\ncsv.reader(csvfile, dialect='excel', **fmtparams)\nReturn a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.\n\n... | [
2
] | [] | [] | [
"csv",
"parsing",
"python",
"tabulate"
] | stackoverflow_0074337838_csv_parsing_python_tabulate.txt |
Q:
Union sets that are linked with a common value
Input:
list_sets = [{1,2,3}, {4,1,7}, {5,8,9}, {4,10,11}]
expected_output = [{'id1': [1,2,3]}, {'id1': [4,1,7]}, {'id2': [5,8,9]}, {'id1': [4,10,11]}]
What I want to achieve is to assign the same id to every set in the list that has common value with the other sets. ... | Union sets that are linked with a common value | Input:
list_sets = [{1,2,3}, {4,1,7}, {5,8,9}, {4,10,11}]
expected_output = [{'id1': [1,2,3]}, {'id1': [4,1,7]}, {'id2': [5,8,9]}, {'id1': [4,10,11]}]
What I want to achieve is to assign the same id to every set in the list that has common value with the other sets. For example 1 is a common value in the first and sec... | [
"Here is a simple fixed-point algorithm for producing your output.\n# I added some more data for testing\nlist_sets = [{1,2,3}, {4,1,7}, {5,8,9}, {4,10,11}, {12, 13, 14}, {0, 44, 64}, {102, 99, 98}, {101, 23, 102}, {64, 23, 101}]\n\n# 1. find all sets that intersect\n\n# Modifying sets later on, hence copy\n# Proba... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074337438_python.txt |
Q:
pd.round returns weird values
a subset of my data looks as follows:
print(test)
created_at
29100988 2020-06-01 00:03:49+00:00
29100989 2020-06-01 00:03:42+00:00
29100990 2020-06-01 00:03:41+00:00
29100991 2020-06-01 00:03:37+00:00
29100992 2020-06-01 00:03:36+00:00
29100993 2020-06-0... | pd.round returns weird values | a subset of my data looks as follows:
print(test)
created_at
29100988 2020-06-01 00:03:49+00:00
29100989 2020-06-01 00:03:42+00:00
29100990 2020-06-01 00:03:41+00:00
29100991 2020-06-01 00:03:37+00:00
29100992 2020-06-01 00:03:36+00:00
29100993 2020-06-01 00:03:36+00:00
29100994 2020-06-... | [
"I found the solution, using test['created_at_Min'] = pd.to_datetime(test['created_at']).dt.floor(\"min\") instead works as desired.\n"
] | [
1
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074338039_datetime_pandas_python.txt |
Q:
multiply column based values with column based on condition, python
I need to write a function that allows me to convert timeseries data (wind speed as the argument) to power output for a turbine. The output is based on several intervals.
So i have tried to create an additional dataframe to store the conversion co... | multiply column based values with column based on condition, python | I need to write a function that allows me to convert timeseries data (wind speed as the argument) to power output for a turbine. The output is based on several intervals.
So i have tried to create an additional dataframe to store the conversion coefficients.
The Problem is, that I get always the error 'float' object is... | [
"You are using .apply method in the power_production_Vestas column, which means that the function will be applied to each element of that column. That's why you are getting the \"float is not subscriptable\" error, that x argument of conv_test is a float.\nTry using the same method but on the dataframe, than x will... | [
0,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074337909_dataframe_numpy_pandas_python.txt |
Q:
How do I select rows within a dataframe which start with the same phrase, without having to individually select the rows, within python?
How do I create a column in my dataframe called 'Declined Or Hired', where a '1' is input into each row where the (Declined - Reason) Or Hire column starts with "Offer Declined -... | How do I select rows within a dataframe which start with the same phrase, without having to individually select the rows, within python? |
How do I create a column in my dataframe called 'Declined Or Hired', where a '1' is input into each row where the (Declined - Reason) Or Hire column starts with "Offer Declined -...). My code below works, however I think I've written a long solution, which could be shorter.
df.loc[(df['(Declined - Reason) Or Hire'] ==... | [
"Use str.startswith and convert the booleans to integers with astype:\ndf['Declined or Hired'] = (df['(Declined - Reason) Or Hire']\n .str.startswith('Offer Declined', na=False)\n .astype(int)\n )\n\nIf you want to match anywhere (not only o... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074338177_dataframe_pandas_python.txt |
Q:
how to convert tensorflow tensor to numpy array from given example?
I am trying to compute Fast Fourier Transform (fft2d) but the following code provides the error:
print("type(pred[2]): ", type(pred[2]))
pred[2] = tf.make_ndarray(pred[2])
fft2_pre = np.fft.fft2(pred[2])
The error and output:
type(pred[2]): <cla... | how to convert tensorflow tensor to numpy array from given example? | I am trying to compute Fast Fourier Transform (fft2d) but the following code provides the error:
print("type(pred[2]): ", type(pred[2]))
pred[2] = tf.make_ndarray(pred[2])
fft2_pre = np.fft.fft2(pred[2])
The error and output:
type(pred[2]): <class 'tensorflow.python.framework.ops.Tensor'>
AttributeError: 'Tensor' obj... | [
"temp = tf.cast(pred[2], dtype=tf.complex64)\ntemp = tf.signal.fft(temp)\n\n"
] | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074337905_python_tensorflow.txt |
Q:
How do parenthesis affect filters in Pandas?
I am learning Pandas and while playing around with some filters something came up.
I was using this filter on the classical stackoverflow survay to get only the rows where the applicants had an even Respondent ID AND they were coding as a hobby:
filt = df["Hobbyist"] ==... | How do parenthesis affect filters in Pandas? | I am learning Pandas and while playing around with some filters something came up.
I was using this filter on the classical stackoverflow survay to get only the rows where the applicants had an even Respondent ID AND they were coding as a hobby:
filt = df["Hobbyist"] == "Yes" & df["Respondent"] % 2 == 0
But then the "... | [
"This is due to operator precedence.\n& has higher precedence than ==, thus your initial code is equivalent to:\nfilt = df[\"Hobbyist\"] == (\"Yes\" & (df[\"Respondent\"] % 2)) == 0\n\nYou should use:\nfilt = (df[\"Hobbyist\"] == \"Yes\") & (df[\"Respondent\"] % 2 == 0)\n\nOr, to avoid parentheses:\nfilt = df[\"Hob... | [
1
] | [] | [] | [
"filtering",
"pandas",
"python"
] | stackoverflow_0074338198_filtering_pandas_python.txt |
Q:
Can I update text in tkinter graphics?
I am working on a pong game, but I have some problems with my score counter. I want it to bounce around the screen and bump into the ball. however, because I have it draw only once in the init function, when the score changes, the counter does not change. I am trying to find ... | Can I update text in tkinter graphics? | I am working on a pong game, but I have some problems with my score counter. I want it to bounce around the screen and bump into the ball. however, because I have it draw only once in the init function, when the score changes, the counter does not change. I am trying to find a way to update the score counter without ch... | [
"In Ball class. I removed\n\nhit_paddle function, so you don't need it.\n\nIn Text class in draw function:\n\nI removed in line 116 score = score + 1\n\nAdded at the end of draw function.\nself.canvas.itemconfig(self.id,\ntext=f'Score: {str(score)}')\n\n\nHere is code:\nfrom tkinter import *\nimport random\nimport... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074310831_python_tkinter.txt |
Q:
TypeError while webscraping using find function in BeautifulSoup
I'm trying to scrape a website from timesjob.com but it returns some type of error can you identify the cause? I still can't understand what causes this type of error
from bs4 import BeautifulSoup
import requests
html_text = requests.get("https://ww... | TypeError while webscraping using find function in BeautifulSoup | I'm trying to scrape a website from timesjob.com but it returns some type of error can you identify the cause? I still can't understand what causes this type of error
from bs4 import BeautifulSoup
import requests
html_text = requests.get("https://www.timesjobs.com/candidate/job-search.html?searchType=personalizedSearc... | [
"The line job = job.text is causing issues for the next line, because now job is just a string rather than a bs4 tag, so .find is a different function entirely.\nChange that line to something like jobTxt = job.text (so that you can still use job) and then print(jobTxt) if that's what you're trying to print at the e... | [
0
] | [] | [] | [
"beautifulsoup",
"data_mining",
"python",
"typeerror",
"web_scraping"
] | stackoverflow_0074337709_beautifulsoup_data_mining_python_typeerror_web_scraping.txt |
Q:
python selenium: clicking buttons with various html element/css attributes
i'm trying to create python automation scripts using selenium to make appointment times, however i'm having some trouble with clicking on certain elements. to confirm an appointment the steps are going to the webpage > selecting the date > ... | python selenium: clicking buttons with various html element/css attributes | i'm trying to create python automation scripts using selenium to make appointment times, however i'm having some trouble with clicking on certain elements. to confirm an appointment the steps are going to the webpage > selecting the date > selecting the time > hitting confirm
this is what i've got so far:
driver = webd... | [
"Selenium doesn't have option to identify the element by DATA-TEST-ID locator.\nIn this case You have to use either by xpath or css selector\ndriver.find_element(By.XPATH,'//button[@data-test-id=\"order_summary_page-button-book\"]').click() \n\nOR\ndriver.find_element(By.CSS_SELECTOR,'button[data-test-id=\"order_su... | [
0
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"webdriver",
"xpath"
] | stackoverflow_0074337879_css_selectors_python_selenium_webdriver_xpath.txt |
Q:
Use a Poetry built module inside of another Poetry built module
I have a custom general module module_a built with poetry and published to a Gitlab private package registry.
I wish to use this module in another more specific module module_b, but I cannot manage to add this dependency with the poetry add <package n... | Use a Poetry built module inside of another Poetry built module | I have a custom general module module_a built with poetry and published to a Gitlab private package registry.
I wish to use this module in another more specific module module_b, but I cannot manage to add this dependency with the poetry add <package name> command.
For now I am only able to install module_a dependency i... | [
"Poetry's dependencies are supposed to be public dependencies. If your module_b is going to be public, publish it to pypi and add it as you normally would. If it isn't, make module_a a git submodule of module_b in the right place, and access module_b that way.\nAlternatively, set up a private repository, and add ... | [
0,
0
] | [] | [] | [
"python",
"python_poetry"
] | stackoverflow_0069495701_python_python_poetry.txt |
Q:
Get text with Xpath
I want to collect GitHub users' monthly contributions from 2004 until now as shown in the picture. And output the monthly data into csv file with corresponding month columns (e.g., 2022_10). The Xpath of these texts is:
#//*[@id="js-contribution-activity"]/div/div/div/div/details/summary/span... | Get text with Xpath | I want to collect GitHub users' monthly contributions from 2004 until now as shown in the picture. And output the monthly data into csv file with corresponding month columns (e.g., 2022_10). The Xpath of these texts is:
#//*[@id="js-contribution-activity"]/div/div/div/div/details/summary/span[1]
This is what my csv ... | [
"You need to use WebDriverWait expected_conditions explicit waits.\nI see there are multiple contribution fields there, so you need to collect all those elements as a list and then to iterate over the list extracting each element text.\nYou need to improve your locators, they should be short and clear as possible.\... | [
1,
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"webdriverwait",
"xpath"
] | stackoverflow_0074337013_python_selenium_selenium_webdriver_webdriverwait_xpath.txt |
Q:
Missing some statements in my code that is keeping me from completing this code
I am trying to complete this.
A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it... | Missing some statements in my code that is keeping me from completing this code | I am trying to complete this.
A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6.
Write a Boolean function named is_prime whi... | [
"The range of numbers checked inside is_prime(number) cannot include the numbers (1, number), because any number is divisible by them. Additionally, you can only return True at the end of the for-loop if no divisors were found:\ndef is_prime(number): \n ...\n\n for x in range (2, number):\n if (number ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074338216_python.txt |
Q:
How to change the foreground or background colour of a Tkinter Button on Mac OS X?
I've been working through the Tkinter chapters in Programming Python and encountered a problem where the foreground and background colours of a button will not change. I am working on a Mac OS X 10.6 system with Python 2.6.1. The co... | How to change the foreground or background colour of a Tkinter Button on Mac OS X? | I've been working through the Tkinter chapters in Programming Python and encountered a problem where the foreground and background colours of a button will not change. I am working on a Mac OS X 10.6 system with Python 2.6.1. The colours of a label will change, but not the colours of a button. For example:
from Tkinter... | [
"There is a solution for changing the background of buttons on Mac. \nUse:\nhighlightbackground=color\n\nFor example:\nsubmit = Button(root, text=\"Generate\", highlightbackground='#3E4149')\n\nThis results in the following, a nice button that fits in with the background:\n\n",
"I think the answer is that the but... | [
61,
32,
24,
21,
8,
2,
1,
0,
0,
0
] | [] | [] | [
"button",
"macos",
"python",
"tkinter",
"tkinter_button"
] | stackoverflow_0001529847_button_macos_python_tkinter_tkinter_button.txt |
Q:
Measuring the goodness quality of VAE-generated tabular data
I have the following DataFrame in pandas python:
index
time
flag
date
number
0
2.7584
0
2.91844
3
1
1.1234
1
3.58941
4
2
5.8583
1
1.81801
5
...
...
...
...
...
305
1.0493
0
1.98321
1
I am using a Variational Autoencoder to generate new data from t... | Measuring the goodness quality of VAE-generated tabular data | I have the following DataFrame in pandas python:
index
time
flag
date
number
0
2.7584
0
2.91844
3
1
1.1234
1
3.58941
4
2
5.8583
1
1.81801
5
...
...
...
...
...
305
1.0493
0
1.98321
1
I am using a Variational Autoencoder to generate new data from the previous DataFrame. Example for 500 generated data... | [
"Assuming the two data frames have the same shape, and you want to compare them element-wise (ie, compare the rows in order), then the simplest approach is to use numpy.linalg.norm to compute the norm of each column after subtracting the two dataframes. The type of norm is specified with the ord parameter; the mos... | [
1
] | [] | [] | [
"data_generation",
"dataframe",
"python"
] | stackoverflow_0074289511_data_generation_dataframe_python.txt |
Q:
cron python script logging messages syslog
I use cron to control a python script
*/10 * * * * /usr/bin/python3 /home/user/FillDatabase.py
and its works well so fare.
The python script itself produce logging in case of error.
import logging
...
logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message... | cron python script logging messages syslog | I use cron to control a python script
*/10 * * * * /usr/bin/python3 /home/user/FillDatabase.py
and its works well so fare.
The python script itself produce logging in case of error.
import logging
...
logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s")
...
try:
...
except Exception as e:
... | [
"found:\nWirte to cron with\nsudo crontab -u root -e\n\ngive cron the permission to write into syslog\n*/10 * * * * /usr/bin/python3 /home/user/FillDatabase.py >> /var/log/syslog 2>&1\n\n"
] | [
0
] | [] | [] | [
"cron",
"python",
"syslog",
"unix"
] | stackoverflow_0074331477_cron_python_syslog_unix.txt |
Q:
pandas shift column for customer last purchase
I want to use pandas shift function to group by and then ungroup.
original table
customer_id | date | price
a | 4/11/2022 | 10
b | 5/11/2022 | 20
c | 5/11/2022 | 30
a | 6/11/2022 | 20
b | 6/11/2022 | 20
a | 7/11/2022 | 30
target
customer_id | date | price | last_... | pandas shift column for customer last purchase | I want to use pandas shift function to group by and then ungroup.
original table
customer_id | date | price
a | 4/11/2022 | 10
b | 5/11/2022 | 20
c | 5/11/2022 | 30
a | 6/11/2022 | 20
b | 6/11/2022 | 20
a | 7/11/2022 | 30
target
customer_id | date | price | last_purchase
a | 4/11/2022 | 10 | NaN
b | 5/11/2022 | 20... | [
"df['last_purchase'] = df.groupby('customer_id')['price'].shift(1)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074338318_pandas_python.txt |
Q:
ImportError: cannot import name 'Item' from partially initialized module 'core.models' (most likely due to a circular import)
This is the full traceback:
Traceback (most recent call last): File
"C:\Users\Abdul\OneDrive\Desktop\django-ecommerce-master\manage.py",
line 15, in <module> execute_from_command_line... | ImportError: cannot import name 'Item' from partially initialized module 'core.models' (most likely due to a circular import) | This is the full traceback:
Traceback (most recent call last): File
"C:\Users\Abdul\OneDrive\Desktop\django-ecommerce-master\manage.py",
line 15, in <module> execute_from_command_line(sys.argv) File
"C:\Users\Abdul\.virtualenvs\django-ecommerce-master-FJQqFcPP\lib\site-packages\django\core\management\__init__.... | [
"Ahh, the problem was in the core app where I used the import statement to import some classes(warehouse,zone,etc).\nRemoving it resolved it.\nStill have no idea why it happened.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074338167_django_python.txt |
Q:
How to get alternating colours in dashed line using matplotlib?
In matplotlib, I want to make a line using matplotlib.pyplot which is alternating black and yellow dashes, and then I want to include that line on the legend. How do I do that?
I could do something like:
from matplotlib import pyplot as plt, gridspec
... | How to get alternating colours in dashed line using matplotlib? | In matplotlib, I want to make a line using matplotlib.pyplot which is alternating black and yellow dashes, and then I want to include that line on the legend. How do I do that?
I could do something like:
from matplotlib import pyplot as plt, gridspec
import numpy as np
grid = gridspec.GridSpec(1,1)
ax = plt.subplot(gr... | [
"Try this.\nfrom matplotlib import pyplot as plt, gridspec, lines\n\nimport numpy as np\n\ngrid = gridspec.GridSpec(1,1)\nax = plt.subplot(grid[0,0])\n\nx = np.arange(1,11)\ny = x * 2\n\nax.plot(x, y, '-', color = 'black', linewidth = 5)\nax.plot(x, y, '--', color = 'lawngreen', linewidth = 5)\n\ndotted_line1 = lin... | [
17,
3,
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0031540258_matplotlib_plot_python.txt |
Q:
Slicing str into specifing chunks reversing said chunks and adding them up back together
I'm currently working on a challange where I need to divide strings by specifing number into chunks reverse them and than glue those reversed chunnks back together.
I came up with way to execute this, however I could't come up... | Slicing str into specifing chunks reversing said chunks and adding them up back together | I'm currently working on a challange where I need to divide strings by specifing number into chunks reverse them and than glue those reversed chunnks back together.
I came up with way to execute this, however I could't come up with way to automate this task.
def switch (n, txt):
a = (txt [0:n] [::-1]) #here I devid... | [
"You can loop using range(start,end,n) to jump n positions between two consecutive interations. In each iteration, you reverse a part of the string:\ndef switch(n, txt):\n result = []\n for i in range(0,len(txt),n):\n result.append(txt[i:i+n].lower()[::-1])\n return ''.join(result)\n\nYou can also w... | [
1,
0
] | [] | [] | [
"automation",
"python",
"reverse",
"slice"
] | stackoverflow_0074338208_automation_python_reverse_slice.txt |
Q:
SQLCODE=-1042ect: [IBM][CLI Driver] SQL1042C An unexpected system error occurred. SQLSTATE=58004
I am trying to connect to the Db2 database on Cloud using Python.
dsn_hostname = ".."
dsn_uid = ".."
dsn_pwd = ".."
dsn_driver = "{IBM DB2 ODBC DRIVER}"
dsn_database = ".."
dsn_port = ".." ... | SQLCODE=-1042ect: [IBM][CLI Driver] SQL1042C An unexpected system error occurred. SQLSTATE=58004 | I am trying to connect to the Db2 database on Cloud using Python.
dsn_hostname = ".."
dsn_uid = ".."
dsn_pwd = ".."
dsn_driver = "{IBM DB2 ODBC DRIVER}"
dsn_database = ".."
dsn_port = ".."
dsn_protocol = "TCPIP"
dsn_security = "SSL"
dsn = (
"DRIVER={0};"... | [
"If you are running Microsoft Windows with python and clidriver then you may be affected by a defect in IBM's clidriver (which gets installed by default when you install the python ibm_db module). This problem only affects some workstations, not all, it depends on what is already installed and what is already on t... | [
0,
0
] | [] | [] | [
"db2",
"ibm_cloud",
"python"
] | stackoverflow_0068857222_db2_ibm_cloud_python.txt |
Q:
Can't connect to DB2 Driver through Python: SQL1042C
I can't connect to a DB2 remote server using Python. Here is what I've done:
Created a virtualenv with Python 2.7.10 (On Mac OS X 10.11.1)
installed ibm-db using sudo pip install ibm_db
Ran the following code:
import ibm_db
ibm_db.connect("my_connection_strin... | Can't connect to DB2 Driver through Python: SQL1042C | I can't connect to a DB2 remote server using Python. Here is what I've done:
Created a virtualenv with Python 2.7.10 (On Mac OS X 10.11.1)
installed ibm-db using sudo pip install ibm_db
Ran the following code:
import ibm_db
ibm_db.connect("my_connection_string", "", "")
I then get the following error:
Exception: [... | [
"Have you followed the setup instructions here?\nhttps://www-01.ibm.com/support/knowledgecenter/SSEPGG_9.7.0/com.ibm.swg.im.dbclient.python.doc/doc/t0054368.html\nYou need your DB2 ODBC driver properly installed before your Python code will work.\nThis issue may also shed light:\nhttps://github.com/ibmdb/node-ibm_d... | [
1,
1,
1,
0
] | [] | [] | [
"dashdb",
"db2",
"python"
] | stackoverflow_0034436084_dashdb_db2_python.txt |
Q:
How does SelectFromModel from scikit-learn select features?
When I use XGBClassifier with SelectFromModel the algorithm always returns around five features regardless of the max_features value
My question is: does XGBClassifier though that there are only five useful features in my dataset?
from sklearn.feature_se... | How does SelectFromModel from scikit-learn select features? | When I use XGBClassifier with SelectFromModel the algorithm always returns around five features regardless of the max_features value
My question is: does XGBClassifier though that there are only five useful features in my dataset?
from sklearn.feature_selection import SelectFromModel
from xgboost i... | [
"\nTo only select based on max_features, set threshold=-np.inf.\n\nI found the above text in the documentation sklearn.feature_selection. This means as priority SelectFromModel depends on the threshold parameter and returns all features that pass the threshold (regardless of max_features).\nIf you want max_features... | [
0
] | [] | [] | [
"feature_selection",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074293626_feature_selection_machine_learning_python_scikit_learn.txt |
Q:
What's the difference between select_related and prefetch_related in Django ORM?
In Django doc,
select_related() "follows" foreign-key relationships, selecting additional related-object data when it executes its query.
prefetch_related() does a separate lookup for each relationship, and does the "joining" in Pyth... | What's the difference between select_related and prefetch_related in Django ORM? | In Django doc,
select_related() "follows" foreign-key relationships, selecting additional related-object data when it executes its query.
prefetch_related() does a separate lookup for each relationship, and does the "joining" in Python.
What does it mean by "doing the joining in python"? Can someone illustrate with a... | [
"Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a \"set\" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what ... | [
631,
34,
30,
1,
1
] | [] | [] | [
"django",
"django_models",
"django_orm",
"python"
] | stackoverflow_0031237042_django_django_models_django_orm_python.txt |
Q:
Convert column based time series data to regular DataFrame
I have the following data:
df = pd.DataFrame({'id' : [1,2,3,4,5,6], 'category' : [1,3,1,4,3,2], 'day1' : [10,20,30,40,50,60], 'day2' : [1,2,3,4,5,7], 'day3' : [0,1,2,3,7,9] })
df
id category day1 day2 day3
0 1 1 10 1 0
1 2 3 20 2... | Convert column based time series data to regular DataFrame | I have the following data:
df = pd.DataFrame({'id' : [1,2,3,4,5,6], 'category' : [1,3,1,4,3,2], 'day1' : [10,20,30,40,50,60], 'day2' : [1,2,3,4,5,7], 'day3' : [0,1,2,3,7,9] })
df
id category day1 day2 day3
0 1 1 10 1 0
1 2 3 20 2 1
2 3 1 30 3 2
3 4 4 40 4 3
4 5 3 50 ... | [
"A possible solution:\ndf.set_index(['id', 'category']).stack().rename(\n 'day').reset_index().drop('level_2', axis=1)\n\nOutput:\n id category day\n0 1 1 10\n1 1 1 1\n2 1 1 0\n3 2 3 20\n4 2 3 2\n5 2 3 1\n6 3 1 30... | [
1,
1
] | [] | [] | [
"pandas",
"python",
"time_series"
] | stackoverflow_0074338455_pandas_python_time_series.txt |
Q:
SVM Loss Function
def svm_loss_naive(W, X, y):
"""
SVM loss function, naive implementation calculating loss for each sample
using loops.
Inputs:
- X: A numpy array of shape (n, m) containing data(samples).
- y: A numpy array of shape (m, ) containing labels
- W: A numpy array of shape (p, n) containing weight... | SVM Loss Function | def svm_loss_naive(W, X, y):
"""
SVM loss function, naive implementation calculating loss for each sample
using loops.
Inputs:
- X: A numpy array of shape (n, m) containing data(samples).
- y: A numpy array of shape (m, ) containing labels
- W: A numpy array of shape (p, n) containing weights.
"""
# Compute ... | [] | [] | [
"This is the SVM loss (data loss) function definition:\n\nIn the internal summation the j index equal to y[i] is explicitly escluded\n"
] | [
-1
] | [
"loss",
"python",
"svm"
] | stackoverflow_0066740435_loss_python_svm.txt |
Q:
Python. AttributeError: 'Text' object has no attribute 'plot'
I followed this guide on internet https://python4astronomers.github.io/plotting/advanced.html, but the axes object created by fig.add_subplot doesn't work.
The error it gives is:
ax_correl_1.plot(correlation_x_axis, energy_correl_array,'.', label=r'$be... | Python. AttributeError: 'Text' object has no attribute 'plot' | I followed this guide on internet https://python4astronomers.github.io/plotting/advanced.html, but the axes object created by fig.add_subplot doesn't work.
The error it gives is:
ax_correl_1.plot(correlation_x_axis, energy_correl_array,'.', label=r'$beta$ = {val:}'.format(val=i))
AttributeError: 'Text' object has no a... | [
"I suggest you try:\nax_correl_1 = fig_correl.add_subplot(2, 2, 1)\nax_correl_2 = fig_correl.add_subplot(2, 2, 2)\nax_correl_3 = fig_correl.add_subplot(2, 1, 2)\n\nax_correl_1.set_title('Energy')\nax_correl_2.set_title('abs(Magnetization')\nax_correl_3.set_title('Magnetization')\n\n... instead of:\nax_correl_1 = fi... | [
0
] | [] | [] | [
"matplotlib",
"object",
"plot",
"python",
"subplot"
] | stackoverflow_0074338431_matplotlib_object_plot_python_subplot.txt |
Q:
How to merge sets in better then O(len(set))?
I have a list of sets called groups. groups[i] is a set of labels (integers) that are part of the same group as i. For example,
# idx: 0 1 2 3 4 5 6 7
groups = [{0}, {1}, {2,5,6}, {3}, {4,7}, {2,5,6}, {2,5,6}, {4,7}]
indicates th... | How to merge sets in better then O(len(set))? | I have a list of sets called groups. groups[i] is a set of labels (integers) that are part of the same group as i. For example,
# idx: 0 1 2 3 4 5 6 7
groups = [{0}, {1}, {2,5,6}, {3}, {4,7}, {2,5,6}, {2,5,6}, {4,7}]
indicates that
0 belongs to the group containing just 0
1 belo... | [
"I think it's about the best you can do.\nSets are, to my knowledge, implemented via a hash table in the Python standard library.\nDepending on the implementation, yes, I think the set unions should be performed in O(min(a,b)) time, where a and b are the length of two sets. You just write each member of the smaller... | [
0
] | [] | [] | [
"disjoint_sets",
"disjoint_union",
"merge",
"python",
"union_find"
] | stackoverflow_0074337128_disjoint_sets_disjoint_union_merge_python_union_find.txt |
Q:
hoe to delete specific strings in a python .txt file after accepting user input on what to delets
This is a python file that's supposed to act like a phone book the file is called exam.txt its supposed to create, save, append, search and delete contacts but the delete part deletes all the strings instead of specif... | hoe to delete specific strings in a python .txt file after accepting user input on what to delets | This is a python file that's supposed to act like a phone book the file is called exam.txt its supposed to create, save, append, search and delete contacts but the delete part deletes all the strings instead of specific strings (the rest of the code is ok when executed the deleting part is the last part of the code)
#i... | [
"A few improvements and corrections (for your specific issue, see Item 6).\n\nYou are first asking the user to enter the number of contacts they wish to enter. What if they have a very long list? You are forcing them to have to manually count the number of names on the list. Better would be to continue entering unt... | [
0,
0,
0
] | [] | [] | [
"phonebook",
"python"
] | stackoverflow_0074337800_phonebook_python.txt |
Q:
What does the "yield" keyword do?
What is the use of the yield keyword in Python? What does it do?
For example, I'm trying to understand this code1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if sel... | What does the "yield" keyword do? | What is the use of the yield keyword in Python? What does it do?
For example, I'm trying to understand this code1:
def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >... | [
"To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.\nIterables\nWhen you create a list, you can read its items one by one. Reading its items one by one is called iteration:\n>>> mylist = [1, 2, 3]\n>>> for i in mylist:\n..... | [
17430,
2430,
722,
612,
529,
434,
305,
297,
276,
236,
235,
207,
207,
162,
158,
146,
133,
127,
116,
100,
86,
82,
78,
74,
72,
71,
67,
65,
55,
52,
50,
46,
39,
31,
30,
22,
17,
16,
12,
8,
8,
5,
4,
4,
4,
3,
3,
2,
2,
2,
1
] | [] | [] | [
"generator",
"iterator",
"python"
] | stackoverflow_0000231767_generator_iterator_python.txt |
Q:
YouTube API, how to post to different channels after approval with Python
I was using this program here to post in YouTube: https://github.com/EnriqueStrange/AutomatedYoutube
I have an account with 4 YouTube Channels and I want to be able to automatically post on the different channels. I created 4 different OAuth... | YouTube API, how to post to different channels after approval with Python | I was using this program here to post in YouTube: https://github.com/EnriqueStrange/AutomatedYoutube
I have an account with 4 YouTube Channels and I want to be able to automatically post on the different channels. I created 4 different OAuth 2.0 Client IDs, and when running the first the browser opens, I give permissio... | [
"You only need one client id. You can authorize the application four times once for each channel. Just store the refresh token. There is no need for a different client.\nIn the example below you would have a separate 'token.json' for each channel.\nif os.path.exists('token.json'):\n creds = Credentials.from_auth... | [
0
] | [] | [] | [
"google_developers_console",
"python",
"youtube_api"
] | stackoverflow_0074338469_google_developers_console_python_youtube_api.txt |
Q:
using s3cmd with a different, s3 like, provider
I'm using s3cmd, a python command line tool, with a S3-like provider different from AWS. When I set up the whole system I clearly remember that I search for the endpoint and change the default AWS one with the one I'm using (so endpoint was not a config option), then... | using s3cmd with a different, s3 like, provider | I'm using s3cmd, a python command line tool, with a S3-like provider different from AWS. When I set up the whole system I clearly remember that I search for the endpoint and change the default AWS one with the one I'm using (so endpoint was not a config option), then complete the configuration process and right now I'm... | [
"In this config file you should have 2 lines like this : \nhost_base = s3.amazonaws.com \nhost_bucket = %(bucket)s.s3.amazonaws.com \n\nYou can then change it to point at your ViPR instance:\nhost_base = s3.mydomain.com \nhost_bucket = %(bucket)s.s3.mydomain.com \n\nNote: Your ViPR solution has to support aws virt... | [
2,
1,
0
] | [] | [] | [
"amazon_s3",
"configuration",
"python",
"s3cmd"
] | stackoverflow_0028984259_amazon_s3_configuration_python_s3cmd.txt |
Q:
How to stop my entire python program from closing?
I am new to Python, so after making simple programs I am making a program. Using Tkinter I have managed to create the main screen and login screen(login form GUI). The functionality works however, if I do not want to log in and click on the back button, it should ... | How to stop my entire python program from closing? | I am new to Python, so after making simple programs I am making a program. Using Tkinter I have managed to create the main screen and login screen(login form GUI). The functionality works however, if I do not want to log in and click on the back button, it should close the login screen(login form GUI), but it closes th... | [
"Use this code.\nThis will close the full login screen.\n\nclass LoginFrame(ttk.Frame):\n def __init__(self, container):\n self.con = container\n super().__init__(container)\n self.__createMain__()\n\n # Creates the widgets for the Main Screen\n def __createMain__(self):\n\n #So... | [
0
] | [] | [] | [
"oop",
"pycharm",
"python",
"tkinter"
] | stackoverflow_0074338546_oop_pycharm_python_tkinter.txt |
Q:
Compatibility problem between python version 3.10 and pygame
Going to keep this short and sweet. I am trying to play a song using pygame's mixer. When I choose the song to play I get this error.
`
File "d:\Study\Python\musicplayer.py", line 32, in PlayMusic
mixer.music.load(Playlist.get(ACTIVE))
pygame.error: ... | Compatibility problem between python version 3.10 and pygame | Going to keep this short and sweet. I am trying to play a song using pygame's mixer. When I choose the song to play I get this error.
`
File "d:\Study\Python\musicplayer.py", line 32, in PlayMusic
mixer.music.load(Playlist.get(ACTIVE))
pygame.error: Failed loading libmpg123-0.dll: The specified module could not be ... | [
"I believe you are running python from the Windows store. People who have had this error before have had this setup, rather than the much more common python.org installs.\nTry updating to the latest pre release version of pygame. python -m pip install pygame --upgrade --pre. You should see \"pygame 2.1.3.dev8\" as ... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074338201_pygame_python.txt |
Q:
How to return empty if object has no attribute 'casefold'
I have currently two different dict where in one data its empty and with data, and I want to compare the data between them and see if the stock is higher than the previous data. Here is a proof of concept I have done:
STOCK_MAP = {
'oos': 0,
'low': ... | How to return empty if object has no attribute 'casefold' | I have currently two different dict where in one data its empty and with data, and I want to compare the data between them and see if the stock is higher than the previous data. Here is a proof of concept I have done:
STOCK_MAP = {
'oos': 0,
'low': 1,
'medium': 2,
'high': 3
}
data_1 = {}
data2 = {
... | [
"You want to use\nvalue[\"stock\"].casefold() if hasattr(value[\"stock\"], \"casefold\") else 0\n"
] | [
0
] | [] | [] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0074338589_dictionary_python_python_3.x.txt |
Q:
NaN from tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))
I am doing a image segmentation using resnet50 as encoder and made the decoder with unpooling layers with skip layers in tensorflow
Here is the model structure,
For the loss function, I used the dice_coefficient and IOU formula, and calculated the to... | NaN from tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) | I am doing a image segmentation using resnet50 as encoder and made the decoder with unpooling layers with skip layers in tensorflow
Here is the model structure,
For the loss function, I used the dice_coefficient and IOU formula, and calculated the total loss by adding both. In addition to the total loss, I added the R... | [
"Two possible solutions:\n\nYou may have an issue with the input data. Try calling assert not\nnp.any(np.isnan(x)) on the input data to make sure you are not introducing\nthe nan. Also make sure all of the target values are valid. Finally, make\nsure the data is properly normalized. You probably want to have the pi... | [
0
] | [] | [] | [
"conv_neural_network",
"keras",
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0074338536_conv_neural_network_keras_python_python_3.x_tensorflow.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.