content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python delete item from a dictionary when double iterating
I want to delet items from a dict where the value is a number and the key a datetime:
Conditions:
if the value is the same i want to delete all items with the same value within 1h
#del duplicates within 60min
for formatted_key in list(formatted_dic... | Python delete item from a dictionary when double iterating | I want to delet items from a dict where the value is a number and the key a datetime:
Conditions:
if the value is the same i want to delete all items with the same value within 1h
#del duplicates within 60min
for formatted_key in list(formatted_dict.keys()):
for temp_key in list(formatted_dict.keys()):
... | [
"A not recommended change (better rewrite your code using another approach) in order to avoid a KeyError would be to use:\nif( formatted_key in formatted_dict and temp_key in formatted_dict and formatted_dict[formatted_key]==formatted_dict[temp_key]):\n\nand\nif temp_key in formatted_dict: del formatted_dict[temp_k... | [
0
] | [] | [] | [
"dictionary",
"key",
"loops",
"python"
] | stackoverflow_0074232387_dictionary_key_loops_python.txt |
Q:
Control the power of a usb port in Python
I was wondering if it could be possible to control the power of usb ports in Python, using vendor ids and product ids. It should be controlling powers instead of just enabling and disabling the ports. It would be appreciated if you could provide some examples.
A:
Look in... | Control the power of a usb port in Python | I was wondering if it could be possible to control the power of usb ports in Python, using vendor ids and product ids. It should be controlling powers instead of just enabling and disabling the ports. It would be appreciated if you could provide some examples.
| [
"Look into the subprocess module in the standard library:\nWhat commands you need will depend on the OS.\nWindows\nFor windows you will want to look into devcon\nThis has been answered in previous posts\nimport subprocess\n# Fetches the list of all usb devices:\nresult = subprocess.run(['devcon', 'hwids', '=usb'], ... | [
2,
0
] | [] | [] | [
"libusb",
"port",
"python",
"pyusb",
"usb"
] | stackoverflow_0064990689_libusb_port_python_pyusb_usb.txt |
Q:
trying to split number but list index out of range
the problem with this code is that it will come to a point, in line 9 (if a[c+1] != 0:), it will recall an index +3 that does not exist and it will give me the error "list index out of range".
a= '555101'
a= list(map(int,a))
c= 0
seq= []
for i in a:
if a... | trying to split number but list index out of range | the problem with this code is that it will come to a point, in line 9 (if a[c+1] != 0:), it will recall an index +3 that does not exist and it will give me the error "list index out of range".
a= '555101'
a= list(map(int,a))
c= 0
seq= []
for i in a:
if a[c] == 1:
if a[c+1] != 0:
... | [
"You can split the string using the python regex module re.\nimport re\n\npattern = (r'[1-9]0*')\na= '10010010010100511'\n\nprint(list(map(int, re.findall(pattern, a))))\n\nOutput\n[100, 100, 100, 10, 100, 5, 1, 1]\n\n",
"Here is how I would do it without additional libraries. Check for values not equal to 0 to s... | [
1,
1,
0
] | [] | [] | [
"indexing",
"list",
"python",
"range"
] | stackoverflow_0074232299_indexing_list_python_range.txt |
Q:
Validate HTML with BeautifulSoup
I use BeautifulSoup 3.2.1 to parse a lot of HTML files translated with eTranslation.
I found
soup = BeautifulSoup(html_file, "html.parser") sometimes cuts a section of my HTML file. And it is related to invalid tags or problems found in the HTML.
Also I found soup = BeautifulSoup(h... | Validate HTML with BeautifulSoup | I use BeautifulSoup 3.2.1 to parse a lot of HTML files translated with eTranslation.
I found
soup = BeautifulSoup(html_file, "html.parser") sometimes cuts a section of my HTML file. And it is related to invalid tags or problems found in the HTML.
Also I found soup = BeautifulSoup(html_file, "lxml") works better in thes... | [
"I solved it using lxml all the time.\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0073867545_beautifulsoup_html_python.txt |
Q:
How to add a new Measure on report.pos.order [Odoo 15]
I'm working with Odoo 15 and I want to add a new measure on a report from point_of_sale. The module I need to inherit to add a new measure is report.pos.order
I've done it before with the module SaleReport, but this module has a _query() function and report.po... | How to add a new Measure on report.pos.order [Odoo 15] | I'm working with Odoo 15 and I want to add a new measure on a report from point_of_sale. The module I need to inherit to add a new measure is report.pos.order
I've done it before with the module SaleReport, but this module has a _query() function and report.pos.order doesn't
report.pos.order module
class PosOrderReport... | [
"You can override _select, _from, and _group_by functions to add the margin_percent field to the pos order report.\nYou can find the following example in the pos_hr module:\nclass PosOrderReport(models.Model):\n _inherit = \"report.pos.order\"\n\n employee_id = fields.Many2one(\n 'hr.employee',... | [
1
] | [] | [] | [
"odoo",
"odoo_15",
"python"
] | stackoverflow_0074230496_odoo_odoo_15_python.txt |
Q:
Convert multiple rows to column headers and include nan values python df
How do I convert multiple rows to different columns?
I have a dataframe like this:
Brand Key Col_Name1 Percentage Col_Name2 Dollar_Value
A 1 Percentage_High 90 Dollar_Value_High 30000
A ... | Convert multiple rows to column headers and include nan values python df | How do I convert multiple rows to different columns?
I have a dataframe like this:
Brand Key Col_Name1 Percentage Col_Name2 Dollar_Value
A 1 Percentage_High 90 Dollar_Value_High 30000
A 1 Percentage_Low 70 Dollar_Value_Low 20000
B ... | [
"I think you are looking for df.groupby. https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#named-aggregation\nExample:\ndf.groupby([\"Brand\",\"Key\"]).agg(\n Percentage_High=(\"Percentage\", \"max\"),\n Percentage_Low=(\"Percentage\", \"min\"),\n Dollar_value_low=(\"Dollar_Value\", \"mi... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074232002_dataframe_pandas_python.txt |
Q:
(OpenCV , cv2) The cv2.error while capture the image through camera lens
Error (-215) size.width>0 && size.height>0 occurred when attempting to display an image using OpenCV
I have the similar issue with this discussion, after I read it still don't have clue for how to address mine,that I post my case here
I use r... | (OpenCV , cv2) The cv2.error while capture the image through camera lens | Error (-215) size.width>0 && size.height>0 occurred when attempting to display an image using OpenCV
I have the similar issue with this discussion, after I read it still don't have clue for how to address mine,that I post my case here
I use raspberrypi 4 ; 32 bit, linux run python ; logitech USB camera lens ; run in v... | [
"after I changed vid = cv2.VideoCapture() to 0 now as video function is working, but my original purpose is taking one image though\nimport cv2\n \n \n# define a video capture object\nvid = cv2.VideoCapture(0) ########## 1- device id =1###if 1 deosn't work try 2\n\n\n \nwhile(True):\n ret, frame = vid.read()\n ... | [
0,
0
] | [] | [] | [
"computer_vision",
"opencv",
"python",
"raspberry_pi4"
] | stackoverflow_0074229735_computer_vision_opencv_python_raspberry_pi4.txt |
Q:
read a entire line in a binary file which consists of multiple lines in python
For example:
in a binary file consists multiple lines of data
xf4\x97V7\xc6e\xf6\xe7mS\xa2\x9ag5\x97\xc5.\x85\xc5\xc4
m4\x1b0\x93\x86\nM-RD\x82@sO\xe5wNb\x1b\xd6\x85\xb4\xd8\x0
\x97V7\xc6e\xf6\xe7mx\e5wNb\x1b\xd6\x85\xb4\xd8\x0
But i ne... | read a entire line in a binary file which consists of multiple lines in python | For example:
in a binary file consists multiple lines of data
xf4\x97V7\xc6e\xf6\xe7mS\xa2\x9ag5\x97\xc5.\x85\xc5\xc4
m4\x1b0\x93\x86\nM-RD\x82@sO\xe5wNb\x1b\xd6\x85\xb4\xd8\x0
\x97V7\xc6e\xf6\xe7mx\e5wNb\x1b\xd6\x85\xb4\xd8\x0
But i need to read data line by line for some process.
Can anyone help me in this logic ?
wi... | [
"You can read the binary file in chunks:\ntest.py:\nCHUNK = 8\n\n\ndef main():\n offset = 0\n\n with open(\"tmp.bin\", \"rb\") as f:\n while chunk := f.read(CHUNK):\n print(f\"{offset:08x} {chunk.hex(' ', 1)}\")\n offset += len(chunk)\n\n print(f\"{offset:08x}\")\n\n\nif _... | [
0
] | [] | [] | [
"byte",
"cryptography",
"file_read",
"python"
] | stackoverflow_0074222526_byte_cryptography_file_read_python.txt |
Q:
Shows "Unable to get repr for " while retrieving data
I've been trying to retrieve all data from model StudentInfo.
But it shows the following error.
django.db.utils.ProgrammingError: column student_studentinfo.gurdians_mobile does not exist
allStudent
Error in formatting: ProgrammingError: column student_st... | Shows "Unable to get repr for " while retrieving data | I've been trying to retrieve all data from model StudentInfo.
But it shows the following error.
django.db.utils.ProgrammingError: column student_studentinfo.gurdians_mobile does not exist
allStudent
Error in formatting: ProgrammingError: column student_studentinfo.gurdians_mobile does not exist
LINE 1: ...ile_n... | [
"So what I've learned so far about this problem is that there is no definitive answer exists for this particular type of problem. Django shows this error for multiple reasons. So I'm going to list all the scenarios and solutions that I've came across so far for this problem:\n\nThis problem might arise if you try t... | [
7,
2,
0,
0,
0,
0
] | [] | [] | [
"django",
"django_models",
"python",
"python_3.x"
] | stackoverflow_0044375188_django_django_models_python_python_3.x.txt |
Q:
ModuleNotFoundError: No module named 'request' in Python
I was trying to install a module named panda, to clarify, I actually want to use the panda package instead of pandas. I installed it using pip install panda, and cmd displayed requirement already satisfied. Normally, I could use this module by using this cod... | ModuleNotFoundError: No module named 'request' in Python | I was trying to install a module named panda, to clarify, I actually want to use the panda package instead of pandas. I installed it using pip install panda, and cmd displayed requirement already satisfied. Normally, I could use this module by using this code:
import panda
But when I typed in this line of code, python... | [
"It looks like this library suffers from relative import errors, which is weird for such a popular library.\nTo fix it, go to the python/site-packages/panda directory, in your case, it is C:\\Users\\xyccx_mdrrjg8\\AppData\\Roaming\\Python\\Python310\\site-packages\\panda\\.\nIn the __init__.py, change the first 5 l... | [
1
] | [] | [] | [
"module",
"pip",
"python"
] | stackoverflow_0074232909_module_pip_python.txt |
Q:
Argparse how to change the default help (usage) section
I have the following Argument Parser configuration, through which I have defined the '--config' argument:
# Initialize the Argument Parser
clArgsParser = argparse.ArgumentParser (
description = __program__.description,
epilog = __program__.epilog,
... | Argparse how to change the default help (usage) section | I have the following Argument Parser configuration, through which I have defined the '--config' argument:
# Initialize the Argument Parser
clArgsParser = argparse.ArgumentParser (
description = __program__.description,
epilog = __program__.epilog,
formatter_class = argparse.RawDescriptionHelpFormatter
)
# ... | [
"When ArgumentParser generates help messages, it needs some way to refer to each expected argument. An alternative name to the expected argument can be specified with metavar option which will overwrite the default expected argument in the help message.\nFor example to change PROGRAMCONFIGPATH to <PROGRAM_CONFIG_PA... | [
0
] | [] | [] | [
"argparse",
"command_line_arguments",
"command_line_interface",
"python"
] | stackoverflow_0074232984_argparse_command_line_arguments_command_line_interface_python.txt |
Q:
How to create a dictionary base SingleTon?
I want to create a dictionary base SingleTon. Some simple example like:
singleton = SingleTon()
singleton['a'] = 5
print(singleton['a']) #5
I have written a basic class:
class SingleTonNew():
_instance = None
def __new__(cls, *args, **kwargs):
id = t... | How to create a dictionary base SingleTon? | I want to create a dictionary base SingleTon. Some simple example like:
singleton = SingleTon()
singleton['a'] = 5
print(singleton['a']) #5
I have written a basic class:
class SingleTonNew():
_instance = None
def __new__(cls, *args, **kwargs):
id = threading.get_ident()
if cls._instance is... | [
"class Singleton(dict):\n def __new__(cls):\n if not hasattr(cls, 'instance'):\n cls.instance = super(Singleton, cls).__new__(cls)\n return cls.instance\n \nsingleton1 = Singleton()\nsingleton2 = Singleton()\n\nsingleton1['a'] = 5\nprint(singleton1 is singleton2)\nprint(singleton2)\n\nSimply inherit ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074232537_python.txt |
Q:
change format with yaml dump python
I need to create a yaml with the following format
hints:
- {
content: "...",
...
}
alredy tried to do something like data['hints'] = {"content" : "a", "foo" : "bar"} giving:
hints:
- content: "a"
foo: "bar"
also tried data['hints'] = "{\n" + f"cont... | change format with yaml dump python | I need to create a yaml with the following format
hints:
- {
content: "...",
...
}
alredy tried to do something like data['hints'] = {"content" : "a", "foo" : "bar"} giving:
hints:
- content: "a"
foo: "bar"
also tried data['hints'] = "{\n" + f"content:{...}," + "\n" + ... + "\n}", giving:... | [
"You can change the style with a custom representer, like so:\nimport sys, yaml\n\nclass BraceDict(dict):\n pass\n\n\ndef represent_brace_dict(dumper, data):\n ret = dumper.represent_dict(data)\n ret.flow_style = True\n return ret\nyaml.add_representer(BraceDict, represent_brace_dict)\n\nyaml.dump({\n ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"pyyaml",
"yaml"
] | stackoverflow_0074230758_python_python_3.x_pyyaml_yaml.txt |
Q:
Detect cropped image is within mask
Say I have an image as follows and I would like to crop some sub-images of the retina only.
So the first step I took is to find a mask
# Find Mask
img = imread(folder + 'test.jpg')
blur = cv2.GaussianBlur(img, (3, 3), cv2.BORDER_DEFAULT)
edged = cv2.Canny(blur, 10, 250)
# thr... | Detect cropped image is within mask | Say I have an image as follows and I would like to crop some sub-images of the retina only.
So the first step I took is to find a mask
# Find Mask
img = imread(folder + 'test.jpg')
blur = cv2.GaussianBlur(img, (3, 3), cv2.BORDER_DEFAULT)
edged = cv2.Canny(blur, 10, 250)
# threshold
thresh = cv2.threshold(edged, 128,... | [
"If you want to extract really random sub-images that is not necessary inscribed in a circle, you can just get some coords within the non-zero mask bounding box, check if it contains only ones, and save them, if so.\nsub_imgs = []\n\n# Define minimum width and height for the cropped region\nmin_width = 32\nmin_heig... | [
1
] | [] | [] | [
"image",
"opencv",
"python"
] | stackoverflow_0074232393_image_opencv_python.txt |
Q:
How to find out the type of partitioning in a table in google bigquery using python apis
def partition(dataset1, dataset2):
try:
client.get_dataset(dataset2)
print("Dataset {} already exists".format(dataset2))
except NotFound:
print("Dataset {} not found".format(dataset2))
... | How to find out the type of partitioning in a table in google bigquery using python apis | def partition(dataset1, dataset2):
try:
client.get_dataset(dataset2)
print("Dataset {} already exists".format(dataset2))
except NotFound:
print("Dataset {} not found".format(dataset2))
createDataset(dataset2)
table = client.get_table(dataset1) # get the source dataset
p... | [
"You can use the following script to get the partition type :\nfrom google.cloud import bigquery\n\nif __name__ == '__main__':\n # Construct a BigQuery client object.\n client = bigquery.Client()\n\n # table_id = 'your-project.your_dataset.your_table'\n\n table = client.get_table('your-project.your_data... | [
1
] | [] | [] | [
"data_partitioning",
"google_bigquery",
"google_cloud_platform",
"python",
"table_partitioning"
] | stackoverflow_0074231129_data_partitioning_google_bigquery_google_cloud_platform_python_table_partitioning.txt |
Q:
How to increase the model accuracy of logistic regression in sklearn.linearP_model?
I am trying to predict the y values using LogisticRegression.
Here is a sample of the that is train.
x = data[["A1", "A2", "A3","A4", "A5", "A6", "A7", "A8", "A9", "A10", "A11"]]
y = data["y"]
x_train, x_test, y_train, y_test = t... | How to increase the model accuracy of logistic regression in sklearn.linearP_model? | I am trying to predict the y values using LogisticRegression.
Here is a sample of the that is train.
x = data[["A1", "A2", "A3","A4", "A5", "A6", "A7", "A8", "A9", "A10", "A11"]]
y = data["y"]
x_train, x_test, y_train, y_test = train_test_split(df, y, test_size=0.4, random_state=42)
log_model = LogisticRegression(so... | [
"There are multiple ways to improve your model, such as:\n\nData Transformation:\n\nCalculate the logrithmic on the original data and see if the data distrition becomes more obivious\nData bining: Split data into different bins, it may make your data more ridged(easier to split)\n...\n\n\nChange your model: There a... | [
0,
0
] | [] | [] | [
"logistic_regression",
"python",
"scikit_learn"
] | stackoverflow_0074232616_logistic_regression_python_scikit_learn.txt |
Q:
Why are my the delimiters not random enough and the numbers subdomain count range aren't correct?
Hello guys i want to ask, why are my punctuations on my domain name generator not random enough? here is my code
import random
Example = open("dictionaries/examples.txt", 'w', encoding="utf-8")
with open("dictionarie... | Why are my the delimiters not random enough and the numbers subdomain count range aren't correct? | Hello guys i want to ask, why are my punctuations on my domain name generator not random enough? here is my code
import random
Example = open("dictionaries/examples.txt", 'w', encoding="utf-8")
with open("dictionaries/Combined.txt") as i:
Test = [line.rstrip() for line in i]
This is a few words what inside the co... | [
"The domain punctuation varies between the three domains generated in the main loop, for example the three domain names with find in them one has a dot and the other has nothing. You are only choosing the delimiter once, and using that one delimiter to join all the elements in data:\nprefix = random.choice(delimete... | [
1
] | [] | [] | [
"jupyter_notebook",
"python",
"random"
] | stackoverflow_0074232813_jupyter_notebook_python_random.txt |
Q:
problem with displaying only one value on the screen
I'm currently working on a project that should display the cost of nickel. When you insert the year you want to have, it should print out what month you want to have out of that year. If you insert the first three letters of the month you should see all months d... | problem with displaying only one value on the screen | I'm currently working on a project that should display the cost of nickel. When you insert the year you want to have, it should print out what month you want to have out of that year. If you insert the first three letters of the month you should see all months displayed.
I was trying to convert it to a string to make i... | [
"The method .find() returns 0 if it finds something, else it returns -1.\nThis should be your code:\nnickel2015 = [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]\n\n\nyearinput = str(input(\"Please enter year to get data:\"))\n\nif \"2015\" in yearinput:\n monthinput = str(input(\"Please... | [
0
] | [] | [] | [
"list",
"printing",
"python",
"string"
] | stackoverflow_0074233304_list_printing_python_string.txt |
Q:
Get text from bs4.element.Tag containing JSON (beautifulsoup)
I have an element with type bs4.element.Tag like:
<span class="hidden gtm-product-data">
{"id":"716727616125500","name":"chinese whitewine","price":7.99,"brand":"silver heights"}
</span>
The span-tag contains a JSON string.
How to extract only the bran... | Get text from bs4.element.Tag containing JSON (beautifulsoup) | I have an element with type bs4.element.Tag like:
<span class="hidden gtm-product-data">
{"id":"716727616125500","name":"chinese whitewine","price":7.99,"brand":"silver heights"}
</span>
The span-tag contains a JSON string.
How to extract only the brand name (JSON field brands value) silver heights?
| [
"Is this what you need?\nimport json\n\nfrom bs4 import BeautifulSoup\n\nsample = '<span class=\"hidden gtm-product-data\">{\"id\":\"716727616125500\",\"name\":\"chinese white wine\",\"price\":7.99,\"brand\":\"silver heights\"}</span>'\n\nsoup = json.loads(BeautifulSoup(sample, 'html.parser').find(\"span\").getText... | [
1
] | [] | [] | [
"beautifulsoup",
"json",
"python"
] | stackoverflow_0074233180_beautifulsoup_json_python.txt |
Q:
Tasks getting duplicated when using multiple celery workers with same queue
I'm using celery to run tasks that are small and big in nature.
Setup:
I'm using separate queues to handle small, medium, and large tasks independently.
There are different celery workers catering to each of the different queues.
Celery 5... | Tasks getting duplicated when using multiple celery workers with same queue | I'm using celery to run tasks that are small and big in nature.
Setup:
I'm using separate queues to handle small, medium, and large tasks independently.
There are different celery workers catering to each of the different queues.
Celery 5.2.7, Python 3.8.10
Using Redis as the broker.
Late ack set to True
Prefetch coun... | [
"Do you have celery beat worker running?\nsomething like this:\ncelery -A run.celery worker --loglevel=info --autoscale=5,2 -n app@beatworker --beat\n\nWe had the same problem, but now I don't remember how was it resolved. Try adding this separate worker with --beat option. there should be only one --beat running\n... | [
0
] | [] | [] | [
"celery",
"multiprocessing",
"python",
"python_3.x",
"redis"
] | stackoverflow_0074233094_celery_multiprocessing_python_python_3.x_redis.txt |
Q:
How to process a column from a dataframe in pandas
I am writing a python program to calculate the chi-square value for a set of observed and expected frequencies. The program that I have constructed is written like so
# Author: Evan Gertis
# Date : 10/25
# program : quantile decile calculator
import csv
import pa... | How to process a column from a dataframe in pandas | I am writing a python program to calculate the chi-square value for a set of observed and expected frequencies. The program that I have constructed is written like so
# Author: Evan Gertis
# Date : 10/25
# program : quantile decile calculator
import csv
import pandas as pd
import numpy as np
from scipy.stats import c... | [
"I believe your DF does not contains 'Expected' columns.\nYou can test it with the below code.\nimport pandas as pd\ndf = pd.DataFrame(columns = ['a','b'], data=[[1,2],[2,2]])\ndf['Expected']\n\nYou can observe the error is the same as yours.\n",
"Expected column name has a space in the beginning, so use df[' Exp... | [
0,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074233204_dataframe_numpy_pandas_python.txt |
Q:
Unable to print Escape Seqences with Python in Visual Studio (Win 10, Python 3.9, VS 2019)
My Issue
I'm a begginer with Python, and I've been working on code in Visual Studio in which I want to be able use ANSI Escape Sequences to format my output on the terminal console.
I'm using Python 3.9, Visual Studio 2019 (... | Unable to print Escape Seqences with Python in Visual Studio (Win 10, Python 3.9, VS 2019) | My Issue
I'm a begginer with Python, and I've been working on code in Visual Studio in which I want to be able use ANSI Escape Sequences to format my output on the terminal console.
I'm using Python 3.9, Visual Studio 2019 (Community Edition) and Windows 10 (64-bit).
I originally wanted to be able to move the cursor on... | [
"Unfortunately, you can't print escape sequences in VSC. Rather try the cmd.\n"
] | [
1
] | [] | [] | [
"ansi_escape",
"python",
"python_3.9"
] | stackoverflow_0074233474_ansi_escape_python_python_3.9.txt |
Q:
Different ways to get unique get_level_values()
Consider the following DataFrame df:
df=
kind A B
names a1 a2 b1 b2 b3
Time
0.0 0.7804 0.5294 0.1895 0.9195 0.0508
0.1 0.1703 0.7095 0.8704 0.8566 0.5513
0.2 0.8147 0.9055 0.0506 0.4212 ... | Different ways to get unique get_level_values() | Consider the following DataFrame df:
df=
kind A B
names a1 a2 b1 b2 b3
Time
0.0 0.7804 0.5294 0.1895 0.9195 0.0508
0.1 0.1703 0.7095 0.8704 0.8566 0.5513
0.2 0.8147 0.9055 0.0506 0.4212 0.2464
0.3 0.3985 0.4515 0.7118 0.6146 0.... | [
"I think you can use levels:\nout = df.columns.levels[0]\nprint (out)\nIndex(['A', 'B'], dtype='object')\n\nEDIT: One idea with lookup by names of MultiIndex:\nd = {v: k for k, v in enumerate(df.columns.names)}\nprint (d)\n{'kind': 0, 'names': 1}\n\nout = df.columns.levels[d['kind']]\nprint (out)\nIndex(['A', 'B']... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074233388_pandas_python.txt |
Q:
How to restrict ManyToManyField in ModelViewSet for no super users?
I have 2 models linked by a ManyToManyField relationship.
class Site(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class Device(models.Model):
name = models.CharField... | How to restrict ManyToManyField in ModelViewSet for no super users? | I have 2 models linked by a ManyToManyField relationship.
class Site(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
class Device(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.TextField(blank=T... | [
"You can filter the devices as well with a Prefetch object [Django-doc]:\nfrom django.db.models import Prefetch\n\n\nclass SiteViewSet(viewsets.ReadOnlyModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = SiteSerializer\n\n def get_queryset(self):\n if self.reque... | [
2
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074233492_django_django_rest_framework_python.txt |
Q:
Variable Updating (Python)
I am trying to create a 3D cube matrix and here is the matrix:
cube = [
[
['W', 'W', 'W'],
['W', 'W', 'W'],
['W', 'W', 'W']
],
[
['G', 'G', 'G'],
['G', 'G', 'G'],
['G', 'G', 'G']
],
[
['R', 'R', 'R'],
... | Variable Updating (Python) | I am trying to create a 3D cube matrix and here is the matrix:
cube = [
[
['W', 'W', 'W'],
['W', 'W', 'W'],
['W', 'W', 'W']
],
[
['G', 'G', 'G'],
['G', 'G', 'G'],
['G', 'G', 'G']
],
[
['R', 'R', 'R'],
['R', 'R', 'R'],
['R', '... | [
"You're referencing the original cube when assigning it to cube_g, you have to make a copy with .copy()\nThis should work:\ndef cube_rotation(rotation):\n if 'U' in rotation:\n cube_g = cube[1].copy()\n direction = 1\n if '\\'' in rotation: direction = -1;\n for i in range(1,4):\n ... | [
2
] | [] | [] | [
"cube",
"matrix",
"python"
] | stackoverflow_0074233455_cube_matrix_python.txt |
Q:
Python InfluxDB2 - write_api.write(...) How to check for success?
I need to write historic data into InfluxDB (I'm using Python, which is not a must in this case, so I maybe willing to accept non-Python solutions). I set up the write API like this
write_api = client.write_api(write_options=ASYNCHRONOUS)
The Data ... | Python InfluxDB2 - write_api.write(...) How to check for success? | I need to write historic data into InfluxDB (I'm using Python, which is not a must in this case, so I maybe willing to accept non-Python solutions). I set up the write API like this
write_api = client.write_api(write_options=ASYNCHRONOUS)
The Data comes from a DataFrame with a timestamp as key, so I write it to the da... | [
"If you use background batching, you can add custom success, error and retry callbacks.\nfrom influxdb_client import InfluxDBClient\n\ndef success_cb(details, data):\n url, token, org = details\n print(url, token, org)\n data = data.decode('utf-8').split('\\n')\n print('Total Rows Inserted:', len(data))... | [
3,
1,
0,
0
] | [] | [] | [
"dataframe",
"influxdb_2",
"influxdb_python",
"pandas",
"python"
] | stackoverflow_0069664307_dataframe_influxdb_2_influxdb_python_pandas_python.txt |
Q:
Parser or postlex causing an error in Lark
everyone. So, I'm parsing a shell output (mocked here) and I'm running into an error where I really don't expect. Minimum reproducible, working example is below:
from rich import print as rprint
import typing as tp
from lark import Lark, Transformer, Tree
from lark.inden... | Parser or postlex causing an error in Lark | everyone. So, I'm parsing a shell output (mocked here) and I'm running into an error where I really don't expect. Minimum reproducible, working example is below:
from rich import print as rprint
import typing as tp
from lark import Lark, Transformer, Tree
from lark.indenter import Indenter
class TreeIndenter(Indenter... | [
"Providing a PostLexer changes the default parser/lexer combo from earley/dynamic to earley/basic, since the dynamic parser can't handle the postlexer. However, the basic lexer is far less powerful and can't handle this kind of ambiguity.It sees that at that point a STRING would fit and then just uses that.\nThere ... | [
1
] | [] | [] | [
"lark_parser",
"parsing",
"python",
"python_3.x"
] | stackoverflow_0074209648_lark_parser_parsing_python_python_3.x.txt |
Q:
How can I change title dynamically in tkinter?
I'm looking for a way to dynamically change the title.
Below is my source code.
root = Tk()
root.title('Title')
root.geometry('300x160')
root.resizable(False,False)
.
.
.
root.mainloop()
Is there any way?
A:
You can set a string vari... | How can I change title dynamically in tkinter? | I'm looking for a way to dynamically change the title.
Below is my source code.
root = Tk()
root.title('Title')
root.geometry('300x160')
root.resizable(False,False)
.
.
.
root.mainloop()
Is there any way?
| [
"You can set a string variable.\nimport tkinter as tk\nw=tk.Tk()\ntitle='my_title'\nw.title(title)\nw.mainloop()\n\nas I understand you want it to change automatically. Instead of 'my_title' you can use a user input or data from database.\nQuick example with input:\nimport tkinter as tk\ni=input('title is: ')\nif ... | [
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0068299606_python_tkinter.txt |
Q:
groupby() with condition - count / mean
im having the dataframe:
test = pd.DataFrame({'Date': [2020 - 12 - 30, 2020 - 12 - 30, 2020 - 12 - 30, 2020 - 12 - 31, 2020 - 12 - 31, 2021 - 0o1 - 0o1, 2021 - 0o1 - 0o1], 'label': ['Positive', 'Positive', 'Negative', 'Negative','Negative', 'Positive', 'Positive'], 'score': ... | groupby() with condition - count / mean | im having the dataframe:
test = pd.DataFrame({'Date': [2020 - 12 - 30, 2020 - 12 - 30, 2020 - 12 - 30, 2020 - 12 - 31, 2020 - 12 - 31, 2021 - 0o1 - 0o1, 2021 - 0o1 - 0o1], 'label': ['Positive', 'Positive', 'Negative', 'Negative','Negative', 'Positive', 'Positive'], 'score': [70, 80, 50, 50, 30, 90, 70]})
Output:
Da... | [
"Try:\nx = df.pivot_table(\n index=[\"Date\", \"label\"],\n columns=\"label\",\n values=\"score\",\n aggfunc=[\"sum\", \"count\"],\n fill_value=0,\n)\n\nx.columns = [\"_\".join(c) for c in x.columns]\nx[\"new_score\"] = x[[\"sum_Negative\", \"sum_Positive\"]].sum(axis=1)\nx = x.drop(columns=[\"sum_Ne... | [
3,
1,
1
] | [] | [] | [
"conditional_formatting",
"group_by",
"pandas",
"python"
] | stackoverflow_0074227476_conditional_formatting_group_by_pandas_python.txt |
Q:
solving a non-linear convex minimization problem in cvxpy
I have a non-linear convex optimization problem, which can be expressed in a cost function like this:
The task of the solver should be to find values for the variables pp which minimize the value.
constraint are :
How would the minimize function for cvxpy... | solving a non-linear convex minimization problem in cvxpy | I have a non-linear convex optimization problem, which can be expressed in a cost function like this:
The task of the solver should be to find values for the variables pp which minimize the value.
constraint are :
How would the minimize function for cvxpy look in that case?
I do this but it doesn't work
import cvxpy ... | [
"The error comes from the fact, that division / is not implemented for generic lists like you are using.\nd = [2648000, 5552000, 4744000, 4056000, 6168000]\nr = [8574212.020483451, 6619470.077787987, 7521159.373986546, 7135440.631765847, 6832684.423897811]\n\nprint(d/r)\n\nResults in the error:\nTypeError: unsuppor... | [
0
] | [] | [] | [
"cvxpy",
"python"
] | stackoverflow_0074233426_cvxpy_python.txt |
Q:
Data frame normalization center = 0 solution (-1, 1)?
I have multiple variables in my data frame with negative and positive values. Thus I'd like to normalize/scale the variables between -1, 1. I didnt find a working solution. Any suggestions? Thanks a lot!
I scaled other variables with the sklearn MinMaxScaler 0,... | Data frame normalization center = 0 solution (-1, 1)? | I have multiple variables in my data frame with negative and positive values. Thus I'd like to normalize/scale the variables between -1, 1. I didnt find a working solution. Any suggestions? Thanks a lot!
I scaled other variables with the sklearn MinMaxScaler 0, 1. Didn't find an additional -1, 1 solution there.
| [
"Min max scaler uses a mathematical formula that converts values between 0,1 not -1,1\nif you want values between -1,1 try sklean's StandardScaler.\nHope this helps.\n",
"Here is a mathematical answer to your question:\nresult = (row - min_col) * (high - low) / (max_col - min_col) + low\nWhere:\n\nrow = the numbe... | [
0,
0
] | [] | [] | [
"normalization",
"pandas",
"python"
] | stackoverflow_0074232723_normalization_pandas_python.txt |
Q:
pandas fill missing values with mean of other columns grouped by a value
I have this dataset where I have NaN values on column 'a'. I want to group rows by 'user_id', compute the mean on column 'c' grouped by 'user_id' and fill NaN values on 'a' with this mean. How can I do it?
this is the code
import pandas as pd... | pandas fill missing values with mean of other columns grouped by a value | I have this dataset where I have NaN values on column 'a'. I want to group rows by 'user_id', compute the mean on column 'c' grouped by 'user_id' and fill NaN values on 'a' with this mean. How can I do it?
this is the code
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': [0, np.nan, np.nan], 'user_id': [... | [
"I think you need processing column c:\ndf['a'].fillna(df.groupby('user_id')['c'].transform('mean'), inplace=True)\ndf['a'] = df['a'].fillna(df.groupby('user_id')['c'].transform('mean'))\nprint (df)\n a user_id c\n0 0.0 1 3\n1 7.0 2 7\n2 7.0 2 7\n\n"
] | [
0
] | [] | [] | [
"fillna",
"pandas",
"python"
] | stackoverflow_0074233654_fillna_pandas_python.txt |
Q:
How to use Python functools.lru_cache (or cache) for methods
I have a class with a method that I want to cache properly, i.e. that the results are properly cleaned when the object is no longer in use. Example:
import functools
import numpy as np
class foo:
def __init__(self, dev):
self.dev = dev
... | How to use Python functools.lru_cache (or cache) for methods | I have a class with a method that I want to cache properly, i.e. that the results are properly cleaned when the object is no longer in use. Example:
import functools
import numpy as np
class foo:
def __init__(self, dev):
self.dev = dev
@functools.cache
def bar(self, len):
return np.random.... | [] | [] | [
"With just two changes, you can considerably improve your algorithm’s runtime:\n\nImport the @lru_cache decorator from the functools module.\nUse @lru_cache to decorate model().\n\nHere’s what the top of the script will look like with the two updates:\nimport functools\nfrom abc import abstractmethod, ABC\n\n\n\"\"... | [
-1
] | [
"functools",
"python"
] | stackoverflow_0074233408_functools_python.txt |
Q:
standard_init_linux.go:178: exec user process caused "exec format error"
docker started throwing this error:
standard_init_linux.go:178: exec user process caused "exec format error"
whenever I run a specific docker container with CMD or ENTRYPOINT, with no regard to any changes to the file other then removing CM... | standard_init_linux.go:178: exec user process caused "exec format error" | docker started throwing this error:
standard_init_linux.go:178: exec user process caused "exec format error"
whenever I run a specific docker container with CMD or ENTRYPOINT, with no regard to any changes to the file other then removing CMD or ENTRYPOINT. here is the docker file I have been working with which worked... | [
"I forgot to put \n#!/bin/bash\n\nat the top of the sh file, problem solved.\n",
"This can happen if you're trying to run an x86 built image on an arm64/aarch64 machine.\nYou'll need to rebuild the image using the corresponding architecture\n",
"This error could also occur if an image was built on a MacBook Pro... | [
460,
290,
151,
84,
76,
52,
20,
12,
12,
6,
5,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"bash",
"docker",
"linux",
"python"
] | stackoverflow_0042494853_bash_docker_linux_python.txt |
Q:
Structural Python Matching with variable pattern keys
As part of a larger problem, I am trying to write a function that uses pattern matching in order to extract fields from a given dictionary.
For example, given a dictionary like:
example = {
'want1': [1, 2, 3],
'want2': ['a', 'b', 'c'],
'want3': [1.1... | Structural Python Matching with variable pattern keys | As part of a larger problem, I am trying to write a function that uses pattern matching in order to extract fields from a given dictionary.
For example, given a dictionary like:
example = {
'want1': [1, 2, 3],
'want2': ['a', 'b', 'c'],
'want3': [1.1, 2.2, 3.3],
'want4': 'hello',
}
I want to write a f... | [
"def extract(field, data):\n match isinstance(value:=data.get(field,None),list):\n case True:\n return value\n return None\n\nThis is a really bad example usage of pattern matching. This can be solved by a much simpler function:\ndef extract(field, data):\n value = data.get(field,None)\n ... | [
0
] | [] | [] | [
"python",
"structural_pattern_matching"
] | stackoverflow_0074232152_python_structural_pattern_matching.txt |
Q:
Why my replace method does not work with the string [B]?
I have the following dataset called world_top_ten:
`
Most populous countries 2000 2015 2030[A]
0 China[B] 1270 1376 1416
1 India 1053 1311 1528
2 United States 283 322 356
3 Indonesia 212 258 295
4 Pakistan 136 208... | Why my replace method does not work with the string [B]? | I have the following dataset called world_top_ten:
`
Most populous countries 2000 2015 2030[A]
0 China[B] 1270 1376 1416
1 India 1053 1311 1528
2 United States 283 322 356
3 Indonesia 212 258 295
4 Pakistan 136 208 245
5 Brazil 176 206 228
6 Nigeria 123 182 263
7 Bangl... | [
"Because [] is special regex character escape it:\nworld_top_ten['Most populous countries'].str.replace(r'\\[B\\]', '', regex=True)\n\n"
] | [
1
] | [] | [] | [
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074233745_jupyter_notebook_pandas_python.txt |
Q:
Python: in dataframe, how to concatenate a column across rows (col. being list of lists)?
I have a Dataframe as shown below as dataframe1:
dataframe1
ID
PATH
ABC
[[orange, apple, kiwi, peach], [strawberry, orange, kiwi, peach]]
ABC
[[apple, plum, peach], [apple, pear, peach]]
BCD
[[blueberry, plum, peach], [pe... | Python: in dataframe, how to concatenate a column across rows (col. being list of lists)? | I have a Dataframe as shown below as dataframe1:
dataframe1
ID
PATH
ABC
[[orange, apple, kiwi, peach], [strawberry, orange, kiwi, peach]]
ABC
[[apple, plum, peach], [apple, pear, peach]]
BCD
[[blueberry, plum, peach], [pear, apple, peach]]
BCD
[[plum, apple, peach], [banana, raspberry, peach]]
I would... | [
"If im interpreting this properly you might want to look into the 'merge' function.\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html\n",
"Try:\ndf = df.groupby(\"ID\")[\"PATH\"].apply(lambda x: list(itertools.chain.from_iterable(x))).reset_index()\n\nor\ndf = df.groupby(\"ID\")[\"PATH\"].... | [
0,
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074227630_list_pandas_python.txt |
Q:
using Python 3 A byte-like object is required not a str" i have tried converting it into bytes but it still giving me the same error
import netfilterqueue
import scapy.all as scapy
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.DNSRR)... | using Python 3 A byte-like object is required not a str" i have tried converting it into bytes but it still giving me the same error | import netfilterqueue
import scapy.all as scapy
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.DNSRR):
qname = scapy_packet[scapy.DNSQR].qname
website = 'www.bing.com'
if website in qname:
... | [
"Try website = b'www.bing.com'. The b makes it a byte literal.\n",
"use website = b\"www.bing.com\" \n\nand also in here\npacket.set_payload(str(scapy_packet))\n\nchange this to\n packet.set_payload(bytes(scapy_packet))\n\n"
] | [
1,
0
] | [] | [] | [
"netfilter",
"python",
"python_3.7",
"python_3.x",
"scapy"
] | stackoverflow_0061688925_netfilter_python_python_3.7_python_3.x_scapy.txt |
Q:
How to detect redundant edge in graph networkx python?
I have a question, how can I detect and get the redundant value from graph connection? i already set the redundant graph connection in add_edges_from() like (1,2) and (1,2). But when i print list of edges, it only detected as 1 connection. Here is my example:
... | How to detect redundant edge in graph networkx python? | I have a question, how can I detect and get the redundant value from graph connection? i already set the redundant graph connection in add_edges_from() like (1,2) and (1,2). But when i print list of edges, it only detected as 1 connection. Here is my example:
test_graph = nx.Graph()
test_graph.add_edges_from([(1, 2), (... | [
"Graphs with what you call \"redundant\" edges are typically called multigraphs.\nIn networkx, you can either (1) use the MultiGraph class to keep track of all edges individually, or (2) you can count the edges and then create a weighted Graph.\n#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport netwo... | [
2
] | [] | [] | [
"edges",
"graph",
"networkx",
"nodes",
"python"
] | stackoverflow_0074230410_edges_graph_networkx_nodes_python.txt |
Q:
How do i read and store items from a csv file into 2D arrays in python?
So I've been tasked with creating a suitable 2D array to contain all of the data from a csv with data on rainfall from the whole year. In the csv file, the rows represent the weeks of the year and the columns represent the day of the week.
I'm... | How do i read and store items from a csv file into 2D arrays in python? | So I've been tasked with creating a suitable 2D array to contain all of the data from a csv with data on rainfall from the whole year. In the csv file, the rows represent the weeks of the year and the columns represent the day of the week.
I'm able to display the date I want using the following code.
import csv
data =... | [
"You could use numpy for that. It seems to me, that you have created a list of lists in data. With that you can directly create a 2D numpy-array:\nimport numpy as np\n\n\n2d_data = np.array(data)\n\nOr you could even try to directly read the file with numpy:\nimport numpy as np\n\n\n# Use the appropriate delimiter ... | [
0
] | [] | [] | [
"csv",
"multidimensional_array",
"python"
] | stackoverflow_0074233356_csv_multidimensional_array_python.txt |
Q:
Program that prompts the user to input 5 integers and outputs these integers in reverse order
I need help with this Python program.
With the input below:
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
the program must output:
Output: 54321
My code is:
n = 0
t = 1
rev = 0
... | Program that prompts the user to input 5 integers and outputs these integers in reverse order | I need help with this Python program.
With the input below:
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
the program must output:
Output: 54321
My code is:
n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a... | [
"try this:\nt = 1\nrev = \"\"\n \nwhile(t <= 5):\n n = input(\"Enter a number:\")\n t+=1\n rev = n + rev\n\nprint(rev)\n\n",
"Try:\nx = [int(input(\"Enter a number\")) for t in range(0,5)]\nprint(x[::-1])\n\n",
"There could be an easier way if you create a list and append all the values in it, then pri... | [
3,
3,
0,
0,
0
] | [] | [] | [
"integer",
"iteration",
"python",
"python_3.x",
"reverse"
] | stackoverflow_0074233774_integer_iteration_python_python_3.x_reverse.txt |
Q:
SQLAlchemy multiple foreign keys on the same column
I am working with the following database table design. The relationship is one-to-many, parent to child. So one parent (mother or father) has multiple children. I'm having issues mapping these tables because the child's column parent_id is a Foreign Key to both o... | SQLAlchemy multiple foreign keys on the same column | I am working with the following database table design. The relationship is one-to-many, parent to child. So one parent (mother or father) has multiple children. I'm having issues mapping these tables because the child's column parent_id is a Foreign Key to both of the parent tables.
class Mother(Base):
id = Column(... | [
"I think that foreign keys should bo on Child table, it would be better and more realistic model:\nclass Mother(Base): \n id = Column(Integer, primary_key=True)\n children = relationship('Child', backref='mother')\n\nclass Father(Base):\n id = Column(Integer, primary_key=True)\n children = relationsh... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074228623_python_sqlalchemy.txt |
Q:
pathlib Path `write_text` in append mode
Is there a shortcut for python pathlib.Path objects to write_text() in append mode?
The standard open() function has mode="a" to open a file for writing and appending to the file if that file exists, and a Paths .open() function seems to have the same functionality (my_pat... | pathlib Path `write_text` in append mode | Is there a shortcut for python pathlib.Path objects to write_text() in append mode?
The standard open() function has mode="a" to open a file for writing and appending to the file if that file exists, and a Paths .open() function seems to have the same functionality (my_path.open("a")).
But what about the handy .write... | [
"Not really, as you can see in the pathlib module exist 2 types of path classes:\n\npure path classes {PurePath, PurePosixPath, PureWindowsPath}\nconcrete path classes {Path, PosixPath, WindowsPath}. \n\nParameters of theses classes constructors will be just *pathsegments.\nAnd if you look at the available read/wri... | [
22,
4,
3,
1,
1,
0
] | [] | [] | [
"pathlib",
"python",
"python_3.x"
] | stackoverflow_0057296168_pathlib_python_python_3.x.txt |
Q:
Difference between 0.0.0.0 and 127.0.0.1 on Windows and Linux
I got a server running on 0.0.0.0:18830.
On windows when I trying to connect to this server with python socket
socket.connect_ex('0.0.0.0', 18830)
it returns 10049
with the following code
socket.connect_ex('127.0.0.1', 18830)
it returns 0 which means ... | Difference between 0.0.0.0 and 127.0.0.1 on Windows and Linux | I got a server running on 0.0.0.0:18830.
On windows when I trying to connect to this server with python socket
socket.connect_ex('0.0.0.0', 18830)
it returns 10049
with the following code
socket.connect_ex('127.0.0.1', 18830)
it returns 0 which means ok
However when I run the server and the two codes above on WSL Deb... | [
"127.0.0.1 is the loopback address (also known as localhost) and 0.0.0.0 is the IP address that is a non-routable meta-address used to indicate an invalid, unknown, or non-applicable destination.\n0.0.0.0 and 127.0.0.1 are easy to confuse, but let's keep remember that an address with four zeros has a few defined us... | [
1,
1
] | [] | [] | [
"linux",
"python",
"sockets",
"windows"
] | stackoverflow_0074233128_linux_python_sockets_windows.txt |
Q:
How do I use GTK4's ColumnView to replace TreeView in Python?
I'm converting a Python (3.10) application from GTK3 to GTK4, and I would like to move away from TreeView/CellRenderer usage, and try to use ColumnView instead. I've read the documentation on GTK4's new list widgets, read their blog post about them, se... | How do I use GTK4's ColumnView to replace TreeView in Python? | I'm converting a Python (3.10) application from GTK3 to GTK4, and I would like to move away from TreeView/CellRenderer usage, and try to use ColumnView instead. I've read the documentation on GTK4's new list widgets, read their blog post about them, searched for examples, and am still quite confused.
As I understand i... | [
"this doesn't perfectly answer your question for python but I made an example of a ColumnView with gtk4-rs (rust) https://github.com/gtk-rs/gtk4-rs/pull/1111\nI use ListStore.append(...) for many items (structs) and then have columnview factory functions that pick the element from the struct to display in a particu... | [
0,
0
] | [] | [] | [
"gtk4",
"python"
] | stackoverflow_0073145916_gtk4_python.txt |
Q:
Requests and Urllib3 is failing when running api get request. Can't connect to HTTPS URL because the SSL module is not available
Im using python 3.10.8 in a linux environment(RedHat 7.9 Maipo).'
After installing python 3.10.8 manually with all libraries I'm facing this error:
> [root@epnm-lab ~]# python3
> Python... | Requests and Urllib3 is failing when running api get request. Can't connect to HTTPS URL because the SSL module is not available | Im using python 3.10.8 in a linux environment(RedHat 7.9 Maipo).'
After installing python 3.10.8 manually with all libraries I'm facing this error:
> [root@epnm-lab ~]# python3
> Python 3.10.8 (main, Oct 14 2022, 02:15:05)
> [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux Type "help",
> "copyright", "credits" or "lic... | [
"Solved!\nThe solution for this error is that the python version 3.10 uses openssl version 1.1.1 and my server is using openssl 1.0.2. The openssl version 1.0.2 on python 3.10 has been deprecated. So you need to install python 3.9.x 'cause this version supports openssl 1.0.2.\nHope that helps!\n"
] | [
1
] | [] | [] | [
"linux",
"python",
"redhat"
] | stackoverflow_0074152778_linux_python_redhat.txt |
Q:
Merging two tensorflow Datasets, albeit at a different pace
I am looking for a way to merge a Dataset with another, but by drawing samples from it only occasionally.
For example, given these two Datasets
ds1 = tf.data.Dataset.range(1, 10).repeat()
ds10 = tf.data.Dataset.range(10, 100, 10).repeat()
I would like to... | Merging two tensorflow Datasets, albeit at a different pace | I am looking for a way to merge a Dataset with another, but by drawing samples from it only occasionally.
For example, given these two Datasets
ds1 = tf.data.Dataset.range(1, 10).repeat()
ds10 = tf.data.Dataset.range(10, 100, 10).repeat()
I would like to add samples from ds10 to those of ds1 but only for every two sam... | [
"You can create your own generator:\nimport tensorflow as tf\nfrom functools import partial\n\nds1_unrepeated = tf.data.Dataset.range(1, 10) # because repeat prevents element_spec\nds1_spec = ds1_unrepeated.element_spec\nds1 = ds1_unrepeated.repeat()\nds10 = tf.data.Dataset.range(10, 100, 10).repeat()\n\ndef my_me... | [
1,
1
] | [] | [] | [
"python",
"tensorflow",
"tensorflow_datasets"
] | stackoverflow_0074232597_python_tensorflow_tensorflow_datasets.txt |
Q:
Python/Excel - transpose row to column
I am trying to format a print statement to align a specific column.
Here is my dataframe:
df = pd.DataFrame({"platform":['test3','test3','test3','test4','test4','test5','test5','test5','test6','test6'],
"ripenes type":['OverRipes', 'Ripes','UnRipes','Ripes'... | Python/Excel - transpose row to column | I am trying to format a print statement to align a specific column.
Here is my dataframe:
df = pd.DataFrame({"platform":['test3','test3','test3','test4','test4','test5','test5','test5','test6','test6'],
"ripenes type":['OverRipes', 'Ripes','UnRipes','Ripes','UnRipes','OverRipes', 'Ripes','UnRipes', '... | [
"You can use the df.pivot function.\nHere is an example:\nimport pandas as pd\n\ndf = pd.DataFrame({\"platform\":['test3','test3','test3','test4','test4','test5','test5','test5','test6','test6'],\n \"ripenes type\":['OverRipes', 'Ripes','UnRipes','Ripes','UnRipes','OverRipes', 'Ripes','UnRipes', '... | [
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0074231373_excel_python.txt |
Q:
How to join table in pandas with multiple interval conditions?
I want to join 2 tables
the first one is
SCORE_BIN NAME GROUP
(0,0.5] A LOW
(0.5,1] A HIGH
(0,0.2] B LOW
(0.2,1] B HIGH
The second one is
SCORE CUST_NM
0.1 A
0.8 A
0.9 B
0.1 ... | How to join table in pandas with multiple interval conditions? | I want to join 2 tables
the first one is
SCORE_BIN NAME GROUP
(0,0.5] A LOW
(0.5,1] A HIGH
(0,0.2] B LOW
(0.2,1] B HIGH
The second one is
SCORE CUST_NM
0.1 A
0.8 A
0.9 B
0.1 B
My expected output is
SCORE CUST_NM GROUP
0.1 A ... | [
"You can reuse bins from qcut to another DataFrame and then use merge:\ndf1[\"SCORE_BIN\"] = pd.qcut(df1[\"SCORE\"], 2)\n\n##https://stackoverflow.com/a/37906403/2901002\nser, bins = pd.qcut(df1[\"SCORE\"], 2, retbins=True)\nprint(bins)\n\ndf2['SCORE_BIN'] = pd.cut(df2[\"SCORE\"], bins=bins, include_lowest=True)\n\... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074233945_dataframe_pandas_python.txt |
Q:
How do I read key asynchronously in Python for a keylogger?
So I am making a Python keylogger, but I don't know of anything to asynchronously read keys being pressed, even when the window is not in focus. I've seen event.ASCII, but nothing came up for it specifically on Google.
As the other part, how do I keep th... | How do I read key asynchronously in Python for a keylogger? | So I am making a Python keylogger, but I don't know of anything to asynchronously read keys being pressed, even when the window is not in focus. I've seen event.ASCII, but nothing came up for it specifically on Google.
As the other part, how do I keep the program running instead of running the script then quitting? I'... | [
"This is a piece of code I wrote long ago. You can use this as a reference.\nimport pyWinhook\nimport pythoncom\nimport win32console\nimport win32gui\n\nwin = win32console.GetConsoleWindow()\nwin32gui.ShowWindow(win, 0)\n\n\ndef onkeyboardevent(event):\n if event.Ascii == 5:\n exit(1)\n if event.Ascii ... | [
0
] | [] | [] | [
"asynchronous",
"keylogger",
"python"
] | stackoverflow_0030203526_asynchronous_keylogger_python.txt |
Q:
Find max values using "for loop" when I have to separate lists
I have the following lists and would like to get the maximum values for each person and create a new list using exclusively the for loop and max function. How can I do it?
persons = ['John', 'James', 'Robert']
values = [
(101, 97, 79),
(67, 85,... | Find max values using "for loop" when I have to separate lists | I have the following lists and would like to get the maximum values for each person and create a new list using exclusively the for loop and max function. How can I do it?
persons = ['John', 'James', 'Robert']
values = [
(101, 97, 79),
(67, 85, 103),
(48, 201, 105),
]
I'm looking for this ouput:
Output 1 =... | [
"for i, j in zip(persons, values):\n print(i,max(j))\n\n",
"persons = ['John', 'James', 'Robert']\nvalues = [ (101, 97, 79), \n\n (67, 85, 103),\n\n (48, 201, 105), \n\n ]\n\noutput_1 = []\noutput_2 = []\n\nfor i, j in zip(persons, values):\n output_1.append( (i, max(j)) ... | [
2,
0,
0,
0
] | [] | [] | [
"for_loop",
"list_comprehension",
"max",
"python"
] | stackoverflow_0074233934_for_loop_list_comprehension_max_python.txt |
Q:
ModuleNotFoundError: No module named 'application' [Deploying Django to AWS]
I've been trying to deploy a Django application at ElasticBeanstalk from AWS.
I have followed this tutorial probably 6 or 7 times.
tried to deploy from Linux and from windows machine in either way I end up getting:
ModuleNotFoundError: No... | ModuleNotFoundError: No module named 'application' [Deploying Django to AWS] | I've been trying to deploy a Django application at ElasticBeanstalk from AWS.
I have followed this tutorial probably 6 or 7 times.
tried to deploy from Linux and from windows machine in either way I end up getting:
ModuleNotFoundError: No module named 'application' or web: Failed to find attribute 'application' in 'app... | [
"Try\nif you are using a mac, make sure you are zipping the files,\nnot at the lop level.\nhttps://docs.aws.amazon.com/elasticbeanstalk/latest/dg/applications-sourcebundle.html\n",
"\nYou have a typo \".ebextentions\" instead of \".ebextensions\"\n\nSince you have a .gitignore I expect that you use git for your p... | [
1,
0
] | [] | [] | [
"amazon_elastic_beanstalk",
"amazon_web_services",
"django",
"python",
"python_3.x"
] | stackoverflow_0069319779_amazon_elastic_beanstalk_amazon_web_services_django_python_python_3.x.txt |
Q:
Optimize and (re)save saved-model with grappler
I've got a (TF2) saved-model full of training ops clutter and I'm trying to optimize it for inference using grappler, but I want to save it back to a TF2 saved-model subsequently (to keep the general workflow away from TF1).
I currently have:
from tensorflow.python.f... | Optimize and (re)save saved-model with grappler | I've got a (TF2) saved-model full of training ops clutter and I'm trying to optimize it for inference using grappler, but I want to save it back to a TF2 saved-model subsequently (to keep the general workflow away from TF1).
I currently have:
from tensorflow.python.framework.convert_to_constants import convert_variable... | [
"Finally got it, not ideal since I use internal (more or less) TF2 API calls, but at least TF1 compat APIs are not used at all. Here's the full code.\nimport tensorflow as tf\nfrom tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph\nfrom tensorflow.lite.python.util im... | [
1
] | [] | [] | [
"deep_learning",
"python",
"tensorflow",
"tensorflow2.0"
] | stackoverflow_0074219568_deep_learning_python_tensorflow_tensorflow2.0.txt |
Q:
Python - Django Rest Framework - Count total row from tables in the database with a single call
I just switched to python and Django-rest-framework from java spring-boot, and I have a question below
Let's say I have some tables:
class table1(CommonModel):
class table2(CommonModel):
class table3(CommonModel):
class... | Python - Django Rest Framework - Count total row from tables in the database with a single call | I just switched to python and Django-rest-framework from java spring-boot, and I have a question below
Let's say I have some tables:
class table1(CommonModel):
class table2(CommonModel):
class table3(CommonModel):
class table4(CommonModel):
....
And I have an API to return total rows in these tables:
{
"table1": 1... | [
"class TestAPIVIew(ListAPIView):\n permission_classes = [AllowAny]\n\n def get(self, request, *args, **kwargs):\n data = dict()\n installed_apps = settings.INSTALLED_APPS[5:-1]\n\n# INSTALLED_APPS are getting apps name in a array. to excludes some of the apps i have used [5:-1]\n for app ... | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"python"
] | stackoverflow_0074218303_django_django_models_django_rest_framework_python.txt |
Q:
converting Python code to Django framework
I have a standalone application on my desktop written in Python. I am using modules like Tkinter, cv2, numpy in my application. My Tkinter renders my GUI (which has a button and an image). Now my issue is that I want to make it a web application. For this purpose, I am us... | converting Python code to Django framework | I have a standalone application on my desktop written in Python. I am using modules like Tkinter, cv2, numpy in my application. My Tkinter renders my GUI (which has a button and an image). Now my issue is that I want to make it a web application. For this purpose, I am using Django framework which asks to segregate Mod... | [
"You can't. Here's the reasoning for those who'd like to understand: \n1st-- Python code is executed by it's interpreter, a program written in C. (The Python Software Foundation's Interpreter is properly called \"Cpython\" to distinguish it from third parter Interpreters that can also run Python code). Python c... | [
2,
1,
0
] | [] | [] | [
"django",
"opencv",
"python"
] | stackoverflow_0024432214_django_opencv_python.txt |
Q:
How to loop through a list of dictionary and extract those with the same 'name' and 'school' into a new list while getting their other values in it
I have this list of dictionary and I would like to get those with the same exact value of 'name' and 'school' into a new list and also getting their 'age' merged into ... | How to loop through a list of dictionary and extract those with the same 'name' and 'school' into a new list while getting their other values in it | I have this list of dictionary and I would like to get those with the same exact value of 'name' and 'school' into a new list and also getting their 'age' merged into a list as well and the rest of the dictionary that is not identical to just add into the list as per usual..
Here is an example of the list of dictionary... | [
"You could use itertools.groupby().\nExample:\nimport itertools\nfrom pprint import pprint\n\ndata = [{'name': 'Jane', 'age':12, 'school': 'SIT'}, {'name': 'John', 'age':13, 'school': 'SMU'},{'name': 'Jane', 'age':14, 'school': 'SIT'}, {'name': 'Jane', 'age':16, 'school': 'SIT'}, {'name': 'John', 'age':13, 'school'... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"list",
"loops",
"python"
] | stackoverflow_0074232771_dictionary_list_loops_python.txt |
Q:
How can I form my dataframe so that each row with same id becomes one row and the values change into columns
So i have data in the following dataframe:
id
hours1
hours2
id_2
status
timeweeks
code1
code2
code3
858
2.087e+06
105
14
1.057e+06
1
96.7143
nan
nan
0.5
505
2.08697e+06
0
28
1.057e+06
1
111.143
nan
0.5
n... | How can I form my dataframe so that each row with same id becomes one row and the values change into columns | So i have data in the following dataframe:
id
hours1
hours2
id_2
status
timeweeks
code1
code2
code3
858
2.087e+06
105
14
1.057e+06
1
96.7143
nan
nan
0.5
505
2.08697e+06
0
28
1.057e+06
1
111.143
nan
0.5
nan
245
2.08695e+06
32
431.5
1.057e+06
1
178.571
nan
nan
5
620
2.08698e+06
10
0
1.057e+06
1
103.571
nan... | [
"Use DataFrame.stack for remove misisng values after DataFrame.set_index, then create helper columns and level in MultiIndex by GroupBy.cumcount and last reshape by Series.unstack:\ncols = ['id','id_2','hours1','hours2', 'status','timeweeks']\ndf1 = df.set_index(cols).stack().to_frame('code')\n\ndf1 = df1.set_index... | [
1
] | [] | [] | [
"dataframe",
"multiple_columns",
"pandas",
"python",
"row"
] | stackoverflow_0074233400_dataframe_multiple_columns_pandas_python_row.txt |
Q:
Show Json Data from Python
How do i make Json requests to an endpoint to show the response in Json rather than show the response
i sent a POST request to a server and i am getting this as response.
D:\python>python runVacc.py
<Response [200]>
Which means its a successful request, but i want it to show both the Su... | Show Json Data from Python | How do i make Json requests to an endpoint to show the response in Json rather than show the response
i sent a POST request to a server and i am getting this as response.
D:\python>python runVacc.py
<Response [200]>
Which means its a successful request, but i want it to show both the Success as well as the Json Respon... | [
"Use print(res.content) instead.\n"
] | [
2
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074234120_json_python.txt |
Q:
Compare the values of 2 columns in pandas dataframe to fill a third column
I have a dataframe (figure). Supose that I will add more observations to my dataframe.
For this new observations (9 and 10) I only add the color, food and age columns. For the score column I want to compare with the other observations if th... | Compare the values of 2 columns in pandas dataframe to fill a third column | I have a dataframe (figure). Supose that I will add more observations to my dataframe.
For this new observations (9 and 10) I only add the color, food and age columns. For the score column I want to compare with the other observations if the column of "food" and "color" got the same label then the score value will be e... | [
"You could try something like below:\nimport pandas as pd\n\n#Shortened working data list, for demonstration purposes\ndata = [[1,'Red','Apple',70,5.0],[2,'Yellow','Pizza',90,6.0],[9,'Red','Apple', 2, None],[10,'Yellow','Pizza',2,None]]\n\n#Set up data frame\ndf = pd.DataFrame(data, columns=['Observations', 'Color'... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074233384_dataframe_pandas_python.txt |
Q:
OpenCV capturing very slowly when using higher resolutions
I read images from a webcam and find some movement data in it.
I wrote a small class which measures all the steps from reading the image, detecting movement, etc and then prints it.
Now when I just init the webcam without a particular resolution, the taken... | OpenCV capturing very slowly when using higher resolutions | I read images from a webcam and find some movement data in it.
I wrote a small class which measures all the steps from reading the image, detecting movement, etc and then prints it.
Now when I just init the webcam without a particular resolution, the taken frame has the size of 640x480. Now I wanted to increase the res... | [
"The main reason for the slow performance of vid.read() is that you are using the YUYV format, which is uncompressed and requires more bandwidth and processing power than the MJPG format, which is compressed and can handle higher resolutions faster.\nTo switch to the MJPG format, you need to add one more line to yo... | [
2
] | [] | [] | [
"opencv",
"python",
"stream",
"webcam"
] | stackoverflow_0074234070_opencv_python_stream_webcam.txt |
Q:
Web Scaping | Selenium webdriver find dynamic elements by xpath in Python
Apologies in advance if this long question seems quite basic!
Given:
search query link in a library website:
url = 'https://digi.kansalliskirjasto.fi/search?query=economic%20crisis&orderBy=RELEVANCE'
I'd like to extract all useful informati... | Web Scaping | Selenium webdriver find dynamic elements by xpath in Python | Apologies in advance if this long question seems quite basic!
Given:
search query link in a library website:
url = 'https://digi.kansalliskirjasto.fi/search?query=economic%20crisis&orderBy=RELEVANCE'
I'd like to extract all useful information for each individual search result (total 20 in 1 page) of this specific quer... | [
"This is an answer for Question#2 only since #1 and #3 (as Prophet've already said in comment) are not valid for SO.\nSince you're dealing with dynamic content find_elements is not what you need. Try to wait for required data to appear:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriv... | [
1,
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"web_scraping",
"xpath"
] | stackoverflow_0074208495_python_selenium_selenium_chromedriver_web_scraping_xpath.txt |
Q:
PyUSB 1.0: NotImplementedError: Operation not supported or unimplemented on this platform
I just began to use pyusb, and basically I'm playing with the sample code here.
I'm using Windows7 64 bit, and downloaded the zip version from https://walac.github.io/pyusb/. Backend is libusb-1.0.19 that is downloaded the w... | PyUSB 1.0: NotImplementedError: Operation not supported or unimplemented on this platform | I just began to use pyusb, and basically I'm playing with the sample code here.
I'm using Windows7 64 bit, and downloaded the zip version from https://walac.github.io/pyusb/. Backend is libusb-1.0.19 that is downloaded the windows binary from http://libusb.info/.
All of my code is:
dev = usb.core.find(idVendor=3544, i... | [
"This also happened me and the problem was that the device was used by other software or driver.\n",
"This issue is about having the right driver on W7/64-bits.\nI tried to connect and use a Microchip self-programmed card. Unfortunately, the driver provided by Microchip is not compliant with the libusb library an... | [
3,
3,
0
] | [] | [] | [
"libusb",
"libusb_1.0",
"python",
"python_2.7",
"pyusb"
] | stackoverflow_0031960314_libusb_libusb_1.0_python_python_2.7_pyusb.txt |
Q:
Module 'pygame' has no 'QUIT' member
I'm trying to create a sidescroller game in pygame and it just makes a black screen when it should make a player sprite walking across a screen which increases speed as time goes along.
When I debug in vscode it comes up with E1101:Module 'pygame' has no 'QUIT' member.
QUIT se... | Module 'pygame' has no 'QUIT' member | I'm trying to create a sidescroller game in pygame and it just makes a black screen when it should make a player sprite walking across a screen which increases speed as time goes along.
When I debug in vscode it comes up with E1101:Module 'pygame' has no 'QUIT' member.
QUIT seems to be in the event.get module so I don... | [
"As @PRMoureu said, you imported everything (including QUIT) from pygame.locals directly, so you don't need a namespace before it.\nif event.type == QUIT\n\n",
"\"E1101:Module 'pygame' has no 'QUIT' member\" is a lint error. PyLint (which VSCode runs to check your code for ['lint'](https://en.wikipedia.org/wiki/L... | [
2,
0
] | [] | [] | [
"pygame",
"python",
"python_3.x"
] | stackoverflow_0053030345_pygame_python_python_3.x.txt |
Q:
Python: Getting only one string of interest out of a series of similar strings
I am looking into this dataset: https://www.kaggle.com/datasets/stefanoleone992/rotten-tomatoes-movies-and-critic-reviews-dataset?select=rotten_tomatoes_movies.csv
I am interested in scores grouped by production companies, but some comp... | Python: Getting only one string of interest out of a series of similar strings | I am looking into this dataset: https://www.kaggle.com/datasets/stefanoleone992/rotten-tomatoes-movies-and-critic-reviews-dataset?select=rotten_tomatoes_movies.csv
I am interested in scores grouped by production companies, but some companies have subdivisions that are very similar to each other, e.g. 20th Century Fox, ... | [
"Maybe some production companies are french ones.\nAccording to Wikipedia : \"The unicode string for \\xe9 is an accented e - é\".\nYou can try to specify the encoding.\ndf = pd.read_csv('rotten_tomatoes_movies.csv', encoding='utf-8')\n\n",
"I guess I've found it.\nIt's still an encoding issue but this time relat... | [
1,
0
] | [] | [] | [
"analysis",
"python",
"string"
] | stackoverflow_0074221375_analysis_python_string.txt |
Q:
API JSON Response to CSV
I am trying to take this JSON response (It is just a sample of the response)
[
[
{
"session_id": "f02f8b6670a2811b2ee0cfd770a871f6",
"url": "https://something.bob.com/courses/10546/external_tools/44",
"context_type": "Course",
"as... | API JSON Response to CSV | I am trying to take this JSON response (It is just a sample of the response)
[
[
{
"session_id": "f02f8b6670a2811b2ee0cfd770a871f6",
"url": "https://something.bob.com/courses/10546/external_tools/44",
"context_type": "Course",
"asset_type": null,
"... | [
"actually this is a list of json.so you need to convert this list to csv by using pandas\ndf = pd.DataFrame(res) #this res is the json response\n\ncsv_data = df.to_csv(index=False)\n\n"
] | [
0
] | [] | [] | [
"csv",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0070297345_csv_pandas_python_python_3.x.txt |
Q:
import the dataset in Python with sci-kit learn for machine learning problems_dataset Winscosin breast cancer
Hello I try to import a dataset to spyder
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('breast-cancer-wisconsin.data1.csv')
X = dataset.iloc[:,0:9].values
y... | import the dataset in Python with sci-kit learn for machine learning problems_dataset Winscosin breast cancer | Hello I try to import a dataset to spyder
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('breast-cancer-wisconsin.data1.csv')
X = dataset.iloc[:,0:9].values
y= dataset.iloc[:,9].values
but when i display the X matrix in the variable explorer it says that object arrays are... | [
"Try this:\nX = dataset.drop('column_9', 1).values\ny = dataset['column_9'].values\n\nJust replace column_9 with whatever the target column's name is.\n",
"Actually in Spyder we can't see the object array. We can only see the data-frame data, but the Spyder team promised that they will provide the object array fe... | [
1,
1,
0
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn",
"sklearn_pandas",
"spyder"
] | stackoverflow_0041770813_machine_learning_python_scikit_learn_sklearn_pandas_spyder.txt |
Q:
Python SHA to hashlib
I am updating some old code and there are a lot of the long depreciated sha module calls such as:
sha.new(borne.mark).digest()[:4]
and many others among the code.
Since I am converting it to modern code, I want to assure compatibility, while using the hashlib package, but I'm not sure which ... | Python SHA to hashlib | I am updating some old code and there are a lot of the long depreciated sha module calls such as:
sha.new(borne.mark).digest()[:4]
and many others among the code.
Since I am converting it to modern code, I want to assure compatibility, while using the hashlib package, but I'm not sure which sha to use, as the oldest d... | [
"It appears the algorithm used is sha1.\nSource: python 2.5 documentation\n"
] | [
0
] | [] | [] | [
"hashlib",
"python",
"sha"
] | stackoverflow_0074233000_hashlib_python_sha.txt |
Q:
How to find the optimal bin width which will include most datapoints in Python
I'm searching for an easier solution to categorize my data. Based on two columns i'm trying to find the best combination of the two which will include most cases. For both of the two columns i've set an deviation of .25 above and below ... | How to find the optimal bin width which will include most datapoints in Python | I'm searching for an easier solution to categorize my data. Based on two columns i'm trying to find the best combination of the two which will include most cases. For both of the two columns i've set an deviation of .25 above and below the value.
To illustrate my problem you could run the following script. The script d... | [
"In order to create the dataframe df_combinations with the columns min_ and max_ for col2 and col3, one way to do it is using pandas.DataFrame as follows\ndeviation = .25\ndf_combinations = pd.DataFrame({'min_c2':df['col2'] -deviation,'max_c2':df['col2'] +deviation,\n 'min_c3':df['col3'] ... | [
1
] | [] | [] | [
"binning",
"data_preprocessing",
"grouping",
"pandas",
"python"
] | stackoverflow_0074232834_binning_data_preprocessing_grouping_pandas_python.txt |
Q:
How can I change the notation in chess-python?
I am trying to change the notation of the moves, I mean the library returns for example g1f3 and I want to change to Nf3 (algebraic notation).
I try this method but it doesn't work:
board.parse_san(move.move)
How can I do it? There is any method in the library?
A:
... | How can I change the notation in chess-python? | I am trying to change the notation of the moves, I mean the library returns for example g1f3 and I want to change to Nf3 (algebraic notation).
I try this method but it doesn't work:
board.parse_san(move.move)
How can I do it? There is any method in the library?
| [
"https://python-chess.readthedocs.io/en/latest/core.html#chess.Board.san\nHere, you can see that given a board: chess.Board and a move: chess.Move, you can get the SAN representation of your move using board.san(move), returning a str.\n"
] | [
4
] | [] | [] | [
"python",
"python_chess"
] | stackoverflow_0074234204_python_python_chess.txt |
Q:
Python: How to read in multiple CSV files fromfolder names stored in a list
I have a function "read" that I want to use to read in multiple CSVs. It looks something like this.
def read(year)
file_path = working_dir + "\\" + year + "\\mycsv.csv"
df = pd.dataframe(pd.read_csv(file_path)
return df
All th... | Python: How to read in multiple CSV files fromfolder names stored in a list | I have a function "read" that I want to use to read in multiple CSVs. It looks something like this.
def read(year)
file_path = working_dir + "\\" + year + "\\mycsv.csv"
df = pd.dataframe(pd.read_csv(file_path)
return df
All the files have the same working_dir and the same mycsv.csv names. The only differen... | [
"To the Error Message you recieved:\nIn short, the current code is trying to combine a list item with a string, likely in the line below:\nfile_path = working_dir + \"\\\\\" + year + \"\\\\mycsv.csv\"\n\nTo that end, the year value is likely being supplied to the function as a list item, instead of a single string\... | [
0
] | [] | [] | [
"arguments",
"pandas",
"python"
] | stackoverflow_0074232925_arguments_pandas_python.txt |
Q:
How to determine the purchase price if the profit percentage is known
I want to do a story problem on the following math.
A merchant sells an item at a price $210.00 and profit 5% of the price buy. Determine the purchase price the item.
The answer is like the following .
Then, I solved it with the code below.
fr... | How to determine the purchase price if the profit percentage is known | I want to do a story problem on the following math.
A merchant sells an item at a price $210.00 and profit 5% of the price buy. Determine the purchase price the item.
The answer is like the following .
Then, I solved it with the code below.
from fractions import Fraction
def purchase_price(pp, profit):
x = pp ... | [
"profit = 0.05\nsell = 210\nprint(f\"Purchase price: ${(sell/(1+profit)):.2f}\")\n\n",
"Just use python's normal fraction 100/105\nYour code should look like this\ndef purchase_price(pp, profit):\n x = pp + profit\n return x\npp = 100\nprofit = 5\na = pp + profit\na = 210 * (100/105)\nprint('${:,.2f}'.for... | [
2,
1
] | [] | [] | [
"python",
"python_fractions"
] | stackoverflow_0074234187_python_python_fractions.txt |
Q:
Convert string(without quotes) to Dict in python to loop through it
I have a string in Python which looks like this
'{NODE: {NODE_NAME:TEST_A,NODE_IDE:TEST_A_NODE},{QUEUE : {QUEUE_NAME:TEST_QUEUE,QUEUE_TYPE_CD:1}}'
I need to convert it to dict to get Node values and Queue Values
I tried eval, ast_eval and json.lo... | Convert string(without quotes) to Dict in python to loop through it | I have a string in Python which looks like this
'{NODE: {NODE_NAME:TEST_A,NODE_IDE:TEST_A_NODE},{QUEUE : {QUEUE_NAME:TEST_QUEUE,QUEUE_TYPE_CD:1}}'
I need to convert it to dict to get Node values and Queue Values
I tried eval, ast_eval and json.loads but nothing seems to work
json.loads error :
>>> a='{NODE: {NODE_NAME... | [
"What you wrote isn't a valid dict. There seems to be an extra curly brace before the second key (Queue).\nOnce you remove that extra curly brace it should be of the correct dict form.\nEach key and value should be in quotations of course (unless it's a variable that was defined beforehand).\nThis is where you're g... | [
1
] | [] | [] | [
"json",
"python",
"python_3.x",
"string"
] | stackoverflow_0074234255_json_python_python_3.x_string.txt |
Q:
How to reduce the time taken by this loop for huge csv data with 26M rows?
n_df = pd.DataFrame(columns=["Geoid", "Occupancy", "BDG_Weights", "CTS_Weights", "BI_Weights"])
for idx, row in dd.iterrows():
for token in ['SFD_', 'MFD_', 'COM_', 'IND_']:
n_df = pd.concat([n_df, pd.DataFrame([[idx, token.spl... | How to reduce the time taken by this loop for huge csv data with 26M rows? | n_df = pd.DataFrame(columns=["Geoid", "Occupancy", "BDG_Weights", "CTS_Weights", "BI_Weights"])
for idx, row in dd.iterrows():
for token in ['SFD_', 'MFD_', 'COM_', 'IND_']:
n_df = pd.concat([n_df, pd.DataFrame([[idx, token.split('_')[0], row[token+'STR_WT'], row[token+'CNT_WT'], row[token+'BI_WT']]], colu... | [
"some 'minor' improvements that you could do is to use f-strings for your string labeling e.x. token+'STR_WT' becomes f{token}STR_WT.\nyou can remove the token.split('_')[0] with token[:-1] as using dot operators are generally slower.\ncolumn_names = [\"Geoid\", \"Occupancy\", \"BDG_Weights\", \"CTS_Weights\", \"BI... | [
0
] | [] | [] | [
"csv",
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074233909_csv_data_science_dataframe_pandas_python.txt |
Q:
Celery keeps trying to connect to localhost instead of Amazon SQS
So I'm trying to setup Celery in my Django project, and using Amazon SQS as my broker. However, Celery keeps trying to find SQS on localhost for some reason.
This is my settings.py:
CELERY_BROKER_TRANSPORT = "sqs"
CELERY_BROKER_USER = env.str("DJANG... | Celery keeps trying to connect to localhost instead of Amazon SQS | So I'm trying to setup Celery in my Django project, and using Amazon SQS as my broker. However, Celery keeps trying to find SQS on localhost for some reason.
This is my settings.py:
CELERY_BROKER_TRANSPORT = "sqs"
CELERY_BROKER_USER = env.str("DJANGO_AWS_ACCESS_KEY_ID")
CELERY_BROKER_PASSWORD = env.str("DJANGO_AWS_SECR... | [
"Hey this is kind of a non issue. The way it is mounted makes it look like localhost but it actually writes to the queue.\n[2022-10-27 18:46:53,847: INFO/MainProcess] Connected to sqs://localhost//\n\nThis is a log from our prod env and everything works\ncreate a message in sqs and you will see it gets processed\n"... | [
0
] | [] | [] | [
"amazon_sqs",
"amazon_web_services",
"celery",
"django",
"python"
] | stackoverflow_0074223483_amazon_sqs_amazon_web_services_celery_django_python.txt |
Q:
python keeps rows from month (int) column when its equal to todaysdate function
Im trying to keeps the rows from a Df when the month columns (int) its equal to the todaysdate function.
i Just bring the month (int) from the todaysdate function. Heres is the code:
import time
todaysdateMes = time.strftime('%m')
toda... | python keeps rows from month (int) column when its equal to todaysdate function | Im trying to keeps the rows from a Df when the month columns (int) its equal to the todaysdate function.
i Just bring the month (int) from the todaysdate function. Heres is the code:
import time
todaysdateMes = time.strftime('%m')
todaysdateMes
And im tryin somethin like this to keeps the equalities
filtered_df = Reg_... | [
"This code worked for me if somebody need its:\nfiltered_df = Reg_10.loc[(Reg_10['First Registration Status Date'] == todaysdateMes)]\nfiltered_df\n\n"
] | [
0
] | [] | [] | [
"date",
"python",
"python_datetime"
] | stackoverflow_0074234378_date_python_python_datetime.txt |
Q:
How can I make "isinstance" on Protocols also include function signatures and data-types?
The following code defines a simple protocol and a class which almost implements that protocol. The only difference is the fact that the run() method takes an argument in the protocol, but it's not implemented that way.
Howev... | How can I make "isinstance" on Protocols also include function signatures and data-types? | The following code defines a simple protocol and a class which almost implements that protocol. The only difference is the fact that the run() method takes an argument in the protocol, but it's not implemented that way.
However, the isinstance() check returns true which was unexpected.
As I understood PEP-544 this shou... | [
"Here's the docstring for the runtime_checkable function in the typing module:\n\"\"\"Mark a protocol class as a runtime protocol.\n\nSuch protocol can be used with isinstance() and issubclass().\nRaise TypeError if applied to a non-protocol class.\nThis allows a simple-minded structural check very similar to\none ... | [
5,
0
] | [] | [] | [
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0068280688_python_python_typing_type_hinting.txt |
Q:
Convert vcf file to phylip format but getting error
Traceback (most recent call last):
File "vcf2phylip.py", line 502, in <module>
main()
File "vcf2phylip.py", line 217, in main
sample_names = extract_sample_names(args.filename)
File "vcf2phylip.py", line 73, in extract_sample_names
for line in v... | Convert vcf file to phylip format but getting error | Traceback (most recent call last):
File "vcf2phylip.py", line 502, in <module>
main()
File "vcf2phylip.py", line 217, in main
sample_names = extract_sample_names(args.filename)
File "vcf2phylip.py", line 73, in extract_sample_names
for line in vcf:
File "/home/moodley/anaconda3/lib/python3.7/codecs.... | [
"Maybe it is gzip-compressed (the byte 0x8b on position 1 hints to that). So try to rename the file to angsd_new_vcf_with_OUTGROUP.vcf.gz and try again.\n"
] | [
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0074234293_linux_python.txt |
Q:
python reads all of the csv into one column
I know it might be a very simple and repeated question, but I am quite stuck in reading dat files.
I have a dat file and I tried to read it as CSV. The dat file itself look likes this (I only paste the beginning part of this, the rest is similar to the 18th line):
#Occul... | python reads all of the csv into one column | I know it might be a very simple and repeated question, but I am quite stuck in reading dat files.
I have a dat file and I tried to read it as CSV. The dat file itself look likes this (I only paste the beginning part of this, the rest is similar to the 18th line):
#Occultation start (UTC): 2020-02-23 00:04:22
#Occultat... | [
"As stated in the Pandas documentation for read_csv, the sep parameter is the CSV delimiter, i.e. the character used to delimit each column. In your case, each column seems to be delimited by tabs or multiple spaces. So, the following should do (untested):\nimport pandas as pd\ndf = pd.read_csv('newfile.csv',sep='\... | [
1
] | [] | [] | [
"csv",
"dataframe",
"python"
] | stackoverflow_0074234166_csv_dataframe_python.txt |
Q:
How to use stdin when stdin is redirected?
I am trying to make a CLI interface for lichess using lichess-bot
link: https://github.com/ShailChoksi/lichess-bot
Moves are made by making a class that extends MinimalEngine and giving it a search method which returns a move to make.
For example this works and I tested i... | How to use stdin when stdin is redirected? | I am trying to make a CLI interface for lichess using lichess-bot
link: https://github.com/ShailChoksi/lichess-bot
Moves are made by making a class that extends MinimalEngine and giving it a search method which returns a move to make.
For example this works and I tested it on lichess, it makes a random legal move.
clas... | [
"Try this :\nclass RandomMove(ExampleEngine):\n def search(self, board, *args):\n mv = input(\"Give me a move\")\n return PlayResult(chess.Move.from_uci(mv), None)\n\nActually your function has to return a PlayResult(chess.Move) type.\n"
] | [
0
] | [] | [] | [
"io",
"lichess",
"python"
] | stackoverflow_0073956272_io_lichess_python.txt |
Q:
Autostart and automatically restart Python Script Raspberry Pi
I know how to autostart a python script (or so I thought). But I want a programm or something, if my python script is not running anymore, it should start the script again. Has anyone a idea how to do this?
Edit:
I tried running it as a service but tha... | Autostart and automatically restart Python Script Raspberry Pi | I know how to autostart a python script (or so I thought). But I want a programm or something, if my python script is not running anymore, it should start the script again. Has anyone a idea how to do this?
Edit:
I tried running it as a service but that didnt work.
import bluetooth
import pygame
pygame.mixer.init()
ser... | [
"You can search more about how a python script can perform as a service or daemon. There are many solutions in this link:\nHow to make a Python script run like a service or daemon in Linux\nBetween all solutions, I prefer 3 of them (I'm not very familiar with raspberry-pi, so check compatibility):\n\nCronjob: You c... | [
1,
0
] | [] | [] | [
"autostart",
"linux",
"python"
] | stackoverflow_0074134770_autostart_linux_python.txt |
Q:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0 when deploying to Heroku
I tried to deploy my simple django project on heroku, but i couldn't understand how to solve this problem
This is the git push heroku master
remote: Traceback (most recent call last):
remote: File "/tmp/codon/tmp/buil... | UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0 when deploying to Heroku | I tried to deploy my simple django project on heroku, but i couldn't understand how to solve this problem
This is the git push heroku master
remote: Traceback (most recent call last):
remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module>
remote: ... | [
"That entire traceback is inside these parentheses: () is not available for this stack. That is the message shown when you request a Python runtime that isn't available. In this case, it looks like your runtime.txt can't even be read due to an unexpected encoding.\nDelete it, then create a new file containing somet... | [
2,
0,
0
] | [] | [] | [
"django",
"django_deployment",
"heroku",
"python",
"web_deployment"
] | stackoverflow_0071095069_django_django_deployment_heroku_python_web_deployment.txt |
Q:
Python: List comprehension to make a list of name with 'i' in the 3rd character from another list
I have a list of city names alphabetically sorted as 'str' and I want to make another new list taking those city names with 'i' as his 3rd character using list comprehension.
I've tried so many things, but the most in... | Python: List comprehension to make a list of name with 'i' in the 3rd character from another list | I have a list of city names alphabetically sorted as 'str' and I want to make another new list taking those city names with 'i' as his 3rd character using list comprehension.
I've tried so many things, but the most intuitive for me is:
`new_list = [word for word in old_list if word[2] == 'i']
And I dont know why, but ... | [
"Some of your words have two characters. You should only apply this rule to words of three characters or more.\ndo:\nnew_list = [word for word in old_list if len(word) >= 3 and word[2] == 'i']\n\n"
] | [
2
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0074234613_list_list_comprehension_python.txt |
Q:
If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file?
I've written some Python code that fetches a zip file from the web and into a string:
In [1]: zip_contents[0:5]
Out[1]: 'PK\x03\x04\x14'
I see there's a zipfile library, but I'm having trouble finding a funct... | If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file? | I've written some Python code that fetches a zip file from the web and into a string:
In [1]: zip_contents[0:5]
Out[1]: 'PK\x03\x04\x14'
I see there's a zipfile library, but I'm having trouble finding a function in it that I can just pass a bunch of raw zip data. It seems to want to read it from a file.
Do I really ne... | [
"zipfile.ZipFile accepts any file-like object, so you can use StringIO (2.x) or BytesIO (3.x):\ntry:\n from cStringIO import StringIO\nexcept:\n from StringIO import StringIO\nimport zipfile\n\nfp = StringIO('PK\\x03\\x04\\x14')\nzfp = zipfile.ZipFile(fp, \"r\")\n\n",
"Wrap your string in a cStringIO object. I... | [
32,
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0001313845_python.txt |
Q:
Can I make the checkbutton already checked when I open the window in tkinter menubar in Python?
I was trying to make a application by tkinter, and I wanted to make a checkbutton in menubar. However, I don't know how to make the checkbutton already checked when I run the code.
Here's my code
import tkinter as tk
de... | Can I make the checkbutton already checked when I open the window in tkinter menubar in Python? | I was trying to make a application by tkinter, and I wanted to make a checkbutton in menubar. However, I don't know how to make the checkbutton already checked when I run the code.
Here's my code
import tkinter as tk
def func():
#some code here
var = tk.BooleanVar
win = tk.Tk()
menubar = tk.Menu(win)
optmenu = tk.M... | [
"use this code below:\nimport tkinter as tk\ndef func():\n pass\n #some code here\n\nwin = tk.Tk()\nvar = tk.StringVar(win,'on')\nmenubar = tk.Menu(win)\noptmenu = tk.Menu(menubar, tearoff=0)\nmenubar.add_cascade(label='Options', menu=optmenu)\noptmenu.add_checkbutton(label='xyz', variable=var, onvalue='on', ... | [
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_menu"
] | stackoverflow_0074233452_python_tkinter_tkinter_menu.txt |
Q:
Using Python to start shell but wont interrupt original script
So I have a "master" python script which should be able to execute different shell scripts and not get stuck in the shell loops.
import socket
import subprocess
UDP_IP = "192.168.50.3"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, # Internet
... | Using Python to start shell but wont interrupt original script | So I have a "master" python script which should be able to execute different shell scripts and not get stuck in the shell loops.
import socket
import subprocess
UDP_IP = "192.168.50.3"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PO... | [
"I used subprocess.call. But if you take subprocess.probe it works without a problem.\n"
] | [
-1
] | [] | [] | [
"linux",
"python",
"raspberry_pi",
"shell"
] | stackoverflow_0074196130_linux_python_raspberry_pi_shell.txt |
Q:
Why am I not getting desired output in this code
I want to write a code for this question:
write a code which creates a new number 'n2' which consists reverse order of digits of a number 'n' which divides it without any remainder for example if input is 122
it will print 221 because 1,2,2 can divide 122 without a... | Why am I not getting desired output in this code | I want to write a code for this question:
write a code which creates a new number 'n2' which consists reverse order of digits of a number 'n' which divides it without any remainder for example if input is 122
it will print 221 because 1,2,2 can divide 122 without any remainder another example is 172336 here 1,2,3,3,6 ... | [
"This should do the Trick\nnum = input()\nnew_num = \"\"\n\nfor i in num:\n\n if int(num)%int(i) == 0:\n new_num += i\n\nprint(new_num[::-1])\n\n",
"The reason why you are not getting the desired output in this code is because of several logical and syntactical errors in your code. Here are some of them... | [
0,
0,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074233503_for_loop_python.txt |
Q:
Sum specific section of column within list of data frames iterative (Python)
I have list of dfs (in the code below named "Input") which can vary in its length (regarding the amount of dfs) and I want to sum specific sections of each column which refers to the year in the first column of each df. In the end I want ... | Sum specific section of column within list of data frames iterative (Python) | I have list of dfs (in the code below named "Input") which can vary in its length (regarding the amount of dfs) and I want to sum specific sections of each column which refers to the year in the first column of each df. In the end I want my code to give me back the exact same list of dfs but with the summed values in e... | [
"I you're looking for an equivalent to SumIf, take a look at groupby operations.\nYou also probably want to define your dataframe with column names; pd.concat is typically used if you're operating with already existing dataframes.\nIt is not clear what difference you expect between the dataframes as all inputs (and... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074234467_dataframe_pandas_python.txt |
Q:
strstr() alternative for bash
I need to search a string for a substring, if the substring is found print the string upto the end of the substring.i.e
str="this is a long string"
substring="long"
expected="this is a long"
I have tried bash string manipulation and failed. Tried to use an awk command, but I can't ge... | strstr() alternative for bash | I need to search a string for a substring, if the substring is found print the string upto the end of the substring.i.e
str="this is a long string"
substring="long"
expected="this is a long"
I have tried bash string manipulation and failed. Tried to use an awk command, but I can't get it right.
This works if substrin... | [
"If you looked for bash only solution, one of the options would be:\nsfx=\"${str#*${substring}}\"\nexpected=\"${str%\"${sfx}\"}\"\n\nWhich uses prefix removal (of anything + $substring) to determine the trailing part. And then uses suffix removal to trim that from $str yielding your expected value.\nSince you seem ... | [
0,
0,
0
] | [] | [] | [
"awk",
"bash",
"python"
] | stackoverflow_0074233022_awk_bash_python.txt |
Q:
System reboot and shut-down from flask app inside docker
I have an application that is now working on Ubuntu, but eventually it should work on Raspberry Pi. Whole app is turn on with docker-compose up. There are three containers inside it, one of it is Flask Api written in Python. Now I need to add two endpoints f... | System reboot and shut-down from flask app inside docker | I have an application that is now working on Ubuntu, but eventually it should work on Raspberry Pi. Whole app is turn on with docker-compose up. There are three containers inside it, one of it is Flask Api written in Python. Now I need to add two endpoints for my Flask Api. One for system shutdown and one for system re... | [
"On Debian based systems (assuming you are running raspbian on your raspberry pi) shutdown and reboot are just symlinks to systemctl.\nSo you need to be able to run systemctl commands on the host from within docker. This can be achieved with a few volume mounts. Here is an example snippet for the docker-compose fil... | [
0
] | [] | [] | [
"docker",
"docker_compose",
"python",
"raspberry_pi",
"ubuntu"
] | stackoverflow_0074231372_docker_docker_compose_python_raspberry_pi_ubuntu.txt |
Q:
is there anyway to run .py in another pc with no python installation package (PIP)
I am newbie at code I made a shutdown that will run music and it will perfect shutdown with the music
but the problem is my friend want to use it but he dont want to use PIP install (i dont know why)
and is there anyway to Run .py i... | is there anyway to run .py in another pc with no python installation package (PIP) | I am newbie at code I made a shutdown that will run music and it will perfect shutdown with the music
but the problem is my friend want to use it but he dont want to use PIP install (i dont know why)
and is there anyway to Run .py in another pc with no PIP or is there anyway to run without PIP
import os
import time
im... | [
"you can convert the application to an executable using Pyinstaller, to run without installing python or pip.\na good GUI interface for it is implemented in auto-py-to-exe, but it is good for a one-time conversion, not for continuous development.\nnote that he has to have powershell installed on his pc to run your ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074234689_python.txt |
Q:
JSON edit in Python
I have a JSON file like this:
{
"Location":true,
"adddress":[
{
"street1":" 1 58 4 16"
},
{
"street2":" 3 76 57 12"
}
{
"street3:":....
}
...
{
"streetn":...
}
]
}
I want to add 10 to the last data... | JSON edit in Python | I have a JSON file like this:
{
"Location":true,
"adddress":[
{
"street1":" 1 58 4 16"
},
{
"street2":" 3 76 57 12"
}
{
"street3:":....
}
...
{
"streetn":...
}
]
}
I want to add 10 to the last data of street1, street2 ....... | [
"Assuming that the data is stored in the variable json\njson = { \"Location\": True, \"adddress\": [ { \"street1\": \" 1 58 4 16\" }, { \"sttreet2\": \" 3 76 57 12\" }, ] }\n\nAs the names are different (street1, sttreet2), there are various approaches.\nOne, that one would be able to use for more cases, would be a... | [
1,
1,
1,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074233536_dataframe_pandas_python_python_3.x.txt |
Q:
Selenium webdriver can't find visible element
I have a problem with finding element on a webpage. It's a popup window with a confirmation [NO]/[YES]. Selenium can find a parent of a buttons but not a button itself.
Popup window view
HTML block of code:
<div tabindex="-1" role="alertdialog" style="position: fixed;... | Selenium webdriver can't find visible element | I have a problem with finding element on a webpage. It's a popup window with a confirmation [NO]/[YES]. Selenium can find a parent of a buttons but not a button itself.
Popup window view
HTML block of code:
<div tabindex="-1" role="alertdialog" style="position: fixed; height: auto; width: 300px; top: 188.5px; left: 8... | [
"As you said that it is a popup window, it is very likely that the button is in an iFrame. You have to wait until the iFrame loads and then search the element again.\nLuckily, selenium has a built in function for dealing with iFrames:\nyour_button = WebDriverWait(driver, \n20).until(EC.frame_to_be_available_and_swi... | [
0
] | [] | [] | [
"automated_tests",
"python",
"selenium_webdriver",
"selenium_webdriver_python"
] | stackoverflow_0074234562_automated_tests_python_selenium_webdriver_selenium_webdriver_python.txt |
Q:
Django function view rewriting to Class View ListView problem with Tag
Im trying to rewrite my whole app from function views to class views.
Right now Im struggle with Tag.
This how its looks before
views.py
def tagged(request, slug):
tag = get_object_or_404(Tag, slug=slug)
articles = Article.objects.filte... | Django function view rewriting to Class View ListView problem with Tag | Im trying to rewrite my whole app from function views to class views.
Right now Im struggle with Tag.
This how its looks before
views.py
def tagged(request, slug):
tag = get_object_or_404(Tag, slug=slug)
articles = Article.objects.filter(tag=tag)
paginator = Paginator(articles, 5)
page_number = request... | [
"You can override get_queryset method to filter Article. For example:\nclass Tagged(ListView):\n model = Article\n paginate_by = 5\n\n def get_queryset(self):\n tag = get_object_or_404(Tag, slug = self.kwargs['slug'])\n return super().get_queryset().filter(tag=tag)\n\n"
] | [
1
] | [] | [] | [
"class",
"django",
"listview",
"python",
"tags"
] | stackoverflow_0074234520_class_django_listview_python_tags.txt |
Q:
Trying to print out a dictionary with index numbers
Hiya I am trying to print out a dictionary so it ends up looking like this
-------- view contacts --------
1 Stish 123
2 Rita 321
I have got so far as to print it like this
-------- view contacts --------
Stish 123
... | Trying to print out a dictionary with index numbers | Hiya I am trying to print out a dictionary so it ends up looking like this
-------- view contacts --------
1 Stish 123
2 Rita 321
I have got so far as to print it like this
-------- view contacts --------
Stish 123
Rita 321
But I am unsure as to how I could g... | [
"This will do what you want:\ndef viewcontacts(contacts):\n print(\"-------- view contacts --------\")\n for ix, (key, value) in enumerate(contacts.items()):\n print(\"{:3} {:10} {:8}\".format(ix+1, key, value))\n\nThis produces the following:\n-------- view contacts --------\n 1 Stish ... | [
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074234706_dictionary_python.txt |
Q:
Compare 2 numpy arrays get positional difference
So i have two arrays as shown in the example below:
import os
import numpy as np
tiA = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]) * 1000
tiB = np.array([0.1,0.2,0.4,0.5,0.6,0.7,0.8,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2... | Compare 2 numpy arrays get positional difference | So i have two arrays as shown in the example below:
import os
import numpy as np
tiA = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]) * 1000
tiB = np.array([0.1,0.2,0.4,0.5,0.6,0.7,0.8,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]) * 1000
res = [idx for idx, elem in enumerate(tiB)
... | [
"Your code was already a good start, but you need to check if the element is not in the other list and not if the elements at the same position are equal.\nimport numpy as np\n\n\ntiA = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2]) * 1000\ntiB = np.array([0.1,0.2,0.4,0.5,0.... | [
0
] | [] | [] | [
"indexing",
"multidimensional_array",
"numpy_ndarray",
"python"
] | stackoverflow_0074225007_indexing_multidimensional_array_numpy_ndarray_python.txt |
Q:
Flask add custom background task
I am trying to create a flask application that has a background task that runs every 10 mins.
I found this module: https://medium.com/greedygame-engineering/an-elegant-way-to-run-periodic-tasks-in-python-61b7c477b679
So I added it to my project:
poetry add timeloop
I have created ... | Flask add custom background task | I am trying to create a flask application that has a background task that runs every 10 mins.
I found this module: https://medium.com/greedygame-engineering/an-elegant-way-to-run-periodic-tasks-in-python-61b7c477b679
So I added it to my project:
poetry add timeloop
I have created the hierachy using Flasky code example... | [
"In the end the solution was something like this:\nI created a background tasks class that accepts the current app and the timeloop object who stores jobs.\nhttps://github.com/Ruggiero-Santo/timeloop\n from app.models import timeloop ... | [
1
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074204050_flask_python.txt |
Q:
ModuleNotFoundError when trying import class from module
I have the following project structure:
└──my_project
└──package
└──subpackage
├──containers.py
├──dbase.py
└──main.py
In "dbase.py" methods for interacting with database, in "main.py" API methods.
And following imports i... | ModuleNotFoundError when trying import class from module | I have the following project structure:
└──my_project
└──package
└──subpackage
├──containers.py
├──dbase.py
└──main.py
In "dbase.py" methods for interacting with database, in "main.py" API methods.
And following imports in apps:
#package/main
from subpackage.dbase import module1
fro... | [
"Problem is in project structure. I change it to:\n└──my_project\n └──package\n ├──subpackage\n | ├──containers.py\n | └──dbase.py\n └──main.py\n\nAnd there are no problems with imports\n"
] | [
0
] | [] | [] | [
"import",
"importerror",
"module",
"python",
"uvicorn"
] | stackoverflow_0074194153_import_importerror_module_python_uvicorn.txt |
Q:
pandas.Series.apply return None but does change the dataframe correctly
Here is the problem described with an example:
My pandas.Series looks like this:
>>> epitope_charge_detail
PyDev console: starting.
Index
1 {56PD_DQ, 185T_DQ, 45EV_DQ, 167H_DQ, rq26Y, 55...
2 {66DR_DQ, 3P_DQ, 66D_DQ, 86G_DR, rq57S,... | pandas.Series.apply return None but does change the dataframe correctly | Here is the problem described with an example:
My pandas.Series looks like this:
>>> epitope_charge_detail
PyDev console: starting.
Index
1 {56PD_DQ, 185T_DQ, 45EV_DQ, 167H_DQ, rq26Y, 55...
2 {66DR_DQ, 3P_DQ, 66D_DQ, 86G_DR, rq57S, 57S_DR...
3 {56PS_DQ, 185I_DQ, rqp57A, rq57S, 13GM_DQ, 56P...
5 ... | [
"Because set.add working inplace, None is expected. Here are alternatives:\nepitope_charge_detail.apply(lambda set_: set_.union({2}))\nepitope_charge_detail.apply(lambda set_: set_ | {2})\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074234931_pandas_python.txt |
Q:
How can i fix this if statement? My last condition seems to break it but I'm not sure why
ip_address = input().split(".")
if ip_address[0] >= 0 and ip_address[0].isnumeric() and ip_address[0] <=255:
print("Valid first byte")
else:
print("Invalid first byte")
In this code, when I add my final condition of... | How can i fix this if statement? My last condition seems to break it but I'm not sure why | ip_address = input().split(".")
if ip_address[0] >= 0 and ip_address[0].isnumeric() and ip_address[0] <=255:
print("Valid first byte")
else:
print("Invalid first byte")
In this code, when I add my final condition of ip_address[0] <=255 I always get my byte as invalid even though it would technically fit those... | [
"The value returned by input() is always a string. When you use .split('.') you then get a list of strings.\nTo test the range of the number you will need to convert it to int first, but even before that you can use the numeric check:\nip_address = input().split(\".\")\n\nif ip_address[0].isnumeric() and (0 <= int(... | [
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074234330_python.txt |
Q:
Pydantic dynamic model creation with json description attribute
When pydantic model is created using class definition, the "description" attribute can be added to the JSON schema by adding a class docstring:
class account_kind(str, Enum):
"""Account kind enum."""
regular = "r"
premium = "p"
yields
"ac... | Pydantic dynamic model creation with json description attribute | When pydantic model is created using class definition, the "description" attribute can be added to the JSON schema by adding a class docstring:
class account_kind(str, Enum):
"""Account kind enum."""
regular = "r"
premium = "p"
yields
"account_kind": {
"title": "account_kind",
"description": "Account k... | [
"Apparently, the most straightforward option is to add the docstring explicitly:\ncompany = create_model(\"company\", **company_attributes)\ncompany.__doc__ = \"Company description.\"\n\n"
] | [
0
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074234979_pydantic_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.