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,855,377
21,346,793
Getting an exception with fine-tuning of model
<p>I am trying to fine-tune a model. There is a dataset:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;sample&quot;: [ &quot; Какие советы помогут вам составить успешный бизнес-план?&quot;, &quot;\n1. Изучите свой целевой рынок: поймите, кому вы продаете, насколько велика конкуренция...
<python><machine-learning><pytorch><huggingface-tokenizers>
2023-03-27 11:46:18
1
400
Ubuty_programmist_7
75,855,339
1,570,911
Convert from flat one-hot encoding to list of indices with variable length
<p>I have a list of integers, which I convert to variable one-hot encoding. For example, consider a list:</p> <pre><code>l = [(4, func1), (3, func2), (6, func3)] </code></pre> <p>The list's meaning is: The function object <code>func1</code> accepts integers in the range 0..3, <code>func2</code> can be called as <code>f...
<python><numpy><functional-programming>
2023-03-27 11:42:53
2
974
Technaton
75,855,273
10,548,152
Dynamic domain for many2one field without onchange
<p>I need to add dynamic domain for many2one field based another(bool) field <strong>without onchange function</strong> .. my code below doesn't work ..</p> <pre><code>is_bus_registered = fields.Boolean( string='Bus Registered', required=False) def _domain_att_policy(self): if self.is_bus_registered: ...
<python><python-3.x><odoo><odoo-16>
2023-03-27 11:36:42
2
663
omar ahmed
75,855,051
9,525,238
Python3: Callbacks from other classes in a class variable list
<p><a href="https://i.sstatic.net/JqGut.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JqGut.png" alt="enter image description here" /></a></p> <p>Hey.</p> <p>So I got this &quot;data&quot; class that contains a dictionary with functions that modify it's contents. And I have 2 widgets that I want to upd...
<python><python-3.x><class><callback><singleton>
2023-03-27 11:10:44
1
413
Andrei M.
75,855,026
913,098
In Pandas, how to retrieve the rows which created each group, after aggregation and filtering, when grouping by multiple columns?
<p>This is a follow up to <a href="https://stackoverflow.com/q/75854693/913098">this question</a></p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': ['A', 'A', 'B', 'B', 'B', 'C'], 'b': ['A', 'A', 'B', 'B', 'B', 'C'], 'hole': [True, True, True, False, False, True] } ) print(d...
<python><pandas><dataframe><aggregate><multi-index>
2023-03-27 11:08:01
4
28,697
Gulzar
75,855,005
8,026,780
How to inherit one class implement by C
<p>I want to add method for one class implemented by C</p> <pre class="lang-py prettyprint-override"><code>from lru import LRU class A(LRU): def foo(self): print(&quot;a&quot;) </code></pre> <p>lru is a lib from <a href="https://github.com/amitdev/lru-dict" rel="nofollow noreferrer">https://github.com/amit...
<python><python-c-api><python-class>
2023-03-27 11:06:31
1
453
Cherrymelon
75,854,837
6,346,482
Seaborn: cumulative sum and hue
<p>I have the following dataframe in pandas:</p> <pre><code>data = { 'idx': [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], 'hue_val': [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quo...
<python><python-3.x><pandas><seaborn><visualization>
2023-03-27 10:49:01
2
804
Hemmelig
75,854,815
19,500,571
Dash: Fit a dropdown and graph in an inline-block
<p>I want to plot 4 graphs side-by-side in the style of a 2x2 grid. The graph in the lower right corner I want to attach a dropdown to with a callback that allows for changing the color.</p> <p>I have an example of it below. However, the issue is that I have to explicitly set the width, otherwise the graph wont display...
<python><html><css><plotly-dash><dashboard>
2023-03-27 10:46:46
1
469
TylerD
75,854,813
1,103,752
Python serial read corrupting print statements
<p>I have this bizarre situation where reading from a serial port is appearing to corrupt calls to <code>print</code>. This code:</p> <pre class="lang-py prettyprint-override"><code> ser = serial.Serial('COM13', 115200, timeout=5) ser.reset_input_buffer() ser.reset_output_buffer() ser.wr...
<python><pyserial>
2023-03-27 10:46:43
1
5,737
ACarter
75,854,750
2,367,231
PyScript - NameError: name 'function' is not defined -- then *.py is load with <py-script src="..."> (DJango)
<p>I have a Python script containing a plot calculation and a function definition:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np from pyscript import Element import datetime x = np.random.randn(1000) y = np.random.randn(1000) fig, ax = plt.subplots() ax.scatter(...
<python><html><django><pyscript>
2023-03-27 10:39:02
0
3,975
Alex44
75,854,693
913,098
In Pandas, how to retrieve the rows which created each group, after aggregation and filtering?
<p>Let</p> <pre><code>import pandas as pd df = pd.DataFrame( { 'a': ['A', 'A', 'B', 'B', 'B', 'C'], 'b': [True, True, True, False, False, True] } ) print(df) groups = df.groupby('a') # &quot;A&quot;, &quot;B&quot;, &quot;C&quot; agg_groups = groups.agg({'b':lambda x: all(x)}) # &quot;A&quot;...
<python><pandas><aggregate>
2023-03-27 10:32:36
3
28,697
Gulzar
75,854,527
10,962,766
How can I assign several consecutive values to a dataframe in a loop?
<p>I am looping through a dataframe in which the &quot;pers_function&quot; column has several values in each cell (separated by a comma) describing people's occupations. I want to duplicate each row and write only ONE profession to each cell in the &quot;pers_function&quot; column.</p> <p>Unfortunately, the result has ...
<python><pandas>
2023-03-27 10:11:28
1
498
OnceUponATime
75,854,518
11,644,523
In Snowflake dataframes, is there an equivalent to pandas.apply function?
<p>I would like to apply functions to specific column in snowflake, but I do not see in the documentation <a href="https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/index.html" rel="nofollow noreferrer">https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/index.html</a>.</p> <p>...
<python><pandas><snowflake-cloud-data-platform>
2023-03-27 10:10:39
1
735
Dametime
75,854,501
6,664,393
setting to default value if None
<p>If I was trying to do</p> <pre><code>safe_value = dict_[key] if key in dict_ else default </code></pre> <p>a more concise way would be</p> <pre><code>safe_value = dict_.get(key, default) </code></pre> <p>Is there something similar to shorten the following (in Python 3.11)?</p> <pre><code>safe_value = value if value...
<python>
2023-03-27 10:08:41
1
1,913
user357269
75,854,442
2,876,079
How to set tab indent for function arguments in PyCharm?
<p>Instead of double indent <strong>for function arguments</strong></p> <pre><code>def foo( name ): print('hello ' + name) </code></pre> <p>I would like to use single indent:</p> <pre><code>def foo( name ): print('hello ' + name) </code></pre> <p>=&gt; How can I tell PyCharm to use single indent for...
<python><pycharm><styling>
2023-03-27 10:03:11
1
12,756
Stefan
75,854,415
17,487,457
DataFrame: impute column with the median value of each category
<p>My dataset looks like:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame( {'sensor1': [1.94,0.93,0.98,1.75,1.75,3.25,0.5,0.5,5.59,6.02,9.21,4.54,3.71,1.05], 'sensor2': [-0.91,0.42,-0.11,0.0,0.0,-0.12,0.0,0.0,0.48,0.26,-1.5,-0.75,-1.45,0.06], 'sensor3': [18,19,20,-2094,-2094,17,17,17,-985,-985,1...
<python><pandas><dataframe>
2023-03-27 10:00:10
1
305
Amina Umar
75,854,392
8,771,201
Mysql query to update record based on other row in same table (with inputparameter)
<p>I have this table to store articles from different suppliers. These are the most important table fields of my table &quot;artPerBrand&quot;:</p> <pre><code>|ID | ArtNrShort | ArtNrLong | SupplierID -------------------------------------------------- |45 | mik25 | mike25_002 | 1 |326 | mik25 ...
<python><mysql><mariadb>
2023-03-27 09:58:09
1
1,191
hacking_mike
75,854,381
21,346,793
How to convert JSON data into JSON?
<p>I have got an a JSON lines file:</p> <pre><code>{&quot;sample&quot;: [&quot; Какие советы помогут вам составить успешный бизнес-план?&quot;, &quot;\n1. Изучите свой целевой рынок: поймите, кому вы продаете, насколько велика конкуренция и текущие тенденции.\n2. Определите свою бизнес-модель и стратегии: решите, какие...
<python><json>
2023-03-27 09:57:28
1
400
Ubuty_programmist_7
75,853,976
13,349,539
Finding a specific element in nested Array MongoDB
<h1>DB Schema</h1> <pre><code>[{ &quot;_id&quot;: 1, &quot;name&quot;: &quot;city1&quot;, &quot;districts&quot;: [ { &quot;id&quot;: 5, &quot;name&quot;: &quot;district 1&quot;, &quot;neighborhoods&quot;: [ { &quot;id&quot;: 309, &quot;name&quot;: &quot;neighborho...
<python><mongodb><nosql><fastapi>
2023-03-27 09:12:53
1
349
Ahmet-Salman
75,853,973
4,594,063
Azure app service - app not in root directory
<p>I have a mono repo with more than one application in it. The application I'm trying to deploy is in the directory rest_api. The deploy as seen in github actions is successful, but start-up fails.</p> <p>This is my start-up command <code>gunicorn -w 1 -k uvicorn.workers.UvicornWorker main:app</code></p> <p>This is wh...
<python><azure><azure-web-app-service>
2023-03-27 09:12:35
1
1,832
Wessi
75,853,946
11,261,546
Declare variable None list of argumetns
<p>I want to error-test several functions in my library by passing <code>None</code> to all their input arguments:</p> <pre><code>fun_1(None) fun_2(None, None) fun_3(None) fun_4(None, None, None) </code></pre> <p>However I have a lot of functions and I want to make it very simple to add each of the to the test.</p> <p>...
<python>
2023-03-27 09:09:51
1
1,551
Ivan
75,853,877
8,184,694
How can I connect with Python to a subfolder in an Azure Container if I only have access to that folder?
<p>I have access to a specific folder in an Azure Blob Container and want to connect to it via Python. In Azure Storage Explorer I was able to set up that connection via selecting &quot;ADLS Gen2 container or directory&quot; as a Resource and then pasting the <code>sas_url</code>.</p> <p><a href="https://i.sstatic.net/...
<python><azure><azure-storage>
2023-03-27 09:02:22
1
541
spettekaka
75,853,665
1,627,106
How to set the python logging class using dictConfig
<p>I'm using a dictConfig to setup logging, for example like this:</p> <pre><code>LOGGING_CONF: typing.Dict[str, typing.Any] = { &quot;version&quot;: 1, &quot;disable_existing_loggers&quot;: False, &quot;formatters&quot;: { &quot;default&quot;: { &quot;format&quot;: &quot;%(asctime)s %(l...
<python><logging><python-logging>
2023-03-27 08:35:33
1
1,712
Daniel
75,853,317
14,912,118
Getting Error: [Errno 95] Operation not supported while writing zip file in databricks
<p>Here i am trying to zip the file and write that to one folder (mount point) using below code in Databricks.</p> <pre><code># List all files which need to be compressed import os modelPath = '/dbfs/mnt/temp/zip/' filenames = [os.path.join(root, name) for root, dirs, files in os.walk(top=modelPath , topdown=False) fo...
<python><python-3.x><azure><zip><databricks>
2023-03-27 07:54:16
1
427
Sharma
75,853,269
6,224,975
Split the use of "n_jobs" in sklearn between StackingClassifier and estimators
<p>Say I have the following flow</p> <pre class="lang-py prettyprint-override"><code>from sklearn.ensemble import StackingClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline X,y = g...
<python><scikit-learn><multiprocessing>
2023-03-27 07:48:51
0
5,544
CutePoison
75,853,190
20,732,098
Merging columns Dataframe
<p>I have the following Dataframe: df1</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>startTimeIso</th> <th>endTimeIso</th> <th>id</th> </tr> </thead> <tbody> <tr> <td>2023-03-07T03:28:56.969000</td> <td>2023-03-07T03:29:25.396000</td> <td>5</td> </tr> <tr> <td>2023-03-07T03:57:08.734000</...
<python><dataframe><time><merge>
2023-03-27 07:38:06
1
336
ranqnova
75,853,184
2,979,441
Unable to get the list of topics from AWS MSK using Python
<p>we are trying to get the list of topics using the Python, but it returns empty list.</p> <pre><code>from kafka.admin import KafkaAdminClient #configure Kafka client for SCRAM client = KafkaAdminClient( bootstrap_servers=&quot;b-2-public.url.url2.c3.kafka.eu-west-3.amazonaws.com:9196&quot;, sasl_mechanism=&quot;SCR...
<python><amazon-web-services><apache-kafka><aws-msk>
2023-03-27 07:37:56
1
607
rholdberh
75,853,048
1,866,775
Why does the memory usage shown by psutil differ so much from what cgroups shows?
<p>While running a Python service in Kubernetes (pod with just one container, my Gunicorn process has PID <code>1</code>), I monitor the memory usage:</p> <pre class="lang-py prettyprint-override"><code>psutil.Process().memory_full_info() </code></pre> <p>output:</p> <pre><code>pfullmem(rss=669609984, vms=5986619392, s...
<python><kubernetes><memory><psutil><cgroups>
2023-03-27 07:21:29
0
11,227
Tobias Hermann
75,852,857
1,388,835
is virtual environment only for development or even for running application
<p>I am using ubuntu 22.04 with python 3.10.6 version. My Django application currently works on python 3.7 version and it gives issues in 3.10 version. I want to use virtual environment with python 3.7 version to make application run. If i run the application with Gunicorn for production, will it run 3.7 version of vir...
<python><django><gunicorn>
2023-03-27 06:54:02
1
1,491
Smith
75,852,617
10,487,667
Python displaying contents of file on browser using Flask
<p>I am working on a Python project using Flask which has the following directory structure -</p> <pre><code>MyProject | +-- app | +-- init.py +-- views.py +-- downloads | +-- myFile.txt +-- static | +-- css | +-- style.css +-- img ...
<python><flask><jinja2>
2023-03-27 06:17:42
1
567
Ira
75,852,581
1,895,996
Is it impossible to select a single dataframe row without unwanted type conversion?
<p>I'm iterating row-by-row over an existing dataframe, and I need to select the contents of one row, preserving all of its properties, and then append new columns to it. The augmented row is then to be appended to a new dataframe. For various reasons, I can't do a bulk operation on the entire dataframe, because comp...
<python><pandas><dataframe>
2023-03-27 06:10:43
1
1,291
Grant Petty
75,852,540
15,051,878
Regex occurrence help in python
<p>I have a specific use case to identify the sentences that end with colon (<code>:</code>) and start with a full stop (<code>.</code>)</p> <p>I have another condition that if the full stop is followed by a number then it should look for previous full stop.</p> <p>Here is an example</p> <p>Input statement: <code>but I...
<python><regex>
2023-03-27 06:03:37
3
354
Tushar Sethi
75,852,442
9,653,254
How to stack columns to rows in Python?
<p>For example, the data structrue is like below.</p> <pre><code>import pandas as pd source={ 'Genotype1':[&quot;CV1&quot;,&quot;CV1&quot;,&quot;CV1&quot;,&quot;CV1&quot;,&quot;CV1&quot;], 'Grain_weight1':[25,26,30,31,29], 'Genotype2':[&quot;CV2&quot;,&quot;CV2&quot;, &quot;CV2&quot;,&quot;CV2&quot;,&quot;CV2&quot;]...
<python><stack><transpose>
2023-03-27 05:44:46
2
964
J.K Kim
75,852,238
1,146,785
python typings - how to handle optional responses
<p>I have a func with return type <code>(str | None)</code></p> <p><code>url = check_file_exists(cloud_path)</code></p> <p>typescript has an AST which is smart enough to know that within the following block the return was indeed NOT <code>None</code>. but mypi will complain about this:</p> <p><code>Incompatible return ...
<python><python-typing>
2023-03-27 04:55:18
1
12,455
dcsan
75,852,199
1,601,580
How do I print the wandb sweep url in python?
<p>For runs I do:</p> <pre><code>wandb.run.get_url() </code></pre> <p>how do I do the same but for sweeps given the <code>sweep_id</code>?</p> <hr /> <p>fulls sample run:</p> <pre><code>&quot;&quot;&quot; Main Idea: - create sweep with a sweep config &amp; get sweep_id for the agents (note, this creates a sweep in wand...
<python><machine-learning><deep-learning><wandb>
2023-03-27 04:44:42
1
6,126
Charlie Parker
75,852,132
4,894,051
Python PANDAS how to drop all rows in dataframe, with duplicate column value, if specific cell in a row is a specific value
<p>This is a little different and I can't find it anywhere. Even good ol' ChatGPT is stuck, so asking real humans.</p> <p>I have a dataframe like so:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>oldVoucherId</th> <th>valuePurchased</th> <th>valueRemaining</th> </tr> </thead> <tbody> <tr...
<python><pandas><dataframe>
2023-03-27 04:26:05
2
656
robster
75,852,122
1,146,785
how to type python API responses similar to TS `as`?
<p>I'm using a lib that types its response as</p> <p><code>-&gt; (Unknown | Response | Any)</code></p> <p>If i know/expect the response to be a <code>Response</code> and that is has an <code>id</code> field, how can I cast that in my code?</p> <p>Typescript provides an <code>as &lt;type&gt;</code> operator for this.</p...
<python><mypy><python-typing>
2023-03-27 04:22:54
1
12,455
dcsan
75,852,084
21,286,804
mypy catches errors better with TypeVar than Union
<p><strong>First Implementation</strong></p> <pre><code>from typing import Union U = Union[int, str] def max_1(var1: U, var2: U) -&gt; U: return max(var1, var2) print(max_1(&quot;foo&quot;, 1)) # mypy accept this, despite the fact that the type of var1 is str and the type of var2 is int print(max_1(1, &quot;foo&...
<python><mypy><python-typing>
2023-03-27 04:12:46
0
427
Magaren
75,852,061
607,453
How does the degree tuple in wand's draw.arc work? Advanced math? Sorcery?
<p>wand's <a href="https://docs.wand-py.org/en/0.6.11/wand/drawing.html#wand.drawing.Drawing.arc" rel="nofollow noreferrer">draw.arc</a> takes three arguments:</p> <ul> <li>starting coordinates</li> <li>ending coordinates</li> <li>a &quot;pair which represents starting degree, and ending degree&quot;</li> </ul> <p>What...
<python><wand>
2023-03-27 04:07:05
2
814
raindog308
75,851,849
10,284,437
Mouve mouse, human like, with Python/Selenium (like pptr ghost-cursor)
<p>I try this code: <a href="https://stackoverflow.com/questions/39422453/human-like-mouse-movements-via-selenium">Human-like mouse movements via Selenium</a> but <strong>trying to figure out how to integrate it in a real life scraper</strong> to follow with my mouse with different DOM elements:</p> <pre><code>#!/usr/b...
<python><selenium-webdriver><web-scraping><selenium-chromedriver><mouse>
2023-03-27 03:14:51
2
731
Mévatlavé Kraspek
75,851,842
13,262,692
tensorflow map function to mulitple tensors
<p>I am using the following function in a custom layer in TensorFlow to rearrange query, key values:</p> <pre><code>q, k, v = map(lambda t: rearrange(t, 'b n (h d) -&gt; b h n d', h = self.heads), (q, k, v)) </code></pre> <p>and it throws this warning:</p> <p><code>WARNING:tensorflow:From /usr/local/lib/python3.9/dist...
<python><tensorflow>
2023-03-27 03:11:32
1
308
Muhammad Anas Raza
75,851,686
12,596,824
DataFrame with repeated indexes - how do I count the frequency of each index?
<p>I have a data frame like so:</p> <pre><code> ages 0 94.0 0 94.0 0 94.0 1 30.0 1 30.0 2 64.0 2 64.0 2 64.0 3 57.0 3 57.0 3 57.0 </code></pre> <p>You can see that the indexes are repeated multiple times for some indexes. I want to count the frequency of each index. How can I do this...
<python><pandas>
2023-03-27 02:22:36
1
1,937
Eisen
75,851,601
6,077,239
How to generate a unique temporary column name to use in a Polars dataframe without conflicts?
<p>I have a custom function that does some data cleaning on a <code>polars</code> DataFrame. For efficiency, I cache some results in the middle and remove them at the end.</p> <p>This is my function:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl def clean_data(df, cols): return ( ...
<python><dataframe><python-polars>
2023-03-27 02:00:12
1
1,153
lebesgue
75,851,531
1,693,057
Why doesn't a read-only Mapping work as a type hint for a Dict attribute in Python?
<p>Why does a read-only <code>Mapping</code> not work as a type hint for a <code>Dict</code> attribute? I know <code>dict</code> is mutable, which makes the <code>field</code> invariant, but could you explain what can go wrong with passing it to a read-only <code>Mapping</code> type?</p> <p>Consider the following code:...
<python><mapping><mypy><typing><pyright>
2023-03-27 01:40:19
1
2,837
Lajos
75,851,481
417,678
Configuring ElasticSearch SSL and Python Querying, Certificates Question
<p>I have certificates from GoDaddy for my ElasticSearch instance. I'm trying to set it up and below I have the configuration for SSL. I can hit this via the browser easily and everything is fine. If I use the Python ElasticSearch package then I start getting SSL errors where it's &quot;unable to get local issuer certi...
<python><elasticsearch><ssl>
2023-03-27 01:27:08
2
6,469
mj_
75,851,415
13,684,789
Why can GET Request Access OAuth-2.0-Protected File Without Bearer Token?
<h4>Context and Details</h4> <p>I was sent a Hirevue link in response to a job application I submitted and I am messing around with the HTTP requests made by page at that URL. I cannot provide the URL to the page nor the URL that the request I am asking about is sent to without compromising personal information. Thus, ...
<python><oauth-2.0><python-requests>
2023-03-27 01:07:50
0
330
Übermensch
75,851,364
3,529,833
Python - Is there a built-in publisher/consumer pattern?
<p>I was looking for a very simple, inline, publisher/consumer, or an event pattern, builtin in Python, is there such thing?</p> <p>For example:</p> <p>db/user.py</p> <pre><code>def create(**kwargs): user = db.put('User', **kwargs) publish('user.created', user) </code></pre> <p>admin/listeners.py</p> <pre><code>@co...
<python><python-3.x><python-3.9>
2023-03-27 00:47:47
2
3,221
Mojimi
75,851,351
5,637,851
ModuleNotFoundError: No module named 'django_heroku' when pushing to heroku
<p>I am trying to upload my project to Heroku and using python 3.11.2. I migrated and was able to run server after changing settings. My Procfile contains:</p> <pre><code>web gunicorn albion.wsgi:application --log-file - release: python manage.py migrate </code></pre> <p>When uploading, I'm getting this error from Hero...
<python><heroku>
2023-03-27 00:44:15
1
800
Doing Things Occasionally
75,851,280
5,212,614
How to loop through records and create multiple WordCloud charts?
<p>I have a simple dataframe with two columns of text. Here is my script.</p> <pre><code>from wordcloud import WordCloud, STOPWORDS for i in df_cat.columns: text = df_cat[i].values wordcloud = WordCloud().generate(str(text)) plt.imshow(wordcloud) plt.axis('off') plt.show() </code></pre> <p>Here's th...
<python><python-3.x><dataframe><word-cloud>
2023-03-27 00:19:58
0
20,492
ASH
75,851,273
523,612
After `x = x.y()`, why did `x` become `None` instead of being modified (possibly causing "AttributeError: 'NoneType' object has no attribute")?
<p><strong>If your question was closed as a duplicate of this, it is because</strong> you have some code of the <em>general form</em></p> <pre><code>x = X() # later... x = x.y() # or: x.y().z() </code></pre> <p>where <code>X</code> is some type that provides <code>y</code> and <code>z</code> methods intended to <em>mut...
<python><attributeerror><nonetype><command-query-separation>
2023-03-27 00:18:30
1
61,352
Karl Knechtel
75,851,213
8,610,346
How to create predefined groups of widgets in QT Designer to add them to a QScrollArea from the final code
<p>Lets say I create a tapi phone application in QT Designer that contains a simple phonebook. There is no code so far, but a basic layout. (see screenshot)</p> <p>As you can see, the phonebook does contain some sample records, you could call it a template of what a record should look like.</p> <p>Is there a way to cre...
<python><qt-designer><pyqt6>
2023-03-26 23:55:33
0
713
Ovski
75,851,187
11,951,910
Check if a list of values are plus or minus 1 of each other
<p>I have a list of values <code>scores = [80,90,50,60,70]</code></p> <p>Trying to write an all statement to determine if the values are +/- 2 of each other.</p> <p>I've figured out how to code if they are +/- 2 of some value say 82, but not sure if it is even possible to do +/- 2 of each other.</p> <p>I am not sure wh...
<python><python-3.x>
2023-03-26 23:44:40
1
718
newdeveloper
75,851,104
15,545,814
When I run a module function, it freezes the program (Python)
<p><strong>Context</strong><br /> I'm writing a parser in Python and have lexer and AST files in other modules</p> <p>In my main.py file, I have this code:</p> <pre><code>from parserdef import Parser def repl(): parser = Parser() while True: source = input(&quot;-&gt; &quot;) if source == &quot;exit&quot;...
<python><parsing><abstract-syntax-tree>
2023-03-26 23:19:04
0
512
LWB
75,850,839
472,297
sympy matrix.factor() fails with message about 'noncommutative scalars'
<p>I am looking for how to extract common factors of sympy symbolic matrices.</p> <p>A minimal example would be:</p> <pre class="lang-py prettyprint-override"><code>import sympy as sy N = sy.Symbol(&quot;N&quot;, integer=True, positive=True) P = sy.Symbol(&quot;P&quot;, integer=True, positive=True) X = sy.MatrixSymbol...
<python><sympy>
2023-03-26 22:07:19
0
841
conjectures
75,850,542
15,363,250
How to create a new worksheet in existing Google Sheets file using python and google sheets api?
<p>I'm trying to use an old python code I used about an year ago (in a different account) but now it's not working anymore and I just can't fix it.</p> <pre><code>def create_new_sheet(sheet_name, sheet_id): SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SERVICE_ACCOUNT_FILE = 'token.json' creds...
<python><google-sheets-api>
2023-03-26 21:02:16
1
450
Marcos Dias
75,850,480
1,667,423
Type annotation for "at least one argument is of type X"
<p>I'm trying to use <a href="https://mypy.readthedocs.io/en/stable/more_types.html" rel="nofollow noreferrer">overloading</a> to make the return type of a variadic function depend on the type of its arguments in a certain way. Specifically, I want the return type to be X if and only if <em>any</em> of its arguments is...
<python><overloading><python-typing><mypy>
2023-03-26 20:47:55
1
1,328
user76284
75,850,340
9,727,674
How to create a clip from an mp4-file quickly?
<p>I have a web app that lets users download a clip from a mp4-file specified before. Currently I use <code>ffmpeg</code> via python like this:</p> <pre><code>os.system('ffmpeg -i original_video -ss {start} -t {duration} result_video') </code></pre> <p>Processing 10 minutes of 720p video with this method also takes a f...
<python><video><ffmpeg><mp4><video-processing>
2023-03-26 20:20:28
2
1,530
Moritz Groß
75,850,315
5,387,770
How to find the lengh of the fields in a pyspark dataframe?
<p>I have a question on pyspark dataframe. I have defined a nested dataframe like the below. How to calculate the number of fields here of the dataframe here. In my understanding the number of fields are 5.</p> <pre><code> schema = StructType( [ StructField('feat_1', TimestampType(), False), ...
<python><pyspark><apache-spark-sql>
2023-03-26 20:14:59
0
625
Arun
75,850,221
9,497,000
Making a layout that automaitcally has the correct spacing
<p>How do I create a layout object (BoxLayout, GridLayout etc...) where If I pass it x objects and the layout object has a height of y then it automatically assigns a space between objects so that they are all evenly spaced out.</p> <p>I tried to follow <a href="https://stackoverflow.com/questions/32518975/kivy-layout-...
<python><android><kivy><kivymd>
2023-03-26 19:55:46
1
472
Oliver Brace
75,850,188
7,581,507
Install wheel from a directory using Poetry
<p>I am using a python package which has a complex build process, and hence it provides wheels for various platforms.</p> <p>I am looking for a way to configurate <code>poetry</code> to be able to install the package using the right wheel (for each platform it will be ran on) given a path to a directory containing the ...
<python><pip><python-packaging><python-poetry>
2023-03-26 19:50:42
2
1,686
Alonme
75,850,114
11,131,258
How to interpolate a value in a dataframe using custom formula
<p>How can I apply a formula to interpolate missing values in my entire dataframe? I have already calculated the formula for one row and now I want to apply it to all the rows in my dataframe.</p> <pre><code>import pandas as pd df = pd.DataFrame({'x': [2.2, 2.32, 2.38], 'y': [4.9644, None, 4.9738], 'z' : [5,4,2]}) ##...
<python><pandas><dataframe>
2023-03-26 19:38:41
1
765
chuky pedro
75,850,111
10,306,927
SettingWithCopyWarning in Pandas 1.5.3 not working
<p>I'm aware there are a few threads about this but I'm having trouble with the actual <code>SettingWithCopyWarning</code> itself so none of them are of any help.</p> <p>I've recently nuked my machine and am in the process of reinstalling Pycharm and all the libraries etc. On running some of my scripts I keep getting a...
<python><pandas><warnings><pandas-settingwithcopy-warning>
2023-03-26 19:38:14
1
615
top bantz
75,850,086
19,838,568
TensorFlow results are not reproducible despite using tf.random.set_seed
<p>According to a tutorial on Tensorflow I am following, the following code is supposed to give reproducible results, so one can check if the exercise is done correctly. Tensorflow version is 2.11.0.</p> <pre><code>import tensorflow as tf import numpy as np class MyDenseLayer(tf.keras.layers.Layer): def __init__(s...
<python><tensorflow><keras><tf.keras>
2023-03-26 19:33:23
1
2,406
treuss
75,850,073
14,462,728
Python Enum AttributeError: module 'enum' has no attribute 'StrEnum'
<p>I am working on Windows 11, using Python 3.11; I'm working on the following code snippet, which comes from from the Python docs on <a href="https://docs.python.org/3/library/enum.html#enum.StrEnum" rel="noreferrer">enum.StrEnum</a></p> <pre class="lang-py prettyprint-override"><code>import enum from enum import StrE...
<python><class><enums>
2023-03-26 19:30:07
1
454
Seraph
75,850,041
3,672,883
Same requests with requests and with scrapy.Requests return diferent results related with headers
<p>I have the following code to call an API in the scrape</p> <pre><code>def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) response = requests.get(self.page) cookies = response.cookies.get_dict() self.instance_token = cookies[&quot;instance_token&quot;] def start_requests(self): ...
<python><scrapy>
2023-03-26 19:23:43
0
5,342
Tlaloc-ES
75,849,926
1,080,517
Import module selectively in python
<p>I'm working on a script where in debug/development mode I'd like to import <code>typing</code> package, but I don't want to have it in production one.</p> <p>The reason I want to do it is because with this package I can use static code analyzers like mypy, while at the same time <code>typing</code> package as I foun...
<python>
2023-03-26 19:02:58
0
2,713
sebap123
75,849,832
673,600
Saving a .CSV file to Google sheets from colab
<p>I am reading from a Google sheets file in Colab, but I'd like to dump a pandas dataframe in its entirety to the colab. I've seen code snippets that deal with ranges, but I'd like some better way to &quot;import&quot; the entire CSV. Does anyone have the code for that?</p> <pre><code>from google.colab import auth aut...
<python><pandas><google-colaboratory>
2023-03-26 18:46:30
2
6,026
disruptive
75,849,749
3,925,758
How to design a Python class that inherits from a type determined at instantiation?
<p>I'm trying to design a Python class called <code>Try</code>, which takes one or more <code>Option[T]</code> types as constructor arguments. <code>Try</code> should inherit all of its attributes and functions from the first non-<code>None</code> value among its arguments, which can be of any type. For illustration, l...
<python><autocomplete><option-type><python-typing>
2023-03-26 18:27:05
0
1,047
dsillman2000
75,849,578
8,571,243
How to you pickle with evolving class objects
<p>I'm making a python software that need to save complex (nested) dataclasses to disk. I've been using <code>pickle</code> which is working fine until I need to modify the class as i'm developing it. Then, I cannot load the pickle as I get an <code>AttributeError</code>. I understand that <code>pickle</code> requires ...
<python><serialization><pickle><python-dataclasses>
2023-03-26 17:59:35
2
1,085
will.mendil
75,849,130
1,102,514
Sympy parsed expression is not evaluating correctly
<p>I'm following the <a href="https://docs.sympy.org/latest/modules/logic.html" rel="nofollow noreferrer">Sympy logical expression documentation</a>, and have tested the following example, which seems to work well.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; (x | y).subs({x: True, y: False}) True <...
<python><expression><sympy>
2023-03-26 16:39:44
0
1,401
Scratcha
75,849,100
11,419,494
An elegant solution for handling Custom Augmentation Layer's batch_size being None during init?
<p>I'm doing a scientific ML project and wrote a custom layer extending from <code>base_layer.BaseRandomLayer</code>. In this layer, I generate some noise data based on physics (wind wave noises), which will be added to the input data. Since I need to generate <code>batch_size</code> number of noise data, the logic mak...
<python><tensorflow><keras>
2023-03-26 16:34:33
0
316
jshji
75,849,046
10,938,315
Mock os.makedirs within class using fixtures
<p>How do I test <code>os.makedirs</code> which sits within a class that I instantiate in a fixture?</p> <p><code>get_images.py</code></p> <pre><code>class Images: def __init__(self, username: str) -&gt; None: self.output_location = os.path.join( r&quot;C:\Users&quot;, self.username, r&quot;Pict...
<python><unit-testing><mocking>
2023-03-26 16:25:15
0
881
Omega
75,848,908
10,161,315
I am trying to apply Lambda Function on a Single Pandas dataframe Column to encode data and combine several values
<p>I have some data on which I am doing feature engineering. I am trying to encode the categorical features but am not doing it successfully. It is only giving me one value, vs 2. I can't see what is wrong with my code and have tried many different ways in Pandas.</p> <p>I am trying to take the feature LotShape and t...
<python><pandas><lambda><encoding>
2023-03-26 16:04:53
2
323
Jennifer Crosby
75,848,736
274,579
How to "un-readline()" a line from a file?
<p>Is there a way to &quot;un-readline&quot; a line of text from a file opened with <code>open()</code>?</p> <pre><code>#!/bin/env python fp = open(&quot;temp.txt&quot;, &quot;r&quot;) # Read a line linein = fp.readline() print(linein) # What I am looking for comes here linein = fp.unreadline() # Read the same line...
<python><python-3.x>
2023-03-26 15:33:04
1
8,231
ysap
75,848,644
1,788,656
metpy get_layer returns only the the first three values
<p>All, The MetPy get_layer function returns only the first 3 pressure values from the following pressure array (is that is correct?)</p> <pre><code>import numpy as np from metpy.calc import get_layer plev = np.array(( 1000.,950.,900.,850.,800.,750.,700.,650.,600., 550.,500.,450.,400.,350.,300.,250.,200., ...
<python><python-3.x><metpy>
2023-03-26 15:19:14
1
725
Kernel
75,848,609
1,667,884
Selective tests from command line for Python unittest
<p>My project has some tests that are not intended to run by default, but I'd like to make them runnable through passing something to CLI.</p> <p>When testing Python core modules we can use something like:</p> <pre><code>python -m test -u largefile,network </code></pre> <p>I'd like to have something similar for unittes...
<python><python-unittest>
2023-03-26 15:15:20
1
2,357
Danny Lin
75,848,483
11,887,333
Type hints support for subclass of dict
<p>How can I implement a subclass of <code>dict</code> so it supports type hints like vanilla <code>dict</code>?</p> <p>I want to create a custom dict that does some extra work when modifying item, I implement it by subclassing the built-in <code>dict</code> class. After doing some googling I learned that I need to use...
<python><python-typing><mypy>
2023-03-26 14:58:38
1
861
oeter
75,848,328
17,001,641
requests.get().text returns an empty string but the webpage displays correctly in a browser
<p>Here is my simple code snippet about Scrapy from <a href="https://club.jd.com/comment/productPageComments.action?productId=100002967883&amp;score=0&amp;sortType=5&amp;page=72&amp;pageSize=10&amp;isShadowSku=0&amp;rid=0&amp;fold=1" rel="nofollow noreferrer">jd-comment</a>.</p> <pre class="lang-py prettyprint-override...
<python><https><python-requests>
2023-03-26 14:33:22
0
353
yaoyhu
75,848,302
5,695,057
Mocking in Python for Unit tests seems not working
<p>I am writing a unit test in Python for the first time.</p> <p>I want to write a unit test for my service function. The structure of the file <code>service.py</code> is:</p> <pre class="lang-py prettyprint-override"><code>class A function A1 function A2 class B function B1 function B2 </code></pre> <p>I want ...
<python><unit-testing><mocking>
2023-03-26 14:27:59
0
347
Moshiur Rahman
75,848,238
9,749,124
How to get text from PDF file with AWS Textract
<p>I have pdf url:</p> <pre><code>pdf_url = &quot;https://www.buelach.ch/fileadmin/files/documents/Finanzen/Bericht_zum_Budget_2023.pdf&quot; </code></pre> <p>I want to extract text from that file. Important thing is that I do not want to save it on my computer or on S3, I want to do it directly from link.</p> <p>My fu...
<python><amazon-web-services><amazon-textract>
2023-03-26 14:01:28
1
3,923
taga
75,848,148
12,361,700
Iterating over a symbolic `tf.Tensor` is not allowed: AutoGraph did convert this function
<p>I'm really not getting why tf keep on throwing this error:</p> <blockquote> <p>File &quot;/var/folders/6f/83fhb735331g631bmd84c_xc0000gn/T/ipykernel_95896/2907429081.py&quot;, line 35, in call<br /> for _ in tf.range(10):<br /> Iterating over a symbolic <code>tf.Tensor</code> is not allowed: AutoGraph did convert th...
<python><tensorflow>
2023-03-26 13:46:24
0
13,109
Alberto
75,848,129
436,559
How to apply rate limit based on method parameter
<p>I'm using the python module <code>ratelimit</code> to throttle a function, which calls a rest api, I need to apply throttle based on the method of the requests, e.g. for <code>PUT/POST/DELETE</code> 1 per 10s, for <code>GET</code> 5 per 1s, how can I achieve this without breaking the function into two?</p> <pre><cod...
<python><python-3.x><python-decorators><throttling><rate-limiting>
2023-03-26 13:44:52
3
13,996
fluter
75,848,114
5,387,770
Error in defining pyspark datastructure variables with a for loop
<p>I would like to define a set of pyspark features as a run time variables (features). I tried the below, it throws an error. Could you please help on this</p> <pre><code>colNames = ['colA', 'colB', 'colC', 'colD', 'colE'] tsfresh_feature_set = StructType( [ StructField('field1', StringType(),...
<python><apache-spark><pyspark>
2023-03-26 13:40:59
1
625
Arun
75,847,922
6,077,239
How to do if and else in Polars group_by context
<p>For a dataframe, the goal is to have the mean of a column - <code>a</code> group_by another column - <code>b</code> given the first value of <code>a</code> in the group is not null, if it is, just return null.</p> <p>The sample dataframe</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({&quot;a&...
<python><dataframe><python-polars>
2023-03-26 13:04:30
1
1,153
lebesgue
75,847,875
11,462,274
TimeoutError thrown despite successful execution of WebApp GAS within defined request timeout value
<p>I've implemented a web app script that performs various actions, including making changes to a Google Sheet, which typically takes slightly more than 60 seconds.</p> <p>However, despite setting <code>timeout=360</code> or <code>timeout=None</code>, I sometimes encounter a <code>TimeoutError</code> in less than 30 se...
<python><google-apps-script>
2023-03-26 12:53:44
1
2,222
Digital Farmer
75,847,820
12,210,377
How To Map Two Columns from One Dataset with One Column from Another Dataset?
<p>I have two datasets:</p> <pre><code>df1 = pd.DataFrame({'id1': 'AAA ABC ACD ADE AEE AFG'.split(), 'id2': 'BBB BBC BCD BDE BEE BFG'.split(),}) print(df1) id1 id2 0 AAA BBB 1 ABC BBC 2 ACD BCD 3 ADE BDE 4 AEE BEE 5 AFG BFG ----------- df2 = pd.DataFrame({'student_id': 'ABC BBB AA...
<python><pandas><dataframe>
2023-03-26 12:44:17
1
1,084
Roy
75,847,569
3,672,883
Scrapy pipeline doesn't runs
<p>I have the following spider:</p> <pre><code>class WebSpider(scrapy.Spider): name = &quot;web&quot; allowed_domains = [&quot;www.web.com&quot;] start_urls = [&quot;https://www.web.com/page/&quot;] custom_settings = { &quot;ITEM_PIPELINES&quot;: { &quot;models.pipelines.ModelsPipeli...
<python><scrapy>
2023-03-26 11:53:18
1
5,342
Tlaloc-ES
75,847,374
1,291,544
Using memory sanitizer (asan) on C/C++ library loaded to python with ctypes
<p>I have C++ library compiled with <a href="https://github.com/google/sanitizers/wiki/AddressSanitizer" rel="nofollow noreferrer">AddressSanitizer(asan)</a> using <code>g++</code> and <code>cmake</code>:</p> <pre><code>SET( AXULIARY_COMPILE_FLAGS &quot;-g -Og -fsanitize=address -fno-omit-frame-pointer&quot;) </code></...
<python><gcc><ctypes><address-sanitizer><ubuntu-22.04>
2023-03-26 11:14:25
1
2,474
Prokop Hapala
75,847,178
386,861
How to list the values of a dataframe based on value
<p>I've got some product data that I'm trying to analyse but returning the product and year where it reached a certain threshold. It looks a bit like this:</p> <pre><code> Product 2006.0 2007.0 2008.0 2009.0 2010.0 2011.0 0 A 10.0 12.0 13.0 15.0 18.0 23.0 1 B 30.0 2...
<python><pandas>
2023-03-26 10:31:59
2
7,882
elksie5000
75,847,159
13,454,049
Merge Sort comparison measurements close to worst case
<p>Could someone explain why my measurements are not close to the average (0.74 * n * log2(n)), but are closer to the worst case (roughly 0.91 * n * log2(n))?</p> <p>This is what I already tried:</p> <ul> <li>Using log instead of log2 (This resulted in more comparisons than the worst case)</li> <li>Using a random seed<...
<python><mergesort>
2023-03-26 10:28:15
1
1,205
Nice Zombies
75,847,136
1,747,743
Cannot run Great Expectations quickstart
<p>I am trying to use Great Expectations (Python data quality framework). I ran the quickstart after installing GX on WSL2 and Python 3.9.16</p> <p>The quickstart code can be found here: <a href="https://docs.greatexpectations.io/docs/tutorials/quickstart/" rel="nofollow noreferrer">https://docs.greatexpectations.io/do...
<python><great-expectations>
2023-03-26 10:22:35
2
657
Łukasz Kastelik
75,847,074
10,696,946
Obtain the generation number in the eval_genome function in neat-python
<p>I am using the <a href="https://neat-python.readthedocs.io/en/latest/neat_overview.html" rel="nofollow noreferrer">neat-python</a> library to tinker around with neural networks. But the specific example I am trying to do requires the following:</p> <pre class="lang-py prettyprint-override"><code> def eval_genome(gen...
<python><neat>
2023-03-26 10:09:42
0
2,387
Ank i zle
75,846,925
6,640,504
How to use Pandas_UDF function in Pyspark program
<p>I have a Pyspark dataframe with million records. It has a column with string persian date and need to convert it to miladi date.I tried several approuches, first I used UDF function in Python which did not have good performance. Then I wrote UDF function in Scala and used its Jar in Pyspark program; but performace d...
<python><pyspark>
2023-03-26 09:39:21
1
1,172
M_Gh
75,846,886
15,098,472
Pythonic way to assign 1 to indices in an 2D array
<p>What I have:</p> <pre><code>indexes = np.array([[4], [3], [2], [1]]) </code></pre> <p>What I want:</p> <pre><code>output = [[0, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0]] </code></pre> <p>So, instead of having a specific number in each index of the input, I want an array with the length of the m...
<python><numpy><indexing>
2023-03-26 09:29:18
2
574
kklaw
75,846,864
10,313,194
Django cannot compare string
<p>I get data from 2 table by search key_id in Data table and find key_name in Key table like this.</p> <pre><code> data=Data.objects.filter(username=username) key=Key.objects.filter(key_id__in=data.values_list('key_id')) data = {'data':data, 'key':key} return render(request,'form.html', data) </code></...
<python><django>
2023-03-26 09:23:57
1
639
user58519
75,846,852
18,948,596
How can I change my color scheme for highlighting markdown text in rich (python)
<p>I am using the <a href="https://rich.readthedocs.io/en/stable/index.html" rel="noreferrer">rich</a> module to enable markdown support in the terminal. However, I am using a light-themed terminal and the default colors of rich markdown highlighting look borderline unreadable. So how would I go about changing the colo...
<python><markdown><color-scheme><rich>
2023-03-26 09:20:55
1
413
Racid
75,846,775
324,827
Embedded Python (3.10) - Py_FinalizeEx hangs/deadlock on "threading._shutdown()"
<p>I am embedding Python in a C++ application, and I think I have some confusion with <code>PyGILState_Ensure/PyGILState_Release</code> which leads eventually to <code>Py_FinalizeEx</code> to hang in <code>threading._shutdown()</code> (called by <code>Py_FinalizeEx</code>) while <code>join()</code>-ing the threads.</p>...
<python><c++><cpython><python-3.10>
2023-03-26 08:59:19
1
5,970
TCS
75,846,681
1,903,387
Locust - Authentication with GCP Metadata Server
<p>Trying to write a simple load test with locust.</p> <p>I just a have a single api which calls an endpoint get some data. The endpoint requires some credentials, lets say Http Basic auth.</p> <p>I'm running this program in a GCP VM or GKE machine with the pods/machine has required permissions to access GCP Secret Man...
<python><locust>
2023-03-26 08:36:44
2
301
Rahul
75,846,668
9,729,023
AWS Lambda : Python Globals() get KeyError
<p>Even though the expression of 'clazz = globals()[table]' is running without any error on production, but it's getting KeyError at my lambda with same code. This error happens in both case of passing table name by Lambda Test Event and by Transformer in EventBridge.</p> <p>May I ask why KeyError could have happened?<...
<python><aws-lambda>
2023-03-26 08:34:30
1
964
Sachiko
75,846,568
6,451,136
Python How to pass continuous generated data stream between methods
<p>I have a method that continuously generates data and prints them on the console. Let's say something simple like generating random number:</p> <pre><code>def number_generator(): while True: random.randint(1,100) time.sleep(0.5) return </code></pre> <p>I have a separate method that is supposed...
<python><kafka-python><data-stream>
2023-03-26 08:07:22
2
345
Varun Pius Rodrigues