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,755,826 | 7,587,176 | Max() function on node ; python DFS | <p>in the classic example of DFS below:</p>
<pre><code>class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def tree_max_depth(root: Node) -> int:
def dfs(root):
# null node adds no depth
if not root:
return 0
# num nodes in longest path of current subtree = max num nodes of its two subtrees + 1 current node
return max(dfs(root.left), dfs(root.right)) + 1
print(dfs(root.left))
return dfs(root) - 1 if root else 0
# this function builds a tree from input; you don't have to modify it
# learn more about how trees are encoded in https://algo.monster/problems/serializing_tree
def build_tree(nodes, f):
val = next(nodes)
if val == 'x': return None
left = build_tree(nodes, f)
right = build_tree(nodes, f)
return Node(f(val), left, right)
if __name__ == '__main__':
root = build_tree(iter(input().split()), int)
res = tree_max_depth(root)
print(res)
</code></pre>
<p>How is the max function calculating the height in the line below?</p>
<pre><code>return max(dfs(root.left), dfs(root.right)) + 1
</code></pre>
| <python><depth-first-search> | 2023-07-24 15:11:52 | 2 | 1,260 | 0004 |
76,755,615 | 18,108,367 | What is the difference between import a module from a folder and import a module from a package? | <p>I need to better understand the difference between a normal directory and a Python package. I know this sentence present in the Python documentation about <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow noreferrer">modules</a> and in particular in the paragraph about <a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="nofollow noreferrer">Packages</a>:</p>
<blockquote>
<p>The <code>__init__.py</code> files are required to make Python treat directories containing the file as packages.</p>
</blockquote>
<p>To explain my doubt I'll show an example of directory structure:</p>
<pre><code>study_import
|-folder1
| |-b.py
|-a.py
</code></pre>
<p>The content of the module <code>study_import/a.py</code> is:</p>
<pre><code>import folder1.b
print(folder1.b.VAR2)
</code></pre>
<p>The content of the module <code>study_import/folder1/b.py</code> is:</p>
<pre><code>VAR2="20"
</code></pre>
<p>The module <code>a.py</code> imports the module <code>b.py</code> from the directory <code>folder1</code> and can be executed correctly. Its output is the printout of the number <code>20</code>.</p>
<p>With the previous folder structure <code>study_import</code> and <code>folder1</code> are not packages because they don't contain the file <code>__init__.py</code>.</p>
<p>In this moment I don't understand the need to have a package because for example the instruction <code>import folder1.b</code> can be executed even the <code>__init__.py</code> there isn't present.
<strong>Until now I thought that packages were needed to correctly import modules.</strong></p>
<p>Could someone help me to understand what is the difference between import a module from a folder and import a module from a package?</p>
<hr />
<p><strong>EDIT</strong>: I have followed the hint of Brian61354270 so I add 2 <code>print()</code> instructions in <code>study_import/a.py</code>:</p>
<pre><code>import folder1.b
print(folder1.b.VAR2)
print(folder1)
print(folder1.b)
</code></pre>
<p>If I execute the script <code>a.py</code> the output is:</p>
<pre><code>20
<module 'folder1' (namespace)>
<module 'folder1.b' from '/path/to/study_import/folder1/b.py'>
</code></pre>
<h2><code>folder1</code> becomes a package</h2>
<p>I add the file <code>__init__.py</code> in <code>folder1</code> ===> <code>folder1</code> becomes a package:</p>
<pre><code>study_import
|-folder1
| |-__init__.py
| |-b.py
|-a.py
</code></pre>
<p>Now the execution of the script <code>a.py</code> produces the followed output:</p>
<pre><code>20
<module 'folder1' from '/path/to/study_import/folder1/__init__.py'>
<module 'folder1.b' from '/path/to/study_import/folder1/b.py'>
</code></pre>
<p>Can someone explain the difference between 2 outputs?</p>
| <python><python-module><python-packaging> | 2023-07-24 14:49:09 | 0 | 2,658 | User051209 |
76,755,607 | 16,383,578 | How to optimize the ulam spiral infinite iterator? | <p>I have created an infinite iterator which maps natural numbers to all lattice points in a spiral like manner, akin to the Ulam Spiral:</p>
<p><img src="https://i.sstatic.net/FkEiu.png" alt="" /></p>
<p>The code is below, I have made it as fast as possible, and I didn't use a single if condition:</p>
<pre><code>from itertools import islice, repeat
def ulamish_spiral_gen():
xc = yc = length = 0
yield 0, 0
while True:
length += 1
yield from zip(range(xc + 1, (xc := xc + length) + 1, 1), repeat(yc))
yield from zip(repeat(xc), range(yc + 1, (yc := yc + length) + 1, 1))
length += 1
yield from zip(range(xc - 1, (xc := xc - length) - 1, -1), repeat(yc))
yield from zip(repeat(xc), range(yc - 1, (yc := yc - length) - 1, -1))
def ulamish_spiral(n):
return list(islice(ulamish_spiral_gen(), n))
</code></pre>
<p>I want to know, how to memoize the output of the infinite iterator, so that <code>list(islice(ulamish_spiral_gen(), n))</code> will be called only when the value of <code>n</code> is greater than the last <code>n</code>.</p>
<p>Something like this:</p>
<pre><code>COMPUTED = []
def ulamish_spiral(n):
global COMPUTED
if n > len(COMPUTED):
COMPUTED = list(islice(ulamish_spiral_gen(), n))
return COMPUTED[:n]
</code></pre>
<p>It is very easy, but the first <code>len(COMPUTED)</code> terms have already been computed, only terms in <code>range(len(COMPUTED), n)</code> need to be computed, but the call computes all the already computed terms. So I tried to reuse the same generator object and only ask for the next <code>n - len(COMPUTED)</code> items, and I have succeeded.</p>
<p>But doing so actually makes code slower:</p>
<pre><code>COMPUTED = []
ULAMISH_GEN = ulamish_spiral_gen()
def ulamish_spiral(n):
if n > (l := len(COMPUTED)):
COMPUTED.extend(islice(ULAMISH_GEN, n - l))
return COMPUTED[:n]
</code></pre>
<pre><code>In [225]: %timeit COMPUTED.clear(); ULAMISH_GEN = ulamish_spiral_gen(); ulamish_spiral(8192)
928 µs ± 8.96 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [226]: %timeit COMPUTED.clear(); ULAMISH_GEN = ulamish_spiral_gen(); ulamish_spiral(1024); ulamish_spiral(2048); ulamish_spiral(4096); ulamish_spiral(8192)
993 µs ± 18.2 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [227]: %timeit COMPUTED.clear(); ULAMISH_GEN = ulamish_spiral_gen(); ulamish_spiral(1024); ulamish_spiral(2048); ulamish_spiral(4096); ulamish_spiral(8192); ulamish_spiral(16384)
2.14 ms ± 106 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [228]: %timeit COMPUTED.clear(); ULAMISH_GEN = ulamish_spiral_gen(); ulamish_spiral(16384)
2 ms ± 88.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [229]: COMPUTED.clear(); ULAMISH_GEN = ulamish_spiral_gen(); ulamish_spiral(1024); ulamish_spiral(2048); ulamish_spiral(16384) == list(islice(ulamish_spiral_gen(), 16384))
Out[229]: True
</code></pre>
<p>How can I skip already computed terms and make code faster?</p>
| <python><python-3.x><performance><optimization> | 2023-07-24 14:47:34 | 2 | 3,930 | Ξένη Γήινος |
76,755,156 | 7,713,770 | relation "django_content_type" already exists django | <p>oke, I have a django application. And I tried to update the models. So I did a</p>
<p>makemigrations and migrate. But that didn't worked. So I truncated the table django_migrations.</p>
<p>And I did a python manage.py makemigrations:</p>
<pre><code>Migrations for 'zijnAdmin':
zijnAdmin\migrations\0001_initial.py
- Create model Category
- Create model Animal
</code></pre>
<p>but when I try now: python manage.py migrate. I get this errors:</p>
<pre><code>Running migrations:
Applying contenttypes.0001_initial...Traceback (most recent call last):
File "C:\repos\DWL_backend\env\lib\site-packages\django\db\backends\utils.py", line 87, in _execute
return self.cursor.execute(sql)
psycopg2.errors.DuplicateTable: relation "django_content_type" already exists
</code></pre>
<p>But I see that changes have been made in the tables. and the app works fine. But I still get this warning when I do a : python manage.py runserver 192.168.1.135:8000</p>
<pre><code>You have 25 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): accounts, admin, auth, authtoken, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 24, 2023 - 15:49:58
Django version 4.2.3, using settings 'zijn.settings.local'
Starting development server at http://192.168.1.135:8000/
Quit the server with CTRL-BREAK.
</code></pre>
<p>Question: how to resolve this error?</p>
| <python><django><django-rest-framework> | 2023-07-24 13:50:39 | 2 | 3,991 | mightycode Newton |
76,755,070 | 1,629,615 | Upgrade to jupyter notebook 7.0.0 produces 500: Internal Server Error for jupyter nbclassic | <p>After a <code>conda update --all</code> of my env, comprising also an upgrade to <code>jupyter notebook 7.0.0</code> the <code>jupyter nbclassic</code> does not allow notebooks to be created or loaded anymore.</p>
<p>Whenever I try, I get a <code>500: Internal Server Error</code>, moreover the console displays the following <code>[E ...]</code> msgs.</p>
<p>Any suggestions on what the problem is and how to fix it are most welcome.</p>
<pre><code>[I 2023-07-24 15:19:00.816 ServerApp] Creating new notebook in
[E 2023-07-24 15:19:01.029 ServerApp] Uncaught exception GET /nbclassic/notebooks/Untitled.ipynb?kernel_name=python3 (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/nbclassic/notebooks/Untitled.ipynb?kernel_name=python3', version='HTTP/1.1', remote_ip='127.0.0.1')
Traceback (most recent call last):
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/tornado/web.py", line 1786, in _execute
result = await result
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/tornado/gen.py", line 786, in run
yielded = self.gen.send(value)
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/nbclassic/notebook/handlers.py", line 101, in get
self.write(self.render_template('notebook.html',
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/jupyter_server/base/handlers.py", line 639, in render_template
return template.render(**ns)
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/jinja2/environment.py", line 1301, in render
self.environment.handle_exception()
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/jinja2/environment.py", line 936, in handle_exception
raise rewrite_traceback_stack(source=source)
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/nbclassic/templates/notebook.html", line 1, in top-level template code
{% extends "page.html" %}
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/nbclassic/templates/page.html", line 190, in top-level template code
{% block header %}
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/nbclassic/templates/notebook.html", line 115, in block 'header'
{% for exporter in get_frontend_exporters() %}
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/nbclassic/notebook/handlers.py", line 46, in get_frontend_exporters
for name in get_export_names():
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/nbconvert/exporters/base.py", line 150, in get_export_names
e = get_exporter(exporter_name)(config=config)
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/nbconvert/exporters/base.py", line 109, in get_exporter
exporter = [e for e in exporters if e.name == name or e.name == name.lower()][0].load()
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/importlib_metadata/__init__.py", line 209, in load
module = import_module(match.group('module'))
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/jupyter_contrib_nbextensions/__init__.py", line 5, in <module>
import jupyter_nbextensions_configurator
File "/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/jupyter_nbextensions_configurator/__init__.py", line 17, in <module>
from notebook import version_info as nb_version_info
ImportError: cannot import name 'version_info' from 'notebook' (/home/UserX/.anaconda3/envs/py/lib/python3.9/site-packages/notebook/__init__.py)
[E 2023-07-24 15:19:01.034 NotebookApp] {
"Host": "localhost:8888",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Referer": "http://localhost:8888/nbclassic/tree",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0"
}
[E 2023-07-24 15:19:01.034 NotebookApp] 500 GET /nbclassic/notebooks/Untitled.ipynb?kernel_name=python3 (3732122b1ec04beabb60168cadc9cdf1@127.0.0.1) 152.26ms referer=http://localhost:8888/nbclassic/tree
</code></pre>
| <python><jupyter-notebook><conda><jupyter><jupyter-nbclassic> | 2023-07-24 13:37:46 | 2 | 659 | Mark |
76,754,830 | 17,471,060 | Create custom field output in Abaqus2021 through Python and view in contour plot | <p>I would like to add my own custom field variable (in this case nodal <code>U</code> values in all 3 translational directions), then I want to view the contour plots. The following code does create the step & frame and dumps given nodal value.</p>
<pre><code>from abaqus import *
from abaqusConstants import *
import odbAccess
odb_path = r"x03_test_st.odb"
instanceName = 'PART-1-1'
odb = odbAccess.openOdb(path=odb_path, readOnly=True)
instance1 = odb.rootAssembly.instances[instanceName]
step1 = odb.Step(name='step1', description='', domain=TIME, timePeriod=1.0)
frame0 = step1.Frame(incrementNumber=1, frameValue=0.1, description='dummy')
frame1 = step1.Frame(incrementNumber=2, frameValue=0.2, description='customFrame')
uField = frame1.FieldOutput(name='U', description='', type=VECTOR)
nodeLabelData = (1, 2, 3, 4, 5, 6)
dispData = ((0.15374583118418694, 0.8585851847069973, 0.3742254744931832),
(0.4070882202130386, 0.6974154877282727, 0.2126706056738057),
(0.5463851799965965, 0.7688165228864976, 0.8131962796810962),
(0.11280984262947236, 0.3143623822894589, 0.905752847147511),
(0.07679643266215119, 0.7547831307161972, 0.6137464800631778),
(0.9094500731020884, 0.19221815308664503, 0.8331704449998695))
uField.addData(position=NODAL, instance=instance1, labels=nodeLabelData, data=dispData)
odb.steps['step1'].setDefaultField(uField)
</code></pre>
<p>By printing the values assigned value of node 6 -</p>
<p><code>print(odb.steps['step1'].frames[-1].fieldOutputs['U'].values[-1])</code></p>
<p><a href="https://i.sstatic.net/xMnqx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xMnqx.png" alt="enter image description here" /></a></p>
<p>However, while no primary variable is present in the field output to plot -</p>
<p><a href="https://i.sstatic.net/YPFQ3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YPFQ3.png" alt="enter image description here" /></a></p>
<p>Here's the inp file of the test analysis -</p>
<pre><code>*Heading
** Job name: x03_test_st Model name: x03_test_st
** Generated by: Abaqus/CAE 2021.HF4
*Preprint, echo=NO, model=NO, history=NO, contact=NO
**
** PARTS
**
*Part, name=Part-1
*Node
1, 0., 0., 0.
2, 1., 0., 0.
3, 1., 0.5, 0.
4, 0., 0.5, 0.
5, 0.576822102, 0.185981557, 0.
6, 0.200000003, 0., 0.
7, 0.400000006, 0., 0.
8, 0.600000024, 0., 0.
9, 0.800000012, 0., 0.
10, 1., 0.166666672, 0.
11, 1., 0.333333343, 0.
12, 0.800000012, 0.5, 0.
13, 0.600000024, 0.5, 0.
14, 0.400000006, 0.5, 0.
15, 0.200000003, 0.5, 0.
16, 0., 0.333333343, 0.
17, 0., 0.166666672, 0.
18, 0.599589348, 0.259053588, 0.
19, 0.564018428, 0.326822132, 0.
20, 0.490946412, 0.349589318, 0.
21, 0.423177868, 0.314018428, 0.
22, 0.400410682, 0.240946427, 0.
23, 0.435981572, 0.173177868, 0.
24, 0.509053588, 0.150410682, 0.
25, 0.480635941, 0.0850624219, 0.
26, 0.517703593, 0.420923859, 0.
27, 0.631206751, 0.16905348, 0.
28, 0.369088441, 0.359036833, 0.
29, 0.635420084, 0.113386989, 0.
30, 0.330888033, 0.23710534, 0.
31, 0.693981647, 0.232443213, 0.
32, 0.192599267, 0.348136783, 0.
33, 0.78786093, 0.158841655, 0.
34, 0.779104173, 0.331114978, 0.
35, 0.208837822, 0.180184364, 0.
36, 0.617957652, 0.369486988, 0.
37, 0.345436871, 0.140329778, 0.
38, 0.5, 0.25, 0.
*Element, type=S3
1, 34, 31, 33
2, 36, 13, 26
3, 26, 13, 14
4, 25, 7, 8
5, 28, 21, 20
6, 25, 24, 23
7, 37, 30, 35
8, 36, 19, 18
*Element, type=S4R
9, 8, 9, 33, 29
10, 29, 24, 25, 8
11, 30, 28, 32, 35
12, 9, 2, 10, 33
13, 29, 33, 31, 27
14, 12, 34, 11, 3
15, 15, 4, 16, 32
16, 6, 35, 17, 1
17, 21, 28, 30, 22
18, 5, 24, 29, 27
19, 26, 20, 19, 36
20, 37, 7, 25, 23
21, 34, 36, 18, 31
22, 32, 28, 14, 15
23, 28, 20, 26, 14
24, 18, 5, 27, 31
25, 32, 16, 17, 35
26, 33, 10, 11, 34
27, 7, 37, 35, 6
28, 34, 12, 13, 36
29, 37, 23, 22, 30
30, 20, 21, 38, 19
31, 22, 23, 38, 21
32, 18, 19, 38, 5
33, 38, 23, 24, 5
*Nset, nset=_PickedSet4, internal, generate
1, 38, 1
*Elset, elset=_PickedSet4, internal, generate
1, 33, 1
** Section: Section-1
*Shell Section, elset=_PickedSet4, material=Material-1
0.01, 5
*End Part
**
**
** ASSEMBLY
**
*Assembly, name=Assembly
**
*Instance, name=Part-1-1, part=Part-1
*End Instance
**
*Node
1, 0.5, 0.25, 0.100000001
*Nset, nset=_PickedSet7, internal, instance=Part-1-1
5, 18, 19, 20, 21, 22, 23, 24
*Elset, elset=_PickedSet7, internal, instance=Part-1-1
5, 6, 8, 17, 18, 19, 24, 29, 30, 31, 32, 33
*Nset, nset=_PickedSet8, internal
1,
*Nset, nset=_PickedSet9, internal, instance=Part-1-1
1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17
*Elset, elset=_PickedSet9, internal, instance=Part-1-1
3, 4, 9, 12, 14, 15, 16, 22, 25, 26, 27, 28
*Nset, nset=_PickedSet10, internal
1,
*Surface, type=NODE, name=_PickedSet7_CNS_, internal
_PickedSet7, 1.
** Constraint: Constraint-1
*MPC
BEAM, _PickedSet7, _PickedSet8
*Element, type=MASS, elset=_PickedSet6_Inertia-1_
1, 1
*Mass, elset=_PickedSet6_Inertia-1_
100.,
*End Assembly
**
** MATERIALS
**
*Material, name=Material-1
*Density
7850.,
*Elastic
2.1e+11, 0.3
**
** BOUNDARY CONDITIONS
**
** Name: BC-1 Type: Symmetry/Antisymmetry/Encastre
*Boundary
_PickedSet9, ENCASTRE
** ----------------------------------------------------------------
**
** STEP: Step-1
**
*Step, name=Step-1, nlgeom=YES
*Static
1., 1., 1e-05, 1.
**
** LOADS
**
** Name: Load-1 Type: Concentrated force
*Cload
_PickedSet10, 1, 0.
_PickedSet10, 2, 0.
_PickedSet10, 3, -1e+06
**
** OUTPUT REQUESTS
**
*Restart, write, frequency=0
**
** FIELD OUTPUT: F-Output-1
**
*Output, field
*Node Output
U,
*Element Output, directions=YES
S,
*Output, history, frequency=0
*End Step
</code></pre>
| <python><python-3.x><abaqus><abaqus-odb> | 2023-07-24 13:08:17 | 1 | 344 | beta green |
76,754,823 | 5,864,426 | Unable to understand why tensorflow cannot convert numpy array to tensor | <p>I'm currently looking to build a CNN-LSTM hybrid model to process Skin cancer images. The images have been resized to (270, 300, 3) (width, height, channels) using the cv2.resize function. This is how I've split the data and created the model.</p>
<pre class="lang-py prettyprint-override"><code>true_labels = np.asarray(test_sample_light_dark['malignant_cancer'])
X_train, X_test, y_train, y_test = train_test_split(sample_light_dark_image_data, true_labels, test_size = 0.2, random_state = 4)
valid_X_train, valid_X_test, valid_y_train, valid_y_test = train_test_split(X_test, y_test, test_size = 0.3, random_state = 4)
# Model Creation
input_shape = (1, 270, 300, 3)
model = Sequential()
model.add(TimeDistributed(Conv2D(64,(3,3),activation='relu'), input_shape=input_shape))
model.add(TimeDistributed(MaxPooling2D(pool_size=(4,4))))
model.add(TimeDistributed(Conv2D(32,(3,3),activation='relu')))
#model_mix_shoulder.add(TimeDistributed(Conv2D(128,(3,3),activation='relu')))
#model_mix_shoulder.add(TimeDistributed(Conv2D(56,(3,3),activation='relu')))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2))))
#model_mix_shoulder.add(TimeDistributed(Conv2D(256,(3,3),activation='relu')))
#model_mix_shoulder.add(TimeDistributed(MaxPooling2D(pool_size=(2,2))))
model.add(TimeDistributed(Flatten()))
#RNN
model.add(LSTM(100,return_sequences=False))
model.add(Dense(2,activation='sigmoid'))
#model.add(activation('sigmoid'))
#model.summary()
model.compile(loss = 'sparse_categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
history = model.fit(X_train, y_train, epochs = 25,validation_data = (valid_X_train, valid_y_train), shuffle=True, batch_size=32)
</code></pre>
<p>The error that I'm getting is as follows:</p>
<pre><code>ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).```
I've double checked that the output of each training dataset sample is a numpy.ndarray of shape (270,300,3) which matches the shape of the input to my CNN. And, I've also checked that I'm able to convert the internal numpy array of the train dataset into a tensor. Where exactly am I going wrong?
I don't have a lot of experience with deep learning in general.
I've tried variaous operations such as reshaping but even they don't work as I got an error saying that the `X_train` data with shape (1600,) cannot be reshaped into (270,300,3).
</code></pre>
| <python><numpy><keras><deep-learning> | 2023-07-24 13:06:59 | 0 | 1,094 | Dhruv Marwha |
76,754,756 | 12,176,250 | Date function, applying to a dataframe not working | <p>Imn trying to write a function that will handle dates in a given format however, i'm having a few issues.</p>
<p>The first issue is when im applying this function using</p>
<pre><code>df['AppointmentDate'] = df['AppointmentDate'].apply(func=date_handler)
</code></pre>
<p>The function works as intended while passing my own list, but it doesnt work when applying to DATAFRAME?</p>
<pre><code>if __name__ == "__main__":
date_handler(
date_list=[
'2022-07-18', '2022-07-02', '2022-07-25', # YYYY-MM-DD
'19-07-2022', '03-07-2022', '26-07-2022', # DD-MM-YYYY
'12-20-2023', '09-08-2022', '05-06-2023', # MM-DD-YYYY
'2022/08/17', '2023/10/20', '2023/01/01', # YYYY/MM/DD
'18/08/2022', '22/10/2023', '01/01/2023', # DD/MM/YYYY
'02/02/2023', '10/23/2023', '12/02/2023', # MM/DD/YYYY
'20230920', '20230822', '20230909', # YYYYMMDD
'20230920', '20230822', '20230909', # DDMMYYYY
'20230920', '20230822', '20230909', # MMDDYYYY
</code></pre>
<p>my dataframe returns with empty values!</p>
<p>The second issue is when i am trying to add more try and excepts (to handle date time (YYYYMMDDHHMMSS+ TIMEZONE) i get the error: SyntaxError: too many statically nested blocks.</p>
<p>Here is my function.</p>
<pre><code>@typechecked
def date_handler(date_list: any) -> print:
for date in date_list:
try:
date_obj = datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%d-%m-%Y')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%m-%d-%Y')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%Y/%m/%d')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%m/%d/%Y')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%Y%m%d')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%d%m%Y')
except ValueError:
try:
date_obj = datetime.datetime.strptime(date, '%m%d%Y')
except ValueError:
print(f"Invalid date format: {date}")
continue
else:
return None
else:
return date_obj.strftime('%Y-%m-%d')
</code></pre>
<p>Any reasons why this is?</p>
| <python><python-3.x> | 2023-07-24 13:00:06 | 2 | 346 | Mizanur Choudhury |
76,754,575 | 859,559 | python glade notebook tabs won't switch | <p>I'm working on a glade python project. I'm using Gtk 3, and I have a notebook widget with several tabs. I cannot get the tabs to work. I double click on a tab and the interface does nothing. What I can do is hit the tab key until the notebook tab is highlighted and then use the arrow keys. I believe it should work if I just double click it. Enclosed is some of my glade file.</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.40.0 -->
<interface>
<requires lib="gtk+" version="3.24"/>
<object class="GtkWindow" id="corpus-top">
<property name="can-focus">False</property>
<child>
<!-- n-columns=1 n-rows=2 -->
<object class="GtkGrid" id="grid">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="hexpand">True</property>
<property name="vexpand">True</property>
<child>
<object class="GtkNotebook" id="notebook">
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="hexpand">True</property>
<property name="vexpand">True</property>
<property name="scrollable">True</property>
<child>
<!-- n-columns=1 n-rows=5 -->
<object class="GtkGrid" id="grid-sources">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="vexpand">True</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkTextView" id="text-sources">
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="hexpand">True</property>
<property name="vexpand">True</property>
<property name="editable">False</property>
<property name="justification">fill</property>
<property name="input-purpose">alpha</property>
<property name="monospace">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">0</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-add">
<property name="label" translatable="yes">add source</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">1</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-finish">
<property name="label" translatable="yes">finish</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">2</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-associate">
<property name="label" translatable="yes">associate</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">3</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-remove">
<property name="label" translatable="yes">remove</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">4</property>
</packing>
</child>
</object>
</child>
<child type="tab">
<object class="GtkLabel" id="label-sources">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="label" translatable="yes">sources</property>
<property name="selectable">True</property>
</object>
<packing>
<property name="tab-fill">False</property>
</packing>
</child>
<child>
<!-- n-columns=1 n-rows=3 -->
<object class="GtkGrid" id="grid-preview">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="vexpand">True</property>
<child>
<object class="GtkTextView" id="text-preview">
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="hexpand">True</property>
<property name="vexpand">True</property>
<property name="editable">False</property>
<property name="accepts-tab">False</property>
<property name="monospace">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">0</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-preview">
<property name="label" translatable="yes">select preview</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">1</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-show">
<property name="label" translatable="yes">show</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">2</property>
</packing>
</child>
</object>
<packing>
<property name="position">1</property>
</packing>
</child>
<child type="tab">
<object class="GtkLabel" id="label-preview">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="label" translatable="yes">preview</property>
<property name="selectable">True</property>
</object>
<packing>
<property name="position">1</property>
<property name="tab-fill">False</property>
</packing>
</child>
<child>
<!-- n-columns=1 n-rows=5 -->
<object class="GtkGrid" id="grid-output">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="vexpand">True</property>
<child>
<object class="GtkButton" id="button-write">
<property name="label" translatable="yes">write</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
<property name="hexpand">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">0</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-spaces">
<property name="label" translatable="yes">spaces for tokenizer</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">1</property>
</packing>
</child>
<child>
<object class="GtkButton" id="button-prompt-edit">
<property name="label" translatable="yes">prompt edit</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">2</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label-status">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="hexpand">True</property>
<property name="label" translatable="yes">option status:</property>
<attributes>
<attribute name="background" value="#f8f8e4e45c5c"/>
</attributes>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">3</property>
</packing>
</child>
<child>
<object class="GtkBox" id="grid-spacer-1">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="vexpand">True</property>
<property name="orientation">vertical</property>
<child>
<placeholder/>
</child>
<child>
<object class="GtkLabel" id="label-mix">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="label" translatable="yes">mix info</property>
<attributes>
<attribute name="background" value="#9999c1c1f1f1"/>
</attributes>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">4</property>
</packing>
</child>
</object>
<packing>
<property name="position">2</property>
</packing>
</child>
<child type="tab">
<object class="GtkLabel" id="label-output">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="label" translatable="yes">output</property>
<property name="selectable">True</property>
</object>
<packing>
<property name="position">2</property>
<property name="tab-fill">False</property>
</packing>
</child>
<child>
<!-- n-columns=3 n-rows=3 -->
<object class="GtkGrid" id="grid-compose">
<property name="visible">True</property>
<property name="can-focus">False</property>
<child>
<object class="GtkButton">
<property name="label" translatable="yes">save</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="left-attach">2</property>
<property name="top-attach">2</property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
<child>
<placeholder/>
</child>
</object>
<packing>
<property name="position">3</property>
</packing>
</child>
<child type="tab">
<object class="GtkLabel" id="label-compose">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="label" translatable="yes">compose dots</property>
</object>
<packing>
<property name="position">3</property>
<property name="tab-fill">False</property>
</packing>
</child>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">1</property>
</packing>
</child>
<child>
<object class="GtkMenuBar" id="menu-bar">
<property name="visible">True</property>
<property name="can-focus">False</property>
<child>
<object class="GtkMenuItem">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="label" translatable="yes">_File</property>
<property name="use-underline">True</property>
<child type="submenu">
<object class="GtkMenu">
<property name="visible">True</property>
<property name="can-focus">False</property>
<child>
<object class="GtkImageMenuItem" id="menu-file-new">
<property name="label">gtk-new</property>
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="use-underline">True</property>
<property name="use-stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="menu-file-open">
<property name="label">gtk-open</property>
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="use-underline">True</property>
<property name="use-stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="menu-file-save">
<property name="label">gtk-save</property>
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="use-underline">True</property>
<property name="use-stock">True</property>
</object>
</child>
<child>
<object class="GtkSeparatorMenuItem">
<property name="visible">True</property>
<property name="can-focus">False</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="menu-file-quit">
<property name="label">gtk-quit</property>
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="use-underline">True</property>
<property name="use-stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="GtkMenuItem">
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="label" translatable="yes">_Help</property>
<property name="use-underline">True</property>
<child type="submenu">
<object class="GtkMenu" id="menu-help-about">
<property name="visible">True</property>
<property name="can-focus">False</property>
<child>
<object class="GtkImageMenuItem">
<property name="label">gtk-about</property>
<property name="visible">True</property>
<property name="can-focus">False</property>
<property name="use-underline">True</property>
<property name="use-stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
</object>
<packing>
<property name="left-attach">0</property>
<property name="top-attach">0</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
</code></pre>
| <python><glade> | 2023-07-24 12:37:25 | 1 | 347 | D Liebman |
76,753,543 | 20,240,835 | snakemake chose rule to run | <p>I am trying to edit a snakemake pipeline, This pipeline has a lot of rules, like:</p>
<pre><code>rule A:
rule B:
rule C:
...
</code></pre>
<p>The <code>rule C</code> input is the output of B, here is a simple example:</p>
<pre><code>rule B:
output:
'path/to/output_B.txt'
shell:
"""
echo "This is rule B output" > {output}
"""
rule C:
input:
'path/to/output_B.txt'
output:
'path/to/output_C.txt'
shell:
"""
cat {input} > {output}
"""
</code></pre>
<p>My expected:</p>
<p>Now, I want to add a <code>rule D</code> and a params in configfile called <code>use_rule_D</code>, when <code>use_rule_D</code> be set to <code>true</code>, I want snakemake call <code>rule D</code> to generate input of <code>rule C</code> instead <code>rule B</code></p>
<p>My solutions:</p>
<p>I add <code>rule D</code> with output <code>/path/to/output_D.txt</code> and use a function to chose the input of <code>rule B</code>, Its work</p>
<pre><code>rule B:
output:
'path/to/output_B.txt'
shell:
"""
echo "This is rule B output" > {output}
"""
def get_input(config):
if config['use_rule_D']:
return 'path/to/output_D.txt'
return 'path/to/output_B.txt'
rule C:
input:
input_data=get_input(config)
output:
'path/to/output_C.txt'
shell:
"""
cat {input.input} > {output}
"""
rule D:
output:
'path/to/output_D.txt'
shell:
"""
echo "This is rule D output" > {output}
"""
</code></pre>
<p>But, there are many rule in my real snakemake script need the output of <code>rule B</code>, This means that I need to modify every relevant input. I want to create a simple method to make Snakemake generate <code>/path/to/output_B.txt</code> using different rules under different parameters.</p>
| <python><bioinformatics><snakemake> | 2023-07-24 10:23:58 | 1 | 689 | zhang |
76,753,393 | 11,016,112 | Challenges Processing TEM Images with Colmap | <p>I am currently facing a challenge with using Colmap for handling Transmission Electron Microscopy (TEM) images, and I'm seeking guidance or insights from anyone familiar with this issue.</p>
<p>I have been using Colmap successfully for other types of images, but when attempting to process TEM images, I encountered unexpected difficulties. Despite following the standard procedures and parameter adjustments, the results obtained from Colmap seem suboptimal or even erroneous. The problem might lie in the specific characteristics of TEM images, such as low signal-to-noise ratios, high contrast, and unique imaging distortions, which might not be effectively handled by the default settings of Colmap.</p>
<p>I have already explored various avenues to resolve the problems, such as experimenting with different feature extractors, adjusting keypoint matching algorithms, and adjusting Colmap parameters, but the results remain unsatisfactory.</p>
<p>If anyone has encountered similar issues while using Colmap with TEM images or has expertise in working with TEM data in other photogrammetry software, I would greatly appreciate any insights, suggestions, or alternative approaches to tackle this challenge.</p>
<p>Alternatively, if you could recommend specialized software or plugins that are better suited for handling TEM images, I would be eager to explore those options as well.</p>
| <python><image-processing><computer-vision><camera-calibration><colmap> | 2023-07-24 10:04:37 | 1 | 617 | Mithun Das |
76,753,346 | 662,285 | validate nested json schema required property | <p>I have nested json schema like below , how to define the required properties for same ?
Let's say i need to define required property for "version" which is under "baseline". Since i have version also under "pattern", so just defining "baseline" as required will work ? "baseline is static text but "version" under "baseline" is something i want to make as required field.</p>
<pre><code> "versions":{
"type":"object",
"properties":{
"pattern":{
"version":{
"type": string
"description": string
}
},
"baseline":{
"version":{
"type": string
"description": string
}
}
},
"required":[
"baseline"
]
}
</code></pre>
| <python><json> | 2023-07-24 09:59:04 | 1 | 4,564 | Bokambo |
76,753,158 | 9,811,964 | Grouping locations of people | <p>I have a pandas dataframe containing information about a person's location, including their <code>latitude</code>, <code>longitude</code>, and <code>story</code>. To break down this dataframe into smaller chunks, each containing 9 rows, I need to consider the following requirements:</p>
<p>Each chunk of the dataframe should not contain rows where both the "latitude" and "longitude" values are identical, as this indicates that both individuals live in the same building. However, within each chunk, the <code>latitude</code> and <code>longitude</code> values should be similar, implying that the people in that chunk live in close proximity to each other, but not at the exact same location.</p>
<p>Perhaps defining the term "close proximity" could prove beneficial. The simplest approach is to determine the closest neighbor. For instance, if individual <code>a</code> is nearby <code>b</code>, and <code>b</code> is the closest to <code>c</code>, and <code>c</code> is the next nearest to <code>d</code> (and so on), this ensures that the cluster (chunk) is composed of people from the same neighborhood.</p>
<p>In essence, we seek an algorithm that groups individuals into chunks based on these criteria, resulting in clusters of people who live in close proximity to each other but not too close.
In the very last step I will append each chunk to create one big dataframe.</p>
<pre><code>df = {
"latitude": [49.5619579, 49.5619579, 49.5628938, 49.5628938, 49.5630028, 49.5633175, 49.56397639999999, 49.5659508, 49.566359, 49.56643220000001, 49.56643220000001, 49.5672061, 49.567729, 49.5677449, 49.5679685, 49.5679685, 49.568089, 49.5686342, 49.5687609, 49.5688543, 49.5690616, 49.5695834, 49.5706579, 49.5711228, 49.5713705, 49.5716422, 49.5717749]
"longitude": [10.9995758, 10.9995758, 11.000319, 11.000319, 10.9990996, 10.9993819, 11.004145, 10.9873409, 11.0003023, 10.9999593, 10.9999593, 10.9935709, 11.0011213, 10.9954016, 10.9982288, 10.9982288, 10.9894035, 10.9896749, 10.9887881, 10.9975928, 10.9931367, 10.9851579, 10.9853273, 10.9912959, 10.9939141, 10.9910182, 10.9867083]
}
"story": [2.0, 4.0, 3.0, 4.0, 1.0, 2.0, 3.0, 1.0, 3.0, 1.0, 5.0, 1.0, 1.0, 1.0, 1.0, 5.0, 5.0, 1.0, 3.0, 2.0, 3.0, 2.0, 2.0, 4.0, 4.0, 5.0, 5.0]
</code></pre>
<p>The actual dataframe is much larger. Here are the first 9 rows:</p>
<pre><code>MasterKitchen_Latitude MasterKitchen_Longitude MasterKitchen_Story
0 49.561958 10.999576 2.0
1 49.561958 10.999576 4.0
2 49.562894 11.000319 3.0
3 49.562894 11.000319 4.0
4 49.563003 10.999100 1.0
5 49.563317 10.999382 2.0
6 49.563976 11.004145 3.0
7 49.565951 10.987341 1.0
8 49.566359 11.000302 3.0
</code></pre>
<h1>Code from ongoing discussion</h1>
<pre><code>df = pd.DataFrame(data)
# Create a new column "lat_long" by combining latitude and longitude as strings
df["lat_long"] = df["latitude"].astype(str) + "_" + df["longitude"].astype(str)
# Now, you can use groupby on the "lat_long" column
grouped_df = df.groupby("lat_long")
print(grouped_df.mean())
</code></pre>
| <python><pandas><dataframe><sorting><localization> | 2023-07-24 09:36:45 | 1 | 1,519 | PParker |
76,753,037 | 10,966,677 | How to list the field names from a Django serializer | <p>I have a model serializer and I was wondering how to get a list of the names of the fields of this serializer. Similarly, I know how to get a list of the fields form a model and from a form.</p>
<p>Example model:</p>
<pre><code>class Account(models.Model):
account_holder = models.CharField(blank=False, max_length=50)
age = models.IntegerField(blank=False)
salary = models.DecimalField(blank=False, max_digits=10, decimal_places=2)
</code></pre>
<p>Then the list of fields can be derived from:</p>
<pre><code>obj_fields = Account._meta.get_fields() # as objects
[field.name for field in Account._meta.get_fields()] # as list of strings
# output: ['id', 'account_holder', 'age', 'salary']
</code></pre>
<p>From the form:</p>
<pre><code>class AccountForm(forms.ModelForm):
class Meta:
fields = '__all__'
model = Account
</code></pre>
<p>The list of the form fields (one of the possible methods without derailing into a different topic):</p>
<pre><code>fields = AccountForm.base_fields # as dictionary of objects
[field for field in AccountForm.base_fields.keys()] # as list of strings
# output: ['account_holder', 'age', 'salary']
</code></pre>
<p>And I have a serializer:</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = (
'id',
'account_holder',
'age',
'salary',
'age_score',
'salary_score',
)
</code></pre>
<p>which has a few more fields than the model. But for example using the following, it throws an error:</p>
<pre><code>>>> AccountSerializer.get_field_names()
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: ModelSerializer.get_field_names() missing 3 required positional arguments: 'self', 'declared_fields', and 'info'
</code></pre>
<p>Clearly, I ignore how to use this method and if there is another method.</p>
| <python><django> | 2023-07-24 09:20:51 | 2 | 459 | Domenico Spidy Tamburro |
76,752,946 | 8,040,369 | Create a custom email template in python | <p>I need to create a email template in Python to send mail in smtp().
And i need the template to be in the below format, will that be possible ?</p>
<p><a href="https://i.sstatic.net/DmoYE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DmoYE.png" alt="enter image description here" /></a></p>
<p>I got this template from python org and i am not sure how to scale it up to something like in the image.</p>
<pre><code> <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
table {
background: white;
border-radius:3px;
border-collapse: collapse;
height: auto;
max-width: 900px;
padding:5px;
width: 100%;
animation: float 5s infinite;
}
th {
color:#FFFFFF;;
background:#1976d2;
border-bottom: 4px solid #9ea7af;
font-size:14px;
font-weight: 300;
padding:10px;
text-align:center;
vertical-align:middle;
}
tr {
border-top: 1px solid #C1C3D1;
border-bottom: 1px solid #C1C3D1;
border-left: 1px solid #C1C3D1;
color:#666B85;
font-size:16px;
font-weight:normal;
}
tr:hover td {
background:#0000FF;
color:#FFFFFF;
border-top: 1px solid #22262e;
}
td {
background:#FFFFFF;
padding:10px;
text-align:left;
vertical-align:middle;
font-weight:300;
font-size:13px;
border-right: 1px solid #C1C3D1;
}
</style>
</head>
<body>
Dear Somebody,<br> <br>
Bla-bla-bla<br><br>
<table>
<thead>
<tr style="border: 1px solid #1b1e24;">
<th>Ticket ID</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
<th>head5</th>
<th>head6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
<br>
Bla-bla.<br>
For more assistance please contact our support team:
<a href='mailto:some_email@gmail.com'>some_email@gmail.com</a>.<br> <br>
Thank you!
</body>
</html>
"""
message = MIMEMultipart("alternative", None, [MIMEText(HTML, 'html')])
message['Subject'] = SUBJECT
message['From'] = SENDER_EMAIL
message['To'] = RECEIVER_EMAIL
</code></pre>
<p>Basically having the skeleton is enough with header and rows.</p>
<p>Anyhelp is much appreciated.</p>
<p>Thanks,</p>
| <python><html><html-table> | 2023-07-24 09:09:57 | 1 | 787 | SM079 |
76,752,630 | 5,363,621 | Python / remove duplicate from each group if condition meets in the group | <p>I want to delete the rows in each group if there is the duplicate only in particular value of a column</p>
<pre><code>df = pd.DataFrame({
'group': ['A', 'A', 'B', 'B', 'B', 'C', 'C'],
'channel':['X','Y','Y','X','X','A','X'],
'value': [1, 2, 3, 3, 4, 5, 5]
})
</code></pre>
<p><a href="https://i.sstatic.net/XX4iE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XX4iE.png" alt="enter image description here" /></a></p>
<p>I want to keep the rows in each group only with first occurence of X and delete others as below</p>
<p><a href="https://i.sstatic.net/j4x0q.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/j4x0q.png" alt="enter image description here" /></a></p>
<p>I tried below code but this delets all rows that have duplicate channel value irrespective of whther channel = X or not</p>
<pre><code>df = df.groupby('group').apply(lambda x: x.drop_duplicates(subset='channel', keep='first') if 'X' in x['channel'].values else x)
</code></pre>
| <python><pandas> | 2023-07-24 08:25:34 | 1 | 915 | deega |
76,752,571 | 5,384,099 | How to convert internal DB models to another model for an API response? | <p>When I do a POST request with the following code, I get a Pydantic conversion error and I don't understand what is wrong.</p>
<pre class="lang-py prettyprint-override"><code>class UserBase(BaseModel):
rest_id: str
email: str
password: str
firstname: str
lastname: str
nickname: str
def db_to_api_User(user : models.User) -> UserBase:
u = UserBase()
u.rest_id = user.rest_id
u.email = user.email
u.password = ""
u.firstname = user.firstname
u.lastname = user.lastname
u.nickname = user.nickname
return u
@app.post("/users/", status_code=status.HTTP_201_CREATED)
def create_user(user: UserBase, db: db_dependency):
if not user.email:
raise HTTPException(status_code = status.HTTP_422_UNPROCESSABLE_ENTITY, detail="email is not allowed to be empty")
if not user.password:
raise HTTPException(status_code = status.HTTP_422_UNPROCESSABLE_ENTITY, detail="password is not allowed to be empty")
user.rest_id = str(uuid4())
new_usr = api_to_db_User(user)
db.add(new_usr)
db.commit()
user = db.query(models.User).filter(models.User.rest_id == new_usr.rest_id).first()
return db_to_api_User(user)
</code></pre>
<p>The entry gets inserted into the db and I thought you could just create a <code>UserBase</code> and return it. I don't want to expose the internal database structure since I want to abstract how it is stored. (It might be changed to different storage methods later).</p>
<p>The return value gives me this error:</p>
<pre><code>draft_1-app_draft_1-1 | ERROR: Exception in ASGI application
draft_1-app_draft_1-1 | Traceback (most recent call last):
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 408, in run_asgi
draft_1-app_draft_1-1 | result = await app( # type: ignore[func-returns-value]
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
draft_1-app_draft_1-1 | return await self.app(scope, receive, send)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 289, in __call__
draft_1-app_draft_1-1 | await super().__call__(scope, receive, send)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 122, in __call__
draft_1-app_draft_1-1 | await self.middleware_stack(scope, receive, send)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 184, in __call__
draft_1-app_draft_1-1 | raise exc
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 162, in __call__
draft_1-app_draft_1-1 | await self.app(scope, receive, _send)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/middleware/exceptions.py", line 79, in __call__
draft_1-app_draft_1-1 | raise exc
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/middleware/exceptions.py", line 68, in __call__
draft_1-app_draft_1-1 | await self.app(scope, receive, sender)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__
draft_1-app_draft_1-1 | raise e
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__
draft_1-app_draft_1-1 | await self.app(scope, receive, send)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 718, in __call__
draft_1-app_draft_1-1 | await route.handle(scope, receive, send)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 276, in handle
draft_1-app_draft_1-1 | await self.app(scope, receive, send)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 66, in app
draft_1-app_draft_1-1 | response = await func(request)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 273, in app
draft_1-app_draft_1-1 | raw_response = await run_endpoint_function(
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 192, in run_endpoint_function
draft_1-app_draft_1-1 | return await run_in_threadpool(dependant.call, **values)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 41, in run_in_threadpool
draft_1-app_draft_1-1 | return await anyio.to_thread.run_sync(func, *args)
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/anyio/to_thread.py", line 33, in run_sync
draft_1-app_draft_1-1 | return await get_asynclib().run_sync_in_worker_thread(
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 877, in run_sync_in_worker_thread
draft_1-app_draft_1-1 | return await future
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/anyio/_backends/_asyncio.py", line 807, in run
draft_1-app_draft_1-1 | result = context.run(func, *args)
draft_1-app_draft_1-1 | File "/code/main.py", line 71, in create_user
draft_1-app_draft_1-1 | return db_to_api_User(user).dict()
draft_1-app_draft_1-1 | File "/code/main.py", line 51, in db_to_api_User
draft_1-app_draft_1-1 | u = UserBase()
draft_1-app_draft_1-1 | File "/usr/local/lib/python3.9/site-packages/pydantic/main.py", line 150, in __init__
draft_1-app_draft_1-1 | __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
draft_1-app_draft_1-1 | pydantic_core._pydantic_core.ValidationError: 6 validation errors for UserBase
draft_1-app_draft_1-1 | rest_id
draft_1-app_draft_1-1 | Field required [type=missing, input_value={}, input_type=dict]
draft_1-app_draft_1-1 | For further information visit https://errors.pydantic.dev/2.0.3/v/missing
draft_1-app_draft_1-1 | email
draft_1-app_draft_1-1 | Field required [type=missing, input_value={}, input_type=dict]
draft_1-app_draft_1-1 | For further information visit https://errors.pydantic.dev/2.0.3/v/missing
draft_1-app_draft_1-1 | password
draft_1-app_draft_1-1 | Field required [type=missing, input_value={}, input_type=dict]
draft_1-app_draft_1-1 | For further information visit https://errors.pydantic.dev/2.0.3/v/missing
draft_1-app_draft_1-1 | firstname
draft_1-app_draft_1-1 | Field required [type=missing, input_value={}, input_type=dict]
draft_1-app_draft_1-1 | For further information visit https://errors.pydantic.dev/2.0.3/v/missing
draft_1-app_draft_1-1 | lastname
draft_1-app_draft_1-1 | Field required [type=missing, input_value={}, input_type=dict]
draft_1-app_draft_1-1 | For further information visit https://errors.pydantic.dev/2.0.3/v/missing
draft_1-app_draft_1-1 | nickname
draft_1-app_draft_1-1 | Field required [type=missing, input_value={}, input_type=dict]
draft_1-app_draft_1-1 | For further information visit https://errors.pydantic.dev/2.0.3/v/missing
</code></pre>
<p>Am I not allowed to create a UserBase class like I do?</p>
| <python><fastapi><pydantic> | 2023-07-24 08:16:35 | 0 | 387 | Decaf Sux |
76,752,429 | 5,528,270 | Using high-pass filters in C# | <p>I generated a 1 Hz sine waveform for 10 seconds.
I passed it through a second-order high-pass filter with a cutoff frequency of 3 Hz.
I saved them to CSV.
I graphed them in Python.
But it is not nearly attenuated.
What am I doing wrong?
I try a similar process in Python and it is attenuated.</p>
<p>I use this.</p>
<p><a href="https://filtering.mathdotnet.com/api/MathNet.Filtering/OnlineFilter.htm#CreateHighpass" rel="nofollow noreferrer">https://filtering.mathdotnet.com/api/MathNet.Filtering/OnlineFilter.htm#CreateHighpass</a></p>
<p>Maybe I should use <code>ImpulseResponse.Infinite</code> instead of <code>ImpulseResponse.Finite</code>. But when I use it, the value keeps increasing and I don't get a decaying sine waveform.</p>
<p>But maybe I should use this.</p>
<p><a href="https://filtering.mathdotnet.com/api/MathNet.Filtering.Butterworth/IirCoefficients.htm#HighPass" rel="nofollow noreferrer">https://filtering.mathdotnet.com/api/MathNet.Filtering.Butterworth/IirCoefficients.htm#HighPass</a></p>
<p>If I give each of the following parameters, how should I replace the current code?</p>
<pre><code>stopbandFreq = 1.0
passbandFreq = 4.0
passbandRipple = 1.0
stopbandAttenuation = -20.0
</code></pre>
<h2>Code by C#</h2>
<pre><code>using System;
using MathNet.Filtering;
using MathNet.Numerics;
using System.IO;
using System.Globalization;
class Program
{
const double sampleFreq = 600;
const double amplitude = 100;
const double frequency = 1;
const double duration = 10;
const double samplePeriod = 1.0 / sampleFreq;
const double cutOffFrequency = 3;
const int filterOrder = 2;
static void Main(string[] args)
{
var sampleCount = sampleFreq * duration;
var signal = Generate.Sinusoidal((int)sampleCount, sampleFreq, frequency, amplitude);
var filter = OnlineFilter.CreateHighpass(ImpulseResponse.Finite, sampleFreq, cutOffFrequency, filterOrder);
var filteredSignal = filter.ProcessSamples(signal);
string path = "data_csharp.csv";
string header = "Time,RawData_uV,FilteredRawData_uV";
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(header);
for (int i = 0; i < sampleCount; i++)
{
DateTime datetime = DateTime.Now.AddSeconds(i * samplePeriod);
sw.WriteLine(String.Format("{0},{1},{2}", datetime.ToString("yyyy/MM/dd HH:mm:ss.fff", CultureInfo.CurrentCulture), signal[i], filteredSignal[i]));
}
}
}
}
</code></pre>
<h2>Code by Python</h2>
<pre><code>import numpy as np
from scipy import signal
import pandas as pd
from datetime import datetime, timedelta
# from matplotlib import pyplot as plt
def generate_dummy_signal(frequency, amplitude, duration, sample_rate):
time = np.arange(0, duration, 1/sample_rate)
signal = amplitude * np.sin(2 * np.pi * frequency * time)
return time, signal
def apply_hpf(input_signal, cutoff_frequency, sample_rate, order):
b, a = signal.butter(order, cutoff_frequency, btype='high', analog=False, fs=sample_rate)
filtered_signal = signal.lfilter(b, a, input_signal)
return filtered_signal
# Constants
FREQUENCY = 1 # in Hz
AMPLITUDE = 100 # in µV
DURATION = 10 # in seconds
SAMPLE_RATE = 600 # in Hz
CUTOFF_FREQUENCY = 3 # in Hz
ORDER = 2 # order of the filter
# Generate the dummy signal
time, raw_signal = generate_dummy_signal(FREQUENCY, AMPLITUDE, DURATION, SAMPLE_RATE)
# Apply the HPF
filtered_signal = apply_hpf(raw_signal, CUTOFF_FREQUENCY, SAMPLE_RATE, ORDER)
# Generate time-series starting from current timestamp
timestamps = [datetime.now() + timedelta(seconds=time[i]) for i in range(len(time))]
# Create dictionary for creating DataFrame
data_dict = {
'Time': timestamps,
'RawData_uV': raw_signal,
'FilteredRawData_uV': filtered_signal
}
# Create DataFrame
data_df = pd.DataFrame(data_dict)
# Write DataFrame to CSV
data_df.to_csv('data.csv', index=False)
</code></pre>
<h2>Generated csv by C# graphed in Python</h2>
<p><a href="https://i.sstatic.net/3BQVU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/3BQVU.png" alt="enter image description here" /></a></p>
<h2>Generated csv by C# (Infinite) graphed in Python</h2>
<p><a href="https://i.sstatic.net/AtsVq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AtsVq.png" alt="enter image description here" /></a></p>
<h2>Generated csv by Python graphed in Python</h2>
<p><a href="https://i.sstatic.net/L6LZb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/L6LZb.png" alt="enter image description here" /></a></p>
| <python><c#><scipy><highpass-filter><mathnet-filtering> | 2023-07-24 07:58:23 | 1 | 1,024 | Ganessa |
76,752,415 | 11,329,736 | Bash command runs in shell, but not via Python subprocess | <p>I want to run the following Bash command in Python:</p>
<pre><code>import subprocess
command = 'tar -vcz -C /mnt/20TB_raid1 Illumina_Sequencing_Data | pigz | tee >(md5sum > "md5sum_Illumina_Sequencing_Data.txt") | split -b 50G - /mnt/4TB_SSD/Illumina_Sequencing_Data.tar.gz.part-'
subprocess.run(command.split(" "))
</code></pre>
<p>When I run this code I get the following error:</p>
<pre><code>tar: 50G: Invalid blocking factor
Try 'tar --help' or 'tar --usage' for more information.
</code></pre>
<p>However, when I run this command in the shell directly it run without any issues. It looks like some code is ignored as it thinks the <code>split</code> -b flag is parsed to tar?</p>
| <python><bash><subprocess> | 2023-07-24 07:56:40 | 1 | 1,095 | justinian482 |
76,752,389 | 1,118,698 | Python Flask: how to build a template via a function that is not a route | <p>I'm trying to build a side navigation and import it into a base html file.</p>
<p>The code in <code>base.html</code> looks like this:</p>
<pre><code><html lang="en">
<head>
</head>
<body>
<p>hello</p>
{% include 'sidenav.html' %}
</body>
</html>
</code></pre>
<p>I then have a file that builds the navigation via code. The relevant code is here:</p>
<pre><code>## sidenav.py
import os
from flask import Flask, render_template
from jinja2 import Environment, BaseLoader
def build():
env = Environment(loader = BaseLoader())
t = env.get_template('sidenav.html')
</code></pre>
<p>then <code>__init__.py</code> has this:</p>
<pre><code>import os
from flask import Flask
def create_app(test_config=None):
from .layout.sidenav import build
build()
</code></pre>
<p>I get <code>jinja2.exceptions.TemplateNotFound: sidenav.html</code></p>
<p>It doesn't matter if I place <code>sidenav.py</code> at the same level as <code>__init__.py</code> or in a subfolder. I get the same error.</p>
<p>I'm hoping it is possible to build this sidenav without passing all the arguments via routes. I'm not sure how I would approach this.</p>
| <python><flask> | 2023-07-24 07:52:46 | 1 | 1,085 | dizzystar |
76,752,255 | 264,136 | Issue in getting Python location in macbook | <p>I had 3.11 already and installed 3.10 now.</p>
<pre class="lang-none prettyprint-override"><code>ls
3.10 3.11 Current
</code></pre>
<pre class="lang-none prettyprint-override"><code>pwd
/Library/Frameworks/Python.framework/Versions/3.10/bin
</code></pre>
<pre class="lang-none prettyprint-override"><code>ls
2to3 pip3.10 python3-intel64
2to3-3.10 pydoc3 python3.10
idle3 pydoc3.10 python3.10-config
idle3.10 python3 python3.10-intel64
pip3 python3-config
</code></pre>
<pre class="lang-none prettyprint-override"><code>python3 --version
Python 3.11.4
</code></pre>
<p>Why is it showing as 3.11.4 when the directory I am in is <code>/Library/Frameworks/Python.framework/Versions/3.10/bin</code>?</p>
| <python><macos> | 2023-07-24 07:29:40 | 1 | 5,538 | Akshay J |
76,752,114 | 16,383,578 | How to efficiently do binary search on reverse sorted list in Python? | <p>I want to do binary search on reverse sorted lists in Python. The list is appended in reverse order, and it has to be like this or else my code will break.</p>
<p>I need the code to be as fast as possible, assume the list is huge. I know Python code is slow so the code has to be compiled. And I know the <code>bisect</code> module in the standard library imports precompiled <code>_bisect</code> module if found, <code>_bisect</code> is implemented in C which is very fast.</p>
<p>However it doesn't work on reverse sorted lists, I tried <code>key = lambda x: -x</code> and it didn't work:</p>
<pre><code>In [51]: l = range(50, 0, -5)
In [52]: from bisect import bisect
In [53]: bisect(l, 18, key=lambda x: -x)
Out[53]: 10
</code></pre>
<p>I copied code from the file from the installation and modified it:</p>
<pre><code>def bisect_right(a, x):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if x < a[mid]:
hi = mid
else:
lo = mid + 1
return lo
</code></pre>
<p>Change <code>x < a[mid]</code> to <code>x > a[mid]</code> will make it work on reverse sorted lists.</p>
<pre><code>def reverse_bisect(a, x):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo + hi) // 2
if x > a[mid]:
hi = mid
else:
lo = mid + 1
return lo
</code></pre>
<p>The uncompiled code is much slower than precompiled code, as expected. Also note I cannot compare the performance of <code>reverse_bisect</code> against <code>_bisect.bisect</code> because the latter doesn't work properly in this case.</p>
<pre><code>In [55]: %timeit bisect(range(0, 10**7, 10), 4096)
2.91 µs ± 97.3 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
In [56]: %timeit bisect_right(range(0, 10**7, 10), 4096)
5.22 µs ± 87.9 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
</code></pre>
<p>So I tried to compile the functions using <code>numba.jit</code>, I added <code>@numba.jit(nopython=True, fastmath=True, cache=True, forceobj=False)</code> to the line before <code>bisect_right</code>, producing <code>bisect_right_nb</code>, but <code>bisect_right_nb</code> gives me a warning and is <em><strong>SIX ORDERS OF MAGNITUDE SLOWER</strong></em>:</p>
<pre><code>In [59]: @numba.jit(nopython=True, fastmath=True, cache=True, forceobj=False)
...: def bisect_right_nb(a: list, x: int):
...: lo, hi = 0, len(a)
...: while lo < hi:
...: mid = (lo + hi) // 2
...: if x < a[mid]:
...: hi = mid
...: else:
...: lo = mid + 1
...: return lo
In [60]: l = list(range(0, 10**7, 10))
In [61]: %timeit bisect_right_nb(l, 4096)
C:\Python310\lib\site-packages\numba\core\ir_utils.py:2149: NumbaPendingDeprecationWarning:
Encountered the use of a type that is scheduled for deprecation: type 'reflected list' found for argument 'a' of function 'bisect_right_nb'.
For more information visit https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-reflection-for-list-and-set-types
File "<ipython-input-59-23a3cb61146c>", line 2:
@numba.jit(nopython=True, fastmath=True, cache=True, forceobj=False)
def bisect_right_nb(a: list, x: int):
^
warnings.warn(NumbaPendingDeprecationWarning(msg, loc=loc))
1.66 s ± 11.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [62]: 1.66*10**6/5.22
Out[62]: 318007.66283524904
</code></pre>
<p>Just how can I improve the performance of <code>reverse_bisect_right</code>?</p>
<hr />
<p>And no, I have read this <a href="https://stackoverflow.com/a/69608002/16383578">answer</a>, I am not trying to insert the element into the list, I am trying to get rid of all elements smaller than it.</p>
<p>(And my network connection is unstable, my ISP is disrupting my VPN connection, so my update took so long.)</p>
| <python><python-3.x><performance><optimization> | 2023-07-24 07:06:09 | 1 | 3,930 | Ξένη Γήινος |
76,751,751 | 11,630,148 | Why are there 2 windows on my app? I'm using ttkbootstrap | <p>I'm creating a small app that just gets jokes from an API using ttkbootstrap. The problem is there are 2 windows showing when I run the app. Anyone know what I'm doing wrong?</p>
<p>Here's the code:</p>
<pre class="lang-py prettyprint-override"><code>import requests
import ttkbootstrap as tb
from ttkbootstrap.constants import *
def get_joke():
url = "https://icanhazdadjoke.com"
headers = {'Accept': 'application/json'}
joke_time = requests.get(url, headers=headers).json().get('joke')
label.config(text=joke_time)
print(joke_time)
label = tb.Label(text="", font=("Poppins", 16), bootstyle='default')
label.pack(padx=5, pady=10)
btn = tb.Button(text="Get Joke!", command=get_joke)
btn.pack(padx=5, pady=10)
if __name__ == '__main__':
app = tb.Window(themename='darkly')
app.title('Joke App')
app.geometry('1280x900')
app.mainloop()
</code></pre>
<p>Here is a screenshot of what's happening
<a href="https://i.sstatic.net/2Vctj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2Vctj.png" alt="double window on tkinter ttkbootstrap" /></a></p>
| <python><tkinter><ttkbootstrap> | 2023-07-24 05:56:42 | 1 | 664 | Vicente Antonio G. Reyes |
76,751,412 | 19,366,064 | SQLAlchemy: Maximum recursion depth exceeded while calling a python object | <p>Here are the 4 tables that I created using sqlalchemy.orm</p>
<pre><code>from sqlalchemy.orm import Mapped, mapped_column, relationship, DeclarativeBase, MappedAsDataclass, Session, sessionmaker
from sqlalchemy import ForeignKey, create_engine
from sqlalchemy.dialects.postgresql import VARCHAR, INTEGER, NUMERIC
DATABASE_URL = 'postgresql://postgres:0000@localhost:5432/store'
engine = create_engine(url = DATABASE_URL)
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = Session()
class Base(DeclarativeBase, MappedAsDataclass):
pass
class User(Base):
__tablename__ = 'user'
id: Mapped[int] = mapped_column(INTEGER, primary_key=True, init=False)
username: Mapped[str] = mapped_column(VARCHAR, unique=True)
purchases: Mapped[list['Purchase']] = relationship(back_populates= 'user', init=False, cascade='all, delete')
class Manufacturer(Base):
__tablename__ = 'manufacturer'
id: Mapped[int] = mapped_column(INTEGER, primary_key=True, init=False)
name: Mapped[str] = mapped_column(VARCHAR)
products: Mapped[list['Product']] = relationship(back_populates='manufacturer', init=False)
class Product(Base):
__tablename__ = 'product'
id: Mapped[int] = mapped_column(INTEGER, primary_key=True, init=False)
name: Mapped[str] = mapped_column(VARCHAR, index=True)
manufacturer_id: Mapped[int] = mapped_column(ForeignKey('manufacturer.id'), init=False)
manufacturer: Mapped['Manufacturer'] = relationship(back_populates='products')
purchases: Mapped[list['Purchase']] = relationship(back_populates= 'product', init=False)
class Purchase(Base):
__tablename__ = 'purchase'
id: Mapped[int] = mapped_column(INTEGER, primary_key=True, init=False)
user_id: Mapped[int] = mapped_column(ForeignKey('user.id'), init=False)
product_id: Mapped[int] = mapped_column(ForeignKey('product.id'), init=False)
cost: Mapped[float] = mapped_column(NUMERIC(10, 2), index=True)
user: Mapped['User'] = relationship(back_populates='purchases')
product: Mapped['Product'] = relationship(back_populates='purchases')
</code></pre>
<p>This is the sequence in which I am running it</p>
<pre><code>def create_user():
u = User(username = 'john')
session.add(u)
session.commit()
def create_manufacturer():
m = Manufacturer(name='apple')
session.add(m)
session.commit()
def create_product():
m = session.query(Manufacturer).where(Manufacturer.id == 1).first()
p = Product(name='iphone', manufacturer=m)
session.add(p)
session.commit()
def create_purchase():
p = session.query(Product).where(Product.id == 1).first()
u = session.query(User).where(User.id == 1).first()
pur = Purchase(cost = 999.99, product=p, user = u)
session.add(pur)
session.commit()
def show_user_purchases():
user = session.query(User).where(User.id == 1).first()
print(user.purchases)
Base.metadata.drop_all(bind=engine)
Base.metadata.create_all(bind = engine)
create_user()
create_manufacturer()
create_product()
create_purchase()
show_user_purchases()
</code></pre>
<p>Base on the output:</p>
<p>[Purchase(id=1, user_id=1, product_id=1, cost=Decimal('999.99'), user=User(id=1, username='john', purchases=[...]), product=Product(id=1, name='iphone', manufacturer_id=1, manufacturer=Manufacturer(id=1, name='apple', products=[...]), purchases=[...]))]</p>
<p>I suspect there is an infinite loop going on between user and purchases. Is there a way to fix it?</p>
| <python><sqlalchemy><fastapi> | 2023-07-24 04:28:07 | 1 | 544 | Michael Xia |
76,751,400 | 1,492,229 | how to shrink number of data in an array in a dataframe in python | <p>I have a dataset that has more than 50,000 records</p>
<p>it looks like this</p>
<pre><code>PtsID VisitID Diseaes
134 529 [Pancreatitis, Anxiety, Bronchitis]
134 909 [Dementia]
608 335 [Fibroids, Anxiety]
531 180 [Nosebleed, Dementia, Pancreatitis, Stroke]
531 773 [Stroke]
599 552 [Tonsillitis, Fibroids]
926 643 [Flu, Depression, Depression]
505 935 [Kidney stones, Bronchitis]
791 359 [Covid]
...
...
960 089 [Scabies, Norovirus, Kidney stones, Hay fever]
827 228 [Schizophrenia]
827 359 [Depression, Chilblains, Allergies]
664 690 [Thrush, Scabies, Flu]
</code></pre>
<p>I want to limit this list of diseases by only keeping the top 100 most common diseases</p>
<p>so the list will be like this (assuming these diseases on the top 100 common diseaese</p>
<pre><code>Anxiety, Bronchitis, Dementia, Flu, Depression, Schizophrenia, Allergies
PtsID VisitID Diseaes
134 529 [Anxiety, Bronchitis]
134 909 [Dementia]
608 335 [Anxiety]
531 180 [Dementia]
531 773 []
599 552 []
926 643 [Flu, Depression]
505 935 [Bronchitis]
791 359 []
...
...
960 089 []
827 228 [Schizophrenia]
827 359 [Depression, Allergies]
664 690 [Flu]
</code></pre>
<p>and then delete records that has no diseases and keep the ones that have one ore more diseases</p>
<pre><code>PtsID VisitID Diseaes
134 529 [Anxiety, Bronchitis]
134 909 [Dementia]
608 335 [Anxiety]
531 180 [Dementia]
926 643 [Flu, Depression]
505 935 [Bronchitis]
...
...
827 228 [Schizophrenia]
827 359 [Depression, Allergies]
664 690 [Flu]
</code></pre>
<p>I have not worked with array in dataframe before and not sure how to start</p>
| <python><arrays><dataframe> | 2023-07-24 04:25:03 | 2 | 8,150 | asmgx |
76,751,383 | 8,323,701 | Assign different combination of weight to variables and calculate the result for each iteration | <p>I have 3 variables where each of the variable's value can range from .05 to 1. The constraints are that the sum of variables should be 1 and the variables should always be a multiple of .05</p>
<p>I want to generate all possible combination of these 3 variables and use these weights for some calculation in each iteration. So for example</p>
<pre><code>Iteration 1:
W1 : .05 W2 : .05 W3: .9
Iteration 2:
W1 : .1 W2 : .05 W3: .85
</code></pre>
<p>So on and so forth, so my question is is there a package in python/ or any other way which can do this, where I can specify the increment size(.05), the constraints(summation of variables = 1) in this case and generate such combinations</p>
| <python><pandas><loops><weighted> | 2023-07-24 04:18:43 | 1 | 323 | bakas |
76,751,247 | 20,591,261 | Change color on plotly | <p>I'm trying to change the color of my scattlerplot, but i still getting the default schema.</p>
<pre><code>import plotly.express as px
mycolour = ['#FF5733', '#33FF57', '#3357FF']
fig = px.scatter(SandiaA, x="Semana", y="PrecioPromedio", color="Anio",
color_discrete_sequence=mycolour)
fig.show()
</code></pre>
<p>Any advice? Thanks a lot!</p>
| <python><plotly> | 2023-07-24 03:37:39 | 1 | 1,195 | Simon |
76,751,179 | 10,669,558 | Celery tasks succeeding in Django but not showing on Flower or Celery Logs | <p>I have a Django project using cookiecutter's template, I have been trying to get celery working with it. I have done the setup according to the celery docs and when I run a task, on Django's output it shows as succeeded but if I check the terminal running celery, celery logs don't even show if it received the tasks, I am running it using <code>celery -A proj_name worker -l DEBUG</code>. I also tried it with <code>INFO</code> but same thing. The tasks also dont show up on the Flower dashboard and I am using <code>django-celery-results</code> with both <code>redis/postgres</code> backends and both don't get the results populated.</p>
<p>I am not really sure what's going on but as far as I can tell celery is not receiving the tasks at all despite what Django's logs show. Also, when I try to print the task's state using <code>AsyncResult</code> it always shows <code>PENDING</code> despite django again saying it succeeded.</p>
<p>Here's my celery.py</p>
<pre><code>import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj_name.config.settings.local")
app = Celery("proj_name")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
</code></pre>
<p>and my celery related configs</p>
<pre><code>if USE_TZ:
CELERY_TIMEZONE = TIME_ZONE
CELERY_BROKER_URL = env("CELERY_BROKER_URL", default="redis://localhost:6379/0")
# CELERY_RESULT_BACKEND = f"db+postgresql://{env('POSTGRES_DB_USER')}:{env('POSTGRES_DB_PWD')}@localhost/{env('POSTGRES_DB_NAME')}"
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
CELERY_CACHE_BACKEND = 'django-cache'
CELERY_TASK_TRACK_STARTED = True
CELERY_RESULT_EXTENDED = True
CELERY_RESULT_BACKEND_ALWAYS_RETRY = True
CELERY_RESULT_BACKEND_MAX_RETRIES = 10
CELERY_ACCEPT_CONTENT = ["application/json"]
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_TIME_LIMIT = 5 * 60
CELERY_TASK_SOFT_TIME_LIMIT = 60
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
CELERY_WORKER_SEND_TASK_EVENTS = True
CELERY_TASK_SEND_SENT_EVENT = True
CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True
</code></pre>
<p>And here's how my task is defined:</p>
<pre><code>@app.task(bind=True)
def send_email_task(self,email_action, recipient_email = "", context={}, attachments = [],
is_sender_email_dynamic = False, dynamic_cc_emails = []):
print('before task',self.request.id, self.request,)
print(self.AsyncResult(self.request.id).state)
# insert async func call to send email
print('after task',self.AsyncResult(self.request.id).state, self.request)
</code></pre>
<p>and a sample Django Log for celery</p>
<p><code>INFO 2023-07-24 03:01:54,640 trace 7804 140679160931904 Task email_services.tasks.send_email_task[5fbbc289-f337-415c-8fad-3100042c422a] succeeded in 0.08931779300019116s: None</code></p>
<p>and my celery <code>celery -A proj_name worker -l DEBUG</code> output</p>
<pre><code>(venv_name) ➜ proj_name git:(main) ✗ celery -A proj_name worker -l DEBUG
[2023-07-24 02:39:31,265: DEBUG/MainProcess] | Worker: Preparing bootsteps.
[2023-07-24 02:39:31,266: DEBUG/MainProcess] | Worker: Building graph...
[2023-07-24 02:39:31,266: DEBUG/MainProcess] | Worker: New boot order: {Beat, Timer, Hub, Pool, Autoscaler, StateDB, Consumer}
[2023-07-24 02:39:31,268: DEBUG/MainProcess] | Consumer: Preparing bootsteps.
[2023-07-24 02:39:31,268: DEBUG/MainProcess] | Consumer: Building graph...
[2023-07-24 02:39:31,274: DEBUG/MainProcess] | Consumer: New boot order: {Connection, Events, Mingle, Gossip, Heart, Agent, Tasks, Control, event loop}
-------------- celery@DESKTOP-SGH5F1FL v5.3.1 (emerald-rush)
--- ***** -----
-- ******* ---- Linux-5.10.16.3-microsoft-standard-WSL2-x86_64-with-glibc2.35 2023-07-24 02:39:31
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app: proj_name:0x7fe89adf1180
- ** ---------- .> transport: redis://localhost:6379/0
- ** ---------- .> results: redis://localhost:6379/0
- *** --- * --- .> concurrency: 20 (prefork)
-- ******* ---- .> task events: ON
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. celery.accumulate
. celery.backend_cleanup
. celery.chain
. celery.chord
. celery.chord_unlock
. celery.chunks
. celery.group
. celery.map
. celery.starmap
. email_services.tasks.send_email_task
. proj_name.celery.debug_task
[2023-07-24 02:39:31,280: DEBUG/MainProcess] | Worker: Starting Hub
[2023-07-24 02:39:31,280: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:31,280: DEBUG/MainProcess] | Worker: Starting Pool
[2023-07-24 02:39:32,539: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:32,539: DEBUG/MainProcess] | Worker: Starting Consumer
[2023-07-24 02:39:32,539: DEBUG/MainProcess] | Consumer: Starting Connection
[2023-07-24 02:39:32,541: WARNING/MainProcess] /home/<name>/.pyenv/versions/3.10.10/envs/<proj_name>/lib/python3.10/site-packages/celery/worker/consumer/consumer.py:498: CPendingDeprecationWarning: The broker_connection_retry configuration setting will no longer determine
whether broker connection retries are made during startup in Celery 6.0 and above.
If you wish to retain the existing behavior for retrying connections on startup,
you should set broker_connection_retry_on_startup to True.
warnings.warn(
[2023-07-24 02:39:32,545: INFO/MainProcess] Connected to redis://localhost:6379/0
[2023-07-24 02:39:32,545: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:32,545: DEBUG/MainProcess] | Consumer: Starting Events
[2023-07-24 02:39:32,545: WARNING/MainProcess] /home/<name>/.pyenv/versions/3.10.10/envs/proj_name/lib/python3.10/site-packages/celery/worker/consumer/consumer.py:498: CPendingDeprecationWarning: The broker_connection_retry configuration setting will no longer determine
whether broker connection retries are made during startup in Celery 6.0 and above.
If you wish to retain the existing behavior for retrying connections on startup,
you should set broker_connection_retry_on_startup to True.
warnings.warn(
[2023-07-24 02:39:32,546: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:32,546: DEBUG/MainProcess] | Consumer: Starting Mingle
[2023-07-24 02:39:32,546: INFO/MainProcess] mingle: searching for neighbors
[2023-07-24 02:39:33,552: INFO/MainProcess] mingle: all alone
[2023-07-24 02:39:33,552: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:33,553: DEBUG/MainProcess] | Consumer: Starting Gossip
[2023-07-24 02:39:33,555: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:33,555: DEBUG/MainProcess] | Consumer: Starting Heart
[2023-07-24 02:39:33,557: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:33,557: DEBUG/MainProcess] | Consumer: Starting Tasks
[2023-07-24 02:39:33,560: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:33,560: DEBUG/MainProcess] | Consumer: Starting Control
[2023-07-24 02:39:33,562: DEBUG/MainProcess] ^-- substep ok
[2023-07-24 02:39:33,562: DEBUG/MainProcess] | Consumer: Starting event loop
[2023-07-24 02:39:33,562: DEBUG/MainProcess] | Worker: Hub.register Pool...
[2023-07-24 02:39:33,562: INFO/MainProcess] celery@DESKTOP-SGH5F1FL ready.
[2023-07-24 02:39:33,563: DEBUG/MainProcess] basic.qos: prefetch_count->80
</code></pre>
| <python><django><celery><flower> | 2023-07-24 03:09:35 | 1 | 645 | Altair21 |
76,751,171 | 3,099,733 | How to flat a list of lists and ensure the output result distributed evenly in python? | <p>Given there is a list if lists like the below.</p>
<pre><code>[
[1, 2, 3],
[4, 5],
[6, 8, 9, 10],
[11]
]
</code></pre>
<p>I hope that I can flatten the list and the output should be <code>[1, 4, 6, 11, 2, 5, 8, 3, 9, 10]</code>. How to implement this in Python?</p>
| <python> | 2023-07-24 03:07:22 | 3 | 1,959 | link89 |
76,751,155 | 9,768,260 | How to install torch in alpine | <p>When I tried to install torch in alpine, it report there is no version distribution found for it.</p>
<pre><code>FROM alpine:3.18
ENV PYTHONUNBUFFERED=1
RUN apk add --update --no-cache python3 && ln -sf python3 /usr/bin/python
RUN python3 -m ensurepip
RUN pip3 install --no-cache --upgrade pip setuptools
RUN pip3 install torch # <-- report: Could not find a version that satisfies the requirement torch (from versions: none)
</code></pre>
| <python><docker><pytorch><dockerfile><alpine-linux> | 2023-07-24 03:01:56 | 1 | 7,108 | ccd |
76,751,074 | 10,366,334 | Python maneuvering with nested generators | <p>I have some codes like this:</p>
<pre class="lang-py prettyprint-override"><code>class A:
def __iter__(self):
for i in range(100):
yield i
class B:
def __init__(self, src):
self.src = src
def __iter__(self):
for i in self.src:
yield i * 2
class C:
def __init__(self, src1, src2):
self.src1 = src1
self.src2 = src2
def __iter__(self):
for i, j in zip(self.src1, self.src2):
yield i + j
a = A()
b = B(a)
c = C(a, b)
it = iter(c)
next(it)
</code></pre>
<p>What I want to do is to decompose the calling chain when invoking <code>next(it)</code>. More specifically, I want to execute some new code after the <code>yield</code> in each class without modifying the class codes. Ideally the new code prints in which class the <code>yield</code> is executed. Is this a possible thing?</p>
| <python><iterator><generator><yield> | 2023-07-24 02:28:03 | 1 | 314 | Nicolás_Tsu |
76,750,967 | 11,481,694 | PyQt5: How do you align widgets on different hierarchy levels? | <p>I'm trying to align the sides of a top button and a bottom button on different hierarchy levels in the widget tree. The top button is on the same level as a widget with horizontal box layout that contains the bottom button.</p>
<p>Here's a simplified version of the code:</p>
<pre><code> self.setContentsMargins(0,0,0,0) # this is the main window
central_widget = QWidget()
self.setCentralWidget(central_widget)
central_widget.setContentsMargins(0,0,0,0)
main_layout = QVBoxLayout()
central_widget.setLayout(main_layout)
main_layout.setContentsMargins(0,0,0,0)
button = QPushButton("1")
main_layout.addWidget(button)
button.setContentsMargins(0,0,0,0)
widget = QWidget()
main_layout.addWidget(widget)
widget.setContentsMargins(0,0,0,0)
layout = QHBoxLayout()
widget.setLayout(layout)
layout.setContentsMargins(0,0,0,0)
button = QPushButton("2")
layout.addWidget(button)
button.setContentsMargins(0,0,0,0)
button = QPushButton("3")
layout.addWidget(button)
button.setContentsMargins(0,0,0,0)
</code></pre>
<p>I've called setContentsMargins(0,0,0,0) on every object involved, widgets and layouts.</p>
<p>Yet I'm getting this result:</p>
<p><a href="https://i.sstatic.net/wdHzY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wdHzY.png" alt="enter image description here" /></a></p>
<p>As you can see, the left side of button 2 isn't aligned with the left side of button 1, and the same goes for the other side.</p>
<p>I want them aligned (and since the actual code is more complicated than this, I'd like to stay with this structure of different hierarchy levels).</p>
<p>I'd appreciate your help with this, thanks!</p>
<hr />
<p>Edit: here's a minimal reproducible example:</p>
<pre><code>from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Test")
self.initUI()
def initUI(self):
self.resize(120, 50)
self.setContentsMargins(0,0,0,0)
central_widget = QWidget()
self.setCentralWidget(central_widget)
central_widget.setContentsMargins(0,0,0,0)
main_layout = QVBoxLayout()
central_widget.setLayout(main_layout)
main_layout.setContentsMargins(0,0,0,0)
button = QPushButton("1")
main_layout.addWidget(button)
button.setContentsMargins(0,0,0,0)
widget = QWidget()
main_layout.addWidget(widget)
widget.setContentsMargins(0,0,0,0)
layout = QHBoxLayout()
widget.setLayout(layout)
layout.setContentsMargins(0,0,0,0)
button = QPushButton("2")
layout.addWidget(button)
button.setContentsMargins(0,0,0,0)
button = QPushButton("3")
layout.addWidget(button)
button.setContentsMargins(0,0,0,0)
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
</code></pre>
| <python><layout><pyqt5><widget><alignment> | 2023-07-24 01:38:10 | 0 | 1,103 | Orius |
76,750,631 | 169,603 | Does an open()ed file get closed when nothing holds a reference to it? | <p>I know that the safe and recommended way to open files is to use context managers:</p>
<pre><code>with open("x") as fh:
do_something_with(fh)
</code></pre>
<p>I frequently encounter situations where I don't want to do anything with the file handle returned by <code>open()</code> other than reading or writing a file completely and then closing it. Closing the file is automatically handled by the context manager. But what if I don't use one?</p>
<p>For example, is this</p>
<pre><code>with open("x.pickle", "rb") as fh:
foo = pickle.load(fh)
more_code()
</code></pre>
<p>more or less equivalent to this?</p>
<pre><code>foo = pickle.load(open("x.pickle", "rb"))
more_code()
</code></pre>
<p>Assuming that pickle (or whatever else creates/consumes the file) doesn't somehow keep the file handle around, and lets it go out of scope, it should eventually be garbage collected and the file closed, right?</p>
<p>I tested this trivial example by inserting <code>sleep(100000)</code> before <code>more_code()</code> and then checking <code>lsof</code> to see if the file still showed up as opened. In this test, it did not. So, again with the assumption that whatever reads/writes the file lets the file handle go out of scope, is this a safe practice?</p>
| <python><file-io><memory-leaks><garbage-collection><contextmanager> | 2023-07-23 23:02:16 | 1 | 9,355 | Zilk |
76,750,524 | 489,088 | Is there some built in facility in Python that provides a set with a maximum size and that deletes oldest entries after max size is reached? | <p>I have a very specific need: a set-like implementation (for O(1) member checking) which allows a maximum number of elements to be added to it, and that many have been added new items would cause the oldest (in the order they have been added to it) from being replaced / deleted. Say, FIFO / First In First Out.</p>
<p>Is there such a thing in Python, either built-in or in a library?</p>
<p>I searched but no luck...</p>
<p>My use case is that I have a steady number of hashes coming in, and I need to detect duplicates. But of course memory is limited and in my case older hashes have lesser value, so after adding new ones to this given set I would like its size to be capped, and older hashes to be replaced in this set as newer ones come in so that the size stays constant from that point on.</p>
<p>Any pointers will be very helpful, thank you!</p>
| <python><python-3.x><set><fifo> | 2023-07-23 22:20:40 | 2 | 6,306 | Edy Bourne |
76,750,452 | 3,047,729 | Save a list of functions in Python | <p>I have written the following code in Python where the intent is to make a list of every possible boolean function which takes arguments from the set <code>var_set</code>. So for instance if <code>var_set</code> is <code>{"P","Q"}</code> then <code>all_var_evals(var_set)</code> should contain four functions. One function would return <code>True</code> on input <code>"P"</code> and input <code>"Q"</code>, another would return <code>True</code> on input <code>"P"</code> but <code>False</code> on input <code>"Q"</code>, and so on.</p>
<pre><code>def all_var_evals(var_set):
# The bucket is an "accumulator" variable, into which I will place each evaluation as I
# construct them. The bucket will then be returned at the end.
bucket = []
var_list = list(var_set) # Gives the variables an indexing (ordering)
for row in range(2**(len(var_set))): # 2^n evaluations
to_bin = row
func_list = []
while to_bin != 0:
func_list.insert(0, to_bin % 2)
to_bin -= to_bin % 2
to_bin //= 2
while len(func_list) < len(var_list):
func_list.insert(0,0)
def f():
return lambda x: func_list[var_list.index(x)]
bucket.append(f())
return bucket
</code></pre>
<p>However, after testing, I find that every function in the list seems to return <code>True</code> on every input. I assume this is because of some kind of copy issue, like every time <code>func_list</code> takes new values, every function in the <code>bucket</code> now points to it. I tried resolving the copy issue by making a closure, hence why it has</p>
<pre><code>def f():
return lambda x: func_list[var_list.index(x)]
</code></pre>
<p>However, that did not resolve the issue. Since I've never implemented closures in Python, though, I wasn't sure how they work and after reading up on them, I still can't see how to get the desired behavior.</p>
<p>I also tried using <code>.hardcopy()</code> in a few different ways, none of which worked.</p>
| <python><copy><closures> | 2023-07-23 21:52:42 | 1 | 4,013 | Addem |
76,750,316 | 16,319,191 | Match two dfs based on conditions in pandas | <p>I have two dfs: dfname (which has different versions of names of player) and dfgoals which has information about the player and their goals scored.
I want to return one row for each player in the answer df based on a condition:</p>
<p>(i) see if name1 value exists in actual_name col in dfgoals and if it does, return the first matched row, otherwise check name2 value and return the first matched row</p>
<p>(ii) whichever value is matched (name1 or name2) return the name col value from dfname as well</p>
<pre><code>dfname = pd.DataFrame({
"name": ["ryan", "bill", "saka", "Henry","Rooney"],
"name1": ["ryan 112", "Bill Matt Cdevaca", "Bukayo Saka", "Super Henry","Rooney"],
"name2": ["NaN", "XXVaca", "Bukayo", "Thierry","Rooney"]})
dfgoals = pd.DataFrame({
"actual_name": ["ryan 112", "XXVaca", "Bukayo", "Thierry", "Ronaldo", "Messi"],
"goals": [0, 2, 5, 10, 100, 200],
"matches": [22, 100, 200, 300, 100, 90]})
answerdf = pd.DataFrame({
"actual_name": ["ryan 112", "XXVaca", "Bukayo", "Thierry", "Rooney"],
"goals": [0, 2, 5, 10, "NaN"],
"matches": [22, 100, 200, 300, "NaN"],
"name_from_dfname": ["ryan", "bill", "saka", "Henry", "Rooney"]})
answerdf
Rooney's values are NaN because his goals record is not available
</code></pre>
<p>I have tried this so far but it does not check for name1-2 values correctly, for example it gives me only ryan's goals and not other player's because their names are mentioned differently</p>
<pre><code>df = dfgoals
values_to_check = ['ryan', 'Bill Matt Cdevaca', 'saka', 'henry', 'Rooney']
filtered_rows = []
# Iterate through the DataFrame rows to find matches and concatenate values
for index, row in dfgoals.iterrows():
matched_values = [value for value in values_to_check if value.lower() in row['actual_name'].lower()]
if matched_values:
row['concatenated_values'] = '|'.join(matched_values)
filtered_rows.append(row)
# Create a new DataFrame from the filtered rows
result_df = pd.DataFrame(filtered_rows)
result_df['concatenated_values'] = pd.Categorical(result_df['concatenated_values'], categories=values_to_check, ordered=True)
# Sort the DataFrame based on the 'concatenated_values' column
result_df.sort_values(by = "concatenated_values")
</code></pre>
| <python><pandas> | 2023-07-23 21:01:10 | 1 | 392 | AAA |
76,750,310 | 9,571,575 | How to use Pydantic2 and Sqlalchemy to serialize nested data in FastAPI | <p>I have a following problem. I have a relationship One to One between User model and Profile model (one user can only have one profile). I use postgres, sqlalchemy, pydantic and fastAPI. Code looks likes this:</p>
<pre><code>class User(Base):
__tablename__ = "users"
id = Column(
UUID(as_uuid=True),
nullable=False,
primary_key=True,
default=uuid.uuid4,
)
...<some other fields>
profile = relationship("Profile", back_populates="user")
</code></pre>
<p>and</p>
<pre><code>class Profile(Base):
__tablename__ = "profiles"
id = Column(
UUID(as_uuid=True),
nullable=False,
primary_key=True,
default=uuid.uuid4,
)
user_id = Column(
UUID(as_uuid=True),
ForeignKey("users.id"),
nullable=False,
unique=True,
)
user = relationship(
"User",
foreign_keys="Profile.user_id",
back_populates="profile"
)
...<some other fields>
</code></pre>
<p>Now, when I get Profile in the following router:</p>
<pre><code>@router.get(
"{user_id}",
status_code=status.HTTP_200_OK,
response_model=ReadProfile,
)
async def get_profile_read(
profile_id: str,
profile_service: ProfilesService = Depends(get_profiles_service),
current_user: str = Depends(get_auth),
):
profile = await profile_service.get(profile_id)
return ReadProfile(**profile.__dict__)
</code></pre>
<p>I'd like to have definition of fields that will be returned defined by pydantic model which looks as follows:</p>
<pre><code>class ReadProfile(BaseModel):
id: UUID
...<some other data>
user: ReadUser
</code></pre>
<p>ReadUser looks like this</p>
<pre><code>class ReadUser(BaseModel):
id: UUID
...some other data
</code></pre>
<p>and the method that reads Profile from db looks like this:</p>
<pre><code>async def get(self, profile_id: str) -> ReadProfile:
q = await self.db_session.execute(
select(Profile)
.where(Profile.id == profile_id)
.options(
selectinload(Profile.user)
)
)
result = q.scalars().first()
if not result:
raise ValueError("Profile not found!")
return result
</code></pre>
<p>When I print result._ <em>dict</em> _ I can see that there is a User model under the attribute "user". Proof:</p>
<pre><code>{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x7faf6cccb820>, 'user_id': UUID('619949c3-a17c-4d59-90fa-b332307a4597'), 'display_name': 'mfoxen0', 'gender': <GenderEnum.female: 'female'>, 'date_modified': datetime.datetime(2023, 7, 23, 19, 12, 2, 98185, tzinfo=datetime.timezone.utc), 'id': UUID('51cdf177-d12d-40e9-8cb3-028f76a762f3'), 'bio': 'venenatis turpis enim blandit mi in porttitor pede justo eu massa donec dapibus', 'date_created': datetime.datetime(2023, 7, 23, 19, 12, 2, 98185, tzinfo=datetime.timezone.utc), 'user': <app.models.user.User object at 0x7faf6f89d420>}
</code></pre>
<p>But for some reason pydantic crashes with an error:</p>
<pre><code>pydantic_core._pydantic_core.ValidationError: 1 validation error for ReadProfile
web_1 | user
web_1 | Input should be a valid dictionary or instance of ReadUser [type=model_type, input_value=<app.models.user.User object at 0x7f8b7c3cca30>, input_type=User]
</code></pre>
<p>What am I doing wrong and how to sort it out? Thanks to everyone who read this :)</p>
| <python><postgresql><sqlalchemy><fastapi><pydantic> | 2023-07-23 20:59:03 | 0 | 831 | ugabuga77 |
76,750,277 | 11,703,015 | Extracting the original image extension from base64 data in Python | <p>I am working on image processing in Python and facing an issue with extracting the original file extension from base64 image data. Initially, I open the image and read it as binary using the following code:</p>
<pre class="lang-py prettyprint-override"><code>with open(img_path_input, 'rb') as img:
img_bin = img.read()
</code></pre>
<p>After obtaining the binary data (<code>img_bin</code>), I convert it to base64 format using the <code>base64</code> module like this:</p>
<pre class="lang-py prettyprint-override"><code>img_base64 = base64.b64encode(img_bin).decode()
</code></pre>
<p>However, I need to recover the original file extension later on without relying on storing or passing the original extension using the <code>img_path_input</code>. I am wondering if there is an alternative method within the <code>base64</code> module or if the extension is implicitly encoded in the base64 string.</p>
<p>Any suggestions or alternatives to solve this problem would be greatly appreciated.</p>
| <python><base64> | 2023-07-23 20:49:13 | 1 | 516 | nekovolta |
76,750,254 | 726,730 | Warning: Unable to set Geometry error - pyqt5 | <p><strong>File: telephone_calls.py</strong></p>
<pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\chris\My Projects\papinhio-player\ui/menu-4/create/telephone-calls.ui'
#
# Created by: PyQt5 UI code generator 5.15.7
#
# 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_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1102, 239)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Dialog.sizePolicy().hasHeightForWidth())
Dialog.setSizePolicy(sizePolicy)
Dialog.setMinimumSize(QtCore.QSize(1102, 239))
Dialog.setMaximumSize(QtCore.QSize(1102, 239))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/rest-windows/assets/images/rest-windows/telephone.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.setWindowIcon(icon)
Dialog.setStyleSheet("")
self.verticalLayout_2 = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout_2.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.label = QtWidgets.QLabel(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setStyleSheet("QLabel{\n"
" font-weight:bold;\n"
" color:green;\n"
"}")
self.label.setWordWrap(True)
self.label.setObjectName("label")
self.verticalLayout_2.addWidget(self.label)
self.add_call_details_const = QtWidgets.QPushButton(Dialog)
self.add_call_details_const.setMinimumSize(QtCore.QSize(0, 29))
self.add_call_details_const.setObjectName("add_call_details_const")
self.verticalLayout_2.addWidget(self.add_call_details_const)
self.add_call_details_dynamic = QtWidgets.QPushButton(Dialog)
self.add_call_details_dynamic.setMinimumSize(QtCore.QSize(0, 29))
self.add_call_details_dynamic.setObjectName("add_call_details_dynamic")
self.verticalLayout_2.addWidget(self.add_call_details_dynamic)
self.scrollArea = QtWidgets.QScrollArea(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
self.scrollArea.setSizePolicy(sizePolicy)
self.scrollArea.setStyleSheet("QScrollArea#scrollArea{\n"
" border:1px solid #ABABAB;\n"
" background:transparent;\n"
"}")
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1082, 56))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollAreaWidgetContents.sizePolicy().hasHeightForWidth())
self.scrollAreaWidgetContents.setSizePolicy(sizePolicy)
self.scrollAreaWidgetContents.setStyleSheet("QWidget#scrollAreaWidgetContents{\n"
" background:rgb(229, 240, 27);\n"
"}")
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.gridLayout_2 = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
self.gridLayout_2.setContentsMargins(9, 9, 9, 9)
self.gridLayout_2.setObjectName("gridLayout_2")
self.details_frame = QtWidgets.QFrame(self.scrollAreaWidgetContents)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.details_frame.sizePolicy().hasHeightForWidth())
self.details_frame.setSizePolicy(sizePolicy)
self.details_frame.setStyleSheet("QFrame#details_frame{\n"
" border:none;\n"
" /*image: url(:/rest-windows/assets/images/rest-windows/telephone-calls-background.png);*/\n"
"}")
self.details_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.details_frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.details_frame.setObjectName("details_frame")
self.verticalLayout = QtWidgets.QVBoxLayout(self.details_frame)
self.verticalLayout.setObjectName("verticalLayout")
self.gridLayout_2.addWidget(self.details_frame, 0, 0, 1, 1)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.verticalLayout_2.addWidget(self.scrollArea)
self.frame_2 = QtWidgets.QFrame(Dialog)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.frame_2.sizePolicy().hasHeightForWidth())
self.frame_2.setSizePolicy(sizePolicy)
self.frame_2.setStyleSheet("QFrame{border:none;}")
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame_2)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setSpacing(7)
self.horizontalLayout.setObjectName("horizontalLayout")
self.save = QtWidgets.QPushButton(self.frame_2)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.save.sizePolicy().hasHeightForWidth())
self.save.setSizePolicy(sizePolicy)
self.save.setMinimumSize(QtCore.QSize(0, 29))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(":/rest-windows/assets/images/rest-windows/save.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.save.setIcon(icon1)
self.save.setObjectName("save")
self.horizontalLayout.addWidget(self.save)
self.cancel = QtWidgets.QPushButton(self.frame_2)
self.cancel.setMinimumSize(QtCore.QSize(0, 29))
self.cancel.setObjectName("cancel")
self.horizontalLayout.addWidget(self.cancel)
self.verticalLayout_2.addWidget(self.frame_2)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Στοιχεία ηχητικών κλήσεων"))
self.label.setText(_translate("Dialog", "Σημείωση 1: Μπορείτε να είσαγετε όσες ηχητικές κλήσεις θέλετε (μέχρι 3 ταυτόχρονα) για μία ζωντανή εκπομπή.\n"
"Σημείωση 2: Η επιλογή του ακριβούς χρονικού διαστήματος (κάθε ηχητικής κλήσης θα γίνει στην συνέχεια στην καρτέλα 5.\n"
"Σημείωση 3: Μία ηχητική κλήση μπορεί να έχει σταθερά στοιχεία κατά τις επαναλήψεις της προγραμματισμένης μετάδοσης αλλά μπορεί και να μην έχει σταθερά στοιχεία (ειδοποίηση 10 λεπτά πριν την έναρξη της προγραμματισμένης μετάδοσης με σκοπό την επιλογή των στοιχείων των ηχητικών κλήσεων)."))
self.add_call_details_const.setText(_translate("Dialog", "Προσθήκη δεδομένων και άλλης ηχητικής κλήσης (με σταθερά στοιχεία (όνομα -επώνυμο - διάρκεια))"))
self.add_call_details_dynamic.setText(_translate("Dialog", "Προσθήκη δεδομένων και άλλης ηχητικής κλήσης (με μή σταθερά στοιχεία (όνομα -επώνυμο - διάρκεια))"))
self.save.setText(_translate("Dialog", "Αποθήκευση"))
self.cancel.setText(_translate("Dialog", "Ακύρωση"))
</code></pre>
<p><strong>File: run_me.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import telephone_calls
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from win32api import GetSystemMetrics
import copy
import traceback
class Run_me:
def __init__(self):
try:
self.live_ip_calls = []
self.app = QtWidgets.QApplication(sys.argv)
self.Dialog = QtWidgets.QDialog()
self.ui = telephone_calls.Ui_Dialog()
self.ui.setupUi(self.Dialog)
self.Dialog.show()
self.label_height = self.ui.label.size().height()
#add_call_details const click event
self.ui.add_call_details_const.clicked.connect(lambda state:self.on_add_call_details_const_click(state))
#add_call_details dynamic click event
self.ui.add_call_details_dynamic.clicked.connect(lambda state:self.on_add_call_details_dynamic_click(state))
self.ui.save.setEnabled(False)
#cancel click event
self.ui.cancel.setEnabled(False)
self.resize_the_Dialog()
self.Dialog.closeEvent = lambda event:self.closeEvent(event)
sys.exit(self.app.exec_())
except Exception as e:
error_message = str(traceback.format_exc())
print(error_message)
#add_call_details const click event
def on_add_call_details_const_click(self,state):
try:
ip_call_item = {}
ip_call_item["ip_call_frame"] = QtWidgets.QFrame(self.Dialog)
ip_call_item["ip_call_frame"].setStyleSheet("QFrame{\n"
" border:1px solid #ABABAB;background-color:#EFEFEF;\n"
"}")
ip_call_item["ip_call_frame"].setFrameShape(QtWidgets.QFrame.StyledPanel)
ip_call_item["ip_call_frame"].setFrameShadow(QtWidgets.QFrame.Raised)
ip_call_item["gridLayout"] = QtWidgets.QGridLayout(ip_call_item["ip_call_frame"])
ip_call_item["ip_call_label"] = QtWidgets.QLabel(ip_call_item["ip_call_frame"])
ip_call_item["ip_call_label"].setStyleSheet("QLabel{border:none;}")
ip_call_item["gridLayout"].addWidget(ip_call_item["ip_call_label"], 0, 0, 1, 1)
ip_call_item["ip_call_delete"] = QtWidgets.QPushButton(ip_call_item["ip_call_frame"])
ip_call_item["ip_call_delete"].setMinimumSize(QtCore.QSize(0, 29))
ip_call_item["ip_call_delete"].clicked.connect(lambda state,index=len(self.live_ip_calls):self.remove_ip_call(index))
ip_call_item["gridLayout"].addWidget(ip_call_item["ip_call_delete"], 1, 0, 1, 1)
ip_call_item["ip_call_label"].setText("Placeholder τηλεφωνικής κλήσης μέσω διαδικτύου όπου τα μη σταθερά στοιιχεία θα οριστούν μεταγενέστερα.")
ip_call_item["ip_call_delete"].setText("Διαγραφή")
self.ui.verticalLayout.addWidget(ip_call_item["ip_call_frame"])
self.live_ip_calls.append(ip_call_item)
self.resize_the_Dialog()
except:
error_message = str(traceback.format_exc())
print(error_message)
def resize_the_Dialog(self):
self.ui.details_frame.setMinimumHeight(0)
self.ui.details_frame.setMaximumHeight(10*1000)
self.ui.scrollAreaWidgetContents.setMinimumHeight(0)
self.ui.scrollAreaWidgetContents.setMaximumHeight(10*1000)
self.Dialog.setMinimumHeight(0)
self.Dialog.setMaximumHeight(11*1000)
self.ui.scrollAreaWidgetContents.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
self.ui.details_frame.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Fixed)
self.ui.details_frame.adjustSize()
self.ui.scrollAreaWidgetContents.adjustSize()
self.ui.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.Dialog.setSizePolicy(QtWidgets.QSizePolicy.Fixed,QtWidgets.QSizePolicy.Expanding)
details_frame_height = 9
#details_frame_height = 0
for ip_call in self.live_ip_calls:
frame = ip_call["ip_call_frame"]
frame_height = frame.sizeHint().height()
details_frame_height += frame_height + 6
if len(self.live_ip_calls)>0:
details_frame_height -= 6
details_frame_height += 9
self.ui.details_frame.setFixedHeight(details_frame_height)
self.ui.scrollAreaWidgetContents.setFixedHeight(9+details_frame_height+9)
self.ui.scrollArea.setFixedHeight(self.ui.scrollAreaWidgetContents.sizeHint().height())
self.Dialog.setFixedWidth(int(0.9*GetSystemMetrics(0)))
#return None
window_height_expanding = 0
add_call_details_const_height = self.ui.add_call_details_const.height()
add_call_details_dynamic_height = self.ui.add_call_details_dynamic.height()
scrollArea_height = self.ui.scrollArea.height()
frame_2_height = self.ui.frame_2.height()
window_height_expanding = copy.deepcopy(int(11 + self.label_height + 6 + add_call_details_const_height + 6 + add_call_details_dynamic_height + 6 + scrollArea_height + 6 + frame_2_height + 11))
self.Dialog.setFixedHeight(window_height_expanding)
window_fixed_width = int(0.9*GetSystemMetrics(0))
window_max_height = int(0.9*GetSystemMetrics(1))
self.Dialog.setFixedHeight(1)
window_height_2 = self.Dialog.frameSize().height()
self.window_height_2 = window_height_2
details_frame_height_max = abs(window_max_height - window_height_2 - 1) - 11 - 11 - self.label_height - 6 - add_call_details_const_height - 6 - add_call_details_dynamic_height - 6 - frame_2_height
self.Dialog.setFixedHeight(window_height_expanding)
#return None
self.ui.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.ui.scrollAreaWidgetContents.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
self.ui.details_frame.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Fixed)
self.Dialog.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
self.ui.scrollAreaWidgetContents.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
self.ui.scrollArea.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
self.ui.details_frame.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding)
if details_frame_height>details_frame_height_max:
self.ui.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.ui.details_frame.setFixedHeight(details_frame_height)
self.ui.scrollAreaWidgetContents.setFixedHeight(9+details_frame_height+9)
self.ui.scrollArea.setFixedHeight(9+details_frame_height_max+9)
scrollArea_height = 9+details_frame_height_max+9
else:
self.ui.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.ui.details_frame.setFixedHeight(details_frame_height)
self.ui.scrollAreaWidgetContents.setFixedHeight(9+details_frame_height+9)
self.ui.scrollArea.setFixedHeight(9+details_frame_height+9)
scrollArea_height = 9+details_frame_height+9
window_height_expanding = 0
add_call_details_const_height = self.ui.add_call_details_const.sizeHint().height()
add_call_details_dynamic_height = self.ui.add_call_details_dynamic.sizeHint().height()
scrollArea_height = self.ui.scrollArea.sizeHint().height()
frame_2_height = self.ui.frame_2.sizeHint().height()
window_height_expanding = 11 + self.label_height + 6 + add_call_details_const_height + 6 + add_call_details_dynamic_height + 6 + scrollArea_height + 6 + frame_2_height + 11
#self.main_self.scheduled_transmitions_create_telephone_calls_window.adjustSize()
if window_height_expanding>window_max_height:
self.Dialog.setFixedHeight(window_max_height)
else:
self.Dialog.setFixedHeight(window_height_expanding)
self.Dialog.setFixedWidth(window_fixed_width)
#self.main_self.scheduled_transmitions_create_telephone_calls_window.update()
self.timer_for_center_the_QDialog = QtCore.QTimer()
self.timer_for_center_the_QDialog.timeout.connect(lambda widget=self.Dialog:self.center_the_QDialog(widget))
self.timer_for_center_the_QDialog.setSingleShot(True)
self.timer_for_center_the_QDialog.start(200)
def center_the_QDialog(self,widget,host=None):
try:
screen_width = GetSystemMetrics(0)
screen_height = GetSystemMetrics(1)
dw = self.app.desktop()
taskbar_height = dw.screenGeometry().height() - dw.availableGeometry().height()
taskbar_width = dw.screenGeometry().width() - dw.availableGeometry().width()
if taskbar_height<100:
available_screen_height = screen_height - taskbar_height
available_screen_width = screen_width
else:
available_screen_height = screen_height
available_screen_width = screen_width - taskbar_width
qdialog_width = self.Dialog.frameSize().width()
qdialog_height = self.Dialog.frameSize().height()
x = (available_screen_width - qdialog_width) / 2
y = (available_screen_height - qdialog_height) / 2
width = self.Dialog.size().width()
height = self.Dialog.size().height()
self.Dialog.move(x,y)
self.Dialog.setFixedWidth(width)
self.Dialog.setFixedHeight(height)
except Exception as e:
error_message = str(traceback.format_exc())
print(error_message)
#add_call_details dynamic click event
def on_add_call_details_dynamic_click(self,state):
try:
ip_call_item = {}
ip_call_item["ip_call_frame"] = QtWidgets.QFrame(self.Dialog)
ip_call_item["ip_call_frame"].setMinimumSize(QtCore.QSize(0, 0))
ip_call_item["ip_call_frame"].setStyleSheet("QFrame{\n"
" border:1px solid #ABABAB;background-color:#EFEFEF;\n"
"}")
ip_call_item["ip_call_frame"].setFrameShape(QtWidgets.QFrame.StyledPanel)
ip_call_item["ip_call_frame"].setFrameShadow(QtWidgets.QFrame.Raised)
ip_call_item["gridLayout_3"] = QtWidgets.QGridLayout(ip_call_item["ip_call_frame"])
ip_call_item["ip_call_label"] = QtWidgets.QLabel(ip_call_item["ip_call_frame"])
ip_call_item["ip_call_label"].setStyleSheet("border:none;color:green;font-weight:bold;")
ip_call_item["gridLayout_3"].addWidget(ip_call_item["ip_call_label"], 0, 0, 1, 1)
ip_call_item["ip_call_delete"] = QtWidgets.QPushButton(ip_call_item["ip_call_frame"])
ip_call_item["ip_call_delete"].setMinimumSize(QtCore.QSize(0, 29))
ip_call_item["ip_call_delete"].clicked.connect(lambda state,index=len(self.live_ip_calls):self.remove_ip_call(index))
ip_call_item["gridLayout_3"].addWidget(ip_call_item["ip_call_delete"], 1, 0, 1, 1)
ip_call_item["ip_call_label"].setText("Placeholder τηλεφωνικής κλήσης μέσω διαδικτύου όπου τα μη σταθερά στοιιχεία θα οριστούν μεταγενέστερα.")
ip_call_item["ip_call_delete"].setText("Διαγραφή")
self.ui.verticalLayout.addWidget(ip_call_item["ip_call_frame"])
self.live_ip_calls.append(ip_call_item)
self.resize_the_Dialog()
except:
error_message = str(traceback.format_exc())
print(error_message)
def remove_ip_call(self,index):
try:
self.ui.verticalLayout.removeWidget(self.live_ip_calls[index]["ip_call_frame"])
self.live_ip_calls[index]["ip_call_frame"].deleteLater()
self.live_ip_calls[index]["ip_call_frame"] = None
del self.live_ip_calls[index]
counter = -1
for live_ip_call in self.live_ip_calls:
counter += 1
self.live_ip_calls[counter]["ip_call_delete"].clicked.disconnect()
self.live_ip_calls[counter]["ip_call_delete"].clicked.connect(lambda state,index=counter:self.remove_ip_call(index))
self.resize_the_Dialog()
except:
error_message = str(traceback.format_exc())
print(error_message)
def closeEvent(self,event):
try:
event.accept()
except Exception as e:
error_message = str(traceback.format_exc())
print(error_message)
if __name__ == "__main__":
programm = Run_me()
</code></pre>
<p>The window is resized, <strong>but</strong> i see this warnings in console:</p>
<pre><code>QWindowsWindow::setGeometry: Unable to set geometry 1525x191+197+412 (frame: 154
1x229+189+382) on QWidgetWindow/"DialogWindow" on "\\.\DISPLAY1". Resulting geom
etry: 1525x237+197+412 (frame: 1541x275+189+382) margins: 8, 30, 8, 8 minimum si
ze: 1525x191 maximum size: 1525x191 MINMAXINFO maxSize=0,0 maxpos=0,0 mintrack=1
541,229 maxtrack=1541,229)
QWindowsWindow::setGeometry: Unable to set geometry 1525x423+197+412 (frame: 154
1x461+189+382) on QWidgetWindow/"DialogWindow" on "\\.\DISPLAY1". Resulting geom
etry: 1525x461+197+412 (frame: 1541x499+189+382) margins: 8, 30, 8, 8 minimum si
ze: 1525x423 maximum size: 1525x11000 MINMAXINFO maxSize=0,0 maxpos=0,0 mintrack
=1541,461 maxtrack=1541,11038)
QWindowsWindow::setGeometry: Unable to set geometry 1525x1+197+412 (frame: 1541x
39+189+382) on QWidgetWindow/"DialogWindow" on "\\.\DISPLAY1". Resulting geometr
y: 1525x461+197+412 (frame: 1541x499+189+382) margins: 8, 30, 8, 8 minimum size:
1525x1 maximum size: 1525x1 MINMAXINFO maxSize=0,0 maxpos=0,0 mintrack=1541,39
maxtrack=1541,39)
...
</code></pre>
<p>Any error would happen, but i may know how can i solve this warnings.</p>
<p>Screenshot:</p>
<p><a href="https://i.sstatic.net/0pVRX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0pVRX.png" alt="enter image description here" /></a></p>
<p>The resize method is called after the click on the first and the second buttons. So one ip_call_frame is added, the resize and the center methods are called.</p>
<p>Related links:</p>
<ol>
<li><p><a href="https://code.qt.io/cgit/qt/qtbase.git/tree/src/plugins/platforms/windows/qwindowswindow.cpp" rel="nofollow noreferrer">https://code.qt.io/cgit/qt/qtbase.git/tree/src/plugins/platforms/windows/qwindowswindow.cpp</a></p>
</li>
<li><p><a href="https://code.qt.io/cgit/qt/qtbase.git/tree/src/plugins/platforms/windows/qwindowswindow.cpp?h=5.7" rel="nofollow noreferrer">https://code.qt.io/cgit/qt/qtbase.git/tree/src/plugins/platforms/windows/qwindowswindow.cpp?h=5.7</a></p>
</li>
</ol>
| <python><user-interface><pyqt5> | 2023-07-23 20:43:08 | 1 | 2,427 | Chris P |
76,750,209 | 2,643,364 | Poetry fails to find a compatible version for the very first added package (numpy) | <p>I initialized a poetry project. It generated the configuration:</p>
<pre><code>[tool.poetry]
name = "projectname"
version = "0.1.0"
description = ""
authors = ["My Name <my@email.com>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.8"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
</code></pre>
<p>Right after that, I launched</p>
<pre><code>poetry add numpy
</code></pre>
<p>And it returned</p>
<pre><code>Using version ^1.25.1 for numpy
Updating dependencies
Resolving dependencies... (0.0s)
The current project's Python requirement (>=3.8,<4.0) is not compatible with some of the required packages Python requirement:
- numpy requires Python >=3.9, so it will not be satisfied for Python >=3.8,<3.9
Because no versions of numpy match >1.25.1,<2.0.0
and numpy (1.25.1) requires Python >=3.9, numpy is forbidden.
So, because janesweather depends on numpy (^1.25.1), version solving failed.
• Check your dependencies Python requirement: The Python requirement can be specified via the `python` or `markers` properties
For numpy, a possible solution would be to set the `python` property to ">=3.9,<4.0"
https://python-poetry.org/docs/dependency-specification/#python-restricted-dependencies,
https://python-poetry.org/docs/dependency-specification/#using-environment-markers
</code></pre>
<p>Why is poetry not able to find a compatible version of numpy?</p>
<p>I tried with <code>python = ">=3.8,<3.9"</code> but it failed the same. I tried to specify a version, e.g., <code>poetry add numpy==1.24.1</code>, which worked. But I assume poetry should be able to find a compatible version by itself.</p>
| <python><python-poetry> | 2023-07-23 20:32:00 | 1 | 373 | olivaw |
76,750,207 | 7,052,933 | AzureOpenAI not Available in Langchain | <p>I am trying to use the <code>langchain</code> package in <code>Python</code> to interact with <code>Azure Open AI</code>.
In my personal laptop, once I run <code>pip install langchain</code> I am successfully able to import using <code>from langchain.llms import AzureOpenAI</code>.
But when I perform the same steps in my office laptop it gives me an <code>ImportError: cannot import name 'AzureOpenAI' from langchain.llms (C:\...\lib\site-packages\langchain\llms\__init__.py)</code></p>
<p>I opened this <code>__init__.py</code> file and they are different in my personal laptop and my office laptop, and when I look for the keyword "<code>AzureOpenAI</code>" there is none in my office laptop.
Why are the <code>langchain</code> installations different between my personal and company laptop even though I ran the same command <code>pip install langchain</code>? Is there a way to make it work in my office laptop?</p>
| <python><pip><package><anaconda><langchain> | 2023-07-23 20:31:39 | 0 | 405 | Kenneth Singh |
76,750,109 | 11,092,636 | Is slicing + assign numpy equivalent to a for loop in C? | <p>When we do, with numpy (in Python):</p>
<pre class="lang-py prettyprint-override"><code>my_array[::4] = 0
</code></pre>
<p>is it:</p>
<pre class="lang-c prettyprint-override"><code>for (int i = 0; i < my_array_size; i += 4) {
my_array[i] = 0;
}
</code></pre>
<p>in C?</p>
<p>Or is there SIMD done by numpy?</p>
<p>If so, what are actual cases where rewriting Python code in C is useful, since I wouldn't expect anyone (unless they have a lot of knowledge) to be able to do SIMD manually in C (or C++ for that matter)?</p>
<p>I'm asking this question because I can't make the Sieve of Eratosthenes significantly faster on C than on Python and I was curious as to why. Here are my implementations (Jérôme Richard suggested using bits instead of bytes for the boolean array which is a good idea):</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <stdint.h>
typedef struct
{
int *primes;
int size;
} Result;
Result EratosthenesSieveC(int n)
{
uint8_t *nbs = (uint8_t *)malloc((n + 1) / 8 + 1);
int i, j, count = 0;
double limit = sqrt(n);
// Initialize the array with true everywhere except for 0 and 1
nbs[0] = nbs[1] = false;
for (i = 2; i <= n; i++)
{
nbs[i / 8] |= 1 << (i % 8);
}
// Apply the Sieve of Eratosthenes algorithm
for (i = 2; i <= limit; i++)
{
if (nbs[i / 8] & (1 << (i % 8)))
{
for (j = i * i; j <= n; j += i)
{
if (nbs[j / 8] & (1 << (j % 8)))
{
nbs[j / 8] &= ~(1 << (j % 8));
count++; // how many numbers are not prime
}
}
}
}
// Allocate memory for the array of primes
int *primes = (int *)malloc((n + 1 - count - 2) * sizeof(int));
// Store the prime numbers in the 'primes' array
int index = 0;
for (i = 2; i <= n; i++)
{
if (nbs[i / 8] & (1 << (i % 8)))
{
primes[index++] = i;
}
}
// Free the memory used by the 'nbs' array
free(nbs);
Result result;
result.primes = primes;
result.size = n - count - 1;
return result; // Note: I never really deallocate the memory of result which might be causing memory leaks??
}
</code></pre>
<p>Numpy:</p>
<pre class="lang-py prettyprint-override"><code>def EratosthenesSieveFullNumpy(n):
nbs = np.ones(n+1, dtype=bool)
nbs[:2] = 0
for i in range(2, int(n**0.5)+1):
if nbs[i]:
nbs[i*i::i] = 0
return np.where(nbs)[0]
</code></pre>
<p>It's worth noting this implementation is really bad:</p>
<pre class="lang-py prettyprint-override"><code>def EratosthenesSieveNumpy(n):
nbs = np.ones(n+1, dtype=bool)
nbs[:2] = 0
for i in range(2, int(n**0.5)+1):
if nbs[i]:
for j in range(i*i, n+1, i):
nbs[j] = 0
return np.where(nbs)[0]
</code></pre>
<p>Which is why I suspected SIMD to be the reason why I couldn't make my C code faster.</p>
<p>To import my C code in Python I used:</p>
<pre class="lang-py prettyprint-override"><code>class Result(ctypes.Structure):
_fields_ = [('primes', ctypes.POINTER(ctypes.c_int)), ('size', ctypes.c_int)]
lib = ctypes.cdll.LoadLibrary(my_path_of_compiled_shared_library)
lib.EratosthenesSieveC.restype = Result
def EratosthenesSieveC(n, lib):
result = lib.EratosthenesSieveC(n)
return result.primes[:result.size]
</code></pre>
<p>My results are:
<a href="https://i.imgur.com/1vUJDv7.png" rel="nofollow noreferrer">https://i.imgur.com/1vUJDv7.png</a></p>
| <python><c><numpy><simd> | 2023-07-23 20:04:48 | 0 | 720 | FluidMechanics Potential Flows |
76,750,006 | 412,234 | Python subprocess Popen set encoding of the child process | <p>This SSCCE reports the encoding rule on sys.stdout. It works by creating a temporary Python file and running it via the subprocess module:</p>
<pre><code>subp_code = "import sys\nprint(sys.stdout.encoding)"
test_fname = 'sub_test123123123_TMP.py' # I doubt anyone on Earth has an *important* file with this name.
with open(test_fname, 'w') as f:
f.write(subp_code)
import os, sys, subprocess
pr = subprocess.Popen(['python', test_fname], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = pr.communicate() # Use this for one-shot interaction. Do not use for processes that you want to have a back-and-forth conv with.
os.remove(test_fname) # Delete the tmp file we just made.
print('Encoding here:', sys.stdout.encoding) #utf-8
print('Encoding in subprocess:', out.decode().strip()) #cp1252 on Windows.
</code></pre>
<p>On windows the child process has cp1252 instead of utf-8 for whatever nonsense reason. This means unicode print statements that work under utf-8 generally won't work under cp1252:</p>
<pre><code>print(chr(1234)) #UnicodeEncodeError: 'charmap' codec can't encode character '\u04d2' in position 0: character maps to <undefined>
</code></pre>
<p>Adding "encoding='utf-8'" to the Popen kwargs doesn't work: the subprocess ends up communicating in strings instead of binary (so you would have to remove the decode() call in the above example) but the child process is still under cp1252.</p>
<p>Within a subprocess it can be manually changed:</p>
<pre><code>sys.stdout.reconfigure(encoding='utf-8')
</code></pre>
<p>However I would like to not rely on adding that line of code to all of my subprocesses. Is there any way to configure the subprocess to use utf-8 std streams from the main process?</p>
| <python><windows><encoding><utf-8><subprocess> | 2023-07-23 19:36:05 | 1 | 3,589 | Kevin Kostlan |
76,749,999 | 610,633 | Print from mapped function in multiprocessing Pool on Windows | <p>I am trying to generate a printout from my mapped workers in Python and the following works when I run it on the command line in Linux, but it doesn't print out when using the IDLE Shell on Windows.</p>
<p>I get <code>outputs: [None, None, None]</code>, but none of the <code>input:</code> prints from the <code>simulate</code> function.</p>
<p>Any ideas why?</p>
<pre><code>import multiprocessing
def simulate(input):
print("input:", input)
inputs = [1, 2, 3]
if __name__ == '__main__':
with multiprocessing.Pool(processes=8) as pool:
outputs = pool.map(simulate, inputs)
print("outputs:", outputs)
</code></pre>
| <python><python-multiprocessing><python-idle> | 2023-07-23 19:32:54 | 1 | 1,025 | Pablitorun |
76,749,985 | 14,072,456 | How to make a layout fill the entire window in PyQt5? | <p>I'm creating an app in PyQt5 and I want a layout that fills the entire window, except the title bar.</p>
<p>When I try to set a <code>QVBoxLayout</code> to a <code>QWidget</code>, there remains a gap, as seen below:</p>
<p><a href="https://i.sstatic.net/88D5p.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/88D5p.png" alt="App" /></a></p>
<p>This is my code:</p>
<pre><code>def main():
app = QApplication(sys.argv)
win = QWidget()
win.setFixedSize(225,150)
label = QLabel("Some Label")
label.setAlignment(QtCore.Qt.AlignCenter)
label.setStyleSheet('background: red')
layout = QVBoxLayout()
layout.addWidget(label)
win.setLayout(layout)
win.show()
sys.exit(app.exec_())
main()
</code></pre>
<p>So how do I remove the gap?</p>
| <python><pyqt5><qwidget><qvboxlayout> | 2023-07-23 19:29:01 | 1 | 339 | Itsjul1an |
76,749,819 | 7,587,176 | Recursive Python Question - Where is n being updated? | <p>In this very classic recursive example, where is the variable n being updated?</p>
<p>Would you not have to</p>
<pre><code>def factorial(n):
if n <= 1: # BASE CASE
return 1
return n * factorial(n - 1) # RECURSIVE CALL
</code></pre>
<p>Why would you not have to have</p>
<pre><code>def factorial(n):
if n <= 1: # BASE CASE
return 1
return n * factorial(n - 1) # RECURSIVE CALL
n = n - 1 ## why is something like this not needed?
</code></pre>
| <python> | 2023-07-23 18:43:57 | 1 | 1,260 | 0004 |
76,749,728 | 9,052,139 | How ChromaDB querying system works? | <p>I am currently learning ChromaDB vector DB.</p>
<p>I can't understand how the querying process works.</p>
<p>When I try to query using text, it's returning all documents.</p>
<pre><code>collection.add(
documents=["This is a document about cat", "This is a document about car"],
metadatas=[{"category": "animal"}, {"category": "vehicle"}],
ids=["id1", "id2"]
)
results = collection.query(
query_texts=["vehicle"],
n_results=2
)
results
</code></pre>
<p>The output is:</p>
<pre><code>{'ids': [['id2', 'id1']],
'distances': [[0.8069301247596741, 1.648103952407837]],
'metadatas': [[{'category': 'vehicle'}, {'category': 'animal'}]],
'embeddings': None,
'documents': [['This is a document about car',
'This is a document about cat']]}
</code></pre>
<p>Even I entered a word the not present anywhere, it's still returning all docs.</p>
<p>Why does this happen?</p>
| <python><chromadb> | 2023-07-23 18:22:51 | 5 | 1,004 | RagAnt |
76,749,710 | 11,969,592 | Create a poetry pypi project & install it with pipx | <p>I have a <a href="https://github.com/Cyfrin/dup-hawk" rel="nofollow noreferrer">python project</a> that I have uploaded to pypi, and now I am attempting to install it with pipx:</p>
<pre><code>pipx install dup-hawk
</code></pre>
<p>however, I'm getting:</p>
<pre><code>No apps associated with package dup-hawk. Try again with '--include-deps' to include apps of dependent packages, which are listed above. If you are
attempting to install a library, pipx should not be used. Consider using pip or a similar tool instead.
</code></pre>
<p>I think this is due to me not having an entry script for my project defined in poetry. How do I define an entry point in a poetry project so it can be installed with pipx?</p>
| <python><python-poetry><pipx> | 2023-07-23 18:18:18 | 1 | 6,207 | Patrick Collins |
76,749,633 | 18,313,588 | Convert text file that contains colon to json | <p>Existing Code</p>
<pre><code>import json
filename = 'thunar-volman/debian/control'
dict1 = {}
with open(filename) as fh:
for line in fh:
print(line)
command, description = line.strip().split(': ')
print(command)
print(description)
dict1[command.strip()] = description.strip()
with open("test.json", "w") as out_file:
json.dump(dict1, out_file, indent=4, sort_keys = False)
</code></pre>
<p>Error</p>
<pre><code>Build-Depends
debhelper-compat (= 13),
intltool,
Traceback (most recent call last):
File "read.py", line 7, in <module>
command, description = line.strip().split(': ')
ValueError: not enough values to unpack (expected 2, got 1)
</code></pre>
<p>The text file I am intending to process to json is here - <a href="https://salsa.debian.org/xfce-team/goodies/thunar-volman/-/blob/debian/master/debian/control" rel="nofollow noreferrer">https://salsa.debian.org/xfce-team/goodies/thunar-volman/-/blob/debian/master/debian/control</a></p>
<p>How can I process the content such that the content behind the colon of <code>Build-Depends</code> would be processed as the <code>description</code> for the <code>Build-Depends</code> <code>command</code>.</p>
<p>Any help would be very much appreciated as I am very new to json.</p>
| <python><json><python-3.x> | 2023-07-23 17:58:02 | 6 | 493 | nerd |
76,748,973 | 1,478,054 | Python Resample 2d Numpy with interpolation | <p>Given a 2d array of size (width=x, height=y), where each row contains entries with a height information in meters each. The distance in meters between two horizontally neighbored entries in a row varies by y-position. Thus in one row the distance between two entries is 30m, where in a row above the distance e.g. is 31m.</p>
<p>How do i resample and interpolate the 2d array to have the horizontal distance between pixels equal a given value for each row? If possible, are there multiple options for interpolating?</p>
| <python><numpy><interpolation><resample> | 2023-07-23 15:13:05 | 1 | 496 | Carsten Drösser |
76,748,794 | 10,945,401 | Error installing python dlib uder jupyrer notebook | <p>Under Jupiter notebook, i tried to install <code>dlib</code> package :</p>
<pre><code>pip install dlib
</code></pre>
<p>I obtained the following error :</p>
<pre><code>Collecting dlib
Using cached dlib-19.24.2.tar.gz (11.8 MB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata (pyproject.toml): started
Preparing metadata (pyproject.toml): finished with status 'done'
Building wheels for collected packages: dlib
Building wheel for dlib (pyproject.toml): started
Building wheel for dlib (pyproject.toml): finished with status 'error'
Failed to build dlib
error: subprocess-exited-with-error
Building wheel for dlib (pyproject.toml) did not run successfully.
exit code: 1
[73 lines of output]
running bdist_wheel
running build
running build_ext
<string>:125: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
Building extension for Python 3.10.10 | packaged by Anaconda, Inc. | (main, Mar 21 2023, 18:39:17) [MSC v.1916 64 bit (AMD64)]
Invoking CMake setup: 'cmake C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-s4im1wse\dlib_6311ea7c12944928afe6fa5cda1f5d5d\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-s4im1wse\dlib_6311ea7c12944928afe6fa5cda1f5d5d\build\lib.win-amd64-cpython-310 -DPYTHON_EXECUTABLE=C:\Users\Rayane_2\AppData\Local\r-miniconda\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-s4im1wse\dlib_6311ea7c12944928afe6fa5cda1f5d5d\build\lib.win-amd64-cpython-310 -A x64'
-- Building for: NMake Makefiles
CMake Error at CMakeLists.txt:5 (message):
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
You must use Visual Studio to build a python extension on windows. If you
are getting this error it means you have not installed Visual C++. Note
that there are many flavors of Visual Studio, like Visual Studio for C#
development. You need to install Visual Studio for C++.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- Configuring incomplete, errors occurred!
Traceback (most recent call last):
File "C:\Users\Rayane_2\AppData\Local\r-miniconda\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module>
main()
File "C:\Users\Rayane_2\AppData\Local\r-miniconda\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main
json_out['return_val'] = hook(**hook_input['kwargs'])
File "C:\Users\Rayane_2\AppData\Local\r-miniconda\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 251, in build_wheel
return _build_backend().build_wheel(wheel_directory, config_settings,
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\build_meta.py", line 416, in build_wheel
return self._build_with_temp_dir(['bdist_wheel'], '.whl',
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\build_meta.py", line 401, in _build_with_temp_dir
self.run_setup()
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\build_meta.py", line 338, in run_setup
exec(code, locals())
File "<string>", line 218, in <module>
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\__init__.py", line 107, in setup
return distutils.core.setup(**attrs)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 185, in setup
return run_commands(dist)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 201, in run_commands
dist.run_commands()
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 969, in run_commands
self.run_command(cmd)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\dist.py", line 1234, in run_command
super().run_command(command)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 988, in run_command
cmd_obj.run()
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\wheel\bdist_wheel.py", line 346, in run
self.run_command("build")
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 318, in run_command
self.distribution.run_command(command)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\dist.py", line 1234, in run_command
super().run_command(command)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 988, in run_command
cmd_obj.run()
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\command\build.py", line 131, in run
self.run_command(cmd_name)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 318, in run_command
self.distribution.run_command(command)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\dist.py", line 1234, in run_command
super().run_command(command)
File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-build-env-6m1cj1ox\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 988, in run_command
cmd_obj.run()
File "<string>", line 130, in run
File "<string>", line 167, in build_extension
File "C:\Users\Rayane_2\AppData\Local\r-miniconda\lib\subprocess.py", line 369, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\Public\\Documents\\Wondershare\\CreatorTemp\\pip-install-s4im1wse\\dlib_6311ea7c12944928afe6fa5cda1f5d5d\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\Public\\Documents\\Wondershare\\CreatorTemp\\pip-install-s4im1wse\\dlib_6311ea7c12944928afe6fa5cda1f5d5d\\build\\lib.win-amd64-cpython-310', '-DPYTHON_EXECUTABLE=C:\\Users\\Rayane_2\\AppData\\Local\\r-miniconda\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\Public\\Documents\\Wondershare\\CreatorTemp\\pip-install-s4im1wse\\dlib_6311ea7c12944928afe6fa5cda1f5d5d\\build\\lib.win-amd64-cpython-310', '-A', 'x64']' returned non-zero exit status 1.
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for dlib
ERROR: Could not build wheels for dlib, which is required to install pyproject.toml-based projects
</code></pre>
<p>I do not understand this error, <code>cmake</code> is already installed.</p>
<pre><code>import sys
print(sys.version)
3.10.10 | packaged by Anaconda, Inc. | (main, Mar 21 2023, 18:39:17) [MSC v.1916 64 bit (AMD64)]
</code></pre>
<p>it seems error is coming from cmake installation , when trying cmake --version command in cmd , the command is not recognized by compiler .</p>
<pre><code>C:\Users\Rayane_2>cmake --version
'cmake' is not recognized as an internal or external command,
operable program or batch file.
</code></pre>
| <python><dlib> | 2023-07-23 14:35:22 | 1 | 1,274 | Tou Mou |
76,748,574 | 11,898,085 | BeutifulSoup image scraping returns too few pictures | <p>Here is my first script for scraping images from the web put together from a few examples from the web. I used <code>nbr_of_images = 50</code> and got 20 dancer and 20 chair images. So I thought that by using <code>nbr_of_images = 100</code> I'd get about 50 of both. But the script still gets me 20 dancer images and 20 chair images. I can't see why. Could someone help me out?</p>
<pre class="lang-py prettyprint-override"><code># A script for downloading images from URLs.
import sys
import requests
from urllib.parse import urlparse
from bs4 import BeautifulSoup as bs
def is_valid(url):
"""is_valid checks whether input URL is valid.
Parameters
----------
url : str
The URL to be validated.
Returns
-------
valid : Bool
a Boolean value describing if the input URL is valid or not.
"""
parsed = urlparse(url)
valid = bool(parsed.netloc) and bool(parsed.scheme)
return valid
def get_n_images(url, folder, nbr_of_images, dancer):
"""get_n_images extracts image URLs from the imput URL and downloads
the image URL contents to a given folder.
Parameters
----------
url : str
The URL from which the image URLs are extracted.
folder : str
Path for the image download folder.
nbr_of_images : int
The number of image URLs to be extracted.
dancer : Bool
A Boolean for checking if the images are dancer images or not.
"""
if is_valid(url):
soup = bs(requests.get(url).text, 'html.parser')
else:
print('Invalid URL. Aborting.')
sys.exit(1)
n_images = soup.find_all('img', limit=nbr_of_images)
for i, image in enumerate(n_images):
# Get the image url.
try:
image_link = image['data-srcset']
except:
try:
image_link = image['data-src']
except:
try:
image_link = image['data-fallback-src']
except:
try:
image_link = image['src']
except:
pass
# Get the content of the image url.
dancers = f'{folder}/dancer{i+1}.jpg'
non_dancers = f'{folder}/image{i+1}.jpg'
try:
image = requests.get(image_link).content
try:
image = str(image, 'utf-8')
except UnicodeDecodeError:
if dancer:
with open(dancers, 'wb') as pic:
pic.write(image)
else:
with open(non_dancers, 'wb') as pic:
pic.write(image)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
nbr_of_images = 100
url_dancers = 'https://www.google.com/search?rlz=1C1GCEA_enFI1058FI1058&q=dancer+from+above&tbm=isch&sa=X&ved=2ahUKEwjTtbm2u6SAAxWaS_EDHYrCC1AQ0pQJegQICBAB&biw=1536&bih=707&dpr=1.25'
url_chairs = 'https://www.google.com/search?q=chair+from+above&tbm=isch&ved=2ahUKEwihr47Uu6SAAxUCIxAIHcHUBAUQ2-cCegQIABAA&oq=chair+from+above&gs_lcp=CgNpbWcQAzIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIGCAAQBxAeMggIABAFEAcQHjIICAAQBRAHEB4yBggAEAUQHjoHCAAQigUQQ1C0F1jhG2DEImgAcAB4AIABPYgByAKSAQE2mAEAoAEBqgELZ3dzLXdpei1pbWfAAQE&sclient=img&ei=KOy8ZKH7OILGwPAPwamTKA&bih=707&biw=1536&rlz=1C1GCEA_enFI1058FI1058'
get_n_images(url_dancers, 'training_images', nbr_of_images, True)
get_n_images(url_chairs, 'training_images', nbr_of_images, False)
</code></pre>
| <python><web-scraping><beautifulsoup> | 2023-07-23 13:47:59 | 1 | 936 | jvkloc |
76,748,303 | 22,212,435 | What happens, if the row parameter of the grid is not supplied? | <p>I thought, that in the case, if you put you row parameter empty (e.g. <code>frame.grid(column=0, pady=5)</code>) it will add this frame after the last occupied row. And it did that in my program. But then I decided to read about this in tcl.tk man doc, and there is a sentence that I can't understand: "<em>If this option is not supplied, then the content is arranged on the same row as the previous content specified on this call to grid, or the next row after the highest occupied row if this is the first content</em>". I can't understand, in what case it will put the content on the same row, in what on the different. Maybe someone could rephrase this in a different words, because can't really understand what did they mean</p>
| <python><tkinter> | 2023-07-23 12:42:19 | 1 | 610 | Danya K |
76,748,279 | 7,339,624 | Changing the Default Cache Path for All HuggingFace Data | <p>The default cache path of huggingface is in <code> ~/.cache/huggingface</code>, and in that folder, there are multiple cache files like <code>models</code>, and <code>hub</code>.</p>
<p>The <a href="https://huggingface.co/docs/datasets/cache" rel="nofollow noreferrer">huggingface documents</a> indicates that the default <code>dataset</code> cache location can be modified by setting the shell environment variable, <code>HF_DATASETS_CACHE</code> to a different directory as shown below:</p>
<pre><code>$ export HF_DATASETS_CACHE="/path/to/another/directory"
</code></pre>
<p>However, my objective is to alter the default cache directory for all HuggingFace data and not solely the <code>dataset</code>. I am facing difficulties in finding the respective shell environment variable in the HuggingFace documentation to accomplish this. Any help would be appreciated.</p>
| <python><nlp><huggingface> | 2023-07-23 12:38:55 | 2 | 4,337 | Peyman |
76,748,224 | 10,303,685 | How to change the color of a single line plot based on another variable | <p>I want to plot a line using the following equation.</p>
<p>y = x(1+0.25ε)
Where,
x = {0, 1, 2, ..., 200}
ε = np.random.randn()</p>
<p>And i want to change the color of the plot based on slop. I.e it should be blue when the slope is positive and it should be red when slope is negative. Like the following</p>
<p><a href="https://i.sstatic.net/xKTG7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xKTG7.png" alt="enter image description here" /></a></p>
<pre><code>import numpy as np
N = 100 # Change the number of data points to 100
x = np.array([i for i in range(N)]) # Use x=[i for i in range(100)]
epsilon = np.random.rand(N) # Generate random noise for N data points
y = x * (1 + 0.25 * epsilon) # Calculate y with noise
slope = np.gradient(y, x) # Calculate the slope of y with respect to x
# Separate the data points based on the condition (slope > 0)
positive_slope = slope > 0
x_positive_slope = x[positive_slope]
y_positive_slope = y[positive_slope]
# Separate the data points based on the condition (slope < 0)
negative_slope = slope < 0
x_negative_slope = x[negative_slope]
y_negative_slope = y[negative_slope]
plt.figure(figsize=(10, 4))
plt.plot(x_positive_slope, y_positive_slope, color='r', label='Positive Slope')
plt.plot(x_negative_slope, y_negative_slope, color='b', label='Negative Slope')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Line Plot with Color Trend Following Slope')
plt.grid(True)
plt.show()
</code></pre>
<p><a href="https://i.sstatic.net/Oi2wC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Oi2wC.png" alt="enter image description here" /></a></p>
<p>but it plots two different lines. Any idea ?</p>
| <python><numpy><matplotlib><plot><visualization> | 2023-07-23 12:25:58 | 2 | 388 | imtiaz ul Hassan |
76,748,150 | 4,225,972 | Writing to SQL yields different results with shell / django | <p>I have a simple model:</p>
<pre><code>class myJSONField(models.JSONField):
def get_prep_value(self, v):
if v is None:
return value
return json.dumps(v, ensure_ascii = False)
class Product(models.Model):
data = myJSONField()
number = models.PositiveIntegerField()
</code></pre>
<p><code>Product.create(number = 1, data = {"direction": "süd"})</code> yields:</p>
<pre><code>"{\"direction\": \"s\u00fcd\"}"
</code></pre>
<p>Testing with sqlite3:</p>
<pre><code>conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
test = json.dumps({"direction": "Süd"}, ensure_ascii = False)
sql = ("""UPDATE test_product SET data = ? WHERE id=1""")
c.execute(sql, [test])
conn.commit()
</code></pre>
<p>yields:</p>
<pre><code>{"direction": "süd"}
</code></pre>
<p>I am using the same <code>db.sqlite3</code> file for both tests.</p>
<ol>
<li>I do not understand why the <code>ensure_ascii = False</code> flag is ignored by the django logic.</li>
<li>How can I obtain a correct JSON in my JSONField (without the escaped <code>"</code>)?</li>
</ol>
<p>Edit: I can see the result in my django admin and I also tested omitting the <code>ensure_ascii = False</code> setting in SQLite:</p>
<pre><code>a = {"direction": "Süd", }
b = json.dumps(a)#, ensure_ascii = False)
sql = ("""UPDATE test_product SET data = ? WHERE id=1""")
c.execute(sql, [b])
conn.commit()
</code></pre>
<p>which leads to:</p>
<pre><code>{"direction": "S\u00fcd"}
</code></pre>
<p>(remark: no <code>"</code> around that one!)</p>
<p>When <strong>writing to the database with Django</strong> and <strong>reading</strong> via <code>python manage.py shell</code> and <strong><code>sqlite3</code></strong> directly:</p>
<pre><code>import sqlite3
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
c.execute('SELECT * FROM virtualShelf_product WHERE id=1')
res = c.fetchall()
[(1, 1, '"{\\"direction\\": \\"s\\u00fcd\\"}"')]
</code></pre>
<p>when <strong>reading</strong> the same product via <strong>Django ORM</strong>:</p>
<pre><code>p = Product.objects.get(id=1)
p.data
'{"direction": "süd"}'
</code></pre>
| <python><django><django-models> | 2023-07-23 12:07:54 | 1 | 1,400 | xtlc |
76,748,095 | 6,628,488 | How can I access the cost at each iteration when using the solve function in the cvxpy library? | <p>If you want to solve a convex optimization problem using the <code>cvxpy</code> library, only the last iteration cost can be calculated and returned, while other intermediate costs and related values are printed during the process. Take a look at the following code, which is obtained from the <a href="https://www.cvxpy.org/tutorial/advanced/index.html#viewing-solver-output" rel="nofollow noreferrer">cvxpy</a> library itself:</p>
<pre><code>import cvxpy
x = cvxpy.Variable(2)
objective = cvxpy.Minimize(x[0] + cvxpy.norm(x, 1))
constraints = [x >= 2]
problem = cvxpy.Problem(objective, constraints)
problem.solve(solver=cvxpy.ECOS, verbose=True)
</code></pre>
<p>And the printed result:</p>
<pre><code>ECOS 2.0.10 - (C) embotech GmbH, Zurich Switzerland, 2012-15. Web: www.embotech.com/ECOS
It pcost dcost gap pres dres k/t mu step sigma IR | BT
0 +6.667e-01 +7.067e-01 +6e+00 6e-01 1e-02 1e+00 9e-01 --- --- 1 1 - | - -
1 +3.500e+00 +3.925e+00 +1e+00 3e-01 4e-03 8e-01 2e-01 0.9890 2e-01 1 1 1 | 0 0
2 +5.716e+00 +5.825e+00 +2e-01 6e-02 8e-04 2e-01 4e-02 0.9091 8e-02 1 1 1 | 0 0
3 +5.997e+00 +5.998e+00 +3e-03 7e-04 1e-05 2e-03 5e-04 0.9881 1e-04 1 1 1 | 0 0
4 +6.000e+00 +6.000e+00 +3e-05 8e-06 1e-07 3e-05 5e-06 0.9890 1e-04 1 1 1 | 0 0
5 +6.000e+00 +6.000e+00 +3e-07 9e-08 1e-09 3e-07 6e-08 0.9890 1e-04 1 0 0 | 0 0
6 +6.000e+00 +6.000e+00 +4e-09 1e-09 1e-11 3e-09 6e-10 0.9890 1e-04 1 0 0 | 0 0
OPTIMAL (within feastol=9.9e-10, reltol=6.2e-10, abstol=3.7e-09).
Runtime: 0.000061 seconds.
</code></pre>
<p>We can only evaluate the final cost value of the last iteration using the <code>objective.value</code> or <code>problem.value</code>.</p>
<p>There is a similar question <a href="https://stackoverflow.com/questions/71692428/cvxpy-how-to-obtain-the-variable-value-after-each-iteration">here</a> but I don't need the other variables, I only need the costs which are printed by the library itself.</p>
| <python><cvxpy><convex-optimization> | 2023-07-23 11:55:19 | 1 | 1,284 | Alireza Roshanzamir |
76,747,664 | 625,350 | Sample 2D grid in Xarray | <p>I have a 1D array of samples, each having a corresponding x and y coordinate. I want to transform this into a 2D grid where each grid cell contains the average of all samples falling in that grid cell. Of course I could program this by hand, but I've got the impression that this is possible with <a href="https://docs.xarray.dev/en/latest/user-guide/groupby.html#multidimensional-grouping" rel="nofollow noreferrer">multidimensional grouping</a>.</p>
<p>As an example data I make a Lissajous curve</p>
<p><a href="https://i.sstatic.net/bHSSy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bHSSy.png" alt="enter image description here" /></a></p>
<p>I put this data in a DataArray and make a MultiIndex with <code>x</code> and <code>y</code> coordinates.</p>
<pre><code>my_data = <xarray.DataArray 'my_data' (time: 1200)>
array([0.000e+00, 1.000e+00, 2.000e+00, ..., 1.197e+03, 1.198e+03,
1.199e+03])
Coordinates:
h (time) float64 0.0 0.5 1.0 1.5 2.0 ... 598.0 598.5 599.0 599.5
* time (time) object MultiIndex
* x (time) float64 0.0 0.3596 0.6711 0.8929 ... 0.5044 0.7812 0.9535
* y (time) float64 1.0 0.9498 0.8041 0.5777 ... -0.6339 -0.36 -0.04993
</code></pre>
<p>The full example code is as follows:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
DIM_TIME = 'time'
t = np.arange(1200.0)
da = xr.DataArray(
name='my_data',
data = t, dims=[DIM_TIME],
coords = {
'x': (DIM_TIME, np.sin(t / np.e)),
'y': (DIM_TIME, np.cos(t / np.pi)),
'h': (DIM_TIME, t/2)})
da = da.set_xindex(['x', 'y']) # Add multi index
print(f"\n{da.name} = {da}")
bins = [-1.0, -0.6, -0.2, 0.2, 0.6, 1.0]
binned_x = da.groupby_bins("x", bins).mean().rename("bin_x_avg")
print(f"\n{binned_x.name} = {binned_x}")
da.to_dataset().plot.scatter(x='x', y='y', hue='h')
plt.show()
# Raises IndexError: too many indices
binned_xy = da.groupby_bins(("y", "x"), (bins, bins)).mean() # Something like this.
</code></pre>
<p>I can group-by one dimension just fine (<code>binned_x</code>), it gives a 1D array with 5 elements.</p>
<pre><code>bin_x_avg = <xarray.DataArray 'bin_x_avg' (x_bins: 5)>
array([603.20738636, 598.84431138, 600.03870968, 596.18823529,
597.48876404])
Coordinates:
* x_bins (x_bins) object (-1.0, -0.6] (-0.6, -0.2] ... (0.2, 0.6] (0.6, 1.0]
</code></pre>
<p>I would like to do something similar that bins in two dimensions. It should return a 5 by 5 DataArray. Something like the last statement in my code (<code>binned_xy</code>).</p>
<p>Is this somehow possible in XArray?</p>
| <python><numpy><python-xarray> | 2023-07-23 10:05:15 | 1 | 5,596 | titusjan |
76,747,574 | 5,640,517 | Querying progress in mega-cmd | <pre class="lang-py prettyprint-override"><code>>>> import os
>>> import subprocess
>>> process = subprocess.run(["mega-get", "https://mega.nz/file/xxxxx#xxxxxxxxxxxxxxxxxxxx", "./"])
TRANSFERRING ||##################################################################################################################################################||(163/163 MB: 100.00 %)
Download finished: /mnt/downloads/games/./game-pc.zip
TRANSFERRING ||##################################################################################################################################################||(163/163 MB: 100.00 %)
>>> process
CompletedProcess(args=['mega-get', 'https://mega.nz/file/xxxxx#xxxxxxxxxxxxxxxxxxxx', './'], returncode=0)
</code></pre>
<p>Once I do subprocess.run I can only watch as the download progresses, I want to use celery to run the download tasks but how would I know what's the progress?</p>
<p>For other hosts I can do this:</p>
<pre class="lang-py prettyprint-override"><code>total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
with open(temp_path, "wb") as file:
for chunk in response.iter_content(chunk_size=4096):
if chunk:
file.write(chunk)
downloaded_size += len(chunk)
# Calculate the progress percentage
progress = int((downloaded_size / total_size) * 100)
current_task.update_state(state='PROGRESS', meta={'progress': progress})
</code></pre>
<p>Do I just parse the progress bar output? Or is there other ways?</p>
| <python> | 2023-07-23 09:45:44 | 0 | 1,601 | Daviid |
76,747,462 | 16,383,578 | How to optimize printing Pascal's Triangle in Python? | <p>I have implemented the <a href="https://en.wikipedia.org/wiki/Pascal%27s_triangle" rel="nofollow noreferrer">Pascal's triangle</a> in Python, it is pretty efficient, but it isn't efficient enough and there are a few things I don't like.</p>
<p>The Pascal's triangle is like the following:</p>
<p><img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/23050fcb53d6083d9e42043bebf2863fa9746043" alt="" /></p>
<p>I have read <a href="https://www.geeksforgeeks.org/python-program-to-print-pascals-triangle/" rel="nofollow noreferrer">this useless tutorial</a> and <a href="https://stackoverflow.com/questions/24093387/pascals-triangle-for-python">this question</a>, and the solutions are extremely inefficient, involving factorials and don't use caching.</p>
<p>Instead, I implemented a different algorithm I created myself. My mathematics isn't that good, but I have spotted the following simple recursive relationships:</p>
<p>The triangle starts with a row with only 1 number in it, and that number is 1.</p>
<p>For each subsequent row, the length of the row increment by 1, and the first and last number of the row is 1.</p>
<p>Each number that isn't the first or last, is the sum of the number at the row above it with index equal to the number's index minus 1, and the number at row above it with the same index.</p>
<p>And the rows of the triangle are symmetric.</p>
<p>In other words, if we use zero-based indexing:</p>
<pre class="lang-none prettyprint-override"><code>p(r, 0) = p(r, r) = 1
p(r, c) = p(r - 1, c - 1) + p(r - 1, c)
p(r, c) = p(r, r - c)
</code></pre>
<p>Below is my code:</p>
<pre class="lang-py prettyprint-override"><code>from typing import List
class Pascal_Triangle:
def __init__(self, rows: int = 0, fill: bool = True):
self.data = []
self.length = 0
if rows:
self.fill_rows(rows)
if fill:
self.fill_values()
def add_row(self, length: int):
row = [0] * length
row[0] = row[-1] = 1
self.data.append(row)
def fill_rows(self, rows: int):
for length in range(self.length + 1, rows + 1):
self.add_row(length)
self.length = rows
def comb(self, a: int, b: int) -> int:
if not 0 <= b <= a:
raise ValueError(f'cannot choose {b} elements from a population of {a}')
if self.length < (length := a + 1):
self.fill_rows(length)
return self.at(a, b)
def at(self, row: int, col: int) -> int:
if val := self.data[row][row - col]:
self.data[row][col] = val
return val
if val := self.data[row][col]:
return val
self.data[row][col] = val = self.at(row - 1, col - 1) + self.at(row - 1, col)
return val
def fill_values(self):
for row in range(2, self.length):
for col in range(1, row):
self.at(row, col)
def get_row(self, row: int) -> List[int]:
if self.length < (length := row + 1):
self.fill_rows(length)
self.fill_values()
return self.data[row]
def pretty_print(self):
print('\n'.join(f"{' ' * (self.length - i)}{' '.join(map(str, row))}" for i, row in enumerate(self.data)))
</code></pre>
<p>First, the output of <code>tri = Pascal_Triangle(12); tri.pretty_print()</code> is extremely ugly:</p>
<pre class="lang-none prettyprint-override"><code> 1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
</code></pre>
<p>How can I dynamically adjust the spacing between the elements so that the output looks more like an equilateral triangle?</p>
<p>Second I don't like the recursive function, is there any way that I can get rid of the recursive function and calculate the values using the recursive relationship by iteration, while remembering already computed numbers?</p>
<p>Third, is there a data structure more efficient than my nested lists for the same data? I have thought of <code>numpy.array</code> but arrays need each row to have the same length and arrays can't grow.</p>
<p>Finally can my algorithm be optimized further?</p>
<hr />
<p>The data after calling <code>tri.at(16, 5)</code> is:</p>
<pre class="lang-none prettyprint-override"><code>[[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 0, 1],
[1, 8, 28, 56, 70, 56, 0, 0, 1],
[1, 9, 36, 84, 126, 126, 0, 0, 0, 1],
[1, 10, 45, 120, 210, 252, 0, 0, 0, 0, 1],
[1, 11, 55, 165, 330, 462, 0, 0, 0, 0, 0, 1],
[1, 12, 66, 220, 495, 792, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 78, 286, 715, 1287, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 364, 1001, 2002, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1365, 3003, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 4368, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]
</code></pre>
<hr />
<p>I know I am already doing <a href="https://en.wikipedia.org/wiki/Memoization" rel="nofollow noreferrer">memoization</a>, and that is not what I meant. I want to calculate the unfilled values without ever using a recursive function. Instead of using the recursive definition and going backwards, we can somehow use iteration, start from where the lowest value that was filled and needed for the query, and iterate through all needed numbers, make two copies of each number and go forwards, until the requested index was reached.</p>
<p>The needed numbers can be computed using indexing and mathematics.</p>
<p>In this way there is no recursive function call at all.</p>
<hr />
<h2><em><strong>Update</strong></em></h2>
<p>I have rewrote my code to the following:</p>
<pre><code>class Pascal_Triangle:
def __init__(self, end_row: int = 2, opt: int = 0):
self.data = [[1], [1, 1]]
self.length = 2
self.opt = [self.add_rows_o0, self.add_rows_o1]
if end_row > 2:
self.opt[opt](end_row)
def add_rows_o0(self, end_row: int):
last_row = self.data[-1]
for _ in range(self.length, end_row):
self.data.append(
last_row := [1] + [a + b for a, b in zip(last_row, last_row[1:])] + [1]
)
self.length = end_row
def add_rows_o1(self, end_row: int):
last_row = self.data[-1]
for n in range(self.length, end_row):
mid = n // 2 + 1
row = [0] * (n - 1)
m = n - 2
for i, (a, b) in enumerate(zip(last_row, last_row[1:mid])):
row[i] = row[m - i] = a + b
self.data.append(last_row := [1] + row + [1])
self.length = end_row
def pretty_print(self):
longest = len(str(self.data[-1][self.length // 2]))
line_length = (longest + 1) * self.length
for row in self.data:
print(" ".join(f"{n:{longest}}" for n in row).center(line_length))
</code></pre>
<p>I have used <a href="https://en.wikipedia.org/wiki/List_comprehension#Python" rel="nofollow noreferrer">list comprehension</a> to generate new rows and got rid of the expensive recursive function call. The code is much faster as a result.</p>
<p>However, I tried to exploit the symmetric nature of the rows and only calculate half of the row and mirror it to get the other half. In this way the number of calculations would be halved.</p>
<p>But it is actually slower:</p>
<pre class="lang-none prettyprint-override"><code>In [257]: %timeit Pascal_Triangle(64, 1)
237 µs ± 7.43 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [258]: %timeit Pascal_Triangle(64, 0)
224 µs ± 9.75 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [259]: Pascal_Triangle(64, 1).data == Pascal_Triangle(64, 0).data
Out[259]: True
</code></pre>
<p>Why is it slower? And how can I actually skip the unnecessary calculations and make it faster?</p>
| <python><python-3.x><algorithm><optimization><pascals-triangle> | 2023-07-23 09:14:19 | 5 | 3,930 | Ξένη Γήινος |
76,747,386 | 15,845,509 | What is S in COCO Object Keypoint Similarity equation? | <p>I am trying to understand Object Keypoint Similarity (OKS) in keypoint detection algorithm. However, based on the definition I cannot fully understand what is "S" in the equation means.
Here is the equation (<a href="https://cocodataset.org/#keypoints-eval" rel="nofollow noreferrer">https://cocodataset.org/#keypoints-eval</a>):</p>
<p>OKS = Σi[exp(-di2/2s2κi2)δ(vi>0)] / Σi[δ(vi>0)]</p>
<p>where "s" is mentioned as object scale. I dont know what does it really means. Can someone give more explanation?
Thank you</p>
| <python><deep-learning><computer-vision><object-detection> | 2023-07-23 08:55:07 | 1 | 369 | ryan chandra |
76,747,352 | 16,719,690 | Is it possible to avoid rewriting code when using both Flask-SQLAlchemy & pydantic? | <p>I'm writing a flask application with Flask-SQLAlchemy for the ORM. I also want to use Pydantic for validation. But this means I have to write a separate schema for Pydantic with the same fields as my SQLAlchemy model. Is this achievable without duplicating code?</p>
| <python><flask><sqlalchemy><pydantic> | 2023-07-23 08:47:11 | 0 | 357 | crabulus_maximus |
76,747,279 | 2,173,773 | PyQt: How to use QMessageBox.open() and connect callback? | <p>How can I connect a callback when using <code>QMessageBox.open()</code> ? In the <a href="https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QMessageBox.html#PySide2.QtWidgets.PySide2.QtWidgets.QMessageBox.open" rel="nofollow noreferrer">documentation</a> it says:</p>
<blockquote>
<p>QMessageBox.open(receiver, member)<br />
Opens the dialog and connects its finished() or buttonClicked() signal to the slot specified by receiver and member . If the slot in member has a pointer for its first parameter the connection is to buttonClicked() , otherwise the connection is to finished() .</p>
</blockquote>
<p>What should I use for <code>receiver</code> and <code>member</code> in the below example:</p>
<pre><code>import sys
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QPushButton, QMessageBox
)
def show_dialog(app, window):
mbox = QMessageBox(window)
mbox.setIcon(QMessageBox.Icon.Information)
mbox.setText("Message box pop up window")
mbox.setWindowTitle("QMessageBox Example")
mbox.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
def button_clicked():
print("message box button clicked")
mbox.done(0)
app.quit()
# How to connect button_clicked() to the standard buttons of the message box?
mbox.open(receiver, member) # What to use for receiver and member?
def main():
app = QApplication(sys.argv)
window = QMainWindow()
window.resize(330, 200)
window.setWindowTitle("Testing")
button = QPushButton(window)
button.setText("Button1")
button.setGeometry(100,100,100,30)
def button_clicked():
print("button clicked")
show_dialog(app, window)
button.clicked.connect(button_clicked)
window.show()
app.exec()
if __name__ == '__main__':
main()
</code></pre>
| <python><pyqt> | 2023-07-23 08:26:25 | 1 | 40,918 | Håkon Hægland |
76,747,123 | 2,510,900 | Efficiently interpolating a small xarray.DataArray into coordinates of a larger array? | <p>I have a large, high-resolution 3D (<code>time: 200, y: 2000, x: 2000</code>) <code>xarray.DataArray</code> similar to this:</p>
<pre><code>import xarray as xr
import numpy as np
import pandas as pd
time = pd.date_range("2019-01-01", "2021-12-30", periods=200)
y_large = np.linspace(-1000000, -1032000, 2000)
x_large = np.linspace(-1968000, -2000000, 2000)
data_large = np.random.randint(low=0, high=10, size=(200, 2000, 2000))
da_large = xr.DataArray(
data=data_large,
coords={"time": time, "y": y_large, "x": x_large},
dims=("time", "y", "x"),
)
da_large
</code></pre>
<p><a href="https://i.sstatic.net/XWx5j.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XWx5j.png" alt="Preview of large array" /></a></p>
<p>I also have a smaller, low-resolution (<code>time: 200, y: 100, x: 100</code>) <code>xarray.DataArray</code> containing different data, but covering the same <code>x</code> and <code>y</code> extents:</p>
<pre><code>y_small = np.linspace(-1000000, -1032000, 100)
x_small = np.linspace(-1968000, -2000000, 100)
data_small = np.random.randint(low=100, high=110, size=(200, 100, 100))
da_small = xr.DataArray(
data=data_small,
coords={"time": time, "y": y_small, "x": x_small},
dims=("time", "y", "x"),
)
da_small
</code></pre>
<p><a href="https://i.sstatic.net/mGZqq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mGZqq.png" alt="Preview of small array" /></a></p>
<p>I need to <strong>interpolate my small low-resolution array (<code>da_small</code>) into the higher resolution grid of my larger array (<code>da_large</code>),</strong> so that I end up with a <code>time: 200, y: 2000, x: 2000</code> array containing values resampled from <code>da_small</code>.</p>
<p>I thought I'd be able to do this using <code>xarray</code>'s <code>.interp()</code> method, by passing in my higher-res coordinates to sample and interpolate values from <code>da_small</code> into each pixel of <code>da_large</code>:</p>
<pre><code>da_small.interp(x=da_large.x, y=da_large.y, method="linear")
</code></pre>
<p>However, my challenge is that this operation causes an extremely large spike in memory, which crashes my kernel. This is a blocker for me, as my actual data can be even larger than this example (up to several thousand pixels tall/wide and several hundred timesteps deep).</p>
<p>My question: <strong>How can I perform this kind of operation (re-scaling or interpolating a small array into the grid of a larger array) in a more efficient way, avoiding such a large peak memory usage?</strong></p>
<p>(If possible, I'd prefer a solution compatible with <code>xarray</code> so it can slot into my existing workflows.)</p>
| <python><numpy><scipy><interpolation><python-xarray> | 2023-07-23 07:42:11 | 0 | 909 | Robbi Bishop-Taylor |
76,746,885 | 3,668,129 | application runs from pycharm but not from command line (ModuleNotfounderror) | <p>I have app with the following folder tree:</p>
<pre><code>MyApp
|
|-- Code
| |
| |-- main.py
| |-- settings.py
| |
|-- vev
</code></pre>
<p><code>venv</code> - is the virtual environment of that project.</p>
<p>I can run main.py from pycharm without any problem.</p>
<p>I'm trying to run it from command line:</p>
<ol>
<li><p>I activate the <code>venv</code></p>
</li>
<li><p>I run the following command from <code>MyApp</code> folder:</p>
<p>python Code\main.py</p>
</li>
</ol>
<p>and I'm getting the following error:</p>
<pre><code>ModuleNotFoundError: No module named 'Code'
</code></pre>
<p>How can I run <code>main.py</code> from command line (without any code change if it possible)</p>
| <python><pycharm> | 2023-07-23 06:25:45 | 1 | 4,880 | user3668129 |
76,746,750 | 4,451,521 | Why is the image being partially processed? | <p>It is been hours writing scripts and I think I am tired overlooking something simple.
I have the following pycuda script</p>
<pre><code>import cv2
import numpy as np
import time
import pycuda.autoinit
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
import pycuda.gpuarray as gpuarray
def apply_threshold(img_src,img_width, img_height, img_dest, mythreshold):
mod = SourceModule("""
__global__ void ThresholdKernel(
const int src_sizeX, //< source image size. x: width,
const unsigned char* src, //< source image pointer
const int dst_sizeX, //< destination image size. x: width, y: height
const int dst_sizeY,
unsigned char* dst, //< destination image pointer
const int mythreshold) {
int col = blockIdx.x * blockDim.x + threadIdx.x;
int row = blockIdx.y * blockDim.y + threadIdx.y;
if (dst_sizeX <= col || dst_sizeY <= row) return;
auto src_val = src[row * src_sizeX + col];
unsigned char dst_val = src_val > mythreshold ? 255 : 0;
dst[row * dst_sizeX + col] = dst_val;
}
""")
block_dim =(32,8,1)
grid_dim_x = (img_width + block_dim[0] -1) // block_dim[0]
grid_dim_y = (img_width + block_dim[1] -1) // block_dim[1]
print(grid_dim_x,grid_dim_y)
thresholdkernel = mod.get_function("ThresholdKernel")
thresholdkernel(np.int32(img_width), img_src, np.int32(img_width),np.int32(img_height),
img_dest,np.int32(mythreshold),
block = block_dim , grid = (grid_dim_x,grid_dim_y))
mythreshold = 128
img_path = "../images/lena_gray.png"
img = cv2.imread(img_path)
if img is None:
print("Image not found")
exit()
else:
height,width,channels = img.shape
print("Hegiht, width and channels",height,width,channels)
print(type(width))
img_gpu = cuda.mem_alloc(img.nbytes)
cuda.memcpy_htod(img_gpu,img)
dtype=img.dtype
# dest_img=gpuarray.empty_like(img.shape,dtype=dtype)
dest_img = cuda.mem_alloc(img.nbytes)
apply_threshold(img_gpu,width,height,dest_img ,mythreshold )
image_result= np.empty_like(img)
cuda.memcpy_dtoh(image_result,dest_img )
cv2.imshow("Original image",img)
cv2.imshow("Thresholded",image_result)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p>When I run it I get a binarized picture but this one</p>
<p><a href="https://i.sstatic.net/sjxrY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sjxrY.png" alt="lena" /></a></p>
<p>What am I overlooking that makes the kernel only process part of the image? It must be something really simple</p>
<p>EDIT: I found the problem. The way I am reading the image.</p>
<p>It should be</p>
<pre><code>img = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE)
</code></pre>
<p>Now it works, although for some reason it takes 10 times the time of a similar script I have that does the same... well...</p>
| <python><cuda><pycuda> | 2023-07-23 05:31:35 | 1 | 10,576 | KansaiRobot |
76,746,536 | 6,087,667 | Filtering on very large array of 3 possible values | <p>I have a 2D array of 0s, 1s and 2s with very large number of columns. I am trying to select only those rows which have consecutive zeros not exceeding certain number. My method is to convert the array into characters, merge columns and then apply the regular expression filter to it. But this is very slow. Especially the conversion and joining the characters in each row. Is there a way to make it faster by an order of magnitude? Maybe using another tactic altogether?</p>
<pre><code>import re
import numpy as np
n=100
k = 1000
x = np.random.choice([0,1,2], replace=True, size=(n,k))
s = np.apply_along_axis(lambda t: ''.join(t) , 1, x.astype(str))
N_ramp=3
mask = [re.search(r'[12]0{1,'+str(N_ramp)+r'}[12]', i) is None for i in s]
</code></pre>
| <python><arrays><string><numpy><python-re> | 2023-07-23 03:17:03 | 1 | 571 | guyguyguy12345 |
76,746,502 | 998,070 | Adjusting Shadows, Midtones, and Highlights with PIL | <p>I'm trying to adjust my Image's shadows, midtones, and highlights separately with PIL. I'm currently selecting these based on a division of 255 total by 3 (e.g. if(i<85) for shadows, if(i >= 85 and i < 170) for midtones, etc.).</p>
<p>This is the input image:
<a href="https://i.sstatic.net/oLCad.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oLCad.jpg" alt="Input Image" /></a></p>
<p>The result is currently very aliased.
<a href="https://i.sstatic.net/jKIOG.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jKIOG.jpg" alt="Results" /></a></p>
<p>Here are the Photoshop Levels Settings for the Desired Output:
<a href="https://i.sstatic.net/G3UEG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/G3UEG.png" alt="Levels" /></a></p>
<p>I've tried resizing the individual channels by twice the size, then resizing again with <code>resample=Image.ANTIALIAS</code>, but that didn't produce a good effect.</p>
<p><code>self.shadows</code>,<code>self.midtones</code>, <code>self.highlights</code>, and <code>self.alpha</code> are a float property value to control the adjustment.</p>
<pre class="lang-py prettyprint-override"><code>pil_image.convert('RGBA')
# Split into 4 channels
r, g, b, a = pil_image.split()
shadow_r = r.point(lambda i: i * self.shadows if(i < 85) else 0)
shadow_g = g.point(lambda i: i * self.shadows if(i < 85) else 0)
shadow_b = b.point(lambda i: i * self.shadows if(i < 85) else 0)
shadow_a = a.point(lambda i: i * self.alpha if(i < 85) else 0)
mid_r = r.point(lambda i: i * self.midtones if(i >= 85 and i < 170) else 0)
mid_g = g.point(lambda i: i * self.midtones if(i >= 85 and i < 170) else 0)
mid_b = b.point(lambda i: i * self.midtones if(i >= 85 and i < 170) else 0)
mid_a = a.point(lambda i: i * self.alpha if(i >= 85 and i < 170) else 0)
highlight_r = r.point(lambda i: i * self.highlights if(i >= 170) else 0)
highlight_g = g.point(lambda i: i * self.highlights if(i >= 170) else 0)
highlight_b = b.point(lambda i: i * self.highlights if(i >= 170) else 0)
highlight_a = a.point(lambda i: i * self.alpha if(i >= 170) else 0)
# Recombine back to RGB image
shadow_img = Image.merge('RGBA', (shadow_r, shadow_g, shadow_b, shadow_a))
mid_img = Image.merge('RGBA', (mid_r, mid_g, mid_b, mid_a))
highlight_img = Image.merge('RGBA', (highlight_r, highlight_g, highlight_b, highlight_a))
pil_image2 = ImageChops.add(shadow_img,mid_img)
pil_image = ImageChops.add(pil_image2,highlight_img)
</code></pre>
<p>Can anyone please guide me on how to adjust the channels with a better falloff for the selection? <strong>Thank you!</strong></p>
| <python><image><image-processing><python-imaging-library> | 2023-07-23 02:56:11 | 1 | 424 | Dr. Pontchartrain |
76,746,455 | 10,659,353 | Keyword arguments not independent in different function calls? | <p>This function receives a dict as a keyword argument. It then
prints this dict, and updates it >after<.</p>
<p>When I run it the first time, without passing arguments, the dict is, obviously,
empty. But when I run the same function again, also without passing arguments,
the dict is not empty, and has the data that was stored in the first call.</p>
<p>Shouldn't these two objects be independent?
If not, how can I make them such, without passing arguments and without copying the object inside the function?</p>
<p>(this is necessary for my usecase, since I want to share a memory recursively, but not between different starting points, and, unfortunately, the function call won't pass this argument).</p>
<p>Thanks</p>
<pre class="lang-py prettyprint-override"><code>def a(b={}):
print(b)
b['c'] = 'd'
a() # {}
a() # {'c': 'd'}
</code></pre>
| <python> | 2023-07-23 02:31:06 | 0 | 381 | Enzo Dtz |
76,746,350 | 9,078,185 | Plotly Sunburst chart, draw thicker borders on certain markers | <p>I am building a sunburst chart in <code>plotly.graph_objects</code>. The MRE below approximates the real data I have. What I'd like to do is draw thicker borders around the inner-most level. E.g., in the toy example, there would be thicker borders around "Magic Kingdom" and "Epcot" extending all the way to the outer levels. Can this be done?
<a href="https://i.sstatic.net/GvGBz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GvGBz.png" alt="enter image description here" /></a></p>
<pre><code>import plotly.graph_objects as go
import pandas as pd
data = {
'category': ['Epcot', 'Magic Kingdom',
'Future World', 'World Showcase',
'Adventure Land', 'Fantasy Land', 'Frontier Land',
'Spaceship Earth', 'Imagination', 'Test Track',
'Remy', 'Frozen',
'Jungle Cruise', 'Pirates',
'Mine Train', 'Small World', 'Tea Cups', 'Peter Pan',
'Big Thunder Mountain'],
'parents': ['', '', 'Epcot', 'Epcot',
'Magic Kingdom', 'Magic Kingdom', 'Magic Kingdom',
'Future World', 'Future World', 'Future World',
'World Showcase', 'World Showcase',
'Adventure Land', 'Adventure Land',
'Fantasy Land', 'Fantasy Land', 'Fantasy Land', 'Fantasy Land',
'Frontier Land'],
'value': [0, 0, 0, 0, 0, 0, 0, 20, 5, 25, 8, 12, 20, 10, 12, 25, 19, 5, 25]}
df = pd.DataFrame(data)
fig = go.Figure(go.Sunburst(ids=df['category'],
labels=df['category'],
parents=df['parents'],
values=df['value']))
fig.update_traces(marker_line_width=4) #updates borders for all markers
# Show the plot
fig.show()
</code></pre>
| <python><plotly> | 2023-07-23 01:27:26 | 1 | 1,063 | Tom |
76,746,256 | 4,902,709 | Dividing by 3 in Python decimal | <p>Just curious about how decimal package deals with infinite decimal. so I tried</p>
<pre class="lang-py prettyprint-override"><code>Python 3.7.3 (default, Oct 31 2022, 14:04:00)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from decimal import *
>>> import math
>>> Decimal(1) / 3 * 3
Decimal('0.9999999999999999999999999999')
>>> 1/3*3
1.0
>>> Decimal(1) / 3 * 3 == Decimal(1)
False
>>> math.floor(Decimal(1) / 3 * 3)
0
>>> math.floor(1 / 3 * 3)
1
</code></pre>
<p>I could guess why this working like this.
But is this expected and should I accepted this <code>math.floor(Decimal(1) / 3 * 3)</code> result?</p>
<hr />
<p>ps.
I added above example to show an unexpected behaviour.
there is more BTW,</p>
<pre class="lang-py prettyprint-override"><code>>>> Decimal(1) / 3 * 3 * 6
Decimal('5.999999999999999999999999999')
>>> math.floor(Decimal(1) / 3 * 3 * 6)
5
>>> math.floor(float(Decimal(1) / 3 * 3 * 6))
6
>>> sum([Decimal(1) / 3 * 3] * 6)
Decimal('6.000000000000000000000000000')
>>> math.floor(sum([Decimal(1) / 3 * 3] * 6))
6
</code></pre>
<p>I wonder should we just be careful to floor/ceil numbers?</p>
<hr />
<p>ps.</p>
<p>Please let me add more idea behind this question.</p>
<p>I was curious about handling the notorious(?) 0.1 + 0.2 issue (<a href="https://0.30000000000000004.com/" rel="nofollow noreferrer">https://0.30000000000000004.com/</a>) in IEE754 double precision floating point number.</p>
<p>Because ceiling/flooring/rounding need to convert binary to decimal, some numbers can be a infinite decimal. and I thought decimal type should have the same case which can be a infinite decimal. So, I was wonder how decimal deals with this flooring.</p>
<p>I was originally wondered if there is some safe way to ceil/floor/round after some arbitrary calculation, where 1 was significant.</p>
| <python><numbers><decimal> | 2023-07-23 00:39:25 | 1 | 1,131 | Kennyhyun |
76,746,196 | 2,725,810 | Getting user information from id_token | <p>I used <code>chrome.identity.launchWebAuthFlow</code> in the frontend to get a Google OAuth2 <code>id_token</code>. I am trying to use this token to obtain user information in the Django backend. As an experiment, I hardcoded the freshly obtained <code>id_token</code> and verified it:</p>
<pre class="lang-py prettyprint-override"><code>from google.oauth2 import id_token
from google.auth.transport import requests
MY_APP_CLIENT_ID = 'xxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com'
token = 'a very long id_token'
idinfo = id_token.verify_oauth2_token(token, requests.Request(), MY_APP_CLIENT_ID)
print(idinfo.keys())
</code></pre>
<p>Here is the output:</p>
<pre><code>dict_keys(['iss', 'azp', 'aud', 'sub', 'at_hash', 'c_hash', 'nbf', 'iat', 'exp', 'jti'])
</code></pre>
<p>So, <code>idinfo</code> does not have the name of the user and his email. What am I missing? How do I obtain those?</p>
<p><strong>EDIT</strong> After adding the <code>email</code> and <code>profile</code> scopes in both the manifest file for my extension and the dictionary passed to <code>chrome.identity.launchWebAuthFlow</code>, I do get the email address, but still no first or last name of the user.</p>
| <python><oauth-2.0><google-oauth><google-api-python-client> | 2023-07-23 00:02:02 | 2 | 8,211 | AlwaysLearning |
76,746,158 | 5,224,236 | pyspark connecting to an already existing session | <p>On the command line I successfully launch pyspark using <code>pyspark</code>
<a href="https://i.sstatic.net/7JvNR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7JvNR.png" alt="enter image description here" /></a></p>
<p>I suppose that there's now a standalone cluster running locally.
Now I'm trying to connect to this spark session / cluster in my IDE. The problem is that it returns another app id, so I suppose that it has created another cluster / session. How can I use only one cluster from both the shell and my IDE?</p>
<pre><code># connecting to spark interactive
import pyspark
spark = pyspark.sql.SparkSession.builder.master("local").getOrCreate()
spark.sparkContext.applicationId
'local-1690068681515'
</code></pre>
| <python><apache-spark><pyspark> | 2023-07-22 23:40:09 | 1 | 6,028 | gaut |
76,745,962 | 6,628,488 | Why is "pcost" or "dcost" increasing in the minimization problem when using cvxpy? | <p>I have an optimization problem which I modeled using the <code>cvxpy</code> library. However, when I run the <code>solve</code> method, I notice that the cost value increases after each iteration, even though the problem is defined as a minimization problem.</p>
<p>Let's consider the following example from the <a href="https://www.cvxpy.org/tutorial/advanced/index.html#viewing-solver-output" rel="nofollow noreferrer">cvxpy</a> documentation itself:</p>
<pre><code>import cvxpy
x = cvxpy.Variable(2)
objective = cvxpy.Minimize(x[0] + cvxpy.norm(x, 1))
constraints = [x >= 2]
problem = cvxpy.Problem(objective, constraints)
problem.solve(solver=cvxpy.ECOS, verbose=True)
print("Optimal value:", problem.value)
print("Object value:", objective.value)
</code></pre>
<p>And here is the result:</p>
<pre><code>ECOS 2.0.10 - (C) embotech GmbH, Zurich Switzerland, 2012-15. Web: www.embotech.com/ECOS
It pcost dcost gap pres dres k/t mu step sigma IR | BT
0 +6.667e-01 +7.067e-01 +6e+00 6e-01 1e-02 1e+00 9e-01 --- --- 1 1 - | - -
1 +3.500e+00 +3.925e+00 +1e+00 3e-01 4e-03 8e-01 2e-01 0.9890 2e-01 1 1 1 | 0 0
2 +5.716e+00 +5.825e+00 +2e-01 6e-02 8e-04 2e-01 4e-02 0.9091 8e-02 1 1 1 | 0 0
3 +5.997e+00 +5.998e+00 +3e-03 7e-04 1e-05 2e-03 5e-04 0.9881 1e-04 1 1 1 | 0 0
4 +6.000e+00 +6.000e+00 +3e-05 8e-06 1e-07 3e-05 5e-06 0.9890 1e-04 1 1 1 | 0 0
5 +6.000e+00 +6.000e+00 +3e-07 9e-08 1e-09 3e-07 6e-08 0.9890 1e-04 1 0 0 | 0 0
6 +6.000e+00 +6.000e+00 +4e-09 1e-09 1e-11 3e-09 6e-10 0.9890 1e-04 1 0 0 | 0 0
OPTIMAL (within feastol=9.9e-10, reltol=6.2e-10, abstol=3.7e-09).
Runtime: 0.000061 seconds.
Optimal value: 5.999999996660147
Object value: 5.999999996660147
</code></pre>
<p>Do I have a wrong understanding of the value of <code>pcost</code>?</p>
| <python><cvxpy><convex-optimization> | 2023-07-22 22:10:21 | 1 | 1,284 | Alireza Roshanzamir |
76,745,715 | 5,573,074 | Elasticsearch Docker container cannot Snapshot to Google Cloud Storage (GCS) | <p>This simple task is starkly difficult to debug using the resources online. Let me explain the use case, then the three lines of code that are expected to perform the task; then the errors, and the permissions conflicts that appear to be innate to the problem. Please advise.</p>
<p><strong>Use Case:</strong></p>
<p>Elasticsearch provides one of the few competitors to Google Cloud Search and Google Search. Elasticsearch is the managed service stack build on top of open-source Solr.</p>
<p>Elasticsearch creates backups of its index, called Snapshots. Elasticsearch manages an internal infrastructure using Google Cloud Services and its standard Service Account permissions files to create a feature for these Snapshots to be uploaded to and downloaded from a Google Storage bucket, instead of the machine running the ElasticSearch server. These internal GCS services are managed by adding a Service Account json file through the <code>bin/elasticsearch-keystore add-file</code> mechanism and registering the expectation using the <code>PUT _snapshot/BACKUP_NAME/</code> mechanism. Then, Snapshots are created or restored using a similar series of <code>PUT</code> and <code>GET</code> calls to the ElasticSearch server.</p>
<p>Elasticsearch conveniently hosts a Docker container so that the entire installation and launch service can be containerized: <code>docker.elastic.co/elasticsearch/elasticsearch:8.8.2</code></p>
<p>This tutorial describes the process, with appropriate links to official Elasticsearch pages, despite being from 2019:
<a href="https://medium.com/@KarakasP/saving-elasticsearch-backups-into-google-cloud-storage-d230ab12a7e7" rel="nofollow noreferrer">https://medium.com/@KarakasP/saving-elasticsearch-backups-into-google-cloud-storage-d230ab12a7e7</a></p>
<p>The process takes four lines of code. The docker container is running on my local laptop, and my Service Account has been used for making Google Storage client calls using my own stack of Google client calls in other applications. The problem is in location appropriate documentation of the workflow from Elasticsearch necessary to launch this feature for software developers.</p>
<p><strong>Problem</strong></p>
<p>Attempting to build that workflow creates a read-permissions error <code>"java.security.AccessControlException","error.message":"access denied \"java.io.FilePermission\"</code> for a specific file, <code>usr/share/elasticsearch/.config/gcloud/active_config</code>. This file does not exist within the Docker container: however, creating this file does not resolve the error. Neither does setting the internal filesystem permissions to <code>chmod 1777</code>. The source of this error is the <code>java.security.FilePermission</code> permission structure of the Java system running Elasticsearch inside the Docker container. Strangely, very, very few forums or search results appear on Google which identify this problem or walk the user through a straightforward solution: that is the over-arching purpose of this ticket as we solve this relatively simple, ground-foundation Elasticsearch troubleshooting. A few forums from years ago mention that user control over <code>java.security</code> has been disabled from Elasticsearch 5.0 forward, which leaves me confused and at a loss for moving ahead. I suspect the problem is one or two lines of configuration file added after the Docker is launched.</p>
<p><strong>Logs</strong></p>
<pre><code>{"@timestamp":"2023-07-22T17:41:34.353Z", "log.level": "INFO", "message":"put repository [cheese7]", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[05b6814dda47][masterService#updateTask][T#1]","log.logger":"org.elasticsearch.repositories.RepositoriesService","elasticsearch.cluster.uuid":"034Ez40kSKiiocCGr8Gw3A","elasticsearch.node.id":"toF_prk7Thm3JYGtsBDBPw","elasticsearch.node.name":"05b6814dda47","elasticsearch.cluster.name":"docker-cluster"}
{"@timestamp":"2023-07-22T17:41:34.464Z", "log.level": "WARN", "message":"failed to load default project id", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[05b6814dda47][snapshot][T#1]","log.logger":"org.elasticsearch.repositories.gcs.GoogleCloudStorageService","elasticsearch.cluster.uuid":"034Ez40kSKiiocCGr8Gw3A","elasticsearch.node.id":"toF_prk7Thm3JYGtsBDBPw","elasticsearch.node.name":"05b6814dda47","elasticsearch.cluster.name":"docker-cluster","error.type":"java.security.AccessControlException","error.message":"access denied (\"java.io.FilePermission\" \"/usr/share/elasticsearch/.config/gcloud/active_config\" \"read\")","error.stack_trace":"java.security.AccessControlException: access denied (\"java.io.FilePermission\" \"/usr/share/elasticsearch/.config/gcloud/active_config\" \"read\")\n\tat java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:488)\n\tat java.base/java.security.AccessController.checkPermission(AccessController.java:1071)\n\tat java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:411)\n\tat java.base/java.lang.SecurityManager.checkRead(SecurityManager.java:742)\n\tat java.base/java.io.FileInputStream.<init>(FileInputStream.java:147)\n\tat com.google.common.io.Files$FileByteSource.openStream(Files.java:132)\n\tat com.google.common.io.Files$FileByteSource.openStream(Files.java:122)\n\tat com.google.common.io.ByteSource$AsCharSource.openStream(ByteSource.java:474)\n\tat com.google.common.io.CharSource.openBufferedStream(CharSource.java:126)\n\tat com.google.common.io.CharSource.readFirstLine(CharSource.java:316)\n\tat com.google.cloud.ServiceOptions.getActiveGoogleCloudConfig(ServiceOptions.java:396)\n\tat com.google.cloud.ServiceOptions.getGoogleCloudProjectId(ServiceOptions.java:413)\n\tat com.google.cloud.ServiceOptions.getDefaultProjectId(ServiceOptions.java:384)\n\tat java.base/java.security.AccessController.doPrivileged(AccessController.java:571)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.doPrivilegedIOException(SocketAccess.java:33)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createStorageOptions(GoogleCloudStorageService.java:196)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createClient(GoogleCloudStorageService.java:172)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.client(GoogleCloudStorageService.java:112)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.client(GoogleCloudStorageBlobStore.java:125)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.lambda$writeBlobMultipart$8(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.lambda$doPrivilegedVoidIOException$0(SocketAccess.java:43)\n\tat java.base/java.security.AccessController.doPrivileged(AccessController.java:571)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.doPrivilegedVoidIOException(SocketAccess.java:42)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlobMultipart(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlob(GoogleCloudStorageBlobStore.java:264)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlob(GoogleCloudStorageBlobContainer.java:80)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlobAtomic(GoogleCloudStorageBlobContainer.java:95)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.blobstore.BlobStoreRepository.startVerification(BlobStoreRepository.java:1707)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.RepositoriesService$4.doRun(RepositoriesService.java:481)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingAbstractRunnable.doRun(ThreadContext.java:983)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)\n\tat java.base/java.lang.Thread.run(Thread.java:1623)\n"}
{"@timestamp":"2023-07-22T17:41:34.466Z", "log.level": "WARN", "message":"failed to load default project id fallback", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[05b6814dda47][snapshot][T#1]","log.logger":"org.elasticsearch.repositories.gcs.GoogleCloudStorageService","elasticsearch.cluster.uuid":"034Ez40kSKiiocCGr8Gw3A","elasticsearch.node.id":"toF_prk7Thm3JYGtsBDBPw","elasticsearch.node.name":"05b6814dda47","elasticsearch.cluster.name":"docker-cluster","error.type":"java.net.UnknownHostException","error.message":"metadata.google.internal","error.stack_trace":"java.net.UnknownHostException: metadata.google.internal\n\tat java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:560)\n\tat java.base/java.net.Socket.connect(Socket.java:666)\n\tat java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:178)\n\tat java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:532)\n\tat java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:637)\n\tat java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:280)\n\tat java.base/sun.net.www.http.HttpClient.New(HttpClient.java:385)\n\tat java.base/sun.net.www.http.HttpClient.New(HttpClient.java:407)\n\tat java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1308)\n\tat java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1241)\n\tat java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1127)\n\tat java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1056)\n\tat java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1657)\n\tat java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1581)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.getDefaultProjectId(GoogleCloudStorageService.java:252)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.lambda$createStorageOptions$4(GoogleCloudStorageService.java:208)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.lambda$doPrivilegedVoidIOException$0(SocketAccess.java:43)\n\tat java.base/java.security.AccessController.doPrivileged(AccessController.java:571)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.doPrivilegedVoidIOException(SocketAccess.java:42)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createStorageOptions(GoogleCloudStorageService.java:207)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createClient(GoogleCloudStorageService.java:172)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.client(GoogleCloudStorageService.java:112)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.client(GoogleCloudStorageBlobStore.java:125)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.lambda$writeBlobMultipart$8(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.lambda$doPrivilegedVoidIOException$0(SocketAccess.java:43)\n\tat java.base/java.security.AccessController.doPrivileged(AccessController.java:571)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.doPrivilegedVoidIOException(SocketAccess.java:42)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlobMultipart(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlob(GoogleCloudStorageBlobStore.java:264)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlob(GoogleCloudStorageBlobContainer.java:80)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlobAtomic(GoogleCloudStorageBlobContainer.java:95)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.blobstore.BlobStoreRepository.startVerification(BlobStoreRepository.java:1707)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.RepositoriesService$4.doRun(RepositoriesService.java:481)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingAbstractRunnable.doRun(ThreadContext.java:983)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)\n\tat java.base/java.lang.Thread.run(Thread.java:1623)\n"}
{"@timestamp":"2023-07-22T17:41:34.477Z", "log.level": "WARN", "message":"failed to load Application Default Credentials", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[05b6814dda47][snapshot][T#1]","log.logger":"org.elasticsearch.repositories.gcs.GoogleCloudStorageService","elasticsearch.cluster.uuid":"034Ez40kSKiiocCGr8Gw3A","elasticsearch.node.id":"toF_prk7Thm3JYGtsBDBPw","elasticsearch.node.name":"05b6814dda47","elasticsearch.cluster.name":"docker-cluster","error.type":"java.io.IOException","error.message":"The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.","error.stack_trace":"java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.\n\tat com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:134)\n\tat com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:125)\n\tat com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:97)\n\tat java.base/java.security.AccessController.doPrivileged(AccessController.java:571)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.doPrivilegedIOException(SocketAccess.java:33)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createStorageOptions(GoogleCloudStorageService.java:220)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createClient(GoogleCloudStorageService.java:172)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.client(GoogleCloudStorageService.java:112)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.client(GoogleCloudStorageBlobStore.java:125)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.lambda$writeBlobMultipart$8(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.lambda$doPrivilegedVoidIOException$0(SocketAccess.java:43)\n\tat java.base/java.security.AccessController.doPrivileged(AccessController.java:571)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.doPrivilegedVoidIOException(SocketAccess.java:42)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlobMultipart(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlob(GoogleCloudStorageBlobStore.java:264)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlob(GoogleCloudStorageBlobContainer.java:80)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlobAtomic(GoogleCloudStorageBlobContainer.java:95)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.blobstore.BlobStoreRepository.startVerification(BlobStoreRepository.java:1707)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.RepositoriesService$4.doRun(RepositoriesService.java:481)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingAbstractRunnable.doRun(ThreadContext.java:983)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)\n\tat java.base/java.lang.Thread.run(Thread.java:1623)\n"}
{"@timestamp":"2023-07-22T17:41:34.479Z", "log.level": "WARN", "message":"path: /_snapshot/cheese7, params: {repository=cheese7}", "ecs.version": "1.2.0","service.name":"ES_ECS","event.dataset":"elasticsearch.server","process.thread.name":"elasticsearch[05b6814dda47][snapshot][T#1]","log.logger":"rest.suppressed","elasticsearch.cluster.uuid":"034Ez40kSKiiocCGr8Gw3A","elasticsearch.node.id":"toF_prk7Thm3JYGtsBDBPw","elasticsearch.node.name":"05b6814dda47","elasticsearch.cluster.name":"docker-cluster","error.type":"org.elasticsearch.repositories.RepositoryVerificationException","error.message":"[cheese7] path is not accessible on master node","error.stack_trace":"org.elasticsearch.repositories.RepositoryVerificationException: [cheese7] path is not accessible on master node\nCaused by: java.security.AccessControlException: access denied (\"java.io.FilePermission\" \"/usr/share/elasticsearch/.config/gcloud/active_config\" \"read\")\n\tat java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:488)\n\tat java.base/java.security.AccessController.checkPermission(AccessController.java:1071)\n\tat java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:411)\n\tat java.base/java.lang.SecurityManager.checkRead(SecurityManager.java:742)\n\tat java.base/java.io.FileInputStream.<init>(FileInputStream.java:147)\n\tat com.google.common.io.Files$FileByteSource.openStream(Files.java:132)\n\tat com.google.common.io.Files$FileByteSource.openStream(Files.java:122)\n\tat com.google.common.io.ByteSource$AsCharSource.openStream(ByteSource.java:474)\n\tat com.google.common.io.CharSource.openBufferedStream(CharSource.java:126)\n\tat com.google.common.io.CharSource.readFirstLine(CharSource.java:316)\n\tat com.google.cloud.ServiceOptions.getActiveGoogleCloudConfig(ServiceOptions.java:396)\n\tat com.google.cloud.ServiceOptions.getGoogleCloudProjectId(ServiceOptions.java:413)\n\tat com.google.cloud.ServiceOptions.getDefaultProjectId(ServiceOptions.java:384)\n\tat com.google.cloud.ServiceOptions.getDefaultProject(ServiceOptions.java:356)\n\tat com.google.cloud.ServiceOptions.<init>(ServiceOptions.java:302)\n\tat com.google.cloud.storage.StorageOptions.<init>(StorageOptions.java:117)\n\tat com.google.cloud.storage.StorageOptions.<init>(StorageOptions.java:34)\n\tat com.google.cloud.storage.StorageOptions$Builder.build(StorageOptions.java:112)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createStorageOptions(GoogleCloudStorageService.java:235)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.createClient(GoogleCloudStorageService.java:172)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageService.client(GoogleCloudStorageService.java:112)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.client(GoogleCloudStorageBlobStore.java:125)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.lambda$writeBlobMultipart$8(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.lambda$doPrivilegedVoidIOException$0(SocketAccess.java:43)\n\tat java.base/java.security.AccessController.doPrivileged(AccessController.java:571)\n\tat org.elasticsearch.repositories.gcs.SocketAccess.doPrivilegedVoidIOException(SocketAccess.java:42)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlobMultipart(GoogleCloudStorageBlobStore.java:474)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobStore.writeBlob(GoogleCloudStorageBlobStore.java:264)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlob(GoogleCloudStorageBlobContainer.java:80)\n\tat org.elasticsearch.repositories.gcs.GoogleCloudStorageBlobContainer.writeBlobAtomic(GoogleCloudStorageBlobContainer.java:95)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.blobstore.BlobStoreRepository.startVerification(BlobStoreRepository.java:1707)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.repositories.RepositoriesService$4.doRun(RepositoriesService.java:481)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.ThreadContext$ContextPreservingAbstractRunnable.doRun(ThreadContext.java:983)\n\tat org.elasticsearch.server@8.8.2/org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:26)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)\n\tat java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)\n\tat java.base/java.lang.Thread.run(Thread.java:1623)\n"}
</code></pre>
<p>I have specifically reverted to earlier attempts to provide the most detailed error logs.
There are solution attempts that I have tried that solve some of the problems, but that seem to be non-essential once the solution itself is determined. These include adding the <code>project id</code> specifically in the <code>PUT _snapshot/BACKUP_NAME/</code> call. Attempts to put the Credential Files data directly in that call, which worked for some users in the past, do not work wither. I suspect the error is a very simple permissions problem I mistook along the way.</p>
<p><strong>References</strong></p>
<ol>
<li>This walks through the specific steps taken. The current version of Docker already installs the GCS plug-in as a standard package, though I have tried with and without installation. Strangely, instructions to restart the Elasticsearch service without restarting the Docker container are also absent, and could help the user building search.
<a href="https://medium.com/@KarakasP/saving-elasticsearch-backups-into-google-cloud-storage-d230ab12a7e7" rel="nofollow noreferrer">https://medium.com/@KarakasP/saving-elasticsearch-backups-into-google-cloud-storage-d230ab12a7e7</a></li>
<li>This issue discusses the same core problem; though this users is able to embed the Credential File information directly in the <code>PUT</code> request. This did not work for me, and this is a non-standard, not-secure approach.
<a href="https://github.com/elastic/elasticsearch/issues/65451" rel="nofollow noreferrer">https://github.com/elastic/elasticsearch/issues/65451</a></li>
<li>This discusses the general problem of Java security and file reading in Elasticsearch.
<a href="https://stackoverflow.com/questions/35401917/reading-a-file-in-an-elasticsearch-plugin">Reading a file in an Elasticsearch plugin</a></li>
<li>This addresses how updated Elasticsearch 5.0+ services are not allowed to access local files. This seems to imply that the <code>keystore</code> mechanism is supposed to read the local file and integrate its contents directly into the Elasticsearch keystore. Diagnosing this confirms that the keystore is aware of the file. It may be that I made an error in this step.
<a href="https://github.com/elastic/elasticsearch/issues/69464" rel="nofollow noreferrer">https://github.com/elastic/elasticsearch/issues/69464</a></li>
</ol>
<p><strong>My Build</strong></p>
<p>This is the docker run command:
<code>docker run --rm -p 9200:9200 -p 9300:9300 -e "xpack.security.enabled=false" -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:8.8.2</code></p>
<p>This is the sequence of client calls being made (commands are displayed in my logs):</p>
<pre><code>INFO:elasticsearch:GET http://localhost:9200/ [status:200 request:0.002s]
INFO:__main__:Cluster connection information: {'name': '69a39f48d8da', 'cluster_name': 'docker-cluster', 'cluster_uuid': 'd4c_Vr9wQdapS99Tozhwhw', 'version': {'number': '8.8.2', 'build_flavor': 'default', 'build_type': 'docker', 'build_hash': '98e1271edf932a480e4262a471281f1ee295ce6b', 'build_date': '2023-06-26T05:16:16.196344851Z', 'build_snapshot': False, 'lucene_version': '9.6.0', 'minimum_wire_compatibility_version': '7.17.0', 'minimum_index_compatibility_version': '7.0.0'}, 'tagline': 'You Know, for Search'}
INFO:elasticsearch:GET http://localhost:9200/_cluster/health [status:200 request:0.012s]
INFO:__main__:Cluster health: {'cluster_name': 'docker-cluster', 'status': 'green', 'timed_out': False, 'number_of_nodes': 1, 'number_of_data_nodes': 1, 'active_primary_shards': 0, 'active_shards': 0, 'relocating_shards': 0, 'initializing_shards': 0, 'unassigned_shards': 0, 'delayed_unassigned_shards': 0, 'number_of_pending_tasks': 0, 'number_of_in_flight_fetch': 0, 'task_max_waiting_in_queue_millis': 0, 'active_shards_percent_as_number': 100.0}
INFO:base.core.lightweight_utilities.process:Executing CMD shell OFF: docker cp base/_db/credentials/BASENAME_REMOVED.json 69a39f48d8da:/usr/share/elasticsearch/BASENAME_REMOVED.json
INFO:base.core.lightweight_utilities.process:Executing CMD complete: 0.033 seconds.
INFO:base.core.lightweight_utilities.process:Executing CMD shell OFF: docker exec -t 69a39f48d8da bin/elasticsearch-keystore add-file --force gcs.client.default.credentials_file /usr/share/elasticsearch/BASENAME_REMOVED.json
INFO:base.core.lightweight_utilities.process:Executing CMD complete: 0.753 seconds.
INFO:base.core.lightweight_utilities.process:Executing CMD shell OFF: docker exec -t 69a39f48d8da bin/elasticsearch-plugin install repository-gcs
INFO:base.core.lightweight_utilities.process:Executing CMD complete: 0.589 seconds.
WARNING:elasticsearch:PUT http://localhost:9200/_snapshot/cheese7 [status:500 request:0.213s]
Traceback (most recent call last):
File "/Users/USERNAME_REMOVED/miniconda3/envs/ML/lib/python3.10/site-packages/elasticsearch/transport.py", line 466, in perform_request
raise e
File "/Users/USERNAME_REMOVED/miniconda3/envs/ML/lib/python3.10/site-packages/elasticsearch/transport.py", line 427, in perform_request
status, headers_response, data = connection.perform_request(
File "/Users/USERNAME_REMOVED/miniconda3/envs/ML/lib/python3.10/site-packages/elasticsearch/connection/http_urllib3.py", line 291, in perform_request
self._raise_error(response.status, raw_data)
File "/Users/USERNAME_REMOVED/miniconda3/envs/ML/lib/python3.10/site-packages/elasticsearch/connection/base.py", line 328, in _raise_error
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(
elasticsearch.exceptions.TransportError: TransportError(500, 'repository_verification_exception', '[cheese7] path is not accessible on master node')
</code></pre>
| <python><docker><elasticsearch><search><google-cloud-storage> | 2023-07-22 20:41:29 | 1 | 362 | David Bernat |
76,745,504 | 15,341,457 | Python - Check progress of dictionary creation | <p>I'm creating a dictionary this way:</p>
<pre><code>num_states = 26565000
num_actions = 7
self.P = {
state: {action: [] for action in range(num_actions)}
for state in range(num_states)
}
</code></pre>
<p>It's taking quite a bit and I would like to insert <code>print(state)</code> to check the progress of the creation. I'm not sure where to put it.</p>
<p>EDIT:</p>
<p>I need this dictionary beacause I need to involve the whole observation space for an agent I'm trying with reinforcement learning</p>
<p>EDIT.2:</p>
<p>I usually use the regular for loops:</p>
<pre><code>for state in range(num_states)
print(state)
for action in range(num_actions)
...
</code></pre>
<p>I'm not sure how to achieve the same result using this way of coding a for loop.</p>
| <python><dictionary><for-loop><time><execution> | 2023-07-22 19:40:30 | 2 | 332 | Rodolfo |
76,745,468 | 2,680,053 | Sympy won't evaluate equation without free variables | <p>I have an equation of one variable that I'd like to evaluate at a given value of that variable, but after calling <code>.subs(...)</code> and getting an equation of zero free symbols, sympy refuses to simplify it to a number. However, if I convert it to a string (as I tried in order to post this question) and then convert it back using <code>sympy.sympify</code>, the expression evaluates just fine. Where could I be going wrong?</p>
<p><code>equation.subs('F', 5)</code> gives me the equation back with F replaced by 5. This does not simplify to a number, even though I believe it should because it has no free symbols.</p>
<p><code>equation.subs('F', 5).free_symbols</code> is the empty set</p>
<p><code>sympy.sympify(str(equation)).subs('F', 5)</code> gives me a number as a result</p>
<p>Here is the result of <code>str(equation)</code>: <code>'(384.905148220275*(0.170386609849201*F - 1)**2 - 1.00032489968052e-5)**2.6312329349372*0.131712523957535 - (3.34281484313696*F - 19.6189996743023 + 2.55848312109802)**(-1)*0.791887145750515'</code></p>
| <python><sympy> | 2023-07-22 19:26:36 | 1 | 1,548 | Marc Bacvanski |
76,745,347 | 2,829,961 | How to make quarto use the same python environment that was specified in RStudio global options? | <p>I have a virtual environment python interpreter selected in RStudio as shown here:</p>
<p><a href="https://i.sstatic.net/UVog1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/UVog1.png" alt="enter image description here" /></a></p>
<p>But when I use a <code>python</code> chunk in quarto, I see that the base environment is being used (the output was rendered by quarto):</p>
<pre><code>```{python}
import sys
print(sys.executable)
```
C:/Users/USERNAME/anaconda3/python.exe
</code></pre>
<p>How can I make quarto use the <code>homl3</code> environment as specified in RStudio global options?</p>
| <python><rstudio><quarto> | 2023-07-22 18:52:57 | 1 | 6,319 | umair durrani |
76,745,306 | 15,233,792 | docker build exactly same requirements.txt & Dockerfile, 4 weeks ago success, but currently failed | <p>Steps to reproduce the failure.</p>
<p>Docker version 24.0.2</p>
<p>Python version in container 3.10.9 see base image</p>
<ol>
<li>requirements.txt</li>
</ol>
<pre><code>pycurl==7.45.1
delta==0.4.2
fiftyone==0.21.0
filetype==1.2.0
Flask==2.2.2
kfp==1.8.19
kfp_pipeline_spec==0.1.16
numpy==1.23.5
pandas==1.5.2
Pillow==9.4.0
pyspark==3.3.2
requests==2.28.1
shortuuid==1.0.11
ultralytics==8.0.109
cvat_sdk==2.4.4
onnxruntime==1.14.1
PyJWT==2.7.0
bcrypt==4.0.1
email-validator==2.0.0.post2
decorator==5.1.1
Flask-Admin==1.5.8
Flask-CAS==1.0.2
Flask-Cors==3.0.10
Flask-JWT-Extended==4.4.4
Flask-Login==0.6.2
flask-mongoengine==1.0.0
Flask-Principal==0.4.0
Flask-PyMongo==2.3.0
Flask-RESTful==0.3.9
Flask-SQLAlchemy==3.0.3
Flask-WTF==1.1.1
SQLAlchemy==1.4.48
SQLAlchemy-Utils==0.41.1
Jinja2==3.0.3
</code></pre>
<ol start="2">
<li>Dockerfile</li>
</ol>
<pre><code>FROM pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime
RUN apt-get update && apt-get install -y curl libcurl4-openssl-dev libssl-dev git gcc ffmpeg libsm6 libxext6 libgl1-mesa-glx wget -y && rm -rf /var/lib/apt/lists/*
RUN mkdir /app
WORKDIR /app
COPY . /app
RUN pip install pip --upgrade && pip install -r requirements.txt
</code></pre>
<ol start="3">
<li><p>command
<code>docker build -t env_test .</code></p>
</li>
<li><p>Error message</p>
</li>
</ol>
<pre><code>#0 33.30 Collecting PyYAML (from fiftyone==0.21.0->-r requirements.txt (line 3))
#0 33.31 Downloading PyYAML-5.4.1.tar.gz (175 kB)
#0 33.33 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 175.1/175.1 kB 15.4 MB/s eta 0:00:00
#0 33.49 Installing build dependencies: started
#0 36.84 Installing build dependencies: finished with status 'done'
#0 36.84 Getting requirements to build wheel: started
#0 37.05 Getting requirements to build wheel: finished with status 'error'
#0 37.06 error: subprocess-exited-with-error
#0 37.06
#0 37.06 × Getting requirements to build wheel did not run successfully.
#0 37.06 │ exit code: 1
#0 37.06 ╰─> [62 lines of output]
#0 37.06 /tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg`
#0 37.06 !!
#0 37.06
#0 37.06 ********************************************************************************
#0 37.06 The license_file parameter is deprecated, use license_files instead.
#0 37.06
#0 37.06 By 2023-Oct-30, you need to update your project and remove deprecated calls
#0 37.06 or your builds will no longer be supported.
#0 37.06
#0 37.06 See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details.
#0 37.06 ********************************************************************************
#0 37.06
#0 37.06 !!
#0 37.06 parsed = self.parsers.get(option_name, lambda x: x)(value)
#0 37.06 running egg_info
#0 37.06 writing lib3/PyYAML.egg-info/PKG-INFO
#0 37.06 writing dependency_links to lib3/PyYAML.egg-info/dependency_links.txt
#0 37.06 writing top-level names to lib3/PyYAML.egg-info/top_level.txt
#0 37.06 Traceback (most recent call last):
#0 37.06 File "/opt/conda/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>
#0 37.06 main()
#0 37.06 File "/opt/conda/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main
#0 37.06 json_out['return_val'] = hook(**hook_input['kwargs'])
#0 37.06 File "/opt/conda/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel
#0 37.06 return hook(config_settings)
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 341, in get_requires_for_build_wheel
#0 37.06 return self._get_build_requires(config_settings, requirements=['wheel'])
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 323, in _get_build_requires
#0 37.06 self.run_setup()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 338, in run_setup
#0 37.06 exec(code, locals())
#0 37.06 File "<string>", line 271, in <module>
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/__init__.py", line 107, in setup
#0 37.06 return distutils.core.setup(**attrs)
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/_distutils/core.py", line 185, in setup
#0 37.06 return run_commands(dist)
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/_distutils/core.py", line 201, in run_commands
#0 37.06 dist.run_commands()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/_distutils/dist.py", line 969, in run_commands
#0 37.06 self.run_command(cmd)
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/dist.py", line 1234, in run_command
#0 37.06 super().run_command(command)
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/_distutils/dist.py", line 988, in run_command
#0 37.06 cmd_obj.run()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/command/egg_info.py", line 314, in run
#0 37.06 self.find_sources()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/command/egg_info.py", line 322, in find_sources
#0 37.06 mm.run()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/command/egg_info.py", line 551, in run
#0 37.06 self.add_defaults()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/command/egg_info.py", line 589, in add_defaults
#0 37.06 sdist.add_defaults(self)
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/command/sdist.py", line 104, in add_defaults
#0 37.06 super().add_defaults()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/_distutils/command/sdist.py", line 251, in add_defaults
#0 37.06 self._add_defaults_ext()
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/_distutils/command/sdist.py", line 336, in _add_defaults_ext
#0 37.06 self.filelist.extend(build_ext.get_source_files())
#0 37.06 File "<string>", line 201, in get_source_files
#0 37.06 File "/tmp/pip-build-env-xd74p4sc/overlay/lib/python3.10/site-packages/setuptools/_distutils/cmd.py", line 107, in __getattr__
#0 37.06 raise AttributeError(attr)
#0 37.06 AttributeError: cython_sources
#0 37.06 [end of output]
#0 37.06
#0 37.06 note: This error originates from a subprocess, and is likely not a problem with pip.
#0 37.06 error: subprocess-exited-with-error
#0 37.06
#0 37.06 × Getting requirements to build wheel did not run successfully.
#0 37.06 │ exit code: 1
#0 37.06 ╰─> See above for output.
#0 37.06
#0 37.06 note: This error originates from a subprocess, and is likely not a problem with pip.
</code></pre>
<p>I try to specified earch dependecies with exact version number, but there is still errors</p>
<p>It was very weird that 4 weeks ago I successfully build this environment into a docker image with exactly the same codes.</p>
<p>====== After I upgraded PyYAML to 6.0.1, still failes ======</p>
<ol>
<li>add line <code>PyYAML==6.0.1</code> in requirements.txt</li>
<li>run docker build again</li>
<li>Error Message</li>
</ol>
<pre><code>#0 103.8 Collecting absl-py<2,>=0.9 (from kfp==1.8.19->-r requirements.txt (line 7))
#0 103.8 Downloading absl_py-1.4.0-py3-none-any.whl (126 kB)
#0 103.8 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 126.5/126.5 kB 3.1 MB/s eta 0:00:00
#0 103.8 INFO: pip is looking at multiple versions of kfp to determine which version is compatible with other requirements. This could take a while.
#0 103.8 ERROR: Cannot install -r requirements.txt (line 4), -r requirements.txt (line 7) and PyYAML==6.0.1 because these package versions have conflicting dependencies.
#0 103.8
#0 103.8 The conflict is caused by:
#0 103.8 The user requested PyYAML==6.0.1
#0 103.8 fiftyone 0.21.0 depends on PyYAML
#0 103.8 kfp 1.8.19 depends on PyYAML<6 and >=5.3
#0 103.8
#0 103.8 To fix this you could try to:
#0 103.8 1. loosen the range of package versions you've specified
#0 103.8 2. remove package versions to allow pip attempt to solve the dependency conflict
</code></pre>
<ol start="4">
<li>Let me try using <code>PyYAML==5.3.1</code> instead
<strong>Success!!!!!!</strong></li>
</ol>
<p>Because <code>kfp 1.8.19 depends on PyYAML<6 and >=5.3</code> will be an constraint in another place</p>
| <python><docker><pip><dependencies><environment> | 2023-07-22 18:38:19 | 3 | 2,713 | stevezkw |
76,745,216 | 9,878,172 | Python Excel package win32com.client doesn't save the file without throwing any error | <p>I'm trying to run some code in Python that opens some .xlsm file (out2.xlsm) and saves it after inserting VBA code under a new name 'output.xlsm'. So I run the code, it gives no error but when I check the folder, there is no file named 'output.xlsm', so it doesn't actually save it apparently.</p>
<p>I've tried so many things but can't seem to figure this out. What can be the reason? The interesting thing is that I have used exactly the same code for some time and it was working — it was saving the file when I run the code. But now somehow it doesn't save the file, I didn't change anything at all in the code. My suspicion is maybe I change something in the Excel programm, some kind of settings maybe?</p>
<pre><code>excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
excel.DisplayAlerts = False
workbook = excel.Workbooks.Open(Filename=r"C:/Users/nnn/Desktop/project3/out2.xlsm")
excel.Visible = False
excelModule = workbook.VBProject.VBComponents.Add(1)
excelModule.CodeModule.AddFromString(macro)
excel.Application.Run(myMacroName)
excel.Workbooks(1).SaveAs('output.xlsm')
excel.Workbooks(1).Close(SaveChanges=True)
excel.Application.Quit()
del excel
</code></pre>
| <python><excel><win32com> | 2023-07-22 18:15:35 | 1 | 372 | hkm |
76,744,963 | 243,563 | How do I change image on tkinter button, after initial load? | <p>I'm building a UI in Pythons with tkinter. I have a button with an image, and I want to change the image when it is clicked.</p>
<p>The button is simple enough:</p>
<pre><code>self.otherImage = tkinter.PhotoImage(file=os.path.join(self.imagesFolder, "image2.png"))
self.image=tkinter.PhotoImage(file=os.path.join(self.imagesFolder, "image1.png"))
self.button = tkinter.Button(self.mainWindow, image=self.image, command=lambda: [self.clicked()])
</code></pre>
<p>And the clicked function, as well:</p>
<pre><code>def clicked(self):
self.button.image=self.otherImage
</code></pre>
<p>But the image in the GUI never changes. I've tried swapping the images and see the same behavior, either image will display on initial load, neither will load on click.</p>
<p>I feel like I'm missing something simple...</p>
| <python><tkinter> | 2023-07-22 17:07:50 | 2 | 11,790 | Jeff Dege |
76,744,865 | 15,341,457 | Python - Encoding all possible 5-combinations into an integer | <p>I've got a set of 25 integers, ranging from 0 to 24 and my application involves selecting 5 of them (there are no repeated values, no value can be selected more than once) obtaining a combination like this one <strong>[15, 7, 12, 3, 22]</strong>. It's important to consider the the previous combination is considered equal to <strong>[7, 22, 12, 15, 3]</strong>, the order doesn't matter, only the values do.</p>
<p>By applying the binomial coefficient (25 choose 5) we can find out that there are 53.130 possible combinations. I want to encode all the possible combinations into an integer so that all values from 0 to 53129 are linked to a combination.</p>
| <python><encoding><integer><combinations><binomial-coefficients> | 2023-07-22 16:37:41 | 2 | 332 | Rodolfo |
76,744,858 | 19,130,803 | Plotly Dash: dbc.Table not displaying list items properly | <p>I am developing a dashboard using <code>plotly dash</code>. I have a dataframe and some of its items are list of string names.</p>
<pre><code>import pandas as pd
# Dataframe
data = {
"A": [['a', 'm', 'n'], 'b', ['c', 'p', 'q'], 'd'],
"B": [['a', 'm', 'n'], 'b', ['c', 'p', 'q'], 'd'],
}
df = pd.DataFrame(data)
print(df)
# Print DF
A B
0 [a, m, n] [a, m, n]
1 b b
2 [c, p, q] [c, p, q]
3 d d
</code></pre>
<p>In <code>app.py</code>, I have dash application where I am displaying the dataframe using dash bootstrap component <code>Table</code></p>
<pre><code>import dash_bootstrap_components as dbc
from dash import Dash, html
app.layout = html.Div([
dbc.Table.from_dataframe(df)
])
if __name__ == "__main__":
app.run(host="0.0.0.0", port="8001", debug=True)
# On Running output as below
A B
amn amn
b b
cpq cpq
d d
</code></pre>
<p>The data is displayed but Issue is with items having list is not displayed properly as in above output.</p>
<pre><code>Observed Output:
amn
Excepted output
[a, m, n] or
a, m, n
</code></pre>
<p>Why <code>dbc.Table</code> not displaying list items properly. What I am missing?</p>
| <python><plotly-dash> | 2023-07-22 16:36:16 | 0 | 962 | winter |
76,744,796 | 5,113,584 | dateutil: No module named 'dateutil' error when Pandas installing using pipenv | <p>I installed pandas usng</p>
<blockquote>
<p>pipenv install pandas</p>
</blockquote>
<p>command when i run my script getting errors as</p>
<blockquote>
<p>ImportError: Unable to import required dependencies:
dateutil: No module named 'dateutil'</p>
</blockquote>
<p>and checked pipenv graph command and got following</p>
<blockquote>
<p>pandas==2.0.3</p>
</blockquote>
<ul>
<li>numpy [required: >=1.21.0, installed: 1.25.1]</li>
<li>python-dateutil [required: >=2.8.2, installed: ?]</li>
<li>pytz [required: >=2020.1, installed: 2023.3]</li>
<li>tzdata [required: >=2022.1, installed: 2023.3]</li>
</ul>
<p>I tried to install dateutil manually</p>
<blockquote>
<p>pipenv install python-dateutil</p>
</blockquote>
<p>Still issue not solved.Why pipenv failed to install python-dateutil. I seen an closed issue in github <a href="https://github.com/dateutil/dateutil/issues/957" rel="nofollow noreferrer">github issue</a></p>
| <python><pandas><pipenv><python-dateutil><pipenv-install> | 2023-07-22 16:23:45 | 0 | 526 | akhil viswam |
76,744,446 | 13,801,302 | How get I the bin size of plotly.express histogram? | <p>I want to have the bin size of the plotly histogram.
I plot my histogram like this and want to mark the x-axis with the bins size:</p>
<pre><code>fig = px.histogram(df_de["len_job_task"], histnorm='probability density')
bin_edges = fig['data'][0]['xbins']['end']
fig.update_layout(xaxis=dict(tickmode='array', tickvals=bin_edges))
fig.update_traces(marker_line_color='black', marker_line_width=1)
fig.show()
</code></pre>
<p><a href="https://i.sstatic.net/QeGkO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QeGkO.png" alt="enter image description here" /></a></p>
<p>But it doesn't work. I would like it like below with matplotlib - there I set the number of bins and get the bins and set them to the x-axis</p>
<pre><code>n, bins, patches = plt.hist(df_de["len_job_task"], bins=20, edgecolor='black')
plt.xticks(bins[::2])
plt.xlabel("Bins")
plt.ylabel("Length")
</code></pre>
<p><a href="https://i.sstatic.net/6f6rs.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6f6rs.png" alt="enter image description here" /></a></p>
<p>How can do I with plotly?</p>
| <python><histogram><plotly> | 2023-07-22 15:03:34 | 1 | 621 | Christian01 |
76,744,224 | 3,076,544 | Decoding problems with fitz (PyMuPdf) | <p>I have a decoding problem with fitz.Document in Python 3.7.</p>
<p>I'm getting a string of unrecognisable characters when calling <code>getText()</code> on a page of a PDF document.</p>
<p>The code I'm using is</p>
<pre><code>import fitz
pdf_reader = fitz.open(input_file)
# Extract the text from the first page
page_content = pdf_reader[0].get_text("text")
</code></pre>
<p>this is the string I get (with lot's of strange characters - <code>chr(65533)</code>):
<code>'���������������������\nu\nv\n�������������������������������������������������������������������������\n����������������������������������������������������������������������������\n����������������������������������������\ns\nt\nu\nv\ns\nt\n�������������������������\n����������������\n�������������\n������������\n������������������������������\n��������\n����������\n�����\n�\n�������������\n��������������������������� ����������\n�������������������� ���������� ����������\n������������������������������������������������\n����������� ����������\n��������� ����������\n����������������������������\n \n������������\n�\n�������\n������������������������������������������\n�����������������������������\n��������\n�������\n�����\n��������������������������������������\n��������\n�������\n�����\n�����������������������������\n��������\n�������\n�����\n������������������������������\n��������\n������\n�����\n�������������\n��������\n��������\n������������������������������������������\n������������������������\n��������\n�����\n�����\n�������������������������������������������������������������������������������������������������������������������������\n������������������������������������������������������������\n��������������\n�������\n������������\n�����������������������������������������\n������������������\n��������\n�����\n�����\n�������������\n��������\n�������\n�����\n������������������\n�������\n�\n������������������\n��������\n����\n����\n������������������\n������������\n������\n��������\n�������\n�\n���������\n�������\n��������������\n���������\n���������������\n����������������������������������������������\n�������\n���������������������\n��������������������������������������������������������������������������\nEmitido por programa certificado nº 2386/AT. Este documento não serve de fatura.\n'</code>
.</p>
<p>I can open the document without any error in Acrobat Reader and other pdf readers, and I can select the text and copy-paste it.
This is an extract of the copy-paste:</p>
<p><code>Pág.1/3 ¤ ¥ A falta de pagamento ou o pagamento depois do prazo limite, pode implicar custos adicionais e a suspensão do serviço. Pode também originar o pagamento de uma caução ou o agravamento da mesma. ¢ £ ¤ ¥ ¢ £ Modalidades de Pagamento: · Débito Direto · Multibanco · Lojas MEO · Pontos de Venda Autorizados · Cheque · Pay Shop . CTT OS SEUS MEOS: Os seus MEOS em 14/07/2023: 1304 Detalhe da Fatura Nº A795979751 julho 2023 Este documento não é válido para efeitos fiscais Nº Cliente: 1290600729 Nº Conta: 1339848861 Data de Emissão: 14 jul 2023 MENSALIDADES PACOTES Nº Serviço 1702361504 · Vila Nova de Gaia Desconto Mensalidade Camp.Emp jul 2023 - 3,250 23,00 Desconto mensalidade fatura eletrónica jul 2023 - 0,813 23,00 Desconto Mensalidade Camp.Emp jul 2023 - 1,223 23,00 M4 (TV+NET 200+VOZ+MÓVEL 10GB) jul 2023 53,000 23,00 Total Pacotes € 47,714 TELEFONE...</code></p>
<p>What might be the problem or solution?</p>
| <python><macos> | 2023-07-22 14:13:19 | 1 | 993 | MrT77 |
76,744,207 | 1,470,314 | Extract links from a dynamically constructed web page in Python | <p>I am trying to extract specific elements from a dynamically constructed site (Namely <a href="https://www.kingstore.co.il/Food_Law/Main.aspx" rel="nofollow noreferrer">this site</a>). While I am not fluent in web technology, looking at the page source code it appears it is dynamically generated.</p>
<p>Therefore, I understood a web driver such as <a href="https://www.selenium.dev/documentation/" rel="nofollow noreferrer">Selenium</a> would be required to scrape it instead of a simple get request. (Which gets me the code generating this page instead of the actual result I view as a user)</p>
<p>However, it was unclear to me how exactly Selenium should be used for such a case. I saw it allows searching by class, and I saw that the smallest class containing what I required was "table table-bordered table-hover " which had a element, and under it a series of tr elements, each broken into td elements, and that I can get the file name from the button onclick action in those.</p>
<p>I saw that the table I required had a tag of <strong>class="table table-bordered table-hover "</strong>, so naturally I tried to look for it with:</p>
<pre><code>driver.find_element(By.CLASS_NAME, 'table table-bordered table-hover ')
</code></pre>
<p>But I got an exception stating it was not found. Since it does exist, I assume I am misusing the find_element command. What is the right way to use it?</p>
<p>Note - I noticed that in this specific case, I can go to MainIO_Hok.aspx instead and get what I need, but I was wondering how I could have handled it directly from the page I was viewing.</p>
| <python><selenium-webdriver><web-scraping> | 2023-07-22 14:08:10 | 3 | 1,012 | yuvalm2 |
76,744,193 | 19,115,554 | Type hint for attribute that might not exist | <p>How do I do a type hint for attribute that might not exist on the object in Python?</p>
<p>For example:</p>
<pre class="lang-py prettyprint-override"><code>class X:
__slots__ = ('attr',)
attr: int # either int or doesn't exist - what do I put here?
</code></pre>
<p>So, concretely:</p>
<pre class="lang-py prettyprint-override"><code>>>> x = X()
>>> x.attr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'X' object has no attribute 'attr'
>>> x.attr = 1
>>> x.attr
1
</code></pre>
<p>...but there are also cases where <code>__slots__</code> isn't involved.</p>
| <python><attributes><python-typing> | 2023-07-22 14:06:15 | 3 | 602 | MarcellPerger |
76,744,079 | 10,620,003 | Change the rows based on the neighbors rows in dataframe in python | <p>I have a df which only contains 0 and zeros. I wnat to change the df with this way:
I move with a sliding window of 4 through the columns and all rows. for example, the first window is df.iloc[:, 0:4] and if we dont have any 1 in this window,
we dont change anything in this. But if we have 1 in this window, only the rows that has 1 changed to 1. For example, for window 1, id=2 has 1, so for row id=2,
column 0:4 change to 1, and also same for row id=3. I provide a df here, and also the desired output.</p>
<p>I can do this with a loop over the df, however, my df has millions rows and it takes time with my inefficient way.
Can you please help me with that? thanks.</p>
<p>here is the df:</p>
<pre><code>import pandas as pd
df = pd.DataFrame()
df['Ids'] = [1, 2, 3]
df['a1'] = [0, 0, 0]
df['a2'] = [0, 0, 1]
df['a3'] = [0, 1, 1]
df['a4'] = [0, 1, 1]
df['a5'] = [0, 0, 0]
df['a6'] = [0, 0, 1]
df['a7'] = [1, 0, 1]
df['a8'] = [1, 0, 1]
df['a9'] = [0, 0, 0]
df['a10'] = [0, 0, 0]
df['a11'] = [0, 0, 0]
df['a12'] = [0, 0, 0]
</code></pre>
<p>and here is the output:</p>
<pre><code> Ids a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12
0 1 0 0 0 0 1 1 1 1 0 0 0 0
1 2 1 1 1 1 0 0 0 0 0 0 0 0
2 3 1 1 1 1 1 1 1 1 0 0 0 0
</code></pre>
| <python><pandas><dataframe> | 2023-07-22 13:38:43 | 1 | 730 | Sadcow |
76,744,004 | 11,440,563 | python project directory structure | <p>i've been self coding in python for a while now but i never ever could learn how to structure my projects into proper structure. this is what i am doing right now</p>
<pre><code>my_project/
src/
__init__.py
dog.py
animal.py
main.py
</code></pre>
<p>each script looks like this</p>
<pre><code># animal.py
class animal:
def __init__(self, kind):
self.kind = kind
if __name__=='__main__':
a=animal("mammal")
#dog.py
if __name__=='__main__':
from animal import animal
else:
from .animal import animal
class dog(animal):
def __init__(self, name, age):
super().__init__('Mammal')
self.name = name
self.age = age
if __name__=='__main__':
d=dog("Fido", 3)
#__init__.pyt
from .animal import *
from .dog import *
# main.py
import src
d=src.dog("Fido", 3)
</code></pre>
<p>My question is is this an at least ok way of structuring things, the imports in dog.py are extremelly ugly imho and i couldn't find any other way to be able to both run the dog.py itself as part of development below if <strong>name</strong> part and also being able to make this script import things correctly when i run stuff from outside the src/ directory (main.py)</p>
| <python> | 2023-07-22 13:23:20 | 0 | 363 | pawelofficial |
76,743,886 | 10,826,692 | How to vectorize the forward method of this pytorch block? | <p>I am making a novel type of fully connected layer that operates with channels analogously to a 2D convolutional layer. Namely, each output channel is the sum of fully connected layers applied to the input channels. I have a fully working prototype below. But it is slow because of the for loops in the forward method. Theoretically all of these operations can happen in parallel. How can I achieve this? Thank you.</p>
<pre><code># assumes shape of input is (BATCH X channels X feature_dim)
class Channelwise_Linear(nn.Module):
def __init__(self, in_channels, out_channels, in_feature_dim, out_feature_dim, drop_rate):
super(Channelwise_Linear, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.in_feature_dim = in_feature_dim
self.out_feature_dim = out_feature_dim
self.linear_layers = []
self.bn_layers = []
self.activation_layers = []
self.do_layers = []
for out_channel in range(out_channels):
temp_linear = nn.ModuleList()
temp_bn = nn.ModuleList()
temp_AL = nn.ModuleList()
temp_do = nn.ModuleList()
for in_channel in range(in_channels):
temp_linear.append(nn.Linear(in_feature_dim, out_feature_dim))
temp_bn.append(nn.BatchNorm1d(out_feature_dim))
temp_AL.append(nn.LeakyReLU())
temp_do.append(nn.Dropout1d(drop_rate))
self.linear_layers.append(temp_linear)
self.bn_layers.append(temp_bn)
self.activation_layers.append(temp_AL)
self.do_layers.append(temp_do)
def forward(self, x):
x = torch.transpose(x,0,1) # now channel is first
output_list = []
for out_channel in range(self.out_channels):
temp = []
for in_channel in range(self.in_channels):
intermediate = self.linear_layers[out_channel][in_channel](x[in_channel])
intermediate = self.bn_layers[out_channel][in_channel](intermediate)
intermediate = self.activation_layers[out_channel][in_channel](intermediate)
intermediate = self.do_layers[out_channel][in_channel](intermediate)
temp.append(intermediate)
temp = torch.sum(torch.stack(temp), axis=0) # each out_channel is the sum of the output of the nn.Linear(in_channels), like Conv2D
output_list.append(temp)
return torch.transpose(torch.stack(output_list), 0, 1) # switch the batch back to first dim
</code></pre>
| <python><deep-learning><pytorch> | 2023-07-22 12:53:31 | 1 | 363 | Ambrose |
76,743,762 | 2,847,689 | Pass query correctly to the mysql database | <p>I am using <code>Python 3.8.10</code>.</p>
<p>I am trying to update categories in my mysql database:</p>
<pre><code>def update_categories(automaton, df, engine):
logging.info("Starting category update process...")
update_list = []
start_time = time.time()
# tqdm is used for showing progress bar
for index, row in tqdm(df.iterrows(), total=df.shape[0]):
matches = list(automaton.iter(row['prompt'].lower()))
if matches:
categories = json.loads(row['categories']) # Convert string back to list
for match in matches:
_, (keyword, category) = match
if category not in categories:
categories.append(category) # Now you can append to the list
update_list.append((json.dumps(row['categories']), row['id']))
if update_list:
try:
with engine.connect() as conn:
for data in update_list:
query = f"UPDATE prompts SET categories = '{data[0]}' WHERE id = {data[1]};"
conn.execute(query) # <--- HERE I GET THE ERROR
logging.info("Updated categories successfully.")
except SQLAlchemyError as e:
logging.error(f"An error occurred: {e}")
print(e)
end_time = time.time()
time_taken = end_time - start_time
logging.info(f"Category update process completed. Time taken: {time_taken} seconds")
</code></pre>
<p>I get the following error:</p>
<pre><code>ObjectNotExecutableError('Not an executable object: \'UPDATE prompts SET categories = \\\'"[\\\\"fashion\\\\", \\\\"Painting\\\\"]"\\\' WHERE id = 1;\'')
</code></pre>
<p>Executing this query on my database directly works:</p>
<p><code>UPDATE prompts SET categories = "[\"fashion\", \"Painting\"]" WHERE id = 1; </code></p>
<p>I need to pass the above query in my python code onto my database.</p>
<p>Any suggestions how to correctly pass my values to update my database?</p>
<p>I appreciate your replies!</p>
| <python><mysql> | 2023-07-22 12:25:32 | 1 | 5,261 | Carol.Kar |
76,743,645 | 2,293,659 | How to close a session connection properly with SQLAlchemy? | <p>I'm closing the session but the connections are still sleep in MySQL for around one hour. The issue is that I have too many connections sleep after a while. I am using Python3, PyMySQL 1.0.2 and SQLAlchemy 2.0.0 with the following code.</p>
<pre><code>import pymysql.cursors
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
connect_string = f"mysql+pymysql://{db_user}@/{db_name}?unix_socket=/cloudsql/{cloudsql_instance}"
engine = create_engine(connect_string, echo=False, pool_recycle=30,pool_size=20, max_overflow=0)
session = sessionmaker(expire_on_commit=True, autoflush=True, autocommit=False)
session.configure(bind=engine())
session = session()
all_users = session.execute(text('SELECT employee_name FROM users WHERE status='1';')).fetchall()
print(all_users)
session.close()
</code></pre>
| <python><mysql><sqlalchemy> | 2023-07-22 11:50:58 | 1 | 820 | PepeVelez |
76,743,561 | 552,231 | does hugging face model.generate for flan-T5 default is summarization? | <p>Given the following code. why does the function:
model.generate()
returns a summary, where does it order to do summary and not some other task? where can I see the documentation for that as well.</p>
<pre><code>model_name = ‘google/flan-t5-base’
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
dataset_name = “knkarthick/dialogsum”
dataset = load_dataset(dataset_name)
for i in example_indices:
dialog = dataset[‘test’][i][‘dialogue’]
input = tokenizer(dialog,sentence,return_tensors=‘pt’)
ground_truth = dataset[‘test’][i][‘summary’]
model_summary = model.generate(input[‘input_ids’],max_new_tokens=50)
summary = tokenizer.decode(model_summary[0],skip_special_tokens=True)
print(summary)
</code></pre>
| <python><python-3.x><huggingface-transformers><huggingface> | 2023-07-22 11:26:59 | 2 | 1,135 | user552231 |
76,743,410 | 5,832,930 | python tic tac toe finding best move using minimax algorithm | <p>I have build a small python tic tac toe game. There's a list <code>board_list = [0,0,0,0,0,0,0,0,0]</code>. Bot player is assumed to be 1 which is "O" and human player is assumed to be 2 which is "X". Tic tac toe game is working as expected. But I want to improve the bot player to pick the best move using minimax algorithm. I have implemented the algorithm and it's working but it is not picking up the best move.</p>
<pre><code>def minimax(board_list, depth, maximizing):
temp_list = list(board_list)
if is_board_full(temp_list):
return 0
if is_win(temp_list):
return 10 if maximizing else -10
if maximizing:
best_score = float('-inf')
for i in range(len(temp_list)):
if temp_list[i] == 0:
temp_list[i] = 1
score = minimax(temp_list, depth + 1, False)
temp_list[i] = 0
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for i in range(len(temp_list)):
if temp_list[i] == 0:
temp_list[i] = 2
score = minimax(temp_list, depth + 1, True)
temp_list[i] = 0
best_score = min(score, best_score)
return best_score
def find_best_move(board_list):
best_score = float('-inf')
best_move = None
temp_list = list(board_list)
for i in range(len(board_list)):
if temp_list[i] == 0:
temp_list[i] = 1
score = minimax(temp_list, 0, False)
print('score', score)
if score is not None:
if (score > best_score) :
best_move = i
best_score = score
return best_move
current_player = 1
winner = False
while not winner and not is_board_full(board_list):
if current_player == 1:
best_move = find_best_move(board_list)
else:
best_move = int(input("Enter your move (1-9): ")) - 1
board_list[best_move] = current_player
if is_win(board_list):
game_board(board_list)
print("Player", current_player, "wins!")
winner = True
current_player = 2 if current_player == 1 else 1
</code></pre>
<p>scenario is like this :</p>
<ul>
<li>So first bot player (1) choose 0 cell</li>
<li>Then human player choose 3 cell.</li>
<li>Then bot player choose 1 cell.</li>
<li>Then human player choose 2 cell.</li>
<li>Then bot player choose 4 cell.</li>
<li>Then human player select 7 cell.</li>
</ul>
<p>The expected behavior is that bot player should choose 8 cell so it will be a win. But instead it always choose 5 cell.</p>
<p>So it is not picking up the winning move. Can anyone help me solve this</p>
| <python><minimax> | 2023-07-22 10:43:19 | 1 | 523 | Kasun |
76,743,212 | 289,784 | Python rich not formatting markup in custom exception | <p>I'm trying to add formatting in a custom exception with <a href="https://rich.readthedocs.io/en/stable/console.html#printing" rel="nofollow noreferrer"><code>rich</code></a>. The same string when printed as a string works (the carat becomes bold red), but as an exception it doesn't. It's stranger because the <code>foo=123</code> gets highlighted automatically in both situations. What am I missing here?</p>
<pre><code>In [7]: class InvalidSpec(ValueError):
...: def __init__(self, args):
...: loc = args.find("=")
...: hdr = "invalid spec: "
...: self.args = (f"{hdr}{args}\n[red][bold]{' ' * (len(hdr) + loc)}^", )
...:
In [8]: rich.print(InvalidSpec("foo=123").args[0])
invalid spec: foo=123
^
In [9]: rich.print(InvalidSpec("foo=123"))
invalid spec: foo=123
[red][bold] ^
</code></pre>
<p><a href="https://i.sstatic.net/HCHhN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HCHhN.png" alt="enter image description here" /></a></p>
| <python><exception><formatting><richtext><rich> | 2023-07-22 09:46:55 | 1 | 4,704 | suvayu |
76,742,809 | 5,119,402 | How to make `python` run Python 3.11.4 instead of Python 2.7.15 in Command Prompt | <p>I have Python 3.11.4 installed and at the very start of my PATH variable. I also have Python 2.7.15 installed because GIMP depends on it for extensions. I want to use Python 3 instead of Python 2 in Command Prompt, but <code>python -V</code> returns 2.7. Weirdly enough, <code>py</code> boots into the 3.11.4 REPL.</p>
<pre><code>PS C:\Users\Haley> py
Python 3.11.4 (tags/v3.11.4:d2340ef, Jun 7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
KeyboardInterrupt
>>> quit()
PS C:\Users\Haley> python -V
Python 2.7.15
</code></pre>
<p>How can I reconfigure my Command Prompt or Windows install to use Python 3.11.4 all across the board?</p>
| <python><windows><command-prompt> | 2023-07-22 07:49:55 | 0 | 909 | haley |
76,742,806 | 5,731,101 | ExactOnline all sales prices for given price-list | <p>I'm building a margin-monitor for exact-online, for this I need to fetch all of the products, sales price and sales prices for a specific price-list.</p>
<p>So far I've managed to get the products and default sales prices via the REST-API. However, getting all the relevant prices for a given price-list still eludes me.</p>
<p>In the frontend, you seem to go to sales -> Price management -> Price lists -> Click the price list -> click the amount of items</p>
<p>This sequence seems to give me a list of items with the pricing I'm looking for.</p>
<p><a href="https://i.sstatic.net/xI2lt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xI2lt.png" alt="Screenshot of data needed" /></a></p>
<p>However on the API side, I can't seem to make heads or tails from this structure.</p>
<p>Suggesting from the title of the screenshot, I need to get <code>/api/v1/{division}/sales/SalesPriceListPeriods</code>. Yet this just returns the periods of the price lists.</p>
<p><code>/api/v1/{division}/sales/SalesPriceLists</code> returns the actual price-lists. Ok, that's clear enough.</p>
<p>But what endpoint do I call, and how to receive the actual price for the given price lists?</p>
| <python><rest><exact-online> | 2023-07-22 07:49:27 | 2 | 2,971 | S.D. |
76,742,805 | 5,790,653 | How to grep regex in python with -1 index | <p>This is my python code:</p>
<pre><code>import re
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from datetime import datetime
with open('all.txt', 'r') as names_file:
with open('email.yaml', 'r') as emails_file:
names = names_file.readlines()
emails = emails_file.readlines()
for name in names:
name = name.strip()
for i, email in enumerate(emails):
email = re.sub('-', '', email)
email = re.sub(' ', '', email)
if re.search(name, email):
prev_email = emails[i-1].strip()
prev_email = re.sub('-', '', prev_email)
prev_email = re.sub(' ', '', prev_email)
html = html.format(name=name)
print(f"Name: {name}, Email: {prev_email}")
break
</code></pre>
<p>This is <code>all.txt</code>:</p>
<pre><code>1.1.1.1
1.1.1.12
1.1.1.11
</code></pre>
<p>This is <code>email.yaml</code>:</p>
<pre><code> - emailA@gmail.com
- 1.1.1.12
- emailB@gmail.com
- 1.1.1.1
- emailC@gmail.com
- 1.1.1.11
</code></pre>
<p>When I run <code>python3 file.py</code>, this is the output:</p>
<pre><code>Name: 1.1.1.1, Email: emailA@gmail.com
</code></pre>
<p>The issue is because <code>1.1.1.1</code> consist <code>1.1.1.1*</code>, then all reports are wrong for such IPs.</p>
<p>Expected output:</p>
<pre><code>Name: 1.1.1.1, Email: emailB@gmail.com
Name: 1.1.1.12, Email: emailA@gmail.com
Name: 1.1.1.11, Email: emailC@gmail.com
</code></pre>
<p>How can I fix this?</p>
| <python> | 2023-07-22 07:49:19 | 1 | 4,175 | Saeed |
76,742,054 | 770,535 | Setting values through result of DataFrame.loc saved in variable | <p>Is there a way to set values through the result of <code>DataFrame.loc</code>, but after saving it in a variable?</p>
<p>For example, given a DataFrame like this:</p>
<pre><code>df = pd.DataFrame({'x':[1,2,3], 'y':[4,5,6]})
</code></pre>
<p>I can select a subset of <code>y</code> based on the values of <code>x</code> and change their values in one line:</p>
<pre><code>df.loc[df['x'] > 1, 'y'] = 7
</code></pre>
<p>However if I save the result of that <code>loc</code> call in a variable, assignment into the variable simply change the variable, not the <code>Series</code> it points to:</p>
<pre><code>sel = df.loc[df['x'] > 1, 'y']
sel = 9
</code></pre>
<p>Is there a method on <code>Series</code> that performs the same operation as with <code>df.loc[...] = ...</code>?</p>
| <python><pandas><dataframe> | 2023-07-22 02:12:34 | 0 | 987 | Sean |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.