QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
75,211,183
7,114,235
What does Pydantic ORM mode exactly do?
<p>According to the <a href="https://docs.pydantic.dev/usage/models/#orm-mode-aka-arbitrary-class-instances" rel="noreferrer">docs</a>, Pydantic &quot;ORM mode&quot; (enabled with <code>orm_mode = True</code> in <code>Config</code>) is needed to enable the <code>from_orm</code> method in order to create a model instanc...
<python><pydantic>
2023-01-23 14:51:54
1
1,504
rrobby86
75,211,035
62,898
When using subprocess.run python script failes to find module
<p>I have a python script that launches several other script inside powershell Every script works fine when I run python in powershell. when I use subprocess.run inside the master script it does not work.</p> <p>This is how I invoke the scripts:</p> <pre><code>subprocess.run([&quot;powershell&quot;, &quot;-Command&quo...
<python><subprocess>
2023-01-23 14:39:29
0
5,554
Amit Raz
75,210,946
10,689,857
Python requests how to know what parameter to pass
<p>I have the following code. I am trying to access to <a href="https://api.github.com/users/jtorre94" rel="nofollow noreferrer">https://api.github.com/users/jtorre94</a> via the requests library.</p> <pre><code>import requests api_url = &quot;https://api.github.com/users&quot; response = requests.get(api_url, params={...
<python><python-requests>
2023-01-23 14:31:49
1
854
Javi Torre
75,210,845
4,909,923
Python: Recursively split strings when longer than max allowed characters, by the last occurrence of a delimiter found before max allowed characters
<p>I have a text transcript of dialogue, consisting of strings of variable length. The string lengths can be anywhere from a few characters to thousands of characters.</p> <p>I want Python to transform the text so that any line is maximally <em>n</em> characters. To make the partitioning natural, I want to recursively ...
<python><string><recursion><split>
2023-01-23 14:23:40
1
5,942
P A N
75,210,554
3,764,619
Importing from folders with the same name gives ImportError in PyCharm
<p>Given the following project structure:</p> <pre><code>test/ data/ __init__.py a/ data/ __init__.py main.py __init__.py </code></pre> <p>In <code>test/data/__init__.py</code></p> <pre><code>from pathlib import Path DATA_DIR = Path(__file__).parent </code></pre> <p>In <code>main.py</code></p> <pre><co...
<python><pycharm>
2023-01-23 13:59:27
2
680
Casper Lindberg
75,210,489
821,995
How to get a consistent WeakSet length during finalization?
<p>Consider the following code which uses a <code>WeakSet</code> at the same time as a finalizer:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import weakref &gt;&gt;&gt; import gc &gt;&gt;&gt; class A: ... pass &gt;&gt;&gt; class Parent: ... def __init__(self, a): ... self.a = a ...
<python><garbage-collection><weak-references>
2023-01-23 13:53:47
1
7,455
F.X.
75,210,362
14,787,964
Image artefacts when using cyclic colormaps for periodic data
<p>I am currently trying to visualize the phase of an electromagnetic field which is 2pi-periodic. To visualize that e.g. 1.9 pi is almost the same as 0, I am using a cyclic colormap (twilight). However, when I plot my images, there are always lines at the sections where the phase jumps from (almost) 2pi to 0. When you...
<python><matplotlib><colormap><cyclic>
2023-01-23 13:42:37
1
867
Oskar Hofmann
75,210,241
12,304,000
How to parse nested XML and extract attributes + tag text both?
<p>My XML looks like this:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;main_heading timestamp=&quot;20220113&quot;&gt; &lt;details&gt; &lt;offer id=&quot;11&quot; new_id=&quot;12&quot;&gt; &lt;level&gt;1&amp;amp;1&lt;/level&gt; &lt;typ&gt;Green&lt;/typ&gt; ...
<python><python-3.x><xml><beautifulsoup><xml-parsing>
2023-01-23 13:33:23
4
3,522
x89
75,209,994
14,744,714
Date search and date output from the same class name when parsing
<p>I'm trying to parse a site. It has the same named classes, while the number of such classes varies from page to page. I'm interested in the class that contains the date, which is written in the following pattern: <code>24 January 2020</code>.</p> <p>Code:</p> <pre><code>import pandas as pd import numpy as np import ...
<python><html><parsing><beautifulsoup>
2023-01-23 13:09:20
2
717
kostya ivanov
75,209,817
12,304,000
filter non-nested tag values from XML
<p>I have an xml that looks like this.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;main_heading timestamp=&quot;20220113&quot;&gt; &lt;details&gt; &lt;offer id=&quot;11&quot; parent_id=&quot;12&quot;&gt; &lt;name&gt;Alpha&lt;/name&gt; &lt;pos&gt;697&lt;/pos&g...
<python><python-3.x><xml><beautifulsoup>
2023-01-23 12:53:46
2
3,522
x89
75,209,722
5,353,753
Extract phone numbers from email-signature (regex)
<p>I'm trying to parse an email signature, that can contain multiple phone numbers in different formats. I've managed to come up with this Regex:</p> <pre><code>(?&lt;![%_])\b(\+?\d{1,}[\s.-]?\(?\d{1,}\)?[\s.-]?\(?\d{1,}\)?[\s.-]?\d{1,}[\s.-]?\d{1,}[\s.-]?\d{3,}) </code></pre> <p>This matches almost any phone number. (...
<python><regex><phone-number>
2023-01-23 12:45:12
2
40,569
sagi
75,209,609
2,179,795
Selenium Python: Not finding element which clearly exists
<p>I am trying to click through the levels of a site's navigation using python and selenium. The navbar contains list items that have subelements within them.</p> <p>Here is the html of the navbar:</p> <p><a href="https://i.sstatic.net/UrbyL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UrbyL.png" alt=...
<python><selenium><selenium-webdriver><mousehover><nosuchelementexception>
2023-01-23 12:36:17
1
1,247
Merv Merzoug
75,209,473
1,574,551
How to convert list column into a single column and the concat in pandas dataframe
<p>I would like convert each list column into one single column and then concat for below dataframe</p> <pre><code> data = {'labels': ['[management,workload,credibility]','[ethic,hardworking,profession]'], 'Score': [[0.55,0.36,0.75],[0.41,0.23,0.14]]} # Create DataFrame df = pd.DataFrame(data) </code></pre> <p>ne...
<python><pandas><list>
2023-01-23 12:25:03
1
1,332
melik
75,209,432
13,285,583
Cannot import tensorflow after a week of no use, no changes was made
<p>What I've did:</p> <ol> <li>uninstall and <code>pip install tensorflow-macos</code></li> <li>uninstall <code>pip install tensorflow-metal</code></li> <li><code>import tensorflow as tf</code></li> </ol> <p>The expected result is no error.</p> <p>However, I got an error after importing tensorflow.</p> <pre><code>TypeE...
<python><python-3.x><tensorflow>
2023-01-23 12:21:02
0
2,173
Jason Rich Darmawan
75,209,418
7,048,760
How to make flask app with projects written in two different Python versions work in endpoints?
<p>I’m building a flask api in which I have to use two different Python projects written in 2 different versions. One is a Python project built on version 3.8+, and another is a proprietary package compatible for version &lt;3.7. I get errors if I use a single version and try to run it, and fixing errors would be too m...
<python><flask><docker-compose>
2023-01-23 12:19:41
1
865
Kuni
75,209,415
5,510,713
Unable to decode Aztec barcode
<p>I'm trying to decode an Aztec barcode using the following script:</p> <pre><code>import zxing reader = zxing.BarCodeReader() barcode = reader.decode(&quot;test.png&quot;) print(barcode) </code></pre> <p><strong>Here is the input image:</strong></p> <p><a href="https://i.sstatic.net/FTlJG.png" rel="nofollow noreferre...
<python><image-processing><zxing><barcode-scanner><aztec-barcode>
2023-01-23 12:19:25
2
776
DhiwaTdG
75,209,261
10,667,216
How to install a Python package inside a docker image?
<p>Is there a way to install a python package without rebuilding the docker image? I have tried in this way:</p> <pre><code>docker compose run --rm web sh -c &quot;pip install requests&quot; </code></pre> <p>but if I list the packages using</p> <pre><code>docker-compose run --rm web sh -c &quot;pip freeze&quot; </code...
<python><docker>
2023-01-23 12:06:43
2
483
Davood
75,209,161
100,214
Does python ecdsa NIST-256p provide recovery code (byte)?
<p>I am using the python <code>ecdsa</code> library for signing messages for blockchain transactions. In the blockchain specification it says, for <code>secp256r1</code> that the signature should have a length of 65 bytes where:</p> <blockquote> <p>The signature must be of length 65 bytes in the form of [r, s, v] where...
<python><python-3.x><ecdsa><ecdsasignature>
2023-01-23 11:57:02
1
8,185
Frank C.
75,209,065
5,775,358
xarray dataset extract values select
<p>I have a xarray dataset from which I would like to extract points based on their coordinates. When <code>sel</code> is used for two coordinates it returns a 2D array. Sometimes this is what I want and it is the intended behavior, but I would like to extract a line from the dataset.</p> <pre><code>import xarray as xr...
<python><arrays><slice><interpolation><python-xarray>
2023-01-23 11:47:33
1
2,406
3dSpatialUser
75,209,058
7,800,760
Utterly lost importing functions for pytest
<p>I know there are several pytest and importing questions and answers here but I'm not able to find a solution :(</p> <p>PS After rereading import tutorials have changed my project folder structure a bit and edited the examples below.</p> <p>My simple directory structure for a demo python project is as follows:</p> <p...
<python><pytest>
2023-01-23 11:46:40
1
1,231
Robert Alexander
75,208,912
10,967,961
Grouping together lists in pandas
<p>I have a database of patents citing other patents looking like this:</p> <pre><code>{'index': {0: 0, 1: 1, 2: 2, 12: 12, 21: 21}, 'docdb_family_id': {0: 57904406, 1: 57904406, 2: 57906556, 12: 57909419, 21: 57942222}, 'cited_docdbs': {0: [15057621, 16359315, 18731820, 19198211, 19198218, 191...
<python><pandas><list>
2023-01-23 11:32:43
2
653
Lusian
75,208,906
3,815,773
How do I catch the PyQt5 QSplitter.resizeEvent?
<p>I can catch the user resizing or repositioning the window simply by defining functions:</p> <pre><code>def resizeEvent(self, event): ... def moveEvent(self, event): ... </code></pre> <p>But I also have 2 QSplitter, and would like to know any new split the user has applied to make it also a default for the next start...
<python><events><pyqt5><qsplitter>
2023-01-23 11:32:23
0
505
ullix
75,208,629
9,929,725
Odoo - Return record lists on form view
<p>I use Odoo 14 Enterprise. From a wizard form, I want to return a form view with record list into domain.</p> <p>If i use tree view, this action is great. But, i want directly show to result into form view.</p> <p>Can you help me ?</p> <p>My code :</p> <pre><code>return { 'type': 'ir.actions.act_window', 'vie...
<python><odoo>
2023-01-23 11:08:09
1
321
PseudoWithK
75,208,539
7,658,051
Ansible: The error was: 'dict object' has no attribute 'stdout_lines', but changing `stdout_lines` to `results` does not solve the problem
<p>I am a beginner with ansible.</p> <p>I have copied a playbook managed by third parts and extended into the following one, then I run it in debug mode (<code>-vvv</code>) via</p> <pre><code>/home/.../ansible-venv/bin/ansible-playbook -vvv playbooks/dump_data_into_csv.yml &gt;/dump_data_into_csv.log 2&gt;&amp;1 </code...
<python><bash><dictionary><ansible>
2023-01-23 10:59:48
0
4,389
Tms91
75,208,468
16,250,224
Creating cumulative product with reset to 1 at each end of the month
<p>I try to create a new column <code>CumReturn</code>in a Dataframe <code>df</code>with the cumulative product over the month. I try to reset the cum_prod() to 1 at the end of each month (if EndMonth == 1) and start new with the cumulative product.</p> <pre><code>df: Date EndMonth ID1 Return 2023-01-30 0 ...
<python><pandas>
2023-01-23 10:53:23
2
793
fjurt
75,208,331
19,580,067
Win32 not recognising the outlook email in Jupyter notebook
<p>Tried to read the outlook email in jupyter notebook for creating a ML algorithm but the win32 is not recognising my outlook account. It was working fine yesterday but somehow same code not wrking today.</p> <p>Any suggestions please?</p> <p>Attached my code below.</p> <pre><code>import win32com #.client import pytts...
<python><jupyter-notebook><outlook><pywin32><win32com>
2023-01-23 10:40:16
2
359
Pravin
75,208,301
12,304,000
a bytes-like object is required, not 'str' while parsing XML files
<p>I am trying to parse an xml that looks like this. I want to extract information regarding the katagorie i.e ID, parent ID etc:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;test timestamp=&quot;20210113&quot;&gt; &lt;kategorien&gt; &lt;kategorie id=&quot;1&quot; parent_id=&q...
<python><python-3.x><xml><utf-8><encode>
2023-01-23 10:39:06
2
3,522
x89
75,208,261
19,716,381
Applying custom functions to groupby objects pandas
<p>I have the following pandas dataframe.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame( { &quot;bird_type&quot;: [&quot;falcon&quot;, &quot;crane&quot;, &quot;crane&quot;, &quot;falcon&quot;], &quot;avg_speed&quot;: [np.random.randint(...
<python><pandas><dataframe>
2023-01-23 10:35:37
2
484
berinaniesh
75,208,221
839,837
Python replace nested dictionary in a dictionary
<p>I'd like to replace a dictionary in a dictionary, but when I try I keep getting quotes and slashes around the added dictionary.</p> <pre><code>current_dict = {&quot;header&quot;: {&quot;from&quot;: &quot;/app/off_grid_control/subscribe&quot;, &quot;messageId&quot;: &quot;ef6b8e50620ac7...
<python><json><dictionary>
2023-01-23 10:31:30
1
727
Markus
75,208,152
15,296,575
Why use "db.*" in SqlAlchemy?
<p>I am working on a project using Flask and SqlAlchemy. Me and my colleagues found two ways to define a table. Both work, but what is the different?</p> <p>Possibility I</p> <pre><code>base = declarative_base() class Story(base): __tablename__ = 'stories' user_id = Column(Integer, primary_key=True) ...
<python><sql><python-3.x><sqlalchemy>
2023-01-23 10:24:46
1
332
Shraft
75,208,050
853,710
xml parsing in python with XPath
<p>I am trying to parse an XML file in Python with the built in xml module and Elemnt tree, but what ever I try to do according to the documentation, it does not give me what I need. I am trying to extract all the <strong>value</strong> tags into a list</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF...
<python><xml><xpath>
2023-01-23 10:12:36
1
1,767
user853710
75,208,047
6,409,572
How can I define plain console output of a class object (vs. __str__)?
<p>When defining my own class, I can overwrite the <code>__str__</code> to define its <code>print(my_class)</code> behavior. What do I have to do to overwrite the behavior when just calling an <code>my_class</code> object?</p> <p>What I get:</p> <pre><code>&gt; obj = my_class(&quot;ABC&quot;) # define &gt; print(obj) ...
<python>
2023-01-23 10:12:06
1
3,178
Honeybear
75,207,803
10,689,857
Calling a SQL script from python
<p>I have a sql script called myscript.sql that looks like this:</p> <pre><code>-- Comment that I have in my sql script. MERGE INTO my_table i using (select several_columns from my_other_table f where condition ) f on (my join conditions) WHEN MATCHED THEN UPDATE SET whatever; COMMIT; </code></pre> <p>I have tried...
<python><sql><oracle-database>
2023-01-23 09:49:46
3
854
Javi Torre
75,207,749
264,136
importlib.import_module is not a package
<p>update.py:</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument(&quot;--data_file&quot;) job_args = parser.parse_known_args()[0] imported = importlib.import_module(job_args.data_file) CURIE_BLR.py testbed = &quot;CURIE_BLR&quot; sockets = [ &quot;10.64.127.135:2005:Fugazi&quot;,...
<python>
2023-01-23 09:43:34
1
5,538
Akshay J
75,207,721
2,178,942
change the factorplot of seaborn to include dots
<p>I have a pandas dataframe that looks like this:</p> <pre><code> feat roi sbj alpha test_type acc 0 cnn2 LOC Subject1 normal_space imagery 0.260961 1 cnn2 LOC Subject1 0.4 imagery 0.755594 2 cnn4 LOC Subject1 normal_space imagery 0.282238 3 cnn4 LO...
<python><matplotlib><plot><seaborn><bar-chart>
2023-01-23 09:40:20
1
1,581
Kadaj13
75,207,414
4,462,086
How to properly type check alembic with mypy
<p>I am using alembic in a project. Everything works as expected, but when checking the types with mypy I am getting:</p> <pre><code>error: Module &quot;alembic&quot; has no attribute &quot;op&quot; [attr-defined] error: Module &quot;alembic&quot; has no attribute &quot;context&quot; [attr-defined] </code></pre> <p>A...
<python><mypy><alembic>
2023-01-23 09:10:13
0
2,525
Imre_G
75,207,366
5,353,753
Regex for URL without path
<p>I know there are many solutions, articles and libraries for this case, but couldn't find one to match my case. I'm trying to write a regex to extract a URL(which represent the website) from a text (a signature of a person in an email), and has multiple cases:</p> <ul> <li>Could contain http(s):// , or not</li> <li>C...
<python><regex><url>
2023-01-23 09:05:25
1
40,569
sagi
75,207,310
8,967,152
How do I set dropdown colors using Google SpreadSheet API?
<p>I am using the gspread library in python to send api requests.<br> The request is to set the dropdown.<br> However, I could not figure out how to set the following.</p> <ol> <li>set a color for each value in the dropdown</li> <li>set the display style to &quot;Chip&quot;</li> </ol> <p><a href="https://i.sstatic.net/...
<python><google-sheets-api><gspread>
2023-01-23 08:59:13
1
369
karutt
75,207,298
998,070
Drawing an arc tangent to two lines segments in Python
<p>I'm trying to draw an arc of n number of steps between two points so that I can bevel a 2D shape. This image illustrates what I'm looking to create (the blue arc) and how I'm trying to go about it:</p> <ol> <li>move by the radius away from the target point (red)</li> <li>get the normals of those lines</li> <li>get t...
<python><numpy><matplotlib><trigonometry>
2023-01-23 08:57:40
2
424
Dr. Pontchartrain
75,207,215
6,494,707
Generating random datasets in a dictionary
<p>I have two datasets dictionary like this:</p> <pre><code>D1 = {'query': torch.tensor([(1, 2)], dtype=torch.float32), 'support': torch.tensor([(2, 4), (3, 1)], dtype=torch.float32)} # (x, y) pairs for query (Q1) and support (S1) set. D2 = {'query': torch.tensor([(4, 1)], dtype=torch.float32), 'support': torc...
<python><dictionary><tensor><torch>
2023-01-23 08:47:40
1
2,236
S.EB
75,207,087
13,238,456
Loading a conda environment in PyCharm - File or directory not found
<p>TLDR: PyCharm can't load my conda environment with a crypted error message:</p> <p><code>Error code 2. *path*: can't open the file 'info' [ErrNo 2] No such file or directory</code></p> <p>And does not list my conda environment in its run configuration.</p> <p>I have a PyCharm Professional and Anaconda installation o...
<python><pycharm><anaconda><conda>
2023-01-23 08:29:13
0
493
Dustin
75,207,049
796,634
Mercurial 'hg commit --logfile' working from commandline but not Python
<p>I'm auto-generating 'hg add' then 'hg commit' commands and executing from Python 3.8 on Win 10.</p> <p>The automation writes the commit template out to a temp file then passes it to the hg commit command using the --logfile / -l parameter. If I run from the commandline 'hg commit' works fine and uses the template s...
<python><mercurial>
2023-01-23 08:24:11
0
2,194
Geordie
75,206,988
4,961,888
Split dataframe and plot subsets with a for loop in jupyter notebook
<p>I am trying to split a dataframe and to plot the create subsets using a for loop in jupyter notebooks:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt data = pd.DataFrame(np.random.rand(120, 10)) for i in range(len(data) // 10): split_data = data.iloc[i:i*(len(data) // 10)...
<python><pandas><matplotlib><jupyter-notebook>
2023-01-23 08:15:01
1
5,182
jim jarnac
75,206,920
7,095,530
Safely store data from GET request - Django
<p>Alright,</p> <p>Let's say we need to create a website with Django where people can book a lodge for the weekends.</p> <p>We add a search form on the homepage where people can fill in the check-in and check-out date to filter for all available lodges.</p> <p>We use a generic Listview to create an overview of all the ...
<python><django><get>
2023-01-23 08:07:10
0
315
Kevin D.
75,206,754
11,895,506
Python: parce json with 2 arrays via json_normalize
<p>Would you help, please, to parce 2-arrayed json via python, json_normalize.</p> <p>Here is the code:</p> <pre><code>import json from pandas.io.json import json_normalize data5 = { &quot;id&quot;: &quot;0001&quot;, &quot;type&quot;: &quot;donut&quot;, &quot;name&quot;: &quot;Cake&quot;, &quot;ppu&qu...
<python><json><json-normalize>
2023-01-23 07:44:01
1
737
Semyon-coder
75,206,732
11,608,962
SparseTermSimilarityMatrix().inner_product() throws "cannot unpack non-iterable bool object"
<p>While working with cosine similarity, I am facing issue calculating the inner product of two vectors.</p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>from gensim.similarities import ( WordEmbeddingSimilarityIndex, SparseTermSimilarityMatrix ) w2v_model = api.load(&quot;glove-wiki-gi...
<python><nlp><nltk><gensim><cosine-similarity>
2023-01-23 07:39:44
1
1,427
Amit Pathak
75,206,490
5,807,808
add new column to dataframe with values matching the keys with existing column in dataframe in python
<p>fairly new to python and pandas/numpy. I have a data frame and a dictionary. I need to add a new column in the data frame where the values would be the values from dictionary for the matching dictionary keys with the existing column in data frame. and have empty string for non matching values.</p> <div class="s-tabl...
<python><python-3.x><pandas><dataframe><numpy>
2023-01-23 07:06:52
1
401
peter
75,206,392
19,238,204
How to Calculate the Volume and Area Surface From the 3D Plot Using Matplotlib and Numpy?
<p>Hi all I want to know how to calculate the volume and the surface area of this 3D plot?</p> <p>I am using the right size for the width and length and height.</p> <p>this is my code:</p> <pre><code>from matplotlib import pyplot as plt from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import nu...
<python><numpy><matplotlib>
2023-01-23 06:53:35
2
435
Freya the Goddess
75,206,372
16,997,421
How to filter emails based on received date using microsoft graph api with python
<p>I'm working on a python script to retrieve emails based on receiveddatetime. When i run my script i get the error below.</p> <p><a href="https://i.sstatic.net/gPAVi.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gPAVi.png" alt="enter image description here" /></a></p> <p>Below is my whole script.</p>...
<python><python-3.x><microsoft-graph-api><filtering><microsoft-graph-mail>
2023-01-23 06:49:44
1
352
Bernietechy
75,206,293
743,086
WinError 10061 and WinError 10022 in socket programming only on Windows
<p>I have a very simple Python code for <code>bind</code> or <code>connect</code> to a port. it works without any error on <code>Ubuntu</code> and <code>CentOs</code> but I have an error on <code>Windows 10</code>. I turned off the firewall and antivirus but it didn't help.</p> <p>my code:</p> <pre><code>import socket ...
<python><linux><sockets><window><try-except>
2023-01-23 06:36:52
1
2,295
Ehsan
75,206,092
7,177,478
FastAPI Sqlalchemy sqlalchemy.exc.InvalidRequestError: Could not refresh instance
<p>I'm new to the sqlalchemy. I was trying to do a simple insert. But I get an InvalidRequestError.</p> <blockquote> <p>sqlalchemy.exc.InvalidRequestError: Could not refresh instance '&lt;Block at 0x2464fd85670&gt;'</p> </blockquote> <p>It seems like there is something wrong with the refresh(). Any advice would be grea...
<python><sqlalchemy><fastapi>
2023-01-23 06:02:27
1
420
Ian
75,205,725
17,778,275
No search results while using API Key to retrieve information using Python
<p>Mouser is a website where electronic components can be bought and are listed with their details and technical parameters.</p> <p>To automate the search of parts from this website, I am trying to automate the processing using the <a href="https://api.mouser.com/api/docs/ui/index" rel="nofollow noreferrer">Mouser API ...
<python><search><ssl-certificate>
2023-01-23 04:42:57
2
354
spd
75,205,674
17,990,405
Have pydantic object dict() method return custom representation for non-pydantic type
<p>I have a pydantic object that has some attributes that are custom types. I was able to create validators so pydantic can validate this type however I want to get a string representation of the object whenever I call the pydantic dict() method. Heres an example:</p> <pre><code>class MongoId(ObjectId): @classmetho...
<python><pydantic>
2023-01-23 04:26:12
1
325
syntactic
75,205,618
5,966,097
winxpgui.SetLayeredWindowAttributes throwing error pywintypes.error: (87, 'SetLayeredWindowAttributes', 'The parameter is incorrect.')
<p>While I am trying to make a window's background transparent using win32gui, I am using following code.</p> <pre><code>hwnd = win32gui.FindWindow(None, &quot;My App Name&quot;) win32gui.SetWindowLong (hwnd, win32con.GWL_EXSTYLE, win32gui.GetWindowLong (hwnd, win32con.GWL_EXSTYLE ) | win32con.WS_EX_LAYERED ) winxpgui....
<python><pywinauto><win32gui><win32con>
2023-01-23 04:12:48
1
2,052
KOUSIK MANDAL
75,205,556
2,580,505
Focal Loss in Pytorch implementation
<p>Where can I find a reliable Pytorch implementation of Focal Loss for a multi-class object detection problem? I have seen some implementations on GitHub, but I am looking for the official Pytorch version, similar to <code>nn.CrossEntropyLoss()</code>.</p> <p>My prediction has a shape of <code>(b, c)</code> and the ta...
<python><deep-learning><pytorch><neural-network><computer-vision>
2023-01-23 03:56:19
0
969
Infintyyy
75,205,435
935,376
Extraction of values from pandas column which is a list of dictionaries
<p>A pandas dataframe called top_chart_movies, which has a column, <strong>genres</strong>, that has a list of dictionaries as shown in the picture below <a href="https://i.sstatic.net/b2bQG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/b2bQG.png" alt="enter image description here" /></a></p> <p>The co...
<python><pandas><dictionary>
2023-01-23 03:19:32
2
2,064
Zenvega
75,205,383
6,676,101
How can we print a list of all printable ASCII characters to the console using python?
<p>Some ASCII characters are printable and some ASCII characters are not printable.</p> <p>The non-printable ASCII characters are shown below:</p> <pre class="lang-None prettyprint-override"><code> 0 NUL (Ctrl-@) NULL 1 SOH (Ctrl-A) START OF HEADING 2 STX (Ctrl-B) START OF TEXT 3 ET...
<python><python-3.x><ascii>
2023-01-23 03:01:09
1
4,700
Toothpick Anemone
75,205,307
787,463
Python iterating through file, "Unresolved attribute reference 'strip' for class 'int'" warning: is it PyCharm or is it me?
<p>As part of something I'm writing, when iterating through a file (using enumerate so I can get line numbers) PyCharm gives me the warning <code>Unresolved attribute reference 'strip' for class 'int'</code> when I try and strip my strings.<br /> Stripped down the essentials, the code is:</p> <pre class="lang-python pr...
<python><pycharm>
2023-01-23 02:39:10
1
325
Slashee the Cow
75,205,306
2,635,209
Why can't I use `statistics.correlation`?
<p>I want to compute correlations in Python. My IDE suggests using <code>statistics.correlation</code>, but when I try it:</p> <pre><code>import statistics x = [1, 2, 3, 4, 5, 6] p = statistics.correlation(x, x) print(p) </code></pre> <p>I get an error that says <code>AttributeError: module 'statistics' has no attribu...
<python><pycharm>
2023-01-23 02:38:39
1
6,104
Thomas Carlton
75,205,254
14,499,516
How to fix the proxy server error ERR_TUNNEL_CONNECTION_FAILED with free-proxy?
<p>I have followed a tutorial to put all required modules for a modified selenium webdriver into one single class. However, as I implemented the codes, the following errors keeps happening:</p> <pre><code>Traceback (most recent call last): File &quot;c:\Users\s1982\Documents\GitHub\Preventing-Selenium-from-being-dete...
<python><selenium><proxy>
2023-01-23 02:22:58
2
699
hokwanhung
75,205,211
12,097,553
django channels: notifications of message not working properly
<p>I am writing a django module that handles real time message paired with notification. So far:<br /> a conversation can only take place between no more than 2 users. a notification should be sent after each message.</p> <p>I am currently working on getting the notifications to show up and the issue is that the notifi...
<python><django><django-channels>
2023-01-23 02:12:51
2
1,005
Murcielago
75,205,191
3,561,314
Python thread calling won't finish when closing tkinter application
<p>I am making a timer using tkinter in python. The widget simply has a single button. This button doubles as the element displaying the time remaining. The timer has a thread that simply updates what time is shown on the button.</p> <p>The thread simply uses a while loop that should stop when an <a href="https://stack...
<python><python-3.x><multithreading><tkinter>
2023-01-23 02:07:18
1
323
wimworks
75,205,126
679,081
Why does lldb only show "dyld" in each stack frame on macOS Ventura?
<p>I maintain a Python library that's written in C++ (using <a href="https://github.com/pybind/pybind11" rel="nofollow noreferrer">Pybind11</a>). For the past couple of years, I've been able to debug it just fine with <code>lldb</code>, just by compiling the extension in debug mode (i.e.: disabling optimization and inc...
<python><lldb><pybind11><macos-ventura>
2023-01-23 01:46:30
1
2,557
Peter Sobot
75,205,081
7,403,752
Identifying websites that use a paywall dynamically
<p>I am interested in identifying websites using paywall, not to bypass to paywall, but use it for research purposes. I use the following code, looks okay for some websites but not for all:</p> <pre><code>import requests url = &quot;wsj.com&quot; response = requests.get(url) if &quot;pay wall&quot; in response.text....
<python><selenium><request>
2023-01-23 01:33:11
1
2,326
edyvedy13
75,205,015
874,380
How can I get the same WordNet output from the terminal in Python/NLTK?
<p>I have WordNet installed on my machine, and when I run the terminal command</p> <pre><code>wn funny -synsa </code></pre> <p>I get the following output:</p> <p><a href="https://i.sstatic.net/VWDs7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VWDs7.png" alt="enter image description here" /></a></p> <...
<python><nltk><wordnet>
2023-01-23 01:17:24
1
3,423
Christian
75,204,971
4,180,276
django.db.utils.ProgrammingError: relation "pdf_conversion" does not exist
<p>I am trying to add in a conversion model that is referenced in the fileurl model that calls my customuser model. But for some reason, I get the following error when loading the admin panel.</p> <pre><code>Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /a...
<python><django><postgresql>
2023-01-23 01:01:54
0
2,954
nadermx
75,204,896
811,359
Google Bigquery SELECT count(*) on API returns 0 when Same Count(*) queryin the GBQ Console returns a count
<p>I'm examining the NOAA severe storms dataset in Google Bigquery and I wanted to iterate over the tables to get the storms per year between 1960 and 2022. with property damage.</p> <pre><code>from google.cloud import bigquery client = bigquery.Client.from_service_account_json(&quot;secret.json&quot;) for year in ran...
<python><google-bigquery>
2023-01-23 00:37:59
2
474
ahalbert
75,204,880
3,195,413
pandas RollingGroupBy agg 'size' of rolling group (not 'count')
<p>It is possible to perform a</p> <pre><code>df.groupby.rolling.agg({'any_df_col': 'count'}) </code></pre> <p>But how about a size agg?</p> <p>'count' will produce a series with the 'running count' of rows that match the groupby condition (1, 1, 1, 2, 3...), but I would like to know, for all of those rows, the total n...
<python><pandas><group-by><rolling-computation>
2023-01-23 00:33:21
3
599
10mjg
75,204,860
19,130,803
Dash: apply 3rd-party or self custom css and js to dash elements
<p>I am developing a dash application which is a multi-page app. I am using bootstrap theme.</p> <p><strong>project structure</strong></p> <pre><code>- proj - app.py - pages/ - index.py - demo.py - assets/ - 1_third_party_style.css - 2_third_party_script.js - 3_custom_script.js </code></pre> <...
<javascript><python><html><plotly-dash>
2023-01-23 00:27:45
0
962
winter
75,204,805
11,649,973
Define multiple templates for a predefined block wagtail CRX
<p>I was moving a site over to wagtail and decided to use the <a href="https://docs.coderedcorp.com/wagtail-crx/" rel="nofollow noreferrer">codered extensions</a>. The library comes with a image-gallery content-block. I want to use this but define a few templates you can choose from in the admin UI.</p> <p>You usually ...
<python><django><wagtail>
2023-01-23 00:11:10
2
425
GreatGaja
75,204,791
12,224,591
Faster Way to Implement Gaussian Smoothing? (Python 3.10, NumPy)
<p>I'm attempting to implement a Gaussian smoothing/flattening function in my <code>Python 3.10</code> script to flatten a set of XY-points. For each data point, I'm creating a Y buffer and a Gaussian kernel, which I use to flatten each one of the Y-points based on it's neighbours.</p> <p>Here are some sources on the G...
<python><numpy><data-analysis>
2023-01-23 00:08:26
2
705
Runsva
75,204,703
5,671,447
Using KDDockWidgets in PySide2 with QML
<p>I am trying to get <a href="https://github.com/KDAB/KDDockWidgets/tree/2.0" rel="nofollow noreferrer">KDDockWidgets 2.0</a> into my PySide2 Python 3.10 application. I have followed the <a href="https://github.com/KDAB/KDDockWidgets/blob/2.0/README-bindings.md" rel="nofollow noreferrer">Python bindings guide</a> they...
<python><qt><cmake><qml><pyside2>
2023-01-22 23:44:57
0
359
Jacob Jewett
75,204,560
2,648,481
Consuming TaskGroup response
<p>In Python3.11 it's suggested to use <code>TaskGroup</code> for spawning Tasks rather than using <code>gather</code>. Given Gather will also return the result of a co-routine, what's the best approach with TaskGroup.</p> <p>Currently I have</p> <pre class="lang-py prettyprint-override"><code>async with TaskGroup() as...
<python><python-asyncio>
2023-01-22 23:10:19
2
1,106
johng
75,204,512
1,816,135
How to get more details on streaming data using Tweepy StreamingClient of Twitter APIv2
<p>I used tweepy for v1.1 Twitter streaming to follow a Twitter account. When someone is tweeting this user for any tweet (let say download this video bot), I get a lot of details about the tweet that the user mentioned and the tweet that has the video. (tweet info, video links etc)</p> <p>used to be something like thi...
<python><tweepy><twitter-api-v2>
2023-01-22 22:59:10
2
1,002
AKMalkadi
75,204,372
9,855,588
where to define variables for startup events fastapi
<p>In reference to -&gt; <a href="https://fastapi.tiangolo.com/advanced/events/" rel="nofollow noreferrer">https://fastapi.tiangolo.com/advanced/events/</a></p> <pre><code>from fastapi import FastAPI app = FastAPI() items = {} @app.on_event(&quot;startup&quot;) async def startup_event(): items[&quot;foo&quot;] ...
<python><python-3.x><fastapi>
2023-01-22 22:30:32
0
3,221
dataviews
75,204,318
6,077,239
How to do conditional scaling in polars?
<p>I have a polars dataframe and I want to do scaling of a column depending on whether its value is positive or negative, scaled by respective sum (positive or negative) and over another column.</p> <p>Below is an example for illustration for what I tried.</p> <pre class="lang-py prettyprint-override"><code>import pola...
<python><python-polars>
2023-01-22 22:19:37
1
1,153
lebesgue
75,204,298
10,400,238
Find index of longest consectuive timespan in pandas time series
<p>I have a time series with gaps (NaN) and I want to find the start and stop index of the longest consecutive sequence where no Nan occurs. I have no clue how to do that.</p> <pre><code>values = [5468.0, 5946.0, np.nan, 6019.0, 5797.0, 5879.0, np.nan, 5706.0, 5986.0, 6228.0, 6285.0, np.nan, 5667.0, 5886.0...
<python><pandas><time-series><subsequence>
2023-01-22 22:15:14
1
488
till Kadabra
75,204,255
16,845
How to force a platform wheel using build and pyproject.toml?
<p>I am trying to force a Python3 non-universal wheel I'm building to be a platform wheel, despite not having any native build steps that happen during the distribution-packaging process.</p> <p>The wheel will include an OS-specific shared library, but that library is built and copied into my package directory by a lar...
<python><setuptools><python-packaging><python-wheel><pep517>
2023-01-22 22:05:44
1
1,216
Charles Nicholson
75,204,254
14,090,167
Build conda package cryptography:37.0.2 with python 3.8.0
<p>I am attempting to build conda package for <a href="https://pypi.org/project/cryptography/37.0.2/" rel="nofollow noreferrer">cryptogaphy</a>:37.0.2 for osx-arm64. The build fails, if I try to build it with dependecy of python 3.8; the same build is successful, if I use python 3.10. Can anyone help me on how to build...
<python><conda><pypi><conda-forge>
2023-01-22 22:05:37
1
717
Chinmaya Biswal
75,204,243
3,132,087
Python Openpyxl library cannot deal with automatic row height
<p>I'm currently using Openpyxl in a Django project to create an excel report. I'm starting from a blank excel model in which column C has text wrap enabled. Infact when I open the model and populate manually a cell I correctly get this</p> <p><a href="https://i.sstatic.net/kg7ta.png" rel="nofollow noreferrer"><img src...
<python><django><openpyxl>
2023-01-22 22:04:44
1
829
Stefano Losi
75,204,137
16,997,421
How to retrieve email based on sender, sent date and subject using graph api with python3
<p>I'm working on a simple python script to help me retrieve email in office365 user mailbox based on the following parameters, <code>sentdatetime, sender or from address and subject</code>.</p> <p>As of current, am able to get the access token using msal, however the email api call does not work. I get an <code>error ...
<python><python-3.x><email><microsoft-graph-api><microsoft-graph-mail>
2023-01-22 21:44:30
1
352
Bernietechy
75,204,066
13,142,245
Python: Extract all possible mutually exclusive pairs?
<p>I have an assignment problem where I have N participants and need to find all possible 2-person assignments where every participant is assigned to exactly one pair.</p> <p>When I use <code>list(combinations(range(100), 2))</code> I get a &quot;flat&quot; list of about 4000 items, each a pair in the form of (i,j).</p...
<python><graph><combinations><combinatorics>
2023-01-22 21:31:57
2
1,238
jbuddy_13
75,203,970
4,936,725
How to add all requirements.txt dependencies to py_library in Bazel BUILD file @rules_python
<p>When using Bazel @rules_python there's is this handy target generator helper <a href="https://github.com/bazelbuild/rules_python/blob/1722988cc407b08a4e7770295452076706823f9d/docs/pip.md#pip_parse" rel="nofollow noreferrer">pip_parse</a>, which generates library targets for every dependency in <code>requirements.txt...
<python><pip><dependencies><bazel>
2023-01-22 21:15:30
0
410
manews
75,203,893
3,971,855
Not getting output when using terms to filter on multiple values
<p>I have a table in opensearch in which the format of every field is &quot;text&quot;.</p> <p>This is how my table looks like</p> <p><a href="https://i.sstatic.net/B0F15.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/B0F15.png" alt="enter image description here" /></a></p> <p>Now the <strong>query(q1)<...
<python><elasticsearch><opensearch><amazon-elasticsearch><amazon-opensearch>
2023-01-22 21:03:05
1
309
BrownBatman
75,203,642
9,822,004
Import problems in python unittest
<p>I'm new to python and trying to get a unittest working, but the imports in the test files don't work. Folder structure:</p> <pre><code>toyProjects └── pythonProj β”œβ”€β”€ mainpack β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ MyClass.py β”‚ └── setup.py └── tests β”œβ”€β”€ __init__.py └── t...
<python><python-import><python-unittest>
2023-01-22 20:23:24
1
400
MJL
75,203,558
20,130,220
How can I count the number of occurrences of a given string in a string array in pandas
<p>I want to see which tags occur most frequently in my dataset. When i try to do this on my own i get something like this:</p> <pre><code>df['tags'].value_counts() </code></pre> <blockquote> <p>['Startup'] 80<br /> ['Bitcoin'] 79<br /> ['The Daily Pick'] 78<br /> ['Addiction', 'Health', 'Body', 'Alcohol', 'Mental ...
<python><pandas><dataframe>
2023-01-22 20:09:48
2
346
IvonaK
75,203,436
14,673,832
Unexpected output while sorting the list of IP address
<p>I am trying to sort the list of ipaddress from the following list.</p> <pre><code>IPlist= ['209.85.238.4', '216.239.51.98', '64.233.173.198', '64.3.17.208', '64.233.173.238'] </code></pre> <p>#1st case</p> <pre><code>tmp1 = [list (map (str, ip.split(&quot;.&quot;))) for ip in IPlist] tmp1.sort() print(tmp1) </code>...
<python><list><sorting>
2023-01-22 19:51:16
1
1,074
Reactoo
75,203,370
6,876,149
Find indices of closest samples in distance matrix
<pre><code>import torch from torch.utils.data import DataLoader from torchvision import datasets, transforms myTransform = transforms.Compose([ transforms.Resize((160, 160)), transforms.ToTensor(), ]) image_datasets = datasets.ImageFolder(data_dir, transform=myTransform) randomIdx = rnd.randint...
<python><matrix><distance><distance-matrix>
2023-01-22 19:41:30
0
2,826
C.Unbay
75,203,248
1,019,129
Deep reference ..? | Intertools.product()
<p>The following (pseudo) code should insert <strong>only one</strong> ZERO per pair</p> <pre class="lang-py prettyprint-override"><code>from itertools import product In [321]: for p in product([[1],[2]],[[4],[5]]): p[0].insert(0,0) print(p) Out [321] ([0, 1], [4]) ([0, 0, 1], [5]) ([0, 2], [4]) ([0, 0, ...
<python><product><pass-by-reference><python-itertools>
2023-01-22 19:24:14
0
7,536
sten
75,203,120
3,881,486
Pandas aggregation groupby and min
<p>I have the following data set and I want to return the <em>minimum</em> of <code>vol</code> grouped by <code>year</code> but I want also to know on which day (<code>date</code> column) this minimum occurred. This is a part of a bigger function.</p> <p>For the example below, the return should be:</p> <pre><code>1997-...
<python><pandas><dataframe><pyspark>
2023-01-22 19:08:09
1
703
Pirvu Georgian
75,203,044
19,079,397
How to create polygon from bbox data in python?
<p>I have created a code in R which extracts <code>bbox</code> from a list of points and then creates a polygon using <code>st_as_sfc</code>. Now I am trying to do the same in python where I was able to get the <code>bbox</code> coordinates from the list of points data and then tried to create polygon using the two poi...
<python><r><polygon><geopandas><point>
2023-01-22 18:57:35
2
615
data en
75,202,868
12,860,924
Split labelling image parts into sub labelled images using python
<p>I am working on medical images. I want to segment each image into sub-segments parts according to the labelled letter in each part of the image. I have tried multiple codes and functions but I don't know how can I do that.</p> <p><strong>Example of my dataset</strong></p> <p>The original image</p> <p><a href="https:...
<python><image-processing><image-segmentation><labeling><east-text-detector>
2023-01-22 18:26:07
0
685
Eda
75,202,810
13,741,789
How to parse html such that the nesting that is implicit by header levels becomes explicit?
<p>I run into the same problem in a different form while web-scraping, over and over, and for some reason I can't seem to push my head through it.</p> <p>The core of it is basically this:</p> <p>HTML has a relatively flat organizational structure with some nesting implicit. I want to make that explicit.</p> <p>To show...
<python><html><json><beautifulsoup>
2023-01-22 18:17:22
1
312
psychicesp
75,202,679
10,633,402
How do I resolve AttributeError: "Pages" object has no attribute "pages"
<p>I have a few custom classes that look like this:</p> <pre class="lang-py prettyprint-override"><code>from typing import List from typing_extensions import Self class Page: def __init__(self, search_id: str, page_num: int) -&gt; None: self.search_id = search_id self.page_num = page_num se...
<python><class>
2023-01-22 17:57:33
2
1,919
prismo
75,202,656
14,282,714
How to change python version in r-reticulate environment?
<p>I would like to upgrade my python version in my <code>r-reticulate</code> environment. First I activate the right environment like this:</p> <pre><code>conda activate /Users/quinten/Library/r-miniconda/envs/r-reticulate </code></pre> <p>Let's check the python version:</p> <pre><code>python3 --version Python 3.7.11 <...
<python><r><conda><reticulate><quarto>
2023-01-22 17:55:10
1
42,724
Quinten
75,202,619
8,964,393
How to calculate the maximum sum in a reverse way in pandas list
<p>I have this list:</p> <pre><code>balance = [300,400,250,100,50,1,2,0,10,15,25,20,10,1,0,10,15] </code></pre> <p>I need to calculate the maximum consecutive increase in balance over a certain period of time. The first element on the right is the most recent.</p> <p>For example, I need to calculate the maximum consecu...
<python><pandas><list><counter>
2023-01-22 17:50:24
1
1,762
Giampaolo Levorato
75,202,610
21,061,285
TypeError: 'type' object is not subscriptable Python
<p>Whenever I try to type-hint a list of strings, such as</p> <pre><code>tricks: list[str] = [] </code></pre> <p>, I get <em>TypeError: 'type' object is not subscriptable</em>. I follow a course where they use the same code, but it works for them. So I guess the problem is one of these differences between my an the cou...
<python><visual-studio-code>
2023-01-22 17:48:01
4
423
Sebastian
75,202,551
147
Segmentation Fault running wxPython 4.20 on macOS Monterey with Python 3.9 or 3.10
<p>I am trying to use wxPython 4.2.0 I have python 3.9.12 and 3.10.7 on my system and the results are identical with both. It's a 2021 MacBook Pro with an M1 chip.</p> <p>I cannot run even the simplest app as my regular user, it fails on <code>import wx</code> with a segmentation fault. If I run under <code>sudo</co...
<python><macos><wxpython>
2023-01-22 17:38:53
1
37,821
Gareth Simpson
75,202,479
2,299,245
Merge overlapping rasters using GDAL
<p>I have around 211 rasters, one for each area of the world. The gdalinfo for one of them is below. They are all the same except for the area of concern. Values are always between 1-6.</p> <p><a href="https://i.sstatic.net/PS3CA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PS3CA.png" alt="enter image...
<python><gdal>
2023-01-22 17:28:21
1
949
TheRealJimShady
75,202,475
1,761,907
joblib persistence across sessions/machines
<p>Is joblib (<a href="https://joblib.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">https://joblib.readthedocs.io/en/latest/index.html</a>) expected to be reliable across different machines, or ways of running functions, even different sessions on the same machine over time?</p> <p>For concreteness if ...
<python><joblib>
2023-01-22 17:27:46
1
2,453
John Kitchin