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,689,081
12,596,824
using np.exp() to convert column in pandas DF
<p>I have the following dataframe:</p> <pre><code>id val 1 10 1 2012 1 65 </code></pre> <p>i want to convert the val column to create values that add up to 1</p> <pre><code>df['val'] = np.exp(df.val)/sum(np.exp(df.val)) </code></pre> <p>but i get the following</p> <pre><code>id val 1 0.0 1 NaN 1 0.0 </code></pre> <p>how can i take care of this to make probabilities equal to 1 for this case?</p>
<python><pandas>
2023-03-09 19:14:45
0
1,937
Eisen
75,689,070
6,467,567
Indexing on ndarrays result in wrong shape
<p>The following snippet</p> <pre><code>x = np.ones((10,10,10)) x = x[2,:,[2,3,7]] print(x.shape) </code></pre> <p>results in <code>x.shape = (3,10)</code> instead of <code>(10,3)</code>. How do I use a list to index the 3rd dimension to get a shape <code>(10,3)</code>?</p>
<python><numpy>
2023-03-09 19:12:58
2
2,438
Kong
75,689,061
4,796,942
Using package to perform a rolling window function with a group by
<p>Could you use a window function on groups, something in <a href="https://readthedocs.org/projects/feature-engine/downloads/pdf/latest/" rel="nofollow noreferrer">feature engine</a>? I have been reading the <a href="https://readthedocs.org/projects/feature-engine/downloads/pdf/latest/" rel="nofollow noreferrer">docs</a> and trying to find some clarity on how to do this but it seems like something that should exist but I can't seem to find how its implemented.</p> <pre><code>import pandas as pd # create a sample dataframe with groups df = pd.DataFrame({'group': ['A', 'A','A', 'B', 'B', 'B','B', 'C', 'C', 'C','C'], 'value': [1, 2, 3, 4, 5, 6, 7, 8,9,10,11]}) # group the data by the 'group' column and apply a rolling window mean of size 2 rolling_mean = df.groupby('group')['value'].rolling(window=2).mean() print(rolling_mean) </code></pre> <p>I am guessing it would look something like this.</p> <pre><code>from feature_engine.timeseries.forecasting import WindowFeatures wf = WindowFeatures( window_size=3, variables=[&quot;value&quot;], operation=[&quot;mean&quot;], groupby_cols=[&quot;group&quot;] ) transformed_df = wf.fit_transform(df) </code></pre> <p>I can't seem to find a group_by (groupby_cols) parameter in feature-engine?</p> <p>It would be great to see other ways of standardising feature engineering for time series data like this, perhaps from sktime or any other framework too.</p>
<python><pandas><group-by><feature-engineering><sktime>
2023-03-09 19:11:03
1
1,587
user4933
75,689,011
2,828,064
Why does coverage.py not report a for loop where the body is not skipped when running it with --branch?
<p>Consider the following example file <code>test.py</code>:</p> <pre class="lang-py prettyprint-override"><code>def fun(l): for i in l: a = 1 print(a) if __name__ == '__main__': fun([1]) </code></pre> <p>Testing branch coverage with</p> <pre class="lang-bash prettyprint-override"><code>coverage erase; coverage run --branch test.py ; coverage html </code></pre> <p>There are no complains about the for loop although it is not tested with an empty list. If it was the program would crash with &quot;UnboundLocalError: local variable 'a' referenced before assignment&quot;. Since I have asked <a href="https://coverage.readthedocs.io/en/7.2.1/" rel="nofollow noreferrer">coverage</a> for branch coverage instead of statement coverage I would expect this to be reported. Why does coverage not report this?</p> <p><a href="https://i.sstatic.net/kIWXI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kIWXI.png" alt="screenshot of HTML report created by coverage" /></a></p>
<python><code-coverage><coverage.py>
2023-03-09 19:05:18
1
674
jakun
75,689,005
1,744,194
Celery Groups: How to create a group of already running tasks?
<p>I have a set of long running tasks I need to coordinate in group. The challenge is the tasks must be fired as soon as they can be created, not after all tasks are defined (as shown below).</p> <p>The problem is <code>group(...)</code> does not accept <code>AsyncTask</code> and calling <code>apply_async</code> on the task results in every task running twice.</p> <pre><code>import time from celery import group, chain, chord, subtask # Run it pipeline = rate_limited_task.s(end_task.s()) job_id_to_track = pipeline.apply_async() # TASKS @app.task(bind=true) def rate_limited_task(self, downstream_task): tasks = [] for random_number in np.random.randint(1, 10, 1000): # ... imagine it takes several seconds to generate a random number. This will loop many times task = parallel_tasks.si(random_number) # This needs to fire immediately tasks.append(task) pipeline = group(tasks) | downstream_task return pipeline() @app.task(bind=true) def parallel_tasks(self, data): # Another long running task print(f'sleeping for {data} seconds') time.sleep(data) return data @app.task(bind=true) def end_task(self, results): print('End task') print(results) </code></pre> <p>Question: Is it possible to create a group of tasks that are already running (or in any state)?</p> <hr /> <p>Current solution (not ideal)</p> <pre><code>from celery.result import allow_join_result, GroupResult @app.task(bind=true) def rate_limited_task(self, downstream_task): tasks = [] for random_number in np.random.randint(1, 10, 1000): # ... imagine it takes several seconds to generate a random number. This will loop many times task = parelel_tasks.apply_async([random_number]) tasks.append(task) gid = uuid() result_set = GroupResult(id=gid, results=tasks) result_set.save(backend=self.backend) chain( group_tasks.s(gid), downstream_task )() ... @app.task(bind=true) def group_tasks(self, group_task_id): group_task = GroupResult.restore(group_task_id, app=app, backend=self.backend) # Less than ideal solution. # Needs logic to handle any failed tasks (solved in the group class) # Tasks should have an expiration time so that they are not retried forever if not group_task.ready(): raise self.retry(countdown=1) with allow_join_result(): results = group_task.join() return results </code></pre>
<python><asynchronous><celery><scheduling><group>
2023-03-09 19:04:34
1
827
X_Trust
75,688,943
18,806,499
My POST method can't receive data (flask api)
<p>I'm working on my flask app. I've successfully implemented the rest APIs and now I want to add views to my app. Here is post method:</p> <pre><code>from flask_restful import Resource from flask import abort, request from flask_apispec import marshal_with, use_kwargs from flask_apispec.views import MethodResource from marshmallow import Schema, fields from app import api, docs, db from app.models import Order class OrderSchema(Schema): waiter_name = fields.String() table = fields.Integer() orders_date = fields.String() status_value = fields.String() class PostOrderSchema(Schema): waiter = fields.Integer() table = fields.Integer() orders_date = fields.String() class GetOrders(MethodResource, Resource): @marshal_with(OrderSchema(many=True)) def get(self): &quot;&quot;&quot; Method which can be used to get all orders Expects: nothing Modifies: nothing Returns: orders &quot;&quot;&quot; waiters = get_orders(request.args) return waiters @use_kwargs(PostOrderSchema, location='json') @marshal_with(OrderSchema) def post(self, **kwargs): &quot;&quot;&quot; Method which can be used to add new orders to the database Expects: nothing Modifies: nothing Returns: created order &quot;&quot;&quot; # args = order_put_args.parse_args() order = add_to_db(Order, **kwargs) return order api.add_resource(GetOrder, '/json_orders/&lt;int:id&gt;') api.add_resource(GetOrders, '/json_orders') docs.register(GetOrder) docs.register(GetOrders) </code></pre> <p>Here is my views:</p> <pre><code>import requests from flask import render_template, redirect, url_for from flask.views import MethodView from app import app, db from app.views.form import AddEditOrderForm from app.models import Waiter, Status BASE = 'http://127.0.0.1:5000/' # Add Views class ControlOrderView(MethodView): def get(self): return render_template('add_edit_forms/add-edit_order.html', **self.prepare_context()) def post(self): form = AddEditOrderForm() if form.validate_on_submit(): requests.post(BASE + 'json_orders', data={ 'waiter': 1, # form.waiter.data.split()[0], 'orders_date': &quot;2023-01-02&quot;, # form.orders_date.data, # 'status': '1', form.status.data.split()[0], 'table': '3' # form.table.data }) return redirect(url_for('get_all_orders')) def prepare_context(self): form = AddEditOrderForm() waiters = Waiter.query.all() form.waiter.choices = list( f'{waiter.first_name} {waiter.last_name}' for waiter in waiters ) statuses = Status.query.all() form.status.choices = list( f'{status.id} - {status.status}' for status in statuses ) title = 'ADD ORDER' submit_url = '/add-order' cancel_button = 'get_all_orders' return { 'title': title, 'form': form, 'submit_url': submit_url, 'cancel_button': cancel_button } app.add_url_rule('/add-order', view_func=ControlOrderView.as_view('add_order'), methods=['GET', 'POST']) </code></pre> <p>With GET request everything is fine, But POST request gives such errors:</p> <pre><code>sqlalchemy.exc.OperationalError: (MySQLdb.OperationalError) (1048, &quot;Column 'waiter' cannot be null&quot;) [SQL: INSERT INTO orders (waiter, `table`) VALUES (%s, %s)] [parameters: (None, None)] </code></pre> <p>It seems the API can't receive the data. I was trying to debug it and found out that <code>**kwargs</code> is an empty dictionary</p> <p>UPDATE</p> <p>Here is implementation of <code>add_to_db</code> function:</p> <pre><code>def add_to_db(cls, **kwargs): obj = cls() for atr, value in kwargs.items(): setattr(obj, atr, value) db.session.add(obj) db.session.commit() return obj </code></pre>
<python><flask>
2023-03-09 18:57:55
1
305
Diana
75,688,938
10,093,190
How to compare two files byte per byte, but also account for missing bytes?
<p>I have two files containing random bytes. An original, and one that was sent back and forth to a remote target.</p> <p>I need to check if both files are identical. Let's take this table as an example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Byte #</th> <th>File1</th> <th>File2</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>01</td> <td>01</td> </tr> <tr> <td>2</td> <td>05</td> <td>05</td> </tr> <tr> <td>4</td> <td>08</td> <td>08</td> </tr> <tr> <td>5</td> <td>0D</td> <td>0D</td> </tr> <tr> <td>6</td> <td>FF</td> <td>1A</td> </tr> <tr> <td>7</td> <td>AA</td> <td>AA</td> </tr> </tbody> </table> </div> <p>Byte 6 is not the same, so it should detect this. So far, not very difficult. Just loop over all bytes (or in my case: chunks) and check if they are the same.</p> <p>However, I also need to be able to detect if a byte went missing!</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Byte #</th> <th>File1</th> <th>File2</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>01</td> <td>01</td> </tr> <tr> <td>2</td> <td>05</td> <td>08</td> </tr> <tr> <td>4</td> <td>08</td> <td>0D</td> </tr> <tr> <td>5</td> <td>0D</td> <td>FF</td> </tr> <tr> <td>6</td> <td>FF</td> <td>AA</td> </tr> <tr> <td>7</td> <td>AA</td> <td>BC</td> </tr> </tbody> </table> </div> <p>We now should NOT report bytes 2 to 7 incorrect, but only report byte 2 as missing. So our checking algorithm should record this &quot;offset&quot; and continue using it for all following bytes. However, I can't really imagine how this would be done if 1) we read the files in chunks; 2) if there can be thousands of bytes missing in a row.</p> <p>Also note that the files can be several GB's big. So the algorithm needs to be somewhat efficient.</p> <p>I wonder if there's a good method for this? Google has let me down unfortunately.</p>
<python>
2023-03-09 18:57:18
0
501
Opifex
75,688,738
817,659
requests doesn't seem to connect and return data from a service but browser does
<p>Both the <code>service</code> and the <code>program</code> are running under <code>Ubuntu</code>.</p> <p>I have an application that calls a <code>service</code> that returns a <code>json pandas dataframe</code>. The service prints out the data to the screen before serving the data.</p> <p>I have tested the service using a browser, and it works great - I see the <code>jsonified</code> data in the browser. However, if I try to call the <code>service</code> using <code>requests</code> from a <code>python</code> program, it goes into a black hole and nothing ever comes back. I am not sure what I am doing wrong?</p> <pre><code>def get_RRDf(ticker, date_years_ago, wind): print(&quot;Entering get_rrDf&quot;) build_params = &quot;thresh=.20&amp;symbol=&quot; + ticker +&quot;&amp;window=&quot; + str(wind) + &quot;&amp;lookback=5&quot; api_url = &quot;http://xx.xx.xx.xx:3000/RR/&quot;+build_params print(api_url) app_headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0' } response = requests.get(api_url, headers=app_headers) print(&quot;==================&quot;) print(type(response)) print(response.text) print(&quot;==================&quot;) ... </code></pre>
<python><python-requests>
2023-03-09 18:35:33
0
7,836
Ivan
75,688,651
12,981,397
Compare dictionaries to check if they are equal or if they go from empty to having a value
<p>I have two dataframes where I am looping through each row and creating a dictionary for the rows that I am looking at to compare against each other.</p> <p>I've done this by doing:</p> <pre><code>ids = [] for row in range(len(df1)-1): df1_row = dict(df1.iloc[row]) df2_row = dict(df2.iloc[row]) if df1_row == df2_row: ids.append(df1_row['ID']) </code></pre> <p>I am checking whether the two rows I am comparing at a time are equal and if they are I am appending the id from that row to a list to return at the end.</p> <p>However I would also like to check the condition where if the row from df2 contains an empty string for a given key and the row from df1 contains a value for that same key, but the rest of the key-value pairs are equal between them, then I want to append that id to the list as well.</p> <p>For example if I am looking at two rows like this</p> <pre><code>df1_row = {'NAME': 'Kelly', 'AGE': '15', 'CITY': 'London', 'GENDER': 'F', 'ID': 15} df2_row = {'NAME': 'Kelly', 'AGE': '15', 'CITY': '', 'GENDER': 'F', 'ID': '15'} </code></pre> <p>Then I would like to append ID 15 to my list since CITY goes from EMPTY in df2_row to having a value in df1_row.</p> <p>If the pair looked like this</p> <pre><code>df1_row = {'NAME': 'Kelly', 'AGE': '15', 'CITY': 'London', 'GENDER':'' 'ID': 15} df2_row = {'NAME': 'Kelly', 'AGE': '15', 'CITY': '', 'GENDER': 'F', 'ID': '15'} </code></pre> <p>I would not want to append id 15 to my resulting list since even though though CITY goes from EMPTY to having a value from df2_row to df1_row, GENDER goes form having a value to EMPTY from df2 to df1.</p> <p>(Basically my checks are: the rows are exactly equal OR they have values that go from empty to non-empty (from df2 to df1) and the rest of the values are equal)</p> <p>I tried doing</p> <pre><code>ids = [] for row in range(len(df1)-1): df1_row = dict(df1.iloc[row]) df2_row = dict(df2.iloc[row]) if df1_row == df2_row: ids.append(df1_row['ID']) else: for key in df1_row: if df1_row[key] == df2_row[key] or (df2_row[key] == '' and df1_row[key] != ''): </code></pre> <p>But I am not sure how to write the second condition so that it only appends the id after the whole row has been checked, rather than just check the condition on the current key-value and append the id right there...is there a way to check this condition for the entire row at once/another way to write this? Thanks! (or maybe there is just a better way to compare two rows in a dataframe for the same id against each other using these conditions without having to turn the rows into dictionaries to compare?)</p> <p>TEST TABLES</p> <p>DF1:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>NAME</th> <th>AGE</th> <th>CITY</th> <th>GENDER</th> <th>ID</th> </tr> </thead> <tbody> <tr> <td>Kelly</td> <td>15</td> <td>London</td> <td>F</td> <td>15</td> </tr> <tr> <td>Jack</td> <td>12</td> <td></td> <td>M</td> <td>98</td> </tr> <tr> <td>Josh</td> <td>30</td> <td>Austin</td> <td>M</td> <td>12</td> </tr> </tbody> </table> </div> <p>DF2:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>NAME</th> <th>AGE</th> <th>CITY</th> <th>GENDER</th> <th>ID</th> </tr> </thead> <tbody> <tr> <td>Kelly</td> <td>15</td> <td></td> <td>F</td> <td>15</td> </tr> <tr> <td>Jack</td> <td></td> <td>Munich</td> <td>M</td> <td>98</td> </tr> <tr> <td>Josh</td> <td>30</td> <td>Austin</td> <td>M</td> <td>12</td> </tr> </tbody> </table> </div> <p>I would want to get back IDs 15 and 12 because 12 matches exactly, and in 15 it matches exactly or it has a column value in df2 that goes to non empty in df1.</p>
<python><pandas><dataframe><dictionary><comparison>
2023-03-09 18:26:02
1
333
Angie
75,688,480
8,713,442
Create group having Percentage diff <=30%
<p>I am calculating % difference among all values and then creating group . As an output I am getting combinations of 2 values but I want combine all values in one group which are less than 30% of each other.</p> <p>Working code is given below</p> <pre><code> from itertools import combinations def pctDiff(A,B): return abs(A-B)*200/(A+B) def main(): dict2={} dict ={'acct_number':10202,'acct_name':'abc','v1_rev':3000,'v2_rev':4444,'v4_rev':234534,'v5_rev':5665,'v6_rev':66,'v7_rev':66,'v3_rev':66} vendors_revenue_list =['v1_rev','v2_rev','v3_rev','v4_rev','v5_rev','v6_rev','v7_rev','v8_rev'] #prepared list of vendors for k in vendors_revenue_list: if k in dict.keys(): dict2.update({k: dict[k]}) print(dict2) #provides all possible combination for a, b in combinations(dict2, 2): groups = [(a,b) for a,b in combinations(dict2,2) if pctDiff(dict2[a],dict2[b]) &lt;= 30] print(groups) </code></pre> <p>output</p> <pre><code>[('v2_rev', 'v5_rev'), ('v3_rev', 'v6_rev'), ('v3_rev', 'v7_rev'), ('v6_rev', 'v7_rev')] </code></pre> <p>Desired output should be</p> <pre><code>[('v2_rev', 'v5_rev'), ('v3_rev', 'v6_rev','v7_rev')] </code></pre> <p><a href="https://i.sstatic.net/UBSZU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UBSZU.png" alt="enter image description here" /></a></p>
<python><python-3.x><data-science>
2023-03-09 18:07:25
5
464
pbh
75,688,389
1,711,271
Fast way to select all the elements of a list of strings, which contain at least a substring from another list
<p>I have a list of strings like this:</p> <pre><code>samples = ['2345_234_1.0_1.35_001', '0345_123_2.09_1.3_003', ...] </code></pre> <p>The list can be quite long (up to 10^6 elements in the worst case). I have another list containing some substrings:</p> <pre><code>matches = ['7895_001', '3458_669', '0345_123', ...] </code></pre> <p>I would like to create a list <code>matched_samples</code> which contains only the elements of <code>samples</code> which contain one or more element of <code>matches</code>. For example, <code>samples[1]</code> ends up in <code>matched_samples</code> because <code>matches[3]</code> is a substring of <code>samples[1]</code>. I could do something like this:</p> <pre><code>matched_samples = [s for s in samples if any(xs in s for xs in matches)] </code></pre> <p>However, this looks like a double for loop, so it's not going to be fast. Is there any alternative? If <code>samples</code> was a <code>pandas</code> dataframe, I could simply do:</p> <pre><code>matches_regex = '|'.join(matches) matched_samples = samples[samples['sample'].str.contains(matches_regex)] </code></pre> <p>Is there a similarly fast alternative with lists?</p>
<python><pandas><regex><list><list-comprehension>
2023-03-09 17:58:12
2
5,726
DeltaIV
75,688,321
16,414,611
Unable to get data from Scrapy API
<p>I'm facing some unexpected issues while trying to get data from an API request. I found that it is throwing a &quot;500&quot; error and also this error message. I'm trying to scrape this URL &quot;https://www.machinerytrader.com/listings/for-sale/excavators/1031&quot; but I have no idea what I actually missing here.</p> <pre><code>raise JSONDecodeError(&quot;Expecting value&quot;, s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2) </code></pre> <p>This is what I tried so far,</p> <pre><code>import scrapy import json class ListingSpider(scrapy.Spider): name = 'listing' allowed_domains = ['www.machinerytrader.com'] # start_urls = ['https://www.machinerytrader.com/listings/for-sale/excavators/1031'] def start_requests(self): payload = { &quot;Category&quot;:&quot;1031&quot;, &quot;sort&quot;: &quot;1&quot;, &quot;page&quot;:&quot;2&quot; } headers= { &quot;User-Agent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36&quot;, &quot;authority&quot;: &quot;www.machinerytrader.com&quot;, &quot;method&quot;: &quot;GET&quot;, &quot;path&quot;: &quot;/ajax/listings/ajaxsearch?Category=1031&amp;sort=1&amp;page=2&quot;, &quot;scheme&quot;: &quot;https&quot;, &quot;accept&quot;: &quot;application/json, text/plain, */*&quot;, &quot;accept-encoding&quot;: &quot;gzip, deflate, br&quot;, &quot;cache-control&quot;: &quot;no-cache&quot;, &quot;content-type&quot;: &quot;application/json&quot;, &quot;cookie&quot;: &quot;ASP.NET_SessionId=uircx3p1up0gs3we43zfy3xp; Tracking=SessionStarted=1&amp;UserReferrer=&amp;GUID=75541984850425423381; __RequestVerificationToken=CqqhcuoUxcCh_VvGb2QkZPTMG1sygAxcDjWmGutWxYGvIScO7I1rCwBZabShMlyTl9syCA2; BIGipServerwww.machinery_tradesites_http_pool=545368256.20480.0000; ln_or=eyI0MjU0ODkyIjoiZCJ9; AMP_TOKEN=%24NOT_FOUND; _gid=GA1.2.104780578.1678372555; _fbp=fb.1.1678372557791.1218325782; _hjFirstSeen=1; _hjIncludedInSessionSample_1143836=1; _hjSession_1143836=eyJpZCI6IjU1ZGYyOGJmLWQ4YjktNGU2Mi04NjU2LWUwYmJkYzdiNGMxMSIsImNyZWF0ZWQiOjE2NzgzNzI1NTgzNDcsImluU2FtcGxlIjp0cnVlfQ==; _hjIncludedInPageviewSample=1; _hjAbsoluteSessionInProgress=1; __gads=ID=2a38a4e969861bb1:T=1678372561:S=ALNI_MarB5bgIDdhzpQPECKDmX-70INeJg; __gpi=UID=00000bd5f25a7b4b:T=1678372561:RT=1678372561:S=ALNI_MapbcTx6haLt65wewjezZyeMFVtCw; _hjSessionUser_1143836=eyJpZCI6IjI3ODM2ZDdhLTc0YzUtNTIwMi05YjdhLWYxMmM5YTk4ZGNmNiIsImNyZWF0ZWQiOjE2NzgzNzI1NTgzMzksImV4aXN0aW5nIjp0cnVlfQ==; __atuvc=2%7C10; __atuvs=6409eecd9390ad6d001; Top_PopUp=true; reese84=3:MhdsyFtuLMcDbPfjHYfnUQ==:Xnyj2+4WPTbNOTnv4Aj99+6mLrSjYnrQVoSGqCJEwqmN/gdPfQuCPFYN1/1sInEQHaUvLNdN2VbgdxeC96k6tr1MUSbHd2GxI4AKb1CxnkZfLm63/CXWNqJ/vlS66hOTSsEn+gxPb2l3g2TD3RGi0H4PjyhskjDIE10USkPi3mm83aG/xkAYL4khuWtRDaYzyHjzQ76f9yRr0tNnEEbUPbxZTW7BPXcEF606e6mzq6v5/YEy17JScccw/CCkXb4Uv1tzeNYhkMuFj5V5upY0a2tC/MiJeCACNCYnX9obZhGsfPbL6VUYdJDEhmyR8OBJsHuH4BwOdjnbr7pFG+o4AZKqDHliWKhUnDxGAHIhKwzhhq5TFjeJbqRwSLrMXH54WxZZHcuvRtwr734U2F3Pmf8NqW+zavYdB/aYrk+HpA9LfQQQFBGd/1FNRAM0e8fxZpj5U/DxTKPMdvwK5qBnfzQaTzycDwe80G7QRYX9kf4=:gQlue37nFKz2zVkiSWGW9vURldmXHHEIxHz2yiUrtF8=; _uetsid=b29154b0be8711edabac07f5e20bba65; _uetvid=b2917380be8711edbb2587449262974a; _ga=GA1.2.1777003444.1678372555; UserID=ID=n2K08gLg7XRct%2fxxJeWEnGDwbYpUh6vQ%2fiE1eBN%2f25lkMV4lKXFpeoTT54DrUsz9CriJRnchYL4PfEPzqxaCRA%3d%3d&amp;LV=sHEWMHROf%2fDobQFZDWX1nWtv%2bf2Uk9i6YA9N5Sk0lGE%2fWiDudiekp7MPDIUnH0jGKMx9VZbhLzD4VuT7pKbqepCdPLaN274I; UserSettingsCookie=screenSize=1246|947; _ga_27QWK2FVDW=GS1.1.1678372557.1.1.1678373273.60.0.0&quot;, &quot;pragma&quot;: &quot;no-cache&quot;, &quot;referer&quot;: &quot;https://www.machinerytrader.com/listings/for-sale/excavators/1031&quot;, &quot;sec-ch-ua-mobile&quot;: &quot;?0&quot;, &quot;sec-ch-ua-platform&quot;: &quot;Windows&quot;, &quot;sec-fetch-dest&quot;: &quot;empty&quot;, &quot;sec-fetch-mode&quot;: &quot;cors&quot;, &quot;sec-fetch-site&quot;: &quot;same-origin&quot;, &quot;x-xsrf-token&quot;: &quot;lKwor8adm67mnDJjariTC1-_x2sWvmjxDtVZerZ6p03OwqvVc10YVZUQMmD4-pTv7E2cTSN-8rsTW6ISckmZVgBek66eHw3iFUngI3jYt6h_rwqQ3pI_QxPjYH1us7eHyW27lxFL_-wSS3QC0&quot;, &quot;sec-ch-ua&quot;: '&quot;Google Chrome&quot;;v=&quot;111&quot;, &quot;Not(A:Brand&quot;;v=&quot;8&quot;, &quot;Chromium&quot;;v=&quot;111&quot;', } yield scrapy.Request( url=&quot;https://www.machinerytrader.com/ajax/listings/ajaxsearch?Category=1031&amp;sort=1&amp;page=2&quot;, method=&quot;GET&quot;, headers=headers, body=json.dumps(payload), callback=self.parse ) def parse(self, response): json_resp = json.loads(response.body) products = json_resp['Listings'] yield { 'DealerLocation': products['DealerLocation'], } </code></pre>
<python><python-3.x><web-scraping><scrapy>
2023-03-09 17:51:21
1
329
Raisul Islam
75,688,238
496,289
pyspark log4j2: How to log full exception stack trace?
<p>I tried</p> <ul> <li><code>logger.error('err', e)</code></li> <li><code>logger.error('err', exc_info=e) # syntax for python's logging</code></li> </ul> <pre><code>&gt;&gt;&gt; &gt;&gt;&gt; logger = spark.sparkContext._jvm.org.apache.log4j.LogManager.getLogger('my-logger') &gt;&gt;&gt; &gt;&gt;&gt; try: 1/0 ... except Exception as e: logger.error('err', e) ... Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt; File &quot;/home/kash/project1/.venv/lib/python3.9/site-packages/pyspark/python/lib/py4j-0.10.9.5-src.zip/py4j/java_gateway.py&quot;, line 1313, in __call__ File &quot;/home/kash/project1/.venv/lib/python3.9/site-packages/pyspark/python/lib/py4j-0.10.9.5-src.zip/py4j/java_gateway.py&quot;, line 1283, in _build_args File &quot;/home/kash/project1/.venv/lib/python3.9/site-packages/pyspark/python/lib/py4j-0.10.9.5-src.zip/py4j/java_gateway.py&quot;, line 1283, in &lt;listcomp&gt; File &quot;/home/kash/project1/.venv/lib/python3.9/site-packages/pyspark/python/lib/py4j-0.10.9.5-src.zip/py4j/protocol.py&quot;, line 298, in get_command_part AttributeError: 'ZeroDivisionError' object has no attribute '_get_object_id' &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; try: 1/0 ... except Exception as e: logger.error('err', exc_info=e) ... Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt; TypeError: __call__() got an unexpected keyword argument 'exc_info' &gt;&gt;&gt; </code></pre> <hr /> <p>of course I can convert the stacktrace myself and pass it as a string to log4j instead of exception object. But don't wanna do all that if I can avoid it.</p> <pre><code>&gt;&gt;&gt; try: 1/0 ... except Exception as e: l.error(f'err {&quot;&quot;.join(traceback.TracebackException.from_exception(e).format())}') ... 23/03/09 11:38:47 ERROR my-logger: err Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ZeroDivisionError: division by zero &gt;&gt;&gt; </code></pre>
<python><exception><logging><pyspark><log4j>
2023-03-09 17:43:13
1
17,945
Kashyap
75,688,222
8,972,915
Polars - Failed to read delta config: Validation failed - Unknown unit 'days'
<p>I am having some delta tables created in my azure data lake using azure databricks. I am trying to follow the below instruction, and to read them using polars.</p> <p><a href="https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.read_delta.html" rel="nofollow noreferrer">https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.read_delta.html</a></p> <p><a href="https://i.sstatic.net/46voJ.png" rel="nofollow noreferrer">image</a> of error executing <code>pl.read delta(table path, storage options-storage_options)</code></p> <p>However, it errors out. Does that mean that the transaction log is structured differently in the databricks implementation of delta?</p> <p>Executing <code>pl.read delta(table path, storage options-storage_options)</code> generates exception:</p> <pre><code>Exception has occurred: PyDeltaTableError X Failed to apply transaction log: Failed to read delta config: Validation failed - Unknown unit 'days File &quot;C:\Users\S1P967\Untitled-1.txt&quot;, line 12, in &lt;module&gt; pl.read_delta(table path, storage_options-storage_options) deltalake.PyDeltaTableError: Failed to apply transaction log: Failed to read delta config: Validation failed - Unknown unit 'days' </code></pre>
<python><azure-databricks><delta-lake><python-polars>
2023-03-09 17:41:26
0
405
Grevioos
75,688,216
719,689
Debugpy won't attach to anything
<p>I've tried everything except what works. Nothing gets my vscode debugger to attach to any breakpoint.</p> <p>Here is my launch.json:</p> <pre><code>{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Python: Docker&quot;, &quot;type&quot;: &quot;python&quot;, &quot;request&quot;: &quot;attach&quot;, &quot;pathMappings&quot;: [ { &quot;localRoot&quot;: &quot;${workspaceFolder}&quot;, &quot;remoteRoot&quot;: &quot;/code&quot; } ], &quot;connect&quot;: { &quot;host&quot;: &quot;localhost&quot;, &quot;port&quot;: 3000 }, &quot;justMyCode&quot;: true, &quot;logToFile&quot;: true } } </code></pre> <p>And here is my docker-compose.yml:</p> <pre><code>services: web: platform: linux/amd64 build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8800:8000 - 3000:3000 </code></pre> <p>And in my manage.py:</p> <pre><code> if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen((&quot;0.0.0.0&quot;, 3000)) # debugpy.wait_for_client() print('debugpy Attached!') </code></pre> <p>My <code>debugpy Attached!</code> is being printed so I know things are set up to be attached to the debugger, but none of my breakpoints work.</p> <p>Also, i'd like to add that i'm testing a Django management command:</p> <p><code>python manage.py myCommand</code></p> <p>I'm assuming that no additional configuration is needed if i'm running a command within the container. It will use the server that is running and debugpy should be loaded. I've tried specifying debugpy in the command itself but still nothing:</p> <p><code>python -m debugpy --listen 0.0.0.0:3000 manage.py myCommand</code></p>
<python><django><vscode-debugger><debugpy>
2023-03-09 17:40:59
1
3,258
AlxVallejo
75,688,185
11,001,493
How to transform row values into column based on specific values from multiple columns?
<p>This is an example of bigger data.</p> <p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({&quot;Year&quot;:[2023, 2023, 2023, 2024, 2024, 2024], &quot;Value&quot;:[0, 2, 3, 1, 5, 2], &quot;Field&quot;:[&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;], &quot;ID&quot;:[&quot;X&quot;, &quot;X&quot;, &quot;X&quot;, &quot;X&quot;, &quot;Z&quot;, &quot;Y&quot;], &quot;Type&quot;:[&quot;class1&quot;,&quot;class2&quot;,&quot;class1&quot;,&quot;class1&quot;,&quot;class1&quot;,&quot;class2&quot;]}) df Out[8]: Year Value Field ID Type 0 2023 0 A X class1 1 2023 2 A X class2 2 2023 3 B X class1 3 2024 1 A X class1 4 2024 5 B Z class1 5 2024 2 B Y class2 </code></pre> <p>I would like to create new columns based on df[&quot;Type&quot;] values and take the values from the column df[&quot;Value&quot;] based on the same data in columns Field and ID. So my output should be something like this:</p> <pre><code> Year Field ID class1 class2 0 2023 A X 0.0 2.0 1 2023 B X 3.0 NaN 2 2024 A X 1.0 NaN 3 2024 B Z 5.0 NaN 4 2024 B Y NaN 2.0 </code></pre> <p>Anyone could help me?</p>
<python><pandas><pivot>
2023-03-09 17:38:13
1
702
user026
75,687,761
3,434,388
How to enforce Protocol class definitions?
<p>Python 3.8 recently introduced Protocol classes, super helpful for defining class method signatures. I'm using them as part of a factory method, something like:</p> <pre><code>class Thing(Protocol): @abstractmethod def do_thing(self, thing_id: int, action: str, monitor: bool = True) -&gt; None: raise NotImplementedError </code></pre> <p>and our factory method is defined something like:</p> <pre><code>def provider_factory(some_data: dict) -&gt; Thing: if some_data['type'] == Thing.ThingTypes.TypeA: return TypeAProcessor(some_data) elif some_data['type'] == Thing.ThingTypes.TypeB: return TypeBProcessor(some_data) .... my_thing = provider_factory(some_data) my_thing.do_thing(thing_id=1, action=&quot;foo&quot;) ... </code></pre> <p>This works great - anyone wanting to implement a new <code>TypeProcessor</code> can clearly infer that it will require a <code>do_thing</code> method, along with the required signature, etc.</p> <p>However, this is a legacy app currently being modernized, so enforcing type checking during build / test isn't possible yet - far too many older parts of the code will fail.</p> <p>Is there some way to selectively enforce, at run-time, that anything returned by the <code>provider_factory</code> conforms to the protocol class definitions, and raise a runtime error if not? The <code>typing</code> module comes with the decorator <code>@typing.runtime_checkable</code>, but it requires writing an explicit <code>assert isinstance(MyTypeProcessor, Thing)</code>, which I'd like to avoid (also related to the legacy nature of this app).</p> <p>tl;dr: Can I enforce Protocol class type checks at runtime other than <code>assert</code>ing with <code>@typing.runtime_checkable</code>?</p>
<python><python-3.x><python-typing>
2023-03-09 17:00:15
0
3,700
Danielle M.
75,687,698
265,629
AsyncMock coroutines never actually yield control?
<p>I'm trying to test some asynchronous code I wrote. The structure is:</p> <ul> <li>A worker object is responsible for receiving a task and asynchronously executing it, often <code>await</code>ing on some asynchronous IO call</li> <li>Sitting above each worker object is a loop that reads from a shared queue, passing tasks down to the worker as each task becomes available. Note that this queue is persistent, and in reality I'm using a blocking persistent queue library.</li> <li>At the very top is an <code>asyncio.gather</code> call, waiting on each of the inner loops. I've constructed a toy example:</li> </ul> <pre class="lang-py prettyprint-override"><code>import asyncio async def loop_inner(worker, worker_num, tasks): while tasks: task = tasks.pop() print('Worker number {} handled task number {}'.format( worker_num, await worker.do_work(task))) async def loop(workers, tasks): tasks = [loop_inner(worker, worker_num, tasks) for worker_num, worker in enumerate(workers)] await asyncio.gather(*tasks) </code></pre> <p>When run on a real workload, the structure works great. High throughput, good use of parallelism, etc.</p> <p>The problem is when I want to test it. I'd like to write tests that mimic the distribute of tasks across the various workers. However, I want to test just the distribution logic, while mocking out the worker code itself. My natural impulse is to replace real workers with <code>AsyncMock</code> objects. Problem is, when I run this test case, all the work is being handled by a single worker:</p> <pre class="lang-py prettyprint-override"><code>from unittest import IsolatedAsyncioTestCase, main from unittest.mock import ANY, AsyncMock, patch class TestCase(IsolatedAsyncioTestCase): async def test_yielding(self): tasks = list(range(10)) workers = [AsyncMock() for i in range(2)] for worker in workers: worker.do_work.side_effect = lambda task: task await loop(workers, tasks) main() </code></pre> <p>My output is as follows:</p> <pre><code>Worker number 0 handled task number 9 Worker number 0 handled task number 8 Worker number 0 handled task number 7 Worker number 0 handled task number 6 Worker number 0 handled task number 5 Worker number 0 handled task number 4 Worker number 0 handled task number 3 Worker number 0 handled task number 2 Worker number 0 handled task number 1 Worker number 0 handled task number 0 </code></pre> <p>What gives? Why is just one worker handling all the work? Is the event loop not passing control off to the other worker? Is the <code>AsyncMock</code> coroutine not really yielding control? What can I do to more realistically test this?</p>
<python><unit-testing><mocking><python-unittest>
2023-03-09 16:54:42
1
28,482
alexgolec
75,687,489
374,458
Circular dendrogram with Altair
<p>I'm trying to build a circular dendrogram with <strong>Python</strong>.</p> <p>This example from Vega is perfect: <a href="https://vega.github.io/vega/examples/radial-tree-layout/" rel="nofollow noreferrer">https://vega.github.io/vega/examples/radial-tree-layout/</a></p> <p>But after several days, I've been unable to reproduce it with <strong>Altair</strong>.</p> <p>Is it because of Vega-lite? Is there a way to make it work?</p>
<python><visualization><altair><vega><dendrogram>
2023-03-09 16:33:00
0
1,870
Nicolas
75,687,409
3,116,231
Issue with creation of nested data classes
<p>I'm trying to create nested data classes:</p> <pre><code>from dataclasses import dataclass, field import datetime from typing import List @dataclass class LineItem: displayName: str compareAtPrice: float discountedPrice: float pricing: str = field(init=False) def __post_init__(self): self.pricing = ( &quot;regular&quot; if self.compareAtPrice == self.discountedPrice else &quot;on sale&quot; ) @dataclass class Order: createdAt: datetime lineItems: List[LineItem] def __post_init__(self): for l in self.lineItems: LineItem(**l) data = { &quot;createdAt&quot;: datetime.datetime.now(), &quot;lineItems&quot;: [ { &quot;displayName&quot;: &quot;lineitem 1&quot;, &quot;compareAtPrice&quot;: 28.1, &quot;discountedPrice&quot;: 28.1, }, { &quot;displayName&quot;: &quot;lineitem 2&quot;, &quot;compareAtPrice&quot;: 88.1, &quot;discountedPrice&quot;: 78.1, }, ], } print(Order(**data)) </code></pre> <p>The output is missing the <code>pricing</code> field which should be populated by <code>__post_init__</code> in <code>class LineItem</code> :</p> <pre><code>Order(createdAt=datetime.datetime(2023, 3, 9, 17, 18, 40, 136535), lineItems=[{'displayName': 'lineitem 1', 'compareAtPrice': 28.1, 'discountedPrice': 28.1}, {'displayName': 'lineitem 2', 'compareAtPrice': 88.1, 'discountedPrice': 78.1}]) </code></pre> <p>What am I doing wrong here?</p>
<python><python-dataclasses>
2023-03-09 16:26:26
1
1,704
Zin Yosrim
75,687,386
386,861
How to upgrade pandas 2.0rc in VSCode
<p>Trying to upgrade to pandas 2.0rc in VSCode using the jupyter notebook extension.</p> <pre><code>! python -m pip install --upgrade pip ! pip install --pre pandas==2.0.0rc0 import pandas as pd pd.__version__ </code></pre> <p>The result is: After the installation stuff...</p> <pre><code>Successfully installed pandas-2.0.0rc0 </code></pre> <p>So why does this still appear for the version?</p> <pre><code>'1.5.2' </code></pre>
<python><pandas><visual-studio-code>
2023-03-09 16:25:03
1
7,882
elksie5000
75,687,278
5,510,540
Python: Sankey plot chart with complex data
<p>I have the following dataset:</p> <pre><code>data = { '1': ['A', 'B', 'C', 'NAN', 'A', 'C', 'NAN', 'C', 'B', 'A'], '2': ['B', 'NAN', 'A', 'B', 'C', 'A', 'B', 'NAN', 'A', 'C'], '3': ['NAN', 'A', 'B', 'C', 'NAN', 'B', 'A', 'B', 'C', 'A'], '4': ['C', 'B', 'NAN', 'A', 'B', 'NAN', 'C', 'A', 'NAN', 'B'] } df = pd.DataFrame(data) </code></pre> <p>and I want to perform a simple Sankey plot of this data structure. I dont even know where to start...</p>
<python><sankey-diagram>
2023-03-09 16:16:12
1
1,642
Economist_Ayahuasca
75,687,150
292,344
How do you convert a dark matplotlib plot to a light grayscale for printing on a printer?
<p>I need to print a matplotlib plot on a printer using pyton 3 and PyQt5. My problem is that the plot has a dark background and colored traces and labels.That will take a lot of ink. I need to print the plot in black and white or gray scale and invert the dark colors to white or gray scale etc. What is the best way to do this?</p>
<python><matplotlib><printing>
2023-03-09 16:04:16
1
361
user292344
75,687,112
12,285,101
Python - check if a two specific words are exists in different items in list
<p>I have many lists that are more or less similar to this:</p> <pre><code> ['my_name:Ruth','my_age:23','hobbies:everything'] </code></pre> <p>I want to verify that all the list contains &quot;my_age&quot; and my_name&quot;, so if list has only &quot;my_name&quot; but doesn't have &quot;my_age&quot;, or opposite, or, doesn't have any of the specificed string, it will be appended to list named &quot;bad&quot;. If the list has both &quot;my_age&quot; and my_name&quot;, I'll append it to the good list.</p> <p>for now I have been able to <a href="https://stackoverflow.com/questions/26355191/python-check-if-a-letter-is-in-a-list">find only if the list has one of the string</a> :</p> <pre><code>def find_letter(letter, lst): return any(letter in word for word in lst) find_letter('my_name' , first3) &gt;&gt;&gt;True </code></pre> <p>But I couldn't put in one code both options. How can I do this?</p>
<python><string>
2023-03-09 16:01:07
1
1,592
Reut
75,686,954
12,596,824
How does np.random.binomial work in numpy python
<p>I have the following code but I'm unsure how it works even after reading documentation..</p> <pre><code>print(np.random.binomial(n = 1, [0.1,0.9])) </code></pre> <p>I want to produce either 0 or 1 values with probability 10% being 1 and 90% being 0. Is the code above how you would do it?</p> <p>What if I changed the code to the following? What does that mean for the distributions when I have 3 values in the p argument? Does n being 2 mean the possible values could be 0,1,2?</p> <pre><code>print(np.random.binomial(n = 2, p = [0.1,0.5,0.4])) </code></pre>
<python><numpy>
2023-03-09 15:48:00
1
1,937
Eisen
75,686,933
8,713,442
Creating new Dictionary based on key values in list
<p>I have dictionary D1 and list l1 .I want to create new dictionary D2 picking key values from List . Is there any direct way of doing this or I need to apply through for loop on list .</p> <pre><code> def main(): dict ={'acct_number':'10202','acct_name':'abc','v1_rev':'30000','v2_rev':'4444', 'v3_rev':'676373'} vendors_revenue_list =['v1_rev','v2_rev','v3_rev'] if __name__ == '__main__': main() </code></pre> <p>I want output like</p> <blockquote> <p>dict2 = {'v1_rev':'30000','v2_rev':'4444','v3_rev':'676373'}</p> </blockquote>
<python>
2023-03-09 15:45:26
1
464
pbh
75,686,858
14,037,283
getenv()s return None when using Pycharm's Play button
<p>I am using:</p> <pre><code>from dotenv import load_dotenv from os import getenv load_dotenv(&quot;config/.env&quot;) </code></pre> <p>in a project which uses the <code>pytest</code> &amp; <code>selenium</code> package.</p> <p>I use <code>getenv(&quot;example_string&quot;)</code> at various points in this file which imports from a <code>.env</code> file.</p> <p>The <code>getenv()</code>s work when I run the <code>pytest</code> command through the command-line. However, the <code>getenv()</code>s all return <code>None</code> when I run pytest through Pycharm's 'play button' like in the picture below:</p> <p><a href="https://i.sstatic.net/k6Xn7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/k6Xn7.png" alt="enter image description here" /></a></p> <p>How can I get the play button to work too?</p>
<python><pycharm><python-dotenv>
2023-03-09 15:39:44
0
2,460
tonitone120
75,686,842
244,297
What's the time complexity of this algorithm for solving an interview question?
<p>The <a href="https://leetcode.com/discuss/interview-question/924141/google-phone-screen-new-grad" rel="nofollow noreferrer">problem</a> goes as follows:</p> <blockquote> <p>You have a stream of RPC requests coming in which is being logged. Each log entry is of the form <code>{rpc_id, timestamp, type (start or end)}</code>. Given a timeout value <code>T</code>, you need to figure out at the earliest possible time if any requests have timed out.</p> </blockquote> <pre><code>E.g.: id - time - type 0 - 0 - Start 1 - 1 - Start 0 - 2 - End 2 - 6 - Start 1 - 7 - End Timeout = 3 Answer: {1, 6} ( figured out id 1 had timed out at time 6 ) </code></pre> <p>The linked page contains some <code>O(n)</code> solutions using a doubly linked list and a hashmap. Since a Python dict preserves the insertion order, I think it's possible to use it as the only data structure:</p> <pre><code>from dataclasses import dataclass @dataclass(frozen=True, slots=True) class LogEntry: rpc_id: int timestamp: int action: str class LogProcessor: def __init__(self, timeout: int): self.entries = {} self.timeout = timeout def process_log_entry(self, entry: LogEntry) -&gt; list[LogEntry]: if entry.action == 'Start': self.entries[entry.rpc_id] = entry elif entry.rpc_id in self.entries and entry.timestamp - self.entries[entry.rpc_id].timestamp &lt;= self.timeout: del self.entries[entry.rpc_id] timed_out = [] for k, v in self.entries.items(): if entry.timestamp - v.timestamp &lt;= self.timeout: break timed_out.append(v) for e in timed_out: del self.entries[e.rpc_id] return timed_out log_processor = LogProcessor(timeout=3) assert log_processor.process_log_entry(LogEntry(1, 0, 'Start')) == [] assert log_processor.process_log_entry(LogEntry(2, 1, 'Start')) == [] assert log_processor.process_log_entry(LogEntry(1, 2, 'End')) == [] assert log_processor.process_log_entry(LogEntry(3, 6, 'Start')) == [LogEntry(2, 1, 'Start')] </code></pre> <p>Is the time complexity of this algorithm still <code>O(n)</code>?</p>
<python><algorithm><dictionary>
2023-03-09 15:38:21
0
151,764
Eugene Yarmash
75,686,755
15,452,168
reading multi-index header based excel file using pandas
<p>I have an excel file where first 3 rows have header names, I want to read it in pandas but facing difficulty in the multi-index header.</p> <pre><code> PLAN 2023 Traffic per channel Traffic Share per Channel month week All Traffic red green orange red green orange jan 1 100 50 30 20 50% 30% 20% </code></pre> <p>for 'month' and 'week', I have the header names stored in row 3 but for others, it's distributed in row 1,2,3. Also, the row number is not fixed, therefore, I need to read by headers.</p> <p>The final expected output should look like this</p> <pre><code>month week plan_2023_Traffic_per_channel_All .....plan_2023_Traffic_Share_per_channel_orange jan 1 100 20% </code></pre> <p>my script is below, for simplicity, I am just printing 1 value</p> <pre><code>import pandas as pd # Load the Excel file df = pd.read_excel('test_3.xlsx', sheet_name='WEEK - 2023', header=None) # Set the first 3 rows as the header header = df.iloc[:3,:].fillna(method='ffill', axis=1) df.columns = pd.MultiIndex.from_arrays(header.values) df = df.iloc[3:,:] # Select only the specified columns df = df.loc[:, ('month', 'week', ('PLAN 2023', 'Traffic per channel', 'red'))] # Rename the columns to remove the multi-level header df.columns = ['month', 'week', 'P_traffic_red'] # Print the final data frame print(df) </code></pre> <p>picture for reference</p> <p><a href="https://i.sstatic.net/whZyC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/whZyC.png" alt="enter image description here" /></a></p> <p>Thank you in advance</p>
<python><excel><pandas><openpyxl><multi-index>
2023-03-09 15:30:46
1
570
sdave
75,686,662
12,248,220
python triply nested for loop code optimization
<p>I have written a code which has its bottleneck in a triply-nested for-loop which goes through the 3-dimensional Physical space (r, theta, phi).</p> <p>[The code has to work on each of the datapoints from this 3D space, so there is no clever way to re-design the logic in order to avoid the triply-nested for loop.]</p> <p>This triply nested for-loop will be called in the main code 8825 times (potentially more). It is allowed to only use 1 core. I need to make it as fast as possible. I can now get it to work in 14 - 15 seconds.</p> <p>Please, do you see any other improvements I could make?</p> <ul> <li>I have tried to minimize brute computations. I.e. avoid repeatedly calling <code>np.sin</code> , <code>np,cos</code>, etc, and pre-compute these calculations' results inside pre-allocated arrays. I then just index these numpy arrays I created before.</li> <li>I have found a function which is O(n * log n) to search through a sorted array.</li> </ul> <p>A MWE is (edit, I now know, due to @JonSG, that the <code>np.imag(conhyp_results[k_idx, :, 0])</code> factor can be taken outside the triply nested-for loop):</p> <pre><code>import numpy as np from time import perf_counter Nb = 300 l_max = 50 Z = 1.0 def Coulomb(r): return (-Z / r) def find_idx_closest_to_input(array, target_value): # it assumes array is sorted and is 1 dimensional n = array.shape[0] if (target_value &lt; array[0]): return -1 elif (target_value &gt; array[n-1]): return n jl = 0 # Initialize lower ju = n-1 # and upper limits. while (ju-jl &gt; 1): # If we are not yet done, jm = (ju+jl) &gt;&gt; 1 # compute a midpoint with a bitshift if (target_value &gt;= array[jm]): jl = jm # and replace either the lower limit else: ju = jm # or the upper limit, as appropriate. # Repeat until the test condition is satisfied. if (target_value == array[0]): # edge cases at bottom return 0 elif (target_value == array[n-1]): # and top return n-1 else: return jl coulomb_array = np.random.rand( Nb ) ris = np.random.rand( Nb ) sin_thetas = np.random.rand( l_max+1 ) cos_thetas = np.random.rand( l_max+1 ) sin_phis = np.random.rand( 2*l_max+2 ) cos_phis = np.random.rand( 2*l_max+2 ) r_vec_cartesian = np.zeros ( (3) ) b_vec = np.random.rand ( 3 ) b_dot_vec = np.random.rand ( 3 ) k_vec_cartesian = np.random.rand ( 3 ) k_wave = 2.0 conhyp_results = np.random.rand( 15, 10000, 2 ) + 1j * np.random.rand( 15, 10000, 2 ) Psi_scattering_prelim = np.zeros ( ( Nb, (l_max+1), (2*l_max+2) ) ) + 1j * np.zeros ( ( Nb, (l_max+1), (2*l_max+2) ) ) tensor_of_exp_of_minusI_bdot_times_r = np.zeros ( (Nb, (l_max+1), (2*l_max+2)) ) + 1j * np.zeros ( (Nb, (l_max+1), (2*l_max+2)) ) difference_in_potential_values = np.zeros( (Nb, (l_max+1), (2*l_max+2)) ) k_idx = 10 prefactor = 10.0 t_coordinates_start = perf_counter() for a in range(Nb): for b in range(l_max+1): for c in range(2*l_max+2): r_vec_cartesian[0] = ris[a] * sin_thetas[b] * cos_phis[c] r_vec_cartesian[1] = ris[a] * sin_thetas[b] * sin_phis[c] r_vec_cartesian[2] = ris[a] * cos_thetas[b] r_minus_b_vec_cartesian = r_vec_cartesian - b_vec r_minus_b_vec_cartesian_modulus = np.sqrt( r_minus_b_vec_cartesian.dot(r_minus_b_vec_cartesian) ) arg3_imag_part = -( k_wave*r_minus_b_vec_cartesian_modulus + k_vec_cartesian.dot(r_minus_b_vec_cartesian) ) # a np.float64 index_from_conhyp_results = find_idx_closest_to_input( np.imag(conhyp_results[k_idx, :, 0]), arg3_imag_part ) result_cpp = conhyp_results[k_idx, index_from_conhyp_results, 1] factor = np.exp( 1j * k_vec_cartesian.dot(r_minus_b_vec_cartesian) ) Psi_scattering_prelim[a, b, c] = prefactor * factor * result_cpp b_dot_vec_times_r_vec = b_dot_vec.dot(r_vec_cartesian) tensor_of_exp_of_minusI_bdot_times_r[a, b, c] = np.exp(-1j * b_dot_vec_times_r_vec) difference_in_potential_values[a, b, c] = coulomb_array[a] - Coulomb(r_minus_b_vec_cartesian_modulus) # END for loop through coordinates t_coordinates_end = perf_counter() print(&quot;We have gone through the coordinates&quot;) print(&quot;To go through coordinates it took: &quot; + str(t_coordinates_end - t_coordinates_start) + &quot; seconds&quot;) </code></pre> <p>It shall run in ~ 15 seconds.</p> <p>Ideally, if one made it to work in &lt; 8-9-10 seconds, it would be great.</p> <p>I do not want to use numba becauase this part of the code is inside a much bigger project.</p> <p>Thank you!</p>
<python><numpy><performance><loops><optimization>
2023-03-09 15:22:50
0
576
velenos14
75,686,570
11,261,546
Is there a numpy object containing all types?
<p>I'm writting a unit test of a function that only accepts numpy arrays of type <code>numpy.uint8</code> and I wanted to test that I get the right exception from <strong>all</strong> the other types.</p> <p>So I did a set like this:</p> <pre><code>self.supported_types = {np.uint8} self.not_supported_types = {np.bool_, np.int8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64, np.longlong, np.ulonglong, np.float16, np.float32, np.float64, np.float128, np.complex64, np.complex128, np.complex256, np.object_, np.bytes_, np.str_, np.void, np.datetime64, np.timedelta64} </code></pre> <p>I was wondering if there's a way to get a list with all numpy's types without writing all of them as:</p> <pre><code>all_types = numpy.something() # does this exist? not_supported = all_types.remove(numpy.uint8) </code></pre>
<python><numpy>
2023-03-09 15:16:21
1
1,551
Ivan
75,686,310
7,544,724
Automating a Script with ClearML
<p>I am using ClearML to automate a script. I'm new to the tool and I haven't found any tutorials for this. The goal I'm trying to accomplish is automate several python scripts so that a server is spun up and torn down as necessary to run them using clearml. Can anyone point me to documentation or explain to me how to do this?</p>
<python><clearml>
2023-03-09 14:57:53
1
450
bballboy8
75,686,137
14,269,252
My Y axis doesnt show all the dates on Y axis while plotting heatmap in plotly
<p>I know how to make a good heatmap in seaborn, but I would like to use the Plotly package. I used the code below, but my Y axis doesn't show all the dates, how can I show all the the dates on my y axis?</p> <p>I want background color be white and each category have different custom color too, how should I modify the code?</p> <p>My data frames includes a date column and other columns which I would put them on X axis</p> <pre><code>import plotly.express as px fig = px.imshow(df, text_auto=True,color_continuous_scale='RdBu_r', origin='lower') fig.show() </code></pre> <p><a href="https://i.sstatic.net/f6UOJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/f6UOJ.png" alt="enter image description here" /></a></p> <p>What I want is the following:</p> <p><a href="https://i.sstatic.net/NXFTW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/NXFTW.png" alt="enter image description here" /></a></p> <p>A sample of my data frame:</p> <pre><code> a b c d e f DATE 2010-04-12 0 1 0 0 0 0 </code></pre> <p>Chart based on code provided as below: <a href="https://i.sstatic.net/HjcUz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HjcUz.png" alt="enter image description here" /></a></p>
<python><plotly><heatmap>
2023-03-09 14:44:20
1
450
user14269252
75,686,071
3,357,270
Why are path variable keys being read as values in my Django application?
<p>I am using Django Rest Framework to build an api. This is my first time working with DRF, but have experience working with Laravel/NestJs so the concept of routing isn't too unfamiliar.</p> <p>In my DRF application, my url config looks something like this:</p> <pre><code>// urls.py urlpatterns = [ path('api/v1/accounts/&lt;str:account_number&gt;/', accounts.AccountsViewSet.as_view()), url('api/v1/', include(router.urls)), ] </code></pre> <p>In Postman, I am sending a <code>GET</code> request to the following url:</p> <pre><code>{{my_host}}/api/v1/accounts/:account_number/ </code></pre> <p>My view looks like this:</p> <pre><code>// view.py def get(self, request, account_number=None, *args, **kwargs): print(account_number) if account_number is not None: print('account_number was provided') else: print('account_number not provided') </code></pre> <p>When sending a <code>GET</code> request to my endpoint, I can provide a value for <code>account_number</code> key. Let's say I use <code>ABC123</code> as the key value. Given the above view, the first print statement returns <code>ABC123</code>.</p> <p>I will also get into the first <code>if</code> block and see the message <code>account_number was provided</code> All is well!</p> <p>However, if I do <em>not</em> provide an account number (I leave the path variable value empty) I am getting the path variable itself in my logging. For example:</p> <pre><code>// view.py def get(self, request, account_number=None, *args, **kwargs): print(account_number) // :account_number if account_number is not None: print('account_number was provided'). &lt;!-- still getting here else: print('account_number not provided') </code></pre> <p>As you can see, I am getting the variable. I would expect to be getting an empty string <code>''</code> not the variable name (key) <code>:account_number</code>.</p> <p>I have tried setting the values to check for empty string, or <code>null</code> (also a string) but since the <code>:account_number</code> key is getting passed in...I'm not sure what else to try.</p> <p>How can I check if <code>:account_number</code> is empty (was not provided) in my view? Is this something unique to DRF? I am able to do these checks quite easily with Laravel and/or NestJs.</p> <p>Thank you for any suggestions!</p>
<python><django><django-rest-framework>
2023-03-09 14:40:07
0
4,544
Damon
75,686,001
5,861,153
How can I position my kivy app window in the right bottom corner
<p>I have a kivy desktop app and want to start it in the corner at the right. Currently, i can only apply the position from the left, top...</p> <pre><code>from kivy.config import Config Config.set('graphics','position','custom') Config.set('graphics','resizable',0) Config.set('graphics','left',20) Config.set('graphics','top',50) Config.write() </code></pre>
<python><kivy>
2023-03-09 14:34:22
2
418
Medera
75,685,860
8,176,763
airflow webserver showing next run as start of data interval
<p>I have a dag like that:</p> <pre><code>@dag( dag_id = &quot;data-sync&quot;, schedule_interval = '*/30 * * * *', start_date=pendulum.datetime(2023, 3, 9, tz=&quot;Asia/Hong_Kong&quot;), catchup=False, dagrun_timeout=timedelta(minutes=20), ) </code></pre> <p>So it runs every 30 minutes , starting today in my timezone. No catchup.... In the webserver UI I have these different fields :</p> <p><a href="https://i.sstatic.net/rMX1i.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rMX1i.png" alt="enter image description here" /></a></p> <p>What I find strange from these fields is the next run time... I was looking at it between 21:01 and 21:29 ... and it's still show the next run as 21:00 or in another words the next run is past...</p> <p>Does the next run mean the logical date in airflow ? that is the start time of the interval ? it is quite non intuitive to look at it and see a time in the past...</p>
<python><airflow>
2023-03-09 14:21:52
1
2,459
moth
75,684,994
11,710,304
Detect rows where uniqueness is not given in polars
<p>Currently I have the following problem. I have to check if there is an infringement if the column values <code>ID</code>, <code>table</code> and <code>value_a</code> are not unique.</p> <pre><code> df = pl.DataFrame( { &quot;ID&quot;: [&quot;1&quot;, &quot;1&quot;, &quot;1&quot;, &quot;1&quot;, &quot;1&quot;], &quot;column&quot;: [&quot;foo&quot;, &quot;foo&quot;, &quot;bar&quot;, &quot;ham&quot;, &quot;egg&quot;], &quot;table&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;], &quot;value_a&quot;: [&quot;tree&quot;, tree, None, &quot;bean&quot;, None,], &quot;value_b&quot;: [&quot;Lorem&quot;, &quot;Ipsum&quot;, &quot;Dal&quot;, &quot;Curry&quot;, &quot;Dish&quot;,], &quot;mandatory&quot;: [&quot;M&quot;, &quot;M&quot;, &quot;M&quot;, &quot;CM&quot;, &quot;M&quot;] } ) print(df) shape: (5, 6) ┌─────┬────────┬───────┬─────────┬─────────┬───────────┐ │ ID ┆ column ┆ table ┆ value_a ┆ value_b ┆ mandatory │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str ┆ str ┆ str │ ╞═════╪════════╪═══════╪═════════╪═════════╪═══════════╡ │ 1 ┆ foo ┆ A ┆ tree ┆ Lorem ┆ M │ │ 1 ┆ foo ┆ B ┆ tree ┆ Ipsum ┆ M │ │ 1 ┆ bar ┆ C ┆ null ┆ Dal ┆ M │ │ 1 ┆ ham ┆ D ┆ bean ┆ Curry ┆ M │ │ 1 ┆ egg ┆ E ┆ null ┆ Dish ┆ M │ └─────┴────────┴───────┴─────────┴─────────┴───────────┘ </code></pre> <p>In the case of df a infringement report should be created with the following dedicated output:</p> <pre><code>shape: (2, 8) ┌───────┬─────┬────────┬───────┬─────────┬─────────┬───────────┬─────────────────────────┐ │ index ┆ ID ┆ column ┆ table ┆ value_a ┆ value_b ┆ mandatory ┆ warning │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str ┆ str ┆ str ┆ str ┆ str ┆ str │ ╞═══════╪═════╪════════╪═══════╪═════════╪═════════╪═══════════╪═════════════════════════╡ │ 0 ┆ 1 ┆ foo ┆ A ┆ tree ┆ Lorem ┆ M ┆ Row value is not unique │ │ 1 ┆ 1 ┆ foo ┆ A ┆ tree ┆ Ipsum ┆ M ┆ Row value is not unique │ └───────┴─────┴────────┴───────┴─────────┴─────────┴───────────┴─────────────────────────┘ </code></pre> <p>The report should contain an <code>index</code> and a <code>warning</code> column. I used this line of code to identify if there are any null values in a row:</p> <pre><code>report = (df.with_row_count(&quot;index&quot;) .filter(pl.any(pl.col(&quot;*&quot;).is_null()) &amp; pl.col(&quot;mandatory&quot;).eq(&quot;M&quot;)) .with_columns(pl.lit(&quot;Missing value detected&quot;).alias(&quot;warning&quot;)) ) </code></pre> <p>How do I need to adapt this code so on the one hand I detect missing values and on the other hand I identify ununique rows. Maybe I create two reports and use .vstack() to combine both reports to a final one. How would you solve it?</p>
<python><python-polars>
2023-03-09 13:01:30
1
437
Horseman
75,684,971
1,576,254
pytest fails on github action with no output, error code 1
<p>I'm running pytest on a self-hosted windows runner (windows server 2019), but it fails with no output, just says <code>exit code 1</code>. No output also despite using debug mode on the runner.</p> <p>I get python via <code>actions/setup-python@v4</code>. Dependencies are installed with <code>python -m pip install -e '.[dev]'</code>, including <code>pytest</code>.</p> <p>Logs of action run:</p> <pre><code>Run pytest --version pytest --version shell: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.EXE -command &quot;. '{0}'&quot; env: ACTIONS_RUNNER_DEBUG: true pythonLocation: C:\Users\User1\GHA_abs\_work\_tool\Python\3.9.13\x64 PKG_CONFIG_PATH: C:\Users\User1\GHA_abs\_work\_tool\Python\3.9.13\x64/lib/pkgconfig Python_ROOT_DIR: C:\Users\User1\GHA_abs\_work\_tool\Python\3.9.13\x64 Python2_ROOT_DIR: C:\Users\User1\GHA_abs\_work\_tool\Python\3.9.13\x64 Python3_ROOT_DIR: C:\Users\User1\GHA_abs\_work\_tool\Python\3.9.13\x64 Error: Process completed with exit code 1. </code></pre>
<python><pytest><github-actions>
2023-03-09 12:59:48
1
3,573
ikamen
75,684,738
18,049,757
Not able to run FastAPI server, ValueError: source code string cannot contain null bytes
<p>Learning FastAPI, however, an error occurs whenever I'm trying to run it.</p> <p>Error:</p> <pre><code>PS C:\Users\obunga\OneDrive\Desktop\py\fastfast&gt; uvicorn main:app --reload INFO: Will watch for changes in these directories: ['C:\\Users\\obunga\\OneDrive\\Desktop\\py\\fastfast'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [5464] using WatchFiles Process SpawnProcess-1: Traceback (most recent call last): File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\process.py&quot;, line 314, in _bootstrap self.run() File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\process.py&quot;, line 108, in run self._target(*self._args, **self._kwargs) File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\_subprocess.py&quot;, line 76, in subprocess_started target(sockets=sockets) File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\server.py&quot;, line 60, in run return asyncio.run(self.serve(sockets=sockets)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py&quot;, line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py&quot;, line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py&quot;, line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\server.py&quot;, line 67, in serve config.load() File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\config.py&quot;, line 477, in load self.loaded_app = import_from_string(self.app) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\site-packages\uvicorn\importer.py&quot;, line 21, in import_from_string module = importlib.import_module(module_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\obunga\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py&quot;, line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1206, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1178, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1149, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 690, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 936, in exec_module File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 1074, in get_code File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 1004, in source_to_code File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes </code></pre> <p>I've tried <strong>re-installing Python, FastAPI and Uvicorn</strong>, but the error remains. My python version: 3.11.2</p> <p>The code is pretty basic one: main.py -</p> <pre><code>from fastapi import FastAPI app = FastAPI() @app.get(&quot;/&quot;) def index(): return {&quot;lyrics&quot;: &quot;heyyyyyyyyy&quot;} </code></pre> <p><a href="http://127.0.0.1:8000" rel="nofollow noreferrer">http://127.0.0.1:8000</a> is unreachable.</p> <p>What is the issue and how to fix it?</p>
<python><python-3.x><webserver><fastapi>
2023-03-09 12:38:42
1
375
sohdata
75,684,557
10,722,752
how to perform multiprocessing inside Azure API run function
<p>I am trying to reduce the execution time of an API call by using multiprocessing:</p> <p>My original requirement is actually on generating and displaying ML explainability using LIME. For simplicity, let's assume I have below data:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({'cust_id' : ['id1','id1','id2','id2','id2','id1','id2','id1','id1','id2'], 'prod_id' : ['p1','p2','p3','p1','p4','p5','p6','p6','p8','p9'], 'cost' : np.random.randint(100, 1000, 10)}) </code></pre> <p>We have another dataframe:</p> <pre class="lang-py prettyprint-override"><code> df1 = pd.DataFrame({'cust_id' : ['id1','id1','id1','id2','id2','id2'], 'prod_id' : ['p1','p8','p3','p8','p9','p7']}) </code></pre> <p>My API function looks something like this:</p> <pre class="lang-py prettyprint-override"><code>import json def main(data): input_data = json.loads(data)[&quot;data&quot;] customer_id = input_data[0] print(customer_id) item_list = df1.loc[df1[&quot;cust_id&quot;] == customer_id, &quot;prod_id&quot;].tolist() idx = df.loc[ (df[&quot;cust_id&quot;] == customer_id) &amp; (df[&quot;prod_id&quot;].isin(item_list)) ].index.values.tolist() for i in idx: df.loc[i, &quot;cost&quot;] = df.loc[i, &quot;cost&quot;] * 2 return df </code></pre> <p>The input is in <code>json</code> format:</p> <pre class="lang-py prettyprint-override"><code>data = '{&quot;data&quot;:[&quot;id1&quot;]}' out = main(data) </code></pre> <p>My actual code consists of this inplace of the multiplication:</p> <pre class="lang-py prettyprint-override"><code>explainer.explain_instance(df.loc[idx], model.predict_proba) </code></pre> <p>In actual scenario, the for loop would run for 24 times, fetching the row and putting it in the <code>explain_instance</code>.</p> <p>Could someone please let me know how to perform multiprocessing of the for loop such that the 24 iterations come down as much as possible. I have 12 CPU cores in my actual instance.</p>
<python><pandas><multiprocessing>
2023-03-09 12:22:15
1
11,560
Karthik S
75,684,328
18,657,095
Strange behaviour of the program after modifying the dictionary of local variables
<p>I find some strange behavior in my program after modifying the dictionary of local variables, and it makes me confused. If we execute the code below, we will get the result as the image I attached. <strong>And now I know I shouldn't modify the local variables using locals().</strong></p> <pre><code>i=0 locals()[f'num_{i}'] = i print(num_0) def lc(): i=1 locals()[f'num_{i}'] = i import pdb; pdb.set_trace() print(num_1) if __name__ == '__main__': lc() </code></pre> <p>My questions are:</p> <ol> <li><p>Why 'num_0' can be printed successfully while 'num_1' cant? <strong>(solved)</strong></p> </li> <li><p>Why 'num_1' can be printed in pdb but 'print(num_1)' cant be executed? <strong>(solved)</strong></p> </li> </ol> <p>Result:</p> <pre><code>python test.py ----- 0 -&gt; print(num_1) (pdb) p num_1 1 (pdb) c Traceback (most recent call last): File &quot;test.py&quot;, line 13, in &lt;module&gt; lc() File &quot;test.py&quot;, line 9, in lc print(num_1) NameError: name 'num_1' is not defined </code></pre> <p>Actually, I have a few ideas but I am not sure. I checked the dictionary of global variables, and 'num_0' is in it. So I suppose the first question is because the interpreter doesn't know that 'num_1' is in the dictionary of local variables, while 'num_0' is not only in the local dictionary but also in the global dictionary. As to the second question, I suppose pdb will know the modified local dictionary, so it can print 'num_1' successfully.</p> <p>I hope someone can help to explain the two questions or give me some reference materials.</p>
<python><local-variables><pdb>
2023-03-09 12:01:17
1
632
x pie
75,684,222
17,834,402
Merge two DataFrames based on containing string without iterator
<p>I have two csv files imported as dataframes <code>A</code> and <code>C</code>. I want to match the strings of column <code>content</code> with the entry in <code>data.data</code> that contains the string from <code>A</code>.</p> <pre><code>A time_a content C time_c data.data 100 f00 400 otherf00other 101 ba7 402 onlyrandom 102 4242 407 otherba7other 409 other4242other Should become: time_a time_c content 100 400 f00 101 407 ba7 102 409 4242 </code></pre> <p>My solution below uses iterators. But it works too slow. <a href="https://stackoverflow.com/a/55557758/17834402">This answer</a> explains why and gives methods how to improve. But I struggle to implement any.</p> <p>How can I do this with the optimized methods from pandas?</p> <pre><code># reset_index() on both df df_alsa_copy = df_alsa.copy() # Never modify your iterator df_alsa_copy['cap_fno'] = -1 for aIndex, aRow in df_alsa.iterrows(): for cIndex, cRow in df_c.iterrows(): if str(aRow['content']) in str(cRow['data.data']): df_alsa_copy.loc[aIndex, 'cap_fno'] = df_c.loc[cIndex, 'frame.number'] # https://stackoverflow.com/questions/31528819/using-merge-on-a-column-and-index-in-pandas # Merge on frame.number column (bc I chose it to be included in alsa_copy as a column) df_ltnc = pd.merge(df_alsa_copy, df_c, left_on='cap_fno', right_on='frame.number') </code></pre> <h4>Also tried:</h4> <ul> <li>Would work, if there is an exact match: <a href="https://stackoverflow.com/questions/44080248/pandas-join-dataframe-with-condition">Pandas: Join dataframe with condition</a>.</li> <li>I also managed to match my second frame against a known string with <code>series.str.contains</code>.</li> <li>The problem is, I fail to enter a dataframe column to match in <code>merge on=</code>. I can only enter a known string.</li> <li>The same problem arose, when I used <code>apply</code>.</li> <li>I did not succeed with <code>isin</code> or similar.</li> </ul> <h4>More info:</h4> <p><code>A</code> holds timestamped content I fed into the program. <code>C</code> is a network capture. I want to know the time in between feeding and capture. I assume:</p> <ul> <li>The string occur in the same order in <code>A</code> and <code>C</code>.</li> <li>But in <code>C</code> there might be lines in between.</li> <li>Strings represent hex values.</li> <li><code>data.data</code> contains other chars as well as the string I look for.</li> <li>Maybe I lack the pandas vocabulary, to look for the correct method.</li> </ul>
<python><pandas>
2023-03-09 11:51:25
2
409
Paul Smith
75,684,073
5,695,336
call_soon_threadsafe never call the function if it is inside an async function
<p>I am working with a third party library that will call a function I gave it from another thread at some random time. It can be modelled as a delayed function call in another thread.</p> <p>The function I want it to call is an async function. The library does not have a special interface for async function, also I do not want it to block the code like <code>asyncio.run</code>. To summarize it:</p> <p>I need a way to run an async function in the background from a non-async function that will be called from another thread.</p> <p>I asked the question in <a href="https://stackoverflow.com/questions/75640960/run-a-coroutine-in-the-background-from-a-non-async-function">this post</a>, and came up with a nearly perfect solution, until I run into the following problem.</p> <p>If the async function tries to run another async function in the same way, it will not work. The cause is <code>call_soon_threadsafe</code> will never call the callback function if it is inside an async function.</p> <p>This is the code that can recreate the problem:</p> <pre><code>import asyncio import threading import time from typing import Coroutine, Any import logging logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO, datefmt='%H:%M:%S') coro_queue: asyncio.Queue[Coroutine[Any, Any, Any]] = asyncio.Queue() task: asyncio.Task[Any] | None = None task_ready = asyncio.Event() loop: asyncio.AbstractEventLoop | None = None async def start_coro_queue() -&gt; None: global task, loop loop = asyncio.get_event_loop() while True: coro = await coro_queue.get() task = asyncio.create_task(coro) task_ready.set() def put_coro_in_queue(coro: Coroutine[Any, Any, Any]) -&gt; None: logging.info(&quot;put_coro_in_queue called.&quot;) coro_queue.put_nowait(coro) logging.info(&quot;put_coro_in_queue finished.&quot;) def run_coro_in_background(coro: Coroutine[Any, Any, Any]) -&gt; asyncio.Task[Any]: logging.info(&quot;run_coro_in_background called&quot;) global task assert loop is not None task_ready.clear() future = asyncio.run_coroutine_threadsafe(task_ready.wait(), loop) loop.call_soon_threadsafe(put_coro_in_queue, coro) future.result() assert task is not None output = task task = None logging.info(&quot;run_coro_in_background finished&quot;) return output async def async_func() -&gt; None: logging.info(&quot;async_func called.&quot;) await asyncio.sleep(2) logging.info(&quot;async_func finished.&quot;) def delayed_async_func() -&gt; None: logging.info(&quot;delayed_async_func called&quot;) time.sleep(5) run_coro_in_background(async_func()) logging.info(&quot;delayed_async_func finished.&quot;) async def nested_async_func() -&gt; None: logging.info(&quot;nested_async_func called&quot;) await asyncio.sleep(3) run_coro_in_background(async_func()) logging.info(&quot;nested_async_func finished&quot;) def delayed_nested_async_func() -&gt; None: logging.info(&quot;delayed_nested_async_func called&quot;) time.sleep(4) run_coro_in_background(nested_async_func()) logging.info(&quot;delayed_nested_async_func finished&quot;) async def main() -&gt; None: t = threading.Thread(target=delayed_nested_async_func) t.start() await start_coro_queue() asyncio.run(main()) </code></pre> <p>The result is:</p> <pre><code>19:25:51 delayed_nested_async_func called 19:25:55 run_coro_in_background called 19:25:55 put_coro_in_queue called. 19:25:55 put_coro_in_queue finished. 19:25:55 nested_async_func called 19:25:55 run_coro_in_background finished 19:25:55 delayed_nested_async_func finished 19:25:58 run_coro_in_background called </code></pre> <p>Then it stuck forever.</p> <p>The expected output should contain:</p> <pre><code>19:25:58 put_coro_in_queue called 19:25:58 put_coro_in_queue finished 19:25:58 async_func called 19:26:00 async_func finished </code></pre> <p>When test the non-nested case by changing <code>main</code> into:</p> <pre><code>async def main() -&gt; None: t = threading.Thread(target=delayed_async_func) t.start() await start_coro_queue() </code></pre> <p>Everything runs as expected.</p> <pre><code>19:34:00 delayed_async_func called 19:34:05 run_coro_in_background called 19:34:05 put_coro_in_queue called. 19:34:05 put_coro_in_queue finished. 19:34:05 async_func called. 19:34:05 run_coro_in_background finished 19:34:05 delayed_async_func finished. 19:34:07 async_func finished. </code></pre>
<python><multithreading><asynchronous><python-asyncio>
2023-03-09 11:37:35
1
2,017
Jeffrey Chen
75,684,031
7,762,646
How to get all the nodes and edges connected to a certain node in networkx?
<p>I have created a simple undirected graph in Python networkx library:</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_nodes_from([&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;]) G.add_edges_from([(&quot;A&quot;,&quot;C&quot;), (&quot;B&quot;,&quot;D&quot;), (&quot;B&quot;,&quot;E&quot;), (&quot;C&quot;, &quot;E&quot;), (&quot;A&quot;, &quot;E&quot;), (&quot;E&quot;, &quot;D&quot;)]) #pos = nx.random_layout(G) fig, ax = plt.subplots() nx.draw_networkx(G, pos=pos, ax=ax) fig.tight_layout() plt.show() </code></pre> <p>I would like to return a subgraph of all the nodes and edges connected to a certain node. As an example, if the node is &quot;A&quot;, the connected nodes are &quot;C&quot; and &quot;E&quot;. So it should return these 3 nodes and the edges between them.</p> <p>This is what I tried following a couple other StackOverflow answers:</p> <pre><code>node = &quot;A&quot; # connected_nodes = nx.shortest_path(G,node).keys() connected_nodes = list(nx.node_connected_component(G, &quot;A&quot;)) connected_edges = G.edges([node]) print(connected_nodes) print(connected_edges) H = nx.Graph() H.add_nodes_from(connected_nodes) H.add_edges_from(connected_edges) # https://stackoverflow.com/questions/33088008/fetch-connected-nodes-in-a-networkx-graph # https://stackoverflow.com/questions/63169294/how-to-plot-a-subset-of-nodes-of-a-networkx-graph fig, ax = plt.subplots() nx.draw_networkx(H, pos=pos, ax=ax) fig.tight_layout() plt.show() </code></pre> <p>The current output looks like this (almost there!) but I am getting more nodes returned than I should:</p> <p><a href="https://i.sstatic.net/kRO6p.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kRO6p.png" alt="enter image description here" /></a></p> <p>How do I fix it?</p>
<python><python-3.x><networkx>
2023-03-09 11:33:17
1
1,541
G. Macia
75,684,005
5,075,502
Wrong shape output with conv1D layer
<p>I'm trying some experiments with a small autoencoder defined like this:</p> <pre><code>input_layer = Input(shape=input_shape) x = Conv1D(8, kernel_size=5, activation='relu', padding='same')(input_layer) x = BatchNormalization()(x) encoded = Conv1D(4, kernel_size=5, activation='relu', padding='same')(x) x = Conv1D(8, kernel_size=5, activation='relu', padding='same')(encoded) x = BatchNormalization()(x) decoded = Conv1D(WINDOW_SIZE, kernel_size=5, activation='relu', padding='same')(x) </code></pre> <p><code>input_shape = 8192</code> and <code>autoencoder.summary()</code> returns:</p> <pre><code> Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 8192, 1)] 0 conv1d (Conv1D) (None, 8192, 8) 48 batch_normalization (BatchN (None, 8192, 8) 32 ormalization) conv1d_1 (Conv1D) (None, 8192, 4) 164 conv1d_2 (Conv1D) (None, 8192, 8) 168 batch_normalization_1 (Batc (None, 8192, 8) 32 hNormalization) conv1d_3 (Conv1D) (None, 8192, 8192) 335872 ================================================================= Total params: 336,316 Trainable params: 336,284 Non-trainable params: 32 </code></pre> <p>Basically, I want an autoencoder that takes a vector of 8192 values and try to predict an another vector of 8192 values.</p> <p>but when I do an inference like that:</p> <pre><code>predictions = autoencoder.predict(batch_data, batch_size=BATCH_SIZE) </code></pre> <p>I've that shape:</p> <pre><code>&gt;&gt;&gt; predictions[0].shape (8192,8192) </code></pre> <p>What I'm doing wrong ? what can I change to get a vector with (8192) ?</p>
<python><tensorflow><keras><autoencoder>
2023-03-09 11:30:36
1
2,945
snoob dogg
75,683,944
1,029,433
Pass custom parameters in locust
<p>Actually, I am in a case study and I would like to use Locust for load testing.</p> <p>As an input, I have a csv file that contains as columns the datetime, number of users and other variable parameters that should be used for each post request as query parameters:</p> <pre><code>datetime,rps,param1,param2 2022-09-18 00:00:00,5,1000,2000 2022-09-18 00:01:00,10,500,1000 </code></pre> <p>I have this following class that I am able to read the CSV file and prepare the stages required for tick function:</p> <pre><code>class StagesShape(LoadTestShape): </code></pre> <p>And in the other hand, I have HttpUser instance that will run the post request:</p> <pre><code>class UserInstance(HttpUser): </code></pre> <p>I would like to know how to pass the param1 and param2 from <code>StagesShape</code> class to <code>UserInstance</code> class that will be used to be added in the header of the post request. By the way, the params are not static and they could be different for each stage.</p>
<python><load-testing><locust>
2023-03-09 11:24:34
2
3,096
kaissun
75,683,934
13,372,881
'float' object has no attribute 'rint'
<p>All the cells of DataFrame are of float type but still it is not able to round off.</p> <p><strong>DataFrame</strong></p> <p><a href="https://i.sstatic.net/CbaeX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CbaeX.png" alt="enter image description here" /></a></p> <p><strong>Dtype</strong> <a href="https://i.sstatic.net/Lr0LN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Lr0LN.png" alt="enter image description here" /></a></p> <p>I am doing this:</p> <pre><code>df_lmsd['LMSD']=np.around(df_lmsd['LMSD'],2) df_lmsd['LMSD(#)']=np.around(df_lmsd['LMSD(#)'],2) df_lmsd </code></pre> <p>Output:- <a href="https://i.sstatic.net/1aTu3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1aTu3.png" alt="enter image description here" /></a></p> <p>Python Version:- Python 3.10.9 Ide:- Jupyter Notebook</p>
<python><pandas><dataframe><rounding>
2023-03-09 11:23:37
2
1,027
Mridul Bagla
75,683,863
16,389,095
Bleak - Python Bluetooth library: RuntimeError asyncio.run() cannot be called from a running event loop
<p>I'm trying to use <em>Bleak</em> , a Python library for Bluetooth devices management. Starting from an <a href="https://pypi.org/project/bleak/#description" rel="nofollow noreferrer">example</a> of use to find active Bluetooth devices</p> <pre><code>import asyncio from bleak import BleakScanner async def main(): devices = await BleakScanner.discover() for d in devices: print(d) asyncio.run(main()) </code></pre> <p>I get a</p> <pre><code>File &quot;C:\Users\ \Desktop\Python_BLE.py&quot;, line 25, in &lt;module&gt; asyncio.run(main()) File &quot;C:\Users\ \Miniconda3\lib\asyncio\runners.py&quot;, line 34, in run &quot;asyncio.run() cannot be called from a running event loop&quot;) RuntimeError: asyncio.run() cannot be called from a running event loop </code></pre> <p>I'm running it on <em>Spyder 5.2.2</em> with <em>Python 3.7.10</em>.</p>
<python><python-3.x><bluetooth-lowenergy><python-asyncio><spyder>
2023-03-09 11:17:18
0
421
eljamba
75,683,849
5,016,028
Compute time differences in Pandas dataframe with respect to first value
<p>I have a question that looks somewhat similar to [this one][1], however I don't know how to modify the answer given there to fit my problem.</p> <p>I have a dataframe that looks like this:</p> <pre><code>Date user 2012-12-05 09:30:00 0 2012-12-05 09:35:00 1 2012-12-05 09:40:00 2 2012-12-05 09:45:00 3 2012-12-05 09:50:00 4 2012-12-06 09:30:00 5 2012-12-06 09:35:00 6 2012-12-06 09:40:00 7 2012-12-06 09:45:00 8 </code></pre> <p>and I want to compute the relative time differences between users 1, 2, 3... and user 0. This value should be added in a third column (preferably in seconds). So in this example, the result should be:</p> <pre><code>Date user diff 2012-12-05 09:30:00 0 0 2012-12-05 09:35:00 1 300 2012-12-05 09:40:00 2 600 2012-12-05 09:45:00 3 900 2012-12-05 09:50:00 4 1200 2012-12-06 09:30:00 5 1500 2012-12-06 09:35:00 6 1800 2012-12-06 09:40:00 7 2100 2012-12-06 09:45:00 8 2400 </code></pre> <p>I am looking at the answer provided but I don't think I can use <code>group_by</code> here. I am a bit stuck. [1]: <a href="https://stackoverflow.com/questions/40104449/pandas-calculating-daily-differences-relative-to-earliest-value">Pandas - Calculating daily differences relative to earliest value</a></p>
<python><python-3.x><pandas><dataframe><group-by>
2023-03-09 11:16:06
2
4,373
Qubix
75,683,804
2,693,551
How many calendar days elapsed since given date?
<p>I need to find how many calendar days elapsed sice given date. When I use the following, it gives me -1 even when the date is today:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; t = datetime.fromisoformat('2023-03-09 08:55:11') &gt;&gt;&gt; (t - datetime.today()).days -1 </code></pre> <p>Whereas the correct answer should be 0.</p> <p>If I ask at <code>00:00:01</code>, and the date was yesterday at <code>23:59:59</code>, it should give me 1 day. But anything today should be 0.</p> <p>How can I do that?</p>
<python>
2023-03-09 11:11:08
3
587
Martin Vegter
75,683,654
7,800,760
Assign unique ID to mixed list of strings and substrings
<p>I have a list of dictionaries of strings (eg people names) which are either complete or just fragments:</p> <pre><code>names = [ {&quot;text&quot;: &quot;Alice&quot;}, {&quot;text&quot;: &quot;Bob&quot;}, {&quot;text&quot;: &quot;Bob Ross&quot;}, {&quot;text&quot;: &quot;Twain&quot;}, {&quot;text&quot;: &quot;Ross&quot;}, {&quot;text&quot;: &quot;Alice Twain&quot;}, {&quot;text&quot;: &quot;Alice&quot;}, {&quot;text&quot;: &quot;Charles&quot;}, ] </code></pre> <p>and would like to add an id to each dictionary unique to each string, irrespective of whether full or fragment.</p> <p>I have written a small function to sort the list of strings in descending length order:</p> <pre><code>def sortlen(lst): lst.sort(key=len, reverse=True) return lst </code></pre> <p>therefore:</p> <pre><code>print(sortlen([name[&quot;text&quot;] for name in names])) </code></pre> <p>would yield:</p> <pre><code>['Alice Twain', 'Bob Ross', 'Charles', 'Alice', 'Twain', 'Alice', 'Ross', 'Bob'] </code></pre> <p>What I would like to end up with, given the above example, is the following:</p> <pre><code>names = [ {&quot;text&quot;: &quot;Alice&quot;, &quot;id&quot;: 2}, {&quot;text&quot;: &quot;Bob&quot;, &quot;id&quot;: 1}, {&quot;text&quot;: &quot;Bob Ross&quot;, &quot;id&quot;: 1}, {&quot;text&quot;: &quot;Twain&quot;, &quot;id&quot;: 2}, {&quot;text&quot;: &quot;Ross&quot;, &quot;id&quot;: 1}, {&quot;text&quot;: &quot;Alice Twain&quot;, &quot;id&quot;: 2}, {&quot;text&quot;: &quot;Alice&quot;, &quot;id&quot;: 2}, {&quot;text&quot;: &quot;Charles&quot;, &quot;id&quot;: 3}, ] </code></pre> <p>Not sure which algorithm/code to apply to the descending length list of strings.</p>
<python>
2023-03-09 10:57:51
0
1,231
Robert Alexander
75,683,607
21,244,591
Multiple object returns from method not acting as expected
<p>While playing around with <code>pyautogui</code> I decided to make a method to limit the position of my cursor depending on the size of my monitor, since I was moving my cursor randomy.</p> <p>This is what my first attempt looked like.</p> <pre><code>max_x = 10 max_y = 40 def limitXandY(x_arg, y_arg): # expected to outputs a tuple of integers with length 2 return x_arg, y_arg if x_arg &lt; max_x and y_arg &lt; max_y else max_x, max_y </code></pre> <p>When running the code I did not get the expected output.</p> <pre><code>print(limitXandY(5, 19)) # (5, 19, 40) =&gt; (x_arg, y_arg, max_y) x, y = limitXandY(5, 19) # ValueError: too many values to unpack (expected 2) print(limitXandY(50, 100)) # (50, 10, 40) =&gt; (x_arg, max_x, max_y) x, y = limitXandY(50, 100) # ValueError: too many values to unpack (expected 2) </code></pre> <p>As you can see above, my method returns a tuple of length 3 instead of 2. If the ternary operator goes in the if statement, I get the desired output plus last value of the else statement and if the operator returns in the else statement, I get the first value of the if statement as the first value of the methods output tuple.</p> <p>I have found a work around using parentheses, but this doesn't really satisfy me and I would like to understand why this ternary operator acts like this.</p> <pre><code>def correctedLimitXandY(x_arg, y_arg): # expected to output a tuple of tuple with length 1 # inner tuple should containt integers of length 2 return (x_arg, y_arg) if x_arg &lt; max_x and y_arg &lt; max_y else (max_x, max_y) print(correctedLimitXandY(5, 19)) # (5, 19) =&gt; (x_arg, y_arg) x, y = correctedLimitXandY(5, 19) # no error print(correctedLimitXandY(50, 100)) # (10, 40) =&gt; (max_x, max_y) x, y = correctedLimitXandY(50, 100) # no error </code></pre> <p>Any explanations would be a help!</p>
<python><methods><conditional-operator><pyautogui><multiple-return-values>
2023-03-09 10:53:00
2
366
Olivier Neve
75,683,529
1,137,043
major gridlines with LogLocator behave incorrectly?
<p>I am trying to mark the major gridlines of a <code>semilogx</code> plot with thicker lines. However, the code below (SSCCE) only highlights every second gridline.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLocator, LogLocator) # configuration xValues = [0.1, 1, 10, 100, 1e3, 10e3, 100e3, 1e6, 10e6, 100e6] yValues = [-70, -95, -135, -165, -175, -180, -180, -180, -180, -180] # plot fig = plt.figure(1, figsize=[10, 5], dpi=150) ax = fig.subplots(1,1) plt.semilogx(xValues, yValues) plt.minorticks_on() ax.yaxis.set_major_locator(MultipleLocator(10)) ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.xaxis.set_major_locator(LogLocator(base=10.0)) ax.xaxis.set_minor_locator(LogLocator(base=10.0,subs=(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9),numticks=72)) plt.grid(True, axis='both', which='major', linestyle=&quot;-&quot;, linewidth=0.8, color=(0.6, 0.6, 0.6)) plt.grid(True, axis='both', which='minor', linestyle=&quot;-&quot;, linewidth=0.5, color=(0.9, 0.9, 0.9)) plt.tight_layout() plt.show() </code></pre> <p>Is there a good way to achieve what I want? (In the plot, you can see that the x axis only hightlights every second decade instead of every decade). Since the axis labels are also on different heights, I believe the reason is that the major gridlines are incorrect?</p> <p><a href="https://i.sstatic.net/GfDaD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GfDaD.png" alt="plot of code example above" /></a></p>
<python><matplotlib><plot><gridlines>
2023-03-09 10:45:56
1
9,562
brimborium
75,683,479
8,176,763
airflow best way to handle async function as task
<p>I have a dag like this:</p> <pre><code>from datetime import timedelta import pendulum from airflow.decorators import dag from stage import stage_data from table_async_pg import merge_data @dag( dag_id = &quot;data-sync&quot;, schedule_interval = &quot;1 * * * *&quot;, start_date=pendulum.datetime(2023, 3, 8, tz=&quot;Asia/Hong_Kong&quot;), catchup=False, dagrun_timeout=timedelta(minutes=20), ) def Pipeline(): a = stage_data() b = merge_data() a &gt;&gt; b pipeline = Pipeline() </code></pre> <p><code>merge_data</code> is an async function that looks like that:</p> <pre><code>import psycopg from config import config import asyncio from airflow.decorators import task URI = f'postgresql://{config.USER_PG}:{config.PASS_PG}@{config.HOST_PG}:{config.PORT_PG}/{config.DATABASE_PG}' @task async def merge_data(): try: async with await psycopg.AsyncConnection.connect(URI,autocommit=True) as aconn: async with aconn.cursor() as cur: await cur.execute(&quot;&quot;&quot; TRUNCATE TABLE host CASCADE &quot;&quot;&quot;) return 0 except Exception as e: return 1 </code></pre> <p>I think it's not valid to return a coroutine so I wrapped into a try exception block to return 0 or 1.However I still get the error message:</p> <pre><code> CLASSNAME: o.__module__ + &quot;.&quot; + o.__class__.__qualname__, AttributeError: 'coroutine' object has no attribute '__module__' sys:1: RuntimeWarning: coroutine 'merge_data' was never awaited </code></pre>
<python><airflow>
2023-03-09 10:41:36
1
2,459
moth
75,683,474
2,258,600
In python, why does select.select require that I sleep in a loop?
<p>I was writing a socket server. In the while loop,</p> <pre class="lang-python prettyprint-override"><code>while True: rlist, wlist, _ = select.select([sock], [sock], []) for rsock in rlist: new_data = rsock.recv(RCV_SIZE) for wsock in wlist: wsock.send(other_data + TERMINATOR) time.sleep(0.1) </code></pre> <p>I noticed that when I exclude the time.sleep function, no data would come in. Why is this the case?</p>
<python><sockets><event-loop>
2023-03-09 10:41:18
0
546
possumkeys
75,683,386
6,498,757
Python sys.argv and argparser conflict
<p>I'm trying to mixed-use both argument handlers but failed. Python doesn't allow me to do so or do there exist some ways to handle mixed usage?</p> <pre class="lang-py prettyprint-override"><code>import argparse import sys # Define an argparse parser parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help') # Parse the arguments using argparse args = parser.parse_args() # Access the value of --foo from argparse if args.foo: print(f'--foo is set to {args.foo}') # Access the value of sys.argv if len(sys.argv) &gt; 1: print(f'The first positional argument is {sys.argv[1]}') </code></pre> <p>my running result:</p> <pre><code># this one ok! python foo.py &quot;asdasd&quot; usage: foo.py [-h] [--foo FOO] foo.py: error: unrecognized arguments: asdasd # this one fail! python foo.py --foo &quot;asdasd&quot; --foo is set to asdasd The first positional argument is --foo </code></pre>
<python><python-3.x>
2023-03-09 10:33:39
1
351
Yiffany
75,683,345
5,994,014
scikit-learn documentation example: 'got an unexpected keyword argument'
<p>When running <a href="https://scikit-learn.org/stable/modules/clustering.html#homogeneity-completeness-and-v-measure" rel="nofollow noreferrer">this example</a> from the scikit-learn documentation, I get the error <code>v_measure_score() got an unexpected keyword argument 'beta'</code>:</p> <pre><code>from sklearn import metrics labels_true = [0, 0, 0, 1, 1, 1] labels_pred = [0, 0, 1, 1, 2, 2] metrics.v_measure_score(labels_true, labels_pred, beta=0.6) </code></pre> <p>It looks like a bug in sklearn.metrics... Any insights?</p>
<python><scikit-learn><unsupervised-learning>
2023-03-09 10:30:04
1
598
NRLP
75,683,306
2,135,504
Why does tf.train.FloatList have rounding errors?
<p>The following code shows that when converting a python float to a <code>tf.train.FloatList</code>, then we lose precision. My understanding was that both native python <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord#setup" rel="nofollow noreferrer">and tensorflow</a> store it as float64. So why the difference?</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf x =2.3 lst = tf.train.FloatList(value=[x]) reloaded = lst.value[0] # 2.299999952316284 </code></pre>
<python><tensorflow><tfrecord>
2023-03-09 10:26:44
1
2,749
gebbissimo
75,683,209
5,510,540
python: sorting time interval data into two days chucks based on index event
<p>I have the following data:</p> <pre><code>df = id date_medication medication index_date 1 2000-01-01 A 2000-01-04 1 2000-01-02 A 2000-01-04 1 2000-01-05 B 2000-01-04 1 2000-01-06 B 2000-01-04 2 2000-01-01 A 2000-01-05 2 2000-01-03 B 2000-01-05 2 2000-01-06 A 2000-01-05 2 2000-01-10 B 2000-01-05 </code></pre> <p>and I would like to transform the data into two days' chucks around the index event (IE). That is creating new columns representing the time intervals such as:</p> <pre><code>df = id -4 -2 0 2 4 6 1 A A IE B 0 0 2 A B IE A A B </code></pre>
<python><pandas>
2023-03-09 10:17:19
2
1,642
Economist_Ayahuasca
75,683,133
3,386,779
Read the content of the file A and match with another file Example.html in given folder and rename the it with Example.html
<p>I have the folder A and Folder B and want to compare the file content in folder A with Folder B files .If the topictitle1 matches rename it with matching file name which is in Folder B.I have the output folder which I created manually to dump the renamed files</p> <p>Folder A 01.html 02.html 03.html</p> <p>Folder B Test1.html Test2.html Test3.html</p> <h2>01.html and Test3.html File content common lines [Need to rename 01.html as Test3.html in output folder]</h2> <p>First line</p> <p>second line</p> <h2>02.html and Test2.html [Need to rename 02.html as Test2.html in output folder]</h2> <p>First line2</p> <p>second line 2</p> <h2>03.html and Test1.html [Need to rename 01.html as Test1.html in output folder]</h2> <p>First line3</p> <p>Second Line3</p> <p>Now comparing two files and copy the file to output folder</p> <pre><code>import os import shutil hosts_filename = 'folderA/01.html' logs_filename = 'folderB/Test3.html' with open(hosts_filename, 'r') as f: hosts = f.read() hostSoup = BeautifulSoup(hosts , 'lxml') hostSoupS=hostSoup.select('h1.topictitle1') #print (hostSoupS) with open(logs_filename, 'r') as f: lines = f.read() lineSoup = BeautifulSoup(lines , 'lxml') lineSoupS=lineSoup.select('h1.topictitle1') #print(lineSoupS) for line in lineSoupS : for host in hostSoupS : if host == line: dest = shutil.copy(hosts_filename, &quot;output/given_name.html&quot;) </code></pre>
<python><html><file>
2023-03-09 10:10:45
0
7,263
user3386779
75,683,130
1,652,954
How to run .sh file from console
<p>I would like to know why I can not run the <code>.sh</code> file via <code>./launch.sh</code> please have a look at the below posted screen-shot</p> <p><strong>image</strong></p> <p><a href="https://i.sstatic.net/KiGPE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KiGPE.png" alt="enter image description here" /></a></p>
<python><powershell><shell>
2023-03-09 10:10:10
3
11,564
Amrmsmb
75,682,987
12,023,442
Why does sys.getsizeof fail on a pandas series or data frame when they hold a type
<p>Python getsizeof fails on a series which holds a type as data , I have function in which I need to calculate the size of any given argument which I do with getsizeof. But this is an issue as getsizeof fails unexpectedly for these kind of dataframes. Is there a way to avoid this failure in <code>getSizeof</code></p> <pre><code>import sys df=pd.Series(str) sys.getsizeof(df) </code></pre> <pre><code>TypeError: descriptor '__sizeof__' of 'str' object needs an argument </code></pre>
<python><python-3.x><pandas><sizeof>
2023-03-09 09:58:49
2
2,254
ArunJose
75,682,803
13,994,829
How to fix Excel COM error cause by Python xlwings?
<p>The first time I use xlwing, I can get result successfully.</p> <p>But when choose different <code>.xlsx</code> file, I get error.</p> <p>I have try to shut down <code>EXCEL.EXE</code> in <code>taskman</code>, but not work still.</p> <h3>Code</h3> <pre class="lang-py prettyprint-override"><code>from PIL import ImageGrab import xlwings as xw import time excel_path = &quot;file.xlsx&quot; sheet_name = &quot;sheet1&quot; img_path = &quot;test.png&quot; app = xw.App(visible=False, add_book=False) wb = app.books.open(excel_path) sheet = wb.sheets(sheet_name) all = sheet.used_range all.api.CopyPicture() sheet.api.Paste() pic = sheet.pictures[-1] pic.api.Copy() time.sleep(3) img = ImageGrab.grabclipboard() img.save(img_path) pic.delete() wb.save(excel_path) wb.close() app.quit() </code></pre> <h3>Result</h3> <p><code>com_error: (-2147417851, 'The server threw an exception。', None, None)</code></p> <ul> <li>I think this is because i <strong>didn't release the com object.</strong> (I should use <code>app.kill()</code> instead of <code>app.quit()</code>)</li> <li>But now, I cannot solve this problem, I have try to shut down and restart computer...</li> <li>Hope someone can help me or tell me how to fix.</li> <li>Besides, I convert to use first time <code>.xlsx</code> file work withour any error, but other file not work.</li> </ul>
<python><excel><windows><com><xlwings>
2023-03-09 09:43:55
0
545
Xiang
75,682,800
17,220,672
Python Protocol error: Incompatible types in "yield" (actual type "Type[Foo]", expected type "FooProtocol")
<p>Lets say I have a class &quot;Foo&quot; and class &quot;Database&quot;. &quot;Database&quot; class provides connection engine, sessions and other related db stuff. Foo class intantiates this class (and some other attributes). &quot;Foo&quot; acts like some context class for entire application, but that does not matter for this question.</p> <pre><code>from some_module import Database class Foo: bar: str = &quot;some string&quot; database: Database = Database(&quot;target_database_url&quot;) </code></pre> <p>If I create a protocol class that should represent the type of Foo class:</p> <pre><code>class FooType(Protocol): bar: str database: Database </code></pre> <p>And somewhere later in my code I have a pytest fixture. Basically I can not add Foo in &quot;-&gt; Generator[Foo,None,None]&quot; because Foo needs to be imported (does not matter why) inside the fixture.</p> <pre><code>@pytest.fixture(autouse=False, scope=&quot;session&quot;) def foo_fixture() -&gt; Generator[FooType,None,None]: #I can not import this at the top, but this is not the issue for this question. from some_other_module import Foo yield Foo </code></pre> <pre><code>I get this error: Only class variables allowed for class object access on protocols, database is an instance variable of &quot;Foo&quot; </code></pre> <p>Can someone help? Thanks</p>
<python><pytest><protocols><python-typing>
2023-03-09 09:43:52
1
419
mehekek
75,682,481
13,443,954
Expect value of a dropdown select based on option text
<p>We have a dropdown select</p> <pre><code>&lt;select id=&quot;favorite-colors&quot; multiple&gt; &lt;option value=&quot;R&quot;&gt;Red&lt;/option&gt; &lt;option value=&quot;G&quot;&gt;Green&lt;/option&gt; &lt;option value=&quot;B&quot;&gt;Blue&lt;/option&gt; &lt;/select&gt; </code></pre> <p>In playwright we can use to check the value</p> <pre><code>expect(locator).to_have_values([re.compile(r&quot;R&quot;), re.compile(r&quot;G&quot;)]) </code></pre> <p>See: <a href="https://playwright.dev/python/docs/api/class-locatorassertions#locator-assertions-to-have-values" rel="nofollow noreferrer">https://playwright.dev/python/docs/api/class-locatorassertions#locator-assertions-to-have-values</a></p> <p>But how can I use the expect to check if the selection is &quot;Red&quot; or &quot;Green&quot; or &quot;Blue&quot; - so instead of the value (R, G, B), base on the text of the options We do not have indicator for &quot;selected&quot; - how should I expect if an option selected?</p>
<python><pytest><playwright><playwright-python>
2023-03-09 09:10:18
2
333
M András
75,682,411
3,560,215
How to write multi-line Python script block in GitLab pipeline using a YAML file
<p>The following script block works perfectly for me when run as a simple Python script from VSCode.</p> <pre><code> d = {'A':123, 'B':456, 'C':789, 'D':222} for key, value in d.items(): print(f'{key} {value}') </code></pre> <p>However, I'm desperate to replicate this in a GitLab pipeline and considered whether something along the lines of what I have depicted below, could do the trick in my .gitlab-ci.yml file.</p> <p>So far, all attempts have proved unsuccessful. Any ideas or suggestions on how I can get this to work, or even an alternative approach that would equally work? My actual intended implementation will be for a slightly more extensive block of code, but any working solution proposed here would be the perfect building block to get that up and running for sure.</p> <pre><code>default: image: name: python:latest entrypoint: [&quot;&quot;] before_script: - python -m pip install --upgrade pip stages: - test_1 variables: OUTPUTFILE: 'testoutput.txt' test_multiline_script_block: stage: test_1 image: name: python:latest script: - | d = {'A':123, 'B':456, 'C':789, 'D':222} for key, value in d.items(): print(f'{key} {value}') </code></pre> <p>NB: So, just for the sake of clarity, let me perhaps elaborate a bit on what I'm seeking to implement.</p> <p>Using a loop function, I want to be able to iterate through a key-value pair list and for each key/value pair obtained, I'll pass them into a python script as two arguments, e.g. <code>python3 myscript.py $key $value</code>. This python script is executed from my .gitlab-ci.yml file.</p> <p>My key-value pair list could be stored in an external file, e.g. kv_list.txt, be initialised as a variable in my .gitlab-ci.yml file, or be stored in any other format for that matter. The key thing is that I should be able to read the list and pass each key/value pair into my python script.</p>
<python><gitlab-ci><codeblocks><gitlab-ci.yml>
2023-03-09 09:04:04
0
971
hitman126
75,682,388
13,174,189
How to merge two data frames and keep not all matches?
<p>there are 2 dataframes: d1:</p> <pre><code>id city position 1 NY manager 2 NY manager 3 NY manager 4 NY Engineer 5 LA Engineer 6 LA Designer </code></pre> <p>d2:</p> <pre><code>team city position a NY manager a NY manager b NY Engineer b LA Engineer </code></pre> <p>I need to left join d1 and d2 by &quot;city&quot; and &quot;position&quot;, but i don't want to keep all matches. d1's shape should not change. but when i do this:</p> <pre><code>d1.merge(d2, how = &quot;left&quot;, on = [&quot;city&quot;, &quot;position&quot;]) </code></pre> <p>I get all possible matches, but what i need is to select some of them and keep d1's shape same</p> <p>so desired result is:</p> <pre><code>team city position id a NY manager 1 a NY manager 2 b NY Engineer 4 b LA Engineer 5 </code></pre> <p>and df1 must be updated and become like this:</p> <pre><code>id city position 3 NY manager 6 LA Designer </code></pre> <p>how could I do it? thanks in advance</p>
<python><python-3.x><dataframe><merge>
2023-03-09 09:02:00
2
1,199
french_fries
75,682,376
8,309,065
scrapy run thousands of instance of the same spider
<p>I have the following task: in the DB we have ~2k URLs. for each URL we need to run spider until all URLs will be processed. I was running spider for a bunch of URLs (10 in one run)</p> <p>I have used the following code:</p> <pre class="lang-py prettyprint-override"><code>from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings URLs = crawler_table.find(crawl_timestamp=None) settings = get_project_settings() for i in range(len(URLs) // 10): process = CrawlerProcess(settings) limit = 10 kount = 0 for crawl in crawler_table.find(crawl_timestamp=None): if kount &lt; limit: kount += 1 process.crawl( MySpider, start_urls=[crawl['crawl_url']] ) process = CrawlerProcess(settings) process.start() </code></pre> <p>but it is running only for the first loop. for the second I have the error:</p> <pre><code> File &quot;C:\Program Files\Python310\lib\site-packages\scrapy\crawler.py&quot;, line 327, in start reactor.run(installSignalHandlers=False) # blocking call File &quot;C:\Program Files\Python310\lib\site-packages\twisted\internet\base.py&quot;, line 1314, in run self.startRunning(installSignalHandlers=installSignalHandlers) File &quot;C:\Program Files\Python310\lib\site-packages\twisted\internet\base.py&quot;, line 1296, in startRunning ReactorBase.startRunning(cast(ReactorBase, self)) File &quot;C:\Program Files\Python310\lib\site-packages\twisted\internet\base.py&quot;, line 840, in startRunning raise error.ReactorNotRestartable() twisted.internet.error.ReactorNotRestartable </code></pre> <p>is there any solution to avoid this error? and run spider for all 2k URLs?</p>
<python><scrapy><twisted>
2023-03-09 09:01:14
1
1,943
Roman
75,682,363
12,536,540
Using numpy in sklearn FunctionTransformer inside pipeline
<p>I'm training a regression model and inside my pipeline I have something like this:</p> <pre><code>best_pipeline = Pipeline( steps=[ ( &quot;features&quot;, ColumnTransformer( transformers=[ ( &quot;area&quot;, make_pipeline( impute.SimpleImputer(), pr.FunctionTransformer(lambda x: np.log1p(x)), StandardScaler(), ), [&quot;area&quot;], ) ] ), ), ( &quot;regressor&quot;, TransformedTargetRegressor( regressor=model, transformer=PowerTransformer(method='box-cox') ), ), ] ) </code></pre> <p>There are obviously more features but the code will be too long. So I train the model and if I predict in the same script everything is fine. I store the model using dill and then try to use it in another python file.</p> <p>In this other file I load the model and try this:</p> <pre><code>import numpy as np df['prediction'] = self.model.predict(df) </code></pre> <p>And internally, when it tries to do the <code>transform</code> it returns:</p> <pre><code>NameError: name 'np' is not defined </code></pre>
<python><numpy><scikit-learn><dill>
2023-03-09 09:00:10
2
992
sergiomahi
75,682,355
6,550,894
Pandas: combination with highest coverage
<p>In a supermarket I selected 30 products on which we want to run an analysis. I want to see which 12 of them give me the widest coverage of clients (on a specific date, no time involved).</p> <p>This means that I have 30!/(12!(30-12)!) = 86493225 combinations of products</p> <p>My pandas dataframe of clients purchases:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Client</th> <th>Product</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>Banana</td> </tr> <tr> <td>B</td> <td>Apple</td> </tr> <tr> <td>B</td> <td>Banana</td> </tr> <tr> <td>C</td> <td>Water</td> </tr> <tr> <td>...</td> <td></td> </tr> </tbody> </table> </div> <p>now I could iterate to see the combination of highest client count, creating them all first with itertools</p> <pre><code>comb = set(itertools.combinations([banana,...], 12)) d = {} for i in comb: d[i] = df[df.product.isin(i)].Client.nunique() </code></pre> <p>but this will take a spectacular amount of time.</p> <p>do you guys see any better way to count this out?</p> <p>please note that I do not want to find the combination of 12 most common products, but the combination that will yield the most clients (possibly the same but not necessarily, as 2 products not individually common may yield more clients if the 2 groups don't overlap much).</p> <p>any thoughts?</p> <p>thank you</p>
<python><pandas>
2023-03-09 08:59:32
1
417
lorenzo
75,682,154
1,920,368
How to hint a custom overload decorator correctly?
<p>is there anyone knows how to overload hint like the default <code>overload.decorator</code> do?</p> <p>I have a custom working overload decorator, but <strong>cannot hint correctly</strong>.</p> <p>* the way to custom overload decorator for example</p> <ul> <li><a href="https://stackoverflow.com/questions/11371309/method-overloading-decorator">Method overloading decorator</a></li> </ul> <p>The reason behind doing this is because of :</p> <ul> <li>1: Default <code>overload.decorator</code> is only for decoration</li> <li>2: Alternative ways like <code>multipledispatch.dispatch</code> are not from standard library</li> </ul> <hr /> <p>For example, in vscode, the default @overload will hint like below</p> <pre><code>from typing import overload class Foo : @overload def bar( self , value : int ) -&gt; int : ... @overload def bar( self , value : str ) -&gt; str : ... </code></pre> <p><a href="https://i.sstatic.net/TKp7N.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TKp7N.jpg" alt="enter image description here" /></a></p> <hr /> <p>The custom overload decorator, however, will only display the last loaded method.</p> <pre><code>def custom_overload( * types ) : # logic to resolve callable ... class Foo : @custom_overload( int ) def bar( self , value : int ) -&gt; int : ... @custom_overload( str ) def bar( self , value : str ) -&gt; str : ... </code></pre> <p><a href="https://i.sstatic.net/fyyjz.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fyyjz.jpg" alt="enter image description here" /></a></p> <hr /> <p>How can I hint the decorated callable like the default <code>overload.decorator</code> do.</p> <p>Is it related to this?</p> <p><a href="https://stackoverflow.com/questions/48347628/how-to-document-python-functions-with-overload-dispatch-decorators">How to document Python functions with overload/dispatch decorators?</a></p> <p>Thank you for your advises.</p>
<python><overloading><decorator><python-decorators>
2023-03-09 08:40:00
1
4,570
Micah
75,681,976
376,929
Call downstream assets or ops in parallel with Dagster
<p>I build a data pipeline with Dagster using the <code>asset</code> API.</p> <p>I am looking for a way to explicitly call/execute an <code>asset</code> (or <code>op</code>) for a list of items. While <code>assets</code> are executed in parallel if they are independent, I did not find a way to include iteration.</p> <p>Simple example: Iterate over a list of files and perform a task for each file. The tasks are independent.</p> <pre class="lang-py prettyprint-override"><code>@asset def iterate_files(): path = Path(&quot;/some/path&quot;) for file in path.iterdir(): # here I would like to start parallel ops ... </code></pre> <p>If I pass a list to a downstream <code>asset</code>, the operation is performed sequentially:</p> <pre class="lang-py prettyprint-override"><code> @asset def list_of_files(): path = Path(&quot;/some/path&quot;) return list(path.iterdir()) @asset def process_files(list_of_files): for file in list_of_files): with open(file, 'rt') as f: for line in f: # write to a DB or other operation </code></pre> <p>Is it possible to achieve a parallel execution of the downstream task with Dagster?</p>
<python><dagster>
2023-03-09 08:20:00
0
9,369
Martin Preusse
75,681,743
5,575,597
How to plot selected columns of a Pandas dataframe using Bokeh 2.4.3
<p><strong>For future visitors: My original question was closed as a duplicate, but the old 'multiline' function in the linked answer is depreciated years ago.</strong></p> <p>I would like to plot a selection of pandas columns using bokeh, i.e. multiple lines in one chart. Code showing one column/line works:</p> <pre><code>import pandas as pd import numpy as np from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource df = pd.DataFrame(np.random.randint(0,100,size=(100, 5)), columns=list('ABCDF')) sss = ColumnDataSource(df) p = figure(height=300, width=300) x = df.index y = df[['B']] p.line(x, y) show(p) </code></pre> <p>Now, how do I plot columns A, C and F in the same line chart?</p> <p>I tried this, but does not work:</p> <pre><code>x = df.index y = df[['A', 'C', 'F']] p.line(x, y) show(p) </code></pre>
<python><pandas><bokeh>
2023-03-09 07:50:43
1
863
cJc
75,681,677
8,176,763
Airflow AttributeError: 'coroutine' object has no attribute 'update_relative'
<p>I have my dag as such:</p> <pre><code>from datetime import timedelta import pendulum from airflow.decorators import dag from stage import stage_data from table_async_pg import main @dag( dag_id = &quot;data-sync&quot;, schedule_interval = &quot;1 * * * *&quot;, start_date=pendulum.datetime(2023, 3, 8, tz=&quot;Asia/Hong_Kong&quot;), catchup=False, dagrun_timeout=timedelta(minutes=20), ) def Pipeline(): a = stage_data() b = main() a &gt;&gt; b pipeline = Pipeline() </code></pre> <p>When I don't include <code>b=main()</code> and <code>a&gt;&gt;b</code> everything works fine. If I include then I get this error:</p> <pre><code>/opt/airflow/dags/airflow_sched.py | Traceback (most recent call last): | File &quot;/opt/.venv/lib/python3.9/site-packages/airflow/models/taskmixin.py&quot;, line 230, in set_downstream | self._set_relatives(task_or_task_list, upstream=False, edge_modifier=edge_modifier) | File &quot;/opt/.venv/lib/python3.9/site-packages/airflow/models/taskmixin.py&quot;, line 175, in _set_relatives | task_object.update_relative(self, not upstream) | AttributeError: 'coroutine' object has no attribute 'update_relative' </code></pre>
<python><airflow>
2023-03-09 07:42:43
2
2,459
moth
75,681,570
17,580,381
Am I misunderstanding the Python documentation?
<p>Although not absolutely necessary, I thought it would be nice to have a multiprocessing Queue that I could use in the style of a Work Manager.</p> <p>This is what I wrote:</p> <pre><code>from multiprocessing import Queue class WMQueue(Queue): def __init__(self): super().__init__() def __enter__(self): return self def __exit__(self, *_): self.close() </code></pre> <p>This induces the following exception:</p> <pre><code>TypeError: method expected 2 arguments, got 3 </code></pre> <p>The reason is that multiprocessing.Queue is a method.</p> <p>However, the <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Queue" rel="nofollow noreferrer">documentation</a> for Queue is as follows:</p> <pre><code>class multiprocessing.Queue([maxsize]) </code></pre> <p>In fact, the Queue method returns an object of type <em>multiprocessing.queues.Queue</em> which, as I can't find any documentation for it, is probably unsafe to [try to] subclass.</p> <p>I know how I can re-write my class so that it could be used as WM but that's not the point. If Queue was a class, as documented, then I should be able to simply subclass it.</p> <p>Or am I misunderstanding Python documentation?</p>
<python>
2023-03-09 07:29:37
1
28,997
Ramrab
75,681,549
1,061,155
Use a pool of coroutine workers or one coroutine per task with Semaphore
<p>Suppose I have one million web pages to download. Should I use a fixed number of coroutine workers to download them, or create a coroutine per url and use <code>asyncio.Semaphore</code> to limit the numbers of coroutines.</p> <p>First option, fixed workers:</p> <pre class="lang-py prettyprint-override"><code>async def worker(queue): while True: try: url = queue.get_nowait() except QueueEmpty: break await download(url) async def main(): queue = asyncio.Queue() for url in urls: await queue.put(url) workers = [worker(queue) for _ in range(10)] await asyncio.wait(workers) asyncio.run(main()) </code></pre> <p>Second option, use semaphore:</p> <pre class="lang-py prettyprint-override"><code>async def worker(url, sema): async with sema: await download(url) async def main(): semaphore = asyncio.Semaphore(10) workers = [worker(url, semaphore) for url in urls] await asyncio.wait(workers) asyncio.run(main()) </code></pre>
<python><python-asyncio>
2023-03-09 07:27:29
1
10,551
ospider
75,681,345
12,135,668
Mark the end of the file in apache beam/dataflow streaming pipeline and ReadAllFromText
<p>Is there any option to achieve in apache beam/dataflow streaming mode (Python SDK) something like this:</p> <ul> <li>read from PubSub. Message will contain path to GCS file [Easy to do].</li> <li>read this file in parallel manner (ReadAllFromText) [Easy to do].</li> <li>Some DoFn transformation operating on single rows [Easy to do].</li> <li>Something that will tell me that this file has been finished. If file had 100 rows, after 100 rows I would like to see e.g. logging.info(&quot;File X is over, had 100 rows&quot;).</li> </ul> <p>I am not able to achieve this final point. The poor alternative is to use <code>GcsIO.open</code> to read GCS file inside some DoFn transformation, but this approach has no possibility to be parallelized.</p> <p>Any ideas appreciated.</p> <p>Edit: The reason of this is to achieve some kind of transnationality. I would like to have a control in the flow to for example:</p> <ul> <li>count valid and invalid rows in each file.</li> <li>once all rows of the file are uploaded somewhere, I would like to send pubsub message to other pipeline, for example:</li> </ul> <pre><code>{ &quot;filename&quot;: &quot;x&quot;, &quot;rows_valid&quot;: 100, &quot;rows_invalid&quot;: 44, &quot;rows_total&quot;: 1044 } </code></pre> <p>In this achievable?</p>
<python><streaming><google-cloud-dataflow><apache-beam>
2023-03-09 06:58:42
0
919
Pav3k
75,680,861
10,437,110
python equivalent for MATLABS vratiotest
<p>I am following the book <code>Algorithmic Trading</code> and I am on <code>Chapter 2: The Basics of Mean Reversion</code>.</p> <p>I have a few pairs and their close prices and I want to check the spread of which pair is mean-reverting.</p> <p>The book uses MATLAB for all its programming and I am using Python.</p> <p>First, there was a mention of <code>adf</code> function in MATLAB's package and its equivalent python code is:</p> <pre><code>from statsmodels.tsa.stattools import adfuller ad = adfuller(spread, maxlag = 1) </code></pre> <p>Then there is a mention of <code>cadf</code> and I think its equivalent python code is:</p> <pre><code>from statsmodels.tsa.stattools import coint t_statistic, p_value, crit_value = coint(x, y) </code></pre> <p>However, I cannot find the python equivalent for <code>MATLAB</code>'s <code>vratiotest</code>.</p> <p>Please let me know if there is a python function which performs same as <code>MATLAB</code>'s <code>vratiotest</code>.</p>
<python><matlab>
2023-03-09 05:50:04
1
397
Ash
75,680,658
10,466,809
Where to put a small utility function that I would like to use across multiple packages/projects that I develop?
<p>Right now I have <em>one</em> function that would be useful in a number of distinct packages that I work on. The function is only a handful of lines. But I would like to be able to use this code in a number of packages/projects that I work on and are deployed, I would like this code to be version controlled etc. There isn't, for example, one package that all the other packages already have as a requirement, otherwise I could put this code inside of that one and import it that way.</p> <p>During my time coding I've come across this issue a couple times. For concreteness some functions <code>f</code> that have this characteristic might be:</p> <ul> <li>A wrapper or context manager which times a block of code with some log statements</li> <li>A function which divides a range of integers into as small number of evenly spaced strides while not exceeding a maximum number of steps</li> <li>A function which converts a center value and a span into a lower and upper limit</li> </ul> <p>Basically the options I see are:</p> <ul> <li>Put the code <code>f</code> in one of the existing packages <code>R</code> and then make any package <code>A</code> that wants to use <code>f</code> have <code>R</code> as a requirement. The downside here is that <code>A</code> may require nothing from <code>R</code> other than <code>f</code> in which case most of the requirement is wasteful.</li> <li>Copy the code <code>f</code> into every package <code>A</code> that requires it. One question that comes up is then where should <code>f</code> live within <code>A</code>? Because the functionality of <code>f</code> is really outside the scope of package <code>A</code> does. This is sort of a minor problem, the bigger problem is that if an improvement is made to <code>f</code> in one package it would be challenging to maintain uniformity across multiple packages that have <code>f</code> in them.</li> <li>I could make an entire package <code>F</code> dedicated to functions like <code>f</code> and import it into each package that needs <code>f</code>. This seems like technically the best approach from a requirements management and separation of responsibility management perspective. But like I said, right now this would be an entire package dedicated to literally one function with a few lines of code.</li> <li>If there is a stdlib function that has the functionality I want I should definitely use that. If there is not, I may be able to find a 3rd party package that has the functionality I want, but this brings about a zoo of other potential problems that I'd prefer to avoid.</li> </ul> <p>What would be the suggested way to do this? Are there other approaches I haven't mentioned?</p>
<python><utility-method><requirements-management>
2023-03-09 05:12:56
1
1,125
Jagerber48
75,680,624
8,176,763
webserver ui shows dag import errors but dag still runs fine
<p>My webserver web UI shows import error messages:</p> <p><a href="https://i.sstatic.net/C0o3b.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/C0o3b.png" alt="enter image description here" /></a></p> <p>However my dags are running fine without error. What could be wrong here ??</p> <p><code>airflow info</code>:</p> <pre><code>Apache Airflow version | 2.5.1 executor | LocalExecutor task_logging_handler | airflow.utils.log.file_task_handler.FileTaskHandler sql_alchemy_conn | postgresql+psycopg2://airflow:xxx@localhost:25011/airflow dags_folder | /opt/airflow/dags plugins_folder | /opt/airflow/plugins base_log_folder | /opt/airflow/logs remote_base_log_folder | System info OS | Linux architecture | x86_64 uname | uname_result(system='Linux', node='hellothere', release='4.18.0-425.10.1.el8_7.x86_64', version='#1 SMP Wed Dec 14 16:00:01 EST 2022', machine='x86_64') locale | ('en_US', 'UTF-8') python_version | 3.9.13 (main, Nov 9 2022, 13:16:24) [GCC 8.5.0 20210514 (Red Hat 8.5.0-15)] python_location | /opt/.venv/bin/python Tools info git | git version 2.31.1 ssh | OpenSSH_8.0p1, OpenSSL 1.1.1k FIPS 25 Mar 2021 kubectl | NOT AVAILABLE gcloud | NOT AVAILABLE cloud_sql_proxy | NOT AVAILABLE mysql | NOT AVAILABLE sqlite3 | 3.26.0 2018-12-01 12:34:55 bf8c1b2b7a5960c282e543b9c293686dccff272512d08865f4600fb58238alt1 psql | psql (PostgreSQL) 14.7 Paths info airflow_home | /opt/airflow system_path | /opt/.venv/bin:/opt/.server/.vscode-server/bin/97dec172d3256f8ca4bfb2143f3f76b503ca0534/bin/remote-cli:/home/d5291029/.local/bin:/home/d5291029/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/puppetlabs/bin python_path | /opt/.venv/bin:/opt/airflow/dags/backend/src:/usr/lib64/python39.zip:/usr/lib64/python3.9:/usr/lib64/python3.9/lib-dynload:/opt/.venv/lib64/python3.9/site-packages:/opt/.venv/lib/python3.9/site-packages:/opt/airflow/dags:/opt/airflow/config:/opt/airflow/plugins airflow_on_path | True Providers info apache-airflow-providers-cncf-kubernetes | 5.2.1 apache-airflow-providers-common-sql | 1.3.3 apache-airflow-providers-ftp | 3.3.0 apache-airflow-providers-http | 4.1.1 apache-airflow-providers-imap | 3.1.1 apache-airflow-providers-sqlite | 3.3.1 </code></pre> <p>On top of that I tried to kill and relaunch everythin with <code>airflow standalone</code> and some process still hang there. But not sure this is helpful for the question:</p> <pre><code>dp-post+ 30859 0.0 0.1 3385112 22688 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34514) idle dp-post+ 30861 0.0 0.1 3385112 22396 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34540) idle dp-post+ 30863 0.0 0.2 3386700 29224 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34562) idle dp-post+ 30865 0.0 0.2 3385112 25216 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34582) idle dp-post+ 30867 0.0 0.2 3386700 29632 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34600) idle dp-post+ 30869 0.0 0.2 3385112 25476 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34618) idle dp-post+ 30895 0.0 0.2 3386840 30460 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34796) idle dp-post+ 30897 0.0 0.2 3386576 27120 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34816) idle dp-post+ 30901 0.0 0.2 3386688 28072 ? Ss 05:02 0:00 postgres: DHKPG00011: airflow airflow 127.0.0.1(34836) idle dp-post+ 49292 0.0 0.2 3385848 24976 ? Ss 05:22 0:00 postgres: DHKPG00011: airflow airflow 10.227.22.152(64509) idle d5291029 52202 0.0 0.0 12148 1152 pts/7 S+ 05:35 0:00 grep --color=auto airflow d5291029 53845 0.0 1.5 604964 189232 ? S Mar08 0:12 gunicorn: master [airflow-webserver] d5291029 63252 0.0 1.4 609168 173904 ? S Mar08 0:00 [ready] gunicorn: worker [airflow-webserver] d5291029 63253 0.0 1.4 609308 173920 ? S Mar08 0:00 [ready] gunicorn: worker [airflow-webserver] d5291029 63254 0.0 1.4 608260 172752 ? S Mar08 0:00 [ready] gunicorn: worker [airflow-webserver] d5291029 63255 0.0 1.4 607748 172436 ? S Mar08 0:00 [ready] gunicorn: worker [airflow-webserver] </code></pre>
<python><airflow>
2023-03-09 05:06:05
1
2,459
moth
75,680,488
10,339,757
Set variable column values to nan based on row condition
<p>I want to be able to variably change a column value based on the value of the first column.</p> <p>Say I have a dataframe as follows:</p> <pre><code>col_ind col_1 col_2 col_3 3 a b c 2 d e f 1 g h i </code></pre> <p>I effectively want to do</p> <pre><code>df.loc[:, df.columns[-df['col_ind']:]] = np.nan </code></pre> <p>Which would result in:</p> <pre><code>col_ind col_1 col_2 col_3 3 nan nan nan 2 d nan nan 1 g h nan </code></pre>
<python><python-3.x><pandas><slice>
2023-03-09 04:38:29
4
371
thefrollickingnerd
75,680,358
7,238,787
PyTorch data/wieght type mismatch event after calling tensor.to(torch.float)
<p>As title, how to solve the issue? OS: Ubuntu 16.04 Python version: 3.8 torch version: 1.10.1</p> <pre><code># Instantiate the neural network and optimizer net = InceptionNetModel() net.to(device) optimizer = optim.Adam(net.parameters(), lr=0.01) criterion = nn.BCELoss() # Train the neural network for epoch in range(500): net.train() iteration = 0 for batch_idx, (apc_batch, pump_batch, vent_batch, kpc_batch, dms_batch, info_batch, y_batch) in enumerate( train_tabular_dataloader): apc_batch, pump_batch, vent_batch, kpc_batch, dms_batch, info_batch, label_batch = \ apc_batch.to(device, torch.float64), pump_batch.to(device, torch.float64), vent_batch.to(device, torch.float64), kpc_batch.to(device, torch.float64), dms_batch.to(device, torch.float64), info_batch.to(device, torch.float64), y_batch.to(device, torch.float64) optimizer.zero_grad() y_pred = net(apc_batch, pump_batch, vent_batch, kpc_batch, dms_batch, info_batch) </code></pre> <p>returns error message:</p> <pre><code> File &quot;/home/user/anaconda3/lib/python3.8/site-packages/torch/nn/modules/conv.py&quot;, line 446, in forward return self._conv_forward(input, self.weight, self.bias) File &quot;/home/user/anaconda3/lib/python3.8/site-packages/torch/nn/modules/conv.py&quot;, line 442, in _conv_forward return F.conv2d(input, weight, bias, self.stride, RuntimeError: Input type (torch.cuda.DoubleTensor) and weight type (torch.cuda.FloatTensor) should be the same </code></pre>
<python><pytorch>
2023-03-09 04:07:38
0
521
jabberwoo
75,680,338
800,735
In Python ProcessPoolExecutor, do you need call shutdown after getting a BrokenProcessPool exception?
<p>In Python ProcessPoolExecutor, do you need call shutdown after getting a BrokenProcessPool exception?</p> <p>Say I have something like this:</p> <pre><code>pool = ProcessPoolExecutor(max_workers=1) try: return pool.submit( do_something, ).result() except concurrent.futures.process.BrokenProcessPool as pool_exc: pool = None return None </code></pre> <ul> <li>Is it a bad idea to just set <code>pool = None</code> do I need to call shutdown?</li> <li>What args should I use with shutdown? <code>pool.shutdown(wait=False, cancel_futures=True)</code>?</li> </ul>
<python><multiprocessing><python-multiprocessing><process-pool>
2023-03-09 04:04:15
1
965
cozos
75,680,321
13,710,421
In python/selenium, how to get Amazon web page item ratings information
<p>In python/selenium, I want to get the item star in Amazon web page, but failed .Anyone can help ? Thanks!</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option('excludeSwitches', ['enable-automation']) chrome_options.add_experimental_option(&quot;detach&quot;, True) prefs = { 'profile.default_content_setting_values': { 'images': 2, } } chrome_options.add_experimental_option('prefs', prefs) chrome_options.add_argument('lang=en') driver = webdriver.Chrome(options=chrome_options) driver.maximize_window() driver.get('https://www.amazon.com/dp/B09VDD8D8R') page_star = driver.find_element(By.CLASS_NAME,&quot;a-icon-alt&quot;) page_star_text = page_star.text # the wished result of page_star_text is &quot;4.1 out of 5 stars&quot; </code></pre> <p><a href="https://i.sstatic.net/CtNU6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CtNU6.png" alt="enter image description here" /></a></p>
<python><selenium-webdriver><web-scraping><css-selectors><webdriverwait>
2023-03-09 04:01:28
1
2,547
anderwyang
75,680,119
2,320,476
Validate data sent as a request in json
<p>I am working on a lambda code for an API in AWS. I am passing a json data within my body which is shown like this when I print my event within the lambda.</p> <pre><code> 'body': '{\r\n &quot;STTN&quot;: &quot;415263&quot;,\r\n &quot;Account&quot;: &quot;22568758&quot;\r\n}\r\n', </code></pre> <p>Here is how I am validating within the lambda</p> <pre><code> try: eventJson['body']['STTN'] except Exception: returnValidateConditional = False validationResponse['apiStatus'] = &quot;failed&quot; validationResponse['apiErrorCode'] =&quot;1&quot; validationResponse['apiDescription'] = &quot;STTN is required&quot; statusCode = 415 return [returnValidateConditional, validationResponse, statusCode] try: eventJson['body']['Account'] except Exception: returnValidateConditional = False validationResponse['apiStatus'] = &quot;failed&quot; validationResponse['apiErrorCode'] =&quot;1&quot; validationResponse['apiDescription'] = &quot;Account is required&quot; statusCode = 415 return [returnValidateConditional, validationResponse, statusCode] </code></pre> <p>My validation fails all the time despite the fact that STTN and Account are not empty. They have values that exist in the body request. All I get is STTN is required</p> <p>How can I validate json items in the body sent as a request?</p>
<python><json>
2023-03-09 03:13:27
2
2,247
Baba
75,680,056
7,995,293
Decorator causing my function to not accept positional argument?
<p>I am learning how to use decorators. Inspired by tqdm library (progress bars), I have cobbled together a decorator, heavily inspired by <a href="https://github.com/tqdm/tqdm/issues/458" rel="nofollow noreferrer">this</a> code. The goal is to use multithreading to have a progress indicator blink/spin/count in stdout while a long-running function that does not depend on iteration is in progress.</p> <p>The decorator is changing something about the function it wraps. <code>spendtime</code> should take one positional argument, an integer, passed to <code>sleep()</code>:</p> <pre><code>@progresswrapper(style=&quot;clock&quot;, msg=&quot;testing...&quot;) def spendtime(x): result = 'foobar' #dosomething sleep(x) return result #returnanything if __name__ == &quot;__main__&quot;: print(spendtime(2)) </code></pre> <p>But this throws a <code>TypeError: spendtime() takes 0 positional arguments but 1 was given.</code> When I comment out the decorator, <code>spendtime()</code> works as expected. When I make the following changes:</p> <pre><code>@progresswrapper(style=&quot;clock&quot;, msg=&quot;testing...&quot;) def spendtime(x=2): #### CHANGED TO KWARG result = 'foobar' #dosomething sleep(x) return result #returnanything if __name__ == &quot;__main__&quot;: print(spendtime()) ### RUNNING WITH NO INPUT </code></pre> <p>this code works too, but is not suitable; I want to be able to call spendtime() with an argument. In my work code, I intend to use this decorator on much more complex functions that take a whole range of args and kwargs.</p> <p>Why is the use of the decorator here causing this behaviour? Why am I seeing this <code>TypeError</code>?</p> <p>Full code:</p> <pre><code>import threading from itertools import cycle from time import sleep import functools # heavy inspiration from duckythescientist: https://github.com/tqdm/tqdm/issues/458 def monitor(func, style=&quot;clock&quot;, msg=None): &quot;&quot;&quot; print progress indicator to same line in stdout while wrapped function progresses &quot;&quot;&quot; styles = {&quot;clock&quot;:(0.1, ['-', '\\', '|', '/']), &quot;blink&quot;:(0.2, [u&quot;\u2022&quot;, ' ']), &quot;jump&quot;:(0.2, [u&quot;\u2022&quot;, '.']), &quot;ellipsis&quot;:(0.2, [&quot; &quot;, &quot;. &quot;, &quot;.. &quot;, &quot;...&quot;]), &quot;shuffle&quot;:(0.2, [u&quot;\u2022 &quot;, u&quot; \u2022&quot;]), &quot;counter&quot;:(1, (f&quot;{n:02}s&quot; for n in range(100))), } if style == &quot;counter&quot;: msg_pad = 10 else: msg_pad = len(styles[style][1][1]) + 7 if msg: msg = (&quot; &quot;*msg_pad) + msg # ensure that progress indocator doesn't overwrite msg print(f&quot;{msg}&quot;, end='\r') marker_cycle = cycle(styles[style][1]) # loop through list tstep = styles[style][0] ret = [None] def runningfunc(func, ret, *args, **kwargs): ret[0] = func(*args, **kwargs) thread = threading.Thread(target=runningfunc, args=(func, ret)) thread.start() while thread.is_alive(): thread.join(timeout=tstep) # call to runningfunc (?) print(f&quot; [ {next(marker_cycle)} ]&quot;, end='\r') print(&quot;done.\033[K&quot;) return ret[0] def progresswrapper(style, msg): def real_decorator(func): @functools.wraps(func) def wrapper(): return monitor(func, style=style, msg=msg) return wrapper return real_decorator @progresswrapper(style=&quot;clock&quot;, msg=&quot;testing...&quot;) def spendtime(x): result = 'foobar' #dosomething sleep(x) return result #returnanything if __name__ == &quot;__main__&quot;: print(spendtime(2)) </code></pre>
<python><typeerror><decorator><python-decorators>
2023-03-09 02:59:52
2
399
skytwosea
75,679,882
4,688,190
Python print every unique combination of list items
<p>What is the cleanest (most &quot;pythonic&quot;) way of printing every unique combination of three items in the following list?</p> <pre><code>strats = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;] </code></pre> <p>The solution needs to avoid duplicates:</p> <pre><code>1 and 1 and 1 No (not unique) 1 and 1 and 2 No (not unique) 1 and 1 and 3 No (not unique) ... 1 and 2 and 3 Yes 1 and 2 and 4 Yes 1 and 3 and 1 No (not unique) 1 and 3 and 2 No (occurred previously) ... </code></pre> <p>I am using numbers here just for clarity, the actual project involve text strings and there are 24 of them, but the same logic should apply.</p> <p>Here is my first attempt:</p> <pre><code>strats = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;] for a in strats: for b in strats: for c in strats: if a != b and a != c and b!=c: print(a+&quot; and &quot;+b+&quot; and &quot;+c) </code></pre> <p>The problem with the output is that it contains duplicates:</p> <pre><code>1 and 2 and 3 Fine 1 and 2 and 4 Fine 1 and 3 and 2 Duplicate 1 and 3 and 4 Fine 1 and 4 and 2 Duplicate 1 and 4 and 3 Duplicate ... </code></pre>
<python><scipy>
2023-03-09 02:17:40
1
678
Ned Hulton
75,679,869
1,610,626
Microsoft Tick time to Python Datetime
<p>There's a lot of answers to my question but mine is a little different in that I'm not entirely sure if its Microsoft's tick time. The situation is I'm receiving the following from my firms API and they've told me its tick time but it doesn't match with what I'm getting after using methods from SO to convert.</p> <p><a href="https://i.sstatic.net/Eu4Yt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Eu4Yt.png" alt="enter image description here" /></a></p> <pre><code> import datetime TICK_MASK = 4611686018427387903 _Datetime_nano_hundred_ticks = 5249825230441140085 print(datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds=TICK_MASK // 100)) print(datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds=_Datetime_nano_hundred_ticks // 100)) </code></pre> <p>As shown above, the actual time that they've converted for me is <code>2023-03-09 01:13:21</code> UTC but no idea how to convert given the above provided fields. My question is whether anyone have come across TICKS_MASK or _Datetime_nano_hundred_ticks and if so if they know how to convert it in python. Wonder if its a field from C# im not aware of. (i would ask my devs but thats a looooonnng story) I need to convert because I need higher granularity which supposedly converting will give me. Reasons unknown to me is why it gives me seconds granularity initially.</p>
<python><c#><.net>
2023-03-09 02:15:35
1
23,747
user1234440
75,679,839
19,425,874
Printing to local printer using Python but printer cannot be found
<p>I'm completely stuck trying to figure out why this code isn't working. I'm ultimately trying to print to the printer named &quot;Label Printer'. I can't seem to figure out why I cannot do it in Python, I've tested it out of Python and it's definitely connected and working.</p> <p>Does it need to be defined differently or something? Or is there a different way to connect?</p> <p>Any advice on connecting to a printer via python is greatly appreciated.</p> <p>My full code is below - this is what I want to update:</p> <pre><code>import gspread from oauth2client.service_account import ServiceAccountCredentials import win32print import tkinter as tk # Authenticate and open the Google Sheet creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']) client = gspread.authorize(creds) sheet = client.open_by_key( '1eRO-30eIZamB5sjBp-Mz2QMKCfGxV037MQO8nS7G7AI').worksheet('Label') class App(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.title('Porter\'s Label Printer') self.master.geometry('400x300') # Set the window size self.counter = 0 self.total_labels = int(sheet.acell('F2').value) self.create_widgets() self.update_counter() def create_widgets(self): self.print_button = tk.Button(self.master, text='Print Labels', command=self.print_labels, font=( 'Arial', 24), bg='lightblue', padx=40, pady=40) self.print_button.pack(fill=tk.BOTH, expand=True) self.counter_label = tk.Label(self.master, text='0 of {} labels printed'.format( self.total_labels), font=('Arial', 18)) self.counter_label.pack(pady=20) self.refresh_button = tk.Button(self.master, text='Refresh', command=self.refresh_labels, font=( 'Arial', 14), bg='lightgrey', padx=20, pady=10) self.refresh_button.pack(pady=20) def print_labels(self): for i in range(self.total_labels): win32print.SetDefaultPrinter('Label Printer') print_label_data = sheet.cell(sheet.find( 'Label').row, sheet.find('Label').col).value print(print_label_data) self.counter += 1 self.update_counter() def refresh_labels(self): try: self.total_labels = int(sheet.acell('F2').value) self.counter = 0 self.update_counter() self.print_button.config(state=tk.NORMAL) self.counter_label.config(fg='black') except ValueError: print('Error: could not convert F2 value to an integer') self.total_labels = 0 self.counter_label.config( text='Invalid number of labels!', fg='red') self.print_button.config(state=tk.DISABLED) def update_counter(self): if self.counter == self.total_labels: self.counter_label.config( text='All documents printed!', fg='green') self.print_button.config(state=tk.DISABLED) else: self.counter_label.config(text='{} of {} labels printed'.format( self.counter, self.total_labels)) # Authenticate and open the Google Sheet creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']) client = gspread.authorize(creds) sheet = client.open_by_key( '1eRO-30eIZamB5sjBp-Mz2QMKCfGxV037MQO8nS7G7AI').worksheet('Label') # Create a GUI window root = tk.Tk() app = App(master=root) # Run the GUI app.mainloop() </code></pre> <p>I've also tried a much more basic script just to print, but can't get this working either:</p> <pre><code>import win32print # Set the IP address of the printer printer_ip = '192.168.1.10' # Create a printer handle printer_handle = win32print.OpenPrinter(fr&quot;\\{printer_ip}\ZDesigner GK420d&quot;) # Get the default printer settings default_printer_settings = win32print.GetPrinter(printer_handle, 2) # Start a print job job_info = ('Test Print', None, default_printer_settings, None) job_id = win32print.StartDocPrinter(printer_handle, 1, job_info) # Send the test page to the printer win32print.StartPagePrinter(printer_handle) win32print.WritePrinter(printer_handle, b'test') win32print.EndPagePrinter(printer_handle) # End the print job win32print.EndDocPrinter(printer_handle) # Close the printer handle win32print.ClosePrinter(printer_handle) </code></pre> <p>I've tried connecting the printer via IP, but it can't be found. I retrieved all of the IP addresses from command prompt, but when it was plugged into the computer and when unplugged the list didn't change - I dont think it's being recognized. I can't get the IP from printer properties either - the port tab doesn't have them.</p>
<python><tkinter><printing><pywin32>
2023-03-09 02:10:00
0
393
Anthony Madle
75,679,799
7,479,675
Finding an element within iframes on a webpage, py + undetected_chromedriver
<p>I want to write a method that can help me locate an element on a webpage that contains multiple iframes. Currently, I have to manually search through these iframes every time I need to find a specific element. I want to automate this process so that I only need to know the name of the element I am looking for.</p> <p>I have written a method to accomplish this</p> <pre><code>def find_elem(self, xpath): try: sleep(2) # Try to find the element using the given XPath element = self.driver.find_element(By.XPATH, xpath) return element except (NoSuchElementException, InvalidSelectorException) as e: # If the element is not found, search for it recursively in all iframes on the page element = None sleep(2) iframes = self.driver.find_element(By.XPATH, &quot;//iframe&quot;) for iframe in iframes: try: self.driver.switch_to.frame(iframe) element = self.find_elem(xpath) if element is not None: break except NoSuchElementException: pass finally: self.driver.switch_to.default_content() # If the element is not found after searching all iframes, raise an exception if element is None: raise NoSuchElementException(&quot;Element not found: &quot; + xpath) return element ... self.driver.switch_to.default_content() found_elem = self.find_elem('//span[@id=&quot;gotItButton&quot;]') found_elem.send_keys(Keys.TAB) # execute some action on the element </code></pre> <p>but it is crashing with an error: pydevd warning getting attribute webelement.screenshot_as_base64 was slow</p> <p>Can anyone help me figure out how to locate an element when I do not know exactly which frame it is in? (I mean to help write a method using python)</p> <p>P.S. I have also tried using the DevTools -&gt; Recorder tool in Google Chrome, but it does not work with frames. An error occurred while attempting to interact with the element: 'waiting for target failed, timeout of 5000ms exceeded'.</p>
<python><selenium-webdriver><undetected-chromedriver>
2023-03-09 02:01:11
1
392
Oleksandr Myronchuk
75,679,667
5,212,614
How can I do a cumulative count of IDs, sorted, in a dataframe?
<p>I have a dataframe that looks like this.</p> <pre><code>import pandas as pd data = {'ID':[29951,29952,29953,29951,29951],'DESCRIPTION':['IPHONE 15','SAMSUNG S40','MOTOROLA G1000','IPHONE 15','IPHONE 15'],'PRICE_PROVIDER1':[1000.00,1200.00,1100.00,1000.00,1000.00]} df = pd.DataFrame(data) df </code></pre> <p><a href="https://i.sstatic.net/hfJnW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hfJnW.png" alt="enter image description here" /></a></p> <p>I want to add a new column that counts unique IDs. The final DF should look like this.</p> <p><a href="https://i.sstatic.net/4gJVM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4gJVM.png" alt="enter image description here" /></a></p> <p>I thought it would be as simple as this:</p> <pre><code>df['cnt'] = df.groupby('ID').cumcount(ascending=True) df </code></pre> <p>That's not doing what I want.</p>
<python><python-3.x><pandas><dataframe>
2023-03-09 01:31:18
2
20,492
ASH
75,679,636
7,794,924
How to add escape characters to a filename to be consumed later by a shell command?
<p>I am trying to find out which of my video files are corrupted. I loop through a directory, grab each video file, and check if it is corrupt/healthy. If the filename has no spaces nor special characters, it will work. Unfortunately, many of my files have spaces or parenthesis in the name, and this causes my shell command <code>ffmpeg</code> within my python script to fail. How can I retrieve the filenames in <code>abs_file_path</code> with the escape characters preceding the special characters?</p> <p><strong>Example filename:</strong> Movie Name (1080p)</p> <p><strong>Goal:</strong> Movie\ Name\ \(1080p\)</p> <pre><code>for filename in os.listdir(directory): if filename.endswith(tuple(VIDEO_EXTENSIONS)): print(f'PROCESSING: {filename}...') abs_file_path = os.path.join(directory, filename) proc = subprocess.Popen(f'./ffmpeg -v error -i {abs_file_path} -f null - 2&gt;&amp;1', shell=True, stdout=subprocess.PIPE) output = proc.communicate()[0] row = '' if not output: # Healthy print(&quot;\033[92m{0}\033[00m&quot;.format(&quot;HEALTHY -&gt; {}&quot;.format(filename)), end='\n') # red row = [filename, 0] else: # Corrupt print(&quot;\033[31m{0}\033[00m&quot;.format(&quot;CORRUPTED -&gt; {}&quot;.format(filename)), end='\n') # red row = [filename, 1] results_file_writer.writerow(row) results_file.flush() results_file.flush() results_file.close() </code></pre>
<python><bash><macos><ffmpeg>
2023-03-09 01:25:44
1
812
nhershy
75,679,635
13,730,432
Integrity error with Django models (NOT NULL constraint failed)
<p>can someone please help with the below error? I get the error when I am trying to update my models database.</p> <p>IntegrityError at /configuration/solarwinds/ NOT NULL constraint failed: pages_cityname.name Django Version: 3.2.5 Exception Type: IntegrityError Exception Value:<br /> NOT NULL constraint failed: pages_cityname.name Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /usr/local/opt/python/bin/python3.7</p> <p>Here is my models.py:</p> <p>Basically, whenever I select a &quot;Region&quot;, there should be a dependent dropdown update to the &quot;Cityname&quot; dropdown. So there is a foreign key relationship between Region and Cityname.</p> <pre><code> class Region(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = 'Region' class Cityname(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class Meta: verbose_name_plural = 'Cityname' class SolarwindsTool(models.Model): region = models.ForeignKey(Region, on_delete=models.SET_NULL, blank=True, null=True,verbose_name='Region') city = models.ForeignKey(Cityname, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='City') class Meta: db_table = 'solarwindstool' def __str__(self): return self.name </code></pre> <p>Here is the relevant code under views.py:</p> <pre><code>myvar = {'Data Centers': ['LAX101', 'LAX100', 'EWR100'], 'Americas': ['MEX01', 'BOU02', 'TOR01', 'LAX55']} for key in sorted(myvar): if Region.objects.filter(name = key).exists(): for items in myvar[key]: if Cityname.objects.filter(name = items).exists(): pass else: # value = Site(name=key) b=Region.objects.get(name=key) # print(b) e=Cityname(region=b,name=items) e.save() else: value = Region(name=key) value.save() print(&quot;THIS IS SITE&quot;,key) for items in myvar[key]: # v = Site.objects.filter(site__name__contains=key) value2 = Cityname(name=items,region=value) print(&quot;THIS IS VALUE2&quot;, value2) value2.save() </code></pre>
<python><django>
2023-03-09 01:25:43
1
701
xis10z
75,679,599
2,903,532
Python context manager to handle multiple exceptions in a series
<p>I am wanting to use a context manager to catch not just one Exception, like in <a href="https://stackoverflow.com/a/60367552/2903532">this answer</a>, but an arbitrary number of Exceptions in series, so that the following code will perform custom code to handle the <code>ModuleNotFoundError</code> three times:</p> <pre class="lang-py prettyprint-override"><code>with handle_ModuleNotFoundErrors(): import this_is_not_installed import neither_is_this import none_of_these_are_installed </code></pre> <p>So far, I have the following code, but it will only handle the first <code>ModuleNotFoundError</code>:</p> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager import re @contextmanager def handle_ModuleNotFoundErrors(): try: yield except ModuleNotFoundError as e: failed_module = re.search(r&quot;'((?:\\'|[^'])+)'&quot;, e.msg).group(1) print(f'Handling {failed_module}...') with handle_ModuleNotFoundErrors(): import asdfasdf1 import asdfasdf2 import asdfasdf3 # Handling asdfasdf1... </code></pre> <p>A correct answer would have the additional output...</p> <pre><code># Handling asdfasdf2... # Handling asdfasdf3... </code></pre>
<python><error-handling><try-except><contextmanager>
2023-03-09 01:18:40
1
1,285
reynoldsnlp
75,679,596
1,012,542
Partitioning a graph by the min cut given the `MaximumFlowResult` from `scipy.sparse.csgraph.maximum_flow`
<p>SciPy provides an implementation of a max flow algorithm: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.maximum_flow.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.maximum_flow.html</a></p> <p>I would like to partition the input graph by the min cut into vertex sets S and T.</p> <p>The SciPy <code>MaximumFlow</code> object contains a <code>flow</code> member, which according to the <a href="https://github.com/scipy/scipy/pull/16004" rel="nofollow noreferrer">SciPy GitHub PR 16004</a>:</p> <blockquote> <p>represents the flow function of the maximum flow, whereas the residual is given by the difference between the input graph and this flow function.</p> </blockquote> <p>Given the <code>MaximumFlow</code> object, how do I partition the graph into the source and sink nodes by cutting along the min cut?</p>
<python><graph><scipy><max-flow>
2023-03-09 01:18:30
1
665
Daniel
75,679,547
4,064,166
Why is there a discrepancy in Chebyshev coefficients?
<p>I am trying to calculate Chebyshev nodes to approximate the cos function in the interval <code>[-1,1]</code> with a polynomial of degree <code>4</code>. In <code>Python3</code>, I used <code>chebyfit</code> from <code>mpmath</code> and <code>chebyshev</code> from <code>numpy</code>.</p> <p>While I am getting accurate approximations,</p> <pre><code>nprint(cos(0.6), 12) nprint(polyval(poly, 0.6), 12) nprint(np.polynomial.chebyshev.chebval(0.6, c), 12) 0.82533561491 0.825331777049 0.825331777049078 </code></pre> <p>I am not sure why the coefficients differ.</p> <pre><code>poly, err = chebyfit(cos, [-1, 1], 5, error=True) nprint(poly) [0.0399612, 2.11758e-23, -0.499576, -2.64698e-23, 1.0] c = np.polynomial.chebyshev.chebinterpolate(np.cos, 4) nprint(c) [ 7.65197687e-01 -6.51999524e-18 -2.29807158e-01 -3.40959333e-18 4.99515460e-03] </code></pre> <p>I am expecting the coefficients to match as the approximation is calculated for the same interval and order.</p>
<python><numpy><curve-fitting><mpmath><polynomial-approximations>
2023-03-09 01:04:32
0
577
Devharsh Trivedi
75,679,449
1,368,195
Built an app with wxPython to send requests to REST API using Windows auth, but the app gets stuck at requests.post when compiled
<p>I tried to build an app (see a simplified version below) using wxPython that sends requests to a REST API endpoint using the <code>requests</code> package and the <code>requests_negotiate_sspi</code> package for Windows authentication. When I run the script in the command line without compiling it with <code>pyinstaller</code> - i.e., <code>python main_test.py</code> - the app runs fine: the <code>wx.Dialog</code> widget after <code>requests.post</code> pops up. However, if I compile the script and execute the executable instead, the app gets stuck at <code>requests.post</code>, and as a result, the second <code>wx.Dialog</code> doesn't pop up. I wonder if anyone knows why this might be the case. Thanks!</p> <pre><code>import wx import sys import subprocess import pyodbc import requests from requests_negotiate_sspi import HttpNegotiateAuth class main(wx.Frame): def __init__(self, parent, title): super(main, self).__init__(parent, title=title, size=(50, 100)) self.Button = wx.Button(self, label=&quot;Post&quot;, size=(50, 100)) self.Button.Bind(wx.EVT_BUTTON, self.OnPost) self.Layout() self.Show() def OnPost(self, evt): dlg = wx.Dialog(self, title= &quot;Before POST&quot;) dlg.Show() r = requests.post('path/to/endpoint', auth=HttpNegotiateAuth(), params=DICTIONARY_OF_PARAMETERS}) dlg = wx.Dialog(self, title= &quot;Post POST&quot;) dlg.Show() if __name__ == &quot;__main__&quot;: app = wx.App() MainFrame = main(None, title = &quot;Main Test&quot;) MainFrame.Show() MainFrame.Centre() app.MainLoop() </code></pre>
<python><rest><python-requests><wxpython><pyinstaller>
2023-03-09 00:39:33
0
4,180
Alex
75,679,369
1,330,719
Picking a Python Interpreter in VS Code when using Docker and poetry
<p>I open a monorepo folder within VS Code where the top folders are different services. One of the services is a python service using poetry to install dependencies.</p> <p>I am using poetry's <code>in-project=true</code> <code>virtualenv</code> setting so that all dependencies are actually stored in <code>./python-service/.venv</code>.</p> <p>The monorepo can be run locally using a docker-compose file. Consequently, any dependency installation is done on the container.</p> <p>VS Code does not automatically detect this virtual environment, but when manually set, it errors immediately:</p> <pre><code>Linter 'flake8' is not installed. Please install it or select another linter&quot;. Error: spawn /Users/me/dev/project/python-service/.venv/bin/python EACCES </code></pre> <p>If I look at the <code>./python-service/.venv/bin/python</code> file, I can see it's actually a symlink pointing at <code>/usr/local/bin/python</code> which does not exist on my machine, only on the container.</p> <p>Since VS Code is running on my machine, not the container, it makes sense that it cannot follow this symlink.</p> <p>I have considered two options:</p> <ol> <li>Use poetry's <code>always-copy</code> <code>virtualenv</code> option. For some reason this does not actually copy the <code>python</code> binary (<a href="https://github.com/python-poetry/poetry/discussions/7323" rel="noreferrer">replicated by someone else</a>). So this doesn't actually resolve this problem.</li> <li>Dev containers plugin for VS Code. While this works in theory, having to open a new window for each python service seems cumbersome. Ideally VS Code is able to use the appropriate venv as necessary.</li> </ol> <p>What is the correct way to configure poetry/vscode/docker to ensure an interpreter can be set in VS Code?</p>
<python><docker><visual-studio-code><python-poetry>
2023-03-09 00:19:37
1
1,269
rbhalla
75,679,120
10,964,685
Include figure parameters as a callback option - Dash
<p>I've got a callback function that changes a figure to various spatial maps. When hexbin is selected, I'm aiming to include parameters to alter the figure.</p> <p>Is it possible to only insert these parameters when the <code>hexbin</code> option is selected?</p> <pre><code>import dash from dash import dcc from dash import html from dash.dependencies import Input, Output import dash_bootstrap_components as dbc import plotly.express as px import plotly.graph_objs as go import pandas as pd import numpy as np import plotly.figure_factory as ff data = pd.DataFrame({ 'Cat': ['t','y','y','y','f','f','j','k','k','k','s','s','s','s'], 'LAT': [5,6,4,5,4,7,8,9,5,6,18,17,15,16], 'LON': [10,11,9,11,10,8,8,5,8,7,18,16,16,17], }) N = 30 data = pd.concat([data] * N, ignore_index=True) data['Color'] = data['Cat'].map(dict(zip(data['Cat'].unique(), px.colors.qualitative.Plotly[:len(data['Cat'].unique())]))) Color = data['Color'].unique() Type_Category = data['Cat'].unique() Type_cats = dict(zip(Type_Category, Color)) external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP] app = dash.Dash(__name__, external_stylesheets = external_stylesheets) filtering = html.Div(children=[ html.Div(children=[ html.Label('Cats', style = {'paddingTop': '2rem', 'display': 'inline-block'}), dcc.Checklist( id = 'Cats', options = [ {'label': 't', 'value': 't'}, {'label': 'y', 'value': 'y'}, {'label': 'f', 'value': 'f'}, {'label': 'j', 'value': 'j'}, {'label': 'k', 'value': 'k'}, {'label': 's', 'value': 's'}, ], value = ['t', 'y', 'f', 'j', 'k', 's'], ), html.Label('Type', style = {'paddingTop': '2rem', 'display': 'inline-block'}), dcc.RadioItems(['Scatter', 'Heatmap', 'Hexbin'], 'Scatter', inline = True, id = 'maps'), html.Label('Opacity', style = {'paddingTop': '2rem', 'display': 'inline-block'}), dcc.Slider(0, 1, 0.1, value = 0.5, id = 'my-slider'), html.Label('nx_hexagon', style = {'paddingTop': '2rem', 'display': 'inline-block'}), dcc.Slider(0, 40, 5, value = 20, id = 'my-slider'), html.Label('min count', style = {'paddingTop': '2rem', 'display': 'inline-block'}), dcc.Slider(0, 5, 1, value = 0, id = 'my-slider' ), ], ) ]) app.layout = dbc.Container([ dbc.Row([ dbc.Col([ html.Div(filtering), ], width = 2), dbc.Col([ html.Div(dcc.Graph()) ]), dbc.Col([ html.Div(dcc.Graph(id = 'chart')) ]) ]) ], fluid = True) df = data @app.callback( Output('chart', 'figure'), [Input(&quot;Cats&quot;, &quot;value&quot;), Input(&quot;maps&quot;, &quot;value&quot;)]) def scatter_chart(cats,maps): if maps == 'Scatter': dff = df[df['Cat'].isin(cats)] data = px.scatter_mapbox(data_frame = dff, lat = 'LAT', lon = 'LON', color = 'Cat', color_discrete_map = Type_cats, zoom = 3, mapbox_style = 'carto-positron', ) fig = go.Figure(data = data) elif maps == 'Heatmap': dff = df[df['Cat'].isin(cats)] # Creating 2-D grid of features [X, Y] = np.meshgrid(dff['LAT'], dff['LON']) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Densitymapbox(lat = dff['LON'], lon = dff['LAT'], z = Z, ) ) fig.update_layout(mapbox_style = &quot;carto-positron&quot;) else: dff = df[df['Cat'].isin(cats)] fig = ff.create_hexbin_mapbox(data_frame = dff, lat = &quot;LAT&quot;, lon = &quot;LON&quot;, ) return fig if __name__ == '__main__': app.run_server(debug=True, port = 8051) </code></pre> <p>Intended output when <code>hexbin</code> is selected:</p> <p><a href="https://i.sstatic.net/wXYfb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wXYfb.png" alt="enter image description here" /></a></p>
<python><plotly><plotly-dash>
2023-03-08 23:25:29
1
392
jonboy
75,679,077
14,088,919
Plot many PartialDependencePlot lines in one plot for multiclass classification
<p>Kind of a broad question but I need to plot many <code>PartialDependencePlot</code> lines in the same plot - one line for each target in the multiclass classification, for each variable in the dataset. So for variable <code>age</code> I'd have one plot with the many PDP lines, one for each target (I have 10), and so on for the rest of the variables.</p> <p>There seems to be no way to do this on the <code>sklearn.inspection.PartialDependenceDisplay</code> method, and I've tried messing with <code>sklearn.inspection.partial_dependence</code> and got so far as to get this, but I don't really know where to go from here:</p> <pre><code>pd =partial_dependence(xgb_clf, X_test, features=['age', 'score1', 'score2'], kind=&quot;average&quot;, grid_resolution=5) pd {'average': array([[[[0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ]], [[0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ], [0.811337 , 0.811337 , 0.811337 , 0.811337 , 0.811337 ]], [[0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 ], [0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 ], [0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 ], [0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 ], [0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 , 0.8237547 ]], [[0.82299083, 0.82299083, 0.82299083, 0.82299083, 0.82299083], [0.82299083, 0.82299083, 0.82299083, 0.82299083, 0.82299083], [0.82299083, 0.82299083, 0.82299083, 0.82299083, 0.82299083], [0.82299083, 0.82299083, 0.82299083, 0.82299083, 0.82299083], [0.82299083, 0.82299083, 0.82299083, 0.82299083, 0.82299083]], [[0.82412416, 0.82412416, 0.82412416, 0.82412416, 0.82412416], [0.82412416, 0.82412416, 0.82412416, 0.82412416, 0.82412416], [0.82412416, 0.82412416, 0.82412416, 0.82412416, 0.82412416], [0.82412416, 0.82412416, 0.82412416, 0.82412416, 0.82412416], [0.82412416, 0.82412416, 0.82412416, 0.82412416, 0.82412416]]], [[[0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061]], [[0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061], [0.01702061, 0.01702061, 0.01702061, 0.01702061, 0.01702061]], [[0.01730013, 0.01730013, 0.01730013, 0.01730013, 0.01730013], [0.01730013, 0.01730013, 0.01730013, 0.01730013, 0.01730013], [0.01730013, 0.01730013, 0.01730013, 0.01730013, 0.01730013], [0.01730013, 0.01730013, 0.01730013, 0.01730013, 0.01730013], [0.01730013, 0.01730013, 0.01730013, 0.01730013, 0.01730013]], [[0.01728426, 0.01728426, 0.01728426, 0.01728426, 0.01728426], [0.01728426, 0.01728426, 0.01728426, 0.01728426, 0.01728426], [0.01728426, 0.01728426, 0.01728426, 0.01728426, 0.01728426], [0.01728426, 0.01728426, 0.01728426, 0.01728426, 0.01728426], [0.01728426, 0.01728426, 0.01728426, 0.01728426, 0.01728426]], [[0.01731277, 0.01731277, 0.01731277, 0.01731277, 0.01731277], [0.01731277, 0.01731277, 0.01731277, 0.01731277, 0.01731277], [0.01731277, 0.01731277, 0.01731277, 0.01731277, 0.01731277], [0.01731277, 0.01731277, 0.01731277, 0.01731277, 0.01731277], [0.01731277, 0.01731277, 0.01731277, 0.01731277, 0.01731277]]], [[[0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252]], [[0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252], [0.00188252, 0.00188252, 0.00188252, 0.00188252, 0.00188252]], [[0.00202412, 0.00202412, 0.00202412, 0.00202412, 0.00202412], [0.00202412, 0.00202412, 0.00202412, 0.00202412, 0.00202412], [0.00202412, 0.00202412, 0.00202412, 0.00202412, 0.00202412], [0.00202412, 0.00202412, 0.00202412, 0.00202412, 0.00202412], [0.00202412, 0.00202412, 0.00202412, 0.00202412, 0.00202412]], [[0.00294247, 0.00294247, 0.00294247, 0.00294247, 0.00294247], [0.00294247, 0.00294247, 0.00294247, 0.00294247, 0.00294247], [0.00294247, 0.00294247, 0.00294247, 0.00294247, 0.00294247], [0.00294247, 0.00294247, 0.00294247, 0.00294247, 0.00294247], [0.00294247, 0.00294247, 0.00294247, 0.00294247, 0.00294247]], [[0.00294639, 0.00294639, 0.00294639, 0.00294639, 0.00294639], [0.00294639, 0.00294639, 0.00294639, 0.00294639, 0.00294639], [0.00294639, 0.00294639, 0.00294639, 0.00294639, 0.00294639], [0.00294639, 0.00294639, 0.00294639, 0.00294639, 0.00294639], [0.00294639, 0.00294639, 0.00294639, 0.00294639, 0.00294639]]], ..., [[[0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533]], [[0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533], [0.08890533, 0.08890533, 0.08890533, 0.08890533, 0.08890533]], [[0.07579581, 0.07579581, 0.07579581, 0.07579581, 0.07579581], [0.07579581, 0.07579581, 0.07579581, 0.07579581, 0.07579581], [0.07579581, 0.07579581, 0.07579581, 0.07579581, 0.07579581], [0.07579581, 0.07579581, 0.07579581, 0.07579581, 0.07579581], [0.07579581, 0.07579581, 0.07579581, 0.07579581, 0.07579581]], [[0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 ], [0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 ], [0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 ], [0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 ], [0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 , 0.0757297 ]], [[0.07584671, 0.07584671, 0.07584671, 0.07584671, 0.07584671], [0.07584671, 0.07584671, 0.07584671, 0.07584671, 0.07584671], [0.07584671, 0.07584671, 0.07584671, 0.07584671, 0.07584671], [0.07584671, 0.07584671, 0.07584671, 0.07584671, 0.07584671], [0.07584671, 0.07584671, 0.07584671, 0.07584671, 0.07584671]]], [[[0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371]], [[0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371], [0.00334371, 0.00334371, 0.00334371, 0.00334371, 0.00334371]], [[0.00339652, 0.00339652, 0.00339652, 0.00339652, 0.00339652], [0.00339652, 0.00339652, 0.00339652, 0.00339652, 0.00339652], [0.00339652, 0.00339652, 0.00339652, 0.00339652, 0.00339652], [0.00339652, 0.00339652, 0.00339652, 0.00339652, 0.00339652], [0.00339652, 0.00339652, 0.00339652, 0.00339652, 0.00339652]], [[0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 ], [0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 ], [0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 ], [0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 ], [0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 , 0.0033935 ]], [[0.00339899, 0.00339899, 0.00339899, 0.00339899, 0.00339899], [0.00339899, 0.00339899, 0.00339899, 0.00339899, 0.00339899], [0.00339899, 0.00339899, 0.00339899, 0.00339899, 0.00339899], [0.00339899, 0.00339899, 0.00339899, 0.00339899, 0.00339899], [0.00339899, 0.00339899, 0.00339899, 0.00339899, 0.00339899]]], [[[0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438]], [[0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438], [0.00560438, 0.00560438, 0.00560438, 0.00560438, 0.00560438]], [[0.00569604, 0.00569604, 0.00569604, 0.00569604, 0.00569604], [0.00569604, 0.00569604, 0.00569604, 0.00569604, 0.00569604], [0.00569604, 0.00569604, 0.00569604, 0.00569604, 0.00569604], [0.00569604, 0.00569604, 0.00569604, 0.00569604, 0.00569604], [0.00569604, 0.00569604, 0.00569604, 0.00569604, 0.00569604]], [[0.00569026, 0.00569026, 0.00569026, 0.00569026, 0.00569026], [0.00569026, 0.00569026, 0.00569026, 0.00569026, 0.00569026], [0.00569026, 0.00569026, 0.00569026, 0.00569026, 0.00569026], [0.00569026, 0.00569026, 0.00569026, 0.00569026, 0.00569026], [0.00569026, 0.00569026, 0.00569026, 0.00569026, 0.00569026]], [[0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 ], [0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 ], [0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 ], [0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 ], [0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 , 0.0056994 ]]]], dtype=float32), 'values': [array([21. , 30.25, 39.5 , 48.75, 58. ]), array([403.91 , 434.205, 464.5 , 494.795, 525.09 ]), array([nan, nan, nan, nan, nan])]} </code></pre> <p>Not very hopeful but has if anyone has done anything similar I'd appreciate the help.</p>
<python><matplotlib><scikit-learn><xgboost>
2023-03-08 23:16:57
1
612
amestrian