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
⌀ |
|---|---|---|---|---|---|---|---|---|
78,052,782
| 21,935,028
|
Antlr4 python runtime error after generating from grammar
|
<p>I using the following Antlr4 PLSQL grammar files:</p>
<p><a href="https://github.com/antlr/grammars-v4/tree/master/sql/plsql" rel="nofollow noreferrer">https://github.com/antlr/grammars-v4/tree/master/sql/plsql</a>.</p>
<p>From here I downloaded as follows:</p>
<pre><code>wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/Python3/PlSqlLexerBase.py
wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/Python3/PlSqlParserBase.py
wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/PlSqlLexer.g4
wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/PlSqlParser.g4
mv PlSql*g4 grammars
wget https://www.antlr.org/download/antlr-4.13.1-complete.jar
mv antlr-4.13.1-complete.jar lib
</code></pre>
<p>Giving me :</p>
<pre><code>├── lib
│ ├── antlr-4.13.1-complete.jar
├── grammars1
│ ├── PlSqlLexer.g4
│ └── PlSqlParser.g4
├── PlSqlLexer.g4
├── PlSqlParser.py
</code></pre>
<p>When I then run:</p>
<pre><code>java -jar ./lib/antlr-4.9.3-complete.jar -Dlanguage=Python3 grammars/*g4
</code></pre>
<p>I get the following generated in <code>grammars</code>:</p>
<pre><code>grammars-v4-master PlSqlLexer.interp PlSqlParserBase.py PlSqlParserListener.py __pycache__
master.zip PlSqlLexer.py PlSqlParser.g4 PlSqlParser.py runPLSQL.py
PlSqlLexer.g4 PlSqlLexer.tokens PlSqlParser.interp PlSqlParser.tokens
</code></pre>
<p>I then create the runPLSQL.py Python script :</p>
<pre><code>cd grammars
python3 runPLSQL.py ../../plsql/test.sql
</code></pre>
<p>But this errored with:</p>
<pre><code>
import pandas
Traceback (most recent call last):
File "/home/me/try2/grammars/runPLSQL.py", line 11, in <module>
from PlSqlParserListener import PlSqlParserListener
File "/home/me/try2/grammars/PlSqlParserListener.py", line 6, in <module>
from PlSqlParser import PlSqlParser
File "/home/me/try2/grammars/PlSqlParser.py", line 14, in <module>
from PlSqlParserBase import PlSqlParserBase
File "/home/me/try2/grammars/PlSqlParserBase.py", line 1, in <module>
{"payload":{"allShortcutsEnabled":false,"fileTree":{"sql/plsql/Python3":{"items":[{"name":"PlSqlLexerBase.py","path":"sql/plsql/Python3/PlSqlLexerBase.py","contentType":"file"}
NameError: name 'false' is not defined. Did you mean: 'False'?
</code></pre>
<p>I had to edit the <code>PlSqlLexerBase.py</code> file as below to overcome this and similar errors:</p>
<ol>
<li>Replace <code>:false</code> with <code>:False</code></li>
<li>Replace <code>:true</code> with <code>:True</code></li>
<li>Replace <code>:null</code> with <code>:None</code></li>
</ol>
<p>But now I get this:</p>
<pre><code> import pandas
Traceback (most recent call last):
File "/home/me/try2/grammars/runPLSQL.py", line 11, in <module>
from PlSqlParserListener import PlSqlParserListener
File "/home/me/try2/grammars/PlSqlParserListener.py", line 6, in <module>
from PlSqlParser import PlSqlParser
File "/home/me/try2/grammars/PlSqlParser.py", line 14, in <module>
from PlSqlParserBase import PlSqlParserBase
ImportError: cannot import name 'PlSqlParserBase' from 'PlSqlParserBase' (/home/me/try2/grammars/PlSqlParserBase.py)
</code></pre>
<p>The <code>PlSqlParserBase.py</code> script starts with:</p>
<pre><code>{"payload":{"allShortcutsEnabled":False,"fileTree":{"sql/plsql/Python3":{"items":[{"name":"PlSqlLexerBase.py","path":"sql/plsql/Python3/PlSqlLexerBase.py","contentType":"file"},{"name":"PlSqlParserBase.py","path":"sql/plsql/Python3/PlSqlParserBase.py","contentType":"file"}],"totalCount":2},"sql/plsql":{"items":[{"name":"CSharp","path":"sql/plsql/CSharp","contentTy......
</code></pre>
<p>I notice it references relative pathnames, should all the paths/files exist?</p>
<p>The top of the <code>runPLSQL.py</code> script is:</p>
<pre><code>import os
import pandas
from antlr4 import InputStream, ParseTreeWalker
from antlr4.CommonTokenStream import CommonTokenStream
from pandas import DataFrame
#from PlSql.grammar.PlSqlListener import PlSqlListener
#from PlSql.grammar.PlSqlLexer import PlSqlLexer
#from PlSql.grammar.PlSqlParser import PlSqlParser
from PlSqlParserListener import PlSqlParserListener
from PlSqlLexer import PlSqlLexer
from PlSqlParser import PlSqlParser
from tabulate import tabulate
class SQLParser(PlSqlListener):
</code></pre>
<p>I also looked in the autogenerated <code>master.zip</code> and it contains file names being referneced, though not the exact same path:</p>
<pre><code>unzip -l master.zip | grep PlSql
896 2024-02-20 11:13 grammars-v4-master/sql/plsql/CSharp/PlSqlLexerBase.cs
720 2024-02-20 11:13 grammars-v4-master/sql/plsql/CSharp/PlSqlParserBase.cs
367 2024-02-20 11:13 grammars-v4-master/sql/plsql/Cpp/PlSqlLexerBase.h
614 2024-02-20 11:13 grammars-v4-master/sql/plsql/Cpp/PlSqlParserBase.h
109954 2024-02-20 11:13 grammars-v4-master/sql/plsql/Dart/PlSqlLexer.g4
358 2024-02-20 11:13 grammars-v4-master/sql/plsql/Dart/PlSqlLexerBase.dart
149085 2024-02-20 11:13 grammars-v4-master/sql/plsql/Dart/PlSqlParser.g4
571 2024-02-20 11:13 grammars-v4-master/sql/plsql/Dart/PlSqlParserBase.dart
354 2024-02-20 11:13 grammars-v4-master/sql/plsql/Java/PlSqlLexerBase.java
610 2024-02-20 11:13 grammars-v4-master/sql/plsql/Java/PlSqlParserBase.java
259 2024-02-20 11:13 grammars-v4-master/sql/plsql/JavaScript/PlSqlLexerBase.js
506 2024-02-20 11:13 grammars-v4-master/sql/plsql/JavaScript/PlSqlParserBase.js
115277 2024-02-20 11:13 grammars-v4-master/sql/plsql/PlSqlLexer.g4
228726 2024-02-20 11:13 grammars-v4-master/sql/plsql/PlSqlParser.g4
157 2024-02-20 11:13 grammars-v4-master/sql/plsql/Python3/PlSqlLexerBase.py
364 2024-02-20 11:13 grammars-v4-master/sql/plsql/Python3/PlSqlParserBase.py
334 2024-02-20 11:13 grammars-v4-master/sql/plsql/TypeScript/PlSqlLexerBase.ts
604 2024-02-20 11:13 grammars-v4-master/sql/plsql/TypeScript/PlSqlParserBase.ts
</code></pre>
|
<python><antlr4>
|
2024-02-24 14:24:23
| 1
| 419
|
Pro West
|
78,052,710
| 6,239,096
|
How to pass a variable value in SSIS to Python Script : Execute Process task
|
<p>I've a execute process task which executes python Script<a href="https://i.sstatic.net/n0qzu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/n0qzu.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/YDWK0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YDWK0.png" alt="enter image description here" /></a></p>
<p>I want to pass root variable value in python from SSIS when I give the project parameter value in Python script it is throwing an error how do I do this?</p>
|
<python><ssis><sql-server-data-tools><ssis-2012><msbi>
|
2024-02-24 14:01:12
| 1
| 844
|
sai bharath
|
78,052,703
| 11,049,863
|
How to automatically scroll (autoscroll) a list of images contained in a list with tkinter
|
<p>My job is to automatically display, one by one, the pages of a pdf file with tkinter. To do this, I create an image for each page and store all the images in a list. I can display all the pages from my list with manual scrolling. But I want it to be automatic (autoscroll). How can I proceed?<br/>
Here is my code:</p>
<pre><code>import os,ironpdf,time
import shutil
from tkinter import *
from PIL import Image,ImageTk
def do_nothing():
print("No thing")
def convert_pdf_to_image(pdf_file):
pdf = ironpdf.PdfDocument.FromFile(pdf_file)
#Extrat all pages to a folder as image files
folder_path = "images"
pdf.RasterizeToImageFiles(os.path.join(folder_path,"*.png"))
#List to store the image paths
image_paths = []
#Get the list of image files in the folder
for filename in os.listdir(folder_path):
if filename.lower().endswith((".png",".jpg",".jpeg",".gif")):
image_paths.append(os.path.join(folder_path,filename))
return image_paths
def on_closing():
#Delete the images in the 'images' folder
shutil.rmtree("images")
window.destroy()
window = Tk()
window.title("PDF Viewer")
window.geometry("1900x800")
canvas = Canvas(window)
canvas.pack(side=LEFT,fill=BOTH,expand=True)
canvas.configure(background="black")
scrollbar = Scrollbar(window,command=canvas.yview)
scrollbar.pack(side=RIGHT,fill=Y)
canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind("<Configure>",lambda e:canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind("<MouseWheel>",lambda e:canvas.yview_scroll(int(-1*(e.delta/120)),"units"))
frame = Frame(canvas)
canvas.create_window((0,0),window=frame,anchor="nw")
images = convert_pdf_to_image("input.pdf")
for image_path in images:
print(image_path)
image = Image.open(image_path)
photo = ImageTk.PhotoImage(image,size=1200)
label = Label(frame,image=photo)
label.image = photo
label.pack(fill=BOTH)
time.sleep(1)
window.mainloop()
</code></pre>
|
<python><tkinter><autoscroll>
|
2024-02-24 13:59:00
| 1
| 385
|
leauradmin
|
78,052,641
| 11,861,874
|
Tkinter Output of Function as Table and Graph
|
<p>I have two functions that produce two types of output one is a data frame table and the other is a plot of that dataframe. All functions take one file as input. which we load from the previous tkinter function. I would like to dynamically select a function from the radio box, next, once we select a particular function it should show a blank box that will ask for input from a user and based on input the function will get executed.</p>
<pre><code>from tkinter import ttk
import tkinter as tk
root= Tk()
root.geometry("800X600")
root.config(bg='light blue')
root.title('Dashboard')
frame = tk.Frame(root,bg='light blue')
frame.pack(padx=10,pady=10)
file_label = tk.Label(frame,text='Input_File')
file_label.grid(row=0,colulmn=0)
def function_1(Input_File,Var1,Var2):
# Table and Graph will be based on the above input.
def function_2(Input_File,Var3,Var4,Var5,Var6):
# Table and Graph will be based on the above input.
root.mainloop()
</code></pre>
<p>Once we select function_1 from the radio box, then immediately we should get two boxes next to the radio box which will ask for "Var1" and "Var2". If we select function_2 then we should get four boxes next to the radio box which will ask for "Var3", "Var4", "Var5", and "Var6".</p>
<p>Once all the input is received we should process the respective function and below we should get two outputs first "dataframe" table produced from function and plot again produced from the function.</p>
<p>Please note "InputFile" in both the function is same as InputFile from file_lable.</p>
|
<python><tkinter>
|
2024-02-24 13:40:31
| 1
| 645
|
Add
|
78,052,611
| 10,470,463
|
How to get the text of the email body?
|
<p>I have this code but I don't actually get the email text.</p>
<p>Have I got to decode the email text?</p>
<pre><code>import sys
import imaplib
import getpass
import email
import email.header
from email.header import decode_header
import base64
def read(username, password, sender_of_interest):
# Login to INBOX
imap = imaplib.IMAP4_SSL("imap.mail.com", 993)
imap.login(username, password)
imap.select('INBOX')
# Use search(), not status()
# Print all unread messages from a certain sender of interest
if sender_of_interest:
status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
else:
status, response = imap.uid('search', None, 'UNSEEN')
if status == 'OK':
unread_msg_nums = response[0].split()
else:
unread_msg_nums = []
data_list = []
for e_id in unread_msg_nums:
data_dict = {}
e_id = e_id.decode('utf-8')
_, response = imap.uid('fetch', e_id, '(RFC822)')
html = response[0][1].decode('utf-8')
email_message = email.message_from_string(html)
data_dict['mail_to'] = email_message['To']
data_dict['mail_subject'] = email_message['Subject']
data_dict['mail_from'] = email.utils.parseaddr(email_message['From'])
#data_dict['body'] = email_message.get_payload()[0].get_payload()
data_dict['body'] = email_message.get_payload()
data_list.append(data_dict)
print(data_list)
# Mark them as seen
#for e_id in unread_msg_nums:
#imap.store(e_id, '+FLAGS', '\Seen')
imap.logout()
return data_dict
</code></pre>
<p>So I do this:</p>
<pre><code>print('Getting the email text bodiies ... ')
emailData = read(usermail, pw, sender_of_interest)
print('Got the data!')
for key in emailData.keys():
print(key, emailData[key])
</code></pre>
<p>The output is:</p>
<blockquote>
<p>mail_to me@mail.com<br />
mail_subject Get json file<br />
mail_from ('Pedro Rodriguez', 'pedro@gmail.com')<br />
body [<email.message.Message object at 0x7f7d9f928df0>, <email.message.Message object at 0x7f7d9f928f70>]</p>
</blockquote>
<p>How to actually get the email text?</p>
|
<python><email><mime>
|
2024-02-24 13:31:00
| 2
| 511
|
Pedroski
|
78,052,486
| 3,995,261
|
How do I make the type of a dictionary inferred from its value in Python?
|
<p>Consider this simple config:</p>
<pre><code>config = {
'sentry': {
'endpoint': '...',
'server_name': '...',
},
}
</code></pre>
<p>let's imagine that it's in fact big (tens of keys on different levels). I'm looking for a way to "infer" the type of config to achieve 3 goals:</p>
<ol>
<li>Suggestions should work fine in VS Code (assume that the keys of <code>config</code> are not changed). As currently written, if I type <code>config[</code>, IntelliSense suggests <code>'sentry'</code> as expected, but if type <code>config['sentry'][</code>, instead of <code>endpoint, server_name</code>, it suggests a whole lot of irrelevant stuff (<code>type, config, add, assert, ......</code>).
<ol>
<li>In fact, I'd also like to highlight adding a key (<code>config['kek'] = 'lol'</code>) as an error (or allow adding only specific keys)</li>
</ol>
</li>
<li>Pylance should highlight reading <code>config['kek']</code> as an error (<code>'kek'</code> doesn't exist in <code>config</code>).</li>
<li>The solution should be DRY: I don't want to repeat each key outside the dictionary, I want them to be inferred from its shape.</li>
</ol>
<p>In TypeScript, I just write</p>
<pre><code>const config = {
sentry: {
endpoint: '...',
cserver_name: 'kek',
},
}
</code></pre>
<p>and all these goals are achieved automatically, can I get these at least by using some annotation in Python?</p>
|
<python><python-typing>
|
2024-02-24 12:55:14
| 0
| 8,448
|
YakovL
|
78,052,480
| 8,484,261
|
Filling up a pandas pivot table with missing columns for months and adding month column headers
|
<p>I am pivoting a dataframe to get it into long form. The data is by month and year. But not all months are present.</p>
<ol>
<li>How do I add the columns for the missing months and fill those with ZERO?</li>
<li>How do I merge the top two column identifiers (Year and Month) into one Date identifier for the month?</li>
</ol>
<p>The executable code is below.</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'Year':[2022,2022,2023,2023,2024,2024],
'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy'],
'Unit Price':[np.nan,200,None,56,75,65],
'Quantity':[1500, 140000, 1400000, 455, 648, 759],
'Amount':[100, 10000, 100000, 5, 48, 59],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey'],
'energy':[100.,100,100,54,98,3],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo']
})
index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount','Quantity']
columns_to_use = ['Year','Month']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
</code></pre>
<p>The solution should be able to identify years in the data and add columns for missing months with ZERO or nan. In the data above for example we have 3 years, 2022, 2023 and 2024 but we have data only for Dec in 2022 and 2023 and Jan in 2024. The output dataframe should have Jan to Dec for all three years 2022, 2023 and 2024 with ZERO or nan in those cells where the original dataframe did not have data?</p>
|
<python><pandas><dataframe><pivot-table><multi-index>
|
2024-02-24 12:53:47
| 1
| 3,700
|
Alhpa Delta
|
78,052,441
| 5,615,873
|
What is the difference between cv2.waitKey() and cv2.waitKey(0)?
|
<p>I have found a lot of questions around about what is <code>cv2.waitKey()</code> used for, about the difference between <code>cv2.waitKey(0)</code> and <code>cv2.waitKey(1)</code>, etc., the answers to which can be found in many OpenCV documentations. Yet, I have not found any documentation or people asking about the <strong>difference between <code>cv2.waitKey(0)</code> and <code>cv2.waitKey()</code></strong>. Both seem to have the same effect, namely waiting for a keypress before the image window is closed. Yet, In dozens of codes that I have seen, they all use <code>cv2.waitKey(0)</code>. For example:</p>
<pre><code>cv2.imshow("my_image", img)
cv2.waitKey(0)
</code></pre>
<p>So, is there a particular reason for that or is <code>0</code> just useless?</p>
<p>(My opencv-python version is 4.9.0.80.)</p>
|
<python><opencv>
|
2024-02-24 12:42:37
| 1
| 3,537
|
Apostolos
|
78,052,412
| 21,935,028
|
Antlr4 PLSQL Errors
|
<p>I'm trying to test the Antlr4 (Oracle) PLSQL grammar, but really struggling. I might have confused things by having followed 2 or 3 different guides.</p>
<p>I performed the following steps, starting with installation, on Ubuntu 22.04.</p>
<p>Install packages, but not sure I ended up using these:</p>
<pre><code>sudo apt-get update
sudo apt-get -y install python3-antlr4
sudo apt install python3-pip
pip3 install antlr-plsql
pip3 install antlr4-python3-runtime==4.9.3
</code></pre>
<p>I then switched to another guide, which seemed simpler and more self-contained:</p>
<pre><code>mkdir lib
cd lib
curl -O https://www.antlr.org/download/antlr-4.9.3-complete.jar
cd ..
mkdir grammars
cd grammars
wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/PlSqlLexer.g4
wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/PlSqlParser.g4
cd ..
wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/Python3/PlSqlLexerBase.py
wget https://github.com/antlr/grammars-v4/blob/master/sql/plsql/Python3/PlSqlParserBase.py
</code></pre>
<p>This gives me:</p>
<pre><code>├── grammars
│ ├── PlSqlLexer.g4
│ └── PlSqlParser.g4
├── lib
│ └── antlr-4.9.3-complete.jar
├── PlSqlLexerBase.py
├── PlSqlParserBase.py
</code></pre>
<p>Generate the Python 3 modules from the grammars:</p>
<pre><code>java -jar ./lib/antlr-4.9.3-complete.jar -Dlanguage=Python3 grammars/*g4
</code></pre>
<p>The result is very long error message:</p>
<pre><code>error(50): /home/me/try2/grammars/PlSqlLexer.g4:1:0: syntax error:
'{"payload":
{"allShortcutsEnabled":false,"fileTree":
{"sql/plsql":
{"items":
[ {"name":"CSharp","path":"sql/plsql/CSharp","contentType":"directory"},
{"name":"Cpp","path":"sql/plsql/Cpp","contentType":"directory"},
{"name":"Dart","path":"sql/plsql/Dart","contentType":"directory"},
.
.
.
"grammars-v4",
"showInvalidCitationWarning":false,
"citationHelpUrl":"https://docs.github.com/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-citation-files",
"actionsOnboardingTip":null},
"truncated":false,"viewable":true,"workflowRedirectUrl":null,"symbols":{"timed_out":false,"not_analyzed":true,"symbols":[]}},
"copilotInfo":null,
"copilotAccessAllowed":false,
"csrf_tokens":{"/antlr/grammars-v4/branches":{"post":"B-JVTx4hyskRLh-IIK4rWkAi5MsB-02SSXgjgq9nYNzDI1ZfW5iKO2EvjBCRVSAFlOtcSNnBT47ACuB9TmN_KA"},"/repos/preferences":{"post":"GKOXPKaenoTNYzUHdAFAZKMu0-z4ENu8r5KmHmhUiOKs4HBOuNY9PVTbSAMl7rKPVfBwRCJRpTY72nxBH5PotA"}}},
"title":"grammars-v4/sql/plsql/PlSqlParser.g4 at master · antlr/grammars-v4"}'
came as a complete surprise to me
</code></pre>
<p>Tried this as well but got the same result:</p>
<pre><code>java -Xmx500M -cp "./lib/antlr-4.9.3-complete.jar:$CLASSPATH" org.antlr.v4.Tool -Dlanguage=Python3 grammars/*g4
</code></pre>
|
<python><parsing><plsql><antlr4>
|
2024-02-24 12:34:31
| 1
| 419
|
Pro West
|
78,052,404
| 13,517,174
|
unreachable network error when establishing a bluetooth connection between raspberrypi and laptop
|
<p>I have a c++ script, which I am running on my raspberry pi to automatically connect to a device that attempts connection and receives arrays of the fixed size 8:</p>
<pre><code>#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main() {
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
socklen_t opt = sizeof(rem_addr);
int server_sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
loc_addr.rc_family = AF_BLUETOOTH;
memset(&loc_addr.rc_bdaddr, 0, sizeof(loc_addr.rc_bdaddr));
loc_addr.rc_channel = (uint8_t) 1;
if (bind(server_sock, (struct sockaddr *)&loc_addr, sizeof(loc_addr)) < 0) {
perror("Failed to bind Bluetooth socket");
return 1;
}
listen(server_sock, 1);
while (true) {
std::cout << "Waiting for connections..." << std::endl;
int client_sock = accept(server_sock, (struct sockaddr *)&rem_addr, &opt);
if (client_sock < 0) {
std::cerr << "Failed to accept connection" << std::endl;
continue;
}
std::cout << "Connection accepted" << std::endl;
while (true) {
float buffer[8];
int bytes_read = read(client_sock, buffer, sizeof(buffer));
if (bytes_read > 0) {
std::cout << "Received array of floats:" << std::endl;
for (int i = 0; i < 8; ++i) {
std::cout << buffer[i] << std::endl;
}
} else {
std::cout << "Connection closed or read error" << std::endl;
break;
}
}
close(client_sock);
}
close(server_sock);
return 0;
}
</code></pre>
<p>When I compile and run it, it waits with the message</p>
<pre><code>$ ./client
Waiting for connections...
</code></pre>
<p>I then run the following python script on my laptop:</p>
<pre><code>import struct
import bluetooth
class Driver():
def __init__(self):
self.serverMACAddress = 'DC:A6:32:99:B1:66' # mock mac address
self.port = 1
self.device_socket = None
def main(self):
print("connecting...")
self.connect()
def connect(self):
self.device_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
self.device_socket.connect((self.serverMACAddress, self.port))
def send(self,message):
print("sending {}".format(message))
data = struct.pack('8f', *message)
self.sock.send(data)
self.sock.close()
if __name__ == "__main__":
d = Driver()
d.main()
d.send([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8])
</code></pre>
<p>However, the python script generates the following error after 2 seconds:</p>
<pre><code>> python .\remote_driver\driver.py
connecting...
Traceback (most recent call last):
File "C:\<Path>\remote_driver\driver.py", line 37, in <module>
d.main()
File "C:\<Path>\remote_driver\driver.py", line 21, in main
self.connect()
File "C:\<Path>\remote_driver\driver.py", line 25, in connect
self.device_socket.connect((self.serverMACAddress, self.port))
File "C:\Users\<User>\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bluetooth\msbt.py", line 96, in connect
bt.connect (self._sockfd, addr, port)
OSError: A socket operation was attempted to an unreachable network.
</code></pre>
<p>Is there anything that I didn't consider when setting up these two scripts that is causing this error to occur? I already made my raspi discoverable with <code>bluetoothctl</code> -> <code>discoverable on</code> but it made no difference, on my windows 11 laptop, all outbound connections that do not match a rule are allowed.</p>
|
<python><c++><raspberry-pi><bluetooth><network-programming>
|
2024-02-24 12:32:21
| 1
| 453
|
Yes
|
78,052,180
| 893,254
|
What are the differences between AbstractEventLoop.create_server and asyncio.start_server?
|
<p>I am trying to understand the differences between</p>
<ul>
<li><code>AbstractEventLoop.create_server()</code></li>
<li><code>asyncio.start_server()</code></li>
</ul>
<p>and why one might choose one of these options over the other.</p>
<p>The relevant documentation pages can be found</p>
<ul>
<li>for <code>AbstractEventLoop.create_server()</code> <a href="https://python.readthedocs.io/en/latest/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_server" rel="nofollow noreferrer">here</a></li>
<li>for <code>asyncio.start_server()</code> <a href="https://python.readthedocs.io/en/latest/library/asyncio-stream.html#asyncio.start_server" rel="nofollow noreferrer">here</a></li>
</ul>
<p>From the documentation they appear to be very similar.</p>
<p>The differences as far as I currently understand are:</p>
<ul>
<li><code>start_server</code> speaks in terms of <code>StreamReader</code> and <code>StreamWriter</code>. These are "higher level" objects compared to their counterparts (not sure exactly what the counterpart is right now). What the detailed consequences of this being "higher level" are for the user I also don't yet fully understand</li>
<li><code>create_server</code> requires a <code>Protocol</code> object to be specified. If I understand correctly, the programmer has to define a <code>class MyProtocol</code> which inherits from <code>asyncio.Protocol</code> and defines implementations for some common callbacks for "events" such as <code>connection_made</code>. Documentation link <a href="https://docs.python.org/3/library/asyncio-protocol.html#protocols" rel="nofollow noreferrer">here</a></li>
</ul>
<p>Other than knowing a few details about the differences I don't have any detailed understanding of what the intended purpose of each of these options are.</p>
|
<python><python-asyncio>
|
2024-02-24 11:14:17
| 1
| 18,579
|
user2138149
|
78,052,149
| 1,608,765
|
Identify lines in spectrogram using python
|
<p>I have a long strip of data with some lines in it that are visually very clear (both blue and red), however, I can't seem to be able to identify them versus the background.</p>
<p>I've tried to average the array in in the time direction, run that through a low pass filter and then identify the peaks. But it does not seem to work. Therefore, I was wondering if perhaps the image itself can be used to look for the locations, using say openCV or such?
<a href="https://i.sstatic.net/jsm2w.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jsm2w.png" alt="enter image description here" /></a></p>
|
<python><signal-processing><spectrum>
|
2024-02-24 11:06:05
| 0
| 2,723
|
Coolcrab
|
78,052,124
| 3,018,893
|
Running the next step of a generator in a separate process
|
<p>How would it be possible to resume a generator in another process.</p>
<p>Assume the following:</p>
<ol>
<li>The processes have access to the same code</li>
<li>The scope should propogate between iterations</li>
<li>If necessary modify the python interpreter itself</li>
</ol>
<p>An example of the kind of generator</p>
<pre><code>def simple_generator():
# do some stuff in process one
yield
# do some stuff in process two
</code></pre>
|
<python>
|
2024-02-24 10:57:06
| 0
| 520
|
Jack burridge
|
78,051,902
| 12,129,443
|
Why I am unable to import trl package in Jupyter?
|
<p>I am trying to import <code>SFTTrainer</code> from <code>trl</code> package. I am getting the error message - <code>ImportError: cannot import name 'override' from 'typing_extensions' (D:\...\..\)</code>. <strong>I am able to do it perfectly well in Google Colab, no issues</strong>. Why is this? How can I import on my local PC/ <code>Jupyter</code>?</p>
<p>I installed the <code>trl</code> package and tried importing <code>SFFTrainer</code> using:</p>
<pre><code>!pip install trl
from trl import SFTTrainer
</code></pre>
<p>I tried uninstalling and reinstalling <code>typing-extensions</code>, that did not work. I uninstalled <code>trl</code> and tried installing it from <code>Anaconda powershell prompt</code> and I tried a few other installations, updates and uninstallations. I even tried importing <code>trl</code> from <code>github</code> and then load. None of them is working.</p>
<p>How to resolve this?</p>
|
<python><machine-learning><jupyter-notebook><huggingface-trainer><nltk-trainer>
|
2024-02-24 09:46:41
| 1
| 668
|
Srinivas
|
78,051,606
| 3,067,485
|
Cannot reproduce a bifurcation diagram from article
|
<p>I have been reading this article <a href="https://www.researchgate.net/publication/348791076_A_Simple_Guide_for_Plotting_a_Proper_Bifurcation_Diagram" rel="nofollow noreferrer">A Simple Guide for Plotting a Proper Bifurcation Diagram</a> and I want to reproduce the following figure (Fig. 10, p. 2150011-7):</p>
<p><a href="https://i.sstatic.net/lrBDr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lrBDr.png" alt="enter image description here" /></a></p>
<p>I have created this procedure that works fine with other classical bifurcation diagrams:</p>
<pre><code>def model(x, r):
return 8.821 * np.tanh(1.487 * x) - r * np.tanh(0.2223 * x)
def diagram(r, x=0.1, n=1200, m=200):
xs = []
for i in range(n):
x = model(x, r)
if i >= n - m:
xs.append(x)
return np.array(xs).T
rlin = np.arange(5, 30, 0.01)
xlin = np.linspace(-0.1, 0.1, 2)
clin = np.linspace(0., 1., xlin.size)
colors = plt.get_cmap("cool")(clin)
fig, axe = plt.subplots(figsize=(8, 6))
for x0, color in zip(xlin, colors):
x = diagram(rlin, x=x0, n=600, m=100)
_ = axe.plot(rlin, x, ',', color=color)
axe.set_title("Bifurcation diagram")
axe.set_xlabel("Parameter, $r$")
axe.set_ylabel("Serie term, $x_n(r)$")
axe.grid()
</code></pre>
<p>But for this system, it renders:</p>
<p><a href="https://i.sstatic.net/wl17T.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wl17T.png" alt="enter image description here" /></a></p>
<p>Which looks similar to some extent but is not at the same scale and when <code>r > 17.5</code> has a totally different behaviour than presented in the article.</p>
<p>I am wondering why this difference happens. What have I missed?</p>
|
<python><ode>
|
2024-02-24 07:51:44
| 1
| 11,564
|
jlandercy
|
78,051,555
| 14,298,525
|
Python + Falcon + OpenTelemetry: Not sending traces to OTEL Collector
|
<p>I am trying to instrument my Falcon app to send traces to OTEL Collector. I am doing auto-instrument via launch command and then trying to send traces like the following:</p>
<blockquote>
<p>OTEL_RESOURCE_ATTRIBUTES=service.name=terminus
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT='http://otel-collector:4317'
OTEL_EXPORTER_OTLP_ENDPOINT='http://otel-collector:4317'
OTEL_EXPORTER_OTLP_PROTOCOL=grpc OTEL_EXPORTER_OTLP_INSECURE=true
opentelemetry-instrument gunicorn -c conf.py</p>
</blockquote>
<p>And then added these libraries in my app:</p>
<pre><code>opentelemetry-distro = "0.43b0"
opentelemetry-exporter-otlp = "1.22.0"
opentelemetry-instrumentation-falcon = "0.43b0"
</code></pre>
<p>However, I am getting the following error:</p>
<blockquote>
<p>Transient error StatusCode.DEADLINE_EXCEEDED encountered while exporting traces to otel-collector:4317, retrying in 1s.</p>
</blockquote>
<p>I am running all this in docker-compose and my config for OTEL Collector looks like:</p>
<pre><code>receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
exporters:
otlp:
endpoint: jaeger-all-in-one:4317
tls:
insecure: true
processors:
batch:
extensions:
health_check:
pprof:
endpoint: :1888
zpages:
endpoint: :55679
service:
extensions: [pprof, zpages, health_check]
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlp]
</code></pre>
|
<python><open-telemetry><falcon>
|
2024-02-24 07:32:09
| 0
| 341
|
mifol68042
|
78,051,321
| 9,211,026
|
Python NSSM commands packaged in .exe
|
<p>I have an app that I built with customtkinter. It needs to configure a file and install a python script as a service. That service reads from the config file. It works when I run it from pycharm but when I use auto_py_to_exe the service fails to start with error code 3.</p>
<p>my code runs the following command to install the service and works from pycharm:</p>
<pre><code>cmds = [
'C:/RT_Apps/RT_SIP_Sounder/config/nssm install "RT SIP Alert" "C:/Users/crixe/PycharmProjects/intercomSounder/venv/Scripts/python.exe" "C:/RT_Apps/RT_SIP_Sounder/svc_build/intercom.py"'
]
for cmd in cmds:
subprocess.run(cmd, cwd="C:/RT_Apps/RT_SIP_Sounder/config", stdout=subprocess.PIPE)
print(f"CMD RUN: {cmd} ")
time.sleep(3)
</code></pre>
<p>I have tried to point to a local python.exe file included with the exe build, even including the Scripts folder. I know I'm doing something real dumb, but can't seem to figure out what it is.</p>
|
<python><auto-py-to-exe><nssm>
|
2024-02-24 05:40:15
| 1
| 2,152
|
cmrussell
|
78,051,188
| 5,695,336
|
Will slice then append back to the same shape increase memory usage?
|
<pre><code>x = np.random.rand(3, 4)
x = x[1:]
x = np.append(x, np.random.rand(1, 4), axis=0)
</code></pre>
<p>The second line creates a new view of the original data, so no memory change. My question is that will the third line increase memory usage?</p>
<p>If <code>append</code> copies the original data, regardless of the view, and appends new data to it, it should increase memory usage.</p>
<p>If <code>append</code> constructs a smaller array based on both the view and the original data, and appends new data to it, it should not increase memory usage.</p>
<p>I am not sure which case is it.</p>
<p>Ultimately I want to know will the following script have memory leak?</p>
<pre><code>x = np.random.rand(3, 4)
for _ in range(1000000):
x = x[1:]
x = np.append(x, np.random.rand(1, 4), axis=0)
</code></pre>
|
<python><numpy>
|
2024-02-24 04:11:57
| 1
| 2,017
|
Jeffrey Chen
|
78,051,181
| 308,827
|
Cannot get a constant when using statsmodels add_constant
|
<p>I have the following python code using statsmodels:</p>
<pre><code>import numpy as np
import statsmodels.api as sm
# Assuming future_time_points is an array like this
future_time_points = np.array([2010])
# Stacking future_time_points and its square
stacked_array = np.column_stack((future_time_points, future_time_points ** 2))
# Adding a constant column to the stacked array
array_with_constant = sm.add_constant(stacked_array)
print(array_with_constant)
</code></pre>
<p>The output is <code>[[ 2010 4040100]]</code></p>
<p>I was expecting the output to have a <code>1</code> because I am using <code>add_constant</code>, however it is not there, how can I fix it? I am using statsmodels version 0.14.0</p>
|
<python><statsmodels>
|
2024-02-24 04:06:07
| 1
| 22,341
|
user308827
|
78,050,943
| 13,174,189
|
How to return Document that was used to answer a question using i am using RetrievalQA?
|
<p>I am using python and langchain RetrievalQA for RAG. Here is sample of code that i have written:</p>
<pre><code>loader = UnstructuredPDFLoader(filename, mode="elements")
data = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size = 300, chunk_overlap = 0)
splits = text_splitter.split_documents(data)
splits = chromautils.filter_complex_metadata(splits)
vectorstore = Chroma.from_documents(documents=splits, embedding=embedding_function, persist_directory=PERSIST_DIRECTORY)
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, openai_api_key=OPENAI_KEY)
qa_chain = RetrievalQA.from_chain_type(
llm,
retriever=vectorstore.as_retriever(),
chain_type_kwargs={"prompt": prompt},
return_source_documents=True
)
result = qa_chain({"query": question})
</code></pre>
<p>It only returns the answer to question. How to return Document from <code>splits</code> that was used as context to answer the question?</p>
|
<python><python-3.x><nlp><artificial-intelligence><langchain>
|
2024-02-24 01:22:37
| 1
| 1,199
|
french_fries
|
78,050,933
| 7,658,985
|
Solving Hcaptcha using 2captcha to automate website search (Python)
|
<p>I'm trying to automate a web search via Python.</p>
<p>The website is behind <code>hCaptcha</code> but I'm using a <code>2captcha</code> solver.</p>
<p>Although, I've replicated web browser's behavior, I'm still being asked to solve the <code>hCaptcha</code> again.</p>
<p>Here's what I've tried:</p>
<pre class="lang-py prettyprint-override"><code>import httpx
import trio
from twocaptcha import TwoCaptcha
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0',
'Referer': 'https://iapps.courts.state.ny.us/nyscef/CaseSearch?TAB=courtDateRange',
'Origin': 'https://iapps.courts.state.ny.us'
}
API_KEY = 'hidden'
async def solve_captcha():
solver = TwoCaptcha(API_KEY)
return solver.hcaptcha(
sitekey='600d5d8e-5e97-4059-9fd8-373c17f73d11',
url='https://iapps.courts.state.ny.us/'
)['code']
async def main():
async with httpx.AsyncClient(base_url='https://iapps.courts.state.ny.us/nyscef/', headers=headers, follow_redirects=True) as client:
r = await client.post('CaseSearch?TAB=courtDateRange')
print('[*] - Solving CAPTCHA!')
cap = await solve_captcha()
print('[*] - CAPTCHA Solved')
# Court: Chautauqua County Supreme Court
data = {
'selCountyCourt': '4667226',
'txtFilingDate': '02/14/2024',
'g-recaptcha-response': cap,
'h-captcha-response': cap,
'btnSubmit': 'Search',
}
r = await client.post('https://iapps.courts.state.ny.us/nyscef/CaseSearch?TAB=courtDateRange', data=data)
with open('r.html', 'w') as f:
f.write(r.text)
if __name__ == "__main__":
trio.run(main)
</code></pre>
|
<python><beautifulsoup><python-requests><httpx><2captcha>
|
2024-02-24 01:17:41
| 1
| 11,557
|
αԋɱҽԃ αмєяιcαη
|
78,050,884
| 4,744,396
|
how to iterate through each element of a unknown length of list while passed as argument to a function in python?
|
<p>how can i modify the tab function to print the element 'c'?</p>
<pre><code> def tab(data):
for i, v in enumerate(data):
print(i, v[0], v[1])
tab([['a', 'b']])
tab([['a', 'b', 'c']])
</code></pre>
<p>Result:</p>
<pre><code>$ python3 tabulate2.py
0 a b
0 a b
</code></pre>
|
<python><list>
|
2024-02-24 00:52:16
| 2
| 437
|
chetan honnavile
|
78,050,843
| 8,484,261
|
Using Pivot Table to reshape data in pandas so that multiple value appear below with their own lines
|
<p>I have a dataframe that I am trying to pivot to get into long form. The executable code is below. But the output is not coming out the way I want it. I want the Amount and Quantity to be coming one below the other</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'Year':[2022,2022,2023,2023,2024,2024],
'Month':[1,12,11,12,1,1],
'Code':[None,'John Johnson',np.nan,'John Smith','Mary Williams','ted bundy'],
'Unit Price':[np.nan,200,None,56,75,65],
'Quantity':[1500, 140000, 1400000, 455, 648, 759],
'Amount':[100, 10000, 100000, 5, 48, 59],
'Invoice':['soccer','basketball','baseball','football','baseball','ice hockey'],
'energy':[100.,100,100,54,98,3],
'Category':['alpha','bravo','kappa','alpha','bravo','bravo']
})
index_to_use = ['Category','Code','Invoice','Unit Price']
values_to_use = ['Amount','Quantity']
columns_to_use = ['Year','Month']
df2 = df.pivot_table(index=index_to_use,
values=values_to_use,
columns=columns_to_use)
</code></pre>
<p>This output i want it so that the quantity is not to the right of the Amount but below and then I can sort it so, that the Quantity and Amount for the same (category, COde, Invoice, Unit Price) appear one below the other</p>
<pre><code> 2022
12
category code invoice Unit Price
200 Amount 10000
200 Quantity 140000
</code></pre>
<p>the idea being that the Amount and Quantity sold of the same kind of articles (with same unit price) appear on succeeding rows.</p>
|
<python><pandas><pivot><pivot-table>
|
2024-02-24 00:34:32
| 1
| 3,700
|
Alhpa Delta
|
78,050,753
| 7,751,438
|
ModuleNotFoundError: No module named 'pybind11_tests'
|
<p>When running the <code>pytest</code> command at the root path of my project, I encounter this error. Since there are no SO question on how to solve this issue, I will provide an answer to my own question for others to benefit. Please see answer below.</p>
|
<python><pybind11>
|
2024-02-23 23:55:37
| 1
| 806
|
jsibs
|
78,050,752
| 1,609,514
|
How to write a function that works on both Numpy arrays and Pandas series, returning the same type
|
<p>A feature of some numpy functions is that they work on both arrays and Pandas series:</p>
<pre class="lang-python prettyprint-override"><code>my_series = pd.Series([10, 20, 30], index=([2000, 2001, 2002]), name='My series')
my_array = np.array([10, 20, 30])
print(np.cumsum(my_series))
print(np.cumsum(my_array))
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>2000 10
2001 30
2002 60
Name: My series, dtype: int64
[10 30 60]
</code></pre>
<p>How is this achieved and can I write my own functions in a way that does this?</p>
<p>As an example, let's say I have a Python function that takes an array and returns an array of the same length:</p>
<pre class="lang-python prettyprint-override"><code>def my_func(x):
a = np.empty_like(x)
b = 0
for i in range(len(x)):
b += x[i]
a[i] = b
return a
</code></pre>
<p>How can I generalize it so that it either returns an array or a Pandas series/dataframe if one was passed?</p>
<p>I realize I could do the following, but I suspect this is not how it is done in the Numpy example above:</p>
<pre class="lang-python prettyprint-override"><code>def my_func_for_array_or_series(x):
try:
a = x.copy()
a[:] = my_func(x.values)
except AttributeError:
a = my_func(x)
return a
</code></pre>
|
<python><pandas><numpy><duck-typing>
|
2024-02-23 23:55:26
| 1
| 11,755
|
Bill
|
78,050,698
| 4,119,262
|
Python "While" calculation returns absurd / random amounts for each new inputs
|
<p>I am trying to learn Python. I am hence working on an exercise, where a user inputs a number, and until the sum of numbers inputted is not reaching a given total, the user is told the missing amount (or the amount given / paid "in excess).</p>
<p>I have the following code:</p>
<pre><code>amount_given = int(input("insert a coin"))
amount_remaining = 50 - amount_given
while amount_remaining < 50:
ask_for_missing_amount = int((input(f"Amount due {amount_remaining}")))
amount_given = amount_given + ask_for_missing_amount
amount_remaining = amount_given - ask_for_missing_amount
else:
print(f"Change Owed {ask_for_missing_amount}")
</code></pre>
<p>I first gave 4, and I was told 46 remained. This make sense.
But then when giving 4 again, I was told 4 remained. And then 8 when I gave 4 etc etc...</p>
<p>Here is the exact output:</p>
<pre><code>insert a coin 5
Amount due 45 4
Amount due 5 4
Amount due 9 34
Amount due 13
</code></pre>
<p>This makes no sense. Why?</p>
|
<python><while-loop><sum>
|
2024-02-23 23:32:14
| 1
| 447
|
Elvino Michel
|
78,050,640
| 1,802,225
|
Web3py: can not find ABI function after decoded
|
<p>Here is transaction <a href="https://etherscan.io/tx/0x6465187a7bb43a6db42ee63e5f5cc30fb094393957a7f1ce6c08b5afddf3e0bc" rel="nofollow noreferrer">https://etherscan.io/tx/0x6465187a7bb43a6db42ee63e5f5cc30fb094393957a7f1ce6c08b5afddf3e0bc</a></p>
<p>I don't know why my script can not find ABI Transfer() function after decoded on <code>Chainlink: LINK Token</code> address. The main problem is that script works correct, I tested on many transactions and appended 2 of them for example.</p>
<p>Perhaps problem is in Transfer() input params after decoding? But how to solve it?</p>
<pre class="lang-py prettyprint-override"><code>import requests
import json
from web3 import Web3
from web3._utils.events import get_event_data
from eth_utils import event_abi_to_log_topic
from hexbytes import HexBytes
API_ETHERSCAN = "" # etherscan works without API, you can remove it from url, but make some seconds delay between requests
transactions = [
'0xff8db775b90935b1ade58182054c0be04f613ea23f9e1df73a6114a726e76237', # Transfer +95352033474036727055914 RIO
'0x7bdfe6c2a9309773ddeafddc2624edc2b38f13ec257182576d95d8b5f5ea2cd1', # Transfer +29000000000000000000 INJ
'0x6465187a7bb43a6db42ee63e5f5cc30fb094393957a7f1ce6c08b5afddf3e0bc', # ABI not found. But must be +7,601.747 LINK
]
testnet = 'https://eth.rpc.blxrbdn.com'
#testnet = 'https://eth.merkle.io'
w3 = Web3(Web3.HTTPProvider(testnet))
for t_hash in transactions:
print(f"tx_hash={t_hash}")
tx_receipt = w3.eth.get_transaction_receipt(t_hash)
for i, log in enumerate(tx_receipt['logs']):
print(f" {i+1}) log['address']={log['address']}")
abi = json.loads(json.loads(requests.get(f"https://api.etherscan.io/api?module=contract&action=getabi&address={log['address']}&apikey={API_ETHERSCAN}").text)['result'])
contract = w3.eth.contract(log["address"], abi=abi)
event_abi = [a for a in contract.abi if a["type"] == "event"]
topic2abi = {event_abi_to_log_topic(_): _ for _ in event_abi}
log_ = {
'address': None, #Web3.toChecksumAddress(address),
'blockHash': None, #HexBytes(blockHash),
'blockNumber': None,
'data': log['data'],
'logIndex': None,
'topics': [HexBytes(_) for _ in log["topics"]],
'transactionHash': None, #HexBytes(transactionHash),
'transactionIndex': None
}
try:
event_abi = topic2abi[log['topics'][0]]
except KeyError as e:
exit('ABI event not found!')
data = get_event_data(w3.codec, event_abi, log_)['args']
print(f" {event_abi['name']} {data['value'] if 'value' in data else ''}")
</code></pre>
<p>Output:</p>
<pre><code>tx_hash=0xff8db775b90935b1ade58182054c0be04f613ea23f9e1df73a6114a726e76237
1) log['address']=0xf21661D0D1d76d3ECb8e1B9F1c923DBfffAe4097
Transfer 95352033474036727055914
tx_hash=0x7bdfe6c2a9309773ddeafddc2624edc2b38f13ec257182576d95d8b5f5ea2cd1
1) log['address']=0xe28b3B32B6c345A34Ff64674606124Dd5Aceca30
Transfer 29000000000000000000
tx_hash=0x6465187a7bb43a6db42ee63e5f5cc30fb094393957a7f1ce6c08b5afddf3e0bc
1) log['address']=0x514910771AF9Ca656af840dff83E8264EcF986CA
ABI event not found!
</code></pre>
<p>Prove:
<a href="https://i.sstatic.net/lB6Xo.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lB6Xo.jpg" alt="enter image description here" /></a></p>
|
<python><ethereum><solidity><smartcontracts><web3py>
|
2024-02-23 23:13:07
| 1
| 1,770
|
sirjay
|
78,050,623
| 5,978,130
|
create virtual conda env from yaml file on macOs
|
<p>I have a macOS Ventura 13.6.4 MacBook Pro. I have installed python 3.11.5 using the anaconda installer for macOs. I am trying to create a conda virtual python environment from a yaml file. The script I'm running in the terminal is below, along with the yaml file and the error message I'm getting. Can you please tell me what is causing the error message and how I can modify the yaml file or bash script to avoid the errors.</p>
<p>bash script:</p>
<pre><code>conda env create -f llm_110623.yml
</code></pre>
<p>error message:</p>
<pre><code>Collecting package metadata (repodata.json): done
Solving environment: failed
ResolvePackageNotFound:
- libunistring==0.9.10=h27cfd23_0
- libstdcxx-ng==11.2.0=h1234567_1
- tbb==2021.8.0=hdb19cb5_0
- libopus==1.3.1=h7b6447c_0
- psutil==5.9.0=py310h5eee18b_0
- bottleneck==1.3.5=py310ha9d4c09_0
- tornado==6.2=py310h5eee18b_0
- abseil-cpp==20211102.0=hd4dd3e8_0
- networkx==2.8.4=py310h06a4308_1
- orc==1.7.4=hb3bc3d3_1
- aws-c-common==0.6.8=h5eee18b_1
- idna==3.4=py310h06a4308_0
- libbrotlicommon==1.0.9=h5eee18b_7
- libvpx==1.7.0=h439df22_0
- tokenizers==0.13.3=py310h22610ee_0
- libcusolver==11.4.0.1=0
- ld_impl_linux-64==2.38=h1181459_1
- yaml==0.2.5=h7b6447c_0
- jupyter_core==5.3.0=py310h06a4308_0
- multidict==6.0.2=py310h5eee18b_0
- comm==0.1.2=py310h06a4308_0
- grpc-cpp==1.48.2=he1ff14a_1
- markupsafe==2.1.1=py310h7f8727e_0
- frozenlist==1.3.3=py310h5eee18b_0
- xformers==0.0.19=py310_cu11.8.0_pyt2.0.0
- gnutls==3.6.15=he1e5248_0
- jinja2==3.1.2=py310h06a4308_0
- libgomp==11.2.0=h1234567_1
- libwebp-base==1.2.4=h5eee18b_1
- wheel==0.38.4=py310h06a4308_0
- lz4-c==1.9.4=h6a678d5_0
- giflib==5.2.1=h5eee18b_3
- libtiff==4.5.0=h6a678d5_2
- re2==2022.04.01=h295c915_0
- sympy==1.11.1=py310h06a4308_0
- libidn2==2.3.4=h5eee18b_0
- libgcc-ng==11.2.0=h1234567_1
- libcurl==8.1.1=h251f7ec_1
- libgfortran5==11.2.0=h1234567_1
- chardet==4.0.0=py310h06a4308_1003
- libwebp==1.2.4=h11a3e52_1
- zlib==1.2.13=h5eee18b_0
- libprotobuf==3.20.3=he621ea3_0
- yarl==1.8.1=py310h5eee18b_0
- bzip2==1.0.8=h7b6447c_0
- freetype==2.12.1=h4a9f257_0
- cuda-cupti==11.7.101=0
- readline==8.2=h5eee18b_0
- ffmpeg==4.2.2=h20bf706_0
- numpy-base==1.25.0=py310hb5e798b_0
- jedi==0.18.1=py310h06a4308_1
- cuda-nvrtc==11.7.99=0
- libcusparse==11.7.4.91=0
- libsodium==1.0.18=h7b6447c_0
- xz==5.4.2=h5eee18b_0
- brotlipy==0.7.0=py310h7f8727e_1002
- ipykernel==6.19.2=py310h2f386ee_0
- pillow==9.4.0=py310h6a678d5_0
- cryptography==41.0.2=py310h22a60cf_0
- mkl-service==2.4.0=py310h5eee18b_1
- lcms2==2.12=h3be6417_0
- colorama==0.4.6=py310h06a4308_0
- libev==4.33=h7f8727e_1
- mkl_random==1.2.2=py310h1128e8f_1
- mpc==1.1.0=h10f8cd9_1
- aws-c-event-stream==0.1.6=h6a678d5_6
- pytorch-cuda==11.7=h778d358_5
- filelock==3.9.0=py310h06a4308_0
- x264==1!157.20191217=h7b6447c_0
- arrow-cpp==11.0.0=h374c478_1
- tqdm==4.65.0=py310h2f386ee_0
- certifi==2023.7.22=py310h06a4308_0
- requests==2.31.0=py310h06a4308_0
- traitlets==5.7.1=py310h06a4308_0
- libcublas==11.10.3.66=0
- gmpy2==2.1.2=py310heeb90bb_0
- cuda-runtime==11.7.1=0
- krb5==1.20.1=h143b758_1
- lerc==3.0=h295c915_0
- intel-openmp==2023.1.0=hdb19cb5_46305
- libtasn1==4.19.0=h5eee18b_0
- libboost==1.73.0=h28710b8_12
- libthrift==0.15.0=h1795dd8_2
- transformers==4.29.2=py310h06a4308_0
- libevent==2.1.12=hdbd6064_1
- libpng==1.6.39=h5eee18b_0
- attrs==23.1.0=py310h06a4308_0
- urllib3==1.26.16=py310h06a4308_0
- xxhash==0.8.0=h7f8727e_3
- libnghttp2==1.52.0=h2d74bed_1
- debugpy==1.5.1=py310h295c915_0
- cuda-libraries==11.7.1=0
- pandas==2.1.1=py310h1128e8f_0
- mkl==2023.1.0=h6d00ec8_46342
- joblib==1.2.0=py310h06a4308_0
- jpeg==9e=h5eee18b_1
- nettle==3.7.3=hbbd107a_1
- aws-checksums==0.1.11=h5eee18b_2
- aws-sdk-cpp==1.8.185=h721c034_1
- mkl_fft==1.3.6=py310h1128e8f_1
- snappy==1.1.9=h295c915_0
- libffi==3.4.4=h6a678d5_0
- et_xmlfile==1.1.0=py310h06a4308_0
- pyopenssl==23.2.0=py310h06a4308_0
- libgfortran-ng==11.2.0=h00389a5_1
- mpmath==1.3.0=py310h06a4308_0
- ncurses==6.4=h6a678d5_0
- pyzmq==25.1.0=py310h6a678d5_0
- pandas-stubs==1.5.3.230203=py310h06a4308_0
- datasets==2.12.0=py310h06a4308_0
- click==8.1.7=py310h06a4308_0
- gmp==6.2.1=h295c915_3
- cudnn==7.6.5=cuda10.1_0
- huggingface_hub==0.15.1=py310h06a4308_0
- multiprocess==0.70.14=py310h06a4308_0
- scikit-learn==1.0.1=py310h00e6091_0
- sqlite==3.41.2=h5eee18b_0
- cuda-cudart==11.7.99=0
- icu==58.2=he6710b0_3
- packaging==23.0=py310h06a4308_0
- dill==0.3.6=py310h06a4308_0
- lame==3.100=h7b6447c_0
- fsspec==2023.9.2=py310h06a4308_0
- libbrotlidec==1.0.9=h5eee18b_7
- openpyxl==3.0.10=py310h5eee18b_0
- libssh2==1.10.0=hdbd6064_2
- torchaudio==2.0.0=py310_cu117
- pygments==2.15.1=py310h06a4308_1
- pip==23.2.1=py310h06a4308_0
- numpy==1.25.0=py310h5f9d8c6_0
- glog==0.5.0=h2531618_0
- torchvision==0.15.0=py310_cu117
- jupyter_client==8.1.0=py310h06a4308_0
- libcurand==10.3.3.53=0
- libbrotlienc==1.0.9=h5eee18b_7
- libcufft==10.7.2.124=h4fbf590_0
- libedit==3.1.20221030=h5eee18b_0
- c-ares==1.19.0=h5eee18b_0
- numexpr==2.8.4=py310h85018f9_1
- pytz==2023.3.post1=py310h06a4308_0
- pytorch==2.0.0=py3.10_cuda11.7_cudnn8.5.0_0
- ca-certificates==2023.08.22=h06a4308_0
- types-pytz==2022.4.0.0=py310h06a4308_1
- openh264==2.1.1=h4ff587b_0
- regex==2023.10.3=py310h5eee18b_0
- zeromq==4.3.4=h2531618_0
- gflags==2.2.2=he6710b0_0
- mpfr==4.0.2=hb69a4c5_1
- _openmp_mutex==5.1=1_gnu
- libnpp==11.7.4.75=0
- pyarrow==11.0.0=py310h468efa6_1
- utf8proc==2.6.1=h27cfd23_0
- boost-cpp==1.73.0=h7f8727e_12
- cudatoolkit==10.1.243=h6bb024c_0
- scipy==1.10.1=py310h5f9d8c6_1
- libnvjpeg==11.8.0.2=0
- libdeflate==1.17=h5eee18b_0
- libuuid==1.41.5=h5eee18b_0
- pysocks==1.7.1=py310h06a4308_0
- python-xxhash==2.0.2=py310h5eee18b_1
- torchtriton==2.0.0=py310
- zstd==1.5.5=hc292b87_0
- cuda-nvtx==11.7.91=0
- cffi==1.15.1=py310h5eee18b_3
- prompt-toolkit==3.0.36=py310h06a4308_0
- async-timeout==4.0.2=py310h06a4308_0
- pyyaml==6.0=py310h5eee18b_1
- platformdirs==2.5.2=py310h06a4308_0
- aiohttp==3.8.5=py310h5eee18b_0
- openssl==3.0.12=h7f8727e_0
- python==3.10.12=h955ad1f_0
- ipython==8.12.0=py310h06a4308_0
- matplotlib-inline==0.1.6=py310h06a4308_0
- setuptools==68.0.0=py310h06a4308_0
- libcufile==1.7.0.149=0
- tk==8.6.12=h1ccaba5_0
</code></pre>
<p>yaml file llm_110623.yml:</p>
<pre><code>name: llm_110623
channels:
- xformers
- pytorch
- conda-forge/label/cf202003
- nvidia
- anaconda
- defaults
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- abseil-cpp=20211102.0=hd4dd3e8_0
- aiohttp=3.8.5=py310h5eee18b_0
- aiosignal=1.2.0=pyhd3eb1b0_0
- appdirs=1.4.4=pyhd3eb1b0_0
- arrow-cpp=11.0.0=h374c478_1
- asttokens=2.0.5=pyhd3eb1b0_0
- async-timeout=4.0.2=py310h06a4308_0
- attrs=23.1.0=py310h06a4308_0
- aws-c-common=0.6.8=h5eee18b_1
- aws-c-event-stream=0.1.6=h6a678d5_6
- aws-checksums=0.1.11=h5eee18b_2
- aws-sdk-cpp=1.8.185=h721c034_1
- backcall=0.2.0=pyhd3eb1b0_0
- blas=1.0=mkl
- boost-cpp=1.73.0=h7f8727e_12
- bottleneck=1.3.5=py310ha9d4c09_0
- brotlipy=0.7.0=py310h7f8727e_1002
- bzip2=1.0.8=h7b6447c_0
- c-ares=1.19.0=h5eee18b_0
- ca-certificates=2023.08.22=h06a4308_0
- certifi=2023.7.22=py310h06a4308_0
- cffi=1.15.1=py310h5eee18b_3
- chardet=4.0.0=py310h06a4308_1003
- charset-normalizer=2.0.4=pyhd3eb1b0_0
- click=8.1.7=py310h06a4308_0
- colorama=0.4.6=py310h06a4308_0
- comm=0.1.2=py310h06a4308_0
- cryptography=41.0.2=py310h22a60cf_0
- cuda-cudart=11.7.99=0
- cuda-cupti=11.7.101=0
- cuda-libraries=11.7.1=0
- cuda-nvrtc=11.7.99=0
- cuda-nvtx=11.7.91=0
- cuda-runtime=11.7.1=0
- cudatoolkit=10.1.243=h6bb024c_0
- cudnn=7.6.5=cuda10.1_0
- datasets=2.12.0=py310h06a4308_0
- debugpy=1.5.1=py310h295c915_0
- decorator=5.1.1=pyhd3eb1b0_0
- dill=0.3.6=py310h06a4308_0
- einops=0.2.0=py_0
- et_xmlfile=1.1.0=py310h06a4308_0
- executing=0.8.3=pyhd3eb1b0_0
- ffmpeg=4.2.2=h20bf706_0
- filelock=3.9.0=py310h06a4308_0
- freetype=2.12.1=h4a9f257_0
- frozenlist=1.3.3=py310h5eee18b_0
- fsspec=2023.9.2=py310h06a4308_0
- gflags=2.2.2=he6710b0_0
- giflib=5.2.1=h5eee18b_3
- glog=0.5.0=h2531618_0
- gmp=6.2.1=h295c915_3
- gmpy2=2.1.2=py310heeb90bb_0
- gnutls=3.6.15=he1e5248_0
- grpc-cpp=1.48.2=he1ff14a_1
- huggingface_hub=0.15.1=py310h06a4308_0
- icu=58.2=he6710b0_3
- idna=3.4=py310h06a4308_0
- intel-openmp=2023.1.0=hdb19cb5_46305
- ipykernel=6.19.2=py310h2f386ee_0
- ipython=8.12.0=py310h06a4308_0
- jedi=0.18.1=py310h06a4308_1
- jinja2=3.1.2=py310h06a4308_0
- joblib=1.2.0=py310h06a4308_0
- jpeg=9e=h5eee18b_1
- jupyter_client=8.1.0=py310h06a4308_0
- jupyter_core=5.3.0=py310h06a4308_0
- krb5=1.20.1=h143b758_1
- lame=3.100=h7b6447c_0
- lcms2=2.12=h3be6417_0
- ld_impl_linux-64=2.38=h1181459_1
- lerc=3.0=h295c915_0
- libboost=1.73.0=h28710b8_12
- libbrotlicommon=1.0.9=h5eee18b_7
- libbrotlidec=1.0.9=h5eee18b_7
- libbrotlienc=1.0.9=h5eee18b_7
- libcublas=11.10.3.66=0
- libcufft=10.7.2.124=h4fbf590_0
- libcufile=1.7.0.149=0
- libcurand=10.3.3.53=0
- libcurl=8.1.1=h251f7ec_1
- libcusolver=11.4.0.1=0
- libcusparse=11.7.4.91=0
- libdeflate=1.17=h5eee18b_0
- libedit=3.1.20221030=h5eee18b_0
- libev=4.33=h7f8727e_1
- libevent=2.1.12=hdbd6064_1
- libffi=3.4.4=h6a678d5_0
- libgcc-ng=11.2.0=h1234567_1
- libgfortran-ng=11.2.0=h00389a5_1
- libgfortran5=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libidn2=2.3.4=h5eee18b_0
- libnghttp2=1.52.0=h2d74bed_1
- libnpp=11.7.4.75=0
- libnvjpeg=11.8.0.2=0
- libopus=1.3.1=h7b6447c_0
- libpng=1.6.39=h5eee18b_0
- libprotobuf=3.20.3=he621ea3_0
- libsodium=1.0.18=h7b6447c_0
- libssh2=1.10.0=hdbd6064_2
- libstdcxx-ng=11.2.0=h1234567_1
- libtasn1=4.19.0=h5eee18b_0
- libthrift=0.15.0=h1795dd8_2
- libtiff=4.5.0=h6a678d5_2
- libunistring=0.9.10=h27cfd23_0
- libuuid=1.41.5=h5eee18b_0
- libvpx=1.7.0=h439df22_0
- libwebp=1.2.4=h11a3e52_1
- libwebp-base=1.2.4=h5eee18b_1
- lz4-c=1.9.4=h6a678d5_0
- markupsafe=2.1.1=py310h7f8727e_0
- matplotlib-inline=0.1.6=py310h06a4308_0
- mkl=2023.1.0=h6d00ec8_46342
- mkl-service=2.4.0=py310h5eee18b_1
- mkl_fft=1.3.6=py310h1128e8f_1
- mkl_random=1.2.2=py310h1128e8f_1
- mpc=1.1.0=h10f8cd9_1
- mpfr=4.0.2=hb69a4c5_1
- mpmath=1.3.0=py310h06a4308_0
- multidict=6.0.2=py310h5eee18b_0
- multiprocess=0.70.14=py310h06a4308_0
- ncurses=6.4=h6a678d5_0
- nettle=3.7.3=hbbd107a_1
- networkx=2.8.4=py310h06a4308_1
- numexpr=2.8.4=py310h85018f9_1
- numpy=1.25.0=py310h5f9d8c6_0
- numpy-base=1.25.0=py310hb5e798b_0
- openh264=2.1.1=h4ff587b_0
- openpyxl=3.0.10=py310h5eee18b_0
- openssl=3.0.12=h7f8727e_0
- orc=1.7.4=hb3bc3d3_1
- packaging=23.0=py310h06a4308_0
- pandas=2.1.1=py310h1128e8f_0
- pandas-stubs=1.5.3.230203=py310h06a4308_0
- parso=0.8.3=pyhd3eb1b0_0
- pexpect=4.8.0=pyhd3eb1b0_3
- pickleshare=0.7.5=pyhd3eb1b0_1003
- pillow=9.4.0=py310h6a678d5_0
- pip=23.2.1=py310h06a4308_0
- platformdirs=2.5.2=py310h06a4308_0
- pooch=1.4.0=pyhd3eb1b0_0
- prompt-toolkit=3.0.36=py310h06a4308_0
- psutil=5.9.0=py310h5eee18b_0
- ptyprocess=0.7.0=pyhd3eb1b0_2
- pure_eval=0.2.2=pyhd3eb1b0_0
- pyarrow=11.0.0=py310h468efa6_1
- pycparser=2.21=pyhd3eb1b0_0
- pygments=2.15.1=py310h06a4308_1
- pyopenssl=23.2.0=py310h06a4308_0
- pysocks=1.7.1=py310h06a4308_0
- python=3.10.12=h955ad1f_0
- python-dateutil=2.8.2=pyhd3eb1b0_0
- python-tzdata=2023.3=pyhd3eb1b0_0
- python-xxhash=2.0.2=py310h5eee18b_1
- pytorch=2.0.0=py3.10_cuda11.7_cudnn8.5.0_0
- pytorch-cuda=11.7=h778d358_5
- pytorch-mutex=1.0=cuda
- pytz=2023.3.post1=py310h06a4308_0
- pyyaml=6.0=py310h5eee18b_1
- pyzmq=25.1.0=py310h6a678d5_0
- re2=2022.04.01=h295c915_0
- readline=8.2=h5eee18b_0
- regex=2023.10.3=py310h5eee18b_0
- requests=2.31.0=py310h06a4308_0
- responses=0.13.3=pyhd3eb1b0_0
- sacremoses=0.0.43=pyhd3eb1b0_0
- scikit-learn=1.0.1=py310h00e6091_0
- scipy=1.10.1=py310h5f9d8c6_1
- setuptools=68.0.0=py310h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- snappy=1.1.9=h295c915_0
- sqlite=3.41.2=h5eee18b_0
- stack_data=0.2.0=pyhd3eb1b0_0
- sympy=1.11.1=py310h06a4308_0
- tbb=2021.8.0=hdb19cb5_0
- threadpoolctl=2.2.0=pyh0d69192_0
- tk=8.6.12=h1ccaba5_0
- tokenizers=0.13.3=py310h22610ee_0
- torchaudio=2.0.0=py310_cu117
- torchtriton=2.0.0=py310
- torchvision=0.15.0=py310_cu117
- tornado=6.2=py310h5eee18b_0
- tqdm=4.65.0=py310h2f386ee_0
- traitlets=5.7.1=py310h06a4308_0
- transformers=4.29.2=py310h06a4308_0
- types-pytz=2022.4.0.0=py310h06a4308_1
- tzdata=2023c=h04d1e81_0
- urllib3=1.26.16=py310h06a4308_0
- utf8proc=2.6.1=h27cfd23_0
- wcwidth=0.2.5=pyhd3eb1b0_0
- wheel=0.38.4=py310h06a4308_0
- x264=1!157.20191217=h7b6447c_0
- xformers=0.0.19=py310_cu11.8.0_pyt2.0.0
- xxhash=0.8.0=h7f8727e_3
- xz=5.4.2=h5eee18b_0
- yaml=0.2.5=h7b6447c_0
- yarl=1.8.1=py310h5eee18b_0
- zeromq=4.3.4=h2531618_0
- zlib=1.2.13=h5eee18b_0
- zstd=1.5.5=hc292b87_0
- pip:
- absl-py==2.0.0
- accelerate==0.24.1
- aiostream==0.5.2
- annotated-types==0.6.0
- anyio==3.7.1
- asgiref==3.7.2
- backoff==2.2.1
- bcrypt==4.1.2
- build==1.0.3
- cachetools==5.3.2
- chroma-hnswlib==0.7.3
- chromadb==0.4.22
- coloredlogs==15.0.1
- dataclasses-json==0.5.14
- deprecated==1.2.14
- distro==1.8.0
- evaluate==0.4.0
- exceptiongroup==1.1.3
- fastapi==0.109.2
- flatbuffers==23.5.26
- google-auth==2.27.0
- googleapis-common-protos==1.62.0
- greenlet==3.0.1
- grpcio==1.60.1
- h11==0.14.0
- httpcore==1.0.1
- httptools==0.6.1
- httpx==0.25.1
- humanfriendly==10.0
- importlib-metadata==6.11.0
- importlib-resources==6.1.1
- jsonpatch==1.33
- jsonpointer==2.4
- kubernetes==29.0.0
- langchain==0.0.150
- langsmith==0.0.60
- llama-index==0.8.64.post1
- marshmallow==3.20.1
- mmh3==4.1.0
- monotonic==1.6
- mypy-extensions==1.0.0
- nest-asyncio==1.5.8
- nltk==3.8.1
- oauthlib==3.2.2
- onnxruntime==1.17.0
- openai==1.2.1
- openapi-schema-pydantic==1.2.4
- opentelemetry-api==1.22.0
- opentelemetry-exporter-otlp-proto-common==1.22.0
- opentelemetry-exporter-otlp-proto-grpc==1.22.0
- opentelemetry-instrumentation==0.43b0
- opentelemetry-instrumentation-asgi==0.43b0
- opentelemetry-instrumentation-fastapi==0.43b0
- opentelemetry-proto==1.22.0
- opentelemetry-sdk==1.22.0
- opentelemetry-semantic-conventions==0.43b0
- opentelemetry-util-http==0.43b0
- overrides==7.7.0
- peft==0.3.0
- posthog==3.4.0
- protobuf==4.25.2
- pulsar-client==3.4.0
- pyasn1==0.5.1
- pyasn1-modules==0.3.0
- pydantic==1.10.13
- pydantic-core==2.10.1
- pypika==0.48.9
- pyproject-hooks==1.0.0
- python-dotenv==1.0.1
- requests-oauthlib==1.3.1
- rouge-score==0.1.2
- rsa==4.9
- sniffio==1.3.0
- sqlalchemy==2.0.23
- starlette==0.36.3
- tenacity==8.2.3
- tiktoken==0.5.1
- tomli==2.0.1
- trl==0.4.2.dev0
- typer==0.9.0
- typing-extensions==4.9.0
- typing-inspect==0.9.0
- uvicorn==0.27.0.post1
- uvloop==0.19.0
- watchfiles==0.21.0
- websocket-client==1.7.0
- websockets==12.0
- wrapt==1.15.0
- zipp==3.17.0
prefix: /home/username/anaconda3/envs/llm_110623
</code></pre>
|
<python><anaconda>
|
2024-02-23 23:08:04
| 1
| 573
|
modLmakur
|
78,050,591
| 1,654,472
|
Inconsistent processing of the form-data POST with multiple files
|
<p>I have a script in python to test posting multiple files to a certain end point. Here is the script:</p>
<pre><code>import requests
url = "https://endpoint.com/api/upload"
payload = {}
files=[
('images',('image01.png',open('H:/image01.png','rb'),'image/png')),
('images',('image02.png',open('H:/image02.png','rb'),'image/png'))
]
headers = {}
response = requests.post(url, files=files)
print(response.text)
</code></pre>
<p>It's generalized of course. But, when I test this script the endpoint receives only 1 file! instead of 2.</p>
<p>If I test this exact script on <code>https://webhook.site/</code> for example - still 1 file instead of two.</p>
<p>Multiple sources keep suggesting this exact layout/structure for the <code>files</code> array. However, it's almost nowhere mentioned that the actual approach should be a little different, providing a different file id/name in each tuple:</p>
<p>SOLUTION:</p>
<pre><code>files=[
('images01',('image01.png',open('H:/image01.png','rb'),'image/png')),
('images02',('image02.png',open('H:/image02.png','rb'),'image/png'))
]
</code></pre>
<p>Only in this case, the endpoint gets 2 files.</p>
<p>My question is: is there an official, correct reference in the requests docs that documents properly how to POST multiple files?</p>
|
<python><rest><python-requests>
|
2024-02-23 22:58:46
| 0
| 731
|
GeekSince1982
|
78,050,439
| 12,415,855
|
Selenium undetected chromedriver with different chrome-versions?
|
<p>I have the following code which works fine on a computer where chrome 122 is installed currently -</p>
<pre><code>import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get('https://ballzy.eu/en/men/sport/shoes')
</code></pre>
<p>But when I run this code on a computer where a different chrome-version is installed like 120, I get the following error -</p>
<pre><code>(selenium) C:\DEV\Fiverr\ORDER\stefamn_jan669_jankore_janxx2\Ballzy>python test3.py
Traceback (most recent call last):
File "C:\DEV\Fiverr\ORDER\stefamn_jan669_jankore_janxx2\Ballzy\test3.py", line 2, in <module>
driver = uc.Chrome(version_main=122)
File "C:\DEV\.venv\selenium\lib\site-packages\undetected_chromedriver\__init__.py", line 466, in __init__
super(Chrome, self).__init__(
File "C:\DEV\.venv\selenium\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__
super().__init__(
File "C:\DEV\.venv\selenium\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 61, in __init__
super().__init__(command_executor=executor, options=options)
File "C:\DEV\.venv\selenium\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 208, in __init__
self.start_session(capabilities)
File "C:\DEV\.venv\selenium\lib\site-packages\undetected_chromedriver\__init__.py", line 724, in start_session
super(selenium.webdriver.chrome.webdriver.WebDriver, self).start_session(
File "C:\DEV\.venv\selenium\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 292, in start_session
response = self.execute(Command.NEW_SESSION, caps)["value"]
File "C:\DEV\.venv\selenium\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 347, in execute
self.error_handler.check_response(response)
File "C:\DEV\.venv\selenium\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:50596
from session not created: This version of ChromeDriver only supports Chrome version 122
Current browser version is 120.0.6099.200
</code></pre>
<p>Is it somehow possible that the correct <code>chromedriver</code> is automatically downloaded?</p>
<p>(when I use the normal <code>selenium</code> driver - I just use the following driver-definition, and it works fine with that on several computers)</p>
<pre><code>srv=Service()
driver = webdriver.Chrome (service=srv, options=options)
</code></pre>
<p>How can i do this also with the undetected chromedriver so it is working on differnt chrome version installations on different computers?</p>
|
<python><python-3.x><selenium-webdriver><selenium-chromedriver><undetected-chromedriver>
|
2024-02-23 22:16:19
| 3
| 1,515
|
Rapid1898
|
78,050,189
| 13,086,128
|
`df.query()` in polars?
|
<p>What is the equivalent of <strong><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.query.html#pandas-dataframe-query" rel="noreferrer">pandas.DataFrame.query</a></strong> in polars?</p>
<pre><code>import pandas as pd
data= {
'A':["Polars","Python","Pandas"],
'B' :[23000,24000,26000],
'C':['30days', '40days',np.nan],
}
df = pd.DataFrame(data)
A B C
0 Polars 23000 30days
1 Python 24000 40days
2 Pandas 26000 NaN
</code></pre>
<p>Now, defining a variable <code>item</code></p>
<pre><code>item=24000
df.query("B>= @item")
A B C
1 Python 24000 40days
2 Pandas 26000 NaN
</code></pre>
<p>Now, using polars:</p>
<pre><code>import polars as pl
df = pl.DataFrame(data)
item=24000
df.query("B>= @item")
</code></pre>
<p>I get:</p>
<pre><code>AttributeError: 'DataFrame' object has no attribute 'query'
</code></pre>
<p>My wild guess is <code>df.filter()</code> but syntax does not look same and <code>filter</code> looks equivalent to <code>df.loc[]</code> as well ?</p>
|
<python><python-3.x><dataframe><python-polars>
|
2024-02-23 21:04:07
| 1
| 30,560
|
Talha Tayyab
|
78,050,174
| 2,030,762
|
Bin packing in OR-Tools with only one bin
|
<p>I've been trying to adapt the bin-packing problem often seen in OR-Tools to optimize space used instead of optimizing number of bins, but I don't seem to be able to sort out how to do it.</p>
<p>So what I want to do is something like:</p>
<p>Given a set of 2D boxes of various sizes, and an arbitrarily long 2D container of fixed width, how tightly can we pack all the boxes?</p>
<p>At first glance, it seems like a decent solution to this problem would be to define variables like:</p>
<pre><code>x1 = [model.NewIntVar(0,L-l[i],f'x1{i}') for i in range(n)]
x2 = [model.NewIntVar(l[i],L,f'x2{i}') for i in range(n)]
</code></pre>
<p>Where L is the maximum container length and l[i] is the length of the ith box, for n boxes.</p>
<p>Then do something similar with the heights, with H as the container height and h[i] as the height of the box.</p>
<p>Then I can get the area of each box with:</p>
<pre><code>a = [model.NewConstant(h[i]*w[i]) for i in range(n)]
</code></pre>
<p>Define some intervals for the lengths and widths:</p>
<pre><code>xinv = [model.NewIntervalVar(x1[i],w[i],x2[i],f'xinv{i}') for i in range(n)]
yinv = [model.NewIntervalVar(y1[i],h[i],y2[i],f'yinv{i}') for i in range(n)]
</code></pre>
<p>And a restriction that the boxes can't overlap:</p>
<pre><code>model.AddNoOverlap2D(xinv,yinv)
</code></pre>
<p>At first glance, it looks like I should be able to use a strategy like:</p>
<ul>
<li>Get the x-coordinate of the box that's furthest from the back of the container</li>
<li>Use that to define a square containing all boxes placed so far (the other sides of the square are the top, bottom, and back of the container)</li>
<li>Add up the area of all the boxes</li>
<li>Subtract that from the square</li>
<li>That result is the area of the empty space not filled by boxes</li>
<li>Set an objective to minimize that empty space</li>
</ul>
<p>The square can be defined by using <code>model.AddMaxEquality</code> to set a variable to the maximum distance that a box reaches. However, I'm stuck on the "add up the areas of all the placed boxes" part. There doesn't seem to be a way to look back and get the coordinates of previously placed boxes, even though it's possible to determine where those boxes were placed to enforce the <code>AddNoOverlap2D</code> constraint.</p>
<p>How do I calculate a total of the area of boxes currently in the container?</p>
|
<python><or-tools><constraint-programming><cp-sat>
|
2024-02-23 21:01:46
| 1
| 776
|
emote_control
|
78,050,169
| 2,035,671
|
Supabase with JWT auth from Python client doesn't work with RLS
|
<p>I have a problem with Supabase that is related to RLS.</p>
<p>In my Python backend, I set up the supabase client and get the user based on the JWT <code>jwt</code> passed by the frontend:</p>
<pre class="lang-py prettyprint-override"><code>user = supabase.auth.get_user(jwt)
user_id = user.dict().get("user").get("id")
response = (
supabase
.table("users")
.update({"credits": 10})
.eq("user_id", user_id)
.execute()
)
</code></pre>
<p>Without RLS, this works fine, updating the row successfully.</p>
<p>However, with the following RLS rules, nothing is modified and 0 rows are returned:</p>
<pre class="lang-sql prettyprint-override"><code>create policy "Everybody can select users."
on users for select
using ( true );
create policy "Users can update own user."
on users for update
using ( auth.uid() = user_id );
</code></pre>
<p>What am I doing wrong? Obviously I have to use <em>some</em> RLS rule… But I guess the authentication check <code>( auth.uid() = user_id )</code> doesn't match up when using the JWT.</p>
<p><strong>I think I need to pass the JWT to the <code>supabase</code> client as well, so it's included in all requests, but I don't know how!</strong></p>
<p>Help!?</p>
|
<python><next.js><jwt><supabase><supabase-py>
|
2024-02-23 20:59:57
| 2
| 490
|
shredEngineer
|
78,050,162
| 5,923,866
|
Pyspark Group By Date Range
|
<p>I have a sample pyspark dataframe that can be created like this</p>
<pre><code>sample_df = spark.createDataFrame([
('2020-01-01', '2021-01-01', 1),
('2020-02-01', '2021-02-01', 1),
('2021-01-15', '2022-01-15', 2),
('2022-01-15', '2023-01-15', 2),
('2022-02-01', '2023-02-01', 3),
('2022-03-01', '2023-03-01', 3),
('2023-03-01', '2024-03-01', 4),
], ['item_date', 'max_window', 'expected_grouping_index'])
</code></pre>
<p>After sorting by <code>item_date</code>, I want to assume the first item starts a grouping. Any following item that is less than or equal to the first items <code>max_window</code> (which will always be the same number of days added to the <code>item_date</code> for the entire df, about 365 days in this example) will be given the same <code>grouping_index</code>.</p>
<p>If an item does not fall inside the grouping, it will start a new grouping and be given another arbitrary <code>grouping_index</code>. Then all following items will be assessed based on that items <code>max_window</code>. And so on.</p>
<p>The <code>grouping_index</code> is just a means goal, I eventually want to only keep the first row in each group.</p>
<p>How can I achieve this without a UDF or converting to a pandas df?</p>
|
<python><pyspark><group-by>
|
2024-02-23 20:58:58
| 1
| 395
|
spatel4140
|
78,050,000
| 13,132,728
|
How to assign each item in a list an equal amount of items from another list in python
|
<p>Let's say I have a list of people</p>
<pre><code>['foo','bar','baz']
</code></pre>
<p>and a list of items</p>
<pre><code>['hat','bag','ball','bat','shoe','stick','pie','phone']
</code></pre>
<p>and I want to <em>randomly</em> assign each person an equal amount of items, like so</p>
<pre><code>{
'foo':['hat','bat','stick'],
'bar':['bag','shoe','phone'],
'baz':['ball','pie']
}
</code></pre>
<p>I think <code>itertools</code> is the job for this, but I couldn't seem to find the right function as most itertools functions seem to just work on one object.</p>
<p>EDIT: Order does <strong>not</strong> matter. I just want to randomly assign each person an equal amount of items.</p>
|
<python><python-itertools>
|
2024-02-23 20:16:08
| 5
| 1,645
|
bismo
|
78,049,835
| 2,274,981
|
SQLite3 - Location of db
|
<p>I have implemented SQLite3 into my discord bot, everything seems to work and I can commit rows to my db, do a select and retrieve them, however in my local directory for the project I can't see the DB itself.</p>
<p>I've tried looking for commands to log the location to my log file but nothing seems to work either.</p>
<p>Am I missing something?</p>
<p>UPDATE:</p>
<p><a href="https://i.sstatic.net/PhTDf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PhTDf.png" alt="enter image description here" /></a></p>
<p><a href="https://i.sstatic.net/JTMI0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JTMI0.png" alt="enter image description here" /></a></p>
<p>This is my function at present:</p>
<pre><code>def add_replay_to_db(filename: str, gamejson: str, playerjson: str, resultjson: str, replaysource: str, messageauthor: str, md5: str):
try:
db_path = '/database/yesman.db'
# Ensure the directory exists
if not os.path.exists(os.path.dirname(db_path)):
fullpath = os.path.dirname(db_path)
os.makedirs(fullpath)
logger.info(f'Database created: {fullpath}')
logger.info(f'Adding {filename} to the SQL database')
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS replay_raw_data (
id INTEGER PRIMARY KEY,
filename TEXT,
game_json TEXT,
player_json TEXT,
result_json TEXT,
replay_source TEXT,
user TEXT,
md5 TEXT
)''')
# INSERT INTO
cursor.execute('INSERT INTO replay_raw_data (filename, game_json, player_json, result_json, replay_source, user, md5) VALUES (?, ?, ?, ?, ?, ?, ?)',
(str(filename), str(gamejson), str(playerjson), str(resultjson), str(replaysource), str(messageauthor), str(md5)))
connection.commit()
# Fetch and print data
cursor.execute('SELECT * FROM replay_raw_data')
rows = cursor.fetchall()
for row in rows:
print(row)
except sqlite3.Error as er:
logger.error(f'{er}')
finally:
if connection:
connection.close()
</code></pre>
|
<python><sqlite><sqlite3-python>
|
2024-02-23 19:39:15
| 1
| 1,149
|
Lynchie
|
78,049,782
| 7,938,796
|
How to make a lighter SciPy package for AWS Lambda
|
<p>AWS Lambda restricts packages to be less than 50MB zipped. I need to use <code>scipy</code> for my workflow which is a large package, so I'm trying to trim it down so I can use it within lambda without having to use container images or anything like that since I'm not as familiar with it. And lambda is the ideal solution for our business' problem so I can't switch to something else.</p>
<p>Here's what I've done so far:</p>
<h2>1 - Make the zip file</h2>
<p>With a <code>requirements.txt</code> file that just has <code>scipy</code>, I ran the following code in my <code>aws-layer</code> folder:</p>
<p><code>pip3 install -r requirements.txt --target aws-layer/python/lib/python3.11/site-packages</code></p>
<p>This downloads both the <code>scipy</code> and <code>numpy</code> packages. From here I went into the <code>scipy</code> folder and deleted folders other than <code>scipy.sparse</code> and <code>scipy.optimize</code> since those are the only two I need. Next I ran <code>zip -r9 lambda-layer.zip .</code> to make a zip folder - the total size of this was 37MB so within the limits for AWS.</p>
<h2>2 - Create the lambda function</h2>
<p>I just created a dummy AWS Lambda function with runtime of python3.11 to match my zipped packages. I added lines to import the applicable packages so that I could confirm everything is working appropriately once it's setup. When I try running this before adding my layer, I get an error <code>No module named 'scipy'</code> as expected.</p>
<pre><code>import json
import scipy.sparse
from scipy.optimize import milp, LinearConstraint, Bounds
import numpy
def lambda_handler(event, context):
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
</code></pre>
<h2>3 - Import the zip file as a layer and add to the Lambda function</h2>
<p>In AWS Lambda I created a new layer where I uploaded the zip file, and made sure to make the runtime python3.11 to match the function.</p>
<h2>4 - Test the code; get error</h2>
<p>And here is where I'm getting errors. I think the layer-upload process itself worked because I no longer get a message saying <code>scipy</code> doesn't exist. Instead, it seems like there's an issue with <code>numpy</code> which is a dependency of <code>scipy</code>.</p>
<pre><code>{
"errorMessage": "Unable to import module 'lambda_function': \n\nIMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!\n\nImporting the numpy C-extensions failed. This error can happen for\nmany reasons, often due to issues with your setup or how NumPy was\ninstalled.\n\nWe have compiled some common reasons and troubleshooting tips at:\n\n https://numpy.org/devdocs/user/troubleshooting-importerror.html\n\nPlease note and check the following:\n\n * The Python version is: Python3.11 from \"/var/lang/bin/python3.11\"\n * The NumPy version is: \"1.21.6\"\n\nand make sure that they are the versions you expect.\nPlease carefully study the documentation linked above for further help.\n\nOriginal error was: No module named 'numpy.core._multiarray_umath'\n",
"errorType": "Runtime.ImportModuleError",
"requestId": "bde94bb7-ba45-4019-bf0f-81ef08c7124b",
"stackTrace": []
}
</code></pre>
<p>I've followed the link that they suggested and I can't figure out what's going on or how to fix it. It seems like maybe there's an issue with <code>Original error was: No module named 'numpy.core._multiarray_umath'</code>, but I didn't delete anything from <code>numpy</code> before I made a zip folder, only <code>scipy</code>. So I'm not sure why any <code>numpy</code> module would be missing.</p>
<hr />
<h2>5 - Potential solution: use built-in <code>pandas</code> layer which has <code>numpy</code></h2>
<p>Lambda has a built-in layer <code>AWSSDKPandas-Python311</code>. When I make a new function and add this as a layer, I'm able to run <code>import numpy</code> just fine. However, I'm unable to add in the trimmed <code>scipy</code> layer (even after removing <code>numpy</code>) because the built-in pandas layer already takes up too much space.</p>
<hr />
<p>So now I'm left brainstorming potential solutions:</p>
<ol>
<li>The easiest would be to just figure out the <code>numpy</code> error that's happening in my 4th step when I test the custom package. If anyone could help me solve this I'd greatly appreciate it.</li>
<li>Slim the custom <code>scipy</code>-only package even further so that I can use both the <code>AWSSDKPandas-Python311</code> layer and my custom <code>scipy</code> layer, but I'm not sure if this is feasible. I'd have to do more research on what exactly I can remove from my <code>scipy</code> layer.</li>
<li>Since any single lambda function can only use 262144000 bytes, maybe I can make a <code>scipy</code>-only package in one lambda function, and the built-in <code>pandas</code> package in another lambda function, and then somehow combine them in a third function? Can someone tell me if this is possible?</li>
<li>Suck it up and learn how to use container images. I'm not sure where to start there.</li>
</ol>
<p>Thanks in advance</p>
|
<python><amazon-web-services><aws-lambda>
|
2024-02-23 19:26:40
| 1
| 767
|
CoolGuyHasChillDay
|
78,049,684
| 9,915,864
|
Python import problem: Why is my python code unexpectedly trying to import a module function?
|
<p>When I run my top-level file <code>downloader.py</code>, I'm getting an unexpected import error, unexpected since I thought the function is finished by the time <code>downloader.py</code> calls it. I'm not sure which file this is supposed to be resolved in. I'm running in VS Code and using the VS Code generated venv</p>
<pre><code>from downloader_mod.shelf import ShelfData
File "c:\archive_shelf_flaskbased\src\downloader_mod\shelf.py", line 6, in <module>
from directory_handler import DirectoryNameHandler
ModuleNotFoundError: No module named 'directory_handler'
</code></pre>
<p>When I run <code>shelf.py</code> directly, where the class is called, it runs fine.
When I ran <code>downloader.py</code> prior to adding the <code>DirectoryNameHandler()</code> call in the submodule it ran fine.</p>
<p><strong>File structure:</strong></p>
<pre><code>archive_shelf_flaskbased/
.vscode/
src/
[app.py] * to do
[views.py] * to do
downloader.py
logging_config.py
__init__.py
downloader_mod/
directory_handler.py
download.py
page.py
shelf.py
__init__.py
</code></pre>
<p><strong>What I tried:</strong></p>
<ul>
<li>I added <code>from downloader_mod.directory_handler import DirectoryNameHandler</code> to <code>downloader.py</code> it didn't make a difference.</li>
<li>Added <code>__init__.py</code> to the <code>downloader_mod</code> folder. That also didn't make a difference.</li>
<li>Ran from command line in venv with no effect</li>
</ul>
<pre><code>(venv) PS C:\archive_shelf_flaskbased\src> & "c:/Goodreads Bookshelf Tool/archive_shelf_flaskbased/venv/Scripts/python.exe" "c:/Goodreads Bookshelf Tool/archive_shelf_flaskbased/src/downloader.py"
Traceback (most recent call last):
File "c:\archive_shelf_flaskbased\src\downloader.py", line 3, in <module>
from downloader_mod.shelf import ShelfData
File "c:\archive_shelf_flaskbased\src\downloader_mod\shelf.py", line 6, in <module>
from directory_handler import DirectoryNameHandler
ModuleNotFoundError: No module named 'directory_handler'
</code></pre>
<p><strong>What I have NOT tried:</strong></p>
<ul>
<li>I have not tried modifying PYTHONPATH yet because I'm not sure that's the problem or the right setting to change. If it is, what needs to be added and where. Does it go in <code>.vscode/settings.json</code>, <code>.vscode/launch.json</code>, <code>.env</code>, or a command line change?</li>
</ul>
<p><strong>File Code:</strong></p>
<p>src/downloader.py</p>
<pre class="lang-py prettyprint-override"><code>from downloader_mod.shelf import ShelfData
from downloader_mod.directory_handler import DirectoryNameHandler
logger = logging.getLogger(__name__)
setup_logging()
sh = ShelfData({'shelf_name': "Generic", 'creation_date': "02/25/2023"})
sh.setup_download_dir()
print(f"{sh.simple_dir = }")
</code></pre>
<p>src/downloader_mod/shelf.py</p>
<pre class="lang-py prettyprint-override"><code>from directory_handler import DirectoryNameHandler
class ShelfData:
def __init__(self, data_dict=None):
self.initialize_shelf_dict()
if data_dict is not None:
self.add_data_to_shelf_dict(data_dict)
# self.shelf_name and self.creation_date made above
dn = DirectoryNameHandler(self.shelf_name, self.creation_date)
self.simple_dir = dn.simple_dir
</code></pre>
<p>downloader_mod/directory_handler.py</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime
class DirectoryNameHandler:
def __init__(self, shelf_name, date_obj) -> None:
year = f'{date_obj.year}'
self.simple_dir = f"{shelf_name}_{date_obj.strftime('%b%d')}"
</code></pre>
|
<python><python-import>
|
2024-02-23 19:07:48
| 1
| 341
|
Meghan M.
|
78,049,538
| 2,824,791
|
Failure to debug Python Functions using VSCode + WSL2 + Ubuntu 22.04
|
<p>Tools</p>
<ul>
<li>VSCode</li>
<li>WSL2</li>
<li>Ubuntu 22.04</li>
<li>Python 3.10.12</li>
</ul>
<p>I am using the Code created when using Workspace/New Project...
Project consistently fails with: <strong>ConnectionRefusedError: [Errno 111]</strong></p>
<h3>Investigative information</h3>
<p>I have tried everything I can find on the internet including #2808;
Python works on this VM;
I have deleted the project and started again and restarted WSl2</p>
<p>If I run: <em>func host start / func start</em> the function works with: p://localhost:7071/api/http_trigger1?name="test"</p>
<p>If I try to make a C# function works as expected.</p>
<p>I modified launch.json to include: "command": "host start --verbose",
Attached is the Output:</p>
<ul>
<li>Executing task: .venv/bin/python -m pip install -r requirements.txt</li>
</ul>
<p>Requirement already satisfied: azure-functions in ./.venv/lib/python3.10/site-packages (from -r requirements.txt (line 5)) (1.18.0)</p>
<ul>
<li><p>Terminal will be reused by tasks, press any key to close it.</p>
</li>
<li><p>Executing task: . .venv/bin/activate && func host start --verbose</p>
</li>
</ul>
<p>Found Python version 3.10.12 (python3).</p>
<pre><code> %%%%%%
%%%%%%
@ %%%%%% @
@@ %%%%%% @@
@@@ %%%%%%%%%%% @@@
@@ %%%%%%%%%% @@
@@ %%%% @@
@@ %%% @@
@@ %% @@
%%
%
Azure Functions Core Tools
Core Tools Version: 4.0.5455 Commit hash: N/A (64-bit)
Function Runtime Version: 4.27.5.21554
[2024-02-23T18:20:57.501Z] Starting metrics publisher for container : wsl. Publishing endpoint is https://:31002/api/metrics
[2024-02-23T18:20:57.557Z] Initializing LinuxContainerActivityPublisher
[2024-02-23T18:20:57.557Z] Starting LinuxContainerActivityPublisher
MS_FUNCTION_LOGS 5,,,,,ScriptApplicationHostOptionsSetup,"","ScmRunFromPackage is empty.",4.27.5.21554,2024-02-23T18:20:57.5600849Z,,"",,,,WSL,,,,
[2024-02-23T18:20:57.607Z] Building host: version spec: , startup suppressed: 'False', configuration suppressed: 'False', startup operation id: '93a298d3-ebf7-4eac-aea6-e67cd4fb582f'
[2024-02-23T18:20:57.612Z] Reading host configuration file '/workspaces/functionApp/host.json'
[2024-02-23T18:20:57.613Z] Host configuration file read:
[2024-02-23T18:20:57.613Z] {
[2024-02-23T18:20:57.613Z] "version": "2.0",
[2024-02-23T18:20:57.614Z] "logging": {
[2024-02-23T18:20:57.614Z] "applicationInsights": {
[2024-02-23T18:20:57.614Z] "samplingSettings": {
[2024-02-23T18:20:57.614Z] "isEnabled": true,
[2024-02-23T18:20:57.614Z] "excludedTypes": "Request"
[2024-02-23T18:20:57.614Z] }
[2024-02-23T18:20:57.614Z] }
[2024-02-23T18:20:57.615Z] },
[2024-02-23T18:20:57.615Z] "extensionBundle": {
[2024-02-23T18:20:57.615Z] "id": "Microsoft.Azure.Functions.ExtensionBundle",
[2024-02-23T18:20:57.615Z] "version": "[4.*, 5.0.0)"
[2024-02-23T18:20:57.615Z] }
[2024-02-23T18:20:57.615Z] }
[2024-02-23T18:20:57.654Z] FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: powershell
[2024-02-23T18:20:57.665Z] FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: node
[2024-02-23T18:20:57.686Z] FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: java
[2024-02-23T18:20:57.687Z] Looking for extension bundle Microsoft.Azure.Functions.ExtensionBundle at /FuncExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle
[2024-02-23T18:20:57.687Z] Looking for extension bundle Microsoft.Azure.Functions.ExtensionBundle at /root/site/wwwroot/.azurefunctions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle
[2024-02-23T18:20:57.687Z] Looking for extension bundle Microsoft.Azure.Functions.ExtensionBundle at /root/data/Functions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle
[2024-02-23T18:20:57.688Z] Found a matching extension bundle at /root/data/Functions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle/4.12.0
[2024-02-23T18:20:57.703Z] Loading functions metadata
[2024-02-23T18:20:57.705Z] Worker indexing is enabled
[2024-02-23T18:20:57.712Z] Fetching metadata for workerRuntime: python
[2024-02-23T18:20:57.712Z] Reading functions metadata (Worker)
[2024-02-23T18:20:58.383Z] Language Worker Process exited. Pid=2686.
[2024-02-23T18:20:58.383Z] python3 exited with code 1 (0x1). ConnectionRefusedError: [Errno 111] Connection refused,ConnectionRefusedError: [Errno 111] Connection refused.
[2024-02-23T18:21:02.566Z] Posting health event {"EventTime":"2024-02-23T18:21:02.5542407Z","EventType":0,"Source":"Microsoft.Azure.WebJobs.Script.WebHost.ContainerManagement.LinuxContainerActivityPublisher","Details":"SpecializationCompleted"}
[2024-02-23T18:21:02.578Z] PublishSpecializationCompleteEvent failed with System.InvalidOperationException: An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.
[2024-02-23T18:21:02.579Z] at System.Net.Http.HttpClient.PrepareRequestMessage(HttpRequestMessage request)
[2024-02-23T18:21:02.579Z] at System.Net.Http.HttpClient.CheckRequestBeforeSend(HttpRequestMessage request)
[2024-02-23T18:21:02.579Z] at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
[2024-02-23T18:21:02.579Z] at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request)
[2024-02-23T18:21:02.579Z] at Microsoft.Azure.WebJobs.Script.WebHost.Management.MeshServiceClient.SendAsync(IEnumerable`1 formData) in /_/src/WebJobs.Script.WebHost/Management/MeshServiceClient.cs:line 154
[2024-02-23T18:21:02.579Z] at Microsoft.Azure.WebJobs.Script.WebHost.Management.MeshServiceClient.NotifyHealthEvent(ContainerHealthEventType healthEventType, Type source, String details) in /_/src/WebJobs.Script.WebHost/Management/MeshServiceClient.cs:line 104
[2024-02-23T18:21:02.579Z] at Microsoft.Azure.WebJobs.Script.WebHost.ContainerManagement.LinuxContainerActivityPublisher.PublishSpecializationCompleteEvent() in /_/src/WebJobs.Script.WebHost/ContainerManagement/LinuxContainerActivityPublisher.cs:line 122
MS_FUNCTION_METRICS ,,,hostjsonfileconfigurationsource.loadhostconfigurationsource.initializehostconfig,0,0,0,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,hostjsonfileconfigurationsource.loadhostconfigurationsource.loadhostconfig,0,0,0,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,workerconfigfactory.getconfigs.buildworkerproviderdictionary.addprovider./usr/lib/azure-functions-core-tools-4/workers/powershell,15,15,15,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,workerconfigfactory.getconfigs.buildworkerproviderdictionary.addprovider./usr/lib/azure-functions-core-tools-4/workers/node,0,0,0,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,workerconfigfactory.getconfigs.buildworkerproviderdictionary.addprovider./usr/lib/azure-functions-core-tools-4/workers/java,20,20,20,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,workerconfigfactory.getconfigs.buildworkerproviderdictionary.addprovider./usr/lib/azure-functions-core-tools-4/workers/python,10,10,10,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,hostjsonfileconfigurationsource.loadhostconfigurationsource,5,5,5,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,workerprocess.start,5,5,5,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
MS_FUNCTION_METRICS ,,,workerconfigfactory.getconfigs,49,49,49,1,4.27.5.21554,2024-02-23T18:21:27.4964945Z,"{'IsStopwatchHighResolution': True}",WSL,,,,
[2024-02-23T18:21:57.757Z] Starting worker process failed
[2024-02-23T18:21:57.757Z] Microsoft.Azure.WebJobs.Script.Grpc: The operation has timed out.
[2024-02-23T18:21:57.759Z] Failed to start language worker process for runtime: (null). workerId:c8db8ef9-b555-4ed0-bf41-9ae967be7b64
[2024-02-23T18:21:57.761Z] Removing errored webhost language worker channel for runtime: python workerId:c8db8ef9-b555-4ed0-bf41-9ae967be7b64
[2024-02-23T18:21:57.761Z] Microsoft.Azure.WebJobs.Script.Grpc: The operation has timed out.
[2024-02-23T18:21:57.786Z] 0 functions loaded
[2024-02-23T18:21:57.789Z] Looking for extension bundle Microsoft.Azure.Functions.ExtensionBundle at /FuncExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle
[2024-02-23T18:21:57.789Z] Looking for extension bundle Microsoft.Azure.Functions.ExtensionBundle at /root/site/wwwroot/.azurefunctions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle
[2024-02-23T18:21:57.789Z] Looking for extension bundle Microsoft.Azure.Functions.ExtensionBundle at /root/data/Functions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle
[2024-02-23T18:21:57.789Z] Found a matching extension bundle at /root/data/Functions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle/4.12.0
[2024-02-23T18:21:57.790Z] Fetching information on versions of extension bundle Microsoft.Azure.Functions.ExtensionBundle available on https://functionscdn.azureedge.net/public/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle/index.json
[2024-02-23T18:21:57.827Z] Skipping bundle download since it already exists at path /root/data/Functions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle/4.12.0
[2024-02-23T18:21:57.828Z] Loading extension bundle from /root/data/Functions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle/4.12.0/bin_v3/linux-x64
[2024-02-23T18:21:57.829Z] Script Startup resetting load context with base path: '/root/data/Functions/ExtensionBundles/Microsoft.Azure.Functions.ExtensionBundle/4.12.0/bin_v3/linux-x64'.
[2024-02-23T18:21:57.837Z] Reading host configuration file '/workspaces/functionApp/host.json'
[2024-02-23T18:21:57.837Z] Host configuration file read:
[2024-02-23T18:21:57.837Z] {
[2024-02-23T18:21:57.837Z] "version": "2.0",
[2024-02-23T18:21:57.837Z] "logging": {
[2024-02-23T18:21:57.837Z] "applicationInsights": {
[2024-02-23T18:21:57.837Z] "samplingSettings": {
[2024-02-23T18:21:57.837Z] "isEnabled": true,
[2024-02-23T18:21:57.837Z] "excludedTypes": "Request"
[2024-02-23T18:21:57.837Z] }
[2024-02-23T18:21:57.837Z] }
[2024-02-23T18:21:57.837Z] },
[2024-02-23T18:21:57.837Z] "extensionBundle": {
[2024-02-23T18:21:57.837Z] "id": "Microsoft.Azure.Functions.ExtensionBundle",
[2024-02-23T18:21:57.837Z] "version": "[4.*, 5.0.0)"
[2024-02-23T18:21:57.837Z] }
[2024-02-23T18:21:57.837Z] }
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","Workers Directory set to: /usr/lib/azure-functions-core-tools-4/workers",4.27.5.21554,2024-02-23T18:21:57.9843144Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","Found worker config: /usr/lib/azure-functions-core-tools-4/workers/powershell/worker.config.json",4.27.5.21554,2024-02-23T18:21:57.9845090Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","EnvironmentVariable FUNCTIONS_WORKER_RUNTIME: python",4.27.5.21554,2024-02-23T18:21:57.9846553Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 4,,,,,Host.LanguageWorkerConfig,"","FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: powershell",4.27.5.21554,2024-02-23T18:21:57.9855122Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
[2024-02-23T18:21:57.992Z] MS_FUNCTION_AZURE_MONITOR_EVENT 4,localhost:7071,Microsoft.Web/sites/functions/log,FunctionAppLogs,,"{'appName':'','roleInstance':'wsl','message':'FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: powershell','category':'Host.LanguageWorkerConfig','hostVersion':'4.27.5.21554','hostInstanceId':'7719dbaf-0319-45f8-a0be-6dacebbe12c4','level':'Information','levelId':2,'processId':2651}",WSL,,02/23/2024 18:21:57
FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: powershell
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","Found worker config: /usr/lib/azure-functions-core-tools-4/workers/python/worker.config.json",4.27.5.21554,2024-02-23T18:21:57.9927588Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","EnvironmentVariable FUNCTIONS_WORKER_RUNTIME: python",4.27.5.21554,2024-02-23T18:21:57.9930990Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","EnvironmentVariable FUNCTIONS_WORKER_RUNTIME_VERSION: 3.10",4.27.5.21554,2024-02-23T18:21:57.9931523Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","Added WorkerConfig for language: python",4.27.5.21554,2024-02-23T18:21:57.9932030Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","Found worker config: /usr/lib/azure-functions-core-tools-4/workers/node/worker.config.json",4.27.5.21554,2024-02-23T18:21:57.9932423Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 5,,,,,Host.LanguageWorkerConfig,"","EnvironmentVariable FUNCTIONS_WORKER_RUNTIME: python",4.27.5.21554,2024-02-23T18:21:57.9933990Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
MS_FUNCTION_LOGS 4,,,,,Host.LanguageWorkerConfig,"","FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: node",4.27.5.21554,2024-02-23T18:21:57.9934933Z,,"",,7719dbaf-0319-45f8-a0be-6dacebbe12c4,,WSL,,,,
[2024-02-23T18:21:57.993Z] FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: nodeMS_FUNCTION_AZURE_MONITOR_EVENT 4,localhost:7071,Microsoft.Web/sites/functions/log,FunctionAppLogs,,"{'appName':'','roleInstance':'wsl','message':'FUNCTIONS_WORKER_RUNTIME set to python. Skipping WorkerConfig for language: node','category':'Host.LanguageWorkerConfig','hostVersion':'4.27.5.21554','hostInstanceId':'7719dbaf-0319-45f8-a0be-6dacebbe12c4','level':'Information','levelId':2,'processId':2651}",WSL,,02/23/2024 18:21:57
</code></pre>
<p>...</p>
|
<python><azure-functions><windows-subsystem-for-linux><ubuntu-22.04><azure-functions-core-tools>
|
2024-02-23 18:37:10
| 1
| 5,096
|
jlo-gmail
|
78,049,416
| 3,778,976
|
How to test warnings with Pytest but exclude from summary report
|
<p>Pytest supports testing for warning messages with warns(). For example,</p>
<p>auth.py:</p>
<pre><code>import warnings
def warn_for_plain_text_security():
warnings.warn("Notice: Credentials in the .rc file is deprecated")
warn_for_plain_text_security()
</code></pre>
<p>test_auth.py:</p>
<pre><code>import unittest
import warnings
import pytest
from auth import warn_for_plain_text_security
class AuthProviderTest(unittest.TestCase):
def test_insecure_creds(self):
with pytest.warns(UserWarning, match='Notice:') as w:
warn_for_plain_text_security()
</code></pre>
<p>However, the warnings -- which are really just successful unit tests -- then show up in the summary report.</p>
<p>I want to be able to test Python warnings, but only see <strong>real</strong> warnings in the summary. Is there a way to do this?</p>
<pre><code>===================================================================================== test session starts ======================================================================================
platform darwin -- Python 3.10.8, pytest-8.0.1, pluggy-1.4.0
rootdir: /private/tmp
collected 1 item
test_auth.py . [100%]
================== warnings summary ==================
auth.py:5
/private/tmp/auth.py:5: UserWarning: Notice: Credentials in the .rc file is deprecated
warnings.warn("Notice: Credentials in the .rc file is deprecated")
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
============ 1 passed, 1 warning in 0.02s ============
</code></pre>
<p>There is a <a href="https://docs.pytest.org/en/8.0.x/how-to/capture-warnings.html#recwarn" rel="nofollow noreferrer">WarningsRecorder</a> instance, but it's unclear if this can be manipulated during the test case.</p>
|
<python><pytest>
|
2024-02-23 18:12:41
| 1
| 1,391
|
Brad Schoening
|
78,049,406
| 13,296,497
|
Pysark dataframe not filtering out rows when comparing two columns
|
<p>Example of my data</p>
<pre><code>
event_id | previous_plan | new_plan
1 | Null | 1mo
2 | Null | 1mo
3 | 1mo | 1mo
4 | 6mo | 6mo
5 | Null | 6mo
6 | 1mo | 6mo
7 | 6mo | 6mo
</code></pre>
<p>I want to filter out rows where "previous_plan" = "new_plan". My code is</p>
<pre><code>from pyspark.sql import functions as F
df.selectExpr("event_id",
"previous_plan",
"new_plan") \
.filter(F.col("previous_plan") != F.col("new_plan"))
</code></pre>
<p>This should filter out rows with event_id of 3, 4, and 7 to return the updated dataframe</p>
<pre><code>
event_id | previous_plan | new_plan
1 | Null | 1mo
2 | Null | 1mo
5 | Null | 6mo
6 | 1mo | 6mo
</code></pre>
<p>However, I am still getting all 7 rows. What am I doing wrong here?</p>
|
<python><dataframe><pyspark>
|
2024-02-23 18:11:17
| 1
| 1,092
|
DSolei
|
78,049,161
| 4,704,065
|
Duplicate and incorrect legends
|
<p>I am creating a plot and have few issues:</p>
<ol>
<li>Legends are duplicated</li>
<li>Legends are shown incorrectly on the left, instead of the right</li>
<li>Same value of legend is shown incorrect for different values and colors</li>
<li>Plots are overlapped</li>
</ol>
<ul>
<li>I am plotting svIonoStdev vs ITow when sourceid= 0 and 1.</li>
<li>With this I need to groupthem based on svGnssId and svSvId.</li>
<li>I am able to group them, but the legends are not shown correctly.</li>
</ul>
<p><strong>Below is code I tried:</strong></p>
<p>Since my DF is too big (around 60K rows) I converted the first 15 rows of my DF into dict and sharing here</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import pandas as pd
new_msg_dict = {
'sourceId': [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0],
'iTOW': [518490.0, 518490.0, 518490.0, 518490.0, 518490.0, 518490.0, 518490.0, 518492.0, 518492.0, 518492.0, 518492.0, 518492.0, 518492.0, 518492.0, 518493.0, 518493.0],
'svGnssId': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
'svSvId': [1.0, 10.0, 14.0, 21.0, 22.0, 27.0, 32.0, 1.0, 10.0, 14.0, 21.0, 22.0, 27.0, 32.0, 1.0, 10.0],
'ionoCorr': [-0.14, 0.034, 1.973, -1.09, 7.136, 4.187, 2.006, -0.14, 0.034, 1.973, -1.09, 7.136, 4.187, 2.0060000000000002, -0.14, 0.034],
'svIonoStdev': [0.03, 0.03, 0.05, 0.03, 0.05, 0.03, 0.03, 0.03, 0.03, 0.05, 0.03, 0.05, 0.03, 0.03, 0.03, 0.03]
}
new_msg_df = pd.DataFrame(new_msg_dict)
satellite = 'GPS'
new_gk_stddev = list(new_msg_df.groupby(['svGnssId', 'svSvId', 'sourceId', 'svIonoStdev']))
fig, ax = plt.subplots(2, constrained_layout=True)
for i in new_gk_stddev:
if i[0][2] == 1.0:
ax[0].plot(i[1]['iTOW'], i[1]['svIonoStdev'], label=f"{satellite} {i[0][1]}")
ax[0].set_ylabel("Standard deviation (TECU)")
ax[0].set_xlabel("Itows (mSec)")
ax[0].grid(True)
ax[0].legend(fontsize=4)
ax[0].set_title('Correction Handler Output')
elif i[0][2] == 2.0:
ax[1].plot(i[1]['iTOW'], i[1]['svIonoStdev'], label=f"{satellite} {i[0][1]}")
ax[1].set_ylabel("Standard deviation (TECU)")
ax[1].set_xlabel("Itows (mSec)")
ax[1].grid(True)
ax[1].legend(fontsize=4)
ax[1].set_ylim([0, 0.05])
ax[1].set_title('HPG Filter Output')
</code></pre>
<p><strong>Current Output:</strong>
<a href="https://i.sstatic.net/Xabys.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Xabys.png" alt="enter image description here" /></a></p>
<p><strong>Expected Output:</strong>
<a href="https://i.sstatic.net/lfDkq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lfDkq.png" alt="enter image description here" /></a></p>
<p>This is part of my DF:</p>
<p><a href="https://i.sstatic.net/UkyZC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UkyZC.png" alt="enter image description here" /></a></p>
|
<python><pandas><matplotlib>
|
2024-02-23 17:25:37
| 1
| 321
|
Kapil
|
78,049,053
| 6,447,399
|
QuantLib Call Options Pricing over rows in a data frame
|
<p>I have some data which looks like:</p>
<pre><code>date call_open call_high call_low call_close put_open put_high put_low put_close stock_open stock_high stock_low stock_close stock_volume
0 2024-01-31 15:30:00 1.03 1.82 0.88 0.95 11.72 12.78 11.34 12.55 488.62 489.09 487.52 487.76 61890.0
1 2024-01-31 15:30:00 1.03 1.82 0.88 0.95 11.72 12.78 11.34 12.55 488.62 489.09 487.52 487.76 61890.0
2 2024-01-31 16:00:00 0.95 0.96 0.79 0.84 12.55 13.80 12.47 13.48 487.73 487.83 486.39 486.75 81468.0
3 2024-01-31 16:00:00 0.95 0.96 0.79 0.84 12.55 13.80 12.47 13.48 487.73 487.83 486.39 486.75 81468.0
4 2024-01-31 17:00:00 0.84 0.92 0.81 0.86 13.48 13.88 12.76 13.39 486.74 487.48 486.34 486.84 53420.0
</code></pre>
<p>I am trying to compute for each row the options price as if I was trying to price the option on that day.</p>
<p>This is the options chain data with a strike of 500 for the S&P500.</p>
<p>I pass it the following:</p>
<ul>
<li>Todays stock <code>S</code> - the <code>stock_close</code> column.</li>
<li>Strike price <code>K</code></li>
<li>volatility <code>v</code> (I know using the volatility of the whole dataset is not useful since its using future stock prices but this is just to assign a realistic value here)</li>
<li><code>ri</code> the risk pree rate</li>
<li>The expiry is the last observed date in the options chain (I downloaded it just before close <code>expiry = pd.to_datetime("2024-02-14")</code></li>
</ul>
<p>What I don't understand is why is my <code>call_option_pricing</code> so different to that of the <code>call_close</code> - i.e. I am getting values of 0.013527 when the actual price was 0.95</p>
<pre><code>date call_open call_high call_low call_close put_open put_high put_low put_close stock_open stock_high stock_low stock_close stock_volume option_pricing
0 2024-01-31 15:30:00 1.03 1.82 0.88 0.95 11.72 12.78 11.34 12.55 488.62 489.09 487.52 487.76 61890.0 0.013527
1 2024-01-31 15:30:00 1.03 1.82 0.88 0.95 11.72 12.78 11.34 12.55 488.62 489.09 487.52 487.76 61890.0 0.013527
2 2024-01-31 16:00:00 0.95 0.96 0.79 0.84 12.55 13.80 12.47 13.48 487.73 487.83 486.39 486.75 81468.0 0.006911
3 2024-01-31 16:00:00 0.95 0.96 0.79 0.84 12.55 13.80 12.47 13.48 487.73 487.83 486.39 486.75 81468.0 0.006911
4 2024-01-31 17:00:00 0.84 0.92 0.81 0.86 13.48 13.88 12.76 13.39 486.74 487.48 486.34 486.84 53420.0 0.007350
import pandas as pd
file_path = "path/expiry_20240214_strike_500.csv"
data = pd.read_csv(file_path)
data = data.dropna(subset=['stock_close'])
data
def compute_option_pricing(row):
S = row['stock_close']
K = 500
v = data['stock_close'].std() / 100
ri = 0.0528 # taken from: https://home.treasury.gov/resource-center/data-chart-center/interest-rates/TextView?type=daily_treasury_bill_rates&field_tdr_date_value_month=202402
date = pd.to_datetime(row['date'])
today = ql.Date(date.day, date.month, date.year)
expiry = pd.to_datetime("2024-02-14")
expiry = ql.Date(expiry.day, expiry.month, expiry.year)
# Set the evaluation date
ql.Settings.instance().evaluationDate = today
# The Instrument
option = ql.EuropeanOption(ql.PlainVanillaPayoff(ql.Option.Call, K),
ql.EuropeanExercise(expiry))
# The Market
u = ql.SimpleQuote(S)
r = ql.SimpleQuote(ri)
sigma = ql.SimpleQuote(v)
riskFreeCurve = ql.FlatForward(0, ql.TARGET(), ql.QuoteHandle(r), ql.Actual365Fixed())
volatility = ql.BlackConstantVol(0, ql.TARGET(), ql.QuoteHandle(sigma), ql.Actual365Fixed())
# The Model
process = ql.BlackScholesProcess(ql.QuoteHandle(u),
ql.YieldTermStructureHandle(riskFreeCurve),
ql.BlackVolTermStructureHandle(volatility))
# The Pricing Engine
engine = ql.AnalyticEuropeanEngine(process)
option.setPricingEngine(engine)
return option.NPV()
# Apply the function to each row and store the results in a new column
data['call_option_pricing'] = data.apply(compute_option_pricing, axis=1)
</code></pre>
|
<python><quantlib>
|
2024-02-23 17:05:23
| 0
| 7,189
|
user113156
|
78,048,953
| 22,212,435
|
Why don't ButtonPress and Button-1 execute together?
|
<p>So I wrote a very simple logic:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
root.bind('<Button-1>', lambda e: print('b-1'), add='+')
root.bind('<ButtonPress>', lambda e: print('some button'), add='+')
root.mainloop()
</code></pre>
<p>I expect that when I click "<code>Button-1</code>", it should print "b-1" and "some button" (in some order). In practice it only prints "b-1". it looks like <code>bind('<Button-1>', …)</code> overrides another bind. I can't really figure out why.</p>
<p>Question: Why does this happen and how to fix this?</p>
<p>P.S. I am pretty sure that this question might be a duplicate due to its simplicity, but I haven't been able to find an answer.</p>
|
<python><tkinter>
|
2024-02-23 16:52:43
| 1
| 610
|
Danya K
|
78,048,862
| 765,800
|
Dynamically add mixin to a class depends on attribute value in python
|
<p>I want to dynamically add a mixin class in an object without effecting any other objects of that class. I have an external service that determine which mixin should be used for a particular object.</p>
<p>I am currently using a metaclass to dynamically add a base class to an object. But the issue is, if I change base class of any object, it effects all other objects as well. Here is a simplified sample code snippet:</p>
<pre><code>class M(type):
def __call__(cls, *args, **kwargs):
obj = type.__call__(cls, *args, **kwargs)
if hasattr(obj, "mixin"):
obj.__class__.__bases__ = (obj.mixin,) + obj.__class__.__bases__
return obj
class MixinA:
name = "A"
attr1 = 100
class MixinB:
name = "B"
attr2 = 200
class A(metaclass=M):
pass
class B(A):
def __init__(self, some_value):
self.mixin = external_function(some_value)
b1 = B('X') # Let's say it should use MixinA
print(b1.name, b1.__class__.__base__)
b2 = B('Y') # Let's say it should use MixinB
print(b2.name, b2.__class__.__base__)
print(b1.name, b1.__class__.__base__)
</code></pre>
<p>This will output:</p>
<pre><code>A <class '__main__.MixinA'>
B <class '__main__.MixinB'>
B <class '__main__.MixinB'>
</code></pre>
<p>What can I do so that changing base class of <code>b2</code> will not effect <code>b1</code>. So the output should be:</p>
<pre><code>A <class '__main__.MixinA'>
B <class '__main__.MixinB'>
A <class '__main__.MixinA'>
</code></pre>
<p>Or is there any other ways where I can access/execute all the properties/methods of the appropriate mixin applied dynamically to that object.</p>
<p><strong>Edit:</strong> Updated description and code snippet for more clarity.</p>
|
<python><inheritance><mixins>
|
2024-02-23 16:37:53
| 2
| 353
|
Ali Hasan Imam
|
78,048,750
| 1,711,271
|
In polars select all column ending with pattern and add new columns without pattern
|
<p>I have the following dataframe:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
import numpy as np
df = pl.DataFrame({
"nrs": [1, 2, 3, None, 5],
"names_A0": ["foo", "ham", "spam", "egg", None],
"random_A0": np.random.rand(5),
"A_A2": [True, True, False, False, False],
})
digit = 0
</code></pre>
<p>For each column X whose name ends with the string <code>suf =f'_A{digit}'</code>, I want to add an identical column to <code>df</code>, whose name is the same as X, but without <code>suf</code>.</p>
<p>In the example, I need to add columns <code>names</code> and <code>random</code> to the original dataframe <code>df</code>, whose content is identical to that of columns <code>names_A0</code> and <code>random_A0</code> respectively.</p>
<pre><code>shape: (5, 6)
┌──────┬──────────┬───────────┬───────┬───────┬──────────┐
│ nrs ┆ names_A0 ┆ random_A0 ┆ A_A2 ┆ names ┆ random │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ f64 ┆ bool ┆ str ┆ f64 │
╞══════╪══════════╪═══════════╪═══════╪═══════╪══════════╡
│ 1 ┆ foo ┆ 0.274748 ┆ true ┆ foo ┆ 0.274748 │
│ 2 ┆ ham ┆ 0.26136 ┆ true ┆ ham ┆ 0.26136 │
│ 3 ┆ spam ┆ 0.718004 ┆ false ┆ spam ┆ 0.718004 │
│ null ┆ egg ┆ 0.303287 ┆ false ┆ egg ┆ 0.303287 │
│ 5 ┆ null ┆ 0.719041 ┆ false ┆ null ┆ 0.719041 │
└──────┴──────────┴───────────┴───────┴───────┴──────────┘
</code></pre>
|
<python><dataframe><python-polars><calculated-columns>
|
2024-02-23 16:19:24
| 3
| 5,726
|
DeltaIV
|
78,048,718
| 8,831,116
|
Derive type hint for my_dict.items() for return type of function (Python)
|
<p>I have a definition of a frequently used type, <code>MyModel</code>. For various reasons, in some models I do not work on <code>MyModel</code> directly but on a stream of tuples of <code>key</code> and <code>value</code>. Currently I have to duplicate the type hints for these iterables.</p>
<p>To give a brief example:</p>
<pre class="lang-py prettyprint-override"><code>import typing as t
MyModel = dict[str, int]
def print_mappings(stream: t.Iterable[tuple[str, int]]) -> None:
...
if __name__ == "__main__":
my_model = {str(n): n for n in range(10)}
print_mappings(my_model.items())
</code></pre>
<p>I would like to put something instead of <code>t.Iterable[...]</code> that automatically resolves to the return type of <code>MyModel.items</code>. Is there a way how this can be achieved?</p>
|
<python><mypy>
|
2024-02-23 16:14:05
| 0
| 858
|
Max Görner
|
78,048,681
| 1,711,271
|
Add a new column into an existing Polars dataframe
|
<p>I want to add a column <code>new_column</code> to an existing dataframe <code>df</code>. I <em>know</em> this looks like a duplicate of</p>
<p><a href="https://stackoverflow.com/q/75720011/1711271">Add new column to polars DataFrame</a></p>
<p>but the answer to that questions, as well as the answers to many similar questions, don't really add a column to an <strong>existing</strong> dataframe. They create a new column with another dataframe. I <em>think</em> this can be fixed like this:</p>
<pre><code>df = df.with_columns(
new_column = pl.lit('some_text')
)
</code></pre>
<p>However, rewriting the whole dataframe just to add a few columns, seems a bit of a waste to me. Is this the right approach?</p>
|
<python><dataframe><python-polars>
|
2024-02-23 16:08:20
| 2
| 5,726
|
DeltaIV
|
78,048,653
| 11,609,834
|
How to hint Python function with an inplace argument?
|
<p>I have a function that takes and <code>inplace</code> argument. Following good practice, the function returns <code>None</code> if it modifies the input (<code>inplace=True</code>) and returns a copy of the input, modified, otherwise (<code>inplace=False</code>). (My preference now would be to just not have the <code>inplace</code> argument, but that ship sailed.)</p>
<p>I typed the function like this:</p>
<pre><code>from typing import Union
A = TypeVar("A")
def func(data: A, inplace=False) -> Union[A, None]:
if inplace:
return None
...
return data.copy()
</code></pre>
<p>But the following has a typing error:</p>
<pre><code>
modified_data = func([1, 2,3])
modified_data.append(4)
</code></pre>
<p>Saying that None Type objects don't have an append attritbute. This is correct: the type checker should, given the way the hint is written, say this is wrong, since we don't know the type of <code>modified_data</code> (given the type hints).</p>
<p>But this is obnoxious and we want the type checker to handle this case and raise a typing if inplace==True but not otherwise. Is there a way to handle it?</p>
|
<python><python-typing>
|
2024-02-23 16:04:01
| 1
| 1,013
|
philosofool
|
78,048,639
| 12,423,732
|
VertexAI: RunName of Experiment
|
<p>Is it possible to get a list of runs for a given experiment using google.cloud.aiplatform?</p>
<p>I've looked through the docs and can't see an obvious way to retrieve this.</p>
|
<python><google-cloud-vertex-ai>
|
2024-02-23 16:01:18
| 1
| 319
|
Iain MacCormick
|
78,048,603
| 4,269,851
|
Python calling function defined in __init__.py not working
|
<p>I created sub folder <code>module1</code> with just _<code>_init__.py</code></p>
<pre><code>def print_hello():
print('Hello')
__all__ = ["print_hello"]
print('Init loaded')
</code></pre>
<p>inside <code>main.py</code> i have</p>
<pre><code>import module1
print_hello()
</code></pre>
<p>Output as follows</p>
<pre><code>print_hello()
^^^^^^^^^^^
NameError: name 'print_hello' is not defined
Init loaded
</code></pre>
|
<python><module><init>
|
2024-02-23 15:55:33
| 1
| 829
|
Roman Toasov
|
78,048,552
| 14,751,182
|
How to retrieve the selected ALPN protocol from an asyncio stream?
|
<p>I am writing a HTTP client in Python.
In order to select the correct HTTP version, I use ALPN.<br>
While there is an easy and documented way to get the selected protocol from a ssl-wrapped socket (<code>SSLSocket.selected_alpn_protocol()</code>), I have found no official way to do this for <code>asyncio</code> streams.</p>
<p>I am quite new to asyncio, so maybe I have completely misunderstood the concept, but this is still puzzling. Although I have found a way to retrieve the selected protocol, it's too complex to be the official way. Additionally, I have found little to no information on this subject online.</p>
<p>I've found the following:</p>
<pre><code>writer.transport._ssl_protocol._sslobj.selected_alpn_protocol()
reader._transport._ssl_protocol._sslpipe.ssl_object.selected_alpn_protocol()
</code></pre>
<p>These sometimes don't work though, so I have no idea whether this is version specific or I'm just doing something completely wrong.</p>
<p><strong>Code to reproduce</strong></p>
<pre class="lang-py prettyprint-override"><code>import asyncio
import ssl
async def test_alpn():
ctx = ssl.create_default_context()
ctx.set_alpn_protocols(["http/1.1", "h2"])
reader, writer = await asyncio.open_connection('example.org', 443, ssl = ctx, server_hostname = 'example.org')
return writer.transport._ssl_protocol._sslobj.selected_alpn_protocol()
print(asyncio.run(test_alpn()))
</code></pre>
|
<python><ssl><python-asyncio><alpn>
|
2024-02-23 15:47:46
| 1
| 604
|
Adam Jenča
|
78,048,327
| 3,751,711
|
AES simple encryption in Node and decryption in Python and vice versa
|
<p>I generate secretKey in nodejs as below,</p>
<pre><code>const generateAesKey = () => {
const { randomBytes } = require('node:crypto');
randomBytes(32, (err, buf) => {
if (err) throw err;
return buf.toString('hex');
});
}
const secretKey = generateAesKey();
</code></pre>
<p>SecretKey looks something like this : <code>491fb9719864f51e19a0705a3ef2de15cd91576d881cdc4bd4394bf7451ee404</code></p>
<p>Using above key, I encrypt and decrypt data as below (Node environment)</p>
<pre><code>const CryptoJS = require("crypto-js");
// updated per Tppaco's comment
const secretKey = CryptoJS.enc.Hex.parse("491fb9719864f51e19a0705a3ef2de15cd91576d881cdc4bd4394bf7451ee404");
const encrypt = (plainText) => {
const iv = CryptoJS.enc.Utf8.parse('BBBBBBBBBBBBBBBB');
const encrypted = CryptoJS.AES.encrypt(plainText, CryptoJS.enc.Utf8.parse(secretKey), {
iv: iv,
mode: CryptoJS.mode.CBC,
});
return encrypted.toString();
}
const decrypt = (cipherText) => {
const iv = CryptoJS.enc.Utf8.parse('BBBBBBBBBBBBBBBB');
const decrypted = CryptoJS.AES.decrypt(cipherText, CryptoJS.enc.Utf8.parse(secretKey), {
iv: iv,
mode: CryptoJS.mode.CBC,
});
return CryptoJS.enc.Utf8.stringify(decrypted);
}
const en = encrypt("Text to be encrypted");
console.log(decrypt(en))
</code></pre>
<p>I am able to encrypt/decrypt data successfully in Node environment. The problem comes when I have to decrypt data in Python environment that I encrypted in Node environment.</p>
<p><strong>Python Environment</strong></p>
<p>I have written below Python code which is equivalent Node code (correct me if this statement is not right).</p>
<pre><code>from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
import base64
import json
import os
#CBC with Fix IV
# key = os.urandom(32) // to generate random secret key
# updated per Tppaco's comment
key = bytes.fromhex('491fb9719864f51e19a0705a3ef2de15cd91576d881cdc4bd4394bf7451ee404')
data = 'Text to be encrypted'
#FIX IV
iv = 'BBBBBBBBBBBBBBBB'.encode('utf-8') #16 char for AES128
def encrypt(data,key,iv):
data= pad(data.encode(),16)
cipher = AES.new(key,AES.MODE_CBC,iv)
return base64.b64encode(cipher.encrypt(data))
def decrypt(enc,key,iv):
enc = base64.b64decode(enc)
cipher = AES.new(key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc),16)
def lambda_handler(event, context):
encrypted = encrypt(data,key,iv)
print('encrypted CBC base64 : ',encrypted.decode("utf-8", "ignore"))
decrypted = decrypt(encrypted,key,iv)
print('decrypted data: ', decrypted.decode("utf-8", "ignore"))
return {
'statusCode': 200,
'decrypted text': json.dumps(decrypted.decode("utf-8", "ignore"))
}
</code></pre>
<p><strong>Error</strong></p>
<blockquote>
<p>"errorMessage": "Padding is incorrect.",
"errorType": "ValueError",</p>
</blockquote>
<p>My main purpose is to encrypt data in Node and decrypt it in Python. What am I doing wrong?</p>
|
<javascript><python><node.js><encryption><aes>
|
2024-02-23 15:07:04
| 0
| 55,623
|
micronyks
|
78,048,307
| 3,433,875
|
Gradient color on broken barh plot in matplotlib
|
<p>I am trying to reproduce this:
<a href="https://i.sstatic.net/pV6fi.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pV6fi.png" alt="enter image description here" /></a></p>
<p>using this code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.lines import Line2D
colors = ["#CC5A43","#5375D4"]*3
data = {
"year": [2004, 2022, 2004, 2022, 2004, 2022],
"countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],
"sites": [13,15,4,10,5,8]
}
df= pd.DataFrame(data)
df['pct_change'] = df.groupby('countries', sort=True)['sites'].apply(
lambda x: x.pct_change()).to_numpy()*-1
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df = df.sort_values(['countries','year'], ascending=True ).reset_index(drop=True)
df['diff'] = df.groupby(['countries'])['sites'].diff()
df['diff'].fillna(df.sites, inplace=True)
countries = df.countries.unique()
code = df.ctry_code.unique()
pct_change = df.pct_change
x_coord = df.groupby('countries')['diff'].apply(lambda x: x.values) #convert the columns into numpy 2D array
fig, ax = plt.subplots(figsize=(6,5), facecolor = "#FFFFFF")
import matplotlib.cm
# use a colormap
cmap = plt.cm.RdBu
for i, (color, x_c, country) in enumerate(zip(colors,x_coord, countries)):
ax.broken_barh([x_c], (i-0.2,0.4),facecolors=cmap(0.7),alpha= 0.2)
ax.scatter( df.sites, df.countries, marker="D", s=300, color = colors)
ax.set(xlim=[0, 16], ylim=[-1, 3])
ax.xaxis.set_ticks(np.arange(0,20,5),labels = [0,5,10,15])
ax.tick_params(axis="x", which="major",length=0,labelsize=14,colors= '#C8C9C9')
# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 16, 1)
ax.set_xticks(major_ticks)
ax.grid(which='major', axis='x', linestyle='-', alpha=0.4, color = "#C8C9C9")
ax.set_axisbelow(True)
plt.yticks([])
plt.box(False)
#add legend
labels = ['2004','2022']
colors = ["#5375D4","#CC5A43",]
lines = [Line2D([0], [0], color=c, marker='D',linestyle='', markersize=12,) for c in colors]
leg = ax.get_legend()
plt.figlegend( lines,labels,
labelcolor="#C8C9C9",
bbox_to_anchor=(0.3, -0.1), loc="lower center",
ncols = 2,frameon=False, fontsize= 12)
</code></pre>
<p>Which produces this:</p>
<p><a href="https://i.sstatic.net/o9HQB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/o9HQB.png" alt="enter image description here" /></a></p>
<p>My question is, how do i do the gradient on the broken_barh plots? I have tried to do a cmap on facecolors, but no luck.</p>
<p>I have also tried using ax.barh and ax.plot but still stuck :(</p>
|
<python><matplotlib>
|
2024-02-23 15:04:14
| 2
| 363
|
ruthpozuelo
|
78,048,241
| 3,240,484
|
typing Protocol valid for Enumerator member
|
<p>What is the right typing to accept an Enumerator Type which should match a Protocol ?
I mean the Enumerator should have members defined inside a Protocol</p>
<p>Here is a simplified code exemple.</p>
<pre class="lang-py prettyprint-override"><code>from typing import Protocol
from enum import Enum
class MyProto(Protocol):
item1: int
item2: int
def check_item1( e: MyProto, value:int):
return e.item1 == value
class MyEnum(int, Enum):
item1 = 0
item2 = 1
other_item_not_in_protocol = 2
check_item1( MyEnum, 0 ) #<-- pyright complains about everything :
</code></pre>
<p>Pyright complains</p>
<pre><code># Argument of type "type[MyEnum]" cannot be assigned to parameter "e" of type "MyProto" #in function "check_item1"
# "item1" is invariant because it is mutable
# "item1" is an incompatible type
# "item1" must be defined as a ClassVar to be compatible with protocol
# "Literal[MyEnum.item1]" is incompatible with "int"
# "item2" is invariant because it is mutable
# "item2" is an incompatible type
# "item2" must be defined as a ClassVar to be compatible with protocol
# "Literal[MyEnum.item2]" is incompatible with "int" [reportArgumentType]
</code></pre>
<p>Mypy also complains:</p>
<pre><code># error: Argument 1 to "check_item1" has incompatible type "type[MyEnum]"; expected # "MyProto" [arg-type]
# Found 1 error in 1 file (checked 1 source file)
</code></pre>
|
<python><enums><python-typing>
|
2024-02-23 14:57:17
| 1
| 314
|
user3240484
|
78,048,223
| 7,981,566
|
Adding folder with data with `pyproject.toml`
|
<p>I would like to package some legacy code to a <code>hello</code> <em>Python</em> package containing only one module (<code>hello.py</code>) file in the top-level directory alongside with some data in a folder called <code>my_data</code> without changing the folder structure:</p>
<pre><code>hello/
|-hello.py
|-pyproject.toml
|-my_data/
|-my_data.csv
</code></pre>
<p>Packaging the <em>Python</em> source code with the following <code>pyproject.toml</code> file is surprisingly simple (without any prior knowledge on packaging), but running <code>pip install . -vvv</code> fails to copy the data:</p>
<pre><code>[project]
name = "hello"
version = "0.1"
[tool.setuptools]
py-modules = ['hello']
[tool.setuptools.package-data]
hello = ['my_data/*']
</code></pre>
<p>The content of <code>hello.py</code> could be minimal:</p>
<pre><code>def hello:
print('Hello, world!')
</code></pre>
<p>I tried multiple variants of this <code>pyproject.toml</code> file according to the documentation on <a href="http://setuptools.pypa.io/en/stable/userguide/datafiles.html" rel="nofollow noreferrer">http://setuptools.pypa.io/en/stable/userguide/datafiles.html</a> as well as a related question on <a href="https://stackoverflow.com/questions/69647590/specifying-package-data-in-pyproject-toml">Specifying package data in pyproject.toml</a>, but none of them would result in copying of the <code>my_data/</code> folder directly into the <code>site-packages</code> folder (which is intended, but probably bad practice).<br />
I also found documentation suggesting to use a <code>MANIFEST.in</code>></p>
<pre><code>graft my_data
</code></pre>
<p>but also this doesn't result in the data to be installed alongside the code.</p>
|
<python><setuptools><python-packaging><pyproject.toml>
|
2024-02-23 14:54:09
| 3
| 1,059
|
NicolasBourbaki
|
78,048,149
| 3,768,497
|
No module named 'regression_testing.common' Python Sphinx
|
<p>Repo is like this, with 2 folders for "individual modules" <code>regression_testing_package</code> and <code>regressin_testing_common</code> but both share the same namespace <code>regression_testing</code> both are managed with their own poetry configuration and both have their own sphinx documentation configuration.</p>
<p>In our python code, there are functions inside the <code>regression_testing_package</code> that use functions from <code>regression_testing_common</code> with imports like <code>from regression_testing.common.deprecation import deprecated</code> working without any issues</p>
<p>This is the folder structure</p>
<pre><code>Root - repo is called regression_testing_package
regression_testing_package (managed using poetry
src
regression_testing
folder_a
folder_b
docs
_source (all sphinx config/files are in here and publish ../ to docs)
regression_testing_common
src
regression_testing
common
docs
_source (all sphinx config/files are in here and publish ../ to docs)
</code></pre>
<p>When trying to build docs for <code>regression_testing_package</code> autodoc gives warnings as such <code>WARNING: autodoc: failed to import module 'pipelines' from module 'regression_testing.azure'; the following exception was raised: No module named 'regression_testing.common'</code></p>
<p>So its been unable to build the docs for the pipeline module as the top of the file includes <code>from regression_testing.common.deprecation import deprecated</code> as i am working on deprecating some functions.</p>
<p>my <code>conf.py</code> contains the following (debug lines included)</p>
<pre><code>import sys
import toml
from pathlib import Path
src_path = Path(__file__).resolve().parents[2] / 'src'
regression_testing_path = Path(__file__).resolve().parents[3] / 'regression_testing_common' / 'src'
print(f"src_path exists: {src_path.exists()}, path: {src_path}")
print(f"regression_testing_path exists: {regression_testing_path.exists()}, path: {regression_testing_path}")
sys.path.insert(0, str(src_path))
sys.path.insert(1, str(regression_testing_path))
os.system("pip list")
</code></pre>
<p>And when running <code>make html</code> I can see from the 2 print statements that the path being added does indeed point to the <code>src</code> folder for both modules</p>
<pre><code>src_path exists: True, path: C:\Users\Karl.Hudgell\Documents\Work\HE\regression-testing-package\regression_testing_package\src
regression_testing_path exists: True, path: C:\Users\Karl.Hudgell\Documents\Work\HE\regression-testing-package\regression_testing_common\src
</code></pre>
<p>the <code>pip list</code> command also seems to show the module is installed</p>
<pre><code>PyYAML 6.0.1
recommonmark 0.7.1
regression-testing-common 0.1.2
regression-testing-package 3.0.9a1 C:\Users\Karl.Hudgell\Documents\Work\HE\regression-testing-package\regression_testing_package
reportlab 4.0.7
requests 2.31.0
</code></pre>
<p>But no matter what I do, I can't seem to get the docs to generate being able to see the functions in <code>regression-testing-common</code></p>
|
<python><python-sphinx>
|
2024-02-23 14:41:46
| 1
| 619
|
Karl
|
78,048,052
| 1,350,082
|
Setting grouped barplot colour based on the category and not the grouping used with hue in Seaborn
|
<p>I am trying to change how the colours are displayed when plotting a grouped barplot with seaborn.</p>
<p>In the following minimal example,you get the output you would expect, the colour being set on the group. However, I want the colour to be set based on the category.</p>
<pre><code>import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = [3, 5, 2, 4, 6, 1]
group = [1, 2, 1, 2, 1, 2]
category = ['a', 'a', 'b', 'b', 'c', 'c']
data = pd.DataFrame(zip(category, group, data), columns=['category', 'group', 'data'])
palette = sns.color_palette("pastel")
fig, ax = plt.subplots(figsize=(15, 15))
sns.barplot(data=data, x='category', y='data', palette=palette, hue='group', edgecolor='k', zorder=3, ax=ax)
ax.grid(zorder=0)
plt.tight_layout()
plt.show()
</code></pre>
<p><a href="https://i.sstatic.net/bFCLR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bFCLR.png" alt="enter image description here" /></a></p>
<p>I attempted to use a custom palette where each colour is repeated twice, but it still colours by the group and therefore displays with the same colour for all bars.</p>
<pre><code>palette = [color for color in sns.color_palette("pastel") for _ in range(2)]
</code></pre>
<p><a href="https://i.sstatic.net/rKzau.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rKzau.png" alt="enter image description here" /></a></p>
<p>Is it possible to change the colouring to have the colour set on the category and not the group with Seaborn?</p>
|
<python><matplotlib><seaborn>
|
2024-02-23 14:25:07
| 1
| 317
|
speeder1987
|
78,048,004
| 7,959,614
|
Rewrite for-loop vectorized using Numpy
|
<p>I have the following code:</p>
<pre><code>def obj(f, pis, rs):
out = np.zeros(f.size)
for pi, r in zip(pis, rs):
out += r * pi / (1 + np.dot(r, f))
return out
p = np.array([0.42, 0.08, 0.42, 0.08])
r = np.array([[-1.0, 7.0, -1.0, 0.4],
[-1.0, 7.0, 0.5, -1.0],
[0.2, -1.0, -1.0, 0.4],
[0.2, -1.0, 0.5, -1.0]
])
f = np.array([0.25, 0.25, 0.25, 0.25])
</code></pre>
<p>I want to vectorize this function.
Why is the below implementation not giving the same output:</p>
<pre><code>def obj_vec(f, pis, rs):
out = rs * pis / (1 + np.dot(r, f))
return np.sum(out, axis=1)
</code></pre>
<p>How should <code>obj_vec()</code> be defined?</p>
|
<python><numpy>
|
2024-02-23 14:16:45
| 2
| 406
|
HJA24
|
78,047,985
| 9,976,891
|
Tkinter scrollable frame cut off when adding horizontal scrollbar
|
<p>I'm modifying <a href="https://stackoverflow.com/a/47985165/9976891">this</a> example to add a horizontal scrollbar. I've looked at similar answers on SO but they don't help, which I'll explain further at the bottom of the question.</p>
<p>Before adding the horizontal scrollbar, I added some code that instead of a single column of buttons, adds a grid of buttons:</p>
<pre><code>for i in range(30):
for j in range(30):
new_button = ttk.Button(
master=scrollable_body,
text="Button " + str(i) + ", " + str(j)
)
new_button.grid(
column=j,
row=i
)
</code></pre>
<p>This works exactly as one would expect (of course with no horizontal scrollbar as I haven't added it yet):</p>
<p><a href="https://i.sstatic.net/inME2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/inME2.png" alt="enter image description here" /></a></p>
<p>However, if I modify the <code>Scrollable</code> class to add a horizontal scrollbar like so:</p>
<pre><code>class Scrollable(tk.Frame):
def __init__(self, frame, width=8):
scrollbar_v = tk.Scrollbar(frame, width=width)
scrollbar_v.pack(side=tk.RIGHT, fill=tk.Y, expand=False)
scrollbar_h = tk.Scrollbar(frame, width=width, orient="horizontal")
scrollbar_h.pack(side=tk.BOTTOM, fill=tk.X, expand=False)
self.canvas = tk.Canvas(frame, yscrollcommand=scrollbar_v.set, xscrollcommand=scrollbar_h.set)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar_v.config(command=self.canvas.yview)
scrollbar_h.config(command=self.canvas.xview)
self.canvas.bind('<Configure>', self.__fill_canvas)
tk.Frame.__init__(self, frame)
self.windows_item = self.canvas.create_window(0, 0, window=self, anchor=tk.NW)
def __fill_canvas(self, event):
canvas_width = event.width
canvas_height = event.height
self.canvas.itemconfig(self.windows_item, width=canvas_width)
self.canvas.itemconfig(self.windows_item, height=canvas_height)
def update(self):
self.update_idletasks()
self.canvas.config(scrollregion=self.canvas.bbox(self.windows_item))
</code></pre>
<p>The the buttons are cut off when scrolling:</p>
<p><a href="https://i.sstatic.net/T4HQz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/T4HQz.png" alt="enter image description here" /></a></p>
<p>There are similar questions on SO but they haven't helped.
<a href="https://stackoverflow.com/a/59530435/9976891">This</a> and <a href="https://stackoverflow.com/a/26216359/9976891">this</a> suggest using <code>.grid()</code> method with the <code>sticky=</code> argument, but that didn't work. Changing the part of <code>__init__()</code> that adds the widgets to use <code>.grid()</code> instead of <code>.pack()</code> did not change the outcome whatsoever:</p>
<pre><code>scrollbar_v = tk.Scrollbar(frame, width=width)
scrollbar_v.grid(
column=1,
row=0,
rowspan=2,
sticky=(tk.N, tk.S)
)
scrollbar_h = tk.Scrollbar(frame, width=width, orient="horizontal")
scrollbar_h.grid(
column=0,
row=1,
columnspan=2,
sticky=(tk.W, tk.E)
)
self.canvas = tk.Canvas(frame, yscrollcommand=scrollbar_v.set, xscrollcommand=scrollbar_h.set)
self.canvas.grid(
column=0,
row=0,
sticky=(tk.N, tk.E, tk.S, tk.W)
)
</code></pre>
<p><a href="https://stackoverflow.com/a/33575534/9976891">This</a> and <a href="https://stackoverflow.com/a/17690152/9976891">this</a> suggests the answer may be to do with using <code>self.canvas.config(scrollregion=self.canvas.bbox("all"))</code> instead, but that didn't work either.</p>
<p>I feel the answer may be to do with the line <code>self.windows_item = self.canvas.create_window(0, 0, window=self, anchor=tk.NW)</code>, but I don't understand how that's wrong - I thought the NW anchor would make sure it worked?</p>
|
<python><user-interface><tkinter>
|
2024-02-23 14:14:07
| 2
| 425
|
GMSL
|
78,047,651
| 14,649,310
|
Celery task chain seems to only run first task. How does the Celery chain works?
|
<p>I have an issue which I believe relates to how this method works. I am creating a chain of lets say 300 pretty big tasks with a lot of items to be processed by each task. I create and async run a Celery task of this events like so:</p>
<pre><code>result = chain(*my_tasks).apply_async(ignore_result=True)
</code></pre>
<p>so sometimes it seems to work and all the tasks are executed. But sometimes especially when I have a lot of big tasks to execute, I see in my logs that the first task run and then nothing. The tasks disappear.</p>
<p>I was reading in the docs that the <code>chain()</code> wraps all the individual tasks under one task. How does that work exactly? I am also using RabbitMQ as message broker.</p>
<p>The times that the chain works, I see in my queue a single message appearing and disappearing. As if there is always just on message in the queue and it is picked up and then another one is put there. Is this what Celery does? Or does the first worker who picks up the task form the RabbitMQ queue executes all the tasks inside one after the other?</p>
<p>If the second case is true could that initial worker just fail and then the message disappears? Any clarification on how this chain method works and/or what might be the problem are both greatly appreciated.</p>
|
<python><rabbitmq><celery>
|
2024-02-23 13:12:06
| 1
| 4,999
|
KZiovas
|
78,047,611
| 1,095,202
|
Debugging tips for CMake's failure to find Python (which is on $PATH)
|
<p>I have a Python virtual environment (<code>venv</code> in the project dir) activated, so that <code>which python</code> points to the Python interpreter in this environment. The environment also has NumPy installed.</p>
<p>I also have a CMake build that should link a C library to this Python and the python is search for with</p>
<pre><code>find_package(Python REQUIRED COMPONENTS Interpreter Development NumPy)
</code></pre>
<p>However, CMake somehow manages not to find this interpreter and fails with an incredibly useful message:</p>
<pre><code> Could NOT find Python (missing: Python_EXECUTABLE Python_INCLUDE_DIRS
Python_LIBRARIES Interpreter Development NumPy Development.Module
Development.Embed)
</code></pre>
<p>Does anyone know any useful tips on how to debug this?
I even tried to set <code>-DPython3_EXECUTABLE=<abs-path-to-project-root/venv/bin/python</code> for CMake, but it does not help.
Thanks!</p>
|
<python><cmake>
|
2024-02-23 13:04:58
| 0
| 927
|
Dmitry Kabanov
|
78,047,287
| 4,865,723
|
PyLint --init-hook via subprocess.run() not working (maybe escape problems)
|
<p>I do run <code>pylint</code> in unittests using <code>subprocess.run()</code>.
I need to use <code>--init-hook=</code> feature of <code>pylint</code> to encourage it to find my modules.</p>
<p>I do run this on shell (bash) and it works as expected:</p>
<pre><code>pylint qttools.py --disable=all --enable=E0401 --init-hook="from pathlib import Path; import sys;sys.path.append('./../common');"
</code></pre>
<p>No error E0401 detected.</p>
<p>Now I try to replicate that but using <code>subprocess.run()</code>.</p>
<pre><code>Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import run
>>> cmd = ['pylint', 'qttools.py', '--disable=all', '--enable=E0401']
>>> cmd.append('--init-hook="from pathlib import Path; import sys;sys.path.append(\'./../common\');"')
>>> run(cmd)
************* Module qttools
qttools.py:48:0: E0401: Unable to import 'snapshots' (import-error)
qttools.py:49:0: E0401: Unable to import 'tools' (import-error)
qttools.py:50:0: E0401: Unable to import 'logger' (import-error)
-------------------------------------------------------------------
Your code has been rated at 9.55/10 (previous run: 10.00/10, -0.45)
CompletedProcess(args=['pylint', 'qttools.py', '--disable=all', '--enable=E0401', '--init-hook="from pathlib import Path; import sys;sys.path.append(\'./../common\');"'], returncode=2)
</code></pre>
<p>My assumption is that escaping the <code>'</code> around the <code>common</code> path is a problem. I tried some alternatives (switching <code>'</code> and <code>"</code>; building the string via <code>+</code> operator). The result keeps the same.</p>
<p>Any ideas?</p>
<p>I am aware that I wouldn't need to use <code>--init-hook</code> or <code>sys.path</code> hacks like this if I created a correct and valid Python package out of this repo. I am working on this, but it is 15 year old Python code.</p>
|
<python><pylint>
|
2024-02-23 12:11:41
| 1
| 12,450
|
buhtz
|
78,047,278
| 4,269,851
|
Python transpose dictionary
|
<p>I have</p>
<pre><code>data_dict = {1: {'One': 110, 'Two': 210, 'three': 310},
2: {'One': 120, 'Two': 220, 'three': 320},
3: {'One': 130, 'Two': 230, 'three': 330}}
</code></pre>
<p>need to print as CSV in this order</p>
<pre><code>'',1,2,3
One,110,120,130
Two,210,220,230
Three,310,320,330
</code></pre>
<p>No idea how to do it spent hours trying totally exhausted.
I need pure python solution without using Numpy Transpose, Itertools etc</p>
|
<python><csv><dictionary><transpose>
|
2024-02-23 12:10:30
| 2
| 829
|
Roman Toasov
|
78,047,244
| 651,779
|
How to run piped command with Python subprocess without deadlocking?
|
<p>I have a python script that runs</p>
<pre><code>for cmd in chr_commands:
info("Run: "+cmd)
subprocess.run(cmd)
</code></pre>
<p>Where each cmd is equivalent to</p>
<pre><code>samtools view -F 0x0004 input.bam chr3:0-500000 2>> log.txt |awk 'BEGIN {OFS="\t"} {bpstart=$4; bpend=bpstart; split ($6,a,"[MIDNSHP]"); n=0;\
for (i=1; i in a; i++){\
n+=1+length(a[i]);\
if (substr($6,n,1)=="S"){\
if (bpend==$4)\
bpstart-=a[i];\
else \
bpend+=a[i]; \
}\
else if( (substr($6,n,1)!="I") && (substr($6,n,1)!="H") )\
bpend+=a[i];\
}\
if (($2 % 32)>=16)\
print $3,bpstart,bpend,"-",$1,$10,$11;\
else\
print $3,bpstart,bpend,"+",$1,$10,$11;}' | sort -k1,1 -k2,2n | awk \
'BEGIN{chr_id="NA";bpstart=-1;bpend=-1; fastq_filename="NA";num_records=0;fastq_records="";fastq_record_sep="";record_log_str = ""}\
{ if ( (chr_id!=$1) || (bpstart!=$2) || (bpend!=$3) )\
{\
if (fastq_filename!="NA") {if (num_records < 1000){\
record_log_str = record_log_str chr_id"\t"bpstart"\t"bpend"\t"num_records"\tNA\n"} \
else{print(fastq_records)>fastq_filename;close(fastq_filename); system("gzip -f "fastq_filename); record_log_str = record_log_str chr_id"\t"bpstart"\t"bpend"\t"num_records"\t"fastq_filename".gz\n"} \
}\
chr_id=$1; bpstart=$2; bpend=$3;\
fastq_filename=sprintf("REGION_%s_%s_%s.fastq",$1,$2,$3);\
num_records = 0;\
fastq_records="";\
fastq_record_sep="";\
}\
fastq_records=fastq_records fastq_record_sep "@"$5"\n"$6"\n+\n"$7; \
fastq_record_sep="\n"; \
num_records++; \
} \
END{ \
if (fastq_filename!="NA") {if (num_records < 1000){\
record_log_str = record_log_str chr_id"\t"bpstart"\t"bpend"\t"num_records"\tNA\n"} \
else{printf("%s",fastq_records)>fastq_filename;close(fastq_filename); system("gzip -f "fastq_filename); record_log_str = record_log_str chr_id"\t"bpstart"\t"bpend"\t"num_records"\t"fastq_filename".gz\n"} \
}\
print record_log_str > "chr3.info" \
}'
</code></pre>
<p>There are between 22-1000 of these commands to run. Each cmd should take a few seconds. Initially, it runs as expected, but after 2-5 loops the job starts hanging. It shows 100% CPU in <code>htop</code> but runs indefinitely.</p>
<p>If instead I write all of chr_commands to <code>example.sh</code> and run it from terminal with <code>bash example.sh</code>, it takes less than a minute to complete. I expect something deadlocks, but I don't know how to prevent it.</p>
<p>Originally the code used <code>map_async</code> which ran into the same issue where some jobs finished quickly but others would never stop. I have also tried with <code>, shell=True</code>, <code>subprocess.call</code>, <code>subprocess.Popen</code> with <code>wait()</code>.</p>
<p>Not sure if it makes a difference, but the python code is in a singularity image that I run with Snakemake.</p>
|
<python><subprocess><snakemake><singularity-container>
|
2024-02-23 12:04:24
| 0
| 8,854
|
Niek de Klein
|
78,047,164
| 11,749,309
|
Optimize assigning an index to groups of split data in Polars
|
<h1>SOLVED:</h1>
<h3>Fastest Function: 995x faster than original function</h3>
<pre class="lang-py prettyprint-override"><code>def add_range_index_stack2(data, range_str):
range_str = _range_format(range_str)
df_range_index = (
data.group_by_dynamic(index_column="date", every=range_str, by="symbol")
.agg()
.with_columns(
pl.int_range(0, pl.len()).over("symbol").alias("range_index")
)
)
data = data.join_asof(df_range_index, on="date", by="symbol")
return data
</code></pre>
<h1>OG Question:</h1>
<h2>Data Logic:</h2>
<p>I have a time series that needs to be split into chunks.</p>
<p>Let's say it needs to be split into 3 chunks for this post. The data I am using is stock quote data and daily prices. If the length of the time series data is 3 months, and the 'split' range is 1 month, then there should be 3 chunks of data, each month labeled with increasing integers. So, there should be 3 sections in the time series, all in one data frame. There should be a column named <code>range_index</code> that starts at 0 and iterates until 2. For example, if the data was January-March data, each price quote should be labeled 0, 1, or 2. 0 for January, 1 for February, and 2 for March data.</p>
<p>I would like for this to be done for each symbol in the data frame. The <code>start_date</code> of each symbol may not be the same, so it should be robust in that way, and correctly assign <code>range_index</code> values based on the <code>symbol</code> stock data.</p>
<h2>What I've Done:</h2>
<p>I have built a function using polar logic that adds a column onto this data frame, but I think that there are possibly faster ways to do this. When I add a few symbols with a few years of data, it slows down to about ~3s to execute.</p>
<p>I would love any advice on how to speed up the function, or even a novel approach. I'm aware that row-based operations are slower in polar than columnar. If there are any polars nerds out there that see a glaring issue....please help!</p>
<pre class="lang-py prettyprint-override"><code>def add_range_index(
data: pl.LazyFrame | pl.DataFrame, range_str: str
) -> pl.LazyFrame | pl.DataFrame:
"""
Context: Toolbox || Category: Helpers || Sub-Category: Mandelbrot Channel Helpers || **Command: add_n_range**.
This function is used to add a column to the dataframe that contains the
range grouping for the entire time series.
This function is used in `log_mean()`
""" # noqa: W505
range_str = _range_format(range_str)
if "date" in data.columns:
group_by_args = {
"every": range_str,
"closed": "left",
"include_boundaries": True,
}
if "symbol" in data.columns:
group_by_args["by"] = "symbol"
symbols = (data.select("symbol").unique().count())["symbol"][0]
grouped_data = (
data.lazy()
.set_sorted("date")
.group_by_dynamic("date", **group_by_args)
.agg(
pl.col("adj_close").count().alias("n_obs")
) # using 'adj_close' as the column to sum
)
range_row = grouped_data.with_columns(
pl.arange(0, pl.count()).over("symbol").alias("range_index")
)
## WIP:
# Extract the number of ranges the time series has
# Initialize a new column to store the range index
data = data.with_columns(pl.lit(None).alias("range_index"))
# Loop through each range and add the range index to the original dataframe
for row in range_row.collect().to_dicts():
symbol = row["symbol"]
start_date = row["_lower_boundary"]
end_date = row["_upper_boundary"]
range_index = row["range_index"]
# Apply the conditional logic to each group defined by the 'symbol' column
data = data.with_columns(
pl.when(
(pl.col("date") >= start_date)
& (pl.col("date") < end_date)
& (pl.col("symbol") == symbol)
)
.then(range_index)
.otherwise(pl.col("range_index"))
.over("symbol") # Apply the logic over each 'symbol' group
.alias("range_index")
)
return data
def _range_format(range_str: str) -> str:
"""
Context: Toolbox || Category: Technical || Sub-Category: Mandelbrot Channel Helpers || **Command: _range_format**.
This function formats a range string into a standard format.
The return value is to be passed to `_range_days()`.
Parameters
----------
range_str : str
The range string to format. It should contain a number followed by a
range part. The range part can be 'day', 'week', 'month', 'quarter', or
'year'. The range part can be in singular or plural form and can be
abbreviated. For example, '2 weeks', '2week', '2wks', '2wk', '2w' are
all valid.
Returns
-------
str
The formatted range string. The number is followed by an abbreviation of
the range part ('d' for day, 'w' for week, 'mo' for month, 'q' for
quarter, 'y' for year). For example, '2 weeks' is formatted as '2w'.
Raises
------
RangeFormatError
If an invalid range part is provided.
Notes
-----
This function is used in `log_mean()`
""" # noqa: W505
# Separate the number and range part
num = "".join(filter(str.isdigit, range_str))
# Find the first character after the number in the range string
range_part = next((char for char in range_str if char.isalpha()), None)
# Check if the range part is a valid abbreviation
if range_part not in {"d", "w", "m", "y", "q"}:
msg = f"`{range_str}` could not be formatted; needs to include d, w, m, y, q"
raise HumblDataError(msg)
# If the range part is "m", replace it with "mo" to represent "month"
if range_part == "m":
range_part = "mo"
# Return the formatted range string
return num + range_part
</code></pre>
<h2>Expected Data Form:</h2>
<p><a href="https://i.sstatic.net/eeav6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eeav6.png" alt="Expected Output Data" /></a>
<a href="https://i.sstatic.net/gaN7U.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gaN7U.png" alt="Expected Data Output cont." /></a></p>
<p>The same is done for PCT stock symbol.</p>
|
<python><dataframe><optimization><indexing><python-polars>
|
2024-02-23 11:48:46
| 2
| 373
|
JJ Fantini
|
78,047,106
| 3,362,720
|
In tox What is the difference between setenv, and passenv
|
<p>I setting up tox to be used in my <code>.gitlab-ci.yml</code> in combination with pytest.
I want pytest to run with specific environment that are set in the .gitlab-ci.yml file</p>
<p>In the documentation I found the <code>tox.ini</code> configurations <code>setenv</code> and <code>passenv</code> but I couldn't understand what is the use case for each configuration.</p>
<p>What is the difference? What are the use cases? i.e. when would I want to use setenv over passenv or vice versa?</p>
|
<python><pytest><gitlab-ci><tox>
|
2024-02-23 11:35:55
| 3
| 4,046
|
Ouss
|
78,047,017
| 13,461,081
|
Python package Expiring Dict is not working (automatic expiring)
|
<p>Using the following <a href="https://pypi.org/project/expiringdict/" rel="nofollow noreferrer">package</a> for expiring dictionaries doesn't work. Is there any known deprecation on the package? The GitHub repository seems inactive but the latest release was 1 and half years ago.</p>
<p>If the package is indeed deprecated, is there a well-known replacement?</p>
<pre class="lang-bash prettyprint-override"><code>Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from expiring_dict import ExpiringDict
>>> denms = ExpiringDict(max_age_seconds=3)
>>> denms["john"] = "doe"
>>> import time
>>> time.sleep(10)
>>> print(list(denms.items()))
[('max_age_seconds', 3), ('john', 'doe')]
</code></pre>
|
<python><dictionary><time><python-3.10>
|
2024-02-23 11:18:42
| 1
| 916
|
André Clérigo
|
78,046,927
| 7,418,045
|
TypeError: 'NoneType' object is not a mapping
|
<p>I am trying to concatenate two dictionaries, and I am getting this error:</p>
<pre><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 5
3 dict_list = [{"a":1}, None, {"b":2}]
4 n = len(dict_list)
----> 5 [{"a": 1, "b": 2, **dict_list[idx]} for idx in range(n)]
Cell In[3], line 5
3 dict_list = [{"a":1}, None, {"b":2}]
4 n = len(dict_list)
----> 5 [{"a": 1, "b": 2, **dict_list[idx]} for idx in range(n)]
TypeError: 'NoneType' object is not a mapping
</code></pre>
<p>This is the code:</p>
<pre><code>import random
# list of dictionaries:
dict_list = [{"a":1}, None, {"b":2}]
n = len(dict_list)
[{"a": 1, "b": 2, **dict_list[idx]} for idx in range(n)]
</code></pre>
<p>What is wrong? Why am I getting this error?</p>
|
<python><dictionary>
|
2024-02-23 11:02:16
| 1
| 743
|
Anmol Deep
|
78,046,895
| 12,415,855
|
Read detailed style of paragraph in docx-file?
|
<p>i try to read a doxc-file using python-docx paragraph by paragraph using the following code:</p>
<pre><code>for p in document.paragraphs:
wStyleName = p.style.name
wText = p.text
</code></pre>
<p>My problem is that i can´t distinguish between a "normal" paragraph and a paragraph where there is also a list numbering.</p>
<p>In both cases the output for the p.style.name is "Normal"</p>
<p>I there any way how i can distiguish between a "normal" paragraph and a "special" paragraph (like List Number, List Bullet, Intense Quote, etc)?</p>
<p>(when creating a paragraph i can set this with the following code - but i would need it to get the info when reading a docx-file)</p>
<pre><code>document.add\_paragraph('Intense quote', style='Intense Quote')
document.add\_paragraph('first item in unordered list', style='List Bullet')
document.add\_paragraph('first item in ordered list', style='List Number')
</code></pre>
|
<python><docx><python-docx>
|
2024-02-23 10:57:14
| 0
| 1,515
|
Rapid1898
|
78,046,821
| 5,021,819
|
Is is possible to get the last file updated in folder and subfolder with specifique name in artifactory?
|
<p>I'm looking to find a solution how I can get the path of the last file updated with name "name_file" in specifique folder and subfolder in artifactory directory.
From documentation, I see this link <a href="https://jfrog.com/help/r/jfrog-rest-apis/get-last-modified-item" rel="nofollow noreferrer">https://jfrog.com/help/r/jfrog-rest-apis/get-last-modified-item</a> but I can't specify the file name as in my root folder I can have a lot of files the same name in the differents subfolders.</p>
<p>Thanks</p>
|
<python><shell><curl><artifactory>
|
2024-02-23 10:47:47
| 1
| 312
|
Younes Ben Tlili
|
78,046,777
| 4,269,851
|
Python function to filter data from array
|
<p>I have made function to loop trough array and filter the results.</p>
<pre><code>def filter_data(data, match_d=None, trim_matches=False):
result_matches = {} # stores matched
result_unmatches = {} # stores not matched
# loop every record in data
for key, value in data.items():
# match record with filter criteria
for search_string, search_key_name in match_d.items():
if search_string == value[search_key_name]:
result_matches[key] = value
else:
result_unmatches[key] = value
if trim_matches is False: # return only matches
return result_matches
else: # return all but matches
return result_unmatches
data_dict = {0: {'name': 'one'},
1: {'name': 'two'},
2: {'name': 'three'},
3: {'name': 'four'},
4: {'name': 'five'}}
result = filter_data(data_dict,
match_d={'one': 'name', 'two': 'name'},
trim_matches=True)
print(result)
#returns: {0: {'name': 'one'}, 1: {'name': 'two'}, 2: {'name': 'three'}, 3: {'name': 'four'}, 4: {'name': 'five'}}
#expected {2: {'name': 'three'}, 3: {'name': 'four'}, 4: {'name': 'five'}}
</code></pre>
<p>When i use <code>trim_matches=False</code> in function call it works as expected, however when i use <code>trim_matches=True</code> it does not.</p>
<p>Reason it's looping the key trough every match and then records in both lists <code>result_matches</code> and <code>result_unmatches</code>, however i cant find an easy fix for it.</p>
<p>I could simply write <code>result_matches</code> then compare the <code>data</code> and remove matches from data when using <code>trim_matches=True</code>, but i dont want to add more code to function.</p>
<p><strong>Solution i am looking for</strong> is to make this current function work somehow with as little additional code as possible. in other words i want this logic to work rather than add more lines of code to this function and change it in any way.</p>
<p><strong>Alternative solution</strong> rewrite full function code and logic, but should be less code than currently used.</p>
<p>No includes allowed only pure Python.</p>
<p><strong>Edit:</strong> Realizing that debugging was difficult i went ahead and colored and spaced the output, now its easy to see what's going on.</p>
<p><a href="https://i.sstatic.net/85BSK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/85BSK.png" alt="enter image description here" /></a></p>
|
<python><loops><filter>
|
2024-02-23 10:39:44
| 1
| 829
|
Roman Toasov
|
78,046,758
| 7,364,381
|
Conda installation failed on Ubuntu 22.04
|
<p>Conda installation failing on WSL Ubuntu 22.04 because of following:</p>
<blockquote>
<p>anaconda.sh: line 353: bunzip2: command not found</p>
</blockquote>
<p>Couldn't find bunzip2 package:</p>
<p><code>sudo apt-get install bunzip2</code> gives</p>
<blockquote>
<p>E: Unable to locate package bunzip2.</p>
</blockquote>
<p>Any suggestions?</p>
|
<python><ubuntu><conda>
|
2024-02-23 10:37:44
| 1
| 713
|
Sukhmeet Sethi
|
78,046,656
| 8,068,825
|
Pandas - Generate multiple rows and multiple columns from pandas DataFrame where column is lists
|
<p>So I have this dataframe that's formatted messily. The columns are <code>messages</code> and <code>url</code>, <code>url</code> is the URL to download the audio file associated with the row and <code>messages</code> is the conversation transcribed between 2 people. So for example:</p>
<pre><code>[{'role': 'A',
'message': 'Hello? Who is this?'},
{'role': 'B'
'message': "Hey, Belinda. This is Kurt Lou. Hope I'm honored to trouble for calling you today."},
{'role': 'A',
'message': "Alright, Curt. You've got me on the line now. What is this about?"}]
</code></pre>
<p>this is an example of a single row of <code>messages</code> column. So a row in the table could look like</p>
<pre><code>messages | url
<list from above> | <some url>
</code></pre>
<p>I'm trying to create a new DataFrame where each row has <code>message</code>, <code>prev_message</code> and <code>url</code> the above example would generate the follow rows and columns.</p>
<pre><code>message | prev_message | url
Hello? Who is this? | <None cause no prev message> | <url from `url` column>
Hey, Belinda. This is Kurt Lou. Hope I'm honored to trouble for calling you today. | Hello? Who is this? | <url from `url` column>
Alright, Curt. You've got me on the line now. What is this about? | Hey, Belinda. This is Kurt Lou. Hope I'm honored to trouble for calling you today. | <url from `url` column>
</code></pre>
<p>So each row is the message, the message that comes before it and the URL to the audio file associated with this conversation. I have this current code to do this:</p>
<pre><code>import ast
def process_data_w_audio(df: pd.DataFrame):
msg_list = list()
bot_list = list()
audio_fps = list()
for _, row in df.iterrows():
messages_list = ast.literal_eval(row["messages"]) # cause list is string when reading from CSV
url = row["url"]
for i, msg_dict in enumerate(messages_list):
msg_list.append(msg_dict["message"].strip())
if i > 0:
bot_list.append(messages_list[i - 1]["message"].strip())
audio_fps.append(url)
return pd.DataFrame({"message": msg_list, "prev_message": bot_list, "audio_fp": audio_fps})
</code></pre>
<p>The issue with this is that it's painfully slow it could take 5 hours just to go over 20k rows. How can I do this way faster?</p>
|
<python><pandas>
|
2024-02-23 10:18:45
| 1
| 733
|
Gooby
|
78,046,643
| 3,813,424
|
Regex pattern no working in Python but on RegExr?
|
<p>From the strings in <code>data</code>, I'm trying to capture "FUND", respectively "FUND*", "Total", and "Rest" in a first group, the following thereafter floating point number, including its prefixed sign, in a second group, and the contents between the parenthesis or brackets in a third group with my regex <code>pattern</code> in Python 3.</p>
<pre class="lang-py prettyprint-override"><code>import re
if __name__ == "__main__":
data = [
" - 🏊♂️ FUND +145.00 [🎁 2 reached]",
" - 🖋 FUND* +25.00 (⟶ Mar. 75.00/300)",
" - 👕 FUND +17.49 (⟶ Apr. 300.00)",
" - 🔦 FUND +36.21 (⟶ May 250.00)",
" - 🚗 FUND +150.00 (⟶ Jul. 1500.00)",
" - 👓 FUND +115.00 (⟶ Sep. 1000.00)",
" - ✒️ FUND +11.30",
" ----------------",
" Total 500.00",
" Rest 0.00"
]
pattern = r"(\w+)\s+([-+]?\d*\.?\d+)\s?([:\(\[].+[:\)\]])?"
for d in data:
match = re.match(pattern, d)
print(match)
</code></pre>
<p>I've tested the <code>pattern</code> on RegExr with the exact same data, and it works fine on the website. However, in Python <code>match</code> is always <code>None</code>?</p>
<p>Do I need to escape some characters in the <code>pattern</code> that I'm unaware of?</p>
|
<python><python-re>
|
2024-02-23 10:17:41
| 1
| 319
|
St4rb0y
|
78,046,500
| 583,464
|
apply to pandas columns doesn't give the correct results
|
<p>I have <a href="https://easyupload.io/d8g1dz" rel="nofollow noreferrer">this file</a>.</p>
<p>If I read it and do some clean up with regex:</p>
<pre><code>import pandas as pd
import re
df = pd.read_csv('data.csv', index_col=[0])
out = df[['X', 'Y']].apply(lambda s: s.str.extract(r'([a-z\d]+\.[a-z\d]+)',
expand=False,flags=re.I).str.replace(r'[^\d.]+', '', regex=True))
out.index+=1
out
</code></pre>
<p>I can see these results:</p>
<pre><code> X Y
2 NaN NaN
3 NaN NaN
4 573456.81 3887265.85
5 573453.26 NaN
6 573450.98 NaN
7 NaN NaN
8 NaN NaN
9 573445.167 3887284.597
10 NaN NaN
11 NaN NaN
12 573703.6758759461 3887233.5301764384
....
</code></pre>
<p>which contains <code>NaN</code> values instead of applying the cleaning.</p>
<p>The weird is that the cleaning works because If I just copy the contents of the dataframe I loaded into a list:</p>
<pre><code>thelist = [['1', '573436.862', '3887259.269'],
['2', '573436.031', '3887248.472'],
['3', '573456.81', '3887265.85'],
['4', '573453.26', '3887273.017'],
['5', '573450.98', '3887275.878'],
['6', '573451.611', '3887276.346'],
['7', '573446.959', '3887285.738'],
['8', 'H5m7er3o4m45h.n1i6a7 print: 19/02/202', '4 15:24 3887284.597'],
['9', '573440.184', '3887292.487'],
['10', '573436.862', '3887259.269'],
['1', '573703.6758759461', '3887233.5301764384'],
['2', '573703.7165950707', '3887233.6523487056'],
['3', '573703.769', '3887233.809'],
['4', '573707.305', '3887241.398'],
['5', '573712.9489897437', '3887251.2139821625'],
['6', '57mro3m71hn2ia.949print: 19/02/2024', '15:22 3887251.2139999997'],
['7', '573712.981495283', '3887251.2813396226'],
['8', '573713H.0m3e2romhnia print: 19/0', '2/2024 15:24 3887251.386'],
['9', '573713.096', '3887251.567'],
['10', '573713.0960000466', '3887251.5670001707'],
['11', '573713.266443923', '3887252.1920684506'],
['12', '573725.815', '3887254.127'],
['13', '573733.267', '3887255.275'],
['14', '573736.197', '3887240.846'],
['15', '573742.399', '3887229.682'],
['16', '573701.647', '3887220.061'],
['17', '573703.6758759461', '3887233.5301764384']]
</code></pre>
<p>and apply the cleaning:</p>
<pre><code>arr = np.hstack(thelist)
arr = arr.reshape(arr.shape[0] // 3, 3)
new_df = pd.DataFrame(arr, columns=['K', 'X', 'Y'])
out = new_df[['X', 'Y']].apply(lambda s: s.str.extract(r'([a-z\d]+\.[a-z\d]+)',
expand=False, flags=re.I)
.str.replace(r'[^\d.]+', '', regex=True))
</code></pre>
<p>I receive the correct results!</p>
<pre><code> X Y
0 573436.862 3887259.269
1 573436.031 3887248.472
2 573456.81 3887265.85
3 573453.26 3887273.017
4 573450.98 3887275.878
5 573451.611 3887276.346
6 573446.959 3887285.738
7 573445.167 3887284.597
8 573440.184 3887292.487
9 573436.862 3887259.269
10 573703.6758759461 3887233.5301764384
11 573703.7165950707 3887233.6523487056
12 573703.769 3887233.809
13 573707.305 3887241.398
....
</code></pre>
|
<python><pandas><dataframe><list><csv>
|
2024-02-23 09:55:19
| 1
| 5,751
|
George
|
78,046,370
| 15,803,668
|
How to Find Text Coordinates for a Given Character Range in a PDF using PyMuPDF?
|
<p>I am working on a project where I want to extract text coordinates for a specific character range within a PDF document using <code>PyMuPDF</code>. I have a PDF file and a character range defined by the start and end indices. I want to locate the exact position (coordinates) of the text within this character range on the PDF.</p>
<p>An example: The text of the pdf is:</p>
<blockquote>
<p>Erste Verordnung zum Sprengstoffgesetz in der Fassung der Bekanntmachung vom 31. Januar 1991 (BGBl. I S. 169), die zuletzt durch Artikel 1 der Verordnung vom 20. Dezember 2021 (BGBl. I S. 5238) geändert worden ist. Das Sprengstoffgesetz ist anzuwenden.</p>
</blockquote>
<p>I have the character range from <code>21 to 38</code>, which in this case represents the phrase <code>Sprengstoffgesetz</code>. I tried using the <code>search_for</code> function, but it gives me all instances of the term, not just the term in the character range.</p>
<p>Furthermore, the character range might not be a full for word, but only a part. For example the range from <code>32 to 38</code>, which represents just the part <code>gesetz</code>.</p>
<p>Is there a way to find the coordinates of the given range.</p>
|
<python><pymupdf>
|
2024-02-23 09:31:16
| 1
| 453
|
Mazze
|
78,046,217
| 13,944,524
|
My custom object is not deepcopied when it is used as the default parameter in Pydantic models
|
<p>I know that Pydantic creates a deepcopy of mutable objects for "<em>every new instances</em>" that we create, if they are placed in the default values.</p>
<p>It holds true for my <code>lst</code> field, but not for my custom object <code>item</code>. (The code for <code>__deepcopy__</code> is taken from <a href="https://stackoverflow.com/a/15774013/13944524">here</a>)</p>
<pre class="lang-py prettyprint-override"><code>from copy import deepcopy
from typing import Self
from pydantic import BaseModel, ConfigDict
class Spam:
def __init__(self) -> None:
self.names = ["hi"]
def __deepcopy__(self, memo: dict) -> Self:
print("deepcopy called")
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo))
return result
class Person(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
item: Spam = Spam()
lst: list = []
print("-----------------------------------")
obj1 = Person()
obj2 = Person()
obj1.lst.append(10)
obj1.item.names.append("bye")
print(obj1.lst)
print(obj1.item.names)
print(obj2.lst)
print(obj2.item.names)
print(id(obj1.item) == id(obj2.item))
</code></pre>
<p>output:</p>
<pre class="lang-none prettyprint-override"><code>deepcopy called
-----------------------------------
[10]
['hi', 'bye']
[]
['hi', 'bye']
True
</code></pre>
<p>I printed the dashed-line after creating the class and before any instantiation just to show that the deepcopy of my object is indeed happened in class creation which is in contrast to the <a href="https://docs.pydantic.dev/latest/concepts/models/#fields-with-non-hashable-default-values" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p>Pydantic will deepcopy the default value when creating each instance of the model</p>
</blockquote>
<p>Do I miss something here?</p>
|
<python><python-3.x><pydantic>
|
2024-02-23 09:00:36
| 1
| 17,004
|
S.B
|
78,046,145
| 298,847
|
Why can't an attribute have the same name as a class if its type is a union and uses a default value?
|
<p>There seems to be some ambiguity in how the use of <code>|</code> in attribute type annotations together with attribute default values is parsed. Leading to the following error:</p>
<pre><code>>>> class A: pass
...
>>> class B:
... A: A | None = None
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in B
TypeError: unsupported operand type(s) for |: 'NoneType' and 'NoneType'
</code></pre>
<p>If we rename the class <code>A</code> to something else it works.</p>
<p>Why does this not parse correctly?</p>
|
<python><python-typing>
|
2024-02-23 08:47:05
| 2
| 9,059
|
tibbe
|
78,046,131
| 1,534,638
|
How to fix smtp connection issue in mail sending?
|
<p>In my erpnext application I need to send bulk email and I am using <code>smtp.gmail.com</code>.
The number vary up to 1000. I can see system can send around 100 email successfully and then getting <strong>Invalid Outgoing Mail Server or Port</strong>. Further deep diving I can see mail exception in smtp login and message is: <strong>Connection unexpectedly closed</strong> from <a href="https://github.com/frappe/frappe/blob/version-13/frappe/email/smtp.py#L267" rel="nofollow noreferrer">frappe SMTP</a></p>
<p>Problem found only in server (dev, live) but works fine in my local machine.</p>
<p>Following mail sending code is running inside a <code>for loop</code>.</p>
<pre><code>frappe.enqueue(
queue="short",
method=frappe.sendmail,
recipients=get_recipients(context.get('email')),
sender=info@example.com,
subject=frappe.render_template(
email_template.subject, context),
message=message,
now=False,
)
</code></pre>
|
<python><smtp><erpnext><frappe>
|
2024-02-23 08:44:16
| 0
| 3,839
|
hizbul25
|
78,045,657
| 14,897,644
|
LSTM forecasting horizontal line with standardized datas
|
<p>I’ve seen many topics about the problem I have in my situation but nothing help.
I am trying to make a forecast on a stock price with a Bidirectional LSTM.
My problem here is that the forecast on test datas looks like almost horizontal during the whole period.
My data are standardized, and I tried to increase the number of epochs (actual is 300, but I tried 2000 and i got only nan values in prediction which seems to be caused by Exploding gradents).
Can you explain me if I made something wrong in my code ? I’ve been working on this since a week and cannot understand where am I wrong.</p>
<p>Thanks you a lot !!!</p>
<p>My code and final output :</p>
<pre><code>!pip install yfinance
For reading stock data from yahoo
from pandas_datareader.data import DataReader
import yfinance as yf
import pandas as pd
import numpy as np
For time stamps
from datetime import datetime,timedelta
import matplotlib.pyplot as plt
import seaborn as sns
end = datetime.now()
print (‘end’,end)
start = “1900-01-01”
print(start)
print (‘start’,start)
globals()[‘SGO’] = yf.download(‘SGO.PA’, start, end,progress=False)
globals()[‘SGO’]=globals()[‘SGO’].filter([‘Close’])
symbols=‘SGO’
dic_train_len={}
data_array={}
data_array[symbols] = globals()[symbols].values
dic_train_len[symbols] = int(np.ceil( len(data_array[symbols]) * .90))
from sklearn.preprocessing import StandardScaler
Créer un dictionnaire pour stocker les scalers
dictio_scalers = {}
Fonction pour scaler un ensemble de données et conserver l’objet scaler
def scale_data(nom_symbole, dataset):
scaler = StandardScaler()
scaled_data = scaler.fit_transform(dataset)
dictio_scalers[nom_symbole] = scaler
return scaled_data
dictio_scaled_values = {}
dataset = globals()[‘SGO’].values
dictio_scaled_values[‘SGO’] = scale_data(‘SGO’, data_array[‘SGO’])
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import Dense, LSTM , Bidirectional
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping
def preparation_train(df_scaled,pas,train_len):
train_data = df_scaled[0:int(train_len)]
# Split the data into x_train and y_train data sets
x_train = []
y_train = []
for i in range(window_size, len(train_data)):
x_train.append(train_data[i-window_size:i, 0])
y_train.append(train_data[i, 0])
# Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
# Reshape the data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
return x_train,y_train
def preparation_test(df_scaled,pas,train_len):
# Create the data sets x_test and y_test
df_test= df_scaled[train_len:, :]
x_test = []
y_test = []
for i in range(pas, len(df_test)):
x_test.append(df_test[i-pas:i, 0])
y_test.append(df_test[i, 0])
Convert the x_test and y_test to numpy arrays
x_test, y_test = np.array(x_test), np.array(y_test)
# Reshape the data
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
return x_test,y_test
def create_model(pas):
model = Sequential()
model.add(Bidirectional(LSTM(units=128, activation=‘relu’, input_shape=(pas,
1),return_sequences=True)))
model.add(Bidirectional(LSTM(units=64, activation=‘relu’,return_sequences=True)))
model.add(Bidirectional(LSTM(units=32, activation=‘relu’)))
model.add(Dense(1))
return model
epochs = 300
batch_size = 256
window_size=60
model = create_model(window_size)
model.compile(optimizer=‘adam’, loss=‘mean_squared_error’)
x_train,y_train = preparation_train(dictio_scaled_values[‘SGO’],window_size,dic_train_len[‘SGO’])
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,verbose=1)
fichier_modele = “SGO.h5”
model.save(fichier_modele)
from keras.models import load_model
def Backtesting_real(df,symbols,train_len,pas):
Pred_Array_Global=df[int(train_len)-pas:int(train_len)]
test=df[train_len:]
# Get the models predicted price values
fichier_modele = f"{symbols}.h5"
model = load_model(fichier_modele)
scaler2=dictio_scalers[symbols]
Pred_Array_Global=scaler2.fit_transform(Pred_Array_Global)
for i in range(0,len(test)):
Pred_Array_Global=np.array(Pred_Array_Global)
Pred_Array=Pred_Array_Global[i:i+pas]
# Convert the data to a numpy array
Pred_Array = np.array(Pred_Array)
# Reshape the data
Pred_Array_Input = np.reshape(Pred_Array,(1,pas, 1 ))
predictions = model.predict(Pred_Array_Input,verbose=0)
Pred_Array_Global=np.append(Pred_Array_Global,predictions)
Pred_Array_Global=Pred_Array_Global.reshape(-1,1)
#pdb.set_trace()
Pred_Array_Global2 = scaler2.inverse_transform(Pred_Array_Global)
Pred_Array_Global2=Pred_Array_Global2[pas:]
rmse = np.sqrt(np.mean(((Pred_Array_Global2 - test) ** 2)))
print("RMSE de l'action",symbols,":", rmse)
test_data={}
test_data['Predictions'] = Pred_Array_Global2
test_data['Close']=test
#pdb.set_trace()
# Visualize the data
plt.figure(figsize=(16,6))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
for k, v in test_data.items():
plt.plot(range(1, len(v) + 1), v, '.-', label=k)
plt.legend([ 'Predictions','Close'], loc='lower right')
plt.savefig(f"Backtesting {symbols}.png")
Backtesting_real(data_array[‘SGO’],‘SGO’,dic_train_len[‘SGO’],60)
</code></pre>
<p><a href="https://i.sstatic.net/Tupjd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Tupjd.png" alt="enter image description here" /></a></p>
|
<python><tensorflow><keras><time-series><lstm>
|
2024-02-23 06:58:15
| 0
| 417
|
Rgrvkfer
|
78,045,588
| 9,983,652
|
Invalid argument when saving pickle file
|
<p>I am trying to save my machine learning model into a pickle file:</p>
<pre class="lang-py prettyprint-override"><code>rf_pickle_path=os.path.join(os.getcwd(),"penguin_ml\random_forest_penguin.pickle")
rf_pickle = open(rf_pickle_path, "wb")
pickle.dump(rfc, rf_pickle)
rf_pickle.close()
</code></pre>
<p>But I got the error below:</p>
<pre><code>File "c:\Python_Sync\penguin_ml\penguins_ml.py", line 39, in <module>
rf_pickle = open(rf_pickle_path, "wb")
OSError: [Errno 22] Invalid argument: 'C:\\Python_Sync\\penguin_ml\random_forest_penguin.pickle'
</code></pre>
<p>Not sure why? Thanks for helping.</p>
|
<python>
|
2024-02-23 06:39:03
| 2
| 4,338
|
roudan
|
78,045,569
| 6,521,116
|
How to get variable from browser context in Selenium and stop breakpoint after getting it?
|
<p>In the browser's devtools, I've make one XHR breakpoint, when the page do XHR, it will pause at the breakpoint. Then I can print some variable in the console. But when I access the same variable with selenium it throw the variable is not defind.</p>
<p>Is it possible to access the same context of the devtools's console in selenium.</p>
<p>From the console:</p>
<pre><code>t
Object { type: "POST", data: '{"comm":{"cv":4747474,"ct
</code></pre>
<p>From the selenium:</p>
<pre><code>dirver.execute_script('''console.log(t)''')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Programs\python\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 884, in execute_script
return self.execute(command, {
^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Programs\python\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 430, in execute
self.error_handler.check_response(response)
File "D:\Programs\python\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: ReferenceError: t is not defined
</code></pre>
<p>I've another question, for now i need to manual open the devtools and manually set breakpoint after the selenium open the page. Is it possible do make it with selenium? I've search a lot, but with no result.</p>
|
<python><selenium-webdriver><devtools>
|
2024-02-23 06:33:21
| 1
| 28,702
|
LF-DevJourney
|
78,045,495
| 5,560,365
|
How can I run python -m http.server in Visual Studio Code?
|
<p>I am just starting to learn Python and I'm using VS Code.</p>
<p>First of all, how does one open a python terminal without running a python script? "Terminal > New Terminal" opens a new Powershell terminal. The plus in the terminal has no option for opening a Python terminal.</p>
<p>The bigger problem: I am learning Python using VS Code and need to use the python webserver but receive "python not found" error. Python is installed and I've added the Python extension in VS Code. I have a workspace and I've created my python environment (venv). I know the python terminal command to run a webserver is python -m http.server 8000. Yet when I run the command I receive "Python not found." I've done this before so clearly there's something else I'm not understanding.</p>
<p>Awhile back I created a workspace in VS Code for something else and created a python environment (venv). Somehow back then I was able to run python -m http.server 8000 from python terminal to start a webserver. To try and solve my current problem, I went back to that workspace, and sure enough I can still run the command from the python terminal that opened with it there. Confused why one terminal works and another doesn't, I opened a new python terminal (the only way I know how, running a python script by clicking the "run python file" play button). A new python terminal opens and there's my little hello world script. I try to run python -m http.server 8000 from there and I get the same "python not found" message as in my other workspace.</p>
<p>What am I missing? How do I have one terminal that can run the command and another that can't? And how do I open python terminals without having to run a python script?</p>
<p>VS Code installed. Python installed. Python Extension installed to VS Code. Opened workspace folder, created python environment (pointed it my python.exe). Ran a "hello world" python script to get a python terminal. Ran python -m http.server 8000 from the terminal and get "Python not found."</p>
|
<python><visual-studio-code><terminal>
|
2024-02-23 06:09:53
| 1
| 333
|
Brad
|
78,045,211
| 2,593,383
|
What type can be used with annotations which won't affect static type checkers
|
<p>I'd like to use Python (3.12) type annotations at runtime for my own purposes that have nothing to do with variable typing. The syntax is very convenient for adding metadata to variables.</p>
<p>So I'd like to annotate with a type that won't affect any static type analysis that may also be occurring. The annotation <a href="https://peps.python.org/pep-0593/" rel="nofollow noreferrer">PEPs</a> make reference to uses like mine (i.e., using annotations for things other than static type analysis), and in particular <a href="https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated" rel="nofollow noreferrer"><code>Annotated</code></a> is close to what I need. The problem is that I'd like to skip the first argument to <code>Annotated</code> since I don't actually want to associate a type with an object—I just want to associate metadata.</p>
<p>Is there a type (or can one be built) that won't alter static type analysis? I know <code>Any</code> is a reasonable choice, but that changes static type analysis. For example, <a href="https://github.com/microsoft/pyright" rel="nofollow noreferrer">Pyright</a> assigns variables with no type annotation the type <code>Unknown</code> (not <code>Any</code>).</p>
|
<python><python-typing><pyright>
|
2024-02-23 04:40:18
| 2
| 3,593
|
nonagon
|
78,044,990
| 716,255
|
How does a list slice itself?
|
<p>Maybe the <strong>I am new to python</strong> was lost on many of you.
The code below returns 8. Why?</p>
<pre><code>numbers = [2,3,5,8]
print(numbers[numbers[1]])
</code></pre>
<p>When working with slicers, I would expect to see:</p>
<pre><code>print(numbers[:]) = [2,3,5,8]
or
print(numbers[:-1]) = [2,3,5]
</code></pre>
<p>I have never seen something like this:</p>
<pre><code> print(numbers[numbers[1]])
</code></pre>
<p>Is the list <em>numbers</em> slicing itself? And if yes, how is it doing it?</p>
|
<python><list>
|
2024-02-23 03:09:00
| 2
| 451
|
user716255
|
78,044,982
| 8,968,910
|
Python: remove unicode from dataframe
|
<p>I will use a simple dataframe as an example:</p>
<pre><code>data = {'A': ['公司\u3000', 'aaaa\uf505'], 'B': ['1', '2']}
df = pd.DataFrame(data)
print(df)
A B
0 公司 1
1 aaaa 2
</code></pre>
<p>I want to remove unicode like '\u3000', '\uf505' from column A, however, there are more unicodes in it that I may not know. So it's not very ideal to use remove method for me. Some rows has Mandarin characters and I have to keep them.</p>
<p>It also did not work when I tried to split '\'</p>
<pre><code>df=df[~df['A'].str.contains(r'\\')]
</code></pre>
<p>My expected result:</p>
<pre><code> A B
0 公司 1
1 aaaa 2
</code></pre>
|
<python><pandas><unicode>
|
2024-02-23 03:06:14
| 2
| 699
|
Lara19
|
78,044,956
| 19,787,814
|
How to convert a Flask simple app to an EXE file (The Flask app is in a PyQt app)?
|
<p>Let's assume I have an <code>app.py</code> file (which is basically a Flask app containing routes and simple methods), this file imports/requires a db_manager.py (a file that handles the database queries and..)</p>
<p>Finally, I am using PyQt5 to make the app running in a desktop application-like app.</p>
<p>When I run the pyqt.py (which is the app I'm running the flask app in) it works greatly!</p>
<p>Here is a code snippet for the pyqt app:</p>
<pre><code>import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl
from threading import Thread
from app import app as flask_app # Import the Flask app
class WebAppWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Flask App in PyQt5')
self.setCentralWidget(QWebEngineView())
self.showMaximized()
self.start_flask_app()
url = QUrl('http://localhost:5000')
self.centralWidget().load(url)
def start_flask_app(self):
flask_thread = Thread(target=flask_app.run, kwargs={'host': 'localhost', 'port': 5000})
flask_thread.daemon = True
flask_thread.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = WebAppWindow()
sys.exit(app.exec_())
</code></pre>
<p>this approach made my flask app look like a desktop app yes, but I want it to package my full app/folder into a .exe file (one file) with no problems when running it!</p>
<p>I appreciate your help.</p>
|
<python><flask><pyqt>
|
2024-02-23 02:48:32
| 1
| 460
|
Nova
|
78,044,949
| 2,195,440
|
Resolving LinkError with jupyter_latex_envs Post-Link Script Failure in Conda
|
<p>I'm encountering a LinkError when trying to install jupyter_latex_envs via conda in my conda environment. The post-link script fails, and it seems related to an issue with type annotations in Python 3.11. Here's the error message:</p>
<pre><code>LinkError: post-link script failed for package conda-forge::jupyter_latex_envs-1.4.6-pyhd8ed1ab_1002
location of failed script: /Users/xxxx/conda/anaconda3/envs/aws-generative-models-env/bin/.jupyter_latex_envs-post-link.sh
==> script messages <==
Traceback (most recent call last):
...
TypeError: type 'List' is not subscriptable
</code></pre>
<p>It seems like the issue is related to the List type not being subscriptable, which might be due to compatibility issues with Python 3.11 used in my environment.</p>
<p>Has anyone faced a similar issue or can offer insights on how to resolve this error? Specifically, I'm looking for a way to successfully complete the post-link script for jupyter_latex_envs without downgrading from Python 3.11, if possible.</p>
<p>Any advice or guidance would be greatly appreciated. Thank you!</p>
|
<python><jupyter-notebook><conda><ipython><python-3.11>
|
2024-02-23 02:45:23
| 0
| 3,657
|
Exploring
|
78,044,770
| 1,383,511
|
How to have many print statements in a project but selectively choose what prints?
|
<p>I am looking for something similar to how logcat works for android development.
In android dev when you are printing to the terminal/logging, the function you call takes a tag and the message to print. That tag can then be used in the logcat terminal to filter what output you see.</p>
<p>Is there something similar(in-built/library/module/script) in python where at the start of a program you can give a set of tags that should print and any print statements with tags not in the set do not get printed?</p>
<p>I have looked at the in built logging and log level stuff that python provides and I don't think it has what I need but maybe someone else could enlighten me to what I don't see.</p>
<p>As a quick example, something like this:</p>
<pre><code>class TagLog():
tag_set = set()
def log(tag, logMsg):
if isinstance(tag, str) and isinstance(logMsg, str):
if tag in TagLog.tag_set:
print(logMsg)
def add_tag(tag):
if isinstance(tag, str):
TagLog.tag_set.add(tag)
def add_set(tag_set):
if isinstance(tag_set, set):
TagLog.tag_set.update(tag_set)
def remove_tag(tag):
if isinstance(tag, str):
TagLog.tag_set.discard(tag)
</code></pre>
|
<python>
|
2024-02-23 01:26:03
| 1
| 516
|
NDEthos
|
78,044,690
| 93,910
|
How to evaluate an expression in a pandas df that finds the greater of two variables?
|
<p>I want to do compute a value that is the maximum of two columns, as follows:</p>
<pre><code>df = pd.DataFrame( {'a':[1,3,5],
'b':[6,4,2] } )
df['c'] = df.eval('maximum(a,b)')
</code></pre>
<p>I am getting 'ValueError: "maximum" is not a supported function'. This is true even when I use <code>engine='python'</code>. Surprising because <code>maximum</code> is a <code>ufunc</code>. The exact computation required must be provided as an external string.
How should I proceed?</p>
<pre><code>eval('maximum(df.a, df.b)')
</code></pre>
<p>does work fine, but I'd rather not do this for readability reasons.</p>
|
<python><pandas><eval>
|
2024-02-23 00:47:36
| 3
| 7,056
|
Sanjay Manohar
|
78,044,556
| 5,038,019
|
What is the correct Splitting of Audio Stream (ByteArray) in python the 2nd file (2nd chunk) is corrupt
|
<p>I did an test implementation to receive an audio stream over an websocket connection
than i buffer and always after 2seconds i would like to save the audio into a file.</p>
<p>For the first chunk that is working well. But for the second and all following chunks the audio files have no sound. I guess its because of the way i am splitting the audio stream into chunks. But I am not sure maybe its something completly different.
Here is the test code i used:</p>
<pre><code>import asyncio
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
app = FastAPI()
async def transcribe_chunk(audio_chunk, filename: str):
print("filename:", filename)
with open('audio_chunk' + filename + '.wav', 'wb') as f:
print("audio_chunk size:", len(audio_chunk))
f.write(audio_chunk)
@app.websocket("/audio")
async def websocket_endpoint(websocket: WebSocket, token: str):
await websocket.accept()
audio_buffer = bytearray()
chunk_size = 16000 * 2 # 2 seconds of audio in bytes
tasks = []
i = 0;
try:
while True:
data = await websocket.receive_bytes()
print("received data")
audio_buffer += data
# Check if the buffer has enough data to approximate 2 seconds of audio
if len(audio_buffer) >= chunk_size:
print("buffer is full")
i += 1
# Slice the buffer to get a 2-second chunk
audio_chunk = audio_buffer[:chunk_size]
print(len(audio_chunk))
# Process the 2-second audio chunk asynchronously
task = asyncio.create_task(transcribe_chunk(audio_chunk, token + str(i)))
tasks.append(task)
audio_buffer = audio_buffer[chunk_size:]
except WebSocketDisconnect:
print("Client disconnected")
if audio_buffer:
# Process any remaining audio data
task = asyncio.create_task(transcribe_chunk(audio_buffer))
tasks.append(task)
# Wait for all tasks to complete before ending the function
await asyncio.gather(*tasks)
</code></pre>
|
<python><audio><websocket><stream>
|
2024-02-22 23:43:46
| 1
| 493
|
shortQuestion
|
78,044,400
| 4,281,353
|
Does iter built in function sort the collection elements whenever possible?
|
<p><a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow noreferrer"><code>iter</code></a> generates an ordered collection from the unordered set as below. Is this sorted result a guaranteed behaviour of Python 3?</p>
<pre><code>>>> x = {1, 9, 2, 8, 4, 6}
>>> y = iter(x)
>>> list(y)
[1, 2, 4, 6, 8, 9] # <--- Sorted
</code></pre>
|
<python>
|
2024-02-22 22:55:51
| 1
| 22,964
|
mon
|
78,044,357
| 4,281,353
|
How to check an object is an ordered collection?
|
<p>Which object of Python <a href="https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes" rel="nofollow noreferrer">ABC</a> is guaranteed to be ordered and how to check?</p>
<p><a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator" rel="nofollow noreferrer"><code>Iterator</code></a> with <code>next</code> method and <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Reversible" rel="nofollow noreferrer"><code>Reversible</code></a> indicate order. Does <code>isinstance(object, (Iterator, Reversible))</code> cover all the cases if an object is ordered?</p>
|
<python>
|
2024-02-22 22:45:43
| 0
| 22,964
|
mon
|
78,044,320
| 985,845
|
Python Inferred class hierarchy
|
<p>I come from a C# background. While learning any OOP language I usually refer back to an old smalltalk interview question I was once asked.</p>
<p>How do you make a Rock, Paper, Scissors game without any conditional statements?</p>
<p>Here's what I came up with:</p>
<p>game_piece.py</p>
<pre><code>"""Game Piece Class represenets the base game piece"""
from __future__ import annotations
class GamePiece:
"""Base class for all game pieces"""
def __init__(self) -> None:
pass
def __repr__(self) -> str:
return "<GamePiece>"
def play(self, game_piece: GamePiece) -> bool:
"""Play method from base class for all game pieces to override.
This method will call the game piece's specific 'do you beat' method
:param game_piece: The user's chosen game piece.
:return: bool
"""
return \
game_piece.do_you_beat_paper() | \
game_piece.do_you_beat_rock() | \
game_piece.do_you_beat_scissors()
def do_you_beat_rock(self) -> bool:
"""Every game piece is asked if they can beat a other game pieces.
Returns a true if it can. Otherwise, returns a false.
:return: bool
"""
return False
def do_you_beat_paper(self) -> bool:
"""Every game piece is asked if they can beat a other game pieces.
Returns a true if it can. Otherwise, returns a false.
:return: bool
"""
return False
def do_you_beat_scissors(self) -> bool:
"""Every game piece is asked if they can beat a other game pieces.
Returns a true if it can. Otherwise, returns a false.
:return: bool
"""
return False
</code></pre>
<p>rock.py</p>
<pre><code>"""Represents the Rock Game Piece"""
from game_piece import GamePiece
class Rock(GamePiece):
"""This class represents the Rock Game Piece"""
def __repr__(self) -> str:
return "<Rock>"
def play(self, game_piece: GamePiece) -> bool:
"""Call this method to have the game pieces play each other.
It'll return a true if the game piece is a Paper.
Otherwise return false.
:param game_piece: Represents the game piece that it's playing against
:returns: bool
"""
return game_piece.do_you_beat_rock()
def do_you_beat_scissors(self) -> bool:
"""When the opponent game piece is a pair of scissors
it will call this method on the Rock opponent piece and
return true to demonstrate that it can beat a pair
of scissors.
:return: bool
"""
return True
</code></pre>
<p>paper.py</p>
<pre><code>"""Represents the Paper Game Piece"""
from game_piece import GamePiece
class Paper(GamePiece):
"""This class represents the Paper Game Piece"""
def __repr__(self) -> str:
return "<Paper>"
def play(self, game_piece: GamePiece) -> bool:
"""Call this method to have the game pieces play each other.
It'll return a true if the game piece is Scissors.
Otherwise return false.
:param game_piece: Represents the game piece that it's playing against
:returns: bool
"""
return game_piece.do_you_beat_paper()
def do_you_beat_rock(self) -> bool:
"""When the opponent game piece is a rock
it will call this method on the Paper opponent piece and
return true to demonstrate that it can beat a rock.
:return: bool
"""
return True
</code></pre>
<p>scissors.py</p>
<pre><code>"""Represents Scissors Game Piece"""
from game_piece import GamePiece
class Scissors(GamePiece):
"""This class represents the Paper Game Piece"""
def __repr__(self) -> str:
return "<Scissors>"
def play(self, game_piece: GamePiece) -> bool:
"""Call this method to have the game pieces play each other.
It'll return a true if the game piece is Paper.
Otherwise return false.
:param game_piece: Represents the game piece that it's playing against
:returns: bool
"""
return game_piece.do_you_beat_scissors()
def do_you_beat_paper(self) -> bool:
"""When the opponent game piece is a Paper
it will call this method on the Scissors opponent piece and
return true to demonstrate that it can beat a Paper.
:return: bool
"""
return True
</code></pre>
<p>main.py</p>
<pre><code>"""The main calling program for the game Rock, Paper, Scissors"""
import random
from typing import Any
import click
from game_piece import GamePiece
from paper import Paper
from rock import Rock
from scissors import Scissors
@click.group()
def cli():
"""Required by click"""
@click.command()
@click.option("--selection",
prompt="Please select: [R]ock, [P]aper or [S]cissors",
help="The user's selection of either \
[R]ock, [P]aper or [S]cissors.")
def shoot(selection: str) -> None:
"""The call to 'Shoot' based on the rules
:param selection: The user's choice
:return: None
"""
game_piece_list = {"R": Rock, "P": Paper, "S": Scissors}
user_selected_game_piece = game_piece_list[selection.upper()]
mach_selected_game_piece: Any = random.choice(
list(game_piece_list.items()))
print(f"You selected {selection} which is {user_selected_game_piece}")
does_user_win = user_selected_game_piece.play(mach_selected_game_piece)
print(f"Can {user_selected_game_piece} beat {mach_selected_game_piece}")
cli.add_command(shoot)
if __name__ == "__main__":
cli()
</code></pre>
<p>The error I'm getting is:</p>
<pre><code>TypeError: Rock.play() missing 1 required positional argument: 'game_piece'
</code></pre>
<p>Since game pieces are chosen at random both by the human & the machine I thought this would work.</p>
<p>Can someone explain how I would infer the type to the base type and accept any child type as a parameter?</p>
|
<python><python-3.x><oop>
|
2024-02-22 22:32:08
| 1
| 479
|
OneClutteredMind
|
78,044,249
| 8,272,788
|
Calling pd.Series.sum() breaks when using `~` operator
|
<p>I am trying to sum the inverse of a bool pd.Series. <code>pd.Series.sum()</code> works fine until i use the <code>~</code> operator. At which point <code>.sum()</code> starts throwing negative values.</p>
<p>Here is a very simple example:</p>
<p><code>.sum()</code> works fine:</p>
<pre><code>import pandas as pd
>>> pd.Series([True]).sum()
1
>>> pd.Series([False]).sum()
0
</code></pre>
<p>But when I invoke the <code>~</code> operator, things break:</p>
<pre><code>>>> ~pd.Series([False]).sum()
-1
>>> ~pd.Series([True]).sum()
-2
</code></pre>
<p>Notably nothing seems wrong with the data:</p>
<pre><code>>>> ~pd.Series([True])
0 False
dtype: bool
>>> ~pd.Series([False])
0 True
dtype: bool
</code></pre>
<p>What is going on here? How can I use sum on the inverse of a pd.Series object?</p>
|
<python><pandas>
|
2024-02-22 22:08:35
| 1
| 1,261
|
MorrisseyJ
|
78,044,194
| 4,269,851
|
Python str = str + value is slow
|
<p>I am writing 2 Mbyte file line by line and using <code>string</code> variable to populate the data line by line first</p>
<p>When i did in loops <code>str = str + new_data</code> it took couple seconds to process the script.</p>
<p>Once i changed to <code>str += new data</code> script finishes instantly.</p>
<p>Though <code>+=</code> was a shortcut for same command they added in newer versions.</p>
<p>Why first syntax causes substantially more time to process?</p>
<p>P.S. When i needed to write 50 MByte file script was never finishing in minutes, i suspect that was a reason.</p>
|
<python><lag><assignment-operator>
|
2024-02-22 21:52:53
| 0
| 829
|
Roman Toasov
|
78,044,157
| 7,168,098
|
query a dataframe with conditions in two columns with groupby
|
<p>I have a dataframe like this:</p>
<pre><code>df = pd.DataFrame(data=[['840', '007658', 'EP010A', 'wrwrwr'],
['841', '007658', 'EP019410A', 'wwtert'],
['842', '007658', 'EP0129W', 'erterte'],
['843', '007658', 'EP0629W', 'ertetet'],
['992', '007675', 'EP0275A', 'ete'],
['993', '007675', 'EP0375A', 'ertre'],
['994', '007675', 'EP02091', 'ert'],
['117', '007690', 'EP02212A', 'sf'],
['118', '007690', 'EP00212A', 'sf'],
['118', '007690', 'EP02281W', 'dg'],
['118', '007690', 'EP07281W', 'dg'],
['118', '007690', 'EP0281W', 'sdf'],
['118', '007690', 'EP02281W', 'ert'],
['118', '007690', 'EP0612A', 'dfg'],
['11', '0076', 'US0612A', 'dfg'],
['12', '0076', 'CA0612A', 'dfg']], columns = ['i', 'fn','docn','ad'])
</code></pre>
<p>I would like to create a dataframe that contain all the data which complies the following condition.
for the same fn number there should be at least one docn number starting with EP and not ending with W and one docn number starting with EP and ending with W:</p>
<p>For instance the fn nr 007658 has docn EP010A EP019410A EP0129W EP0629W which qualifies
nevertheless 007675 does not qualify because it does not contain any value in docn that starts with EP and ends with W.
fn '0076' does not qualify neither since tehre is no single docn corresponding doc starting by EP.</p>
<p>I am trying a million things with groupby fn but nothing works.</p>
<p>For instance:</p>
<pre><code>for i,group in enumerate(df2.groupby("fn")):
display(group)
has_EP = group[1]['docn'].apply(lambda docns: any(docn.startswith('EP') and not docn.endswith('W') for docn in docns))
has_EP_W= group[1]['docn'].apply(lambda docns: any(docn.startswith('EP') and docn.endswith('W') for docn in docns))
total_condition =has_EP & has_EP_W
display(group[1]['docn'].loc[total_condition])
if i==3:
break
</code></pre>
<p>does not work.</p>
|
<python><pandas><group-by>
|
2024-02-22 21:42:55
| 1
| 3,553
|
JFerro
|
78,044,103
| 7,211,014
|
pip install in editable mode from a pyproject in a docker container, ModuleNotFoundError not found
|
<p>When I <code>pip install -e .</code> my python package in a container (using <code>setup.py</code> and <code>pyproject.toml</code>, not requirements.txt), python cannot find my package.
If I remove <code>-e</code> from the pip install, so its just <code>pip install .</code> then it works in the container.
I added a <code>pip list</code> and I see my module installed on the container, yet it cant be used.
Note: I am using a docker volume for my project on the container. I thought this would allow me to edit the files locally without having to restart the container in and editable mode.</p>
<p>Here is my docker-compose</p>
<pre><code>version: '3.3'
services:
myapp:
container_name: myapp
build:
context: ./services/myapp
dockerfile: Dockerfile.dev
restart: always
volumes:
- ./services/myapp/:/usr/src/app/
ports:
- 5000:5000
env_file:
- ./.env/.env.dev.myapp
networks:
- myapp-network
networks:
myapp-network:
driver: bridge
</code></pre>
<p>My docker file</p>
<pre><code># pull official base image
FROM python:3.10.7-slim-buster
# set work directory
WORKDIR /usr/src/app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install system dependencies
RUN apt-get update && apt-get install -y netcat ansible ssh sshpass
# Copy certs over
COPY certs/* /app/
# install dependencies
RUN pip install --upgrade pip
RUN pip install -e .
# Show all installed modules
RUN pip list
# run entrypoint.sh
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]
</code></pre>
<p>After that my entrypoint calls a <code>manage.py</code> that is outside of my project and I try to import some moduels with it, But this is where it fails. It cant find those modules.</p>
<p>If I use <code>pip install -e .</code> in my python evn outside of the container it works.
Is there a reason why <code>pip install -e .</code> wont work in my docker container?</p>
<p><strong>UPDATE:</strong>
I found that if I go directly into the container and uninstall the module and reinstall it with <code>pip install -e .</code> it works.
Is this just a race condition problem with docker volumes?</p>
|
<python><docker><pip><dockerfile>
|
2024-02-22 21:30:23
| 1
| 1,338
|
Dave
|
78,044,030
| 14,250,641
|
Key Error when Implementing Cross Validation with GroupKFold
|
<p>I have a df with 3 main columns 'label', 'embeddings' (features), 'chr'. I am trying to do a 10-fold cross validation by grouping the chromosomes such that the chr1 rows are all either in the train or test (not split across the train/test).
I have a df that looks like:
<a href="https://i.sstatic.net/rxmAC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rxmAC.png" alt="enter image description here" /></a></p>
<p>I believe I did it correctly in my code, but I keep running into this Key Error:
<a href="https://i.sstatic.net/W4dwW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/W4dwW.png" alt="enter image description here" /></a></p>
<p>Here's my code:</p>
<pre><code>import numpy as np
from sklearn.model_selection import GroupKFold
X = np.array([np.array(x) for x in mini_df['embeddings']])
y = mini_df['label']
groups = mini_df['chromosome']
group_kfold = GroupKFold(n_splits=10)
# Initialize figure for plotting
plt.figure(figsize=(10, 6))
# Perform cross-validation and plot ROC curves for each fold
for i, (train_idx, val_idx) in enumerate(group_kfold.split(X, y, groups)):
X_train_fold, X_val_fold = X[train_idx], X[val_idx]
y_train_fold, y_val_fold = y[train_idx], y[val_idx]
# Initialize classifier
rf_classifier = RandomForestClassifier(n_estimators=n_trees, random_state=42, max_depth=max_depth, n_jobs=-1)
# Train the classifier on this fold
rf_classifier.fit(X_train_fold, y_train_fold)
# Make predictions on the validation set
y_pred_proba = rf_classifier.predict_proba(X_val_fold)[:, 1]
# Calculate ROC curve
fpr, tpr, _ = roc_curve(y_val_fold, y_pred_proba)
# Calculate AUC
roc_auc = auc(fpr, tpr)
# Plot ROC curve for this fold
plt.plot(fpr, tpr, lw=1, alpha=0.7, label=f'ROC Fold {i+1} (AUC = {roc_auc:.2f})')
# Plot ROC for random classifier
plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Random', alpha=0.8)
# Add labels and legend
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves for Random Forest Classifier')
plt.legend(loc='lower right')
plt.show()
</code></pre>
|
<python><pandas><dataframe><scikit-learn><cross-validation>
|
2024-02-22 21:11:16
| 2
| 514
|
youtube
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.