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
76,704,696
5,722,359
Why would the ttk widget only appears after there is a configuration change event and not when the button is pressed?
<p>Can you help me understand why the <code>ttk.Checkbutton</code> widget does not appear after the <code>ttk.Button</code> widget is pressed? The <code>ttk.Checkbutton</code> widget would only appear when there is a configuration change event, for example after moving the sash of the <code>ttk.PanedWindow</code> widget or by resizing the root window. Or, when the height of <code>self.f2</code> is less than the Checkbutton. This code uses a <a href="https://github.com/sunbearc22/tkinterWidgets/blob/master/scrframe.py" rel="nofollow noreferrer">vertical scroll frame</a> which is saved in the file named <code>scrframe.py</code></p> <p>Test Code:</p> <pre><code>import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk from scrframe import VerticalScrollFrame class App(ttk.PanedWindow): def __init__(self, parent, orient=&quot;vertical&quot;): super().__init__(parent, orient=orient) self.parent = parent self.after_id = None self.f1 = ttk.Frame(self, style=&quot;Top.TFrame&quot;) self.f2 = VerticalScrollFrame(self, background='green') self.add(self.f1) self.add(self.f2) self.b1 = ttk.Button(self.f1, text=&quot;Button&quot;, command=self.load_image, width=30) self.b1.grid(row=0, column=0, sticky=&quot;nsew&quot;, padx=5, pady=5) self.f1.bind(&quot;&lt;Configure&gt;&quot;, self.schedule_event) self.f2.bind(&quot;&lt;Configure&gt;&quot;, self.schedule_event) self.bind(&quot;&lt;&lt;SashMoved&gt;&gt;&quot;, self.do_something) # Event handlers def schedule_event(self, event): if self.after_id: self.after_cancel(self.after_id) self.after_id = self.after(500, self.event_generate, &quot;&lt;&lt;SashMoved&gt;&gt;&quot;) def do_something(self, event): print(&quot;do_something was called&quot;) def load_image(self): im = '/home/user/Pictures/image.jpeg' im = Image.open(im) im.thumbnail((200, 200)) self.thumbnail = ImageTk.PhotoImage(im) self.thumbnail.image = im self.cb = ttk.Checkbutton(self.f2.interior, text=&quot;Image&quot;, image=self.thumbnail, compound=&quot;top&quot;) self.cb.grid(row=0, column=0, padx=5, pady=5) self.update_idletasks() # Does not work if __name__ == '__main__': root = tk.Tk() ss = ttk.Style() ss.configure('Top.TFrame', background=&quot;red&quot;) app = App(root) app.pack(fill=&quot;both&quot;, expand=True) root.mainloop() </code></pre> <p>Issue: Checkbutton does not appears immediately when the height of <code>self.f2</code> is greater than the Checkbutton.</p> <p><a href="https://i.sstatic.net/vZII7.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/vZII7.gif" alt="Issue" /></a></p> <p>Checkbutton appears immediately when the height of <code>self.f2</code> is less than the Checkbutton:</p> <p><a href="https://i.sstatic.net/mJRu4.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mJRu4.gif" alt="Checkbutton appears immediately when the height of self.f2 is less than the Checkbutton" /></a></p>
<python><tkinter><tcl><ttk>
2023-07-17 12:56:05
1
8,499
Sun Bear
76,704,505
9,944,937
Track Mouse (animal) in video using YOLO v8 trained on fiftyone.zoo dataset
<h1>The problem:</h1> <p>I am trying to train a YOLO v8 model using a custom dataset to detect (and track) a mouse in a video but with poor results. Can you help me improve the performances of my model?</p> <p><strong>PS: The training of the model require a quite some time, I'm asking you for tips to improve the performances so I won't waste too much time changing or optimising parameters that have little or no effect to the overall performances of the model.</strong></p> <h2>Essential details:</h2> <p>I'm a researcher, and I'm completely new to computer vision. I am running an experiment where I need to track a mouse's movements inside a cage from a camera (fixed angle). I am trying to train a YOLO v8 model using the fiftyone.zoo dataset &quot;open-images-v7&quot; however this is just my approach as a novice in the field so I'm happy to follow better suggestions:</p> <pre class="lang-py prettyprint-override"><code>import fiftyone as fo from ultralytics import YOLO from pathlib import Path from tqdm import tqdm import shutil # Load the FiftyOne dataset dataset = fo.zoo.load_zoo_dataset( &quot;open-images-v7&quot;, split=&quot;train&quot;, label_types=[&quot;detections&quot;], classes=[&quot;Mouse&quot;], max_samples=100, ) # Convert FiftyOne dataset to YOLO format output_dir = Path(&quot;yolo_dataset&quot;) output_dir.mkdir(exist_ok=True) for sample in tqdm(dataset): img_path = sample.filepath img_filename = Path(img_path).name yolo_labels_path = output_dir / (Path(img_filename).stem + &quot;.txt&quot;) with open(yolo_labels_path, &quot;w&quot;) as f: for detection in sample.ground_truth.detections: if detection.label == &quot;Mouse&quot;: bbox = detection.bounding_box x, y, width, height = bbox[0], bbox[1], bbox[2], bbox[3] x_center = x + width / 2 y_center = y + height / 2 yolo_label = f&quot;0 {x_center} {y_center} {width} {height}\n&quot; f.write(yolo_label) # Copy image file to the YOLO dataset folder shutil.copy(img_path, output_dir / img_filename) # Load a model model = YOLO('yolov8n.pt') # Train the model with the YOLO dataset model.train(data='config.yaml', epochs=100, device='mps') # Track with the model results = model.track(source=&quot;catmouse.mov&quot;, show=True) </code></pre> <p>my <code>config.yaml</code> file is:</p> <pre class="lang-yaml prettyprint-override"><code>path: /home/path/to/code/folder train: yolo_dataset # train images (relative to 'path') val: yolo_dataset # val images (relative to 'path') # Classes names: 0: Mouse </code></pre> <p>as for the video <code>catmouse.mov</code> in this example is just an extract of this video from YouTube: <a href="https://youtu.be/6pbreU5ChmA" rel="nofollow noreferrer">https://youtu.be/6pbreU5ChmA</a>. Feel free to use any other video with a mouse/mice.</p>
<python><deep-learning><computer-vision><yolo><yolov8>
2023-07-17 12:34:44
1
1,101
Fabio Magarelli
76,704,445
7,445,658
Difference between caching methods in python
<p>What difference is there between using the <code>@cache</code> decorator from the built-in <code>functools</code> module and the one from <code>joblib</code>?</p> <p>Also, <a href="https://docs.python.org/3/library/functools.html#functools.cache" rel="nofollow noreferrer"><code>@functools.cache</code>'s documentation</a> mentions</p> <blockquote> <p>Returns the same as lru_cache(maxsize=None), creating a thin wrapper around a dictionary lookup for the function arguments. Because it never needs to evict old values, this is smaller and faster than lru_cache() with a size limit.</p> </blockquote> <p>which seems counter-intuitive to me: why would storing more values lead to a <em>smaller and faster</em> solution than <code>lru_cache()</code>?</p>
<python><caching><joblib>
2023-07-17 12:26:29
0
339
alexis_thual
76,704,151
1,469,954
Service relaunch Python script when it has stalled in Linux
<p>I am trying to run a Python script as service in Linux. I found some good instructions <a href="https://websofttechs.com/tutorials/how-to-setup-python-script-autorun-in-ubuntu-18-04/" rel="nofollow noreferrer">here</a>, and how to restart a failed script in the next run <a href="https://forums.raspberrypi.com/viewtopic.php?t=324417" rel="nofollow noreferrer">here</a>.</p> <p>However, I have another scenario, where the script does not abort with failure, but it just stalls (it is downloading some resource, and it just stays stuck at 99%). When I run it manually, I can observe it stuck for 1-2 minutes, and then I force abort the script (<code>CTRL-C</code>) and rerun and it works fine.</p> <p>How can I make the service do that as well? I can pipe all the output of the script to a file (right now the output is being piped to <code>STDOUT</code>, where I can observe the stalling), is there a way for the service to observe that the piped output file hasn't updated in last 5 minutes, and then so that it can force restart the script, even though the script was already in running mode (but stalled)?</p>
<python><linux><service><python-daemon>
2023-07-17 11:49:15
1
5,353
NedStarkOfWinterfell
76,703,932
4,141,120
Type variable ... is unbound (Python)
<p>I've realised that the following works as long as the TypeVar statement is in the same module as where it is applied:</p> <pre><code>import pathlib PathLike = TypeVar(&quot;PathLike&quot;, str, pathlib.Path) </code></pre> <p>However, when I move the TypeVar statement to another module - say customtypes - and I only use PathLike to indicate the type of the variable holding the path to my file, then this happens:</p> <pre><code>fn: PathLike </code></pre> <p>Mypy: Type variable &quot;customtypes.PathLike&quot; is unbound (Hint: Use &quot;Generic[PathLike]&quot; or &quot;Protocol[PathLike]&quot; base class to bind &quot;PathLike&quot; inside a class) (Hint: Use &quot;PathLike&quot; in function signature to bind &quot;PathLike&quot; inside a function). I'm not using &quot;PathLike&quot; within a class or function. I'm not getting the hints in the first place. I don't understand the use of the keyword Generic.</p> <p>Furthermore, typing is not able to handle the following:</p> <pre><code>import array from typing import NewType, TypeVar try: import numpy as np ArrayLike = TypeVar(&quot;ArrayLike&quot;, array.array, np.ndarray) except ImportError: ArrayLike = NewType(&quot;ArrayLike&quot;, array.array) </code></pre> <p>The error is: Mypy: Cannot redefine &quot;ArrayLike&quot; as a NewType Name &quot;ArrayLike&quot; already defined on line 5</p> <p>When I try to add the definition of ArrayLike to my module customtypes, things seem to go wrong. In the module where I try to then use the new types I have this:</p> <pre><code>import pandas as pd from customtypes import PathLike, ArrayLike df = pd.read_csv(fn) result = [] for i, row in df.iterrows(): arr: ArrayLike = row.to_numpy(dtype=&quot;float32&quot;) result.append(arr) </code></pre> <p>Mypy: Incompatible types in assignment (expression has type &quot;ndarray[Any, Any]&quot;, variable has type &quot;array[Any]&quot;). I guess that MyPy is programmed to assume that ndarray is a multidimensional array. How can I indicate to MyPy that ndarray is a flat array?</p>
<python><arrays><mypy><typing>
2023-07-17 11:19:13
0
588
Dobedani
76,703,900
5,269,892
Python shell script cannot be executed with source command
<p>I want to call a bash script from a python script using <code>subprocess.Popen()</code>. Calling the shell script as an executable works, but <code>source</code>ing it does not. Why?</p> <p>File <em><strong>test_python.py</strong></em>:</p> <pre><code>import sys import os import subprocess os.putenv(&quot;testvar&quot;, &quot;testvalue&quot;) test = subprocess.Popen(&quot;./test_shell.sh&quot;, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print(test) test = subprocess.Popen(&quot;. test_shell.sh&quot;, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print(test) test = subprocess.Popen(&quot;source test_shell.sh&quot;, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print(test) test = subprocess.Popen(&quot;/bin/bash test_shell.sh&quot;, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print(test) test = subprocess.Popen(&quot;/bin/sh test_shell.sh&quot;, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print(test) </code></pre> <p>File <em><strong>test_shell.sh</strong></em>:</p> <pre><code>#!/bin/bash echo &quot;$testvar&quot; </code></pre> <p>Output of <code>python test_python.py</code>:</p> <pre><code>('testvalue\n', '') ('', '/bin/sh: .: test_shell.sh: cannot open [No such file or directory]\n') ('', '/bin/sh: .: test_shell.sh: cannot open [No such file or directory]\n') ('testvalue\n', '') ('testvalue\n', '') </code></pre>
<python><bash><shell><subprocess>
2023-07-17 11:14:27
1
1,314
silence_of_the_lambdas
76,703,878
583,464
swap columns from multidimensional array
<p>I have this array:</p> <pre><code>my_array = np.arange(1216800).reshape(2, 100, 78, 78) </code></pre> <p>The shape now is: <code>(2, 100, 78, 78)</code> and I want to reorder to : <code>(100, 78, 78, 2)</code>.</p> <p>I tried something like:</p> <pre><code>my_array[:, :, 2, :], my_array[:, :, :, 3] = my_array[:, :, :, 3], my_array[:, :, 2, :].copy() </code></pre> <p>to swap first those columns, but I am receiving the same array.</p> <p>I saw <a href="https://stackoverflow.com/questions/4857927/swapping-columns-in-a-numpy-array">this</a> but whatever I try, I am having the same array.</p>
<python><numpy>
2023-07-17 11:11:57
2
5,751
George
76,703,598
14,282,714
Add slide numbers to Jupyter Notebook Slides
<p>I would like to add slide numbers to a Jupyter Notebook slideshow. I found an <a href="https://github.com/jupyter/nbconvert/issues/737" rel="nofollow noreferrer">issue</a> about this, but I am not sure how and if it possible to add slide numbers to your slides in Jupyter Notebook slideshow. Here is some reproducible code to make a slide show:</p> <pre><code># Jupyter Notebook Slides I would like to add a slide number here? </code></pre> <p>Using the command in the terminal:</p> <pre><code>jupyter nbconvert test_slides.ipynb --to slides --post serve </code></pre> <p>So I was wondering if anyone knows how to add a page number to your slides in a Jupyter Notebook Slideshow?</p>
<python><jupyter-notebook><jupyter><slideshow><page-numbering>
2023-07-17 10:32:12
1
42,724
Quinten
76,703,551
2,690,578
Statsforecast for python seems to predict values "one day ahead"
<p>I have been trying Statsforecast for Python now for a couple of weeks. It seems really good, however I noticed that my predictions always feels a bit off by one day. If you look at the first image, you can see how the graph almost matches with a difference of a day. If I displace the values one day, you can see that the graphs matches much better, however I lose the last day, 31st on this case.</p> <p>I feel like I am missing something when I am training the model. Has anyone experienced this?</p> <p><a href="https://i.sstatic.net/xtyjp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xtyjp.png" alt="initial predictions" /></a></p> <p><a href="https://i.sstatic.net/KQfTG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KQfTG.png" alt="predictions displaced by -1" /></a></p>
<python><time-series><statsforecast>
2023-07-17 10:26:42
1
609
Gabriel
76,703,308
2,138,913
Qt: Replacing deprecated pos() methods
<p>I have a simple app (a piano keyboard which receives midi and shows which keys are pressed) with a frameless window that I can drag around with the left mouse button.</p> <p>This works:</p> <pre class="lang-py prettyprint-override"><code> def mousePressEvent(self,e): modifiers = e.modifiers() if modifiers == Qt.ControlModifier: app.quit() else: self.mpos = e.pos() def mouseMoveEvent(self,e): buttons = e.buttons() if buttons == Qt.LeftButton: dpos = e.pos() - self.mpos newpos = self.pos() + dpos self.move(newpos) </code></pre> <p>But <code>pos()</code> is deprecated and I can't figure out what to replace it with.</p>
<python><qt>
2023-07-17 09:56:17
1
1,292
John Allsup
76,703,233
12,131,472
how to move dataframe's one column names(hierarchical) to index?
<p>I am sorry this seems a basic manipulation but I can't figure it out after searching. The title is probably not accurate.</p> <p>I have this dataframe</p> <pre><code>Bunker Port Rotterdam Singapore ... Rotterdam Singapore bunker HSFO HSFO ... VLSFO VLSFO period ... Jul 23 453.318000 461.028000 ... 518.098000 553.426000 Aug 23 448.266000 454.016000 ... 513.596000 549.716000 </code></pre> <p>There are 2 levels for the column names: 'Bunker Port' and 'bunker'</p> <p>and I wish to convert the df to below(the 0-4 index is unecessary):</p> <pre><code> bunker HSFO MGO VLSFO 0 period Bunker Port NaN NaN NaN 1 Jul 23 Rotterdam 453.318 723.83300 518.098 2 Aug 23 Rotterdam 448.266 735.00000 513.596 3 Jul 23 Singapore 461.028 734.04850 553.426 4 Aug 23 Singapore 454.016 738.74945 549.716 </code></pre> <p>Thanks a lot</p>
<python><pandas><dataframe>
2023-07-17 09:47:01
1
447
neutralname
76,703,126
8,329,213
Selecting all rows which contain values greater than a percentage of Average
<p>I have a <code>DataFrame</code>, which have 3 numeric columns <code>A,B,C</code>. I need to extract only those rows where values in all these 3 columns <code>A,B,C</code> is more than 40% of their <strong>row average</strong>.</p> <pre><code>df = pd.DataFrame([['AA',10,8,12],['BB',10,2,18],['CC',10,6,14]], columns=['ID','A', 'B', 'C']) print(df) ID A B C 0 AA 10 8 12 1 BB 10 2 18 2 CC 10 6 14 </code></pre> <p>I mean the following: For Row 1, the mean of A,B,C is 30/3=10, and I want that in Row 1 all values, be it A or B or C should be more than 40% of 10, i.e; 4. Similarly, for Row 2 and Row 3. In case even one element is less than that, we remove that row.</p> <p><strong>My attempt:</strong> I used <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.any.html" rel="nofollow noreferrer"><code>any()</code></a> function, but that does't help me when involving average of columns. I always get empty <code>DF</code>.</p> <pre><code>df = df[(df[['A','B','C']] &gt; (0.4*df[['A','B','C']].mean(axis=1))).all(1)] print(df) ID A B C </code></pre> <p>I was expecting this:</p> <pre><code> ID A B C 0 AA 10 8 12 2 CC 10 6 14 </code></pre> <p>The average of all rows is 10, so if I would have hardcoded it, it would work, like this:</p> <pre><code>df[(df[['A','B','C']] &gt; 0.4*10).all(1)] </code></pre> <p>How can I do this dynamically? Thanks.</p>
<python><pandas><dataframe>
2023-07-17 09:32:10
2
7,707
cph_sto
76,702,936
348,168
Replace $..$ within a string with \(...\) in Python
<p>I have a string here 'Let $[C | d]$ be $Star$'.</p> <p>How to replace $..$ within the above string with \(...\).</p> <p>The result should be 'Let \([C | d]\) be \(Star\)'.</p> <p>How can I do it python.</p> <p>I have tried as</p> <pre><code>import re x = 'Let $[C | d]$ be $Star$' y = re.sub(r'\$.*?\$', r'\\(.*?\\)', x) </code></pre> <p>but not working.</p> <p>the output was 'Let \(.<em>?\) be \(.</em>?\)'</p> <p>Ref : <a href="https://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclud">Regular Expression to find a string included between two characters while EXCLUDING the delimiters</a></p>
<python><regex>
2023-07-17 09:06:12
1
4,378
Vinod
76,702,921
2,583,670
Forming n-grams for a dataframe (numbers) in python
<p>I found many posts explaining <strong>n-grams</strong> in words. However, I need to apply n-grams (n = 2 or 3) on a dataframe that has integer numbers of n x m. For example: Consider the below dataframe (3 x 5)</p> <pre><code>df = 1, 2, 3, 4, 5 6, 7, 8, 9, 10 11, 12, 13, 14, 15 </code></pre> <p>I need to apply <strong>bigram</strong> and <strong>trigram</strong> on df.</p> <p>I tried this code, but it does not work properly</p> <pre><code>for i in range(df.shape[0]): row = list(str(df.iloc[i,:])) print(&quot;row: &quot;, row) bigrams = [b for l in row for b in zip(l.split(&quot; &quot;)[:-1], l.split(&quot; &quot;)[1:])] print(bigrams) </code></pre> <p>If the input is <code>df = [10,20,30,40,50,60,...]</code></p> <p>Expected output</p> <p>Bigram</p> <p><code>(10,20)(20,30)(30,40)(40,50)...</code></p> <p>Trigram</p> <p><code>(10,20,30)(20,30,40)(30,40,50)...</code></p>
<python><pandas><n-gram>
2023-07-17 09:04:09
1
711
Mohsen Ali
76,702,919
19,155,645
access function from a different subfolder in python project
<p>I have a python project with the following structure:</p> <pre><code>project_folder/ __init__.py subfolder/ __init__.py main.py generate_values.py lib/ __init__.py external.py </code></pre> <p>where I am running <code>subfolder/main.py</code>, and it internally calls <code>generate_values.py</code>.<br> Inside <code>generate_values.py</code> I am calling the function calculate_external from <code>lib/external.py</code>.</p> <p>The original code was: <code>from lib.external import calculate_external</code><br> this was working when the main and generate_values py files were not in a subfolder.</p> <p>but now I get the error <code>ModuleNotFoundError: No module named 'lib'</code></p> <p>after some research i tried the following but still got errors:</p> <ol> <li><code>from project_folder.lib.external import calculate_external</code> --&gt;<br> <code>ModuleNotFoundError: No module named 'project_folder'</code></li> <li><code>from ..lib.external import calculate_external</code> --&gt;<br> <code>ImportError: attempted relative import with no known parent package</code></li> </ol> <p>Any help in resolving this would be great. <br></p> <p>Note that the main and generate_values must stay in a subfolder, because there will be different such subfolders that do different things but all use the lib folder.</p>
<python>
2023-07-17 09:03:59
1
512
ArieAI
76,702,772
6,546,694
Why does pandas fail to join on two columns of object dtype (one of them is converted from int to object)?
<p>The following merge strategy fails:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data1 = {'c1': ['J', 'A', 'B'], 'key': [25, 30, 35]} df1 = pd.DataFrame(data1) data2 = {'c2': ['A', 'B', 'C'], 'key': [&quot;25&quot;,&quot;30&quot;,&quot;36&quot;]} df2 = pd.DataFrame(data2, dtype=&quot;O&quot;) df1.key = df1.key.astype(&quot;O&quot;) print(df1.merge(df2, on = &quot;key&quot;)) output: Empty DataFrame Columns: [c1, key, c2] Index: [] </code></pre> <p>Why is pandas failing in this merge? I can convert the column to string <code>dtype</code> as follows and then back to <code>object</code> and it works:</p> <pre><code>df1.key = df1.key.astype(str).astype(&quot;O&quot;) </code></pre> <p>Now the merge is okay and finds the matches. How should I understand this behavior?</p>
<python><pandas><dataframe><numpy>
2023-07-17 08:43:30
1
5,871
figs_and_nuts
76,702,709
6,220,759
Why is exporting a query result via SQLite command line shell so slow?
<p>To export the result of a query (~45 million records) to a CSV file I used the command line shell:</p> <pre><code>$ sqlite3 db.db3 &gt; .headers on &gt; .mode csv &gt; .once result.csv &gt; select ..... </code></pre> <p>This took about 9 hours to run. I then used Python:</p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connect('db.db3') df = pd.read_sql(query, conn) df.to_csv('output.csv') </code></pre> <p>This took about 20 minutes. I understand why Python might be a little bit faster but did not expect such a huge difference. Why is the SQLite command line shell so slow?</p>
<python><pandas><performance><sqlite><export>
2023-07-17 08:32:54
1
11,757
Josh Friedlander
76,702,630
14,082,033
Error during training: layout failed: INVALID_ARGUMENT: Size of values 0 does not match size of permutation 4
<p>I am training a segmentation model using TensorFlow, and I encountered an error during the training process. After approximately 6 seconds, the training stopped with the following error message:</p> <pre><code>Epoch 1/100 2023-07-17 08:14:20.618828: E tensorflow/core/grappler/optimizers/meta_optimizer.cc:954] layout failed: INVALID_ARGUMENT: Size of values 0 does not match size of permutation 4 @ fanin shape inmodel_3/dropout_15/dropout/SelectV2-2-TransposeNHWCToNCHW-LayoutOptimizer 8278/8278 [==============================] - 6s 198us/step - loss: 2.1831 - accuracy: 0.8421 - val_loss: 2.2880 - val_accuracy: 0.8349 </code></pre> <p>I am using a custom data generator (<code>DataGen</code>) to load and preprocess the input images and masks. The error seems to be related to the layout of the model, particularly the <code>dropout</code> layer. I'm not sure why the sizes of the values do not match the permutation size. I think it might be related to Data Generator.</p> <p>I have included the relevant code snippets below:</p> <pre class="lang-py prettyprint-override"><code># Data generator class DataGen(tf.keras.utils.Sequence): def __init__(self, path_input, path_mask, class_name='person', batch_size=8, image_size=128): self.ids = os.listdir(path_mask) self.path_input = path_input self.path_mask = path_mask self.class_name = class_name self.batch_size = batch_size self.image_size = image_size self.on_epoch_end() def __load__(self, id_name): image_path = os.path.join(self.path_input, id_name) mask_path = os.path.join(self.path_mask, id_name) image = cv2.imread(image_path, 1) # 1 specifies RGB format image = cv2.resize(image, (self.image_size, self.image_size)) # resizing before inserting into the network mask = cv2.imread(mask_path, -1) mask = cv2.resize(mask, (self.image_size, self.image_size)) mask = mask.reshape((self.image_size, self.image_size, 1)) # normalize image image = image / 255.0 mask = mask / 255.0 return image, mask def __getitem__(self, index): id_name = self.ids[index] image, mask = self.__load__(id_name) if image is not None and mask is not None: images = np.expand_dims(image, axis=0) masks = np.expand_dims(mask, axis=0) else: images = np.empty((self.image_size, self.image_size, 3)) masks = np.empty((self.image_size, self.image_size, 1)) return images, masks def on_epoch_end(self): pass def __len__(self): return len(self.ids) # Configure model image_size = 128 epochs = 100 batch_size = 10 # Create data generators train_gen = DataGen(path_input=&quot;/kaggle/input/coco-2014-dataset-for-yolov3/coco2014/images/train2014&quot;, path_mask=&quot;/kaggle/working/mask_train_2014&quot;, batch_size=batch_size, image_size=image_size) val_gen = DataGen(path_input=&quot;/kaggle/input/coco-2014-dataset-for-yolov3/coco2014/images/val2014&quot;, path_mask=&quot;/kaggle/working/mask_val_2014&quot;, batch_size=batch_size, image_size=image_size) # Define model architecture inputs = Input(shape=(128, 128, 3)) # ... # Compile and train the model optimizer = tf.keras.optimizers.Adam(lr=1e-4) model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) model.fit(train_gen, validation_data=val_gen, steps_per_epoch=train_steps, epochs=epochs) </code></pre> <p>Any insights or suggestions on how to resolve this issue would be greatly appreciated.</p> <p>I am using coco2014 dataset. tf version '2.12.0'</p>
<python><tensorflow><keras><deep-learning>
2023-07-17 08:19:56
1
331
Arman Asgharpoor
76,702,574
726,730
Python - PyQt5 style checkable QGroupBox (Fusion) like WindowsVista
<p>Python code:</p> <pre><code># -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\custom_qgroubox.ui' # # Created by: PyQt5 UI code generator 5.15.9 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(&quot;MainWindow&quot;) MainWindow.resize(474, 223) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName(&quot;centralwidget&quot;) self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName(&quot;gridLayout_2&quot;) self.groupBox = QtWidgets.QGroupBox(self.centralwidget) self.groupBox.setStyleSheet(&quot;QGroupBox{\n&quot; &quot; border:1px solid #dadada;\n&quot; &quot; font-size:50px;\n&quot; &quot; margin-top:26px;\n&quot; &quot; padding-top:35px;\n&quot; &quot;}\n&quot; &quot;\n&quot; &quot;QGroupBox::title{\n&quot; &quot; subcontrol-origin:margin;\n&quot; &quot; subcontrol-position: top left;\n&quot; &quot; background:green;\n&quot; &quot; left:10px;\n&quot; &quot; top:0px;\n&quot; &quot; padding:0px;\n&quot; &quot; spacing:0px;\n&quot; &quot;}&quot;) self.groupBox.setCheckable(True) self.groupBox.setObjectName(&quot;groupBox&quot;) self.gridLayout = QtWidgets.QGridLayout(self.groupBox) self.gridLayout.setObjectName(&quot;gridLayout&quot;) self.pushButton = QtWidgets.QPushButton(self.groupBox) self.pushButton.setObjectName(&quot;pushButton&quot;) self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1) self.pushButton_2 = QtWidgets.QPushButton(self.groupBox) self.pushButton_2.setObjectName(&quot;pushButton_2&quot;) self.gridLayout.addWidget(self.pushButton_2, 1, 0, 1, 1) self.pushButton_3 = QtWidgets.QPushButton(self.groupBox) self.pushButton_3.setObjectName(&quot;pushButton_3&quot;) self.gridLayout.addWidget(self.pushButton_3, 2, 0, 1, 1) self.gridLayout_2.addWidget(self.groupBox, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 474, 22)) self.menubar.setObjectName(&quot;menubar&quot;) MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName(&quot;statusbar&quot;) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate(&quot;MainWindow&quot;, &quot;MainWindow&quot;)) self.groupBox.setTitle(_translate(&quot;MainWindow&quot;, &quot;GroupBox&quot;)) self.pushButton.setText(_translate(&quot;MainWindow&quot;, &quot;PushButton&quot;)) self.pushButton_2.setText(_translate(&quot;MainWindow&quot;, &quot;PushButton&quot;)) self.pushButton_3.setText(_translate(&quot;MainWindow&quot;, &quot;PushButton&quot;)) if __name__ == &quot;__main__&quot;: import sys app = QtWidgets.QApplication(sys.argv) app.setStyle(&quot;Fusion&quot;) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre> <p>Output:</p> <p><a href="https://i.sstatic.net/M9IcL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/M9IcL.png" alt="enter image description here" /></a></p> <p>In the green area i want to control (set/get):</p> <ol> <li>The space between the indicator and the groupbox title</li> <li>The space between the groupbox title and the top of green area</li> <li>The space between the right side of groupbox title and the end of right side of green area.</li> </ol> <p>For 1. i want it to be 10px, for 2. i want it to be 0px and for 3. i also want it to be 0px.</p> <p>Is that possible?</p> <p>Thanks.</p>
<python><css><pyqt5><qtstylesheets><qgroupbox>
2023-07-17 08:11:24
1
2,427
Chris P
76,702,453
1,153,290
Django 4 backport old Oracle 12 support
<p>Django 4.0 release notes <a href="https://docs.djangoproject.com/en/4.2/releases/4.0/#dropped-support-for-oracle-12-2-and-18c" rel="nofollow noreferrer">https://docs.djangoproject.com/en/4.2/releases/4.0/#dropped-support-for-oracle-12-2-and-18c</a></p> <p>says:</p> <blockquote> <p>Dropped support for Oracle 12.2 and 18c¶</p> <p>Upstream support for Oracle 12.2 ends in March 2022 and for Oracle 18c it ends in June 2021. Django 3.2 will be supported until April 2024. Django 4.0 officially supports Oracle 19c.</p> </blockquote> <p>So, what if I will use this simple backend for continue to use oracle 12 as secondary data sourse <strong>just for select</strong> from it, is it may cause any problems?</p> <pre><code>from django.db.backends.oracle.base import DatabaseWrapper as DatabaseWrapperOracle from django.db.utils import NotSupportedError class DatabaseWrapper(DatabaseWrapperOracle): def check_database_version_supported(self): try: super().check_database_version_supported() except NotSupportedError as e: pass # Oracle 19 or later is required (found 12.1.0.2.0). </code></pre> <p>Please share your experience</p> <p>*DatabaseWrapper seems works fine</p>
<python><django><oracle-database>
2023-07-17 07:53:28
1
6,840
Vladimir
76,702,391
5,269,892
Transferring variables between python and python or shell scripts
<p>From a main python script, here <code>main.py</code>, I would like to call multiple subscripts, which are either python scripts themselves (here <code>sub1.py</code> for simplicity) or bash/shell scripts (here <code>sub2.sh</code> for simplicity; these are called via <code>subprocess.Popen()</code>). The subscripts need several variables from <code>main.py</code>; and conversely <code>main.py</code> may need variables set in the subscripts. Therefore variables need to be transferred between python-python (<code>main.py</code> &lt;--&gt; <code>sub1.py</code>) and python-shell (<code>main.py</code> &lt;--&gt; <code>sub2.sh</code>).</p> <p>Some ways I know:</p> <ul> <li><code>main.py</code> --&gt; <code>sub1.py</code>: call <code>sub1.py</code> from <code>main.py</code> via <code>os.system()</code> or <code>subprocess.Popen()</code>, pass variables as script arguments, retrieve from e.g. <code>sys.argv[1]</code> in <code>sub1.py</code></li> <li><code>main.py</code> --&gt; <code>sub1.py</code>: import <code>sub1.py</code> into <code>main.py</code>; variables from <code>main.py</code> must be set to <code>sub1.py</code> namespace, else not recognized by <code>sub1.py</code>; if there's non-function/-class code in <code>sub1.py</code> (i.e. &quot;global&quot; script code, is it executed properly as well)?</li> <li><code>main.py</code> --&gt; <code>sub2.sh</code>: call <code>sub2.sh</code> from <code>main.py</code> via <code>os.system()</code> or <code>subprocess.Popen()</code>, pass variables as script arguments, retrieve from e.g. <code>$1</code> in <code>sub2.sh</code></li> <li>all directions / script types: store variables in some file from one script in whichever format (e.g. .txt, .dat, .pickle (for python-python transfer)), read variables from file in the other script</li> <li>all directions / script types: store variables as environment variables from one script (in the <code>os.environ[]</code> dictionary), extract from there as needed within the other script</li> </ul> <p><strong>Question: What is the <em>most convenient</em> method to transfer variables (share info) between python and python or between python and shell scripts?</strong></p> <p>Background of the question: <code>main.py</code> is a python translation of a previous shell script <code>main.sh</code>. In <code>main.sh</code>, any subscript <code>subX.sh</code> (there were fewer python scripts at that point) was called via <code>source subX.sh</code>, such that variables from <code>main.sh</code> and <code>subX.sh</code> were always known to the respective other scripts (as <code>source</code> runs the subscript in the same shell).</p> <p>The python version used is <code>2.7.18</code> (compatibility reasons; I am not allowed to install a newer interpreter).</p>
<python><bash><shell><global-variables>
2023-07-17 07:43:24
1
1,314
silence_of_the_lambdas
76,702,390
10,666,991
CPU Out of memory when training a model with pytorch lightning
<p>I am trying to train a BERT model on my data using the <code>Trainer</code> class from <code>pytorch-lightning</code>. However, I encountered an out-of-memory exception in the <strong>CPU memory</strong>.</p> <p>Here is the code:</p> <pre><code>from transformers.data.data_collator import DataCollatorForLanguageModeling from datasets import load_dataset dataset = load_dataset('text', data_path) # The dataset is only 33GB, while my GPU has 350GB of RAM. class BertDataModule(pl.LightningDataModule): def __init__(self, dataset, train_split, batch_size, data_collator): super().__init__() self.train_dataset = None self.dataset = dataset self.collator = data_collator self.batch_size = batch_size self.train_split = train_split def train_dataloader(self): return torch.utils.data.DataLoader(self.train_dataset, batch_size=self.batch_size, collate_fn=self.collator, num_workers=30) # I defined the similar methods for val_dataloader, test_dataloader, and predict_dataloader. bert_collator = DataCollatorForLanguageModeling(tokenizer=bert_tokenizer) bert_data_module = BertDataModule(dataset=my_dataset['train'], train_split=0.98, batch_size=32, data_collator=bert_collator) bert_model = BertModel(...) trainer = pl.Trainer(devices=1, max_epochs=50, logger=comment_logger, accelerator='gpu', precision=16, val_check_interval=50000, callbacks=[checkpoint_callbacks]) trainer.fit(bert_model, datamodule=bert_data_module) # Crash due to CPU OOM here </code></pre> <p>My code crashed due to an out-of-memory (OOM) error, even though my data is only 33GB and my CPU memory in the OpenShift pod is 350GB.</p> <p>Do you have any idea what could be causing the memory of the CPU to continue increasing during training?</p> <p>Thank you very much.</p>
<python><pytorch><bert-language-model><pytorch-lightning><huggingface-datasets>
2023-07-17 07:43:11
1
781
Ofir
76,702,263
9,636,225
making menu and sub-menu python
<p>I'm learning to make menus in python using the statemachine module,</p> <p>here is the code i ran and it works fine</p> <pre><code>from statemachine import State, StateMachine class MenuStateMachine(StateMachine): # States main_menu = State('Main Menu', initial=True) menu1 = State('Option1') menu2 = State('Option2') submenu1 = State('Sub-Menu1') # Transitions select_menu1 = main_menu.to(menu1) select_menu2 = main_menu.to(menu2) select_submenu1 = menu1.to(submenu1) back_to_main_menu = menu1.to(main_menu) | menu2.to(main_menu) back_to_menu1 = submenu1.to(menu1) def on_main_menu(self): print('=== Main Menu ===') print('[1] Option1') print('[2] Option2') print('[3] Exit') def on_menu1(self): print('=== Option1 Menu ===') print('[1] SubOption1') print('[2] SubOption2') print('[3] SubOption3') print('[4] Previous Menu') def on_submenu1(self): print('=== SubOption1 Menu ===') print('[1] Act1') print('[2] Act2') print('[3] Act3') print('[4] Previous Menu') def on_menu2(self): print('=== Option2 Menu ===') print('[1] Previous Menu') # Create an instance of the MenuStateMachine class menu = MenuStateMachine() # Start the menu state machine while True: menu.on_main_menu() choice = input('Enter Choice: ') if choice == '1': menu.select_menu1() while menu.current_state.id == 'menu1': menu.on_menu1() menu_choice = input('Enter Choice : ') if menu_choice == '1': menu.select_submenu1() while menu.current_state.id == 'submenu1': menu.on_submenu1() submenu_choice = input('Enter Choice : ') if submenu_choice == '1': print('Do Something Here') break elif submenu_choice == '2': print('Do Something Here') break elif submenu_choice == '3': print('Do Something Here') break elif submenu_choice == '4': menu.back_to_menu1() else: print('Invalid choice. Please try again.') elif menu_choice == '4': menu.back_to_main_menu() elif menu_choice in ['2','3']: print('There is no menu yet, please choose another') else: print('Invalid choice. Please try again.') elif choice == '2': menu.select_menu2() menu.on_menu2() menu_choice = input('Enter Choice : ') if menu_choice == '1': menu.back_to_main_menu() else: print('Invalid choice. Please try again.') elif choice == '3': print('=== Exit ===') exit() else: print(&quot;Invalid choice. Please try again.&quot;) </code></pre> <p>but I imagine that my code can be improved to be better, I think my code is not efficient especially the use of if and while. If there are a lot of sub menus or sub-sub menus will look messy, and I think this can be improved even better, any suggestions to improve my code?</p>
<python><if-statement><state-machine>
2023-07-17 07:23:32
0
307
ExHunter
76,702,207
15,320,579
Two level sorting in a nested tuple of nested lists in Python
<p>I have a deeply nested tuple of nested lists as follows:</p> <pre><code>ip = (array([[[ 50, 73]], [[ 50, 107]], [[ 55, 108]], [[ 55, 121]], [[978, 87]], [[977, 86]], [[977, 73]]], dtype=int32), array([[[ 669, 3]], [[ 668, 4]], [[ 667, 4]], [[1033, 71]], [[1035, 69]], [[1035, 4]], [[ 848, 4]], [[ 847, 3]], [[ 813, 3]], [[ 718, 4]], [[ 717, 3]]], dtype=int32), array([[[ 17, 3]], [[ 16, 4]], [[ 0, 4]], [[ 0, 49]], [[197, 49]], [[197, 8]], [[ 84, 4]], [[ 83, 3]]], dtype=int32)) </code></pre> <p>The length of the main tuple in above example is 3. I want to <strong>perform a 2 level sorting</strong> on the above structure. First I want to <strong>sort all the 3 elements in the main list in increasing order based on the first value of nested list</strong>. So in the above case the <strong>third element</strong> will come first as it has the <strong>lowest value</strong> of the first element i.e. <code>0</code>. Second should be the <strong>first element</strong> as it has the <strong>second lowest value</strong> of <code>50</code>and last should be the <strong>third element</strong> as it has the <strong>third lowest value</strong> of <code>1035</code>. The output of the first level sorting should be:</p> <pre><code>op = (array([[[ 17, 3]], [[ 16, 4]], [[ 0, 4]], [[ 0, 49]], [[197, 49]], [[197, 8]], [[ 84, 4]], [[ 83, 3]]], dtype=int32), array([[[ 50, 73]], [[ 50, 107]], [[ 55, 108]], [[ 55, 121]], [[978, 87]], [[977, 86]], [[977, 73]]], dtype=int32), array([[[ 669, 3]], [[ 668, 4]], [[ 667, 4]], [[1033, 71]], [[1035, 69]], [[1035, 4]], [[ 848, 4]], [[ 847, 3]], [[ 813, 3]], [[ 718, 4]], [[ 717, 3]]], dtype=int32), ) </code></pre> <p>Now I want to perform the same sorting again on the above <code>op</code> but instead of the first value of the nested list I want to <strong>sort based on the second value</strong> of the nested list. So now the final output would be as follows:</p> <pre><code>final_op = (array([[[ 17, 3]], [[ 16, 4]], [[ 0, 4]], [[ 0, 49]], [[197, 49]], [[197, 8]], [[ 84, 4]], [[ 83, 3]]], dtype=int32), array([[[ 669, 3]], [[ 668, 4]], [[ 667, 4]], [[1033, 71]], [[1035, 69]], [[1035, 4]], [[ 848, 4]], [[ 847, 3]], [[ 813, 3]], [[ 718, 4]], [[ 717, 3]]], dtype=int32), array([[[ 50, 73]], [[ 50, 107]], [[ 55, 108]], [[ 55, 121]], [[978, 87]], [[977, 86]], [[977, 73]]], dtype=int32) ) </code></pre> <p>Any help is appreciated!</p> <p>Thanks in advance!</p>
<python><python-3.x><list><sorting><tuples>
2023-07-17 07:13:06
1
787
spectre
76,702,040
1,142,881
Can I chain where clauses conditionally?
<p>I'm using Peewee as ORM extensively and within my DAO API layer I need to conditionally make a query narrower e.g.</p> <pre><code>query = UserModel.select().where(UserModel.last_name == last_name) if first_name is not None: query = query.where(UserModel.first_name == first_name) # ... more conditions then df = pd.DataFrame(query.dicts()) </code></pre> <p>is this the most idiomatic way to conditionally make the queries narrower in Peewee or is there another way? Are there any pros and cons of doing this?</p>
<python><orm><peewee>
2023-07-17 06:44:38
2
14,469
SkyWalker
76,701,955
4,260,959
How can I draw a contour for a piecewise function with pyplot.imshow
<p>My function is <code>z = (x - 1) **10 + 5*(x - 1)**5*(y - 1)**5 + (y - 1)**10</code>. However, the contour can't show clear about negative value because of large positive value.</p> <p>So I just need to show positive value by logarithm (<code>np.log(1 + 0)</code> if <code>z &lt; 0</code>), but keep negative as origin.</p> <p>How can I do this with pyplot.imshow?</p> <p>This code doesn't work:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def z(x, y): z0 = (x - 1) **10 + 5*(x - 1)**5*(y - 1)**5 + (y - 1)**10 # ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() return z0 if z0 &lt; 0 else np.log(1 + z0) def main(): x, y = np.linspace(0.0, 3.0, 300), np.linspace(0.0, 3.0, 300) X, Y = np.meshgrid(x, y) plt.imshow(z(X, Y), origin='lower', extent = [0, 3, 0, 3], cmap=plt.cm.hsv) plt.colorbar() plt.show() if __name__ == '__main__': main() </code></pre>
<python><matplotlib><imshow>
2023-07-17 06:25:45
1
2,573
auntyellow
76,701,905
3,897,012
How to pass selenium webdriver instance to another class in Python
<p>I am creating a few classes for some automated tests. I've created a LoginTest class that logs into a website. Once the LoginTest class is finished testing I would like to pass the logged in instance to the next class. How should I go about doing that?</p> <p>Here is my code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from dotenv import load_dotenv import os import unittest import time class LoginTest(unittest.TestCase): @classmethod def setUpClass(self): # load env load_dotenv() # Initialize Chrome driver self.driver = webdriver.Chrome() # Set implicit wait to 10 seconds self.driver.implicitly_wait(10) def test_login(self): # Get email and password from environment variables email = os.getenv(&quot;EMAIL&quot;) password = os.getenv(&quot;PASSWORD&quot;) driver = self.driver # Go to login screen driver.get(&quot;https://website.com/login&quot;) # Locate the email and password input fields and enter the credentials email_field = driver.find_element(By.ID, &quot;input_email&quot;) email_field.send_keys(email) password_field = driver.find_element(By.ID, &quot;input_password&quot;) password_field.send_keys(password) # Click the login button driver.find_element(By.NAME, &quot;form.submitted&quot;).click() watchlist_title = EC.title_contains('Login | Dashboard') # test this if it works # probably should just check if the url is correct self.assertIsNotNone(watchlist_title, &quot;Login failed. Home page title is not found.&quot;) @classmethod def tearDownClass(self): # Close the browser self.driver.quit() class DataTableTest(LoginTest): def test_table_entries(self): driver = self.driver # Continue using the logged-in session for further test steps driver.get(&quot;https://datatable.com&quot;) class ChartTest(LoginTest): def test_chart(self): driver = self.driver # Continue using the logged-in session for further test steps driver.get(&quot;https://chart.com&quot;) if __name__ == &quot;__main__&quot;: unittest.main() </code></pre>
<python><python-3.x><selenium-webdriver>
2023-07-17 06:16:37
0
686
Ryan113
76,701,863
241,515
Iterating through a pair of DataFrames, modifying one of the two at each iteration and feeding back the results
<p>I am trying to reimplement a (rather complex) algorithm from R in Python. The algorithm operates on two dataframes (<code>short</code> and <code>long</code> for simplicity) which have this basic structure:</p> <pre><code>index chrom chr_arm start end ratio_median size 0 chr1 p 1 100 0.789 100 </code></pre> <p>The structures of <code>short</code> and <code>long</code> are identical, they differ from the range in the <code>size</code> column (10K-3M for <code>short</code> and &gt; 3M for <code>long</code>). They are also not identical in length. The algorithm iteratively compares <code>short</code> with <code>long</code> in different ways and then performs some calculations which <strong>alter <code>long</code> in-place</strong>, so that at every iteration the calculations are made with an updated <code>long</code>.</p> <p>EDIT: Someone requested a more detailed description, and I will provide one. This approach needs to merge part the data from <code>short</code> into <code>long</code> basing on whether they are above or below a certain threshold (defined as <code>threshold</code>).</p> <p>There is also an additional data frame called <code>bins</code>, which are the raw data from where <code>short</code> and <code>long</code> were derived, with this structrure:</p> <pre><code>chrom chr_arm start end ratio ratio_median size 1 p 1 5 0.3 0.7 5 1 p 1 5 0.9 0.7 5 </code></pre> <p>The algorithm is as follows:</p> <pre><code>1. Iterate through the lines (indices) of short 2. For each line in short, iterate through the lines of long 3. For each line of long, do a comparison on coordinates between short and long: if short is fully upstream (short end &lt; long start) of long, the check is successful 4. If the check is successful: I. measure if the absolute value of the difference between short's ratio_median and the one in long II. if the difference is below threshold: a. construct a new line (segment) by using the start from short and the end of long b. Measure overlaps between the new line and bins, and recalculate a new ratio_median by doing a median of the overlapping ratios from bins c. Replace the current line in long with a new line containing these data III. If the difference is above threshold: a. Append the current line from short immediately after the current one of long 6. Continue until all lines of short have been used </code></pre> <p>This works more or less in R, but at least in Pandas, modifying DataFrames in-place during iteration is not a good practice (and for good reason). I don't want to replicate the exact way it is done in R (in reality, it's a 600-line <code>while</code> loop with multiple nested <code>if</code>s) so I tried to make something simpler and more Pythonic.</p> <p>My first implementation did the logic without updating the DataFrame in place:</p> <pre><code>def adjust_segments(short: pd.DataFrame, long: pd.DataFrame) -&gt; pd.DataFrame: dest_long = long.copy() for gid, group in short.groupby([&quot;chrom&quot;, &quot;chr_arm&quot;], sort=False): # To reduce the number of loops for rowid, row in group.iterrows(): for long_id, long_row in long.iterrows(): if (row.end &lt; long_row.start): # Simplified check here, there are several if abs(row.ratio_median - long_row.ratio_median) &lt; threshold: new_line = recompute_ratio(row, long_row, bins) dest_long.loc[long_id, :] = new_line else: # Omitted all checks to see if it's at the end, etc. dest_long.loc[long_id + 1, :] = new_line </code></pre> <p>This &quot;works&quot;, but it doesn't feed back the changes on every iteration (it was made like this on purpose before I noticed that the R code - I didn't write it - did things differently).</p> <p>As I have a numerical <code>index</code> column outside the DataFrame index I thought of using that to modify the DataFrame in-place without iterating, but as rows are appended (if checks are not successful) this wouldn't work well with &quot;feeding back&quot; the changes at every iteration.</p> <p>What approach could be done in a case like this? I really don't want to copy the R approach, as I said, as it would lead to an unmaintainable mess.</p>
<python><pandas><dataframe><algorithm><iteration>
2023-07-17 06:06:45
0
4,973
Einar
76,701,681
1,990,924
No such file or directory with import
<p>I'm a beginner with Python and I'm not able to run anything with installed modules. For example I have very simple script</p> <pre><code>#!/usr/bin/env python3 import subprocess import killport subprocess.run([&quot;killport&quot;, &quot;1111&quot;]) </code></pre> <p>but the result is</p> <pre><code>Traceback (most recent call last): File &quot;/Users/jklimcik/bin/infra-scripts/test.py&quot;, line 5, in &lt;module&gt; subprocess.run([&quot;killport&quot;, &quot;1111&quot;]) File &quot;/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py&quot;, line 505, in run with Popen(*popenargs, **kwargs) as process: File &quot;/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py&quot;, line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File &quot;/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py&quot;, line 1821, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'killport' </code></pre> <p>I have installed this module:</p> <pre><code>$ python3 -m pip show killport Name: killport Version: 1.2.0 Summary: Home-page: https://github.com/dannysepler/killport Author: Danny Sepler Author-email: dannysepler@gmail.com License: MIT Location: /Users/jklimcik/Library/Python/3.9/lib/python/site-packages Requires: psutil Required-by: </code></pre> <p>I'm using PIP. I've already tried to completely uninstall and reinstall it again.</p> <pre><code>pip3 --version pip 23.2 from /Users/jklimcik/Library/Python/3.9/lib/python/site-packages/pip (python 3.9) </code></pre> <p>What's wrong or what am I missing? I'm using Python 3.9.6 and running on MacOS, Apple M1</p>
<python><python-3.x><pip>
2023-07-17 05:27:08
2
4,888
Jaroslav Klimčík
76,701,594
8,726,488
Python Dict - How to change Key name based on another dict
<p>I have Python dict with keys and values. I want to rename/mapping the dict key based on another dict keys and values. For example</p> <pre><code>data = {'a': 1, 'b': 2, 'c': 3, 'd': 4} </code></pre> <p>my source data and mapping data is below.</p> <pre><code>key_changes ={'a': 'a1', 'b': 'b1'} </code></pre> <p>expected output is</p> <pre><code>{'a1': 1, 'b1': 2, 'c': 3, 'd': 4} </code></pre> <p>I tried to solve this issue using <strong>for comprehension</strong>. But I am getting Invalid syntax.</p> <p>I have tried below solution</p> <pre><code>res = { key_chages[_key]:_value else _key:_value for _key,_value in data.items() if _key in key_chages } </code></pre>
<python><python-3.x><dictionary>
2023-07-17 04:58:54
2
3,058
Learn Hadoop
76,701,561
1,477,364
How to get detailed error messages for invalid OR-Tools CP-SAT models?
<p>I'm trying to recreate the Google OR-Tools <a href="https://developers.google.com/optimization/lp/stigler_diet" rel="nofollow noreferrer">Stigler Diet</a> example using the CP-SAT solver instead of the linear solver, and it results in a status of <code>MODEL_INVALID</code>. I don't know how to get detailed error messages or get any additional details as to why the model is invalid.</p> <p>Looking into the Python source code, a code comment next to the definition of <code>MODEL_INVALID</code> says &quot;The given CpModelProto didn't pass the validation step. You can get a detailed error by calling <code>ValidateCpModel(model_proto)</code>.&quot; But, I can't figure out how to access <code>ValidateCpModel()</code> and it's not referenced in <a href="https://developers.google.com/optimization/reference/python/sat/python/cp_model" rel="nofollow noreferrer">the docs</a> or any examples in the or-tools repo.</p> <p>For reference, here's the program I'm trying to run:</p> <pre><code>from ortools.sat.python import cp_model import sys # Minimum and maximum values for each nutrient nutritional_requirements = [ [1, 2], # Vitamin A [1, 2], # Vitamin B [1, 2], # Vitamin C ] # Nutritional value for each food foods = [ # Vitamins # A B C [1, 0, 0], # Food A [0, 1, 0], # Food B [0, 0, 1], # Food C ] model = cp_model.CpModel() quantity_of_food = [model.NewIntVar(0, sys.maxsize, str(i)) for i in range(len(foods))] for i, nutrient in enumerate(nutritional_requirements): model.Add( sum([food[i] * quantity_of_food[i] for food in foods]) &gt;= nutrient[0] ) model.Add( sum([food[i] * quantity_of_food[i] for food in foods]) &lt; nutrient[1] ) model.Minimize(sum(quantity_of_food)) solver = cp_model.CpSolver() status = solver.Solve(model) outcomes = [ &quot;UNKNOWN&quot;, &quot;MODEL_INVALID&quot;, &quot;FEASIBLE&quot;, &quot;INFEASIBLE&quot;, &quot;OPTIMAL&quot;, ] print(outcomes[status]) # Prints &quot;MODEL_INVALID&quot; </code></pre> <p>This program seems pretty simple to me. How do I find a detailed error message explaining why the model is invalid?</p>
<python><solver><or-tools><cp-sat>
2023-07-17 04:49:43
1
2,048
Travis
76,701,427
840,352
Reading AWS environment variables using python
<p>I've configured AWS CLI in my laptop. I'm passing the region details etc either at prompt or baked as part of the code. I'm able to connect to aws through python and read the items. But when trying to develop a class so that it get the environment variables like AWS_REGION, AWS_SECRET_ACCESS_KEY etc all that is returned is null. Is there anything i'm missing apart from configuring the aws cli in my laptop. <strong>Take note while installing it in my (windows) laptop, at the prompt i enter the AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY etc.</strong></p> <p>Thanks</p>
<python><amazon-web-services>
2023-07-17 04:06:31
1
654
luckyluke
76,701,351
23,512,643
HTML/XML: Understanding How "Scroll Bars" Work
<p>I am working with the R programming language and trying to learn about how to use Selenium to interact with webpages.</p> <p><strong>For example, using Google Maps - I am trying to find the name, address and longitude/latitude of all Pizza shops around a certain area.</strong> As I understand, this would involve entering the location you are interested in, clicking the &quot;nearby&quot; button, entering what you are looking for (e.g. &quot;pizza&quot;), scrolling all the way to the bottom to make sure all pizza shops are loaded - and then copying the names, address and longitude/latitudes of all pizza locations.</p> <p>I have been self-teaching myself how to use Selenium in R and have been able to solve parts of this problem myself. Here is what I have done so far:</p> <p><strong>Part 1:</strong> Searching for an address (e.g. Statue of Liberty, New York, USA) and returning a longitude/latitude :</p> <pre><code>library(RSelenium) library(wdman) library(netstat) selenium() seleium_object &lt;- selenium(retcommand = T, check = F) remote_driver &lt;- rsDriver(browser = &quot;chrome&quot;, chromever = &quot;114.0.5735.90&quot;, verbose = F, port = free_port()) remDr&lt;- remote_driver$client remDr$navigate(&quot;https://www.google.com/maps&quot;) search_box &lt;- remDr$findElement(using = 'css selector', &quot;#searchboxinput&quot;) search_box$sendKeysToElement(list(&quot;Statue of Liberty&quot;, key = &quot;enter&quot;)) Sys.sleep(5) url &lt;- remDr$getCurrentUrl()[[1]] long_lat &lt;- gsub(&quot;.*@(-?[0-9.]+),(-?[0-9.]+),.*&quot;, &quot;\\1,\\2&quot;, url) long_lat &lt;- unlist(strsplit(long_lat, &quot;,&quot;)) &gt; long_lat [1] &quot;40.7269409&quot; &quot;-74.0906116&quot; </code></pre> <p><strong>Part 2:</strong> Searching for all Pizza shops around a certain location:</p> <pre><code>library(RSelenium) library(wdman) library(netstat) selenium() seleium_object &lt;- selenium(retcommand = T, check = F) remote_driver &lt;- rsDriver(browser = &quot;chrome&quot;, chromever = &quot;114.0.5735.90&quot;, verbose = F, port = free_port()) remDr&lt;- remote_driver$client remDr$navigate(&quot;https://www.google.com/maps&quot;) Sys.sleep(5) search_box &lt;- remDr$findElement(using = 'css selector', &quot;#searchboxinput&quot;) search_box$sendKeysToElement(list(&quot;40.7256456,-74.0909442&quot;, key = &quot;enter&quot;)) Sys.sleep(5) search_box &lt;- remDr$findElement(using = 'css selector', &quot;#searchboxinput&quot;) search_box$clearElement() search_box$sendKeysToElement(list(&quot;pizza&quot;, key = &quot;enter&quot;)) Sys.sleep(5) </code></pre> <p><strong>But from here, I do not know how to proceed.</strong> I do not know how to scroll the page all the way to the bottom to view all such results that are available - and I do not know how to start extracting the names.</p> <p>Doing some research (i.e. inspecting the HTML code), I made the following observations:</p> <ul> <li><p>The name of a restaurant location can be found in the following tags: <code>&lt;a class=&quot;hfpxzc&quot; aria-label=</code></p> </li> <li><p>The address of a restaurant location be found in the following tags: <code>&lt;div class=&quot;W4Efsd&quot;&gt;</code></p> </li> </ul> <p><strong>In the end, I would be looking for a result like this:</strong></p> <pre><code> name address longitude latitude 1 pizza land 123 fake st, city, state, zip code 45.212 -75.123 </code></pre> <p><strong>Can someone please show me how to proceed?</strong></p> <p><strong>Note:</strong> Seeing as more people likely use Selenium through Python - I am more than happy to learn how to solve this problem in Python and then try to convert the answer into R code.r</p> <p>Thanks!</p> <p><strong>References:</strong></p> <ul> <li><a href="https://medium.com/python-point/python-crawling-restaurant-data-ab395d121247" rel="nofollow noreferrer">https://medium.com/python-point/python-crawling-restaurant-data-ab395d121247</a></li> <li><a href="https://www.youtube.com/watch?v=GnpJujF9dBw" rel="nofollow noreferrer">https://www.youtube.com/watch?v=GnpJujF9dBw</a></li> <li><a href="https://www.youtube.com/watch?v=U1BrIPmhx10" rel="nofollow noreferrer">https://www.youtube.com/watch?v=U1BrIPmhx10</a></li> </ul> <p><strong>UPDATE:</strong> Some further progress with addresses</p> <pre><code>remDr$navigate(&quot;https://www.google.com/maps&quot;) Sys.sleep(5) search_box &lt;- remDr$findElement(using = 'css selector', &quot;#searchboxinput&quot;) search_box$sendKeysToElement(list(&quot;40.7256456,-74.0909442&quot;, key = &quot;enter&quot;)) Sys.sleep(5) search_box &lt;- remDr$findElement(using = 'css selector', &quot;#searchboxinput&quot;) search_box$clearElement() search_box$sendKeysToElement(list(&quot;pizza&quot;, key = &quot;enter&quot;)) Sys.sleep(5) address_elements &lt;- remDr$findElements(using = 'css selector', '.W4Efsd') addresses &lt;- lapply(address_elements, function(x) x$getElementText()[[1]]) result &lt;- data.frame(name = unlist(names), address = unlist(addresses)) </code></pre>
<python><html><r><xml><selenium-webdriver>
2023-07-17 03:39:03
2
6,799
stats_noob
76,701,326
8,726,488
Python for comprehension with dict keys and values in else clause
<p>Attached is my sample in below. Aim's want to update dict based on key which is present in another list. if key is present in the list update value +1 otherwise value -1. I tried with for comprehension approach and getting syntax error. through simple for loop , will solve the problem. but i am looking for approach with for comprehension.</p> <p><a href="https://i.sstatic.net/QsqGK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QsqGK.png" alt="enter image description here" /></a></p>
<python><python-3.x><dictionary><for-loop><for-comprehension>
2023-07-17 03:28:03
1
3,058
Learn Hadoop
76,701,248
3,099,733
Can I annotate a member field as read only or immutable in Python?
<p>I am not looking for a &quot;physically&quot; immutable member field in Python as I know it is impossible, but just a type annotation to tell type checker that this field should not be re-assign a new value.</p> <p>For example,</p> <pre class="lang-py prettyprint-override"><code> class A: def __init__(self, x: int): self.x: Annotated[int, Immutable] = x def do_something(self): self.x = 1 # type checker should be able to report error </code></pre> <p>Can I do this in Python? Or are there any better solutions?</p>
<python><dependency-injection><immutability><python-typing>
2023-07-17 02:54:05
2
1,959
link89
76,701,199
2,981,639
Creating a Huggingface Dataset with categorical class labels from a file
<p>Most (if not all) of the huggingface <code>datasets</code> examples I've found that use <code>ClassLabel</code> hard-code the list of labels, i.e. from <a href="https://huggingface.co/datasets/ag_news/blob/main/ag_news.py" rel="nofollow noreferrer">ag_news</a></p> <pre class="lang-py prettyprint-override"><code> def _info(self): return datasets.DatasetInfo( description=_DESCRIPTION, features=datasets.Features( { &quot;text&quot;: datasets.Value(&quot;string&quot;), &quot;label&quot;: datasets.features.ClassLabel(names=[&quot;World&quot;, &quot;Sports&quot;, &quot;Business&quot;, &quot;Sci/Tech&quot;]), } ), homepage=&quot;http://groups.di.unipi.it/~gulli/AG_corpus_of_news_articles.html&quot;, citation=_CITATION, task_templates=[TextClassification(text_column=&quot;text&quot;, label_column=&quot;label&quot;)], ) </code></pre> <p>I'm trying to construct a dataset which has a large number of labels, and the labels have additional metadata, i.e. say I have a labels.json file containing</p> <pre><code>{&quot;name&quot;:&quot;label_1&quot;, &quot;category&quot;:&quot;c1&quot;, &quot;reference&quot;:123} {&quot;name&quot;:&quot;label_2&quot;, &quot;category&quot;:&quot;c1&quot;, &quot;reference&quot;:456} {&quot;name&quot;:&quot;label_3&quot;, &quot;category&quot;:&quot;c2&quot;, &quot;reference&quot;:789} </code></pre> <p>(Later I want to expose the additional metadata for use at inference time but it's not relevant to this question)</p> <p>I want to read this file in order to construct the <code>DatasetInfo</code>, specifically construct the <code>names</code> array when the dataset is loaded. The issue is how do I obtain the filename - the <code>_info</code> method doesn't pass the <code>download_manager</code> which afaik is required in order to locate the local copy of the file in the cache.</p>
<python><huggingface-datasets>
2023-07-17 02:34:32
0
2,963
David Waterworth
76,701,183
13,916,049
Conditional creation of row values based on another row
<p>If the <code>days_to_last_follow_up</code> row value is equal to or more than <code>1825</code>, assign the value in the <code>survival</code> row as <code>0</code>. Otherwise, if it is less than <code>1825</code> or is <code>NA</code>, assign the <code>survival</code> row as <code>1</code>.</p> <pre><code># Long-term survival &gt;= 5 years (1825 days) # Short-term survival &lt; 5 years OR NA def survival_status(col): if col.loc[&quot;days_to_last_follow_up&quot;] &gt;= 1825: return col.loc[&quot;survival&quot;] == 0 # lts else: return col.loc[&quot;survival&quot;] == 1 # non-lts clinical.loc[&quot;survival&quot;] = clinical.apply(survival_status, axis=0) </code></pre> <p>Input:</p> <p><code>clinical.iloc[0:4,0:4]</code></p> <pre><code>pd.DataFrame({'TCGA-2K-A9WE-01': {'admin.batch_number': '398.45.0', 'age': '53', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': '207.0'}, 'TCGA-2Z-A9J1-01': {'admin.batch_number': '398.45.0', 'age': '71', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': '2298.0'}, 'TCGA-2Z-A9J3-01': {'admin.batch_number': '398.45.0', 'age': '67', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': nan}, 'TCGA-2Z-A9J6-01': {'admin.batch_number': '398.45.0', 'age': '60', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': '1731.0'}}) </code></pre> <p>Expected output:</p> <pre><code>pd.DataFrame({'TCGA-2K-A9WE-01': {'admin.batch_number': '398.45.0', 'age': '53', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': '207.0', 'survival': '1'}, 'TCGA-2Z-A9J1-01': {'admin.batch_number': '398.45.0', 'age': '71', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': '2298.0', 'survival': '0'}, 'TCGA-2Z-A9J3-01': {'admin.batch_number': '398.45.0', 'age': '67', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': nan, 'survival': '1'}, 'TCGA-2Z-A9J6-01': {'admin.batch_number': '398.45.0', 'age': '60', 'days_to_initial_pathologic_diagnosis': '0', 'days_to_last_follow_up': '1731.0', 'survival': '0'}}) </code></pre>
<python><pandas>
2023-07-17 02:26:19
1
1,545
Anon
76,701,101
3,560,202
Write huge xarray dataset physically reorganized by `MultiIndex` to disk
<p>When collapsing xarray dimensions into <code>MultiIndex</code>, merely the index is changed, leaving the underlying data as is.</p> <p>This new data organisation can then be reflected in the underlying memory the data occupies by accessing <code>.values</code>, causing the data to be computed.</p> <p>My dataset is too big, however, to be loaded into memory with <code>.values</code>. As such, I would like to write it to memory (preferably in Zarr format) by each chunk. I do not care about the underlying dimensions and only want to persist the <code>MultiIndex</code> as a 1D array.</p> <p>Zarr does not support <code>MultiIndex</code>, unfortunately. The solution proposed by the error message, namely to use <a href="https://cf-xarray.readthedocs.io/en/latest/generated/cf_xarray.encode_multi_index_as_compress.html" rel="nofollow noreferrer">cf_xarray.encode_multi_index_as_compress</a> makes the underlying dimensions reappear and it seems that when writing, the data will not be reorganised.</p> <p>How do I proceed here?</p>
<python><numpy><dask><python-xarray>
2023-07-17 01:57:13
0
1,582
Post Self
76,700,916
5,528,270
Reproduce the results of using Python's spectrogram() in C#
<p>I would like you to point out various insights from the perspective of a C# expert, a Python expert, and an EEG expert.</p> <p>I would like to get the same results using MathNet in C# as I get using <code>scipy.signal.spectrogram</code> in Python.</p> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html</a> <a href="https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm" rel="nofollow noreferrer">https://numerics.mathdotnet.com/api/MathNet.Numerics.IntegralTransforms/Fourier.htm</a></p> <p>I got to the point where I could get pretty close data. I multiply the C# results by 1.5 to get results that are about equal to the Python results. But I do not want to use a magic number. I want to find out why and fix my code. Could you please point out the errors in my code?</p> <p>The fact that they match by a factor of 1.5 leads me to believe I am making a mistake in multiplication or division. I moved the timing of using the correction factor for the Hamming window back and forth, which produced more different results.</p> <p>What did I do wrong?</p> <h2>Python</h2> <pre><code># Sampling rate [Hz] fs = 600.0 # FFT window length [sec]. win_sec = 3.0 # Upper frequency [Hz] fq_lim = 50 # Sampling interval [sec] dt = 1. / fs # Data length [points] n = int(fs * win_sec) # Power of 2 greater than argument calculated nfft = 2 ** math.ceil(math.log2(n)) # Frequency signal interval [/sec]. df_f = 1.0 / (nfft * dt) # Spectrogram calculation Frequency (freq) Time (t) Power spectral density PSD (μV²/Hz) calculation freq, t, spctgram = signal.spectrogram(sig, fs=fs, nperseg=n, nfft=nfft, noverlap=(win_sec-1)*fs, window='hamming', mode='psd', return_onesided=True) </code></pre> <h2>C#</h2> <pre><code> public Dictionary&lt;string, float&gt; Analyze(List&lt;float&gt; brainwaveData) { // power of 2 greater than the sampling number var fftWindowSize = (int)Math.Pow(2, Math.Ceiling(Math.Log(Const.NumOfSampling, 2))); // Fill with zeros until sampling number is next power of 2 while (brainwaveData.Count &lt; fftWindowSize) { brainwaveData.Add(0f); } // Apply Hamming window for FFT var coefficientHammingWindow = 0.54f; double[] window = Window.HammingPeriodic(fftWindowSize); var signalWindow = brainwaveData.Select((d, i) =&gt; new Complex32((float)(d * window[i] / coefficientHammingWindow), 0)).ToArray(); // Execute FFT Fourier.Forward(signalWindow, FourierOptions.Matlab); // Power spectrum [μV²] calculation Amplitude squared var powerSpectrum = signalWindow.Select(d =&gt; (d.Real * d.Real) + (d.Imaginary * d.Imaginary)).ToArray(); // power spectrum normalization [μV²] var normalizedPowerSpectrum = powerSpectrum.Select(d =&gt; d / fftWindowSize).ToArray(); // Power spectral density [μV²/Hz] calculation var powerSpectrumDensity = normalizedPowerSpectrum.Select(d =&gt; d / Const.SamplingFrequencyHz).ToArray(); // Calculated for each EEG component Dictionary&lt;string, float&gt; result = new Dictionary&lt;string, float&gt;(); foreach (var listBand in listBands) { result.Add(listBand.BandName, calcFrequencyBandAverage(powerSpectrumDensity, Const.SamplingFrequencyHz, listBand.MinFreqHz, listBand.MaxFreqHz)); } return result; } private float calcFrequencyBandAverage(float[] spectrum, int sampleRate, double minHz, double maxHz) { // Find the index for a given frequency band (Hz) var minIndex = (int)Math.Ceiling(spectrum.Length * minHz / sampleRate); var maxIndex = (int)Math.Floor(spectrum.Length * maxHz / sampleRate); // Calculate average return spectrum.Skip(minIndex).Take(maxIndex - minIndex).Average(); } List&lt;BrainwaveFrequencyBands&gt; listBands = new List&lt;BrainwaveFrequencyBands&gt; { new BrainwaveFrequencyBands{ BandName = &quot;Delta&quot;, MinFreqHz = 1f, MaxFreqHz = 4f }, new BrainwaveFrequencyBands{ BandName = &quot;Theta&quot;, MinFreqHz = 4f, MaxFreqHz = 8f }, new BrainwaveFrequencyBands{ BandName = &quot;Alpha1&quot;, MinFreqHz = 8f, MaxFreqHz = 10f }, new BrainwaveFrequencyBands{ BandName = &quot;Alpha2&quot;, MinFreqHz = 10f, MaxFreqHz = 12f }, new BrainwaveFrequencyBands{ BandName = &quot;Beta1&quot;, MinFreqHz = 12f, MaxFreqHz = 20f }, new BrainwaveFrequencyBands{ BandName = &quot;Beta2&quot;, MinFreqHz = 20f, MaxFreqHz = 30f }, new BrainwaveFrequencyBands{ BandName = &quot;Gamma1&quot;, MinFreqHz = 30f, MaxFreqHz = 40f }, new BrainwaveFrequencyBands{ BandName = &quot;Gamma2&quot;, MinFreqHz = 40f, MaxFreqHz = 50f }, }; </code></pre>
<python><c#><scipy><fft><mathnet-numerics>
2023-07-17 00:28:23
0
1,024
Ganessa
76,700,778
3,334,355
Numpy einsum getting crazy slow after certain problem size
<p>I have the following benchmarking script</p> <pre><code>import numpy as np import timeit import matplotlib.pyplot as plt n1, n2, n3, n4, n5, m = (101, 33, 1, 32, 2, 32) def make_arrays(aOrder, bOrder, cOrder): a = np.random.randn(n1, m) + 1j * np.random.randn(n1, m) b = np.random.randn(n2, m) + 1j * np.random.randn(n2, m) c = np.random.randn(n1, n2, n3, n4, n5) + 1j * np.random.randn(n1, n2, n3, n4, n5) return ( np.array(a, order=aOrder), np.array(b, order=bOrder), np.array(c, order=cOrder), ) # used in B() blockSize = 84 resA = [] resB = [] resC = [] sizes = np.unique(np.exp(np.linspace(2, 6, 8)).astype(np.int64)) numTrials = 10 # overrides m form above for m in sizes: a, b, c = make_arrays(&quot;F&quot;, &quot;F&quot;, &quot;F&quot;) path = np.einsum_path( a, [0, 5], b, [1, 5], c, [0, 1, Ellipsis], [Ellipsis, 5], optimize=&quot;greedy&quot;, ) def A(): np.einsum( a, [0, 5], b, [1, 5], c, [0, 1, 2, 3, 4], [5, 2, 3, 4], optimize=&quot;greedy&quot;, order=&quot;F&quot;, ) # print(&quot;einsum\n&quot;, res.flags) def B(): numBlocks = int(a.shape[1] // blockSize) np.concatenate( tuple( np.einsum( c, [1, 2, Ellipsis], a[:, kk * blockSize : (kk + 1) * blockSize], [1, 0], b[:, kk * blockSize : (kk + 1) * blockSize], [2, 0], [0, Ellipsis], optimize=&quot;greedy&quot;, order=&quot;F&quot;, ) for kk in range(numBlocks) ) + ( np.einsum( c, [1, 2, Ellipsis], a[:, numBlocks * blockSize :], [1, 0], b[:, numBlocks * blockSize :], [2, 0], [0, Ellipsis], optimize=&quot;greedy&quot;, order=&quot;F&quot;, ), ), axis=0, ) def C(): tmp = np.einsum(a, [0, 5], c, [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], order=&quot;F&quot;) np.einsum(b, [1, 5], tmp, [1, 2, 3, 4, 5], [2, 3, 4, 5], order=&quot;F&quot;) A() B() C() measured = np.mean(timeit.repeat(A, number=numTrials, repeat=numTrials)) / ( numTrials * m ) resA.append(measured) measured = np.mean(timeit.repeat(B, number=numTrials, repeat=numTrials)) / ( numTrials * m ) resB.append(measured) measured = np.median(timeit.repeat(C, number=numTrials, repeat=numTrials)) / ( numTrials * m ) resC.append(measured) plt.figure() plt.semilogy(sizes, resA, label=&quot;A&quot;) plt.semilogy(sizes, resB, label=&quot;B&quot;) plt.semilogy(sizes, resC, label=&quot;C&quot;) plt.legend() plt.show() </code></pre> <p>I think one only needs <code>numpy</code> and <code>matplotlib</code> to run it.</p> <p>Approach <code>A</code> is my naive way of using einsum, since I expect this to work well. After some time this code has been residing in my codebase, I noticed that after a certain size of <code>m</code>, the computation just gets very slow. Hence, I went ahead and implemented <code>B</code>, which is producing satisfactory results across the board, but especially in the beginning it looses against <code>A</code>. Also, no matter how I toss and turn this in terms of memory-layout of the input and output-arrays, I see no noticeable difference in qualitative behavior.</p> <p>Just to retain my sanity, I went ahead and tried out an even more naive way by using <code>C</code>, which is superslow as expected.</p> <p>On a very powerful <code>AMD EPYC 7343 16-Core Processor</code> with numpy-intelpython, i.e. using MKL, where I have forced the MKL to only use one core for the computation, I get the following result:</p> <p><a href="https://i.sstatic.net/T18Fk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/T18Fk.png" alt="enter image description here" /></a></p> <p>Essentially I divide the runtime by the problem size <code>m</code>, to get an estimate for the cost of a single &quot;slice&quot; of the problems.</p> <p>To iron out any relation to the CPU or MKL, I used my Macbook Air with the M2 chip first with a vanilla numpy:</p> <p><a href="https://i.sstatic.net/AP9C1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AP9C1.png" alt="enter image description here" /></a></p> <p>and then also with a numpy linking again the accelerateBLAS library to make use of the GPU, or whatever, don't really care. Then I get</p> <p><a href="https://i.sstatic.net/YlpCF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YlpCF.png" alt="enter image description here" /></a></p> <p>So my question is: what the effing heck is wrong with <code>A</code>?</p> <p>As a kinda off-topic sidenote: I am also running the same code on cupy from time to time and there this behavior is not visible. There the corresponding version of <code>A</code> is scaling nicely, at least for the exact same problem sizes as used above.</p> <p>Another off-topic sidenote: If I use <code>opt_einsum</code> for the contraction, basically with the code of <code>A</code>, I get something similar to <code>B</code> from above, but slightly slower.</p>
<python><numpy><optimization><benchmarking><einsum>
2023-07-16 23:17:30
1
333
Labello
76,700,701
2,867,356
additional TaintStep for taint tracking in python programs
<p>I am using codeql TaintTracking and I noticed by default it does not follow data for functions it doesn't know.</p> <p>for exapmple for this code:</p> <pre class="lang-py prettyprint-override"><code>import pd a = src + anything df = pd.DataFrame(a) </code></pre> <p>if src is the source, then a is defined as a sink (as expected) but df isn't.</p> <p>I want to arrive to any &quot;contaminated&quot; variable, including df. Any ideas how to do that? I saw the documentation for overriding <code>isAdditionalTaintStep</code> in <code>TaintTracking::Configuration</code> which seems like a good direction but I only found examples of it crossing a specific function, and not any value assignment by any function (which I believe can be useful to many cases)</p> <p>An</p>
<python><static-analysis><codeql>
2023-07-16 22:46:56
1
592
Atlantis
76,700,620
9,588,300
Difference between PySpark functions write.parquet vs write.format('parquet')
<p>In PySpark DataFrames can be saved in two ways, irrespective of the data it contains</p> <pre><code>df.write.format('parquet').save(&lt;path&gt;) </code></pre> <p>and</p> <pre><code>df.write.parquet(&lt;path&gt;) </code></pre> <p>What is the difference between these two functions?</p>
<python><apache-spark><pyspark><databricks><parquet>
2023-07-16 22:17:24
1
462
Eugenio.Gastelum96
76,700,489
8,560,600
How to play Audio file at specific time?
<p>I have a video which I am processing, frame by frame, and I would like based on the result of frame processing to add multiple (short) audio file to it.</p> <p>For example, let's say I have a program for <strong>SQUAT COUNTING</strong>, and every time I detect a <strong>successful</strong> or <strong>unsuccessful</strong> squat, I want to add a specific sound.</p> <p>How would I do that, which libraries to use? I am using OpenCV for iterating through video frames, so the code looks something like this:</p> <pre><code>while(True): # Capture the video frame # by frame try: ret, frame = vid.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) out_frame, curr_proper_squat_num, curr_improper_squat_num = process_frame.process(frame, pose) if curr_proper_squat_num != prev_proper_squat_num: prev_proper_squat_num = curr_proper_squat_num # APPEND AUDIO STARTING FROM THIS FRAME elif curr_improper_squat_num != prev_improper_squat_num: prev_improper_squat_num = curr_improper_squat_num # APPEND AUDIO STARTING FROM THIS FRAME out_frame = cv2.cvtColor(out_frame, cv2.COLOR_RGB2BGR) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break except Exception as err: break </code></pre> <p>Which libraries would I use to append audio when I detect the frame from which I need audio to play?</p> <p>Thanks!</p>
<python><audio>
2023-07-16 21:27:28
0
1,608
Stefan Radonjic
76,700,162
442,351
sklearn - ModuleNotFound despite is installing successfully
<p>I'm importing <code>get_embedding</code> from <code>openai.embeddings_utils</code>.</p> <p>I received a <code>ModuleNotFound</code> error and, after installing</p> <ol> <li><code>matplotlib</code></li> <li><code>plotly</code></li> <li><code>scipy</code></li> </ol> <p>I got another saying that <code>sklearn</code> wasn't found. I've installed that, apparently successfully:</p> <pre><code>Successfully built sklearn Installing collected packages: sklearn Successfully installed sklearn-0.0.post5 </code></pre> <p>When I run the code though:</p> <pre class="lang-py prettyprint-override"><code>from openai.embeddings_utils import get_embedding df['embedding'] = df['text'].apply(lambda x: get_embedding(x, engine='text-embedding-ada-002')) </code></pre> <p>I still get the exception:</p> <p><code>ModuleNotFoundError: No module named 'sklearn'</code></p> <p>I'm <em>very</em> new to Python and Pip, is there some magic I need to do for this particular package?</p>
<python><scikit-learn><pip><openai-api>
2023-07-16 19:51:54
1
28,726
BanksySan
76,700,157
12,787,469
Unable to receive email during AWS Cognito signup phase
<p>After have client_id and client_secret properly imported into my code and have the hash secret generated using the credential and username, this is what i have for sign up:</p> <pre><code>user_attributes = [{&quot;Name&quot;: &quot;email&quot;, &quot;Value&quot;: email}] cognito_client.sign_up( ClientId=_CLIENT_ID, SecretHash=secret_hash, Username=username, UserAttributes=user_attributes, Password=password, ) </code></pre> <p>I tried to trigger this <code>sign_up()</code> method using a Lambda function, and this is what I get in the terminal every time when I wanted to create a new user</p> <pre><code>on 'AuthFunction' timed out after 10 seconds &quot;errorMessage&quot;: &quot;An error occurred (CodeDeliveryFailureException) when calling the SignUp operation: Unable to deliver message&quot;. </code></pre> <p>I checked my userpool in AWS Cognito console, and I can see a user created but with the email field left unverified. The email I used here has been verified on SES (I am currently in the sandbox mode)</p> <p>Anyone ran into this issue before?</p> <p>UPDATE: I might have to contact AWS support for the issue described in this thread because it looks like this very Userpool I created also has other weird problems: 1. I can't update REPLY-TO email config (originally left blank) under the Messaging tab 2. I can't deactivate Deletion Protection, which in turn prevents me from deleting the Userpool as a whole. The error message I received after implementing any of the actions listed above is <code>code: InvalidParameterException message: Unable to deliver message</code>. So what I did was I created a new Userpool with a valid REPLY-TO email (updated the corresponding credentials), and I received an automated email with verification code.</p>
<python><aws-lambda><amazon-cognito>
2023-07-16 19:50:18
0
397
TechSelfLearner
76,700,089
15,098,472
Adding a column in a DataFrame based on thresholds and size of group
<p>I have a DataFrame with x and y coordinates, where the index represents a timestamp. We may assume it is an object that moves every timestep. The distance between consecutive timestamps is expected to increase. However, if the distance doesn't increase by a certain threshold, I consider it a potential &quot;waiting&quot; position. I use the word potential, because the data is quite noisy, and a single 'waiting' condition is not enough to be really sure that the object was not moving. Thus, I require at least 3 or more consecutive 'waiting' conditions, before I can be sure the object was indeed not moving.</p> <p>I would like to detect these waiting positions and label them accordingly in a new column.</p> <pre><code>Example : x y timestamp 2023-07-01 00:00:00 1 5 2023-07-01 00:01:00 2 6 2023-07-01 00:02:00 3 7 2023-07-01 00:03:00 4 8 2023-07-01 00:04:00 4 8 2023-07-01 00:05:00 5 9 2023-07-01 00:06:00 6 9 2023-07-01 00:07:00 7 10 2023-07-01 00:08:00 7 10 2023-07-01 00:09:00 7 10 2023-07-01 00:10:00 7 10 2023-07-01 00:11:00 8 11 2023-07-01 00:12:00 9 11 </code></pre> <p>To compute the distance, I already shifted the dataframe by 1, and caluclate the distance:</p> <pre><code> x y distance timestamp 2023-07-01 00:00:00 1 5 NaN 2023-07-01 00:01:00 2 6 1.414214 2023-07-01 00:02:00 3 7 1.414214 2023-07-01 00:03:00 4 8 1.414214 2023-07-01 00:04:00 4 8 0.000000 2023-07-01 00:05:00 5 9 1.414214 2023-07-01 00:06:00 6 9 1.000000 2023-07-01 00:07:00 7 10 1.414214 2023-07-01 00:08:00 7 10 0.000000 2023-07-01 00:09:00 7 10 0.000000 2023-07-01 00:10:00 7 10 0.000000 2023-07-01 00:11:00 8 11 1.414214 2023-07-01 00:12:00 9 11 1.000000 </code></pre> <p>Now, assume if the distance is lower than 1, it could potentially be a waiting position:</p> <pre><code> x y distance condition_fulfilled timestamp 2023-07-01 00:00:00 1 5 NaN NaN 2023-07-01 00:01:00 2 6 1.414214 False 2023-07-01 00:02:00 3 7 1.414214 False 2023-07-01 00:03:00 4 8 1.414214 False 2023-07-01 00:04:00 4 8 0.000000 True 2023-07-01 00:05:00 5 9 1.414214 False 2023-07-01 00:06:00 6 9 1.000000 False 2023-07-01 00:07:00 7 10 1.414214 False 2023-07-01 00:08:00 7 10 0.000000 True 2023-07-01 00:09:00 7 10 0.000000 True 2023-07-01 00:10:00 7 10 0.000000 True 2023-07-01 00:11:00 8 11 1.414214 False 2023-07-01 00:12:00 9 11 1.000000 False </code></pre> <p>Since I require at least 3 consecutive fulfilled condtions, the expected output would be:</p> <pre><code> x y distance status timestamp 2023-07-01 00:00:00 1 5 NaN moving 2023-07-01 00:01:00 2 6 1.414214 moving 2023-07-01 00:02:00 3 7 1.414214 moving 2023-07-01 00:03:00 4 8 1.414214 moving 2023-07-01 00:04:00 4 8 0.000000 moving 2023-07-01 00:05:00 5 9 1.414214 moving 2023-07-01 00:06:00 6 9 1.000000 moving 2023-07-01 00:07:00 7 10 1.414214 moving 2023-07-01 00:08:00 7 10 0.000000 waiting 2023-07-01 00:09:00 7 10 0.000000 waiting 2023-07-01 00:10:00 7 10 0.000000 waiting 2023-07-01 00:11:00 8 11 1.414214 moving 2023-07-01 00:12:00 9 11 1.000000 moving </code></pre>
<python><pandas>
2023-07-16 19:34:01
3
574
kklaw
76,700,067
9,588,300
Pyspark get max value of column of a csv the quickest way possible
<p>I am trying to get the max value of a column using this: <code>df.agg(max(col('some_integer_column')),min(col('some_integer_column')))</code></p> <p>The df is a csv file. Which I know if it was a parquet/delta it would be much easier and faster. As the csv file needs to shuffle data because it doesn't have the metadata stats that a parquet/delta has. But I am not interested in rewriting the csv as parquet/delta</p> <p>So in my df from the csv, I checked the execution plan from that command, and I see it does some exchange of partitions. While I know it theoretically needs to do so because data is scattered across partitions. Can't there just exist a quicker way to minimize the shuffle?</p> <p>Like letting each executor check for each of his partitions what is the maximum value within each partition. And then share that value in the exchange. For example, if I have 200 partitions, then I can get 200 values. So now I just have to shuffle 200 values and get the max of 200 values.</p> <p>Instead of shuffling all the data inside the 200 partitions which is what I understand this execution plan is doing:</p> <p><a href="https://i.sstatic.net/t4CPY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/t4CPY.png" alt="Execution Plan" /></a></p>
<python><pyspark><databricks><distributed-computing><spark-ui>
2023-07-16 19:29:02
1
462
Eugenio.Gastelum96
76,699,993
19,366,064
Python How to move/centralize pycache files
<p>Below is what my project looks like</p> <pre><code>Project src folder1 __pycache__ ... folder2 __pycache__ ... main __pycache__ tests __pycache__ ... </code></pre> <p>Is there a way to centralize all the pycache files in one folder so that it looks something like this?</p> <pre><code>Project __pycache__ src folder1 folder2 main tests </code></pre>
<python>
2023-07-16 19:10:48
2
544
Michael Xia
76,699,846
19,574,336
form element is not valid
<p>I'm trying to make a form (without using django's template forms) but for some reason my forms are never valid when I try them. Here is my code:</p> <p>forms.py:</p> <pre><code>class AddressForm(forms.Form): address_long = forms.CharField(max_length=500) class Meta: model = Address fields = ['address_long'] def save(self, commit=True): address = Address.objects.create() address.address_long = self.cleaned_data['address_long'] if commit: address.save() return address </code></pre> <p>views.py:</p> <pre><code>@login_required def add_address_view(request): if request.method == 'POST': form = AddressForm(request.POST) print(request.POST) if form.is_valid(): print(&quot;Valid&quot;) address = form.save() user_profile = request.user.userprofile user_profile.addresses.add(address) # Add to many to many field user_profile.save() return redirect('core:profile') # Redirect to the user's profile page else: form = AddressForm() return render(request, 'Test_site/add-address.html', {'form': form, 'countries': COUNTRIES}) </code></pre> <p>And my html looks like this:</p> <pre><code>... &lt;form method=&quot;POST&quot; class=&quot;col-md-5 border-right&quot;&gt; {% csrf_token %} ... &lt;div class=&quot;col-md-12&quot;&gt; &lt;label class=&quot;labels&quot;&gt;Address Long&lt;/label&gt; &lt;input name=&quot;{{ form.address_long.name }}&quot; id=&quot;{{ form.address_long.auto_id }}&quot; type=&quot;text&quot; class=&quot;input-field form-control&quot; placeholder=&quot;enter address line&quot; value=&quot;&quot;&gt; &lt;/div&gt; ... &lt;/form&gt; </code></pre> <p>When I try this on my local host I get this output from the print statements in the view function:</p> <pre><code>&lt;QueryDict: {'csrfmiddlewaretoken': ['my_generated_token'], 'address_long': ['Long address try']}&gt; </code></pre> <p>But no matter what I do it just doesn't pass the '.is_valid()' check. Also I can't look up on what 'form' holds, like trying to do <code>form.cleaned_data['address_long']</code> causes a 'form doesnt have member cleaned_data' error. It acts like it can't create the object. For example form.address_long is also invalid, eventhough I've created the form, it says it's not there.</p> <p>What's the issue here?</p> <p>Note: I have more members in AddressForm then address_long, but they are all char fields and I made sure all the fields are filled on every step.</p>
<python><django><forms>
2023-07-16 18:33:37
1
859
Turgut
76,699,785
8,176,763
Airflow SqlSensor
<p>I have a dag that checks if a database is in recovery mode. The task is a sqlsensor, and I'm struggling to get this correct. I want to check every 5 minutes to see if a database is in recovery mode or not. The sql query will return one row, either false or true. I want to mark the task as Failed if it returns False and Success if it return True. The problem is that this code for some reason is continuously checking the database every second, it seems the cacthup argument is not working and is backfilling everything. I set the poke_interval differently for 5 minutes but this does not work as I expect. I also don't know how to handle the parameters <code>success</code> and <code>failure</code> in this case when the sql query returns <code>false</code> and <code>true</code>.</p> <pre><code>from airflow.sensors.sql import SqlSensor from airflow import DAG from datetime import datetime, timedelta # Define the DAG default_args = { 'start_date': datetime(2023, 7, 15), 'catchup': False, } dag = DAG( 'database_monitor', default_args=default_args, schedule_interval='*/10 * * * *' # Runs every 10 minutes ) check_db_alive = SqlSensor( task_id=&quot;check_db_alive&quot;, conn_id=&quot;evergreen&quot;, sql=&quot;SELECT pg_is_in_recovery()&quot;, #failure= lambda x: x == 'false', poke_interval= 60 * 5, timeout = 60 * 2, mode = &quot;reschedule&quot;, dag=dag ) check_db_alive </code></pre>
<python><airflow>
2023-07-16 18:16:34
0
2,459
moth
76,699,483
13,849,446
Handle Add Extension Alert from webstore using only Selenium to make it work in headless
<p>All the current solutions on Stack Overflow use pyautogui or some other method to click on the add extension alert. Or some will say to download and load the extension using ChromeOptions. Well, I do not want any of these. The reason is I need to make it work in headless mode and I can not download the extension for some reason.</p> <p>Here is a link to similar question: <a href="https://stackoverflow.com/questions/69269098/python-selenium-how-to-handle-chrome-store-alert">Python Selenium How to handle chrome store alert?</a></p> <p>I have tried the steps in this post but they do not work. The code snippet to work with is:</p> <pre><code>import time import pyautogui from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager from undetected_chromedriver import Chrome, ChromeOptions from selenium.webdriver.support import expected_conditions as EC service = Service(ChromeDriverManager().install()) options = ChromeOptions() options.add_argument(&quot;--disable-web-security&quot;) options.add_argument(&quot;--disable-xss-auditor&quot;) options.add_argument(&quot;--no-sandbox&quot;) driver = Chrome(service=service, chrome_options=options) driver.execute_script(&quot;Object.defineProperty(navigator, 'webdriver', {get: function() {return false}})&quot;) wait = WebDriverWait(driver, 50) driver.get(&quot;https://chrome.google.com/webstore/detail/chatgpt-chrome-extension/gabfffndnhbbjlgmbogpfaciajcbpkdn&quot;) wait.until(EC.element_to_be_clickable((By.XPATH, '//div[contains(@class, &quot;webstore-test-button-label&quot;) and contains(text(), &quot;Add&quot;)]'))) driver.find_element(By.XPATH, '//div[contains(@class, &quot;webstore-test-button-label&quot;) and contains(text(), &quot;Add&quot;)]').click() time.sleep(5) pyautogui.hotkey('tab','enter', interval=0.1) time.sleep(5) driver.quit() </code></pre>
<python><python-3.x><selenium-webdriver>
2023-07-16 17:04:05
0
1,146
farhan jatt
76,699,398
3,071,728
pyftpdlib ftp server unavailable from outside local network
<p>my server is simple:</p> <pre><code>from pyftpdlib import servers, handlers address = (&quot;0.0.0.0&quot;, 21) server = servers.FTPServer(address, handlers.FTPHandler) server.banner = &quot;Welcome to My FTP Server&quot; handler = server.handler handler.authorizer.add_user(&quot;username&quot;, &quot;password&quot;, &quot;.&quot;, perm=&quot;elr&quot;) handler.authorizer.add_anonymous(&quot;.&quot;, perm=&quot;elr&quot;) handler.masquerade_address = '97.117.28.178' # from `curl ifconfig.me` handler.passive_ports = range(60000, 60100) server.serve_forever() </code></pre> <p>running in a docker container:</p> <pre><code>docker run --rm -it -p 20:20 -p 21:21 -p 60000-60100:60000-60100 python:slim bash </code></pre> <p>then I run a client (in the same image):</p> <pre><code>import os from ftplib import FTP class FTPClient: def __init__(self, host): self.host = host def _connect(self): self.ftp = FTP(self.host) self.ftp.set_pasv(True) self.ftp.login('username', 'password') def _disconnect(self): ''' Disconnect from the FTP server ''' self.ftp.quit() def connect(self): self.ftp = FTP(self.host) self.ftp.login('username', 'password') @staticmethod def manageConnection(func): def wrapper(self, *args, **kwargs): self._connect() result = func(self, *args, **kwargs) self._disconnect() return result return wrapper @manageConnection def pull(self, filename: str, path: str = None, local: str = '.') -&gt; bool: if path is not None: self.ftp.cwd(path) if filename in self.ftp.nlst(): # Specify the desired folder or path here local_path = os.path.join(local, filename) with open(local_path, 'wb') as file: self.ftp.retrbinary('RETR ' + filename, file.write) return True return False @manageConnection def view(self, path: str = None) -&gt; bool: if path is not None: self.ftp.cwd(path) for file in self.ftp.nlst(): print(file) return False </code></pre> <p>and it works fine locally:</p> <pre><code>f = FTPClient('127.0.0.1') f.connect() # works - I see logs on server f.pull('utils.py') # works - downloads files </code></pre> <p>but when I point it to the public address it fails:</p> <pre><code>f = FTPClient('97.117.28.178') f.connect() # doesn't work - no log entries on server, it doesn't even reach it &gt; Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;&lt;stdin&gt;&quot;, line 13, in wrapper File &quot;&lt;stdin&gt;&quot;, line 5, in _connect File &quot;/usr/local/lib/python3.11/ftplib.py&quot;, line 121, in __init__ self.connect(host) File &quot;/usr/local/lib/python3.11/ftplib.py&quot;, line 158, in connect self.sock = socket.create_connection((self.host, self.port), self.timeout, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/usr/local/lib/python3.11/socket.py&quot;, line 851, in create_connection raise exceptions[0] File &quot;/usr/local/lib/python3.11/socket.py&quot;, line 836, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused </code></pre> <p>What could be the cause of this? I want the FTP server to be accessible online.</p>
<python><docker><ftp><connection-refused>
2023-07-16 16:44:30
0
3,848
MetaStack
76,699,105
8,207,754
~900 line error message when pip installing numpy
<p>I'm using MacOS Ventura 13.4.1 (Apple M1 chip). Here's some info about my local setup:</p> <pre><code>&gt; uname -m arm64 &gt; pyenv -v pyenv 2.3.22 &gt; pyenv versions system * 3.6.15 (set by /Users/user1/.pyenv/version) 3.7.17 &gt; python -V Python 3.6.15 &gt; pip -V pip 21.3.1 from /Users/user1/.pyenv/versions/3.6.15/lib/python3.6/site-packages/pip (python 3.6) </code></pre> <p>I can run Python files just fine. But when I do <code>pip install numpy</code>, I get the ~900 line error message below (truncated in the middle). I've also tried with <code>--no-cache-dir</code>. Other pip installs are successful, e.g. pytest. I do need to use Python 3.6 here, which I know is an older version.</p> <pre><code>(conda_env) user1@xxx directory % pip install numpy --no-cache-dir Collecting numpy Downloading numpy-1.19.5.zip (7.3 MB) |████████████████████████████████| 7.3 MB 4.4 MB/s Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: numpy Building wheel for numpy (pyproject.toml) ... error ERROR: Command errored out with exit status 1: command: /Users/user1/.pyenv/versions/3.6.15/bin/python3.6 /Users/user1/.pyenv/versions/3.6.15/lib/python3.6/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/tmp10f0xbak cwd: /private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/pip-install-2mc8sdc8/numpy_e35df2512ab24c5382ec786ebe6e6e01 Complete output (901 lines): numpy/random/_bounded_integers.pxd.in has not changed numpy/random/_philox.pyx has not changed numpy/random/_bounded_integers.pyx.in has not changed numpy/random/_sfc64.pyx has not changed numpy/random/_mt19937.pyx has not changed numpy/random/bit_generator.pyx has not changed Processing numpy/random/_bounded_integers.pyx numpy/random/mtrand.pyx has not changed numpy/random/_generator.pyx has not changed numpy/random/_pcg64.pyx has not changed numpy/random/_common.pyx has not changed Cythonizing sources blas_opt_info: blas_mkl_info: customize UnixCCompiler libraries mkl_rt not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE blis_info: libraries blis not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE openblas_info: libraries openblas not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE atlas_3_10_blas_threads_info: Setting PTATLAS=ATLAS libraries tatlas not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE atlas_3_10_blas_info: libraries satlas not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE atlas_blas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE atlas_blas_info: libraries f77blas,cblas,atlas not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE accelerate_info: libraries accelerate not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] Library accelerate was not found. Ignoring libraries veclib not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] Library veclib was not found. Ignoring FOUND: extra_compile_args = ['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers'] extra_link_args = ['-Wl,-framework', '-Wl,Accelerate'] define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)] FOUND: extra_compile_args = ['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers'] extra_link_args = ['-Wl,-framework', '-Wl,Accelerate'] define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)] non-existing path in 'numpy/distutils': 'site.cfg' lapack_opt_info: lapack_mkl_info: libraries mkl_rt not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE openblas_lapack_info: libraries openblas not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE openblas_clapack_info: libraries openblas,lapack not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE flame_info: libraries flame not found in ['/Users/user1/.pyenv/versions/3.6.15/lib', '/usr/local/lib', '/usr/lib', '/opt/local/lib'] NOT AVAILABLE atlas_3_10_threads_info: Setting PTATLAS=ATLAS libraries lapack_atlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries tatlas,tatlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries lapack_atlas not found in /usr/local/lib libraries tatlas,tatlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/lib libraries tatlas,tatlas not found in /usr/lib libraries lapack_atlas not found in /opt/local/lib libraries tatlas,tatlas not found in /opt/local/lib &lt;class 'numpy.distutils.system_info.atlas_3_10_threads_info'&gt; NOT AVAILABLE atlas_3_10_info: libraries lapack_atlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries satlas,satlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries lapack_atlas not found in /usr/local/lib libraries satlas,satlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/lib libraries satlas,satlas not found in /usr/lib libraries lapack_atlas not found in /opt/local/lib libraries satlas,satlas not found in /opt/local/lib &lt;class 'numpy.distutils.system_info.atlas_3_10_info'&gt; NOT AVAILABLE atlas_threads_info: Setting PTATLAS=ATLAS libraries lapack_atlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries ptf77blas,ptcblas,atlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries lapack_atlas not found in /usr/local/lib libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/lib libraries ptf77blas,ptcblas,atlas not found in /usr/lib libraries lapack_atlas not found in /opt/local/lib libraries ptf77blas,ptcblas,atlas not found in /opt/local/lib &lt;class 'numpy.distutils.system_info.atlas_threads_info'&gt; NOT AVAILABLE atlas_info: libraries lapack_atlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries f77blas,cblas,atlas not found in /Users/user1/.pyenv/versions/3.6.15/lib libraries lapack_atlas not found in /usr/local/lib libraries f77blas,cblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/lib libraries f77blas,cblas,atlas not found in /usr/lib libraries lapack_atlas not found in /opt/local/lib libraries f77blas,cblas,atlas not found in /opt/local/lib &lt;class 'numpy.distutils.system_info.atlas_info'&gt; NOT AVAILABLE FOUND: extra_compile_args = ['-faltivec', '-I/System/Library/Frameworks/vecLib.framework/Headers'] extra_link_args = ['-Wl,-framework', '-Wl,Accelerate'] define_macros = [('NO_ATLAS_INFO', 3), ('HAVE_CBLAS', None)] running bdist_wheel running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options running build_src build_src building py_modules sources building library &quot;npymath&quot; sources Could not locate executable gfortran Could not locate executable f95 Could not locate executable f90 Could not locate executable f77 Could not locate executable xlf90 Could not locate executable xlf Could not locate executable ifort Could not locate executable ifc Could not locate executable g77 Could not locate executable g95 Could not locate executable pgfortran don't know how to compile Fortran code on platform 'posix' adding 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath' to include_dirs. None - nothing done with h_files = ['build/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath/npy_math_internal.h'] building library &quot;npysort&quot; sources adding 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/common' to include_dirs. None - nothing done with h_files = ['build/src.macosx-13.4-arm64-3.6/numpy/core/src/common/npy_sort.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/common/npy_partition.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/common/npy_binsearch.h'] building library &quot;npyrandom&quot; sources building extension &quot;numpy.core._multiarray_tests&quot; sources building extension &quot;numpy.core._multiarray_umath&quot; sources adding 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath' to include_dirs. adding 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath' to include_dirs. adding 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/common' to include_dirs. numpy.core - nothing done with h_files = ['build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath/funcs.inc', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath/simd.inc', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath/loops.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath/matmul.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath/clip.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath/npy_math_internal.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/src/common/templ_common.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy/config.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy/_numpyconfig.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy/__multiarray_api.h', 'build/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy/__ufunc_api.h'] building extension &quot;numpy.core._umath_tests&quot; sources building extension &quot;numpy.core._rational_tests&quot; sources building extension &quot;numpy.core._struct_ufunc_tests&quot; sources building extension &quot;numpy.core._operand_flag_tests&quot; sources building extension &quot;numpy.fft._pocketfft_internal&quot; sources building extension &quot;numpy.linalg.lapack_lite&quot; sources building extension &quot;numpy.linalg._umath_linalg&quot; sources building extension &quot;numpy.random._mt19937&quot; sources building extension &quot;numpy.random._philox&quot; sources building extension &quot;numpy.random._pcg64&quot; sources building extension &quot;numpy.random._sfc64&quot; sources building extension &quot;numpy.random._common&quot; sources building extension &quot;numpy.random.bit_generator&quot; sources building extension &quot;numpy.random._generator&quot; sources building extension &quot;numpy.random._bounded_integers&quot; sources building extension &quot;numpy.random.mtrand&quot; sources building data_files sources build_src: building npy-pkg config files running build_py (Removed chunk of error message) numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) numpy/core/src/npysort/selection.c.src:328:9: warning: code will never be executed [-Wunreachable-code] npy_intp k; ^~~~~~~~~~~ numpy/core/src/npysort/selection.c.src:326:14: note: silence by adding parentheses to mark code as explicitly dead else if (0 &amp;&amp; kth == num - 1) { ^ /* DISABLES CODE */ ( ) 22 warnings generated. ar: adding 7 object files to build/temp.macosx-13.4-arm64-3.6/libnpysort.a ranlib:@ build/temp.macosx-13.4-arm64-3.6/libnpysort.a building 'npyrandom' library compiling C sources C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include creating build/temp.macosx-13.4-arm64-3.6/numpy/random creating build/temp.macosx-13.4-arm64-3.6/numpy/random/src creating build/temp.macosx-13.4-arm64-3.6/numpy/random/src/distributions compile options: '-Inumpy/core/include -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/Users/user1/.pyenv/versions/3.6.15/include/python3.6m -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/common -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath -c' clang: numpy/random/src/distributions/logfactorial.c clang: numpy/random/src/distributions/distributions.c clang: numpy/random/src/distributions/random_mvhg_marginals.c clang: numpy/random/src/distributions/random_mvhg_count.c clang: numpy/random/src/distributions/random_hypergeometric.c ar: adding 5 object files to build/temp.macosx-13.4-arm64-3.6/libnpyrandom.a ranlib:@ build/temp.macosx-13.4-arm64-3.6/libnpyrandom.a running build_ext customize UnixCCompiler customize UnixCCompiler using new_build_ext building 'numpy.core._multiarray_tests' extension compiling C sources C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include creating build/temp.macosx-13.4-arm64-3.6/build/src.macosx-13.4-arm64-3.6/numpy/core/src/multiarray creating build/temp.macosx-13.4-arm64-3.6/numpy/core/src/common compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -Inumpy/core/include -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/Users/user1/.pyenv/versions/3.6.15/include/python3.6m -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/common -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath -c' clang: build/src.macosx-13.4-arm64-3.6/numpy/core/src/multiarray/_multiarray_tests.c clang: numpy/core/src/common/mem_overlap.c In file included from numpy/core/src/multiarray/_multiarray_tests.c.src:7: In file included from numpy/core/include/numpy/npy_math.h:596: numpy/core/src/npymath/npy_math_internal.h.src:490:21: warning: incompatible pointer types passing 'npy_longdouble *' (aka 'double *') to parameter of type 'long double *' [-Wincompatible-pointer-types] return modfl(x, iptr); ^~~~ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/math.h:394:52: note: passing argument to parameter here extern long double modfl(long double, long double *); ^ numpy/core/src/multiarray/_multiarray_tests.c.src:1895:61: warning: format specifies type 'long double' but the argument has type 'npy_longdouble' (aka 'double') [-Wformat] PyOS_snprintf(str, sizeof(str), &quot;%.*Lg&quot;, precision, x); ~~~~~ ^ %.*g 2 warnings generated. clang -bundle -undefined dynamic_lookup -L/opt/homebrew/opt/readline/lib -L/opt/homebrew/opt/readline/lib -L/opt/homebrew/opt/openssl@3/lib -L/Users/user1/.pyenv/versions/3.6.15/lib -Wl,-rpath,/Users/user1/.pyenv/versions/3.6.15/lib -L/opt/homebrew/lib -Wl,-rpath,/opt/homebrew/lib -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib -L/opt/homebrew/opt/readline/lib -L/opt/homebrew/opt/readline/lib -L/opt/homebrew/opt/openssl@3/lib -L/Users/user1/.pyenv/versions/3.6.15/lib -Wl,-rpath,/Users/user1/.pyenv/versions/3.6.15/lib -L/opt/homebrew/lib -Wl,-rpath,/opt/homebrew/lib -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib build/temp.macosx-13.4-arm64-3.6/build/src.macosx-13.4-arm64-3.6/numpy/core/src/multiarray/_multiarray_tests.o build/temp.macosx-13.4-arm64-3.6/numpy/core/src/common/mem_overlap.o -L/Users/user1/.pyenv/versions/3.6.15/lib -Lbuild/temp.macosx-13.4-arm64-3.6 -lnpymath -o build/lib.macosx-13.4-arm64-3.6/numpy/core/_multiarray_tests.cpython-36m-darwin.so building 'numpy.core._multiarray_umath' extension compiling C sources C compiler: clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include creating build/temp.macosx-13.4-arm64-3.6/numpy/core/src/multiarray creating build/temp.macosx-13.4-arm64-3.6/numpy/core/src/umath creating build/temp.macosx-13.4-arm64-3.6/build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath creating build/temp.macosx-13.4-arm64-3.6/build/src.macosx-13.4-arm64-3.6/numpy/core/src/common creating build/temp.macosx-13.4-arm64-3.6/private creating build/temp.macosx-13.4-arm64-3.6/private/var creating build/temp.macosx-13.4-arm64-3.6/private/var/folders creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm/906grd657hd0rc9std54b39w0000gn creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/pip-install-2mc8sdc8 creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/pip-install-2mc8sdc8/numpy_e35df2512ab24c5382ec786ebe6e6e01 creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/pip-install-2mc8sdc8/numpy_e35df2512ab24c5382ec786ebe6e6e01/numpy creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/pip-install-2mc8sdc8/numpy_e35df2512ab24c5382ec786ebe6e6e01/numpy/_build_utils creating build/temp.macosx-13.4-arm64-3.6/private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/pip-install-2mc8sdc8/numpy_e35df2512ab24c5382ec786ebe6e6e01/numpy/_build_utils/src compile options: '-DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -DNO_ATLAS_INFO=3 -DHAVE_CBLAS -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/umath -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/common -Inumpy/core/include -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/Users/user1/.pyenv/versions/3.6.15/include/python3.6m -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/common -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath -c' extra options: '-faltivec -I/System/Library/Frameworks/vecLib.framework/Headers' clang: numpy/core/src/multiarray/alloc.c clang: numpy/core/src/multiarray/array_assign_scalar.c clang: numpy/core/src/multiarray/common.c clang: numpy/core/src/multiarray/datetime_strings.c clang: numpy/core/src/multiarray/descriptor.c clang: numpy/core/src/multiarray/buffer.c clang: numpy/core/src/multiarray/conversion_utils.c clang: build/src.macosx-13.4-arm64-3.6/numpy/core/src/multiarray/einsum.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/hashdescr.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: build/src.macosx-13.4-arm64-3.6/numpy/core/src/multiarray/lowlevel_strided_loops.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/multiarraymodule.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/nditer_constr.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/refcount.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/scalarapi.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/temp_elide.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/multiarray/vdot.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: build/src.macosx-13.4-arm64-3.6/numpy/core/src/umath/loops.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/umath/ufunc_object.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/umath/ufunc_type_resolution.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: build/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath/ieee754.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: numpy/core/src/common/array_assign.c clang: numpy/core/src/common/ucsnarrow.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: build/src.macosx-13.4-arm64-3.6/numpy/core/src/common/npy_cpu_features.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: /private/var/folders/sm/906grd657hd0rc9std54b39w0000gn/T/pip-install-2mc8sdc8/numpy_e35df2512ab24c5382ec786ebe6e6e01/numpy/_build_utils/src/apple_sgemv_fix.c clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly Running from numpy source directory. /Users/user1/.pyenv/versions/3.6.15/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'define_macros' warnings.warn(msg) error: Command &quot;clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -DNPY_INTERNAL_BUILD=1 -DHAVE_NPY_CONFIG_H=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE=1 -D_LARGEFILE64_SOURCE=1 -DNO_ATLAS_INFO=3 -DHAVE_CBLAS -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/umath -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/common -Inumpy/core/include -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/include/numpy -Inumpy/core/src/common -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -I/Users/user1/.pyenv/versions/3.6.15/include/python3.6m -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/common -Ibuild/src.macosx-13.4-arm64-3.6/numpy/core/src/npymath -c numpy/core/src/multiarray/array_assign_scalar.c -o build/temp.macosx-13.4-arm64-3.6/numpy/core/src/multiarray/array_assign_scalar.o -MMD -MF build/temp.macosx-13.4-arm64-3.6/numpy/core/src/multiarray/array_assign_scalar.o.d -faltivec -I/System/Library/Frameworks/vecLib.framework/Headers&quot; failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for numpy Failed to build numpy ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects </code></pre>
<python><numpy><pip><apple-m1>
2023-07-16 15:40:01
1
794
K--
76,698,958
2,393,472
There is an error adding a custom LibreOffice extension
<p>Good afternoon.</p> <p>I wrote an extension for LibreOffice. Here is its structure:</p> <p><a href="https://i.sstatic.net/8jDgc.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8jDgc.png" alt="enter image description here" /></a></p> <p>The contents of the file <strong>datalink.py</strong>:</p> <pre><code>import uno import unohelper from com.sun.star.task import XJobExecutor from pythonpath.services.messageboxservice import MessageBoxService class DataLink(unohelper.Base, XJobExecutor): implementationName = &quot;vnd.datalink&quot; serviceNames = (&quot;com.sun.star.task.Job&quot;,) def __init__(self, context): self.context = context def trigger(self, args): MessageBoxService(&quot;Hello World!!! Args: &quot; + args, &quot;Info&quot;) g_ImplementationHelper = unohelper.ImplementationHelper() g_ImplementationHelper.addImplementation(DataLink, DataLink.implementationName, DataLink.serviceNames,) </code></pre> <p>The contents of the file <strong>messageboxservice.py</strong>:</p> <pre><code>import uno from com.sun.star.awt.MessageBoxType import INFOBOX from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK class MessageBoxService: @staticmethod def Show(text, caption, type = INFOBOX): context = uno.getComponentContext() sManager = context.ServiceManager toolkit = sManager.createInstance(&quot;com.sun.star.awt.Toolkit&quot;) msgbox = toolkit.createMessageBox(None, type, BUTTONS_OK, caption, text) return msgbox.execute() </code></pre> <p>The contents of the file <strong>manifest.xml</strong>:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;manifest:manifest xmlns:manifest=&quot;http://openoffice.org/2001/manifest&quot;&gt; &lt;manifest:file-entry manifest:full-path=&quot;Addons.xcu&quot; manifest:media-type=&quot;application/vnd.sun.star.configuration-data&quot;/&gt; &lt;manifest:file-entry manifest:full-path=&quot;datalink.py&quot; manifest:media-type=&quot;application/vnd.sun.star.uno-component;type=Python&quot;/&gt; &lt;/manifest:manifest&gt; </code></pre> <p>When you add a <strong>DataLink.oxt</strong> extension file to LibreOffice, the following error occurs: <a href="https://i.sstatic.net/S9SSW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/S9SSW.png" alt="enter image description here" /></a></p> <p><strong>Question</strong>: How did I correct this error?</p> <p><strong>P.S.</strong> may need to make any changes to the above files</p>
<python><libreoffice-calc>
2023-07-16 15:09:58
1
333
Anton
76,698,934
14,068,964
getting upgrade pip warning but requirement already satisfied
<p>I have started a fresh venv in a new project location and after activating it used <code>pip list</code> to see what a fresh venv included. The listing included a warning that I was not using the latest version of pip:</p> <pre><code>WARNING: You are using pip version 21.2.4; however, version 23.2 is available. You should consider upgrading via the '&lt;path to project&gt;/venv/bin/python3 -m pip install --upgrade pip' command. </code></pre> <p>However, when I execute the recommended command I get another warning that the requirement is already satisfied:</p> <pre><code>Requirement already satisfied: pip in ./venv/lib/python3.9/site-packages (23.2) </code></pre> <p>which just hangs there forever until I kill it.</p> <p>What am I missing here? Is this a PATH conflict and it might be looking elsewhere in my environment?</p> <p>Thanks, in advance.</p>
<python><pip><warnings><upgrade>
2023-07-16 15:04:50
2
329
Bruce Altner
76,698,792
8,485,638
Setting the type of a hard coded string in a column_property in SQLAlchemy?
<p>Given the following model using flask_sqlalchemy:</p> <pre><code>class Student(DB.Model): &quot;&quot;&quot;A student.&quot;&quot;&quot; id_: DB.Mapped[uuid.UUID] = DB.mapped_column( primary_key=True, default=uuid.uuid4 ) first_name: DB.Mapped[str] = DB.mapped_column(StrippedString(16)) last_name: DB.Mapped[str] = DB.mapped_column(StrippedString(32)) full_name: DB.Mapped[str] = DB.column_property( first_name + &quot; &quot; + last_name, ) </code></pre> <p>Whenever printing out <code>full_name</code>, the space in between is not there. I figured that this is because <code>first_name</code> is of type <code>StrippedString</code>:</p> <pre><code>class StrippedString(TypeDecorator): &quot;&quot;&quot;An augmented string type. It strips whitespace upon the binding of the value as a parameter to a query. &quot;&quot;&quot; impl = DB.String cache_ok = True def process_bind_param(self, value, dialect): &quot;&quot;&quot;Strip the value (if it exists) from leading and trailing whitespace.&quot;&quot;&quot; return value.strip() if value else None </code></pre> <p>The <code>process_bind_param</code> function above is applied to the <code>&quot; &quot;</code> as well, resulting in no space between <code>first_name</code> and <code>last_name</code>.</p> <p>If I change the column type of <code>first_name</code> to <code>DB.String(16)</code>, all is well. Except, of course, I want to retain the <code>StrippedString</code> type for <code>first_name</code>.</p> <p>So, now my question is: how can I set (or influence) the type of the plain string <code>&quot; &quot;</code>? Basically, I want the hard coded <code>&quot; &quot;</code> to be left alone, and not seen as another <code>StrippedString</code>.</p>
<python><sqlalchemy>
2023-07-16 14:30:37
1
1,530
Bart Van Loon
76,698,709
1,451,346
In what way does `runpy` leave functions or classes in an incorrect state?
<p>The documentation for <code>runpy</code> <a href="https://docs.python.org/3.11/library/runpy.html" rel="nofollow noreferrer">warns</a></p> <blockquote> <p>…any functions and classes defined by the executed code are not guaranteed to work correctly after a <code>runpy</code> function has returned.</p> </blockquote> <p>What does that mean in practice? If they functioned normally during <code>runpy</code> execution, what can happen after <code>runpy</code> returns to make them go awry?</p>
<python><python-import><runpy>
2023-07-16 14:11:03
0
3,525
Kodiologist
76,698,680
3,489,155
Curl works but python requests doesnt (curl gives 304 and 200, requests a 403). Datadome, Cloudflare?
<p>When I go to vinted.nl a cookie is set. This allows me to do an api call in the browser and i can also do it in curl, but not using python requests. I am also wondering if this is because they use <a href="https://datadome.co/products/" rel="nofollow noreferrer">Datadome</a> to prevent certain http requests? Or is it just a mistake in my python requests code? Or is it CloudFlare causing this?</p> <p>I've tried VPN, home network, work network etc. Always this response when i use python requests, but when i use curl or postman i do get a correct response from the api.</p> <p>This works:</p> <pre class="lang-bash prettyprint-override"><code>curl 'https://www.vinted.nl/api/v2/languages' \ -H 'cookie: anon_id=2ec2c37b-7d7a-4e65-b010-f9779852300c; v_udt=dFpFa0JZbDhLcnpXTzBMRGNHQ1Qwa3RGZm1vNFg0aVhOM29WTmc9PS0tVXIrVEtZRDNhMFdVMnhnbS0tVE1qVVVUeHRFMEk3LzVESlVwUEZ0UT09; v_sid=2e6ae0379a464a29cd97ead68aae344f; ab.optOut=This-cookie-will-expire-in-2024; _pbjs_userid_consent_data=7944749324711140; __cf_bm=dYupWIvIxLP6czwXium_JL.Sa1ALZDQydFWupYQS2lc-1689514518-0-Aev5HXwCkVwTwm5ecWnXi203ANDsvXiys1gB77le1YfP7/taQfDKbSTZadENhutigSewOGb98KaDPQrzXAIwJQYsYnIhckhdrhgaUdvJ3pkogtE6Jwxqiy2dZrbksApOrA==; viewport_size=374; _vinted_fr_session=b1psTUhzYXE0cjEwMGw4ck9CNWlVeEVtcG5kRTRES1dneHE0c3pEOEtxbUxNM0ZpTFdSS0NpZDdBdSs0a0FnR0RsZmtRL25wbDJBNjV0NFBKZzkwTWhBQzB4bndtNEhsWUFGVEpHM2xYRkY2K2ozcEhsUVNDdGgraHJBdlZVSVlRNUc0WHRHb0tidEFLQmI3NFovVEVTQUtDWnJvNkFKdlloVTRrL01UdjU3SW9vdWxmT3Y5RG12dTYvNGNMQmtxdkdyTHRMdUZuYWc0VW1vdGJYZGZydnFrbURUZFBHa2Z1b040VHM2WXpGT0dvbzJNZEFmY3FTYWVXcFR5OS9BYXZuMFU1NFpLTjY3WW83QlBlTjVNL0pDWm5WTXVoRmQ3Zm5Obmh3SjdsOTdrTU5rWjd5MGNydFlBVVJ1RmJjKzhFZkNEMy81MEoyeDB2Zm5kdGRMcmMzaElYSlkyNW9nTjZWRks2VXpjUVp2WW9TY3dDOWFtVnNNVDBabHhzZXhvZS9HQ2p4NTh6VHdKTWhCajVpSlRZQUlZdXBlZXVEUFlCaSt1ejU4U1pLUTNMMVNiTmR4ZEdBa1RKMDBLTUVJV0JrYkdmaStoN3BEcWNSWWgwdCttNE1Gd0FOSG9aeS9mRTFRZmhSaStZN3A5TXhiOXJjdE5LWWxPNzBBK29ydHl5MDhDbEd6RlU5OVJLYS95cVBNLzhnRWRjRlV0U00vL3RzYVZjdGVlY1dWTVl1cURLa1BjWnFabm5Ga01vUUNOYzMxUTRua3lyKyt3d2c1SlR5SU1KS3UvT3N3YUxsYzUzWURXQy95Q2V6TUpXeE1hdXk5eUR5dGFUSWZpYStLeEZLcU13NHBFcW9CT2d0VEZMWGZQbjdDMnFMV21FMk5WRmRxclhGYWlYaFNxa0lQeW9OYXpQSmpjVGQ5bGx5WmhaUGN0NjMxVmRNUDViTWE2ZnJ1bUlhNkh0R09FeCtJSCtrMERrTnVoRGFJWkhPc1JLa2x4QUlyb1dwYk1wSWJmNEM1ZGFSQlNVaGs2QndYRnBZZC90Z29ZNTZ2UXZVWWVHWFg1TVA3ZDY2RDFhbzJjKzVKMU04d0JyWEZQWUtsdlpFanAwRSt1R0FiR0EwTklCeDJyM0Mwc25LUktTMzRXNU1VaU45RGJweWdPNHJyUGx3UkxUenJ5Sy9PcndZb1JBemhqWUJUZTl4bGJadGtWUjEzSHRYNjRodkNETU9MS1ZTWXBkUTdQQ21OdDdTdWMvNzZLazRQY0ZiZlJpRXFjVHFTQWZJZ3B0RXdCS2dTTWRvb0J4RUFhTzZ2cFBKM0JpNFpNZnpValFYZ29va0FtRGgvZVc0VWhCNkd5aGFSVXJNVUZmRDEwVmNxbkMwU05QeW8vSXVpV3AvOER3cEd4Kzk5K0tISndNWkZJTzFpRGVGQXJVZmFxd1lpb1c0ZFllakUzYVNVQmswUDFzVFNRNmNDVkFYRUVRWjlPTnY2QXN0Zmw0MC94S3Ewd0JOR2gyNCtONjhQNnVtOXNodi9TbThLSUhhbEduM1h5N0IxZjg0UUh0NDFrMHhvejJkZUtKVHBUQ3hjdk1DST0tLVJnaVJLemdFamhpZ1pZQWphd3dpaUE9PQ%3D%3D--3c0df38decfa6be41b27f65b0f8073cf25f84a48; datadome=2~IXr6AtVrQ0uioqk1ZON1BWpEibj33CUCIOS8wuwAYvBWYjeE60K14p5Njb3e4VqYk2k3NOFnLFTDgRwSX4fC9dCfPRXpwgksoLXck2Y56oUZ2yK~nbLHpZdGyOnZh4; OptanonConsent=isGpcEnabled=0&amp;datestamp=Sun+Jul+16+2023+15%3A49%3A51+GMT%2B0200+(Central+European+Summer+Time)&amp;version=202305.1.0&amp;browserGpcFlag=0&amp;isIABGlobal=false&amp;consentId=2ec2c37b-7d7a-4e65-b010-f9779852300c&amp;hosts=&amp;interactionCount=0&amp;landingPath=https%3A%2F%2Fwww.vinted.nl%2F&amp;groups=C0001%3A1%2CC0002%3A0%2CC0003%3A0%2CC0004%3A0%2CSTACK42%3A0%2CC0015%3A0; _dd_s=rum=0&amp;expire=1689516288792' </code></pre> <br> I saw that curl sets some additional default headers, so i added those also to my python request: <pre class="lang-bash prettyprint-override"><code>&gt; GET /api/v2/languages HTTP/2 &gt; Host: www.vinted.nl &gt; user-agent: curl/7.88.1 &gt; accept: */* &gt; cookie: anon_id=2ec2c37b-7d7a-4e65-b010-f9779852300c etc etc </code></pre> <p>However when i try this with python requests, I get a 403:</p> <pre class="lang-py prettyprint-override"><code>import requests cookie = &quot;anon_id=2ec2c37b-7d7a-4e65-b010-f9779852300c; v_udt=dFpFa0JZbDhLcnpXTzBMRGNHQ1Qwa3RGZm1vNFg0aVhOM29WTmc9PS0tVXIrVEtZRDNhMFdVMnhnbS0tVE1qVVVUeHRFMEk3LzVESlVwUEZ0UT09; v_sid=2e6ae0379a464a29cd97ead68aae344f; ab.optOut=This-cookie-will-expire-in-2024; _pbjs_userid_consent_data=7944749324711140; __cf_bm=dYupWIvIxLP6czwXium_JL.Sa1ALZDQydFWupYQS2lc-1689514518-0-Aev5HXwCkVwTwm5ecWnXi203ANDsvXiys1gB77le1YfP7/taQfDKbSTZadENhutigSewOGb98KaDPQrzXAIwJQYsYnIhckhdrhgaUdvJ3pkogtE6Jwxqiy2dZrbksApOrA==; viewport_size=374; _vinted_fr_session=b1psTUhzYXE0cjEwMGw4ck9CNWlVeEVtcG5kRTRES1dneHE0c3pEOEtxbUxNM0ZpTFdSS0NpZDdBdSs0a0FnR0RsZmtRL25wbDJBNjV0NFBKZzkwTWhBQzB4bndtNEhsWUFGVEpHM2xYRkY2K2ozcEhsUVNDdGgraHJBdlZVSVlRNUc0WHRHb0tidEFLQmI3NFovVEVTQUtDWnJvNkFKdlloVTRrL01UdjU3SW9vdWxmT3Y5RG12dTYvNGNMQmtxdkdyTHRMdUZuYWc0VW1vdGJYZGZydnFrbURUZFBHa2Z1b040VHM2WXpGT0dvbzJNZEFmY3FTYWVXcFR5OS9BYXZuMFU1NFpLTjY3WW83QlBlTjVNL0pDWm5WTXVoRmQ3Zm5Obmh3SjdsOTdrTU5rWjd5MGNydFlBVVJ1RmJjKzhFZkNEMy81MEoyeDB2Zm5kdGRMcmMzaElYSlkyNW9nTjZWRks2VXpjUVp2WW9TY3dDOWFtVnNNVDBabHhzZXhvZS9HQ2p4NTh6VHdKTWhCajVpSlRZQUlZdXBlZXVEUFlCaSt1ejU4U1pLUTNMMVNiTmR4ZEdBa1RKMDBLTUVJV0JrYkdmaStoN3BEcWNSWWgwdCttNE1Gd0FOSG9aeS9mRTFRZmhSaStZN3A5TXhiOXJjdE5LWWxPNzBBK29ydHl5MDhDbEd6RlU5OVJLYS95cVBNLzhnRWRjRlV0U00vL3RzYVZjdGVlY1dWTVl1cURLa1BjWnFabm5Ga01vUUNOYzMxUTRua3lyKyt3d2c1SlR5SU1KS3UvT3N3YUxsYzUzWURXQy95Q2V6TUpXeE1hdXk5eUR5dGFUSWZpYStLeEZLcU13NHBFcW9CT2d0VEZMWGZQbjdDMnFMV21FMk5WRmRxclhGYWlYaFNxa0lQeW9OYXpQSmpjVGQ5bGx5WmhaUGN0NjMxVmRNUDViTWE2ZnJ1bUlhNkh0R09FeCtJSCtrMERrTnVoRGFJWkhPc1JLa2x4QUlyb1dwYk1wSWJmNEM1ZGFSQlNVaGs2QndYRnBZZC90Z29ZNTZ2UXZVWWVHWFg1TVA3ZDY2RDFhbzJjKzVKMU04d0JyWEZQWUtsdlpFanAwRSt1R0FiR0EwTklCeDJyM0Mwc25LUktTMzRXNU1VaU45RGJweWdPNHJyUGx3UkxUenJ5Sy9PcndZb1JBemhqWUJUZTl4bGJadGtWUjEzSHRYNjRodkNETU9MS1ZTWXBkUTdQQ21OdDdTdWMvNzZLazRQY0ZiZlJpRXFjVHFTQWZJZ3B0RXdCS2dTTWRvb0J4RUFhTzZ2cFBKM0JpNFpNZnpValFYZ29va0FtRGgvZVc0VWhCNkd5aGFSVXJNVUZmRDEwVmNxbkMwU05QeW8vSXVpV3AvOER3cEd4Kzk5K0tISndNWkZJTzFpRGVGQXJVZmFxd1lpb1c0ZFllakUzYVNVQmswUDFzVFNRNmNDVkFYRUVRWjlPTnY2QXN0Zmw0MC94S3Ewd0JOR2gyNCtONjhQNnVtOXNodi9TbThLSUhhbEduM1h5N0IxZjg0UUh0NDFrMHhvejJkZUtKVHBUQ3hjdk1DST0tLVJnaVJLemdFamhpZ1pZQWphd3dpaUE9PQ%3D%3D--3c0df38decfa6be41b27f65b0f8073cf25f84a48; datadome=2~IXr6AtVrQ0uioqk1ZON1BWpEibj33CUCIOS8wuwAYvBWYjeE60K14p5Njb3e4VqYk2k3NOFnLFTDgRwSX4fC9dCfPRXpwgksoLXck2Y56oUZ2yK~nbLHpZdGyOnZh4; OptanonConsent=isGpcEnabled=0&amp;datestamp=Sun+Jul+16+2023+15%3A49%3A51+GMT%2B0200+(Central+European+Summer+Time)&amp;version=202305.1.0&amp;browserGpcFlag=0&amp;isIABGlobal=false&amp;consentId=2ec2c37b-7d7a-4e65-b010-f9779852300c&amp;hosts=&amp;interactionCount=0&amp;landingPath=https%3A%2F%2Fwww.vinted.nl%2F&amp;groups=C0001%3A1%2CC0002%3A0%2CC0003%3A0%2CC0004%3A0%2CSTACK42%3A0%2CC0015%3A0; _dd_s=rum=0&amp;expire=1689516288792&quot; headers = { &quot;Host&quot;: &quot;www.vinted.nl&quot;, &quot;User-Agent&quot;: &quot;curl/7.88.1&quot;, &quot;Accept-Encoding&quot;: None, &quot;Connection&quot;: None, &quot;accept&quot;: &quot;*/*&quot;, &quot;cookie&quot;: cookie, } url = &quot;https://www.vinted.nl/api/v2/languages&quot; response = requests.get(url=url, headers=headers) print(response) </code></pre> <p>The cookie probably expires, so you probably have to get the cookie value from your browser developer tools if you want to try my code.</p> <p>This is a screenshot of how i get the cookie using Chrome dev tools: <a href="https://i.sstatic.net/Rdm6ym.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Rdm6ym.png" alt="chrome dev tools Copy as Curl vinted.nl" /></a></p> <p>response.status_code: 403</p> <p>response.text:</p> <pre><code> &lt;h1&gt;Access denied&lt;/h1&gt; &lt;p&gt;You do not have access to www.vinted.nl.&lt;/p&gt;&lt;p&gt;The site owner may have set restrictions that prevent you from accessing the site.&lt;/p&gt; &lt;ul class=&quot;cferror_details&quot;&gt; &lt;li&gt;Ray ID: 7e90b3ed3aa9b8c6&lt;/li&gt; &lt;li&gt;Timestamp: 2023-07-19 05:53:13 UTC&lt;/li&gt; &lt;li&gt;Your IP address: 86.etc&lt;/li&gt; &lt;li class=&quot;XXX_no_wrap_overflow_hidden&quot;&gt;Requested URL: www.vinted.nl/api/v2/languages &lt;/li&gt; &lt;li&gt;Error reference number: 1020&lt;/li&gt; &lt;li&gt;Server ID: FL_521F90&lt;/li&gt; &lt;li&gt;User-Agent: Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Mobile Safari/537.36&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>response.headers</p> <pre><code>{'Date': 'Wed, 19 Jul 2023 05:53:13 GMT', 'Content-Type': 'text/html; charset=UTF-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'X-Frame-Options': 'SAMEORIGIN', 'Referrer-Policy': 'same-origin', 'Cache-Control': 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'Expires': 'Thu, 01 Jan 1970 00:00:01 GMT', 'Set-Cookie': '__cf_bm=LPhOJ80GUwCYRjFvS6m.8i.7NVl_YXcuEJufH5WHhrQ-1689745993-0-AWu4bkuqNL4hf1bx/IwLfM/RZY9dzgtyBMXq6m/gLv+s+nUHb1Lbc5Cw3/XPcVX9OnUAQURGbclo/OI7TyglbdEdVQr7S5r0Yq334L15kkKx; path=/; expires=Wed, 19-Jul-23 06:23:13 GMT; domain=.vinted.nl; HttpOnly; Secure; SameSite=None', 'Vary': 'Accept-Encoding', 'Server': 'cloudflare', 'CF-RAY': '7e90b3ed3aa9b8c6-AMS', 'Content-Encoding': 'gzip'} </code></pre> <p>response.request.headers:</p> <pre><code>{ 'User-Agent': 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Mobile Safari/537.36', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'host': 'www.vinted.nl', 'Cache-Control': 'no-cache', 'cookie': '_vinted_fr_session=MElmUmdUcmNOb etc etc'} </code></pre>
<python><python-3.x><curl><python-requests><cloudflare>
2023-07-16 14:06:45
3
13,022
Sander van den Oord
76,698,670
1,303,562
Fixture not found although it exist in conftest.py
<p>This is my test class:</p> <pre><code>import pytest class TestInstallation: def test_some(self, fix_test): print(fix_test) </code></pre> <p><strong>conftest.py</strong></p> <pre><code>import pytest @pytest.fixture() def fix_test(): return 123 </code></pre> <p>And when I try to run my test I received this <code>error</code>:</p> <blockquote> <pre><code>&gt; def test_install(self, fix_test): E fixture 'fix_test' not found &gt; &gt; available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, &gt; record_property, record_testsuite_property, record_xml_attribute, &gt; recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory &gt; &gt; use 'pytest --fixtures [testpath]' for help on them. </code></pre> </blockquote> <p>When I put my <code>fixture</code> inside my test class this works fine.</p> <p>What I am doing wrong ?</p>
<python><pytest><fixtures>
2023-07-16 14:03:33
0
721
Dana Yeger
76,698,668
4,386,557
tmpfs disk usage : python vs bash
<p>I have a ramdrive created through fstab as</p> <pre><code>tmpfs /mnt/ram tmpfs defaults,size=2048M 0 0 </code></pre> <p>This space filled up to 86% so I deleted some large files.</p> <p>Now the python view and the linux view differ on this disk usage. It looks like the python view does not account for the deleted files.</p> <pre><code>&gt;&gt;&gt; from os import system &gt;&gt;&gt; import psutil &gt;&gt;&gt; import shutil &gt;&gt;&gt; cmd = 'du -s /mnt/ram/' &gt;&gt;&gt; system(cmd) 632 /mnt/ram/ 0 &gt;&gt;&gt; psutil.disk_usage('/mnt/ram/') sdiskusage(total=2147483648, used=1862307840, free=285175808, percent=86.7) &gt;&gt;&gt; shutil.disk_usage('/mnt/ram/') usage(total=2147483648, used=1862500352, free=284983296) </code></pre>
<python><du>
2023-07-16 14:02:57
0
1,239
Stephen Boston
76,698,632
1,938,552
How to access PEP-526 local variable annotations in Python?
<p>I made a variable annotation of a local variable:</p> <pre><code>def a(): x: int = 1 </code></pre> <p>But the annotations dict is empty:</p> <pre><code>&gt; a.__annotations__ {} </code></pre> <p>Same when I use <code>inspect.get_annotations()</code> or <code>typing.get_type_hints()</code>. How can I access the annotation? Is this feature implemented at all?</p> <p>I'm using Python 3.10.7.</p>
<python><python-typing>
2023-07-16 13:56:51
3
1,059
haael
76,698,515
15,547,292
Difference between `multiprocessing.shared_memory` and anonymous mmap?
<p>What is the technical difference between multiprocessing SharedMemory and an anonymous mmap? Is one better than the other?</p>
<python><shared-memory><mmap>
2023-07-16 13:29:18
0
2,520
mara004
76,698,405
8,523,868
Unable to post files to Telegram from pycharm
<p>I searched google Bard and ChatGPT and found the above code. I am trying to send files from my directory To telegram to my channel It's is showing the below error.</p> <p>Below configuration: Windows 11 OS and pycharm as the IDE. Installed selenium and telegram in the pycharm addon</p> <p>My code:-</p> <pre><code>Import os From telegram import Bot bot=Bot(token=&quot;xxxxxx&quot;) #Replace'YOUR_TELEGRAM_TOKEN'withyouractualTelegrambottoken TOKEN='xxxx' #Replace'YOUR_CHAT_ID'withyouractualTelegramchatID CHAT_ID='xxxx' #Directorypathcontainingthefilestoupload DIRECTORY_PATH='E:\\upload\\2017' defupload_files_to_telegram(): bot=Bot(token=TOKEN) forfilenameinos.listdir(DIRECTORY_PATH): file_path=os.path.join(DIRECTORY_PATH,filename) ifos.path.isfile(file_path): withopen(file_path,'rb')asfile: bot.send_document(chat_id=CHAT_ID,document=file) print(f&quot;Uploaded{filename}successfully.&quot;) </code></pre> <p>Error Message:-</p> <pre><code>Traceback (most recent call last): File &quot;E:\vss coding\Dayscoding100\venv\telegramupload.py&quot;, line 2, in &lt;module&gt; from telegram import Bot ImportError: cannot import name 'Bot' from 'telegram' (E:\vss coding\Dayscoding100\venv\lib\site-packages\telegram\__init__.py) </code></pre> <p>Process finished with exit code 1</p>
<python><selenium-webdriver><pycharm><telegram><python-telegram-bot>
2023-07-16 13:04:01
1
911
vivek rajagopalan
76,698,367
4,534
How to visualize a Panda with a lot of columns interactively?
<p><a href="https://i.sstatic.net/rxqlx.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rxqlx.jpg" alt="plotting a panda" /></a></p> <p>I have a panda with a 200+ columns, that I plot currently with</p> <pre><code>ranked.plot.line(figsize=(20,10),title='Rank Over Time') </code></pre> <p>I would like to interactively look at one or several at a time. Ideally tracing the line for exact values. How can I do this in my Jupyter Notebook with my dataframe please?</p>
<python><pandas>
2023-07-16 12:54:18
1
11,105
hendry
76,698,314
1,172,907
How to display a picture completely in tkinter?
<p>I tried many approaches to no avail (commented lines). Any other ideas?</p> <p><img src="https://i.imgur.com/bu4HDX0.png" alt="screenshot" title="Screenshot" /></p> <p>Get the picture first via curl <code>curl https://i.imgur.com/VYdf3vp.png --output pic.png</code></p> <pre class="lang-py prettyprint-override"><code>from tkinter import Tk, Label, PhotoImage,Canvas # Create the main window window = Tk() window.title(&quot;Image Viewer&quot;) window.geometry(&quot;600x600&quot;) # Load and display the image # curl https://i.imgur.com/VYdf3vp.png --output pic.png image = PhotoImage(file=&quot;./pic.png&quot;) label = Label(window, image=image) # Doesn't help # label = Label(window, image=image, anchor=&quot;nw&quot;, padx=10, pady=10) label.pack() # Doesn't help # label.config(width=image.width(), height=image.height()) # Doesn't help # desired_width = image.width() # desired_height = image.height() # label.config(width=desired_width, height=desired_height) # Doesn't help # label.place(x=0, y=0, width=desired_width, height=desired_height) # Doesn't help # canvas = Canvas(window, width=image.width(), height=image.height()) # canvas.pack() # canvas.create_image(0, 0, anchor=&quot;nw&quot;, image=image) # Start the tkinter event loop window.mainloop() </code></pre>
<python><tkinter>
2023-07-16 12:42:07
0
605
jjk
76,698,128
4,409,163
How serialize a Gtk.Textview buffer in Gtk4
<p>I’m working on a flatpak python+gtk4 application which is, roughly speaking, a text editor, and I need a way to save the contents of a TextView including all the tags.</p> <p>What I know: In Gtk 4, TextView buffer no longer has built-in serialization methods. To seralilize the contents of the buffer it is necessary to create my own serializer, for that I must use <code>gdk_content_register_serializer</code> (and the corresponding one to create the deserializer). Something like that:</p> <pre><code>def _r_serializer(self): Gdk.content_register_serializer(Gtk.TextBuffer, &quot;text/plain;charset=utf-8&quot;, self._serialize_text, None, None) </code></pre> <p>What I don’t know: While the use of <code>gdk_content_register_serializer</code> is fairly straightforward and simple, the same is not true about <code>GdkContentSerializeFunc</code> (<code>self._serialize_text</code>). From the documentation, I couldn’t understand what this function should be exactly. I tried looking at how Textbuffer’s serializer worked in GTk3, but I’m fairly new to working with Gtk/Gdk and don’t fully understand the workflow, and besides, my knowledge of C is limited.</p> <p>What I need: I would like a minimal code example (python would be nice, but it can be any language) of a <code>GdkContentSerializeFunc</code> that serializes at least one tag (italics, for example) to plain text, so that I can use it as a basis for build my own serializer.</p>
<python><serialization><gtk4><gtktextview>
2023-07-16 11:57:06
0
544
Kripto
76,698,069
719,001
Speed up call to secret manager in bash
<p>I have a bash script in each environment that with it I set up all the env variables before each script. Recently changed the script and added a python script that gets a list of aws secrets and store them in env variables. So in <code>env.sh</code> instead of:</p> <pre><code>pass=1234 </code></pre> <p>now I have:</p> <pre><code>pass=$(get-key.py dev/pass) </code></pre> <p><code>get-key.py</code> (which was based of <a href="https://docs.aws.amazon.com/code-library/latest/ug/python_3_secrets-manager_code_examples.html" rel="nofollow noreferrer">this</a>) runs in about 0.4s which make all my scripts 0.4s slower (and much more if it is a script calling a script etc...). I'm open to hear how can I make <code>env.sh</code> faster while keeping security, caching is one thing that comes into mind. Not sure how though.</p>
<python><linux><bash><caching>
2023-07-16 11:41:30
2
2,677
Nir
76,697,938
3,423,825
How to get the column with the lowest number of na cells in Pandas?
<p>I have a dataframe with multiple columns and some of them has a lot of <code>nan</code>. How can I select the column with the lowest number of <code>nan</code> cells ?</p>
<python><pandas>
2023-07-16 11:10:44
1
1,948
Florent
76,697,883
16,454,377
delta packages installation on local with pyspark: ivy-cache file not found
<p>I am triying to use delta format so trying this from this site <a href="https://docs.delta.io/0.8.0/quick-start.html" rel="nofollow noreferrer">delta lake</a>. On cmd <code>pyspark --packages io.delta:delta-core_2.12:0.8.0 --conf &quot;spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension&quot; --conf &quot;spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog&quot;</code> but giving error like.</p> <p><a href="https://i.sstatic.net/FwGIn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FwGIn.png" alt="this is the error" /></a></p> <p>I tried manually put jar file but not working.</p>
<python><pyspark><delta-lake>
2023-07-16 10:56:07
0
469
Avinash
76,697,815
10,848,158
How can I listen to the onFieldChange event in Odoo 16 using JavaScript?
<p>I would like to listen for the onChange event of a field in Odoo 16 using JavaScript. I have attempted the following code snippets, but they did not yield the desired results.</p> <p>my_module/static/src/js/on_field_changes.js</p> <pre><code>odoo.define('my_module.on_field_changes', function (require) { &quot;use strict&quot;; const fieldRegistry = require('web.field_registry'); const { FieldChar } = require('web.basic_fields'); const onchange_widget = FieldChar.extend({ _onFieldChanged(ev) { console.log('========= &gt; &gt; &gt; &gt; Hello') this._super.apply(this, arguments); }, }); fieldRegistry.add('onchange_widget', onchange_widget); }); </code></pre> <p>In form view:</p> <pre><code>&lt;field name=&quot;father_name&quot; widget=&quot;onchange_widget&quot;/&gt; </code></pre> <p>In manifest.py:</p> <pre><code>'assets': { 'web.assets_backend': [ 'my_module/static/src/js/on_field_changes.js', ] } </code></pre> <p>In addition, I have attempted several other code snippets, but unfortunately, none of them proved successful either.</p>
<javascript><python><python-3.x><odoo><odoo-16>
2023-07-16 10:38:53
0
789
Habib Mhamadi
76,697,781
2,173,773
pytest-qt: using qtbot gives segmentation fault
<p>I am on Ubuntu 22.04, using <a href="https://python-poetry.org/" rel="nofollow noreferrer">Poetry</a>, Python 3.10, <a href="https://pypi.org/project/PyQt6/" rel="nofollow noreferrer">PyQt6</a>, and <a href="https://docs.pytest.org/en/stable/" rel="nofollow noreferrer">pytest</a> with the <a href="https://pytest-qt.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">pytest-qt</a> plugin. When I run a test with pytest using the <a href="https://pytest-qt.readthedocs.io/en/latest/reference.html#module-pytestqt.qtbot" rel="nofollow noreferrer"><code>qtbot</code> fixture</a> I get a segmentation fault. If I remove the <code>qtbot</code> fixture from the test file, it works fine. Here is a minimal example (my real test case is more complicated):</p> <pre><code>$ poetry new --src myproject $ cd myproject $ poetry add pyqt6 $ poetry add --group=dev pytest $ poetry add --group=dev pytest-qt $ cat &lt;&lt;'END' &gt; pytest.ini [pytest] qt_api=pyqt6 END $ cat &lt;&lt;'END' &gt; src/myproject/main.py from PyQt6.QtWidgets import QApplication def qapp(app: QApplication) -&gt; None: # This is the function that we will test with pytest app.quit() END $ cat &lt;&lt;'END' &gt; tests/test_main.py # This is the test file import pytest from PyQt6.QtWidgets import QApplication import myproject.main from typing import Any QtBot = Any # Missing type hints here def test_app(qtbot: QtBot) -&gt; None: app = QApplication([]) myproject.main.qapp(app) assert 1 == 1 END $ poetry install $ poetry shell $ pytest ============================================================================ test session starts ============================================================================ platform linux -- Python 3.10.4, pytest-7.4.0, pluggy-1.2.0 PyQt6 6.5.1 -- Qt runtime 6.5.1 -- Qt compiled 6.5.1 rootdir: /home/hakon/test/python/pytest-qt/qtbot/myproject plugins: qt-4.2.0 collected 1 item tests/test_main.py Fatal Python error: Segmentation fault Current thread 0x00007f24e2fc1740 (most recent call first): File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/python.py&quot;, line 194 in pytest_pyfunc_call File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_callers.py&quot;, line 80 in _multicall File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_manager.py&quot;, line 112 in _hookexec File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_hooks.py&quot;, line 433 in __call__ File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/python.py&quot;, line 1788 in runtest File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/runner.py&quot;, line 169 in pytest_runtest_call File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_callers.py&quot;, line 80 in _multicall File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_manager.py&quot;, line 112 in _hookexec File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_hooks.py&quot;, line 433 in __call__ File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/runner.py&quot;, line 262 in &lt;lambda&gt; File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/runner.py&quot;, line 341 in from_call File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/runner.py&quot;, line 261 in call_runtest_hook File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/runner.py&quot;, line 222 in call_and_report File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/runner.py&quot;, line 133 in runtestprotocol File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/runner.py&quot;, line 114 in pytest_runtest_protocol File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_callers.py&quot;, line 80 in _multicall File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_manager.py&quot;, line 112 in _hookexec File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_hooks.py&quot;, line 433 in __call__ File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/main.py&quot;, line 349 in pytest_runtestloop File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_callers.py&quot;, line 80 in _multicall File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_manager.py&quot;, line 112 in _hookexec File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_hooks.py&quot;, line 433 in __call__ File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/main.py&quot;, line 324 in _main File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/main.py&quot;, line 270 in wrap_session File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/main.py&quot;, line 317 in pytest_cmdline_main File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_callers.py&quot;, line 80 in _multicall File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_manager.py&quot;, line 112 in _hookexec File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/pluggy/_hooks.py&quot;, line 433 in __call__ File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/config/__init__.py&quot;, line 166 in main File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/lib/python3.10/site-packages/_pytest/config/__init__.py&quot;, line 189 in console_main File &quot;/home/hakon/.cache/pypoetry/virtualenvs/myproject-rfHFWcwh-py3.10/bin/pytest&quot;, line 8 in &lt;module&gt; Extension modules: PyQt6.QtCore, PyQt6.QtGui, PyQt6.QtWidgets, PyQt6.QtTest (total: 4) Segmentation fault (core dumped) </code></pre>
<python><pytest><python-poetry><pyqt6><pytest-qt>
2023-07-16 10:28:37
0
40,918
Håkon Hægland
76,697,684
1,255,819
How to force pip to install latest requirement.txt versions without use cache?
<p>I have this requirements.txt</p> <pre><code>esphome tornado esptool pyparsing &gt;=3.0 </code></pre> <p>When I call it with <code>pip install -r requirements.txt</code>, it says:</p> <blockquote> <p>Requirement already satisfied: esphome in /usr/local/lib/python3.11/site-packages (from -r requirements.txt (line 1)) (2023.6.4)</p> </blockquote> <p>But if I see on searching on <a href="https://pypi.org/search/?q=esphome" rel="nofollow noreferrer">https://pypi.org/search/?q=esphome</a> I see: <a href="https://i.sstatic.net/z5Wbp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/z5Wbp.png" alt="newer esphome version" /></a></p> <p>How can I let <code>pip</code> known that a new version exists? As workaround I am changing the dependency manually but I always want to use the latest versions of <code>esphome</code>.</p> <p>I already tried the <code>--no-cache-dir</code> flag but it does not help.</p>
<python><pip><requirements.txt>
2023-07-16 10:04:41
1
7,101
distante
76,697,681
5,733,709
Retrieval QA with custom prompt with multiple inputs and memory
<p>I am trying to provide a custom prompt for doing Q&amp;A in langchain.</p> <p>I wasn't able to do that with RetrievalQA as it was not allowing for multiple custom inputs in custom prompt.I have loaded a sample pdf file, chunked it and stored the embeddings in vector store which I am using as a retriever and passing to Retreival QA chain.</p> <p>How do I add <strong>memory + custom prompt with multiple inputs to Retrieval QA</strong> in langchain?</p> <pre><code>import openai import numpy as np import pandas as pd import os from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.llms import OpenAI from langchain.chains import RetrievalQA, ConversationalRetrievalChain,RetrievalQAWithSourcesChain from langchain.chains.qa_with_sources import load_qa_with_sources_chain from langchain.chains.question_answering import load_qa_chain from langchain.document_loaders import UnstructuredFileLoader from langchain.prompts import PromptTemplate from langchain.document_loaders import UnstructuredExcelLoader loader = UnstructuredFileLoader(&quot;../Test.pdf&quot;, mode=&quot;elements&quot;) documents = loader.load() from langchain.docstore.document import Document import json # Opening JSON file with open('Customer_profile.json', 'r') as openfile: # Reading from json file json_object = json.load(openfile) cName=json_object['Customer_Name'] cState=json_object['Customer_State'] cGen=json_object['Customer_Gender'] cProfile = &quot;Customer's Name is &quot;+cName+&quot;\nCustomer's Resident State is &quot;+cState+&quot;\nCustomer's Gender is &quot;+cGen print(cProfile) # cProfileDoc = Document(page_content=cProfile, metadata={&quot;source&quot;: &quot;customerProfile.json&quot;}) # documents.insert(0, cProfileDoc) prompt_template = &quot;&quot;&quot;You are a Chat customer support agent. Address the customer as Dear Mr. or Miss. depending on customer's gender followed by Customer's First Name. Use the following customer related information (delimited by &lt;cp&gt;&lt;/cp&gt;) context (delimited by &lt;ctx&gt;&lt;/ctx&gt;) and the chat history (delimited by &lt;hs&gt;&lt;/hs&gt;) to answer the question at the end: If you don't know the answer, just say that you don't know, don't try to make up an answer. Below are the details of the customer:\n &lt;cp&gt; Customer's Name: {Customer_Name} Customer's Resident State: {Customer_State} Customer's Gender: {Customer_Gender} &lt;/cp&gt; &lt;ctx&gt; {context} &lt;/ctx&gt; &lt;hs&gt; {history} &lt;/hs&gt; Question: {query} Answer: &quot;&quot;&quot; #print(prompt_template.format(cProfile)) PROMPT = PromptTemplate( template=prompt_template, input_variables=[&quot;history&quot;,&quot;context&quot;, &quot;query&quot;,&quot;Customer_Name&quot;,&quot;Customer_State&quot;,&quot;Customer_Gender&quot;] ) text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) #embeddings = OpenAIEmbeddings() from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings embeddings = SentenceTransformerEmbeddings(model_name=&quot;all-MiniLM-L6-v2&quot;) vectorDB = Chroma.from_documents(texts,embeddings) from langchain.memory import ConversationBufferMemory memory = ConversationBufferMemory(memory_key=&quot;history&quot;,input_key=&quot;query&quot; ,output_key='answer',return_messages=True) qa = RetrievalQA.from_chain_type( llm=OpenAI(), chain_type='stuff', retriever=vectorDB.as_retriever(), verbose=True, chain_type_kwargs={ &quot;verbose&quot;: True, &quot;prompt&quot;: PROMPT, &quot;memory&quot;: memory } ) qa({&quot;query&quot;: &quot;who's the client's friend?&quot;,&quot;Customer_Gender&quot;:&quot;Male&quot;,&quot;Customer_State&quot;:&quot;New York&quot;,&quot;Customer_Name&quot;:&quot;Aaron&quot;}) </code></pre>
<python><openai-api><langchain><py-langchain>
2023-07-16 10:04:12
2
786
Jason
76,697,678
15,002,748
Extract google reviews from google map
<pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys import time # Specify the URL of the business page on Google Maps url = 'https://www.google.com/maps/place/FRUYO+MALAYSIA/@2.2916032,111.8210233,17z/data=!4m8!3m7!1s0x31f77f4fb024a7e1:0x468c52dc9e9179c3!8m2!3d2.2916032!4d111.8210233!9m1!1b1!16s%2Fg%2F11p65htbhd?entry=ttu' # Create an instance of the Chrome driver driver = webdriver.Chrome() # Navigate to the specified URL driver.get(url) # Wait for the reviews to load wait = WebDriverWait(driver, 20) # Increased the waiting time # Scroll down to load more reviews body = driver.find_element(By.XPATH, '//body') num_reviews = len(driver.find_elements(By.CLASS_NAME, 'wiI7pd')) while True: body.send_keys(Keys.END) time.sleep(2) # Adjust the delay based on your internet speed and page loading time new_num_reviews = len(driver.find_elements(By.CLASS_NAME, 'wiI7pd')) if new_num_reviews == num_reviews: # Scroll to the top to ensure all reviews are loaded body.send_keys(Keys.HOME) time.sleep(2) break num_reviews = new_num_reviews # Wait for the reviews to load completely wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'wiI7pd'))) # Extract the text of each review review_elements = driver.find_elements(By.CLASS_NAME, 'wiI7pd') reviews = [element.text for element in review_elements] # Print the reviews print(reviews) # Close the browser driver.quit() </code></pre> <p>Hi Everyone,</p> <p>I need help in scraping the google reviews. The code above works fine, but it only scrap the first 8 reviews without scrolling to the bottom even though I already tried scroll down to load more reviews in my code but it doesn't work. Any one have any idea why is it so? Any help or advise is greatly appreciated!</p>
<python><selenium-webdriver><web-scraping>
2023-07-16 10:03:15
1
1,127
weizer
76,697,535
1,690,805
setter methods and Restricted Python
<p>I have a class &quot;MyClass&quot; with a class attribute and its methods.</p> <pre><code>class MyClass: def __init__(self): self._my_attr = None @property def my_attr(self): return self._my_attr @my_attr.setter def my_attr(self, value): self._my_attr = value def set_my_attr(self, value): self._my_attr = value </code></pre> <p>When I try to assign a value in Zope (in a Python Script, which uses Restricted Python), I get a TypeError <code>attribute-less object (assign or del)</code> when I try to assign the value with <code>=</code>.</p> <p>It also says in the traceback: <code>AttributeError: 'MyClass' object has no attribute '__guarded_setattr__'</code></p> <pre><code>obj = MyClass() obj.my_attr = 42 # error in Restricted Python obj.set_my_attr(value=42) # does work in Restricted Python </code></pre> <p>What does the error mean? Is there a way to allow setter methods for direct assignment in Restricted Python or do I have to implement a normal method to set the value?</p>
<python><setter><zope><restrictedpython>
2023-07-16 09:28:03
1
1,629
Georg Pfolz
76,697,534
13,557,319
Cleaning Latitudes and Longitudes Data
<p>I have a csv file containing Latitudes, longitudes and Date but <code>lat</code> and <code>long</code> contains some special characters like comma(,) and (\t) etc.</p> <p>CSV file look like this:</p> <pre><code>| lat | long | date | | 30.970695, | 72.482265 | 05/23/2015 | | 30.284493\t | 73.106275 | 07/01/2015 | | 30.311023\t | 73.153053 | 07/01/2015 | | 30.289273` | 73.067512 | 07/02/2015 | | 30.309319\t | 73.068774 | 07/03/2015 | </code></pre> <p>The data types are:</p> <pre><code> lat object long object date object dtype: object </code></pre> <p>I tried to remove special characters from latitude and longitude</p> <pre><code>df['lat'] = df['lat'].str.replace(r'[^\d.-]', '', regex=True) df['long'] = df['long'].str.replace(r'[^\d.-]', '', regex=True) </code></pre> <p>I want to convert lat longs into float but I noticed this result after removing special charachters.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>index</th> <th>lat</th> <th>long</th> <th>date</th> </tr> </thead> <tbody> <tr> <td>5514</td> <td>30.30116873.070213</td> <td>30.30116873.070213</td> <td>12/28/2015</td> </tr> </tbody> </table> </div> <p>lat and long values of row <code>5514</code> get merged.</p> <p>Why am I getting this behavior? How do I solve this? I am new with spatiotemporal data any recommendations and help will be appreciated.</p>
<python><pandas>
2023-07-16 09:27:47
2
342
Linear Data Structure
76,697,516
15,528,750
Debugging in VSCode Not Working because of ImportError
<p>When I launch VSCode in debug mode, I get an ImportError for <code>numpy</code>. However, I have <code>numpy</code> installed in my conda environment and was hence wondering why this error message occurs? When I only import Python built-in modules and no third-party libraries, the debug mode runs fine.</p>
<python><visual-studio-code><debugging>
2023-07-16 09:22:40
1
566
Imahn
76,697,301
8,491,363
Is the file read in import module saved in memory in Jupyter Notebook?
<p>There are a bunch of datasets that I have to import/preprocess many times.</p> <p>What I'm doing is putting all of <code>pd.read_csv()</code> inside a single <code>my_datasets.py</code> file like this:</p> <pre class="lang-py prettyprint-override"><code># my_datasets.py import pandas as pd dataset1 = pd.read_csv('file1.csv') dataset2 = pd.read_csv('file2.csv') dataset3 = pd.read_csv('file3.csv') </code></pre> <p>and then I simply import this module from Jupyter Notebook whenever I need some data.</p> <p>When I do this, on <code>EDA.ipynb</code>, am I storing dataset1, 2, 3 in RAM memory so that I don't make file IO every time I call <code>my_datasets.dataset1</code>?</p> <p>Is there any other inefficiencies that you'd like to address?</p>
<python><pandas><jupyter-notebook><io>
2023-07-16 08:19:02
1
4,040
user8491363
76,697,253
5,239,250
The second call to a tkinter dialog does not fill the list
<p>In a Python script, I display twice the same tkinter dialog.</p> <p>The first time, it's correctly filled with the value returned from <code>get_items()</code>, the second time the list is shown empty.</p> <p>Here is a simplified version of my code, that reproduces the behavior:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk class ItemSelector: def __init__(self, title='title'): self.selection = None self.root = tk.Tk() self.root.attributes('-type', 'dialog') self.root.title(title) self.root.bind('&lt;Escape&gt;', self.cancel) self.root.bind('&lt;Return&gt;', self.send) frame = tk.Frame(self.root) # we need a frame, if we want scrollbar frame.pack() items = self.get_items() self.items_tk = tk.Variable(value=items) # FIX: tk.Variable(frame, value=items) self.items_ui = tk.Listbox(frame, listvariable=self.items_tk, height=12) scrollbar = tk.Scrollbar(frame, orient=&quot;vertical&quot;) scrollbar.config(command=self.items_ui.yview) scrollbar.pack(side=&quot;right&quot;, fill=&quot;y&quot;) self.items_ui.config(yscrollcommand=scrollbar.set) self.items_ui.pack() submitButton = tk.Button(self.root, text='Submit', command=self.send) submitButton.pack() self.root.mainloop() def get_items(self): return ['a', 'b', 'c', 'd'] def cancel(self, *args): self.root.quit() self.root.withdraw() def send(self, *args): self.root.withdraw() self.root.quit() def main(): itemSelector = ItemSelector('A') itemSelector = ItemSelector('B') if __name__ == '__main__': main() </code></pre> <p>How can I get the list of items to be shown also in the second call?</p> <h2>First solution</h2> <p>Swifty's answer helped me understand and circumscribe the issue: It's because I have multiple Tk instances.</p> <p>His solution with <code>root</code> as a class variable does work, but, if I have one single root, I'd prefer to have it <em>outside</em> of the list dialog and share it with both classes. (I don't have working code for that solution but I will post if and when I get to that.)</p> <p>As a first solution, I've added a <code>#FIX</code> in the original code applying <em>TheLizzard</em>'s hints from <a href="https://stackoverflow.com/a/69062053/5239250">https://stackoverflow.com/a/69062053/5239250</a> to my code: if you have multiple Tk instances you need to always explicitly pass the Tk context when creating Tk variables!</p>
<python><tkinter>
2023-07-16 08:05:28
1
878
a.l.e
76,696,870
22,234,318
How to import variable from a root directory
<p>i have Telegram Bot project:</p> <pre><code>bot.py ----- handlers/ ----- --------- create_ticket.py </code></pre> <p>in file create_ticket.py i need import a variable &quot;bot&quot; from file bot.py</p> <p>i try</p> <pre><code>from ..bot import bot </code></pre> <p>and get an error:</p> <pre><code>ImportError: attempted relative import beyond top-level package </code></pre>
<python><import>
2023-07-16 05:52:48
1
569
jetgreen
76,696,832
1,279,318
How to send attachment on s/mime email
<p>I'm trying to send an encrypted mail, using s/mime protocol, but the mail client doesn't acknowledge the attachments, and doesn't decrypt them. I've checked some answers on stack overflow, but none of them worked for me. Please note that the encryption itself does work (see below)</p> <p>Here is my code:</p> <pre><code>import os import ssl from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from smtplib import SMTP from typing import List, Optional, Union from M2Crypto import BIO, SMIME, X509 port = 587 def send_email_by_smtp(sender: str, receiver: List[str], message: Union[bytes, str]): # getting the credentials fron evironemnt host = os.environ.get(&quot;SMTP_FQDN&quot;) user = os.environ.get(&quot;SMTP_USER_ID&quot;) password = os.environ.get(&quot;SMTP_PASSWORD&quot;) # setting up ssl context context = ssl.create_default_context() # creating an unsecure smtp connection with SMTP(host, port) as server: # securing using tls server.starttls(context=context) # authenticating with the server to prove our identity server.login(user=user, password=password) # sending a plain text email return server.sendmail(sender, receiver, message) def send_mail( *, recipient: List[str], subject: str, body: str, attachments: Optional[List[str]] = None, ): if attachments is None: attachments = [] message = MIMEMultipart() from_address = os.environ.get(&quot;FROM_ADDRESS&quot;) body_part = MIMEText(body, &quot;html&quot;) message.attach(body_part) for attachment in attachments: with open(attachment, &quot;rb&quot;) as fh: attachment_part = MIMEApplication(fh.read()) filename = os.path.basename(fh.name) attachment_part.add_header( &quot;Content-Disposition&quot;, &quot;attachment&quot;, filename=filename, Content_Transfer_Encoding=&quot;base64&quot;, Content_ID=f&quot;&lt;{filename}&gt;&quot;, Content_Type=&quot;text/csv&quot;, Content_Disposition=f&quot;attachment; filename={filename}&quot;, ) message.attach(attachment_part) # data = message.as_string() data = encrypt_message( from_address, recipient, subject, message.as_bytes(), from_key=&quot;certs/new/signer_key.pem&quot;, from_cert=&quot;certs/new/signer.pem&quot;, to_certs=[&quot;certs/new/recipient.pem&quot;], ) return send_email_by_smtp(from_address, recipient, data) def encrypt_message(from_addr, to_addrs, subject, msg, from_key, from_cert=None, to_certs=None): msg_bio = BIO.MemoryBuffer(msg) sign = from_key encrypt = to_certs p7 = None s = SMIME.SMIME() if sign: s.load_key(from_key, from_cert) if encrypt: p7 = s.sign(msg_bio, flags=SMIME.PKCS7_TEXT) else: p7 = s.sign(msg_bio, flags=SMIME.PKCS7_TEXT | SMIME.PKCS7_DETACHED) msg_bio = BIO.MemoryBuffer(msg) # Recreate coz sign() has consumed it. if encrypt: sk = X509.X509_Stack() for x in to_certs: sk.push(X509.load_cert(x)) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher(&quot;aes_256_cbc&quot;)) tmp_bio = BIO.MemoryBuffer() if sign: s.write(tmp_bio, p7) else: tmp_bio.write(msg) p7 = s.encrypt(tmp_bio) out = BIO.MemoryBuffer() out.write(f&quot;From: {from_addr}\r\n&quot;) out.write(f&quot;To: {', '.join(to_addrs)}\r\n&quot;) out.write(f&quot;Subject: {subject}\r\n&quot;) if encrypt: s.write(out, p7) else: if sign: s.write(out, p7, msg_bio, SMIME.PKCS7_TEXT) else: out.write(&quot;\r\n&quot;) out.write(msg) out.close() return out.read() if __name__ == &quot;__main__&quot;: res = send_mail(recipient=os.environ.get(&quot;TO_ADDRESS&quot;, &quot;&quot;).split(&quot;,&quot;), subject=&quot;some subject&quot;, body=&quot;some body&quot;, attachments=[__file__]) print(res) </code></pre> <p>and the results on the client :</p> <pre><code>Content-Type: multipart/mixed; boundary=&quot;===============2300897735206349356==&quot; MIME-Version: 1.0 --===============2300897735206349356== Content-Type: text/html; charset=&quot;us-ascii&quot; MIME-Version: 1.0 Content-Transfer-Encoding: 7bit some body --===============2300897735206349356== Content-Type: application/octet-stream MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=&quot;smtp_test.py&quot;; Content-Transfer-Encoding=&quot;base64&quot;; Content-ID=&quot;&lt;smtp_test.py&gt;&quot;; Content-Type=&quot;text/csv&quot;; Content-Disposition=&quot;attachment; filename=smtp_test.py&quot; aW1wb3J0IG9zCmltcG9ydCBzc2wKZnJvbSBlbWFpbC5taW1lLnRleHQgaW1wb3J0IE1JTUVUZXh0 CmZyb20gZW1haWwubWltZS5hcHBsaWNhdGlvbiBpbXBvcnQgTUlNRUFwcGxpY2F0aW9uCmZyb20g ZW1haWwubWltZS5tdWx0aXBhcnQgaW1wb3J0IE1JTUVNdWx0aXBhcnQKZnJvbSBzbXRwbGliIGlt cG9ydCBTTVRQCmZyb20gdHlwaW5nIGltcG9ydCBMaXN0LCBPcHRpb25hbCwgVW5pb24KCmZyb20g TTJDcnlwdG8gaW1wb3J0IEJJTywgU01JTUUsIFg1MDkKCnBvcnQgPSA1ODcKCgpkZWYgc2VuZF9l bWFpbF9ieV9zbXRwKHNlbmRlcjogc3RyLCByZWNlaXZlcjogTGlzdFtzdHJdLCBtZXNzYWdlOiBV bmlvbltieXRlcywgc3RyXSk6CiAgICAjIGdldHRpbmcgdGhlIGNyZWRlbnRpYWxzIGZyb24gZXZp cm9uZW1udAogICAgaG9zdCA9IG9zLmVudmlyb24uZ2V0KCJTTVRQX0ZRRE4iKQogICAgdXNlciA9 IG9zLmVudmlyb24uZ2V0KCJTTVRQX1VTRVJfSUQiKQogICAgcGFzc3dvcmQgPSBvcy5lbnZpcm9u LmdldCgiU01UUF9QQVNTV09SRCIpCgogICAgIyBzZXR0aW5nIHVwIHNzbCBjb250ZXh0CiAgICBj b250ZXh0ID0gc3NsLmNyZWF0ZV9kZWZhdWx0X2NvbnRleHQoKQoKICAgICMgY3JlYXRpbmcgYW4g dW5zZWN1cmUgc210cCBjb25uZWN0aW9uCiAgICB3aXRoIFNNVFAoaG9zdCwgcG9ydCkgYXMgc2Vy dmVyOgogICAgICAgICMgc2VjdXJpbmcgdXNpbmcgdGxzCiAgICAgICAgc2VydmVyLnN0YXJ0dGxz KGNvbnRleHQ9Y29udGV4dCkKCiAgICAgICAgIyBhdXRoZW50aWNhdGluZyB3aXRoIHRoZSBzZXJ2 ZXIgdG8gcHJvdmUgb3VyIGlkZW50aXR5CiAgICAgICAgc2VydmVyLmxvZ2luKHVzZXI9dXNlciwg cGFzc3dvcmQ9cGFzc3dvcmQpCgogICAgICAgICMgc2VuZGluZyBhIHBsYWluIHRleHQgZW1haWwK ICAgICAgICByZXR1cm4gc2VydmVyLnNlbmRtYWlsKHNlbmRlciwgcmVjZWl2ZXIsIG1lc3NhZ2Up CgoKZGVmIHNlbmRfbWFpbCgKICAgICosCiAgICByZWNpcGllbnQ6IExpc3Rbc3RyXSwKICAgIHN1 YmplY3Q6IHN0ciwKICAgIGJvZHk6IHN0ciwKICAgIGF0dGFjaG1lbnRzOiBPcHRpb25hbFtMaXN0 W3N0cl1dID0gTm9uZSwKKToKICAgIGlmIGF0dGFjaG1lbnRzIGlzIE5vbmU6CiAgICAgICAgYXR0 YWNobWVudHMgPSBbXQoKICAgIG1lc3NhZ2UgPSBNSU1FTXVsdGlwYXJ0KCkKICAgIGZyb21fYWRk cmVzcyA9IG9zLmVudmlyb24uZ2V0KCJGUk9NX0FERFJFU1MiKQoKICAgIGJvZHlfcGFydCA9IE1J TUVUZXh0KGJvZHksICJodG1sIikKICAgIG1lc3NhZ2UuYXR0YWNoKGJvZHlfcGFydCkKICAgIGZv ciBhdHRhY2htZW50IGluIGF0dGFjaG1lbnRzOgogICAgICAgIHdpdGggb3BlbihhdHRhY2htZW50 LCAicmIiKSBhcyBmaDoKICAgICAgICAgICAgYXR0YWNobWVudF9wYXJ0ID0gTUlNRUFwcGxpY2F0 aW9uKGZoLnJlYWQoKSkKICAgICAgICAgICAgZmlsZW5hbWUgPSBvcy5wYXRoLmJhc2VuYW1lKGZo Lm5hbWUpCiAgICAgICAgICAgIGF0dGFjaG1lbnRfcGFydC5hZGRfaGVhZGVyKAogICAgICAgICAg ICAgICAgIkNvbnRlbnQtRGlzcG9zaXRpb24iLAogICAgICAgICAgICAgICAgImF0dGFjaG1lbnQi LAogICAgICAgICAgICAgICAgZmlsZW5hbWU9ZmlsZW5hbWUsCiAgICAgICAgICAgICAgICBDb250 ZW50X1RyYW5zZmVyX0VuY29kaW5nPSJiYXNlNjQiLAogICAgICAgICAgICAgICAgQ29udGVudF9J RD1mIjx7ZmlsZW5hbWV9PiIsCiAgICAgICAgICAgICAgICBDb250ZW50X1R5cGU9InRleHQvY3N2 IiwKICAgICAgICAgICAgICAgIENvbnRlbnRfRGlzcG9zaXRpb249ZiJhdHRhY2htZW50OyBmaWxl bmFtZT17ZmlsZW5hbWV9IiwKICAgICAgICAgICAgKQogICAgICAgIG1lc3NhZ2UuYXR0YWNoKGF0 dGFjaG1lbnRfcGFydCkKCiAgICAjIGRhdGEgPSBtZXNzYWdlLmFzX3N0cmluZygpCiAgICBkYXRh ID0gZW5jcnlwdF9tZXNzYWdlKAogICAgICAgIGZyb21fYWRkcmVzcywKICAgICAgICByZWNpcGll bnQsCiAgICAgICAgc3ViamVjdCwKICAgICAgICBtZXNzYWdlLmFzX2J5dGVzKCksCiAgICAgICAg ZnJvbV9rZXk9ImNlcnRzL25ldy9zaWduZXJfa2V5LnBlbSIsCiAgICAgICAgZnJvbV9jZXJ0PSJj ZXJ0cy9uZXcvc2lnbmVyLnBlbSIsCiAgICAgICAgdG9fY2VydHM9WyJjZXJ0cy9uZXcvcmVjaXBp ZW50LnBlbSJdLAogICAgKQogICAgcmVzdWx0ID0gKHNlbmRfZW1haWxfYnlfc210cChmcm9tX2Fk ZHJlc3MsIHJlY2lwaWVudCwgZGF0YSkpCiAgICBwcmludChyZXN1bHQpCiAgICByZXR1cm4gcmVz dWx0CgoKZGVmIGVuY3J5cHRfbWVzc2FnZShmcm9tX2FkZHIsIHRvX2FkZHJzLCBzdWJqZWN0LCBt c2csIGZyb21fa2V5LCBmcm9tX2NlcnQ9Tm9uZSwgdG9fY2VydHM9Tm9uZSk6CiAgICBtc2dfYmlv ID0gQklPLk1lbW9yeUJ1ZmZlcihtc2cpCiAgICBzaWduID0gZnJvbV9rZXkKICAgIGVuY3J5cHQg PSB0b19jZXJ0cwogICAgcDcgPSBOb25lCgogICAgcyA9IFNNSU1FLlNNSU1FKCkKICAgIGlmIHNp Z246CiAgICAgICAgcy5sb2FkX2tleShmcm9tX2tleSwgZnJvbV9jZXJ0KQogICAgICAgIGlmIGVu Y3J5cHQ6CiAgICAgICAgICAgIHA3ID0gcy5zaWduKG1zZ19iaW8sIGZsYWdzPVNNSU1FLlBLQ1M3 X1RFWFQpCiAgICAgICAgZWxzZToKICAgICAgICAgICAgcDcgPSBzLnNpZ24obXNnX2JpbywgZmxh Z3M9U01JTUUuUEtDUzdfVEVYVCB8IFNNSU1FLlBLQ1M3X0RFVEFDSEVEKQogICAgICAgIG1zZ19i aW8gPSBCSU8uTWVtb3J5QnVmZmVyKG1zZykgICMgUmVjcmVhdGUgY296IHNpZ24oKSBoYXMgY29u c3VtZWQgaXQuCgogICAgaWYgZW5jcnlwdDoKICAgICAgICBzayA9IFg1MDkuWDUwOV9TdGFjaygp CiAgICAgICAgZm9yIHggaW4gdG9fY2VydHM6CiAgICAgICAgICAgIHNrLnB1c2goWDUwOS5sb2Fk X2NlcnQoeCkpCiAgICAgICAgcy5zZXRfeDUwOV9zdGFjayhzaykKICAgICAgICBzLnNldF9jaXBo ZXIoU01JTUUuQ2lwaGVyKCJhZXNfMjU2X2NiYyIpKQogICAgICAgIHRtcF9iaW8gPSBCSU8uTWVt b3J5QnVmZmVyKCkKICAgICAgICBpZiBzaWduOgogICAgICAgICAgICBzLndyaXRlKHRtcF9iaW8s IHA3KQogICAgICAgIGVsc2U6CiAgICAgICAgICAgIHRtcF9iaW8ud3JpdGUobXNnKQogICAgICAg IHA3ID0gcy5lbmNyeXB0KHRtcF9iaW8pCgogICAgb3V0ID0gQklPLk1lbW9yeUJ1ZmZlcigpCiAg ICBvdXQud3JpdGUoZiJGcm9tOiB7ZnJvbV9hZGRyfVxyXG4iKQogICAgb3V0LndyaXRlKGYiVG86 IHsnLCAnLmpvaW4odG9fYWRkcnMpfVxyXG4iKQogICAgb3V0LndyaXRlKGYiU3ViamVjdDoge3N1 YmplY3R9XHJcbiIpCiAgICBpZiBlbmNyeXB0OgogICAgICAgIHMud3JpdGUob3V0LCBwNykKICAg IGVsc2U6CiAgICAgICAgaWYgc2lnbjoKICAgICAgICAgICAgcy53cml0ZShvdXQsIHA3LCBtc2df YmlvLCBTTUlNRS5QS0NTN19URVhUKQogICAgICAgIGVsc2U6CiAgICAgICAgICAgIG91dC53cml0 ZSgiXHJcbiIpCiAgICAgICAgICAgIG91dC53cml0ZShtc2cpCiAgICBvdXQuY2xvc2UoKQoKICAg IHJldHVybiBvdXQucmVhZCgpCgppZiBfX25hbWVfXyA9PSAiX19tYWluX18iOgogICAgcmVzID0g c2VuZF9tYWlsKHJlY2lwaWVudD1vcy5lbnZpcm9uLmdldCgiVE9fQUREUkVTUyIsICIiKS5zcGxp dCgiLCIpLCBzdWJqZWN0PSJzb21lIHN1YmplY3QiLCBib2R5PSJzb21lIGJvZHkiLCBhdHRhY2ht ZW50cz1bX19maWxlX19dKQogICAgcHJpbnQocmVzKQo= --===============2300897735206349356==-- </code></pre>
<python><smime>
2023-07-16 05:33:46
1
706
eplaut
76,696,752
13,060,649
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>`
<p>I want to async view with my django rest framework <code>api_view</code> but I am getting the above error even if I had awaited my response. Here is my view</p> <pre><code>@api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([]) async def login(request): email = request.data.get('email') if email is None or email == '': return Response(data={'success': False, 'message': 'Invalid credentials'}) user = await sync_to_async(User.get_by_email)(email=email) if user is not None and user.is_active and user.check_password(raw_password=request.data.get('password')): serializer = UserSerializer(user) # TODO async tokens_map = await sync_to_async(AuthUtils.generate_token)(request=request, user=user) return Response({'success': True, 'user': serializer.data, 'tokens': tokens_map}) return Response(data={'success': False, 'message': 'Invalid login credentials'}, status=status.HTTP_404_NOT_FOUND) </code></pre> <p>Is there any way to use async views with django in an efficient way?</p> <p>Also for async views will the traditional django middlewares needs to changed?</p>
<python><django><django-rest-framework><python-asyncio><asgi>
2023-07-16 05:00:14
1
928
suvodipMondal
76,696,731
446,215
'langchain' is not a package
<p>Running into this error while trying to run a basic tutorial script for langchain:</p> <pre><code>ModuleNotFoundError: No module named 'langchain.llms'; 'langchain' is not a package </code></pre> <p>Here is the code snippet:</p> <pre><code>from langchain.llms import OpenAI llm = OpenAI(temperature=0.9) text = &quot;What is a popular recipe using coconut milk?&quot; print(llm(text)) </code></pre>
<python><langchain><chatgpt-api>
2023-07-16 04:50:32
2
6,056
Deepak Joy Cheenath
76,696,685
6,294,231
Unable to import holidays from fb prophet package
<p>Getting error while importing holidays from fb prophet as below. Seems like an intermittent issue.</p> <pre><code>import fbprophet.hdays as hdays_part2 TypeError: This is a python-holidays entity loader class. For entity inheritance purposes please import a class you want to derive from directly: e.g., `from holidays.countries import Entity` or `from holidays.financial import Entity`. fbprophet version == 0.7.1 </code></pre>
<python><facebook-prophet><python-holidays>
2023-07-16 04:33:06
0
2,021
Sarang Manjrekar
76,696,590
6,929,343
Tkinter Treeview how to change tree.item(Id)['text']
<p>Getting a Tkinter Treeview item's text is straight forward:</p> <pre class="lang-py prettyprint-override"><code>my_text = tree.item(Id)['text'] </code></pre> <p>I can't seem to find a way of setting the <code>text</code> to a new value.</p> <p>I've tried:</p> <pre class="lang-py prettyprint-override"><code>tree.set(Id, text=legal_string) # TypeError: set() got an unexpected keyword argument 'text' tree.set(Id, ['text']=legal_string) # SyntaxError: keyword can't be an expression tree.set(Id)['text'] = legal_string # Has no effect tree.set(Id, &quot;#0&quot;, legal_string) # 'text' # TclError: Display column #0 cannot be set tree.set(Id, 0, legal_string) # Changes Count/Last Access Column (first column, not 'text' or &quot;#0&quot;) </code></pre>
<python><tkinter><treeview>
2023-07-16 03:44:02
1
2,005
WinEunuuchs2Unix
76,696,579
8,497,844
Variables in decorators without syntactic sugar
<p>There is code:</p> <pre><code>def bread(func): def wrapper(*args, **kwargs): print('&lt;/------\&gt;') func(*args, **kwargs) print('&lt;\______/&gt;') return wrapper def ingredients(func): def wrapper(*args, **kwargs): print('tomato') func(*args, **kwargs) print('lettuce') return wrapper def burger(food='bacon'): print(food) burger = bread(ingredients(burger)) burger() </code></pre> <p>Output:</p> <pre><code>&lt;/------\&gt; tomato bacon lettuce &lt;\______/&gt; </code></pre> <p>How you can understand there are present two decorators without syntactic sugar.</p> <p><code>burger = bread(ingredients(burger))</code> like</p> <pre><code>@bread @ingredients def burger(...): ... </code></pre> <p>I want to push a some variable to the <code>burger()</code>. If I change <code>burger = bread(ingredients(burger))</code> to <code>burger = bread(ingredients(burger(&quot;cheese&quot;)))</code> I get an errors.</p> <p><code>TypeError: 'NoneType' object is not callable</code></p> <h1>My questions:</h1> <p>Main question: I learn decorators in detail and I want to know how variables transfer in decorators without syntactic sugar?</p> <h2>Subquestionals:</h2> <ol> <li>Why does not work <code>burger = bread(ingredients(burger(&quot;cheese&quot;)))</code> in my case?</li> <li>How are variables actually passed to the <code>wrapper</code> sub function in <code>bread</code> and <code>ingredients</code> functions in without syntactic sugar?</li> <li>Are there difference between work with variables passed to the decorator function and decorator sub function (Question #2) without syntactic sugar? Or the code will be the same - level add only.</li> </ol> <p>I mean this exanple in Q. 3:</p> <pre><code>def bread(*args, **kwargs): def wrapper(func): def subwrapper(*args, **kwargs): print('&lt;/------\&gt;') func(*args, **kwargs) print('&lt;\______/&gt;') return subwrapper return wrapper @bread('test') def burger(food='bacon'): print(food) </code></pre>
<python><python-decorators>
2023-07-16 03:33:48
2
727
Pro
76,696,569
9,588,300
Pyspark stuck and not processing. It shows more than 1K processes
<p>I have a <strong>for loop</strong> running in databricks and the first iterations run fast, then it <strong>gets slower and then it doesn't proceeds at all</strong>. While I know that is common in for loops if data size is increasing on each iteration and/or there's garbage variables not being deleted, <strong>at least I should see that either RAM/CPU/DISK/NETWORK are nearing 100%, right?</strong> but they are not, in fact they are not used at all. And also, at least I hoped to see spark Jobs being processed at SparkUI but there are none when the for loop gets stuck. <strong>Despite the notebook cell says the cell is still running.</strong></p> <p>So do I have some resource that got clugged that is neither RAM/CPU/DISK/NETWORK? And why spark shows no running jobs despite the for is still running?</p> <p>Also, spark UI shows there's no job running, despite the notebook says the command is still running, and I know for sure it hasn't finished because I should see files getting created on AWS S3.</p> <p>My case is that I am trying to generate some dummy data for testing. My goal is to create many csv files of the same dataframe schema that vary just in a datestamp column, so to emulate incremental load scenario. My goal is to have 400 csv that are essentially the same dataframe but with the datestamp column changing by 1 day, as if I received a file on Jan 01, another on Jan 02, another in Jan 03 and so on for 400 days.</p> <p>For that, I have my &quot;base&quot; dataframe <code>input_df</code>, and I have a for loop in databricks that reads from it, increases the <code>id</code> column and <code>datestamp</code> column (as if they were new rows) and writes into S3 with a datestamp string. Here is the loop</p> <pre><code>another=input_df for i in range(400): # I get the min and max values of column &quot;id&quot; to then add the ids for the new df aggs=another.agg(max('id'),min('id')) max_id=aggs.collect()[0][0] min_id=aggs.collect()[0][1] # Here I add the id column to emulate &quot;new data&quot; and the datestamp column another=another.withColumn('id',col('id')+max_id-min_id+1).\ withColumn('created_time',date_add(col('created_time'),1)).\ withColumn('created_time',date_format(col(&quot;created_time&quot;), &quot;yyyy-MM-dd'T'HH:mm:ss.SSSZ&quot;)) #here I create the file name by using the datestamp date_procesed=datetime.strptime('20220112','%Y%m%d') + timedelta(days=i+1) date_procesed=date_procesed.strftime('%Y%m%d') print(date_procesed) #And here I write it in a single csv file another.coalesce(1).write.option('header','true').csv('dbfs:/tmp/wiki/transaction/'+date_procesed) </code></pre> <p>Now the cell of the notebook runs for about 11 files (that created and completed about 40 jobs) and then stops. I thought some resource was nearing capacity. But this is my problem</p> <ol> <li>At Spark UI no job is running. As if the notebook is not even creating more jobs</li> <li>All the first 40 jobs created my the first 11 iterations of the loop are completed (and I see the files written on S3)</li> <li>At GangliaUI I see only the driver is doing everything (which is expected cause my input_df was created using the <code>rand</code> library. But neither its CPU/RAM/NETWORK/DISK are full, and they are not even fluctuating for nearly an hour</li> </ol> <p>here's a picture of the driver at ganglia. you can see the resources (CPU,RAM,NETWORK) kind of do spike at some point in time (when the for loop was actually working, creating and completing spark jobs). But then they downsized and are stable, but the for loop stops and I know it shouldn't .</p> <p>My ultimate questions are</p> <ol> <li>Do I have some resource that got clugged that is neither RAM/CPU/DISK/NETWORK?</li> <li>And why spark shows no running jobs despite the for is still running? Why this for loop</li> <li>doesn't works? I know they are not good practice in python, let alone in spark. But I have no answer why it's not processing</li> </ol> <p><a href="https://i.sstatic.net/6BvfN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6BvfN.png" alt="Ganglia" /></a></p> <p>Also as a side note, I noticed this on processes running on the driver (despite there's no spar job running) So I suspect spark is not closing some ports/connections or declaring processes as done</p> <p><a href="https://i.sstatic.net/0atMe.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0atMe.png" alt="Process running" /></a></p>
<python><apache-spark><databricks><cluster-computing><ganglia>
2023-07-16 03:28:22
2
462
Eugenio.Gastelum96
76,696,552
17,275,588
Most effective way to programmatically sort images into categories by color?
<p>I'm working on a project where I need to sort a large pool of images into a variety of color categories. It's pretty complicated because first, the sorting needs to happen at three levels:</p> <ol> <li><p>Very simple basic colors: &quot;blue&quot;, &quot;green&quot;, etc.</p> </li> <li><p>More specific colors: &quot;steel blue&quot;, &quot;crimson red&quot;, etc.</p> </li> <li><p>Very broad color groups: &quot;vibrant and colorful&quot;, &quot;warm colors&quot;, &quot;neutral colors&quot;, etc.</p> </li> </ol> <p>It's even MORE complicated because, how humans would sort the images kind of depends and might vary image by image. What I mean is, in some cases, the actual surface area covered by a specific color might be small, but if it's a really prominent focal point (for example, a bright red barn amid a black and white landscape scene), the human might sort it into the &quot;red&quot; category since the red is so pronounced. In other cases, there might be a fairly large surface area spanned by a certain color, but maybe the distribution of the color across the image actually makes it not really stand out or even &quot;feel&quot; like an image of that color. This mostly comes down to &quot;surface area&quot; vs. &quot;color dominance/prominence&quot;.</p> <p>While it felt like a simple task at first, the more I work on it, the more complex it seems to become.</p> <p>Are there any standardized APIs, python libraries, or software tools that massively simplify this process by taking these different factors into consideration?</p> <p>A few approaches I've tested so far are: Custom Python scripts that use kmeans to get the RGB color codes of the colors whose proportion in the image passes some specified threshold. I then tried taking that a step further, and mapping those more complex colors onto the closest match &quot;simple colors&quot;, by mapping &quot;steel blue&quot; onto just &quot;plain blue&quot;, etc. Really after lots of experimenting with this, the results simply weren't that good.</p> <p>Others I've experimented with are: Using tools like Google Cloud Vision to get the &quot;dominant colors.&quot; This is really a mixed bag. For example, sometimes an entirely black and white image with just like a small dash of another color will show the &quot;another color&quot; as the dominant color and totally miss the black and white. Another API-based tool, Ximilar, seems to output probably some of the best results I've seen -- but it appears to mostly be based entirely on surface area vs. color prominence.</p> <p>Other ideas / other standard solutions to this problem would be greatly appreciated, as I've been working for hours on it and haven't seemed to hit upon the optimal solution yet.</p>
<python><machine-learning><automation><colors><artificial-intelligence>
2023-07-16 03:20:59
2
389
king_anton
76,696,379
9,588,300
spark read file with string column as factor (or enum)
<p>I have seen in pyspark you can define a schema to a file that is going to be read. One very simple example is below:</p> <pre><code>schema_input=StructType([StructField('some_string_column',StringType(),False)]) df=spark.read.schema(schema_input).option('header','true').csv(&lt;path&gt;) </code></pre> <p>Assuming I have a column that has only three possible string values (red,blue and yellow) but the dataframe is 1 billion rows long, isn't there a way to read as factors or enum to save some space/time?</p> <p>I don't know if there's an equivalent <code>EnumType(&lt;enum_list&gt;)</code> to the <code>StringType()</code> data type. I have read the <a href="https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/data_types.html" rel="nofollow noreferrer">documentation</a> on pyspark datatypes and it only seems to understand strings as strings, there doesn't seems to be a something like reading as factors/enums to save space</p> <p>One important note is that I am asking if it's possible to do this while reading time, not to encode the string column after it has been read.</p>
<python><apache-spark><pyspark>
2023-07-16 01:42:59
1
462
Eugenio.Gastelum96
76,696,347
11,748,924
Efficient code for screencap adb with python
<p>I have this code, it works like I expect:</p> <pre><code>import subprocess from time import sleep # Run the command and capture the stdout COMMAND = 'adb exec-out screencap -p' FRAME_COUNT = 0 while 1: with open(f'./frames/frame_{FRAME_COUNT}.png', 'wb') as file: stdout, stderr = subprocess.Popen(COMMAND, stdout=subprocess.PIPE).communicate() # Store the byte stdout in a variable file.write(stdout) sleep(1) FRAME_COUNT += 1 </code></pre> <p>But I'm doubting about efficiency of code, mainly <code>Popen</code>. Every iteration, it's creating instance <code>Popen</code>, is it okay for memory?, Any idea for better solution?</p> <p>Update, I added opencv:</p> <pre><code>import subprocess import cv2 import numpy as np from time import time COMMAND = 'adb exec-out screencap -p' while True: tLast = time() # Capture the screen using adb png_stdout_bytes = subprocess.check_output(COMMAND) # Convert the stdout bytes to a numpy array png_bytes = np.frombuffer(png_stdout_bytes, np.uint8) # Decode the image from the numpy array img = cv2.imdecode(png_bytes, cv2.IMREAD_COLOR) # Resize the image to be 50% smaller width = int(img.shape[1] * 0.45) height = int(img.shape[0] * 0.45) resized_img = cv2.resize(img, (width, height)) fps = 1 / (time() - tLast) cv2.putText(resized_img, f'FPS: {fps:.2f}', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # Display the resized image cv2.imshow('Screen Capture', resized_img) cv2.waitKey(1) </code></pre>
<python><subprocess><pipe><adb>
2023-07-16 01:22:28
1
1,252
Muhammad Ikhwan Perwira
76,696,045
14,397,434
How to return file names that don't have certain sentences?
<p>So I made some code that returns the names for each file in a directory. I want to move on to <em>filtering</em> the files that my loop comes across whether that be during the loop itself or during the Path() function. <strong>Help?</strong></p> <pre><code>from pathlib import Path # grab all the pdf's, essentially pdf_files = Path(&quot;C:\\Users\\ME\\Documents\\PretendFolder&quot;).glob(&quot;*.pdf&quot;) for pdf in pdf_files: print(pdf) </code></pre> <p>My Output:</p> <p><code>C:\Users\ME\Documents\PretendFolder\Adjusted NO STORY.pdf C:\Users\ME\Documents\PretendFolder\Adjusted.pdf</code></p> <p>My 1st Attempt:</p> <pre><code>canvas = [] for pdf in pdf_files: canvas.append(pdf =! 'NO STORY') print(pdf) </code></pre> <p>My 2nd Attempt: This second attempt doesn't print anything at all for some reason.</p> <pre><code>pdf_files = Path(&quot;C:\\Users\\ME\\Documents\\PretendFolder&quot;).glob(&quot;*.pdf&quot;) for pdf in pdf_files: if not pdf.__contains__('NO STORY'): print(pdf) </code></pre>
<python><for-loop><path>
2023-07-15 22:47:42
1
407
Antonio
76,695,861
9,901,261
How to get enum value
<pre><code>from pynput.keyboard import Key from pynput.mouse import Button from enum import Enum value=Key.esc def corresponding_event(key): print(type(key)) corresponding_event(value) </code></pre> <p>produces &lt;enum 'Key'&gt;</p> <p>How would I obtain the value for the enum 'Key'and also check if it's an enum the function can pass different type of values as well. &lt;enum 'Button'&gt; ,&lt;enum 'Key'&gt; ,&lt;class 'str'&gt; ,&lt;class 'int'&gt;</p> <p>I know you can check for enums with</p> <pre><code>if isinstance(key,Enum): print(key.name,key.value) </code></pre> <p>I would like to do different actions if it's a key or button.</p>
<python><enums><pynput>
2023-07-15 21:34:11
1
9,989
Arundeep Chohan
76,695,759
1,056,563
Permission denied on creating a file after os.makedirs even after setting umask(0)
<p>A popular question <a href="https://stackoverflow.com/questions/5231901/permission-problems-when-creating-a-dir-with-os-makedirs-in-python">Permission problems when creating a dir with os.makedirs in Python</a>, as well as a number of other resources mention setting</p> <blockquote> <p>os.umask(0)</p> </blockquote> <p>before calling <code>os.makedirs()</code>. I have done this, but still have permission denied on creating files in the new directory.</p> <pre><code>BASEDIR=&quot;./cdm&quot; import os from pathlib import Path try: original_umask = os.umask(0) print(&quot;original_umask&quot;, original_umask) os.makedirs(BASEDIR, mode = 0o777, exist_ok = True) print(&quot;files: &quot;,[f.name for f in Path(BASEDIR).glob(&quot;*&quot;)]) print('perms on dir', hex(os.stat(BASEDIR).st_mode)) finally: os.umask(original_umask) with open(f&quot;{BASEDIR}/xx.yml&quot;,'w') as f: f.write(&quot;hi&quot;) </code></pre> <p>Here is the result:</p> <pre><code>original_umask 18 files: [] perms on dir 0x4177 PermissionError: [Errno 13] Permission denied: './cdm/xx.yml </code></pre> <p>So the perms are not open to the world (<em>4177</em>) even after setting <code>umask(0)</code>. But that should not matter here since the code creating the new files is in the same process/owner.</p> <p>I am on <code>macOS</code> <code>Ventura 13.4.1</code> using <code>python3.10</code></p>
<python>
2023-07-15 20:59:46
0
63,891
WestCoastProjects
76,695,216
6,779,049
Python string to formatted text in Apple Notes?
<p>I've written a Python script to extract notes and highlights from my kindle. Now I would like to create a formatted string that I can write from Python to my clipboard, and then ideally paste into Apple Notes with formatting (headers, font style, etc.). I've looked around by can't really find anything on this. Is this possible? I'm open to using additional tools (shortcuts, applescript, etc.) if absolutely necessary, but my preference would be to have a self-contained python script.</p>
<python><applescript><richtext>
2023-07-15 18:27:42
1
398
Nick-H
76,695,194
6,380,992
Why setting index_col to zero shifts the first column heading by one row?
<p>I have the following code:</p> <pre><code>import pandas as pd df = pd.read_csv('data.csv', index_col=0) print(df) </code></pre> <p>The <em>data.csv</em> file contents are:</p> <pre><code>Reg. No, Score 234, 78 467, 98 876, 23 675, 49 123, 56 </code></pre> <p>This gives me the following weird output:</p> <pre><code> Score Reg. No 234 78 467 98 876 23 675 49 123 56 </code></pre> <p>If I remove the <code>index_col</code> parameter or set it to <code>None</code> then both <strong>Reg. No</strong> and <strong>Score</strong> are aligned to the same row. But, for further processing of this data, I need the <code>index_col=0</code>. How to get around this?</p>
<python><pandas>
2023-07-15 18:21:55
1
1,232
Seshadri R
76,694,986
19,366,064
Python poetry set up
<pre><code>[tool.poetry] name = &quot;webapp&quot; version = &quot;0.1.0&quot; description = &quot;&quot; authors = [] readme = &quot;README.md&quot; [tool.poetry.dependencies] python = &quot;^3.11&quot; [tool.poetry.group.dev.dependencies] pytest = &quot;^7.4.0&quot; [build-system] requires = [&quot;poetry-core&quot;] build-backend = &quot;poetry.core.masonry.api&quot; </code></pre> <p>I have a pyproject.toml file. What would be the command line to change dependency versions? How do I add depdencies to .group.dev.depdencies only?</p>
<python><python-poetry>
2023-07-15 17:21:10
1
544
Michael Xia
76,694,813
10,179,854
Application bundles uploaded using Google Developer API do not appear anywhere, despite successful request execution
<p>Here is the Python code I am using, building on the <code>googleapiclient</code> module:</p> <pre><code>from googleapiclient.discovery import build, MediaFileUpload from oauth2client.service_account import ServiceAccountCredentials app_id = &quot;com.myapp.myapp.app&quot; aab_file_path = &quot;H:/packages/0.0.18/com.myapp.myapp.app.aab&quot; service_account_file_path = &quot;service-account-key.json&quot; # Create the service account credentials object. credentials = ServiceAccountCredentials.from_json_keyfile_name( service_account_file_path, [&quot;https://www.googleapis.com/auth/androidpublisher&quot;] ) # Create the API client object. service = build(&quot;androidpublisher&quot;, &quot;v3&quot;, credentials=credentials) # Get an edit ID. request = service.edits().insert(packageName=app_id) response = request.execute() editId = response['id'] media_body = MediaFileUpload(aab_file_path, mimetype='application/octet-stream', resumable=True) request = service.edits().bundles().upload( packageName=app_id, editId=editId, media_body=media_body, ) response = request.execute() # Check that the response contains a versionCode. versionCode = response.get(&quot;versionCode&quot;) if response.get(&quot;versionCode&quot;) is not None: print(&quot;Bundle successfully uploaded.&quot;) else: print(&quot;Failed to upload bundle.&quot;) </code></pre> <p>The script runs through, the <code>versionCode</code> retrieved is correct, but the bundle is not actually visible in the <code>App bundle explorer</code> in the Google Play Console, neither is it useable to update a track, or returned by <code>edits.bundles.list</code>.</p> <p>Could someone please explain to me what I am doing wrong?</p>
<python><android><google-api><google-play-console>
2023-07-15 16:43:01
1
399
Julien Debache
76,694,633
6,357,916
Giving user input to interactive command line tool from jupyter notebook
<p>Many command line utilities do certain things and then wait for user input before proceeding further. I was trying one such utility but inside jupyter notebook. But let me give an example of reading variable command. I typed <code>! read var</code> in jupyter notebook cell, it simply hanged awaiting (with * in front of it) for user input:</p> <p><a href="https://i.sstatic.net/OjmQz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OjmQz.png" alt="enter image description here" /></a></p> <p>The utility I am trying to use in jupyter notebook exhibits same behavior. It executes and then simply hangs for user input with no way to provide a user input to it.</p> <p>Is it possible to give user input to interactive command line tool when used jupyter notebook? And if yes, how?</p> <p>PS: I want to do this because its great way to document in jupyter notebook (even full command line utility output).</p> <p>PS: More common use case will be command line utilities that ask for y/n input. But more complex scenario will be: command line tools / scripts that themselves ask for user input &quot;programatically&quot;? By &quot;programatically&quot;, I mean, in some environments, they may ask for one input while in other environment, it might ask for different input.</p>
<python><jupyter-notebook><jupyter><jupyter-lab>
2023-07-15 16:03:19
0
3,029
MsA
76,694,599
4,451,315
Print source of lambda without surrounding call
<p>If I define a function</p> <pre class="lang-py prettyprint-override"><code>def foo(function): import inspect return inspect.getsource(function) </code></pre> <p>and then call it, I get:</p> <pre class="lang-py prettyprint-override"><code>In [11]: foo(lambda x: x[0] + x[1]*2) Out[11]: 'foo(lambda x: x[0] + x[1]*2)\n' </code></pre> <p>Note how it printed the entire line, rather than just the lambda function.</p> <p>Is there a way to get it to output just the lambda?</p> <p>Desired output:</p> <pre class="lang-py prettyprint-override"><code>In [11]: foo(lambda x: x[0] + x[1]*2) lambda x: x[0] + x[1]*2' </code></pre> <p>Is there a way to do this that doesn't involve using a regular expression?</p> <p>EDIT:</p> <p>Example of how <code>ast.parse(inspect.getsource(function))</code> may fail:</p> <pre class="lang-py prettyprint-override"><code>ast.parse(foo( lambda x: x+1)) </code></pre>
<python><lambda><abstract-syntax-tree><python-ast>
2023-07-15 15:56:13
1
11,062
ignoring_gravity
76,694,467
11,168,443
Is it possible to access SQL Trace Data (same as what SQL Profiler can see) through python?
<p>Overview: I need to monitor traffic to the SQL server, and be able to extract some of the parameters, and determine which user sent the request. This all needs to be done in python.</p> <p>I'm going to lay out how I need this to work, because I may be looking at it wrong.</p> <p>I have User A, User B, and User C. All three of these users are using an inventory software (very large program, made by a big company) to communicate with the Server. The server is running SQL Server 17. I have a python application each user has installed on their computer and they are using alongside their inventory management software. This program gives the users the ability to do things the inventory software just simply doesn't offer. My python program uses PYODBC to connect to the SQL server and run queries to the same SQL database the inventory management server is already connected to.</p> <p>I need my python software to be able to monitor the SQL queries sent between the inventory software on each users computer and the SQL server. I can already do this by logging into the SQL server VM and opening up SQL Server Profiler and starting a trace. But now I need to access that information inside my python application on each of the users computers.</p> <p>The end goal here is for the python application on user A computer to be monitoring the SQL queries, and then a specific query is ran to the server (IE: exec StoredProc1 4, 500, 100) I need to be able to extract the parameters, and call functions to be able to display additional data in my python application.</p> <p>The python program installed on User A's computer only needs to monitor traffic between user A and the server. I do not care about any traffic between any other computer and the server.</p> <p>I tried to create an Extended Event Session, and log the data to a file, and just access that file with my python program to read from it, but the problem is this needs to happen in real time, and I could not access the .xel file while the SQL server is writing to it.</p> <p>One &quot;idea&quot; I had was to instead of logging the data to a .xel file, I could instead insert it into a table, and then just select from the table with my python application every 1-2 seconds, but I am not sure how to set the Extended Event session to log the data into a table. Another &quot;idea&quot; I had was to just monitor the packets sent from the users computer to the specific server IP address and port and try and dissect that, but I am not exactly sure this will work either.</p> <p>If anyone has ever done anything like this and has any input on how to best make this work, without taxing the server too much, it would be greatly appreciated.</p>
<python><sql><python-3.x><sql-server>
2023-07-15 15:26:17
0
965
Lzypenguin