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:
Post processing method to make alpha mask of an image better in Python?
I am working on a background removal model for images containing human. Which post-processing methods can I apply to erase unwanted noisy white areas from the produced alpha mask, as can be seen from the image?
sample image. I want to remove n... | Post processing method to make alpha mask of an image better in Python? | I am working on a background removal model for images containing human. Which post-processing methods can I apply to erase unwanted noisy white areas from the produced alpha mask, as can be seen from the image?
sample image. I want to remove noisy-cloudy area between sharp edges
I tried basic opencv operations like ero... | [
"If you apply a threshold, the cloudy (grey) area is removed:\nimport cv2\n\nimg = cv2.imread(\"img.jpg\", cv2.IMREAD_GRAYSCALE)\n_, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\ncv2.imwrite(\"out.jpg\", thresh)\n\nOutput:\n\n"
] | [
0
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074393789_image_processing_opencv_python.txt |
Q:
How to write to the last occurrence of loc?
I have a dataFrame with date column, and sometimes the date might appear twice.
When I write to a certain date, I would like to write to the last row that have this date, not the first.
Right now I use:
df.loc[df['date'] == date, columnA] = value
Which in the case of a... | How to write to the last occurrence of loc? | I have a dataFrame with date column, and sometimes the date might appear twice.
When I write to a certain date, I would like to write to the last row that have this date, not the first.
Right now I use:
df.loc[df['date'] == date, columnA] = value
Which in the case of a df like this will write at index 1, not 2:
dat... | [
"You can chain mask for last duplicated date value by Series.duplicated:\nprint (df)\n date columnA\n0 17.4.2022 8\n1 17.5.2022 1\n2 17.5.2022 1\n2 17.5.2022 1\n3 17.6.2022 3\n\ndate = '17.5.2022'\ndf.loc[(df['date'] == date) & ~df['date'].duplicated(keep='last'), 'co... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074399314_pandas_python.txt |
Q:
How to give html actions/variables to flask submit button
I have a flask app with a form that takes awhile for my backend to process. I want to display a loading gif while this happens to refrain people from refreshing or resubmitting.
My current flask form submit html looks like this:
<div class="form=group">
... | How to give html actions/variables to flask submit button | I have a flask app with a form that takes awhile for my backend to process. I want to display a loading gif while this happens to refrain people from refreshing or resubmitting.
My current flask form submit html looks like this:
<div class="form=group">
{{ form.submit(class='btn btn-outline-info') }}
</div>
I am a... | [
"You need change:\n\ntype=\"submit\" to type=\"button\"\n\n<input type=\"button\" name=\"anything_submit\" value=\"Submit\" onclick=\"loading();\">\n\nAnd you need add in your function loading();\n$(\"#loading\").show();\ndocument.getElementById(\"myForm\").submit();\n\nthis allows us to generate a submit action:\n... | [
0
] | [] | [] | [
"flask",
"html",
"javascript",
"python"
] | stackoverflow_0074398661_flask_html_javascript_python.txt |
Q:
Replacing empty cells with new value based on other column in Pandas
I have DataFrame where:
if in column C row has no value than based on value in column D I want to assign value to column C
For example:
row 1 in column C is empty and same row in column D has value 'cat', so I want fill empty cell in column C wit... | Replacing empty cells with new value based on other column in Pandas | I have DataFrame where:
if in column C row has no value than based on value in column D I want to assign value to column C
For example:
row 1 in column C is empty and same row in column D has value 'cat', so I want fill empty cell in column C with value 'home'
Below my the ways I've tried but none worked:
for line in d... | [
"i think you can use np.select():\nimport numpy as np\n\ncondlist=[(df1['C'].isnull()) & (df1['D'].str.contains('cat|dog')),((df1['C'].isnull()) & ((df1['D'].str.contains('horse|cow|bird'))))]\nchoicelist=['house','garden']\ndefault=df1['C']\ndf1['C']=np.select(condlist,choicelist,default)\n\n\n"
] | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074392955_numpy_pandas_python.txt |
Q:
pip install cmd but modules not found in PyCharm
So, I have Pycharm and pip up to date, and after installing any module with pip install, no matter where I install it (/current_python_project) or somewhere else (\python310\lib\site-packages)...
When I pip install let's say pandas, and then try
import matplotlib.py... | pip install cmd but modules not found in PyCharm | So, I have Pycharm and pip up to date, and after installing any module with pip install, no matter where I install it (/current_python_project) or somewhere else (\python310\lib\site-packages)...
When I pip install let's say pandas, and then try
import matplotlib.pyplot as plt
console says: ModuleNotFoundError: No mod... | [
"Please try the following instructions:\npython -m pip install – upgrade pip\npip install pandas\npip install matplotlib\n\nOr you can try following instructios:\nopen cmd, and type \"where python\". Once you have opened the Python folder, browse and open the Scripts folder and copy its location. Also verify that t... | [
0
] | [] | [] | [
"pandas",
"pip",
"python"
] | stackoverflow_0074393492_pandas_pip_python.txt |
Q:
mock.patch in pytest fixture doesn't work when other tests have run
Given the following code and tests:
# some module
from other.module import a_func # returns False by default
def do_stuff():
return "banana" if a_func() else "pear"
#############################
# tests in a different module
@pytest.fixt... | mock.patch in pytest fixture doesn't work when other tests have run | Given the following code and tests:
# some module
from other.module import a_func # returns False by default
def do_stuff():
return "banana" if a_func() else "pear"
#############################
# tests in a different module
@pytest.fixture
def my_fixture():
with mock.patch("other.module.a_func", lambda:... | [
"You should do\nmock.patch(\"some.module.a_func\")\n\ninstead of\nmock.patch(\"other.module.a_func\")\n\nfrom other.module import a_func means that a_func becomes part of the some.module, so patching the origin of function definition has no effect - instead, patching should be done where the function is used. Read ... | [
2
] | [] | [] | [
"fixtures",
"mocking",
"pytest",
"python"
] | stackoverflow_0074394875_fixtures_mocking_pytest_python.txt |
Q:
Can not find BatchNormalization with tensorflow-macos
I have working code on Nvidia GPUs but now I moved to my Mac M1. Although the GPU is found and tensorflow is installed when I would like to import BatchNormalization layer I get the following error:
from tensorflow.python.keras.layers import BatchNormalization
... | Can not find BatchNormalization with tensorflow-macos | I have working code on Nvidia GPUs but now I moved to my Mac M1. Although the GPU is found and tensorflow is installed when I would like to import BatchNormalization layer I get the following error:
from tensorflow.python.keras.layers import BatchNormalization
ImportError: cannot import name 'BatchNormalization' from... | [
"Please check if the tensorflow is installed in your system by following the below code:\nimport tensorflow as tf\nprint(tf.__version__)\n\nif it shows the output as version: 2.8.0, this means tensorflow installed and imported successfully in your system and now you can import keras libraries from tensorflow as ten... | [
0
] | [] | [] | [
"keras",
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0072448166_keras_python_python_3.x_tensorflow.txt |
Q:
Pywhatkit - Not Working - “Pywhatkit” Is Not Accessedpylance
Import "pywhatkit" could not be resolvedPylance
"pywhatkit" is not accessedPylance
Import "pywhatkit" could not be resolvedPylancereportMissingImports
pywhatkit is not working, how can I fix it?
I updated pywhatkit but the error is still here.
A:
This ... | Pywhatkit - Not Working - “Pywhatkit” Is Not Accessedpylance | Import "pywhatkit" could not be resolvedPylance
"pywhatkit" is not accessedPylance
Import "pywhatkit" could not be resolvedPylancereportMissingImports
pywhatkit is not working, how can I fix it?
I updated pywhatkit but the error is still here.
| [
"This type of errors with imports is very common when working with Visual Studio Code, this is generated by a misconfiguration of the interpreter with the environments, in case you are working with a virtual environment you need to configure it.\nRemember that Pylance is a visual code extension that allows us to de... | [
0
] | [] | [] | [
"python",
"whatsapp"
] | stackoverflow_0074399321_python_whatsapp.txt |
Q:
Copying range from one excel workbook to another
I am trying to copy a range form one excel sheet to another.
This is my code:
import openpyxl
import os
#Current path
path = os.path.dirname(os.path.abspath(__file__))
#Beregningsmodul navn
Beregningsmodul_moder = "Beregning COREP LCR - MODER - 202202.xlsx"
#Skem... | Copying range from one excel workbook to another | I am trying to copy a range form one excel sheet to another.
This is my code:
import openpyxl
import os
#Current path
path = os.path.dirname(os.path.abspath(__file__))
#Beregningsmodul navn
Beregningsmodul_moder = "Beregning COREP LCR - MODER - 202202.xlsx"
#Skema 72 navn
workbook_skema_72 ="C_72_00_a.xlsx"
#workbo... | [
"My best solution was to use VBA code to solve the issue I hope this can help someone in the future:\nSub HentData()\n\n'Improves performance / stability\nCall OptimizeCode_Begin\n\nDim Time As Variant\n\n'Monitor duration of runtime\nStartDateTime = Now\n\nDim tws As Worksheet\nDim Path As String\nDim Files As Str... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python"
] | stackoverflow_0071707543_excel_openpyxl_python.txt |
Q:
What does this code encoded with \x... do?
I got this from a security book and I wonder how can I decode the part shellcode
#!/usr/bin/python
from socket import *
# *** Generated with libShellCode
# setuid(0) + setgid(0) + bind(/bin/sh) on port 31337
shellcode = \
"\x31\xc0\x31\xdb\xb0\x17\xcd\x80\x31\xc0\x31\xd... | What does this code encoded with \x... do? | I got this from a security book and I wonder how can I decode the part shellcode
#!/usr/bin/python
from socket import *
# *** Generated with libShellCode
# setuid(0) + setgid(0) + bind(/bin/sh) on port 31337
shellcode = \
"\x31\xc0\x31\xdb\xb0\x17\xcd\x80\x31\xc0\x31\xdb\xb0\x2e\xcd\x80" + \
"\x31\xdb\xf7\xe3\xb0\x66... | [
"OK... checking out libShellCode more carefully, there's a library of byte code instructions.\nAs an example, \\x31\\xc0 is here (lib/i386/i386_doces.c):\n XOR_EAX_EAX = (char *) strdup(\"\\x31\\xc0\"); // xor %eax, %eax\n\nSo here a XOR is defined.\n"
] | [
0
] | [] | [] | [
"python",
"security"
] | stackoverflow_0074396247_python_security.txt |
Q:
plot modulus functions in matplotlib
im pretty new to matplotlib and plottings.
im trying to plot the function |x| + |y| = 0.1 in matplotlib. but im unable to do due to the below syntax. Is there a way i can do this with single function ? Also if the range of x and y values are increased beyond [-0.1,0.11] graph i... | plot modulus functions in matplotlib | im pretty new to matplotlib and plottings.
im trying to plot the function |x| + |y| = 0.1 in matplotlib. but im unable to do due to the below syntax. Is there a way i can do this with single function ? Also if the range of x and y values are increased beyond [-0.1,0.11] graph is not correct. Kindly help
| [
"You are plotting a function of two variables, hence you can use plt.contour. If you rewrite your equation as |x| + |y| - 0.1, the \"equal to zero\" correspond to the contour level 0.\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\n\nl = 0.25 # plot the function f... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074398702_matplotlib_python.txt |
Q:
(python) for loop operation 0 time, 1 time, many times differencate
(python) for loop operation 0 time, 1 time, many times for creating several cv2.rectangle on same img
I plan to draw square on original img show the part of duplicate, and if there is three, just over write 2 times of first original pic output, th... | (python) for loop operation 0 time, 1 time, many times differencate | (python) for loop operation 0 time, 1 time, many times for creating several cv2.rectangle on same img
I plan to draw square on original img show the part of duplicate, and if there is three, just over write 2 times of first original pic output, that should has 2 square though
I tried to commont every step in below scri... | [
"You don't need those if statements at all. You're in a for loop based on the length of that list. If the length is zero, the loop is not going to run. And a length can never be < 0.\n"
] | [
0
] | [] | [] | [
"for_loop",
"python",
"python_3.x",
"while_loop"
] | stackoverflow_0074387614_for_loop_python_python_3.x_while_loop.txt |
Q:
Giving names to returned values with python type hints
Let's say I have a function like
def basic_stats(data: List[float]):
"""This returns a tuple with the mean and median values of the data
"""
return (np.mean(data), np.median(data))
and I want to use type hints to self-document the code instead of ... | Giving names to returned values with python type hints | Let's say I have a function like
def basic_stats(data: List[float]):
"""This returns a tuple with the mean and median values of the data
"""
return (np.mean(data), np.median(data))
and I want to use type hints to self-document the code instead of a comment. The standard way isn't super clear:
def basic_st... | [
"There's nothing that can do that in the type hints. I can think of several reasons not to, such as overwriting a variable in the caller with the same name you're returning.\nAn approach might be to return a named tuple using namedtuple from collections (https://docs.python.org/3/library/collections.html#collection... | [
3,
1
] | [] | [] | [
"python",
"type_hinting"
] | stackoverflow_0073654751_python_type_hinting.txt |
Q:
Take the image printed with plt.imshow as a variable
I'm using a custom library to print the execution of a transform from a 1D signal. The output is 2D and it's printed through plt.imshow(), used by a function inside of the library. I have the result but i don't want to save the picture locally. There is a way to... | Take the image printed with plt.imshow as a variable | I'm using a custom library to print the execution of a transform from a 1D signal. The output is 2D and it's printed through plt.imshow(), used by a function inside of the library. I have the result but i don't want to save the picture locally. There is a way to get as a PIL image what is being used by plt.imshow?
p.s.... | [
"You can use ax.images[idx].get_array() to retrieve the data, after which you can use it on PIL. ax is the axes where the image has been plotted. idx is the index of the image you are interested: if you have plotted a single image, then idx=0.\n"
] | [
1
] | [] | [] | [
"imshow",
"matplotlib",
"python",
"python_imaging_library"
] | stackoverflow_0074399566_imshow_matplotlib_python_python_imaging_library.txt |
Q:
How to dynamically generate a regular expression in python?
I have this regular expression r'\b28\b'. In this expression 28 should be dynamic. In other words, 28 is a dynamic value which the user enters. So, instead of 28 it can have 5. In that case, the expression would be r'\b5\b'.
I tried the below two approach... | How to dynamically generate a regular expression in python? | I have this regular expression r'\b28\b'. In this expression 28 should be dynamic. In other words, 28 is a dynamic value which the user enters. So, instead of 28 it can have 5. In that case, the expression would be r'\b5\b'.
I tried the below two approaches but they are not working.
r"r'\b" + room_number + r"\b'"
"r'\... | [
"Contrary to the previous answer, you should generally use r for regular expression strings. But the way you had it, the r was inside the strings. It needs to go outside. It would look like this:\nregex = r\"\\b\" + str(my_var) + r\"\\b\"\n\nbut in general it's nicer to use raw f-strings. This way you don't have to... | [
2,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074398213_python_regex.txt |
Q:
Python Multiple Dictonary Values into one List
so im using xml.etree.ElementTree to read multiple .xmls in a Folder.
i extract the desired Attributes using x.attrib and put those into a variable.
attributes = x.attrib
The stored information comes in multiple dictonaries:
{'Key1': 'Value1', 'Key2': 'Value2', 'Key3... | Python Multiple Dictonary Values into one List | so im using xml.etree.ElementTree to read multiple .xmls in a Folder.
i extract the desired Attributes using x.attrib and put those into a variable.
attributes = x.attrib
The stored information comes in multiple dictonaries:
{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'Value_1'}
{'... | [
"I think you are trying to do this:\nimport xml.etree.ElementTree as ET\nimport os\n\npath = \"directory/here\"\n\nfor filenames in os.listdir(path):\n if filenames.endswith('.xml'):\n fullnames = os.path.join(path, filenames)\n tree = ET.parse(fullnames)\n root = tree.getroot()\n l =... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0074399510_python.txt |
Q:
use a specfic coumn values as a checker to change other column values in pyspark/pandas
If I have below table
|a | id | year|m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 2001 | 0 | 0 | 0 | ... | 0 |
|"hello"| 1 | 2015 | 0 | 0 | 0 | ... | 0 |
|"hello"| 2 | 2002 | 0 ... | use a specfic coumn values as a checker to change other column values in pyspark/pandas | If I have below table
|a | id | year|m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 2001 | 0 | 0 | 0 | ... | 0 |
|"hello"| 1 | 2015 | 0 | 0 | 0 | ... | 0 |
|"hello"| 2 | 2002 | 0 | 0 | 0 | ... | 0 |
|"hello"| 2 | 2015 | 0 | 0 | 0 | ... | 0 |
How... | [
"new = df.select('a','id','year',*[when((size(F.array_distinct(F.array(F.lit(col('year').astype('string')), lit(x[1:])))))==1,1).otherwise(0).alias(x) for x in df.columns if x not in ['a','id','year']])\n\nnew.groupBy('a','id').agg(*[max(x).alias(x) for x in new.columns if x not in ['a','id','year']] ).show()\n\nHo... | [
1,
0
] | [] | [] | [
"apache_spark",
"dataframe",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074378545_apache_spark_dataframe_pandas_pyspark_python.txt |
Q:
How to type hint variable that is initially None but is guaranteed to get a value
I have a class variable as shown below:
class MyClass:
def __init__(self):
self.value: MyOtherClass | None = None
self.initialize_value()
def initialize_value(self):
self.value = MyOtherClass()
d... | How to type hint variable that is initially None but is guaranteed to get a value | I have a class variable as shown below:
class MyClass:
def __init__(self):
self.value: MyOtherClass | None = None
self.initialize_value()
def initialize_value(self):
self.value = MyOtherClass()
def use_value(self):
return self.value.used
self.value is guaranteed to be init... | [
"To avoid repetition, when such an attribute is used throughout the class in multiple methods, a common pattern for me is protecting it and defining a property that raises an error, if the attribute behind it is not set:\nclass MyClass:\n def __init__(self):\n self._value: MyOtherClass | None = None\n ... | [
1
] | [] | [] | [
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0074396955_python_python_typing_type_hinting.txt |
Q:
How to find the matrix dimensions using OpenCV from an image
I am trying to extract the dimensions of a matrix from an image which is like a tic-tac-toe with a dimension of N x M. How do I find the dimension of the matrix using OpenCV. There are many images with varying matrix dimensions like 3x3, 4x4, 4x5, 5x6, e... | How to find the matrix dimensions using OpenCV from an image | I am trying to extract the dimensions of a matrix from an image which is like a tic-tac-toe with a dimension of N x M. How do I find the dimension of the matrix using OpenCV. There are many images with varying matrix dimensions like 3x3, 4x4, 4x5, 5x6, etc... How to find them all
I tried to use contours and didn't know... | [
"This is a sample code which detects the vertical lines.\n(This code is in C++, but I think you can see what it's doing.)\nint main()\n{\n //Load Image\n cv::Mat Img = cv::imread( \"Grid.png\", cv::IMREAD_GRAYSCALE );\n if( Img.empty() )return 0;\n\n //\n // 1D Hough-Transform ( Vertical Black Line D... | [
2
] | [] | [] | [
"image_processing",
"matrix",
"opencv",
"python"
] | stackoverflow_0074397717_image_processing_matrix_opencv_python.txt |
Q:
Return html tag by calling python function in django template
Guys actually i am expecting the django view should return only the tag like
def load_tags():
return httpresponse("<span>span tag</span>")
def home(request):
return render(request, 'index.html',{"func":load_tags()})
html file
<h2>Calling python... | Return html tag by calling python function in django template | Guys actually i am expecting the django view should return only the tag like
def load_tags():
return httpresponse("<span>span tag</span>")
def home(request):
return render(request, 'index.html',{"func":load_tags()})
html file
<h2>Calling python function {{ func }} </h2>
-In browser it displayed as
Calling py... | [
"I tried to solve your requirement like this...\nviews.py\ndef TagsView():\n html_h1 = \"<h1>Hello django</h1>\"\n html_italic = \"<h4><i>Hello django</i></h4>\"\n html_hr = \"<hr>\"\n my_code = \"<code>print('Hello world')</code>\"\n return html_h1,html_italic,html_hr,my_code\n\ndef DemoView(request... | [
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074361955_django_django_templates_django_views_python.txt |
Q:
How to ask for user input cotinuously after finishing one round of opetation?
i've got a python script that eliminates the print out of vowels inside a word (the ugly vowel eater). I meant to let the user input a new word once the previous word is examed. Please help me with that, i've attaced the code below.
Many... | How to ask for user input cotinuously after finishing one round of opetation? | i've got a python script that eliminates the print out of vowels inside a word (the ugly vowel eater). I meant to let the user input a new word once the previous word is examed. Please help me with that, i've attaced the code below.
Many thanks!
user_word = input("Please enter a word: ")
user_word = user_word.upper()
... | [
"while True:\n\n # take user input in the while loop\n user_word = input(\"Please enter a word: \")\n user_word = user_word.upper()\n\n if user_word != \"END\":\n for letter in user_word:\n if letter == \"A\":\n continue\n elif letter == \"E\":\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074399675_python.txt |
Q:
My kv file is a python file instead of a text file
I have a main with a main class called MyApp, but when I try to create a kv text file in file->new->name: my.kv, my new created file is a python file and not a text file.
Change directory... Or create a new project.
A:
Try opening the file which should be in .kv... | My kv file is a python file instead of a text file | I have a main with a main class called MyApp, but when I try to create a kv text file in file->new->name: my.kv, my new created file is a python file and not a text file.
Change directory... Or create a new project.
| [
"Try opening the file which should be in .kv format with any text editor which can save the file as .ky file. For example, in Windows you can create a new text document and open it by notepad from which you can convert it into .ky file.\nProcedure with images:-\n\nGo to the project folder, right click and hover ove... | [
1
] | [] | [] | [
"file",
"kivy",
"kivy_language",
"pycharm",
"python"
] | stackoverflow_0074396579_file_kivy_kivy_language_pycharm_python.txt |
Q:
How to sort numeric strings with 2 decimal points in python
I have some directories in linux having version as directory name :
1.1.0 1.10.0 1.5.0 1.7.0 1.8.0 1.8.1 1.9.1 1.9.2
I want to sort the above directories from lowest to highest version
when i try to use .sort in python i end up getting below
['1.1... | How to sort numeric strings with 2 decimal points in python | I have some directories in linux having version as directory name :
1.1.0 1.10.0 1.5.0 1.7.0 1.8.0 1.8.1 1.9.1 1.9.2
I want to sort the above directories from lowest to highest version
when i try to use .sort in python i end up getting below
['1.1.0', '1.10.0', '1.5.0', '1.7.0', '1.8.0', '1.8.1', '1.9.1']
whic... | [
"Since your versions are of string datatype. We would have to split after each dot.\nv_list = ['1.1.0','1.10.0','1.5.0','1.7.0','1.8.0','1.8.1','1.9.1','1.9.2']\nv_list.sort(key=lambda x: list(map(int, x.split('.'))))\n\nor you can also try this:\nv_list = ['1.1.0','1.10.0','1.5.0','1.7.0','1.8.0','1.8.1','1.9.1','... | [
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074399725_list_python_python_3.x_sorting.txt |
Q:
Python datetime not correct with regards to timezones when running in docker
I have a python 2.7 codebase that I'm trying to containerize. Much as I'd like to, our devs cannot move to Python 3.
When running natively in their dev environments, datetimes respect timezones. I can confirm that the output is as expecte... | Python datetime not correct with regards to timezones when running in docker | I have a python 2.7 codebase that I'm trying to containerize. Much as I'd like to, our devs cannot move to Python 3.
When running natively in their dev environments, datetimes respect timezones. I can confirm that the output is as expected on a Mac running Python 3.9.6. But when we containerize this on Ubuntu base imag... | [
"You can avoid changing environment variables by using aware datetime consistently. To calculate Unix time, derive it from a timedelta.\nfrom datetime import datetime\nfrom dateutil import tz\n\ndef to_unix(dt, _epoch=datetime(1970, 1, 1, tzinfo=tz.UTC)):\n \"\"\"convert aware datetime object to seconds since th... | [
0,
0
] | [] | [] | [
"datetime",
"python",
"python_2.x",
"timezone"
] | stackoverflow_0074395944_datetime_python_python_2.x_timezone.txt |
Q:
Scraping online and last seen recently users from Telegram chats
I want to scrape a Telegram group with Telethon API. But this code scrapes all users in the group. But I want to scrape only online and last seen recently users. How to do it?
from telethon.sync import TelegramClient
from telethon.tl.functions.messag... | Scraping online and last seen recently users from Telegram chats | I want to scrape a Telegram group with Telethon API. But this code scrapes all users in the group. But I want to scrape only online and last seen recently users. How to do it?
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmp... | [
"Hope this helps:\n...\nfor user in all_participants:\n if not user.user.status in ['online','recently']: continue \n if user.username:\n username= user.username\n...\n\n",
"I try this code and another with num.date condition but show me one member and even show nothing but i think better to change o... | [
0,
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram",
"telegram_bot",
"telethon"
] | stackoverflow_0065586009_python_python_telegram_bot_telegram_telegram_bot_telethon.txt |
Q:
How to generate a unique specific ID in python that's derived from the hardware info on any system (Mac, Linux or Windows)?
I want to derive a master key solely from the system on which the user is working on, I don't want to store a master key so then we decided to derive a unique ID from the system the user will... | How to generate a unique specific ID in python that's derived from the hardware info on any system (Mac, Linux or Windows)? | I want to derive a master key solely from the system on which the user is working on, I don't want to store a master key so then we decided to derive a unique ID from the system the user will be working on.
For example if a user is on System A, everytime the code runs it should return the same key, but on System B it'l... | [
"Try:\nfrom pprint import pprint\nprint('===================')\n\nimport psutil\npprint(f'{psutil.net_if_addrs().keys()=}')\n\nprint('===================')\n\nimport socket\npprint(f'{socket.if_nameindex()=}' )\n\nprint('===================')\n\nimport netifaces # https://pypi.org/project/netifaces/\nppri... | [
0
] | [] | [] | [
"cross_platform",
"cryptography",
"encryption",
"python",
"security"
] | stackoverflow_0074399823_cross_platform_cryptography_encryption_python_security.txt |
Q:
I want to check in Panda Dataframe if testsubject( "ID") has given info(datapoint) on a certain day
i'm fairly new to Python and Pandas so I'm thinking maybe this is obvious but I just don't get it.
I have a dataset that has columns "ID"s (random numbers), "Date", and a datapoint on that day "Activity"
So if I hav... | I want to check in Panda Dataframe if testsubject( "ID") has given info(datapoint) on a certain day | i'm fairly new to Python and Pandas so I'm thinking maybe this is obvious but I just don't get it.
I have a dataset that has columns "ID"s (random numbers), "Date", and a datapoint on that day "Activity"
So if I have five(or X amount of) IDs, ID : [1,2,3,4,5] and then each ID has Dates running for lets say 30 days.( Th... | [
"I've created a dummy dataframe using the following:\ndf = pd.DataFrame()\nID = [1,2,3,4,5]\nDates = ['01/05/2022', '02/03/2022', '12/03/2022', '02/03/2022', '02/04/2022']\nActivity = [0, 1, 4, 5, 1]\ndf['ID'], df['Date'], df['Activity'] = ID, Dates, Activity\n\nGiving me this dataframe:\nID Date Activity\n... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074399712_dataframe_pandas_python.txt |
Q:
index string by character
I need to determine the most frequent character of a list of strings by each index in Python.
Example
list1 = ['one', 'two', 'twin', 'who']
the most frequent character between all the strings at index 0 is 't'
the most frequent character between all the strings at index 1 is 'w'
the most ... | index string by character | I need to determine the most frequent character of a list of strings by each index in Python.
Example
list1 = ['one', 'two', 'twin', 'who']
the most frequent character between all the strings at index 0 is 't'
the most frequent character between all the strings at index 1 is 'w'
the most frequent character between all ... | [
"from itertools import zip_longest\n\nlist1 = ['one', 'two', 'twin', 'who']\n\nchars = {}\nfor i, item in enumerate(zip_longest(*list1)):\n set1 = set(item)\n if None in set1:\n set1.remove(None)\n chars[i] = max(set1, key=item.count)\n\nWithout importing any library:\nlist1 = ['one', 'two', 'twin',... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0074399538_python.txt |
Q:
Can you plot interquartile range as the error band on a seaborn lineplot?
I'm plotting time series data using seaborn lineplot (https://seaborn.pydata.org/generated/seaborn.lineplot.html), and plotting the median instead of mean. Example code:
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
fmri ... | Can you plot interquartile range as the error band on a seaborn lineplot? | I'm plotting time series data using seaborn lineplot (https://seaborn.pydata.org/generated/seaborn.lineplot.html), and plotting the median instead of mean. Example code:
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
fmri = sns.load_dataset("fmri")
ax = sns.lineplot(x="timepoint", y="signal", estimat... | [
"I don't know if this can be done with seaborn alone, but here's one way to do it with matplotlib, keeping the seaborn style. The describe() method conveniently provides summary statistics for a DataFrame, among them the quartiles, which we can use to plot the medians with inter-quartile-ranges.\nimport seaborn as ... | [
12,
6,
0
] | [] | [] | [
"graph",
"line_plot",
"python",
"seaborn"
] | stackoverflow_0061888674_graph_line_plot_python_seaborn.txt |
Q:
cannot install annoy wheel
I have been trying to install the python package annoy but it always gives an error, I have tried different methods but they don't work.
I have even tried to install the module manually but it does not work either
My Code:
pip install annoy
Error:
Collecting annoy
Using cached annoy-1.... | cannot install annoy wheel | I have been trying to install the python package annoy but it always gives an error, I have tried different methods but they don't work.
I have even tried to install the module manually but it does not work either
My Code:
pip install annoy
Error:
Collecting annoy
Using cached annoy-1.17.0.tar.gz (646 kB)
Preparin... | [
"Below command worked in my case.\npipwin install annoy\n\n"
] | [
0
] | [
"Try installing with conda.\nA lot of libraries that require C/C++ code to be compiled as part of their build and installation can be finicky on windows machines.\nhttps://anaconda.org/conda-forge/python-annoy\nThis article might help too\nhttps://www.programmersought.com/article/95834605670/\n"
] | [
-2
] | [
"annoy",
"python",
"python_3.x"
] | stackoverflow_0071884718_annoy_python_python_3.x.txt |
Q:
Looping an input in Python
I am creating a list with all 12 months of the year. I want to create a loop that will ask as input ("Enter a number) and store all these inputs into an empty list (promptList).
Here is some of my code. I keep getting a TypeError saying at least 1 input is expected.
monthsList = ["Januar... | Looping an input in Python | I am creating a list with all 12 months of the year. I want to create a loop that will ask as input ("Enter a number) and store all these inputs into an empty list (promptList).
Here is some of my code. I keep getting a TypeError saying at least 1 input is expected.
monthsList = ["January", "February", "March", "April"... | [
"Well, the message error is a bit different, and solves it pretty quickly:\nTypeError: input expected at most 1 argument, got 3here\n\nThe input() function expects only one argument - the message prompt. You provided 3 of them (a string, a list element, a string). So refactoring your message to f-string does the jo... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074396988_python.txt |
Q:
Opencv converts transparency to white
I have some images opened from a post request in Django. When I export the image to png, the file is exported right, and the transparency is preserved. When I export to webp format, the transparent layer becomes white. I think there is a problem with the first list of the code... | Opencv converts transparency to white | I have some images opened from a post request in Django. When I export the image to png, the file is exported right, and the transparency is preserved. When I export to webp format, the transparent layer becomes white. I think there is a problem with the first list of the code. The last two lines work just fine when I ... | [
"You need to convert the image img to 4 channels that contains alpha channel\n"
] | [
0
] | [] | [] | [
"image",
"opencv",
"python",
"transparency",
"webp"
] | stackoverflow_0066241687_image_opencv_python_transparency_webp.txt |
Q:
i want to get a specific link, but getting error: AttributeError: 'NoneType' object has no attribute 'get_text'
i want to get the specific link, i know my variable data2 has some errors...
and i'm not sure is this line of code used correctly or not either : "print(data2.strip())"
enter image description here
impo... | i want to get a specific link, but getting error: AttributeError: 'NoneType' object has no attribute 'get_text' | i want to get the specific link, i know my variable data2 has some errors...
and i'm not sure is this line of code used correctly or not either : "print(data2.strip())"
enter image description here
import requests as rq
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from bs... | [
"You can use API for this\nimport requests\n\n\ndef get_stock(code):\n url = f\"https://wwwapi.lcsc.com/v1/products/detail?product_code={code}\"\n headers = {\n 'accept': 'application/json, text/plain, */*',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, li... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074399716_python.txt |
Q:
pandas: subtract row of column from another next row of another column
I have a datetime columns on that basis I calculate min_time and max_time. so from current min_time of the row want to subtract from previous row max_time and want to save into another column. How to do that?
data = pd.DataFrame()
data['datetim... | pandas: subtract row of column from another next row of another column | I have a datetime columns on that basis I calculate min_time and max_time. so from current min_time of the row want to subtract from previous row max_time and want to save into another column. How to do that?
data = pd.DataFrame()
data['datetime'] = 18-6-22 8:22:22, 18-6-22 8:22:23, 18-6-22 8:22:24, 18-6-22 8:22:25, 18... | [
"You can use a combination of sub() and shift(). Of course, the first value will be null because for the first min there is no previous max. Try with:\ndf['diff'] = df['min_time'].sub(df['max_time'].shift(1))\n\nOr, equally in result:\ndf['diff'] = df['min_time'] - df['max_time'].shift(1)\n\nReturning:\n ... | [
0,
0
] | [] | [] | [
"datetime",
"math",
"pandas",
"python"
] | stackoverflow_0074400160_datetime_math_pandas_python.txt |
Q:
I want to send data from my React application to python
I have a React Application with backend on Nodejs and database MySQL, I am using a python api and I want to send data from my React input fields to python so that I can use that data as parameters to my python functions. For this, I am using axios to send dat... | I want to send data from my React application to python | I have a React Application with backend on Nodejs and database MySQL, I am using a python api and I want to send data from my React input fields to python so that I can use that data as parameters to my python functions. For this, I am using axios to send data to a flask server, but I am getting this cyclic object erro... | [
"It seems that you pass strikePrice as an object instead of value field and JSON.stringify() doesn't support object references. Try this:\n axios.post(\"127.0.0.1:5000/trade_data\" , {\n trade_no : trade.value,\n index_name : index.value,\n trade_type : tradeType.value,\n strike_price : ... | [
1
] | [
"Stringify JSON Object and then try sending it. maybe works\n"
] | [
-1
] | [
"axios",
"flask",
"python",
"reactjs"
] | stackoverflow_0074400170_axios_flask_python_reactjs.txt |
Q:
something is wrong google crawler. please
# 뉴스 크롤링.py
#######################################'사용후핵연료' 키워드 검색##################################################
import sys, os
from bs4 import BeautifulSoup
import requests
from selenium import webdriver
import selenium
from selenium.webdriver.common.keys import Keys... | something is wrong google crawler. please | # 뉴스 크롤링.py
#######################################'사용후핵연료' 키워드 검색##################################################
import sys, os
from bs4 import BeautifulSoup
import requests
from selenium import webdriver
import selenium
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import ... | [
"Here is one possible solution:\nfrom openpyxl import Workbook\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.support.ui import WebDriverWait\n... | [
0
] | [] | [] | [
"python",
"web_crawler",
"web_scraping"
] | stackoverflow_0074386364_python_web_crawler_web_scraping.txt |
Q:
interactive 3D surface plot - how to control Plotly's update behaviour
I'm building an interactive plot with the code below: everything works fine, except that Plotly refreshes the figure every time I change a property. So when I move the slider by one tick, Plotly refreshes the figure 4 times, which is annoying t... | interactive 3D surface plot - how to control Plotly's update behaviour | I'm building an interactive plot with the code below: everything works fine, except that Plotly refreshes the figure every time I change a property. So when I move the slider by one tick, Plotly refreshes the figure 4 times, which is annoying to see.
Is there a way to ask Plotly to only refresh the figure at the end of... | [
"Turns out that I need to use panel's Plotly pane. Note that its constructor requires a dictionary with the keys data, layout. If you give it a Plotly figure it will work, but the update will be extremely slow and unreliable.\nSo this is the correct way to achieve my goal. By executing this code, the update will be... | [
0
] | [] | [] | [
"holoviz_panel",
"plotly",
"python"
] | stackoverflow_0072137807_holoviz_panel_plotly_python.txt |
Q:
Swap quoted word in random position with last word in Python
I have a txt file with lines of text like this, and I want to swap the word in
quotations with the last word that is separated from the sentence with a tab:
it looks like this:
This "is" a person are
She was not "here" right
"The" pencil is not sha... | Swap quoted word in random position with last word in Python | I have a txt file with lines of text like this, and I want to swap the word in
quotations with the last word that is separated from the sentence with a tab:
it looks like this:
This "is" a person are
She was not "here" right
"The" pencil is not sharpened a
desired output:
This "are" a person is
She was not ... | [
"You don't really need re for something this trivial.\nAssuming you want to rewrite the file:\nwith open('foo.txt', 'r+') as txt:\n lines = txt.readlines()\n for k, line in enumerate(lines):\n words = line.split()\n for i, word in enumerate(words[:-1]):\n if word[0] == '\"' and word[-... | [
1,
1,
1,
0
] | [] | [] | [
"python",
"regex",
"swap"
] | stackoverflow_0074399654_python_regex_swap.txt |
Q:
How to display the actual HTML page from HTMLResponse in Swagger UI using FastAPI?
I have a FastAPI app that returns an HTMLResponse. The code is simple and straightforward, as the examples in FastAPI's documentation. The response works fine, but Swagger UI displays the raw HTML content. Is there a way to display ... | How to display the actual HTML page from HTMLResponse in Swagger UI using FastAPI? | I have a FastAPI app that returns an HTMLResponse. The code is simple and straightforward, as the examples in FastAPI's documentation. The response works fine, but Swagger UI displays the raw HTML content. Is there a way to display the actual HTML page?
from fastapi import FastAPI
from fastapi.responses import HTMLResp... | [
"This is the expected behaviour by Swagger UI (see here as well). Swagger UI correctly displays the response body, and not how that response would be interpeted by a user-agent; more specifically, a Web browser. That being said, if you return an image using a FileResponse (including the correct media_type, which wo... | [
1
] | [] | [] | [
"fastapi",
"openapi",
"python",
"swagger",
"swagger_ui"
] | stackoverflow_0074399181_fastapi_openapi_python_swagger_swagger_ui.txt |
Q:
Python version 3.9 does not support match statements
I installed Python on a new computer and unfortunately I get an error message from a code that I had been using for quite some time. It is about the 'match' statement. Here is the code:
import os
def save(df, filepath):
dir, filename = os.path.split(filepat... | Python version 3.9 does not support match statements | I installed Python on a new computer and unfortunately I get an error message from a code that I had been using for quite some time. It is about the 'match' statement. Here is the code:
import os
def save(df, filepath):
dir, filename = os.path.split(filepath)
os.makedirs(dir, exist_ok=True)
_, ext = os.pat... | [
"Match statements are a feature of Python 3.10. You'd do best by upgrading to 3.10 or 3.11.\nhttps://monovm.com/blog/how-to-update-python-version/\n",
"Or just if and elif.\nimport os\n\ndef save(df, filepath):\n dir, filename = os.path.split(filepath)\n os.makedirs(dir, exist_ok=True)\n _, ext = os.path... | [
1,
1,
0
] | [] | [] | [
"python",
"python_3.9"
] | stackoverflow_0074400296_python_python_3.9.txt |
Q:
How to replace and split a simple data string using Python into 2 separate outputs
This is the input data I am dealing with.
November (5th-26th)
What I want to do is get 2 seperate outputs from this data string. i.e. {November 5th} and {November 26th}
I currently use this python script to remove the uneccesary ch... | How to replace and split a simple data string using Python into 2 separate outputs | This is the input data I am dealing with.
November (5th-26th)
What I want to do is get 2 seperate outputs from this data string. i.e. {November 5th} and {November 26th}
I currently use this python script to remove the uneccesary characters in it
Name = input_data['date'].replace("(", "").replace(")", "")
output = [{"... | [
"You could do it like this in two steps:\nstring = \"November (5th-26th)\"\nmonth, days = [x.strip('()') for x in string.split(' ')]\nstart, end = days.split('-')\n\noutput = {'date_range' : [f\"{month} {start}\", f\"{month} {end}\"]}\nprint(output)\n\n{'date_range': ['November 5th', 'November 26th']}\n\n2nd task:\... | [
2,
0,
0
] | [] | [] | [
"python",
"split"
] | stackoverflow_0074399948_python_split.txt |
Q:
Istead of replacing a part of a string with the value associated with the key 22, it just replaces it with the value associated with key 2, 2 times
I am converting information about a delivery from a file given to me, it contains information like this:
name, item_number, item_number, item_number
for example
Joe, 2... | Istead of replacing a part of a string with the value associated with the key 22, it just replaces it with the value associated with key 2, 2 times | I am converting information about a delivery from a file given to me, it contains information like this:
name, item_number, item_number, item_number
for example
Joe, 2, 22, 10, 17
The issue is whenever i try to replace the number in the line, with a value associated with the key, which is indetical to the item_number f... | [
"The core problem you have is that you're performing string replacement, which as you've observed, replaces every instance of \"2\" with a value.\nTo illustrate:\n>>> \"222\".replace(\"2\", \"something\")\n'somethingsomethingsomething'\n\nSo, what's a better approach?\nGiven the following file contents as a source:... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074399863_python.txt |
Q:
moving files to new folder in FTP using Python
I am a bit lost. I'm trying to move a bunch of files to a new folder in FTP using python. I have tried a lot of function but what seems to work best is the ftp.rename function. In fact, it works to move only one file at a time to a new folder but it doesn't work to do... | moving files to new folder in FTP using Python | I am a bit lost. I'm trying to move a bunch of files to a new folder in FTP using python. I have tried a lot of function but what seems to work best is the ftp.rename function. In fact, it works to move only one file at a time to a new folder but it doesn't work to do it for a lot of files (like in my screenshot) using... | [
"I was able to find a way to sort my different files :\nI had first to sort my dirList (list with all the files) with new sub list (like allDivers) and then I used the following code\nfor file in allDivers:\n destination_folder = \"/divers/\"\n destination = destination_folder + file\n ftp.rename(fi... | [
1
] | [] | [] | [
"file",
"ftp",
"function",
"python",
"sorting"
] | stackoverflow_0074277070_file_ftp_function_python_sorting.txt |
Q:
python: search in list of lists of dictionaries
I want to iterate over a list of lists of dictionaries:
data = [
{'name': 'sravan'},
{'name': 'bobby'},
{'name': 'ojsawi', 'number': '123'},
{'name': 'rohith', 'number': '456'},
{'name': 'gnanesh', 'number': '123'}
]
Furthermore I want to check e... | python: search in list of lists of dictionaries | I want to iterate over a list of lists of dictionaries:
data = [
{'name': 'sravan'},
{'name': 'bobby'},
{'name': 'ojsawi', 'number': '123'},
{'name': 'rohith', 'number': '456'},
{'name': 'gnanesh', 'number': '123'}
]
Furthermore I want to check each entry if there is a key number where the value is... | [
"You can define it with list comprehensions with a nested if/else in it:\nnew_list = [x.get('name') if x.get('number') == '123' else 0 for x in data]\n\nOutputting:\n[0, 0, 'ojsawi', 0, 'gnanesh']\n\n",
"Other than list comprehensions, you can also do it using map() and functional programming if you want. Note th... | [
2,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"search"
] | stackoverflow_0074400327_dictionary_list_python_search.txt |
Q:
Changing color of a specific object in an image using Opencv
I want to change the color of sofa in the given image:
Background remains same, only color of the sofa need to be changed. I have tried with masking technique but couldn't get the needed color. I am giving sample color.
Please, let me know if there are... | Changing color of a specific object in an image using Opencv | I want to change the color of sofa in the given image:
Background remains same, only color of the sofa need to be changed. I have tried with masking technique but couldn't get the needed color. I am giving sample color.
Please, let me know if there are any easy techniques to customise the color of sofa.
I have alread... | [
"Here is a very basic example on how you can modify hue, saturation and value of a masked object:\nimport cv2\nimport numpy as np\n\n\nimg = cv2.imread('bluesofa.jpg')\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\nlower = np.array([90, 100, 20])\nupper = np.array([120, 255, 255])\n\nmask = cv2.inRange(hsv, lower, ... | [
0
] | [] | [] | [
"colors",
"opencv",
"picker",
"python"
] | stackoverflow_0074386394_colors_opencv_picker_python.txt |
Q:
replace function isn't working the it supposed to work
Hello guys I'm trying to create a function that returns a list out of a string ((((Without the space))))
I'm using the replace function to remove the space however I'm still getting a space
def str2list(argstr):
retlist = []
for c in argstr:
c=... | replace function isn't working the it supposed to work | Hello guys I'm trying to create a function that returns a list out of a string ((((Without the space))))
I'm using the replace function to remove the space however I'm still getting a space
def str2list(argstr):
retlist = []
for c in argstr:
c=c.replace(" ", "")
retlist.append(c)
return retl... | [
"A simple list comprehension should suffice:\ndef str2list(argstr):\n return [c for c in argstr if c != ' ']\n\n",
"If you are open to using regex, you may try:\ninp = \"abc efg\"\nletters = re.findall(r'[a-z]', inp, flags=re.I)\nprint(letters) # ['a', 'b', 'c', 'e', 'f', 'g']\n\nYou could also use:\ninp = \"... | [
3,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074400479_python.txt |
Q:
How to change all the language of Google speech recognition?
Audio_text_from_wav_file = r.recognize_google(audio)
The above line reads only english language but,
If I use:
Audio_text_from_wav_file = r.recognize_google(audio, language ="ru-RU")
My .wav file reads only russian language. How can I able to read all th... | How to change all the language of Google speech recognition? | Audio_text_from_wav_file = r.recognize_google(audio)
The above line reads only english language but,
If I use:
Audio_text_from_wav_file = r.recognize_google(audio, language ="ru-RU")
My .wav file reads only russian language. How can I able to read all the langauges from gtts or googletrans python.
I used libraries such... | [
"You could create a list with all the target languages you want to try, and use a for loop to iterate over that list of target languages:\nimport speech_recognition as sr \nfrom googletrans import Translator \nfrom gtts import gTTS \nimport os\n\n# Set the list of target languages you want here\ntargetLanguages = [... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074397604_python.txt |
Q:
Get HTML class attribute by a the content with bs4 webscraping
So I'm currently trying to get a certain attribute just by the content of the HTML element.
I know how to get an attribute by another attribute in the same HTML section. But this time I need the attribute by the content of the section.
"https://www.ska... | Get HTML class attribute by a the content with bs4 webscraping | So I'm currently trying to get a certain attribute just by the content of the HTML element.
I know how to get an attribute by another attribute in the same HTML section. But this time I need the attribute by the content of the section.
"https://www.skatedeluxe.ch/de/adidas-skateboarding-busenitz-vulc-ii-schuh-white-col... | [
"Try:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.skatedeluxe.ch/de/adidas-skateboarding-busenitz-vulc-ii-schuh-white-collegiate-navy-bluebird_p155979?cPath=216&value[55][]=744\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nsizes = soup.select_one(\"#product-size... | [
2,
1,
1
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074400369_beautifulsoup_html_python_python_requests_web_scraping.txt |
Q:
Validation Json Schema
I am trying to validate the json for required fields using python. I am doing it manually like iterating through the json reading it. Howerver i am looking for more of library / generic solution to handle all scenarios.
For example I want to check in a list, if a particular attribute is avai... | Validation Json Schema | I am trying to validate the json for required fields using python. I am doing it manually like iterating through the json reading it. Howerver i am looking for more of library / generic solution to handle all scenarios.
For example I want to check in a list, if a particular attribute is available in all the list items.... | [
"A JSON Schema is a way to define the structure of JSON.\nThere are some accompanying python packages which can use a JSON schema to validate JSON (jsonschema).\nThe JSON Schema for your example would look approximately like this:\n{\n \"type\": \"object\",\n \"properties\": {\n \"service\": {\n ... | [
0,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074400434_json_python.txt |
Q:
Python - nested list comprehension with tokenizing
Python question: I have a list of sentences on which I want to apply nltk stemming. So for each word in each sentence, I want to apply, in this case, the nltk snowball.stem function.
I want to write that as short as possible via list comprehension.
Below code work... | Python - nested list comprehension with tokenizing | Python question: I have a list of sentences on which I want to apply nltk stemming. So for each word in each sentence, I want to apply, in this case, the nltk snowball.stem function.
I want to write that as short as possible via list comprehension.
Below code works fine, but I want to write it in less lines:
data_stemm... | [
"nltk.word_tokenize accepts as input a string, but data is a list of strings. What you need is:\ndata = ['doing do done', 'requires require', 'shoe shoes']\njoined_data = ' '.join(data)\ndata_stemming=[[snowball.stem(w) for w in word_list] for word_list in nltk.word_tokenize(joined_data)]\n\n",
"You can try doing... | [
0,
0
] | [] | [] | [
"list",
"list_comprehension",
"nested",
"python"
] | stackoverflow_0074353671_list_list_comprehension_nested_python.txt |
Q:
Sort list of dictionaries based on multiple values inside the dictionaries
I know how to sort a list of dictionaries based on the values, however in this problem I have a couple of conditions that I need the list to sorted based on.
Imagine a list of 4 footbal teams, like in group stage of the Worldcup. For each t... | Sort list of dictionaries based on multiple values inside the dictionaries | I know how to sort a list of dictionaries based on the values, however in this problem I have a couple of conditions that I need the list to sorted based on.
Imagine a list of 4 footbal teams, like in group stage of the Worldcup. For each team we have a dictionary containing team's wins,loses and points.
Now we need to... | [
"Just specify them like this:\nnew_list=sorted(teams, key=lambda d: (d['points'], d['wins'], d['names']))\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074400569_dictionary_list_python.txt |
Q:
Extract Lists from tuple with a condition
I was trying to extract lists from a tuple with a condition that every X numbers in ascending order should be extracted in same list, using a list comprehension.
Example:
Input: (4,2,2,3,5,6,0,0,2)
Desired output: [[4],[2,2,3,5,6],[0,0,2]]
I tried the following:
E=tuple(... | Extract Lists from tuple with a condition | I was trying to extract lists from a tuple with a condition that every X numbers in ascending order should be extracted in same list, using a list comprehension.
Example:
Input: (4,2,2,3,5,6,0,0,2)
Desired output: [[4],[2,2,3,5,6],[0,0,2]]
I tried the following:
E=tuple([random.randint(0,10) for x in range(10)])
Res=... | [
"Here, simple logic to create new list already with the first element tuple. and then loop over tuple and if its current element is less then last element or not, if its smaller then append element as a list or append element into the last list.\nCode:\nimport random\nE=tuple([random.randint(0,10) for x in range(10... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074400007_python.txt |
Q:
Pip install a package in a way that it gets not listed in requirements.txt
Is it possible to install a pip package in a way so that it gets not listed when doing pip freeze > requirements.txt?
I am thinkging of an equivalent to: poetry add --dev which adds (installs) a package as a development dependency, but it d... | Pip install a package in a way that it gets not listed in requirements.txt | Is it possible to install a pip package in a way so that it gets not listed when doing pip freeze > requirements.txt?
I am thinkging of an equivalent to: poetry add --dev which adds (installs) a package as a development dependency, but it does not appear in dependency list.
Is there a way in pip to do something similar... | [
"What you want is pipenv.\nThere are ways of making RStudio work with pipenv (link to an article).\nThis allows both complete package control, python version specification for a project as well as virtualenv, all in one.\nOtherwise, you'd have to maintain your requirements.txt file manually, and further down the li... | [
1
] | [] | [] | [
"pip",
"python",
"python_3.x",
"python_poetry"
] | stackoverflow_0074400450_pip_python_python_3.x_python_poetry.txt |
Q:
Python serializer one universal function
Please help! The reviewer wants me to correct my code. I have such a code structure . He wants me to move this line ('if request is None or request.user.is_anonymous: return False') to a separate code structure (function or class).
class CustomUserSerializer(UserSerializer)... | Python serializer one universal function | Please help! The reviewer wants me to correct my code. I have such a code structure . He wants me to move this line ('if request is None or request.user.is_anonymous: return False') to a separate code structure (function or class).
class CustomUserSerializer(UserSerializer):
""" Сериализатор модели пользователя. """
i... | [
"Moving a piece of code into a function or method is a common refactoring pattern. You can also move it to a class, but in your particular case, that would not make too much sense since it's a very simple expression and classes aren't meant for such simple expressions.\nAfter you move the boolean expression into a ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074400457_python.txt |
Q:
Seaborn.lineplot() SEM error bars not working
I have the following code. I want to plot error bars representing the standard error of the mean on the graphs below. However, when I run the code, I get the error: 'Line2D' object has no property 'errorbar'
fig, axes = plt.subplots(nrows=2,figsize=(15, 15))
fig.tight_... | Seaborn.lineplot() SEM error bars not working | I have the following code. I want to plot error bars representing the standard error of the mean on the graphs below. However, when I run the code, I get the error: 'Line2D' object has no property 'errorbar'
fig, axes = plt.subplots(nrows=2,figsize=(15, 15))
fig.tight_layout(pad=6)
newerdf=newdf.copy()
bins = [0, 2, 4... | [
"The seaborn version 0.11 don't have this feature.\nYou should upgrade your seaborn at least to version 0.12.x in your environment with the command:\npip install --upgrade seaborn\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"plot",
"python"
] | stackoverflow_0074179577_matplotlib_pandas_plot_python.txt |
Q:
How to get immediate next index in dataframe if we don't know how indexing was done?
Let's say we getting pandas index as input for a function. Then I need to get the next immediate index from the dataframe based on the index input. The dataframe index can be a string or number. I want to know how to do this.
For ... | How to get immediate next index in dataframe if we don't know how indexing was done? | Let's say we getting pandas index as input for a function. Then I need to get the next immediate index from the dataframe based on the index input. The dataframe index can be a string or number. I want to know how to do this.
For example:
index
col 1
2342
aaa
2822
bbb
3452
ccc
If the function gets 2342 ... | [
"You can start by finding the actual row index of the row with the index you want to get. With the example dataframe and 2342 as input, this would be 0. Then simply add 1 to this row index and use iloc. Code:\ni = 2342\nrow_index = df.loc[df['index'] == i].index.item()\ndf.iloc[row_index + 1, df.columns.get_loc('in... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074397991_pandas_python.txt |
Q:
How to transpose a single column into an index row in the same dataframe?
This is my dataset:
Name
Assignment
Scores
Boo
Test1
0.9
Buzz
Test3
0.7
Bree
Test2
1.0
Boo
Quiz
1.0
Buzz
Test1
0.8
How I want my result:
Name
Test1
Test3
Test2
Quiz
Boo
0.9
0
0
1.0
Buzz
0.8
0.7
0
0
Bree
0
0
1.0
0
.T only seems to... | How to transpose a single column into an index row in the same dataframe? | This is my dataset:
Name
Assignment
Scores
Boo
Test1
0.9
Buzz
Test3
0.7
Bree
Test2
1.0
Boo
Quiz
1.0
Buzz
Test1
0.8
How I want my result:
Name
Test1
Test3
Test2
Quiz
Boo
0.9
0
0
1.0
Buzz
0.8
0.7
0
0
Bree
0
0
1.0
0
.T only seems to work for the entire df and I tried .pivot() as well :/... | [
"use pivot_table\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html\ndf.pivot_table('Scores', index='Name', columns='Assignment', fill_value=0)\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"matrix",
"pandas",
"python",
"transpose"
] | stackoverflow_0074400633_dataframe_matrix_pandas_python_transpose.txt |
Q:
if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta'
A source Django 3 by examples Chapter 14
When I try to run
python manage.py migrate --settings=educa.settings.pro
Another files are copies and pastes from the book
The result is
File "C:... | if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' | A source Django 3 by examples Chapter 14
When I try to run
python manage.py migrate --settings=educa.settings.pro
Another files are copies and pastes from the book
The result is
File "C:\Python\educa\manage.py", line 22, in <module>
main()
File "C:\Python\educa\manage.py", line 18, in main
execute_from_comm... | [
"If you provide the code for your models.py file, that would help. However, a good reason for this type of error is when you're creating a through table for a many to many join and the through model has no __str__ method in it's Meta class. If the method exists check that the indentation is correct.\n",
"I also ... | [
0,
0,
0
] | [] | [] | [
"django",
"django_3.2",
"django_migrations",
"django_rest_framework",
"python"
] | stackoverflow_0069676161_django_django_3.2_django_migrations_django_rest_framework_python.txt |
Q:
Time of day Python
for i in range(len(df)):
if df.loc[i, 'Hour'] >=6 & df.loc[i, 'Hour'] <= 12:
df['time_of_day'] = "Morning"
elif df.loc[i, 'Hour'] > 12 & df.loc[i, 'Hour'] <= 17:
df['time_of_day'] == "Afternoon"
elif df.loc[i, 'Hour'] > 17 & df.loc[i, 'Hour'] <= 22:
... | Time of day Python | for i in range(len(df)):
if df.loc[i, 'Hour'] >=6 & df.loc[i, 'Hour'] <= 12:
df['time_of_day'] = "Morning"
elif df.loc[i, 'Hour'] > 12 & df.loc[i, 'Hour'] <= 17:
df['time_of_day'] == "Afternoon"
elif df.loc[i, 'Hour'] > 17 & df.loc[i, 'Hour'] <= 22:
df['time_of_day'] == "Ev... | [
"When you call df['time_of_day'] = \"Morning\" , you are assigning \"morning\" to every value in that column. What you really want to do is apply your logic to each row separately. The smartest way to do this is with the apply method. All you need to do is define a function for your logic beforehand.\n\ndef determi... | [
1
] | [] | [] | [
"python",
"time"
] | stackoverflow_0074400646_python_time.txt |
Q:
How to convert JSON data into a Python class?
How to convert JSON data into a Python class?
class AnotherClass():
test: int
class MyClass():
a: int
c: AnotherClass
json = {
"a": 1,
"c": {
"test": 2
}
}
my_class = MyClass(json)
print(my_class.a) # 1
print(my_class.c.test) # error
... | How to convert JSON data into a Python class? | How to convert JSON data into a Python class?
class AnotherClass():
test: int
class MyClass():
a: int
c: AnotherClass
json = {
"a": 1,
"c": {
"test": 2
}
}
my_class = MyClass(json)
print(my_class.a) # 1
print(my_class.c.test) # error
I've tried using the _dict_ attribute, but the va... | [
"You can use dataclasses as follows, note the quirk of __post_init__ to handle nested dataclasses:\nfrom dataclasses import dataclass\n\n@dataclass\nclass AnotherClass:\n test: int\n\n@dataclass\nclass MyClass:\n a: int\n c: AnotherClass\n\n def __post_init__(self):\n self.c = AnotherClass(**self... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074399174_python.txt |
Q:
Tensorflow padding error: paddings must be no greater than the dimension size: 62, 61 greater than 5
I want to pad my tensor from shape (1, 5, 256) to (1, 128, 256). When I try the below code with constants 0 then it works.
tensor = tf.expand_dims(image_output, axis=1)
logg = tf.constant([ [0, 0] , [62, 61], ... | Tensorflow padding error: paddings must be no greater than the dimension size: 62, 61 greater than 5 | I want to pad my tensor from shape (1, 5, 256) to (1, 128, 256). When I try the below code with constants 0 then it works.
tensor = tf.expand_dims(image_output, axis=1)
logg = tf.constant([ [0, 0] , [62, 61], [0, 0] ])
new_tensor = tf.pad(tensor, logg, mode ='CONSTANT', constant_values=0)
However when I try ... | [
"that is because padding of the target dimension is the result of the padding input array, see my example the function allowed that's because matches the shape size. ( Matrixes dimensions )\n\nSample: Matrixes is the name of the clock when it counters it creates new dimensions.\n\nimport os\nfrom os.path import exi... | [
1
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074400566_python_tensorflow.txt |
Q:
Pass a dictionary as default arguments of a function
let's say i have a function like this:
def foo (a = "a", b="b", c="c", **kwargs):
#do some work
I want to pass a dict like this to the function as the only argument.
arg_dict = {
"a": "some string"
"c": "some other string"
}
which should change the... | Pass a dictionary as default arguments of a function | let's say i have a function like this:
def foo (a = "a", b="b", c="c", **kwargs):
#do some work
I want to pass a dict like this to the function as the only argument.
arg_dict = {
"a": "some string"
"c": "some other string"
}
which should change the values of the a and c arguments but b still remains the d... | [
"This works out of the box like\nfoo(**arg_dict)\n\n",
"You can unpack the arg_dict using ** operator.\n>>> def foo (a = \"a\", b=\"b\", c=\"c\", **kwargs):\n... print(f\"{a=}\")\n... print(f\"{b=}\")\n... print(f\"{c=}\")\n... print(f\"{kwargs=}\")\n... \n>>> arg_dict = {\n... \"a\": \"some s... | [
1,
1
] | [] | [] | [
"arguments",
"parameter_passing",
"python"
] | stackoverflow_0074400829_arguments_parameter_passing_python.txt |
Q:
Tkinter hangs after using `destroy` and `quit`
I'm using Tkinter to show a login dialog and then run my main logic.
I intend for the following snippet to close the window (finish the main loop of tk) after clicking the button and just print indefinitely (it is wrapped in while True is in order for the whole script... | Tkinter hangs after using `destroy` and `quit` | I'm using Tkinter to show a login dialog and then run my main logic.
I intend for the following snippet to close the window (finish the main loop of tk) after clicking the button and just print indefinitely (it is wrapped in while True is in order for the whole script to continue executing, which simulates a real progr... | [
"Try this:\nfrom Tkinter import *\ndef quit():\n global root\n root.quit()\n\nroot = Tk()\nwhile True:\n Button(root, text=\"Quit\", command=quit).pack()\n root.mainloop()\n\n"
] | [
0
] | [] | [] | [
"macos",
"python",
"tkinter"
] | stackoverflow_0074395130_macos_python_tkinter.txt |
Q:
The view products.views.get_product didn't return an HttpResponse object. It returned None instead
ValueError at /product/apple-ipad-air-5th-gen-64-gb-rom-109-inch-with-wi-fi5g-purple/
The view products.views.get_product didn't return an HttpResponse object. It returned None instead.
how can i solve this problem p... | The view products.views.get_product didn't return an HttpResponse object. It returned None instead | ValueError at /product/apple-ipad-air-5th-gen-64-gb-rom-109-inch-with-wi-fi5g-purple/
The view products.views.get_product didn't return an HttpResponse object. It returned None instead.
how can i solve this problem please help me
`
from django.shortcuts import render,redirect
from products.models import Product
from ac... | [
"You got this error because return is inside if statement.\nI have modified this:\n try:\n context = {'product': product, }\n if request.GET.get('size'):\n size = request.GET.get('size')\n price = product.get_product_price_by_size(size)\n context['selected_size'] = ... | [
0
] | [] | [] | [
"django",
"httpresponse",
"python",
"valueerror"
] | stackoverflow_0074400888_django_httpresponse_python_valueerror.txt |
Q:
'expand' won't do what I want. How do I generate a custom list of inputs to a rule in Snakemake?
I want to run a Snakemake workflow where the input is defined by a combination of different variables (e.g. pairs of samples, sample ID and Nanopore barcode,...):
sample_1 = ["foo", "bar", "baz"]
sample_2 = ["spam", "h... | 'expand' won't do what I want. How do I generate a custom list of inputs to a rule in Snakemake? | I want to run a Snakemake workflow where the input is defined by a combination of different variables (e.g. pairs of samples, sample ID and Nanopore barcode,...):
sample_1 = ["foo", "bar", "baz"]
sample_2 = ["spam", "ham", "eggs"]
I've got a rule using these:
rule frobnicate:
input:
assembly = "{first_samp... | [
"Using expand with other combinatoric functions\nBy default, expand uses the itertools function product. However, it's possible to specify another function for expand to use. \nTo combine the first variable in the first with the first in the second and so on, one can tell expand to use zip:\nsample_1 = [\"foo\", \"... | [
4
] | [] | [] | [
"python",
"snakemake"
] | stackoverflow_0074400966_python_snakemake.txt |
Q:
Unable to refresh plt.axhline() in matplotlib
I'm just trying to make a live graph using matplotlib.However I couldn't find a way to draw-remove-redraw axhline(). My aim is to show a horizontal line of newest value of Y axis values and of course remove the recent horizontal line.
`
import matplotlib.pyplot as plt
... | Unable to refresh plt.axhline() in matplotlib | I'm just trying to make a live graph using matplotlib.However I couldn't find a way to draw-remove-redraw axhline(). My aim is to show a horizontal line of newest value of Y axis values and of course remove the recent horizontal line.
`
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matpl... | [
"In your code, this:\nplt.axhline(y = ys[-2], linewidth=2, color='r', linestyle='-').remove()\n\ndoesn't remove the previous axhline; it adds a new axhline at y=ys[-2] and then immediately removes it. So, it effectively does nothing.\nYou have to remove the same line you inserted with plt.axhline. Save the object r... | [
0
] | [] | [] | [
"livegraph",
"matplotlib",
"matplotlib_animation",
"python"
] | stackoverflow_0074394510_livegraph_matplotlib_matplotlib_animation_python.txt |
Q:
vscode Flake8 ignore
Flake8 was installed lately by one of the updates of vscode. I think it is time to comply to the "rules" of python to writer better and more readable code. Unfortunately I have some errors that I cannot fix in the code (no discussion about that, but a local module has to be loaded before some ... | vscode Flake8 ignore | Flake8 was installed lately by one of the updates of vscode. I think it is time to comply to the "rules" of python to writer better and more readable code. Unfortunately I have some errors that I cannot fix in the code (no discussion about that, but a local module has to be loaded before some others). I want to ignore ... | [
"seems like python.linting.flake8Args no longer works, I can get flake to work, but I get everything.\nMy solution was to install the flake8 plugin: https://marketplace.visualstudio.com/items?itemName=ms-python.flake8\nand use the flake8.args:\n\"flake8.args\": [\n \"--ignore=E24,E128,E201,E202,E225,E231,E252,E265... | [
1
] | [] | [] | [
"flake8",
"python",
"visual_studio_code"
] | stackoverflow_0074400353_flake8_python_visual_studio_code.txt |
Q:
if string is not in a df column save in new variable - python
I have a list with numbers e.g (1,2,3,4,5,6,7,8,9) called allowed_numbers
and a column in a df with numbers e.g (1,3,5,6,8,9,10,15,24) B-NUMBER
I would like to save the numbers that dont match in another variable, in this example '10,15,24'
fraud = (df[... | if string is not in a df column save in new variable - python | I have a list with numbers e.g (1,2,3,4,5,6,7,8,9) called allowed_numbers
and a column in a df with numbers e.g (1,3,5,6,8,9,10,15,24) B-NUMBER
I would like to save the numbers that dont match in another variable, in this example '10,15,24'
fraud = (df['B-NUMBER'] != allowed_number)
This gives me an error that the len... | [
"Use lambda function with filter values of strings if not match splitted string s converted to sets for improve performance:\ns = '1,2,3,4,5,6,7'\n\nS = set(s.split(','))\n\ndf = pd.DataFrame({'numbers':['001272532129', '001272532129']})\n\ndf['new'] = df['numbers'].apply(lambda x: ''.join(y for y in x if y not in ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"string"
] | stackoverflow_0074400656_dataframe_pandas_python_string.txt |
Q:
SVG rendering in a PyGame application. Prior to Pygame 2.0, Pygame did not support SVG. Then how did you load it?
In a pyGame application, I would like to render resolution-free GUI widgets described in SVG.
How can I achieve this?
(I like the OCEMP GUI toolkit but it seems to be bitmap dependent for its rendering... | SVG rendering in a PyGame application. Prior to Pygame 2.0, Pygame did not support SVG. Then how did you load it? | In a pyGame application, I would like to render resolution-free GUI widgets described in SVG.
How can I achieve this?
(I like the OCEMP GUI toolkit but it seems to be bitmap dependent for its rendering)
| [
"This is a complete example which combines hints by other people here.\nIt should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.\n#!/usr/bin/python\n\nimport array\nimport math\n\nimport cairo\nimport pygame\nimp... | [
21,
16,
11,
7,
4,
3,
2,
1,
0,
0
] | [] | [] | [
"pygame",
"pygame_surface",
"python",
"svg",
"widget"
] | stackoverflow_0000120584_pygame_pygame_surface_python_svg_widget.txt |
Q:
Build a monthly index schedule, considering business days in Pandas
Found similar questions that beat around the bush but could not nail down this one.
I want to input an arbitrary date (ex 2022 4 11) and from there build a monthly schedule of dates for "n" months (48 for example) but the series has to:
(a) take i... | Build a monthly index schedule, considering business days in Pandas | Found similar questions that beat around the bush but could not nail down this one.
I want to input an arbitrary date (ex 2022 4 11) and from there build a monthly schedule of dates for "n" months (48 for example) but the series has to:
(a) take into account business days only and exclude holidays (I have a list of the... | [
"I have found a way \"adding up\" a couple of other solutions to similar problems. Code below.\n import pandas as pd\n from pandas.tseries.offsets import Day, BDay\n from pandas.tseries.offsets import CustomBusinessDay\n\n hols = list(pd.to_datetime(pd.read_csv(\"hols.csv\", delimiter=\";\", > parse_dat... | [
0
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074400689_datetime_pandas_python.txt |
Q:
How to average numeric values across multiple lists in a dictionary?
I created the following dictionary that includes multiple key-value pairs. The values are lists containing numbers.
PLE_dict = {
"Task_1": [1, 2, 8],
"Task_2": [5, 1, 9],
"Task_3": [1, 1, 3],
"Task_4": [5, 3 ,5],
... | How to average numeric values across multiple lists in a dictionary? | I created the following dictionary that includes multiple key-value pairs. The values are lists containing numbers.
PLE_dict = {
"Task_1": [1, 2, 8],
"Task_2": [5, 1, 9],
"Task_3": [1, 1, 3],
"Task_4": [5, 3 ,5],
}
I also have an empty list: Task_mean = []
My aim is to compute t... | [
"Here is one solution with zip, sum and len which are builtin functions in python.\n>>> PLE_dict = {\n... \"Task_1\": [1, 2, 8],\n... \"Task_2\": [5, 1, 9],\n... \"Task_3\": [1, 1, 3],\n... \"Task_4\": [5, 3 ,5],\n... }\n>>> \n>>> [sum(lst) / len(lst) for lst in zip(*PLE_dict... | [
2,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074401152_dictionary_python.txt |
Q:
How to extract multi table from pdf with their page number by using camelot?
I have one pdf file, it has 40 tables in different pages. I want to extract each table with its page number.
I have tried to use this code:
import camelot
tables = camelot.read_pdf('2003.pdf', flavor='stream', pages='8,9,10,14,15,18,24..... | How to extract multi table from pdf with their page number by using camelot? | I have one pdf file, it has 40 tables in different pages. I want to extract each table with its page number.
I have tried to use this code:
import camelot
tables = camelot.read_pdf('2003.pdf', flavor='stream', pages='8,9,10,14,15,18,24...', edge_tol=500, flag_size=True)
for page in range(tables.n):
tables[page].to... | [
"As mentioned in the Camelot Quickstart guide,\n\nNow, we have a TableList object called tables, which is a list of\nTable objects. We can get everything we need from this object.\n[…]\nLet's print the parsing report.\nprint tables[0].parsing_report\n{\n 'accuracy': 99.02,\n 'whitespace': 12.24,\n 'order':... | [
0
] | [] | [] | [
"python",
"python_camelot"
] | stackoverflow_0074392467_python_python_camelot.txt |
Q:
In python-igraph, find the number and mode of edges between two vertices
In a directed python-igraph, I can find the paths between two vertices as follows:
g=ig.Graph(directed=True)
g.add_vertices(range(4))
g.add_edges([(0,1),(0,2),(1,3)])
paths=g.get_all_shortest_paths(3,2,mode='all')
paths
[[3, 1, 0, 2]]
Is t... | In python-igraph, find the number and mode of edges between two vertices | In a directed python-igraph, I can find the paths between two vertices as follows:
g=ig.Graph(directed=True)
g.add_vertices(range(4))
g.add_edges([(0,1),(0,2),(1,3)])
paths=g.get_all_shortest_paths(3,2,mode='all')
paths
[[3, 1, 0, 2]]
Is there a simple way to get the modes (in or out) of the edges along the path?
I... | [
"Something like this should do the trick:\ndef consecutive_pairs(items):\n return zip(items, items[1:])\n\n\ndef classify_edges_in_path(path, graph):\n return [\n \"in\" if graph.get_eid(u, v, error=False) >= 0 else \"out\"\n for u, v in consecutive_pairs(path)\n ]\n\nThe trick here is that g... | [
2
] | [] | [] | [
"directed_graph",
"igraph",
"python"
] | stackoverflow_0074366295_directed_graph_igraph_python.txt |
Q:
how do you properly reuse an httpx.AsyncClient wihtin a FastAPI application?
I have a FastAPI application which, in several different occasions, needs to call external APIs. I use httpx.AsyncClient for these calls. The point is that I don't fully understand how I shoud use it.
From httpx' documentation I should us... | how do you properly reuse an httpx.AsyncClient wihtin a FastAPI application? | I have a FastAPI application which, in several different occasions, needs to call external APIs. I use httpx.AsyncClient for these calls. The point is that I don't fully understand how I shoud use it.
From httpx' documentation I should use context managers,
async def foo():
""""
I need to call foo quite often f... | [
"You can have a global client that is closed in the FastApi shutdown event.\nimport logging\nfrom fastapi import FastAPI\nimport httpx\n\nlogging.basicConfig(level=logging.INFO, format=\"%(levelname)-9s %(asctime)s - %(name)s - %(message)s\")\nLOGGER = logging.getLogger(__name__)\n\n\nclass HTTPXClientWrapper:\n\n ... | [
5,
3
] | [
"Well your alternative look good to me, you spawn a client and reuse it every time you need it but you are right nobody close the session.\nfrom httpx doc: (in your case import BackgroundTask and StreamingResponse from fastApi)\nimport httpx\nfrom starlette.background import BackgroundTask\nfrom starlette.responses... | [
-2
] | [
"fastapi",
"httpx",
"python"
] | stackoverflow_0071031816_fastapi_httpx_python.txt |
Q:
Kedro - Getting path to item in the datacatalog
I'm training an nlp model using spacy. I have the preprocessing steps all written as a pipeline, and now I need to do the training. According to spacy's documentation I need to run the following command:
python -m spacy train config.cfg --output ./output --paths.trai... | Kedro - Getting path to item in the datacatalog | I'm training an nlp model using spacy. I have the preprocessing steps all written as a pipeline, and now I need to do the training. According to spacy's documentation I need to run the following command:
python -m spacy train config.cfg --output ./output --paths.train ./train.spacy --paths.dev ./dev.spacy
The files co... | [
"The variables you are using as input are strings. While data catalog is different. The data catalog variables are Kedro Dataset.\nBoth are different. Store the path as part of config and you shall get your project started.\n",
"This is probably not the most elegant solution to this, but it works for me so I'll u... | [
0,
0
] | [] | [] | [
"kedro",
"machine_learning",
"mlops",
"python",
"spacy_3"
] | stackoverflow_0074400188_kedro_machine_learning_mlops_python_spacy_3.txt |
Q:
QR decomposition
Is there a way to implement a QR decomposition like in Matlab? In particular, I am interested in the following command:
[C,R,P] = qr(S,B)
According to the description it "returns a permutation matrix P that is chosen to reduce fill-in in R. You can use C, R, and P to compute a least-squares soluti... | QR decomposition | Is there a way to implement a QR decomposition like in Matlab? In particular, I am interested in the following command:
[C,R,P] = qr(S,B)
According to the description it "returns a permutation matrix P that is chosen to reduce fill-in in R. You can use C, R, and P to compute a least-squares solution to the sparse linea... | [
"scipy.linalg.qr provides the functionality you're looking for when given the argument pivoting=True.\n"
] | [
0
] | [] | [] | [
"matrix",
"matrix_decomposition",
"python",
"qr_decomposition"
] | stackoverflow_0074401008_matrix_matrix_decomposition_python_qr_decomposition.txt |
Q:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 1, 5), found shape=(None, 5)
I've split my dataset into X_train and y_train dataframes with respective shapes of (371,5) and (371,) and I can't understand why I keep getting the above error. Code is below:
`
import tens... | ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 1, 5), found shape=(None, 5) | I've split my dataset into X_train and y_train dataframes with respective shapes of (371,5) and (371,) and I can't understand why I keep getting the above error. Code is below:
`
import tensorflow as tf #machine learning
from sklearn import metrics
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_... | [] | [] | [
"The input shape should be the shape of a single sample. In the following case, the input data has 4 rows and 5 columns. Each row represents a sample, and the sample size is (5,). As a result, the first layer's input shape should be (5,).\nimport numpy as np\nimport tensorflow as tf\n#dummy data\nx_train = np.array... | [
-1
] | [
"keras",
"multiclass_classification",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074268987_keras_multiclass_classification_neural_network_python_tensorflow.txt |
Q:
Odoo 14, issue when trying to computing bank balance in treasury module
i got work to fix error when computing but i still dont have idea how to fix it because i'm still newbie
Odoo Server Error
Traceback (most recent call last): File
"/home/equipAccounting/equip/odoo/addons/base/models/ir_http.py", line
237, i... | Odoo 14, issue when trying to computing bank balance in treasury module | i got work to fix error when computing but i still dont have idea how to fix it because i'm still newbie
Odoo Server Error
Traceback (most recent call last): File
"/home/equipAccounting/equip/odoo/addons/base/models/ir_http.py", line
237, in _dispatch
result = request.dispatch() File "/home/equipAccounting/equip/o... | [
"Odoo has a very powerful ORM API to do the psql queries. Is there a good reason you use sql instead?\nThe functions you need are, Read for selecting the fields you use, search and filtered for filtering the results.\nI suggest reading the following tutorial.\nhttps://www.odoo.com/documentation/14.0/developer/refer... | [
1,
1
] | [] | [] | [
"odoo",
"odoo_14",
"postgresql",
"python"
] | stackoverflow_0074398981_odoo_odoo_14_postgresql_python.txt |
Q:
Python NumPy, can't create array of items array
I have a NumPy dataset with sentence IDs and descriptions values. I would like to create an ordered list in my desired format which is... [['value'], ['value']] containing just description values. The order of the new list must stay the same as the original so I can... | Python NumPy, can't create array of items array | I have a NumPy dataset with sentence IDs and descriptions values. I would like to create an ordered list in my desired format which is... [['value'], ['value']] containing just description values. The order of the new list must stay the same as the original so I can match them back to the IDs later.
My issue is that I... | [
"You can simply add the additional dimension when defining your array: description = np.array([[description[1]] for description in chunk]).\n"
] | [
2
] | [] | [] | [
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074401251_numpy_python_python_3.x.txt |
Q:
Failing to install GDAL on python:3.9 as of Nov 8th
I have a docker container that has been successfully installing GDAL 3.5.0 up until Nov 8th, 2022. The last passing build with the exact same code was on Nov 7th. The failures occur in a remote environment on the default GitHub Action (or AWS codebuild runner), a... | Failing to install GDAL on python:3.9 as of Nov 8th | I have a docker container that has been successfully installing GDAL 3.5.0 up until Nov 8th, 2022. The last passing build with the exact same code was on Nov 7th. The failures occur in a remote environment on the default GitHub Action (or AWS codebuild runner), and I haven't had the same error locally. Without changing... | [
"I have the same problem with the exact same error\n/usr/bin/ld: /lib/x86_64-linux-gnu/libmvec.so.1: unknown type [0x13] section `.relr.dyn'\n\nin a container installing the R package \"bit\" that used to be perfectly functional a few days ago. I think that it is related to this: https://www.mail-archive.com/debian... | [
3
] | [] | [] | [
"docker",
"g++",
"gcc",
"gdal",
"python"
] | stackoverflow_0074377793_docker_g++_gcc_gdal_python.txt |
Q:
SharePoint checkout File by python
So, I already searched a lot in different forums but I just can´t make it work for me.
I want to automate a tool. Therefore I´m trying to checkout a SharePoint File in a python script:
import requests
from requests.auth import HTTPBasicAuth
headers = {'User-Agent': 'Mozilla/5.0 ... | SharePoint checkout File by python | So, I already searched a lot in different forums but I just can´t make it work for me.
I want to automate a tool. Therefore I´m trying to checkout a SharePoint File in a python script:
import requests
from requests.auth import HTTPBasicAuth
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537... | [
"The problem seems that you are not passing the correct form digest value in your headers. The form digest value is a security token that SharePoint requires for any POST requests that modify the state of the server. You can obtain the form digest value by making a POST request to the /_api/contextinfo endpoint and... | [
0
] | [
"it looks like you're trying to connect to a corporate account. \nThis probably does not answer your question, but here I might suggest another way using the Microsoft Graph API.\nThe advantage of this way is that every user can use this interface with his individual rights. To allow authentication you first need t... | [
-1
] | [
"post",
"python",
"rest",
"sharepoint"
] | stackoverflow_0059838913_post_python_rest_sharepoint.txt |
Q:
Adding a simple row into a dataframe?
I was spending hours trying to do such a simple thing,
I have a dataframe:
a b c d
0 1 2 3 4
1 5 6 7 8
2 2 3 4 5
3 5 6 7 8
4 1 2 3 4
I have a dictionary:
dic = {'b':6,'d':2}
I would like to do 2 different things :
Simply add a row to the df, with this dic using NaN for co... | Adding a simple row into a dataframe? | I was spending hours trying to do such a simple thing,
I have a dataframe:
a b c d
0 1 2 3 4
1 5 6 7 8
2 2 3 4 5
3 5 6 7 8
4 1 2 3 4
I have a dictionary:
dic = {'b':6,'d':2}
I would like to do 2 different things :
Simply add a row to the df, with this dic using NaN for column 'a' and 'c'
Modify a row with a condit... | [
"For new row with default RangeIndex use DataFrame.loc:\ndic = {'b':6,'d':2}\ndf.loc[len(df)] = dic\n\nFor modify columns by condition working well for me with your solution, for oldier pandas/python version convert keys and values to lists:\ndic = {'b':60,'d':20}\n\ndf.loc[df['a'] == 1, list(dic.keys())] = list(di... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074401422_pandas_python.txt |
Q:
How can I use Sagemaker built-in algorithms locally without estimators?
I am interested in using the AWS Sagemaker built-in algorithms (or pre-trained models) without calling an Estimator class, just like I would do with tensorflow or scikit-learn locally.
I have found this but it uses an Estimator class to do the... | How can I use Sagemaker built-in algorithms locally without estimators? | I am interested in using the AWS Sagemaker built-in algorithms (or pre-trained models) without calling an Estimator class, just like I would do with tensorflow or scikit-learn locally.
I have found this but it uses an Estimator class to do the training:
https://sagemaker.readthedocs.io/en/stable/overview.html?highlight... | [
"Pretrained models\nIf you want to use a pretrained model, you don't have to go through the estimator because you already have the artifact of the model.\nYou can see a guide here: Host a Pretrained Model on SageMaker\nIn a nutshell, the turn it takes is to load the pre-trained model and package it in the usual mod... | [
1
] | [] | [] | [
"amazon_sagemaker",
"amazon_web_services",
"python"
] | stackoverflow_0074401139_amazon_sagemaker_amazon_web_services_python.txt |
Q:
Object of type QueryResponse is not JSON serializable - Python 3.9 fastAPI using Pinecone
Given the following API response from pinecone (https://www.pinecone.io/docs/api/operation/query/)
results = {'matches': [{'id': 'yral5m',
'metadata': {'subreddit': '2qkq6',
'text': 'B... | Object of type QueryResponse is not JSON serializable - Python 3.9 fastAPI using Pinecone | Given the following API response from pinecone (https://www.pinecone.io/docs/api/operation/query/)
results = {'matches': [{'id': 'yral5m',
'metadata': {'subreddit': '2qkq6',
'text': 'Black Friday SaaS Deals - 2022'},
'score': 0.772717535,
'sparseValue... | [
"Somewhat of a solution -> just iterate over and build an object to return, not ideal though\n``blah = []\n for x in query_results.matches:\n blah.append({\n \"id\": x.id,\n \"metadata\": x.metadata,\n \"score\": x.score\n })\n json.dumps(blah)``\n\n"
] | [
0
] | [] | [] | [
"fastapi",
"json",
"python",
"python_3.x",
"typeerror"
] | stackoverflow_0074389257_fastapi_json_python_python_3.x_typeerror.txt |
Q:
count the number of three way conversations in a group chat dataset using pandas
I wanted to count the number of three way conversations that have occured in a dataset.
A chat group_x can consist of multiple members.
What is a three way conversation?
1st way - red_x sends a message in the group_x.
2nd way - green... | count the number of three way conversations in a group chat dataset using pandas | I wanted to count the number of three way conversations that have occured in a dataset.
A chat group_x can consist of multiple members.
What is a three way conversation?
1st way - red_x sends a message in the group_x.
2nd way - green_x replies in the same group_x.
3rd way - red_x sends a reply in the same group_x.
Th... | [
"You can use .groupby to act on the whole dataset at once.\n# Get first occurence of sent_time for each group if touchpoint==2\ngroups = t1_df[t1_df['touchpoint']==2].groupby('group_id')['sent_time'].first()\n\n# Reformat dataframe\ngroups = groups.reset_index().rename(columns={'sent_time':'first_time'})\n\n# Add t... | [
4,
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074290259_group_by_pandas_python.txt |
Q:
3.11 Lab: Smallest number
Write a program whose inputs are three integers, and whose output is the smallest of the three values.
If the input is:
7
15
3
The output is: 3
This is the code I have come up with:
num1 = input()
num2 = input()
num3 = input()
if (num1 < num2):
if (num1 < num3):
smallest_nu... | 3.11 Lab: Smallest number |
Write a program whose inputs are three integers, and whose output is the smallest of the three values.
If the input is:
7
15
3
The output is: 3
This is the code I have come up with:
num1 = input()
num2 = input()
num3 = input()
if (num1 < num2):
if (num1 < num3):
smallest_num = num1
elif (num2 < num1):
... | [
"The issue is that input() returns a string. So when you compare your variables, you're doing string comparisons instead of numerical comparisons. So, you need to convert your input to integers.\nnum1 = int(input(\"Enter num1: \"))\nnum2 = int(input(\"Enter num2: \"))\nnum3 = int(input(\"Enter num3: \"))\n\nprint(m... | [
2,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0072325239_python.txt |
Q:
Can you add percentages to elements of a pie chart using Openpyxl in Python?
I have a pie chart in excel file which I created with Openpyxl.
Is there a way to add percentages to every element in the pie chart like the below image for example?
For some further context, the excel file is created in Python. I have ... | Can you add percentages to elements of a pie chart using Openpyxl in Python? | I have a pie chart in excel file which I created with Openpyxl.
Is there a way to add percentages to every element in the pie chart like the below image for example?
For some further context, the excel file is created in Python. I have isolated the code segment that creates the pie chart from my code:
from openpyxl i... | [
"Yes, you can add labels to your chart with the \"DataLabelList\"\nSOLUTION - Following your code, add the import and then set the object:\nfrom openpyxl.chart.label import DataLabelList\n\npie=PieChart()\n\nlabels = Reference(sheet, min_col=1, min_row=11, max_row=18)\ndata = Reference(sheet, min_col=3, min_row=10,... | [
1,
0
] | [] | [] | [
"excel",
"openpyxl",
"python"
] | stackoverflow_0074264322_excel_openpyxl_python.txt |
Q:
Returning support vectors of OneVsRestClassifier - sklearn
I'm not able to get the support vectors out of a OneVsRest or OneVsOne Classifier in Python.
The code looks like this but the classifiers don't seem to have a support vector attribute.
The normal SVC model has them, so my question is: is there any way to g... | Returning support vectors of OneVsRestClassifier - sklearn | I'm not able to get the support vectors out of a OneVsRest or OneVsOne Classifier in Python.
The code looks like this but the classifiers don't seem to have a support vector attribute.
The normal SVC model has them, so my question is: is there any way to get them out of the classifier?
model_linear = svm.SVC(kernel="li... | [
"The or_linear is an array of SVC estimators.\nif you print\nprint(or_linear.estimators_)\n\nyou will get:\n[SVC(kernel='linear'), SVC(kernel='linear'), SVC(kernel='linear'), SVC(kernel='linear'), SVC(kernel='linear'), SVC(kernel='linear'), SVC(kernel='linear'), SVC(kernel='linear'), SVC(kernel='linear'), SVC(kerne... | [
2
] | [] | [] | [
"classification",
"python",
"scikit_learn",
"svc",
"svm"
] | stackoverflow_0074401151_classification_python_scikit_learn_svc_svm.txt |
Q:
Removing only checkerboard pattern while reading a png file in opencv python
Facing problem while removing checkerboard pattern. I'm using cv2.Threshold but it selected unexpected pixels too (red marked) .
import cv2
import numpy as np
input = cv2.imread('image.png')
ret, logo_mask = cv2.threshold(input[:,:,0], 0... | Removing only checkerboard pattern while reading a png file in opencv python | Facing problem while removing checkerboard pattern. I'm using cv2.Threshold but it selected unexpected pixels too (red marked) .
import cv2
import numpy as np
input = cv2.imread('image.png')
ret, logo_mask = cv2.threshold(input[:,:,0], 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
cv2.imshow(logo_mask)
Input image:
Out... | [
"Getting perfect results that covers all cases is challenging.\nThe following solution assumes that the white checkerboard color is (255, 255, 255), and gray is (230, 230, 230).\nAnother assumptions is that the clusters with that specific colors in the other parts of the image are very small.\nWe may use the follow... | [
3
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074399905_opencv_python.txt |
Q:
Azure Python SDK Filter issue (Logic App Service)
I'm having issues using filters while retrieving data from azure (Logic apps). When using a filter to retrieve data from Azure I get an error while iterating over the iterator object returned. If re-running the code the error happens at different stages of the iter... | Azure Python SDK Filter issue (Logic App Service) | I'm having issues using filters while retrieving data from azure (Logic apps). When using a filter to retrieve data from Azure I get an error while iterating over the iterator object returned. If re-running the code the error happens at different stages of the iteration process (e.g. sometimes it fails at the 3rd itera... | [
"The new library version of azure-mgmt-logic (v 10.1.0b1) solves the issue. Details:\nGithub issue\n"
] | [
0
] | [] | [] | [
"azure_sdk",
"azure_sdk_python",
"python"
] | stackoverflow_0073853468_azure_sdk_azure_sdk_python_python.txt |
Q:
value counts problem in a column contained a list (python)
value_counts can't count values in list.
Hi,
Some of the columns in my dataframe have a list.
X
Y
101
['A']
200
['A','O']
32
['B']
41
['A','AB,'O']
202
['A']
When i use value_counts() ; i get this result:
['A']
2
['A' , 'O']
1
['B']
1
['A','AB... | value counts problem in a column contained a list (python) | value_counts can't count values in list.
Hi,
Some of the columns in my dataframe have a list.
X
Y
101
['A']
200
['A','O']
32
['B']
41
['A','AB,'O']
202
['A']
When i use value_counts() ; i get this result:
['A']
2
['A' , 'O']
1
['B']
1
['A','AB','O']
1
But i want this results:
... | [
"I think explode will work for you\nimport pandas as pd\ndf = pd.DataFrame({\"a\": [['A'], ['A', 'O'], ['B'], ['A', 'AB', 'O'], ['A']]})\ndf[\"a\"].explode().value_counts()\n\n# output\nA 4\nO 2\nB 1\nAB 1\n\n# If your dataframe is like this\nfrom ast import literal_eval\ndf = pd.DataFrame({\"a\": [\... | [
0,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074401487_dataframe_python.txt |
Q:
How do I compare version numbers in Python?
I am walking a directory that contains eggs to add those eggs to the sys.path. If there are two versions of the same .egg in the directory, I want to add only the latest one.
I have a regular expression r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$ to extract the... | How do I compare version numbers in Python? | I am walking a directory that contains eggs to add those eggs to the sys.path. If there are two versions of the same .egg in the directory, I want to add only the latest one.
I have a regular expression r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$ to extract the name and version from the filename. The problem... | [
"Use packaging.version.parse.\n>>> # pip install packaging\n>>> from packaging import version\n>>> version.parse(\"2.3.1\") < version.parse(\"10.1.2\")\nTrue\n>>> version.parse(\"1.3.a4\") < version.parse(\"10.1.2\")\nTrue\n>>> isinstance(version.parse(\"1.3.a4\"), version.Version)\nTrue\n>>> isinstance(version.par... | [
610,
130,
76,
31,
16,
11,
9,
8,
2,
1,
1,
0,
0,
0
] | [
"... and getting back to easy ...\nfor simple scripts you can use:\nimport sys\nneeds = (3, 9) # or whatever\npvi = sys.version_info.major, sys.version_info.minor \n\nlater in your code\ntry:\n assert pvi >= needs\nexcept:\n print(\"will fail!\")\n # etc.\n\n"
] | [
-1
] | [
"python",
"string_comparison",
"version"
] | stackoverflow_0011887762_python_string_comparison_version.txt |
Q:
How to use a function with select to batch select columns
I want to select columns from a dataframe,
however, I want to get the names and aliases from a config file and keep it variable.
The config.json file give me a dict like
conf
"data":
{
"a":"a",
"b":"great",
"c":"example"
}
Now, I can select my... | How to use a function with select to batch select columns | I want to select columns from a dataframe,
however, I want to get the names and aliases from a config file and keep it variable.
The config.json file give me a dict like
conf
"data":
{
"a":"a",
"b":"great",
"c":"example"
}
Now, I can select my columns like this:
from pyspark import functions as F
df= df.s... | [
"you could do a list comprehension with the dict items.\nhere's an example\ncols = {\n \"a\":\"a\",\n \"b\":\"great\",\n \"c\":\"example\"\n}\n\nspark.sparkContext.parallelize([(1, 2, 3)]).toDF(['a', 'b', 'c']). \\\n selectExpr(*['{0} as {1}'.format(item[0], item[1]) for item in cols.items()]). \\\n ... | [
1,
1
] | [] | [] | [
"dictionary",
"for_loop",
"pyspark",
"python"
] | stackoverflow_0074401366_dictionary_for_loop_pyspark_python.txt |
Q:
Change volume before playback in python-vlc
I'm trying to adjust the volume of an instance of vlc.MediaPlayer before playback. Running the below snippet (python3 test.py) plays five seconds of the audio file path/to/file.m4a. It appears that audio_set_volume does actually set the volume of the player, given that t... | Change volume before playback in python-vlc | I'm trying to adjust the volume of an instance of vlc.MediaPlayer before playback. Running the below snippet (python3 test.py) plays five seconds of the audio file path/to/file.m4a. It appears that audio_set_volume does actually set the volume of the player, given that the subsequent print statement returns 10; but the... | [
"You didn't create a vlc.Instance() which probably won't help matters.\nTry:\nimport vlc \nfrom time import sleep\n\ninstance = vlc.Instance() \nmedia_player = instance.media_player_new() \nmedia = instance.media_new('./vp1.mp3')\nmedia_player.set_media(media)\nmedia.parse()\nmedia_player.audio_set_volume(30)\nmed... | [
0
] | [] | [] | [
"libvlc",
"python",
"python_vlc",
"vlc"
] | stackoverflow_0074248578_libvlc_python_python_vlc_vlc.txt |
Q:
Python - generalised function to subset columns
I am currently trying to create a generalised function which subsets a dataset based on the list of column names specified in the argument parameters.
This function works well when one column is specified, but fails when more than one column is specified.
I would lik... | Python - generalised function to subset columns | I am currently trying to create a generalised function which subsets a dataset based on the list of column names specified in the argument parameters.
This function works well when one column is specified, but fails when more than one column is specified.
I would like a function which is able to accommodate multiple co... | [
"I would design the API like this.\nYou can passed in a list of cols that you want to select from dataframe and then use\ndf.loc[:, [*cols, \"static\"]]\nsyntax to unpack it as separate column names. ie,\n>>> import pandas as pd\n>>> \n>>> testdb = pd.DataFrame(\n... {\"first\": [1, 3, 4], \"second\": [1, 3, 4]... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074401654_dataframe_pandas_python_python_3.x.txt |
Q:
Print the duplicate values from a dictionary in Python
I just wonder if it's possible to print the duplicate values from a dictionary.
For exemple I have this dictonary:
responses={
'greet':'Hello! How can I help you?',
'types':'Our coffee types are: light roasted, medium roasted, medium dark roasted, dark... | Print the duplicate values from a dictionary in Python | I just wonder if it's possible to print the duplicate values from a dictionary.
For exemple I have this dictonary:
responses={
'greet':'Hello! How can I help you?',
'types':'Our coffee types are: light roasted, medium roasted, medium dark roasted, dark roasted.',
'light':'Coffee Bros Paraideli Cup Of Excell... | [
"EDIT: After some clarification from OP, the keys needs to be input from the console, so I will keep the old answer as well, adding a way to get the keys from user input:\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"key1\",)\nparser.add_argument(\"key2\")\n\ncommand = input() #Input s... | [
3,
3,
2,
2
] | [] | [] | [
"dictionary",
"duplicates",
"python"
] | stackoverflow_0074401399_dictionary_duplicates_python.txt |
Q:
tkinter grid index arguments
I am trying to understand tkinter grids, especially this example: https://github.com/TomSchimansky/CustomTkinter/blob/master/examples/complex_example.py
I get the basic principle of grids but I cannot find anything about the arguments that can be passed into columnconfigure / rowconfig... | tkinter grid index arguments | I am trying to understand tkinter grids, especially this example: https://github.com/TomSchimansky/CustomTkinter/blob/master/examples/complex_example.py
I get the basic principle of grids but I cannot find anything about the arguments that can be passed into columnconfigure / rowconfigure for index.
Basically all tutor... | [
"while the documentation of tkinter is a mess, you can read the cleaned up docs, or the reference docs for the answer, note that python tkinter module is just a wrapper, so the exact syntax may be slightly different than the docs.\nthe input can be a list (python list or tuple or sequence) as shown here:\n\nQuery o... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074401652_python_tkinter.txt |
Q:
Change cell value according to values within another column [pandas]
I have a dataframe such as
Names Value COLA COLB COLC
A 100 0 4 1
B NaN 0 2 1
C 20 3 0 0
D 1 0 1 0
E 300 3 0 0
And I would like to change all the COLA,B and C values (except the 0) :... | Change cell value according to values within another column [pandas] | I have a dataframe such as
Names Value COLA COLB COLC
A 100 0 4 1
B NaN 0 2 1
C 20 3 0 0
D 1 0 1 0
E 300 3 0 0
And I would like to change all the COLA,B and C values (except the 0) :
to 1 if the Value col > 30
to 2 if the Value col <=30 or NaN.
I should ... | [
"Use numpy.where with chain condition used for broadcasting - assign mask from Series to multiple columns, for set 0 multiple ouput to boolean mask for set 0:\ncols = ['COLA','COLB','COLC']\n\ndf[cols] = np.where(df['Value'].gt(30).to_numpy()[:, None], 1, 2) * df[cols].ne(0)\nprint (df)\n Names Value COLA COLB ... | [
4
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074401702_pandas_python.txt |
Q:
Selenium Scroll Down Facebook Album Several Times
I try to scraping Facebook album but there is two scroll bar in the page and I want to know how to locating the inside scroll bar so it can automatically scroll down
I try to use
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
but it doesn... | Selenium Scroll Down Facebook Album Several Times | I try to scraping Facebook album but there is two scroll bar in the page and I want to know how to locating the inside scroll bar so it can automatically scroll down
I try to use
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
but it doesn't work. I also tried
driver.find_element(By.TAG_NAME,"... | [
"This command worked for me:\ndriver.execute_script(\"window.scrollBy(0, arguments[0]);\", 600)\n\nThe entire code I used is:\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.... | [
1
] | [] | [] | [
"automation",
"python",
"scroll",
"selenium",
"web_scraping"
] | stackoverflow_0074399470_automation_python_scroll_selenium_web_scraping.txt |
Q:
Error: maximum recursion depth exceeded in multipe processing
i trying run multipe processing with ThreadPool and i have error maximum recursion depth exceeded
this is my code:
def extract_all_social_link(bio_url):
data = extract_all_social_link(bio_url)
return data
def run_extract_all_social_link(df, max_... | Error: maximum recursion depth exceeded in multipe processing | i trying run multipe processing with ThreadPool and i have error maximum recursion depth exceeded
this is my code:
def extract_all_social_link(bio_url):
data = extract_all_social_link(bio_url)
return data
def run_extract_all_social_link(df, max_count, displays_steps = 1000):
tt = time.time()
user_data =... | [
"Don't even try to change the recursion limit config.\nYou have to change the code of extract_all_social_link() that's called recursively with always the same arg bio_url.\ndef extract_all_social_link(bio_url):\n data = extract_all_social_link(bio_url) # infinite recursion\n return data # never reached !!\n... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074400724_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.