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,816,573
| 2,406,499
|
Finding Values in a Panda Series that can't be Converted to a Particular Datatype
|
<p>I have a dataframe called df which has a series, let's called it 'date', that have strings that refer to dates of the format 'YYYY-mm-dd' and hence every single value on the series should only have strings that can be converted to datetime objects.</p>
<p>I need to be able to show/filter only the rows which values on the df['date'] can't be converted to a datetime object so I can review them and decide what to do with those values, or at least know how many of them there are before removing them from df.</p>
<p>I looked into <code>isintance(value, datetime)</code>, but I can't seem to figure out a way to apply that to pandas series, I figure, I could do it in a non-pythonic way with an apply-lamba option but I was hoping to not having to resort to that.</p>
<p>I thought also about doing it with <code>df[datetimeFromDate] = pd.to_datetime(df['date], errors='coerce')</code> and then filter by <code>df[datetimeFromDate].isnull()</code> which is fine, and possibly more pythonic but I was really hoping to do it in one liner and I'm not thrilled about having to add another column, if I can avoid it.</p>
|
<python><pandas><dataframe>
|
2023-03-22 19:33:13
| 2
| 1,268
|
Francisco Cortes
|
75,816,464
| 1,988,046
|
Strange increase in latency of ZeroMQ between c# and python
|
<p>I'm trying to send images from C# running on win 11 to a python server running on WSL2.</p>
<p>I'm using ZeroMQ to send byte arrays, but as soon as the byte arrays cross a threshold (~8kb) the latency spikes from 0.3ms to 50ms. This 50ms latency remains until I get to ~74KB. Then it reduces back to about 0.3ms.</p>
<p>I have seen references to Nagle's algorithm (<a href="https://stackoverflow.com/a/75190133/1988046">https://stackoverflow.com/a/75190133/1988046</a>) but it seems that Nagle's is disabled by default in zeromq (<a href="http://wiki.zeromq.org/area:faq" rel="nofollow noreferrer">http://wiki.zeromq.org/area:faq</a>).</p>
<p>[Update] I ran it with a local install of python on the Win 11 side and did not see this problem at all, even though I was using exactly the same code file.</p>
<p>Can anyone suggest what I'm doing wrong?</p>
<p><strong>C# Client</strong></p>
<pre class="lang-cs prettyprint-override"><code>using System.Diagnostics;
using NetMQ;
using NetMQ.Sockets;
namespace ChatGptUdp;
internal class Program
{
private static void Main(string[] args)
{
var socket = new RequestSocket();
socket.Connect("tcp://localhost:5555");
var data = new byte[100000];
for (var i = 0; i < data.Length; i++) data[i] = (byte) i;
for (var i = 1; i < 100; i++)
{
var targetLength = 1000 * i;
var chunk = data.Take(targetLength).ToArray();
var elapsed = new List<TimeSpan>();
for (var j = 0; j < 100; j++)
{
var sw = Stopwatch.StartNew();
socket.SendFrame(chunk);
var response = socket.ReceiveFrameString();
sw.Stop();
elapsed.Add(sw.Elapsed);
}
// I skip the first 50 so that I ignore any startup delays.
// I don't think that will happen with this version of my algorithm, but just to be sure.
Console.Out.WriteLine($"{targetLength}: {elapsed.Skip(50).Average(s => s.TotalMilliseconds)}");
}
}
}
</code></pre>
<p><strong>Python Server</strong></p>
<pre class="lang-py prettyprint-override"><code>import zmq
import numpy as np
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind('tcp://*:5555')
print("Server connected")
while True:
msg = socket.recv()
data = {
'str': 'Hello there!'
}
socket.send_json(data)
</code></pre>
<p><strong>Latency results</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Size in bytes</th>
<th>Time in ms</th>
</tr>
</thead>
<tbody>
<tr>
<td>1000</td>
<td>0.3235700000000001</td>
</tr>
<tr>
<td>2000</td>
<td>0.28261</td>
</tr>
<tr>
<td>3000</td>
<td>0.28320400000000007</td>
</tr>
<tr>
<td>4000</td>
<td>0.280366</td>
</tr>
<tr>
<td>5000</td>
<td>0.35102799999999995</td>
</tr>
<tr>
<td>6000</td>
<td>0.2954839999999999</td>
</tr>
<tr>
<td>7000</td>
<td>0.30082</td>
</tr>
<tr>
<td>8000</td>
<td>0.27812799999999993</td>
</tr>
<tr>
<td>9000</td>
<td>50.00155000000001</td>
</tr>
<tr>
<td>10000</td>
<td>49.99915800000001</td>
</tr>
<tr>
<td>11000</td>
<td>50.00125</td>
</tr>
<tr>
<td>12000</td>
<td>50.008024</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>70000</td>
<td>50.004577999999995</td>
</tr>
<tr>
<td>71000</td>
<td>49.986256</td>
</tr>
<tr>
<td>72000</td>
<td>49.99861</td>
</tr>
<tr>
<td>73000</td>
<td>49.998368</td>
</tr>
<tr>
<td>74000</td>
<td>2.3343279999999997</td>
</tr>
<tr>
<td>75000</td>
<td>0.337194</td>
</tr>
<tr>
<td>76000</td>
<td>1.37548</td>
</tr>
<tr>
<td>77000</td>
<td>0.34829199999999993</td>
</tr>
<tr>
<td>78000</td>
<td>0.31957599999999997</td>
</tr>
<tr>
<td>79000</td>
<td>0.3393840000000001</td>
</tr>
<tr>
<td>80000</td>
<td>0.34001999999999993</td>
</tr>
</tbody>
</table>
</div>
|
<python><c#><tcp><zeromq><low-latency>
|
2023-03-22 19:19:43
| 0
| 513
|
mike1952
|
75,816,380
| 2,591,343
|
How to login on Pixelfed instances with Mastodon.py
|
<p>I used Mastodon.py and successfully had connected to a Mastodon instance using user/password.</p>
<p>But what I really need is to connect to a Pixelfed instance. Reading documentation from Pixelfed it's said you can connect to it like you do with Mastodon, just with some caveats, like (if I understood alright) you can only do this with a Personal Token or OAuth2.</p>
<p>As I don't need (or have to) an OAuth2 way to connect, as what I'm trying to do is upload a sizable number of pictures into my Pixelfed profile, I tried to use either user/pass and user/Personal Token...</p>
<p>But the same crashes.</p>
<p>I created my server connect object and tried to run this code on this gist with the results there...</p>
<p><a href="https://gist.github.com/fabiocosta0305/4638c6413be9ef7c5588cb337ab11a19" rel="nofollow noreferrer">https://gist.github.com/fabiocosta0305/4638c6413be9ef7c5588cb337ab11a19</a></p>
<pre><code>api.log_in("fabiocosta0305@gmail.com","<password>",scopes=['read','write','follow','push'])
Traceback (most recent call last):
File "/home/s192199488/.local/lib/python3.10/site-packages/mastodon/authentication.py", line 322, in log_in
response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting=False)
File "/home/s192199488/.local/lib/python3.10/site-packages/mastodon/internals.py", line 299, in __api_request
raise ex_type('Mastodon API returned error', response_object.status_code, response_object.reason, error_msg)
mastodon.errors.MastodonUnauthorizedError: ('Mastodon API returned error', 401, 'Unauthorized', 'invalid_client')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/s192199488/.local/lib/python3.10/site-packages/mastodon/authentication.py", line 328, in log_in
raise MastodonIllegalArgumentError('Invalid user name, password, or redirect_uris: %s' % e)
mastodon.errors.MastodonIllegalArgumentError: Invalid user name, password, or redirect_uris: ('Mastodon API returned error', 401, 'Unauthorized', 'invalid_client')
</code></pre>
<p>Any tips?</p>
|
<python><mastodon><mastodon-py>
|
2023-03-22 19:10:16
| 0
| 463
|
HufflepuffBR
|
75,816,237
| 6,552,666
|
Why is this JOIN+AND query identical to this JOIN query?
|
<p>I have an SQLite database with an events, a participants tables, and a third table linking each participant to each event they attended. I wanted a list of the events that a given participant attended.</p>
<pre><code>only_joined_table = mydb.execute('SELECT * FROM event_participant_link LEFT JOIN event '
'ON event_participant_link.event_id = event.event_id').fetchall()
joined_table = mydb.execute('SELECT * FROM event_participant_link LEFT JOIN event '
'ON event_participant_link.event_id = event.event_id '
'AND event_participant_link.participant_id = ?',
[participant_id]).fetchall()
print(len(only_joined_table), len(joined_table)) # Result: 7929 7929
</code></pre>
<p>These two queries apparently show the same number of entries, indicating that <code>AND event_participant_link.participant_id = participant_id</code> doesn't actually do anything. Is this not the right way to add a constraining filter on a joined table? Or does something else pop up that explains the unexpected result?</p>
|
<python><sqlite>
|
2023-03-22 18:53:30
| 2
| 673
|
Frank Harris
|
75,816,024
| 1,319,406
|
List comprehension vs. for loop performance testing
|
<p>In an effort to avoid Django ModelSerialization performance hits, I am looking at "serializing" a result set on my own. Many related Stackoverflow questions say that list comprehension should be the fastest, but my own tests are showing nested for loops being consistently faster.</p>
<p>I have raw DB results (100) that need to be converted into a list of OrderedDict based on an ordered list of fields (14). Is my use case too complex for the list comprehension performance advantage, or my sample size too small? Maybe the performance is negligible? My overall question is: am I going about testing the performance properly?</p>
<p><strong>Nested for-loop (0.000919342041015625)</strong></p>
<pre class="lang-py prettyprint-override"><code>serialized = []
start = time.time()
for raw in results:
result = OrderedDict()
for index, field in enumerate(fields):
result[field] = raw[index]
serialized.append(result)
end = time.time()
print("For loop + for loop " + str(end - start))
</code></pre>
<p><strong>Nested list comprehension (0.011911153793334961)</strong></p>
<pre class="lang-py prettyprint-override"><code>serialized = []
start = time.time()
serialized = [OrderedDict((field, raw[index]) for index, field in enumerate(fields)) for raw in results]
end = time.time()
print("List comprehensions + list comprehensions " + str(end - start))
</code></pre>
<p><strong>For-loop + list comprehension (0.020151615142822266)</strong></p>
<pre class="lang-py prettyprint-override"><code>serialized = []
start = time.time()
for raw in results:
result = OrderedDict((field, raw[index]) for index, field in enumerate(fields))
serialized.append(result)
end = time.time()
print("For loop + list comprehensions " + str(end - start))
</code></pre>
|
<python><list><performance>
|
2023-03-22 18:29:34
| 1
| 490
|
Danielle
|
75,815,967
| 4,042,278
|
How to run anaconda python with "execute a process" in Pentaho(PDI) in windows?
|
<p>I'm going to run a python program by "execute a process" in pdi and on a specific anaconda environment.</p>
<p>This is my solution which didn't work:</p>
<p><a href="https://i.sstatic.net/L0ELa.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/L0ELa.png" alt="enter image description here" /></a></p>
<pre><code>run_on_win = "C:\Users\x\Anaconda3\Scripts\activate.bat & python"
api_call = my python file
Remains fields are my parameters
</code></pre>
<p>How these commands, which run successfully on cmd, raise this error in PDI?</p>
<p><code> Cannot run program "C:\Users\x\Anaconda3\Scripts\activate.bat & python": CreateProcess error=2, The system cannot find the file specified</code></p>
|
<python><pentaho><pentaho-spoon><pentaho-data-integration>
|
2023-03-22 18:20:57
| 2
| 1,390
|
parvij
|
75,815,959
| 10,428,677
|
Check if columns exist and if not, create and fill with NaN using PySpark
|
<p>I have a pyspark dataframe and a separate list of column names. I want to check and see if any of the list column names are missing, and if they are, I want to create them and fill with null values.</p>
<p>Is there a straightforward way to do this in pyspark? I can do it in Pandas, but it's not what I need.</p>
|
<python><apache-spark><pyspark>
|
2023-03-22 18:20:27
| 1
| 590
|
A.N.
|
75,815,913
| 1,056,563
|
ModuleNotFoundError on pytz,yaml, delta even though installed in same python instance
|
<p>Let's consider carefully the <em><code>pytz</code></em> library (<code>yaml</code> and <code>delta[-spark]</code> have an identical pattern.).</p>
<p>'<code>pytz</code> has been installed via <code>pip</code> and then re-confirmed in a couple of different ways:</p>
<ul>
<li>Initial installation</li>
</ul>
<pre><code>+ /root/miniconda3/envs/py310/bin/python3 -m pip install -r requirements.txt
</code></pre>
<ul>
<li>Here it is in action being installed</li>
</ul>
<pre><code>Collecting pytz
Downloading pytz-2022.7.1-py2.py3-none-any.whl (499 kB)
ββββββββββββββββββββββββββββββββββββββ 499.4/499.4 kB 44.5 MB/s eta 0:00:00
...
Successfully installed pytz-2022.7.1
</code></pre>
<p>Let's try to [re-]install it manually: we get the expected message that it's already present</p>
<pre><code>+ /root/miniconda3/envs/py310/bin/python3 -m pip install pytz
Requirement already satisfied: pytz in /root/miniconda3/envs/py310/lib/python3.10/site-packages
(from -r requirements_localdev.txt (line 3)) (2022.7.1)
</code></pre>
<p>Let's run `pytest' in specifically the same python instance:</p>
<pre><code>+ /root/miniconda3/envs/py310/bin/python3 -m pytest -s -rA
============================= test session starts ==============================
platform linux -- Python 3.10.10, pytest-7.2.2, pluggy-1.0.0
</code></pre>
<p>But <code>pytz</code> is not found?</p>
<pre><code> File "/__w/1/s/src/framework/ddex/utils/logger.py", line 15, in <module>
import pytz
ModuleNotFoundError: No module named 'pytz'
</code></pre>
<p>Note: there are nearly 800 testcases with several dozen dependent packages. Only 21 testcases fail - those associated with <code>pytz</code> and the two other libraries that also fail the same way.</p>
|
<python><pip>
|
2023-03-22 18:14:50
| 0
| 63,891
|
WestCoastProjects
|
75,815,782
| 8,981,425
|
Using all the div width when using imshow with dash
|
<p>I am working on an application with Dash. It has a really simple layout: a main area with a viewer and a left column with the controls. I am using Plotly express imshow in order to display the image. The figure is occupying all the width of the main area, but the 'canvas' is centered and keeps the image's original aspect ratio. In the example shown below the image is zoomed in, and as you can see there are black bars on the sides. I would like to use all the main area for the viewer.</p>
<p><a href="https://i.sstatic.net/j1klw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/j1klw.png" alt="Current viewer with black bars." /></a></p>
<p>The code used to create this figure is:</p>
<pre><code>import plotly.express as px
import pydicom as dic
img = dic.read_file('front/assets/test_img.dicom').pixel_array
fig = px.imshow(img, binary_string=True, template='plotly_dark')
fig.update_yaxes(
ticklabelposition="inside top",
title=None,
ticks="inside",
ticklen=10,
tickcolor='white',
minor_ticks="inside")
fig.update_xaxes(
ticklabelposition="inside",
title=None,
ticks="inside",
ticklen=10,
tickcolor='white',
minor_ticks="inside")
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0, autoexpand=False))
</code></pre>
<p>I would like to move the left rule to the left and use all the area when zooming in, with independence of the image aspect ratio.</p>
|
<python><plotly><plotly-dash>
|
2023-03-22 18:02:15
| 0
| 367
|
edoelas
|
75,815,764
| 4,167,457
|
How can I clear the input in a gradio app automatically?
|
<p>I want to be able to clear the input with gradio at the end of completing the inference without any additional click from the user. Currently with live=True, the inference function is triggered when the recording is stopped.</p>
<p>Here is the relevant part of my code:</p>
<pre><code>audio_input = gr.Audio(source="microphone", type="filepath")
demo = gr.Interface(
fn=inference,
inputs=audio_input,
outputs="text",
live=True
)
demo.launch()
</code></pre>
<ul>
<li>I tried re-initializing the audio component at the end of my inference function. That didn't change anything</li>
<li>I looked through the docs related to components and all examples I found for other components and couldn't find anything to do this.</li>
</ul>
|
<python><gradio>
|
2023-03-22 18:00:26
| 3
| 310
|
Corey
|
75,815,741
| 5,056
|
What is the scope inside a comprehension directly in a class?
|
<p>Note that what I'm after here is deeper understanding of how python works. I am aware that I can use methods or <code>@property</code> and that any practical needs here would be esoteric and odd.</p>
<p>It is my understanding that when a class is initialized in python, its body is executed within a new namespace, then the locals of that namespace are copied into the class definition.</p>
<p>That said, something odd is happening with comprehensions.</p>
<pre class="lang-py prettyprint-override"><code>class Foo:
a = (1,2,3)
b = [2*x for x in a]
</code></pre>
<p>This works fine as expected. No errors.</p>
<p>But simply adding an <code>if</code> clause that references <code>a</code></p>
<pre class="lang-py prettyprint-override"><code>class Foo:
a = (1,2,3)
b = [2*x for x in (2,3,4) if x in a]
</code></pre>
<p>Results in</p>
<pre class="lang-py prettyprint-override"><code>Input In [3], in <listcomp>(.0)
1 class Foo:
2 a = (1,2,3)
----> 3 b = [2*x for x in (2,3,4) if x in a]
NameError: name 'a' is not defined
</code></pre>
<p>Confusing since <code>a</code> <em>is</em> accessible inside the comprehension. Though I suppose there's a difference between specifying what is being iterated and what happens on an iteration.</p>
<p>But even more confusing, this works fine.</p>
<pre class="lang-py prettyprint-override"><code>class Foo:
a = (1,2,3)
b = []
for x in (2,3,4):
if x in a:
b.append(x)
</code></pre>
<p>So what is going on? What is the comprehension doing that <code>a</code> was not accessible? I always thought it just expanded into something of this sort but clearly that's not the case.</p>
|
<python><class><list-comprehension>
|
2023-03-22 17:57:44
| 0
| 122,870
|
George Mauer
|
75,815,628
| 7,059,087
|
How to trace DNS for intermittent python `socket.gaierror: [Errno -3] Temporary failure in name resolution`
|
<p>I have an API that calls another API endpoint. An <em>extremely</em> simplified version of the Flask code can be considered</p>
<pre><code>@app.route(route, methods=['POST'])
async def index():
json = await request.get_json()
headers = request.headers
endpoint = "some endpoint that comes from other logic"
# do some other work
async with aiohttp.ClientSession() as session:
response = await session.post(endpoint, json=json, headers=headers)
# do some other work
return (output, 200)
</code></pre>
<p>Very very intermittently (approximately .07% of requests and only under heavy load) I see the following error that causes the code to crash out after about <code>10 seconds</code></p>
<pre><code>socket.gaierror: [Errno -3] Temporary failure in name resolution
</code></pre>
<p>From this question <a href="https://stackoverflow.com/questions/40238610/what-is-the-meaning-of-gaierror-errno-3-temporary-failure-in-name-resolutio">here</a> I've learned that this is a <strong>G</strong>et <strong>a</strong>ddress <strong>i</strong>nfo <strong>error</strong> (gaierror) that occurs from a problem with the DNS lookup stage. The endpoints I am calling exist though, as can be seen since the error is only intermittent across all endpoints and inputs without a real pattern.</p>
<p>This leads me to <a href="https://stackoverflow.com/questions/61377263/gaierror-errno-3-temporary-failure-in-name-resolution-while-sending-outlook">this</a> question which suggests that its probably a problem having to do with an unreliable network. My suspicion specifically is that in our internal network we might have a faulty DNS server, and want to see if I can trace this to check. As such I had some specific questions that I'd appreciate if anyone knew the answers to</p>
<ol>
<li><p>Is it possible that this code is not <code>async</code> safe and a race condition could be causing a problem?</p>
</li>
<li><p>For this error and with the <code>aiohttp</code> library, is it possible to get a traceback / return of the IP of the DNS server that it attempted to hit so that I can verify to see if it is the same DNS server every time?</p>
</li>
</ol>
|
<python><python-3.x><flask><dns>
|
2023-03-22 17:43:45
| 0
| 532
|
wjmccann
|
75,815,523
| 6,849,363
|
Python sqlite3 .fetchmany(batch_size) while loop exiting after one loop
|
<p>I have the following code:</p>
<pre><code>import openai
import sqlite3
import os
from dotenv import load_dotenv
load_dotenv()
def clean_and_save_descriptions_subset(days_old = 7, num_reivew = 1000, batch_size = 50):
api_key = os.getenv("OPEN_AI_API_KEY")
sql = f"""
SELECT e.mp3_url, e.episode_description
From episodes e
JOIN shows s
ON e.itunesid = s.itunesid
WHERE published_date > STRFTIME('%s', 'now') - ({days_old} *24 *60 *60)
AND s.num_reviews > {num_reivew}
AND e.clean_episode_description is NULL
"""
conn = sqlite3.connect("db/chatterpulse.db")
cursor = conn.cursor()
cursor.execute(sql)
batch_no = 0
while True:
batch = cursor.fetchmany(batch_size)
if not batch:
break
print(batch_no)
mp3_urls = [row[0] for row in batch]
episode_descriptions = [row[1] for row in batch]
cleaned_descriptions = clean_descriptions(episode_descriptions, api_key)
for mp3_url, cleaned_description in zip(mp3_urls, cleaned_descriptions):
update_sql = f"""
UPDATE episodes
SET clean_episode_description = ?
WHERE mp3_url = ?;
"""
cursor.execute(update_sql, (cleaned_description, mp3_url))
conn.commit()
batch_no += 1
conn.close()
clean_and_save_descriptions_subset()
</code></pre>
<p>The code all works as expected, getting and setting data to the database as expected. However, it then exits the loop after exactly one batch. I've tried a couple of different itterations of this code and still get the same issue.</p>
<p>Chatgpt and I are both at a loss. Apologies for the lack of reproducibility, but not really feasible.</p>
|
<python><sqlite><while-loop>
|
2023-03-22 17:33:28
| 0
| 470
|
Tanner Phillips
|
75,815,522
| 6,543,183
|
Get the name of columns from rows distinct from zero python
|
<p>I have this dataframe:</p>
<pre><code>df0 = pd.DataFrame({'points': [0, 0, -3, 16, 0, 5, -3, 14],
'assists': [0, 0, 2, 0, 1, -7, 0, 6],
'numbers': [0, 0, 1, 6, 10, 5, 8, 7]})
</code></pre>
<p>and my desired dataset looks like this:</p>
<pre><code>points assists numbers colX
0 0 0 0
0 0 0 0
-3 2 1 'points-assists-numbers'
16 0 6 'points-numbers'
0 1 10 'assists-numbers'
5 7 5 'points-assists-numbers'
-3 0 8 'points-numbers'
14 8 7 'points-assists-numbers'
</code></pre>
<p>A function that create a string from columns names that have values distinct from zero.</p>
<p>Any help?</p>
|
<python><pandas><dataframe>
|
2023-03-22 17:33:12
| 3
| 880
|
rnv86
|
75,815,457
| 5,605,510
|
Custom BooleanField name in Django admin list filter
|
<p>In Django admin I can change default True/False representation of <code>BooleanField</code> using <code>choices</code> argument. It appears in object page and list page. But it doesn't changes in admin list filter. Why? How can I change defaults 'All/Yes/No/Unknown' in <code>list_filter</code>?</p>
<p>app/models.py</p>
<pre><code>CHOICES_BUILDING_CONDITION = (
(True, 'New'),
(False, 'Old'),
(None, 'Unknown'),
)
class Flat(models.Model):
is_new_building = models.BooleanField(
'Building condition', null=True, blank=True, choices=CHOICES_BUILDING_CONDITION
)
</code></pre>
<p>app/admin.py</p>
<pre><code>class FlatAdmin(admin.ModelAdmin):
list_filter = ('is_new_building', )
</code></pre>
|
<python><django><filter><boolean><django-admin>
|
2023-03-22 17:25:26
| 1
| 480
|
Andrei Alekseev
|
75,815,288
| 3,337,089
|
Slice a multidimensional pytorch tensor based on values in other tensors
|
<p>I have 4 PyTorch tensors:</p>
<ul>
<li><code>data</code> of shape <code>(l, m, n)</code></li>
<li><code>a</code> of shape <code>(k,)</code> and datatype <code>long</code></li>
<li><code>b</code> of shape <code>(k,)</code> and datatype <code>long</code></li>
<li><code>c</code> of shape <code>(k,)</code> and datatype <code>long</code></li>
</ul>
<p>I want to slice the tensor <code>data</code> such that it picks the element addressed by <code>a</code> in <code>0th</code> dimension. In the <code>1st</code> and <code>2nd</code> dimensions, I want to pick a patch of values based on the element addressed by <code>b</code> and <code>c</code>. Specifically, I want to pick 9 values - a <code>3x3</code> patch around the value addressed by <code>b</code>. Thus my sliced tensor should have a shape <code>(k, 3, 3)</code>.</p>
<p>MWE:</p>
<pre><code>data = torch.arange(200).reshape((2, 10, 10))
a = torch.Tensor([1, 0, 1, 1, 0]).long()
b = torch.Tensor([5, 6, 3, 4, 7]).long()
c = torch.Tensor([4, 3, 7, 6, 5]).long()
data1 = data[a, b-1:b+1, c-1:c+1] # gives error
>>> TypeError: only integer tensors of a single element can be converted to an index
</code></pre>
<p>Expected output</p>
<pre><code>data1[0] = [[143,144,145],[153,154,155],[163,164,165]]
data1[1] = [[52,53,54],[62,63,64],[72,73,74]]
data1[2] = [[126,127,128],[136,137,138],[146,147,148]]
and so on
</code></pre>
<p>How can I do this without using for loop?</p>
<p>PS:</p>
<ul>
<li>I've padded <code>data</code> to make sure that the locations addressed by <code>a,b,c</code> are within the limit.</li>
<li>I don't need gradients to flow through this operation. So, I can convert these to NumPy and slice if that is faster. But I would prefer a solution in PyTorch.</li>
</ul>
|
<python><pytorch><vectorization><slice><numpy-slicing>
|
2023-03-22 17:09:27
| 2
| 7,307
|
Nagabhushan S N
|
75,815,275
| 8,497,979
|
Filter list for dictionaries for key based on a particular value
|
<p>I have a list of dictionaries:</p>
<pre><code>lst = [
{
'meter_design': {'S': 'digital'},
'meter_calibration_period': {'S': '2022'},
'meter_counting_type': {'S': 'Quantity meter'},
'meter_kind': {'S': 'Gas'},
'meter_serial_number': {'S': '10030507'}
},
{
'meter_design': {'S': 'digital'},
'meter_calibration_period': {'S': '2026'},
'meter_counting_type': {'S': 'Quantity meter'},
'meter_kind': {'S': 'Heat'},
'meter_serial_number': {'S': '7GMT0008942175'}
}
]
</code></pre>
<p>that I want to filter to show only the dictionaries, which contain a certain key-value pair like "meter_calibration_period" == '2026'. So far Ive tried this:</p>
<pre><code>res = [
{
"Calibration" : item["meter_calibration_period"]["S"],
"serial number" : item["meter_serial_number"]["S"],
}
for item in lst if "meter_calibration_period" == '2026'
]
</code></pre>
<p>But I only get back an empty list.
What am I doing wrong?</p>
|
<python>
|
2023-03-22 17:08:16
| 1
| 1,410
|
aerioeus
|
75,815,249
| 854,791
|
Spark container keeps restarting
|
<p>I'm trying to write some data to a Delta Table using Spark. For this, I'm running Spark in a Docker container through docker compose. Whenever I try to create a Delta Table, the container keeps restarting in a loop, with nothing happening. It's giving me this output:</p>
<pre><code>biocloud-core-dockercompose-spark-1 | 23/03/22 16:56:41 INFO Master: Removing executor app-20230322165616-0000/23 because it is EXITED
biocloud-core-dockercompose-spark-1 | 23/03/22 16:56:41 INFO Master: Launching executor app-20230322165616-0000/25 on worker worker-20230322165555-172.21.0.4-39781
biocloud-core-dockercompose-spark-worker-2 | 23/03/22 16:56:41 INFO Worker: Asked to launch executor app-20230322165616-0000/25 for create-Raw-tables
biocloud-core-dockercompose-spark-worker-2 | 23/03/22 16:56:41 INFO SecurityManager: Changing view acls to: spark
biocloud-core-dockercompose-spark-worker-2 | 23/03/22 16:56:41 INFO SecurityManager: Changing modify acls to: spark
biocloud-core-dockercompose-spark-worker-2 | 23/03/22 16:56:41 INFO SecurityManager: Changing view acls groups to:
biocloud-core-dockercompose-spark-worker-2 | 23/03/22 16:56:41 INFO SecurityManager: Changing modify acls groups to:
biocloud-core-dockercompose-spark-worker-2 | 23/03/22 16:56:41 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(spark); groups with view permissions: Set(); users with modify permissions: Set(spark); groups with modify permissions: Set()
biocloud-core-dockercompose-spark-worker-2 | 23/03/22 16:56:41 INFO ExecutorRunner: Launch command: "/opt/bitnami/java/bin/java" "-cp" "/opt/bitnami/spark/conf/:/opt/bitnami/spark/jars/*" "-Xmx1024M" "-Dspark.driver.port=54879" "-XX:+IgnoreUnrecognizedVMOptions" "--add-opens=java.base/java.lang=ALL-UNNAMED" "--add-opens=java.base/java.lang.invoke=ALL-UNNAMED" "--add-opens=java.base/java.lang.reflect=ALL-UNNAMED" "--add-opens=java.base/java.io=ALL-UNNAMED" "--add-opens=java.base/java.net=ALL-UNNAMED" "--add-opens=java.base/java.nio=ALL-UNNAMED" "--add-opens=java.base/java.util=ALL-UNNAMED" "--add-opens=java.base/java.util.concurrent=ALL-UNNAMED" "--add-opens=java.base/java.util.concurrent.atomic=ALL-UNNAMED" "--add-opens=java.base/sun.nio.ch=ALL-UNNAMED" "--add-opens=java.base/sun.nio.cs=ALL-UNNAMED" "--add-opens=java.base/sun.security.action=ALL-UNNAMED" "--add-opens=java.base/sun.util.calendar=ALL-UNNAMED" "--add-opens=java.security.jgss/sun.security.krb5=ALL-UNNAMED" "org.apache.spark.executor.CoarseGrainedExecutorBackend" "--driver-url" "spark://CoarseGrainedScheduler@host.docker.internal:54879" "--executor-id" "25" "--hostname" "172.21.0.4" "--cores" "1" "--app-id" "app-20230322165616-0000" "--worker-url" "spark://Worker@172.21.0.4:39781"
biocloud-core-dockercompose-spark-worker-1 | 23/03/22 16:56:43 INFO Worker: Executor app-20230322165616-0000/24 finished with state EXITED message Command exited with code 1 exitStatus 1
biocloud-core-dockercompose-spark-worker-1 | 23/03/22 16:56:43 INFO ExternalShuffleBlockResolver: Clean up non-shuffle and non-RDD files associated with the finished executor 24
biocloud-core-dockercompose-spark-worker-1 | 23/03/22 16:56:43 INFO ExternalShuffleBlockResolver: Executor is not registered (appId=app-20230322165616-0000, execId=24)
</code></pre>
<p>This keeps happening on repeat. I connect with Spark with the following code:</p>
<pre><code>builder = SparkSession.builder.appName(app_name).master(self.spark_master) \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
.config("spark.jars.packages", "{maven_packages}") \
.config("spark.hadoop.fs.s3a.access.key", Config.S3_ACCESS_KEY_ID) \
.config("spark.hadoop.fs.s3a.secret.key", Config.S3_SECRET_ACCESS_KEY) \
.config("spark.hadoop.fs.s3a.path.style.access", "true") \
.config("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") \
.config("spark.shuffle.service.enabled", "false") \
.config("spark.dynamicAllocation.enabled", "false")
self.spark_session = configure_spark_with_delta_pip(builder).enableHiveSupport().getOrCreate()
</code></pre>
<p>The docker-compose looks like this:</p>
<pre><code>version: '2'
services:
spark:
image: docker.io/bitnami/spark:3.3
hostname: spark
environment:
- SPARK_MODE=master
- SPARK_RPC_AUTHENTICATION_ENABLED=no
- SPARK_RPC_ENCRYPTION_ENABLED=no
- SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no
- SPARK_SSL_ENABLED=no
ports:
- '8080:8080'
- '7077:7077'
volumes:
- /data/spark:/bitnami/spark
spark-worker:
image: docker.io/bitnami/spark:3.3
deploy:
replicas: 2
environment:
- SPARK_MODE=worker
- SPARK_MASTER_URL=spark://spark:7077
- SPARK_WORKER_MEMORY=1G
- SPARK_WORKER_CORES=1
- SPARK_RPC_AUTHENTICATION_ENABLED=no
- SPARK_RPC_ENCRYPTION_ENABLED=no
- SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no
- SPARK_SSL_ENABLED=no
</code></pre>
<p>Does anyone have any idea why this happens? This only seems to happen on Windows btw, my colleagues that use Linux don't have this problem.</p>
|
<python><docker><apache-spark><pyspark><delta-lake>
|
2023-03-22 17:05:01
| 0
| 12,536
|
Leon Cullens
|
75,815,202
| 4,115,378
|
group nearby timestamps together in pandas
|
<p>I understand Pandas has a <code>pd.Grouper</code> where we can specify time frequency. However, it uses the frequency as border for each sample, similar to how resample does it.
For example:</p>
<pre><code>df.groupby(pd.Grouper(key='Timestamp', freq='1s')).agg({...})
</code></pre>
<p>will create a grouped dataframe with index that are <code>1s</code> apart.
However, I want to group all rows where the difference between the previous and next rows are less than <code>1s</code>. For example, my timestamp might be (ignoring datetimes for simplicity, only showing the seconds, assume the same datetime before second precision) <code>1.1s, 1.8s, 2.4s, 5s, 5.9s, 9s</code>, in which case I want <code>(1.1s, 1.8s, and 2.4s)</code>, <code>(5s, 5.9s)</code>, <code>(9s)</code> grouped together, and the indexes to the grouped dataframe are <code>(1.1s, 5s, 9s)</code>.</p>
<p>How can I achieve this?</p>
|
<python><pandas>
|
2023-03-22 17:00:08
| 1
| 1,364
|
A1122
|
75,815,136
| 6,077,239
|
Correlation dataframe convertion from results from pl.corr
|
<p>I have a simple dataframe as follows:</p>
<pre><code>import polars as pl
df = pl.DataFrame(
{
"group": [1, 1, 1, 1, 2, 2, 2, 2],
"a": [1, 2, 3, 4, 1, 2, 3, 4],
"b": [5, 1, 7, 9, 2, 4, 9, 7],
"c": [2, 6, 3, 9, 1, 5, 3, 6],
}
)
</code></pre>
<p>I want to have a correlation 'matrix' resides in polars dataframe structured like the one below. How can I do that?</p>
<pre><code>βββββββββ¬βββββββ¬βββββββββββ¬βββββββββββ¬βββββββββββ
β group β name β a β b β c β
β --- β --- β --- β --- β --- β
β i64 β str β f64 β f64 β f64 β
βββββββββͺβββββββͺβββββββββββͺβββββββββββͺβββββββββββ‘
β 1 β a β 1.0 β 0.680336 β 0.734847 β
β 1 β b β 0.680336 β 1.0 β 0.246885 β
β 1 β c β 0.734847 β 0.246885 β 1.0 β
β 2 β a β 1.0 β 0.830455 β 0.756889 β
β 2 β b β 0.830455 β 1.0 β 0.410983 β
β 2 β c β 0.756889 β 0.410983 β 1.0 β
βββββββββ΄βββββββ΄βββββββββββ΄βββββββββββ΄βββββββββββ
</code></pre>
<p>Currently, this is what I tried:</p>
<pre><code>df.group_by("group").agg(
pl.corr(col1, col2).alias(f"{col1}_{col2}")
for col1 in ["a", "b", "c"]
for col2 in ["a", "b", "c"]
)
shape: (2, 10)
βββββββββ¬ββββββ¬βββββββββββ¬βββββββββββ¬ββββ¬βββββββββββ¬βββββββββββ¬βββββββββββ¬ββββββ
β group β a_a β a_b β a_c β β¦ β b_c β c_a β c_b β c_c β
β --- β --- β --- β --- β β --- β --- β --- β --- β
β i64 β f64 β f64 β f64 β β f64 β f64 β f64 β f64 β
βββββββββͺββββββͺβββββββββββͺβββββββββββͺββββͺβββββββββββͺβββββββββββͺβββββββββββͺββββββ‘
β 2 β 1.0 β 0.830455 β 0.756889 β β¦ β 0.410983 β 0.756889 β 0.410983 β 1.0 β
β 1 β 1.0 β 0.680336 β 0.734847 β β¦ β 0.246885 β 0.734847 β 0.246885 β 1.0 β
βββββββββ΄ββββββ΄βββββββββββ΄βββββββββββ΄ββββ΄βββββββββββ΄βββββββββββ΄βββββββββββ΄ββββββ
</code></pre>
<p>So, not sure about how can I transform it to the shape/structure I want? Or, are there some other (potentially better) ways to generate the results I want directly?</p>
|
<python><python-polars>
|
2023-03-22 16:53:32
| 3
| 1,153
|
lebesgue
|
75,815,091
| 7,437,143
|
Storing only unique/non-isomorphic undirected networkx graphs?
|
<h2>Context</h2>
<p>After thinking about the most efficient way to store unique graphs (in plain text), I determined the following procedure:</p>
<ul>
<li>create a folder with the graph size (nr of nodes) as name</li>
<li>when storing a new graph of size <code>n</code>, load the graphs inside the folder of graph size <code>n</code>, and check if any of them is isomorphic (with the to be stored/new graph).</li>
</ul>
<h2>Issue</h2>
<p>However that has a (*checking) complexity of O(m) per graph, and I thought, perhaps it is possible to compute some kind of hash of each graph and store the graph with that hash as that filename, such that the new graph can compute its own hash, and directly see whether the hash/graph already exists (in some form), or not, by simply reading the filenames (instead of the file-content). This would have a (*checking) complexity of O(1) (actually O(0) according to the clarification below) instead of O(n) per graph.</p>
<h2>Clarification *Checking</h2>
<ul>
<li>With *checking, I mean the amount of times a graph is loaded from file (to compute some property of it).</li>
<li>O(m) where m is the number of non-isomorphic graphs exist of size <code>n</code>.</li>
</ul>
<h2>Assumptions</h2>
<p>I assume the graphs need to be stored in plain text.
I assume checking (by means of loading a plain text graph) is quite expensive.</p>
<h2>Question</h2>
<p>Is it possible to compute some hash of an undirected networkx graph <code>x</code> in Python that allows another graph <code>y</code> to determine whether it is isomorphic to that graph or not by comparison of its own hash to that hash of graph <code>x</code>? If yes, how would one do that?</p>
|
<python><networkx><graph-theory><isomorphism>
|
2023-03-22 16:49:15
| 1
| 2,887
|
a.t.
|
75,814,954
| 11,143,781
|
OpenCV imshow window doesnt update itself
|
<p>I have the code as follows:</p>
<pre><code>import cv2
import numpy as np
source = 'test.mp4'
cap = cv2.VideoCapture(source)
window = "Window"
cv2.startWindowThread()
cv2.namedWindow(window)
cv2.moveWindow(window, 10, 10)
while cap.isOpened():
ret, img = cap.read()
if not ret:
break
# Convert the image to grayscale
n_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Apply Gaussian Blur to reduce noise
blur = cv2.GaussianBlur(n_gray, (5, 5), 0)
# Sobel Edge Detection
# Sobel Edge Detection on the X axis
sobel_x = cv2.Sobel(src=blur, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=5)
# Sobel Edge Detection on the Y axis
sobel_y = cv2.Sobel(src=blur, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=5)
# Combined X and Y Sobel Edge Detection
sobel_xy = cv2.Sobel(src=blur, ddepth=cv2.CV_64F, dx=1, dy=1, ksize=5)
img = np.hstack((sobel_x, sobel_y, sobel_xy))
img = cv2.resize(img, (1920, 1080))
cv2.imshow('Window', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
</code></pre>
<p>However, I can see imshow window is opened but it does not update itself, so it stays blank. I got <code>Qt: Session management error: Could not open network socket</code> message on the console. Could you help me if there is anything wrong? Thanks!</p>
|
<python><qt><opencv>
|
2023-03-22 16:37:18
| 0
| 316
|
justRandomLearner
|
75,814,843
| 7,984,318
|
How to convert a pandas Dataframe to a xml tree format like pattern
|
<p>I have a Dataframe ,you can have it by running :</p>
<pre><code>import pandas as pd
from io import StringIO
df = """
Name Type Format
loan1 i type:num;width:10
loan2 a type:char;width:2
loan3 i type:date;width:8;dec:0
"""
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')
</code></pre>
<p>I want to receive something like this:</p>
<pre><code><th name="loan1" type="i" format="type:num;width:10">loan1</th>
<th name="loan2" type="a" format="type:char;width:2">loan2</th>
<th name="loan3" type="i" format="type:date;width:8;dec:0">loan3</th>
</code></pre>
<p>It can be either string in txt or a xml file , Any friend can help ?</p>
|
<python><pandas><xml><dataframe><python-xmlschema>
|
2023-03-22 16:25:30
| 1
| 4,094
|
William
|
75,814,839
| 6,524,326
|
Download all pubmed central article ids that have a keyword appearing in their titles/abstracts and also falling between two dates
|
<p>I am using the following code to download all pubmed central article ids that have a keyword appearing in their titles/abstracts and also falling between two dates. The code seems to work when I select database = "pubmed" but when I switch to database = "pmc" I get empty list. For example, using the start and end dates as mentioned in the code I get 4 PubMed ids: ['36902449', '36880658', '36583446', '35239250'] and when I check manually, the first one among them (which is '36902449') is also present in PMC database, of course, the id is different (10003631) but same article. The code is expected to fetch that id. I'd appreciate it if someone could point out what I'm missing here.</p>
<pre><code>import os
import datetime
from Bio import Entrez
# Set the email address to identify yourself to NCBI
Entrez.email = "example@gmail.com"
# Set the date range for the search
start_date = datetime.datetime(2023, 3, 1)
end_date = datetime.datetime(2023, 3, 22)
# Format the dates as strings in the correct format
start_date_str = start_date.strftime("%Y/%m/%d")
end_date_str = end_date.strftime("%Y/%m/%d")
# Build the search query with the date range
keyword = "dosage compensation"
# database = "pubmed"
database = "pmc"
# Use esearch to fetch the list of matching article IDs
if database == "pubmed":
search_term = f'("{start_date_str}"[Date - Publication] : "{end_date_str}"[Date - Publication]) AND {keyword}[Title/Abstract]'
handle = Entrez.esearch(db=database,
term=search_term,
retmax=100,
api_key = os.environ['ENTREZ_API_KEY'])
elif database == "pmc":
search_term = f'("{start_date_str}"[Publication Date] : "{end_date_str}"[Publication Date]) AND {keyword}[Title/Abstract] AND open_access[filter]'
handle = Entrez.esearch(db=database,
term=search_term,
retmax=1000,
api_key = os.environ['ENTREZ_API_KEY'])
record = Entrez.read(handle)
id_list = record['IdList']
handle.close()
# Print the number of matching articles
print(f"Found {len(id_list)} articles published between {start_date_str} and {end_date_str} in {database}")
# print(id_list)
</code></pre>
|
<python><biopython>
|
2023-03-22 16:24:58
| 1
| 828
|
Wasim Aftab
|
75,814,736
| 12,743,647
|
Gracefully handling keyboard interrupt for Python multi-processing
|
<p>I am working on a project which runs two separate python processes. When I do a <code>ctrl + c</code> to end the program, I would like the program to end gracefully.</p>
<p>I can produce a minimum working version of the code through the following:</p>
<pre><code>from multiprocessing import Process
import os
import sys
import time
class Test:
def __init__(self):
pass
def run(self):
self.process_a = Process(target=self.main, daemon=True)
self.process_b = Process(target=self.other_func, daemon=True)
self.process_a.start()
self.process_b.start()
self.process_a.join()
self.process_b.join()
def main(self):
try:
while True:
print('sending stuff...')
time.sleep(5)
except KeyboardInterrupt:
self.shutdown()
def other_func(self):
while True:
print("do other stuff...")
time.sleep(5)
def shutdown(self):
print("\nCTRL+C pressed ...")
print("Shutting Down...")
# os._exit(1)
if __name__ == '__main__':
mytest = Test()
mytest.run()
</code></pre>
<p>When performing a keyboard interrupt, I get the error after it prints <code>Shutting Down...</code>:</p>
<pre><code>Traceback (most recent call last):
File "testing-error.py", line 47, in <module>
mytest.run()
File "testing-error.py", line 18, in run
self.process_a.join()
File "/usr/lib/python3.8/multiprocessing/process.py", line 149, in join
res = self._popen.wait(timeout)
File "/usr/lib/python3.8/multiprocessing/popen_fork.py", line 47, in wait
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
File "/usr/lib/python3.8/multiprocessing/popen_fork.py", line 27, in poll
pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt
</code></pre>
<p>In fact, I can further reduce the code down to the following and get the same error:</p>
<pre><code>from multiprocessing import Process
import os
import sys
import time
class Test:
def __init__(self):
pass
def run(self):
self.process_a = Process(target=self.main, daemon=True)
self.process_a.start()
self.process_a.join()
def main(self):
try:
while True:
print('sending stuff...')
time.sleep(5)
except KeyboardInterrupt:
self.shutdown()
def shutdown(self):
print("\nCTRL+C pressed ...")
print("Shutting Down...")
# os._exit(1)
if __name__ == '__main__':
mytest = Test()
mytest.run()
</code></pre>
<p>Can anyone help me understand what's going wrong?</p>
|
<python><python-3.x><multithreading><process><multiprocessing>
|
2023-03-22 16:13:11
| 1
| 518
|
bgmn
|
75,814,642
| 1,401,560
|
How can I fix ModuleNotFoundError: No module named 'pysftp' for an Ansible library?
|
<p>On a Mac OS</p>
<pre><code>$ ansible --version
ansible 2.10.8
config file = /Users/cfouts/.ansible.cfg
configured module search path = ['/Users/myUser/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/Cellar/ansible/3.3.0/libexec/lib/python3.9/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.9.4 (default, Apr 5 2021, 01:50:46) [Clang 12.0.0 (clang-1200.0.32.29)]
</code></pre>
<p>This is a follow up to <a href="https://stackoverflow.com/questions/75632371/in-ansible-how-to-download-from-a-secure-ftp-sftp-server">In Ansible, how to download from a secure FTP (SFTP) server?</a></p>
<p>I'm trying to modify the <a href="https://github.com/melmorabity/ansible-ftp/blob/master/ftp.py" rel="nofollow noreferrer">ftp.py</a> library mentioned in the answer in above post to support SFTP by adding the <code>pysftp</code> library. So I added</p>
<pre class="lang-py prettyprint-override"><code>import contextlib
from enum import Enum
import ftplib
import hashlib
import os
import tempfile
import time
import pysftp <--------- Added this
</code></pre>
<p>Now I'm getting</p>
<pre><code>TASK [downloader : Download] **************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ModuleNotFoundError: No module named 'pysftp'
fatal: [10.227.x.x]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/Users/myUser/.ansible/tmp/ansible-tmp-1679500320.631737-50774-110602676057179/AnsiballZ_ftp.py\", line 102, in <module>\n _ansiballz_main()\n File \"/Users/myUser/.ansible/tmp/ansible-tmp-1679500320.631737-50774-110602676057179/AnsiballZ_ftp.py\", line 94, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/Users/myUser/.ansible/tmp/ansible-tmp-1679500320.631737-50774-110602676057179/AnsiballZ_ftp.py\", line 40, in invoke_module\n runpy.run_module(mod_name='ansible.modules.ftp', init_globals=None, run_name='__main__', alter_sys=True)\n File \"/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py\", line 210, in run_module\n return _run_module_code(code, init_globals, run_name, mod_spec)\n File \"/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py\", line 97, in _run_module_code\n _run_code(code, mod_globals, init_globals,\n File \"/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py\", line 87, in _run_code\n exec(code, run_globals)\n File \"/var/folders/kb/mk006j312mz2nyxbxd66gmth9fk800/T/ansible_ftp_payload_3u9acyhb/ansible_ftp_payload.zip/ansible/modules/ftp.py\", line 27, in <module>\nModuleNotFoundError: No module named 'pysftp'\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
</code></pre>
<p>It can't find the <code>pysftp</code> module. I even added this task before calling the <code>ftp.py</code> module</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Install pysftp
pip:
name:
- pysftp
delegate_to: localhost
- name: Download from SFTP server using ftp.py library
ftp:
protocol: sftp
...
delegate_to: localhost
</code></pre>
<p>But I just get</p>
<pre><code>TASK [downloader : Install pysftp] ********************************************************************************************************************
ok: [10.227.x.x]
</code></pre>
<p>which indicates that the module is installed?</p>
<p>What gives? How can I fix this? TIA</p>
|
<python><python-3.x><ansible>
|
2023-03-22 16:03:35
| 0
| 17,176
|
Chris F
|
75,814,525
| 19,980,284
|
Statsmodels Clustered Logit Model With Robust Standard Errors
|
<p>I have the following dataframe:</p>
<pre class="lang-py prettyprint-override"><code>df.head()
id case volfluid map rr o2 fluid
1044 36 3 3.0 1.0 3.0 2.0 0.0
1045 37 3 2.0 3.0 1.0 2.0 1.0
1046 38 3 3.0 2.0 2.0 1.0 0.0
1047 36 4 2.0 3.0 1.0 3.0 1.0
1048 37 4 1.0 1.0 3.0 3.0 1.0
.
.
.
</code></pre>
<p>I want to run a logistic regression model clustered on <code>id</code> and with robust standard errors. Here is what I have for the equation</p>
<pre class="lang-py prettyprint-override"><code>smf.logit('''fluid ~ C(volfluid) + C(map, Treatment(reference = 3.0)) +
C(o2, Treatment(reference = 3.0)) + C(rr) +
C(case, Treatment(reference = 4))''',
data = df).fit(cov_type='cluster', cov_kwds={'groups': df['id']})
</code></pre>
<p>I'm not sure if this accomplishes both the clustering, and the robust std. errors. I understand that setting <code>cov_type = 'hc0'</code> provides robust std. errors, but if I do that can I still cluster on <code>id</code>? And do I need to do that, or are clustered standard errors inherently robust?</p>
<p>Thank you!</p>
|
<python><logistic-regression><statsmodels><stderr>
|
2023-03-22 15:52:04
| 1
| 671
|
hulio_entredas
|
75,814,486
| 9,205,210
|
In sklearn, is there a way to get access to the .loss_curve_ attribute of an MLPClassifier after using GridSearchCV?
|
<p>I would like to be able to plot the loss curves for each set of parameter combinations that was used within a run of fitting MLP models within GridSearchCV.</p>
<p>I am able to access the loss curve if I have a fixed set of parameters, eg:</p>
<pre><code>import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.neural_network import MLPClassifier
mlp_nickname = 'my_mlp'
def test(
X_TV,
y_TV,
X_Test,
y_Test,
train_dict,
random_state,
):
# Initialize learner pipeline
pipeline = Pipeline([])
learner = MLPClassifier()
learner.set_params(random_state=random_state)
pipeline.steps.append((mlp_nickname, learner))
# Set hard-coded parameters for this experiment
pipeline.set_params(**hf.pipeline_helper(train_dict, mlp_nickname))
# Test model
final_model = pipeline.fit(X_TV, y_TV)
plt.plot(final_model[mlp_nickname].loss_curve_) # This works!
</code></pre>
<p>However, if I do training through GridSearchCV, I am not seeing if/how to access the loss curve data</p>
<pre><code>def train(
X_TV,
y_TV,
train_dict,
param_grid,
random_state,
):
# Initialize learner pipeline
pipeline = Pipeline([])
learner = MLPClassifier()
learner.set_params(random_state=random_state)
pipeline.steps.append((mlp_nickname, learner))
# Set hard-coded parameters for this experiment
pipeline.set_params(**hf.pipeline_helper(train_dict, mlp_nickname))
# Fit
print('\tGridSearch verbose:')
grid = GridSearchCV(
pipeline,
param_grid,
scoring = 'f1_weighted',
n_jobs = -1,
refit = True,
cv = 5,
verbose = 1,
return_train_score = False,
)
grid.fit(X=X_TV, y=y_TV)
</code></pre>
<p>At this stage, GridSearchCV works as expected and I am able to access the hyperparameters that perform the best. However, I also want to be able to view the loss curves from each run, is this possible?</p>
<p>Thanks!</p>
|
<python><scikit-learn>
|
2023-03-22 15:48:18
| 0
| 400
|
Francisco C
|
75,814,350
| 1,158,427
|
Bamboolib in Databricks
|
<p>I was looking to have a UI within databricks notebook use it to display data from a dataframe. I also wanted to edit the rows or insert new rows from the UI.</p>
<p>I tried bamboolib but the edit button looks disabled. Is there a way I can insert new rows and possibly edit existing ones from the UI itself ?</p>
<p><a href="https://i.sstatic.net/7F9Wa.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7F9Wa.png" alt="enter image description here" /></a></p>
|
<python><azure-databricks>
|
2023-03-22 15:37:30
| 2
| 1,447
|
Chhaya Vishwakarma
|
75,814,306
| 5,090,059
|
Tensorflow vs. Pytorch β identical model leads to different results
|
<p>I'm trying to implement 2 identical models in Tensorflow and Pytorch. I am using an extremely simple network. To make sure they are identical I am copying over the initial weights from Tensorflow to Pytorch. This seems to work if I don't fit the model. The initial weights lead to identical predictions.</p>
<p>However, as soon as I run a single training epoch, the models diverge. I am using the same hyperparameters/optimizers. How is this possible?</p>
<h2>Loading the data</h2>
<pre><code>from sklearn.datasets import load_diabetes
X, y = load_diabetes(as_frame=True, return_X_y = True)
shape = X.to_numpy().shape[1]
</code></pre>
<h2>Initializing the tensorflow model</h2>
<pre><code>import tensorflow as tf
feature_inputs = tf.keras.layers.Input(name="feature_input", shape=shape)
hidden_layer = tf.keras.layers.Dense(10)(feature_inputs)
activation = tf.keras.layers.Activation('relu')(hidden_layer)
output = tf.keras.layers.Dense(1)(activation)
model = tf.keras.Model(inputs=feature_inputs, outputs=output)
keras_weights = model.get_weights()
</code></pre>
<h2>Initializing the pytorch model</h2>
<pre><code>import torch
from torch import nn
from torch.utils.data import DataLoader
class MLP(nn.Module):
def __init__(self, input_shape, *args, **kwargs):
super().__init__()
self.layer1 = nn.Linear(input_shape, 10)
self.layer2 = nn.Linear(10, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.layer1(x)
x = self.relu(x)
x = self.layer2(x)
return x
class Dataset(torch.utils.data.Dataset):
def __init__(self, X, y):
if not torch.is_tensor(X) and not torch.is_tensor(y):
self.X = torch.from_numpy(X)
self.y = torch.from_numpy(y)
def __len__(self):
return len(self.X)
def __getitem__(self, i):
return self.X[i], self.y[i]
train_data = Dataset(X=X.to_numpy(), y=y.to_numpy())
trainloader = torch.utils.data.DataLoader(train_data, shuffle=False)
mlp = MLP(input_shape=shape)
torch_weights = mlp.state_dict()
</code></pre>
<h2>Copying over initial weights</h2>
<pre><code>new_weights = {}
for idx, key in enumerate(torch_weights.keys()):
if key.endswith('weight'):
new_weights[key] = torch.Tensor(keras_weights[idx].T)
else:
new_weights[key] = torch.Tensor(keras_weights[idx])
mlp.load_state_dict(new_weights)
</code></pre>
<h2>Comparing outputs</h2>
<p>The model now give identical predictions when giving it the training data:</p>
<pre><code>mlp(torch.from_numpy(X.astype(np.float32).to_numpy()))[0]
# Returns -0.0361
model.predict(X)[0]
# Returns -0.0361313
</code></pre>
<h2>Running 5 training epochs</h2>
<p>For tensorflow:</p>
<pre><code>optimizer = tf.keras.optimizers.SGD(learning_rate=1e-8)
model.compile(optimizer, loss="mean_squared_error")
history = model.fit(x=X, y=y,
epochs=5,
verbose=True,
shuffle=False)
</code></pre>
<p>For pytorch:</p>
<pre><code>loss_function = nn.MSELoss()
optimizer = torch.optim.SGD(mlp.parameters(), lr=1e-8)
for epoch in range(0, 5):
for i, train_data in enumerate(trainloader, 0):
inputs, targets = train_data
inputs, targets = inputs.float(), targets.float()
targets = targets.reshape((targets.shape[0], 1))
optimizer.zero_grad()
outputs = mlp(inputs)
training_loss = loss_function(outputs, targets)
training_loss.backward()
optimizer.step()
</code></pre>
<p>If I now repeat the prediction step, the models have diverged:</p>
<pre><code>mlp(torch.from_numpy(X.astype(np.float32).to_numpy()))[0]
# Returns -0.025996
model.predict(X)[0]
# Returns -0.037605
</code></pre>
|
<python><tensorflow><pytorch>
|
2023-03-22 15:34:15
| 0
| 429
|
Nils Mackay
|
75,814,043
| 5,212,614
|
How can we convert a Pandas Core Series into separate and distinct columns?
|
<p>I am normalizing a JSON response, like this.</p>
<pre><code>df = pd.json_normalize(response, record_path=['data'])
</code></pre>
<p>Now, if I run this: <code>print(type(df['locations']))</code></p>
<p>I get this result: <code><class 'pandas.core.series.Series'></code></p>
<p>So, <code>'df['locations']'</code> is comprised of this:</p>
<pre><code>df['locations']
Out[246]:
0 [{'time': '2023-01-01T06:49:49Z', 'latitude': ...
1 [{'time': '2023-01-01T01:03:35Z', 'latitude': ...
2 [{'time': '2023-01-01T02:30:45Z', 'latitude': ...
3 [{'time': '2023-01-01T06:38:42Z', 'latitude': ...
4 [{'time': '2023-01-01T01:02:19Z', 'latitude': ...
</code></pre>
<p>Now, if I try this: <code>df = pd.DataFrame([df['locations']])</code></p>
<p>I get this result: <code>[1 rows x 196 columns]</code></p>
<p>I tried to mess around with the string, like this...</p>
<pre><code>df_final = df.iloc[1:100].to_string()
df_final = pd.DataFrame(df_final)
</code></pre>
<p>I got an error saying:</p>
<pre><code>ValueError: DataFrame constructor not properly called!
</code></pre>
<p>How can I normalize df['locations'] into 196 separate and distinct columns? That seems to be the issue here.</p>
|
<python><python-3.x><dataframe><series>
|
2023-03-22 15:10:07
| 0
| 20,492
|
ASH
|
75,813,849
| 10,428,677
|
Approach for improving runtime of Python function
|
<p>I have a function that relies on a dictionary to identify the files it needs to read and the variable names they're linked to. The function then reads the file, calculates the outputs (in this case a mean value) and returns it as a column in an existing dataframe. This all works well when the files are different, but I have a few cases where I have different variables that are linked to the same file. The function calculates some zonal stats for a Geopandas df.</p>
<p>Is there a more efficient way of going about how I read the files? At the moment the function reads the same file multiple times and calculates the same values, but saves them under a different column name. It's proving to be quite inefficient in terms of time.</p>
<pre><code># The data dictionary has a structure like the one below. Sometimes there are 4-5 variables linked to the same file.
FILEPATH = {"variable_1": "path/commonfile.tif",
"variable_2": "path/commonfile.tif",
"variable_3": "path/commonfile.tif",
"variable_4": "path/otherfile1.tif",
"variable_5": "path/someotherfile1.tif"}
# my function is like the one below
for variable, filename in FILEPATH.items():
my_df.loc[:, f'{variable}'] = myfunction(df=my_df, file=f'{filename}', stats_list = ['mean'])
</code></pre>
|
<python><pandas><dictionary><geopandas>
|
2023-03-22 14:54:17
| 1
| 590
|
A.N.
|
75,813,754
| 13,484,397
|
Validate audio coming from FastAPI using Pydantic
|
<p>I'm working on a transcriber API. It has one endpoint /transcribe, and takes an audio file to be transcribed.
I want to add some Pydantic validators (make sure that the MIME type is audio/, make sure that the audio is big enough (bigger than 1 sec). I have not found any way to validate data coming from a form.</p>
<p>I have tried making an Audio base model than inherits from both the BaseModel and UploadFile, but it is not working:</p>
<pre><code># Audio validator
class Audio(UploadFile, BaseModel):
content_type: str
data: bytes
@validator('data')
def validate_data(cls,data):
if data <= 1:
raise ValueError("Audio file uploaded is too short.")
return data
@validator('content_type')
def validate_type(cls,content_type):
if not content_type.startswith("audio/"):
raise TypeError("The file uploaded is not an audio file.")
</code></pre>
<p>The endpoint and header are as follows:</p>
<pre><code>@app.post("/transcribe")
async def transcribe(request: Request, lang: str = None, file: Audio = File(...), doctor_name: str = "Dr"):
audio = await file.read()
</code></pre>
<p>Any advice?</p>
|
<python><validation><fastapi><mime-types><pydantic>
|
2023-03-22 14:45:42
| 0
| 414
|
Ralph Aouad
|
75,813,713
| 3,924,118
|
Is it possible not to show the arguments in a specific parametrized test function?
|
<p>I have a pytest's paremetrized test function like this</p>
<pre><code># imports
LONG_STRING = "hello world " * 10000
@mark.parametrize("a,c,b", [[LONG_STRING, 2, 3], [LONG_STRING, 2, 3]])
def test_something(a, b, c):
# test whatever
</code></pre>
<p>Now, when I run this test function, I see the value of <code>LONG_STRING</code> in the stdout. Is there a way not to show this argument for this <strong>specific</strong> test function (so I don't want to disable this for all test functions)?</p>
<p>I've noticed that pytest sometimes shows the value (e.g. in the case above), but it doesn't always show the value. For example, if the argument is a list or dictionary, then it shows the parameter name rather than its value.</p>
|
<python><pytest>
|
2023-03-22 14:42:25
| 1
| 16,044
|
nbro
|
75,813,668
| 528,369
|
Read pandas dataframe from file until sentinel value?
|
<p>Given the CSV file below that stores multiple dataframes, can I use <code>pd.read_csv()</code> to read until a sentinel value is detected, in this case "#"?</p>
<pre><code>x,y
2,4
3,9
#
x,y
2,8
3,27
</code></pre>
|
<python><pandas>
|
2023-03-22 14:39:26
| 1
| 2,605
|
Fortranner
|
75,813,646
| 19,889,754
|
Why am I getting 'Different version pinnings of the same package' error when pinning python version in Foundry Code Repository?
|
<p>I'm facing an error when trying to require a minimum python version for my shared library in the <code>meta.yml</code> file (by pinning python >= 3.6) in order to use it in various repositories supporting different python version (3.6, 3.8 for instance).</p>
<p>When pinning Python>= 3.6 the checks are not passing and I got the error in the screenshot below. How would I go about debugging this?</p>
<p><a href="https://i.sstatic.net/0ngcQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0ngcQ.png" alt="enter image description here" /></a></p>
|
<python><palantir-foundry><foundry-code-repositories>
|
2023-03-22 14:37:14
| 1
| 355
|
Max Magid
|
75,813,603
| 14,607,802
|
Python, working with sound: librosa and pyrubberband conflict
|
<p>I have the following script that I was using to manipulate an mp3:</p>
<pre><code>import librosa
import soundfile as sf
from playsound import playsound
from direct.showbase.ShowBase import ShowBase
#import pyrubberband as pyrb
filename = "music.mp3"
y, sr = librosa.load(filename)
tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
bars = []
bar_dif=[]
initial_beat = beat_frames[0]
for i in range(0,len(beat_frames)):
if i != 0:
bar_dif.append(beat_frames[i]-beat_frames[i-1])
if i % 16 == 0:
bars.append(beat_frames[i])
for i in range(0,len(bars)):
if i != len(bars) - 1:
start = bars[i]
end = bars[i+1]+1
start_sample = librosa.frames_to_samples(start)
end_sample = librosa.frames_to_samples(end)
y_cut = y[start_sample:end_sample]
sf.write(f"bar_{i}.wav", y_cut, sr)
base = ShowBase()
#Section A
#sound = base.loader.loadSfx("bar_27.wav")
#sound.setLoop(True)
#sound.setPlayRate(1.5)
#sound.play()
#base.run()
#Section B
#stretched_samples, _ = sf.read("bar_27.wav")
#tempo_factor = 1.5
#stretched_samples = pyrb.time_stretch(stretched_samples, sr, tempo_factor)
#stretched_sound = base.loader.loadSfxData(stretched_samples.tobytes())
#stretched_sound.setLoop(True)
#stretched_sound.setLoop(True)
#stretched_sound.play()
#base.run()
</code></pre>
<p>Originally I just had section A up and running with no pyrubberband. The script at this stage split the song bar bars of 4. It would then play a loop of a specific bar. It would then speed the loop up. The issue with this is that it pitched my sample up, which I did not want.</p>
<p>I then decided to install pyrubberband to try to pitch shift the sample. Now I receive errors on the line <code>y, sr = librosa.load(filename)</code> (See below) I then decided to uninstall/delete pyrubberband / section B, put the problem still persists. I then uninstalled and reinstalled librosa and re-downloaded the mp3, but he problem still persists.</p>
<p>Have I broken my computer?</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Charlie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\librosa\core\audio.py", line 176, in load
y, sr_native = __soundfile_load(path, offset, duration, dtype)
File "C:\Users\Charlie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\librosa\core\audio.py", line 209, in __soundfile_load
context = sf.SoundFile(path)
File "C:\Users\Charlie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\soundfile.py", line 740, in __init__
self._file = self._open(file, mode_int, closefd)
File "C:\Users\Charlie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\soundfile.py", line 1264, in _open
_error_check(_snd.sf_error(file_ptr),
File "C:\Users\Charlie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\soundfile.py", line 1455, in _error_check
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
RuntimeError: Error opening 'music.mp3': File contains data in an unknown format.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Charlie\Desktop\BeatMaker\beatmaker.py", line 12, in <module>
y, sr = librosa.load(filename)
File "C:\Users\Charlie\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\librosa\core\audio.py", line 178, in load
except sf.SoundFileRuntimeError as exc:
AttributeError: module 'soundfile' has no attribute 'SoundFileRuntimeError'
</code></pre>
|
<python><librosa>
|
2023-03-22 14:33:16
| 2
| 817
|
Charmalade
|
75,813,474
| 12,214,867
|
I'm trying to scrape a Bing dict page with BeautifulSoup. However, response.content doesn't contain the actual data, how do I do?
|
<p>I'm trying to scrape a Bing dict page <a href="https://cn.bing.com/dict/search?q=avengers" rel="nofollow noreferrer">https://cn.bing.com/dict/search?q=avengers</a></p>
<p>Here is the code</p>
<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup
url = "https://cn.bing.com/dict/search?q=avengers"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, "html.parser")
examples = soup.find_all("div", class_="sen_en b_regtxt")
for example in examples:
print(example.text.strip())
</code></pre>
<p>In particular, I'm trying scrape all the example sentences on that page, which is contained in a <code>div</code> with class <code>sen_en b_regtxt</code></p>
<p>However, <code>response.content</code> doesn't even contain one example sentence in it, what am I missing?</p>
<p>PS, access to the page doesn't need login</p>
<p><a href="https://i.sstatic.net/7qDLD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7qDLD.png" alt="enter image description here" /></a></p>
<p>With @Artur Chukhrai's help, I also tried with selenium and I got "No results found for avenger"</p>
<p><a href="https://i.sstatic.net/FhxnN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FhxnN.png" alt="enter image description here" /></a></p>
<p>However, if I access the url "cn.bing.com/dict" first, and then put the keyword in the search box, I would get the result page.</p>
|
<python><web-scraping><beautifulsoup>
|
2023-03-22 14:21:50
| 3
| 1,097
|
JJJohn
|
75,813,381
| 21,037,446
|
Python for loop through nested dictionary question?
|
<p>Trying to loop through a nested dictionary and want to store values into name, age and occupation. Without manually creating those variables within the for loop. Is this even possible? Just trying to create cleaner looking code. Thank you.</p>
<pre><code>people = {
1: {"name": "Simon", "age": 20, "occupation": "Data scientist"},
2: {"name": "Kate", "age": 30, "occupation": "Software engineer"},
3: {"name": "George", "age": 22, "occupation": "Manager"},
}
for person in people:
for name, age, occupation in people[person].values():
print(name, age, occupation)
</code></pre>
|
<python><dictionary><for-loop><nested>
|
2023-03-22 14:13:59
| 2
| 439
|
RishV
|
75,813,348
| 9,182,743
|
Missleading display of values in pandas column when each cell is a list
|
<p>In jupiter notebook</p>
<p>This column made up of two different lists, are displayed the same way.</p>
<pre class="lang-py prettyprint-override"><code>pd.DataFrame({
"user": ["a", "b"],
"values": [['1', '2, 1', '2', '3'], ['1, 2', '1, 2, 3']]
})
</code></pre>
<p><a href="https://i.sstatic.net/vG1NL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vG1NL.png" alt="![enter image description here" /></a></p>
<p><strong>Q:</strong> how to display these lists so that they look different.</p>
|
<python><pandas>
|
2023-03-22 14:10:32
| 1
| 1,168
|
Leo
|
75,813,337
| 1,298,461
|
How to save/load faiss KMeans for later inference
|
<p>I have successfully clustered a bunch of vectors using the faiss kmeans. But now I am not able to store the model and load it later for inference.</p>
<pre><code>clustering = faiss.Kmeans(candles.shape[1], k=clusters, niter=epochs, gpu=gpu, verbose=True)
clustering.train(X)
cluster_index = clustering.index
# failed with "don't know how to serialize this type of index"
faiss.write_index(cluster_index, f"{out_file}.faiss")
model2 = faiss.read_index(f"{out_file}.faiss")
model2.search(x, 1)
</code></pre>
|
<python><faiss>
|
2023-03-22 14:09:42
| 1
| 6,069
|
KIC
|
75,813,310
| 11,829,398
|
Is it possible to have a pandas categorical column where each row can contain multiple categories?
|
<p>I would like to categorize the rows in my dataframe. Each row can belong to multiple categories.</p>
<pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({
'A': ['a, b', 'b, c, d', 'c'],
'B': [1, 2, 3]
})
</code></pre>
<p>If I do</p>
<pre class="lang-py prettyprint-override"><code>df['A'].astype('category')
Out[1]:
0 a, b
1 b, c, d
2 c
Name: A, dtype: category
Categories (3, object): ['a, b', 'b, c, d', 'c']
</code></pre>
<p>It thinks the categories are the full strings. I'd like the categories to be a, b, c, and d.</p>
<p>P.S. I know I can do this by having separate columns <code>is_a</code>, <code>is_b</code> etc. but thought this solution may be easier/more scalable.</p>
|
<python><pandas>
|
2023-03-22 14:06:56
| 3
| 1,438
|
codeananda
|
75,813,294
| 351,885
|
How should I obtain the covariance matrix for the fit parameters calculated by numpy.polynomial.polynomial.polyfit?
|
<p>In the past I have used the numpy.polyfit function for least-squares fitting to a straight line in a first-year programming course for physics students. However, the NumPy documentation now recommends using numpy.polynomial.polynomial.polyfit instead as this newer Polynomial library is more stable numerically. However, the newer function does not have the <code>cov</code> parameter to calculate the covariance matrix as well as the best-fit values for the parameters.</p>
<p>Is there a way to get this information from numpy.polynomial.polynomial.polyfit, or is there another NumPy function that can be used instead?</p>
<p>This can be done using scipy.optimize.curve_fit, but I would like to avoid the additional complexity for now as most of our students are new to programming.</p>
|
<python><numpy>
|
2023-03-22 14:05:38
| 0
| 2,398
|
Ben
|
75,813,223
| 6,224,975
|
Get columns of 2D ndarray defined by index' in another 2D ndarray
|
<p>I have an ndarray <code>arr = np.array([[1,2,3],[4,5,6],[7,8,9]])</code> and an index-array</p>
<p><code>arr_idx = np.array([[0,2],[1,2],[2,1]])</code> where each row in <code>arr_idx</code> corresponds to the index of <code>arr</code> which I want to have i.e the result should be <code>[[1,3],[5,6],[9,8]]</code>.</p>
<p>Can this be done using numpy-operations? I can do it using e.g listcomprehension, but it's some fairly large data that I have, thus if we can vectorize it, that would be better.</p>
<p>I have tried</p>
<pre class="lang-py prettyprint-override"><code>
result = arr[arr_idx]
</code></pre>
<p>which results in</p>
<pre><code>array([[[1, 2, 3],
[7, 8, 9]],
[[4, 5, 6],
[7, 8, 9]],
[[7, 8, 9],
[4, 5, 6]]])
</code></pre>
<p>which should've been <code>array([[1,3],[5,6],[9,8]])</code></p>
|
<python><arrays><numpy>
|
2023-03-22 13:58:40
| 1
| 5,544
|
CutePoison
|
75,813,077
| 4,907,339
|
Peewee x Dash: DB connections aren't reused when called inside a Dash callback function
|
<p>I'm noticing that within a Plotly Dash app that uses a DB managed by Peewee, I'm getting <code>playhouse.pool.MaxConnectionsExceeded: Exceeded maximum connections.</code>, which is visible here:</p>
<pre class="lang-sql prettyprint-override"><code>ariobot=# SELECT count(*) FROM pg_stat_activity where client_port > 0 and application_name = 'test 1';
count
-------
21
(1 row)
ariobot=#
</code></pre>
<p>This is the code that presents this behaviour:</p>
<pre class="lang-py prettyprint-override"><code># test1.py
from peewee import Model, TextField
from playhouse.pool import PooledPostgresqlExtDatabase
db = PooledPostgresqlExtDatabase(
"postgresql://postgres@127.0.0.1:5432/ariobot", autoconnect=True, application_name='test 1'
)
class BaseModel(Model):
class Meta:
database = db
class Test(BaseModel):
test = TextField()
db.create_tables([Test])
from dash import register_page, dash_table, callback, dcc, Input, Output, html, Dash
app = Dash(__name__)
app.layout = html.Div(
[
html.Div(id="value"),
dcc.Interval(id="db_query_interval", interval=10000, n_intervals=0),
]
)
@callback(
Output("value", "children"),
Input("db_query_interval", "n_intervals"),
)
def do_stuff(interval):
db = Test.select()
for db in db:
val = db.test
return val
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>This <code>test2.py</code> re-uses the same connection on each iteration of the loop, which is how I would have expected Dash to work:</p>
<pre class="lang-py prettyprint-override"><code># test2.py
from peewee import Model, TextField
from playhouse.pool import PooledPostgresqlExtDatabase
db = PooledPostgresqlExtDatabase(
"postgresql://postgres@127.0.0.1:5432/ariobot", autoconnect=True, application_name='test 2'
)
class BaseModel(Model):
class Meta:
database = db
class Test(BaseModel):
test = TextField()
db.create_tables([Test])
from time import sleep
while True:
db = Test.select()
for db in db:
val = db.test
print(val)
sleep(1)
</code></pre>
<pre class="lang-sql prettyprint-override"><code>ariobot=# SELECT count(*) FROM pg_stat_activity where client_port > 0 and application_name = 'test 2';
count
-------
2
(1 row)
ariobot=#
</code></pre>
<p>Why is the connection not getting re-used in the <code>test1.py</code> case?</p>
|
<python><plotly-dash><peewee>
|
2023-03-22 13:46:01
| 1
| 492
|
Jason
|
75,812,976
| 5,212,614
|
How to normalize JSON response and convert it into a DataFrame?
|
<p>I am trying to standardize a JSON string and convert it into a dataframe. My actual data is for work and it's confidential so I can't show it here, but I think this small made-up scenario below illustrates the point I'm trying to make.</p>
<pre><code>import json
import requests
import pandas as pd
from pandas.io.json import json_normalize
# doesn't work at all...
url = 'http://api.open-notify.org/iss-now.json'
response = requests.get(url)
text = response.text
# throws error
df = json_normalize(text)
# can convert to list but can't print columns
my_list=[]
my_list.append(text)
print(type(my_list))
df = json_normalize(my_list)
df.columns
print(type(df))
df
</code></pre>
<p>What I get is a dictionary wrapped inside a list. How can I normalize the JSON string and/or convert it into a standardized dataframe? My actual JSON file has a structure like this:</p>
<pre><code>[{'id': '21201', 'name': 'SRW Utility, 4x4', 'latitude': 35.31068751, 'longitude': -80.66177891, 'headingDegrees': 161.2, 'speedMilesPerHour': 0}]
</code></pre>
<p>I am trying to extract 'id', 'latitude', 'longitude', etc, as headers, and show the data in rows below these headers.</p>
|
<python><json><python-3.x><dataframe>
|
2023-03-22 13:37:45
| 1
| 20,492
|
ASH
|
75,812,786
| 6,197,439
|
Have Python output .csv with space-padded, fixed width, but comma-separated columns?
|
<p>Let's say I have CSV data as note below; let's call this <code>original.csv</code>:</p>
<pre><code>name,value1,value2
firstname,34326408129478932874,553
secondname_a_very_long_one,65,123987
thirdname_medium,9686509933423,33
</code></pre>
<p>Basically, it's either single word text (no space separation, so no need for quoting) or numbers (here integers, but could be floats with decimals or scientific 1e-5 notation) - and there is no expectation that a comma could appear somewhere (outside of being a delimiter), so no need for special handling of the quoting of comma either ...</p>
<p>So, to ease the strain on my eyes when I view this .csv file in a text editor, I would like to format it with fixed width - space padded (left or right padding choice made per column, and separately for header row); note that the file is still comma delimited as a data format, the fixed width is just for viewing in editor - this is how I would like it to look like, let's call this <code>tmpfw.csv</code>:</p>
<pre><code>name , value1 , value2
firstname , 34326408129478932874, 553
secondname_a_very_long_one, 65, 123987
thirdname_medium , 9686509933423, 33
</code></pre>
<p>So here, the heading row is all left-aligned (right-padded with spaces); columns <code>name</code> and <code>value2</code> are also left-aligned (right-padded with spaces); and column <code>value1</code> is right-aligned (right-padded with spaces). The columns are sized (in characters) according to the largest string length of the data in that column; and there is an extra space as visual delimiter after the commas.</p>
<p>Of course, if I want to use this data in Python properly, I'd have to "strip" it first - but I don't mind, since as I mentioned, the data is such that I don't have to worry about quoting issues; here is a Python example of how I could use <code>tmpfw.csv</code> - let's call it <code>test.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>import sys
import csv
import pprint
with open('tmpfw.csv', newline='') as csvfile:
my_csv = csv.reader(csvfile)
my_csv_list = list(my_csv)
my_csv_list_stripped = [list(map(str.strip, irow)) for irow in my_csv_list]
print("\nmy_csv_list:\n")
pprint.pprint( my_csv_list )
print("\nmy_csv_list_stripped:\n")
pprint.pprint( my_csv_list_stripped )
#print("\nreprint stripped as csv:\n")
#csvwriter = csv.writer(sys.stdout) # just print out to terminal
#csvwriter.writerows(my_csv_list_stripped)
</code></pre>
<p>This is what I get printed:</p>
<pre class="lang-none prettyprint-override"><code>$ python3 test.py
my_csv_list:
[['name ', ' value1 ', ' value2'],
['firstname ', ' 34326408129478932874', ' 553'],
['secondname_a_very_long_one', ' 65', ' 123987'],
['thirdname_medium ', ' 9686509933423', ' 33']]
my_csv_list_stripped:
[['name', 'value1', 'value2'],
['firstname', '34326408129478932874', '553'],
['secondname_a_very_long_one', '65', '123987'],
['thirdname_medium', '9686509933423', '33']]
</code></pre>
<p>I can use this as a base to convert the numbers to int later - so, I can use such a fixed-width csv fine, all is good ...</p>
<p>So, my question is: let's say I have the <code>original.csv</code> - what would be the easiest way in Python to obtain a "fixed-width formatted" <code>tmpfw.csv</code>? Do <code>csv</code> or <code>pandas</code> or other libraries have facilities for exporting a CSV format like this?</p>
|
<python><csv><string-formatting><fixed-width>
|
2023-03-22 13:21:25
| 1
| 5,938
|
sdbbs
|
75,812,672
| 5,969,893
|
Airflow Trigger Rule Wait for Parent Tasks to finish
|
<p>For my DAG I have a main task(task_1) and then I have 4 additional tasks that follow and need to be executed in sequential order due to system constraints.</p>
<p>Tasks 2,3,4, and 5 need to be executed in sequential order but are dependent on task_1 being successful but are not dependent on other tasks being successful.</p>
<p>So if task_1 is success, then task_2 should kick off, if task_2 fails, task_3 would then kick off because task_1 finished successfully and task_2 has completed although it failed.</p>
<p>I tried using <code>one_sucess</code> for tasks 2,3,4, and 5 but as soon as task_1 completes, all other tasks kick off instead of running in sequential order.</p>
<p>Is there a way to wait for all parent tasks to complete?</p>
<pre><code> task_1>> task_2>> task_3>> task_4>> task_5>>email
task_1>> task_3
task_1>> task_4
task_1>> task_5
</code></pre>
|
<python><airflow><directed-acyclic-graphs>
|
2023-03-22 13:10:23
| 0
| 667
|
AlmostThere
|
75,812,616
| 9,301,805
|
Pandas does not respect conversion to time type
|
<p>I have this dataframe:</p>
<pre><code> site date time
1 AA 2018-01-01 0100
2 AA 2018-01-01 0200
3 AA 2018-01-01 0300
4 AA 2018-01-01 0400
5 AA 2018-01-01 0500
6 AA 2018-01-01 0600
7 AA 2018-01-01 0700
8 AA 2018-01-01 0800
9 AA 2018-01-01 0900
df.dtypes
>>> site object
date datetime64[ns]
time object
</code></pre>
<p>I would like to convert the <code>time</code> column to <code>time</code> type (without date) to later filter the dataframe between desired hours. So I did:</p>
<pre><code>df['time'] = df['time'].apply(lambda x: pd.to_datetime(x, format='%H%M').time())
</code></pre>
<p>The dataframe now looks like this:</p>
<pre><code> site date time
1 AA 2018-01-01 01:00:00
2 AA 2018-01-01 02:00:00
3 AA 2018-01-01 03:00:00
4 AA 2018-01-01 04:00:00
5 AA 2018-01-01 05:00:00
6 AA 2018-01-01 06:00:00
7 AA 2018-01-01 07:00:00
8 AA 2018-01-01 08:00:00
9 AA 2018-01-01 09:00:00
</code></pre>
<p>However, the data type is still an object type:</p>
<pre><code>df.dtypes
>>> site object
date datetime64[ns]
time object
dtype: object
</code></pre>
<p>But, when I check the type for individual value, it does seem to work:</p>
<pre><code>df.at[5,'time']
>>> datetime.time(5, 0)
type(df.at[5,'time'])
>>> datetime.time
</code></pre>
<p>Still, I can't filter the data based on time:</p>
<pre><code>from datetime import time
df[df['time'].between_time(time(5),time(8))]
>>> TypeError: Index must be DatetimeIndex
</code></pre>
|
<python><pandas><datetime><filter><time>
|
2023-03-22 13:04:14
| 1
| 1,575
|
user88484
|
75,812,512
| 8,497,979
|
Filter List of Dictionaries and omit keys
|
<p>I have a list of dictionaries:</p>
<pre><code>resp = [
{
'meter_id': {'S': 'M#G000140'},
'meter_reading_reader': {'S': 'Meyer'},
'meter_reading_date': {'S': '2021-12-21T12:00:00'},
'item_type': {'S': 'READING'},
'meter_reading_value': {'S': '225'},
'meter_reading_unit': {'S': 'cbm'},
'meter_kind': {'S': 'Gas'},
'month': {'S': 'December'},
'year': {'S': '2021'},
'SK': {'S': 'MPID#P-00002-01-MG-001'},
'building_id': {'S': 'B#BUI-00001'},
'PK': {'S': 'READ#G000140#2021#Dec'},
'meter_serial_number': {'S': '7GMT0008942175'}
},
{
'meter_id': {'S': 'M#G000155'},
'meter_reading_reader': {'S': 'Meyer'},
'meter_reading_date': {'S': '2022-02-28T12:00:00'},
'item_type': {'S': 'READING'},
'meter_reading_value': {'S': '45'},
'meter_reading_unit': {'S': 'cbm'},
'meter_kind': {'S': 'Gas'},
'month': {'S': 'February'},
'year': {'S': '2022'},
'SK': {'S': 'MPID#P-00002-01-MG-001'},
'building_id': {'S': 'B#BUI-00001'},
'PK': {'S': 'READ#G000155#2022#Feb'},
'meter_serial_number': {'S': '7GMT0008942175'}
}
]
</code></pre>
<p>that I want to filter to show only 2 key-Value pairs - 'meter_reading_date' and 'meter_reading_value'. So far I can filter with one value.</p>
<pre><code>for item in resp:
details = item['meter_reading_value']
print(details)
</code></pre>
<p>That gives me:</p>
<pre><code>{'S': '225'}
{'S': '45'}
{'S': '12'}
</code></pre>
<p>but what I want to achieve is the following:</p>
<pre><code>{
'meter_reading_date': '2021-12-21T12:00:00',
'meter_reading_value': '225'
},
{
'meter_reading_date': '2022-02-28T12:00:00',
'meter_reading_value': '45'
},
</code></pre>
<p>How is that achievable?</p>
|
<python>
|
2023-03-22 12:52:15
| 4
| 1,410
|
aerioeus
|
75,812,487
| 1,667,018
|
Custom method decorator aware of a class
|
<p>I had an idea for a simple decorator that would probably not be very useful (feel free to comments on that, but it's not my main focus here). Regardless of that, I think it'd show how to achieve certain things and these are my main interest.</p>
<p><strong>The idea:</strong> A decorator <code>@inherit_docs</code> that would simply assign method's <code>__doc__</code> from the one with the same name in the first parent of the class that has it.</p>
<p>For example, let's say that we have this:</p>
<pre class="lang-py prettyprint-override"><code>class A:
def foo(self):
"""
Return something smart.
"""
return ...
</code></pre>
<p>Now, I want this:</p>
<pre class="lang-py prettyprint-override"><code>class B(A):
@inherit_docs
def foo(self):
# Specifically for `B`, the "smart" thing is always 17,
# so the docstring still holds even though the code is different.
return 17
</code></pre>
<p>to be equivalent to this:</p>
<pre class="lang-py prettyprint-override"><code>class B(A):
def foo(self):
"""
Return something smart.
"""
# Specifically for `B`, the "smart" thing is always 17,
# so the docstring still holds even though the code is different.
return 17
</code></pre>
<p>One purpose of this could be to have a base class that declares some functionality and then its inherited classes implement this functionality for different types of data (polymorphism). The methods are doing the same thing, so automating docstrings consistency would be nice. <code>help</code> itself deals with it ok, but <code>B.foo.__doc__</code> does not (<code>B.foo</code> without a docstring has that value as <code>None</code>).</p>
<p>The problems here (and the main reasons why I am interested in it) are:</p>
<ol>
<li>How can <code>inherit_docs</code> know which class it is in (so, how can it now about <code>B</code>)?</li>
<li>How can it get anything about the class (in this case, it's parents) when the class itself doesn't exist at the moment when <code>@inherit_docs</code> is executed?</li>
</ol>
<p>I could likely MacGyver something with metaclasses, but that would mean that the decorator works only on the classes that inherit some class made specifically for this purpose, which is ugly.</p>
<p>I could also have it do nothing when <code>@inherit_docs</code> is called, but then do something when <code>foo</code> itself is called. This would normally work fine (because the call would get <code>self</code> and then play with it or with <code>type(self)</code>), but that won't help in this case, as <code>B.foo.__doc__</code> or <code>help(B.foo)</code> do not call <code>foo</code> itself.</p>
<p>Is this even possible and, if so, how?</p>
|
<python><python-decorators><python-class>
|
2023-03-22 12:50:21
| 2
| 3,815
|
Vedran Ε ego
|
75,812,439
| 4,676,162
|
How to override QMessageBox blocking behavior?
|
<p>I have 2 blocking actions, one of them being QMessageBox <code>exec_</code> method. Second one is a <code>get_weight()</code> function that when it's executed it waits until user puts an item on a scale.</p>
<p>What I'm trying to accomplish is to inform the user with <code>QMessageBox</code> that he needs to do put an item on a scale and then get the weight of the item via <code>get_weight()</code>.</p>
<p>My problem is if I execute <code>exec_()</code> first, I'm unable to call <code>get_weight()</code> in parallel since <code>exec_()</code>is blocking. I could run <code>get_weight()</code> 1st in a separate thread, and then call <code>exec_()</code>, but I have no idea how to programatically close <code>QMessageBox</code>when a certain event happens.</p>
|
<python><pyqt5>
|
2023-03-22 12:46:15
| 0
| 633
|
Sir DrinksCoffeeALot
|
75,812,382
| 11,635,654
|
crash of a nb 22thMarch23 while it was ok 19thJan2023
|
<p>I have a problem that I do not know how to tackle it. I have a nb on Colab that was working perfectly on CPU <a href="https://colab.research.google.com/drive/1gOk9-DqZqF6xbdHM5GBopjOmMAKioSgD" rel="nofollow noreferrer">Here is the working nb 19th Jan 23</a></p>
<p>Then, I was looking to get a new nb working in the same condition (CPU)</p>
<ol>
<li>Dealing with JAX 0.3.25 version I have pip install</li>
</ol>
<pre class="lang-py prettyprint-override"><code>!pip install jax==0.3.25
!pip install jaxlib==0.3.25
</code></pre>
<p>then also pip install my repo at it was Jan 203, using the git commit "tag"</p>
<pre class="lang-py prettyprint-override"><code>!pip install -q git+https://<git-repo>@a3ecb7f
</code></pre>
<p>Now proceeding the same as the Jan nb, crashes
as you can see <a href="https://colab.research.google.com/drive/12jVn9LUDcF6eHqIpBLAN9Ccq0QVegPrE#scrollTo=Mt9PbcUmhszn" rel="nofollow noreferrer">HERE nb 22 March 23 </a></p>
<p>My repo is a fork of an other repo done Nov. 2022.</p>
<p>Is there a reason why the March nb may crash due to some hidden changes? I'm not so confortable with git so may I was doing something wrong on Calob.</p>
<p>Help is warmly welcome.</p>
|
<python><git><google-colaboratory><jax>
|
2023-03-22 12:40:32
| 1
| 402
|
Jean-Eric
|
75,812,237
| 5,359,846
|
How to send API call when the payload contains lists and objects?
|
<p>I need to send a Post request via Python code, like using Postman.</p>
<p>When I look at the Payload tab under the Network in Google Chrome I see this data:</p>
<pre><code>version: abcd
password: Somepassowrd
links[0].XYZ: DC-DC-02-01
links[0].Change: 4321
</code></pre>
<p>How to send links[0].xyz? Is is a dictionary or an object?</p>
<pre><code>data = {'Token': settings.TOKEN,
'links': [{'xyz': 'DC-DC-02-01',
'Change': 4321}],
'version': abcd, 'password': 'SomePassword'}
</code></pre>
<p>Send Request with this data always give me code 500 and "Internal server error":</p>
<pre><code>response = self.api.post(url=url, form=data,
ignore_https_errors=True)
</code></pre>
|
<python><request><postman>
|
2023-03-22 12:25:00
| 2
| 1,838
|
Tal Angel
|
75,811,998
| 19,467,973
|
Set cookies and return the message in FastAPI
|
<p>Why don't I have cookies installed in my browser when I try to return a message in this code?</p>
<pre><code>@post("/registration_user")#, response_class=JSONResponse)
async def sign_in_user(self, item: schemas.RegistrWithoutLogin):
print("-------------------------------------------------------------------")
self.registration_user(models.User, models.Credentials, item.middlename, item.name, item.lastname, item.phone, item.login, item.password)
jwt_user = self.authenticate_user(item.login, item.password)
print(jwt_user)
print("-------------------------------------------------------------------")
response = Response(status_code=200)
response.set_cookie(key="Authorization", value=_T.encode_jwt(jwt_user), max_age=600)
#role = [{"role": "user"}]
return {"role": "user", "cookie_set": True} #JSONResponse(role, headers=response.headers)
</code></pre>
<p>In the code in the comments there are also options that I tried for my purpose, but they also did not install cookies in the browser.</p>
<p>I run everything if anything in another file
Here is his code</p>
<pre><code>app = FastAPI()
origins = [
"http://localhost.GideOne.com",
"https://localhost.GideOne.com",
"http://localhost",
"http://localhost:8000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def main():
app.include_router(AuthenticateController.create_router())
app.include_router(Company.create_router())
app.include_router(InviteEmployee.create_router())
app.include_router(Criteries.create_router())
app.include_router(OwnersDashboard.create_router())
app.include_router(WorkersDashboard.create_router())
app.include_router(ManagersDashboard.create_router())
uvicorn.run(app, host="0.0.0.0", port=8000,)
if __name__ == "__main__":
main()
</code></pre>
|
<python><cookies><fastapi><jsonresponse>
|
2023-03-22 12:02:18
| 1
| 301
|
Genry
|
75,811,990
| 5,452,365
|
Check if pathlib.Path is a file or directory without pathlib.Path exist on directory
|
<p>How to tell if pathlib.Path is a file or dir path without being physically present on disk.
I do not want to check if the actual file exists on the disk. Something like this.</p>
<pre><code>from pathlib import Path
home = Path.home()
def function_to_differentiate_file_and_dir(filepath):
return 'file' is filepath is file
return 'dir' if filepath is dir
assert function_to_differentiate_file_and_dir(home / 'test.txt') == 'file'
assert function_to_differentiate_file_and_dir(home / 'test.txt') == 'file'
</code></pre>
<p>What have you tried?:</p>
<pre><code>def function_to_differentiate_file_and_dir(filepath):
return 'file' if filepath.suffix else 'dir'
</code></pre>
|
<python>
|
2023-03-22 12:01:21
| 1
| 11,652
|
Rahul
|
75,811,936
| 7,822,387
|
how to create this linear program in PULP
|
<p>How can I create the following linear program using PuLP? The structure is as follows. A list of orders must be processed in the order they came in, and has a list of items that can be made by a set of different machines. Each machine can only process one item per order, but each item can be processed by multiple machines in one order. The table below is the list of binary assignment variables that will be created for this LP.</p>
<pre><code>order item machine
1 A 1
1 A 2
1 B 1
1 B 2
2 A 1
2 A 2
2 D 1
2 D 2
3 E 1
3 E 2
</code></pre>
<p>I want the LP to assign items to 1+ machine(s) for each order, to minimize the total run time. The run time is composed of two parts, a fixed runtime for each item, and a cleaning time if a machine has previously processed a specific ingredient. The tables for this data are below:</p>
<pre><code>item runtime
A 50
B 60
C 70
D 80
E 90
prev item
A B C D E
curr A 0 0 1 1 2
item B 0 0 2 1 0
C 0 0 0 1 1
D 0 0 0 0 1
E 1 0 0 0 0
</code></pre>
<p>For example, if machine 1 makes item A and then wants to make item E next, then there would be 2 seconds added to the runtime.</p>
<p>The only constraints are that each machine can only make 1 item per order, and each item in an order needs to be made by at least one machine. Thanks in advance.</p>
<p>Edit:
To reformulate the simplified problem, does this capture all the constraints? also, how can I create the cleaning constraint without using a min function?</p>
<pre><code>Variables:
A(oim) - asn for order, ing, machine
D(oim) - duration of order, ing, machine
D(oi) - duration of order, ing
C(oim) - cleaning for order, ing, machine
Constants:
R(oi) - fixed runtime of order, ing
C(xy) - fixed cleaning for ing x to ing y
M - much larger than total runtimes
Formulation:
min sum( D(oim)) + C(oim) )
s.t. D(oim) <= M * A(oim) for all oim
sum( A(oim) ) >= 1 for all oi (this may be redundant bc of duration constraint?)
sum( D(oim) ) = R(oi) for all oi
M * A(oim) - D(oi) + D(oim) <= M for all oim
M * A(oim) + D(oi) - D(oim) <= M for all oim
sum( A(oim) ) <= 1 for all om
C(xy) * min(A(-oim),A(oim)) <= C(oim) for all oim, where A(-oim) is previous order for machine m
</code></pre>
|
<python><pulp>
|
2023-03-22 11:54:44
| 1
| 311
|
J. Doe
|
75,811,897
| 567,595
|
Separate comma-separated values within pandas dataframe cells
|
<p>I am getting data from an API in CSV format, which I read into a pandas dataframe like this:</p>
<pre><code>import io
import requests
import pandas as pd
response = requests.get(url, params=params, headers=headers)
df = pd.read_csv(io.StringIO(response.content.decode("utf-8")))
</code></pre>
<p>(As requested in a comment, here are the first 2 lines of <code>response.content.decode("utf-8")</code>)</p>
<pre><code>dataset_version,dataset_generated_datetime,dataset_linked_data_default,last_updated_datetime,xml_lang,default_currency,humanitarian,hierarchy,linked_data_uri,budget_not_provided,iati_identifier,reporting_org_ref,reporting_org_type,reporting_org_secondary_reporter,reporting_org_narrative,reporting_org_narrative_xml_lang,title_narrative,title_narrative_xml_lang,description_type,description_narrative,description_narrative_xml_lang,participating_org_ref,participating_org_type,participating_org_role,participating_org_activity_id,participating_org_crs_channel_code,participating_org_narrative,participating_org_narrative_xml_lang,other_identifier_ref,other_identifier_type,other_identifier_owner_org_ref,other_identifier_owner_org_narrative,other_identifier_owner_org_narrative_xml_lang,activity_status_code,activity_date_type,activity_date_iso_date,activity_date_narrative,activity_date_narrative_xml_lang,contact_info_type,contact_info_organisation_narrative,contact_info_organisation_narrative_xml_lang,contact_info_department_narrative,contact_info_department_narrative_xml_lang,contact_info_person_name_narrative,contact_info_person_name_narrative_xml_lang,contact_info_job_title_narrative,contact_info_job_title_narrative_xml_lang,contact_info_telephone,contact_info_email,contact_info_website,contact_info_mailing_address_narrative,contact_info_mailing_address_narrative_xml_lang,activity_scope_code,recipient_country_code,recipient_country_percentage,recipient_country_narrative,recipient_country_narrative_xml_lang,recipient_region_code,recipient_region_vocabulary,recipient_region_vocabulary_uri,recipient_region_percentage,recipient_region_narrative,recipient_region_narrative_xml_lang,location_ref,location_location_reach_code,location_location_id_code,location_location_id_vocabulary,location_name_narrative,location_name_narrative_xml_lang,location_description_narrative,location_description_narrative_xml_lang,location_activity_description_narrative,location_activity_description_narrative_xml_lang,location_administrative_code,location_administrative_vocabulary,location_administrative_level,location_point_srsName,location_point_pos,location_exactness_code,location_location_class_code,location_feature_designation_code,sector_vocabulary,sector_vocabulary_uri,sector_code,sector_percentage,sector_narrative,sector_narrative_xml_lang,tag_code,tag_vocabulary,tag_vocabulary_uri,tag_narrative,tag_narrative_xml_lang,country_budget_items_vocabulary,country_budget_items_budget_item_code,country_budget_items_budget_item_percentage,country_budget_items_budget_item_description_narrative,country_budget_items_budget_item_description_narrative_xml_lang,humanitarian_scope_type,humanitarian_scope_vocabulary,humanitarian_scope_vocabulary_uri,humanitarian_scope_code,humanitarian_scope_narrative,humanitarian_scope_narrative_xml_lang,policy_marker_vocabulary,policy_marker_vocabulary_uri,policy_marker_code,policy_marker_significance,policy_marker_narrative,policy_marker_narrative_xml_lang,collaboration_type_code,default_flow_type_code,default_finance_type_code,default_aid_type_code,default_aid_type_vocabulary,default_tied_status_code,budget_type,budget_status,budget_period_start_iso_date,budget_period_end_iso_date,budget_value,budget_value_currency,budget_value_value_date,planned_disbursement_type,planned_disbursement_period_start_iso_date,planned_disbursement_period_end_iso_date,planned_disbursement_value,planned_disbursement_value_currency,planned_disbursement_value_value_date,planned_disbursement_provider_org_ref,planned_disbursement_provider_org_provider_activity_id,planned_disbursement_provider_org_type,planned_disbursement_provider_org_narrative,planned_disbursement_provider_org_narrative_xml_lang,planned_disbursement_receiver_org_ref,planned_disbursement_receiver_org_receiver_activity_id,planned_disbursement_receiver_org_type,planned_disbursement_receiver_org_narrative,planned_disbursement_receiver_org_narrative_xml_lang,capital_spend_percentage,transaction_ref,transaction_humanitarian,transaction_transaction_type_code,transaction_transaction_date_iso_date,transaction_value,transaction_value_currency,transaction_value_value_date,transaction_description_narrative,transaction_description_narrative_xml_lang,transaction_provider_org_ref,transaction_provider_org_provider_activity_id,transaction_provider_org_type,transaction_provider_org_narrative,transaction_provider_org_narrative_xml_lang,transaction_receiver_org_ref,transaction_receiver_org_receiver_activity_id,transaction_receiver_org_type,transaction_receiver_org_narrative,transaction_receiver_org_narrative_xml_lang,transaction_disbursement_channel_code,transaction_sector_vocabulary,transaction_sector_vocabulary_uri,transaction_sector_code,transaction_sector_narrative,transaction_sector_narrative_xml_lang,transaction_recipient_country_code,transaction_recipient_country_narrative,transaction_recipient_country_narrative_xml_lang,transaction_recipient_region_code,transaction_recipient_region_vocabulary,transaction_recipient_region_vocabulary_uri,transaction_recipient_region_narrative,transaction_recipient_region_narrative_xml_lang,transaction_flow_type_code,transaction_finance_type_code,transaction_aid_type_code,transaction_aid_type_vocabulary,transaction_tied_status_code,document_link_url,document_link_format,document_link_title_narrative,document_link_title_narrative_xml_lang,document_link_description_narrative,document_link_description_narrative_xml_lang,document_link_category_code,document_link_language_code,document_link_document_date_iso_date,related_activity_ref,related_activity_type,legacy_data_name,legacy_data_value,legacy_data_iati_equivalent,conditions_attached,conditions_condition_type,conditions_condition_narrative,conditions_condition_narrative_xml_lang,result_type,result_aggregation_status,result_title_narrative,result_title_narrative_xml_lang,result_description_narrative,result_description_narrative_xml_lang,result_document_link_url,result_document_link_format,result_document_link_title_narrative,result_document_link_title_narrative_xml_lang,result_document_link_description_narrative,result_document_link_description_narrative_xml_lang,result_document_link_category_code,result_document_link_language_code,result_document_link_document_date_iso_date,result_reference_code,result_reference_vocabulary,result_reference_vocabulary_uri,result_indicator_measure,result_indicator_ascending,result_indicator_aggregation_status,result_indicator_title_narrative,result_indicator_title_narrative_xml_lang,result_indicator_description_narrative,result_indicator_description_narrative_xml_lang,result_indicator_document_link_url,result_indicator_document_link_format,result_indicator_document_link_title_narrative,result_indicator_document_link_title_narrative_xml_lang,result_indicator_document_link_description_narrative,result_indicator_document_link_description_narrative_xml_lang,result_indicator_document_link_category_code,result_indicator_document_link_language_code,result_indicator_document_link_document_date_iso_date,result_indicator_reference_vocabulary,result_indicator_reference_code,result_indicator_reference_indicator_uri,result_indicator_baseline_iso_date,result_indicator_baseline_year,result_indicator_baseline_value,result_indicator_baseline_location_ref,result_indicator_baseline_dimension_name,result_indicator_baseline_dimension_value,result_indicator_baseline_document_link_url,result_indicator_baseline_document_link_format,result_indicator_baseline_document_link_title_narrative,result_indicator_baseline_document_link_title_narrative_xml_lang,result_indicator_baseline_document_link_description_narrative,result_indicator_baseline_document_link_description_narrative_xml_lang,result_indicator_baseline_document_link_category_code,result_indicator_baseline_document_link_language_code,result_indicator_baseline_document_link_document_date_iso_date,result_indicator_baseline_comment_narrative,result_indicator_baseline_comment_narrative_xml_lang,result_indicator_period_period_start_iso_date,result_indicator_period_period_end_iso_date,result_indicator_period_target_value,result_indicator_period_target_location_ref,result_indicator_period_target_dimension_name,result_indicator_period_target_dimension_value,result_indicator_period_target_comment_narrative,result_indicator_period_target_comment_narrative_xml_lang,result_indicator_period_target_document_link_url,result_indicator_period_target_document_link_format,result_indicator_period_target_document_link_title_narrative,result_indicator_period_target_document_link_title_narrative_xml_lang,result_indicator_period_target_document_link_description_narrative,result_indicator_period_target_document_link_description_narrative_xml_lang,result_indicator_period_target_document_link_category_code,result_indicator_period_target_document_link_language_code,result_indicator_period_target_document_link_document_date_iso_date,result_indicator_period_actual_value,result_indicator_period_actual_location_ref,result_indicator_period_actual_dimension_name,result_indicator_period_actual_dimension_value,result_indicator_period_actual_comment_narrative,result_indicator_period_actual_comment_narrative_xml_lang,result_indicator_period_actual_document_link_url,result_indicator_period_actual_document_link_format,result_indicator_period_actual_document_link_title_narrative,result_indicator_period_actual_document_link_title_narrative_xml_lang,result_indicator_period_actual_document_link_description_narrative,result_indicator_period_actual_document_link_description_narrative_xml_lang,result_indicator_period_actual_document_link_category_code,result_indicator_period_actual_document_link_language_code,result_indicator_period_actual_document_link_document_date_iso_date,crs_add_other_flags_code,crs_add_other_flags_significance,crs_add_loan_terms_rate_1,crs_add_loan_terms_rate_2,crs_add_loan_terms_repayment_type_code,crs_add_loan_terms_repayment_plan_code,crs_add_loan_terms_commitment_date_iso_date,crs_add_loan_terms_repayment_first_date_iso_date,crs_add_loan_terms_repayment_final_date_iso_date,crs_add_loan_status_year,crs_add_loan_status_currency,crs_add_loan_status_value_date,crs_add_loan_status_interest_received,crs_add_loan_status_principal_outstanding,crs_add_loan_status_principal_arrears,crs_add_loan_status_interest_arrears,crs_add_channel_code,fss_extraction_date,fss_priority,fss_phaseout_year,fss_forecast,fss_forecast_year,fss_forecast_currency,fss_forecast_value_date
2.03,2023-02-16T09:12:32Z,,2023-02-16T09:12:32Z,EN,USD,,1,,,XI-IATI-WBTF-TF072664,XI-IATI-WBTF,40,,World Bank Trust Funds,,Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund,,1,This EDF Trust Fund financed by the European Commission aims to provide additional financing to the original Saint Lucia Disaster Vulnerability Reduction Project,,"TF612001,XI-IATI-WBTF","40,40","1,4",,,"EU-Commission of the European Communities,World Bank Trust Funds",,,,,,,2,"1,2,3","2015-09-01T00:00:00Z,2015-09-01T00:00:00Z,2023-12-31T00:00:00Z",,,3,,,"HIS-Urban\, Rural & Soc Dev - GP",,,,,,1202-458-7916,,,"1818 H St\, NW\, Washington DC - 22036",,4,LC,,SAINT LUCIA,,,,,,,,,,,,,,,,,,,,,,,,,,"1,1,1,1",,"11120,12230,14021,74020","11.0,11.0,4.0,74.0","+![cdata[Education facilities and training]]+,+![cdata[Basic health infrastructure]]+,+![cdata[Water supply - large systems]]+,+![cdata[Multi-hazard response preparedness]]+",,,,,,,,,,,,,,,,,,,,,,,,2,,,B03,,5,1,,2015-09-01T00:00:00Z,2023-12-31T00:00:00Z,6935451.25,USD,2023-01-31T00:00:00Z,,,,,,,,,,,,,,,,,,,,"1,1,11,2,2,2,2","2020-06-30T00:00:00Z,2022-08-31T00:00:00Z,2020-06-30T00:00:00Z,2020-06-30T00:00:00Z,2020-06-30T00:00:00Z,2022-09-30T00:00:00Z,2022-10-31T00:00:00Z","5519956.0,1236173.25,6935451.25,5341367.39,73469.52,87015.94,1098401.07","USD,USD,USD,USD,USD,USD,USD","2023-01-31T00:00:00Z,2023-01-31T00:00:00Z,2023-01-31T00:00:00Z,2023-01-31T00:00:00Z,2023-01-31T00:00:00Z,2023-01-31T00:00:00Z,2023-01-31T00:00:00Z","Incoming Funds (Cumulative Paid-In Contribution )-as of June 30th\, 2020,Incoming Funds (Paid-In Contribution ) - for August \, 2022,Incoming Commitment(Cumulative Signed Contribution)-as of June 30th\, 2020,Outgoing Commitment ( Total Grant Allocated Amount to Project ) - as of June 30th\, 2020,Allocation to Bank executed activities - as of June 30th\, 2020,Allocation to Bank executed activities - for September \, 2022,Outgoing Commitment ( Grant Allocated Amount to Project ) - for October \, 2022",,,"TF612001,TF612001,TF612001,XI-IATI-WBTF-TF072664,XI-IATI-WBTF-TF072664,XI-IATI-WBTF-TF072664,XI-IATI-WBTF-TF072664",,"EU-Commission of the European Communities,EU-Commission of the European Communities,EU-Commission of the European Communities,Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund,Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund,Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund,Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund",,,"XI-IATI-WBTF-TF072664,XI-IATI-WBTF-TF072664,XI-IATI-WBTF-TF072664,XI-IATI-WBTF-P127226,XI-IATI-WBTF-P127226,XI-IATI-WBTF-P127226,XI-IATI-WBTF-P127226",,"Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund,Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund,Saint Lucia: Disaster Vulnerability Reduction Project EDF Single Donor Trust Fund,SAINT LUCIA,SAINT LUCIA,SAINT LUCIA,SAINT LUCIA",,,,,,,,,,,,,,,,,"110,110,110,110,110,110,110",,,,,,,,,,,,,XI-IATI-WBTF-P127226,4,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
</code></pre>
<p>Upon inspection, many of the cells in the dataframe contain comma-separated data, of varying length. The comma-separated values are not surrounded by quotation marks, and some of the values contain commas escaped using backslashes. Example columns would look like this:</p>
<pre><code>eg = pd.DataFrame({"a": ["A single value", "Three,separate,values", "This value contains a \,, and so does\, this one", pd.NA], "b": ["", pd.NA, "2,3,4","12,17"]})
</code></pre>
<p>I need to separate these cells into either a list within each cell or separate columns. I can do this one cell at a time, like this:</p>
<pre><code>import csv
def to_list_of_strings(cell):
if pd.isnull(cell):
return []
elif "," in cell:
return next(csv.reader(io.StringIO(cell), escapechar="\\"))
else:
return [cell]
result = eg.a.apply(to_list_of_strings)
</code></pre>
<p>(I used <code>csv</code> in the hope that this will take care of other parsing that may be needed, such as quotation marks.)</p>
<p>The desired result looks like this (for <code>list(result)</code>)</p>
<pre><code>[['A single value'],
['Three', 'separate', 'values'],
['This value contains a ,', ' and so does, this one'],
[]]
</code></pre>
<p>This can be slow across multiple columns and thousands of rows. Is there any faster vectorized way to do this?</p>
|
<python><pandas><csv>
|
2023-03-22 11:50:59
| 2
| 9,877
|
Stuart
|
75,811,887
| 6,543,836
|
Dependency Injector. Inject a dependency into a route method from app.py
|
<p>I have a small flask application that consists only from one <code>app.py</code> file. I'm using <a href="https://python-dependency-injector.ets-labs.org/" rel="nofollow noreferrer">python-dependency-injector</a> package. I want to inject a service into the <code>hello_world()</code> route method.</p>
<pre><code>class MyService:
def getMessage(self):
return "Hello World!"
class Container(containers.DeclarativeContainer):
my_service = providers.Factory(MyService)
wiring_config = containers.WiringConfiguration(
modules=[__name__],
)
app = Flask(__name__)
container = Container()
app.run()
@app.route('/')
@inject
def hello_world(my_service: MyService = Provide[Container.my_service]):
return my_service.getMessage()
</code></pre>
<p>For unknown reason, when <code>hello_world()</code> is executed, <code>my_service.getMessage()</code> fails because <code>my_service</code> is not an instance, but a provider object.</p>
<pre><code>AttributeError: 'Provide' object has no attribute 'getMessage'
</code></pre>
<p>Probably I've missed something in the current setup. But I would like to receive <code>my_service</code> instance in <code>hello_word()</code>, so that I could call <code>my_service.getMessage()</code></p>
|
<python><flask><dependency-injection>
|
2023-03-22 11:50:18
| 0
| 519
|
Eugeniu Znagovan
|
75,811,845
| 1,613,983
|
How to visualize timeseries output at each epoch in tensorboard
|
<p>I have a keras model that outputs an MxN tensor along with several scalar metrics. The metrics show up just fine in the <em>SCALARS</em> and <em>TIME SERIES</em> tabs:</p>
<p><a href="https://i.sstatic.net/uv5Au.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uv5Au.png" alt="enter image description here" /></a></p>
<p>This view is great for visualising scalars where the x-axis is the total number of epochs in my training run.</p>
<p>However, I would like to visualise the MxN tensor output at various epochs as well, e.g. by picking an epoch and viewing the tensor as a plot of N lines on a chart where the X axis is of length M (in my case this would be time).</p>
<p>Can tensorboard facilitate this? If so, how?</p>
<p>I am using tensorflow 2.9.0.</p>
|
<python><tensorflow><tensorboard>
|
2023-03-22 11:45:14
| 0
| 23,470
|
quant
|
75,811,688
| 2,281,274
|
How to avoid showing orginal exception in pytest when reraising exception?
|
<p>I use a library with very deep stack. When there is an exception, trace is enormous (~6 pages), even the true reason is a side effect (no permission), and it's very clear from exception text. It is really confusing in tests, so I wrote this code:</p>
<pre><code>def _command(self, lib_handler, cmd):
try:
lib_handler.run(cmd)
except Exception as e:
raise MyError(e) from e
</code></pre>
<p>The problem is that when exception happens in tests, and there is <code>MyError</code> exception, pytest shows original (enormous) traceback, then write <code>The above exception was the direct cause of the following exception:</code> and shows my (tiny and reasonable) traceback.</p>
<p>I want to disable showing the original traceback and keep pytest to shorter traceback in mine code (without unwinding traceback into the library call). Is it possible? How to do it?</p>
|
<python><pytest><traceback>
|
2023-03-22 11:29:53
| 1
| 8,055
|
George Shuklin
|
75,811,600
| 11,803,687
|
Convert stringified json objects to json
|
<p>I'm using MariaDB, and unfortunately, JSON objects are returned as strings. I want to convert these stringified JSON objects back to JSON, but the problem is - I only want to do so if they are actually JSON objects, and ignore all fields that are, for example, just normal strings (but <strong>can</strong> convert to JSON without causing an error).</p>
<p>My approach to do this, is to check if the string contains a double-quote, but this seems a bit too naive, because it will also convert a string which just naturally contains a double quote, but isn't intended as a JSON object. Is there a more robust way to achieve this?</p>
<pre><code>import json
results = {"not_string": 1234,
"not_json": "1234",
"json": '[{"json": "1234"}]',
"false_positive": '["actually a quote in brackets"]'}
# load the json fields in the results
for key, value in results.items():
if isinstance(value, str) and '"' in value:
try:
results[key] = json.loads(value)
except Exception as e:
pass
for key, value in results.items():
print(type(value))
</code></pre>
<pre><code><class 'int'>
<class 'str'>
<class 'list'>
<class 'list'> <--
</code></pre>
<p>Expected:</p>
<pre><code><class 'int'>
<class 'str'>
<class 'list'>
<class 'str'> <--
</code></pre>
<p>basically, I don't want to rely on "asking for forgiveness", because the string can be converted to JSON without causing an error, but this is a false-positive and shouldn't be done.</p>
|
<python><json><mariadb>
|
2023-03-22 11:20:41
| 2
| 1,649
|
c8999c 3f964f64
|
75,811,420
| 8,472,781
|
Add Python entry point to local APPDATA
|
<p>I am writing a command line tool with Python. It should be as easy as possible for Windows 10 / 11 users to install and use. My goal is to make the following procedure work:</p>
<ol>
<li>Install Python from the Microsoft Store</li>
<li>Install my program using <code>pip install "C:\path\to\myprogram.zip"</code></li>
<li>Start my program using <code>myprogram</code> in Windows cmd</li>
</ol>
<p>Currently, I have a <code>setup.py</code> like this:</p>
<pre><code>from setuptools import setup
setup(
name="myprogram",
# image additional arguments here
entry_points={"console_scripts": ["myprogram=myprogram.module:function"]},
)
</code></pre>
<p>Everything works great in virtual environments, but I don't want my users to necessarily deal with them. I understand that running the <code>pip install ...</code> command above installs the entry point (in my case) to <code>C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts</code>, which is obviously not in Windows %PATH%.</p>
<p>So here comes my question: Is it possible to either</p>
<ol>
<li>write the script to one of the Windows %PATH%s (for example <code>C:\Users\myuser\AppData\Local\Microsoft\WindowsApps</code>) or</li>
<li>add <code>C:\Users\myuser\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts</code> to Windows %PATH%?</li>
</ol>
<p>I want the solution to work directly from the <code>setup.py</code> such that no additional installation step is necessary. I'm fully aware that there is only a small chance to find a solution that is not "hacky" in some way.</p>
<hr />
<p><strong>Workaround:</strong> As of now, I am building an executable with <a href="https://pyinstaller.org/en/stable/" rel="nofollow noreferrer">PyInstaller</a>.</p>
|
<python><windows-10><setuptools><python-packaging><windows-11>
|
2023-03-22 11:04:12
| 1
| 586
|
d4tm4x
|
75,811,395
| 1,736,294
|
FastApi Sessions for Anonymous Users
|
<p>I'm looking for a simple way to achieve this:</p>
<p>Anonymous users access a fastapi service. From a client, a user begins a session and sends a request. The fastapi service captures dependency data from the request. If the user makes further requests during the same session, the dependency data is updated and so on. Ditto for all anonymous users.</p>
<p><s>Not looking for a cookie solution.</s> In the Get-Current-User method <a href="https://fastapi.tiangolo.com/tutorial/security/get-current-user/" rel="nofollow noreferrer">https://fastapi.tiangolo.com/tutorial/security/get-current-user/</a> it says (paraphrasing):</p>
<p>"If you have users, robots, bots, or other systems that log in to your application with an access token, it all works the same."</p>
<p>How does it work for anonymous users? Thanks</p>
|
<python><security><fastapi>
|
2023-03-22 11:02:03
| 0
| 4,617
|
Henry Thornton
|
75,811,312
| 2,958,883
|
12 hperthread used evenly with 7 processes in multiprocessing.Pool
|
<p>I have a task <code>get_geotif_by_band(band_number):...</code>.</p>
<p>Now my multiprocessing code is as follow:</p>
<pre><code>if __name__ == '__main__':
with Pool(12) as p:
p.map(get_geotif_by_band, [1,2,3,4,5,6,7])
</code></pre>
<p>My cpu has 6 cores and 12 Logical processors.</p>
<p>Now I expect 7 logical processor to be fully used other being used normally by other task.</p>
<p>But I see all the processors are used equally (evenly).</p>
<p><a href="https://i.sstatic.net/p0C9O.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/p0C9O.png" alt="enter image description here" /></a></p>
<p>How can we explain this?</p>
|
<python><multiprocessing><python-multiprocessing>
|
2023-03-22 10:52:47
| 1
| 1,406
|
wrufesh
|
75,811,178
| 7,800,760
|
Folium: how to create some leeway for displayed placemarkers
|
<p>The following simple code creates three placemarks, computes the proper NE and SW bounding box and uses folium.Map.fit_bounds to set the proper zoom level to display them on the map.</p>
<p>What I'd like to achieve if possible is to have some more space around the placemarks, just like the user would have clicked on the "-" control on the map to "un-zoom" it a little bit. Is this possibile?</p>
<pre><code>from folium import Map, Marker
from dash import html, Dash
def create_map(coordinates, output_file="map.html"):
# Create a map centered at the first pair of coordinates
#my_map = Map(location=coordinates[0], zoom_start=13)
my_map = Map()
# Add a marker for each pair of coordinates
for coord in coordinates:
Marker(location=coord).add_to(my_map)
# Calculate the bounds of the markers
sw = [min(coord[0] for coord in coordinates), min(coord[1] for coord in coordinates)]
ne = [max(coord[0] for coord in coordinates), max(coord[1] for coord in coordinates)]
# Fit the map to the bounds
my_map.fit_bounds([sw, ne])
# Save the map as an HTML file
my_map.save(output_file)
if __name__ == "__main__":
# Replace these with your desired list of coordinates
coordinates = [
[37.7749, -122.4194],
[37.7899, -122.4062],
[37.7531, -122.4470]
]
create_map(coordinates)
# Initialize the Dash app
app = Dash(__name__)
# Read the map HTML file
with open("map.html", "r") as f:
map_html = f.read()
# Define the app layout
app.layout = html.Div([
html.H1("Interactive Map with Folium and Plotly Dash"),
html.Iframe(srcDoc=map_html, width="100%", height="600px")
])
# Run the Dash app
app.run_server(debug=True)
</code></pre>
|
<python><plotly><plotly-dash><folium>
|
2023-03-22 10:39:55
| 0
| 1,231
|
Robert Alexander
|
75,810,821
| 188,331
|
How to specify a PyTorch script to use specific GPU unit?
|
<p>I have a Python training script that makes use of CUDA GPU to train the model (Kohya Trainer script available <a href="https://github.com/Linaqruf/kohya-trainer/blob/main/train_network.py" rel="nofollow noreferrer">here</a>). It encounters out-of-memory error:</p>
<pre><code>OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 MiB (GPU 1; 23.65
GiB total capacity; 144.75 MiB already allocated; 2.81 MiB free; 146.00 MiB
reserved in total by PyTorch) If reserved memory is >> allocated memory try
setting max_split_size_mb to avoid fragmentation. See documentation for Memory
Management and PYTORCH_CUDA_ALLOC_CONF
</code></pre>
<p>After investigation, I found out that the script is using GPU unit 1, instead of unit 0. Unit 1 is currently in high usage, not much GPU memory left, while GPU unit 0 still has adequate resources. How do I specify the script to use GPU unit 0?</p>
<p>Even I change from:</p>
<pre><code>text_encoder.to("cuda")
</code></pre>
<p>to:</p>
<pre><code>text_encoder.to("cuda:0")
</code></pre>
<p>The script is still using GPU unit 1, as specified in the error message.</p>
<p>Output of <code>nvidia-smi</code>:</p>
<pre><code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.60.11 Driver Version: 525.60.11 CUDA Version: 12.0 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA GeForce ... Off | 00000000:81:00.0 Off | Off |
| 66% 75C P2 437W / 450W | 5712MiB / 24564MiB | 100% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
| 1 NVIDIA GeForce ... Off | 00000000:C1:00.0 Off | Off |
| 32% 57C P2 377W / 450W | 23408MiB / 24564MiB | 100% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| 0 N/A N/A 1947 G /usr/lib/xorg/Xorg 4MiB |
| 0 N/A N/A 30654 C python 5704MiB |
| 1 N/A N/A 1947 G /usr/lib/xorg/Xorg 4MiB |
| 1 N/A N/A 14891 C python 23400MiB |
+-----------------------------------------------------------------------------+
</code></pre>
<hr />
<p><strong>UPDATE 1</strong></p>
<p>The same notebook can see 2 GPU units:</p>
<pre><code>import torch
for i in range(torch.cuda.device_count()):
print(torch.cuda.get_device_properties(i))
</code></pre>
<p>which outputs:</p>
<pre><code>_CudaDeviceProperties(name='NVIDIA GeForce RTX 4090', major=8, minor=9, total_memory=24217MB, multi_processor_count=128)
_CudaDeviceProperties(name='NVIDIA GeForce RTX 4090', major=8, minor=9, total_memory=24217MB, multi_processor_count=128)
</code></pre>
<hr />
<p><strong>UPDATE 2</strong></p>
<p>Setting <code>CUDA_VISIBLE_DEVICES=0</code> results this error:</p>
<blockquote>
<p>RuntimeError: CUDA error: invalid device ordinal</p>
</blockquote>
|
<python><pytorch><gpu>
|
2023-03-22 10:05:04
| 1
| 54,395
|
Raptor
|
75,810,448
| 2,546,099
|
String-based flags in python
|
<p>For my python-based class I'd like to limit the input strings to certain strings, as they represent the file endings I want to allow to be loaded, i.e.</p>
<pre><code>class DemoClass:
def __init__(self, allowed_endings: Literal[".csv", ".txt", ".docx"] = ".docx") -> None:
self.allowed_endings: Literal[".csv", ".txt", ".docx"] = allowed_endings
</code></pre>
<p>Now, I'd like to replace that implementation with a flag-based system, i.e.</p>
<pre><code>class DemoClass:
def __init__(self, allowed_endings: AllowedFileEndings = AllowedFileEndings.TXT) -> None:
self.allowed_endings: AllowedFileEndings = allowed_endings
</code></pre>
<p>such that I can write a similar class as</p>
<pre><code>class DemoClass:
def __init__(self, allowed_endings: AllowedFileEndings = AllowedFileEndings.TXT | AllowedFileEndings.CSV) -> None:
self.allowed_endings: AllowedFileEndings = allowed_endings
</code></pre>
<p>I am aware of StrEnum, where I can create a class which behaves like enums, but also can be used to be compared with strings. Unfortunately, it does not work with with bitwise OR/AND-operators, as demonstrated above. Moreover, it only works for python 3.11 and above, while I'm limited to 3.9.</p>
<p>Is there a way to implement such a StrFlag-class in Python 3.9?</p>
<p>Ideally, I can then still use string-based comprehensions, i.e.</p>
<pre><code>".csv" is in AllowedFileEndings.TXT | AllowedFileEndings.CSV
</code></pre>
<p>if possible.</p>
|
<python><string><flags>
|
2023-03-22 09:30:20
| 2
| 4,156
|
arc_lupus
|
75,810,407
| 19,574,336
|
Django AttributeError: type object 'Admin' has no attribute '_meta' error when creating custom user
|
<p>I'm learning django and I want to have my custom user and admin object but I'm encountering an error when running server after applying my changes. I'm not sure if this is the right approach to do this so do enlighten me if I'm following the wrong approach.</p>
<p>So I have created an app called 'core' where I want to do authentication stuff so that's where I've put my custom user models.</p>
<p>Here are the files I've written for that task so far:</p>
<p><strong>models.py</strong>:</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
from store.models import CartItem
from django.contrib.auth.models import AbstractBaseUser, UserManager
from enum import Enum
from django_countries.fields import CountryField
from django.contrib import admin
ADDRESS_CHOICES = (
('B', 'Billing'),
('S', 'Shipping'),
)
class AuthLevel(Enum):
NONE = 0
Customer = 1
Admin = 2
Programmer = 3
class Address(models.Model):
street_address = models.CharField(max_length=100)
apartment_address = models.CharField(max_length=100)
country = CountryField(multiple=False)
zip = models.CharField(max_length=100)
address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES)
default = models.BooleanField(default=False)
def __str__(self):
return self.street_address.name + " " + self.apartment_address.name
class Meta:
verbose_name_plural = 'Addresses'
class BaseUser(AbstractBaseUser):
name = models.CharField(max_length=100, unique=True)
auth_level = AuthLevel.NONE
class Customer(AbstractBaseUser):
username = models.CharField(max_length=100, unique=True)
email = models.EmailField()
address = models.OneToOneField(Address, on_delete=models.CASCADE)
stripe_customer_id = models.CharField(max_length=50, blank=True, null=True)
one_click_purchasing = models.BooleanField(default=False)
cart = models.ManyToManyField(CartItem) #on_delete=models.CASCADE)
auth_level = AuthLevel.Customer
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
objects = UserManager()
def __str__(self):
return self.user.username
class Worker(models.Model):
auth_level = AuthLevel.Worker
class Admin(admin.ModelAdmin):
auth_level = AuthLevel.Admin
list_display = ('username', 'email', 'last_login')
list_filter = ('is_superuser',)
search_fields = ('username', 'email')
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(pk=request.user.pk)
class Programmer(Owner):
auth_level = AuthLevel.Programmer
def __str__(self):
return self.user.username + ": PROGRAMMER"
</code></pre>
<p><strong>backends.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from django.shortcuts import get_object_or_404
from .models import Customer
import logging
from django.contrib.auth.backends import BaseBackend
class AuthCustomer(BaseBackend):
def authenticate(self, request, name=None, password=None):
try:
user = get_object_or_404(Customer, name=name)
if user.check_password(password):
return user
else:
return None
except Customer.DoesNotExist:
logging.getLogger("error_logger").error("user with login %s does not exists ")
return None
except Exception as e:
logging.getLogger("error_logger").error(repr(e))
return None
def get_user(self, user_id):
try:
user = Customer.objects.get(id=user_id)
if user.is_active:
return user
return None
except Customer.DoesNotExist:
logging.getLogger("error_logger").error("user with %(user_id)d not found")
return None
</code></pre>
<p><strong>admin.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from django.contrib import admin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from core.models import Admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import Group
from django import forms
class UserCreationForm(forms.ModelForm):
# A form for creating new users. Includes all the required
# fields, plus a repeated password.
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = Admin
fields = ('name',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
# A form for updating users. Includes all the fields on
# the user, but replaces the password field with admins
# password hash display field.
password = ReadOnlyPasswordHashField()
class Meta:
model = Admin
fields = ('name', 'address', 'desc', 'is_staff')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class AdminModelAdmin(BaseUserAdmin):
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('name', 'is_staff')
list_filter = ('name',)
fieldsets = (
(None, {'fields': ('name', 'password', 'desc', 'address')}),
('Permissions', {'fields': ('is_staff', 'auth_level')}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('name', 'password1', 'password2')}
),
)
search_fields = ('name',)
ordering = ('name',)
filter_horizontal = ()
admin.site.register(Admin, AdminModelAdmin)
admin.site.unregister(Group)
</code></pre>
<p>And here are the changes I've done in my settings.py:
settings.py</p>
<pre class="lang-py prettyprint-override"><code>...
INSTALLED_APPS = [
'core',
...
]
...
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = "core.Customer"
</code></pre>
<p>My goal is to have customer as the user form people register with and have Admin as the super user model used by djangos admin panel.</p>
<p>When I run <code>python manage.py runserver</code> I get this error:</p>
<pre><code>PS C:\Users\Asus\Desktop\Projects\Ecommerce_tutorial> python manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
autoreload.raise_last_exception()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 398, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 124, in populate
app_config.ready()
File "C:\Users\Asus\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\apps.py", line 27, in ready
AttributeError: type object 'Admin' has no attribute '_meta'
</code></pre>
<p>I've searched some related questions on stackoverflow and tried doing them to no avail. How can I fix this? Is there a better way to implement this?</p>
|
<python><django><django-models>
|
2023-03-22 09:26:18
| 1
| 859
|
Turgut
|
75,810,403
| 1,754,221
|
How to access a TypeVariable's instance from a class decorator
|
<p>I'm creating a class decorator but have some issues getting the typing right. Below is a minimal reproducable example which runs (no run-time errors) but lets pylance (using the static type checker pyright) complain.</p>
<p>My issue is, that <code>cls</code> in the wrapper function is <code>Type[T@wrapper]</code> (which in this example realizes to <code>Type[Base]</code>, not <code>Base</code>). This causes <code>cls.__init__ = init</code> to raise a pyright error <code>cannot be assigned to member "__init__" of class "type"</code>.</p>
<p>I tried to avoid using T instead of Type[T] throughout the Decorator definition which leads to the following pyright error:</p>
<pre><code>Argument of type "Type[Base]" cannot be assigned to parameter of type "T@Decorator"
Type "Type[Base]" cannot be assigned to type "Base"
"Type[type]" is incompatible with "Type[Base]"
</code></pre>
<p>So it seems that Decorator's expect a Type and not a Type-instance. If that is correct, then the question is: How to access a TypeVariable's instance from a class decorator?</p>
<pre><code>from typing import Any, Callable, TypeVar, Optional, Dict, Union, Generic, Type
class Base:
def __init__(self, config: str):
self.config = config
T = TypeVar('T', bound=Base)
def Decorator(arg: str) -> Callable[[Type[T]], Type[T]]:
def wrapper(cls: Type[T]) -> Type[T]:
# remember original initializer
_init = cls.__init__
# updated initializer
def init(self: T, config: str, *args, **kwargs):
_init(self, config, *args, **kwargs)
setattr(self, arg, config)
# set updated initializer
cls.__init__ = init # <-------- type missmatch
# return class with updated initializer and
return cls
return wrapper
@Decorator('test')
class Test(Base):
test: str
def task(self):
print("test module dummy task: ", self.test)
</code></pre>
<p>Although the code works as intended, having the described issue made me think if I took the right aproach here.</p>
|
<python><python-decorators>
|
2023-03-22 09:25:56
| 0
| 1,767
|
Leo
|
75,810,397
| 7,074,716
|
How to draw edge labels when there are multi edges in networkx?
|
<p>I have a node called T in the middle that has two bidirectional nodes going from it to other 2 nodes. I want to draw the edge weight in the plot.</p>
<pre><code>import matplotlib.pyplot as plt
import networkx as nx
G=nx.MultiGraph()
edge_list = [("1","2", 1),
("3", "1", 2)]
G.add_weighted_edges_from(edge_list)
pos=nx.spring_layout(G,seed=5)
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_nodes(G, pos, node_color = 'b', node_size = 500, alpha = 1)
nx.draw_networkx_labels(G, pos, font_color='w')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels)
</code></pre>
<p>It fails at the 'nx.draw_networkx_edge_labels' saying:</p>
<pre><code>NetworkXError: draw_networkx_edge_labels does not support multiedges.
</code></pre>
<p>The rest of the code:</p>
<pre><code>ax = plt.gca()
for e in G.edges:
ax.annotate("",
xy=pos[e[0]], xycoords='data',
xytext=pos[e[1]], textcoords='data',
arrowprops=dict(arrowstyle="-", color="0",
shrinkA=12, shrinkB=12,
patchA=None, patchB=None,
connectionstyle="arc3,rad=rrr".replace('rrr',str(0.3*e[2])
),
),
)
plt.axis('off')
</code></pre>
<p>I have tried following the answer from Github by <a href="https://github.com/WestHealth/pyvis/issues/51" rel="nofollow noreferrer">aristaeus</a>:</p>
<pre><code>from pyvis.network import Network
nt = Network(directed=False)
nt.from_nx(G)
nt.set_edge_smooth('dynamic')
nt.show('foo.html')
</code></pre>
<p>Unfortunately, I received:</p>
<pre><code>AttributeError: 'NoneType' object has no attribute 'render'
</code></pre>
<p>How do I solve it?</p>
|
<python><graph><networkx>
|
2023-03-22 09:25:20
| 0
| 825
|
Curious
|
75,810,342
| 7,214,714
|
Porting third-party python packages onto Snowpark
|
<p>I'm trying to port the Googletrans package onto Snowflake snowpark, and use it in a UDf.</p>
<p>As the package is unsupported by Snowpark natively, I zipped up the package folder, and uploaded it to a snowpark stage at <code>@DWH.MY_SCHEMA.PACKAGES</code> stage. My code then looks like this</p>
<pre><code>import
from snowflake.snowpark.functions import udf
import googletrans
session = snowpark_session('DWH', 'MY_SCHEMA')
session.add_import("@PACKAGES/googletrans.zip")
session.add_packages("snowflake-snowpark-python", "pandas", "numpy", "scikit-learn", "spacy")
@udf(name='MY_FUNCTION', replace=True, is_permanent=True, stage_location="@MODEL_STAGE")
def myFun(text:str) -> bool:
translator = googletrans.Translator()
/.../
return True
</code></pre>
<p>Here, I'm getting a <code>ModuleNotFoundError</code>. Any idea on what additional steps I would need to take to make Snowflake recognize the package?</p>
|
<python><snowflake-cloud-data-platform>
|
2023-03-22 09:19:20
| 1
| 302
|
Vid Stropnik
|
75,810,318
| 12,769,783
|
Hint instance of subtype of type
|
<p>I want to write a type hint that allows a function argument to be an instance of an arbitrary subtype of a previous type (that is derived from a type hint).</p>
<p>I know that <code>Type[cls]</code> indicates that we receive a type that derives from <code>cls</code>. Is there a way to express that I would like to receive an instance of that type?</p>
<pre class="lang-py prettyprint-override"><code>from typing import *
CallbackArgs = ParamSpec('CallbackArgs')
CallbackReturn = TypeVar('CallbackReturn')
SuperType = TypeVar('SuperType')
def check(func: Callable[Concatenate[SuperType, CallbackArgs], CallbackReturn]) \
-> Callable[[Callable[Concatenate[Type[SuperType], CallbackArgs], CallbackReturn]], None]:
# TODO: in the line above and below this line, I would like to specify, that we accept an instance of an abritrary subtype
# of SuperType, what I wrote is "I expect an arbitrary subtype of SuperType as first argument"
def inner(function: Callable[Concatenate[Type[SuperType], CallbackArgs], CallbackReturn]) -> None:
return None
return inner
class Parent:
def func(self, a :int) -> None:
...
class Child(Parent):
@check(Parent.func)
def func(self, a: int) -> None:
...
</code></pre>
<p><a href="https://mypy-play.net/?mypy=latest&python=3.12&gist=1eda15afddf599c9c70b8bf9b095e63f" rel="nofollow noreferrer">MyPy playground</a></p>
<p>My motivation for the question is <a href="https://stackoverflow.com/questions/75802870">Type hint that indicates that class contains method with signature</a> and <a href="https://mypy-play.net/?mypy=latest&python=3.12&gist=f028f92b54e36b53a9bb0b978cae67a5" rel="nofollow noreferrer">this code sample</a> I came up with following the chepner's suggestion in the comments of that question. For now, I replaced <code>Type[SuperType]</code> by <code>Any</code> in the decorator to supress the warning, but I wonder if there is a more elegant solution, that would also report a warning if I wrongly used <code>check</code> for static methds.</p>
<p>Using <code>SuperType</code> <a href="https://mypy-play.net/?mypy=latest&python=3.12&gist=31ce3922f173f4cd3bdea0a41ce29228" rel="nofollow noreferrer">results in</a>:</p>
<pre><code>Argument 1 has incompatible type "Callable[[Child, int], None]"; expected "Callable[[Parent, int], None]" [arg-type]
</code></pre>
<p>Is it possible to write a type hint that indicates that instances of any type extending Parent are accepted?</p>
|
<python><python-typing>
|
2023-03-22 09:17:36
| 1
| 1,596
|
mutableVoid
|
75,810,236
| 3,564,468
|
Does the python requests library support query param with no value?
|
<p>I have a server side API with the following URL</p>
<pre><code>https://example.com/abc/JSONInterface.jsp?param1=param1_val&param2=param2_val&param3
</code></pre>
<p>If you notice the param3 it has no value nor is it null/None</p>
<p>As per this <a href="https://stackoverflow.com/a/4557490/3564468">source</a> such URLs are acceptable.</p>
<p>Is it possible to call such an api with python requests library?
<a href="https://requests.readthedocs.io/en/latest/user/quickstart/" rel="nofollow noreferrer">https://requests.readthedocs.io/en/latest/user/quickstart/</a></p>
<p>If not is there another library that can handle this?</p>
|
<python><python-3.x><python-requests>
|
2023-03-22 09:07:22
| 1
| 3,023
|
amitection
|
75,810,215
| 6,840,039
|
Pandas: changing the data after saving and loading
|
<p>I have a dataframe, which contains column <code>user_pseudo_id</code> and it looks like</p>
<pre><code>user_pseudo_id
2041513012.1676969234
2041513191.1677359234
2041513765.1677359510
</code></pre>
<p>And it's a string type.
Then I try to save it and load it again. So the problem is that I get the different values in this column.</p>
<p>I get</p>
<pre><code>user_pseudo_id
2041513012.1676967
2041513191.1677360
2041513765.1677360
</code></pre>
<p>For writing and loading I use usual code</p>
<pre><code>df.to_csv(path_to_data, index=False)
df = pd.read_csv(path_to_data)
</code></pre>
<p>What is the problem and how can I fix it?</p>
|
<python><pandas>
|
2023-03-22 09:05:10
| 1
| 4,492
|
Petr Petrov
|
75,810,214
| 14,917,676
|
Resizing Image Data Pixel-by-Pixel using Python
|
<h2>Description</h2>
<p>Say, I have the data about an 4x4 image:</p>
<pre class="lang-py prettyprint-override"><code>IMG = (
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12],
[13,14,15,16]
)
</code></pre>
<p>How would I, without using those of "heavy" big-data modules, Scale it up to 6x6 or 8x8?</p>
<h2>Trials</h2>
<p>I made these two attempts, (upon help from ChatGPT and Bing's GPT)</p>
<pre class="lang-py prettyprint-override"><code>def resize_image(image):
height = len(image)
width = len(image[0])
new_height = height * 1.5
new_width = width * 1.5
new_image = [[0 for j in range(new_width)] for i in range(new_height)]
for i in range(new_height):
for j in range(new_width):
x = i // 2
y = j // 2
new_image[i][j] = image[x][y]
return new_image
</code></pre>
<p>It works but only for sizes that are integer-multiples of the original resolution, say I want <code>4x4</code> to <code>8x8</code> It will work fine... but not for <code>4x4</code> to <code>6x6</code>...</p>
<p>After more trials and *<em>ChatGPT</em>*, I assembled this:</p>
<pre><code>def resize_image(image, new_height, new_width):
height = len(image)
width = len(image[0])
scale_factor_x = (width - 1) / (new_width - 1)
scale_factor_y = (height - 1) / (new_height - 1)
new_image = [[0 for j in range(new_width)] for i in range(new_height)]
for i in range(new_height):
for j in range(new_width):
x = j * scale_factor_x
y = i * scale_factor_y
x1 = int(x)
y1 = int(y)
x2 = min(x1 + 1, width - 1)
y2 = min(y1 + 1, height - 1)
q11 = image[y1][x1]
q12 = image[y2][x1]
q21 = image[y1][x2]
q22 = image[y2][x2]
new_image[i][j] = int(q11 * (x2 - x) * (y2 - y) + q21 * (x - x1) * (y2 - y) + q12 * (x2 - x) * (y - y1) + q22 * (x - x1) * (y - y1))
return new_image
</code></pre>
<p>which hillariously gives me this:</p>
<pre><code>[
[1, 1, 2, 2, 3, 0],
[3, 3, 4, 5, 5, 0],
[5, 6, 7, 7, 8, 0],
[8, 8, 9, 9, 10, 0],
[10, 11, 11, 12, 13, 0],
[0, 0, 0, 0, 0, 0]
]
</code></pre>
<p>What am I missing in here?</p>
|
<python><algorithm><image><vector><scaling>
|
2023-03-22 09:05:09
| 1
| 487
|
whmsft
|
75,810,163
| 13,158,157
|
pyspark to pandas dataframe: datetime compatability
|
<p>I am using pyspark to do most of the data wrangling but at the end I need to convert to pandas dataframe. When converting columns that I have formatted to date become "object" dtype in pandas.</p>
<p>Are datetimes between pyspark and pandas incompatible? How can I keep dateformat after pyspark -> pandas dataframe convertion ?</p>
<p>EDIT: <a href="https://stackoverflow.com/questions/57131202/converting-pyspark-dataframe-with-date-column-to-pandas-results-in-attributeerro">converting to timestamp</a> is a workaround as suggested in other question. How can I find out more on data type compatability between pyspark vs pandas ? There is not much info on <a href="https://docs.databricks.com/pandas/pyspark-pandas-conversion.html" rel="nofollow noreferrer">documentation</a></p>
|
<python><pandas><pyspark>
|
2023-03-22 08:58:50
| 1
| 525
|
euh
|
75,810,094
| 19,580,067
|
Automate Python Script in Microsoft Power Automate
|
<p>I tried to automate the python script in Microsoft Power Automate to run daily. The python Script is all about doing some enquiries from the newly received emails and fetching keywords and sending all of them as a new email.
The Script is working fine in visual studio code, command prompt.
But not sure what I'm doing wrong in the power automate. This is the first time I'm using power automate. The script is not working seems.. not receiving any output emails.</p>
<p>I have Created two variable first in power automate.</p>
<p>First variable: Path to the python executable
Second variable: Path to my python script
Then run both of them using powershell script. Tried with python script as well. Didn't work</p>
<p><a href="https://i.sstatic.net/6gXlq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6gXlq.png" alt="enter image description here" /></a>
<a href="https://i.sstatic.net/sTo47.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sTo47.png" alt="enter image description here" /></a></p>
|
<python><power-automate-desktop>
|
2023-03-22 08:52:13
| 1
| 359
|
Pravin
|
75,809,897
| 11,703,015
|
pd.groupby in two columns sum() function does not work
|
<p>I am trying to do the next example. I want to get the total number of survivors (<em>survived</em>) and the total amount paid per class (<em>fared</em>) using the Titanic dataset.</p>
<pre><code>import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/bvalgard/data/main/titanic.csv')
df.groupby(['pclass'])[['survived', 'fare']].sum()
</code></pre>
<p>When I run this code, I only get the total number of survivors, but not the total amount paid. However, if I use other functions such as <code>.min()</code>, <code>.max()</code> etc it works.</p>
<p>What is the problem with the <code>.sum()</code> function then?</p>
|
<python><pandas><dataframe><group-by>
|
2023-03-22 08:29:37
| 1
| 516
|
nekovolta
|
75,809,848
| 10,037,034
|
How to filter date column data from sas with saspy (Python)?
|
<p>I want to filter date column for a table</p>
<pre><code>data = sas.sasdata("METEOGROUP", "ABC", "PANDAS",
{
"where":
"DATE_DAY>'2021-04-20'"
}
).to_df()
</code></pre>
<p>But there is no result from this query.
Without where clause i can see this dates.
How can i solve this problem?</p>
<p>DATE_DAY continues dates like this ; 2016-05-03</p>
|
<python><sas><where-clause><saspy>
|
2023-03-22 08:23:46
| 1
| 1,311
|
Sevval Kahraman
|
75,809,832
| 16,475,089
|
"image" is not accessed - Pylance
|
<p>Pyance is showing false warnings in certain functions.</p>
<p><a href="https://i.sstatic.net/qP7we.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qP7we.png" alt="enter image description here" /></a></p>
<p>Even the variable is used it still shows as it. For example in the above picture</p>
<ul>
<li>The varible <code>image</code> from line 1984 is accessed in line number 1986.</li>
<li>The varible <code>image_obj</code> from line 1985 is accessed in line number 1991 and 1992.</li>
<li>And similar cases on other lines too.</li>
</ul>
<p>Can anyone help me figure why this is happening?</p>
|
<python><visual-studio-code><pylance>
|
2023-03-22 08:21:58
| 1
| 1,839
|
ilyasbbu
|
75,809,698
| 1,838,230
|
Python using self to call function syntax
|
<p>Been digging into the source code of the Python package <code>transformers</code>, saw this code and am stumped.</p>
<pre><code>model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
outputs = self(
**model_inputs,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
</code></pre>
<p>What is the <code>self()</code> call doing here? Is it calling the class instance?</p>
<p>For reference, the source code is here: <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/generation/utils.py" rel="nofollow noreferrer">https://github.com/huggingface/transformers/blob/main/src/transformers/generation/utils.py</a></p>
<p>Please read the source code on the link, this class does not have a <code>__call__</code> method implemented.</p>
|
<python><class>
|
2023-03-22 08:04:34
| 0
| 892
|
ZWang
|
75,809,648
| 12,242,085
|
How to upper all columns from DataFrame except columns from list if columns from list exists in DataFrame in Python Pandas?
|
<p>I have DataFrame in Python Pandas like below (my real DF has many many more columns):</p>
<p><strong>Input data:</strong></p>
<pre><code>COL1 | col2 | col3
------|--------|-------
X | 11 | 2021
Y | 22 | 1990
</code></pre>
<p><strong>Requirements:</strong></p>
<p>And I need to make upper each column names in DataFrame except column names from list below if columns from list exists:</p>
<pre><code>list_not_to_up = ["col2", "col55"]
</code></pre>
<p>my code is:</p>
<pre><code>df.columns = [x.upper() if x not in df[list_not_to_up].columns else x for x in df.columns]
</code></pre>
<p>Nevertheless I have error: <code>KeyError: "['col55'] not in index"</code></p>
<p><strong>Desire output:</strong></p>
<pre><code>COL1 | col2 | COL3
------|--------|-------
X | 11 | 2021
Y | 22 | 1990
</code></pre>
<p>How to modify my code so as to upper all columns from DataFrame except columns from list if of course columns from list exists in DataFrame in Python Pandas?</p>
|
<python><pandas><dataframe><list><uppercase>
|
2023-03-22 07:58:24
| 1
| 2,350
|
dingaro
|
75,809,249
| 16,869,946
|
Generating new dataframe based on combination of rows
|
<p>I have a dataframe that is indexed by <code>Race_ID</code></p>
<pre><code>Race_ID Student_ID Rank
1 1 3
1 2 2
1 3 1
1 4 4
2 1 2
2 2 3
2 3 1
</code></pre>
<p>And I want to create a new dataframe based on the above dataframe by generating a new row using combination of each <code>Student_ID</code> within each <code>Race_ID</code>
So the outcome looks like</p>
<pre><code>Race_ID Student_ID_pair Rank_sum
1 1-2 5
1 1-3 4
1 1-4 7
1 2-3 3
1 2-4 6
1 3-4 5
2 1-2 5
2 1-3 3
2 2-3 4
</code></pre>
<p>So there are now 4C2=6 rows for <code>Race_ID = 1</code> and 3C2=3 rows for <code>Race_ID = 2</code>, and <code>Rank_sum</code> is just the sum of ranks of the respective students. Thanks in advance.</p>
|
<python><python-3.x><pandas><dataframe>
|
2023-03-22 07:07:00
| 1
| 592
|
Ishigami
|
75,809,212
| 19,945,688
|
Python - How can I simplify updating dictionary value to update it with substring of it
|
<p>Instead of repeating or assigning it to a new variable how can I simplify this expression?</p>
<blockquote>
<pre class="lang-py prettyprint-override"><code>
dict['key'] = dict['key'][0:100]
</code></pre>
</blockquote>
<p>In Dart one can do</p>
<pre><code> map.update('key', (v)=> v.substring(0,100));
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I see an update method in Python that I can be use as</p>
<pre><code>dict.update({'key': new_value})
</code></pre>
<p>What I want is some kind of callback with a pointer to the original value of the dictionary.</p>
<p><strong>UPDATE 2</strong></p>
<p>Python</p>
<pre><code>dict.update({'key': new_value})
</code></pre>
<p>What I want is</p>
<pre><code>dict.update({'key' *self[0,100]})
</code></pre>
<p>where <code>*self</code> is original value instead of using <code>dict.get('key')</code></p>
|
<python><python-3.x>
|
2023-03-22 07:00:56
| 3
| 1,396
|
Soliev
|
75,808,891
| 4,447,853
|
Alternatives to brute force algebra with additive/sigma functions
|
<p>I have an equation</p>
<pre><code> 7405
210000 = Ξ£ (x * (1 - 1/y)^n)
n = 0
</code></pre>
<p>My goal is to find various x and y values that make it true. I also require for x and y to be whole numbers.</p>
<p>The way I have been doing it so far takes an incredible amount of time and is not very efficient... and right now I get no certain answers as they start to end in .999999999999</p>
<p>I am not sure if the numbers are not exactly precise which you get with floats on occasion or they actually have that many trailing 9s.</p>
<pre class="lang-py prettyprint-override"><code>def closest_to_21000(a, b):
diff_a = abs(a - 21000)
diff_b = abs(b - 21000)
if diff_a < diff_b:
return a
else:
return b
def func():
n = 7405 # for sigma
maxResult = 0 # to keep track of our closest winners
maxX = 0
for x in range(1, 1001): # looping through X vals
for y in range(1, 10001): # looping through Y vals
result = sum(x * (1 - 1/y)**i for i in range(1, n+1)) # summization func
if result > 21000: # if it's over 21,000 we can move to the next Y val
break
resu = closest_to_21000(maxResult, result) # is maxResult or new result is closer
if maxResult == resu and x == maxX: # if that and x are the same as last one, new Y
break
maxResult = resu # max result = whichever was closer
if maxResult == result: # if the new result was
maxX = x # update maxX
print(result, x, y)
func()
# closest answer I got was "20999.999999999996 700 31"
</code></pre>
<p>Is there a more efficient way I can do it? And a way to guarantee it's a whole number so I don't have to guess if it just has a trailing 0.99999999 after it? It takes a super long time if I want it to equal 21000000 instead of 21000. As of right now I am fine with it only checking x and y values between 1000 and 10000.</p>
|
<python><math><sum><brute-force><algebra>
|
2023-03-22 06:06:54
| 1
| 527
|
chriscrutt
|
75,808,619
| 992,165
|
Overriding method python class of a pip module to update its behavior globally
|
<p>Using OOP I want to do something like</p>
<pre><code>from django.contrib import admin
class NavigateFormAdmin(admin.ModelAdmin):
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
context['next_record_id'] = custom_function_to_calculate(context['obj'].id)
res = super().render_change_form(request, context, add, change, form_url)
return res
</code></pre>
<p>And <strong>expect</strong> that whenever <code>render_change_form</code> of <code>admin.ModelAdmin</code> is called, it should first my overridden method (above) which then should call the original (parent) method. but it makes no difference, because my overridden method never gets called rather on any call to <code>render_change_form</code> the method from original class <code>admin.ModelAdmin</code> is called.</p>
<hr />
<p>Using undesired monkey patching</p>
<p><strong>I am able to achieve</strong> what I need by adding following code to any of my py file that is read by interpreter at the start of my project/service execution</p>
<pre><code>from django.contrib import admin
from django.template.response import TemplateResponse
# and also all the other imports used in original medthod
class NavigateFormAdmin(admin.ModelAdmin):
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
opts = self.model._meta
app_label = opts.app_label
preserved_filters = self.get_preserved_filters(request)
# and all the code of existing function has to be repeated here
context['next_record_id'] = custom_function_to_calculate(context['obj'].id)
res = TemplateResponse(request, form_template, context)
return res
admin.ModelAdmin.render_change_form = NavigateFormAdmin.render_change_form
</code></pre>
<p>Now on every call to <code>admin.ModelAdmin.render_change_form</code> off-course <code>NavigateFormAdmin.render_change_form</code> is executed</p>
<p><strong>But I need to</strong> use <code>super()</code> like (the first piece of code which is not working) here because OOP means re-usability, so what I could achieve is not satisfactory as all the 50 lines code of original method is repeated to only one line for overriding. Also this repeated code cause some unexpected results for changed version of <code>admin.ModelAdmin</code></p>
|
<python><django><oop><overriding><monkeypatching>
|
2023-03-22 05:08:34
| 1
| 8,449
|
Sami
|
75,808,346
| 6,546,694
|
How to manage python dependencies based upon user input? A question about structuring the python code
|
<p>I am trying to implement the methodology described <a href="https://medium.com/optuna/lightgbm-tuner-new-optuna-integration-for-hyperparameter-optimization-8b7095e99258" rel="nofollow noreferrer">here</a>. The details except for the ones I will post here are irrelevant to the scope of the question</p>
<ol>
<li>The intent is to implement hyperparameter tuning for lightgbm</li>
<li>I do it the typical way - import lightgbm via <code>import lightgbm</code>, write a class that does it for me</li>
<li>There is a special way to do hyperparameter optimization for lightgbm and that requires me to import lightgbm like <code>from optuna.integration import lightgbm</code> and the rest of the code can remain identical</li>
<li>I want to provide the end users the capability to choose between the vanilla methodology (in point 2) or the special methodology (point 3). To implement that I have the following in the <code>__init__</code> of the main class and the <code>__init__</code> takes and argument <code>use_lightgbm_heuristics=True</code></li>
</ol>
<pre><code>global lightgbm
if use_lightgbm_heuristics:
print("will be using heuristics")
from optuna.integration import lightgbm
else:
print("will be using vanilla lgbm")
import lightgbm
</code></pre>
<p>There is an import statement in the main class of my code. Can I do better?</p>
|
<python><python-3.x><design-patterns>
|
2023-03-22 03:59:24
| 1
| 5,871
|
figs_and_nuts
|
75,808,155
| 4,299,527
|
How to apply a function while filtering using loc method in pandas?
|
<p>I have a dataframe <strong>A</strong> and dataframe <strong>B</strong> in pandas. I want to update one of A's column based if certain conditions for a row is matched in B. While matching with multiple conditions, I want to apply a function called "<strong>similar</strong>" on the current row like below:</p>
<pre><code>def similar(a, b):
match_ratio = SequenceMatcher(None, a, b).ratio()
if match_ratio > 0.6:
return True
else:
return False
def updateLabel(repo_name, str_a):
str_to_check = re.sub('[^a-zA-Z0-9]+', '', str_a)
data = B.loc[(B['repo_name'] == repo_name) & similar(B["sanitized_str_b"], str_to_check)]
if len(data) > 0:
return "TP"
return "FP"
A["label"] = A[["repo_name", "str_a"]].apply(lambda x: updateLabel(x.repo_name, x.str_a), axis = 1)
</code></pre>
<p>However, it throws an error. Then I tried like below but it is very slow.</p>
<pre><code>def updateLabel(repo_name, str_a):
str_to_check = re.sub('[^a-zA-Z0-9]+', '', str_a)
def similar(a):
match_ratio = SequenceMatcher(None, a, str_to_check).ratio()
if match_ratio > 0.6:
return True
else:
return False
data = B.loc[(B['repo_name'] == repo_name)]
data = B.loc[data.sanitized_str_b.apply(similar)]
if len(data) > 0:
return "TP"
return "FP"
A["label"] = A[["repo_name", "str_a"]].apply(lambda x: updateLabel(x.repo_name, x.str_a), axis = 1)
</code></pre>
<p>What is the correct way to filter a dataframe with multiple conditions and conditions by calling a function in pandas?</p>
|
<python><pandas>
|
2023-03-22 03:14:52
| 2
| 12,152
|
Setu Kumar Basak
|
75,808,091
| 12,702,027
|
Python skips coroutine evaluation
|
<p>I've been trying to get around Python's recursion limit using coroutines, and through trial and error arrived at <a href="https://github.com/jc65536/pyrecfun/blob/main/fibawait2.py" rel="nofollow noreferrer">this code</a> which recursively calculates Fibonacci numbers:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
from typing import Callable, Coroutine
def recursive(f: Callable[[int], Coroutine]):
return lambda x: asyncio.create_task(f(x))
m = [0, 1]
@recursive
async def f(x: int):
if len(m) <= x:
m.append(await f(x - 1) + await f(x - 2))
return m[x]
async def main():
print(await f(2000))
asyncio.run(main())
# prints 4224696333392304878706725602341482782579852840250681098010280137314308
# 58437013070722412359963914151108844608753890960360764019471164359602927198331
# 25987373262535558026069915859152294924539049987222567953169828744824729922639
# 01833716778060607011615497886719879858311468870876264597369086722884023654422
# 29524334796448013951534956297208765265606952980649984197744872015561280266540
# 4554171717881930324025204312082516817125
</code></pre>
<p>Could someone explain why this does not cause infinite recursion? As stated in the comments in the linked file, I expected Python to eagerly evaluate <code>f(x)</code> in the lambda, which seems like it would have lead to infinite recursion. What surprised me was that while stepping through the code using a debugger, it seems like the lambda just skipped evaluating <code>f(x)</code> entirely and was somehow immediately able to pass a coroutine to <code>asyncio.create_task</code>. (*)</p>
<p>I should add, this is on Python 3.10.10.</p>
<p>Edit: to clarify (*)</p>
<p>Suppose we had this instead of the lambda:</p>
<pre><code>def my_create_task(c):
return asyncio.create_task(c)
def recursive(f):
def callf(x):
return my_create_task(f(x))
return callf
</code></pre>
<p>What'll happen as I keep pressing "step into" is</p>
<ol>
<li>Enter <code>callf</code></li>
<li>Enter <code>my_create_task</code>, with <code>c</code> bound to a coroutine - I expected the debugger to enter <code>f</code> here</li>
<li>Return from <code>my_create_task</code></li>
<li>Return from <code>callf</code></li>
<li>Enter <code>f</code> with <code>x=2000</code></li>
</ol>
|
<python><recursion><python-asyncio><coroutine>
|
2023-03-22 02:57:37
| 1
| 386
|
Jason
|
75,808,046
| 2,128,799
|
Strange errors using factory_boy and DjangoModelFactory
|
<p>I've created several factories including a user factory that looks like so</p>
<pre><code>class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.User
django_get_or_create = ('phonenumber',)
uuid = factory.Faker('uuid4')
email = factory.Faker('email')
phonenumber = factory.Sequence(generate_phone_number)
</code></pre>
<p>I'm using the django unit test TestCase model like so</p>
<pre><code>class ApiV1TestCase(TestCase):
def setUp(self):
self.user = UserFactory.create()
</code></pre>
<p>and getting the following error: <code>*** django.db.utils.IntegrityError: duplicate key value violates unique constraint "accounts_user_pkey" DETAIL: Key (id)=(1) already exists.</code></p>
<p>when I run it several times I get a continual error with what looks like a correctly autoincremented ID field, ie. <code>Key (id)=(2) already exists.</code> ... <code>Key (id)=(3) already exists.</code> on each subsequent create() call.</p>
<p>If I check the test database, I see that <code>User.objects.all()</code> is empty in all of these cases.</p>
<p>Alternatively I'm able to successfully run</p>
<pre><code>UserFactory.build()
u.save()
</code></pre>
<p>however this isn't great for obvious reasons (ie. I want to override an <code>auto_now</code> datetime field in some tests)</p>
<p>I've also noticed some strange behavior, if I check <code>transaction.get_connection().in_atomic_block </code> from <code>django.db.transaction</code> I get <code>True</code> which seems to indicate somehow that I'm in an atomic block? I'm not sure if this is normal behavior.</p>
|
<python><django><django-rest-framework><django-orm><factory-boy>
|
2023-03-22 02:44:04
| 1
| 1,294
|
Dash Winterson
|
75,807,897
| 1,857,373
|
NotOneValueFound: Expected one value, found 0 sklean 1.02 updated to sklean 1.2.2 then code broke
|
<p><strong>problem</strong></p>
<p>Defining models for OneVsRestClassifier and OneVsOneClassifier for SVC kernel='rbf'. Code was running fine until I updated sklearn from 1.02 to 1.2.2</p>
<p>I first perform a min max scaler to transform the training data, working code.
Perform standard scaling. Then select with iloc[] the pixels range. Then select the y label for y response. Then create the OneVsRestClassifier and OneVsOneClassifier model classifiers to execute on SCV with kernel choice of RBF, all working code before upgrading to sklearn 1.2.2.</p>
<p>What is the compiler complaining regarding 'A task has failed to un-serialize'?</p>
<p><strong>Code</strong></p>
<pre><code>train = train.loc[(train['label'] > 1) & (train['label'] < 4)]
y = train['label']
X_train, X_test, y_train, y_test = train_test_split(train, y, test_size=0.60, random_state=42)
min_max_scaler = preprocessing.MinMaxScaler()
X_train_scaled = min_max_scaler.fit_transform(X_train.iloc[:, 2:786])
X = X_train.iloc[:, 2:786]
y = X_train['label']
X_train = X_train.drop(['label'], axis=1)
svc_RBF_OVR_model = OneVsRestClassifier(SVC(kernel='rbf'))
svc_RBF_OVO_model = OneVsOneClassifier(SVC(kernel='rbf'))
param_grid = {
"estimator__C": [1,2,4,8],
"estimator__kernel": ["poly","rbf"],
"estimator__degree":[1, 2, 3, 4]
}
# Tune the hyperparameters using GridSearchCV
svc_RBF_OVR_grid_param = RandomizedSearchCV(svc_RBF_OVR_model, param_grid, cv=5, n_jobs=3, error_score="raise")
svc_RBF_OVO_grid_param = RandomizedSearchCV(svc_RBF_OVO_model, param_grid, cv=5, n_jobs=3, error_score="raise")
svc_RBF_OVR_model_fit = svc_RBF_OVR_grid_param.fit(X_train_scaled, y_train)
svc_RBF_OVO_model_fit = svc_RBF_OVO_grid_param.fit(X_train_scaled, y_train)
</code></pre>
<p><strong>Error message trace</strong></p>
<pre><code>exception calling callback for <Future at 0x7fc951a564f0 state=finished raised BrokenProcessPool>
joblib.externals.loky.process_executor._RemoteTraceback:
"""
Traceback (most recent call last):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/process_executor.py", line 391, in _process_worker
call_item = call_queue.get(block=True, timeout=timeout)
File "/Users/matthew/opt/anaconda3/lib/python3.9/multiprocessing/queues.py", line 122, in get
return _ForkingPickler.loads(res)
AttributeError: Can't get attribute '_FuncWrapper' on <module 'sklearn.utils.fixes' from '/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/fixes.py'>
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/_base.py", line 625, in _invoke_callbacks
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 359, in __call__
###############################################################################
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 792, in dispatch_next
def _effective_n_jobs(self):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 859, in dispatch_one_batch
# queue, _ready_batches, that is looked-up prior to re-consuming
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 777, in _dispatch
if self.timeout is not None and not self._backend.supports_timeout:
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/_parallel_backends.py", line 531, in apply_async
"DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/reusable_executor.py", line 177, in submit
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/process_executor.py", line 1102, in submit
worker_exit_lock.acquire()
joblib.externals.loky.process_executor.BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.
Unexpected exception formatting exception. Falling back to standard exception
joblib.externals.loky.process_executor._RemoteTraceback:
"""
Traceback (most recent call last):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/process_executor.py", line 391, in _process_worker
call_item = call_queue.get(block=True, timeout=timeout)
File "/Users/matthew/opt/anaconda3/lib/python3.9/multiprocessing/queues.py", line 122, in get
return _ForkingPickler.loads(res)
AttributeError: Can't get attribute '_FuncWrapper' on <module 'sklearn.utils.fixes' from '/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/fixes.py'>
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3442, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "/var/folders/zl/zh18_1yx1b74nzd6kt936mlh0000gn/T/ipykernel_67007/2196762926.py", line 20, in <module>
svc_RBF_OVR_model_fit = svc_RBF_OVR_grid_param.fit(X_train_scaled, y_train)
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/sklearn/model_selection/_search.py", line 891, in fit
self.refit, refit_metric, results
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/sklearn/model_selection/_search.py", line 1766, in _run_search
def _run_search(self, evaluate_candidates):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/sklearn/model_selection/_search.py", line 838, in evaluate_candidates
if len(out) < 1:
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 1054, in __call__
if hasattr(pre_dispatch, 'endswith'):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 933, in retrieve
self._print('Done %3i tasks | elapsed: %s',
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/_parallel_backends.py", line 542, in wrap_future_result
elif not (self.in_main_thread() or self.nesting_level == 0):
File "/Users/matthew/opt/anaconda3/lib/python3.9/concurrent/futures/_base.py", line 446, in result
return self.__get_result()
File "/Users/matthew/opt/anaconda3/lib/python3.9/concurrent/futures/_base.py", line 391, in __get_result
raise self._exception
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/_base.py", line 625, in _invoke_callbacks
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 359, in __call__
###############################################################################
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 792, in dispatch_next
def _effective_n_jobs(self):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 859, in dispatch_one_batch
# queue, _ready_batches, that is looked-up prior to re-consuming
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/parallel.py", line 777, in _dispatch
if self.timeout is not None and not self._backend.supports_timeout:
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/_parallel_backends.py", line 531, in apply_async
"DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/reusable_executor.py", line 177, in submit
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/joblib/externals/loky/process_executor.py", line 1102, in submit
worker_exit_lock.acquire()
joblib.externals.loky.process_executor.BrokenProcessPool: A task has failed to un-serialize. Please ensure that the arguments of the function are all picklable.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 2057, in showtraceback
stb = self.InteractiveTB.structured_traceback(
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 1118, in structured_traceback
return FormattedTB.structured_traceback(
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 1012, in structured_traceback
return VerboseTB.structured_traceback(
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 865, in structured_traceback
formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 818, in format_exception_as_a_whole
frames.append(self.format_record(r))
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 736, in format_record
result += ''.join(_format_traceback_lines(frame_info.lines, Colors, self.has_colors, lvals))
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/stack_data/core.py", line 698, in lines
pieces = self.included_pieces
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/stack_data/core.py", line 649, in included_pieces
pos = scope_pieces.index(self.executing_piece)
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/stack_data/utils.py", line 145, in cached_property_wrapper
value = obj.__dict__[self.func.__name__] = self.func(obj)
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/stack_data/core.py", line 628, in executing_piece
return only(
File "/Users/matthew/opt/anaconda3/lib/python3.9/site-packages/executing/executing.py", line 164, in only
raise NotOneValueFound('Expected one value, found 0')
executing.executing.NotOneValueFound: Expected one value, found 0
</code></pre>
|
<python><python-3.x><scikit-learn>
|
2023-03-22 02:08:35
| 1
| 449
|
Data Science Analytics Manager
|
75,807,664
| 3,944,252
|
Issues Handling ChatGPT Streaming Response in Terminal using OpenAI API - Using Python, rich library
|
<p>I am trying to integrate the <strong>openAi API</strong> model - <code>gpt-4</code> with Terminal to enable <strong>ChatGPT</strong>. My objective is to receive streaming responses from <strong>ChatGPT</strong> and print them in the Terminal.
Although I can successfully print the entire response without streaming, I'm facing issues with streaming responses. Specifically, the <code>ask_stream</code> function is printing every word on a new line, which is not the desired behavior. I'm using the rich library to handle Markups</p>
<p>My code:</p>
<pre><code>import openai
from rich.markdown import Markdown
from rich.console import Console
from prompt_toolkit import PromptSession
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.history import InMemoryHistory
import time
import argparse
import asyncio
openai.api_key = "MY API KEY"
model = "gpt-4"
delay_time = 0.01
max_response_length = 200
console = Console()
async def ask_stream(prompt):
response = openai.ChatCompletion.create(model='gpt-4',
messages=[{"role": "user", "content": f"{prompt}"}], max_tokens=8000,
temperature=0.4, stream=True)
answer = ''
for event in response:
if answer:
console.print(Markdown(answer), end='')
# sys.stdout.flush()
event_text = event['choices'][0]['delta']
answer = event_text.get('content', '')
time.sleep(0.01)
async def ask(prompt) -> Markdown:
if prompt:
completion = openai.ChatCompletion.create(model=model,
messages=[{"role": "user", "content": f"{prompt}"}])
if completion:
if 'error' in completion:
return completion['error']['message']
return Markdown(completion.choices[0].message.content)
else:
raise Exception("")
def create_session() -> PromptSession:
return PromptSession(history=InMemoryHistory())
async def get_input_async(
session: PromptSession = None,
completer: WordCompleter = None,
) -> str:
"""
Multiline input function.
"""
return await session.prompt_async(
completer=completer,
multiline=True,
auto_suggest=AutoSuggestFromHistory(),
)
async def main():
print(f"Starting Chatgpt with model - {model}")
session = create_session()
while True:
print("\nYou:")
question = await get_input_async(session=session)
print()
print()
if question == "!exit":
break
elif question == "!help":
print(
"""
!help - Show this help message
!exit - Exit the program
""",
)
continue
print("ChatGPT:")
if args.no_stream:
console.print(await ask(prompt=question))
else:
await ask_stream(prompt=question)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--no-stream", action="store_true")
args = parser.parse_args()
asyncio.run(main())
</code></pre>
<p><code>ask_stream</code> prints like below
<a href="https://i.sstatic.net/cEJWC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cEJWC.png" alt="enter image description here" /></a></p>
<p>Can someone suggest a solution to fix this issue? I am pretty new to Python.</p>
|
<python><openai-api><rich><gpt-4>
|
2023-03-22 01:09:17
| 1
| 1,588
|
sparker
|
75,807,577
| 820,088
|
Convert a Python List Stored in a Pandas Dataframe Column, to CSV List
|
<p>I have a pandas dataframe column that stores a list. i.e.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>State</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>Oregon</td>
<td>[u'Eugen', u'Portland']</td>
</tr>
<tr>
<td>New York</td>
<td>[u'New Jersey', u'Buffalo']</td>
</tr>
<tr>
<td>Utah</td>
<td>[u'Salt Lake CIty']</td>
</tr>
<tr>
<td>Texas</td>
<td>None</td>
</tr>
</tbody>
</table>
</div>
<p>I want to convert the list of unicode values to a simple csv list.</p>
<p>Something like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>State</th>
<th>Cities</th>
</tr>
</thead>
<tbody>
<tr>
<td>Oregon</td>
<td>'Eugen', 'Portland'</td>
</tr>
<tr>
<td>New York</td>
<td>'New Jersey', 'Buffalo'</td>
</tr>
<tr>
<td>Utah</td>
<td>'Salt Lake CIty'</td>
</tr>
</tbody>
</table>
</div>
<p>I also need to handle cases where 'Cities' is None or the list only has one item.</p>
<p>There are over 1700 records, so I'd like to do this in one bit of code. I've tried weird things like:</p>
<pre><code>df['Cities'] = ','.join(str(row) for row in df['cities'])
</code></pre>
<p>but that seemed to keep appending the list to itself in long sequences and kept returning the unicode list.</p>
|
<python><pandas>
|
2023-03-22 00:50:20
| 2
| 4,435
|
Mike
|
75,807,522
| 6,197,439
|
Exporting arbitrary fields in list of dataclass objects to a dict?
|
<p>Consider this example:</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, asdict, astuple
@dataclass
class Player:
id: int
name: str
color: str
players = [
Player(123, "Alice", "green"),
Player(456, "Bob", "red"),
Player(789, "Gemma", "blue"),
]
print("players:", players)
print("players[0] as dict:", asdict( players[0] ) )
</code></pre>
<p>The printout I get is:</p>
<pre class="lang-none prettyprint-override"><code>players: [Player(id=123, name='Alice', color='green'), Player(id=456, name='Bob', color='red'), Player(id=789, name='Gemma', color='bl
ue')]
players[0] as dict: {'id': 123, 'name': 'Alice', 'color': 'green'}
</code></pre>
<p>Given that all of the entries above have unique values, what would be an easy way to convert specific pairs of <code>Player</code> class fields from the <code>players</code> into a dict?</p>
<p>For instance, if I want to specify <code>Player.id</code> as key and <code>Player.name</code> as value, then the corresponding dict based on the <code>players</code> list will be:</p>
<pre class="lang-none prettyprint-override"><code>{
123: 'Alice',
456: 'Bob',
789: 'Gemma'
}
</code></pre>
<p>The inverse, where <code>Player.name</code> is taken as key and <code>Player.id</code> as value, would then be:</p>
<pre class="lang-none prettyprint-override"><code>{
'Alice': 123,
'Bob': 456,
'Gemma': 789
}
</code></pre>
<p>... or if I want <code>Player.name</code> as key, and <code>Player.color</code> as value, from the <code>players</code> list I'd get:</p>
<pre class="lang-none prettyprint-override"><code>{
'Alice': 'green',
'Bob': 'red',
'Gemma': 'blue'
}
</code></pre>
<p>Is there an easier way to do this (other that loop through the list, and then construct the dictionary "manually")?</p>
<p>Also, in case some values in the list are not unique, how could such a technique be persuaded to only "save" the first key/value combo it encounters in the dict, and ignore subsequent duplicates of the key?</p>
|
<python><list><dictionary><python-dataclasses>
|
2023-03-22 00:35:55
| 2
| 5,938
|
sdbbs
|
75,807,443
| 13,566,716
|
redis lock acquiring not working - stays running and never acquires
|
<p>this is my code:</p>
<pre><code>pool = aioredis.ConnectionPool.from_url("redis://localhost:6379")
redis = await aioredis.Redis(connection_pool=pool, ssl=False, ssl_cert_reqs="None")
async with redis.lock("hello_lock") as lock:
print("hello")
await redis.hset("hello", "1", "2")
</code></pre>
<p>the Context Manager never gets entered and it seems like the lock is not being acquired at all. The program stays running/stuck on this line:
<code>async with redis.lock("hello_lock") as lock:</code></p>
<p>Acquiring the lock should be a very quick thing so i'm confused whats happening here. Any help would be appreciated.</p>
|
<python><python-3.x><redis><locking><aioredis>
|
2023-03-22 00:18:18
| 1
| 369
|
3awny
|
75,807,298
| 3,915,051
|
Sympy: drop terms with small coefficients
|
<p>Is it possible to drop terms with coefficients below a given, small number (say 1e-5) in a Sympy expression? I.e., such that</p>
<pre><code>0.25 + 8.5*exp(-2.6*u) - 2.7e-17*exp(-2.4*u) + 1.2*exp(-0.1*u)
</code></pre>
<p>becomes</p>
<pre><code>0.25 + 8.5*exp(-2.6*u) + 1.2*exp(-0.1*u)
</code></pre>
<p>for instance.</p>
|
<python><sympy><coefficients>
|
2023-03-21 23:47:09
| 3
| 678
|
Tamas Ferenci
|
75,807,210
| 10,363,163
|
How to speed up sentence tokenization with Spacy
|
<p>I am trying to extract the first sentences from a list of paragraphs with the following function (that I apply in a for loop):</p>
<pre class="lang-py prettyprint-override"><code>def extract_first_sentence(text):
doc = nlp(text)
return [sent.text for sent in doc.sents][0]
</code></pre>
<p>The code does what I want but is slow. It seems inefficient to extract all sentences first with <code>.text</code> but apparently there is no way to subset <code>doc.sents</code> directly. The tips given in <a href="https://stackoverflow.com/questions/55597688/speed-up-spacy-tokenizer">this question</a> do not really apply for the most part because I do not need to read and write files as I go. I'm using the model <code>"en_core_web_trf"</code>.</p>
|
<python><spacy><spacy-transformers>
|
2023-03-21 23:25:14
| 0
| 3,489
|
dufei
|
75,807,012
| 21,420,742
|
How to map previous values by ID. Python
|
<p>I tried asking this before and the last post was hard to understand. I have a dataset that looks at Employee IDs, their job, manager, and previous managers. What I want to do is update the previous manager column so that it displays only the most recent of the previous managers. Here is what I have:</p>
<pre><code> ID Date Job_Title Current_Manager Previous Manager MGR_Change
1 2/2/2022 Sales John D. NaN No
1 3/2/2022 Sales John D. John D. No
1 4/2/2022 Sales John D. John D. No
2 1/14/2022 Tech Mary S. NaN No
2 2/14/2022 Tech Mary S. Mary S. No
2 3/14/2022 Tech Larry H. Mary S. Yes
2 4/14/2022 Tech Larry H. Larry H. No
3 7/16/2022 Advisor Karl M. Nan No
3 8/16/2022 Advisor Sarah D. Karl M. Yes
3 9/16/2022 Advisor Michael S. Sarah D. Yes
</code></pre>
<p>From here I would like to only display the most recent of the previous managers in the 'Previous Manager' off of the MGR_Change column like so:</p>
<pre><code> ID Date Job_Title Current_Manager Previous Manager
1 2/2/2022 Sales John D. John D.
1 3/2/2022 Sales John D. John D.
1 4/2/2022 Sales John D. John D.
2 1/14/2022 Tech Mary S. Mary S.
2 2/14/2022 Tech Mary S. Mary S.
2 3/14/2022 Tech Larry H. Mary S.
2 4/14/2022 Tech Larry H. Mary S.
3 7/16/2022 Advisor Karl M. Sarah D.
3 8/16/2022 Advisor Sarah D. Sarah D.
3 9/16/2022 Advisor Michael S. Sarah D.
</code></pre>
|
<python><python-3.x>
|
2023-03-21 22:47:49
| 1
| 473
|
Coding_Nubie
|
75,806,892
| 1,763,602
|
Is it possible to build an ARM64 linux wheel on Github?
|
<p>Currently I use <code>cibuildwheel</code> for building a c extension on Github.</p>
<p><code>cibuildwheel</code> supports ARM64 for Windows (experimental) and Mac. It seems to support also ARM64 linux, with the name aarch64 (that is the "canonical" name of ARM64).</p>
<p>AArch64 linux needs QEMU. The problem is that in the <a href="https://cibuildwheel.readthedocs.io/en/stable/options/#examples_2" rel="nofollow noreferrer">example</a> it's not clear how to specify in the Github pipeline the use of QEMU for AArch64.</p>
|
<python><arm><github-actions>
|
2023-03-21 22:28:51
| 2
| 16,005
|
Marco Sulla
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.