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,449,324
| 1,405,689
|
Wrong matrix assigment in Python?
|
<p>I have this code:</p>
<pre><code>#! /usr/bin/env python
import sys
import numpy
import math
inputfile = open(sys.argv[1], 'r')
atoms = numpy.zeros((6, 3), dtype='float64')
for line in inputfile:
sline = line.split()
header = sline[0]
for i in range(1, 4, 1):
atoms[i] = float(sline[i])
# print(float(sline[i]))
print(atoms)
</code></pre>
<p>The content of the input file is:</p>
<pre><code> O5 -2.978 -1.342 0.528
C1 -4.475 -1.062 0.491
C2 -4.710 -0.049 -0.519
C3 -4.193 1.266 -0.144
C4 -3.045 1.113 0.856
C5 -2.268 -0.070 0.555
</code></pre>
<p>I want to extract the coordinates and save them in a matrix called atoms. But, the content of the matrix that I am getting is:</p>
<pre><code>[[ 0. 0. 0. ]
[-2.268 -2.268 -2.268]
[-0.07 -0.07 -0.07 ]
[ 0.555 0.555 0.555]
[ 0. 0. 0. ]
[ 0. 0. 0. ]]
</code></pre>
<p><strong>What is wrong with this code?</strong></p>
|
<python><numpy>
|
2024-05-08 14:37:21
| 2
| 2,548
|
Another.Chemist
|
78,449,321
| 2,612,235
|
Seeking an Efficient Perfect Hashing Function integer keys running on a small MCU?
|
<p>I am developing a CANopen slave stack on a 200 MHz microcontroller and require a highly efficient lookup method to match a 16-bit object index (e.g., 0x603d) with a table index where the objects are stored. The expected range for used objects is between 200 and 400.</p>
<p>Although I considered using a perfect hashing function with a 16-bit table, the fill factor for this hash map would be only <code>400 / (2**16 - 1) * 100</code>, or approximately 0.6%. I believe my challenge lies in finding a code generator for a perfect hashing function for 16-bit integers. I've explored options like <strong>MPHF</strong>, <strong>BBHash</strong>, <strong>gperf</strong>, and <strong>CMPH</strong>. Most of these either work primarily with strings or they offer <code>O(1)</code> lookup time but involve complex algorithms that are not suitable for my embedded application.</p>
<p>As an alternative, I experimented with a brute force technique using two different typical xor/shift hashing functions. By iterating over the seed, I search for a minimal collision ratio to then build an open addressing hash map table.</p>
<p>Here is a snippet of the Python code I used:</p>
<pre><code>def hash32(key, seed):
h = seed
h ^= ((h << 7) ^ key * (h >> 3) ^ (~((h << 11) + (key ^ (h >> 5))))) & 0xFFFFFFFF
h = (~h + (h << 15)) & 0xFFFFFFFF
h ^= (h >> 11) & 0xFFFFFFFF
h = ((h + (h << 3)) + (h << 8)) & 0xFFFFFFFF
h ^= (h >> 13) & 0xFFFFFFFF
h = ((h + (h << 2)) + (h << 4)) & 0xFFFFFFFF
h ^= (h >> 17) & 0xFFFFFFFF
h = (h + (h << 15)) & 0xFFFFFFFF
return h
def fatou(key, seed=0):
return ((key ^ seed) * 0x45d9f3b) & 0xFFFFFFFF
# Some data
data = [4096, 4097, 4098, 4099, 5120, 5121, 5122, 5123, 5632, 5633, 5634, 5635,
6147, 8710, 8711, 8712, 4112, 4113, 8720, 8721, 8723, 16400, 16401, 4119,
4120, 4121, 8728, 8729, 16403, 16404, 16405, 16406, 8736, 8737, 8738, 8741,
4137, 9474, 25858, 9475, 24639, 24640, 24641, 24666, 16402, 24669, 24672,
24673, 24674, 24676, 24677, 24678, 24679, 24680, 24683, 24684, 24685, 24686,
24687, 24688, 24689, 24690, 24691, 24692, 24693, 24694, 24695, 24696, 24697,
24698, 24700, 24701, 24702, 24703, 24704, 20480, 24705, 24707, 24708, 24709,
20481, 24711, 24719, 24721, 24722, 24728, 24729, 24730, 24744, 24745, 24746,
24747, 6144, 24773, 6145, 24774, 6146, 6656, 6657, 6658, 6659, 24803, 24818,
24824, 24831, 8448, 8449, 8450, 8451, 8960, 8961, 8962, 8963, 9472, 8964,
9473, 8965, 8966, 9476, 9477, 8704, 8705, 8706, 8707, 9216, 8708, 9217,
9728, 9220, 9729, 9221, 8713, 9222, 9223, 9224, 8722, 12288, 26622]
def countCollisions(data, seed, map_size, hf):
""" Count collisions in a hash map for a given hash function and seed"""
max_collisions = 0
collisions = 0
m = [0] * map_size
for key in data:
m[hf(key, seed) % map_size] += 1
for i in range(map_size):
max_collisions = m[i] if m[i] > max_collisions else max_collisions
collisions += m[i] - 1 if m[i] > 1 else 0
return collisions, max_collisions
def findBestSeed(data, mapsize, hh):
""" Find the best seed for a given hash function and data"""
print("Finding best seed...")
m = len(data)
s = 0
for i in range(0xffff):
c, cc = countCollisions(data, i, mapsize, hh)
if c < m:
m = c
s = i
print(f" Found seed {s} with {m} collisions, worse case with a maximum of {cc} elements per bucket")
if c == 0:
break
return s, m
def buildOpenAdressingMap(data, seed, mapsize, hh):
""" Build an open addressing hash map for a given hash function and seed"""
d = [None] * mapsize
for key in data:
index = hh(key, seed) % mapsize
while d[index] is not None:
index += 1
d[index] = key
return d
fill_factor = 0.5
map_size = int(len(data) / fill_factor)
hfunc = fatou
seed, collisions = findBestSeed(data, map_size, hfunc)
print(f"Best seed {seed} with {collisions} collisions")
hm = buildOpenAdressingMap(data, seed, map_size, hfunc)
</code></pre>
<p>The output is:</p>
<pre><code>Finding best seed...
Found seed 0 with 14 collisions, worse case with a maximum of 2 elements per bucket
Found seed 4 with 12 collisions, worse case with a maximum of 2 elements per bucket
Found seed 7 with 11 collisions, worse case with a maximum of 2 elements per bucket
Found seed 768 with 8 collisions, worse case with a maximum of 2 elements per bucket
Found seed 4316 with 7 collisions, worse case with a maximum of 2 elements per bucket
Found seed 16428 with 6 collisions, worse case with a maximum of 2 elements per bucket
Found seed 16430 with 4 collisions, worse case with a maximum of 2 elements per bucket
Found seed 16431 with 3 collisions, worse case with a maximum of 2 elements per bucket
Best seed 16431 with 3 collisions
</code></pre>
<p>Interestingly, the <code>hash32</code> function is less efficient than the <code>fatou</code> function when translated into ARM 32-bit assembly, which consists of 19 instructions versus just 5 for <code>fatou</code>.</p>
<p>Given that even with a fill factor of 0.5, I still encounter three collisions, I am seeking a hashing function that could potentially achieve a 1.0 fill factor with zero collisions. Ideally, the hashing function should be executable in fewer than ten assembly instructions.</p>
<p>Fatou's assembly:</p>
<pre><code> eors r0, r0, r1
movw r3, #40763
movt r3, 1117
mul r0, r3, r0
bx lr
</code></pre>
<p>This <a href="https://stackoverflow.com/a/70926647/2612235">answer</a> looks interesting, but I don't really understand how I can store data in my buckets. I tried to build something (with great help of ChatGPT) but it doesn't give me unique buckets indices.</p>
<pre><code>import sys
import random
from collections import defaultdict
def generate_constants():
return random.randint(1, sys.maxsize), random.randint(1, sys.maxsize)
class HashTable:
def __init__(self, list_of_keys, retry_limit=10):
self.m = len(list_of_keys) # Define table size based on the number of keys
attempt = 0
while attempt < retry_limit:
self.C1, self.C2 = generate_constants()
self.graph, self.edges = self.create_graph(list_of_keys)
if not self.is_cyclic(self.graph):
self.setup_hash_table(self.edges)
return
attempt += 1
raise Exception("Failed to create an acyclic graph after several attempts.")
def setup_hash_table(self, edges):
table1 = [None] * self.m
table2 = [None] * self.m
for key, (index1, index2) in edges.items():
if table1[index1] is None and table2[index2] is None:
assign_value = random.randint(0, 100)
table1[index1] = assign_value
table2[index2] = key - assign_value
elif table1[index1] is not None:
table2[index2] = key - table1[index1]
elif table2[index2] is not None:
table1[index1] = key - table2[index2]
self.table1 = table1
self.table2 = table2
def h1(self, key):
return ((key * self.C1) + (self.C1 >> 5)) % self.m
def h2(self, key):
return ((key * self.C2) + (self.C2 >> 5)) % self.m
def __call__(self, key):
return self.table1[self.h1(key)] + self.table2[self.h2(key)]
def create_graph(self, list_of_keys):
graph = defaultdict(list)
edges = {}
for key in list_of_keys:
index1 = self.h1(key)
index2 = self.h2(key)
graph[index1].append(index2)
graph[index2].append(index1)
edges[key] = (index1, index2)
return graph, edges
def is_cyclic(self, graph):
visited = [False] * self.m
rec_stack = [False] * self.m
def dfs(node, parent):
visited[node] = True
rec_stack[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
if dfs(neighbor, node):
return True
elif rec_stack[neighbor] and neighbor != parent:
return True
rec_stack[node] = False
return False
for i in range(self.m):
if not visited[i]:
if dfs(i, -1):
print("Cycle detected involving node", i)
return True
return False
keys = [4, 8, 15, 16, 23, 42]
hf = HashTable(keys)
for key in keys:
print(key, hf(key))
</code></pre>
<p>Is there a different approach, a parametric hashing function suitable for brute force exploration to achieve zero collisions and a 100% fill factor? What would you recommend for this application?</p>
|
<python><hash><perfect-hash>
|
2024-05-08 14:37:06
| 1
| 29,646
|
nowox
|
78,449,301
| 10,639,694
|
Pythonic way of dumping a valid JSON string as JSON
|
<p>Suppose I have a valid JSON string that I want to make part of a larger JSON object. The most straightforward solution is parsing the string as dict, then dumping it again to JSON:</p>
<pre class="lang-py prettyprint-override"><code>import json
json_str = '{"name": "Alice", "age": 30}'
# Write the JSON-encoded string to a string
new_json_str = json.dumps({"foo": "bar", "user": json.loads(json_str)})
</code></pre>
<p>Is the parsing - dumping round trip avoidable?</p>
<p>I'm trying to avoid the inverse of <a href="https://stackoverflow.com/questions/69546331/how-to-convert-string-json-inside-a-valid-json-into-valid-json-python">how to convert string json inside a valid json into valid json python</a></p>
|
<python><json>
|
2024-05-08 14:34:15
| 1
| 989
|
AlexNe
|
78,449,229
| 3,204,810
|
Reading file, if-statement and break
|
<p>What I need is read a simple text file and stop to read when a certain string matches. Text file is:</p>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Watermelon</li>
<li>Pear</li>
<li>Apricot</li>
</ul>
<p>My minimal "working" example</p>
<pre><code> with open("C:\\Python\\test.txt") as file:
while line := file.readline():
print(line.rstrip())
if line.rstrip() == "Pear":
break
</code></pre>
<p>This returns me the error message</p>
<blockquote>
<p>TabError: inconsistent use of tabs and spaces in indentation</p>
</blockquote>
<p>Can you help me?</p>
|
<python>
|
2024-05-08 14:21:50
| 1
| 391
|
user3204810
|
78,449,183
| 1,208,289
|
sample using negated normal via numpy
|
<p>I have a sorted list that I need to sample from. I want to favor the items towards each end of the list. In other words, I want to sample from the list using a negated normal function such that the first and last entries of the list are chosen more frequently than items in the middle of the list. I tried this:</p>
<pre class="lang-py prettyprint-override"><code>slots = np.floor(np.random.normal(scale=len(children)//2, size=max_children)) - max_children//2
return children[slots]
</code></pre>
<p>However, it returns numbers that are out of range. It also returns duplicate numbers. What can I do better?</p>
|
<python><numpy><random>
|
2024-05-08 14:13:39
| 1
| 5,422
|
Brannon
|
78,449,105
| 1,243,247
|
How to extract text from ipwidgets Text widget
|
<p>The documentation for this is very cumbersome and time-consuming. I need a simple basic Hello World example to extract a simple text from a text box</p>
<pre class="lang-py prettyprint-override"><code>from ipywidgets import interact, widgets
from IPython.display import display
dossier_number_widget = widgets.Text(
value='EP23210283',
placeholder='EP23210283',
description='Dossier Number:',
disabled=False,
continuous_update=True
)
display(dossier_number_widget)
def callback(wdgt):
print(wdgt) # it doesn't print
display(wdgt) # it doesn't display
print(wdgt.value) # it doesn't print
display(wdgt.value) # it doesn't display
dossier_number_widget.observe(callback, 'value')
</code></pre>
<p>It's not working, what am I doing wrong?</p>
<p>Other examples here on SO mention <code>on_submit</code> but this method is deprecated</p>
<p>I tried with a button with no result, it simply doesn't print the result</p>
<pre class="lang-py prettyprint-override"><code>from ipywidgets import interact, widgets
from IPython.display import display
submit_button=widgets.Button(description='Submit',button_style='success')
dossier_number_widget = widgets.Text(
value='EP23210283',
placeholder='EP23210283',
description='Dossier Number:',
disabled=False,
continuous_update=False
)
def on_button_clicked(wdgt):
print(dossier_number_widget.value) # it doesn't print
display(dossier_number_widget.value) # it doesn't display
submit_button.on_click(on_button_clicked)
display(dossier_number_widget, submit_button)
</code></pre>
|
<python><jupyter-notebook><ipywidgets>
|
2024-05-08 13:58:50
| 1
| 16,504
|
João Pimentel Ferreira
|
78,449,045
| 214,296
|
How to combine list of objects into list of tuples (matrix style) in Python?
|
<p>Let's say that I have a list of tuples <code>foo</code> (object, integer) and a list of objects <code>bar</code>. The length of each of these parent lists is variable. How do I combine them into a single list of tuples, wherein each tuple is a unique combination of elements from each of the two parent lists?</p>
<ul>
<li><p>Example 1:</p>
<pre class="lang-py prettyprint-override"><code>foo = [(A, i)]
bar = [X, Y]
# missing magic
expected_result = [(A, i, X), (A, i, Y)]
</code></pre>
</li>
<li><p>Example 2:</p>
<pre class="lang-py prettyprint-override"><code>foo = [(A, i), (B, j)]
bar = [X, Y]
# missing magic
expected_result = [(A, i, X), (A, i, Y), (B, j, X), (B, j, Y)]
</code></pre>
</li>
<li><p>Example 3:</p>
<pre class="lang-py prettyprint-override"><code>foo = [(A, i), (B, j), (C, k)]
bar = [X, Y]
# missing magic
expected_result = [(A, i, X), (A, i, Y), (B, j, X), (B, j, Y), (C, k, X), (C, k, Y)]
</code></pre>
</li>
<li><p>Example 4:</p>
<pre class="lang-py prettyprint-override"><code>foo = [(A, i), (B, j)]
bar = [X]
# missing magic
expected_result = [(A, i, X), (B, j, X)]
</code></pre>
</li>
</ul>
<p>Preferably, I'd like to do this in one line, if possible. The order of the resulting list is unimportant, but the order of the elements within the tuples of that list need to be predictable.</p>
<p>In addition to trying various solutions using <code>itertools.product</code> and <code>zip</code>, I also looked at the answers to other similar questions, but I was unable to find the solution to this problem.</p>
|
<python><tuples>
|
2024-05-08 13:49:49
| 2
| 14,392
|
Jim Fell
|
78,449,042
| 562,697
|
QTreeWidget findItems always returns nothing
|
<p>I have a simple tree with at most 30 items and at most a depth of 2. I am trying to find a specific item in the tree that is in the second column (which is hidden from display). When I search for a string I can guarantee it in the tree, I still get a list of nothing.</p>
<p>I am obviously misunderstanding the documentation. The <code>columnCount()</code> for the tree is 1, so there is no second column from the tree's perspective, which is why the search fails.</p>
<p>The <a href="https://doc.qt.io/qt-6/qtreewidgetitem.html#QTreeWidgetItem-3" rel="nofollow noreferrer">QTreeWidgetItem documentation</a> states "The given list of strings will be set as the item text for each column in the item." So, I assume the item itself has multiple columns that has nothing at all to do with the tree's columns.</p>
<p>I am really just trying to add a hidden, known id for each item, specifically for searching so the text can change if needed, such that find and load functionality isn't dependent on the text or the index (as various sort options are also allowed in the real code). Sorry, new to trees.</p>
<p>MWE:</p>
<pre><code>from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem, QDialog, QVBoxLayout, QLabel
import sys
app = QApplication([])
main = QDialog()
main.setLayout(QVBoxLayout())
tree = QTreeWidget()
QTreeWidgetItem(tree, ['Test', 'test'])
main.layout().addWidget(tree)
label = QLabel()
main.layout().addWidget(label)
found = tree.findItems('test', Qt.MatchFlag.MatchRecursive | Qt.MatchFlag.MatchFixedString, 1)
label.setText(f'Found {len(found)} item(s)')
main.show()
sys.exit(app.exec())
</code></pre>
<p><strong>EDIT</strong>
If I add <code>tree.setColumnCount(2)</code> the search works as expected. However, it also displays the column I want to keep hidden. Anyway around this limitation that <code>findItems()</code> only works on visible columns?</p>
|
<python><pyqt6>
|
2024-05-08 13:49:04
| 0
| 11,961
|
steveo225
|
78,449,014
| 3,873,799
|
Slow download speed on Azure VM when installing Python library
|
<p>Disclaimer: I have read other similar SO questions but none of them applies to this case<sup>1,2</sup>.</p>
<p>I am trying to install a Python library in my Azure Ubuntu VM.
The library is <a href="https://github.com/PaddlePaddle/PaddleOCR/blob/main/doc/doc_en/quickstart_en.md#11-install-paddlepaddle" rel="nofollow noreferrer">PaddleOCR</a>. Its installation instructions require you to run:</p>
<pre class="lang-bash prettyprint-override"><code>python3 -m pip install paddlepaddle-gpu -i https://pypi.tuna.tsinghua.edu.cn/simple
</code></pre>
<p>Which downloads and installs an ~800Mb <code>whl</code> file.</p>
<p>This completes very fast on my <strong>local machine</strong>, which proves it's not a source availability throttling issue:</p>
<p><a href="https://i.sstatic.net/Mxeb2IpB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Mxeb2IpB.png" alt="Local machine download" /></a></p>
<p>On the Azure VM, I get a variable initial download speed between 150-450kb/s, which quickly (within 1-2 minutes) goes down to ~25kb/s. This makes the download fail with a Timeout after some time, and I can never get to download the file. If you re-run the command, the initial download speed always varies between 150-400kb/s, and invariably it decreases down to about ~25kb/s after some time.</p>
<p>Here are some screenshots of re-runs on my Azure VM, which I manually cancel after a bit just to test:</p>
<p><a href="https://i.sstatic.net/CR4SfArk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CR4SfArk.png" alt="VM download" /></a></p>
<h3>Azure VM specifications</h3>
<ul>
<li>Non-spot <code>NC4as-T4-v3</code> instance with a Premium SSD</li>
<li>It's idle -- it's not used for anything else than downloading</li>
<li>It sits in the UK South region, physically the same location where my local machine from where I can successfully download is based (London, UK).</li>
<li>... let me know if I should specify more info here.</li>
</ul>
<h3>What I tried</h3>
<ol>
<li>Shutting down and restarting the VM</li>
<li><a href="https://learn.microsoft.com/en-gb/troubleshoot/azure/virtual-machines/windows/redeploy-to-new-node-windows" rel="nofollow noreferrer">Redeploy</a> the VM</li>
<li>Disabling IPv6, which <a href="https://stackoverflow.com/a/74618669/3873799">sometimes seems linked</a> to a general slowness of <code>pip</code> download speed.</li>
<li>Ran <code>sudo apt-get update && sudo apt-get upgrade</code> as suggested <a href="https://stackoverflow.com/a/71771150/3873799">here</a></li>
<li>Updated <code>conda</code> and <code>pip</code></li>
</ol>
<h3>Possible explanation</h3>
<p>The fact that the speed is initially "faster" (150-400kb/s) then it slows down (25kb/s) seems to me quite telling of a throttling being made by Azure. However, I cannot find any reference online about this. Is there some setting I can change to avoid this?</p>
<hr />
<sub>
<p>1: <a href="https://stackoverflow.com/questions/51907967/how-to-improve-download-speed-on-azure-vms">How to improve download speed on Azure VMs?</a></p>
<p>2: <a href="https://stackoverflow.com/questions/46957704/slow-download-speed-from-azure-storage">Slow download speed from Azure Storage</a></p>
</sub>
|
<python><azure><virtual-machine><throttling><download-speed>
|
2024-05-08 13:45:34
| 1
| 3,237
|
alelom
|
78,448,914
| 13,314,132
|
Why did my fine-tuning T5-Base Model for a sequence-to-sequence task has short incomplete generation?
|
<p>I am trying to fine-tune a <code>t5-base</code> model for creating appropriate question against a compliance item. Compliance iteams are paragraph of texts and my question are in the past format of them. I have trained the model, saved it and loaded it back for future usecases.</p>
<p>The problem is when I am trying to use the model for creating new questions on unknown statements the response is coming as incomplete.</p>
<p>Code:</p>
<pre><code>import pandas as pd
import torch
from datasets import Dataset
import transformers
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer, T5Tokenizer
df = pd.read_csv(r'/content/questionsgenerator.csv', encoding='unicode_escape')
df.head()
# Load pre-trained model and tokenizer
model_name = "t5-base"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
# Define the training arguments
training_args = Seq2SeqTrainingArguments(
output_dir="./output_dir",
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
predict_with_generate=True,
logging_steps=100,
save_steps=5000,
eval_steps=5000,
num_train_epochs=3,
learning_rate=1e-4,
warmup_steps=1000,
save_total_limit=3,
)
# Define the training dataset
train_dataset = Dataset.from_pandas(df.rename(columns={"Compliance Item": "input_text", "Question": "target_text"}))
# Define the function to preprocess the dataset
def preprocess_function(examples):
inputs = [f"compliance item: {ci}" for ci in examples["input_text"]]
targets = [f"{question} </s>" for question in examples["target_text"]]
model_inputs = tokenizer(inputs, max_length=512, padding="max_length", truncation=True)
with tokenizer.as_target_tokenizer():
labels = tokenizer(targets, max_length=32, padding="max_length", truncation=True)
model_inputs["labels"] = labels["input_ids"]
return model_inputs
# Preprocess the dataset
train_dataset = train_dataset.map(preprocess_function, batched=True)
# Define the trainer
trainer = Seq2SeqTrainer(
model=model,
args=training_args,
train_dataset=train_dataset,
)
# Fine-tune the model on the dataset
trainer.train()
model.save_pretrained("./fine_tuned_model_question_generation")
tokenizer = T5Tokenizer.from_pretrained("t5-large")
model = transformers.AutoModelForSeq2SeqLM.from_pretrained("./fine_tuned_model_question_generation")
context = 'When the Installment Due Date falls on a non-business day, the Mortgagee must consider a Borrower’s Notice of Intent to Prepay or the receipt of the prepayment amount for a Mortgage closed before January 21, 2015 timely if received on the next business day.'
encoding = tokenizer.encode_plus(context, return_tensors="pt")
input_ids = encoding["input_ids"]
attention_mask = encoding["attention_mask"]
output = model.generate(input_ids=input_ids, attention_mask=attention_mask, max_length=1000)
decoded_output = tokenizer.decode(output[0], skip_special_tokens=True)
decoded_output
</code></pre>
<p>Here the response is:
<code>When the Installment Due Date fell on a non-business day, was the Borrower’s Notice of Intent to Prepay or the receipt of the prepayment amount for</code>
which is obviously incomplete.</p>
<p>So my question is what do i need to do increase the output?</p>
<ol>
<li>Should I increase the epochs?</li>
<li>Or is there a better model for this task?</li>
</ol>
<p>Please help in this.</p>
|
<python><huggingface-transformers><bert-language-model><nlp-question-answering>
|
2024-05-08 13:28:09
| 2
| 655
|
Daremitsu
|
78,448,761
| 18,730,707
|
How can I observe the intermediate process of cv2.erode()?
|
<p>I've been observing the results when I apply <code>cv2.erode()</code> with different <code>kernel</code> values. In the code below, it is <code>(3, 3)</code>, but it is changed to various ways such as <code>(1, 3)</code> or <code>(5, 1)</code>. The reason for this observation is to understand <code>kernel</code>.</p>
<p>I understand it in theory. And through practice, I can see what kind of results I get. But I want to go a little deeper.</p>
<p><strong>I would like to see what happens every time the pixel targeted by <code>kernel</code> changes.</strong></p>
<p>It's okay if you have thousands of images stored.</p>
<p>How can I observe the intermediate process of <code>cv2.erode()</code>? Am I asking too much?</p>
<pre class="lang-py prettyprint-override"><code>image = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
_, thresholded_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
inverted_image = cv2.bitwise_not(thresholded_image)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
eroded_image = cv2.erode(inverted_image, kernel, iterations=5)
cv2.imshow('image', eroded_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
|
<python><opencv><image-processing><mathematical-morphology>
|
2024-05-08 13:05:38
| 2
| 878
|
na_sacc
|
78,448,727
| 223,960
|
How to get an Exception out of an ExceptionGroup?
|
<p>If I have an <code>ExceptionGroup</code> how do I get the <code>Exception</code> out of it? I happen to be using Trio.</p>
<pre><code>>>> exc
>>> ExceptionGroup('Exceptions from Trio nursery', [HTTPStatusError("Client error
'400 Bad Request' for url 'https://api.fastly.com/service/xyz/acl/xyz/entries'
\nFor more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400")])
</code></pre>
|
<python><python-3.x><python-trio>
|
2024-05-08 13:01:27
| 3
| 8,190
|
Brian C.
|
78,448,698
| 447,426
|
How can I change pytest's working directory?
|
<p>I want to run the test if started via Visual Studio Code in the same directory as started from command line with <code>pytest tests</code>.</p>
<p>The folder structure is as follows:</p>
<pre><code>project-root
|- .vscode
- settings.json
|-data-processing
| |-src
| |-tests
</code></pre>
<p>I run pytest from <code>data-processing</code> folder <code>pytest tests</code> with <code>os.getcwd()</code> yielding:</p>
<pre><code>...project-root/data-processing
</code></pre>
<p>If I run from VS Code <code>os.getcwd()</code> yields:</p>
<pre><code>...project-root
</code></pre>
<p>With this setup (<code>settings.json</code>):</p>
<pre class="lang-json prettyprint-override"><code>{
"python.testing.pytestArgs": [
"data-processing/tests",
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
</code></pre>
<p>I tried to use <code>python.testing.cwd</code> option to set working directory:</p>
<pre class="lang-json prettyprint-override"><code>{
"python.testing.pytestArgs": [
"tests",
],
"python.testing.cwd": "./data-processing/",
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
</code></pre>
<p>The problem is as soon as I set <code>cwd</code> the test discovery stops working - no test discovered at all. I tried different paths with and without "./". I also checked <a href="https://github.com/microsoft/vscode-python/issues/22504" rel="nofollow noreferrer">microsoft/vscode-python#22504</a>.</p>
<p>So how to get the same working directory in VS Code for test runs? Changing the directory with <code>os.chdir</code> is not working since my problem is due to module resolution from within pyspark.</p>
|
<python><visual-studio-code><pytest>
|
2024-05-08 12:57:01
| 1
| 13,125
|
dermoritz
|
78,448,694
| 216,575
|
Jupter notebook - 500 : Internal Server Error - Mac M1
|
<p>I am getting "500 : Internal Server Error" on my jupter when I click on ipynb or try to create a new one.</p>
<p>In the console I see the following:</p>
<pre><code>[E 22:52:50.872 NotebookApp] 500 GET /notebooks/Untitled.ipynb (::1) 73.950000ms referer=http://localhost:8888/tree
[E 22:53:32.304 NotebookApp] Uncaught exception GET /notebooks/Untitled.ipynb (::1)
HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/notebooks/Untitled.ipynb', version='HTTP/1.1', remote_ip='::1')
Traceback (most recent call last):
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/tornado/web.py", line 1704, in _execute
result = await result
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/tornado/gen.py", line 775, in run
yielded = self.gen.send(value)
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/notebook/notebook/handlers.py", line 95, in get
self.write(self.render_template('notebook.html',
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/notebook/base/handlers.py", line 516, in render_template
return template.render(**ns)
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/jinja2/environment.py", line 1301, in render
self.environment.handle_exception()
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/notebook/templates/notebook.html", line 1, in top-level template code
{% extends "page.html" %}
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/notebook/templates/page.html", line 154, in top-level template code
{% block header %}
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/notebook/templates/notebook.html", line 115, in block 'header'
{% for exporter in get_frontend_exporters() %}
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/notebook/notebook/handlers.py", line 40, in get_frontend_exporters
for name in get_export_names():
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/nbconvert/exporters/base.py", line 146, in get_export_names
e = get_exporter(exporter_name)(config=config)
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/nbconvert/exporters/base.py", line 102, in get_exporter
exporter = entrypoints.get_single('nbconvert.exporters', name).load()
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/entrypoints.py", line 82, in load
mod = import_module(self.module_name)
File "/Users/ali/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/nbconvert/__init__.py", line 4, in <module>
from .exporters import *
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/nbconvert/exporters/__init__.py", line 3, in <module>
from .html import HTMLExporter
File "/Users/ali/opt/anaconda3/lib/python3.9/site-packages/nbconvert/exporters/html.py", line 14, in <module>
from jinja2 import contextfilter
ImportError: cannot import name 'contextfilter' from 'jinja2' (/Users/ali/opt/anaconda3/lib/python3.9/site-packages/jinja2/__init__.py)
</code></pre>
<p>Any ideas how to fix this?</p>
<p>I installed this using <code>pip</code> , I am running it in a <code>venv</code> using python <code>3.12.2</code></p>
<p>Thanks</p>
|
<python><jupyter-notebook>
|
2024-05-08 12:56:12
| 0
| 7,019
|
Ali Salehi
|
78,448,578
| 12,820,223
|
module has no attribute OOP in python
|
<p>I'm very new to OOP in python.</p>
<p>I wrote a python script which takes an input file and plots some data from it. Now I want to make the same plots for several different data files, so I thought I'd make my script into a class.</p>
<p>This class lives in a file called <code>TargetRunAnalyser.py</code> and goes like this so far:</p>
<pre><code>from ROOT import TFile, TCanvas
import os, sys
def tot_event_waveforms(root_file):
sd = root_file.Get("Target/Waveforms")
NEvents=0
for keyname in sd.GetListOfKeys():
NEvents+=1
NEvents/=32
return NEvents
class TargetRunAnalyser:
x_channels = [8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,0]
y_channels = [27,28,26,29,25,30,24,31,23,16,22,17,21,18,20,19]
intersection = set(x_channels) & set(y_channels)
if len(x_channels) != 16 or len(y_channels) != 16:
print(f"x_channel array length: {len(x_channels)}, y_channel array length: {len(y_channels)}")
raise Exception("Check channel arrays, they should both have 16 elements")
if len(intersection) !=0:
raise Exception(f"The following channels are in both x and y: {intersection}")
def __init__(self,run_no):
self.run_no = run_no
self.file_path=os.path.join("/Users/bethlong/Downloads/", f"Run{self.run_no}_HistoFile.root")
self.root_file = TFile(self.file_path,"read")
self.n_event_print = 100
#check how many events you have waveforms for so that you don't print more
n_event_tot = tot_event_waveforms(self.root_file)
if self.n_event_print>n_event_tot:
self.n_event_print = n_event_tot
def canvas_creator(self, canv_name):
my_canvas = TCanvas("mycanv","mycanv",900,700)
return my_canvas
</code></pre>
<p>I call this class in a separate file which goes like this:</p>
<pre><code>import TargetRunAnalyser
import ROOT
def main():
RunsToAnalyse = [50252,50305]
Analysers = [TargetRunAnalyser.TargetRunAnalyser(run) for run in RunsToAnalyse]
print([i_Analyser.n_event_print for i_Analyser in Analysers])
canvas_x_signals = TargetRunAnalyser.canvas_creator("x_signals")
if __name__ == '__main__':
main()
</code></pre>
<p>But I get the error:</p>
<pre><code> canvas_x_signals = TargetRunAnalyser.canvas_creator("x_signals")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'TargetRunAnalyser' has no attribute 'canvas_creator'
</code></pre>
<p>Can anyone tell me why <code>TargetRunAnalyser.TargetRunAnalyser(run)</code> is fine but <code>TargetRunAnalyser.canvas_creator("x_signals")</code> isn't?</p>
|
<python><class><oop>
|
2024-05-08 12:37:02
| 1
| 411
|
Beth Long
|
78,448,223
| 14,824,108
|
Different y-scales for barplot with multiple groups
|
<p>I have two groups in a barplot in <code>matplotlib</code> with measurements on different scales. I want the one on the right to have a separate y axis to not appear shrinked with respect to the one on the left. This is what I've tried so far:</p>
<p>CODE:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 300
plt.rcParams['font.size'] = 14
# set width of bars
barWidth = 0.15
bars1 = [10, 0.5]
bars2 = [11, 0.8]
bars3 = [20, 1.0]
bars4 = [30, 1.5]
bars5 = [40, 1.8]
# Set position of bar on X axis
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
r4 = [x + barWidth for x in r3]
r5 = [x + barWidth for x in r4]
# Make the plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white')
ax.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white')
ax.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white')
ax.bar(r4, bars4, color='#2d7f5e', width=barWidth, edgecolor='white')
ax.bar(r5, bars5, color='#2d7f5e', width=barWidth, edgecolor='white')
# Create secondary y-axis for the right group
ax2 = ax.twinx()
ax2.set_ylabel('scale2', fontweight='bold', labelpad=10)
group_labels = ['group1', 'group2']
ax.set_xlabel('Datasets', fontweight='bold', labelpad=10)
ax.set_ylabel('scale1', fontweight='bold', labelpad=10,)
ax.set_xticks([r + 2 * barWidth for r in range(len(bars1))])
ax.set_xticklabels(group_labels)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
</code></pre>
<p>Current output:</p>
<p><a href="https://i.sstatic.net/c46fQsgY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/c46fQsgY.png" alt="enter image description here" /></a></p>
<p>how can I make <code>group2</code> be affected only by <code>scale2</code>?</p>
|
<python><matplotlib>
|
2024-05-08 11:39:58
| 1
| 676
|
James Arten
|
78,448,089
| 17,174,267
|
Socket force different TCP packages
|
<p>I'm currently writing a few tests in Python regarding a TCP server of mine. I want to test behaviour when a message is split into multiple different packages. How can I force the OS to actually send the message and not wait for more data to avoid sending small packages? Just waiting <code>time.sleep</code> is not an option.</p>
<pre><code> def send(self, msg: Union[str,List[str]]):
if isinstance(msg, list):
for m in msg:
self.s.sendall(m.encode())
else:
self.s.sendall(msg.encode())
</code></pre>
|
<python><sockets>
|
2024-05-08 11:18:15
| 2
| 431
|
pqzpkaot
|
78,447,870
| 10,348,047
|
Why can't python httpd start a thread inside a python docker container?
|
<p>I'm trying to run a webserver to examine a system's behaviour under load.</p>
<p>While looking at alternatives, I thought to try Python's webserver:</p>
<p>If I run the following, it works as expected:</p>
<pre><code>$ sh -c 'ulimit; date>date.txt ; python3 -m http.server' &
unlimited
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
$ curl localhost:8000/date.txt
Wed May 8 10:11:00 UTC 2024
</code></pre>
<p>If I try to run it within a docker container, it can't fork:</p>
<pre><code>$ docker run --detach --name pyhttp -p 8000:8000 python:3 sh -c 'ulimit ; date>date.txt python3 -m http.server'
$ curl localhost:8000/date.txt
curl: (52) Empty reply from server
$ docker logs pyhttp
unlimited
----------------------------------------
Exception occurred during processing of request from ('172.18.0.1', 23904)
Traceback (most recent call last):
File "/usr/local/lib/python3.12/socketserver.py", line 318, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/local/lib/python3.12/socketserver.py", line 706, in process_request
t.start()
File "/usr/local/lib/python3.12/threading.py", line 992, in start
_start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread
----------------------------------------
</code></pre>
|
<python><multithreading><docker><apache>
|
2024-05-08 10:40:03
| 1
| 618
|
Tim Baverstock
|
78,447,452
| 955,273
|
Coerce dataframe dtypes so dask doesn't issue a warning?
|
<p>I have a normal <code>pandas.DataFrame</code> which contains some string columns.</p>
<pre class="lang-py prettyprint-override"><code>symbol_exch = pd.DataFrame(
[
{'exchange': s['exchange'], 'symbol': s['symbol']}
for s in exchange.symbols
],
)
</code></pre>
<p>I would like to merge this with a <code>dask.dataframe</code> which is constructed from an <code>apache.arrow</code> dataset, and so has <code>arrow</code> datatypes rather than the pandas-native equivalent.</p>
<p>As such, I am converting the <code>dtypes</code> to <code>string[pyarrow]</code></p>
<pre class="lang-py prettyprint-override"><code>symbol_exch = symbol_exch.astype(
dtype={'exchange': 'string[pyarrow]', 'symbol': 'string[pyarrow]'},
)
</code></pre>
<p>As can be seen, this seemingly works correctly, the <code>dtypes</code> are reported as <code>string[pyarrow]</code>:</p>
<pre class="lang-none prettyprint-override"><code>>>> symbol_exch.dtypes
exchange string[pyarrow]
symbol string[pyarrow]
dtype: object
</code></pre>
<p>So now I attempt to merge my <code>dask.dataframe</code> with the above:</p>
<pre class="lang-py prettyprint-override"><code>df = dask.dataframe.from_delayed(tasks, meta)
df = df.merge(symbol_exch, on='symbol', how='left')
</code></pre>
<p>The operation does actually complete successfully, but <code>dask</code> issues a warning:</p>
<pre class="lang-none prettyprint-override"><code>/usr/local/lib/python3.10/site-packages/dask/dataframe/multi.py:520: UserWarning: Merging dataframes with merge column data type mismatches:
+----------------------+-----------------+-------------+
| Merge columns | left dtype | right dtype |
+----------------------+-----------------+-------------+
| ('symbol', 'symbol') | string[pyarrow] | string |
+----------------------+-----------------+-------------+
Cast dtypes explicitly to avoid unexpected results.
warnings.warn(
</code></pre>
<p>Even though I explicitly set the <code>dtypes</code> in the right-hand dataframe, the warning is still issued.</p>
<p>What do I need to do to my <code>symbol_exch</code> dataframe in order to suppress this warning?</p>
|
<python><pandas><dataframe><pyarrow><dask-dataframe>
|
2024-05-08 09:33:37
| 1
| 28,956
|
Steve Lorimer
|
78,447,289
| 1,320,143
|
How can I generate a UUID in a Pydantic BaseModel subclass?
|
<p>My code looks a bit like this:</p>
<pre><code>class Error(BaseModel):
id: uuid.UUID
code: int
def __init__(self, code: int) -> None:
self.id = uuid.uuid4()
self.code = code
super().__init__(id=self.id, code=code)
</code></pre>
<p>This errors out with:</p>
<blockquote>
<p>AttributeError: 'Error' object has no attribute '<strong>pydantic_fields_set</strong>'</p>
</blockquote>
<p>I just don't want to have the boilerplate of generating the UUID each time I create a new Error(), plus... it should be the Error class' responsibility to instantiate its own UUID.</p>
<p>I'm not sure what I'm doing wrong.</p>
|
<python><validation><pydantic>
|
2024-05-08 09:06:30
| 1
| 1,673
|
oblio
|
78,447,245
| 16,511,234
|
My function does not close the WebSocket connection
|
<p>I have a websocket client which connects to a real time data stream. The connection works fine and when I run <code>hello</code> it connects to the stream. Since the WebSocket server runs and sends permanently there is to much data in a really short time and I want to close the connection manually. I wrote the function <code>close_connection</code> but nothing happens when I call it and I do not know why.</p>
<p>This is what my code looks like:</p>
<pre><code>import websockets
from websockets.sync.client import connect
URL = "wss://test.com/test"
AUTHENTIFICATION = {'Authorization': 'Basic someToken'}
def hello():
with connect(URL,
additional_headers = AUTHENTIFICATION) as websocket:
message = websocket.recv()
resp = websocket.response.status_code
if websocket.response.status_code == 101:
print('Connection successful')
else:
print('Failure')
for message in websocket:
print(f"Received: {message}")
def close_connection():
with connect(URL,
additional_headers=AUTHENTIFICATION) as websocket:
websocket.close()
</code></pre>
|
<python><websocket>
|
2024-05-08 08:58:07
| 1
| 351
|
Gobrel
|
78,447,053
| 7,499,018
|
Create multiple columns from a single column and group by pandas
|
<pre><code>work = pd.DataFrame({"JOB" : ['JOB01', 'JOB01', 'JOB02', 'JOB02', 'JOB03', 'JOB03'],
"STATUS" : ['ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED', 'ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED'],
"PART" : ['PART01', 'PART02','PART03','PART04','PART05','PART06']})
</code></pre>
<p>How can I use Pandas to groupby the JOB, split Status into columns based on the values and concatenate the Part field based on the JOB.</p>
<p>Desired Output:</p>
<pre><code>JOB | ON_ORDER | ACTIVE | TO_BE_ALLOCATED | PART_CON
JOB01 | True | True | False | Part01\nPart02
JOB02 | True | False | True | Part03\nPart04
JOB03 | False | True | True | Part05\nPart06
</code></pre>
|
<python><pandas><dataframe><group-by>
|
2024-05-08 08:24:57
| 2
| 487
|
Martin Cronje
|
78,446,907
| 163,768
|
Loading MATLAB data in Python with h5py causes permuted dimensions
|
<p>I'm using the following code to load a MATLAB file into Python</p>
<pre class="lang-python prettyprint-override"><code>import h5py
import numpy as np
filepath = 'file.mat'
arrays = {}
f = h5py.File(filepath)
for k, v in f.items():
arrays[k] = np.array(v)
a=arrays['data']
a.shape
</code></pre>
<p>Where in MATLAB my data has the following size:</p>
<pre class="lang-matlab prettyprint-override"><code>>> size(dataset)
ans =
64 50 21 2
</code></pre>
<p>While in Python</p>
<pre class="lang-python prettyprint-override"><code>>>> a.shape
(2, 21, 50, 64)
</code></pre>
<p>Why are my dimensions permuted backwards and how can I fix this?</p>
|
<python><matlab><import><hdf5><h5py>
|
2024-05-08 07:58:18
| 1
| 1,669
|
Demiurg
|
78,446,740
| 4,415,232
|
Normalize / flatten nested list of JSON
|
<p>I have this list with lots of JSON (here shortened) in it, which are very nested and I want to normalize it and bring it all to one level in the JSON.</p>
<p>What I have:</p>
<pre><code>[{'index': 'exp-000005',
'type': '_doc',
'id': 'jdaksjdlkj',
'score': 9.502488,
'source': {'user': {'resource_uuid': '123'},
'verb': 'REPLIED',
'resource': {'resource_uuid': '/home'},
'timestamp': '2022-01-20T08:14:00+00:00',
'with_result': {},
'in_context': {'screen_width': '3440',
'screen_height': '1440',
'build_version': '7235',
'clientid': '123',
'question': 'Hallo',
'request_time': '403',
'status': 'success',
'response': '[]',
'language': 'de'}}},
{'index': 'exp-000005',
'type': '_doc',
'id': 'dddddd',
'score': 9.502488,
'source': {'user': {'resource_uuid': '44444'},
'verb': 'REPLIED',
'resource': {'resource_uuid': '/home'},
'timestamp': '2022-01-20T08:14:10+00:00',
'with_result': {},
'in_context': {'screen_width': '3440',
'screen_height': '1440',
'build_version': '7235',
'clientid': '345',
'question': 'Ich brauche Hilfe',
'request_time': '111',
'status': 'success',
'response': '[{"recipientid":"789", "text":"Bitte sehr."}, {"recipientid":"888", "text":"Kann ich Ihnen noch mit etwas anderem behilflich sein?"}]',
'language': 'de'}}},
{'index': 'exp-000005',
'type': '_doc',
'id': 'jdhdgs',
'score': 9.502488,
'source': {'user': {'resource_uuid': '333'},
'verb': 'REPLIED',
'resource': {'resource_uuid': '/home'},
'timestamp': '2022-01-20T08:14:19+00:00',
'with_result': {},
'in_context': {'screen_width': '3440',
'screen_height': '1440',
'build_version': '7235',
'clientid': '007',
'question': 'Zertifikate',
'request_time': '121',
'status': 'success',
'response': '[{"recipientid":"345", "text":"Künstliche Intelligenz"}, {"recipientid":"123", "text":"Kann ich Ihnen noch mit etwas anderem behilflich sein?"}]',
'language': 'de'}}}]
</code></pre>
<p>What I want:</p>
<pre><code>[{'index': 'exp-000005',
'type': '_doc',
'id': 'jdaksjdlkj',
'score': 9.502488,
'resource_uuid': '123',
'verb': 'REPLIED',
'resource_uuid': '/home',
'timestamp': '2022-01-20T08:14:00+00:00',
'with_result': {},
'screen_width': '3440',
'screen_height': '1440',
'build_version': '7235',
'clientid': '123',
'question': 'Hallo',
'request_time': '403',
'status': 'success',
'response': '[]',
'language': 'de'},
{'index': 'exp-000005',
'type': '_doc',
'id': 'dddddd',
'score': 9.502488,
'resource_uuid': '44444',
'verb': 'REPLIED',
'resource_uuid': '/home',
'timestamp': '2022-01-20T08:14:10+00:00',
'with_result': {},
'screen_width': '3440',
'screen_height': '1440',
'build_version': '7235',
'clientid': '345',
'question': 'Ich brauche Hilfe',
'request_time': '111',
'status': 'success',
'recipientid1': "789",
'text1': "Bitte sehr",
'recipientid2': "888",
'text2': "Kann ich Ihnen noch mit etwas anderem behilflich sein?",
'language': 'de'},
{'index': 'exp-000005',
'type': '_doc',
'id': 'jdhdgs',
'score': 9.502488,
'resource_uuid': '333',
'verb': 'REPLIED',
'resource_uuid': '/home',
'timestamp': '2022-01-20T08:14:19+00:00',
'with_result': {},
'screen_width': '3440',
'screen_height': '1440',
'build_version': '7235',
'clientid': '007',
'question': 'Zertifikate',
'request_time': '121',
'status': 'success',
'recipientid1': "345",
'text1': "Künstliche Intelligenz",
'recipientid1': "123",
'text2': "Kann ich Ihnen noch mit etwas anderem behilflich sein?",
'language': 'de'}]
</code></pre>
<p>I am not sure whether to use JSON flatten or some magic with pandas normalize.</p>
|
<python><json>
|
2024-05-08 07:26:05
| 2
| 1,235
|
threxx
|
78,446,556
| 10,308,337
|
Parallel computing for sequentially dependent tasks
|
<p>I understand that Python <a href="https://youtu.be/YOhrIov7PZA?si=3mvIr-ETh4yAjXxJ" rel="nofollow noreferrer">multi-processing</a> and <a href="https://youtu.be/3dEPY3HiPtI?si=FtSzYULS4xb-s2QJ" rel="nofollow noreferrer">multi-threading</a> can accelerate running independent tasks. However, If I have 10 tasks sequentially and each one's input rely on the previous one's output, is it still possible to accelerate using parallel computing or parallel processing? Any perspective from software or hardware will be appreciated!</p>
|
<python><tensorflow><pytorch><parallel-processing>
|
2024-05-08 06:49:38
| 1
| 327
|
John
|
78,446,412
| 6,042,172
|
python plotly x axis dates show all ticks
|
<p>I'm using plotly.graph_objects to generate a html with data embedded.</p>
<p>Although I am really pleased with the library, I cannot make it display all my x-axis ticks in some scenarios, as shown below.</p>
<p><a href="https://i.sstatic.net/pzI2itFf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pzI2itFf.png" alt="Missing ticks on x-axis" /></a></p>
<p>Yet, if I zoom in, I get all the ticks (desired behaviour)</p>
<p>Question is: Is there any way I can enforce plotly to display all ticks, when they refer to months? (Displaying all ticks regarding days while displaying one whole year would be too much ticks)</p>
<p>My current code is:</p>
<pre><code>import pandas as pd
import plotly.graph_objects as go
list_data_mb = [
('2023-01-01',10 ,'dat') , ('2023-01-15',15 ,'dat'),('2023-01-01',10 ,'ind') , ('2023-01-15',15 ,'ind'),
('2023-02-01',20 ,'dat') , ('2023-02-15',25 ,'dat'),('2023-02-01',20 ,'ind') , ('2023-02-15',25 ,'ind'),
('2023-03-01',30 ,'dat') , ('2023-03-15',35 ,'dat'),('2023-03-01',30 ,'ind') , ('2023-03-15',35 ,'ind'),
('2023-04-01',40 ,'dat') , ('2023-04-15',45 ,'dat'),('2023-04-01',40 ,'ind') , ('2023-04-15',45 ,'ind'),
('2023-05-01',50 ,'dat') , ('2023-05-15',55 ,'dat'),('2023-05-01',50 ,'ind') , ('2023-05-15',55 ,'ind'),
('2023-06-01',60 ,'dat') , ('2023-06-15',65 ,'dat'),('2023-06-01',60 ,'ind') , ('2023-06-15',65 ,'ind'),
('2023-07-01',70 ,'dat') , ('2023-07-15',75 ,'dat'),('2023-07-01',70 ,'ind') , ('2023-07-15',75 ,'ind'),
('2023-08-01',80 ,'dat') , ('2023-08-15',85 ,'dat'),('2023-08-01',80 ,'ind') , ('2023-08-15',85 ,'ind'),
('2023-09-01',90 ,'dat') , ('2023-09-15',95 ,'dat'),('2023-09-01',90 ,'ind') , ('2023-09-15',95 ,'ind'),
('2023-10-01',100,'dat') , ('2023-10-15',102,'dat'),('2023-10-01',100,'ind') , ('2023-10-15',102,'ind'),
('2023-11-01',104,'dat') , ('2023-11-15',106,'dat'),('2023-11-01',104,'ind') , ('2023-11-15',106,'ind'),
('2023-12-01',108,'dat') , ('2023-12-15',110,'dat'),('2023-12-01',108,'ind') , ('2023-12-15',108,'ind'),
('2024-01-01',112,'dat') , ('2024-01-15',114,'dat'),('2024-01-01',112,'ind') , ('2024-01-15',114,'ind'),
]
df = pd.DataFrame(list_data_mb,columns=['date','size','tbs'])
df['date'] = pd.to_datetime(df['date'], format="%Y-%m-%d")
data = [go.Bar(name=tbs, x=dfg['date'], y=dfg['size']) for tbs,dfg in df.groupby(by='tbs')]
fig = go.Figure(data)
fig.update_layout(
barmode = 'stack',
title = 'Tablespaces size over time',
xaxis_title = 'Date',
)
fig.update_xaxes(
rangeslider_visible=True,
tickmode='array', #linear: too many values. And for "1d", it will not display hours
rangeselector=dict(
buttons=list([
dict(count=1, label="1d" , step="day", stepmode="backward"),
dict(count=1, label="1m" , step="month", stepmode="backward"),
dict(count=6, label="6m" , step="month", stepmode="backward"),
dict(count=1, label="1y" , step="year", stepmode="backward"),
dict(count=1, label="YTD", step="year", stepmode="todate" ),
dict( step="all" )
])
)
)
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='white')
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='white')
fig.write_html("./aux_0.html")
</code></pre>
|
<python><date><plotly>
|
2024-05-08 06:18:52
| 1
| 908
|
glezo
|
78,446,337
| 11,082,866
|
Merge columns with same name but one empty and another containing values
|
<p>I have a dataframe in which there are couple of columns with same name. How can I merge them in the same dataframe?
df:</p>
<pre><code>items_group quantity items_group quantity
KIT1240 12
KIT1265 7
KIT1265 6
KIT1198A 6
KIT1264 12
</code></pre>
<p>expected output:</p>
<pre><code>items_group quantity
KIT1240 12
KIT1265 7
KIT1265 6
KIT1198A 6
KIT1264 12
</code></pre>
|
<python><pandas>
|
2024-05-08 05:56:47
| 1
| 2,506
|
Rahul Sharma
|
78,446,023
| 6,011,193
|
In colab, `ollama serve &` froze running
|
<p>I run following sh in colab</p>
<pre><code>!ollama serve &
!ollama run llama3
</code></pre>
<p>it out</p>
<pre><code>2024/05/08 03:51:17 routes.go:989: INFO server config env="map[OLLAMA_DEBUG:false OLLAMA_LLM_LIBRARY: OLLAMA_MAX_LOADED_MODELS:1 OLLAMA_MAX_QUEUE:512 OLLAMA_MAX_VRAM:0 OLLAMA_NOPRUNE:false OLLAMA_NUM_PARALLEL:1 OLLAMA_ORIGINS:[http://localhost https://localhost http://localhost:* https://localhost:* http://127.0.0.1 https://127.0.0.1 http://127.0.0.1:* https://127.0.0.1:* http://0.0.0.0 https://0.0.0.0 http://0.0.0.0:* https://0.0.0.0:*] OLLAMA_RUNNERS_DIR: OLLAMA_TMPDIR:]"
time=2024-05-08T03:51:17.536Z level=INFO source=images.go:897 msg="total blobs: 0"
time=2024-05-08T03:51:17.536Z level=INFO source=images.go:904 msg="total unused blobs removed: 0"
time=2024-05-08T03:51:17.538Z level=INFO source=routes.go:1034 msg="Listening on 127.0.0.1:11434 (version 0.1.34)"
time=2024-05-08T03:51:17.627Z level=INFO source=payload.go:30 msg="extracting embedded files" dir=/tmp/ollama2853183168/runners
time=2024-05-08T03:51:28.627Z level=INFO source=payload.go:44 msg="Dynamic LLM libraries [rocm_v60002 cpu cpu_avx cpu_avx2 cuda_v11]"
time=2024-05-08T03:51:28.629Z level=INFO source=gpu.go:122 msg="Detecting GPUs"
time=2024-05-08T03:51:28.662Z level=INFO source=cpu_common.go:11 msg="CPU has AVX2"
</code></pre>
<p>it is frozen in <code>!ollama serve &</code>, I think & has make running server in backend, why is it frozen?</p>
|
<python><jupyter-notebook><artificial-intelligence><google-colaboratory><ollama>
|
2024-05-08 03:55:01
| 1
| 4,195
|
chikadance
|
78,446,021
| 89,233
|
How to properly refresh Google Cloud Python API credentials?
|
<p>I'll re-formulate this question based on the feedback.</p>
<p>First, a few base facts:</p>
<ol>
<li>I'm writing a GUI application that talks to google cloud services using the <code>google.cloud</code> Python SDK.</li>
<li>I'm using google oauth <code>DeviceClient</code> flow to sign in from a GUI application.</li>
<li>I'd like the user to sign in once, and then remember the sign-in persistently in device-local storage. Having to sign in again when re-starting the GUI application is not good enough.</li>
<li>I know how to run through the device flow, get the oauth response back, save it and reload it, and use it to create a <code>credentials.Credentials</code> object, and use this to create a google cloud client like <code>storage.Client</code></li>
<li>I know that the client will attempt to re-refresh credentials when necessary as part of its internal work.</li>
</ol>
<p>I <em>previously believed</em> that when using a refresh token to re-authorize, oauth returns a new refresh token that's not the same as the originally issued refresh token. I have verified that that's not actually the case here.</p>
<p>I <em>believe</em> that there is no good way to detect whether the <code>storage.Client</code> object has refreshed the credentials or not, nor do I <em>believe</em> that there is a good way to get the credentials back out from the client so I can introspect them and save the new refresh token for later use.</p>
<p>This is a problem, because if I re-create a new <code>credentials.Credentials</code> with the JSON I got back from the previous login, and then create a <code>storage.Client</code> from that token and refresh token, this client will blow up and claim it's not properly authorized. I then walk through the device login flow again, which generates a new oauth JSON payload, which works when I create a new client with these credentials. However, if I write that JSON payload to disk, re-start the program, re-load the JSON, and try to create a new <code>credentials.Credentials</code> from this JSON, the <code>storage.Client</code> created from those credentials no longer works; it claims I need to "re-login with gcloud auth" (which of course isn't the flow I use.)</p>
<p>My current theory is that the <code>storage.Client</code> re-creates a new authtoken, which invalidates the old authtoken, and when the program re-loads, the old authtoken saved to JSON is no longer valid, and rather than refreshing using the refresh token, the <code>storage.Client</code> simply throws. So, for this to work, I need to be able to store the current authtoken that the <code>storage.Client</code> ends up using, and there doesn't seem to be an accessor to read that back out.</p>
<p>This theory is strengthened, because the documentation for the <code>token</code> argument to <code>Credentials</code> says:</p>
<pre><code> token (Optional(str)): The OAuth 2.0 access token. Can be None
if refresh information is provided.
refresh_token (str): The OAuth 2.0 refresh token. If specified,
credentials can be refreshed.
</code></pre>
<p>However, passing <code>None</code> for the <code>token</code> argument and passing in the proper <code>refresh_token</code> will immediately cause the <code>storage.Client</code> using the credentials to blow up when trying to refresh, with the following stack:</p>
<pre><code> File "videoripper/upload.py", line 157, in run
blob.upload_from_filename(f)
File "venv/lib/python3.12/site-packages/google/cloud/storage/blob.py", line 2959, in upload_from_filename
self._handle_filename_and_upload(
File "venv/lib/python3.12/site-packages/google/cloud/storage/blob.py", line 2829, in _handle_filename_and_upload
self._prep_and_do_upload(
File "venv/lib/python3.12/site-packages/google/cloud/storage/blob.py", line 2637, in _prep_and_do_upload
created_json = self._do_upload(
^^^^^^^^^^^^^^^^
File "venv/lib/python3.12/site-packages/google/cloud/storage/blob.py", line 2443, in _do_upload
response = self._do_multipart_upload(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "venv/lib/python3.12/site-packages/google/cloud/storage/blob.py", line 1956, in _do_multipart_upload
response = upload.transmit(
^^^^^^^^^^^^^^^^
File "venv/lib/python3.12/site-packages/google/resumable_media/requests/upload.py", line 153, in transmit
return _request_helpers.wait_and_retry(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "venv/lib/python3.12/site-packages/google/resumable_media/requests/_request_helpers.py", line 155, in wait_and_retry
response = func()
^^^^^^
File "venv/lib/python3.12/site-packages/google/resumable_media/requests/upload.py", line 145, in retriable_request
result = transport.request(
^^^^^^^^^^^^^^^^^^
File "venv/lib/python3.12/site-packages/google/auth/transport/requests.py", line 537, in request
self.credentials.before_request(auth_request, method, url, request_headers)
File "venv/lib/python3.12/site-packages/google/auth/credentials.py", line 230, in before_request
self._blocking_refresh(request)
File "venv/lib/python3.12/site-packages/google/auth/credentials.py", line 193, in _blocking_refresh
self.refresh(request)
File "venv/lib/python3.12/site-packages/google/oauth2/credentials.py", line 431, in refresh
) = reauth.refresh_grant(
^^^^^^^^^^^^^^^^^^^^^
File "venv/lib/python3.12/site-packages/google/oauth2/reauth.py", line 348, in refresh_grant
raise exceptions.RefreshError(
google.auth.exceptions.RefreshError: Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate.
</code></pre>
<p>The credentials have not expired; they were minted just a few moments ago. Passing in the authtoken returned by the device auth flow, makes this work, once -- but the next attempts, even if it's just moments later, fail with this same stack trace.</p>
<p>The code I'm using is as follows (copy-paste-assembled from a few functions):</p>
<pre><code>import json
from oauthlib.oauth2 import DeviceClient
from requests_oauthlib import OAuth2Session
from google.cloud import storage
# Constants
CLIENT_ID = 'xxxxx.apps.googleusercontent.com'
CLIENT_SECRET = 'GOCSPX-xxxxx'
SCOPE = ['https://www.googleapis.com/auth/devstorage.read_write']
# URLs for device and token requests
device_auth_url = 'https://oauth2.googleapis.com/device/code'
token_url = 'https://oauth2.googleapis.com/token'
try:
with open("/opt/store/creds.json", "w") as f:
stored = json.load(f)
creds = credentials.Credentials(
stored['access_token'],
refresh_token=stored['refresh_token'],
token_uri=oa.token_url,
client_id=oa.CLIENT_ID,
client_secret=oa.CLIENT_SECRET)
gclient = storage.Client(project=PROJECT, credentials=creds)
gclient.list_buckets()
# it worked
return stored
except Exception as e:
# it didn't work
pass
client = DeviceClient(client_id=CLIENT_ID)
oauth = OAuth2Session(client=client)
device_auth_response = oauth.post(device_auth_url, data={
'client_id': CLIENT_ID,
'scope': ' '.join(SCOPE)
})
darj = device_auth_response.json()
device_code = darj['device_code']
user_code = darj['user_code']
verification_url = darj['verification_url']
print(f"Please visit {verification_url} and paste the code: {user_code}", flush=True)
# now wait for the user to go through the flow, polling for success
token_response = oauth.post(token_url, data={
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'device_code': device_code,
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code'
})
if token_response.status_code == 200:
# Successfully retrieved the token
token = token_response.json()
with open("/opt/store/creds.json", "w") as f:
json.dump(token, f)
return token
raise Exception("Computer says no.")
</code></pre>
<p>As an additional challenge, when I try the <code>creds.refresh</code> call, I get an error that credentials have expired, even if I just got them back from logging in.</p>
<pre><code>>>> creds.refresh(requests.Request())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "venv/lib/python3.12/site-packages/google/oauth2/credentials.py", line 431, in refresh
) = reauth.refresh_grant(
^^^^^^^^^^^^^^^^^^^^^
File "venv/lib/python3.12/site-packages/google/oauth2/reauth.py", line 348, in refresh_grant
raise exceptions.RefreshError(
google.auth.exceptions.RefreshError: Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate.
</code></pre>
<p>This happens even when the credentials themselves work fine.</p>
|
<python><google-cloud-storage><google-oauth><google-api-python-client><google-cloud-sdk>
|
2024-05-08 03:54:03
| 1
| 7,386
|
Jon Watte
|
78,446,007
| 9,516,820
|
Is it necessary to call torch.no_grad() even in evaluation mode?
|
<p>I am learning <code>pytorch</code>. In the code examples, the model is switched between training and testing by using the <code>model.train()</code> and <code>model.eval()</code> modes. I understand that this has to be done to deactivate training specific behaviour such as dropouts and normalisation and gradient computation while testing.</p>
<p>In many such examples, they also use <code>torch.no_grad()</code>, which I understand is a way of explicitly asking to stop the calculations of the gradients.</p>
<p>My question is, if gradient calculation is stopped in <code>model.eval()</code> mode then why do we also have to set <code>torch.no_grad()</code>?</p>
<p>Below is an example of a code where both <code>model.eval()</code> and <code>torch.no_grad()</code> is used</p>
<pre><code>class QuertyModel(nn.Module):
def __init__(self):
super().__init__()
self.input = nn.Linear(2, 8)
self.hl1 = nn.Linear(8, 16)
self.hl2 = nn.Linear(16, 32)
self.hl3 = nn.Linear(32, 16)
self.hl4 = nn.Linear(16, 8)
self.output = nn.Linear(8, 3)
def forward(self, x):
x = F.relu(self.input(x))
x = F.relu(self.hl1(x))
x = F.relu(self.hl2(x))
x = F.relu(self.hl3(x))
x = F.relu(self.hl4(x))
return self.output(x)
</code></pre>
<p>Function to train the model</p>
<pre><code>def train_model(model, lr, num_epochs):
loss_function = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
train_acc, train_loss, test_acc, test_loss = [], [], [], []
for epoch in range(num_epochs):
print(f"{epoch+1}/{num_epochs}")
model.train() # switch to training mode
batch_acc, batch_loss = [], []
for X, y in train_loader:
# forward pass
y_hat = model(X)
loss = loss_function(y_hat, y)
# backward pass
optimizer.zero_grad()
loss.backward()
optimizer.step()
matches = torch.argmax(y_hat, axis=1) == y # true/false
matches = matches.float() # 0/1
batch_acc.append(100*torch.mean(matches))
batch_loss.append(loss.item())
train_acc.append(np.mean(batch_acc))
train_loss.append(np.mean(batch_loss))
model.eval() # switch to evaluation mode
X, y = next(iter(test_loader))
with torch.no_grad():
y_hat = model(X)
test_acc.append(100*(torch.mean(y_hat) == y).float())
test_loss.append(loss_function(y_hat, y).item())
return train_acc, train_loss, test_acc, test_loss
</code></pre>
|
<python><pytorch>
|
2024-05-08 03:45:46
| 1
| 972
|
Sashaank
|
78,445,820
| 432,509
|
How to inspect the body of a function (without it's signiture)
|
<p>How can a function's body be inspected in Python?</p>
<pre class="lang-py prettyprint-override"><code>def main():
def example_function():
x = 4
y = 3
if x + y < 6:
print("Test")
print("Example")
import inspect
print(inspect.getsource(example_function))
main()
</code></pre>
<p>This prints out:</p>
<pre><code> def example_function():
x = 4
y = 3
if x + y < 6:
print("Test")
print("Example")
</code></pre>
<p>Is there a robust way of only printing the function body without it's signature?</p>
<p>Which would only output:</p>
<pre class="lang-py prettyprint-override"><code> x = 4
y = 3
if x + y < 6:
print("Test")
print("Example")
</code></pre>
<p>In most cases skipping the first line would be sufficient, but it's not guaranteed the function signature isn't multi-line so a way to skip any signature would be better.</p>
|
<python><introspection>
|
2024-05-08 02:23:13
| 0
| 49,183
|
ideasman42
|
78,445,577
| 14,230,633
|
Polars select multiple element-wise products
|
<p>Suppose I have the following dataframe:</p>
<pre><code>the_df = pl.DataFrame({'x1': [1,1,1], 'x2': [2,2,2], 'y1': [1,1,1], 'y2': [2,2,2]})
┌─────┬─────┬─────┬─────┐
│ x1 ┆ x2 ┆ y1 ┆ y2 │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 1 ┆ 2 │
│ 1 ┆ 2 ┆ 1 ┆ 2 │
│ 1 ┆ 2 ┆ 1 ┆ 2 │
└─────┴─────┴─────┴─────┘
</code></pre>
<p>And and two lists, <code>xs = ['x1', 'x2']</code>, <code>ys = ['y1', 'y2']</code>.</p>
<p>Is there a good way to add the products between x1/y1 and x2/y2 using <code>.select()</code>? So the result should look like the following. Specifically, I want to use the lists rather than writing out <code>z1=x1*y1, z2=x2*y2</code> (the real data has more terms I want to multiply).</p>
<pre><code>┌─────┬─────┬─────┬─────┬─────┬─────┐
│ x1 ┆ x2 ┆ y1 ┆ y2 ┆ z1 ┆ z2 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╪═════╪═════╡
│ 1 ┆ 2 ┆ 1 ┆ 2 ┆ 1 ┆ 4 │
│ 1 ┆ 2 ┆ 1 ┆ 2 ┆ 1 ┆ 4 │
│ 1 ┆ 2 ┆ 1 ┆ 2 ┆ 1 ┆ 4 │
└─────┴─────┴─────┴─────┴─────┴─────┘
</code></pre>
|
<python><dataframe><python-polars>
|
2024-05-08 00:15:44
| 1
| 567
|
dfried
|
78,445,534
| 1,606,161
|
ManagedIdentityCredential authentication unavailable, no managed identity found - Azure Synapse PySpark
|
<p>We are trying to generate token for custom rest api endpoint. We are using Azure Synapse Notebook in PySpark.</p>
<pre><code>from azure.identity import DefaultAzureCredential,ManagedIdentityCredential
import requests
credential = ManagedIdentityCredential(client_id='xxxxxx-xxxx-xxxx-xxxx-xxxxx')
</code></pre>
<p>This code execute successfully without error. I know alternatively we can use ClientSecret authentication but because of complaince reason we have to use <a href="https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.managedidentitycredential?view=azure-python-preview" rel="nofollow noreferrer">ManagedIdentityCredential</a> only.</p>
<p>But using <strong>credential</strong> object if we try to get_token it throws error</p>
<pre><code>token = credential.get_token("api://xxxxxx-xxxx-xxxx-xxxx-xxxxx/.default")
</code></pre>
<blockquote>
<p>ManagedIdentityCredential.get_token failed: ManagedIdentityCredential
authentication unavailable, no managed identity endpoint found.
--------------------------------------------------------------------------- CredentialUnavailableError Traceback (most recent call
last) Cell In [9], line 1
----> 1 token = credential.get_token("api://xxxxxx-xxxx-xxxx-xxxx-xxxxx/.default")</p>
<p>File
~/cluster-env/clonedenv/lib/python3.10/site-packages/azure/identity/_internal/decorators.py:27,
in log_get_token..decorator..wrapper(*args, **kwargs)
24 @functools.wraps(fn)
25 def wrapper(*args, **kwargs):
26 try:
---> 27 token = fn(*args, **kwargs)
28 _LOGGER.info("%s succeeded", qualified_name)
29 return token</p>
<p>File
~/cluster-env/clonedenv/lib/python3.10/site-packages/azure/identity/_credentials/managed_identity.py:93, in ManagedIdentityCredential.get_token(self, *scopes, **kwargs)
91 if not self._credential:
92 raise CredentialUnavailableError(message="No managed identity endpoint found.")
---> 93 return self._credential.get_token(*scopes, **kwargs)</p>
<p>File
~/cluster-env/clonedenv/lib/python3.10/site-packages/azure/identity/_credentials/managed_identity.py:190,
in ImdsCredential.get_token(self, *scopes, **kwargs)
188 if not self._endpoint_available:
189 message = "ManagedIdentityCredential authentication unavailable, no managed identity endpoint found."
--> 190 raise CredentialUnavailableError(message=message)
192 if len(scopes) != 1:
193 raise ValueError("This credential requires exactly one scope per token request.")</p>
<p>CredentialUnavailableError: ManagedIdentityCredential authentication
unavailable, no managed identity endpoint found.</p>
</blockquote>
|
<python><pyspark><azure-synapse><azure-managed-identity><azure-identity>
|
2024-05-07 23:56:28
| 1
| 909
|
arpan desai
|
78,445,520
| 432,509
|
Alternative to bare except in Python?
|
<p>Documentation on exception handling tends to focus on using specific exception types – which is good advice in general.</p>
<p>However there are times I want to run some Python code which <strong>under no circumstances</strong> throws an exception that isn't handled and stops the program from running:</p>
<p>For example, a graphical application might run a user-defined script. I don't know what errors that script could trigger, so it's not useful to check for specific errors:</p>
<pre class="lang-py prettyprint-override"><code>try:
run_script_file(filepath)
except:
import traceback
print("Script:", filepath, "failed with error!")
traceback.print_exc()
</code></pre>
<p>This works, but code checking tools warn that bare <code>except</code> should not be used. While I could suppress the warnings in each case, I was considering using <code>except BaseException:</code> to quiet the warnings.</p>
<hr />
<p>Is a bare <code>except:</code> <strong>guaranteed</strong> to be the equivalent of <code>except BaseException:</code> or are there subtle differences where a bare except might catch exceptions a <code>BaseException</code> wouldn't?</p>
|
<python><exception>
|
2024-05-07 23:46:27
| 1
| 49,183
|
ideasman42
|
78,445,511
| 11,104,068
|
Unable to read socket stream in Python, gets stuck at recvfrom. Works in DotNet/Terminal
|
<p>I have a device that converts analog audio to digital audio, and there's a way to listen to the stream in my local server through the UDP protocol.</p>
<ul>
<li>Working- When in my terminal, if I run <code>echo 'subscribe' | nc -u 192.168.0.194 9444</code>, I receive a response for ~15 seconds shown as below which I should be able to convert to an audio that I can play:</li>
</ul>
<pre><code>?a?????̻?yyzzyyzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}|||}|}~~~~~~~~~~~}~~~~~~}}~~~}}}}}|||||}|||||||||||}|||||||||||{{{{{{{{{{{{{{zzzzzzzzzzzzzz?a???p?̻?zzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzywxxxxxwwxxxxxxxxxxxyyyzzyyzyyyyyyyyyzzzyyyyzzzzzzzzz{zz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{|{|||||||||||||||||||||||||||||?a???P?̻?||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}||||}|}~~~~~~~~~~~}~~~~~~}}}}~~~}}}}|||||}||||||||||||||||||{|||{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy?a???0?̻?yyyzzzzzzzzzzyzzzyyzzzzzzzzzzzzzzzzzzzzzzxwwwxxxxwwxxxxxxxxxxyyyzyyyyyyyyyyzzzyyyyyyyyzzzzzzzzzzz{zz{z{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}~~~~~~~~~~?a???̻?~~~~}}~~~~~}}}}}}}}}}|||{|}|||||||||}}|||||||{|||{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxyyyyyyyyyyyzyyyyzzzzzzzzyyyyyzzzzzzzzzzzzzzzzzzzzxwwwxxxxwwxxxxxxxxxxxyyyyyyyyyyyyzzzyxy?a????̻?yyzzyyzzzzzzzzzzzz{z{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}||||||}~~~~~~~~~~~~~}}}~~~~~}}~}}}}}}}||{|}|||||||||||||||||{{||{{{{{{{{{{{{{{{zzzzzzzzzzzzzzz?a????̻?zzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzyyzzzzzzzzzzzzzzzzzzzzzzzzzzzxwwxxxxxwxxxxxxxxxxxyyyzyyzyyyyyyzzzyyyyyyyyzzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{|||||||||||||||||||||||||||||?a?İ?̻?||||||||||||||||||||{||{|||||||||||||||||||||||||||||||||||||}}}||||}~~~~~~~~~~~~~~~~~~~~}}}~~~~}}}||||{|}||||||||||||||||||||||{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxyyyyyyyzy?a?Ɛ?̻?zzzzzzzzzzzzyyzzzzyzzzzzzzzzzzzzzzzzzzzzzxwxxxxwwwxxxxxxxxxxxyyyzyyyyyyyyyzzzyyyyyzyyzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{|{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||~~~~~~~~~~?a??p?̻?~~~}}}~~~~~~~~}}}}}}}||{|}||||||||||||}}||{{|||{|{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzxwxxxxwwwxxxxxxxxxxxyyyzyyyyyyzyyyyzzzz?a??P?̻?yyyyyzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}||||}~~~~~~~~~~~~~~~~~~}}}}}~~}}}}||||{|}|||||||||||||||||{||{|{{{{{{{{{{{{{{zzzzzzzzzzzzzzz?a??0?̻?zzzzzzzzzzzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxyyyyyyyyyyyyzyyzzzzzzzzzyyzzzzzzzzzzzzzzzzzzzzzzzywwwxxyyxxwxxxxxxxxxxyyyzyyzyyyyyyzzzyyyyzyyyzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||????̻?|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}|}}}~~~~~~~~~~~}~~~~~~}}~~~}}}}}|||||}|||}|||||||||||||||||||{{{{{{{{{{{{{{{{{{zzzzzzzzzzzzzzzzzzzzzzzyyyyyyyyyyyyyyyzzzyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzz?a ????̻?zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzywwwxxyyxxxxxxxxxxyyyyyyzyyzyyyyyyzzzzyyyzzzyyzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}||}}}~~~~~~~?a...
</code></pre>
<ul>
<li>Working- I get a similar response when I try to run it in C#:</li>
</ul>
<pre><code>async Task StartListener(){
UdpClient listener = new UdpClient(9444);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Parse("192.168.0.194"), 9444);
byte[] requestMessage = Encoding.ASCII.GetBytes("subscribe");
await listener.SendAsync(requestMessage, requestMessage.Length, groupEP);
while (true){
await listener.SendAsync(requestMessage, requestMessage.Length, groupEP);
var udpReceiveResult = await listener.ReceiveAsync(); //Waiting for broadcast
byte[] bytes = udpReceiveResult.Buffer;
Console.WriteLine($"Received broadcast from {groupEP} : {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
</code></pre>
<ul>
<li>Not working- In Python, I use the following script but it times out at the receive function, even though Wireshark shows UDP packets (of a similar kind to the Working instances) being initiated and sent from that device, to my laptop correctly. Not sure what's wrong with my code</li>
</ul>
<pre><code>import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(b"subscribe", ("192.168.0.194", 9444))
sock.connect(("192.168.0.194", 9444)) # Keeping this seems to make no difference
sock.settimeout(5)
try:
while True:
print("Stream receiving.") # Receive data from UDP
data, addr = sock.recvfrom(1024) # <-GETS STUCK HERE, then times out
print(data) # Doesnt land here, prints nothing
except KeyboardInterrupt:
pass
finally:
sock.close() # Stream stopping
print("Stream closed and socket closed.")
</code></pre>
<p>Unhelpful Error message, since without adding the timeout, it just stay stuck at the <code>sock.recvfrom</code> line and does nothing, even after the device has stopped sending data:</p>
<pre><code>Traceback (most recent call last):
File "/Users/saamer/Documents/GitHub/api/a2.py", line 11, in <module>
data, addr = sock.recvfrom(1024) # Buffer size is ?? bytes
^^^^^^^^^^^^^^^^^^^
TimeoutError: timed out
</code></pre>
<hr />
<p>Possibly useful information:</p>
<p>Eventually I want to be able to do something <a href="https://gist.github.com/saamerm/1aa6df3c17456fccf193766e8e77a445" rel="nofollow noreferrer">like this</a> to play the audio. I tried to ask this question to chatGPT and the only thing it suggested was to change the value inside <code>recvfrom()</code>, which I did to 1 million with no positive results
<a href="https://i.sstatic.net/pBxi3Baf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pBxi3Baf.png" alt="Image showing packets in Wireshark" /></a></p>
|
<python><.net><sockets><udp><pyaudio>
|
2024-05-07 23:41:09
| 1
| 5,159
|
Saamer
|
78,445,464
| 2,986,153
|
how to control size of images in quarto html report
|
<p>I have tried to set image size using the chunk options <code>fig.height</code> and <code>fig-height</code> but the image sizes are unaffected.</p>
<pre><code>---
title: 'image size'
author: 'Joseph Powers'
date: 2024-05-07
format:
html:
toc: true
toc-depth: 3
html-math-method: webtex
editor: source
fig.align: 'center'
dpi: 300
include: TRUE
echo: FALSE
message: FALSE
warning: FALSE
error: FALSE
cache: FALSE
code-fold: true
df-print: kable
---
```{python}
import pandas as pd
import numpy as np
from plotnine import *
from mizani.formatters import percent_format
from scipy import stats
my_blue = '#0177c9'
my_red = '#bd0707'
x = np.random.normal(.05, .025, 4000)
# Estimate pdf using kde
pdf = stats.gaussian_kde(x)
# Evaluate pdf at a set of points
points = np.linspace(min(x), max(x), 1000)
estimated_density = pdf.evaluate(points)
df_dens = pd.DataFrame({
'x': points,
'y': estimated_density
})
p = (ggplot(df_dens, aes('x', 'y')) +
geom_line() +
geom_area(data = df_dens[df_dens['x'] >= 0], fill = my_blue) +
geom_area(data = df_dens[df_dens['x'] <= 0], fill = my_red) +
theme_bw() +
theme(panel_grid=element_blank(), axis_text_y=element_blank(), axis_ticks_y=element_blank()) +
labs(y='', x="\nPlausible Treatment Effects") +
scale_x_continuous(
breaks=np.arange(-1, 1.01, 0.01),
labels=percent_format()
)
)
p
```
```{python}
#| out-width: '20%'
#| out-height: '20%'
p
```
```{python}
#| fig-height: 3
#| fig-width: 10
p
```
```{python, fig.height=1, fig.width=1}
#| fig-height: 1
#| fig-width: 1
p
```
</code></pre>
<p><a href="https://i.sstatic.net/IYtQxaeW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IYtQxaeW.png" alt="enter image description here" /></a></p>
|
<python><html><jupyter><quarto>
|
2024-05-07 23:18:57
| 1
| 3,836
|
Joe
|
78,445,434
| 2,192,824
|
How to parse the content in a file to multiple protobuf message
|
<p>For example, I have the following txt file, and I want to use python to parse them to two protobuf message lists. list1 contains an object of "description" and list2 contains two objects of "msg". What would be the best way to do it? I looked into the text_format.py defined by google protobuf, and there is a method called "parse" to parse the text to a message, but it seems it only generates one protobuf message each time, which means I would need to scan the txt file and feed the lines into the parse function. This seems a little cumbersome to me. Wonder whether there are better way to parse the file. Thanks!</p>
<pre><code> description {
type: text
}
msg {
text {
message: "hello"
caller: friend1
}
timestamp {
time:12345
}
}
msg {
text {
message: "how are you"
caller: friend2
}
timestamp {
time:67890
}
}
</code></pre>
|
<python><python-3.x><protocol-buffers>
|
2024-05-07 23:05:04
| 0
| 417
|
Ames ISU
|
78,445,429
| 4,613,606
|
Scraping data after clicking a checkbox in python
|
<p>I am trying to scrape some links from this <a href="https://jobs.tjx.com/global/en/search-results?rk=l-retail-jobs" rel="nofollow noreferrer">career website</a>. Problem is, before scraping the links, I need to select a particular brand (Say Sierra). Question is how do I click on dropdowns and checkboxes to select a brand.</p>
<p>I tried to do following:</p>
<p>Step 1: Click on "Brand" first to enable the checkbox of brands.
(Once we click on Brand, the checkboxes becomes available on normal webpage).</p>
<p>Step 2:
Select the brand by clicking the checkbox. However, I can't find the checkbox using css or xpath.</p>
<p>Step 3:
Once the checkbox is selected, we will get links of many job postings. but only first 10 are shown on each page. I need to navigate and find the links of all job postings. (11-20, 21-30 etc.)</p>
<p>Code for step 1:
I tried following code to click on Brand, but I am not sure if my code is able to do that (I don't know how to verify if following is working).</p>
<pre><code>brand_dropdown_button = driver.find_element(By.XPATH, "//button[contains(text(), 'Brand')]")
brand_dropdown_button.click()
</code></pre>
<p>Code for step 2: (I tried following, which does not work).</p>
<pre><code>checkbox = driver.find_element(By.XPATH, "//input[@value='Sierra']") # no such elements
checkbox = driver.find_element(By.CSS_SELECTOR, "input[value='Sierra']") # no such element
</code></pre>
<p>I tried giving it time, but even after waiting for 10 seconds, my code can't find any checkboxes</p>
<p>Another problem is that the url does not change when we click "brand" to enable checkboxes, or when we select a particular brand. That is why I can't verify anything manually.</p>
|
<python><html><css><selenium-webdriver><web-scraping>
|
2024-05-07 23:03:11
| 1
| 1,126
|
Gaurav Singhal
|
78,445,394
| 2,475,195
|
Pandas rolling min, corresponding value from other column
|
<p>I have an index-like column whose value I want to report for the rolling min value. Here's the code:</p>
<pre><code>d = pd.DataFrame.from_dict({'ix':[0,1,2,3,4,5], 'val': [1,-2,5,4,9,6]})
d['first'] = d['val'].rolling(3).apply(lambda x: x.iloc[0] if not x.empty else None)
d['min'] = d['val'].rolling(3).min()
d['ix_min'] = [np.nan, np.nan, 1, 1, 3, 3] # this is what I actually want to compute
print (d)
val first min ix_min
0 1 NaN NaN NaN
1 -2 NaN NaN NaN
2 5 1.0 -2.0 1.0
3 4 -2.0 -2.0 1.0
4 9 5.0 4.0 3.0
5 6 4.0 4.0 3.0
</code></pre>
|
<python><pandas><dataframe><rolling-computation>
|
2024-05-07 22:47:58
| 1
| 4,355
|
Baron Yugovich
|
78,445,374
| 2,561,747
|
How to expand dict into f-string similar to {variable=}?
|
<p>Is there a way to expand a dict into a f-string with a similar result to using the <code>{variable=}</code> syntax? Where each key-value pair would be treated as key=value, and items would be separated by commas?</p>
<p>For example:</p>
<pre><code>kwargs = dict(a=5, b=2)
f'got {**kwargs=}' # results in an error:
SyntaxError: f-string: invalid syntax
# desired output: 'got a=5, b=2'
</code></pre>
|
<python>
|
2024-05-07 22:39:25
| 1
| 1,394
|
user2561747
|
78,445,372
| 18,764,592
|
Flask: cannot curl it from docker container
|
<p>Have 2 applications:</p>
<ol>
<li>Inside docker container</li>
<li>Python Flask as http://localhost:5000. 1st application should call
Python Flask.</li>
</ol>
<p>Yes, I know that localhost unreachable from docker container. To get localhost, I put the following lines in <code>docker-compose.yml</code>:</p>
<pre class="lang-yaml prettyprint-override"><code> extra_hosts:
- "host.docker.internal:host-gateway"
</code></pre>
<p>Check availability of localhost from docker container:</p>
<pre class="lang-bash prettyprint-override"><code>vbulash@vbulash-notebook:~/VSCode/device$ docker compose exec app_device bash
www@c23d9e616cf9:/var/www$ ping -c5 host.docker.internal
PING host.docker.internal (172.17.0.1): 56 data bytes
64 bytes from 172.17.0.1: icmp_seq=0 ttl=64 time=0.203 ms
64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.108 ms
64 bytes from 172.17.0.1: icmp_seq=2 ttl=64 time=0.111 ms
64 bytes from 172.17.0.1: icmp_seq=3 ttl=64 time=0.107 ms
64 bytes from 172.17.0.1: icmp_seq=4 ttl=64 time=0.112 ms
--- host.docker.internal ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.107/0.128/0.203/0.037 ms
</code></pre>
<p>Ping - ok</p>
<p>Then I try to call existing route in working Flask:</p>
<pre class="lang-bash prettyprint-override"><code>www@c23d9e616cf9:/var/www$ curl -X 'POST' http://host.docker.internal:5000/ping
curl: (7) Failed to connect to host.docker.internal port 5000 after 0 ms: Couldn't connect to server
</code></pre>
<p>What's wrong?</p>
|
<python><python-3.x><docker><flask><docker-compose>
|
2024-05-07 22:36:23
| 0
| 385
|
vbulash
|
78,445,310
| 3,746,427
|
Custom x-axis matplotlib
|
<p>I have written this python code to plot normal distribution where I am trying to modify x-axis, however, it is not appearing</p>
<pre><code>import numpy as np
from scipy.stats import norm
from matplotlib import rcParams
import matplotlib.pyplot as plt
import matplotlib as mpl
# make greek symbols appear on plot
rcParams.update(mpl.rcParamsDefault)
mean = 0
standard_deviation = 1
num_points = 10**6
# Range for smooth plotting, covering 3 standard deviations
x = np.linspace(mean - 3*standard_deviation, mean + 3*standard_deviation, num_points)
kde = norm.pdf(x, mean, standard_deviation)
num_std_ticks = 4 # Number of standard deviation marks on either side
ticks = np.arange(mean - num_std_ticks * standard_deviation,
mean + (num_std_ticks + 1) * standard_deviation,
standard_deviation)
plt.plot(x, kde)
plt.suptitle("Normal Distribution", fontsize=14, fontweight='bold', y=1)
plt.title("(Empirical Rule)", fontsize=12, x=0.5, y=1.025)
plt.text(0.5, 1,
r'$\mu = ' + str(mean) + r',\sigma = ' + str(standard_deviation) + r'$',
transform=plt.gca().transAxes, ha='center', fontsize=10)
ax = plt.gca() # Get the current Axes object
ax.axis('off') # Remove all axes
ax.spines['bottom'].set_visible(True) # Show only the x-axis
ax.xaxis.set_ticks_position('bottom') # Set the tick position to the bottom
ax.set_xticks(ticks) # Set the x-ticks
plt.show()
</code></pre>
<p><code>ax.axis('off')</code> seems to work fine to remove the axes, but the following lines of code not adding the axis back. I want the x-axis to look like this in the figure below (I know it is bit complicated but any help is appreciated).</p>
<p><a href="https://i.sstatic.net/ek9TwKvI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ek9TwKvI.png" alt="enter image description here" /></a></p>
|
<python><matplotlib>
|
2024-05-07 22:10:46
| 1
| 2,022
|
nsinghphd
|
78,445,270
| 825,227
|
Python defaultdict using lambda function causes error: TypeError: <lambda>() missing 1 required positional argument: 'x'
|
<p>Trying to map input text to associated numeric values, allowing for missing non-represented entries using a <code>defaultdict</code>.</p>
<p>Running the below works, but when I add the default using a <code>lambda</code> I get an error.</p>
<pre><code>z
Out[216]:
0 $1,001
1 $1,001
2 $50,001
3 $15,001
4 $50,001
586 $1,001
587 $1,001
588 $1,001
589 $1,001
590 $1,001
Name: 0, Length: 591, dtype: object
amt_map = {
"$1": 500,
"$1,001": 2500,
"$15,001": 32500,
"$50,001": 75000,
"$100,001": 175000,
"$250,001": 350000,
"$500,001": 750000,
"$1,000,001": 2000000,
"$5,000,001": 10000000,
"25,000,001": 25000000
}
z.map(amt_map)
Out[220]:
0 2500.0
1 2500.0
2 75000.0
3 32500.0
4 75000.0
</code></pre>
<p>Using the default lambda throws causes an error however:</p>
<pre><code>from collections import defaultdict
d = {
"$1": 500,
"$1,001": 2500,
"$15,001": 32500,
"$50,001": 75000,
"$100,001": 175000,
"$250,001": 350000,
"$500,001": 750000,
"$1,000,001": 2000000,
"$5,000,001": 10000000,
"25,000,001": 25000000
}
amt_map = defaultdict(lambda x: x.replace('$',''), d)
z.map(amt_map)
Traceback (most recent call last):
File "/tmp/ipykernel_470946/75548175.py", line 1, in <module>
z.map(amt_map)
File "/home/chris/anaconda3/lib/python3.9/site-packages/pandas/core/base.py", line 825, in <lambda>
mapper = lambda x: dict_with_default[x]
TypeError: <lambda>() missing 1 required positional argument: 'x'
</code></pre>
<p>Searching has suggested this is due to different number of arguments used by a function and included lambda, but I'm not seeing how/why that would cause an issue here.</p>
<p><a href="https://stackoverflow.com/questions/56813440/typeerror-lambda-missing-1-required-positional-argument-item">TypeError: <lambda>() missing 1 required positional argument: 'item'</a></p>
|
<python><lambda><defaultdict>
|
2024-05-07 21:58:54
| 2
| 1,702
|
Chris
|
78,445,183
| 2,475,195
|
Pandas rolling - first value in window
|
<p>I have code that looks like this</p>
<pre><code>d = pd.DataFrame.from_dict({'ix':[0,1,2,3,4,5], 'val': [1,-2,5,4,9,6]})
d['first'] = d['val'].rolling(3).agg(lambda rows: rows[0])
</code></pre>
<p>Per the suggestion here <a href="https://stackoverflow.com/questions/60940098/taking-first-and-last-value-in-a-rolling-window">Taking first and last value in a rolling window</a>, but I am getting the following error:</p>
<pre><code>ValueError: 0 is not in range
</code></pre>
<p>Any idea how I can get the first and last value from a rolling window in <code>pandas</code>?</p>
|
<python><pandas><dataframe><rolling-computation>
|
2024-05-07 21:34:35
| 1
| 4,355
|
Baron Yugovich
|
78,445,161
| 8,652,920
|
How to set the permissions of all files in a folder, given directory name using python?
|
<p>Self explanatory. But basically I'm trying to <code>shutil.rmtree</code> <code>~/.ssh</code> and a private key has restrictive read/write permissions.</p>
<p>I don't want to make any assumptions about the name of the key, so I want to chmod 777 everything in <code>~/.ssh</code> and then <code>shutil.rmtree</code> it. How do I do that?</p>
|
<python><python-3.x><chmod><shutil>
|
2024-05-07 21:29:15
| 1
| 4,239
|
notacorn
|
78,445,033
| 6,546,694
|
Implement frequency encoding in polars
|
<p>I want to replace the categories with their occurrence frequency. My dataframe is lazy and currently I cannot do it without 2 passes over the entire data and then one pass over a column to get the length of the dataframe. Here is how I am doing it:</p>
<p>Input:</p>
<pre><code>df = pl.DataFrame({"a": [1, 8, 3], "b": [4, 5, None], "c": ["foo", "bar", "bar"]}).lazy()
print(df.collect())
output:
shape: (3, 3)
┌─────┬──────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪═════╡
│ 1 ┆ 4 ┆ foo │
│ 8 ┆ 5 ┆ bar │
│ 3 ┆ null ┆ bar │
└─────┴──────┴─────┘
</code></pre>
<p>Required output:</p>
<pre><code>shape: (3, 3)
┌─────┬──────┬────────────────────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪════════════════════╡
│ 1 ┆ 4 ┆ 0.3333333333333333 │
│ 8 ┆ 5 ┆ 0.6666666666666666 │
│ 3 ┆ null ┆ 0.6666666666666666 │
└─────┴──────┴────────────────────┘
</code></pre>
<p>transformation code:</p>
<pre><code>l = df.select("c").collect().shape[0]
rep = df.group_by("c").len().collect().with_columns(pl.col("len")/l).lazy()
df_out = df.with_context(rep.select(pl.all().name.prefix("context_"))).with_columns(pl.col("c").replace(pl.col("context_c"), pl.col("context_len"))).collect()
print(df_out)
output:
shape: (3, 3)
┌─────┬──────┬────────────────────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪════════════════════╡
│ 1 ┆ 4 ┆ 0.3333333333333333 │
│ 8 ┆ 5 ┆ 0.6666666666666666 │
│ 3 ┆ null ┆ 0.6666666666666666 │
└─────┴──────┴────────────────────┘
</code></pre>
<p>As you can see I am collecting the data 2 times full and there is one collect over a single column. Can I do better?</p>
|
<python><dataframe><python-polars>
|
2024-05-07 21:00:23
| 1
| 5,871
|
figs_and_nuts
|
78,444,883
| 13,119,730
|
Duplicate traces in FastAPI OpenTelemetry Azure Application Insight
|
<p>Im currently setting up Otel for our cloud azure solution. We are using Azure WebApp and AzureAppInsights. The app is fastapi backend.</p>
<p>I have set up the otel like:</p>
<pre class="lang-py prettyprint-override"><code>def setup_otel(app: FastAPI):
if settings.APPLICATIONINSIGHTS_CONNECTION_STRING:
configure_azure_monitor(
connection_string=settings.APPLICATIONINSIGHTS_CONNECTION_STRING,
logger_name=settings.LOGGER_NAME
)
</code></pre>
<p>The traces for transactions are present in App Insight but the root (probably) fastapi implementation traces are duplicated - <code>POST /api/ingest/v2/upload http receive</code>, more can be seen at screenshot:</p>
<p><a href="https://i.sstatic.net/QsFQqgGn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QsFQqgGn.png" alt="AppInsights" /></a></p>
<p>Can this be somehow fixed?</p>
<p>Thanks in advance</p>
|
<python><azure><fastapi><azure-application-insights><open-telemetry>
|
2024-05-07 20:19:20
| 1
| 387
|
Jakub Zilinek
|
78,444,814
| 5,693,706
|
Altair use multiple selections in multi-layer chart
|
<p>I would like to have multiple selections in a multi-layer chart. One selection should highlight the closest line and the other should highlight the point on each line closest to the current x position of the mouse.</p>
<p>I can achieve this separately as shown below.</p>
<p>Highlight line:</p>
<pre class="lang-py prettyprint-override"><code>select = alt.selection_point(encodings=['x'], on='mouseover', nearest=True)
line_select = alt.selection_point(fields=['symbol'], nearest=True, on='mouseover')
base = alt.Chart(data.stocks.url).encode(color='symbol:N', x='date:T', y='price:Q')
selected_lines = base.mark_point(opacity=0).add_params(line_select)
line = base.mark_line().encode(
strokeWidth=alt.condition(line_select, alt.value(3), alt.value(1))
)
(
line
+ selected_lines
)
</code></pre>
<p><a href="https://i.sstatic.net/kEtzRisb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kEtzRisb.png" alt="enter image description here" /></a></p>
<p>Highlight points:</p>
<pre class="lang-py prettyprint-override"><code>select = alt.selection_point(encodings=['x'], on='mouseover', nearest=True)
base = alt.Chart(data.stocks.url).encode(color='symbol:N', x='date:T', y='price:Q')
line = base.mark_line().encode(
)
marks = base.mark_point(fill='black', strokeWidth=0).encode(
opacity=alt.condition(select, alt.value(1), alt.value(0)),
).add_params(select)
(
line
+ marks
)
</code></pre>
<p><a href="https://i.sstatic.net/9QWEhOLK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9QWEhOLK.png" alt="enter image description here" /></a></p>
<p>However, if I try to combine them the point selection stops working and only the line selection applies.</p>
<pre class="lang-py prettyprint-override"><code>select = alt.selection_point(encodings=['x'], on='mouseover', nearest=True)
line_select = alt.selection_point(fields=['symbol'], nearest=True, on='mouseover')
base = alt.Chart(data.stocks.url).encode(color='symbol:N', x='date:T', y='price:Q')
selected_lines = base.mark_point(opacity=0).add_params(line_select)
line = base.mark_line().encode(
strokeWidth=alt.condition(line_select, alt.value(3), alt.value(1))
)
marks = base.mark_point(fill='black', strokeWidth=0).encode(
opacity=alt.condition(select, alt.value(1), alt.value(0)),
).add_params(select)
(
line
+ selected_lines
+ marks
)
</code></pre>
<p><a href="https://i.sstatic.net/EuvvKAZP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EuvvKAZP.png" alt="enter image description here" /></a></p>
<p>I have also recreated this behavior with a small modification to the example suggested by @r-beginners in the comments.</p>
<p>Example as is:</p>
<pre class="lang-py prettyprint-override"><code>import altair as alt
import pandas as pd
import numpy as np
np.random.seed(42)
columns = ["A", "B", "C"]
source = pd.DataFrame(
np.cumsum(np.random.randn(100, 3), 0).round(2),
columns=columns, index=pd.RangeIndex(100, name="x"),
)
source = source.reset_index().melt("x", var_name="category", value_name="y")
# Create a selection that chooses the nearest point & selects based on x-value
nearest = alt.selection_point(nearest=True, on="pointerover",
fields=["x"], empty=False)
# The basic line
line = alt.Chart(source).mark_line(interpolate="basis").encode(
x="x:Q",
y="y:Q",
color="category:N"
)
# Draw points on the line, and highlight based on selection
points = line.mark_point().encode(
opacity=alt.condition(nearest, alt.value(1), alt.value(0))
)
# Draw a rule at the location of the selection
rules = alt.Chart(source).transform_pivot(
"category",
value="y",
groupby=["x"]
).mark_rule(color="gray").encode(
x="x:Q",
opacity=alt.condition(nearest, alt.value(0.3), alt.value(0)),
tooltip=[alt.Tooltip(c, type="quantitative") for c in columns],
).add_params(nearest)
# Put the five layers into a chart and bind the data
alt.layer(
line, points, rules
).properties(
width=600, height=300
)
</code></pre>
<p>I can create a line selector by adding this line of code</p>
<pre class="lang-py prettyprint-override"><code>nearest_line = alt.selection_point(nearest=True, on="mouseover", fields=["category"])
</code></pre>
<p>and can then highlight the lines by changing the line definition to:</p>
<pre class="lang-py prettyprint-override"><code># The basic line
line = alt.Chart(source).mark_line(interpolate="basis").encode(
x="x:Q",
y="y:Q",
color="category:N",
strokeWidth=alt.condition(nearest_line, alt.value(3), alt.value(1)),
)
</code></pre>
<p>I then tried to attach the new parameter to all three layers, and it did not work for any case.</p>
<ol>
<li>Line layer (all lines show true condition, 3 stroke width)</li>
<li>Points layer (Line highlight works, but points/tooltips no longer appear)</li>
<li>Rules layer (all lines show false condition, 1 stroke width)</li>
</ol>
|
<python><altair>
|
2024-05-07 20:01:49
| 0
| 1,038
|
kgoodrick
|
78,444,757
| 20,179,987
|
How to use the Frida Interceptor JS script from Python
|
<p>I'm working on a plugin for Binary Ninja where one of the features is to trace functions using Frida. The plugin is written in python (using python 3.10) but the Frida commands are in JavaScript. I am trying to load some JS code and make Frida run it (It is part of my understanding that Frida provides its own VM for JS, but I may have misunderstood).</p>
<p>My current problem is that I can't get the JS template <code>trace_template</code> to work (it doesn't print any of the <code>console.log</code> into the Binary Ninja Console). I am not sure if the problem is the template itself (which seems to print correctly) or the <code>frida.core.Session.create_script(formatted)</code>. I am not seeing the <code>console.log</code> from the <code>Interceptor.attach</code> <code>onEnter</code> and <code>onLeave</code> functions, and I need those to run to continue.</p>
<p>I added 3 blocks of code, the first two I include the necessary code to reproduce the error. The last one is just there in case a view of the whole file where the 2nd code block resides is necesary.</p>
<p>This code is an object representing the function being traced. The <code>trace_template</code> is the JS code I want to run.</p>
<pre class="lang-py prettyprint-override"><code>import frida
class Tracee:
session: frida.core.Session
pid: int
active: bool
def __init__(self, session, pid):
self.session = session
self.pid = pid
self.active = False
def __eq__(self, other):
if not isinstance(other, Tracee):
return NotImplemented
return self.pid == other.pid
def __hash__(self):
return hash(self.pid)
trace_template = """
const base_mod = Process.getModuleByName('{binary_name}').base;
const func_ptr = ptr(base_mod.add({func_addr}));
Interceptor.attach(func_ptr, {{
onEnter: function(args) {{
console.log('Entered function! had argument: ', args[0].toInt32().toString(16));
var msg = {{
'event': 'call',
'args': args[0].toInt32().toString(16)
}};
send(msg);
}},
onLeave: function(retval) {{
console.log('Returning from function: ', retval.toInt32().toString(16));
var msg = {{
'event': 'return',
'args': retval.toInt32().toString(16)
}};
send(msg);
}}
}});
send({{
'maybeidk': DebugSymbol.fromName('{func_name}')
}})
"""
</code></pre>
<p>This is the function which uses the <code>trace_template</code> and is supposed to run it.</p>
<pre class="lang-py prettyprint-override"><code>import binaryninja as bn
from .trace import Tracee, trace_template
from frida_tools.application import Reactor
def trace_functions(self, tracee: Tracee):
bv = bn.BinaryView
t = self.targets[0]
fn = self.bv.file.original_filename.split('/')[-1]
formatted = trace_template.format(
binary_name=fn,
func_addr=t.lowest_address,
func_name=t.name)
slog.log_warn(formatted)
script = tracee.session.create_script(formatted)
script.on('message', lambda message,data: Reactor.schedule(
lambda: self._on_message(tracee.pid, message)
))
script.load()
self._device.resume(tracee.pid)
def _on_message(self, pid: int, msg: str):
"""
Takes messages sent from gadgets/controllers and handles them
Msg is sent as str, convert to dict using json.loads()
"""
msg = loads(msg)
match msg['type']:
case "log":
payload = msg['payload']
level = msg['level']
glog.log_info(f"[PID {pid}-{level}] {payload}")
case _:
glog.log_warn(f"[PID {pid}] {msg}")
</code></pre>
<p>And that function is part of this file of code, which I'm adding in case more context is necessary:</p>
<pre class="lang-py prettyprint-override"><code>import json
import binaryninja as bn
import frida
import time
import threading
from enum import Enum
from pathlib import Path
from frida_tools.application import Reactor
from typing import Optional, List, Callable
from json import loads
from .settings import SETTINGS
from .log import system_logger as slog, gadget_logger as glog
from .helper import TRACE_TAG, get_functions_by_tag, mark_func
from .trace import Tracee, trace_template
__portal_thread = None
_stop_event = threading.Event()
class PortalAction(Enum):
INIT = 1
TRACE = 2
def stop_server(bv: bn.BinaryView) -> None:
"""
Stops server with stop_event
"""
global __portal_thread, _stop_event
if __portal_thread is None:
slog.log_warn("Portal thread not up")
bn.show_message_box(
"Error: Portal not instantiated",
"Frida-portal thread is not running.",
bn.MessageBoxButtonSet.OKButtonSet,
bn.MessageBoxIcon.ErrorIcon)
return
slog.log_info("Stopping server...")
_stop_event.set()
__portal_thread.join()
__portal_thread = None
_stop_event.clear()
slog.log_info("Server closed.")
def mark_function(bv: bn.BinaryView, func: bn.Function):
"""
Uses helper to mark function and schedule a reload of all marked functions
"""
global __portal_thread
mark_func(bv, func)
if is_portal_running():
__portal_thread.app.schedule_reload()
def is_portal_running() -> bool:
return __portal_thread is not None and __portal_thread.is_alive()
def clear_traced_functions(bv: bn.BinaryView):
if not is_portal_running():
slog.log_warn("No functions to clear!")
return
for mark in __portal_thread.app.targets:
mark_func(bv, mark)
__portal_thread.app.schedule_reload()
def start_server(bv: bn.BinaryView) -> None:
"""
Start server thread with PortalApp running.
Run thread as daemon to not block and be closed when exiting.
"""
global __portal_thread
if __portal_thread is not None:
bn.show_message_box(
"Error",
"Error: Portal already running",
bn.MessageBoxButtonSet.OKButtonSet,
bn.MessageBoxIcon.ErrorIcon)
slog.log_warn("Portal server already created!")
else:
slog.log_info('Starting frida portal...')
__portal_thread = threading.Thread(target=instance_app, args=(bv, ))
__portal_thread.daemon = True
__portal_thread.start()
def instance_app(bv: bn.BinaryView) -> None:
global __portal_thread
app = PortalApp(bv)
__portal_thread.app = app
app.run()
class PortalApp:
"""
Portal app based on example found under frida_python
Uses Reactor from frida_tools to handle async tasks
"""
bv: bn.BinaryView
_reactor: Reactor
_session: Optional[frida.core.Session]
cluster_params: frida.EndpointParameters
control_params: frida.EndpointParameters
action: PortalAction
targets: List[bn.Function]
tracees: List[Tracee]
def __init__(self, bv: bn.BinaryView):
self._reactor = Reactor(run_until_return=self.handle)
self.bv = bv
try:
cluster_ip = bv.query_metadata('fridalens_cluster_ip')
cluster_port = int(bv.query_metadata('fridalens_cluster_port'))
control_ip = bv.query_metadata('fridalens_control_ip')
control_port = int(bv.query_metadata('fridalens_control_port'))
except:
print('No saved settings, using defailt\nAddress=127.0.0.1\ncluster port=27052\ncontrol port=27042')
cluster_ip = "127.0.0.1"
cluster_port = 27052
control_ip = "127.0.0.1"
control_port = 27042
cluster_params = frida.EndpointParameters(
address=cluster_ip,
port=cluster_port
)
control_params = frida.EndpointParameters(
address=control_ip, port=control_port, authentication=None)
service = frida.PortalService(cluster_params, control_params)
self._service = service
self._device = service.device
self._session = None
self.action = PortalAction.INIT
self.targets = get_functions_by_tag(bv, TRACE_TAG)
self.tracees = []
service.on("node-connected", lambda *args: self._reactor.schedule(
lambda: self._on_node_connected(*args)
))
service.on("node-joined", lambda *args: self._reactor.schedule(
lambda: self._on_node_joined(*args)
))
service.on("node-left", lambda *args: self._reactor.schedule(
lambda: self._on_node_left(*args)
))
service.on("node-disconnected", lambda *args: self._reactor.schedule(
lambda: self._on_node_disconnected(*args)
))
service.on("message", lambda *args: self._reactor.schedule(
lambda: self._on_message(*args)
))
service.on("controller-connected", lambda *args: self._reactor.schedule(
lambda: self._on_controller_connected(*args)
))
service.on("controller-disconnected", lambda *args: self._reactor.schedule(
lambda: self._on_controller_disconnected(*args)
))
service.on("subscribe", lambda *args: self._reactor.schedule(
lambda: self._on_subscribe(*args)
))
def _on_node_connected(self, connection_id, remote_addr):
slog.log_info(f"Node connected: {connection_id}, Address: {remote_addr}")
def _on_node_disconnected(self, connection_id, remote_addr):
slog.log_info(f"Node disconnected: {connection_id}, Address: {remote_addr}")
def _on_detached(self, pid: int, reason: str):
slog.log_info(f"[DETACH] Tracee: {pid} reason: {reason}")
def _on_node_joined(self, connection_id, app):
"""
Happens along with connecting, but passes application info
Do most of logic here
"""
slog.log_info(f"Node joined: {connection_id}, Application: {app}")
sesh = self._device.attach(app.pid)
#TODO
sesh.on("detached",
lambda reason: self._reactor.schedule(
lambda: self._on_detached(app.pid, reason)
))
tracee = Tracee(sesh, app.pid)
if tracee not in self.tracees:
self.tracees.append(tracee)
self.action = PortalAction.TRACE
else:
slog.log_warn(f"Repeated tracee triggered node_joined; PID: {tracee.pid}")
def _on_node_left(self, connection_id, app):
"""
Happens along with disconnecting, but passes application info
Do most of logic here
"""
slog.log_info(f"Node left: {connection_id}, Address: {app}")
self.tracees = [tracee for tracee in self.tracees if tracee.pid != app.pid]
#TODO rename to idle or something similar
if len(self.tracees) == 0:
self.action = PortalAction.INIT
def _on_controller_connected(self, connection_id, remote_addr):
slog.log_info(f"Controller Connected: {connection_id}, Address: {remote_addr}")
def _on_controller_disconnected(self, connection_id, remote_addr):
slog.log_info(f"Controller disconnected: {connection_id}, Address: {remote_addr}")
def _on_message(self, pid: int, msg: str):
"""
Takes messages sent from gadgets/controllers and handles them
Msg is sent as str, convert to dict using json.loads()
"""
msg = loads(msg)
match msg['type']:
case "log":
payload = msg['payload']
level = msg['level']
glog.log_info(f"[PID {pid}-{level}] {payload}")
case _:
glog.log_warn(f"[PID {pid}] {msg}")
def _on_subscribe(self, connection_id):
slog.log_info(f'New subscription: {connection_id}')
def run(self):
slog.log_info("Starting portal run")
self._reactor.schedule(self._start)
self._reactor.run()
def _start(self):
self._service.start()
self._device.enable_spawn_gating()
def _stop(self):
for tracee in self.tracees:
self._reactor.schedule(lambda: tracee.session.detach())
self._service.stop()
def _reload(self):
targets = get_functions_by_tag(self.bv, TRACE_TAG)
self.targets = targets
slog.log_info(f"Targets found: {targets}")
if len(self.tracees) > 0:
self.action = PortalAction.TRACE
def schedule_reload(self):
"""
KISS for now ig
"""
self._reactor.schedule(self._reload)
def trace_functions(self, tracee: Tracee):
t = self.targets[0]
fn = self.bv.file.original_filename.split('/')[-1]
formatted = trace_template.format(
binary_name=fn,
func_addr=t.lowest_address,
func_name=t.name)
slog.log_warn(formatted)
script = tracee.session.create_script(formatted)
script.on('message', lambda message,data: self._reactor.schedule(
lambda: self._on_message(tracee.pid, message)
))
script.load()
self._device.resume(tracee.pid)
def handle(self, reactor):
global _stop_event
while not _stop_event.is_set():
match self.action:
case PortalAction.INIT:
slog.log_info("Idling...")
if len(self.targets) > 0:
slog.log_info(f"Functions marked: {self.targets}")
case PortalAction.TRACE:
slog.log_info(f"Tracees: {list(map(lambda t: t.pid, self.tracees))}")
if len(self.targets) <= 0:
slog.log_warn("No functions to trace yet!")
else:
for t in list(filter(lambda x: not x.active, self.tracees)):
t.active = True
self._reactor.schedule(
lambda: self.trace_functions(t)
)
time.sleep(1)
slog.log_info("Finishing up")
self._stop()
</code></pre>
|
<javascript><python><plugins><frida>
|
2024-05-07 19:45:19
| 0
| 322
|
GABRIEL R GARCIA-AVILES
|
78,444,497
| 6,817,610
|
Upgrading to Python 3.10, different users - python3 alias points to same binary but shows different versions
|
<p>In Debian 11 based docker container, I'm a bit confused as to why <code>root</code> and <code>jenkins</code> users' <code>python3</code> command is pointing to the same binary but have different versions:</p>
<pre><code>sh-5.1$ whoami
jenkins
sh-5.1$ python3 --version
Python 3.9.2
sh-5.1$ which python3
/usr/bin/python3
sh-5.1$
exit
root@c5891e24911a:/home/jenkins#
root@c5891e24911a:/home/jenkins# whoami
root
root@c5891e24911a:/home/jenkins# which python3
/usr/bin/python3
root@c5891e24911a:/home/jenkins# python3 --version
Python 3.8.16
</code></pre>
<p>I tried changing version in <code>.bachrc</code> to 3.10 but I guess it wouldn't work because that's for non-login shells:
<a href="https://i.sstatic.net/vQyCeeo7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vQyCeeo7.png" alt="enter image description here" /></a></p>
<p>How can I make jenkins user's <code>python3</code> command to point to version <strong>3.10</strong> permanently?</p>
|
<python><linux><bash><shell><debian>
|
2024-05-07 18:43:39
| 1
| 953
|
Anton Kim
|
78,444,488
| 9,251,158
|
How to force x label on Matplotlib
|
<p>I want to add labels on the horizontal and vertical axes on Matplotlib, and I can't seem to. Here's a minimal reproducible example:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
# generate x and y
x = np.linspace(0, 1, 101)
y = 1 + x + 0.4 * np.random.random(len(x))
plt.figure(figsize = (5, 2.7))
plt.plot(x, y, 'b.')
plt.ylabel('y')
plt.xlabel('x')
plt.savefig("tmp.png", dpi=300)
</code></pre>
<p>and the result show the <code>y</code> label, but not <code>x</code>. (Due to <code>sstatic.net</code> problems, I can't include the image here, but you can find it <a href="https://www.dropbox.com/scl/fi/f2sm7waicn5ssh6gj6sin/tmp.png?rlkey=oxv6os5magwtcwwafoxrzrowl&st=sep0t1wy&dl=0" rel="nofollow noreferrer">here</a>.</p>
<p>I searched online and couldn't find a solution. If I added subplots or axes, I could do <code>ax.set_xlabel("x")</code>, but I think it should work without axes.</p>
<p>I have Python 3.11.6.</p>
<p>How can I force adding a horizontal label to a plot?</p>
|
<python><matplotlib><axis-labels>
|
2024-05-07 18:39:51
| 0
| 4,642
|
ginjaemocoes
|
78,444,253
| 5,878,756
|
Autoencoders and Polar Coordinates
|
<p>Can an autoencoder learn the transformation into polar coordinates? If a set of 2D data lies approximately on a circle, there is a lower-dimensional manifold, parameterized by the angle, that describes the data 'best'.</p>
<p>I tried various versions without success.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import layers, losses
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
class DeepAutoEncoder(Model):
def __init__(self, dim_data: int, num_hidden: int,
num_comp: int,
activation: str = 'linear'):
super(DeepAutoEncoder, self).__init__()
self.encoder = tf.keras.Sequential([
layers.Dense(num_hidden, activation=activation),
layers.Dense(num_comp, activation=activation),
])
self.decoder = tf.keras.Sequential([
layers.Dense(num_hidden, activation=activation),
layers.Dense(dim_data, activation='linear')
])
def call(self, x):
encoded = self.encoder(x)
decoded = self.decoder(encoded)
return decoded
# Data
num_obs = 1000
np.random.seed(1238)
e = np.random.randn(num_obs, 1)
t = np.linspace(0, 2*np.pi, num_obs)
x = 1 * np.cos(t)
y = np.sin(t) + 0.2*e[:, 0]
X = np.column_stack((x, y))
num_comp = 1
activations = ['linear', 'sigmoid']
ae = {a: None for a in activations}
for act in activations:
ae[act] = DeepAutoEncoder(dim_data=2, num_comp=num_comp,
num_hidden=3, activation=act)
ae[act].compile(optimizer=Adam(learning_rate=0.01),
loss='mse')
ae[act].build(input_shape=(None, 2))
ae[act].summary()
history = ae[act].fit(X, X, epochs=200,
batch_size=32,
shuffle=True)
ae[act].summary()
plt.plot(history.history["loss"], label=act)
plt.legend()
f, axs = plt.subplots(2, 2)
for i, a in enumerate(activations):
axs[0, i].plot(x, y, '.', c='k')
z = ae[a].encoder(X)
# x_ae = ae[a].decoder(ae[a].encoder(X))
x_ae = ae[a](X)
axs[0, i].plot(x_ae[:, 0], x_ae[:, 1], '.')
# axs[0, i].plot(x_pca[:, 0], x_pca[:, 1], '.', c='C3')
axs[1, i].plot(z)
axs[0, i].axis('equal')
axs[0, i].set(title=a)
</code></pre>
<p>The reconstructed data looks like:</p>
<p><a href="https://i.sstatic.net/fORDaL6t.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fORDaL6t.png" alt="enter image description here" /></a></p>
<p>I assume that the reason is that the transformation sigmoid(W * z + b) is far away from a non-linear matrix [[cos(theta) sin(theta)], [-sin(theta) sin(theta)]] required to map the latent variable back into the original space.</p>
<p>Any thoughts would be great!</p>
<p>Thank you very much.</p>
|
<python><tensorflow><autoencoder><polar-coordinates>
|
2024-05-07 17:46:17
| 1
| 924
|
deckard
|
78,444,223
| 6,714,667
|
How to deal with csvs with description on top in langchain & Missing columns?
|
<p>I have the following csv i want to load with langchain:</p>
<p><a href="https://i.sstatic.net/2fy8Hw8M.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2fy8Hw8M.png" alt="enter image description here" /></a></p>
<p>i did the following:</p>
<pre><code>loader = CSVLoader(file_path='shopids.csv', encoding="utf-8",csv_args={'delimiter': ','} )
</code></pre>
<p>however when i looked at the output it misses the Comment column and i am unsure how to parse this csv when it has a header like above.</p>
<pre><code>[
Document(page_content='\ufeff: \n: \nID: 123456\nparent org: 12', metadata={'source': 'shopids.csv', 'row': 0}),
Document(page_content='\ufeff: \n: \nID: sallys clothes\nparent org: H&M', metadata={'source': 'shopids.csv', 'row': 1}),
Document(page_content='\ufeff: \n: \nID: \nparent org: ', metadata={'source': 'shopids.csv', 'row': 2}),
Document(page_content='\ufeff: \n: \nID: \nparent org: ', metadata={'source': 'shopids.csv', 'row': 3}),
Document(page_content='\ufeff: DocID\n: Country\nID: ID\nparent org: parent org', metadata={'source': 'shopids.csv', 'row': 4}),
Document(page_content='\ufeff: sads\n: UK\nID: 34554\nparent org: julies', metadata={'source': 'shopids.csv', 'row': 5}),
Document(page_content='\ufeff: b. shp insurance\n: Spain\nID: 4567\nparent org: aa', metadata={'source': 'shopids.csv', 'row': 6}),
Document(page_content='\ufeff: sads\n: Germany\nID: 34554\nparent org: julies', metadata={'source': 'shopids.csv', 'row': 7}),
Document(page_content='\ufeff: b. shp insurance\n: USA\nID: 4567\nparent org: aa', metadata={'source': 'shopids.csv', 'row': 8}),
Document(page_content='\ufeff: sads\n: USA\nID: 34554\nparent org: julies', metadata={'source': 'shopids.csv', 'row': 9}),
Document(page_content='\ufeff: b. shp insurance\n: USA\nID: 924923044\nparent org: annies', metadata={'source': 'shopids.csv', 'row': 10}),
Document(page_content='\ufeff: sads\n: USA\nID: e645605469\nparent org: hulberts', metadata={'source': 'shopids.csv', 'row': 11}),
Document(page_content='\ufeff: b. shp insurance\n: USA\nID: 4567\nparent org: aa', metadata={'source': 'shopids.csv', 'row': 12})
]
</code></pre>
<p>how can i change the code such that i can include Comment column and deal with the content on first 3 lines?
unsure what ufeff is as well when i encoded it as utf-8.</p>
|
<python><csv><parsing><langchain>
|
2024-05-07 17:36:46
| 1
| 999
|
Maths12
|
78,444,199
| 2,840,125
|
PyQt5 - Return the value of a textbox that's next to a checkbox created via looping
|
<p>I'm created a PyQt5 dialog that builds a form based on a supplied pandas DataFrame. Each row of the form contains a QCheckBox with a name, a type label, and a status QLineEdit. The user is able to select/deselect rows and change the contents of the status QLineEdit. When the user clicks the OK button, I want the <code>onokclick</code> function to find the rows that are checked, get the value of the QLineEdit for that row, and upload that value to a database. Here is the code I have now:</p>
<pre><code>class EditDetails(QDialog):
def __init__(self, dftable, srecnum, parent=None):
super().__init__(parent)
self.setWindowTitle("Select Names and Edit Status")
self.resize(600,400)
self.dftable = dftable
self.srecnum = srecnum
vlayout = QVBoxLayout()
self.glayout = QGridLayout()
self.glayout.addWidget(QLabel("Name"),0,0)
self.glayout.addWidget(QLabel("Type"),0,1)
self.glayout.addWidget(QLabel("Status"),0,2)
i = 1
for index, row in self.dftable.iterrows():
checkbox = QCheckBox(row["Name"])
checkbox.setChecked(True)
self.glayout.addWidget(checkbox,i,0)
slabel = row["Type"]
qtlabel = QLabel(slabel)
self.glayout.addWidget(qtlabel,i,1)
qtentry = QLineEdit(row[srecnum]["status"])
self.glayout.addWidget(qtentry,i,2)
i += 1
vlayout.addLayout(self.glayout)
newqw = QWidget()
newqw.setLayout(vlayout)
scrollarea = QScrollArea(widgetResizable=False)
scrollarea.setWidget(newqw)
layout = QVBoxLayout()
layout.addWidget(scrollarea)
QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
self.buttonBox = QDialogButtonBox(QBtn)
self.buttonBox.accepted.connect(self.onokclick)
self.buttonBox.rejected.connect(self.reject)
layout.addWidget(self.buttonBox,i,0)
self.setLayout(layout)
def onokclick(self):
widgets = (self.glayout.itemAt(i).widget() for i in range(self.glayout.count()))
for widget in widgets:
if isinstance(widget, QCheckBox):
if widget.isChecked():
name = widget.text()
status = ??? # How do I fetch the contents of the QLineEdit widget that's in the same grid layout row as this QCheckBox?
self.uploadToDatabase(name, status)
</code></pre>
|
<python><pyqt5>
|
2024-05-07 17:31:33
| 1
| 477
|
Kes Perron
|
78,444,144
| 10,181,236
|
is there a way to know when stable-baselines use actor or critic net?
|
<p>Using stable-baselines3 I am implementing a custom feature extractor for a PPO agent. As the docs says <a href="https://stable-baselines3.readthedocs.io/en/master/guide/custom_policy.html" rel="nofollow noreferrer">here</a> the custom feature extractor net is shared between actor and critic network. I want to print a log only when the policy network is called, so the actor. Is there a way to distinguish between the two?</p>
<pre><code>import torch as th
import torch.nn as nn
from gymnasium import spaces
from stable_baselines3 import PPO
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
class CustomCNN(BaseFeaturesExtractor):
"""
:param observation_space: (gym.Space)
:param features_dim: (int) Number of features extracted.
This corresponds to the number of unit for the last layer.
"""
def __init__(self, observation_space: spaces.Box, features_dim: int = 256):
super().__init__(observation_space, features_dim)
# We assume CxHxW images (channels first)
# Re-ordering will be done by pre-preprocessing or wrapper
n_input_channels = observation_space.shape[0]
self.cnn = nn.Sequential(
nn.Conv2d(n_input_channels, 32, kernel_size=8, stride=4, padding=0),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2, padding=0),
nn.ReLU(),
nn.Flatten(),
)
# Compute shape by doing one forward pass
with th.no_grad():
n_flatten = self.cnn(
th.as_tensor(observation_space.sample()[None]).float()
).shape[1]
self.linear = nn.Sequential(nn.Linear(n_flatten, features_dim), nn.ReLU())
def forward(self, observations: th.Tensor) -> th.Tensor:
# here I need a way to print only if the forward is done by the actor
return self.linear(self.cnn(observations))
policy_kwargs = dict(
features_extractor_class=CustomCNN,
features_extractor_kwargs=dict(features_dim=128),
)
model = PPO("CnnPolicy", "BreakoutNoFrameskip-v4", policy_kwargs=policy_kwargs, verbose=1)
model.learn(1000)
</code></pre>
|
<python><reinforcement-learning><stable-baselines>
|
2024-05-07 17:20:52
| 0
| 512
|
JayJona
|
78,444,101
| 825,227
|
Footnotes causing errant match using regex in Python
|
<p>I'm parsing text in Python using regex that typically looks like some version of this:</p>
<pre><code>JT Meta Platforms, Inc. - Class A
Common Stock (META) [ST]S (partial) 02/08/2024 03/05/2024 $1,001 - $15,000
F S: New
S O: Morgan Stanley - Select UMA Account # 1
JT Microsoft Corporation - Common
Stock (MSFT) [ST]S (partial) 02/08/2024 03/05/2024 $1,001 - $15,000
F S: New
S O: Morgan Stanley - Select UMA Account # 1
JT Microsoft Corporation - Common
Stock (MSFT) [OP]P 02/13/2024 03/05/2024 $500,001 -
$1,000,000
F S: New
S O: Morgan Stanley - Portfolio Management Active Assets Account
D: Call options; Strike price $170; Expires 01/17 /2025
C: Ref: 044Q34N6
</code></pre>
<p>I've set up a regex to extract 'ticker' (eg, MSFT, META) that looks like this:</p>
<pre><code>r"\(([A-Z]+\.?[A-Z]*?)\)"
</code></pre>
<p>This pulls capitalized adjacent chars (eg, IBM, T) sitting within parens, and also allows there to be an optional period (happens occasionally eg, BRK.B) for certain situations.</p>
<p>The below example is matching starting with the '(BM)' characters, which are included in a footnote for a previous transaction, and not valid tickers. The logic to identify these would be that they're preceded by the 'F S:' footnote designation, where there can be slight deviations in spaces but will include always include 'FS:'.</p>
<p>How to exclude these errant situations using regex in Python?</p>
<pre><code>Alibaba Group Holding Limited
American Depositary Shares each
representing eight Ordinary share
(BABA) [ST]S 01/19/2024 01/22/2024 $1,001 - $15,000
F S: New
S O: Iron Gate GA Brokerage Portfolio > IGGA IRA (BM)
Alphabet Inc. - Class C Capital Stock
(GOOG) [ST]S 01/19/2024 01/22/2024 $1,001 - $15,000
F S: New
S O: Iron Gate GA Brokerage Portfolio > IGGA ROTH IRA (JM)
Alphabet Inc. - Class C Capital Stock
(GOOG) [ST]S 01/19/2024 01/22/2024 $15,001 -
$50,000
F S: New
S O: Iron Gate GA Brokerage Portfolio > IGGA IRA (BM)
Amazon.com, Inc. (AMZN) [ST] S 01/19/2024 01/22/2024 $15,001 -
$50,000
F S: New
S O: Iron Gate GA Brokerage Portfolio > IGGA IRA (BM)
Amazon.com, Inc. (AMZN) [ST] S 01/19/2024 01/22/2024 $1,001 - $15,000
F S: New
S O: Iron Gate GA Brokerage Portfolio > IGGA ROTH IRA (JM)
Amazon.com, Inc. (AMZN) [ST] S 01/19/2024 01/22/2024 $1,001 - $15,000
F S: New
S O: Iron Gate GA Brokerage Portfolio > IGGA ROTH IRA (BM)Filing ID #20024354
</code></pre>
|
<python><regex>
|
2024-05-07 17:12:40
| 1
| 1,702
|
Chris
|
78,443,992
| 1,075,332
|
Specifying custom arguments in sklear-style classes
|
<p>I'm trying to implement my own, sklearn-compatible classifier in Python. To that end, I inherit from <code>BaseEstimator</code> and <code>ClassifierMixin</code>, but I also define my own arguments in the constructor.</p>
<p>While debugging, I noticed that invoking <code>__repr__()</code> interactively, in the IPython console, produces an <code>AttributeError</code>, claiming that my classifier lacks attributes which I specified. No such error appears when I run the file as a program. Also, the error appears only in Spyder on my Mac, but not in PyCharm on Windows.</p>
<p>Here is my minimal reproducible example:</p>
<pre class="lang-py prettyprint-override"><code>from sklearn.base import BaseEstimator, ClassifierMixin
class MyClassifier(BaseEstimator, ClassifierMixin):
def __repr__(self, **kwargs):
return "In MyClassifier.__repr__() ..."
def __init__(self, my_arg=0):
pass
mc = MyClassifier()
# The following line produces
# AttributeError: 'MyClassifier' object has no attribute 'my_arg'
# but only when run interactively:
mc
</code></pre>
<p>I also noticed that the error doesn't appear if I don't inherit from <code>BaseEstimator</code>. Also, the error doesn't appear if I assign <code>my_arg</code> to a member variable of the same name: In <code>__init__()</code>, substitute <code>self.my_arg = my_arg</code> for <code>pass</code>. <code>self.my_differently_named_arg = my_arg</code>, on the other hand, doesn't help.</p>
<p>So, is there some implicit contract that member variables must have the same names as the formal arguments, or is it a quirk in Spyder, or in the Python implementation on Mac, in sklearn, in PyCharm, in the Python implementation on Windows, or am I doing something wrong?</p>
<p>My configuration is: Spyder is 5.5.2, Python 3.9.7, IPython 8.18.1, sklearn 1.3.2, and my Mac is Intel Core i7 with Sonoma 14.4.1.</p>
|
<python><inheritance><scikit-learn><spyder>
|
2024-05-07 16:48:50
| 1
| 2,699
|
Igor F.
|
78,443,857
| 8,758,459
|
Python app stuck on deployment to Azure App Service via GitHub Actions
|
<p>I ran into an issue deploying a Python fastAPI server to an Azure App Service via GitHub Actions. I linked the code to a repository and then set up the CI pipeline to execute a deployment on new commits. The issue is that it never finishes deploying, seems to be stuck on the "deploy" task (waited 30+ min).</p>
<p>Furthermore, it works fine locally. The GitHub Actions setup was done on Azure Portal with the default deployment profile (shown below).</p>
<p>What could be the issue?</p>
<p>I have the following environment variables:</p>
<pre><code>SCM_DO_BUILD_DURING_DEPLOYMENT = 1
</code></pre>
<p>Here is an example server code:</p>
<pre><code>from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World!"}
</code></pre>
<p>This is the content of requirements.txt:</p>
<pre><code>fastapi==0.108.0
uvicorn==0.25.0
</code></pre>
<p>The app is started via a run.sh script:</p>
<pre><code>uvicorn app:app
</code></pre>
<p>And this is the default deployment profile generated from the Deployment Center on Azure Portal:</p>
<pre><code># Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions
name: Build and deploy Python app to Azure Web App - test-app
on:
push:
branches:
- main
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python version
uses: actions/setup-python@v1
with:
python-version: '3.10'
- name: Create and start virtual environment
run: |
python -m venv venv
source venv/bin/activate
- name: Install dependencies
run: pip install -r requirements.txt
# Optional: Add step to run tests here (PyTest, Django test suites, etc.)
- name: Zip artifact for deployment
run: zip release.zip ./* -r
- name: Upload artifact for deployment jobs
uses: actions/upload-artifact@v3
with:
name: python-app
path: |
release.zip
!venv/
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}
permissions:
id-token: write #This is required for requesting the JWT
steps:
- name: Download artifact from build job
uses: actions/download-artifact@v3
with:
name: python-app
- name: Unzip artifact for deployment
run: unzip release.zip
- name: Login to Azure
uses: azure/login@v1
with:
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_CBD8C3026E1A4282B849F09360374194 }}
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_A6EA60031331436B85135D7D38DEA5C0 }}
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_342877BC8990412AAE8316D6F51A7355 }}
- name: 'Deploy to Azure Web App'
uses: azure/webapps-deploy@v2
id: deploy-to-webapp
with:
app-name: 'test-app'
slot-name: 'Production'
</code></pre>
|
<python><azure-web-app-service><github-actions><fastapi>
|
2024-05-07 16:14:18
| 1
| 395
|
John Szatmari
|
78,443,797
| 3,022,254
|
Trouble with Python Selenium Key Press
|
<p>I'm trying to set up some batch look-ups using the orthographic dictionary <a href="https://lcorp.ulif.org.ua/dictua/" rel="nofollow noreferrer">here</a>. Normally this requires one to type in the search box on the left and then click the "пошук" button beneath it:</p>
<p><a href="https://i.sstatic.net/eqik3hvI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eqik3hvI.png" alt="enter image description here" /></a></p>
<p>There are three elements that seem relevant to me.</p>
<pre><code>search_bar = driver.find_element(By.ID, "ContentPlaceHolder1_tsearch")
search_button = driver.find_element(By.ID, "ContentPlaceHolder1_search")
current_word = driver.find_element(By.CLASS_NAME, "word_style")
</code></pre>
<p>The first is the search bar input element; the second is the search (пошук) button below it; and the third corresponds to the element that contains the searched word in the populated result on the right side of the page:</p>
<p><a href="https://i.sstatic.net/GPUZewNQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GPUZewNQ.png" alt="enter image description here" /></a></p>
<p>I tried simulating a key-press per the answer <a href="https://stackoverflow.com/questions/63775539/key-press-with-javascript-python-selenium">here</a>, but the following code did not seem to change the result from "привіт" (the default value) to the searched word "людина". If anyone is able to see what I've messed up, I'd appreciate the help:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
url = "https://lcorp.ulif.org.ua/dictua/"
op = webdriver.ChromeOptions()
op.add_argument('headless')
driver = webdriver.Chrome(options=op)
driver.get(url)
search_bar = driver.find_element(By.ID, "ContentPlaceHolder1_tsearch")
search_button = driver.find_element(By.ID, "ContentPlaceHolder1_search")
search_bar.clear()
search_bar.send_keys("людина")
ActionChains(driver).move_to_element(search_button).click(search_button).key_down(Keys.CONTROL).key_up(Keys.CONTROL).perform()
current_word = driver.find_element(By.CLASS_NAME, "word_style")
print(current_word.text) # привіт, not людина
</code></pre>
|
<python><selenium-webdriver>
|
2024-05-07 16:03:49
| 1
| 1,372
|
Mackie Messer
|
78,443,779
| 11,246,056
|
How to check if a LazyFrame is empty?
|
<p>Polars dataframes have an <code>is_empty</code> attribute:</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
df = pl.DataFrame()
df.is_empty() # True
df = pl.DataFrame({"a": [], "b": [], "c": []})
df.is_empty() # True
</code></pre>
<p>This is not the case for Polars lazyframes, so I devised the following helper function:</p>
<pre class="lang-py prettyprint-override"><code>def is_empty(data: pl.LazyFrame) -> bool:
return (
data.width == 0 # No columns
or data.null_count().collect().sum_horizontal()[0] == 0 # Columns exist, but are empty
)
other = pl.LazyFrame()
other.pipe(is_empty) # True
other = pl.LazyFrame({"a": [], "b": [], "c": []})
other.pipe(is_empty) # True
</code></pre>
<p>Is there a better way to do this? By better, I mean either without collecting or less memory-intensive if collecting can not be avoided.</p>
|
<python><memory><python-polars><lazyframe>
|
2024-05-07 16:00:39
| 1
| 13,680
|
Laurent
|
78,443,705
| 11,505,680
|
Portable launcher for pdoc
|
<p>I have a Python package hosted in a private GitHub space. I want to distribute it with a batch file that launches <code>pdoc</code> (we can assume all users are on Windows). I wrote such a batch file for myself, and it's only one line:</p>
<pre><code>"C:\ProgramData\anaconda3\Scripts\pdoc.exe" my_package
</code></pre>
<p>The problem is that the Python path is installation-dependent. How do I make the batch file portable?</p>
<p>I considered making a Python script to launch <code>pdoc</code>, using <a href="https://github.com/mitmproxy/pdoc/blob/main/examples/library-usage/make.py" rel="nofollow noreferrer">this example</a>, but the example seems to generate a single HTML file, which is a small part of the functionality of <code>pdoc.exe</code>.</p>
<p>I then tried to write a short Python script, embedded within a <code>python -c "do stuff"</code> construct, to build the needed command string (using <code>sys.executable</code>). I got a syntax error.</p>
<p>I came up with a solution that works (see below) but decided to post the question anyway in case someone has a better one.</p>
|
<python><batch-file><pdoc>
|
2024-05-07 15:45:56
| 1
| 645
|
Ilya
|
78,443,666
| 378,340
|
Sparse Clouds in Metashape Python Standalone Module don't match results in app with same settings
|
<p>I'm automating the the photogrammetry workflow for building models of objects on turntables. I have a pot, and I've taken pictures of the top and bottom. I've put these in one chunk rather than two. When I run the align photos workflow step with the following settings, I get a nice point cloud with all pictures aligned.
<a href="https://i.sstatic.net/EDvmus7Z.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EDvmus7Z.png" alt="Align photos dialog with High accuracy, generic preselection, tiepoints=0 and other options" /></a></p>
<p>When I run the following code, which to my knowledge, should do the same thing, I get four pictures aligned, and none of the cameras in the right positions. I've checked in the file, the correct masks have imported correctly. Do you have any idea what I'm doing wrong?</p>
<pre><code>maskKeypoints=False
if config["mask_path"]:
mp = os.path.join(config["mask_path"])
ext = config["mask_ext"]
masktemplate = f"{mp}{os.sep}{{filename}}.{ext}"
chunk.generateMasks(masktemplate,Metashape.MaskingMode.MaskingModeFile)
maskKeypoints=True
doc.save()
#match photos/align photos
chunk.matchPhotos(downscale=consts.PhotogrammetryConsts.AlignDownscale["HIGH"],# =1
filter_stationary_points=True,
reset_matches=True,
filter_mask = maskKeypoints,
generic_preselection=True,
keypoint_limit=40000,
tiepoint_limit=0,
guided_matching=True)
chunk.alignCameras()
doc.save()
</code></pre>
|
<python><photogrammetry><metashape>
|
2024-05-07 15:38:53
| 1
| 1,009
|
Rokujolady
|
78,443,422
| 7,395,686
|
Tkinter UI auto enlarges after changing style
|
<p>So, I followed an online video, and tried to replicate the UI, while applying my own changes to fit my needs, but I ended up with a UI that keeps enlarging every time I change the theme.</p>
<p>I tried commenting some parts of the code, to see where the problem lies, but to no avail, I'm pretty new to Tkinter, but I can handle my way after seeing a couple of examples, but this error, I couldn't understand.</p>
<p>This is what it looks like:
<a href="https://youtu.be/3K3HWjYSB5s" rel="nofollow noreferrer">https://youtu.be/3K3HWjYSB5s</a></p>
<p>And here's a working code snippet:</p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
from tkinter import ttk
def toggle_mode():
if mode_switch.instate(["selected"]):
style.theme_use("forest-light")
else:
style.theme_use("forest-dark")
def select(event=None):
treeview.selection_toggle(treeview.focus())
print(treeview.selection())
root = tk.Tk()
root.title('Generator')
#root.geometry("1280x720")
style = ttk.Style(root)
root.tk.call("source", "Theme/forest-dark.tcl")
root.tk.call("source", "Theme/forest-light.tcl")
style.theme_use("forest-dark")
frame = ttk.Frame(root)
frame.pack(fill=tk.BOTH) #Expand the frame to fill the root window
widgets_frame = ttk.LabelFrame(frame, text="Title 2")
widgets_frame.grid(row=1, column=0, padx=20, pady=10)
mode_switch = ttk.Checkbutton(widgets_frame, text="Mode", style="Switch", command=toggle_mode)
mode_switch.grid(row=0, column=0, padx=5, pady=10, sticky="nsew")
separator = ttk.Separator(widgets_frame)
separator.grid(row=0, column=1, padx=(20, 0), pady=5, sticky="ew")
button = ttk.Button(widgets_frame, text="Generate")#, command=todo)
button.grid(row=0, column=2, padx=5, pady=5, sticky="nsew")
treeFrame = ttk.LabelFrame(frame, text="Title 1")
treeFrame.grid(row=0, column=0, pady=10, sticky="nsew")
treeScroll = ttk.Scrollbar(treeFrame)
treeScroll.pack(side="right", fill="y")
cols = ("1", "2", "3", "4")
treeview = ttk.Treeview(treeFrame, show=("headings"), selectmode="none", yscrollcommand=treeScroll.set, columns=cols, height=13)
treeview.bind("<ButtonRelease-1>", select)
treeview.column("1", width=100)
treeview.column("2", width=150)
treeview.column("3", width=300)
treeview.column("4", width=100)
treeview.pack()
treeview.pack_propagate(False)
treeScroll.config(command=treeview.yview)
#load_data()
root.mainloop()
</code></pre>
|
<python><python-3.x><tkinter>
|
2024-05-07 14:58:13
| 1
| 542
|
Amine Messabhia
|
78,443,220
| 17,388,934
|
Replace an element of a list with its value from a dataframe
|
<p>I have a data dictionary and a column_list. I want to replace the value in the column_list with its matching value from the data dictionary. I have written the below code; however, I'm unable to get the required output.
Can someone please help to fix the overlapping values?</p>
<pre><code>col_list = ['eff_strt_dte', 'eff_sta_dt', 'birth_dt', 'cus_idr', 'cust_id']
data_dict = {'eff': 'effective', 'dt': 'date', 'dte': 'date', 'str': 'start', 'cus': 'customer', 'cust': 'customer', 'id':'identifier', 'idr': 'identifier', 'sta': 'start'}
new_list = []
for col in col_list:
for key, value in data_dict.items():
if key in col:
col = col.replace(key, value)
new_list.append(col)
print(new_list)
</code></pre>
<p>Expected output is:
<code>['effective_start_date', 'effective_start_date', 'birth_date', 'customer_identifier', 'customer_identifier']</code></p>
<p>Output I'm getting now: <code>['effective_startt_datee', 'effective_sta_date', 'birth_date', 'customeromer_identifierr', 'customeromert_identifier']</code></p>
|
<python><list><replace>
|
2024-05-07 14:28:03
| 2
| 319
|
be_real
|
78,443,142
| 9,302,146
|
Snowflake.py: RemovedInAirflow3Warning: This module is deprecated. Please use `airflow.providers.common.sql.hooks.sql`
|
<p>After upgrading airflow from <code>2.2.0</code> to <code>2.9.0</code> I have been getting the following warning:</p>
<pre><code>snowflake.py:29 RemovedInAirflow3Warning: This module is deprecated. Please use `airflow.providers.common.sql.hooks.sql`.
</code></pre>
<p>However, it does not clearly state which changes I need to make in order to switch to the other module. Does anyone know how to fix this warning?</p>
|
<python><snowflake-cloud-data-platform><airflow>
|
2024-05-07 14:15:33
| 1
| 429
|
Abe Brandsma
|
78,443,067
| 2,662,302
|
How make multiple when condition on polars
|
<p>I have a dictionary with strings as keys an polars expresions as values.</p>
<p>How can I do something like this in a concise way:</p>
<pre class="lang-py prettyprint-override"><code>df = df.with_columns(
pl.when(condition_1)
.then(pl.lit(key_1))
.when(pl.lit(condition_2))
.then(pl.lit(key_2))
...
.otherwise(None)
.alias("new_column")
)
</code></pre>
|
<python><dataframe><python-polars>
|
2024-05-07 14:03:47
| 1
| 505
|
rlartiga
|
78,442,790
| 4,415,232
|
python - Combine structured JSON with remaining JSON
|
<p>I have this structured df (json) which includes another json and I want to combine them to access all the values:</p>
<pre><code>{
"index": "exp-000005",
"type": "_doc",
"score": 9.502488,
"source": {
"verb": "REPLIED",
"timestamp": "2022-01-20T08:14:00+00:00",
"in_context": {
"screen_width": "3440",
"screen_height": "1440",
"build_version": "7235",
"question": "Hallo",
"request_time": "403",
"status": "success"
}
}
}
</code></pre>
<p>The result I want is the following:</p>
<pre><code>{
"index": "exp-000005",
"type": "_doc",
"score": 9.502488,
"verb": "REPLIED",
"timestamp": "2022-01-20T08:14:00+00:00",
"screen_width": "3440",
"screen_height": "1440",
"build_version": "7235",
"question": "Hallo",
"request_time": "403",
"status": "success"
}
</code></pre>
<p>How can I combine this structured json to one unstructured json? In R I used <a href="https://www.rdocumentation.org/packages/tidyjson/versions/0.3.2/topics/tbl_json" rel="nofollow noreferrer">tbl_json</a>. Maybe there is something similar for python?</p>
|
<python><json>
|
2024-05-07 13:16:11
| 1
| 1,235
|
threxx
|
78,442,703
| 9,302,146
|
ERROR - Failed to execute task ' ti' (KeyError: ' ti' in Apache Airflow)
|
<p>I have been getting the following error (repeatedly) in <code>Airflow 2.9.0</code> after upgrading from <code>2.2.0</code>:</p>
<pre class="lang-bash prettyprint-override"><code>2024-05-07T11:10:43.522+0000] {local_executor.py:139} ERROR - Failed to execute task ' ti'.
Traceback (most recent call last):
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/executors/local_executor.py", line 135, in _execute_work_in_fork
args.func(args)
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/cli/cli_config.py", line 49, in command
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/utils/cli.py", line 114, in wrapper
return f(*args, **kwargs)
^^^^^^^^^^^^^^^^^^
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/cli/commands/task_command.py", line 422, in task_run
ti.init_run_context(raw=args.raw)
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/models/taskinstance.py", line 3307, in init_run_context
self._set_context(self)
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/utils/log/logging_mixin.py", line 127, in _set_context
set_context(self.log, context)
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/utils/log/logging_mixin.py", line 274, in set_context
flag = cast(FileTaskHandler, handler).set_context(value)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/providers/microsoft/azure/log/wasb_task_handler.py", line 89, in set_context
super().set_context(ti, identifier=identifier)
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/utils/log/file_task_handler.py", line 219, in set_context
local_loc = self._init_file(ti, identifier=identifier)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/utils/log/file_task_handler.py", line 500, in _init_file
local_relative_path = self._render_filename(ti, ti.try_number)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/airflow/.local/lib/python3.11/site-packages/airflow/utils/log/file_task_handler.py", line 290, in _render_filename
return str_tpl.format(
^^^^^^^^^^^^^^^
KeyError: ' ti'
</code></pre>
<p>I used <code>Airflow 2.2.0</code> before and there everything was still working fine without any errors or warnings. After the update to 2.9.0 and upgrading the database (using <code>airflow db migrate --to-version="2.9.0"</code>), I started receiving this error. This error also seemingly results in the scheduler crashing. The webserver is still accessible though.</p>
<p>Airflow is being run inside a docker container with the following base image: <code>apache/airflow:2.9.0-python3.11</code></p>
<hr />
<p>So far, I have already tried to set <code>'provide_context'=True</code> in the default args and to specific PythonOperators.</p>
<p>Also note that the key where the key error occurs has a space in it (<code>' ti'</code>), which seems weird to me.</p>
<p>Does anyone know how to fix this error?</p>
<hr />
<p>Edit 1: Even when Airflow does not have any DAGs loaded, it still has the same error. Which makes me believe that it has something to do with the database. I use a postgresql database for the metadata.</p>
<p>Edit 2: It seems like Airflow runs as long as no DAGs are running. However, if I execute any DAG it crashes immediately with the specified error.</p>
|
<python><docker><airflow>
|
2024-05-07 13:00:32
| 1
| 429
|
Abe Brandsma
|
78,442,635
| 6,763,074
|
Rhinoceros 8, Grasshopper and sys.path in Python IDE
|
<p>I work with <a href="https://www.rhino3d.com/8/new/" rel="nofollow noreferrer">Rhino 3d</a> and Grasshopper to support an engineer with some programming work in Python. The Python runtime was automatically installed to <code>C:\Users\Patrick Bucher\.rhinocode\py39-rh8</code>. The scripts work fine when executed in the integrated Python editor. However, we'd like to use an external IDE (Visual Studio Code, PyCharm) to program and to write some tests using PyTest.</p>
<p>For this purpose, I created a Virtual Environment based on the existing one:</p>
<pre><code>'C:\Users\Patrick Bucher\.rhinocode\py39-rh8\python.exe' -m venv env --system-site-packages
</code></pre>
<p>Note the <code>--system-site-packages</code> flag to prefix the path with the site packages.</p>
<p>However, I cannot run the following script from my virtual environment (<code>demo.py</code>):</p>
<pre class="lang-py prettyprint-override"><code>import Rhino
dir(Rhino)
</code></pre>
<p>Result:</p>
<pre><code>> python .\demo.py
Traceback (most recent call last):
File "C:\Users\Patrick Bucher\solartables-constructable\demo.py", line 1, in <module>
import Rhino
ModuleNotFoundError: No module named 'Rhino
</code></pre>
<p>So I ran the following script <strong>in Grasshopper</strong> to get the proper path:</p>
<pre class="lang-py prettyprint-override"><code>import sys
print(sys.path)
</code></pre>
<p>Which outputs:</p>
<pre><code>['C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-envs\\default-kG+mgfz0', 'C:\\Users\\Patrick Bucher\\AppData\\Roaming\\McNeel\\Rhinoceros\\8.0\\scripts', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-rhinoghpython', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-rhinopython', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-interop', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\python39.zip', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\DLLs', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\lib', 'C:\\Program Files\\Rhino 8\\System', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\lib\\site-packages', 'C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\7.0.0\\']
</code></pre>
<p>So I compared this to my environment that I run from the IDE (<code>syspathdiff.py</code>):</p>
<pre class="lang-py prettyprint-override"><code>import sys
rhino = set(['C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-envs\\default-kG+mgfz0', 'C:\\Users\\Patrick Bucher\\AppData\\Roaming\\McNeel\\Rhinoceros\\8.0\\scripts', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-rhinoghpython', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-rhinopython', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-interop', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\python39.zip', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\DLLs', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\lib', 'C:\\Program Files\\Rhino 8\\System', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\lib\\site-packages', 'C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\7.0.0\\'])
actual = set(sys.path)
missing = rhino - actual
print(missing)
</code></pre>
<p>Which outputs the following differences:</p>
<pre><code>{'C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\7.0.0\\', 'C:\\Program Files\\Rhino 8\\System', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-rhinoghpython', 'C:\\Users\\Patrick Bucher\\AppData\\Roaming\\McNeel\\Rhinoceros\\8.0\\scripts', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-interop', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-envs\\default-kG+mgfz0', 'C:\\Users\\Patrick Bucher\\.rhinocode\\py39-rh8\\site-rhinopython'}
</code></pre>
<p>Here are my questions:</p>
<ol>
<li>How do I configure my (virtual) environment so that the <code>Rhino</code> module can be imported upon running PyTest test cases or any other scripts involving <code>Rhino</code>?</li>
<li>Which additional path shall I include in order to have access to the <code>Rhino</code> module in my Python code?</li>
</ol>
<p>Thanks!</p>
<p>EDIT: There is a <code>RhinoCommon.dll</code> for the CLR, which can be imported using the <code>pythonnet</code> package (<code>pip install pythonnet</code>):</p>
<pre class="lang-py prettyprint-override"><code>try:
import Rhino.Geometry as rg
except ModuleNotFoundError:
import clr
rhino = clr.AddReference(r"C:\Program Files\Rhino 8\System\netcore\RhinoCommon.dll")
print(rhino)
</code></pre>
<p>Output:</p>
<pre><code>RhinoCommon, Version=8.6.24101.5001, Culture=neutral, PublicKeyToken=552281e97c755530
</code></pre>
<p>I don't know how to use the resulting library in Python. Any hints on this?</p>
|
<python><virtualenv><python.net>
|
2024-05-07 12:49:34
| 0
| 1,618
|
Patrick Bucher
|
78,442,459
| 956,424
|
Django 4.2 how to display deleted object failure in modeladmin page?
|
<p>Code used to override the delete_queryset in the modeladmin:</p>
<pre><code> def get_actions(self, request):
actions = super().get_actions(request)
del actions['delete_selected']
return actions
def really_delete_selected(self, request, queryset):
'''
# 1. Update the group-mailbox relation: `goto` values if mailbox(es) are deleted
# 2. Sending a mail to the current user with CSV of mailboxes deleted
# 3. Used domain space will reduce by the maxquota of mailbox
'''
response = None
print('delete from mailbox queryset called')
try:
mbox_list = []
failed_deletions = []
print(queryset)
for obj in queryset:
mdomain = None
# COMPLETE MAILBOX DELETION OF FOLDERS, DOVECOT ENTRY, ADMIN PANEL PERMANENTLY
api_delete_status = call_purge_mailbox_api(request,obj)
response = api_delete_status
print('response---------',response, response['status_code'])
if response['status_code'] == 200:
# Set the quota value after deletion of mailbox(es)
mdomain = Domain.objects.get(id=obj.domain.pk)
mdomain.quota -= obj.maxquota
mdomain.save()
mbox_list.append(obj.email)
# Remove the user from the group mailing lists
# master_grp_list = GroupMailIds.objects.exclude(goto=None)
removed_from_groups :bool = remove_from_group_lists(obj.email,mbox_list)
print('mailbox deletion completed.....')
# TODO: List for sending a mail to the currently logged in user with CSV of
# mailboxes deleted
else:
print('Failed to delete mailbox:', obj.email)
failed_deletions.append(obj.email)
print(failed_deletions, len(failed_deletions))
if mbox_list: # Check if any mailboxes were successfully deleted
self.message_user(request, f"Successfully deleted {len(mbox_list)} mailbox(es).",level='success')
for email in failed_deletions: # Display error message for each failed deletion
self.message_user(request, f"Failed to delete {email}. Mailbox absent. Contact helpdesk.",level='error')
if not mbox_list and not failed_deletions: # Check if no deletions were attempted
self.message_user(request, "No mailboxes were selected for deletion.",level='error')
#return messages.error(request, "No mailboxes were selected for deletion.")
except Exception as e:
print(e)
self.message_user(request, f"Failed to delete items: {str(e)}", level='error')
really_delete_selected.short_description = "Delete selected entries"
def delete_model(self, request, obj):
try:
if obj.id is None:
# If the object's ID is None, it means the object doesn't exist
self.message_user(request, "Failed to delete object. Object does not exist.", level='error')
return HttpResponseRedirect(request.path)
# Perform the deletion
api_delete_status = call_purge_mailbox_api(request, obj)
mbox_list = []
if isinstance(api_delete_status, dict) and 'status_code' in api_delete_status:
status_code = api_delete_status['status_code']
if status_code == 200:
# If the deletion was successful, trigger response_delete
mdomain = Domain.objects.get(id=obj.domain.pk)
mdomain.quota -= obj.maxquota
mdomain.save()
mbox_list.append(obj)
# Remove the user from the group mailing lists
removed_from_groups :bool = remove_from_group_lists(obj.email,mbox_list)
print('mailbox deletion completed.....')
# TODO: List for sending a mail to the currently logged in user with CSV of
# mailboxes deleted
else:
# If the deletion operation did not succeed, handle the failure
#self.message_user(request, f"Failed to delete mailbox {obj}. Contact Helpdesk", level='error')
return None
except Exception as e:
# Handle deletion failure
self.message_user(request, f"Failed to delete {obj}. Error: {str(e)}", level='error')
return None
def response_delete(self, request, obj_display, obj_id):
obj = Mailbox.objects.filter(id=obj_id).first()
if obj:
self.message_user(request, f"Failed to delete mailbox {obj_display} Contact Helpdesk", level='error')
else:
print('no obj iddddddd present anymore, successfully deleted')
self.message_user(request, f"Successfully deleted {obj_display}.", level='success')
return HttpResponseRedirect(reverse('admin:myapp_mailbox_changelist'))
</code></pre>
<p>This code is displaying correctly for the delete_queryset on failure of deletion. But when we delete the mailbox object in the model admin page after confirm_delete(confirm_delete.html), the message displayed after returning to the listing page are:</p>
<p><strong>Failed to delete mailbox yy@domain1.net. Contact Helpdesk</strong></p>
<p><strong>as well as</strong></p>
<p><strong>The mailbox “yy@domain1.net” was deleted successfully.</strong></p>
<p><strong>Failure is the expected result</strong>. But why does django also display successful deletion? How to hide this message in the modeladmin listing page for failed cases?</p>
<p>Deletion from queryset works as expected. Displays the failed message only</p>
|
<python><django>
|
2024-05-07 12:21:59
| 1
| 1,619
|
user956424
|
78,442,162
| 11,922,237
|
How to construct a networkx graph from a dictionary with format `node: {neighbor: weight}`?
|
<p>I have the following dictionary that contains node-neighbor-weight pairs:</p>
<pre class="lang-py prettyprint-override"><code>graph = {
"A": {"B": 3, "C": 3},
"B": {"A": 3, "D": 3.5, "E": 2.8},
"C": {"A": 3, "E": 2.8, "F": 3.5},
"D": {"B": 3.5, "E": 3.1, "G": 10},
"E": {"B": 2.8, "C": 2.8, "D": 3.1, "G": 7},
"F": {"G": 2.5, "C": 3.5},
"G": {"F": 2.5, "E": 7, "D": 10},
}
</code></pre>
<p>The visual representation of the graph is this:</p>
<p><a href="https://i.sstatic.net/8RHy8HTK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8RHy8HTK.png" alt="enter image description here" /></a></p>
<p>How do I go from that dictionary to a <code>networkx</code> graph object:</p>
<pre class="lang-py prettyprint-override"><code>import networkx as nx
G = nx.Graph()
# YOUR SUGGESTION HERE #
</code></pre>
|
<python><graph><networkx><graph-theory>
|
2024-05-07 11:33:19
| 2
| 1,966
|
Bex T.
|
78,442,086
| 11,432,290
|
How to maintain separate sessions for diff users in llama_index chat also how can we pass previous chat messages in query for future responses?
|
<p>Hi I am using llama_index for indexing hundreds of docs that contain some specific details, now I want to build an API over it(in which I would get the session_id, query_text), which should be able to answer queries as per the info indexed from the docs, my implementation works for a single user, but the API would be used by hundreds of diff users simultaneously so how can i maintain diff chat sessions and pass previous chats as a context for new query, looked into the docs but found nothing regarding this, so it would be beneficial if someone can guide me as to what should be my approach moving forward to power my use-case.</p>
<p><strong>Current Implementation</strong></p>
<p>index_builder.py</p>
<pre><code>from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, PromptHelper, ServiceContext
import os
os.environ["OPENAI_API_KEY"] = ''
persist_dir = "./doc_index"
def construct_index(directory_path):
try:
print(f"Beginning to load data in directory: {directory_path}")
documents = SimpleDirectoryReader(directory_path).load_data()
print(f"***** Documents for indexing ***** : {documents}, length: {len(documents)}")
index = VectorStoreIndex.from_documents(documents, show_progress=True)
index.storage_context.persist(persist_dir=persist_dir)
except Exception as e:
print(f"Exception occurred in construct_index, reason is: {e}")
construct_index("docs")
</code></pre>
<p>chatbot.py</p>
<pre><code>from llama_index.core import StorageContext, load_index_from_storage
import gradio as gr
import os
os.environ["OPENAI_API_KEY"] = ''
persist_dir = "./doc_index"
index = None
def load_index():
global index
# Load index and query engine
print(f"Beginning to load index")
storage_context = StorageContext.from_defaults(persist_dir=persist_dir)
index = load_index_from_storage(storage_context)
print(f"Index loaded successfully for querying")
if not index:
print(f"Index not found. Please run the indexing script first.")
# Loading index before chatBot loads to avoid delay in response, any also to avoid re-loading index for every request
load_index()
def chatbot(input_text):
global index
chat_engine = index.as_chat_engine(
chat_mode="context",
system_prompt=(
"You are a chatbot who responds only as per the data available in the VectorStoreIndex in detail and nothing from internet"
"Also if data is not available, you can respond with 'Sorry, I don't have the information regarding this'"
),
)
print("Input text: ", input_text)
response = chat_engine.chat(input_text, session_state)
print('Response is: ', response)
return response
# Launch Gradio interface
iface = gr.Interface(fn=chatbot,
inputs=gr.components.Textbox(lines=7, label="Enter your query"),
outputs="text",
title="AI Chatbot")
iface.launch(share=True)
print(f"ChatBot is ready...")
</code></pre>
|
<python><chatbot><openai-api><llama><llama-index>
|
2024-05-07 11:19:43
| 0
| 475
|
Yash Tandon
|
78,441,981
| 8,510,149
|
Groupby with condition - best practice
|
<p>I want to a groupby with a condition and then feed back the result to the original dataframe. In this case feature 'COl_COND' could either be 1 or 0, and the feature to be summarized is 'AMOUNT'.</p>
<p>Below this is done by performing two groupby's, storing the result in pandas series and then merge back to the original dataframe.</p>
<p>Can this be done without doing a merge?</p>
<p>If memory usage is an issue, what method would be the most rational to apply?</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'ID':[1,1,2,2,3,3,3,4,5,5,6],
'COL_COND':[1,0,1,0,1,0,1,0,1,0,0],
'AMOUNT':[5, 80,100, 50, 100, 100, 20, 1, 51, 11, 12]})
series1 = df[df.COL_COND==1].groupby('ID')['AMOUNT'].sum().rename('sum_amount_1')
series0 = df[df.COL_COND==0].groupby('ID')['AMOUNT'].sum().rename('sum_amount_0')
df = df.merge(series1.to_frame().reset_index(), on='ID', how='left')\
.merge(series0.to_frame().reset_index(), on='ID', how='left')
print(df)
</code></pre>
<pre><code> ID COL_COND AMOUNT sum_amount_1 sum_amount_0
0 1 1 5 5.0000000 80
1 1 0 80 5.0000000 80
2 2 1 100 100.0000000 50
3 2 0 50 100.0000000 50
4 3 1 100 120.0000000 100
5 3 0 100 120.0000000 100
6 3 1 20 120.0000000 100
7 4 0 1 NaN 1
8 5 1 51 51.0000000 11
9 5 0 11 51.0000000 11
10 6 0 12 NaN 12
</code></pre>
|
<python><pandas><group-by>
|
2024-05-07 10:59:01
| 3
| 1,255
|
Henri
|
78,441,494
| 21,117,677
|
Calling inference (ONNXRuntime) with largest-possible image size
|
<p>I'm using ONNX Runtime for image segmentation inference with a model converted from PyTorch. I want to run the image size as large as possible without crashing.</p>
<p>Is there a method to dynamically check what image shape my graphics card can handle for a particular deep learning model?</p>
<p>I call inference with the following pattern:</p>
<pre><code>sess = onnxruntime.InferenceSession("my_model.onnx")
input_name = sess.get_inputs()[0].name
pred_onx = sess.run(None, {input_name: X_test.astype(numpy.float32)})[0]
</code></pre>
<p>This works when images are small. When the input tensor is too large for the GPU to handle, it throws an exception or crashes.</p>
<p>I've tried a method that starts with a large input image size, tries <code>sess.run()</code> and then catches exceptions and if so, retries with a smaller scale. But crashes are not always caught so it's unsafe.</p>
|
<python><deep-learning><onnx><inference><onnxruntime>
|
2024-05-07 09:31:54
| 0
| 396
|
rovsmor
|
78,441,462
| 3,076,544
|
Inconsistent Import Reordering on Save in VSCode with isort and autopep8
|
<p>I'm experiencing inconsistent behavior with VSCode's format on save feature, specifically with the organization of Python imports. Each time I save, the arrangement of imports alternates between two different formats.</p>
<p>I'm using the Python extension along with the isort tool. My current settings are as follows:</p>
<pre><code>"[python]": {
"editor.defaultFormatter": "ms-python.autopep8",
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports.isort": "explicit"
}
},
</code></pre>
<p>For demonstration, consider this simple initial code snippet:</p>
<pre><code>import modules.report_common as rpc
import modules.utils as utl
import numpy as np
import pandas as pd
</code></pre>
<p>Upon the first save, the imports are organized like this:</p>
<pre><code>import numpy as np
import pandas as pd
import modules.report_common as rpc
import modules.utils as utl
</code></pre>
<p>This is the desired format. However, a subsequent save (e.g. after making unrelated edits), reverts the imports to their original order:</p>
<pre><code>import modules.report_common as rpc
import modules.utils as utl
import numpy as np
import pandas as pd
</code></pre>
<p>How can I ensure consistent import organization with each save, maintaining the sorted import sections as desired? I prefer to keep using isort for import sorting, but require a stable configuration that does not alternate with every save action.</p>
|
<python><visual-studio-code><isort>
|
2024-05-07 09:26:39
| 0
| 993
|
MrT77
|
78,441,361
| 1,020,139
|
Is it permitted to supply a value for a TypeVar in Python?
|
<p>Consider the following generic type:</p>
<p><code>Response(Generic[ResponseT])</code></p>
<p>The type var is defined as follows:</p>
<p><code>ResponseT = TypeVar("ResponseT")</code></p>
<p>I have seen <code>Response[None]</code> usages without VS Code (Pylance/Pyright) complaining about type issues.</p>
<p>So, is it permitted to supply arbitrary values for <code>TypeVar</code>? I thought that only types could be provided as arguments, but <code>None</code> is not a type</p>
|
<python><python-typing><pyright>
|
2024-05-07 09:11:40
| 0
| 14,560
|
Shuzheng
|
78,441,342
| 16,567,918
|
django - is UniqueConstraint with multi fields has same effect as Index with same field?
|
<p>I wrote a django model that you can see below, I want to know having the <strong>UniqueConstraint</strong> is enough for <em><strong>Search and Selecting row base on user and soical type</strong></em> or I need to add the <strong>Index</strong> for them. if yes what is the different between them becuse base on my search the UniqueConstraint create an Unique Index on DB like <strong>posgresql</strong>.</p>
<p>model:</p>
<pre class="lang-py prettyprint-override"><code>class SocialAccount(Model):
"""Social account of users"""
added_at: datetime = DateTimeField(verbose_name=_("Added At"), auto_now_add=True)
user = ForeignKey(
to=User,
verbose_name=_("User"),
db_index=True,
related_name="socials",
)
type = PositiveSmallIntegerField(
verbose_name=_("Type"),
choices=SocialAcountType,
)
class Meta:
constraints = UniqueConstraint(
# Unique: Each User Has Only one Social Account per Type
fields=(
"user",
"type",
),
name="user_social_unique",
)
# TODO: check the UniqueConstraints is enough for index or not
indexes = (
Index( # Create Index based on `user`+`type` to scan faster
fields=(
"user",
"type",
),
name="user_social_index",
),
)
</code></pre>
<p>base on the above description I searched but I can't find any proper document to find how django act and we need extra index for them if they are a unique togher already?</p>
<blockquote>
<p>Note: I know there are some other questions that are similar but they can't answer my question exactly</p>
</blockquote>
|
<python><django><postgresql><indexing><orm>
|
2024-05-07 09:09:07
| 1
| 445
|
Nova
|
78,441,134
| 2,405,663
|
Translate VBA function in Python
|
<p>I have VBA function and I'm trying to convert this application in Python.</p>
<p>Now I need to translate the following VBA code:</p>
<pre><code>Dim R_SH(1 To 3, 1 To 3) As Double
</code></pre>
<p>in Python.</p>
<p>I tried to write the following Python code but I think that is not correct:</p>
<pre><code>w, h = 2, 3
R_SH = [[0 for x in range(w)] for y in range(h)]
</code></pre>
<p>Could we support me?</p>
|
<python><vba>
|
2024-05-07 08:31:14
| 1
| 2,177
|
bircastri
|
78,441,056
| 16,511,234
|
Connect to websocket from request
|
<p>I want to connect to a websocket to process real time data. The URL look like this: <code>https://testsite.test.de/Interfaces</code>. When I enter it in Firefox it asks immediately for username and password. After I enter them the status codes are 200 with HTTP/1.1, 200 HTTP/2, 101 switching protocols connection upgrade and the Scheme changes to wws://.</p>
<p>With this code I can log in and get the status code 200 with print(r):</p>
<pre><code>import requests
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0'}
r = requests.get('https://testsite.test.de/Interfaces',
auth=('my_username', 'my_password'), headers=headers)
print(r)
</code></pre>
<p>print(r.cookie) is empty.</p>
<p>I do not know the next steps to get the data.</p>
<p>I tried this with no result:</p>
<pre><code>import websocket
ws = websocket.WebSocketApp('wss://testsite.test.de/Interfaces')
ws.run_forever
</code></pre>
<p>This is what the Inspector shows:
<a href="https://i.sstatic.net/oDh4g6A4.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oDh4g6A4.jpg" alt="enter image description here" /></a></p>
|
<python><websocket>
|
2024-05-07 08:16:43
| 0
| 351
|
Gobrel
|
78,440,849
| 7,106,508
|
sqlite3.DataError: query string is too large
|
<p>I'm trying to analyze this wiktionary dump with is 5GB, but I'm getting the above error message in the title. Here is my code:</p>
<pre class="lang-py prettyprint-override"><code> import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
sql_file = open(f'wiktionary_categories.sql',encoding = "ISO-8859-1")
sql_as_string = sql_file.read()
c.executescript(sql_as_string)
</code></pre>
<p>Is there some way I can use a with statement? Such as:</p>
<pre class="lang-py prettyprint-override"><code> with open(f'wiktionary_categories.sql',encoding = "ISO-8859-1") as sql_file:
sql_as_string = sql_file.read()
c.executescript(sql_as_string)
</code></pre>
<p>I just want to run through the file and pick out all of the words that belong to a certain category.</p>
|
<python><sql><sqlite3-python>
|
2024-05-07 07:35:30
| 1
| 304
|
bobsmith76
|
78,440,435
| 736,662
|
Is it possible to pick out an element in a JSON response structure based on a name in letters
|
<p>I am making an HTTP API call using Pytest and want to obtain a value given a name in letters.
The response looks like this:</p>
<pre><code> [
{
"hpsId": 10032,
"powerPlant": {
"name": "Svartisen",
"id": 67302,
"regionId": 40,
"priceArea": 4,
"timeSeries": null,
"units": [
{
"generatorName": "Svartisen G1",
"componentId": 673021,
"timeSeries": null
},
{
"generatorName": "Svartisen G2",
"componentId": 673022,
"timeSeries": null
}
]
}
},
{
"hpsId": 10037,
"powerPlant": {
"name": "Stølsdal",
"id": 16605,
"regionId": 20,
"priceArea": 2,
"timeSeries": null,
"units": [
{
"generatorName": "Stølsdal G1",
"componentId": 166051,
"timeSeries": null
}
]
}
}
]
</code></pre>
<p>I want ot get the attribute value (166051) for componentId for generatorName Stølsdal G1 in the above response and save the value.</p>
<p>But how can I search for this given I only know the name of the generator before the request is being made?</p>
<p>I was thinking like this:</p>
<pre><code>componentId= response.json()[what to put here?]["hpsId"]["componentId"]
</code></pre>
|
<python><json>
|
2024-05-07 06:08:14
| 2
| 1,003
|
Magnus Jensen
|
78,440,430
| 2,981,639
|
Sorting a Polars list of structs based on a struct field value
|
<p>How do I use <code>polars.Expr.list.sort</code> to sort a list of structs by one of the struct values, i.e.</p>
<pre class="lang-py prettyprint-override"><code>import polars as pl
df = pl.DataFrame([{"id": 1, "data": [{"key": "A", "value": 2}, {"key": "B", "value": 1}]}])
</code></pre>
<pre><code>shape: (1, 2)
┌─────┬────────────────────┐
│ id ┆ data │
│ --- ┆ --- │
│ i64 ┆ list[struct[2]] │
╞═════╪════════════════════╡
│ 1 ┆ [{"A",2}, {"B",1}] │
└─────┴────────────────────┘
</code></pre>
<p>I want to sort <code>data</code> by the <code>value</code> field, i.e. the result should be</p>
<pre class="lang-py prettyprint-override"><code>out = pl.DataFrame([{"id": 1, "data": [{"key": "B", "value": 1}, {"key": "A", "value": 2}]}])
</code></pre>
<pre><code>shape: (1, 2)
┌─────┬────────────────────┐
│ id ┆ data │
│ --- ┆ --- │
│ i64 ┆ list[struct[2]] │
╞═════╪════════════════════╡
│ 1 ┆ [{"B",1}, {"A",2}] │
└─────┴────────────────────┘
</code></pre>
<p><code>.list.sort()</code> returns the input unchanged and doesn't accept any arguments.</p>
<pre class="lang-py prettyprint-override"><code>df.with_columns(pl.col("data").list.sort())
</code></pre>
|
<python><dataframe><python-polars>
|
2024-05-07 06:06:51
| 3
| 2,963
|
David Waterworth
|
78,440,228
| 2,966,723
|
Understanding the role of `shuffle` in np.random.Generator.choice()
|
<p>From the documentation for <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.choice.html#numpy.random.Generator.choice" rel="nofollow noreferrer">numpy's <code>random.Generator.choice</code></a> function, one of the arguments is <code>shuffle</code>, which defaults to <code>True</code>.</p>
<p>The documentation states:</p>
<blockquote>
<p><strong>shuffle</strong> bool, optional</p>
<p>Whether the sample is shuffled when sampling without replacement. Default is True, False provides a speedup.</p>
</blockquote>
<p>There isn't enough information for me to figure out what this means. I don't understand why we would shuffle if it's already appropriately random, and I don't understand why I would be given the option to not shuffle if that yields a biased sample.</p>
<p>If I set <code>shuffle</code> to <code>False</code> am I still getting a random (independent) sample? I'd love to also understand why I would ever want the default setting of <code>True</code>.</p>
|
<python><numpy><random>
|
2024-05-07 05:09:02
| 2
| 24,012
|
Joel
|
78,440,162
| 2,023,397
|
How to scrape table data from HTML with BeautifulSoup?
|
<p>I have been trying to scrape a table from this website <a href="https://www.alphaquery.com/stock/aapl/earnings-history" rel="nofollow noreferrer">https://www.alphaquery.com/stock/aapl/earnings-history</a>
but in no way I can achieve it. I can t even find the table.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
def get_eps(ticker):
url = f"https://www.alphaquery.com/stock/{ticker}/earnings-history"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
# Attempt to more robustly find the table by checking for specific headers
table = None
for table_candidate in soup.find_all("table"):
headers = [th.get_text(strip=True) for th in table_candidate.find_all("th")]
if "Estimated EPS" in headers:
table = table_candidate
break
if table:
rows = table.find_all('tr')[1:6]
for row in rows:
cells = row.find_all('td')
if len(cells) >= 4: # Ensure there are enough columns in the row
try:
est_eps = cells[2].text.strip().replace('$', '').replace(',', '')
except ValueError:
continue # Skip rows where conversion from string to float fails
else:
print(f"Failed to find earnings table for {ticker}")
return est_eps
# Example usage
ticker = 'AAPL'
beats = get_eps(ticker)
print(f'{ticker} estimates {est_eps}')
</code></pre>
|
<python><web-scraping><beautifulsoup><html-table><python-requests>
|
2024-05-07 04:44:49
| 1
| 397
|
Gloria Dalla Costa
|
78,440,085
| 1,019,455
|
Python packaged installed on Windows11, but not found when call
|
<p>I am using OSX 14.4.1 (23E224). Running parallel 18 + Windows 11.
I have to run Windows because MetaTrader5(MT5) python package is not support OSX.</p>
<p>Use 3.10 because it does support up to 3.10 <a href="https://stackoverflow.com/a/74346406/1019455">https://stackoverflow.com/a/74346406/1019455</a></p>
<pre><code>PS Microsoft.PowerShell.Core\FileSystem::\\Mac\Home\Documents> python -V
Python 3.10.11
</code></pre>
<p>I installed <code>pip-tools</code> in order to use <code>pip-compile</code></p>
<pre><code>PS Microsoft.PowerShell.Core\FileSystem::\\Mac\Home\Documents> pip freeze build==1.2.1 click==8.1.7 colorama==0.4.6 packaging==24.0
pip-tools==7.4.1
pyproject_hooks==1.1.0
tomli==2.0.1
</code></pre>
<p><strong>Problem</strong>:</p>
<pre><code>PS Microsoft.PowerShell.Core\FileSystem::\\Mac\Home\Documents> pip-compile
pip-compile : The term 'pip-compile' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ pip-compile
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (pip-compile:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS Microsoft.PowerShell.Core\FileSystem::\\Mac\Home\Documents> pip -V
pip 24.0 from C:\Users\sarit\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip (python 3.10)
</code></pre>
<p><strong>Attempt</strong>:
I have search the Internet, I found not related to my question for example
<a href="https://stackoverflow.com/questions/23708898/pip-is-not-recognized-as-an-internal-or-external-command">'pip' is not recognized as an internal or external command</a></p>
<p><a href="https://www.liquidweb.com/kb/adding-python-path-to-windows-10-or-11-path-environment-variable/" rel="nofollow noreferrer">https://www.liquidweb.com/kb/adding-python-path-to-windows-10-or-11-path-environment-variable/</a>
I don't found <code>Python</code> like this article.</p>
<pre><code> Directory: C:\Users\sarit\AppData\Local
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 4/29/2024 12:32 AM Comms
d----- 4/29/2024 12:31 AM ConnectedDevicesPlatform
d----- 4/29/2024 12:39 AM Microsoft
d----- 5/5/2024 12:55 PM Packages
d----- 5/5/2024 12:34 PM PlaceholderTileLogoFolder
d----- 4/29/2024 12:40 AM Publishers
d----- 5/7/2024 10:39 AM Temp
d----- 4/29/2024 12:32 AM VirtualStore
-a---- 5/7/2024 10:24 AM 1855 parallels.log
-a---- 5/5/2024 12:56 PM 14932 prlextscache.ini
PS C:\Users\sarit\AppData\Local>
</code></pre>
|
<python><macos><powershell><pip><windows-11>
|
2024-05-07 04:12:10
| 1
| 9,623
|
joe
|
78,439,955
| 7,085,728
|
Django `db_table` not renaming table
|
<p>This question is (surprisingly) unlike similar ones, which ask about doing this dynamically, or ask how to do it in the first place. This question regards those suggestions not working as expected.</p>
<p>Brief summary of situation:</p>
<ol>
<li>We made a series of Django apps as part of an API used in a real web app.</li>
<li>We named those apps in ways that made sense at the time, e.g., "organizations" and "authentication".</li>
<li>Now, we are packaging these apps as a distributable library, so a third party can install our apps in their API.</li>
<li>The client already has apps named "organizations" and "authentication", causing conflicts (because Django apps must have unique names).</li>
<li>Because we are creating the reusable library, we are renaming our apps from <code>organizations</code> to <code>mycompany_organizations</code> to make them unique and distinguishable.</li>
<li>I have made a series of migrations following <a href="https://realpython.com/move-django-model/#the-django-way-rename-the-table" rel="nofollow noreferrer">this guide</a> to create a new app and move the models over without losing data.</li>
<li>Everything worked until someone added a new app that referenced our <code>Organization</code> model. This migration results in <code>relation my_company_organization does not exist</code>, despite multiple foreign keys already pointing to <code>my_company_organizations.organization</code> and working fine.</li>
<li>I inspected the database and found that the table names were still in the style of <code>organizations_organization</code> instead of <code>my_company_organizations_organization</code>.</li>
<li>I set <code>db_table = "my_company_organization"</code> on the <code>MyCompanyOrganization</code> model to try to rename the database table.</li>
<li>I made and ran migrations. I <strong>verified that the 000x_alter_organization_table</strong> migration has been successfully applied.</li>
<li>I still get the same error on the first migration in the new app.</li>
<li>I inspected the database, and the table name is <strong>still</strong> <code>organizations_organization</code>!</li>
</ol>
<p>How can I <strong>rename the database table</strong> using Django migrations? Changing <code>db_table</code> is plainly not working.</p>
<p>Here is the code of a migration that renames a table:</p>
<pre><code>from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("my_company_organizations", "0005_do_stuff"),
]
operations = [
migrations.AlterModelTable(
name="organization",
table="my_company_organizations_organization",
),
migrations.AlterModelTable(
name="organizationemaildomain",
table="my_company_organizations_organizationemaildomain",
),
]
</code></pre>
<p>Neither of these tables are actually renamed to <code>my_company_x</code> after successfully running the migration.</p>
<p><strong>Update:</strong> It works if the new app depends not only on the latest migration in the <code>my_company_organizations</code> app, but also the latest migration in the old <code>organizations</code> app (which is depended upon by the new app). It makes no sense to me, since the migrations to rename the tables, and all migrations in the old app, have been executed before it reaches the failing migration anyway. Adding the dependency should change nothing because the migrations it depends on have already been executed anyway, but adding that dependency works for some reason, and I see the rename in the database. I can't help but consider this a bug in Django.</p>
|
<python><django><django-migrations>
|
2024-05-07 03:20:40
| 0
| 689
|
Audiopolis
|
78,439,954
| 17,835,120
|
Adapt variables of recommendations from yfinance using python
|
<p>How do you adapt variables <a href="https://pypi.org/project/yfinance/" rel="nofollow noreferrer">recommendations</a> for consensus recs using yfinance library in python such as specified number of months, intervals and time period?</p>
<p>The script below for example will provide 4 months, 1 month interval from current date.</p>
<pre><code>import pandas as pd # Import the missing "pd" module
import yfinance as yf
# Define the stock ticker
stock = yf.Ticker("AAPL")
# Get stock info
info = stock.info
# Access analyst recommendations if available
recommendations = stock.recommendations
print(recommendations) # Print the full DataFrame
</code></pre>
<p>Output</p>
<pre><code> period strongBuy buy hold sell strongSell
0 0m 11 21 6 0 0
1 -1m 10 17 12 2 0
2 -2m 10 17 12 2 0
3 -3m 10 24 7 1 0
</code></pre>
<p>But trying to have script where I can specify either dates, months or intervals and then will have more periods provided</p>
<p>For example, periods=12, interval = 2 months, end=mm/dd/yyyy will provide 12 periods dating back a total of 24 months.</p>
<p><strong>My attempt ran into a series of errors</strong></p>
<pre><code>import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta
def get_analyst_recommendations(stock_ticker, num_months, interval_months, end_date=None):
if end_date is None:
end_date = datetime.now().strftime("%Y-%m-%d")
else:
end_date = datetime.strptime(end_date, "%m/%d/%Y").strftime("%Y-%m-%d")
start_date = (datetime.strptime(end_date, "%Y-%m-%d") - timedelta(days=num_months*30)).strftime("%Y-%m-%d")
stock = yf.Ticker(stock_ticker)
if hasattr(stock, 'recommendations'):
recommendations = stock.recommendations
if recommendations is None or recommendations.empty:
print(f"No analyst recommendations found for {stock_ticker}")
return None
else:
print(f"Recommendations data not available for {stock_ticker}")
return None
recommendations = recommendations.loc[start_date:end_date]
# Convert the index to a DatetimeIndex
recommendations.index = pd.to_datetime(recommendations.index)
# Resample the recommendations based on the specified interval
resampled_recommendations = recommendations.resample(f'{interval_months}ME', label='right').agg('last')
# Count the number of each recommendation grade
grade_counts = resampled_recommendations.value_counts().unstack(fill_value=0)
# Reset the index
grade_counts = grade_counts.reset_index()
# Convert the relevant column to datetime and format it as a string
grade_counts['your_datetime_column'] = pd.to_datetime(grade_counts['your_datetime_column']).dt.strftime('-%mME')
# Set the formatted column as the index
grade_counts = grade_counts.set_index('your_datetime_column')
grade_counts.index = grade_counts.index.strftime('-%mME')
# Rename the columns to match the desired output format
grade_counts.columns = grade_counts.columns.str.replace(' ', '')
grade_counts = grade_counts.reindex(columns=['strongBuy', 'Buy', 'Hold', 'Sell', 'strongSell']).fillna(0).astype(int)
# Add the '0m' row at the beginning
grade_counts.loc['0m'] = 0
grade_counts = grade_counts.sort_index(ascending=False)
return grade_counts
# Example usage
stock_ticker = "AAPL"
num_months = 24
interval_months = 2
end_date = "05/06/2024"
recommendations = get_analyst_recommendations(stock_ticker, num_months, interval_months, end_date)
print(recommendations)
</code></pre>
<p><strong>Example of 6 periods</strong></p>
<pre><code>Custom Time-based Analyst Recommendations:
period strongBuy buy hold sell strongSell
Date
2023-06-31 -9m 10 24 7 1 0
2023-08-30 -7m 10 17 12 2 0
2023-09-30 -5m 11 21 6 0 0
2023-10-31 -3m 10 24 7 1 0
2023-12-31 -1m 10 17 12 2 0
2024-02-29 0m 11 21 6 0 0
</code></pre>
|
<python><pandas><yfinance>
|
2024-05-07 03:20:30
| 1
| 457
|
MMsmithH
|
78,439,812
| 3,179,698
|
Using jupyterhub/jupyterhub in docker hub get error
|
<p>I want to use jupyterhub/jupyterhub to start a container running jupyterhub.</p>
<p>So I create a Dockerfile:</p>
<pre><code>FROM jupyterhub/jupyterhub
RUN useradd -m test && \
echo "test:password" | chpasswd
</code></pre>
<p>And using <code>docker build -t jupyterhub_test:3 .</code> to build a image with user test and password password.</p>
<p>However, when I start the container using <code>docker run -itp 8080:8000 jupyterhub_test:3</code></p>
<p>I could log in in the host machine with hostmachine_ip:8080; but there is the error saids "No module named jupyter_core"</p>
<p>And I search for the solution, someone suggest to install notebook in Dockerfile and I tried, it works, but when I log in, I was in jupyterlab instead of jupyterhub interface.</p>
<p>So here comes two question:</p>
<p>1 How could I login into the jupyterhub instead of jupyterlab?</p>
<p>2 As an official docker hub, how come jupyterhub/jupyterhub image didn't work until I installed some other module, are there some things I didn't make correct? I suppose I should get a container immediately worked based on this image.</p>
<p>Addition:
I thought this is what the jupyterhub like:
<a href="https://i.sstatic.net/nSlrfwKP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/nSlrfwKP.png" alt="jupyterhub pic 1" /></a></p>
<p><a href="https://i.sstatic.net/6HqfUzWB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6HqfUzWB.png" alt="jupyterhub pic 2" /></a></p>
<p>May be the answer by @datawookie is also jupyterhub page</p>
<p>or the one I used before is jupyterhub + jupyter notebook
while the answer is jupyterhub + jupyterlab</p>
<p>or just the one I used is an old version.</p>
|
<python><docker><dockerhub><jupyterhub>
|
2024-05-07 02:16:22
| 1
| 1,504
|
cloudscomputes
|
78,439,806
| 9,129,978
|
Getting OSError: [Errno 86] Bad CPU type in executable when using PuLP CBC solver
|
<p>I am trying to use the following Python package on M3 Max Mac: <code>pydfs_lineup_optimizer</code>.</p>
<p>I am using <code>Python 3.12.2</code>.</p>
<p>However, I am getting the following error:</p>
<pre><code>Traceback (most recent call last):
File "/private/tmp/test.py", line 6, in <module>
for lineup in optimizer.optimize(10):
File "/private/tmp/venv/lib/python3.12/site-packages/pydfs_lineup_optimizer/lineup_optimizer.py", line 417, in optimize
solved_variables = solver.solve()
^^^^^^^^^^^^^^
File "/private/tmp/venv/lib/python3.12/site-packages/pydfs_lineup_optimizer/solvers/pulp_solver.py", line 47, in solve
self.prob.solve(self.LP_SOLVER)
File "/private/tmp/venv/lib/python3.12/site-packages/pulp/pulp.py", line 1737, in solve
status = solver.actualSolve(self, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/private/tmp/venv/lib/python3.12/site-packages/pulp/apis/coin_api.py", line 101, in actualSolve
return self.solve_CBC(lp, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/private/tmp/venv/lib/python3.12/site-packages/pulp/apis/coin_api.py", line 152, in solve_CBC
cbc = subprocess.Popen(args, stdout = pipe, stderr = pipe, stdin=devnull)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/python@3.12/3.12.2_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/subprocess.py", line 1026, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/opt/homebrew/Cellar/python@3.12/3.12.2_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/subprocess.py", line 1953, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
OSError: [Errno 86] Bad CPU type in executable: '/private/tmp/venv/lib/python3.12/site-packages/pulp/apis/../solverdir/cbc/osx/64/cbc'
</code></pre>
<p>The same package works fine on M3 Pro.</p>
<p>Does anyone know how I can resolve this error?</p>
|
<python><linear-programming><solver><pulp>
|
2024-05-07 02:15:00
| 1
| 539
|
tera_789
|
78,439,733
| 4,613,606
|
Access data on EMR directory from EMR Studio: Workspaces (Notebooks)
|
<p>I have some data saved on s3, which I want to import while running a python script on EMR.</p>
<p>To do it through a python code on EMR console: I just create the directories/file on my EMR like this <code>/home/mysource/settings</code> by copying the files from S3 to EMR and then the following code works as it should.</p>
<pre><code>import sys
from mysource.settings import *
</code></pre>
<p>Now I want to do the same thing from EMR studio: Workspaces, but apparently, even after attaching the EMR cluster to a workspace notebook, I am not able to make the import work.
It would be even better if I can import directly from s3, without creating this directory/file structure on EMR in first place.</p>
<p>I use an access key and a secret access key to transfer data between s3 and EMR (without tokens).</p>
|
<python><amazon-s3><import><amazon-emr>
|
2024-05-07 01:34:14
| 1
| 1,126
|
Gaurav Singhal
|
78,439,624
| 5,924,264
|
Hotkey for equal sign and colon alignment?
|
<p>I joined a company recently where they seem to like to align the <code>=</code> and <code>:</code> on consecutive lines in python, e.g., instead of</p>
<pre><code>a = 0
bb = 2
ccc = 3
</code></pre>
<p>they do</p>
<pre><code>a = 0
bb = 2
ccc = 3
</code></pre>
<p>and likewise for <code>:</code>. I find it very tedious to have to do this for every line when the spacing needs to be adjusted. Is there a hotkey for doing this in standard text editors? I most use VSCode and sublime.</p>
|
<python><visual-studio-code><sublimetext3><text-alignment>
|
2024-05-07 00:40:53
| 1
| 2,502
|
roulette01
|
78,439,411
| 10,224
|
Can I install the mltable package into Anaconda?
|
<p>I need to use the mltable package to create mltable files for Azure Machine Learning from CSV files.</p>
<p>I have Anaconda installed, but there does not seem to be a way to install the mltable package, since it is in PyPI but not anaconda.org. This seems like a common problem in general.</p>
<p>What can I do here?</p>
|
<python><package><anaconda><azure-machine-learning-service>
|
2024-05-06 22:40:26
| 1
| 6,804
|
Pittsburgh DBA
|
78,439,134
| 235,218
|
How to use Python's subprocess to run a 'conda list' command and pipe it to a text file
|
<p>My objective is to use Python's subprocess module to run the following 'conda list>[fullPath_based_on_date]' command in the Anaconda prompt environment:</p>
<pre><code>r'conda list>z:\backup\Anaconda\conda_list_2024-05-06_13-23-45.txt'
</code></pre>
<p>I have not been able to find a way to get subprocess to run that command in an Anaconda environment.
But I composed the Python script below hoping that someone will give me some hints about how to fix it, and where I can learn about what I did wrong.
Here is my Python script:</p>
<pre><code>import os
import subprocess
from datetime import datetime as DTT
NL, TAB, NLT = '\n', '\t', '\n\t'# {NL}{TAB}{NLT}
DT_now_str = (f'''{(DTT.now()).strftime("%Y-%m-%d_%H-%M")}''')
DT_now_str_wSeconds = (f'''{(DTT.now()).strftime("%Y-%m-%d_%H-%M-%S")}''')
print(f'''{DT_now_str = }{NLT}''' +
f'''{DT_now_str_wSeconds = }''')
dst_fullPath_based_on_date = r'z:\backup\Anaconda' + os.sep + 'conda_list_' + DT_now_str_wSeconds + '.txt'
cmd_conda_list_piped2txt = r'conda list>' + dst_fullPath_based_on_date
print(f'''{NL}{cmd_conda_list_piped2txt = }''')
subprocess.run(cmd_conda_list_piped2txt)
print(f'''{NL}{exitcode = }''' +
f'''{out = }''' +
f'''{err = }''')
cmd_edit_conda_list = r"C:\Program Files\Notepad++\notepad++.exe" + ' ' + dst_fullPath_based_on_date
print(f'''{NL}{cmd_edit_conda_list = }''')
subprocess.run(cmd_edit_conda_list)
print(f'''{NL}{exitcode = }''' +
f'''{out = }''' +
f'''{err = }''')
</code></pre>
<p>Any suggestions about how to get the subprocess module to run the 'conda list>[fullPath_based_on_date]' command in an Anaconda environment would be much appreciated.</p>
<p>Thank you,
Marc</p>
|
<python><anaconda><subprocess><conda>
|
2024-05-06 21:09:23
| 3
| 767
|
Marc B. Hankin
|
78,438,990
| 6,197,439
|
Python3 custom pretty printer for derived class objects?
|
<p>I have attempted to make a pretty printer for a number of objects deriving from a class; but I have arrived at some behavior that puzzles me - I hope I can get some help to understand (and fix) it. Consider the following code:</p>
<pre class="lang-python prettyprint-override"><code>from collections import OrderedDict
import pprint
class Basis(OrderedDict):
def __init__(self):
self["name"] = "Basis"
def __str__(self):
return "{{ {} }}".format(
", ".join(["'{}': {}".format(k, "'{}'".format(v) if type(v)==str else v) for k,v in self.items()])
)
#def __repr__(self):
# return self.__str__()
class ClassOne(Basis):
def __init__(self):
self["name"] = "ClassOne"
self["keyA"] = "ValueA"
class ClassTwo(Basis):
def __init__(self):
self["name"] = "ClassTwo"
self["keyB"] = "ValueB"
class Collector(Basis):
def __init__(self):
pass #self["name"] = "Collector"
class Collector2(Basis):
def __init__(self):
self["name"] = "Collector2"
class ODPPrinter(pprint.PrettyPrinter):
# based on https://stackoverflow.com/q/40828173 ; https://stackoverflow.com/q/3258072 ;
_dispatch = pprint.PrettyPrinter._dispatch.copy()
def _pprint_odtype(self, object, stream, indent, allowance, context, level): # _pprint_yourtype ; _pprint_operation
print("ODPPrinter", f"{object=}", flush=True)
items = object.items()
if not items:
print("not items: {}".format(items), flush=True)
stream.write(repr(object))
return
cls = object.__class__
print("ODPPrinter", f"{cls=}", flush=True)
stream.write(cls.__name__ + "(")
self._format_items(
items, stream, indent + len(cls.__name__), allowance + 1, context, level
)
stream.write(')')
print(f"# ODPPrinter {hex(id(Basis.__repr__))=}", flush=True)
_dispatch[Basis.__repr__] = _pprint_odtype
def main():
col = Collector()
col["c1"] = ClassOne()
col2 = Collector2()
col2["c2"] = ClassTwo()
odpp = ODPPrinter()
print("\n** col", f"{col.__repr__=}\n{hex(id(col.__repr__))=}\n", "col printout:\n", odpp.pformat(col), "\n", flush=True)
print("\n** col2", f"{col2.__repr__=}\n{hex(id(col2.__repr__))=}\n", "col2 printout:\n", odpp.pformat(col2), "\n", flush=True)
if __name__ == '__main__':
main()
</code></pre>
<p>If you run the code as-is, then: <code>class Basis</code> has no custom <code>__repr__()</code> method; <code>class Collector</code> has <code>pass</code> in its init, while <code>class Collector2</code> initializes a key/value par in its init; if you call the code, you get this printout:</p>
<pre class="lang-none prettyprint-override"><code>$ python3 test.py
# ODPPrinter hex(id(Basis.__repr__))='0x21580c40bd0'
** col col.__repr__=<method-wrapper '__repr__' of Collector object at 0x00000215814a3840>
hex(id(col.__repr__))='0x215814dc190'
col printout:
Collector([('c1', ClassOne([('name', 'ClassOne'), ('keyA', 'ValueA')]))])
ODPPrinter object=Collector2([('name', 'Collector2'), ('c2', ClassTwo([('name', 'ClassTwo'), ('keyB', 'ValueB')]))])
ODPPrinter cls=<class '__main__.Collector2'>
** col2 col2.__repr__=<method-wrapper '__repr__' of Collector2 object at 0x00000215814a3940>
hex(id(col2.__repr__))='0x215814dc190'
col2 printout:
Collector2(('name', 'Collector2'),
('c2', ClassTwo([('name', 'ClassTwo'), ('keyB', 'ValueB')])))
</code></pre>
<p>So, when <code>class Basis</code> has no custom <code>__repr__()</code>, <code>ODPPrinter._pprint_odtype()</code> got only triggered for <code>Collector2</code> (which did not just <code>pass</code>, but initialized a key/value in its <code>__init__()</code>), even though both col and col2 report their repr to be "<code><method-wrapper '__repr__' of Collector* object</code>"</p>
<p>If I now uncomment the repr method of <code>class Basis</code>:</p>
<pre class="lang-python prettyprint-override"><code> def __repr__(self):
return self.__str__()
</code></pre>
<p>... and re-run the code, I get:</p>
<pre class="lang-none prettyprint-override"><code>$ python3 test.py
# ODPPrinter hex(id(Basis.__repr__))='0x183c8ec1620'
** col col.__repr__=<bound method Basis.__repr__ of { 'c1': { 'name': 'ClassOne', 'keyA': 'ValueA' } }>
hex(id(col.__repr__))='0x183c8eafb40'
col printout:
{ 'c1': { 'name': 'ClassOne', 'keyA': 'ValueA' } }
** col2 col2.__repr__=<bound method Basis.__repr__ of { 'name': 'Collector2', 'c2': { 'name': 'ClassTwo', 'keyB': 'ValueB'
} }>
hex(id(col2.__repr__))='0x183c8eafbc0'
col2 printout:
{ 'name': 'Collector2', 'c2': { 'name': 'ClassTwo', 'keyB': 'ValueB' } }
</code></pre>
<p>So, when <code>class Basis</code> <em>does</em> have custom <code>__repr__()</code>, <em>both</em> col and col2 report their repr to be "<code><bound method Basis.__repr__ of {...}</code>", regardless of if they just <code>pass</code> their init or not - and I'd expect <code>_dispatch[Basis.__repr__] = _pprint_odtype</code> to establish the triggering of <code>_pprint_odtype</code> precisely when <code>Basis.__repr__</code> is reported by the type of <code>__repr__()</code> of the respective object - but here, <code>ODPPrinter._pprint_odtype()</code> <em>never</em> triggers?</p>
<p>So, my question is - is there a way to set up the pretty printer, so it always runs on objects derived from (in this case) <code>class Basis</code> - regardless of whether they just <code>pass</code> (or actually initialize keys/properties) in their <code>__init__</code>, and regardless of whether the <code>Basis.__repr__()</code> method has been overloaded or not?</p>
|
<python><python-3.x><class><inheritance><pretty-print>
|
2024-05-06 20:26:59
| 0
| 5,938
|
sdbbs
|
78,438,946
| 2,675,981
|
ModuleNotFoundError: No module named 'argparse_formatter'
|
<p>I feel like I am missing something incredibly simple, but I can't, for the life of me figure out what it is.</p>
<p>I am trying to run a <strong>Python3</strong> script on a <strong>Windows</strong> box, and I get the error
<code>ModuleNotFoundError: No module named 'argparse_formatter'</code>. However, when I check to see if the module is installed, it shows it is.</p>
<pre><code>pip3 install argparse_formatter
Requirement already satisfied: argparse_formatter in c:\users\scott\appdata\local\programs\python\python311\lib\site-packages (1.4)
</code></pre>
<p>And when I look in that directory, it is indeed there. Yet, I get an error with this</p>
<pre><code>python3 -c "import argparse_formatter; print(argparse_formatter);"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'argparse_formatter'
</code></pre>
<p>I read that it could be some environmental variables, but they all seem to be correct. And most posts about this are Linux based... which is not exactly helpful for Windows based users.</p>
<p>Any help would be much appreciated!</p>
|
<python><python-3.x><pip><argparse><formatter>
|
2024-05-06 20:17:41
| 1
| 885
|
Apolymoxic
|
78,438,807
| 4,375,983
|
Moving to python 3.12.2 generates PicklingError during spark dataframe creation
|
<p>I am not very experienced in spark, spark context elements and handling them... Please advise on the following problem:</p>
<p>I used to run a test involving the creation of a mocked spark context in python <code>3.9.6</code> that worked well. Since we moved to python <code>3.12.2</code>, this code raises an Exception when trying to create a simple dataframe with a schema (This is a simplified version of my code that raises the same error):</p>
<pre><code>from pyspark.sql import SparkSession
from pyspark.sql.types import (
StructType,
StructField,
StringType,
TimestampType,
)
BODACC_SCHEMA = StructType(
[
StructField("siren", StringType(), True),
StructField("identifier", StringType(), True),
StructField("nojo", StringType(), True),
StructField("type_annonce", StringType(), True),
StructField("date_publication", TimestampType(), True),
StructField("source_identifier", StringType(), True),
StructField("data_source", StringType(), True),
StructField("created_at", TimestampType(), True),
StructField("updated_at", TimestampType(), True),
]
)
spark_session = SparkSession.builder.master("local[1]").appName("LocalExample").getOrCreate()
spark_session.createDataFrame([], BODACC_SCHEMA)
</code></pre>
<p>This is the exception that is raised.</p>
<pre><code>Traceback (most recent call last):
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/serializers.py", line 458, in dumps
return cloudpickle.dumps(obj, pickle_protocol)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/cloudpickle/cloudpickle_fast.py", line 73, in dumps
cp.dump(obj)
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/cloudpickle/cloudpickle_fast.py", line 602, in dump
return Pickler.dump(self, obj)
^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/cloudpickle/cloudpickle_fast.py", line 692, in reducer_override
return self._function_reduce(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/cloudpickle/cloudpickle_fast.py", line 565, in _function_reduce
return self._dynamic_function_reduce(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/cloudpickle/cloudpickle_fast.py", line 546, in _dynamic_function_reduce
state = _function_getstate(func)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/cloudpickle/cloudpickle_fast.py", line 157, in _function_getstate
f_globals_ref = _extract_code_globals(func.__code__)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/cloudpickle/cloudpickle.py", line 334, in _extract_code_globals
out_names = {names[oparg]: None for _, oparg in _walk_global_ops(co)}
~~~~~^^^^^^^
IndexError: tuple index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/sql/session.py", line 894, in createDataFrame
return self._create_dataframe(
^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/sql/session.py", line 938, in _create_dataframe
jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd())
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/rdd.py", line 3113, in _to_java_object_rdd
return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, True)
^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/rdd.py", line 3505, in _jrdd
wrapped_func = _wrap_function(
^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/rdd.py", line 3362, in _wrap_function
pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/rdd.py", line 3345, in _prepare_for_python_RDD
pickled_command = ser.dumps(command)
^^^^^^^^^^^^^^^^^^
File "/home/user/.pyenv/versions/3.12.2/envs/data_pipelines/lib/python3.12/site-packages/pyspark/serializers.py", line 468, in dumps
raise pickle.PicklingError(msg)
_pickle.PicklingError: Could not serialize object: IndexError: tuple index out of range
</code></pre>
<p>I am using <code>pyspark==3.3.0</code>.</p>
<p>Why is this happening, how can I fix it?</p>
<p>Edit : I tried with <code>pyspark==3.5.1</code> aswell, and it's not working either. (See Edit 2)</p>
<p>Edit 2 : Running this code in fact with <code>python==3.12.2</code> & <code>pyspark==3.5.1</code> "simply" does not produce an error. The first time it did was because I ran it through debugpy and that apparently interferes with pickling somehow.... I don't fully understand the details of this yet, if somebody can explain why it worked on prior versions of python (even through debugpy) and doesn't anymore, I'd really appreciate it.</p>
<p>P.S This code is simplified to illustrate the problem, what I am doing in reality is sending a packaged .tar.gz of my code via dagster to an <strong>EMR Serverless</strong> app that is running pyspark code. There is certainly a parallel between debugpy and the way this code is running through EMR...</p>
|
<python><python-3.x><apache-spark><pyspark><apache-spark-sql>
|
2024-05-06 19:43:24
| 1
| 2,811
|
Imad
|
78,438,768
| 5,316,326
|
Dask set dtype to an array of integers
|
<p>With Dask I try to create a column that has type list with integers. For example:</p>
<pre class="lang-py prettyprint-override"><code>import dask.dataframe as dd
import pandas as pd
# Have an example Dask Dataframe
ddf = dd.from_pandas(pd.DataFrame({
'id': [1, 2, 3, 4, 5],
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emma'],
'age': [25, 30, 35, 40, 45]
}), npartitions=1)
# now create an array type column
ddf["alist"] = ddf.apply(
lambda k: [1, 0, 0], axis=1, meta=("alist", "list<item: int64>")
)
</code></pre>
<p>This particular case fails because:</p>
<blockquote>
<p>TypeError: data type 'list<item: int64>' not understood</p>
</blockquote>
<p>Eventually I want to write to parquet:</p>
<pre class="lang-py prettyprint-override"><code>ddf.to_parquet(
"example",
engine="pyarrow",
compression="snappy",
overwrite=True,
)
</code></pre>
<p>and if I specify the dtype incorrect it raises:</p>
<pre><code>ValueError: Failed to convert partition to expected pyarrow schema:
`ArrowInvalid('Could not convert [1, 2, 3] with type list: tried to convert to int64', 'Conversion failed for column alist with type object')`
Expected partition schema:
id: int64
name: large_string
age: int64
alist: int64
__null_dask_index__: int64
Received partition schema:
id: int64
name: large_string
age: int64
alist: list<item: int64>
child 0, item: int64
__null_dask_index__: int64
This error *may* be resolved by passing in schema information for
the mismatched column(s) using the `schema` keyword in `to_parquet`.
</code></pre>
|
<python><pandas><dask>
|
2024-05-06 19:32:37
| 2
| 4,147
|
Joost Döbken
|
78,438,685
| 6,606,057
|
Using a Mask to Insert Values from sklearn Iterative Imputer
|
<p>I created a set of random missing values to practice with a tree imputer. However, I'm stuck on how to overwrite the missing values into the my dataframe. My missing values look like this:</p>
<p><a href="https://i.sstatic.net/erMMITvI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/erMMITvI.png" alt="enter image description here" /></a></p>
<pre><code>from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
df_post_copy = df_post.copy()
missing_mask = df_post_copy.isna()
imputer = IterativeImputer(max_iter=10, random_state=0)
imputed_values = imputer.fit_transform(df_post_copy)
df_copy[missing_mask] = imputed_values[missing_mask]
</code></pre>
<p>Results in:</p>
<pre><code>ValueError: other must be the same shape as self when an ndarray
</code></pre>
<p>But the shape matches...</p>
<pre><code>imputed_values.shape
(16494, 29)
</code></pre>
<p>The type is:</p>
<pre><code>type(imputed_values)
numpy.ndarray
</code></pre>
<p>What I have tried since it is the right shape is to convert it to a pandas dataframe:</p>
<pre><code>test_imputed_values = pd.DataFrame(imputed_values)
</code></pre>
<p>When I try:</p>
<pre><code>df_copy[missing_mask] = test_imputed_values[missing_mask]
</code></pre>
<p>I get the same as above:</p>
<p><a href="https://i.sstatic.net/kpQ4iBb8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kpQ4iBb8.png" alt="enter image description here" /></a></p>
<p>How do I use a mask to insert the imputed values where needed?</p>
|
<python><pandas><sklearn-pandas><imputation>
|
2024-05-06 19:14:48
| 2
| 485
|
Englishman Bob
|
78,438,668
| 12,227,905
|
Generating random passphrases from sets of strings with secrets.random is not very random
|
<p>I have a requirement for a basic passphrase generator that uses set lists of words, one for each position in the passphrase.</p>
<pre><code> def generate(self) -> str:
passphrase = "%s-%s-%s-%s-%s%s%s" % (
self.choose_word(self.verbs),
self.choose_word(self.determiners),
self.choose_word(self.adjectives),
self.choose_word(self.nouns),
self.choose_word(self.numbers),
self.choose_word(self.numbers),
self.choose_word(self.numbers),
)
</code></pre>
<p>The lists chosen from contain 100 adjectives, 9 determiners, 217 nouns, 67 verbs, and digits 1-9 and the choices are made using secrets.choice</p>
<pre><code> def choose_word(cls, word_list: List[str]) -> str:
return secrets.choice(word_list)
</code></pre>
<p>In theory I thought this would give me a shade under 13 billion unique passwords. However I have written a test case that generates 10,000 passphrases and checks that they are all unique through a membership check on a sequence of the generated passphrases</p>
<pre><code>def test_can_generate_10000_passphrases_without_collision(passphrase: Passphrase):
generated_passphrases = []
for i in range(10000):
generated_passphrase = passphrase.generate()
assert generated_passphrase is not None and len(generated_passphrase) > 10
assert generated_passphrase not in generated_passphrases
generated_passphrases.append(generated_passphrase)
assert len(generated_passphrases) == 10000
</code></pre>
<p>However, the test does not reflect the probability of duplicates I expected. Using pytest-repeat I setup this test to run 10,000 times and it failed/generated duplicate passwords 24 times in 4145 runs before I killed the process. In each case the output of the test is truncated but shows that a chosen passphrase was found 'in' the set of generated phrases, and the phrase is different each time.</p>
<p>I don't really have a specific question here, it just seems like I'm misunderstanding something, either my probability calculations are wrong and I need to add more words to the lists or something about the test in sequence check is doing a looser match then I expected.</p>
<p>I switched from random.choices to secrets.choices, I tried re-instantiating the password generator class between runs, tried adding checks that the password was non-empty (because empty strings always match) and also tried running in and out of a docker container thinking there might be something messing up the randomness.</p>
|
<python><random><sequence><membership><secrets>
|
2024-05-06 19:09:45
| 1
| 2,029
|
Alec Joy
|
78,438,612
| 274,601
|
create column based on another column value in the same dataframe
|
<p>I have a dataframe, that looks like:</p>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th>Question</th>
<th>Answer</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Category1</td>
</tr>
<tr>
<td>1</td>
<td>Category1</td>
</tr>
<tr>
<td>1</td>
<td>Not Important</td>
</tr>
<tr>
<td>2</td>
<td>Category2</td>
</tr>
<tr>
<td>2</td>
<td>Category2</td>
</tr>
<tr>
<td>2</td>
<td>Very Important</td>
</tr>
</tbody>
</table></div>
<p>My goal is to create another column 'Category' in the dataframe which fetches the value of the category from the answer column
The resulting dataframe:</p>
<div class="s-table-container"><table class="s-table">
<thead>
<tr>
<th>Question</th>
<th>Answer</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Category1</td>
<td>Category1</td>
</tr>
<tr>
<td>1</td>
<td>Category1</td>
<td>Category1</td>
</tr>
<tr>
<td>1</td>
<td>Not Important</td>
<td>Category1</td>
</tr>
<tr>
<td>2</td>
<td>Category2</td>
<td>Category2</td>
</tr>
<tr>
<td>2</td>
<td>Category2</td>
<td>Category2</td>
</tr>
<tr>
<td>2</td>
<td>Very Important</td>
<td>Category2</td>
</tr>
</tbody>
</table></div>
|
<python><pandas><dataframe>
|
2024-05-06 18:57:28
| 0
| 3,181
|
Lisa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.