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:
Replacing the last row value of a specific column value
I have a dataframe df which looks something like this:
key
id
x
0.6
x
0.5
x
0.43
x
0.56
y
13
y
14
y
0.4
y
0.1
I'd like to replace the Last value for every key value with 0, so that the df looks like this:
key
id
x
0.6
x
0.5
x
0.43
x
0
y
13
y
... | Replacing the last row value of a specific column value | I have a dataframe df which looks something like this:
key
id
x
0.6
x
0.5
x
0.43
x
0.56
y
13
y
14
y
0.4
y
0.1
I'd like to replace the Last value for every key value with 0, so that the df looks like this:
key
id
x
0.6
x
0.5
x
0.43
x
0
y
13
y
14
y
0.4
y
0
I've tried th... | [
"Use Series.duplicated for get last value per key and set 0 in DataFrame.loc:\ndf.loc[~df['key'].duplicated(keep='last'), 'id'] = 0\n\nprint (df)\n key id\n0 x 0.60\n1 x 0.50\n2 x 0.43\n3 x 0.00\n4 y 13.00\n5 y 14.00\n6 y 0.40\n7 y 0.00\n\nHow it working:\nprint (df.assign(mask=df... | [
3,
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074532302_pandas_python.txt |
Q:
I have an interval of integers that comprises some inner intervals. Given these intervals I want to compute a list including the intervals between
Inner intervals are always inside the global one.
All intervals are integer, left-closed, right-open intervals.
Let's take this example.
The "global" interval is [0, 22... | I have an interval of integers that comprises some inner intervals. Given these intervals I want to compute a list including the intervals between | Inner intervals are always inside the global one.
All intervals are integer, left-closed, right-open intervals.
Let's take this example.
The "global" interval is [0, 22[.
"Inner" intervals are [3, 6[ and [12, 15[.
For this example I expect :
[0, 3[ U [3, 6[ U [6, 12[ U [12, 15[ U [15, 22[
I've tried to define a functio... | [
"Yes you have to iterate over your spans but take care of maintaining a position to correctly fill the spaces between.\nfrom typing import Generator\n\ndef allspans(r, spans) -> Generator:\n pos = 0\n for lower, upper in spans:\n if pos < lower:\n yield pos, lower\n yield lower, upper... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074531960_python.txt |
Q:
Python - Summing values and number of duplicates
I have csv file looking like this: part of the data.
X and Y are my coordinates of pixel.
I need to filter column ADC only for TDC values (in this column are also 0 values), and after this I need to sum up the energy value for every unique value of pixel, so for eve... | Python - Summing values and number of duplicates | I have csv file looking like this: part of the data.
X and Y are my coordinates of pixel.
I need to filter column ADC only for TDC values (in this column are also 0 values), and after this I need to sum up the energy value for every unique value of pixel, so for every x=0 y=0, x=0 y=1, x=0 y=2... until x=127 y=127. And... | [
"The following StackOverflow question and answers might help you out:\nGroup dataframe and get sum AND count?\nBut here is some code for your case which might be useful, too:\n# import the pandas package, for doing data analysis and manipulation\nimport pandas as pd\n\n# create a dummy dataframe using data of the t... | [
0
] | [] | [] | [
"data_analysis",
"duplicates",
"python",
"sum"
] | stackoverflow_0074532074_data_analysis_duplicates_python_sum.txt |
Q:
Is it possible to access keyword arguments passed to a Field in a Pydantic BaseModel?
I need to access my_key in a Pydantic Field, as shown below:
class MyModel(BaseModel):
x: str = Field(default=None, my_key=7)
def print_field_objects(self):
for obj in self.something_something: # What do I use... | Is it possible to access keyword arguments passed to a Field in a Pydantic BaseModel? | I need to access my_key in a Pydantic Field, as shown below:
class MyModel(BaseModel):
x: str = Field(default=None, my_key=7)
def print_field_objects(self):
for obj in self.something_something: # What do I use here
print(obj.my_key) # ... so that i can use my_key?
I tri... | [
"Field doesn't take arbitrary arguments, what exactly are you trying to achieve, perhaps there's a more appropriate solution.\nPer your other question, x is a class attribute, whose definition can be found in self.__class__.__fields__, while its instance value can be found by calling self.x\n",
"You can generate ... | [
2,
1
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074525003_pydantic_python.txt |
Q:
Convert data into same unit in a dataframe
enter image description here
there are different unit for size : like k for 1,000, M for mega. I want to convert all data into same unit - bytes
may i know how to make it?
The expected result is update the size column into bytes like 9k will be 9,000
A:
def convert_unit... | Convert data into same unit in a dataframe | enter image description here
there are different unit for size : like k for 1,000, M for mega. I want to convert all data into same unit - bytes
may i know how to make it?
The expected result is update the size column into bytes like 9k will be 9,000
| [
"def convert_unit(value):\n if value in \"kb\":\n #convert to bytes \n return bytes\n elif value in \"mb\":\n # convert to bytes\n return bytes\n\n# the above function is just an example\n\ndf['column'].map(convert_unit)\n\nYou can map all the column values using the function.... | [
0,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074532217_dataframe_python.txt |
Q:
pyinstaller doesn't change python executable window icon
I am trying to change the default python icon in my executable using pyinstaller. I'm trying this on Windows 10 and the GUI framework is pyqt5.
I have only managed to change the icon of the application (as seen in a file) but not the icons when you open the ... | pyinstaller doesn't change python executable window icon | I am trying to change the default python icon in my executable using pyinstaller. I'm trying this on Windows 10 and the GUI framework is pyqt5.
I have only managed to change the icon of the application (as seen in a file) but not the icons when you open the application (on the app's window).
These are the commands I us... | [
"After Alexander's comment, I found this answer that explains how to fix this. Basicaly you need to compile the image with the code.\nnew pyinstaller command would look like this (after following the answer linked):\n\npyinstaller --onefile -w --add-data \"favicon.ico;.\" --icon=\"favicon.ico\"\n--paths=<C:\\Users\... | [
0
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0074517925_pyinstaller_python.txt |
Q:
How to run python function in laravel with symfony process?
I have a python function which returns string data, code runs fine after run
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="db_absensi"
)
mycursor = mydb.cursor()
def example(... | How to run python function in laravel with symfony process? | I have a python function which returns string data, code runs fine after run
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="db_absensi"
)
mycursor = mydb.cursor()
def example():
mycursor.execute("SELECT * FROM examples)
data = mycu... | [
"For your first python script I would suggest you to simply recreate that mysql select within php.\nFor def video_feed: Like Christoph mentioned in the comments, this return value looks like a http response. So you mixing something up. Probably simply return face_recognition() as json and use it with python process... | [
0
] | [] | [] | [
"laravel",
"php",
"python",
"symfony_process"
] | stackoverflow_0074528415_laravel_php_python_symfony_process.txt |
Q:
manipulate tuple into a list of tuples
I have the following variable for class label in my dataset:
y = np.array([3, 3, 3, 2, 3, 1, 3, 2, 3, 3, 3, 2, 2, 3, 2])
To determine the number of each class, I do:
np.unique(y, return_counts=True)
(array([1, 2, 3]), array([1, 5, 9]))
How then do I manipulate this into a ... | manipulate tuple into a list of tuples | I have the following variable for class label in my dataset:
y = np.array([3, 3, 3, 2, 3, 1, 3, 2, 3, 3, 3, 2, 2, 3, 2])
To determine the number of each class, I do:
np.unique(y, return_counts=True)
(array([1, 2, 3]), array([1, 5, 9]))
How then do I manipulate this into a list of tuples for (label, n_samples)? So th... | [
"If you want a simple list, use zip:\nout = list(zip(*np.unique(y, return_counts=True)))\n\nOutput: [(1, 1), (2, 5), (3, 9)]\nAlternatively, you can create an array with:\nnp.vstack(np.unique(y, return_counts=True)).T\n\nOutput:\narray([[1, 1],\n [2, 5],\n [3, 9]])\n\n",
"list_1 = ['a', 'b', 'c']\nlis... | [
2,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074532304_numpy_python.txt |
Q:
ModuleNotFoundError while using geodesic in udf pyspark function
We have pyspark dataframe like:
df = spark.createDataFrame([(['target'], [2], [2], [3], [3]), (['NJ'],[3],[3], [4], [4]), (['target', 'target'],[4,5], [4,5], [6,7], [6,7]), (['CA'],[5],[5], [6], [6]), ], ('group_name', 'long', 'lat','com_long','com_l... | ModuleNotFoundError while using geodesic in udf pyspark function | We have pyspark dataframe like:
df = spark.createDataFrame([(['target'], [2], [2], [3], [3]), (['NJ'],[3],[3], [4], [4]), (['target', 'target'],[4,5], [4,5], [6,7], [6,7]), (['CA'],[5],[5], [6], [6]), ], ('group_name', 'long', 'lat','com_long','com_lat'))
Schema
We want to extract the data at the position of target an... | [
"The problem is with the use of the nodes. The library is not installed in the node. Using a udf does not use sparklogik but python and would need the library on each node.\n-> If possible, do not use a udf but a pyspark/spark native function.\ndef calc_distance(df, suffix, lat1, lat2, lon1, lon2):\n#Haversine form... | [
0
] | [] | [] | [
"geopy",
"module",
"pyspark",
"python"
] | stackoverflow_0074521514_geopy_module_pyspark_python.txt |
Q:
Create a matrix using a certain vector in Python
I have this vector m = [1,0.8,0.6,0.4,0.2,0] and I have to create the following matrix in Python:
I create a matrix of zeros and a double
mm = np.zeros((6, 6))
for j in list(range(0,6,1)):
for i in list(range(0,6,1)):
ind = abs(i-j)
m[j,i] = mm... | Create a matrix using a certain vector in Python | I have this vector m = [1,0.8,0.6,0.4,0.2,0] and I have to create the following matrix in Python:
I create a matrix of zeros and a double
mm = np.zeros((6, 6))
for j in list(range(0,6,1)):
for i in list(range(0,6,1)):
ind = abs(i-j)
m[j,i] = mm[ind]
But, I got the following output:
array([[1. , 0... | [
"This could be written by comprehension if you do not want to use numpy,\n[m[i::-1] + m[1:len(m)-i] for i in range(len(m))]\n\n",
"Here is a way to implement what you want with only numpy functions, without loops (m is your numpy array):\nx = np.tile(np.hstack([np.flip(m[1:]), m]), (m.size, 1))\nrows, column_ind... | [
1,
1
] | [] | [] | [
"matrix",
"python",
"vector"
] | stackoverflow_0074531389_matrix_python_vector.txt |
Q:
ValueError: Could not interpret value for parameter
load "bmi.csv" into the Dataframe and create a scatter plot of the data using
relplot() with height on x-axis and weight on y-axis and color the plot
points based on Gender and vary the size of the points by BMI index.
My code is:
import pandas as pd
import seabo... | ValueError: Could not interpret value for parameter | load "bmi.csv" into the Dataframe and create a scatter plot of the data using
relplot() with height on x-axis and weight on y-axis and color the plot
points based on Gender and vary the size of the points by BMI index.
My code is:
import pandas as pd
import seaborn as sns
df = pd.read_csv('bmi.csv')
BMI = pd.DataFrame... | [
"Besides the error, why are you constructing a dataframe from a dataframe and also you're not using it ? I'm talking about BMI here :\ndf = pd.read_csv('bmi.csv')\nBMI = pd.DataFrame(df)\n\nAnd regarding the error, this one has occured because Height is not one of the columns of df. I suggest you to check the conte... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"relplot",
"seaborn"
] | stackoverflow_0074531969_dataframe_pandas_python_relplot_seaborn.txt |
Q:
Knapsack with SPECIFIC AMOUNT of items from different groups
So this is a variation of the Knapsack Problem I came with the other day.
It is like a 0-1 Knapsack Problem where there are multiple groups and each item belongs to only one group. The goal is to maximize the profits subject to the constraints. In this c... | Knapsack with SPECIFIC AMOUNT of items from different groups | So this is a variation of the Knapsack Problem I came with the other day.
It is like a 0-1 Knapsack Problem where there are multiple groups and each item belongs to only one group. The goal is to maximize the profits subject to the constraints. In this case, a fixed number of items from each group have to be chosen for... | [
"Full code also in: https://github.com/pabloroldan98/knapsack-football-formations\nExplanation after the code.\nThis code is for an example where you have a Fantasy League with a playersDB where each player has price (weight), points (value) and position (group); there is a list of possible_formations (group variat... | [
0
] | [] | [] | [
"algorithm",
"dynamic_programming",
"knapsack_problem",
"python",
"recursion"
] | stackoverflow_0074503207_algorithm_dynamic_programming_knapsack_problem_python_recursion.txt |
Q:
Difference between *3 in String to make Each Characters Triple
I have a code that answer the question, the code is like this:
def three_words(text):
result = ''
for letter in text:
result += letter*3
return print(result)
The function is returning three characters of each letter, example Ab wi... | Difference between *3 in String to make Each Characters Triple | I have a code that answer the question, the code is like this:
def three_words(text):
result = ''
for letter in text:
result += letter*3
return print(result)
The function is returning three characters of each letter, example Ab will return AAAbbb
My question is why it is not returning AbAbAb?, li... | [
"basically when you loop through a string you get each seperate character per loop:\ntest = '123'\n\nfor c in test:\n print(c)\n\noutput:\n'1'\n'2'\n'3'\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074532225_python.txt |
Q:
run my .feature files using multiple userdata possibilities
i'm running my .feature files with userdata
what i'm trying to do is to add multiple values in userdata
and loop the execution on every value
for exemple: running login test many times with a different username and password in every try but with one comma... | run my .feature files using multiple userdata possibilities | i'm running my .feature files with userdata
what i'm trying to do is to add multiple values in userdata
and loop the execution on every value
for exemple: running login test many times with a different username and password in every try but with one command line
Feature: login
Scenario Outline : authentification ... | [
"Why not using it like this:\n\nFeature: login \n\n Scenario Outline : authentification \n Given open application\n When enter user email and password\n And click on button Log In\n Then user connected\nExamples:\n |email | passsword |\n |test | test |\n |automation | au... | [
0
] | [] | [] | [
"automated_tests",
"python",
"python_behave",
"selenium",
"testing"
] | stackoverflow_0074531920_automated_tests_python_python_behave_selenium_testing.txt |
Q:
simpler way to Concatenate string and int
Here's the code I got so far:
x = 2
y = 3
print('hi' + str(x) + 'hello' + str(y))
Is there any simpler way to concatenate strings and ints? I would like some examples.
A:
you should use formatted strings (fstrings):
x = 2
y = 3
print(f'hi {x} hello {y}')
| simpler way to Concatenate string and int | Here's the code I got so far:
x = 2
y = 3
print('hi' + str(x) + 'hello' + str(y))
Is there any simpler way to concatenate strings and ints? I would like some examples.
| [
"you should use formatted strings (fstrings):\nx = 2\ny = 3\n\nprint(f'hi {x} hello {y}')\n\n"
] | [
1
] | [
"you have multiple way to do that ! :)\ni found a article with multiple one:\nhttps://datagy.io/python-concatenate-string-int/\nthis one should be a good fit in your case:\n# Concatenating a String and an Int in Python with f-strings\nword = 'datagy'\ninteger = 2022\nnew_word = f'{word}{integer}'\nprint(new_word)\n... | [
-1
] | [
"python"
] | stackoverflow_0074532441_python.txt |
Q:
connecting mysql using sqlalchemy & Docker compose
I tried to make mysql connect with docker below is my docker compose file:
version: "3.9"
services:
db:
# build: ./mysql
image: mysql:8
hostname: localhost
environment:
MYSQL_DATABASE: finops
MYSQL_USER: root
MYSQL_ALLOW_EMPTY_P... | connecting mysql using sqlalchemy & Docker compose | I tried to make mysql connect with docker below is my docker compose file:
version: "3.9"
services:
db:
# build: ./mysql
image: mysql:8
hostname: localhost
environment:
MYSQL_DATABASE: finops
MYSQL_USER: root
MYSQL_ALLOW_EMPTY_PASSWORD: 1
MYSQL_PASSWORD: Roh1t#mishra
# MY... | [
"The default database port is 3306, by commenting the env line it still remains 3306 (uncommenting it and setting a different value will change the port).\nIf you don't need to connect to the database externally (outside of the containers) then there is no need for expose/ports, which is currently set to port 3307 ... | [
0
] | [] | [] | [
"docker",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0074532444_docker_mysql_python_sqlalchemy.txt |
Q:
create new column group by values of other column
I Have the following dataframe
df1 = pd.DataFrame({'sentence': ['A', "A", "A", "A", 'A', 'B', "B", 'B'], 'entity': ['Stay home', "Stay home", "WAY", "WAY", "Stay home", 'Go outside', "Go outside", "purpose"], 'token' : ['Severe weather', "raining", "smt", "SMT0", "... | create new column group by values of other column | I Have the following dataframe
df1 = pd.DataFrame({'sentence': ['A', "A", "A", "A", 'A', 'B', "B", 'B'], 'entity': ['Stay home', "Stay home", "WAY", "WAY", "Stay home", 'Go outside', "Go outside", "purpose"], 'token' : ['Severe weather', "raining", "smt", "SMT0", "Windy", 'Sunny', "Good weather", "smt"]
})
senten... | [
"Filter rows for non matched rows by Series.isin in boolean indexing with ~ for invert mask, aggregate join and use DataFrame.join for filter rows matched list with DataFrame.pivot_table:\nvals = ['WAY','purpose']\n\nm = df1['entity'].isin(vals)\n\ndf2 = df1[m].pivot_table(index='sentence',columns='entity',values='... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"python",
"python_3.x"
] | stackoverflow_0074532513_dataframe_group_by_python_python_3.x.txt |
Q:
How do I set the area to 0 after the loop has run 1 time?
a = 0
b = 2
n = 1
delta_x = (b-a) / n
x = 0
area = 0
def f(x):
return 1/2*x**2 + 4
while area < 9.333:
for i in range (0, n):
area += f(x) * delta_x
x += delta_x
n += 1 # i want to set the area to 0 here so that i can check ... | How do I set the area to 0 after the loop has run 1 time? | a = 0
b = 2
n = 1
delta_x = (b-a) / n
x = 0
area = 0
def f(x):
return 1/2*x**2 + 4
while area < 9.333:
for i in range (0, n):
area += f(x) * delta_x
x += delta_x
n += 1 # i want to set the area to 0 here so that i can check for what n value area < 9.333
print(n)
I tried to set area = 0... | [
"As suziex has said you need to assign area as 0 between while and for this way area is reset every time for i in range(0 n) is run\nwhile area < 9.333:\n area = 0\n for i in range (0, n):\n area += f(x) * delta_x \n x += delta_x\n n += 1\nprint(n)\n \n\n"
] | [
0
] | [] | [] | [
"for_loop",
"python",
"while_loop"
] | stackoverflow_0074532492_for_loop_python_while_loop.txt |
Q:
django getting all objects from select
I also need the field (commentGroupDesc) from the foreign keys objects.
models.py
class commentGroup (models.Model):
commentGroup = models.CharField(_("commentGroup"), primary_key=True, max_length=255)
commentGroupDesc = models.CharField(_("commentGroupDe... | django getting all objects from select | I also need the field (commentGroupDesc) from the foreign keys objects.
models.py
class commentGroup (models.Model):
commentGroup = models.CharField(_("commentGroup"), primary_key=True, max_length=255)
commentGroupDesc = models.CharField(_("commentGroupDesc"),null=True, blank=True, max_length=255)
... | [
"At first, it's not a good thing to name same your model field as model name which is commentGroup kindly change field name, and run migration commands.\nYou can simply use chaining to get commentGroupDesc, also it's better to use get_object_or_404() so:\ncomment = get_object_or_404(Comment,pk=commentID)\n\ngroup_d... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0074532381_django_django_forms_django_models_django_queryset_python.txt |
Q:
Assign index number after every two consecutive row within a group after pandas groupby
I have a dataframe like below:
TileDesc ReportDesc UrlLink
'AA' 'New Report-1' 'link-1'
'AA' 'New Report-2' 'link-2'
'AA' 'New Report-1' 'link-1'
'AA' 'New Report-1' '... | Assign index number after every two consecutive row within a group after pandas groupby | I have a dataframe like below:
TileDesc ReportDesc UrlLink
'AA' 'New Report-1' 'link-1'
'AA' 'New Report-2' 'link-2'
'AA' 'New Report-1' 'link-1'
'AA' 'New Report-1' 'link-1'
'AA' 'New Report-1' 'link-1'
'BB' 'New Report-4' 'link-4'
'B... | [
"IIUC, you could group by and use cumcount(). The added trick is that you can replace the initial 0 ( cumcount starts from 0) with blank and replace with 1 (i.e. bfill):\ndf['Group'] = df.groupby('TileDesc').cumcount().replace(0,np.nan).bfill().astype(int)\n\nresult:\n TileDesc ReportDesc UrlLink Group\n... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074531796_python.txt |
Q:
Check if any string in a list of strings is in a pandas row and return bool result
I want to return bool column based on a condition:
column with sentences
list = ['foo', 'box']
if any from list in row -> return True, else return False
My code does not work and I can't find the mistake:
clean_df['to_process'] = ... | Check if any string in a list of strings is in a pandas row and return bool result | I want to return bool column based on a condition:
column with sentences
list = ['foo', 'box']
if any from list in row -> return True, else return False
My code does not work and I can't find the mistake:
clean_df['to_process'] = clean_df['sentence'].apply(
lambda x: True if any(st in x for st in ['foo','box']) e... | [
"Use Series.str.contains with join list for regex OR:\nL = ['foo','box']\nclean_df['to_process'] = clean_df['sentence'].str.contains('|'.join(L))\n\n"
] | [
2
] | [] | [] | [
"pandas",
"python",
"string"
] | stackoverflow_0074532647_pandas_python_string.txt |
Q:
Replace and overwrite instead of appending
I have the following code:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
where I'... | Replace and overwrite instead of appending | I have the following code:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
where I'd like to replace the old content that's in the ... | [
"You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:\nimport re\n\nmyfile = \"path/test.xml\"\n\nwith open(myfile, \"r+\") as f:\n data = f.read()\n f.seek(0)\n f.write(re.sub(r\"<string>ABC</string>(\\s+)<string>(.*)</string>\", r\"<xyz... | [
157,
124,
21,
3,
3,
0,
0
] | [] | [] | [
"python",
"replace"
] | stackoverflow_0011469228_python_replace.txt |
Q:
How to configure mypy to ignore a stub file for a specific module?
I installed a "dnspython" package with "pip install dnspython" under Ubuntu 22.10 and made a following short script:
#!/usr/bin/env python3
import dns.zone
import dns.query
zone = dns.zone.Zone("example.net")
dns.query.inbound_xfr("10.0.0.1", zon... | How to configure mypy to ignore a stub file for a specific module? | I installed a "dnspython" package with "pip install dnspython" under Ubuntu 22.10 and made a following short script:
#!/usr/bin/env python3
import dns.zone
import dns.query
zone = dns.zone.Zone("example.net")
dns.query.inbound_xfr("10.0.0.1", zone)
for (name, ttl, rdata) in zone.iterate_rdatas("SOA"):
serial_nr ... | [
"I would recommend ignoring only the specific wrong line, not the whole module.\ndns.query.inbound_xfr(\"10.0.0.1\", zone) # type: ignore[attr-defined]\n\nThis will suppress attr-defined error message that is generated on that line. If you're going to take this approach, I'd also recommend running mypy with the --... | [
5,
3,
2
] | [] | [] | [
"dnspython",
"mypy",
"python"
] | stackoverflow_0074425218_dnspython_mypy_python.txt |
Q:
FastAPI does not throw exception
I continue writing my first project on the FastAPI. My final method is delete. It deletes record. But after deleting record i post the same "delete" request and the FastAPI says that it was deleted instead of throwing the exception. I checked version_instance and it is None. I chec... | FastAPI does not throw exception | I continue writing my first project on the FastAPI. My final method is delete. It deletes record. But after deleting record i post the same "delete" request and the FastAPI says that it was deleted instead of throwing the exception. I checked version_instance and it is None. I checked db and there is no such version. Y... | [
"You have to raise the exception instead of returning it:\nBelow is the example:\n@app.delete('/', status_code=status.HTTP_204_NO_CONTENT)\nasync def delete_config(service: str, version: str, db: Session = Depends(get_db)):\n service_instance = db.query(models.Service).filter(\n models.Service.name == ser... | [
1
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0074519795_fastapi_python.txt |
Q:
Is there a way to use Pathlib to traverse parents folders until a name matches?
I was discussing with a colleague if there is a built-in (or clean) way to use Pathlib to traverse through an arbitrary Path to find a given parent folder, for example the root of your repository (which may differ per user that has a l... | Is there a way to use Pathlib to traverse parents folders until a name matches? | I was discussing with a colleague if there is a built-in (or clean) way to use Pathlib to traverse through an arbitrary Path to find a given parent folder, for example the root of your repository (which may differ per user that has a local copy of said repo). I simulated the desired behaviour below:
from pathlib import... | [
"You could iterate over path.parents (plural) directly, which makes this a bit cleaner:\ndef find_parent(path: Path, target_parent: str) -> Path | None:\n # `path.parents` does not include `path`, so we need to prepend it if it is\n # to be considered\n for parent in [path] + list(path.parents):\n i... | [
3,
0
] | [] | [] | [
"pathlib",
"python"
] | stackoverflow_0074532372_pathlib_python.txt |
Q:
How to update DataTable interactively with a callback function in dash?
I feel like this is a basic problem and I`ve looked through all relevant topics on SO but still can't manage to update a simple table in dash with interactive input.
Basically I have a table that contains data and want to be able to change tha... | How to update DataTable interactively with a callback function in dash? | I feel like this is a basic problem and I`ve looked through all relevant topics on SO but still can't manage to update a simple table in dash with interactive input.
Basically I have a table that contains data and want to be able to change that data depending on manual user inputs. I feel like this should be possible w... | [
"I found the problem in your code.\n\nI have changed the order of the code and I have also set the debug mode which helps to debug your code.\nBelow is the code with few modifications and fully functional\n# import dash and standard packages\nimport dash\nfrom dash import html, dcc, Input, Output\nimport pandas as... | [
1
] | [] | [] | [
"callback",
"dashboard",
"interactive",
"plotly_dash",
"python"
] | stackoverflow_0074531568_callback_dashboard_interactive_plotly_dash_python.txt |
Q:
Custom standard input for python subprocess
I'm running an SSH process like this:
sshproc = subprocess.Popen([command], shell=True)
exit = os.waitpid(sshproc.pid, 0)[1]
This works and opens an interactive terminal. Based on the documentation for subprocess, sshproc is using the script's sys.stdin.
The question i... | Custom standard input for python subprocess | I'm running an SSH process like this:
sshproc = subprocess.Popen([command], shell=True)
exit = os.waitpid(sshproc.pid, 0)[1]
This works and opens an interactive terminal. Based on the documentation for subprocess, sshproc is using the script's sys.stdin.
The question is: how can I print to stderr or a file what input... | [
"sshproc = subprocess.Popen([command],\n shell=True,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n\nstdout_value, stderr_value = sshproc.communicate('through stdin ... | [
8,
0
] | [] | [] | [
"python",
"stdin",
"subprocess"
] | stackoverflow_0003729366_python_stdin_subprocess.txt |
Q:
Creating a list of n numbers between x and y who sum up to z
I am trying to create a random set of 25 numbers, which are between 2 and 25, and sum up to 100 in python.
This Question gives an answer, but it seems that the maximum number never ends up being close to 25.
I've tried creating a list, dividing each numb... | Creating a list of n numbers between x and y who sum up to z | I am trying to create a random set of 25 numbers, which are between 2 and 25, and sum up to 100 in python.
This Question gives an answer, but it seems that the maximum number never ends up being close to 25.
I've tried creating a list, dividing each number, and recreating the list, but it essentially nullifies my min a... | [
"You haven't specified what probability distribution the numbers should have so this could be an easy valid way although very unlikely to yield numbers close to 25:\nimport numpy as np \nnumbers = np.full(25,2)\nwhile numbers.sum() < 100:\n i = np.random.randint(25)\n if numbers[i] < 25: # almost guaranteed..... | [
0,
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"random"
] | stackoverflow_0074527506_numpy_pandas_python_random.txt |
Q:
How to make Python recognize installed SQLite?
My Linux machine has sqlite3 installed:
[root@airflow-xxxxx bin]# which sqlite3
/bin/sqlite3
[root@airflow-xxxxx bin]#
However there are two versions of Python on my machine; 3.6.8 and 3.9.10:
[root@airflow-xxxxx bin]# python3
Python 3.6.8 (default, Aug 13 2020, 07:4... | How to make Python recognize installed SQLite? | My Linux machine has sqlite3 installed:
[root@airflow-xxxxx bin]# which sqlite3
/bin/sqlite3
[root@airflow-xxxxx bin]#
However there are two versions of Python on my machine; 3.6.8 and 3.9.10:
[root@airflow-xxxxx bin]# python3
Python 3.6.8 (default, Aug 13 2020, 07:46:32)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on lin... | [
"i actually had this problem recently, the issue is the order of installation, the _sqlite3 problem only seems to happen for versions of python 3.8 and above\nwhen python is built from source.\nhow were the two installations of python put on the machine? one solution would be to uninstall the 3.9 completely, (i use... | [
0
] | [] | [] | [
"python",
"python_3.x",
"sqlite"
] | stackoverflow_0074532551_python_python_3.x_sqlite.txt |
Q:
How to find a value up to some decimal point?
I have a csv file with thousand of rows like:
name,post
x1,25.84
x2,51.0634699001
x3,73.01
x4,72.0
x5,79.0
x6,75.9
x7,95.29
x8,93.55
x9,93.7
x10,10.0
x11,93.99
I am trying to write a python code, possibly something with pandas maybe that will pick up only the post val... | How to find a value up to some decimal point? | I have a csv file with thousand of rows like:
name,post
x1,25.84
x2,51.0634699001
x3,73.01
x4,72.0
x5,79.0
x6,75.9
x7,95.29
x8,93.55
x9,93.7
x10,10.0
x11,93.99
I am trying to write a python code, possibly something with pandas maybe that will pick up only the post values ending with .0 The desired output in this case ... | [
"If you have floats, this is not possible.\nAssuming you have strings, use str.endswith:\nout = df[df['post'].str.endswith('0')]\n\nIf you want to ensure matching a decimal ending in 0 (again, with a string as input), use:\nTo allow integers without decimal part (10)\nout = df[df['post'].str.fullmatch(r'\\d+(\\.\\d... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074532786_dataframe_pandas_python.txt |
Q:
How to change view in pycharm in SciView
I have an example to multiple each row and column and I am getting good results but I want to change view, when I multiply column I want to have result in n-columns in one row, and when I multiply rows I want to have one column and n-rows. Now it shows in both cases one row... | How to change view in pycharm in SciView | I have an example to multiple each row and column and I am getting good results but I want to change view, when I multiply column I want to have result in n-columns in one row, and when I multiply rows I want to have one column and n-rows. Now it shows in both cases one row and multiple columns, and it is difficult to ... | [
"You can use reshape or vstack.\nThe best way in my experience is to use reshape(-1, 1) because you don't have to specify the size of the array. It works like this:\n>>> a=np.arange(1,4)\n>>> a\narray([1, 2, 3])\n>>> a.reshape(3,1)\narray([[1],\n [2],\n [3]])\n>>> np.vstack(a)\narray([[1],\n [2],\... | [
0
] | [] | [] | [
"numpy_ndarray",
"pycharm",
"python"
] | stackoverflow_0074531120_numpy_ndarray_pycharm_python.txt |
Q:
How to modify values in xml using python?
I am trying to modify the values of xml files using python.
Here is a sample xml file
I wrote a code for adding the text to the name with iteration.
If given a set of inputs in an array, how can we check the values name
example:"Belgian Waffles" and add 2$ more price to it... | How to modify values in xml using python? | I am trying to modify the values of xml files using python.
Here is a sample xml file
I wrote a code for adding the text to the name with iteration.
If given a set of inputs in an array, how can we check the values name
example:"Belgian Waffles" and add 2$ more price to it ?
example : array=[Strawberry Belgian Waffles,... | [
"Try it this way:\nwaffles = [\"Strawberry Belgian Waffles\", \"Belgian Waffles\"]\n\nfor food in myroot.findall('.//food'):\n item = food.find('./name').text\n if item in waffles:\n cur_price = food.find('.//price').text\n\n #next one is a little tricky - the price is a string on which you need... | [
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0074532158_python_xml.txt |
Q:
Store indexes of a Series into an array
My idea is to apply linear regression to draw a line on a time series dataset to approximate the direction it is evolving in (first I draw the line, then I calculate the slope and I see if my plot is increasing decreasing, or constant).
For that, I relied on this code
def es... | Store indexes of a Series into an array | My idea is to apply linear regression to draw a line on a time series dataset to approximate the direction it is evolving in (first I draw the line, then I calculate the slope and I see if my plot is increasing decreasing, or constant).
For that, I relied on this code
def estimate_coef(x, y):
# number of observations/p... | [
"You can do:\nx=[i + 1 for i in A.index] # to make data x starts with 1 instead of 0\ny=A['lift']\n\nAnd you apply your functions on those x and y\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074532795_numpy_python.txt |
Q:
Error when installing prophet package in python
I am trying to install the prophet package in python, but it gives the following error. Can you please help?
It is required for the darts package. Actually, the main goal is to install the darts package but it gives an error when it comes to installing prophet as a s... | Error when installing prophet package in python | I am trying to install the prophet package in python, but it gives the following error. Can you please help?
It is required for the darts package. Actually, the main goal is to install the darts package but it gives an error when it comes to installing prophet as a sub-package. So, when I try installing prophet separat... | [
"This is used for installing prophet from conda ->\n\nconda install -c conda-forge prophet\n\nusing pip ->\n\npip install prophet\n\nor\ninstall pystan and fbprophet ->\npip install pystan~=2.14\npip install fbprophet\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0072132548_python_python_3.x.txt |
Q:
How create a string by another one? | Selenium Python
First of all, I would like to apologize for my question and for my English, it's my first time here on the forum and I'm noob in python, I'm still learning.
So, in my code, I imported a module that contains some strings for example:
users.py:
user1 = Jeremy
us... | How create a string by another one? | Selenium Python | First of all, I would like to apologize for my question and for my English, it's my first time here on the forum and I'm noob in python, I'm still learning.
So, in my code, I imported a module that contains some strings for example:
users.py:
user1 = Jeremy
user2 = John
user3 = Alana
user4 = Bella
...
and in my code... | [
"Firstly your users.py since it is not a python script should be changed to users.txt\nSo the contents of the text file is:\n\nuser1 = Jeremy\nuser2 = John\nuser3 = Alana\nuser4 = Bella\n...\n\nThen you can read everything within the text file, convert it into an array and call upon elements within the array, here ... | [
0
] | [] | [] | [
"python",
"selenium",
"string"
] | stackoverflow_0074512386_python_selenium_string.txt |
Q:
convert series of dates to int number of dates
I have a pandas Series that is of the following format
dates = [Nov 2022, Dec 2022, Jan 2023, Feb 2023 ..]
I want to create a dataframe that takes these values and has the number of days. I have to consider of course the case if it is a leap year
I have created a sma... | convert series of dates to int number of dates | I have a pandas Series that is of the following format
dates = [Nov 2022, Dec 2022, Jan 2023, Feb 2023 ..]
I want to create a dataframe that takes these values and has the number of days. I have to consider of course the case if it is a leap year
I have created a small function that splits the dates into 2 dataframes ... | [
"If you want the number of days in this month:\ndates = pd.Series(['Nov 2022', 'Dec 2022', 'Jan 2023', 'Feb 2023'])\n\nout = (pd.to_datetime(dates, format='%b %Y')\n .dt.days_in_month\n )\n\n# Or\n\nout = (pd.to_datetime(dates, format='%b %Y')\n .add(pd.offsets.MonthEnd(0))\n .dt.day\n ... | [
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074532851_datetime_pandas_python.txt |
Q:
How to change the y tick label in matplotlib
The below code generates a scatter plot.
#KNNClassifier_weighted
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(100, 30))
xy = np.array([
(x, y) for x, lst in df_param.items()
for sublst in lst for y in sublst
])
plt.scatter(*xy.T, s=500... | How to change the y tick label in matplotlib | The below code generates a scatter plot.
#KNNClassifier_weighted
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(100, 30))
xy = np.array([
(x, y) for x, lst in df_param.items()
for sublst in lst for y in sublst
])
plt.scatter(*xy.T, s=500, edgecolors='black', linewidth=3)
plt.title("KNN... | [] | [] | [
"I haven't tried this myself but something like this may help:\nplt.yticks([1.0, 0.0], labels, fontsize=45)\n\n"
] | [
-1
] | [
"matplotlib",
"python",
"visualization"
] | stackoverflow_0074531458_matplotlib_python_visualization.txt |
Q:
Delete specific parts in a txt file
I am working on a txt file which and in between the data that I need there are also information that I want to delete. For instance the txt file is built like this:
|important|data|that|I|need|to|keep|
-------------------------------
---------------
----------------
info|I|dont|... | Delete specific parts in a txt file | I am working on a txt file which and in between the data that I need there are also information that I want to delete. For instance the txt file is built like this:
|important|data|that|I|need|to|keep|
-------------------------------
---------------
----------------
info|I|dont|need|
----------------
---------------
--... | [
"Type str comes with a feature startswith to check if the string starts with a specific user-defined character.\nMore information can be found in the following documentation - python startswith\nwith open(\"<file_name>.txt\", \"r\") as f:\n for line in f:\n if line.startswith(\"|\"):\n print(li... | [
0,
0
] | [] | [] | [
"python",
"split",
"txt"
] | stackoverflow_0074532678_python_split_txt.txt |
Q:
Why is declaring `size_x` and `size_y` different from delcaring both in `size` in kivy?
Why do these two blocks yield different results in kivy?
size
size: [50,50]
size_x and size_y
size_x: 50
size_y: 50
Example
For example, the following code does not render the same looking app
size
Using just size has more pa... | Why is declaring `size_x` and `size_y` different from delcaring both in `size` in kivy? | Why do these two blocks yield different results in kivy?
size
size: [50,50]
size_x and size_y
size_x: 50
size_y: 50
Example
For example, the following code does not render the same looking app
size
Using just size has more padding around the label
#!/usr/bin/env python3
from kivy.uix.button import Button
from kivy.... | [
"size_x and size_y doesn't exist at all in the Kivy's API, and in the Kivy widget attributes.\nsize is a reference to a list of [width, height]. Theses code are identicals:\nsize: 100, 100\nsize_hint: None, None\n\nis equal to:\nwidth: 100\nheight: 100\nsize_hint: None, None\n\nYour example have a different behavio... | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"python",
"stacklayout"
] | stackoverflow_0074482717_kivy_kivy_language_python_stacklayout.txt |
Q:
Better way to get multi lines input from console on python 3?
I want to know how to handle multi lines input on python 3.
When the input is
10
1
6
8
5
4
7
3
2
9
0
, and the code is
numbers=[]
n = int(input()) # Get n numbers
for i in range(n): # Add n numbers in list
numbers.append(int(input()... | Better way to get multi lines input from console on python 3? | I want to know how to handle multi lines input on python 3.
When the input is
10
1
6
8
5
4
7
3
2
9
0
, and the code is
numbers=[]
n = int(input()) # Get n numbers
for i in range(n): # Add n numbers in list
numbers.append(int(input()))
I cannot input the text by copy & paste whole text block, cause... | [
"One solution:\nsample_input=input().splitlines()\nsample_input_as_int = [int(value) for value in sample_input]\nn, *data = sample_input_as_int\n\nif len(data) != n:\n raise ValueError(\"wrong number of data provided\")\n\nDo you really need to ask the user how many numbers they are going to enter?\nIf they ente... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074531288_python_python_3.x.txt |
Q:
How to translate this small part of TensorFlow code into pyTorch?
How to translate this small part of TensorFlow code into pyTorch?
def transforms(x):
# stft returns spectogram for each sample and each eeg
# input X contains 3 signals, apply stft for each
# and get array with shape [sample... | How to translate this small part of TensorFlow code into pyTorch? | How to translate this small part of TensorFlow code into pyTorch?
def transforms(x):
# stft returns spectogram for each sample and each eeg
# input X contains 3 signals, apply stft for each
# and get array with shape [samples, num_of_eeg, time_stamps, freq]
# change dims and return [sam... | [
"You can find the doc for STFT pytorch implementation here. The rest is fast-forward. It should be:\ndef transforms(x: torch.Tensor) -> torch.Tensor:\n \"\"\"Return Fourrier spectrogram.\"\"\"\n spectrograms = torch.stft(x, win_length=32, n_fft=4, hop_length=64)\n spectrograms = torch.abs(spectrograms)\n ... | [
0
] | [] | [] | [
"deep_learning",
"machine_learning",
"python",
"pytorch",
"tensorflow"
] | stackoverflow_0074523337_deep_learning_machine_learning_python_pytorch_tensorflow.txt |
Q:
appending xml node with subnodes of sam name
I have key-value pairs: task_vars = '{"BNS_DT": "20220831","DWH_BD": "dwh_bd=2022-08-31","LAYR_CD": "STG"}'
with which I would like to generate subnodes variable: tsk_var = ET.fromstring("""<variable><name></name><value></value></variable>""")
and then append variables... | appending xml node with subnodes of sam name | I have key-value pairs: task_vars = '{"BNS_DT": "20220831","DWH_BD": "dwh_bd=2022-08-31","LAYR_CD": "STG"}'
with which I would like to generate subnodes variable: tsk_var = ET.fromstring("""<variable><name></name><value></value></variable>""")
and then append variables node in: payload = ET.fromstring("""<task-launch... | [
"Try it this way:\ndestination = payload.find('.//variables')\n\n# use f-strings to insert the values into the <variable> children\nfor name, value in tsk_vars.items():\n new_childs = ET.fromstring(f\"\"\"<variable><name>{name}</name><value>{value}</value></variable>\"\"\")\n destination.insert(0,new_childs)\... | [
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0074532082_elementtree_python_xml.txt |
Q:
python multiprocessing write data to the same list
I want to write data to the same list via python multiprocessing, I do interprocess data sharing via mp.manager.list. The code is shown below, this is just a demo, I want to add the same numbers to the same list. However, counter can be increased, but grp remains ... | python multiprocessing write data to the same list | I want to write data to the same list via python multiprocessing, I do interprocess data sharing via mp.manager.list. The code is shown below, this is just a demo, I want to add the same numbers to the same list. However, counter can be increased, but grp remains the same. Where is the problem?
import multiprocessing a... | [
"Put it this way, self.grp is a managed object, any change on it using self.grp.append or self.grp[i] = x will be transferred to the manager process.\nThe objects inside self.grp are not managed, any change to them will not be transferred to the manager, you only get a copy of them when you use self.grp[i].\nIn ord... | [
1
] | [] | [] | [
"concurrency",
"multiprocessing",
"python"
] | stackoverflow_0074532214_concurrency_multiprocessing_python.txt |
Q:
Order the sub-lists in a nested list
I have a series of lists, and I want to combine them in a larger nested list. However, I want to order them in a certain way. I want the first sub-list to be the one whose first element is zero. Then i want the second sub-list to be the one whose first element is the same as th... | Order the sub-lists in a nested list | I have a series of lists, and I want to combine them in a larger nested list. However, I want to order them in a certain way. I want the first sub-list to be the one whose first element is zero. Then i want the second sub-list to be the one whose first element is the same as the LAST element of the previous list.
For e... | [
"I think of your list as being a collection of links which are to be arranged into a chain. Here is an approach which uses @quanrama 's idea of a dictionary keyed by the first element of that link:\nlinks = [[0, 3], [7, 0], [3, 8], [8, 7]]\n\nd = {link[0]:link for link in links}\nchain = []\ni = min(d)\nwhile d:\n ... | [
1,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074532216_list_python.txt |
Q:
convert the usual file.txt format into dictionaty format, nested dictionary python
I am opening a cook-book 'recipes.txt' and it reads like this:
f = open('recipes.txt', 'r', encoding='utf-8')
for x in f:
print(x)
result:
Omelet
3
Egg | 2 | PCS
Milk | 100 | ml
Tomato | 2 | PCS
Peking Duck
4
Duck | 1 | ... | convert the usual file.txt format into dictionaty format, nested dictionary python | I am opening a cook-book 'recipes.txt' and it reads like this:
f = open('recipes.txt', 'r', encoding='utf-8')
for x in f:
print(x)
result:
Omelet
3
Egg | 2 | PCS
Milk | 100 | ml
Tomato | 2 | PCS
Peking Duck
4
Duck | 1 | PCS
Water | 2 | l
Honey | 3 | t.sp
Soy sauce | 60 | ml
I need to read / convert it i... | [
"Hey maybe a little shorter then @Hunters solution\nwith open('recipes.txt', 'r', encoding='utf-8') as recipes:\n cook_book = {}\n for line in recipes:\n if (line.replace(\"\\n\", \"\")).isnumeric() or line == \"\\n\": # Ignore unwanted lines\n continue\n elif \"|\" not in line: ... | [
2,
1
] | [] | [] | [
"dictionary",
"file_read",
"nested_lists",
"python",
"readline"
] | stackoverflow_0074530101_dictionary_file_read_nested_lists_python_readline.txt |
Q:
ModuleNotFoundError: No module named 'kivymd'
i installed kivy and kivymd. now i try to use it and it seems like i've never installed any of it.
# importing all necessary modules
# like MDApp, MDLabel Screen, MDTextField
# and MDRectangleFlatButton
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
... | ModuleNotFoundError: No module named 'kivymd' | i installed kivy and kivymd. now i try to use it and it seems like i've never installed any of it.
# importing all necessary modules
# like MDApp, MDLabel Screen, MDTextField
# and MDRectangleFlatButton
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.screen import Screen
from kivymd.ui... | [
"Please try to install it again with\npip install kivymd\n\nif above solution won't work please do:\npip install --force-reinstall https://github.com/kivymd/KivyMD/archive/master.zip\n\nEdit:\nAnother option:\ngit clone https://github.com/kivymd/KivyMD.git --depth 1\ncd KivyMD\npip install .\n\nRead more about the ... | [
1
] | [] | [] | [
"kivy",
"kivymd",
"modulenotfounderror",
"python"
] | stackoverflow_0074533016_kivy_kivymd_modulenotfounderror_python.txt |
Q:
Why is the str() data type not making the input into a string variable?
cement = str(input("Do you want premium cement or standard cement? "))
print(cement)
It works for the choice of cement but also for a number.
When I try an input with numbers the program doesn't close and tells me that an integer is wrong. In... | Why is the str() data type not making the input into a string variable? | cement = str(input("Do you want premium cement or standard cement? "))
print(cement)
It works for the choice of cement but also for a number.
When I try an input with numbers the program doesn't close and tells me that an integer is wrong. Instead, it takes the number as a string but I don't want it to.
Is there any w... | [
"This should work for what you need:\ncement = str(input(\"Do you want premium cement or standard cement? \"))\nif (any(char.isdigit() for char in cement)) == True:\n exit()\nelse:\n print(cement)\n\nWhen you enter any sentence containing a number such as 1a or 1 it exits the program.\nHope this helps\n"
] | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074494767_python_string.txt |
Q:
Isinstance slice in Numba jitclass __getitem__
I am using a numba jitclass and would like to make a transformation on the key whenever it is not a slice (but I want to keep the slice functionality).
Question: How can I?
To give a little context, I would rather write tensor[coord] than tensor[tensor_to_formalseries... | Isinstance slice in Numba jitclass __getitem__ | I am using a numba jitclass and would like to make a transformation on the key whenever it is not a slice (but I want to keep the slice functionality).
Question: How can I?
To give a little context, I would rather write tensor[coord] than tensor[tensor_to_formalseries(coord, tensor.dim)] and I also like the condensed t... | [
"As of numba 0.56, isinstance() is not supported inside a numba class. Source: numba jitclass documentation\nIs it really needed to numba compile the \"is this a slice\" check? Most likely your code spent the most time on the transformation part, which means that the transformation part is where you need to focus y... | [
1
] | [] | [] | [
"isinstance",
"numba",
"python",
"slice"
] | stackoverflow_0074532282_isinstance_numba_python_slice.txt |
Q:
Problem "EXCEPTION NOT FOUND" in Cryptography (Python)
CODE
start_time1 = time.time()
ec = EC(a, b, num)
g, _ = ec.at(at)
assert ec.order(g) <= ec.q
# ElGamal enc/dec usage
eg = ElGamal(ec, g)
# mapping value to ec point
# "masking": value k to point ec.mul(g, k)
# ("imbedding" on proper n:use a poin... | Problem "EXCEPTION NOT FOUND" in Cryptography (Python) | CODE
start_time1 = time.time()
ec = EC(a, b, num)
g, _ = ec.at(at)
assert ec.order(g) <= ec.q
# ElGamal enc/dec usage
eg = ElGamal(ec, g)
# mapping value to ec point
# "masking": value k to point ec.mul(g, k)
# ("imbedding" on proper n:use a point of x as 0 <= n*v <= x < n*(v+1) < q)
mapping = [ec.mul(g, ... | [
"The exception appear to originate in this code for calculating (or really, just brute-forcing by trying all integer possibilities) the square root of a number n, modulo q.\ndef sqrt(n, q):\n \"\"\"sqrt on PN modulo: returns two numbers or exception if not exist\n >>> assert (sqrt(n, q)[0] ** 2) % q == n\n ... | [
0
] | [] | [] | [
"cryptography",
"elliptic_curve",
"exception",
"python",
"python_cryptography"
] | stackoverflow_0074522426_cryptography_elliptic_curve_exception_python_python_cryptography.txt |
Q:
Only Owner of the Profile able to Update the data
Using class Based (APIView) in Django rest framework for Getting and Patch (Updating) UserInfo data.
views.py
class getUserInfo(APIView):
permission_classes = [permissions.IsAuthenticated]
def get(self, request, format=None):
user = request.user
... | Only Owner of the Profile able to Update the data | Using class Based (APIView) in Django rest framework for Getting and Patch (Updating) UserInfo data.
views.py
class getUserInfo(APIView):
permission_classes = [permissions.IsAuthenticated]
def get(self, request, format=None):
user = request.user
userinfos = user.userinfo_set.all()
seria... | [
"Don't use the primary key to get the user.You are using user = request.user to get the user on get method, use the same mechanism also on update. Then the login user can only update his/her info not others info or another way you can check the user = UserInfo.objects.get(id=pk) is same as the current user request... | [
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_views",
"python",
"serialization"
] | stackoverflow_0074527821_django_django_rest_framework_django_views_python_serialization.txt |
Q:
Python: how to replace the characters between fixed format of a column with another column in DataFrame?
for example, how to replace <Isis/> with twins in the first row in the whole table?
I try to use the following codes, but Python indicates:"TypeError: replace() argument 1 must be str, not None"
import pandas a... | Python: how to replace the characters between fixed format of a column with another column in DataFrame? |
for example, how to replace <Isis/> with twins in the first row in the whole table?
I try to use the following codes, but Python indicates:"TypeError: replace() argument 1 must be str, not None"
import pandas as pd
import re
df = pd.read_csv('train.csv')
p = re.compile('<\w+/>')
df['original'] = df.apply(lambda x:... | [
"can you try:\nimport re\ndf['original'] = df.apply(lambda x: re.sub(\"<.*?>\", x['edit'], x['original']),axis=1)\n\n"
] | [
0
] | [] | [] | [
"data_processing",
"dataframe",
"python",
"replace"
] | stackoverflow_0074533087_data_processing_dataframe_python_replace.txt |
Q:
No module named cv cv2 No matching distribution found for mediapipe
I am using windows
import cv2
ModuleNotFoundError: No module named 'cv2'
how to fix it?
I tried
pip install opencv-contrib-python
pip3 install opencv-python
pip install opencv-python
etc etc, still did not work
update: cv2 is fixed, but I ... | No module named cv cv2 No matching distribution found for mediapipe | I am using windows
import cv2
ModuleNotFoundError: No module named 'cv2'
how to fix it?
I tried
pip install opencv-contrib-python
pip3 install opencv-python
pip install opencv-python
etc etc, still did not work
update: cv2 is fixed, but I am having a problem on mediapipe.
it's showing like this:
ERROR: Could no... | [
"It seems the install of cv2 goes nicer with system install: apt install python3-opencv\n",
"I think, with Python 3.11.0 we can't install mediapipe. What I suggest you is to try lowering your Python version to 3.7.0 and install mediapipe. If you face the same issue then try installing mediapipe==0.8.9\n"
] | [
0,
0
] | [] | [] | [
"artificial_intelligence",
"mediapipe",
"python"
] | stackoverflow_0074525008_artificial_intelligence_mediapipe_python.txt |
Q:
Tasket cmd in Python (windows)
Hi all I am just wondering how I can use Taskset command in windows?
Here's Part of code which is written in python and I am running it on windows it is giving error as taskset' is not recognized as an internal or external command
here's code below :-
event_list = df.to_records(i... | Tasket cmd in Python (windows) | Hi all I am just wondering how I can use Taskset command in windows?
Here's Part of code which is written in python and I am running it on windows it is giving error as taskset' is not recognized as an internal or external command
here's code below :-
event_list = df.to_records(index=False)
event_list = list(e... | [
"You can use the psutil library which implements the taskset command. For example:\np = psutil.Process(pid)\np.cpu_affinity(cpus)\n\nwhere cpus is a list of integers specifying the new CPUs affinity. The documentation is here.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0072433504_python.txt |
Q:
Using `to_string` with formatters removes one space between columns of a Pandas DataFrame
I am using formatters to display a column of a Pandas DataFrame in a certain way:
import pandas
df = pandas.DataFrame({"id": [0, 10, 288, 1], "value": [38.8, 88.3, 15, 19.8], "percent": [0.55, 0.05, 0.008, 0.12]})
print(df.to... | Using `to_string` with formatters removes one space between columns of a Pandas DataFrame | I am using formatters to display a column of a Pandas DataFrame in a certain way:
import pandas
df = pandas.DataFrame({"id": [0, 10, 288, 1], "value": [38.8, 88.3, 15, 19.8], "percent": [0.55, 0.05, 0.008, 0.12]})
print(df.to_string(formatters={"percent": "{:}".format}))
which outputs as:
id value percent
0 0 ... | [
"import pandas\ndf = pandas.DataFrame({\"id\": [0, 10, 288, 1], \"value\": [38.8, 88.3, 15, 19.8], \"percent\": [0.55, 0.05, 0.008, 0.12]})\nprint(df.to_string(formatters={\"id\":\"{:4}\".format, \"value\": \"{:6}\".format,\"percent\": \"{:8}\".format}))\n\nOutput:\n id value percent\n0 0 38.8 0.55\n1... | [
0
] | [] | [] | [
"dataframe",
"format",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0065772452_dataframe_format_pandas_python_python_3.x.txt |
Q:
How to use a counter in a program, or how to use looping in simple code
I have a pre-defined invited guest list. I ask a user for their name and check if the name is in the list. If it is, we simply print welcome. If not, we print the statement in the else condition. After that I want to add looping of name.
What ... | How to use a counter in a program, or how to use looping in simple code | I have a pre-defined invited guest list. I ask a user for their name and check if the name is in the list. If it is, we simply print welcome. If not, we print the statement in the else condition. After that I want to add looping of name.
What should I add in this? The program should work repeatedly when run once.
guest... | [
"guest_list = ['abhishek olkha' , 'monika' , 'chanchal' , 'daisy' , 'mayank']\n#infinite loop\nwhile True:\n name= input('enter your name please ')\n if name in guest_list:\n print( \"welcome sir/ma'am\")\n else:\n print('sorry you are not invited')\n\n",
"If you want to indefinitely loop ... | [
1,
0,
0
] | [] | [] | [
"counter",
"if_statement",
"list",
"loops",
"python"
] | stackoverflow_0074533169_counter_if_statement_list_loops_python.txt |
Q:
Adding a hyperlink to Tkinter Treeview Values
I'm putting together a decision tree tool using Tkinter. I would like to turn the values in the hyperlink column into clickable hyperlinks. How do i do this?
Here is the relevant code.
root=Tk()
root.title('Decision Tree')
root.geometry("600x600")
my_tree = ttk.Treev... | Adding a hyperlink to Tkinter Treeview Values | I'm putting together a decision tree tool using Tkinter. I would like to turn the values in the hyperlink column into clickable hyperlinks. How do i do this?
Here is the relevant code.
root=Tk()
root.title('Decision Tree')
root.geometry("600x600")
my_tree = ttk.Treeview(root)
#Define the columns
my_tree['columns'] =... | [
"It should be fairly straightforward to grab the hyperlink from the treeview selection and open it in a browser\nimport webbrowser as wb\n\n\ndef open_link(event):\n tree = event.widget # get the treeview widget\n item = tree.item(tree.focus()) # get the treeview selection\n link = item['values'][1] # g... | [
1
] | [] | [] | [
"hyperlink",
"python",
"tkinter"
] | stackoverflow_0074532947_hyperlink_python_tkinter.txt |
Q:
Remove two first character of line if match (Python)
I have a text file large with content format below, i want remove two first character 11, i try to search by dont know how to continue with my code. Looking for help. Thanks
file.txt
11112345,67890,12345
115432,a123q,hs1230
11s1a123,qw321,98765321
342342,121sa,... | Remove two first character of line if match (Python) | I have a text file large with content format below, i want remove two first character 11, i try to search by dont know how to continue with my code. Looking for help. Thanks
file.txt
11112345,67890,12345
115432,a123q,hs1230
11s1a123,qw321,98765321
342342,121sa,12123243
11023456,sa123,d32acas2
My code
import re
with ... | [
"Here is a suggestion of easy-to-read solution, without using regex that I find a bit cumbersome here (but this is obviously a personal opinion):\nwith open('in.txt', 'r') as oldfile, open('out.txt', 'w') as newfile:\n for line in oldfile:\n newfile.write(line[2:] if line.startswith('11') else line)\n\nAd... | [
6,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074532767_python_python_3.x.txt |
Q:
Count Odd Numbers in an Interval Range. Leetcode problem №1523. Python
I tried to solve this problem from leetcode and I came up with the following code but the testcase where low = 3 and high = 7 gives 2 as an output and 3 is expected by leetcode. I will be grateful if you explain what is wrong and how it should ... | Count Odd Numbers in an Interval Range. Leetcode problem №1523. Python | I tried to solve this problem from leetcode and I came up with the following code but the testcase where low = 3 and high = 7 gives 2 as an output and 3 is expected by leetcode. I will be grateful if you explain what is wrong and how it should be done.
class Solution:
def countOdds(self, low: int, high: int) -> int:... | [
"range(low, high) will result in a range of (low, low+1, low+2, ..., high -1). Meaning that in your case high will not be considered.\nIf high should also be considered use:\nrange(low, high + 1)\n\n"
] | [
2
] | [] | [] | [
"count",
"numbers",
"python"
] | stackoverflow_0074533366_count_numbers_python.txt |
Q:
How to assign cpu affinity for Python 3 subprocess?
I am very much a novice at Python.
I am running a Tkinter GUI on Windows 7 and Windows 10. I have a subprocess running a data logger routine at 1 KHz. I would like to set a cpu affinity for the subprocess,
I am building with Python 3.8.
A:
You can use the psu... | How to assign cpu affinity for Python 3 subprocess? | I am very much a novice at Python.
I am running a Tkinter GUI on Windows 7 and Windows 10. I have a subprocess running a data logger routine at 1 KHz. I would like to set a cpu affinity for the subprocess,
I am building with Python 3.8.
| [
"You can use the psutil library. This answer should help you.\n"
] | [
0
] | [] | [] | [
"affinity",
"cpu",
"python",
"subprocess",
"tkinter"
] | stackoverflow_0069872036_affinity_cpu_python_subprocess_tkinter.txt |
Q:
PIL - draw multiline text on image
I try to add text at the bottom of image and actually I've done it, but in case of my text is longer then image width it is cut from both sides, to simplify I would like text to be in multiple lines if it is longer than image width. Here is my code:
FOREGROUND = (255, 255, 255)
W... | PIL - draw multiline text on image | I try to add text at the bottom of image and actually I've done it, but in case of my text is longer then image width it is cut from both sides, to simplify I would like text to be in multiple lines if it is longer than image width. Here is my code:
FOREGROUND = (255, 255, 255)
WIDTH = 375
HEIGHT = 50
TEXT = 'Chyba naj... | [
"You could use textwrap.wrap to break text into a list of strings, each at most width characters long: \nimport textwrap\nlines = textwrap.wrap(text, width=40)\ny_text = h\nfor line in lines:\n width, height = font.getsize(line)\n draw.text(((w - width) / 2, y_text), line, font=font, fill=FOREGROUND)\n y_t... | [
69,
25,
17,
11,
0,
0,
0,
0
] | [
"text = textwrap.fill(\"test \",width=35)\nself.draw.text((x, y), text, font=font, fill=\"Black\")\n\n"
] | [
-2
] | [
"image",
"python",
"python_imaging_library",
"text"
] | stackoverflow_0007698231_image_python_python_imaging_library_text.txt |
Q:
Django Ninja API framework Pydantic schema for User model ommits fields
Project running Django with Ninja API framework. To serialize native Django's User model I use following Pydantic schema:
class UserBase(Schema):
"""Base user schema for GET method."""
id: int
username = str
first_name = str
... | Django Ninja API framework Pydantic schema for User model ommits fields | Project running Django with Ninja API framework. To serialize native Django's User model I use following Pydantic schema:
class UserBase(Schema):
"""Base user schema for GET method."""
id: int
username = str
first_name = str
last_name = str
email = str
But, this approach gives me response:
{
... | [
"Looks like the problem is that you didn't specify type for other fields. Just replace = with : in your schema for all fields:\nclass UserBase(Schema):\n \"\"\"Base user schema for GET method.\"\"\"\n\n id: int\n username: str # not =\n first_name: str\n last_name: str\n email: str\n\n"
] | [
1
] | [] | [] | [
"django",
"pydantic",
"python"
] | stackoverflow_0074533382_django_pydantic_python.txt |
Q:
Using python AI mnist to recognize my picture, trained accuracy is 97.99%, but accuracy to my img is less than 20%
Using python AI mnist to recognize my picture, trained accuracy is 97.99%, but accuracy to my img is less than 20%
I'm hoping can use MNIST doing 0~9 number recognition, and trainning accuracy rate re... | Using python AI mnist to recognize my picture, trained accuracy is 97.99%, but accuracy to my img is less than 20% | Using python AI mnist to recognize my picture, trained accuracy is 97.99%, but accuracy to my img is less than 20%
I'm hoping can use MNIST doing 0~9 number recognition, and trainning accuracy rate reach up to 97% , I thought it will be fine to reconize my pic
but predict/recognize my 2 picture as number 7
predict/rec... | [
"As Dr. Snoopy mentioned, MNIST is an academic dataset, the handwritten numbers are in the same size, and all of them are in the center of the image, but we know in the real world this rarely happens. I think the best thing you should do is use data augmentation.\nWith data augmentation, you can train the model wit... | [
2,
1
] | [] | [] | [
"artificial_intelligence",
"keras",
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0074517638_artificial_intelligence_keras_python_python_3.x_tensorflow.txt |
Q:
BERT word embeddings
I'm trying to use BERT in a static word embeddings kind of way to compare to Word2Vec and show the differences and how BERT is not really meant to be used in a contextless manner.
This is how (based on many blogsposts and tutorials) I am attempting to do that
def get_hidden_states(encoded, mod... | BERT word embeddings | I'm trying to use BERT in a static word embeddings kind of way to compare to Word2Vec and show the differences and how BERT is not really meant to be used in a contextless manner.
This is how (based on many blogsposts and tutorials) I am attempting to do that
def get_hidden_states(encoded, model, layers):
with torc... | [
"you can just add a add_special_tokens paramater to add or remove special tokens\nfrom transformers import AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pertrained('bert-base-uncased')\n\nsentence = 'test 1 2 3'\n\nfeatures = tokenizer(\n sentence, padding='do_not_pad', add_special_tokens=False, return_tensors=... | [
0
] | [] | [] | [
"bert_language_model",
"huggingface_transformers",
"python",
"pytorch",
"word_embedding"
] | stackoverflow_0074531494_bert_language_model_huggingface_transformers_python_pytorch_word_embedding.txt |
Q:
Python pickle adds first double value instead of single
This is the version of rock paper scissors game but I dont seem to find the solution to why it always adds double values to the first score that you get. For example if I play two games in a row it prints out double the amount of the first score and single am... | Python pickle adds first double value instead of single | This is the version of rock paper scissors game but I dont seem to find the solution to why it always adds double values to the first score that you get. For example if I play two games in a row it prints out double the amount of the first score and single amount of the second score and stores both of them inside the p... | [
"First - you have an error in this part:\n\n elif computer_choice > player_choice:\n computer_choice += 1\n print(\"Tu pralaimėjai!\")\n\n\nIt should be adding to defeat, not computer_choice. That is the cause of seem different behaviors for wins and losses.\nSecond: you are counting th... | [
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0074533201_pickle_python.txt |
Q:
do fit function of QSVC require float values as parameters?
Following is my code. The error seems to be in qsvc.fit() line but I can't understand why.one of the error line says "TypeError: Invalid parameter values, expected Sequence[Sequence[float]]." I'm pretty much sure I have passed arrays as parameters in fit ... | do fit function of QSVC require float values as parameters? | Following is my code. The error seems to be in qsvc.fit() line but I can't understand why.one of the error line says "TypeError: Invalid parameter values, expected Sequence[Sequence[float]]." I'm pretty much sure I have passed arrays as parameters in fit function but do they need to be float type because labels are gen... | [
"You can use values 0,1 and 2 to represent \"marital\", \"balance\" and \"loan\". sklearn has a LabelEncoder to help such a conversion.\n"
] | [
0
] | [] | [] | [
"machine_learning",
"python",
"qiskit",
"quantum_computing"
] | stackoverflow_0074522968_machine_learning_python_qiskit_quantum_computing.txt |
Q:
I need to break a for loop in python with specific condition but i am not sure what condition I should use
here is my dummy data df
parent
children
a
b
a
c
a
d
b
e
b
f
c
g
c
h
c
i
d
j
d
k
e
l
e
m
f
n
f
o
f
p
import pandas as pd
df=pd.read_csv("myfile.csv")
dfnew=pd.DataFrame(columns=["parent","ch... | I need to break a for loop in python with specific condition but i am not sure what condition I should use | here is my dummy data df
parent
children
a
b
a
c
a
d
b
e
b
f
c
g
c
h
c
i
d
j
d
k
e
l
e
m
f
n
f
o
f
p
import pandas as pd
df=pd.read_csv("myfile.csv")
dfnew=pd.DataFrame(columns=["parent","children"])
x=input("enter the name of root parent : ")
generation=int(input("how many gen... | [
"So you want to find the successors of a given node, with a depth limit?\nYou should use networkx directly and dfs_successors:\nimport pandas as pd\nimport networkx as nx\n\nG = nx.from_pandas_edgelist(df, source='parent', target='children',\n create_using=nx.DiGraph)\n\nroot = 'b'\ngener... | [
0,
0
] | [] | [] | [
"break",
"family_tree",
"for_loop",
"python"
] | stackoverflow_0074533195_break_family_tree_for_loop_python.txt |
Q:
Can't see my widget in frame in tkinter. I want to see button in bottom of the frame in on ceneter
I don't see my buttons.
I want to get this:
enter image description here
I want to see button in bottom of the frame in on ceneter.
This is my code:
from tkinter import ttk
from tkinter import *
import tkinter as tk
... | Can't see my widget in frame in tkinter. I want to see button in bottom of the frame in on ceneter | I don't see my buttons.
I want to get this:
enter image description here
I want to see button in bottom of the frame in on ceneter.
This is my code:
from tkinter import ttk
from tkinter import *
import tkinter as tk
root = tk.Tk()
root.geometry('900x650+0+0')
root.title("SV Configuration")
root.eval('tk::PlaceWindow ... | [
"First, the size of frame_btn will be 1x1 because its only child frame_center is put inside the frame using .place() which does not adjust its size automatically.\nYou need to use root.rowconfigure(4, weight=1) and root.columnconfigure(1, weight=1) (as frame_center is put at row 4 and column 1) to let frame_center ... | [
1
] | [] | [] | [
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074531069_python_python_3.x_tkinter.txt |
Q:
Python libgpiod vs gpiod packages in Linux?
I wrote a little test program in Python to manipulate GPIO pins on an an Intel Up Xtreme i11. First running under NixOS, I brought in the package as "libgpiod" and things are working. (MacOS package managers also know "libgpiod".) Then I tried to port this to an Ubuntu w... | Python libgpiod vs gpiod packages in Linux? | I wrote a little test program in Python to manipulate GPIO pins on an an Intel Up Xtreme i11. First running under NixOS, I brought in the package as "libgpiod" and things are working. (MacOS package managers also know "libgpiod".) Then I tried to port this to an Ubuntu world on the same hardware. But apt and apt-get k... | [
"What you refer to as \"libgpiod\" library are system packages based on this C library.\nFrom its documentation:\nlibgpiod\n========\n\n libgpiod - C library and tools for interacting with the linux GPIO\n character device (gpiod stands for GPIO device)\n\nSince linux 4.8 the GPIO sysfs interface is de... | [
0
] | [] | [] | [
"gpio",
"libgpiod",
"python"
] | stackoverflow_0074352978_gpio_libgpiod_python.txt |
Q:
Can anyone help me with the problem. I am trying to read my csv file in jupyter notebook
pwd
ls
import pandas as pd
DF = pd.read_csv('~/downloads/world_mortality.csv')
FileNotFoundError Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 DF = pd.read_csv('~/download... | Can anyone help me with the problem. I am trying to read my csv file in jupyter notebook | pwd
ls
import pandas as pd
DF = pd.read_csv('~/downloads/world_mortality.csv')
FileNotFoundError Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 DF = pd.read_csv('~/downloads/world_mortality.csv')
File ~\anaconda3\lib\site-packages\pandas\util\_decorators.py:311, in... | [
"Did you check that the file exists in python? You can check that with os.path using the exist function os.path.exists(path).\n"
] | [
0
] | [] | [] | [
"excel",
"jupyter_notebook",
"python",
"python_3.x"
] | stackoverflow_0074533354_excel_jupyter_notebook_python_python_3.x.txt |
Q:
Django and channels, expose model data via websockets after save
I am new to websocket and channel with django.
In my django project i would to expose saved data after a post_save event occur in a specific model via websocket.
I have django 3.2 and i install:
channels==3.0.4
channels-redis==3.3.1
then in my setti... | Django and channels, expose model data via websockets after save | I am new to websocket and channel with django.
In my django project i would to expose saved data after a post_save event occur in a specific model via websocket.
I have django 3.2 and i install:
channels==3.0.4
channels-redis==3.3.1
then in my settings.py i add channels to my app list and set:
CHANNEL_LAYERS = {
'... | [
"I don't know if you found the answer to your question. If I understood correctly, you want to send a message to the channel from the signals.\nIf this is the case you can use the get_channel_layer function in the doc\nfrom channels.layers import get_channel_layer\nchannel_layer = get_channel_layer()\n\nawait chann... | [
0
] | [] | [] | [
"django",
"django_channels",
"django_models",
"python",
"websocket"
] | stackoverflow_0070983044_django_django_channels_django_models_python_websocket.txt |
Q:
How to Run an ML model with Django on Live server
I have a Django project that uses a public ML model("deepset/roberta-base-squad2") to make some predictions. The server receives a request with parameters which trigger a queued function. This function is what makes the predictions. But this works only on my local.... | How to Run an ML model with Django on Live server | I have a Django project that uses a public ML model("deepset/roberta-base-squad2") to make some predictions. The server receives a request with parameters which trigger a queued function. This function is what makes the predictions. But this works only on my local. Once I push my project to a live server, the model no ... | [
"I have solved this. So all the while, I had been running the ML model in a background process using Celery but it worked when I ran it on the main thread. I don't know yet why it wouldn't run in the background process though.\n"
] | [
0
] | [] | [] | [
"django",
"machine_learning",
"python"
] | stackoverflow_0074512457_django_machine_learning_python.txt |
Q:
How to get timezone rules version used by datetime?
In John Skeet's blog post about handling timezone information when storing future datetimes, he suggests storing the version of timezone rules in the database along with the local time and timezone id.
His example:
ID: 1
Name: KindConf
LocalStart: 2022-07-10T09:0... | How to get timezone rules version used by datetime? | In John Skeet's blog post about handling timezone information when storing future datetimes, he suggests storing the version of timezone rules in the database along with the local time and timezone id.
His example:
ID: 1
Name: KindConf
LocalStart: 2022-07-10T09:00:00
Address: Europaplein 24, 1078 GZ Amsterdam, Netherla... | [
"The method of getting timezone rules depends on the library used to create the tzinfo instance.\nIf using pytz, the timezone database used is the Olson timezone database.\nimport pytz\nprint(pytz.OLSEN_VERSION) # e.g. 2021a\n\nWhen using zoneinfo, the system's timezone data is used by default.\nFrom the docs: By ... | [
2,
0
] | [] | [] | [
"datetime",
"python",
"python_3.x",
"timezone",
"zoneinfo"
] | stackoverflow_0070807339_datetime_python_python_3.x_timezone_zoneinfo.txt |
Q:
Is there abstract syntax tree (AST) in python extension module (files with suffix .so)?
I can check AST in python file:
python3 -m ast some_file.py
But, when I compile it with nuitka:
nuitka3 --module some_file.py
I get some_file.so extension module and when I run
python3 -m ast some_file.so
I get error.
So,... | Is there abstract syntax tree (AST) in python extension module (files with suffix .so)? | I can check AST in python file:
python3 -m ast some_file.py
But, when I compile it with nuitka:
nuitka3 --module some_file.py
I get some_file.so extension module and when I run
python3 -m ast some_file.so
I get error.
So, question my is:
is there abstract syntax tree (AST) in python extension module?
| [
"A .so is almost certainly a Linux or MacOSX Shared Object (as the tag indicates). It almost certainly does not contain Python byte code, the usual content is raw binary instructions in the format that your CPU understands.\nViewing the symbols in a .so file\n"
] | [
1
] | [] | [] | [
".so",
"abstract_syntax_tree",
"nuitka",
"python",
"python_3.x"
] | stackoverflow_0074533424_.so_abstract_syntax_tree_nuitka_python_python_3.x.txt |
Q:
Django REST Framework - How to get current user in serializer
I have TransactionSerializer:
class TransactionSerializer(serializers.ModelSerializer):
user = UserHider(read_only=True)
category_choices = tuple(UserCategories.objects.filter(user=**???**).values_list('category_name', flat=True))
category =... | Django REST Framework - How to get current user in serializer | I have TransactionSerializer:
class TransactionSerializer(serializers.ModelSerializer):
user = UserHider(read_only=True)
category_choices = tuple(UserCategories.objects.filter(user=**???**).values_list('category_name', flat=True))
category = serializers.ChoiceField(choices=category_choices)
def create(... | [] | [] | [
"UserCategories.objects.filter(user=user.id)\n\nI guess this is what you want?? your current user id\n"
] | [
-1
] | [
"authentication",
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074532716_authentication_django_django_rest_framework_python.txt |
Q:
How to perform sorting using pyreadstat library
I am using pyreadstat library to read sas dataset files(*.sas7bdat, *.xpt).
import pyreadstat as pd
import pandas as pda
import sys
import json
FILE_LOC = sys.argv[1]
PAGE_SIZE = 100
PAGE_NO = int(sys.argv[2])-1
START_FROM_ROW = (PAGE_NO * PAGE_SIZE)
pda.set_option('... | How to perform sorting using pyreadstat library | I am using pyreadstat library to read sas dataset files(*.sas7bdat, *.xpt).
import pyreadstat as pd
import pandas as pda
import sys
import json
FILE_LOC = sys.argv[1]
PAGE_SIZE = 100
PAGE_NO = int(sys.argv[2])-1
START_FROM_ROW = (PAGE_NO * PAGE_SIZE)
pda.set_option('display.max_columns',None)
pda.set_option('display.wi... | [
"Unfortunately Pyreadstat cannot return sorted data. You need to read the sas7bdat file data into memory and then you can sort it.\nIn order to sort, take into consideration that Pyreadstat returns a tuple of a pandas dataframe and a metadata object. Once you have the dataframe you can sort it by one or multiple co... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074514147_dataframe_pandas_python.txt |
Q:
Remove [255,255,255] entries from list of image RGB values
I reshaped an image (included below) as a list of pixels, and now I want to remove the black ones (with value [255,255,255]). What is an efficient way to do it?
I tried using IM[IM != [255,255,255]] and I got a list of values, instead of a list of value tr... | Remove [255,255,255] entries from list of image RGB values | I reshaped an image (included below) as a list of pixels, and now I want to remove the black ones (with value [255,255,255]). What is an efficient way to do it?
I tried using IM[IM != [255,255,255]] and I got a list of values, instead of a list of value triplets. Here is the code I'm using:
import cv2
import numpy as n... | [
"The issue is that numpy automatically does array-boradcasting, so using IM != [255,255,255] will compare each element to [255,255,255] and return a boolean array with the same shape as the one with the image data. Using this as a mask will return the values as 1D array.\nAn easy way to fix this is to use np.all:\n... | [
2
] | [] | [] | [
"image",
"list",
"python"
] | stackoverflow_0074533331_image_list_python.txt |
Q:
Cannot compute simple gradient of lambda function in JAX
I'm trying to compute the gradient of a lambda function that involves other gradients of functions, but the computation is hanging and I do not understand why.
In particular, the code below successfully computes f_next, but not its derivative (penultimate an... | Cannot compute simple gradient of lambda function in JAX | I'm trying to compute the gradient of a lambda function that involves other gradients of functions, but the computation is hanging and I do not understand why.
In particular, the code below successfully computes f_next, but not its derivative (penultimate and last line).
Any help would be appreciated
import jax
import ... | [
"It is because you're trying to define f_x using f_x in penultimate line so you are trying to compute gradient indefinitely. If you change it by:\nnew_f_x = jax.grad(f[1])\n\nit will work.\nBy the way, even if in your case the model parameters are constants, your functions have side effects (impure) and should not ... | [
0
] | [] | [] | [
"autograd",
"jax",
"python"
] | stackoverflow_0074532784_autograd_jax_python.txt |
Q:
Add Categorical Column with Specific Count
I'm trying to create a new categorical column of countries with specific percentage values. Take the following dataset, for instance:
df = sns.load_dataset("titanic")
I'm trying the following script to get the new column:
country = ['UK', 'Ireland', 'France']
df["countr... | Add Categorical Column with Specific Count | I'm trying to create a new categorical column of countries with specific percentage values. Take the following dataset, for instance:
df = sns.load_dataset("titanic")
I'm trying the following script to get the new column:
country = ['UK', 'Ireland', 'France']
df["country"] = np.random.choice(country, len(df))
df["c... | [
"Do you want to change the probabilities of numpy.random.choice?\ndf[\"country\"] = np.random.choice(country, len(df), p=[0.91, 0.06, 0.03])\ndf[\"country\"].value_counts(normalize=True)\n\nOutput:\nUK 0.902357\nIreland 0.058361\nFrance 0.039282\nName: country, dtype: float64\n\nIf you want a exact n... | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074533638_dataframe_pandas_python.txt |
Q:
Attempt to request Access token for Zoom OAuth API results in invalid redirect url
I am using the tutorial in the following link to create an Access Token automatically for Oauth Zoom API: OAuth with Zoom
The issue lies in the first step where I am required to provide a redirect link. Everytime I try to make a pos... | Attempt to request Access token for Zoom OAuth API results in invalid redirect url | I am using the tutorial in the following link to create an Access Token automatically for Oauth Zoom API: OAuth with Zoom
The issue lies in the first step where I am required to provide a redirect link. Everytime I try to make a post request to their API, I get an error
"Invalid redirect url (4,700)".
This token whic... | [
"If you check the documentation for Oauth 2.o Authorization you will find that the Redirect Uri is defined as folows\n\nSo the redirect URI is the endpoint on your system which is designed to handle the oauth response, it must have also been added to the Oauth app settings when you set up your project on zoom.\nY... | [
1,
0
] | [] | [] | [
"oauth",
"python",
"python_requests",
"zoom_sdk"
] | stackoverflow_0064853114_oauth_python_python_requests_zoom_sdk.txt |
Q:
Could not build wheels for pyarrow
This issue occurred when I install streamlit.
I had also tried to install "pyarrow" separately.
But the same error occurred.
Both Window and Python are 64bit.
Can anyone please help me with this Issue? Thank you in advance.
enter image description here
enter image description her... | Could not build wheels for pyarrow | This issue occurred when I install streamlit.
I had also tried to install "pyarrow" separately.
But the same error occurred.
Both Window and Python are 64bit.
Can anyone please help me with this Issue? Thank you in advance.
enter image description here
enter image description here
Also tried to install pyproject.toml.
| [
"pyarrow wheels are not available for Python3.11 on PyPi yet. There is a minor pyarrow release 10.0.1 being voted at the moment that should be released soon. See this thread for the release approval:\nhttps://lists.apache.org/thread/rlkrj9lnfmwgn7kq8hvmzf06l5z6w30k\nAnd this thread for asking for the 10.0.1 release... | [
1
] | [] | [] | [
"pyarrow",
"python",
"streamlit"
] | stackoverflow_0074532185_pyarrow_python_streamlit.txt |
Q:
Twitter API error, Invalid or expired token
I joined the Twitter API developer portal to collect tweet data using Twitter API, got an approval email(academic research level) from Twitter, and got issued both access tokens and keys.
When I tried to collect tweet data with Python, I kept getting errors.
unauthorized... | Twitter API error, Invalid or expired token | I joined the Twitter API developer portal to collect tweet data using Twitter API, got an approval email(academic research level) from Twitter, and got issued both access tokens and keys.
When I tried to collect tweet data with Python, I kept getting errors.
unauthorized: 401 unauthorized 89 - Invalid or expanded talk.... | [
"A couple of quick things to check for an invalid access_token type error in OAuth:\n\nCheck that the access_token was in fact successfully passed in the Authorization header of your request, and it's not null or undefined\nRule out that an invalid access_token was used (typo, invalid string, etc.)\nEnsure that the... | [
0
] | [] | [] | [
"python",
"twitter",
"twitterapi_python"
] | stackoverflow_0073863559_python_twitter_twitterapi_python.txt |
Q:
Haystack's ElasticsearchDocumentStore() cannot connect running ElasticSearch container
I am using ElasticSearch version 8.5.1 and the latest python library of ElasticSearch concurrent with version 8.5.1. Also, my Python version is 3.10.4. I was trying to follow this tutorial but clearly some of the software have c... | Haystack's ElasticsearchDocumentStore() cannot connect running ElasticSearch container | I am using ElasticSearch version 8.5.1 and the latest python library of ElasticSearch concurrent with version 8.5.1. Also, my Python version is 3.10.4. I was trying to follow this tutorial but clearly some of the software have changed a few things over the past year.
I am having trouble with Haystack's ElasticsearchDoc... | [
"It seems that I simply forgot to add in the parameter ca_certs=\"../http_ca.crt\" after copying the security certificate from the container onto the local machine.\n"
] | [
0
] | [] | [] | [
"docker",
"elasticsearch",
"haystack",
"python",
"ssl"
] | stackoverflow_0074533736_docker_elasticsearch_haystack_python_ssl.txt |
Q:
KERAS stuck randomly while adding first layer inside docker container
I have created a classification model using Python 3.9.5, Keras 2.4.3 and tensorflow-cpu 2.5.0. The model works fine in on my Windows 10 development environment but it stops executing further script and gets stuck when I deploy it in a Docker co... | KERAS stuck randomly while adding first layer inside docker container | I have created a classification model using Python 3.9.5, Keras 2.4.3 and tensorflow-cpu 2.5.0. The model works fine in on my Windows 10 development environment but it stops executing further script and gets stuck when I deploy it in a Docker container. The step where it gets stuck and becomes unresponsive is when I ad... | [
"As you are using uvicorn, the uvicorn workers get resources from docker and everytime the model layers are created it gets stored in the memory, and the issue of stucking up is due to the lack of workers resources given to it by the container.\nSo, you can try another wsgi server or try profiling the workers how ... | [
1
] | [] | [] | [
"docker",
"fastapi",
"keras",
"python",
"tensorflow"
] | stackoverflow_0068121104_docker_fastapi_keras_python_tensorflow.txt |
Q:
Python script for postgres table partitioning
I want to write python script to partition postgres table based on months for the given year, if that month already exists in database pass else create partition for that month. Kindly suggest
pyspark , using for loop to iterate over
A:
I once did something like this... | Python script for postgres table partitioning | I want to write python script to partition postgres table based on months for the given year, if that month already exists in database pass else create partition for that month. Kindly suggest
pyspark , using for loop to iterate over
| [
"I once did something like this. It may need adaptation for the specific situation. It also needs to be executed on the database.\n\"\"\"\nGenerate SQL for adding partitions \n\"\"\"\nSCHEMA_NAME = 'something'\nTABLE_NAME = 'other'\nYEAR_START = 2023\nYEAR_END = 2024\n\nfor y in range(YEAR_START, YEAR_END + 1):\n ... | [
0
] | [] | [] | [
"postgresql",
"pyspark",
"python"
] | stackoverflow_0074518819_postgresql_pyspark_python.txt |
Q:
Is there a way to filter widgets in a ScrollArea with a QLineEdit based on specific attributes?
I'm doing an app in PyQt through Qt Designer and I've populated a (container widget inside a) Scroll Area with a list of cards (custom widgets that contains informations). I've put outside of the scroll area a QLineEdit... | Is there a way to filter widgets in a ScrollArea with a QLineEdit based on specific attributes? | I'm doing an app in PyQt through Qt Designer and I've populated a (container widget inside a) Scroll Area with a list of cards (custom widgets that contains informations). I've put outside of the scroll area a QLineEdit and I want to use this QLineEdit to filter the cards based on specific attributes of each card (name... | [
"What @jfaccioni commented in the original post was really a clear, easy, and effective solution, so I will make this question as answered posting it here. To connect these fields you need to create one method to update the scrollArea and one function to verify the matches. For me it was something like this:\nclass... | [
0
] | [] | [] | [
"filter",
"pyqt",
"python",
"qt"
] | stackoverflow_0073990099_filter_pyqt_python_qt.txt |
Q:
Resample with specific condition in pandas
I have a dataframe df that looks like the following:
Start date Final date Value ID Serial
2022-09-01 01:09:07.093 2022-09-01 05:43:55.092999999 10.92 200 120
2022-09-01 01:14:07.093 2022-09-01 05:43:55.092999999 10.92 ... | Resample with specific condition in pandas | I have a dataframe df that looks like the following:
Start date Final date Value ID Serial
2022-09-01 01:09:07.093 2022-09-01 05:43:55.092999999 10.92 200 120
2022-09-01 01:14:07.093 2022-09-01 05:43:55.092999999 10.92 200 120
2022-09-01 01:19:07.093 2022-09-01 05... | [
"You can use a groupby.apply :\nout = (df.groupby(pd.Grouper(freq='15T', key='Start date'))\n .apply(lambda x: x.drop_duplicates(subset=['ID', 'Serial'])['Value'].sum())\n )\n\nOutput:\nStart date\n2022-09-01 01:00:00 22.77\n2022-09-01 01:15:00 10.92\n2022-09-01 01:30:00 0.00\n2022-09-01 01... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074533833_dataframe_pandas_python.txt |
Q:
PySpark - converting sas macro with scan function to pyspark
I am a beginner in pyspark and python, and trying to convert one of my SAS macro to pyspark, but unable to find useful resources which are equivalent to SCAN function in SAS and also having difficulties when executing while loop in EMR studio pyspark clu... | PySpark - converting sas macro with scan function to pyspark | I am a beginner in pyspark and python, and trying to convert one of my SAS macro to pyspark, but unable to find useful resources which are equivalent to SCAN function in SAS and also having difficulties when executing while loop in EMR studio pyspark cluster. I am trying to convert the following SAS macro to pyspark, t... | [
"This would be the equivalent Python code:\nfor d in [124.0, 416.0, 205.0, 332.0]:\n print(d)\n\n"
] | [
0
] | [] | [] | [
"database",
"pandas",
"pyspark",
"python",
"sas"
] | stackoverflow_0074532824_database_pandas_pyspark_python_sas.txt |
Q:
How can I use Python to read and capture images from a GIGE camera?
I have been working on a codebar recognition project for weeks,. I was asked to use GIGE cameras to recognize the code bars from a PCB and I choosed to use python for the job.
So far, I've finished the recognition of codebars from a picture with O... | How can I use Python to read and capture images from a GIGE camera? | I have been working on a codebar recognition project for weeks,. I was asked to use GIGE cameras to recognize the code bars from a PCB and I choosed to use python for the job.
So far, I've finished the recognition of codebars from a picture with Opencv. The problem is how to connect to a GIGE camera and grab a photo wi... | [
"I was struggling a lot with this, but I found this method by accident. I have an IDS industrial vision camera (IDS GV-5860-CP) which has a supported Python library. The IDS Peak IPL SDK has an extension to convert the image to a NumPy 3D array.\nMy code makes connection with the camera and accesses the datastream ... | [
0
] | [] | [] | [
"gige_sdk",
"halcon",
"opencv",
"python"
] | stackoverflow_0056441004_gige_sdk_halcon_opencv_python.txt |
Q:
How do I select rows from a DataFrame based on column values with given conditions?
How to apply rules in python, if i want A, B = 1,2 and C,D = 3,4 and E,F = 5,6 each
and drop the remaining
Type Set
1 A 1
2 B 2
3 B 3
4 C 4
5 D 5
6 ... | How do I select rows from a DataFrame based on column values with given conditions? | How to apply rules in python, if i want A, B = 1,2 and C,D = 3,4 and E,F = 5,6 each
and drop the remaining
Type Set
1 A 1
2 B 2
3 B 3
4 C 4
5 D 5
6 A 2
7 F 3
8 F 2
9 E 1
10 D 5
11 ... | [
"What about using multiple masks:\nm1 = df['Type'].isin(['A', 'B'])\nm2 = df['Type'].isin(['C', 'D'])\n\nm3 = df['Set'].isin([1, 2])\nm4 = df['Set'].isin([3, 4])\n\nout = df.loc[(m1&m3)|(m2&m4)]\n\nOr:\nm1 = df['Type'].isin(['A', 'B'])\nm2 = df['Type'].isin(['C', 'D'])\n\nm3 = df.loc[m1, 'Set'].isin([1, 2]).reindex... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074533908_pandas_python.txt |
Q:
How to merge common strings with different values between parenthesis in Python
I am processing some strings within lists that look like these:
['COLOR INCLUDES (40)', 'LONG_DESCRIPTION CONTAINS ("BLACK")', 'COLOR INCLUDES (38)']
['COLOR INCLUDES (30,31,32,33,56,74,84,85,93,99,184,800,823,830,833,838,839)', 'COLOR... | How to merge common strings with different values between parenthesis in Python | I am processing some strings within lists that look like these:
['COLOR INCLUDES (40)', 'LONG_DESCRIPTION CONTAINS ("BLACK")', 'COLOR INCLUDES (38)']
['COLOR INCLUDES (30,31,32,33,56,74,84,85,93,99,184,800,823,830,833,838,839)', 'COLOR INCLUDES (30,31,32,33,56,74,84,85,93,99,184,409,800,823,830,833,838,839)', 'COLOR IN... | [
"Split this task into smaller, simpler tasks.\nFirst task:\nWrite a function that takes a string and returns a pair (name, list_of_values) where name is the first part of the string and list_of_values is a python list of integers.\nHint: You can use '(' in s to test whether string s contains an opening parenthesis;... | [
1
] | [] | [] | [
"lcs",
"nlp",
"python",
"substring"
] | stackoverflow_0074533266_lcs_nlp_python_substring.txt |
Q:
How to go from a contour to an image mask in with Matplotlib
If I plot a 2D array and contour it, I can get the access to the segmentation map, via cs = plt.contour(...); cs.allsegs but it's parameterized as a line. I'd like a segmap boolean mask of what's interior to the line, so I can, say, quickly sum everythin... | How to go from a contour to an image mask in with Matplotlib | If I plot a 2D array and contour it, I can get the access to the segmentation map, via cs = plt.contour(...); cs.allsegs but it's parameterized as a line. I'd like a segmap boolean mask of what's interior to the line, so I can, say, quickly sum everything within that contour.
Many thanks!
| [
"I dont think there is a really easy way, mainly because you want to mix raster and vector data. Matplotlib paths fortunately have a way to check if a point is within the path, doing this for all pixels will make a mask, but i think this method can get very slow for large datasets.\nimport matplotlib.patches as pat... | [
7,
5,
0
] | [] | [] | [
"contour",
"mask",
"matplotlib",
"plot",
"python"
] | stackoverflow_0016975458_contour_mask_matplotlib_plot_python.txt |
Q:
CNN model did not learn anything from the training data. Where are the mistakes I made?
The shape of the train/test data is (samples, 256, 256, 1). The training dataset has around 1400 samples, the validation dataset has 150 samples, and the test dataset has 250 samples. Then I build a CNN model for a six-object c... | CNN model did not learn anything from the training data. Where are the mistakes I made? | The shape of the train/test data is (samples, 256, 256, 1). The training dataset has around 1400 samples, the validation dataset has 150 samples, and the test dataset has 250 samples. Then I build a CNN model for a six-object classification task. However, no matter how hard I tuning the parameters and add/remove layers... | [
"How is the accuracy of the training data? If you have a small dataset and the model does not overfit after training for a while, then something is wrong with the model. You can also test with existing datasets, which the model should be able to handle (like Fashion MNIST).\nTesting if you handled the data correctl... | [
0
] | [] | [] | [
"conv_neural_network",
"python",
"tensorflow",
"time_series",
"wavelet_transform"
] | stackoverflow_0074516257_conv_neural_network_python_tensorflow_time_series_wavelet_transform.txt |
Q:
How do I add the format for underlining text in xlsxwriter?
Just want to know how to create a variable for underlining text in the package xlsxwriter. For example, this is the one I created for making it bold:
bold_format = workbook.add_format({'bold': True})
Sorry if the answer is blatantly obvious, I tried look... | How do I add the format for underlining text in xlsxwriter? | Just want to know how to create a variable for underlining text in the package xlsxwriter. For example, this is the one I created for making it bold:
bold_format = workbook.add_format({'bold': True})
Sorry if the answer is blatantly obvious, I tried looking it up to no avail.
| [
"You can specify several different cell formats in the dictionary:\ncell_format = workbook.add_format({'bold': True, 'font_color': 'red', 'num_format': '$#,##0.00',})\nworksheet.write('A1', 'Cell A1', cell_format)\n\n# Later...\ncell_format.set_font_color('green')\nworksheet.write('B1', 'Cell B1', cell_format)\n\n"... | [
1
] | [] | [] | [
"python",
"xlsxwriter"
] | stackoverflow_0074533834_python_xlsxwriter.txt |
Q:
Error: RuntimeError: file : Object's name 'scrollList' is not unique
New to python and coding in general so I'm having trouble understanding how to do stuff. This is for a class so I can't do mel or pyMel.
I'm trying to write a code that can save faces and store them in a UI however it gives me an error that "# Er... | Error: RuntimeError: file : Object's name 'scrollList' is not unique | New to python and coding in general so I'm having trouble understanding how to do stuff. This is for a class so I can't do mel or pyMel.
I'm trying to write a code that can save faces and store them in a UI however it gives me an error that "# Error: RuntimeError: file line 28: Object's name 'scrollList' is not unique... | [
"First make sure there is no window with the same name by using deleteUI if it exists. Next, it is not a good practice to rely on names for maya ui elements because maya renames the elements if it thinks this is necessary. So something like:\nselection_textscrollList = cmds.textScrollList(\"scrollList\", ams = True... | [
1
] | [] | [] | [
"maya",
"python",
"python_3.x",
"user_interface"
] | stackoverflow_0074532479_maya_python_python_3.x_user_interface.txt |
Q:
Adding a plot to a matplotlib table
I have the following table:
fig,ax = plt.subplots(1,1,figsize=(16,16))
ax.axis('off')
nrows= 6
ncols=3
table = ax.table(cellText=[['']*ncols]*nrows,loc='top', rowLoc='center',colLoc='center')
for j,text in zip(range(3),['Group','Chart','Comments']):
table[(0,j)].get_text().... | Adding a plot to a matplotlib table | I have the following table:
fig,ax = plt.subplots(1,1,figsize=(16,16))
ax.axis('off')
nrows= 6
ncols=3
table = ax.table(cellText=[['']*ncols]*nrows,loc='top', rowLoc='center',colLoc='center')
for j,text in zip(range(3),['Group','Chart','Comments']):
table[(0,j)].get_text().set_text(text)
for i,text in zip(range... | [
"I agree with Stef's comment, this would probably be easier using GridSpec and subplots. But for the sake of documenting this workaround:\nYou could use an inset axis inside the existing Table's axis. You would just have to find the xy location of the cell in which you want to plot them and their width/height.\nYou... | [
2
] | [] | [] | [
"matplotlib",
"pandas",
"plot",
"python",
"visualization"
] | stackoverflow_0074529651_matplotlib_pandas_plot_python_visualization.txt |
Q:
Paramiko's SSHClient with SFTP
How I can make SFTP transport through SSHClient on the remote server? I have a local host and two remote hosts. Remote hosts are backup server and web server. I need to find on backup server necessary backup file and put it on web server over SFTP. How can I make Paramiko's SFTP tran... | Paramiko's SSHClient with SFTP | How I can make SFTP transport through SSHClient on the remote server? I have a local host and two remote hosts. Remote hosts are backup server and web server. I need to find on backup server necessary backup file and put it on web server over SFTP. How can I make Paramiko's SFTP transport work with Paramiko's SSHClient... | [
"paramiko.SFTPClient\nSample Usage:\nimport paramiko\nparamiko.util.log_to_file(\"paramiko.log\")\n\n# Open a transport\nhost,port = \"example.com\",22\ntransport = paramiko.Transport((host,port))\n\n# Auth \nusername,password = \"bar\",\"foo\"\ntransport.connect(None,username,password)\n\n# Go! \nsftp = para... | [
207,
29,
8,
4,
1
] | [] | [] | [
"paramiko",
"python",
"sftp",
"ssh"
] | stackoverflow_0003635131_paramiko_python_sftp_ssh.txt |
Q:
Kivy + pyzbar does not decode QR properly on Android
I am working on a Kivy App that takes an image through:
texture = self.camera.texture
size = texture.size
pixels = texture.pixels
The information above is used for the following function:
import numpy
from PIL import Image
from pyzbar.pyzbar import decode
def... | Kivy + pyzbar does not decode QR properly on Android | I am working on a Kivy App that takes an image through:
texture = self.camera.texture
size = texture.size
pixels = texture.pixels
The information above is used for the following function:
import numpy
from PIL import Image
from pyzbar.pyzbar import decode
def convert_qr(size, pixels):
pil_image = Image.from... | [
"It might be a dependency issue. Make sure that you add libzbar to your requirements field in buildozer.spec file. pyzbar depends on this to work. Here is some more info about this from a repo I found zbarcamera\n",
"Somehow the picture is mirrored in Android so flipping it with e.g. opencv if the platform is And... | [
0,
0
] | [] | [] | [
"android",
"kivy",
"python"
] | stackoverflow_0069457638_android_kivy_python.txt |
Q:
List View is not working but get_context_data() works
I have a ListView but when I call it only the get_context_data method works (the news and category model, not the product) when I try to display the information of the models in the templates.
view:
class HomeView(ListView):
model = Product
context_obje... | List View is not working but get_context_data() works | I have a ListView but when I call it only the get_context_data method works (the news and category model, not the product) when I try to display the information of the models in the templates.
view:
class HomeView(ListView):
model = Product
context_object_name='products'
template_name = 'main/home.html'
... | [
"You can also try this:\nclass HomeView(ListView):\n model = Product\n context_object_name='products'\n template_name = 'main/home.html'\n paginate_by = 25\n\n def get_context_data(self, **kwargs):\n categories = Category.objects.all()\n news = News.objects.all()\n context = supe... | [
2,
1
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074533558_django_django_templates_django_views_python.txt |
Q:
Pandas function only works on individual columns but not entire dataframe
I have a dataframe like the following (example data given):
df = pd.DataFrame({'smiles': ['CCCCC', 'CCCC1', 'CCCN1'],
'ID' : ['A-111', 'A112', 'A-113'],
'Parameter_1':[30.0, 31.4, 15.9],
'P... | Pandas function only works on individual columns but not entire dataframe | I have a dataframe like the following (example data given):
df = pd.DataFrame({'smiles': ['CCCCC', 'CCCC1', 'CCCN1'],
'ID' : ['A-111', 'A112', 'A-113'],
'Parameter_1':[30.0, 31.4, 15.9],
'Parameter_2':[NaN, '0.644', '4.38E-02'],
'Date': [dt.date(2021, 1,... | [
"Use applymap()\ndf.applymap(num_parse)\n\nYou could also:\ndf.apply(num_parse, axis=1)\n\n"
] | [
2
] | [] | [] | [
"function",
"pandas",
"python"
] | stackoverflow_0074534214_function_pandas_python.txt |
Q:
How to open a json.gz file and return to dictionary in Python
I have downloaded a compressed json file and want to open it as a dictionary.
I used json.load but the data type still gives me a string.
I want to extract a keyword list from the json file. Is there a way I can do it even though my data is a string?
He... | How to open a json.gz file and return to dictionary in Python | I have downloaded a compressed json file and want to open it as a dictionary.
I used json.load but the data type still gives me a string.
I want to extract a keyword list from the json file. Is there a way I can do it even though my data is a string?
Here is my code:
import gzip
import json
with gzip.open("19.04_associ... | [
"In the first with block you already got the uncompressed string, no need to open it a second time.\nimport gzip\nimport json\n\nwith gzip.open(\"19.04_association_data.json.gz\", \"r\") as f:\n data = f.read()\n j = json.loads (data.decode('utf-8'))\n print (type(j))\n\n\n",
"Open the file using the gzip p... | [
4,
2,
0
] | [] | [] | [
"json",
"python",
"python_3.x"
] | stackoverflow_0056677516_json_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.