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
77,686,818
5,924,264
How to do a cartesian join of a numpy array and a pandas series?
<p>I have a numpy array <code>ids</code> (unique) and a pandas series <code>dates</code>.</p> <p>I want to create a pandas dataframe that is a cartesian product of <code>ids</code> and <code>dates</code> with columns <code>id</code> and <code>date</code> grouped by date.</p> <p>e.g., <code>ids = [1, 2]</code> and <code>dates = [10032023, 10042023]</code>, with resulting dataframe:</p> <pre><code>id date 1 10032023 2 10032023 1 10042023 2 10042023 </code></pre> <p>I can't seem to figure out how to do this using the existing vectorized operations in pandas. My currently approach is just to iterate over both and assign the rows individually.</p>
<python><pandas><cartesian-product>
2023-12-19 16:59:35
3
2,502
roulette01
77,686,715
1,574,054
How can I get the x coordinate of a ylabel in matplotlib?
<p>I have this example:</p> <pre><code>from numpy import linspace, sin from matplotlib.pyplot import plot, ylabel, gcf, text x = linspace(0, 1) y = x ** 2 plot(x, y) ylabel(&quot;test&quot;) </code></pre> <p>I now want to place some text <em>approximately</em> like &quot;abc&quot; in this figure:</p> <p><a href="https://i.sstatic.net/GOZXK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GOZXK.png" alt="A cut out version of the plot that would be generated by the above code, showing parts of the left y-axix and the y-axis label. The text &quot;abc&quot; is added in red below the y-axis label so that their left margins with respect to the figure coincide." /></a></p> <p>For this, I need the x coordinate of the y-label, or at least approximately. I tried the following:</p> <pre><code>xd, _ = pyplot.gca().yaxis.get_label().get_transform().transform((0, 0)) </code></pre> <p>But it seems that <code>xd</code> is now always 0 in display coordinates. That is clearly not correct. Furthermore, if I want to transform it back to figure coordinates to display the text:</p> <pre><code>x, _ = gcf().transFigure.inverted().transform_point((xd, 0)) text(0, 0.5, &quot;abcdefg&quot;, transform=gcf().transFigure) </code></pre> <p>I get this:</p> <p><a href="https://i.sstatic.net/ZR5Ia.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZR5Ia.png" alt="A cut out version of the plot that would be generated by the above code, showing parts of the left y-axix and the y-axis label. The text &quot;abcdefg&quot; has a smaller left margin with respect to the figure and therefore runs over the y-axis label." /></a></p> <p>So clearly, the x coordinate is not correct.</p>
<python><matplotlib>
2023-12-19 16:42:28
1
4,589
HerpDerpington
77,686,694
15,893,581
SVD Decomposition for linear equation solving
<p>I'm looking for <a href="https://www.ltu.se/cms_fs/1.51590!/svd-fitting.pdf" rel="nofollow noreferrer">Algo here</a> &amp; trying to implement <a href="https://sthalles.github.io/svd-for-regression/" rel="nofollow noreferrer">this code</a>, I'm getting different <code>l2-norms</code> for resulting vectors of params for linear equation.</p> <p>Where am I mistaken in my attempt to adopt the code?</p> <pre><code>import numpy as np from scipy import linalg np.random.seed(123) v = np.random.rand(4) A = v[:,None] * v[None,:] b = np.random.randn(4) x = linalg.inv(A.T.dot(A)).dot(A.T).dot(b) #Usually not recommended because of Numerical Instability of the Normal Equations https://johnwlambert.github.io/least-squares/ l2_0= linalg.norm(A.dot(x) - b) print(&quot;manually: &quot;, l2_0) x = linalg.lstsq(A, b)[0] l2_1= linalg.norm(A.dot(x) - b) print(&quot;scipy.linalg.lstsq: &quot;, l2_1) # 2-norm of two calculations compared print(np.allclose(l2_0, l2_1, rtol=1.3e-1)) def direct_ls_svd(x,y): # append a columns of 1s (these are the biases) x = np.column_stack([np.ones(x.shape[0]), x]) # calculate the economy SVD for the data matrix x U,S,Vt = linalg.svd(x, full_matrices=False) # solve Ax = b for the best possible approximate solution in terms of least squares x_hat = Vt.T @ linalg.inv(np.diag(S)) @ U.T @ y #print(x_hat) # perform train and test inference #y_pred = x @ x_hat return y-x @ x_hat #x_hat x= direct_ls_svd(A, b) l2_svd= linalg.norm(A.dot(x) - b) print(&quot;svd: &quot;, l2_svd) # LU x= linalg.solve(A.T@A, A.T@b) l2_solve= linalg.norm(A.dot(x) - b) print(&quot;scipy.linalg.solve: &quot;, l2_solve) # manually: 2.9751344995811313 # scipy.linalg.lstsq: 2.9286130558050654 # True # svd: 6.830550019041984 # scipy.linalg.solve: 2.928613055805065 </code></pre> <p>If my error is in SVD decomposition algorithm imlementation for solving least-squares problem or perhaps in Numpy relative Scipy <a href="https://stackoverflow.com/a/16078114/15893581">rounding</a> or precision differences? How to correct svd-algo for least squares to become comparable with scipy's? And will this algorithm be faster &amp; less memory-consuming than iterative least squares methods?</p> <p>PS: <a href="https://www.educative.io/answers/what-is-scipylinalgsvd-in-python" rel="nofollow noreferrer">SVD</a> applications or <a href="https://inst.eecs.berkeley.edu/%7Eee127/sp21/livebook/l_svd_main.html#:%7E:text=The%20singular%20value%20decomposition%20%28SVD%29%20generalizes%20the%20spectral,matrix%29%2C%20to%20any%20non-symmetric%2C%20and%20even%20rectangular%2C%20matrix." rel="nofollow noreferrer">here</a>, <a href="https://machinelearningmastery.com/singular-value-decomposition-for-machine-learning/" rel="nofollow noreferrer">SVD for PCA</a> &amp; <a href="https://www.geeksforgeeks.org/partial-least-squares-singular-value-decomposition-plssvd/" rel="nofollow noreferrer">PLS-SVD</a> is my final goal -- will be the algo the same as for Least-Squares approximation ? I'm confused with such a question in general (even with code examples). Can somebody add some clarity for newbie like me, please?</p> <p>PPS: applying <a href="https://stackoverflow.com/a/59292892/15893581">such implementation</a> - I'm getting even worse result: <code>svd: 10.031259300735462</code> for l2-norm</p> <p>PPPS: also I lack some understanding of <a href="https://www.bing.com/search?q=svd+in+singular+spectral+decomposition&amp;src=IE-SearchBox&amp;FORM=IE11SR" rel="nofollow noreferrer">svd in singular spectral decomposition</a> if exists <a href="https://math.stackexchange.com/questions/2987056/does-the-singular-value-decomposition-coincide-with-the-spectral-decomposition-f">ref</a>, as 1st for unsupervised dim.reduction &amp; 2nd for non-parametric TS analysis, <a href="https://www.researchgate.net/publication/318066716_Linear_Algebra_Theory_and_Algorithms" rel="nofollow noreferrer">for practice</a></p> <p>PPPPS: ! PCA is used preliminary estimating if Multicollinearity exists, otherwise strange results can get (biased etc.)... (if no collinearity =&gt; no sensitivity to error of estimation, aka shown in small condition number of OLS analysis, - vc.vs huge cond.num.==collinearity for multivariable/multidimensional regression)</p>
<python><scipy><svd>
2023-12-19 16:38:43
1
645
JeeyCi
77,686,665
2,711,059
Understanding Exception Handling on the context of Inheritance in Python
<p>On the context of Inheritance of the Exception handling class</p> <p><a href="https://i.sstatic.net/uYRCM.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uYRCM.jpg" alt="enter image description here" /></a></p> <p>Exception is inherited from BaseException, so all the implementation of the BaseException class should be found inside the Exception class, from this understanding when i run the code</p> <pre><code>import sys class calc: def learn_exception(self): try: sys.exit() except Exception as exp: print(f'system exited {exp}') print('code running after main execution') c=calc() c.learn_exception() </code></pre> <p>The above code should enter into the Exception class, then it should resume the normal code flow, but it is not happening, but when i add this code snippet</p> <pre><code>import sys class calc: def learn_exception(self): try: sys.exit() except Exception as exp: print(f'system exited {exp}') except BaseException as ex: print(f'error while running the code {ex}') print('code running after main execution') c=calc() c.learn_exception() </code></pre> <p>The code is entering inside the BaseException class and it is resuming the normal flow. can somebody help me undertand how it is possible</p>
<python><inheritance>
2023-12-19 16:34:08
2
5,268
Lijin Durairaj
77,686,557
1,838,726
For a given node, how to find small cycles of which that node is a member?
<p>I'm using python and <a href="https://graph-tool.skewed.de/" rel="nofollow noreferrer">graph-tool</a> to do graph analysis. In a graph <code>g</code>, I want to find all cycles up to a specific length <code>max_length</code> of which a given node <code>node</code> is a member.</p> <p>Related question:<br /> <a href="https://stackoverflow.com/questions/77686189/how-to-iterate-simple-cycles-in-ascending-cycle-length-order">How to iterate simple cycles in ascending cycle length order?</a> is a broader question, which is more general and about a broader aspect. These questions act on different levels of abstraction and they are not duplicates of each other.</p> <p>I've tried <a href="https://graph-tool.skewed.de/static/doc/autosummary/graph_tool.topology.all_circuits.html" rel="nofollow noreferrer"><code>graph_tool.topology.all_circuits</code></a>, but that runs far too long. It finds way too many cycles, e.g. for a <a href="https://en.wikipedia.org/wiki/Zachary%27s_karate_club" rel="nofollow noreferrer">graph with just 34 nodes</a>, it finds 1462130 many cycles. In practice, I want to analyse a graph with more than 2 million nodes and there it would probably run for years. Here is an example to test this:</p> <pre><code>import graph_tool.collection import graph_tool.topology g = graph_tool.collection.data[&quot;karate&quot;] print(&quot;number of nodes in graph:&quot;, g.num_vertices()) print() print(f&quot;circ_idx\tcircuit&quot;) circuit_iter = graph_tool.topology.all_circuits(g) i = 0 for circuit in circuit_iter: i += 1 if i % 152371 == 0: print(f&quot;{i}\t{circuit}&quot;) print(&quot;total number of circuits:&quot;, i) </code></pre> <p>Output:</p> <pre><code>number of nodes in graph: 34 circ_idx circuit 152371 [ 0 3 1 13 2 28 31 25 24 27 33 29 23 32 8] 304742 [ 0 7 1 30 32 23 33 27 24 25 31 28 2 3 12] 457113 [ 0 8 30 1 19 33 18 32 29 23 25 24 31] 609484 [ 0 8 33 27 24 25 23 29 32 2 3] 761855 [ 0 13 1 7 3 2 32 31 25 23 33 19] 914226 [ 0 17 1 7 3 2 32 31 24 27 23 29 33 30 8] 1066597 [ 0 19 33 27 24 25 23 29 32 30 1 3] 1218968 [ 0 31 24 27 23 29 26 33 22 32 2 3 12] 1371339 [ 0 31 32 23 25 24 27 33 13 3 2 1 30 8] total number of circuits: 1462130 </code></pre> <p>Therefore, I think that the best approach is to use breadth first search (BFS), starting at node <code>node</code>, to find the cycles up to a specific length of which this node is a member, and stopping the BFS when the <code>max_length</code> is reached. I've tried that using <a href="https://graph-tool.skewed.de/static/doc/autosummary/graph_tool.search.bfs_iterator.html" rel="nofollow noreferrer">graph_tool.search.bfs_iterator</a> and <a href="https://graph-tool.skewed.de/static/doc/autosummary/graph_tool.search.bfs_search.html" rel="nofollow noreferrer">graph_tool.search.bfs_search</a>, but surprisingly, neither of them can be used to find cycles at all, as can be seen from the output of the following program:</p> <pre><code>import graph_tool.collection import graph_tool.search g = graph_tool.collection.data[&quot;karate&quot;] print(&quot;number of nodes in graph:&quot;, g.num_vertices()) print() print(&quot;adjacencies&quot;) for src in range(5): neighbors_list = g.get_all_neighbors(src) neighbors_list.sort() print(&quot; &quot;, src, neighbors_list) print(&quot; ...&quot;) node = 0 print() print(&quot;graph_tool.search.bfs_iterator&quot;) bfs_iter = graph_tool.search.bfs_iterator(g, node) for edge in bfs_iter: src = g.vertex_index[edge.source()] tar = g.vertex_index[edge.target()] found = &quot; ############################## cycle found!!!&quot; if tar == node else &quot; no cycle found&quot; print(&quot; &quot;, src, tar, found) </code></pre> <p>Output:</p> <pre><code>number of nodes in graph: 34 adjacencies 0 [ 1 2 3 4 5 6 7 8 10 11 12 13 17 19 21 31] 1 [ 0 2 3 7 13 17 19 21 30] 2 [ 0 1 3 7 8 9 13 27 28 32] 3 [ 0 1 2 7 12 13] 4 [ 0 6 10] ... graph_tool.search.bfs_iterator 0 1 no cycle found 0 2 no cycle found 0 3 no cycle found 0 4 no cycle found 0 5 no cycle found 0 6 no cycle found 0 7 no cycle found 0 8 no cycle found 0 10 no cycle found 0 11 no cycle found 0 12 no cycle found 0 13 no cycle found 0 17 no cycle found 0 19 no cycle found 0 21 no cycle found 0 31 no cycle found 1 30 no cycle found 2 9 no cycle found 2 27 no cycle found 2 28 no cycle found 2 32 no cycle found 5 16 no cycle found 8 33 no cycle found 31 24 no cycle found 31 25 no cycle found 27 23 no cycle found 32 14 no cycle found 32 15 no cycle found 32 18 no cycle found 32 20 no cycle found 32 22 no cycle found 32 29 no cycle found 33 26 no cycle found </code></pre> <p>The <a href="https://graph-tool.skewed.de/static/doc/autosummary/graph_tool.search.bfs_search.html" rel="nofollow noreferrer">graph_tool.search.bfs_search</a> together with a <a href="https://graph-tool.skewed.de/static/doc/autosummary/graph_tool.search.BFSVisitor.html" rel="nofollow noreferrer">BFSVisitor</a> is another approach to BFS, but it has the same obstacle for detecting cycles, and it is thus unusable for my purpose. (Update: I doubt my own assessment here. See comment.)</p> <p>Do I really have to implement BFS on my own in order to use a BFS for cycle detection? It's not tons of work, but I wonder if there is a better alternative. Moreover, implementing it in python will make it slow.</p>
<python><graph-theory><graph-tool><cycle-detection>
2023-12-19 16:17:26
0
6,700
Daniel S.
77,686,480
8,938,220
python dbf query with multiple conditions
<p>I am using <a href="https://pypi.org/project/dbf/" rel="nofollow noreferrer">dbf</a> strong text module in my projects.</p> <p>my dbf file condtains 5 fields. (ACKNO is primary key field)</p> <p>ACKNO INVNO INVDT CTYPE DTYPE</p> <p>Read DBF is working file and querying single field (using .index_search)is working fine</p> <p>Now I have <strong>problem with querying multiple fields with multiple conditions</strong>.</p> <p>I tried with with List Comprehension, it is working, but slow with records with more than 2000 records</p> <p>Currently i am converting my dbf table into pandas dataframe and using query with pandas dataframe. Problem here is, it is very slow even for 1000 records also.</p> <p>I would like to use dbf <strong>index and index_search with multiple criteria using 1) query or 2) search or 3) index_search functions.</strong></p> <p>My code is below</p> <pre><code>import dbf import datetime table = dbf.Table('inv.dbf', 'ACKNO N(12,0); INVNO N(8,0); INVDT D; CTYPE C(1); DTYPE C(1);') table.open(dbf.READ_WRITE) for datum in ( (1000000001, 1001, dbf.Date(2023, 11, 23), 'A', 'I'), (1000000002, 1002, dbf.Date(2023, 11, 23), 'G', 'D'), (1000000003, 1003, dbf.Date(2023, 11, 23), 'G', 'I'), (1000000004, 1004, dbf.Date(2023, 11, 23), 'A', 'C'), (1000000005, 1005, dbf.Date(2023, 11, 23), 'G', 'C'), (1000000006, 1006, dbf.Date(2023, 11, 23), 'A', 'I'), (1000000007, 1007, dbf.Date(2023, 11, 23), 'G', 'D'), (1000000008, 1008, dbf.Date(2023, 11, 23), 'A', 'D'), (1000000009, 1009, dbf.Date(2023, 11, 24), 'G', 'I'), (1000000010, 1010, dbf.Date(2023, 11, 24), 'A', 'C'), (1000000011, 1011, dbf.Date(2023, 11, 24), 'A', 'I'), (1000000012, 1012, dbf.Date(2023, 11, 24), 'A', 'I'), (1000000013, 1013, dbf.Date(2023, 11, 24), 'N', 'D'), (1000000014, 1014, dbf.Date(2023, 11, 24), 'A', 'I'), (1000000015, 1015, dbf.Date(2023, 11, 25), 'A', 'C'), (1000000016, 1016, dbf.Date(2023, 11, 25), 'G', 'I'), (1000000017, 1017, dbf.Date(2023, 11, 25), 'A', 'I'), (1000000018, 1018, dbf.Date(2023, 11, 25), 'A', 'C'), (1000000019, 1019, dbf.Date(2023, 11, 25), 'A', 'D'), (1000000020, 1020, dbf.Date(2023, 11, 26), 'A', 'D'), (1000000021, 1021, dbf.Date(2023, 11, 26), 'G', 'I'), (1000000022, 1022, dbf.Date(2023, 11, 26), 'N', 'D'), (1000000023, 1023, dbf.Date(2023, 11, 26), 'A', 'I'), (1000000024, 1024, dbf.Date(2023, 11, 26), 'G', 'D'), (1000000025, 1025, dbf.Date(2023, 11, 26), 'N', 'I'), ): table.append(datum) # I am using List Comprehension, it is working but slow with records with more than 2000 records records = [rec for rec in table if (rec.INVDT == datetime.datetime.strptime('23-11-2023','%d-%m-%Y').date()) &amp; (rec.CTYPE == &quot;A&quot;) &amp; (rec.DTYPE == &quot;I&quot;)] for row in records: print(row[0], row[1], row[2], row[3], row[4]) table.close() </code></pre>
<python><pandas><dataframe><dbf>
2023-12-19 16:02:32
1
343
Ravi Kannan
77,686,416
9,173,710
How to use different colorpalette for each subplot in seaborn catplot
<p>I am plotting categorical data with seaborn catplot. I want to make 2 plots from my data, they just differ in that the x, hue and col parameters are swapped around.</p> <p><a href="https://i.sstatic.net/r9ebtm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/r9ebtm.png" alt="enter image description here" /></a> <a href="https://i.sstatic.net/se1Kgm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/se1Kgm.png" alt="enter image description here" /></a></p> <p>In the second plot, every bar in subplot &quot;C&quot; would be shades of green to correspond with the legend coloring from the first plot. &quot;D&quot; would be red, &quot;E&quot; purple, etc.</p> <p>How can I do that? I want to use some method where I can still let Seaborn calculate the error bars.</p> <p>The code for the plots is</p> <pre class="lang-py prettyprint-override"><code> fig:sns.FacetGrid = sns.catplot(kind=&quot;bar&quot;, data = data, y=&quot;Value&quot;, x=&quot;config&quot;, hue=&quot;Surface&quot;, col=&quot;Height&quot;, col_wrap=2) plt.subplots_adjust(right=0.75) fig:sns.FacetGrid = sns.catplot(kind=&quot;bar&quot;, data = data[data[&quot;Surface&quot;] != &quot;A&quot;], y=&quot;Value&quot;, x=&quot;Height&quot;, hue=&quot;Config&quot;, col=&quot;Surface&quot;, col_wrap=2) for ax,title in zip(fig.axes, [&quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;B&quot;]): ax.set_title(title) fig.set_all_xlabels(&quot;Height&quot;) fig.set_xticklabels([2.8, 7.8, 12.8, 22.8]) fig._legend.set_title(&quot;Config&quot;) plt.subplots_adjust(right=0.74) </code></pre> <p>I gave it a shot but this still isn't working correctly:</p> <pre class="lang-py prettyprint-override"><code> g: sns.FacetGrid = sns.FacetGrid(data, hue=&quot;Config&quot;, col=&quot;Surface&quot;, hue_order=[1,2,3], col_order=[&quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;B&quot;], col_wrap=2, **figure_kwargs, **kwargs) def draw_colored_subplots(*args, **kwargs): color_order = [&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;] color_palette = sns.color_palette(&quot;muted&quot;) values = color_palette.as_hex() d = kwargs[&quot;data&quot;] base_color = values[color_order.index(d[&quot;Surface&quot;].iloc[0])] sns.barplot(*args, **kwargs, **error_kwargs, palette=sns.light_palette(base_color)) g.map_dataframe(draw_colored_subplots, y=&quot;Value&quot;, x=&quot;Height&quot;) </code></pre> <p>Gives me the error</p> <pre><code>Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect. UserWarning: The palette list has more values (6) than needed (4), which may not be intended. sns.barplot(*args, **kwargs, **error_kwargs, palette=sns.light_palette(base_color)) </code></pre> <p>and no legend is created. Somehow this is not passed through from the facetgrid? If I pass <code>hue</code> explicitly to <code>sns.barplot</code> I get the error</p> <pre><code>seaborn.utils._get_patch_legend_artist.&lt;locals&gt;.legend_artist() got multiple values for keyword argument 'label' </code></pre> <p>But the image produced is not that bad, the coloring is getting there, even though the hue should not be the same as the x axis. And the bars overlap and the legend is missing.</p> <p><a href="https://i.sstatic.net/cWRQOm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cWRQOm.png" alt="My own try" /></a></p>
<python><matplotlib><plot><seaborn>
2023-12-19 15:52:13
1
1,215
Raphael
77,686,189
1,838,726
How to iterate simple cycles in ascending cycle length order?
<p>I want to find all nodes of a graph, which are in simple cycles of length up to some given maximum cycle length <code>max_length</code>. Along with this I want to make a histogram of the number of cycles (per cycle length) that each node is contained in. I'm trying to figure out what the best way is to get this task done.</p> <p>Related question:<br /> <a href="https://stackoverflow.com/questions/77686557/for-a-given-node-how-to-find-small-cycles-of-which-that-node-is-a-member">For a given node, how to find small cycles of which that node is a member?</a> is a related question which is more specific than this question here. They are not duplicates.</p> <p>I'm using python and <a href="https://graph-tool.skewed.de/" rel="nofollow noreferrer">graph-tool</a> for analysing the graph, which seems to be a good choice, because several tests indicate that graph-tool is among the world's top performance graph libraries, esp. for python. I prefer to use python for this. In particular, others were not fast enough (networkx) or had bad time complexity (edge deletion in igraph) and hence didn't scale for other tasks for what I need them.</p> <p>Here are my ideas for approaches:</p> <p>Idea 1:<br /> Iterate over all cycles of the graph in the order of ascending cycle length and take note of the nodes therein.</p> <p>Idea 1.1. (Following up Idea 1.):<br /> There is the function <a href="https://graph-tool.skewed.de/static/doc/autosummary/graph_tool.topology.all_circuits.html" rel="nofollow noreferrer"><code>graph_tool.topology.all_circuits</code></a>, but that doesn't seem to iterate over only simple cycles or not in the order that I want. I don't really know what it does exactly. I just know that I can't use it, because it has exploding time complexity with my graph. E.g. for the small <a href="https://en.wikipedia.org/wiki/Zachary%27s_karate_club" rel="nofollow noreferrer">Zachary's karate club</a> with just 34 nodes, it finds 1462130 many cycles. I want to analyse graphs with about 2 million nodes and 4 million edges. I've tried to run <a href="https://graph-tool.skewed.de/static/doc/autosummary/graph_tool.topology.all_circuits.html" rel="nofollow noreferrer"><code>graph_tool.topology.all_circuits</code></a> for such a graph, but this way I didn't even get to see many of the shorter cycles that I'm interested in. I estimate that the cycle search on graphs like the ones I want to analyse would run for several years using this approach. Illustration:</p> <pre><code>import graph_tool.collection import graph_tool.topology g = graph_tool.collection.data[&quot;karate&quot;] print(&quot;number of nodes in graph:&quot;, g.num_vertices()) print() print(f&quot;circ_idx\tcircuit&quot;) circuit_iter = graph_tool.topology.all_circuits(g) i = 0 for circuit in circuit_iter: i += 1 if i % 152371 == 0: print(f&quot;{i}\t{circuit}&quot;) print(&quot;total number of circuits:&quot;, i) </code></pre> <p>Output:</p> <pre><code>number of nodes in graph: 34 circ_idx circuit 152371 [ 0 3 1 13 2 28 31 25 24 27 33 29 23 32 8] 304742 [ 0 7 1 30 32 23 33 27 24 25 31 28 2 3 12] 457113 [ 0 8 30 1 19 33 18 32 29 23 25 24 31] 609484 [ 0 8 33 27 24 25 23 29 32 2 3] 761855 [ 0 13 1 7 3 2 32 31 25 23 33 19] 914226 [ 0 17 1 7 3 2 32 31 24 27 23 29 33 30 8] 1066597 [ 0 19 33 27 24 25 23 29 32 30 1 3] 1218968 [ 0 31 24 27 23 29 26 33 22 32 2 3 12] 1371339 [ 0 31 32 23 25 24 27 33 13 3 2 1 30 8] total number of circuits: 1462130 </code></pre> <p>Idea 1.2. (Following up Idea 1.):<br /> Implement Idea 1. myself. Doable, but this sounds like quite some work. I don't want to invent the wheel another time. Is there a better way?</p> <p>Idea 2:<br /> As an alternative to Idea 1., it's also okay to iterate per node over the cycles that a given node is contained in, again in the order of ascending cycle lengths. This can be done with a breadth first search (BFS), starting from the node in question.<br /> With this I can then check membership of a node in said cycles and then move on to the next node. This is less efficient, because I will process cycles repeatedly for every node that is contained in the same cycle, but it will still give reasonable overall time complexity.<br /> The big advantage of this approach is that the implementation will be easier than Idea 1.</p> <p>Are there better approaches? Does graph-tool offer something that is more well suited for this task?</p>
<python><graph-theory><graph-tool><cycle-detection>
2023-12-19 15:12:48
2
6,700
Daniel S.
77,686,182
1,874,170
Override or augment setuptools build_ext error messages
<p>I'm trying to build on a fresh Linux installation a CFFI-based package I'm maintaining.</p> <p>However, out of the box, the errors it gives about the dependencies pip couldn't fetch (attached at the end of this post) are useless and inscrutable.</p> <p>I want to <strong>catch, override, or somehow augment</strong> these error messages so I can give the naive user trying to execute <code>python -m build</code> or <code>pip install .</code> on a new platform some actually meaningful, <strong>actionable</strong> error messages suggesting what packages to install (including, for example, the link to Windows' <a href="https://visualstudio.microsoft.com/visual-cpp-build-tools/" rel="nofollow noreferrer">Build Tools</a>).</p> <p>My project is pyproject.toml-based, with the default backend / no backend specified. It seems to be using <code>build_ext</code> due to its cffi build-time dependency.</p> <p>How can this be done?</p> <hr /> <h3>Appendix: Error messages</h3> <p>The solution to this one was <code>dnf groupinstall 'Development Tools'</code>/<code>apt install build-essential</code>:</p> <pre><code>… creating build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/__init__.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece348864.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece460896.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece6688128.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece6960119.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece8192128.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem running build_ext … error: command 'gcc' failed: No such file or directory ERROR Backend subprocess exited when trying to invoke build_wheel $ </code></pre> <p>The solution to this one was <code>dnf install python3-devel</code>/<code>apt install python3-dev</code>:</p> <pre><code>… creating build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/__init__.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece348864.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece460896.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece6688128.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece6960119.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem copying pqc/kem/mceliece8192128.py -&gt; build/lib.linux-x86_64-cpython-39/pqc/kem running build_ext … build/temp.linux-x86_64-cpython-39/pqc._lib.mceliece348864f_clean.c:50:14: fatal error: pyconfig.h: No such file or directory 50 | # include &lt;pyconfig.h&gt; | ^~~~~~~~~~~~ compilation terminated. error: command '/usr/bin/gcc' failed with exit code 1 ERROR Backend subprocess exited when trying to invoke build_wheel $ </code></pre> <hr /> <h3>Appendix 2: MRE</h3> <p>As requested by a guy in the comments, here is a &quot;minimal reproducible example&quot; of a CFFI-based setuptools package which will demonstrate these errors, in case you are unfamiliar with them yet hope to answer this question anyway — this will allow you to reproduce the error on any <strong>fresh installation</strong> of Windows 10 or Ubuntu LTS (I don't know enough about Python use on Macs to say how the cookie would crumble there, though):</p> <pre class="lang-py prettyprint-override"><code>from itertools import chain, repeat, islice import os from pathlib import Path import platform import shlex import subprocess import sys import tempfile from textwrap import dedent import venv BUILD_CMD = ['python', '-m', 'pip', 'install', '-v', '.'] def main(): with tempfile.TemporaryDirectory() as td: td = os.path.realpath(td) venv.create(td, with_pip=True) root = Path(td) / 'stackoverflow-77686182' root.mkdir() # 1. create setup.py (root / 'setup.py').write_text(dedent('''\ # https://foss.heptapod.net/pypy/cffi/-/issues/441 # https://github.com/python-cffi/cffi/issues/55 from setuptools import setup setup( cffi_modules = [ 'cffi_module.py:ffi' ] ) ''')) # 2. create CFFI module (root / 'cffi_module.py').write_text(dedent('''\ from cffi import FFI from pathlib import Path root = Path(__file__).parent ffibuilder = FFI() ffibuilder.cdef('unsigned short spam();') ffibuilder.set_source( 'stackoverflow_77686182._libspam', '#include &quot;libspam.h&quot;', sources=[(root / 'libspam.c').as_posix()], include_dirs=[root.as_posix()] ) ffi = ffibuilder ''')) # 3. create C source (root / 'libspam.c').write_text(dedent('''\ unsigned short spam() { return 69; } ''')) # 4. Create C headers (root / 'libspam.h').write_text(dedent('''\ unsigned short spam(); ''')) # 5. Create Python package code (root / 'src' / 'stackoverflow_77686182').mkdir(parents=True, exist_ok=True) (root / 'src' / 'stackoverflow_77686182' / '__init__.py').write_text(dedent('''\ from . import _libspam ''')) (root / 'src' / 'stackoverflow_77686182' / '__main__.py').write_text(dedent('''\ from stackoverflow_77686182._libspam import ffi, lib if lib.spam() == 69: print('OK') else: raise AssertionError('FAIL') ''')) # 6. Create Python packaging metadata (root / 'pyproject.toml').write_text(dedent('''\ [project] name = 'stackoverflow_77686182' version = '0' dependencies = [ 'cffi &gt;= 1.0.0;platform_python_implementation != &quot;PyPy&quot;', ] [build-system] requires = [ 'cffi &gt;= 1.14', 'setuptools &gt;= 49.5.0' ] ''')) (root / 'requirements-dev.txt').write_text(dedent('''\ pip &gt;= 21.1.3 setuptools &gt;= 49.5.0 ''')) # 7. Build and install _check_call_in_venv(td, ['python', '-m', 'pip', 'install', '-r', root / 'requirements-dev.txt']) _check_call_in_venv(td, BUILD_CMD, cwd=root) # 8. Run _check_call_in_venv(td, ['python', '-m', 'stackoverflow_77686182']) raise NotImplementedError('This script should be run on a machine that LACKS the necessary items for a CFFI project build, but the build seems to have succeeded.') def _check_call_in_venv(env_dir, cmd, *a, **k): script = [] is_win = (platform.system() == 'Windows') script.append(['.', Path(env_dir) / 'bin' / 'activate'] if not is_win else [Path(env_dir) / 'Scripts' / 'activate.bat']) script.append(cmd) _cmd = ['sh', '-c', ';\n'.join(shlex.join(cmd) for cmd in ['set -e'] + script)] if not is_win else f'cmd /C &quot;{&quot; &quot;.join(_intersperse(&quot;&amp;&amp;&quot;, (&quot; &quot;.join(map(str, cmd)) for cmd in script)))}&quot;' return subprocess.check_call(_cmd, *a, **k) def _intersperse(delim, seq): # https://stackoverflow.com/a/5656097/1874170 return islice(chain.from_iterable(zip(repeat(delim), seq)), 1, None) if __name__ == '__main__': main() </code></pre>
<python><error-handling><setuptools><python-packaging><code-documentation>
2023-12-19 15:11:28
0
1,117
JamesTheAwesomeDude
77,686,120
15,991,297
Get Lowest Elementwise Values from Multiple Numpy Arrays Which May be Different Lengths
<p>I can get the lowest values from multiple arrays by using the following:</p> <pre><code>first_arr = np.array([0,1,2]) second_arr = np.array([1,0,3]) third_arr = np.array([3,0,4]) fourth_arr = np.array([1,1,9]) print(np.minimum.reduce([first_arr, second_arr, third_arr, fourth_arr])) </code></pre> <p>Result = [0 0 2]</p> <p>However if the arrays are different lengths or empty I get an error:</p> <pre><code>ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (4,) + inhomogeneous part. </code></pre> <p>The arrays will often be different lengths or empty. How can I handle this? I want to compare all elements that exist.</p> <p>So, changing the above example:</p> <pre><code>first_arr = np.array([0,1]) second_arr = np.array([1,0,3]) third_arr = np.array([3,0,4]) fourth_arr = np.array([1,1,9]) print(np.minimum.reduce([first_arr, second_arr, third_arr, fourth_arr])) </code></pre> <p>The result should be [0 0 3].</p>
<python><numpy>
2023-12-19 15:00:49
3
500
James
77,686,078
7,766,158
Django : Update object in database using UpdateAPIView
<p>I have a Django project with the the following <code>models.py</code></p> <pre><code>from django.db import models class RawUser(models.Model): id = models.CharField(max_length=256, primary_key=True) field1 = models.IntegerField(null=True) field2 = models.CharField(max_length=256) </code></pre> <p>And the following <code>view.py</code>. The goal of the <code>UserUpdate</code> view is to <code>create</code> or <code>update</code> a user when I get a PUT request.</p> <pre><code>from django.http import JsonResponse from rest_framework import generics from profiling.api.serializers import RawUserSerializer from profiling.models import RawUser class UserUpdate(generics.UpdateAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer def put(self, request, *args, **kwargs): instance = self.get_object() raw_user_serializer: RawUserSerializer = self.get_serializer(instance, data=request.data, partial=False) raw_user_serializer.is_valid(raise_exception=True) # More logic here raw_user = raw_user_serializer.update(instance, raw_user_serializer.validated_data) self.perform_update(raw_user_serializer) return JsonResponse({'user_id':raw_user.id}, status = 201) class UserDetail(generics.RetrieveAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer </code></pre> <p>The issue here is that when I try to PUT a user that exists already, I get the following error on <code>raw_user_serializer.is_valid(raise_exception=True)</code>:</p> <pre><code>Bad Request: /api/profiling/users/1/ { &quot;id&quot;: [ &quot;This field is required.&quot; ] } </code></pre> <p>And when I try to PUT a user that doesn't exist already, I get the following error on <code>instance = self.get_object()</code>:</p> <pre><code>Not Found: /api/profiling/users/25/ { &quot;detail&quot;: &quot;Not found.&quot; } </code></pre> <p>Here is my <code>urls.py</code></p> <pre><code>from django.urls import path from . import views app_name = 'app' urlpatterns = [ path('users/&lt;str:pk&gt;/', views.UserUpdate.as_view(), name='user-create'), ] </code></pre> <p>What am I doing wrong here ? (I don't mind having my user_id in request's body or in URL path)</p> <p>--- EDIT : Add serializer code ---</p> <pre><code>from rest_framework import serializers from profiling.models import ProfileProductScore, RawUser, Profile class RawUserSerializer(serializers.ModelSerializer): class Meta: model = RawUser fields = [&quot;id&quot;, &quot;field1&quot;, &quot;field2&quot;] </code></pre>
<python><django>
2023-12-19 14:55:12
0
1,931
Nakeuh
77,686,072
6,067,741
Issues with azure.identity when using federated credentials
<p>I'm running a GH actions pipeline which is configured to login Azure cli using federated credentials (and this works fine):</p> <pre><code>env: ARM_USE_OIDC: true steps: - name: az login uses: azure/login@v1 with: client-id: ${{ env.ARM_CLIENT_ID }} tenant-id: ${{ env.ARM_TENANT_ID }} subscription-id: ${{ env.ARM_SUBSCRIPTION_ID }} </code></pre> <p>then I'm running pytest which does some python code, some TF runs, etc. plain Az Cli\TF calls using subprocess work, however when I'm using <code>AzureCliCredential</code> or <code>DefaultAzureCredential</code> calls to <code>get_token</code> fail with:</p> <blockquote> <p>Output: ERROR: AADSTS700024: Client assertion is not within its valid time range. Current time: 2023-12-19T07:20:31.3554289Z, assertion valid from 2023-12-19T05:59:24.0000000Z, expiry time of assertion 2023-12-19T06:04:24.0000000Z</p> </blockquote> <p>The same code was working previously using certificate auth</p> <p>EDIT: what was confusing me is the fact that the tokens I'm getting have proper lifetime, which doesnt match the error. what I'm thinking now is that the underlying OIDC token issued by Github has only 5 minutes of lifetime hence it doesnt matter if oAuth tokens have 1h lifetime</p> <p>EDIT: related issues:<br /> <a href="https://github.com/Azure/login/issues/372" rel="nofollow noreferrer">https://github.com/Azure/login/issues/372</a><br /> <a href="https://github.com/Azure/login/issues/180" rel="nofollow noreferrer">https://github.com/Azure/login/issues/180</a></p>
<python><azure><authentication><github><pytest>
2023-12-19 14:54:14
1
71,429
4c74356b41
77,686,055
2,414,957
lmdb/cpython.c:26:10: fatal error: Python.h: No such file or directory
<p>[Disclaimer] I need to use same exact version Blender as well as the bundled Python that comes with it for <a href="https://github.com/zju3dv/pvnet-rendering/" rel="nofollow noreferrer">PVNET-Rendering git repo</a>. Steps to reproduce the error:</p> <p>1.</p> <pre><code>root@fae597dbdb79:/home# wget https://bootstrap.pypa.io/pip/3.5/get-pip.py --2023-12-15 18:28:14-- https://bootstrap.pypa.io/pip/3.5/get-pip.py Resolving bootstrap.pypa.io (bootstrap.pypa.io)... 151.101.0.175, 151.101.64.175, 151.101.128.175, ... Connecting to bootstrap.pypa.io (bootstrap.pypa.io)|151.101.0.175|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1908223 (1.8M) [text/x-python] Saving to: 'get-pip.py' get-pip.py 100%[================================================================================================================&gt;] 1.82M --.-KB/s in 0.07s 2023-12-15 18:28:20 (27.6 MB/s) - 'get-pip.py' saved [1908223/1908223] </code></pre> <ol start="2"> <li><p><code>root@fae597dbdb79:/home# cd blender-2.79a-linux-glibc219-x86_64/2.79/python/bin/</code></p> </li> <li></li> </ol> <pre><code>root@fae597dbdb79:/home/blender-2.79a-linux-glibc219-x86_64/2.79/python/bin# ./python3.5m /home/get-pip.py DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality. Collecting pip&lt;21.0 Downloading pip-20.3.4-py2.py3-none-any.whl (1.5 MB) |################################| 1.5 MB 6.9 MB/s Collecting setuptools Using cached setuptools-50.3.2-py3-none-any.whl (785 kB) Collecting wheel Using cached wheel-0.37.1-py2.py3-none-any.whl (35 kB) Installing collected packages: wheel, setuptools, pip Successfully installed pip-20.3.4 setuptools-50.3.2 wheel-0.37.1 </code></pre> <ol start="4"> <li></li> </ol> <pre><code>root@fae597dbdb79:/home/pvnet-rendering# /home/blender-2.79a-linux-glibc219-x86_64/2.79/python/bin/pip3 install lmdb DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality. Collecting lmdb Using cached lmdb-1.4.1.tar.gz (881 kB) Building wheels for collected packages: lmdb Building wheel for lmdb (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/blender-2.79a-linux-glibc219-x86_64/2.79/python/bin/python3.5m -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '&quot;'&quot;'/tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/setup.py'&quot;'&quot;'; __file__='&quot;'&quot;'/tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/setup.py'&quot;'&quot;';f=getattr(tokenize, '&quot;'&quot;'open'&quot;'&quot;', open)(__file__);code=f.read().replace('&quot;'&quot;'\r\n'&quot;'&quot;', '&quot;'&quot;'\n'&quot;'&quot;');f.close();exec(compile(code, __file__, '&quot;'&quot;'exec'&quot;'&quot;'))' bdist_wheel -d /tmp/pip-wheel-eb8274q3 cwd: /tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/ Complete output (26 lines): py-lmdb: Using bundled liblmdb with py-lmdb patches; override with LMDB_FORCE_SYSTEM=1 or LMDB_PURE=1. patching file lmdb.h patching file mdb.c py-lmdb: Using CPython extension; override with LMDB_FORCE_CFFI=1. running bdist_wheel running build running build_py creating build/lib.linux-x86_64-3.5 creating build/lib.linux-x86_64-3.5/lmdb copying lmdb/tool.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/cffi.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/__init__.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/_config.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/__main__.py -&gt; build/lib.linux-x86_64-3.5/lmdb running build_ext building 'cpython' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/lmdb creating build/temp.linux-x86_64-3.5/build creating build/temp.linux-x86_64-3.5/build/lib gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Ilib/py-lmdb -Ibuild/lib -I/home/blender-2.79a-linux-glibc219-x86_64/2.79/python/include/python3.5m -c lmdb/cpython.c -o build/temp.linux-x86_64-3.5/lmdb/cpython.o -DHAVE_PATCHED_LMDB=1 -UNDEBUG -w lmdb/cpython.c:26:10: fatal error: Python.h: No such file or directory #include &quot;Python.h&quot; ^~~~~~~~~~ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for lmdb Running setup.py clean for lmdb Failed to build lmdb Installing collected packages: lmdb Running setup.py install for lmdb ... error ERROR: Command errored out with exit status 1: command: /home/blender-2.79a-linux-glibc219-x86_64/2.79/python/bin/python3.5m -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '&quot;'&quot;'/tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/setup.py'&quot;'&quot;'; __file__='&quot;'&quot;'/tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/setup.py'&quot;'&quot;';f=getattr(tokenize, '&quot;'&quot;'open'&quot;'&quot;', open)(__file__);code=f.read().replace('&quot;'&quot;'\r\n'&quot;'&quot;', '&quot;'&quot;'\n'&quot;'&quot;');f.close();exec(compile(code, __file__, '&quot;'&quot;'exec'&quot;'&quot;'))' install --record /tmp/pip-record-xca485a8/install-record.txt --single-version-externally-managed --compile --install-headers /home/blender-2.79a-linux-glibc219-x86_64/2.79/python/include/python3.5m/lmdb cwd: /tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/ Complete output (26 lines): py-lmdb: Using bundled liblmdb with py-lmdb patches; override with LMDB_FORCE_SYSTEM=1 or LMDB_PURE=1. patching file lmdb.h patching file mdb.c py-lmdb: Using CPython extension; override with LMDB_FORCE_CFFI=1. running install running build running build_py creating build/lib.linux-x86_64-3.5 creating build/lib.linux-x86_64-3.5/lmdb copying lmdb/tool.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/cffi.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/__init__.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/_config.py -&gt; build/lib.linux-x86_64-3.5/lmdb copying lmdb/__main__.py -&gt; build/lib.linux-x86_64-3.5/lmdb running build_ext building 'cpython' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/lmdb creating build/temp.linux-x86_64-3.5/build creating build/temp.linux-x86_64-3.5/build/lib gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Ilib/py-lmdb -Ibuild/lib -I/home/blender-2.79a-linux-glibc219-x86_64/2.79/python/include/python3.5m -c lmdb/cpython.c -o build/temp.linux-x86_64-3.5/lmdb/cpython.o -DHAVE_PATCHED_LMDB=1 -UNDEBUG -w lmdb/cpython.c:26:10: fatal error: Python.h: No such file or directory #include &quot;Python.h&quot; ^~~~~~~~~~ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /home/blender-2.79a-linux-glibc219-x86_64/2.79/python/bin/python3.5m -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '&quot;'&quot;'/tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/setup.py'&quot;'&quot;'; __file__='&quot;'&quot;'/tmp/pip-install-sz6nq7pp/lmdb_95a8258634164c42b71528bea9b99efe/setup.py'&quot;'&quot;';f=getattr(tokenize, '&quot;'&quot;'open'&quot;'&quot;', open)(__file__);code=f.read().replace('&quot;'&quot;'\r\n'&quot;'&quot;', '&quot;'&quot;'\n'&quot;'&quot;');f.close();exec(compile(code, __file__, '&quot;'&quot;'exec'&quot;'&quot;'))' install --record /tmp/pip-record-xca485a8/install-record.txt --single-version-externally-managed --compile --install-headers /home/blender-2.79a-linux-glibc219-x86_64/2.79/python/include/python3.5m/lmdb Check the logs for full command output. </code></pre> <p>I am using Docker with Ubuntu 18.04 inside native Ubuntu 22.04.</p>
<python><ubuntu><pip><blender><lmdb>
2023-12-19 14:52:42
1
38,867
Mona Jalal
77,686,033
10,145,953
OpenCV boundingRect to detect rectangle?
<p>I am new to OpenCV and I'm having some trouble figuring out how to crop a rectangle in an image. I have a PDF of a form (which I've converted to an image) which looks similar to this <a href="https://img.yumpu.com/16772683/1/500x640/dd-form-2585-repatriation-processing-center-processing-sheet-.jpg" rel="nofollow noreferrer">here</a>. I want to crop to the large rectangle (not each individual rectangle) so my output image is just the large rectangle and every contained within.</p> <p>I am trying to eventually extract out the information contained within the large rectangle but my first step is I need to crop around the rectangle; my actual image has some text at the top of the rectangle as well as text below like in the example image. I attempted to use the code in <a href="https://stackoverflow.com/questions/53127776/opencv-boundingrect-output">this question</a> but the output image it produced was no different from the original and did not crop around the rectangle.</p> <pre><code>thresh_value = 10 img = cv2.medianBlur(img_raw, 5) dilation = cv2.dilate(img,(3,3),iterations = 3) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) (T, thresh) = cv2.threshold(img_gray, thresh_value, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = [i for i in contours if cv2.contourArea(i) &lt; 5000] cv2.drawContours(img, contours, -1, (0,0,0), 10, lineType=8) cv2.imwrite(&quot;cropped_img.jpg&quot;, img) </code></pre> <p>The original code on the line where you define contours and hierarchy was <code>_, contours, hierarchy =</code> but I received an error saying <code>ValueError: not enough values to unpack (expected 3, got 2)</code>.</p> <p>I did use the <code>boundingRect</code> function to remove whitespace (as seen in the code block below) and I think this is the most promising but I'm not totally clear on how to tweak this to instead of looking for text, look for the rectangle.</p> <pre><code>gray = 255*(img_raw &lt; 128).astype(np.uint8) coords = cv2.findNonZero(gray) x, y, w, h = cv2.boundingRect(coords) processed_image = img_raw[y:y+h, x:x+w] </code></pre> <p>What am I doing wrong here?</p>
<python><opencv>
2023-12-19 14:49:17
1
883
carousallie
77,686,020
9,973,879
How to align the axes of a figure in matplotlib?
<p>I have a figure with a <code>2x2</code> grid of <code>plt.Axes</code> (one of which is actually removed). Axes of the same row (resp. col) share the same y-axis (resp. x-axis) range. For example,</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np fig, axs = plt.subplots(2, 2) axs[0, 0].imshow(np.zeros((2, 2))) axs[0, 1].imshow(np.zeros((2, 1))) axs[1, 0].imshow(np.zeros((1, 2))) axs[1, 1].remove() plt.show(block=True) </code></pre> <p>This looks like this:</p> <p><a href="https://i.sstatic.net/wlYYj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/wlYYj.png" alt="enter image description here" /></a></p> <p>I want the axes to be aligned, that is, that points with the same x (resp. y) coordinates in the axes of the same column (resp. row) also share the same x (resp. y) coordinate in the figure. What do I need to change to achieve this?</p> <p>I tried <code>sharex='col', sharey='row'</code> as it seemed to provide a solution in <a href="https://stackoverflow.com/a/54473768">other answers</a>, but all I got is this change in ticks, not in figure alignment:</p> <p><a href="https://i.sstatic.net/gpzYJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gpzYJ.png" alt="enter image description here" /></a></p>
<python><matplotlib>
2023-12-19 14:47:47
2
1,967
user209974
77,685,970
3,445,378
How to use the python-flask server generated by swagger-codegen?
<p>I have a simple open-api-definition that can used by swagger-codegen to generate a client and server application. While using the client is not a problem, I find no information how to use the server.</p> <p>So far I can see, that the server is based on connextion. There is also a setup.py from setup-tools.</p> <p>The readme tells me to use <code>python -m test_server</code> to run the sever. This ends in a error message <code>ModuleNotFoundError: No module named 'connexion.apps.flask_app'</code>.</p> <p>My first goal is to get it to run in some way. But after that, there is another question, how to extend it for you application and how to deal with new api-versions.</p>
<python><swagger-codegen>
2023-12-19 14:37:53
0
1,280
testo
77,685,924
1,933,185
Uncaught ReferenceError: IPython is not defined
<p>I try to pass a javascript variable to python in a jupyter notebook, as described in <a href="https://stackoverflow.com/q/37172978/1933185">How to pass variables from javascript to python in Jupyter?</a></p> <p>Somehow the <code>IPython.notebook.kernel.execute(&quot;foo=97&quot;)</code> seems not to work, but IPython itself works.</p> <p>Here my code from the jupyter notebook</p> <pre><code># [1] from IPython.display import HTML # [2] HTML('''&lt;script&gt;console.log('foo=101')&lt;/script&gt;''') # [3] HTML(''' &lt;script type=&quot;text/javascript&quot;&gt; IPython.notebook.kernel.execute(&quot;foo=97&quot;) &lt;/script&gt; ''') </code></pre> <p>Executing cell [2] after cell [1] shows in the console <code>foo=101</code>. Executing cell [3] shows this error in the console</p> <pre><code>VM1448:2 Uncaught ReferenceError: IPython is not defined at &lt;anonymous&gt;:2:5 at t.attachWidget (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:1594384) at t.insertWidget (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:1593735) at j._insertOutput (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:925178) at j.onModelChanged (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:922355) at m (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:1560386) at Object.l [as emit] (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:1560046) at e.emit (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:1558291) at c._onListChanged (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:918778) at m (jlab_core.e37d4bbc8c984154bc26.js?v=e37d4bbc8c984154bc26:2:1560386) </code></pre> <p>Any ideas how to solve my problem?</p> <p>My jupyter setup:</p> <pre><code>IPython : 8.6.0 ipykernel : 6.17.1 ipywidgets : 8.1.1 jupyter_client : 7.4.7 jupyter_core : 5.0.0 jupyter_server : 1.23.2 jupyterlab : 3.5.0 nbclient : 0.7.0 nbconvert : 7.2.5 nbformat : 5.7.0 notebook : 6.5.2 qtconsole : not installed traitlets : 5.5.0 </code></pre>
<python><jupyter-notebook><ipython>
2023-12-19 14:30:12
0
5,797
jerik
77,685,797
8,510,149
Create a dynamic case when statement based on pyspark dataframe
<p>I have a dataframe called <code>df</code> with <code>features, col1, col2, col3</code>. Their values should be combined and produce a result. What result each combination will produce is defined in <code>mapping_table</code>.</p> <p>However, mapping_table sometimes has the value '*'. This mean that this feature can have any value, it doesn't affect the result.</p> <p>This makes a join impossible(?) to make, since I need to evaluate which features to use in the join for every row.</p> <p>What would be a good pyspark solution for this problem?</p> <pre><code>from pyspark.sql import SparkSession from pyspark.sql.functions import col # Create a Spark session spark = SparkSession.builder.appName(&quot;example&quot;).getOrCreate() # Example DataFrames map_data = [('a', 'b', 'c', 'good'), ('a', 'a', '*', 'very good'), ('b', 'd', 'c', 'bad'), ('a', 'b', 'a', 'very good'), ('c', 'c', '*', 'very bad'), ('a', 'b', 'b', 'bad')] columns = [&quot;col1&quot;, &quot;col2&quot;, 'col3', 'result'] mapping_table = spark.createDataFrame(X, columns) data =[[('a', 'b', 'c'), ('a', 'a', 'b' ), ('c', 'c', 'a' ), ('c', 'c', 'b' ), ('a', 'b', 'b'), ('a', 'a', 'd') ]] columns = [&quot;col1&quot;, &quot;col2&quot;, 'col3'] df = spark.createDataFrame(data, columns) </code></pre>
<python><pyspark>
2023-12-19 14:10:24
1
1,255
Henri
77,685,544
8,030,746
Selenium: Chrome suddenly stopped working
<p>I have a scraping script that worked perfectly, but then out of the blue suddenly stopped. This is the error I'm getting:</p> <pre><code>Traceback (most recent call last): File &quot;/home/user/myproject/scraping_all.py&quot;, line 29, in &lt;module&gt; driver = webdriver.Chrome(options=options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/home/user/myproject/myprojectenv/lib/python3.11/site-packages/selenium/webdriver/chrome/webdriver.py&quot;, line 45, in __init__ super().__init__( File &quot;/home/user/myproject/myprojectenv/lib/python3.11/site-packages/selenium/webdriver/chromium/webdriver.py&quot;, line 56, in __init__ super().__init__( File &quot;/home/user/myproject/myprojectenv/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py&quot;, line 208, in __init__ self.start_session(capabilities) File &quot;/home/user/myproject/myprojectenv/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py&quot;, line 292, in start_session response = self.execute(Command.NEW_SESSION, caps)[&quot;value&quot;] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/home/user/myproject/myprojectenv/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py&quot;, line 347, in execute self.error_handler.check_response(response) File &quot;/home/user/myproject/myprojectenv/lib/python3.11/site-packages/selenium/webdriver/remote/errorhandler.py&quot;, line 229, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome failed to start: exited normally. (unknown error: unable to discover open pages) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) </code></pre> <p>Google Chrome version is: <code>Google Chrome 120.0.6099.109</code></p> <p>And this is how I set up the options for the scraping, as well:</p> <pre><code>options = Options() options.add_argument(&quot;start-maximized&quot;) options.add_argument('--headless=new') options.add_argument('--disable-dev-shm-usage') options.add_argument('--disable-gpu') options.add_argument('--no-sandbox') options.add_argument('--user-data-dir=/home/user/myproject') options.add_argument(&quot;--remote-debugging-port=9222&quot;) driver = webdriver.Chrome(options=options) </code></pre> <p>What's going on here? Is there something I should update besides Chrome, and how? Or is my setup wrong?</p> <p>Thank you!</p>
<python><google-chrome><selenium-webdriver>
2023-12-19 13:27:57
0
851
hemoglobin
77,685,213
13,518,907
How to Speed up RetrievalQA Chain?
<p>I have created a RetrievalQA chain and now want to speed up the process. At the moment, the generation of the text takes too long (1-2minutes) with the qunatized Mixtral 8x7B-Instruct model from &quot;TheBloke&quot;.</p> <p>I am running the chain locally on a Macbook Pro (Apple M2 Max) with 64GB RAM, and 12 cores.</p> <p>Here is my code:</p> <pre><code>from dotenv import find_dotenv, load_dotenv import box import yaml from langchain.llms import LlamaCpp from langchain.callbacks.manager import CallbackManager from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler # Load environment variables from .env file load_dotenv(find_dotenv()) # Import config vars with open('config/config.yml', 'r', encoding='utf8') as ymlfile: cfg = box.Box(yaml.safe_load(ymlfile)) def build_llm(model_path): callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]) n_gpu_layers = 1 # Metal set to 1 is enough. # ausprobiert mit mehreren n_batch = 1024 # Should be between 1 and n_ctx, consider the amount of RAM of your Apple Silicon Chip. llm = LlamaCpp( max_tokens =cfg.MAX_TOKENS, #model_path=&quot;/Documents/rag_example/Modelle/mixtral-8x7b-instruct-v0.1.Q5_K_M.gguf&quot;, model_path=model_path, temperature=0.1, f16_kv=True, n_ctx=28000, # 28k because Mixtral can take up to 32k n_gpu_layers=n_gpu_layers, n_batch=n_batch, callback_manager=callback_manager, verbose=True, # Verbose is required to pass to the callback manager top_p=0.75, top_k=40, model_kwargs={ 'repetition_penalty': 1.1, 'mirostat': 2, }, ) return llm mistral_prompt = &quot;&quot;&quot; &lt;s&gt; [INST] Du bist ein hilfreicher Chat-Assistent names Mixtral, der nur auf Deutsch antworten kann. Deine Aufgabe ist es, die Fragen des Nutzers ausschließlich auf Deutsch zu beantworten. Nutze den gefundenen Kontext, um die Fragen zu beantworten. Falls du die Antwort nicht weißt, sag einfach, dass du die Antwort nicht kennst. Falls sich die Antwort nicht im Kontext befindet, antworte: &quot;Es gibt nicht genug Informationen im Kontext, um die Frage zu beantworten.&quot;. Halte deine Antworten präzise und vermeide spekulative oder erfundene Informationen. Erfinde nichts, falls du die Antwort nicht kennst oder du dir nicht sicher bist! Ein Konversationsverlauf steht dir nach &quot;Chat History&quot; zur Verfügung. Wenn du merkst, dass der Nutzer Smalltalk betreibt, führe Smalltalk mit ihm. Chat History: {chat_history} Context: {context} Question: {question} Answer: [/INST] &quot;&quot;&quot; def set_mistral_prompt(): &quot;&quot;&quot; Prompt template for QA retrieval for each vectorstore &quot;&quot;&quot; prompt = PromptTemplate(template=mistral_prompt, input_variables=['chat_history', 'context', 'question']) return prompt def build_retrieval_qa(llm, prompt, vectordb, chain_type=&quot;RetrievalQA&quot;): chain_type_kwargs={ #&quot;verbose&quot;: True, &quot;prompt&quot;: prompt, &quot;memory&quot;: ConversationBufferMemory( memory_key=&quot;chat_history&quot;, input_key=&quot;question&quot;, #output_key=&quot;answer&quot;, return_messages=True), &quot;verbose&quot;: False } if chain_type == &quot;RetrievalQA&quot;: dbqa = RetrievalQA.from_chain_type(llm=llm, chain_type='stuff', retriever=vectordb.as_retriever(search_kwargs={'k': cfg.VECTOR_COUNT, 'score_treshold': cfg.SCORE_TRESHOLD}, search_type=&quot;similarity&quot;), # search_type=&quot;mmr&quot; for Similarity AND diversity return_source_documents=cfg.RETURN_SOURCE_DOCUMENTS, chain_type_kwargs=chain_type_kwargs, verbose=False ) return dbqa from langchain.embeddings import HuggingFaceBgeEmbeddings, HuggingFaceEmbeddings, SentenceTransformerEmbeddings from langchain.vectorstores import FAISS import pickle from src.utils import setup_dbqa, build_retrieval_qa, set_mistral_prompt from src.utils import setup_dbqa from src.text_preprocess import clean_document, clean_document_confluence from src.llm import build_llm # Load documents with open(f'confluence_docs.pkl', 'rb') as documents: documents = pickle.load(documents) # Preprocess the text before chunking documents = clean_document_confluence(documents) embeddings = HuggingFaceEmbeddings(model_name=&quot;intfloat/multilingual-e5-large&quot;, model_kwargs={'device': 'mps'}) vectorstore = FAISS.from_documents(documents, embeddings) chat_history = [] qa_prompt = set_mistral_prompt() llm = build_llm(model_path=&quot;/Users/mweissenba001/Documents/rag_example/Modelle/mixtral-8x7b-instruct-v0.1.Q5_K_M.gguf&quot;) mixtral_qa = build_retrieval_qa(llm=llm,prompt=qa_prompt,vectordb=vectorstore) mixtral_qa({'query': &quot;Wer ist Dr. Nicolai Bieber?&quot;, &quot;chat_history&quot;: []}) # takes longer than 1min </code></pre> <p>So which steps may I have to adapt to get faster responses? The Mixtral-Model without the RetrievalQA chain only takes a couple of seconds.</p> <p>Increasing &quot;n_gpu_layers&quot; and &quot;n_batch&quot; didn't really help. I also added &quot;n_threads = 8&quot; to llm = LlamaCpp(...)</p>
<python><artificial-intelligence><langchain>
2023-12-19 12:33:01
0
565
Maxl Gemeinderat
77,685,135
12,704,700
How do i write to dynamo from pyspark without the attributevalues?
<p>I have a dynamicframe which has following schema</p> <pre><code>root |-- data1: string (nullable = false) |-- data2: string (nullable = false) |-- data3: array (nullable = false) | |-- element: string (containsNull = true) </code></pre> <p>Now when i write this to dynamodb using the</p> <pre><code>glue_context.write_dynamic_frame_from_options( frame=DynamicFrame.fromDF(df, glue_context, &quot;output&quot;), connection_type=&quot;dynamodb&quot;, connection_options={ &quot;dynamodb.output.tableName&quot;: &quot;table_name&quot;, &quot;dynamodb.throughput.write.percent&quot;: &quot;1.0&quot;, }, ) </code></pre> <p>The data three is being written as <code>[ { &quot;L&quot; : [ { &quot;S&quot; : &quot;&quot; }, { &quot;S&quot; : &quot;&quot; }, { &quot;S&quot; : &quot;&quot; }, { &quot;S&quot; : &quot;&quot; } ] } ]</code> but instead i want it as <code>[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]</code>,</p> <p>How do i achieve this?</p>
<python><pyspark><amazon-dynamodb>
2023-12-19 12:19:09
1
2,505
Sundeep
77,684,851
7,566,673
Cluster list elements into sublists if an element is greater than threshold
<p>I have a list which has <code>str</code>, <code>int</code>, and <code>float</code> elements.</p> <p>I want to create sublists (cluster elements) in such a way that if any numeric element is greater than threshold (here threshold is 3), a cluster will be created containing the previous elements. Code and expected output is given below.</p> <pre><code>L = [&quot;this is&quot;, &quot;my&quot;, 1, &quot;first line&quot;, 4, &quot;however this&quot;, 3.5, &quot;is my last line&quot;, 4] out = [] temp = [] for x in L: if isinstance(x, str) or x &lt;3: temp.append(x) else: out.append(temp) temp = [] print(out) [['this is', 'my', 1, 'first line'], ['however this'], ['is my last line']] </code></pre> <p>I want to check how I can cluster in more advanced ways, such as <code>itertools.groupby</code> or <code>filter</code> or any other advanced methods?</p>
<python><python-3.x><list>
2023-12-19 11:30:31
1
1,219
Bharat Sharma
77,684,767
10,595,871
Azure speech to text gives "The recordings URI contains invalid data"
<p>I am trying to transcribe the text from an audio, I'm using the code provided by azure: <a href="https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/master/samples/batch/python/python-client/main.py" rel="nofollow noreferrer">https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/master/samples/batch/python/python-client/main.py</a></p> <p>the problem is that it keeps telling me: Transcription failed: The recordings URI contains invalid data.</p> <p>I don't understand how to fix this issue. The file is one hour long (220mb).</p> <p>here is my transcription:</p> <pre><code> {'_self': None, 'content_container_url': None, 'content_urls': ['https://gruppofinservi7339283933.blob.core.windows.net/audio/giacomo3.wav?sv=xxx'], 'created_date_time': None, 'custom_properties': None, 'dataset': None, 'description': 'Simple transcription description', 'display_name': 'Simple transcription', 'last_action_date_time': None, 'links': None, 'locale': 'it-IT', 'model': None, 'project': None, 'properties': {'channels': None, 'destination_container_url': None, 'diarization': {'speakers': {'max_count': 30, 'min_count': 1}}, 'diarization_enabled': True, 'display_form_word_level_timestamps_enabled': None, 'duration': None, 'email': None, 'error': None, 'language_identification': None, 'profanity_filter_mode': None, 'punctuation_mode': None, 'time_to_live': None, 'word_level_timestamps_enabled': None}, 'status': None} </code></pre> <p>Thanks!</p>
<python><azure><speech-to-text>
2023-12-19 11:17:09
1
691
Federicofkt
77,684,764
883,164
Getting this message on langchain: The FileType.UNK file type is not supported in partition. Has anyone figured this out?
<p>Getting this message on langchain: The FileType.UNK file type is not supported in partition.</p> <p>I haven't found much info on the web. The folder only contains PDF documents, nothing else.</p> <p>This is what I'm running:</p> <pre><code>from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import Milvus from langchain.chains import ConversationalRetrievalChain from langchain.document_loaders import UnstructuredFileLoader # Recursive loader to get files loader = UnstructuredFileLoader(mydocs, recursive=True) docs = loader.load() </code></pre> <p>This is what I'm getting:</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[3], line 10 8 # Recursive loader to get files 9 loader = UnstructuredFileLoader(mydocs, recursive=True) ---&gt; 10 docs = loader.load() File ~/anaconda3/lib/python3.11/site-packages/langchain/document_loaders/unstructured.py:86, in UnstructuredBaseLoader.load(self) 84 def load(self) -&gt; List[Document]: 85 &quot;&quot;&quot;Load file.&quot;&quot;&quot; ---&gt; 86 elements = self._get_elements() 87 self._post_process_elements(elements) 88 if self.mode == &quot;elements&quot;: File ~/anaconda3/lib/python3.11/site-packages/langchain/document_loaders/unstructured.py:172, in UnstructuredFileLoader._get_elements(self) 169 def _get_elements(self) -&gt; List: 170 from unstructured.partition.auto import partition --&gt; 172 return partition(filename=self.file_path, **self.unstructured_kwargs) File ~/anaconda3/lib/python3.11/site-packages/unstructured/partition/auto.py:489, in partition(filename, content_type, file, file_filename, url, include_page_breaks, strategy, encoding, paragraph_grouper, headers, skip_infer_table_types, ssl_verify, ocr_languages, languages, detect_language_per_element, pdf_infer_table_structure, pdf_extract_images, pdf_image_output_dir_path, xml_keep_tags, data_source_metadata, metadata_filename, request_timeout, **kwargs) 487 else: 488 msg = &quot;Invalid file&quot; if not filename else f&quot;Invalid file {filename}&quot; --&gt; 489 raise ValueError(f&quot;{msg}. The {filetype} file type is not supported in partition.&quot;) 491 for element in elements: 492 element.metadata.url = url ValueError: Invalid file .... The FileType.UNK file type is not supported in partition.``` </code></pre>
<python>
2023-12-19 11:16:43
1
570
biogeek
77,684,593
2,813,085
Is there a way to retain keys in Polars left join
<p>Is there a way to retain both the left and right join keys when performing a left join using the Python Polars library? Currently it seems that only the left join key is retained but the right join key gets dropped.</p> <p>Please see example code below:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;foo&quot;: [1, 2, 3], &quot;bar&quot;: [6.0, 7.0, 8.0], &quot;ham&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], } ) other_df = pl.DataFrame( { &quot;apple&quot;: [&quot;x&quot;, None, &quot;z&quot;], &quot;ham&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;d&quot;], } ) df.join(other_df, on=&quot;ham&quot;, how=&quot;left&quot;) </code></pre> <p>In other data manipulation libraries this is possible for example using the <code>R dplyr</code> library you can do the below or even in standard <code>SQL</code> we can access the right join key in the <code>SELECT</code> clause.</p> <pre><code>library(dplyr) df &lt;- data.frame( foo = c(1, 2, 3), bar = c(6.0, 7.0, 8.0), ham = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) ) other_df &lt;- data.frame( apple = c(&quot;x&quot;, NA, &quot;z&quot;), ham = c(&quot;a&quot;, &quot;b&quot;, &quot;d&quot;) ) df %&gt;% left_join(other_df, by = c(&quot;ham&quot; = &quot;ham&quot;), suffix = c(&quot;&quot;, &quot;_right&quot;), keep = TRUE) </code></pre>
<python><dataframe><left-join><python-polars>
2023-12-19 10:45:01
2
644
jeremyh
77,684,402
7,766,158
Django : Serializer validation prevents my code from updating an existing object
<p>I have a Django project that get some user data and store them in a database. I want my function to handle both <code>Create</code> and <code>Update</code> with the same method, so I created a view that inherit from <code>UpdateAPIView</code></p> <pre><code>class UserList(generics.UpdateAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer def put(self, request, *args, **kwargs): raw_user_serializer: RawUserSerializer = self.get_serializer(data=request.data) raw_user_serializer.is_valid(raise_exception=True) # Fail when user already exists raw_user: RawUser = RawUser(**raw_user_serializer.validated_data) // Some custom computing # Create or update raw_user self.perform_update(raw_user_serializer) return JsonResponse({'user_id':raw_user.id}, status = 201) class UserDetail(generics.RetrieveAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer </code></pre> <p>I think that the use of a <code>UpdateAPIView</code> and the function <code>perform_update()</code> is good. It works well when the user doesn't exist already, but when I try to create a new user with the same primary key, I get : <code>Bad Request: /api/profiling/users/</code>, with the following response :</p> <pre><code>{ &quot;id&quot;: [ &quot;raw user with this id already exists.&quot; ] } </code></pre> <p>It look like it fails on <code>raw_user_serializer.is_valid(raise_exception=True)</code> instruction. How can I solve my issue ? (while keeping the validation of my object)</p>
<python><django>
2023-12-19 10:12:17
1
1,931
Nakeuh
77,684,346
219,976
Type checking in pycharm for class-decorated property
<p>I'm using PyCharm 2023.2.3 (Community Edition) for developing. There's a script:</p> <pre><code>from functools import cached_property from collections.abc import Callable from typing import TypeVar, Generic, Any, overload, Union T = TypeVar(&quot;T&quot;) class result_property(cached_property, Generic[T]): def __init__(self, func: Callable[[Any], T]) -&gt; None: super().__init__(func) def __set_name__(self, owner: type[Any], name: str) -&gt; None: super().__set_name__(owner, name) @overload def __get__(self, instance: None, owner: Union[type[Any], None] = None) -&gt; 'result_property[T]': ... @overload def __get__(self, instance: object, owner: Union[type[Any], None] = None) -&gt; T: ... def __get__(self, instance, owner=None): return super().__get__(instance, owner) def func_str(s: str) -&gt; None: print(s) class Foo: @result_property def prop_int(self) -&gt; int: return 1 foo = Foo() func_str(foo.prop_int) # type error is expected here </code></pre> <p>PyCharm types checker reports it's correct. However I except it reports a type error on the last line. If I run mypy check on this script, it reports:</p> <pre><code>tmp.py:38: error: Argument 1 to &quot;func_str&quot; has incompatible type &quot;int&quot;; expected &quot;str&quot; [arg-type] Found 1 error in 1 file (checked 1 source file) </code></pre> <p>Why Pycharm reports it's ok?<br /> Is it possible to somehow modify the script for PyCharm to report type error in this situation as well?</p>
<python><pycharm><python-decorators><python-typing>
2023-12-19 10:04:03
1
6,657
StuffHappens
77,684,053
10,468,528
"Module does not explicitly reexport attribute" Mypy implicit-reexport
<p>I have a python library of the following structure:</p> <pre><code>module &gt; module_namespace __init__.py MyClass.py &gt; asyncio __init__.py MyClass.py </code></pre> <p>In the <strong>ini</strong>.py files I have explicitly exported the classes like:</p> <pre><code># __init__.py from .MyClass import ClassType __all__ = [&quot;ClassType&quot;] </code></pre> <p>Then, I import it from another application</p> <pre><code>from module_namespace import ClassType # Or # from module_namespace.asyncio import ClassType </code></pre> <p>However, mypy complains that the module does not reexport &quot;ClassType&quot;. I have a <code>mypy.ini</code> with <code>implicit_reexport=false</code>, which I don't want to change. And my understanding was that adding the <code>__all__</code> was enough to reexport the symbols. Anyone knows what I could be doing wrong?</p>
<python><mypy><python-module><python-typing>
2023-12-19 09:15:17
0
395
Miguel Wang
77,684,046
955,885
How to access rest point from Python that requires a google sign on?
<p>I am trying to do a:</p> <pre><code>response = requests.post(url, json=payload) </code></pre> <p>call in Python to a site, but get &quot;unauthorized&quot; response. If I use a browser, I get redirected first to &quot;https://accounts.google.com/v3/signin/identifier/...&quot; to authenticate (which I do) before allowed on website. Is there a way I can do this programmatically through Python. Ideally without browser? Thanks ahead for any suggestions!</p>
<python><python-3.x><rest><oauth-2.0><google-api-python-client>
2023-12-19 09:13:24
1
727
Nicko Po
77,684,036
7,566,673
summing up elements between two strings in list
<p>I have a list of <code>str</code> and <code>int</code> elements as given below</p> <pre><code>L = [1, &quot;a&quot;, &quot;b&quot;, 1, 2, 1, &quot;d&quot;, 1, &quot;e&quot;, 4, 5, &quot;f&quot;, &quot;g&quot;, 2] </code></pre> <p>I want to sum up numbers found between two string elements so resultant output is excpected like this.</p> <pre><code>[1, &quot;a&quot;, &quot;b&quot;, 4, &quot;d&quot;, 1, &quot;e&quot;, 9, &quot;f&quot;, &quot;g&quot;, 2] </code></pre> <p>I would like to solve this in a pythonic way. How this can be done?</p>
<python>
2023-12-19 09:12:22
2
1,219
Bharat Sharma
77,683,855
2,803,777
Can I use a more pythonic way for my conditional array operations?
<p>In Python using <code>numpy</code> I have to do some iterations over a <code>numpy</code> 2D array. I boiled down the original problem to its essentials:</p> <pre><code>f = np.array([[0, 0, 0, 0, 0, 0, 0], [0, 10, 22, 30, 40, 50, 0], [0, 11, 22, 33, 44, 55, 0], [0, 0, 0, 0, 0, 0, 0]]) u = np.array([[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, -1, 1], [1, 1, -1, -1, -1, 1, 1], [1, 1, 1, 1, 1, 1, 1]]) x = np.zeros_like(f) for i in range(1,u.shape[0]-1): for j in range(1,u.shape[1]-1): if u[i,j] &gt; 0: x[i,j] = u[i,j]*(f[i,j]-f[i,j-1]) else: x[i,j] = -u[i,j]*(f[i,j+1]-f[i,j]) </code></pre> <p>In this iteration I have to iterate over all 2D indices. Is there a more elegant way? If there would be no condition on u I would just write:</p> <pre><code>y = np.zeros_like(f) y[1:-1, 1:-1] = u[1:-1, 1:-1] * (f[1:-1, 1:-1] - f[1:-1, :-2]) </code></pre> <p>which gives the same result, given u&gt;0</p> <p>I was thinking to use <code>m = ma.masked_array(u, (u &gt; 0)).mask</code> somehow, but by indexing like <code>f[m]</code> I get only a 1D array, so I get the 2D structure lose. Is there a more Pythonic way to carry out this iteration?</p>
<python><numpy>
2023-12-19 08:42:16
2
1,502
MichaelW
77,683,810
21,049,944
fastest way to use cmaps in Polars
<p>I would like to create a column of color lists of type [r,g,b,a] from another float column using a matplotlib cmap.</p> <p>Is there a faster way then:</p> <pre><code>data.with_columns( pl.col(&quot;floatCol&quot;)/100) .map_elements(cmap1) ) </code></pre> <p>Minimal working example:</p> <pre><code>import matplotlib as mpl import polars as pl cmap1 = mpl.colors.LinearSegmentedColormap.from_list(&quot;GreenBlue&quot;, [&quot;limegreen&quot;, &quot;blue&quot;]) data = pl.DataFrame( { &quot;floatCol&quot;: [12,135.8, 1235.263,15.236], &quot;boolCol&quot;: [True, True, False, False] } ) data = data.with_columns( pl.when( pl.col(&quot;boolCol&quot;).not_() ) .then( mpl.colors.to_rgba(&quot;r&quot;) ) .otherwise( ( pl.col(&quot;floatCol&quot;)/100) .map_elements(cmap1) ) .alias(&quot;c1&quot;) ) </code></pre>
<python><python-polars>
2023-12-19 08:33:22
1
388
Galedon
77,683,734
3,336,423
Prevent Ctrl+C sent to child process being received by parent process too
<p>Consider this very simple Python program:</p> <pre><code>import subprocess import time import signal import sys if __name__ == '__main__': process = subprocess.Popen( [&quot;timeout&quot;,&quot;5&quot;] ) time.sleep(1) print(&quot;PID is &quot; + str(process.pid)) process.send_signal( signal.CTRL_C_EVENT ) time.sleep(1) print(&quot;Done&quot;) sys.exit(0) </code></pre> <p>When I run this (under Windows), console outputs:</p> <pre><code> File &quot;src\caid_utl\test\test_colcon_sigint.py&quot;, line 35, in &lt;module&gt; time.sleep(1) KeyboardInterrupt ^C </code></pre> <p>&quot;Done&quot; is not printed, parent process (this program) exited due to Ctrl+C being sent to child process.</p> <p>How to get rid of that?</p> <p>I see that catching <code>KeyboardInterrupt</code> fixes the issue:</p> <pre><code>if __name__ == '__main__': process = subprocess.Popen( [&quot;timeout&quot;,&quot;5&quot;] ) time.sleep(1) try: print(&quot;PID is &quot; + str(process.pid)) process.send_signal( signal.CTRL_C_EVENT ) time.sleep(1) except KeyboardInterrupt: print(&quot;Ignored Ctrl+C from parent&quot;) pass print(&quot;Done&quot;) sys.exit(0) </code></pre> <p>But it makes no sense as the current program did not receive any keyboard interruption. Is there no alternative to this? A way to isolate parent and child processes for good?</p>
<python>
2023-12-19 08:16:47
0
21,904
jpo38
77,683,731
23,106,915
Smoother Tkinter GUI
<p>So instead of tkinter, I am using customtkinter for my python GUIs. So what I am trying to do is whenever a user clicks a button in my project the frame changes to another frame</p> <p><strong>Example:</strong></p> <pre><code>def analytics_win(): if frame_main_win.winfo_ismapped(): frame_main_win.pack_forget() elif encrypt_frame_win.winfo_ismapped(): encrypt_frame_win.pack_forget() elif decrypt_frame_win.winfo_ismapped(): decrypt_frame_win.pack_forget() elif keys_frame_win.winfo_ismapped(): keys_frame_win.pack_forget() elif settings_frame_win.winfo_ismapped(): settings_frame_win.pack_forget() analytics_frame_win.pack() </code></pre> <p>In this method I have observed a lot of delay as well as creation and removal of tkinter widgets when the button is clicked.</p> <p><strong>Suggestion:</strong> Is there a better way to perform this action making tkinter frames to switch smoother and also make the project efficient.</p>
<python><user-interface><tkinter>
2023-12-19 08:16:00
1
546
AshhadDevLab
77,683,712
5,594,008
Refactoring multiple ifs
<p>My current code is this</p> <pre><code>class CounterFilters(TextChoices): publications_total = &quot;publications-total&quot; publications_free = &quot;publications-free&quot; publications_paid = &quot;publications-paid&quot; comments_total = &quot;comments-total&quot; votes_total = &quot;voted-total&quot; class SomeView: def get(self, request, format=None): user = request.user response_data = [] if &quot;fields&quot; in request.query_params: fields = request.GET.getlist(&quot;fields&quot;) for field in fields: if field == CounterFilters.publications_total: response_data.append({&quot;type&quot;: CounterFilters.publications_total, &quot;count&quot;: some_calculations1}) if field == CounterFilters.publications_free: response_data.append({&quot;type&quot;: CounterFilters.publications_free, &quot;count&quot;: some_calculations2}) if field == CounterFilters.publications_paid: response_data.append({&quot;type&quot;: CounterFilters.publications_paid, &quot;count&quot;: some_calculations3}) if field == CounterFilters.comments_total: response_data.append({&quot;type&quot;: CounterFilters.comments_total, &quot;count&quot;: some_calculations4}) if field == CounterFilters.votes_total: response_data.append({&quot;type&quot;: CounterFilters.votes_total, &quot;count&quot;: some_calculations5}) return Response(response_data) </code></pre> <p>Based on get-param fields (which is list) I fill response_data data with some calculations, different for each CounterFilters.value .</p> <p>I'm wondering, if there is a way to avoid this big amounts of ifs ?</p>
<python><django>
2023-12-19 08:12:13
2
2,352
Headmaster
77,683,522
1,799,528
Retrieve all documents related to a long text file from FAISS Vectorstore
<p>Sorry if this question is too basic. But is it possible to retrieve all documents in a vectorstore which are chunks of a larger text file before embedding? Are the documents in vectorstore related to each other according to their metadata or something like that or is it only the similarity between the vectors that related them together?</p> <p>This is my code :</p> <pre><code>from langchain.embeddings.openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings( deployment=&quot;embedding&quot;, model=&quot;text-embedding-ada-002&quot;, openai_api_base=&quot;https://test.openai.azure.com/&quot;, openai_api_type=&quot;azure&quot;, chunk_size=1) text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=50) loader = PyPDFLoader(&quot;data2/&quot;+file_item) documents = loader.load() texts = text_splitter.split_documents(documents) db = FAISS.from_documents( documents=texts, embedding=embeddings ) ... document_ids(&quot;based on pdf file name&quot;). this should return list of ids get_list_of_documents_from_faiss(document_ids). this should return the entire documents with the goal to construct some kind of text again from embedding </code></pre>
<python><embedding><langchain><large-language-model><faiss>
2023-12-19 07:34:42
0
1,376
gabi
77,683,462
988,279
Python SQLAlchemy upgrade from 1.X to 2.X...add_entity is no more working
<p>Here is my models.py</p> <pre><code>Base = declarative_base() class Service(Base): __tablename__ = 'Service' id = Column('ID', primary_key=True) f_Service_type_id = Column('f_ServiceTypeID', Integer) sType = relationship('ServiceType', primaryjoin=&quot;Service.f_Service_type_id == ServiceType.id&quot;, foreign_keys=&quot;[Service.f_Service_type_id]&quot;) class ServiceType(Base): __tablename__ = 'ServiceType' id = Column(&quot;ID&quot;, Integer, primary_key=True) name = Column(&quot;Name&quot;, String(100)) class Services2Produkt(Base): __tablename__ = 'services2produkt' service_id = Column(&quot;service_id&quot;, Integer, primary_key=True) service = relationship('Service', primaryjoin=&quot;Services2Produkt.service_id == Service.id&quot;, foreign_keys=&quot;[Services2Produkt.service_id]&quot; ) </code></pre> <p>The following &quot;add_entity&quot; stuff is working with SQLAlchemy 1.x.x.</p> <pre><code>def get_services_of_product(): query = session.query(Services2Produkt) query = query.add_entity(Service).join(&quot;service&quot;, &quot;sType&quot;) return [service for (s2p, service) in query.all()] </code></pre> <p>When upgrading to SQLAlchemy 2.x I get the following error:</p> <pre><code>sqlalchemy.exc.ArgumentError: Join target, typically a FROM expression, or ORM relationship attribute expected, got 'service'. </code></pre> <p>What has changed here? I can't find it in the changelog... And how do I get it fixed?</p>
<python><python-3.x><sqlalchemy>
2023-12-19 07:21:22
2
522
saromba
77,683,384
15,222,211
Python prometheus_client, how to get counter from the registry?
<p>How can I obtain a Counter object from the registry? In the example below, I am currently using the private argument to achieve this. Perhaps someone knows a more elegant way to accomplish this using only public methods?</p> <pre class="lang-py prettyprint-override"><code>from prometheus_client import CollectorRegistry, Counter, write_to_textfile registry = CollectorRegistry() name = &quot;NAME&quot; counter = Counter(name, &quot;DOCUMENTATION&quot;, registry=registry) counter.inc(2) # get a Counter object from the registry and increment value to 5 counter = registry._names_to_collectors.get(name) if isinstance(counter, Counter): counter.inc(3) write_to_textfile(&quot;counters.prom&quot;, registry) # # HELP NAME_total DOCUMENTATION # # TYPE NAME_total counter # NAME_total 5.0 # # HELP NAME_created DOCUMENTATION # # TYPE NAME_created gauge # NAME_created 1.7029690363513136e+09 </code></pre>
<python><prometheus>
2023-12-19 07:04:33
1
814
pyjedy
77,683,316
1,106,951
How to extract every 6th columns of a horizontally wide dataframe and append as rows into new cleaner dataframe
<p>I have a horizontally large CSV file with 606 columns. I have imported the csv into Pandas dataframe as</p> <pre><code>df = pd.read_csv(&quot;groups.csv&quot;) </code></pre> <p>but I need to change this weird horizontal length to a more readable vertically table. How can I extract every 6 columns in a loop from <code>df</code>, skip the header and append to <code>df_target</code></p> <pre><code>df_target = pd.DataFrame(columns=['GroupA', 'GroupB', 'GroupC','GroupD', 'GroupE', 'GroupF']) </code></pre> <p>As I said it is important to extract every 6 columns without headers</p>
<python><pandas>
2023-12-19 06:45:28
1
6,336
Behseini
77,682,954
2,360,477
Connecting to SQL Server in PySpark
<p>Currently, I've got my PySpark python script in a Docker container, which is using the jupyter/pyspark-notebook image.</p> <p>I've downloaded the Microsoft JDBC driver (<a href="https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver16" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver16</a>). I've copied and renamed mssql-jdbc-12.4.2.jre11.jar file to the tmp folder in my Docker container (mssql-jdbc.jar).</p> <p>However, my PySpark script keeps failing with the following error when I run it within the container &quot;py4j.protocol.Py4JJavaError: An error occurred while calling o26.jdbc. : java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver&quot;</p> <pre><code>spark_conf = SparkConf().setAppName(&quot;PortfolioPerformance&quot;).set(&quot;spark.jars&quot;, &quot;/tmp/mssql-jdbc.jar&quot;) # Create the SparkSession with the configured SparkConf. spark = SparkSession.builder.config(conf=spark_conf).getOrCreate() database_url = &quot;jdbc:sqlserver://my_server;databaseName=Fusion&quot; properties = { &quot;user&quot;: &quot;my_user&quot;, &quot;password&quot;: &quot;my_password!&quot;, &quot;driver&quot;: &quot;com.microsoft.sqlserver.jdbc.SQLServerDriver&quot; } df = spark.read.jdbc( url=database_url, table='SELECT * FROM my_query', properties=properties ) </code></pre> <p>Any ideas?</p>
<python><docker><pyspark>
2023-12-19 04:43:58
0
1,075
user172839
77,682,908
1,502,898
Python: patch sqlite3.Cursor to accept kwargs
<p>I'm trying to patch <code>sqlite3.Cursor</code> to accept any random kwargs and ignore them.</p> <p>My attempt is below. Essentially this is trying to patch <code>sqlite3.Cursor</code> with <code>TestCursor</code> which accepts <code>**kwargs</code>, and ignores them.</p> <pre class="lang-py prettyprint-override"><code># in my test code import sqlite3 from contextlib import contextmanager from unittest.mock import patch class TestCursor(sqlite3.Cursor): def __init__(self, **kwargs): super().__init__() @contextmanager def get_connection(): with patch('sqlite3.Cursor', TestCursor): conn = sqlite3.connect(':memory:') # do some database setup try: yield conn finally: conn.close() # The function I'm trying to test def send_query(): with get_connection() as conn: #offending line cur = conn.cursor(row_factory='foo') cur.execute(&quot;SELECT * FROM table&quot;) data = cur.fetchall() return data send_query() </code></pre> <p>This gives me <code>TypeError: 'row_factory' is an invalid keyword argument for this function</code></p> <p>Where am I going wrong?</p> <p>I also tried patching <code>conn</code> directly, but it complains that <code>conn.cursor</code> is read only.</p>
<python><sqlite><pytest>
2023-12-19 04:23:44
1
1,607
jprockbelly
77,682,444
7,796,211
PyGame: Use SDL2 to render a pixel
<p>I want to render a singular green pixel in PyGame with SDL2. This is my current code:</p> <pre class="lang-py prettyprint-override"><code>import pygame import pygame._sdl2 SCREEN_W = 800 SCREEN_H = 800 pygame.init() pygame_screen = pygame.display.set_mode((SCREEN_W, SCREEN_H), vsync=0, flags=pygame.SCALED) window = pygame._sdl2.Window.from_display_module() renderer = pygame._sdl2.Renderer.from_window(window) renderer.draw_color = (0, 255, 0, 255) # Set the draw color to green clock = pygame.time.Clock() scale_factor = 1 # Create a green surface green_pixel = pygame.Surface((scale_factor, scale_factor)) green_pixel.fill((0, 255, 0, 255)) use_sdl2 = True while True: msec = clock.tick(60) pygame_screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if use_sdl2: renderer.clear() dest_rect = pygame.rect.Rect(100, 100, scale_factor, scale_factor) renderer.blit(green_pixel, dest_rect) renderer.present() else: dest_rect = pygame.rect.Rect(100, 100, scale_factor, scale_factor) pygame_screen.blit(green_pixel, dest_rect) pygame.display.flip() </code></pre> <p>This gives the following error:</p> <pre><code>Traceback (most recent call last): File &quot;/home/harald-yoga/Documents/Projects/Python/game-engine/src/game_engine/main.py&quot;, line 37, in &lt;module&gt; renderer.blit(green_pixel, dest_rect) File &quot;src_c/cython/pygame/_sdl2/video.pyx&quot;, line 1166, in pygame._sdl2.video.Renderer.blit File &quot;src_c/cython/pygame/_sdl2/video.pyx&quot;, line 1179, in pygame._sdl2.video.Renderer.blit TypeError: source must be drawable </code></pre> <p>The non-SDL2 version (use_sdl2 = False) works fine and renders a green pixel at x: 100, y: 100. What am I doing wrong with the SDL version?</p>
<python><pygame>
2023-12-19 00:56:49
1
418
Thegerdfather
77,682,374
5,942,100
transform and replace values in existing column IF multiple matching values exist using pandas
<p>I have two datasets: A and B.</p> <p>If dataset A's <code>year</code>, <code>ID</code>, <code>delivery</code>, <code>type</code>, and <code>vendor</code> columns all match with dataset B's <code>Tags</code>, <code>ID</code>, <code>qtr</code>, <code>TYPE</code>, and <code>msc</code> columns, then I want to replace the <code>project_id</code> of the matching row in dataset A with the <code>Project Name</code> from the corresponding row in dataset B. Otherwise, I don't want to change the <code>project_id</code> in A.</p> <p>dataset A:</p> <pre><code>Year ID deliv Gen type vendor project_id 2022 BR Q2 2022 L aa d BR2 aa1 Q2 2022 - L 2022 BR Q2 2022 L dd d BR2 dd1 Q2 2022 - L 2022 BR Q2 2022 L dd d BR2 dd2 Q2 2022 - L 2022 BR Q3 2022 L bb d BR2 bb1 Q3 2022 - L 2022 BR Q4 2022 L aa d BR2 aa1 Q4 2022 - L 2022 BR Q4 2022 L dd nd BR2 dd1 Q4 2022 - L </code></pre> <p>dataset B:</p> <pre><code>Project Name Tags ID qtr TYPE msc NUM BB H_AA01 Q4 2022 2022 BOLOL Q4 2022 aa d 01 BR2 H_DD_nd02 Q4 2022 2022 BR Q4 2022 dd nd 02 BR2 BB01 Q3.2022 2022 BR Q3 2022 bb d 01 BR2 H_DD01 Q2 2022 2022 BR Q2 2022 dd d 01 BR2 H_DD02 Q2 2022 2022 BR Q2 2022 dd d 02 BR2 H_AA01 Q2 2022 2022 BR Q2 2022 aa d 01 </code></pre> <p>desired result:</p> <pre><code>Year ID delivery Gen type vendor project_id 2022 BR Q2 2022 L aa d BR2 H_AA01 Q2 2022 2022 BR Q2 2022 L dd d BR2 H_DD01 Q2 2022 2022 BR Q2 2022 L dd d BR2 H_DD02 Q2 2022 2022 BR Q3 2022 L bb d BR2 BB01 Q3.2022 2022 BR Q4 2022 L aa d BR2 aa1 Q4 2022 - L 2022 BR Q4 2022 L dd nd BR2 H_DD_nd02 Q4 2022 </code></pre> <p>Here is my current attempt:</p> <pre><code>df_merged = pd.merge(df_A, df_B[['Project Name', 'Tags', 'ID', 'qtr', 'TYPE', 'msc']], how='left', left_on=['Year', 'ID', 'delivery', 'type', 'vendor'], right_on=['Tags', 'ID', 'qtr', 'TYPE', 'msc']) # Replacing 'project_id' in A with 'Project Name' from B where there is a match df_merged['project_id'] = df_merged['Project Name'].combine_first(df_merged['project_id']) # Dropping unnecessary columns from the merge df_final = df_merged.drop(['Project Name', 'Tags', 'qtr', 'TYPE', 'msc'], axis=1) </code></pre> <p>However, the above script blows up my dataset, creating unnecessary rows and multiple columns.</p> <p>The final output should have the same enumber of rows and columns as the original dataset. The only difference is that the <code>project_id</code> column is being updated. How do I properly perform this operation?</p>
<python><pandas>
2023-12-19 00:24:09
2
4,428
Lynn
77,682,075
189,270
splitlines() of lldb SBValue.GetSummary() result doesn't work?
<p>I have a program that supplies context dependent information that I'd like to display in lldb. For illustration purposes, imagine that program is as simple as:</p> <pre><code>#include &lt;stdio.h&gt; const char * get_perform_stack() { return &quot;CARP-AND-RETURN-IF-VSAM-ERROR\nMAIN\n&quot;; } int main() { return 0; } </code></pre> <p>In an lldb session, after breaking in main, I can run:</p> <pre><code>(lldb) expression -l c -- (char *)get_perform_stack() (char *) $2 = 0x00000000004005e8 &quot;CARP-AND-RETURN-IF-VSAM-ERROR\nMAIN\n&quot; </code></pre> <p>I'd like to make an lldb python script that calls this function, but displays the results, in this case, as two lines:</p> <pre><code>CARP-AND-RETURN-IF-VSAM-ERROR MAIN </code></pre> <p>Given such a string with newlines in it, I can tokenize it in pure python with something like:</p> <pre><code>stack = &quot;CARP-AND-RETURN-IF-VSAM-ERROR\nMAIN\n&quot; print(type(stack)) print(stack) a = stack.splitlines() for f in a: print(f) </code></pre> <p>which gives:</p> <pre><code># python3 ./sp &lt;class 'str'&gt; CARP-AND-RETURN-IF-VSAM-ERROR MAIN CARP-AND-RETURN-IF-VSAM-ERROR MAIN </code></pre> <p>I'm also able to obtain this result using lldb python code, but if I put in the same sort of tokenizing code, it doesn't work within my lldb python script. Example:</p> <pre><code>import lldb # (lldb) command script import ~/lldb/cobbt.py # (lldb) script cobbt.main() def main() -&gt; None: debugger = lldb.target.GetDebugger() exprOptions = lldb.SBExpressionOptions() c = lldb.SBLanguageRuntime_GetLanguageTypeFromString(&quot;c&quot;) exprOptions.SetLanguage( c ) result = lldb.target.EvaluateExpression(&quot;(char *)get_perform_stack()&quot;, exprOptions) print(type(result)) s = result.GetSummary() print(type(s)) print(s) stack = s.splitlines() for f in stack: print(f) </code></pre> <p>The splitlines() doesn't seem to do anything, and I get a single element back:</p> <pre><code>(lldb) command script import ~/lldb/cobbt.py (lldb) script cobbt.main() &lt;class 'lldb.SBValue'&gt; &lt;class 'str'&gt; &quot;CARP-AND-RETURN-IF-VSAM-ERROR\nMAIN\n&quot; &quot;CARP-AND-RETURN-IF-VSAM-ERROR\nMAIN\n&quot; (lldb) </code></pre> <p>In both cases, python seems to think that the result that I'm trying to tokenize is a &quot;class str&quot;, but the behaviour within lldb's python interpreter is different than that of standalone python, and I'm not sure what that difference is, or how to fix my code to display the results separately?</p> <p>For reference: I'm running lldb version 14.0.6, built with python3 scripting support.</p>
<python><lldb>
2023-12-18 22:30:27
1
8,350
Peeter Joot
77,682,050
2,749,393
Is there an API call to find out the random seed used for the Python `hash()` function?
<p>I know that if the <code>PYTHONHASHSEED</code> environment variable is not set or set to <code>&quot;random&quot;</code> then the hash function (used for <code>set</code>, <code>frozenset</code>, and <code>dict</code>) is salted with a random number.</p> <p>So I want to know if it is possible to find out what value is used for a given run of the program.</p> <p>For context, my Python program generates some output and I want to ensure that it is deterministic for each run of the program. At different points the program iterates over the values in various <code>set</code> and <code>frozenset</code> objects. For the cases where the order of iteration will effect the generated output I first sort the elements before iterating. But the code is fairly complicated so it is not always obvious which cases need sorting and which cases don't, and I don't want to sort unnecessarily.</p> <p>So I want to write some unit tests to catch and fix the cases where I need to add a sorted iteration. In order to do this I plan to run the program using <code>multiprocessing.Process</code> (in <code>spawn</code> mode) where I explicitly set the <code>PYTHONHASHSEED</code> environment variable.</p> <p>But to do this I need determine the seed values that produced the different output for the same input. But I haven't found any documented API that can tell me what random seed was used for a given run of the program.</p>
<python>
2023-12-18 22:22:40
1
930
daveraja
77,681,935
1,473,517
Can this simpler case of the 2d maximum submatrix problem be solved more quickly?
<p>Given an n by m matrix of integers, there is a well known problem of finding the submatrix with maximum sum. This can be solved with a 2d version of <a href="https://en.wikipedia.org/wiki/Maximum_subarray_problem" rel="nofollow noreferrer">Kadane's algorithm</a>. An explanation of an O(nm^2) time algorithm for the 2D version which is based on Kadane's algorithm can be found <a href="https://www.geeksforgeeks.org/maximum-sum-submatrix/" rel="nofollow noreferrer">here</a>.</p> <p>I am interested in a simpler version where only submatrices that include the top left cell of the matrix are considered. Can this version be solved faster in O(nm) time? If so, how can you do it? I would also like to see what the optimal submatrix is, not just its sum.</p>
<python><algorithm>
2023-12-18 21:51:49
2
21,513
Simd
77,681,902
1,423,938
MySQLdb call procedure with long name
<p>In the <a href="https://mysqlclient.readthedocs.io/user_guide.html#cursor-objects" rel="nofollow noreferrer">documentation for callproc</a>, it uses the procedure name prepended by an underscore and appended with an underscore and the parameter's position. When calling a stored procedure with a long name, this causes a 3061 error <code>User variable name '_extremely_super_duper_long_procedure_name_gets_used_here_0' is illegal</code>. In this specific case, the generated name is 65 characters long (and I believe the maximum length is <a href="https://dev.mysql.com/doc/refman/8.0/en/identifier-length.html" rel="nofollow noreferrer">64 for user-defined variables</a>.</p> <p>I'm looking for a workaround to this issue that won't require me to rename all of the stored procedures in my database. I'm working on a one-off project to do a complex data migration, so modifying and retesting a bunch of production stored procedures and all of the applications that call them is not an option.</p>
<python><mysql><stored-procedures><database-cursor>
2023-12-18 21:44:53
1
2,433
Dewey Vozel
77,681,797
1,185,254
How to mock a constant value
<p>I have a structure like so:</p> <pre><code>mod1 ├── mod2 │ ├── __init__.py │ └── utils.py └── tests └── test_utils.py </code></pre> <p>where</p> <ul> <li><code>__init__.py</code>:</li> </ul> <pre><code>CONST = -1 </code></pre> <ul> <li><code>utils.py</code>:</li> </ul> <pre><code>from mod1.mod2 import CONST def mod_function(): print(CONST) </code></pre> <ul> <li><code>test_utils.py</code>:</li> </ul> <pre><code>from mod1.mod2.utils import mod_function def test_mod_function(mocker): mock = mocker.patch(&quot;mod1.mod2.CONST&quot;) mock.return_value = 1000 mod_function() </code></pre> <p>I'm using <a href="https://docs.pytest.org/en/7.4.x/" rel="nofollow noreferrer"><code>pytest</code></a> with <a href="https://pypi.org/project/pytest-mock/" rel="nofollow noreferrer"><code>mocker</code></a>.</p> <p>By running <code>python -m pytest -s ./mod1/tests</code> I expected to see <code>1000</code> as an output, but got <code>-1</code>. Why?</p> <p>How to patch a constant from the <code>__init__.py</code> file?</p>
<python><pytest><python-mock><pytest-mock>
2023-12-18 21:22:37
1
11,449
alex
77,681,786
1,804,173
Is it possible to statically wrap/derive a parameter from another paramerter in pytorch?
<p>I often run into situations where I want to train a parameter, but that parameter only gets used by the model in a transformed form. For example, think of a simple scalar parameter defined on <code>(-∞, +∞)</code>, but the model only wants to use that parameter wrapped in a sigmoid, to constrain it to <code>(0, 1)</code> e.g. to model a probability. A naive attempt to implemented such a wrapped/derived parameter would be:</p> <pre class="lang-py prettyprint-override"><code>class ConstrainedModel(torch.nn.Module): def __init__(self): super().__init__() self.x_raw = torch.nn.Parameter(torch.tensor(0.0)) self.x = torch.nn.functional.sigmoid(self.x_raw) def forward(self) -&gt; torch.Tensor: # An actual model of course would use self.x in a more sophisticated way... return self.x </code></pre> <p>The model is only really interested in using the constrained/transformed <code>self.x</code>, e.g. because it is semantically more relevant than the underlying/unstransformed <code>self.x_raw</code>. In a sense, the implementation tries to hide away <code>self.x_raw</code> because it is more confusing to think in this unconstrained parameter.</p> <p>However training this model with something like this...</p> <pre class="lang-py prettyprint-override"><code>def main(): model = ConstrainedModel() opt = torch.optim.Adam(model.parameters()) loss_func = torch.nn.MSELoss() y_truth = torch.tensor(0.9) for i in range(10000): y_predicted = model.forward() loss = loss_func.forward(y_predicted, y_truth) print(f&quot;iteration: {i+1} loss: {loss.item()} x: {model.x.item()}&quot;) loss.backward() opt.step() opt.zero_grad() </code></pre> <p>... will fail in the second iteration with the infamous error:</p> <blockquote> <p>RuntimeError: Trying to backward through the graph a second time [...]</p> </blockquote> <p>Note that the reason here is different from the common causes (<a href="https://stackoverflow.com/q/48274929/1804173">1</a>, <a href="https://stackoverflow.com/q/61015728/1804173">2</a>) of this error: In this case the issue is hidden by the fact that the model has wrapped/derived <code>self.x</code> from <code>self.x_raw</code> in its constructor, which leads to holding a reference to something from the previous backwards pass.</p> <p>My standard work-around is to make all wrapping repeatedly/dynamically only inside <code>forward</code>, i.e., this would work:</p> <pre class="lang-py prettyprint-override"><code>class ConstrainedModelWorkAround(torch.nn.Module): def __init__(self): super().__init__() self.x_raw = torch.nn.Parameter(torch.tensor(0.0)) def forward(self) -&gt; torch.Tensor: x = torch.nn.functional.sigmoid(self.x_raw) return x </code></pre> <p>But now the model only exposes <code>model.x_raw</code> and lacks the more human-friendly <code>model.x</code> representation of the parameter, which would be nicer to work with inside the model code, and which would also be more convenient to monitor during training (e.g. in a tensorboard display).</p> <p>I'm wondering if I'm missing a trick how to achieve a kind of &quot;static&quot; wrapping of parameters instead?</p>
<python><pytorch>
2023-12-18 21:19:11
1
27,316
bluenote10
77,681,757
643,920
determine availability (and price?) of 50k domains
<p>I have a list of 50k possible domain names. I'd like to find out which ones are available and if possible how much they cost. the list looks like this</p> <pre><code>presumptuous.ly principaliti.es procrastinat.es productivene.ss professional.ly profession.ally professorshi.ps prognosticat.es prohibitioni.st </code></pre> <p>I've tried whois but that runs way too slow to complete in the next 100 years.</p> <pre><code>def check_domain(domain): try: # Get the WHOIS information for the domain w = whois.whois(domain) if w.status == &quot;free&quot;: return True else: return False except Exception as e: print(&quot;Error: &quot;, e) print(domain+&quot; had an issue&quot;) return False def check_available(matches): print('checking availability') available=[] for match in matches: if(check_domain(match)): print(&quot;found &quot;+match+&quot; available!&quot;) available.append(match) return available </code></pre> <p>I've also tried names.com/names bulk upload tool but that doesn't seem to work at all.</p> <p>How do I determine the availability of these domains?</p>
<python><linux><dns><whois>
2023-12-18 21:09:50
1
2,879
gnarbarian
77,681,622
1,181,452
OpenCV - motion detection in large video files
<p>I have large video files (over a few GB each) that I am trying detect motion on. I am using fairly basic OpenCV code in python with ROI to detect motion in a certain area of the video only. This works absolutely fine but takes absolutely ages to process large files. Is there any way to speed things up? I am simply just checking to see which file has motion detected in it and will not be outputting a video. The moment the first motion is detected the rest of the file is not checked.</p> <pre><code>import sys import cv2 video_path = “video.mp4” capture = cv2.VideoCapture(video_path) # Set the first frame as the reference background _, background = capture.read() # Define the region of interest (ROI) x, y, w, h = 1468, 1142, 412, 385 roi = (x, y, x + w, y + h) while capture.isOpened(): ret, frame = capture.read() if not ret: break # Extract the region of interest from the current frame frame_roi = frame[y:y + h, x:x + w] # Calculate the absolute difference between the ROI and the background diff = cv2.absdiff(background[y:y + h, x:x + w], frame_roi) gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY) # Check if motion is detected in the ROI (adjust threshold as needed) if cv2.countNonZero(thresh) &gt; 75: print(&quot;YES&quot;) break # Release the video capture object capture.release() </code></pre>
<python><opencv><ffmpeg><video-processing>
2023-12-18 20:35:40
0
3,296
M9A
77,681,610
6,168,639
Make a Django application pip-installable with pyproject.toml?
<p>I've got a couple Django projects that use the same 'shared application', which we will call <code>shared-django-app</code>. The shared application has it's own git repository.</p> <p>Recently, instead of having to run <code>git clone</code> after setting up the project to bring in the <code>shared-django-app</code> we have been considering adding it to the requirements file so it gets installed via <code>pip</code> when we install all the other requirements.</p> <p>Currently the <code>shared-django-app</code> repo has a structure like this:</p> <pre><code>|- .gitignore |- __init__.py |- models.py |- pyproject.toml |- README.md |- views.py |- # other flat files |- static/ |- shared-django-app |- # static files |- templates/ |- shared-django-app |- # template files |- templatetags/ |- tests/ </code></pre> <p>I've read that you can install directly from a git repo and that's what I think we would like to try to do.</p> <p>I added this to a <code>pyproject.toml</code> and put it in the <code>shared-django-app</code> repository:</p> <pre><code>[build-system] requires = [&quot;setuptools&quot;] [project] name = &quot;django-shared-app&quot; version = &quot;1.0.0&quot; [packages] packages = [find_packages()] </code></pre> <p>But I'm getting an error when I run <code>pip install git+ssh://git@bitbucket.org:&lt;org&gt;/shared-django-app.git@dev</code> :</p> <pre><code> Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─&gt; [14 lines of output] error: Multiple top-level packages discovered in a flat-layout: ['static', 'templates', 'migrations', 'management', 'templatetags']. </code></pre> <p>What do I need to put in the <code>pyproject.toml</code> to make this a pip-installable package?</p>
<python><django><git><pip><python-packaging>
2023-12-18 20:33:16
0
722
Hanny
77,681,471
9,357,484
Unable to tag the POS of the text file
<p>I want to tag the parts of speech of a sentence. For this task I am using <a href="https://huggingface.co/flair/pos-english-fast" rel="nofollow noreferrer">pos-english-fast</a> model. If there was one sentence the model identified the tags for the pos. I created a data file where I kept all my sentences. The name of the data file is 'data1.txt'. Now if I try to tag the sentences on the data file it does not work.</p> <p>My code</p> <pre><code>from flair.models import SequenceTagger model = SequenceTagger.load(&quot;flair/pos-english&quot;) #Read the data from the data.txt with open('data1.txt') as f: data = f.read().splitlines() #Create a list of sentences from the data sentences = [sentence.split() for sentence in data] #Tag each sentence using the model tagged_sentences = [] for sentence in sentences: tagged_sentences.append(model.predict(sentence)) for sentence in tagged_sentences: print(sentence) </code></pre> <p>The error I received</p> <pre><code>AttributeError Traceback (most recent call last) &lt;ipython-input-16-03268ee0d9c9&gt; in &lt;cell line: 10&gt;() 9 tagged_sentences = [] 10 for sentence in sentences: ---&gt; 11 tagged_sentences.append(model.predict(sentence)) 12 for sentence in tagged_sentences: 13 print(sentence) 1 frames /usr/local/lib/python3.10/dist-packages/flair/data.py in set_context_for_sentences(cls, sentences) 1116 previous_sentence = None 1117 for sentence in sentences: -&gt; 1118 if sentence.is_context_set(): 1119 continue 1120 sentence._previous_sentence = previous_sentence AttributeError: 'str' object has no attribute 'is_context_set' </code></pre> <p>The snapshot of the errors <a href="https://i.sstatic.net/0h0ZC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0h0ZC.png" alt="enter image description here" /></a></p> <p>How could I resolve it?</p>
<python><nlp><tagging><huggingface><flair>
2023-12-18 20:02:17
1
3,446
Encipher
77,681,420
7,487,335
Python Playwright - How can I check that an element does not have an href?
<p>As part of my automated testing I'm trying to validate that an href is correctly removed from an element on the page.</p> <pre class="lang-py prettyprint-override"><code>from playwright.sync_api import Page, expect def test_reset_button(page: Page): page.goto(&quot;https://www.example.com&quot;) page.locator(&quot;#reset&quot;).click() expect(page.locator(&quot;#download&quot;)).not_to_have_attribute(&quot;href&quot;, value=&quot;&quot;) </code></pre> <p>In my example code above it ends up testing that the href attribute on the element is not equal to <code>value=&quot;&quot;</code>, which means that if <code>value=&quot;nonsense&quot;</code> this test will pass.</p> <p>Based on the <a href="https://playwright.dev/python/docs/api/class-locatorassertions#locator-assertions-not-to-have-attribute" rel="nofollow noreferrer"><code>not_to_have_attribute</code></a> documentation it seems that you have to pass a value to it to test that it does not have that specific value. I'd like to test that the &quot;href&quot; attribute does not exist on the element at all.</p> <p>How can I test for that?</p>
<python><playwright-python>
2023-12-18 19:48:23
2
4,400
Josh Correia
77,681,288
3,583,669
Getting dependency error installing chatterbot
<p>I am trying to create a chatbot using Python. When I run &quot;pip3 install chatterbot&quot; I get the error</p> <blockquote> <p>ERROR: Some build dependencies for preshed&lt;2.1.0,&gt;=2.0.1 from <a href="https://files.pythonhosted.org/packages/0b/14/c9aa735cb9c131545fc9e23031baccb87041ac9215b3d75f99e3cf18f6a3/preshed-2.0.1.tar.gz" rel="nofollow noreferrer">https://files.pythonhosted.org/packages/0b/14/c9aa735cb9c131545fc9e23031baccb87041ac9215b3d75f99e3cf18f6a3/preshed-2.0.1.tar.gz</a> conflict with the backend dependencies: wheel==0.42.0 is incompatible with wheel&gt;=0.32.0,&lt;0.33.0.</p> </blockquote> <p>Querying ChatGPT, it suggested that version constraint on the 'wheel' package specified by the 'preshed' dependency is causing the issue. It suggested I install 'preshed' first by running 'pip install preshed==2.0.1', then retry installing chatterbot, but I still get the same error. I even created a virtual environment and installed it there, but I got the same error. How do I resolve this?</p> <p>This is my pip list</p> <pre><code>Package Version ---------- ---------- certifi 2023.11.17 cymem 2.0.8 murmurhash 1.0.10 pip 23.3.2 </code></pre> <p>And I have python3 3.12.1 installed.</p> <p>Here's the full error</p> <pre><code>Collecting chatterbot Using cached ChatterBot-1.0.5-py2.py3-none-any.whl (67 kB) Collecting mathparse&lt;0.2,&gt;=0.1 (from chatterbot) Using cached mathparse-0.1.2-py3-none-any.whl (7.2 kB) Collecting nltk&lt;4.0,&gt;=3.2 (from chatterbot) Using cached nltk-3.8.1-py3-none-any.whl (1.5 MB) Collecting pint&gt;=0.8.1 (from chatterbot) Using cached Pint-0.23-py3-none-any.whl.metadata (8.1 kB) Collecting pymongo&lt;4.0,&gt;=3.3 (from chatterbot) Using cached pymongo-3.13.0.tar.gz (804 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Collecting python-dateutil&lt;2.8,&gt;=2.7 (from chatterbot) Using cached python_dateutil-2.7.5-py2.py3-none-any.whl (225 kB) Collecting pyyaml&lt;5.2,&gt;=5.1 (from chatterbot) Using cached PyYAML-5.1.2.tar.gz (265 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Collecting spacy&lt;2.2,&gt;=2.1 (from chatterbot) Using cached spacy-2.1.9.tar.gz (30.7 MB) Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─&gt; [15 lines of output] Collecting setuptools Using cached setuptools-69.0.2-py3-none-any.whl.metadata (6.3 kB) Collecting wheel&lt;0.33.0,&gt;0.32.0 Using cached wheel-0.32.3-py2.py3-none-any.whl (21 kB) Collecting Cython Using cached Cython-3.0.6-cp312-cp312-macosx_10_9_x86_64.whl.metadata (3.2 kB) Collecting cymem&lt;2.1.0,&gt;=2.0.2 Using cached cymem-2.0.8-cp312-cp312-macosx_10_9_x86_64.whl.metadata (8.4 kB) Collecting preshed&lt;2.1.0,&gt;=2.0.1 Using cached preshed-2.0.1.tar.gz (113 kB) 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' ERROR: Some build dependencies for preshed&lt;2.1.0,&gt;=2.0.1 from https://files.pythonhosted.org/packages/0b/14/c9aa735cb9c131545fc9e23031baccb87041ac9215b3d75f99e3cf18f6a3/preshed-2.0.1.tar.gz conflict with the backend dependencies: wheel==0.42.0 is incompatible with wheel&gt;=0.32.0,&lt;0.33.0. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─&gt; See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. </code></pre> <p>Thanks.</p>
<python><python-3.x><chatbot><chatterbot>
2023-12-18 19:17:45
2
313
Obi
77,681,239
9,983,652
How to find matching date index in multiple dataframes FASTER without using a loop?
<p>I am trying to find matching index for each date inside a multiple dataframes. if a date is found inside a dataframe, then move to next matching date. I am using a loop and it is very slow when dataframe is big. I am looking for a way to make it faster. Thanks for your help.</p> <p>Here is the way I am doing. It will be slow when dataframe is big and number of time to find is big. Here is just a simple example.</p> <p>I think using loop is not a good idea. However I have to check if a data is inside a dataframe or not. that is why I have to loop over each date. Thanks for your help.</p> <pre><code>df_tomatch_1=pd.DataFrame({'a':[1,2,3,4],'b':[10,20,30,40]}) df_tomatch_1.index=['2023-01-01 10:00','2023-01-01 11:00','2023-01-01 12:00','2023-01-01 13:00'] df_tomatch_1 a b 2023-01-01 10:00 1 10 2023-01-01 11:00 2 20 2023-01-01 12:00 3 30 2023-01-01 13:00 4 40 df_tomatch_2=pd.DataFrame({'c':[1,2,3,4],'d':[10,20,30,40]}) df_tomatch_2.index=['2023-01-02 10:00','2023-01-02 11:00','2023-01-02 12:00','2023-01-02 13:00'] df_tomatch_2 c d 2023-01-02 10:00 1 10 2023-01-02 11:00 2 20 2023-01-02 12:00 3 30 2023-01-02 13:00 4 4 time_tomatch=['2023-01-01 10:30','2023-01-01 12:30','2023-01-02 11:30'] def find_matched_date_index(df_tomatch_list,time_tomatch): indx_time=[] for date_str in time_tomatch: print(date_str) thisdate=pd.to_datetime(date_str) # print('this date is',date_str for ix_file,df in enumerate(df_tomatch_list): df.index=pd.to_datetime(df.index) if thisdate&gt;=df.index[0]-timedelta(days=0.01) and thisdate&lt;=df.index[-1]+timedelta(days=0.01): indx_found=df.index.get_indexer([thisdate],method='nearest')[0] indx_time.append([ix_file,indx_found]) break # exit for loop of dataframe return indx_time indx_time=find_matched_date_index([df_tomatch_1,df_tomatch_2],time_tomatch) print(indx_time) 2023-01-01 10:30 2023-01-01 12:30 2023-01-02 11:30 [[0, 1], [0, 3], [1, 2]] </code></pre>
<python><pandas>
2023-12-18 19:07:01
2
4,338
roudan
77,681,216
6,109,394
How to draw a tick in the mid of a line segment for Manim animation?
<h2>Problem</h2> <p>I want to mark two line segments as of equal length using ticks, like it is commonly done in geometry. <a href="https://i.sstatic.net/mo3xX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mo3xX.png" alt="enter image description here" /></a>.</p> <p>Despite my search effort, I failed to find a simple build-in solution for this.</p> <h2>My bulky solution</h2> <p>Of course, one can draw ticks directly if a line segment is given. For example, I do it as follows.</p> <pre class="lang-py prettyprint-override"><code>from manim import * class Test(Scene): def construct(self): line = Line() line.shift(3 * RIGHT + UP).rotate(35 * DEGREES) # Adding a tick at the center of the line as submobject size = 0.1 tick = Line (size * DOWN, size * UP) tick.rotate(line.get_angle()) tick.move_to(line.get_center()) line.add(tick) self.add(line) </code></pre> <h2>Question</h2> <p>What is the best practice to add ticks to Line object?</p>
<python><geometry><manim>
2023-12-18 19:02:58
0
621
pch
77,681,163
388,038
Python type hint name of enum
<p>In Python how can I type hint a variable to restrict it to the names in an Enum?</p> <pre class="lang-py prettyprint-override"><code>class DataFormatOptions(Enum): calibrate = &quot;Calibrate&quot; lrs = &quot;LRS&quot; custom = &quot;Custom&quot; _E = TypeVar(&quot;_E&quot;, bound=DataFormatOptions) class DataFormat(BaseModel): name: Type[_E] # &lt;- How do type hint this? It should be either &quot;calibrate&quot;, &quot;lrs&quot; or &quot;custom&quot; displayName: DataFormatOptions </code></pre> <p>I would like to reuse the names in the enum rather than just duplicating in a Literal such as</p> <pre class="lang-py prettyprint-override"><code>name: Literal[&quot;calibrate&quot;, &quot;lrs&quot;, &quot;custom&quot;] </code></pre>
<python><mypy><python-typing>
2023-12-18 18:50:50
1
3,182
André Ricardo
77,681,060
519,422
How to get JSON-formatted data from a website into a dataframe? I.e., extract values following identifiers?
<p>I asked <a href="https://stackoverflow.com/questions/77616133/python-pandas-how-to-get-data-from-a-website-into-a-dataframe-by-searching-for">this</a> question about how to extract data from a website into a Pandas (Python) dataframe. There was a very helpful answer that worked for a snippet of the data I posted directly into my code. The answer helped me understand that the data at the website are in JSON format. I thought I had things figured out, but have not yet been able to extract the data directly from the website. If someone could please help me figure out where I'm going wrong, I would be grateful.</p> <p>What I need is to get <strong>only</strong> property names and values in the Pandas data frame. For example:</p> <pre><code>CH4 Methane Property1 5.00000 Property2 20.00000 Property3 500.66500 Property4 100.00000 ... </code></pre> <p>First, here's the error I get when I use <a href="https://stackoverflow.com/questions/77616133/python-pandas-how-to-get-data-from-a-website-into-a-dataframe-by-searching-for">this</a> suggestion:</p> <p>I can't post the website link directly, but am hoping that it will be useful to post a more detailed example.</p> <pre><code>Traceback (most recent call last): File &quot;/Users/me , in &lt;module&gt; data = json.load(StringIO(rawstr)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/usr/local/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/__init__.py&quot;, line 293, in load return loads(fp.read(), ^^^^^^^^^^^^^^^^ File &quot;/usr/local/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/__init__.py&quot;, line 346, in loads return _default_decoder.decode(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/usr/local/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py&quot;, line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/usr/local/Cellar/python@3.11/3.11.4_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/decoder.py&quot;, line 355, in raw_decode raise JSONDecodeError(&quot;Expecting value&quot;, s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) </code></pre> <p>So I searched online for information on how to imported JSON-formatted data from a website and tried this:</p> <pre><code>import json import pandas as pd from io import StringIO import requests url = &quot;https://testurl.com&quot; response = requests.request(&quot;GET&quot;, url) data = response.json() print(type(data)) # &lt;class 'dict'&gt; data = json.dumps(data) # Convert Set to JSON string. print(data) # Works up to here to import raw data from website. cdata = [] for v in data[&quot;blob&quot;][&quot;rawLines&quot;]: vals = [x for x in v.strip().split(' ') if x != ''] cdata.append([vals[0], &quot; &quot;.join(vals[1:])]) cdata = [] for v in data: vals = [x for x in v.strip().split(' ') if x != ''] cdata.append([vals[0], &quot; &quot;.join(vals[1:])]) </code></pre> <p>As indicated by the comment in my code above (<code># Works up to here to import raw data from website.</code>), I am able to import the raw (ugly) data, but just cannot figure out how to extract only the values I need. I bet there's something wrong with my indexing. Here is what I have up to the comment (below). It appears as a very long string because I want to show accurately what I'm seeing; however, if it would be better to use line breaks, I would be happy to edit it:</p> <pre><code>{&quot;payload&quot;: {&quot;allShortcutsEnabled&quot;: false, &quot;fileTree&quot;: {&quot;&quot;: {&quot;items&quot;: [{&quot;name&quot;: &quot;thing&quot;, &quot;path&quot;: &quot;thing&quot;, &quot;contentType&quot;: &quot;directory&quot;}, {&quot;name&quot;: &quot;.repurlignore&quot;, &quot;path&quot;: &quot;.repurlignore&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;README.md&quot;, &quot;path&quot;: &quot;README.md&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing2&quot;, &quot;path&quot;: &quot;thing2&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing3&quot;, &quot;path&quot;: &quot;thing3&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing4&quot;, &quot;path&quot;: &quot;thing4&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing5&quot;, &quot;path&quot;: &quot;thing5&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing6&quot;, &quot;path&quot;: &quot;thing6&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing7&quot;, &quot;path&quot;: &quot;thing7&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing8&quot;, &quot;path&quot;: &quot;thing8&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing9&quot;, &quot;path&quot;: &quot;thing9&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing10&quot;, &quot;path&quot;: &quot;thing10&quot;, &quot;contentType&quot;: &quot;file&quot;}, {&quot;name&quot;: &quot;thing11&quot;, &quot;path&quot;: &quot;thing11&quot;, &quot;contentType&quot;: &quot;file&quot;}], &quot;totalCount&quot;: 500}}, &quot;fileTreeProcessingTime&quot;: 5.262188, &quot;foldersToFetch&quot;: [], &quot;reducedMotionEnabled&quot;: null, &quot;repo&quot;: {&quot;id&quot;: 1234567, &quot;defaultBranch&quot;: &quot;main&quot;, &quot;name&quot;: &quot;repository&quot;, &quot;ownerLogin&quot;: &quot;contributor&quot;, &quot;currentUserCanPush&quot;: false, &quot;isFork&quot;: false, &quot;isEmpty&quot;: false, &quot;createdAt&quot;: &quot;2023-10-31&quot;, &quot;ownerAvatar&quot;: &quot;https://avatars.repurlusercontent.com/u/98765432?v=1”, &quot;public&quot;: true, &quot;private&quot;: false, &quot;isOrgOwned&quot;: false}, &quot;symbolsExpanded&quot;: false, &quot;treeExpanded&quot;: true, &quot;refInfo&quot;: {&quot;name&quot;: &quot;main&quot;, &quot;listCacheKey&quot;: &quot;v0:13579”, &quot;canEdit&quot;: false, &quot;refType&quot;: &quot;branch&quot;, &quot;currentOid&quot;: “identifier”2}, &quot;path&quot;: &quot;thing2&quot;, &quot;currentUser&quot;: null, &quot;blob&quot;: {&quot;rawLines&quot;: [&quot; C_1H_4 Methane &quot;, &quot; 5.00000 Property1 &quot;, &quot; 20.00000 Property2 &quot;, &quot; 500.66500 Property3 &quot;, &quot; 100.00000 Property4 &quot;, &quot; -4453.98887 Property5 &quot;, &quot; 100.48200 Property6 &quot;, &quot; 59.75258 Property7 &quot;, &quot; 5.33645 Property8 &quot;, &quot; 0.00000 Property9 &quot;, &quot; 645.07777 Property10 &quot;, &quot; 0.00000 Property11 &quot;, &quot; 0.00000 Property12 &quot;, &quot; 0.00000 Property13 &quot;, &quot; 0.00000 Property14 &quot;, &quot; 0.00000 Property15 &quot;, &quot; 0.00000 Property16 &quot;, &quot; 0.00000 Property17 &quot;, &quot; 0.00000 Property18 &quot;, &quot; 0.00000 Property19 &quot;, &quot; 0.00000 Property20 &quot;, &quot; 0.00000 Property21 &quot;, &quot; 0.00000 Property22 &quot;, &quot; 0.00000 Property23 &quot;, &quot; 0.00000 Property24 &quot;, &quot; 0.00000 Property25 &quot;, &quot; 0.57876 Property26 &quot;, &quot; 4.00000 Property27 &quot;, &quot; 0.00000 Property28 &quot;, &quot; 0.00000 Property29 &quot;, &quot; 0.00000 Property30 &quot;, &quot; 0.00000 Property31 &quot;, &quot; 0.00000 Property32 &quot;, &quot; 1.00000 Property33 &quot;, &quot; 0.00000 Property34 &quot;, &quot; 26.00000 Property35 &quot;, &quot; 1.44571 Property36 &quot;, &quot; 1.08756 Property37 &quot;, &quot; 0.00000 Property38 &quot;, &quot; 0.00000 Property39 &quot;, &quot; 0.00000 Property40 &quot;, &quot; 6.00000 Property41 &quot;, &quot; 9.00000 Property42 &quot;, &quot; 0.00000 Property43 &quot;], &quot;stylingDirectives&quot;: [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []], &quot;csv&quot;: null, &quot;csvError&quot;: null, &quot;dependabotInfo&quot;: {&quot;showConfigurationBanner&quot;: false, &quot;configFilePath&quot;: null, &quot;networkDependabotPath&quot;: &quot;/contributor/repository/network/updates&quot;, &quot;dismissConfigurationNoticePath&quot;: &quot;/settings/dismiss-notice/dependabot_configuration_notice&quot;, &quot;configurationNoticeDismissed&quot;: null, &quot;repoAlertsPath&quot;: &quot;/contributor/repository/security/dependabot&quot;, &quot;repoSecurityAndAnalysisPath&quot;: &quot;/contributor/repository/settings/security_analysis&quot;, &quot;repoOwnerIsOrg&quot;: false, &quot;currentUserCanAdminRepo&quot;: false}, &quot;displayName&quot;: &quot;thing2&quot;, &quot;displayUrl&quot;: &quot;https://repurl.com/contributor/repository/blob/main/thing2?raw=true&quot;, &quot;headerInfo&quot;: {&quot;blobSize&quot;: &quot;3.37 KB&quot;, &quot;deleteInfo&quot;: {&quot;deleteTooltip&quot;: &quot;You must be signed in to make or propose changes&quot;}, &quot;editInfo&quot;: {&quot;editTooltip&quot;: “XXX”}, &quot;ghDesktopPath&quot;: &quot;https://desktop.repurl.com&quot;, &quot;repurlLfsPath&quot;: null, &quot;onBranch&quot;: true, &quot;shortPath&quot;: “5678”, &quot;siteNavLoginPath&quot;: &quot;/login?return_to=identifier”, &quot;isCSV&quot;: false, &quot;isRichtext&quot;: false, &quot;toc&quot;: null, &quot;lineInfo&quot;: {&quot;truncatedLoc&quot;: “33”, &quot;truncatedSloc&quot;: “33”}, &quot;mode&quot;: &quot;executable file&quot;}, &quot;image&quot;: false, &quot;isCodeownersFile&quot;: null, &quot;isPlain&quot;: false, &quot;isValidLegacyIssueTemplate&quot;: false, &quot;issueTemplateHelpUrl&quot;: &quot;https://docs.repurl.com/articles/about-issue&quot;, &quot;issueTemplate&quot;: null, &quot;discussionTemplate&quot;: null, &quot;language&quot;: null, &quot;languageID&quot;: null, &quot;large&quot;: false, &quot;loggedIn&quot;: false, &quot;newDiscussionPath&quot;: &quot;/contributor/repository/issues/new&quot;, &quot;newIssuePath&quot;: &quot;/contributor/repository/issues/new&quot;, &quot;planSupportInfo&quot;: {&quot;repoOption1”: null, &quot;repoOption2”: null, &quot;requestFullPath&quot;: &quot;/contributor/repository/blob/main/thing2&quot;, &quot;repoOption4”: null, &quot;repoOption5”: null, &quot;repoOption6”: null, &quot;repoOption7”: null}, &quot;repoOption8”: {&quot;repoOption9”: &quot;/settings/dismiss-notice/repoOption10”, &quot;repoOption11”: &quot;/settings/dismiss&quot;, &quot;releasePath&quot;: &quot;/contributor/repository/releases/new=true&quot;, &quot;repoOption11: false, &quot;repoOption12”: false}, &quot;rawBlobUrl&quot;: &quot;https://repurl.com/contributor/repository/raw/main/thing2&quot;, &quot;repoOption13”: false, &quot;richText&quot;: null, &quot;renderedFileInfo&quot;: null, &quot;shortPath&quot;: null, &quot;tabSize&quot;: 8, &quot;topBannersInfo&quot;: {&quot;overridingGlobalFundingFile&quot;: false, &quot;universalPath&quot;: null, &quot;repoOwner&quot;: &quot;contributor&quot;, &quot;repoName&quot;: &quot;repository&quot;, &quot;repoOption14”: false, &quot;citationHelpUrl&quot;: &quot;https://docs.repurl.com/en/repurl/archiving/about&quot;, &quot;repoOption15”: false, &quot;repoOption16”: null}, &quot;truncated&quot;: false, &quot;viewable&quot;: true, &quot;workflowRedirectUrl&quot;: null, &quot;symbols&quot;: {&quot;timedOut&quot;: false, &quot;notAnalyzed&quot;: true, &quot;symbols&quot;: []}}, &quot;collabInfo&quot;: null, &quot;collabMod&quot;: false, “wtsdf_signifier”: {&quot;/contributor/repository/branches&quot;: {&quot;post&quot;: “identifier”}, &quot;/repos/preferences&quot;: {&quot;post&quot;: “identifier”}}}, &quot;title&quot;: &quot;repository/thing2 at main \u0000 contributor/repository&quot;} </code></pre>
<python><json><python-3.x><pandas><file-io>
2023-12-18 18:27:46
1
897
Ant
77,680,833
5,815,127
Load Mongo `Binary.createfrombase64` field in Python
<p>I have a Mongo collection with this kind of documents:</p> <pre class="lang-json prettyprint-override"><code> { _id: ObjectId('656f001650078dc1d50872ed'), created_at: ISODate('2023-12-05T10:48:54.641Z'), user_id: Binary.createFromBase64('MjkyMmZkYmUtOTM1Yi0xMWVlLTlkMjEtN2U2NjQwYmEyNGEw', 4), } </code></pre> <p>Here is how I load the data in Python:</p> <pre class="lang-py prettyprint-override"><code>from pymongo import MongoClient client = MongoClient(os.getenv(&quot;MONGO_URL&quot;)) collection = client.get_database(os.getenv(&quot;MONGO_DB&quot;)).get_collection(os.getenv(&quot;MONGO_COLLECTION&quot;)) select = {'created_at': 1} result = collection.find_one({}, select) </code></pre> <p>if I replace</p> <pre class="lang-py prettyprint-override"><code>select = {'created_at': 1} </code></pre> <p>with</p> <pre class="lang-py prettyprint-override"><code>select = {'user_id': 1} </code></pre> <p>I get this error:</p> <pre><code>... File ~/.pyenv/versions/3.11.5/lib/python3.11/site-packages/pymongo/message.py:1619, in _OpMsg.unpack_response(self, cursor_id, codec_options, user_fields, legacy_response) 1617 # If _OpMsg is in-use, this cannot be a legacy response. 1618 assert not legacy_response -&gt; 1619 return bson._decode_all_selective(self.payload_document, codec_options, user_fields) File ~/.pyenv/versions/3.11.5/lib/python3.11/site-packages/bson/__init__.py:1259, in _decode_all_selective(data, codec_options, fields) 1236 &quot;&quot;&quot;Decode BSON data to a single document while using user-provided 1237 custom decoding logic. 1238 (...) 1256 .. versionadded:: 3.8 1257 &quot;&quot;&quot; 1258 if not codec_options.type_registry._decoder_map: -&gt; 1259 return decode_all(data, codec_options) 1261 if not fields: 1262 return decode_all(data, codec_options.with_options(type_registry=None)) File ~/.pyenv/versions/3.11.5/lib/python3.11/site-packages/bson/__init__.py:1167, in decode_all(data, codec_options) 1164 if not isinstance(codec_options, CodecOptions): 1165 raise _CODEC_OPTIONS_TYPE_ERROR -&gt; 1167 return _decode_all(data, codec_options) InvalidBSON: invalid length or type code </code></pre> <p>Here are the version I use:</p> <pre><code>Python: 3.11.5 pymongo: 4.6.1 MongoDB: 5.0.23 </code></pre> <p>It seems to come from the <code>Binary.createFromBase64</code>.</p> <p>Does anybody have a clue ?</p>
<python><mongodb><pymongo>
2023-12-18 17:38:43
1
4,603
Till
77,680,831
16,205,113
SignalR communication between python and aspnet
<p>I COMMUNICATE BETWEEN ASP NET C# AND PYTHON using a websocket, or more specifically, I use a signalR library in both cases. I'm trying to get my server to respond in some way when a Python client sends a message. nothing helps for now. anyone had this problem?</p> <p>it is enough that after the client sends the message, the function in the hub named SendGemstoneDetailMessage will work.that's what I mean</p> <p>Python Code:</p> <pre><code>import logging from signalrcore.hub_connection_builder import HubConnectionBuilder import asyncio class SignalRClient: def __init__(self): self.hub_connection = None def connect(self): try: self.hub_connection = HubConnectionBuilder() \ .configure_logging(logging.DEBUG) \ .with_automatic_reconnect({ &quot;type&quot;: &quot;raw&quot;, &quot;keep_alive_interval&quot;: 10, &quot;reconnect_interval&quot;: 5, &quot;max_attempts&quot;: 5 }) \ .with_url(&quot;https://localhost:7294/WebSocketMessageHub&quot;, options={&quot;verify_ssl&quot;: False}) \ .build() self.hub_connection.on(&quot;ReceiveMessage&quot;, self.receive_message) self.hub_connection.start() self.hub_connection.on_open(lambda: print(&quot;connection opened and handshake received ready to send messages&quot;)) self.hub_connection.on_close(lambda: print(&quot;connection closed&quot;)) self.hub_connection.on_error(lambda data: print(f&quot;An exception was thrown closed{data.error}&quot;)) print(&quot;Connected to SignalR Hub&quot;) # Send a message after connection self.hub_connection.send(&quot;SendGemstoneDetailMessage&quot;, [&quot;dwdw&quot;]) except Exception as e: print(f&quot;Failed to connect to the server: {e}&quot;) def receive_message(self, *args, **kwargs): # Handle received messages print(f&quot;ITS MEE: {args}&quot;) async def listen_forever(self): while True: await asyncio.sleep(1) # not blocking threads async def main(): signalr_client = SignalRClient() signalr_client.connect() await signalr_client.listen_forever() if __name__ == &quot;__main__&quot;: asyncio.run(main()) </code></pre> <p>C# code:</p> <pre><code>public class WebSocketHub : Hub { private readonly IWebSocketService _webSocketService; public WebSocketHub(IWebSocketService webSocketService) { _webSocketService = webSocketService; } public override Task OnConnectedAsync() { _webSocketService.ConnectAdmin(Context); return base.OnConnectedAsync(); } public async Task SendGemstoneDetailMessage(List&lt;string&gt; messag) { Console.WriteLine(&quot;HELLO&quot;); } } </code></pre> <p>Logs from client in python:</p> <pre><code>2023-12-18 18:41:25,857 - SignalRCoreClient - DEBUG - Handler registered started ReceiveMessage 2023-12-18 18:41:25,857 - SignalRCoreClient - DEBUG - Connection started 2023-12-18 18:41:25,857 - SignalRCoreClient - DEBUG - Negotiate url:https://localhost:7294/WebSocketMessageHub/negotiate /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py:1100: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings warnings.warn( Connected to SignalR Hub 2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - Response status code200 2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - start url:wss://localhost:7294/WebSocketMessageHub?id=0JER4PQd5JeF97061acC2Q 2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - Sending message InvocationMessage: invocation_id 6c1a818b-9aae-4d95-b08b-85c2c08606fc, target SendGemstoneDetailMessage, arguments ['dwdw'] 2023-12-18 18:41:27,021 - SignalRCoreClient - DEBUG - {&quot;type&quot;: 1, &quot;headers&quot;: {}, &quot;target&quot;: &quot;SendGemstoneDetailMessage&quot;, &quot;arguments&quot;: [&quot;dwdw&quot;], &quot;invocationId&quot;: &quot;6c1a818b-9aae-4d95-b08b-85c2c08606fc&quot;} 2023-12-18 18:41:27,021 - SignalRCoreClient - WARNING - Connection closed socket is already closed. 2023-12-18 18:41:27,022 - SignalRCoreClient - INFO - on_reconnect not defined 2023-12-18 18:41:27,022 - SignalRCoreClient - DEBUG - Negotiate url:https://localhost:7294/WebSocketMessageHub/negotiate?id=0JER4PQd5JeF97061acC2Q /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/urllib3/connectionpool.py:1100: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings warnings.warn( 2023-12-18 18:41:27,541 - SignalRCoreClient - DEBUG - Response status code200 2023-12-18 18:41:27,541 - SignalRCoreClient - DEBUG - start url:wss://localhost:7294/WebSocketMessageHub?id=cQ-mlq9xR3QcJLxuREJVyw 2023-12-18 18:41:27,738 - SignalRCoreClient - DEBUG - -- web socket open -- 2023-12-18 18:41:27,738 - SignalRCoreClient - DEBUG - Sending message &lt;signalrcore.messages.handshake.request.HandshakeRequestMessage object at 0x103513bd0&gt; 2023-12-18 18:41:27,738 - SignalRCoreClient - DEBUG - {&quot;protocol&quot;: &quot;json&quot;, &quot;version&quot;: 1} 2023-12-18 18:41:28,272 - SignalRCoreClient - DEBUG - -- web socket open -- 2023-12-18 18:41:28,272 - SignalRCoreClient - DEBUG - Sending message &lt;signalrcore.messages.handshake.request.HandshakeRequestMessage object at 0x1058e3b50&gt; 2023-12-18 18:41:28,272 - SignalRCoreClient - DEBUG - {&quot;protocol&quot;: &quot;json&quot;, &quot;version&quot;: 1} 2023-12-18 18:41:28,280 - SignalRCoreClient - DEBUG - Message received{} 2023-12-18 18:41:28,280 - SignalRCoreClient - DEBUG - Evaluating handshake {} connection opened and handshake received ready to send messages 2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - Message received{&quot;type&quot;:7,&quot;error&quot;:&quot;Connection closed with an error.&quot;,&quot;allowReconnect&quot;:true} 2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - Raw message incomming: 2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - {&quot;type&quot;:7,&quot;error&quot;:&quot;Connection closed with an error.&quot;,&quot;allowReconnect&quot;:true} 2023-12-18 18:41:31,695 - SignalRCoreClient - INFO - Close message received from server 2023-12-18 18:41:31,695 - SignalRCoreClient - DEBUG - Connection stop </code></pre>
<python><websocket><asp.net-core-signalr>
2023-12-18 17:38:23
2
385
Majkelele
77,680,667
16,578,438
transforming a 7 digit integer number to unique alphanumeric value and vice versa
<p>I am trying to convert a 7 digit integer to 6 character alphanumeric value (ALL CAPS a). I don't want to translate the integer value, is there any other way I can do it ? encode it and decode with output value back to the function and get in input back again -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Input</th> <th style="text-align: center;">Output</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">7200123</td> <td style="text-align: center;">ABC123</td> </tr> <tr> <td style="text-align: center;">ABC123</td> <td style="text-align: center;">7200123</td> </tr> <tr> <td style="text-align: center;">1234567</td> <td style="text-align: center;">12X7S3</td> </tr> <tr> <td style="text-align: center;">12X7S3</td> <td style="text-align: center;">1234567</td> </tr> </tbody> </table> </div> <p>Ideally I should be able to pass any integer and get an encoded 6 character alphanumeric value and pass the 6 Character Alphanumeric value to get the integer back</p>
<python><pyspark>
2023-12-18 17:06:03
2
428
NNM
77,680,557
4,111,341
Python, using UDP ports to transfer data from common pool makes threads crawl to a halt
<p>I'm quite stuck with while implementing a proxy tunnel. Based on pysoxy, I basically split it in half, a local &quot;half&quot; that deals with connecting to the client, and a remote &quot;half&quot; that does the proxying to the destination. The two parts communicate with each other via UDP.</p> <p>The problem is, I keep on getting 100% CPU usage even when loading a simple page, performance is abysmal, and clearly the threads are getting super stuck.</p> <p>I'm mostly sure this is about my usage of UDP sockets, but I tried making sure there is no blocking io or similar stuff hindering performance. And yet, I'm seeing the threads crawling even going from one line to the next.</p> <p>I've tried to make an MCVE but it escapes me. The part I'm worried about the most is this:</p> <pre><code> def proxy_loop_inbound(destination_socket, connection_details, stop_event, connection_queue): while not EXIT.get_status() or not stop_event.is_set(): with connection_queue[&quot;lock&quot;]: for index, proxy_loop in enumerate(connection_queue[&quot;queues&quot;]): if int(proxy_loop[&quot;id&quot;]) == connection_details[&quot;id&quot;]: proxy_loop_content = base64.b64decode(proxy_loop[&quot;proxy_loop&quot;]) if int(proxy_loop[&quot;sequence&quot;])==inbound_sequence: del connection_queue[&quot;queues&quot;][index] while True: _, ready_to_write, _ = select.select([], [destination_socket], [], 0.01) if ready_to_write: break # Break the loop if the socket is ready to write time.sleep(0.01) # Sleep for a short duration to yield to other threads destination_socket.send(proxy_loop_content) break else: pass def proxy_loop_outbound(destination_socket, connection_details, stop_event): while not EXIT.get_status() or not stop_event.is_set(): try: ready_to_read, _, _ = select.select([destination_socket], [], [], 1) if destination_socket in ready_to_read: data = destination_socket.recv(BUFSIZE) if not data: return while True: _, ready_to_write, _ = select.select([], [udp_socket], [], 0.01) if ready_to_write: break # Break the loop if the socket is ready to write time.sleep(0.01) # Sleep for a short duration to yield to other threads udp_socket.sendto(proxy_loop_outbound_details.encode(), (&quot;127.0.0.1&quot;, UDP_PORT_WRITE)) except BlockingIOError: print(&quot;Blocking IO error&quot;) pass # No data available except socket.error as err: stop_event.set() error(&quot;Loop failed&quot;, err) return </code></pre> <p>Both loops are the same mirrored on the other side of the proxy. These proxy loops are spawned for each connection, so for every request there are two such threads, and there is a UDP listener thread that will append the (possibly unordered) data to a list that is shared between threads. The threads will keep on doing the back and forth of the data until the socket is closed by either the client or the destination.</p> <p>Sometimes threading is so blocked I get a second and a half to go from non blocking line to the next (i.e. literally time between two prints). Sometimes I get full seconds to do the write to the UDP port.</p> <p>Also, this wrecks havoc on my ability to properly close the threads, as keyboard interrupts are basically never caught. What am I doing wrong?</p> <p>I'm putting the whole code here to try the whole thing out:</p> <p>local part: <a href="https://dpaste.org/E4FVT" rel="nofollow noreferrer">https://dpaste.org/E4FVT</a></p> <p>remote part: <a href="https://dpaste.org/68EtV" rel="nofollow noreferrer">https://dpaste.org/68EtV</a></p>
<python><multithreading><sockets><udp>
2023-12-18 16:46:08
0
323
Marco Carandente
77,680,539
2,556,795
How to get QoQ, MoM values from previous years
<p>I have a dataframe with quarterly values for various items and I need to create a column showing quarter values from previous year of each item (Ex: 2021_Q1 value of item A to be compared with 2020_Q1 and so on for other items) similarly for MoM.</p> <p>Below is my reproducible dataframe.</p> <pre><code>df = pd.DataFrame({'item':['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 'quarter':['FY20_Q1','FY20_Q2','FY20_Q3','FY20_Q4','FY21_Q1','FY21_Q2', 'FY20_Q1','FY20_Q2','FY20_Q3','FY20_Q4','FY21_Q1','FY21_Q2', 'FY20_Q1','FY20_Q2','FY20_Q3','FY20_Q4','FY21_Q1','FY21_Q2'], 'value':[100,150,120,135,128,160,230,210,240,220,250,230,125,230,162,111,134,135]}) </code></pre> <p>I sorted values and used <code>groupby</code> and <code>shift</code> but I am not getting desired result.</p> <pre><code>df['value_prev'] = df.sort_values(by=['item','quarter']).groupby(['item'])['value'].shift() </code></pre> <p>This gives me below result which obviously is comparing values from preceding quarter and not year.</p> <pre><code> item quarter value value_prev 0 A FY20_Q1 100 NaN 1 A FY20_Q2 150 100 2 A FY20_Q3 120 150 3 A FY20_Q4 135 120 4 A FY21_Q1 128 135 5 A FY21_Q2 160 128 ... </code></pre> <p>My expected result is as below. Is there any method which can be used to get this.</p> <pre><code> item quarter value value_prev 0 A FY20_Q1 100 NaN 1 A FY20_Q2 150 NaN 2 A FY20_Q3 120 NaN 3 A FY20_Q4 135 NaN 4 A FY21_Q1 128 100 5 A FY21_Q2 160 150 </code></pre>
<python><pandas>
2023-12-18 16:42:14
3
1,370
mockash
77,680,307
509,977
Check the status of a running async ansible playbook using Python Flask API
<p>In a Flask API I have an endpoint able to run an ansible playbook on remote host using:</p> <pre><code>ansible_runner.run_async </code></pre> <p>The playbook is running for long time and I would like to allow my users to check playbook status using another endpoint.</p> <p>How is this possible if the only data I have is the job id?</p>
<python><ansible>
2023-12-18 16:03:14
1
8,679
Pitto
77,680,284
2,363,318
python fabric set ssh_path via config yaml file
<p>What is the proper way to store and use a custom ssh path for fabric to run</p> <p>This does not seem to be working:</p> <p>fabric.yaml:</p> <pre><code>set_runtime_ssh_path: 'my/ssh/path' </code></pre> <p>main.py:</p> <pre><code>with open('fabric.yaml') as config_file: config = yaml.safe_load(config_file) with Connection('example.com', connect_kwargs={'set_runtime_ssh_path': config.get('set_runtime_ssh_path'), 'password': 'password'}) as conn: conn.run('whoami', pty=True) </code></pre>
<python><python-3.x><fabric>
2023-12-18 16:00:48
1
1,067
user2363318
77,680,237
20,233,502
Deploying Python Function Application with DevOps is moving files but not actually deploying application
<p>This is a repost of this question, <a href="https://learn.microsoft.com/en-us/answers/questions/1462841/deploying-python-function-application-with-devops" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/answers/questions/1462841/deploying-python-function-application-with-devops</a> adding to SO to get more views.</p> <p>A Python Azure Function (Model V2) was created using VS Code and following the Microsoft article linked below, with the default code for the Function Application.</p> <p><a href="https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python?pivots=python-mode-decorators" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python?pivots=python-mode-decorators</a></p> <p>A Build Pipeline and a Release Pipeline were set up in Azure DevOps, using the article linked below (which is a few years old). The Tasks in the Release pipeline are not the same as the article, but everything else seemed to flow well.</p> <p><a href="https://medium.com/globant/how-to-create-and-deploy-a-python-azure-function-using-azure-devops-ci-cd-2aa8f8675716" rel="nofollow noreferrer">https://medium.com/globant/how-to-create-and-deploy-a-python-azure-function-using-azure-devops-ci-cd-2aa8f8675716</a></p> <p>From the currently available tasks, the “Azure Function Deploy”-task seemed the best and only fit. The screenshot below shows the Tasks available.</p> <p><a href="https://i.sstatic.net/TKXze.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/TKXze.png" alt="enter image description here" /></a></p> <p>When the Release Pipeline is run, it runs successfully. All of the files were moved to the Function Application service according to the screenshot below. It ran multiple times with edits to comments in the default “function_app.py” file and new files added to ensure the build pipeline + deployment pipeline were moving the documents.</p> <p><a href="https://i.sstatic.net/59uYt.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/59uYt.png" alt="enter image description here" /></a></p> <p>However, there is no actual Function running and available to interact with. (See screenshot below). Any idea on what modification is needed in the Deployment pipeline to make this work?</p> <p><a href="https://i.sstatic.net/rckjF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rckjF.png" alt="enter image description here" /></a></p> <p>EDIT:</p> <p>The instructions in the response from @wade-zhou-msft were attempted by my colleague, and here was her response:</p> <p>&quot;Hello @Wade Zhou - thank you for posting this answer. I did confirm that the code works when deployed directly from VS Code. So this is not a function code problem. I tried to recreate your yaml code using the pipeline builder, as I am a beginner and I am not familiar with yaml files. I did not get it to run successfully. Can you provide some insight on how is the repo associated with the DevOps Pipeline you used for testing and in your response? Currently, my repo looks like the screenshot below. Perhaps I have to create an artifact that only looks at the Function App code.</p> <p><a href="https://i.sstatic.net/ZC3c7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZC3c7.png" alt="enter image description here" /></a></p> <p>Note that I cloned the repo into my local machine before creating my Azure Function workspace. The workspace for VS Code was created within the repo, and then merged into master branch of the repo.</p> <p>I tried the copy activity, I got it to work, but still having issues with the artifact step picking up the files from the sub directory&quot;</p>
<python><azure-devops><azure-functions><azure-pipelines><azure-pipelines-release-pipeline>
2023-12-18 15:53:11
4
320
Mike
77,680,161
1,862,861
Get final values from a specific dimension/axis of an arbitrarily dimensioned PyTorch Tensor
<p>Suppose I had a PyTorch tensor such as:</p> <pre><code>import torch x = torch.randn([3, 4, 5]) </code></pre> <p>and I wanted to get a new tensor, with the same number of dimensions, containing everything from the final value of dimension 1. I could just do:</p> <pre><code>x[:, -1:, :] </code></pre> <p>However, if <code>x</code> had an arbitrary number of dimensions, and I wanted to get the final values from a specific dimension, what is the best way to do it?</p>
<python><pytorch><tensor>
2023-12-18 15:41:52
2
7,300
Matt Pitkin
77,679,978
20,771,478
Memory overflow when reading excel with pandas
<p>I am loading excel files into pandas dataframes to do work with their data.</p> <p>The script works on my machine with 16GB RAM but not on the machine where it is supposed to run with 8GB of RAM.</p> <p>With the function <code>df.info(memory_usage=’deep’)</code> I have checked the size of the dataframes coming out of pd.read_excel. The largest dataframe is 4MB.</p> <p>My conclusion from this is that there must be something happening within the <code>read_excel</code> function that causes the memory overflow.</p> <p><a href="https://%20https://stackoverflow.com/questions/46478427/pd-read-excel-memory-usage" rel="nofollow noreferrer">This post</a> suggests that it is possible that pandas is reading what Excel considers the used range which might be far beyond the range actually holding data. Since the files are in active use by people it feels foolish to just remove blank cells from Excel and call it a day. Users can always add the blank cells back. And it feels just as foolish to limit the read_excel function to a max amount of rows/columns because that might be surpassed in the future.</p> <p>Is there a method to reduce memory usage when reading Excel files with used ranges that go far beyond the range where the data actually is?</p> <p>Below is my code:</p> <pre><code>df = pd.read_excel( file_location , sheet_name = sheet_name , header = None , skiprows = number_of_rows_to_skip , usecols = used_cols , names = col_names # For some reason if I don't set this the dataframe gets unreasonably large. , nrows = 1000000 ) </code></pre> <ul> <li><p><code>used cols</code> is a string containing the column characters like &quot;A, C, F&quot;.</p> </li> <li><p><code>col_names</code> is a list of names I want to give to each column.</p> </li> <li><p><code>nrows</code> is strange. One example: If I don't use it my 88KB dataframe is growing to 136MB. However, Excel has just over 1 million rows, right? So why is there this huge difference between parsing all rows or just 1 million?</p> </li> </ul>
<python><pandas><excel><dataframe><memory-optimization>
2023-12-18 15:05:47
0
458
Merlin Nestler
77,679,964
3,795,597
Set document title with custom sphinx parser
<p>I am looking into using sphinx to generate documentation for a non-python (SKILL, though not relevant here) project. Most of the functions have docstrings, so as a first approach I settled on creating a custom parser to document <em>procedures</em> from files, using the provided docstrings.</p> <p>The following is my current parser structure, that I also provided <a href="https://stackoverflow.com/a/77661688/3795597">in this other answer</a>:</p> <pre class="lang-py prettyprint-override"><code>from docutils import nodes from sphinx.parsers import Parser class MySkillParser(Parser): supported = (&quot;skill&quot;,) # Declare supported languages def parse(self, inputstring, document): # Here, parse the document contained in &quot;inputstring&quot; and dynamically generate content txt = nodes.Text('HI') document += txt def setup(app): # This is called when loading the extension app.add_source_suffix('.il', 'skill') app.add_source_parser(MySkillParser) return {'version': '0.1'} </code></pre> <p>Besides some difficulty encountered with adding nodes, this seems to work well, except for the following warning:</p> <p><code>WARNING: toctree contains reference to document 'myfile' that doesn't have a title: no link will be generated</code></p> <p>This happens when referencing <code>myfile</code> in the table of content of some other document, such as the index. <code>myfile.il</code> is parsed and an html file is generated from it thanks to the parser (with the code above, it will contain &quot;HI&quot;). However, sphinx does not know the document title, so it refuses to generate a table of contents entry.</p> <p><strong>My question is simple</strong>: how do I make the name of the document known to sphinx?</p> <p>This is similar to the following questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/45987449/cant-display-multiple-md-files-in-rst-toctree-sphinx">Can&#39;t display multiple .md files in .rst toctree Sphinx</a></li> <li><a href="https://stackoverflow.com/questions/14079655/cannot-get-toctree-in-sphinx-to-show-link">Cannot Get TOCTREE in Sphinx to Show Link</a></li> </ul> <p>However, these do not refer to a custom parser, but use an existing <em>rst</em> or <em>md</em> parser.</p> <p>The sphinx documentation <a href="https://www.sphinx-doc.org/en/master/usage/restructuredtext/field-lists.html#file-wide-metadata" rel="nofollow noreferrer">states that</a>:</p> <blockquote> <p>A field list near the top of a file is normally parsed by docutils as the docinfo and shown on the page. However, in Sphinx, a field list preceding any other markup is moved from the docinfo to the Sphinx environment as document metadata, and is not displayed in the output.</p> </blockquote> <p>So <em>I think</em> the parser needs to modify the sphinx environment, but what exactly? Following sphinx source code and some documentation, I tried multiple things, independently and in combination, to no avail:</p> <hr /> <pre class="lang-py prettyprint-override"><code>title = &quot;Document title&quot; def parse(self, inputstring, document): # The following was also tried with self.env.get_doctree(self.env.docname) instead of &quot;document&quot; document.settings.title = titletxt document.settings._title = titletxt # Inspired from https://github.com/sphinx-doc/sphinx/blob/35965903177c6ed9a6afb62ccd33243a746a3fc0/sphinx/builders/latex/__init__.py#L314C20-L314C20 document['docname'] = titletxt # from https://github.com/sphinx-doc/sphinx/blob/35965903177c6ed9a6afb62ccd33243a746a3fc0/sphinx/builders/latex/__init__.py#L347 document['contentsname'] = titletxt # from https://github.com/sphinx-doc/sphinx/blob/35965903177c6ed9a6afb62ccd33243a746a3fc0/sphinx/builders/latex/__init__.py#L306C17-L306C40 titlenode = nodes.title('Hi', nodes.Text('Title node')) document += titlenode self.env.titles[self.env.docname] = titlenode self.env.longtitles[self.env.docname] = titlenode self.env.tocs[self.env.docname] = titlenode # Less sure about this one document.title = 'another futile attempt' # Also tried: parse a rst string into the document with docutils.core.publish_doctree(rst) </code></pre> <p>After quite a few more attempts, I resolved to ask here. At this point, I am unsure if the Parser is responsible for setting the title, or if it should be set somewhere else.</p>
<python><python-sphinx><docutils>
2023-12-18 15:03:25
1
2,089
MayeulC
77,679,855
10,595,871
Jupyter Notebook can't hold type string if string is too long
<p>I'm working with python and Jupyter Notebook, I've a dictionary in which values are lists with strings in them.</p> <p>The thing is that the code is giving me an error, I printed the dictionary and everything seems fine, but when I tried to copy and paste it in a cell, I noticed that from a certain point, the strings are no more red but black. So it seems like it don't recognize them as strings anymore.</p> <p>The strange thing is that if a go to a new line after the last string seen as a proper string (so, displayed in red), the strings that follows are displayed as proper strings.</p> <p>I manually tried to to this with almost the whole dictionary and with this method the code works.</p> <p>I don't understand what I'm doing wrong and how to fix this strange behaviour (of course I can't do it manually as I did).</p> <p>example:</p> <pre><code>dict = {'red_key1' : { 'red_key1.1' : [&quot;red_string&quot;, &quot;black_string&quot;]}, 'black_key2': {'black_key2.1' : [&quot;black_string&quot;]}} dict = {'red_key1' : { 'red_key1.1' : [&quot;red_string&quot;, &quot;red_string&quot;]}, 'red_key2': {'red_key2.1' : [&quot;black_string&quot;]}} dict = {'red_key1' : { 'red_key1.1' : [&quot;red_string&quot;, &quot;red_string&quot;]}, 'red_key2': {'red_key2.1' : [&quot;red_string&quot;]}} </code></pre> <p>In the example above, the &quot;dict&quot; never changes, I'm just going a capo when I see that the strings are no more displayed in red.</p> <p>Two screenshot, in the first one you can see the transition from red to black. In the second one the result after pressing enter (the strings that were black before are now red).</p> <p><a href="https://i.sstatic.net/At0WI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/At0WI.png" alt="enter image description here" /></a></p> <p><a href="https://i.sstatic.net/WGHDz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WGHDz.png" alt="enter image description here" /></a></p> <p>If I go to the new line every time black strings start, all the black strings become red and the code works fine until the end. Instead it gives me an error if I keep everything in the original format.</p> <p>If I run the cell it works fine, but if I try to put the variable in this function:</p> <pre><code>def remove(diz): return {k: {inner_key: inner_value for inner_key, inner_value in v.items() if inner_value} for k, v in diz.items() if v} </code></pre> <p>it raises the error 'list' object has no attribute item().</p> <p>If I manage to go a capo with all the strings the same code works fine.</p> <p>Thanks!</p>
<python><dictionary><jupyter-notebook>
2023-12-18 14:45:17
0
691
Federicofkt
77,679,808
219,976
mypy for derived class of cached_property
<p>When I run mypy check for the following code:</p> <pre><code>from functools import cached_property def func(s: str) -&gt; None: print(s) class Foo: @cached_property def prop(self) -&gt; int: return 1 foo = Foo() func(foo.prop) </code></pre> <p>I got error: <code>error: Argument 1 to &quot;func&quot; has incompatible type &quot;int&quot;; expected &quot;str&quot;</code></p> <p>Now I want to extend behavior of cached_property for my project by inheriting it:</p> <pre><code>from functools import cached_property def func(s: str) -&gt; None: print(s) class result_property(cached_property): pass class Foo: @result_property def prop(self) -&gt; int: return 1 foo = Foo() func(foo.prop) </code></pre> <p>No extra behavior is added to <code>result_property</code> yet. But when I run mypy check for it I get: <code>Success: no issues found in 1 source file</code> I expect the result of type check should by the same in both cases. Why is it different?</p>
<python><properties><decorator><python-decorators><mypy>
2023-12-18 14:37:06
1
6,657
StuffHappens
77,679,764
3,511,695
Reliably clean/convert all unicode/emojis for JSON parsing
<p>I'm seeking the correct sequence of Python <code>decode()</code> and <code>encode()</code> functions required to result in completely clean and parse-able JSON, no matter which combinations of unusual ASCII/unicode/emoji characters present.</p> <p>In Javascript, I'm trying to <code>JSON.parse()</code> some API data returned from my Python backend. My first hurdle was this entry:</p> <blockquote> <p>🔥My name is Miguel Ive been in the flooring industry since 2014, on 2018 I started my own flooring store and our priority is provide the best customer service to our clients ! Visit us on our new showroom on woods cross we will be happy to help you with your project and we will give you a free in home consultation and ask about our 10%discount on same day booking ! 🔥</p> </blockquote> <p>I successfully used <a href="https://stackoverflow.com/a/65384920/3511695">this answer</a> to decode such characters on the Python backend:</p> <pre><code>value.encode('cp1252','backslashreplace').decode('utf-8','backslashreplace') </code></pre> <p>Result:</p> <blockquote> <p>🔥My name is Miguel Ive been in the flooring industry since 2014, on 2018 I started my own flooring store and our priority is provide the best customer service to our clients ! Visit us on our new showroom on woods cross we will be happy to help you with your project and we will give you a free in home consultation and ask about our 10%discount on same day booking ! 🔥</p> </blockquote> <p>But then I ran into new API calls with JSON that <code>JSON.parse()</code> threw errors for. For example, these <code>\x92</code> characters were preventing the JSON from correctly parsing (&quot;<code>Bad escaped character</code>&quot;):</p> <blockquote> <p>Hello, I\x92m Eric, I\x92ve been around all phases of construction since I was old enough to hold a hammer. Was taught by my father how to do it right the first time, and make it so people can afford to do more with their budget. I can do it all, but enjoy doing flooring and tile work. I\x92m not afraid of a creative challenge</p> </blockquote> <p>So I reluctantly (since I knew it wouldn't be a reliable solution) added a simple <code>replace()</code> statement:</p> <pre><code>decoded_text.replace('\\x92', &quot;’&quot;) </code></pre> <p>But I (expectedly) soon ran into new API calls that returned data that <code>JSON.parse()</code> refused to work with, like <code>\u011f\x9f\x91\x8c\u011f\x9f\ufffd\xbd</code> in the string below:</p> <blockquote> <p>Went and above and beyond to expose and fix other poorly done installations \u011f\x9f\x91\x8c\u011f\x9f\ufffd\xbd</p> </blockquote> <p>Here is my full Python code for calling the API, and my attempt at properly decoding it:</p> <pre><code># models/api_connector.py from odoo import models, fields, api import requests import base64 import configparser import os class MyAPIConnector(models.Model): _name = 'api.connector' _description = 'API Connector' name = fields.Char('Name') def _generate_auth_header(self): # Read configuration config = configparser.ConfigParser() config_path = os.path.join(os.path.dirname(__file__), '..', 'config.ini') config.read(config_path) # Combine and encode credentials org_name = config.get('api_credentials', 'org_name') secret_key = config.get('api_credentials', 'secret_key') combined_credentials = f&quot;{org_name}:{secret_key}&quot; encoded_credentials = base64.b64encode(combined_credentials.encode()).decode() return f&quot;Basic {encoded_credentials}&quot; def fetch_data(self, zip_code): try: headers = {'Authorization': self._generate_auth_header()} category_pk = '123456789' API_ENDPOINT = f&quot;https://api.myapi.com/v1/partners/discoverylite/pros?zip_code={zip_code}&amp;category_pk={category_pk}&amp;utm_source=myCompany&quot; response = requests.get(API_ENDPOINT, headers=headers) response_text = response.text # Decoding and re-encoding the response text decoded_text = response_text.encode('cp1252', 'backslashreplace').decode('utf-8', 'backslashreplace') decoded_text = decoded_text.replace('\\x92', &quot;’&quot;) return decoded_text except Exception as e: _logger.error(f&quot;Error: {e}&quot;) </code></pre> <p>Here is the <strong>raw, untouched</strong> data returned from the API for the latest problematic entry (which <code>JSON.parse()</code> parses just fine but contains encoded characters):</p> <pre><code>{ &quot;results&quot;: [{ &quot;service_id&quot;: &quot;490803031657299972&quot;, &quot;business_name&quot;: &quot;Jay Contractors LLC&quot;, &quot;rating&quot;: 4.972222222222222, &quot;num_reviews&quot;: 36, &quot;years_in_business&quot;: 1, &quot;num_hires&quot;: 87, &quot;thumbtack_url&quot;: &quot;https://www.thumbtack.com/pa/lansdowne/handyman/jay-contractors-llc/service/490803031657299972?category_pk=151436204227846419\u0026utm_medium=partnership\u0026utm_source=cma-hewn\u0026zip_code=19701&quot;, &quot;image_url&quot;: &quot;https://production-next-images-cdn.thumbtack.com/i/490934068026425349/desktop/standard/thumb&quot;, &quot;background_image_url&quot;: &quot;https://production-next-images-cdn.thumbtack.com/i/319588452476190788/small/standard/hero&quot;, &quot;featured_review&quot;: &quot;Went and above and beyond to expose and fix other poorly done installations 👌ğŸ�½&quot;, &quot;quote&quot;: { &quot;starting_cost&quot;: 5000, &quot;cost_unit&quot;: &quot;on-site estimate&quot; }, &quot;introduction&quot;: &quot;My focus is quality, and dedication to the job. I take pride in every job, from start to finish. Always go for 100% satisfaction by client and see them smiling after the work is completed.\n\nPlease keep in mind if your using the instant book feature, it means your hiring me for my services and if you decide to cancel later on there will be a charge.\n\nAccept Cash, Cashapp, Zelle, and Venmo.\nNo Checks please.\n\nLicensed and Insured&quot;, &quot;pills&quot;: [&quot;popular&quot;, &quot;licensed&quot;], &quot;location&quot;: &quot;Bear, DE&quot;, &quot;similar_jobs_done&quot;: 1, &quot;license_verified&quot;: true, &quot;num_of_employees&quot;: 2, &quot;has_background_check&quot;: true, &quot;iframe_url&quot;: &quot;&quot; }] } </code></pre> <p>And here is that same entry's JSON after being processed my Python's decoding functions, which <code>JSON.parse()</code> refuses to parse (with the error <code>SyntaxError: Bad escaped character in JSON at ... JSON.parse (&lt;anonymous&gt;)</code>):</p> <pre><code>{ &quot;results&quot;: [{ &quot;service_id&quot;: &quot;490803031657299972&quot;, &quot;business_name&quot;: &quot;Jay Contractors LLC&quot;, &quot;rating&quot;: 4.972222222222222, &quot;num_reviews&quot;: 36, &quot;years_in_business&quot;: 1, &quot;num_hires&quot;: 87, &quot;thumbtack_url&quot;: &quot;https://www.thumbtack.com/pa/lansdowne/handyman/jay-contractors-llc/service/490803031657299972?category_pk=151436204227846419\u0026utm_medium=partnership\u0026utm_source=cma-hewn\u0026zip_code=19701&quot;, &quot;image_url&quot;: &quot;https://production-next-images-cdn.thumbtack.com/i/490934068026425349/desktop/standard/thumb&quot;, &quot;background_image_url&quot;: &quot;https://production-next-images-cdn.thumbtack.com/i/319588452476190788/small/standard/hero&quot;, &quot;featured_review&quot;: &quot;Went and above and beyond to expose and fix other poorly done installations \u011f\x9f\x91\x8c\u011f\x9f\ufffd\xbd&quot;, &quot;quote&quot;: { &quot;starting_cost&quot;: 5000, &quot;cost_unit&quot;: &quot;on-site estimate&quot; }, &quot;introduction&quot;: &quot;My focus is quality, and dedication to the job. I take pride in every job, from start to finish. Always go for 100% satisfaction by client and see them smiling after the work is completed.\n\nPlease keep in mind if your using the instant book feature, it means your hiring me for my services and if you decide to cancel later on there will be a charge.\n\nAccept Cash, Cashapp, Zelle, and Venmo.\nNo Checks please.\n\nLicensed and Insured&quot;, &quot;pills&quot;: [&quot;popular&quot;, &quot;licensed&quot;], &quot;location&quot;: &quot;Bear, DE&quot;, &quot;similar_jobs_done&quot;: 1, &quot;license_verified&quot;: true, &quot;num_of_employees&quot;: 2, &quot;has_background_check&quot;: true, &quot;iframe_url&quot;: &quot;&quot; }] } </code></pre>
<python><json><jsonparser>
2023-12-18 14:29:33
0
1,000
velkoon
77,679,562
18,904,265
Docker build failed with Gitlab CI, service didn't start properly
<p>So I wanted to move my build step of my docker image to Gitlab CI. Since this is my first time using Gitlab CI to build a Docker Image, I'm guessing that I have an error in my configuration somewhere.</p> <p>The Error I get is: <code>ERROR: error during connect: Get &quot;http://docker:2375/_ping&quot;: dial tcp: lookup docker on 172.16.1.1:53: no such host</code></p> <p>The runner itself works, I am successfully testing my project with pytest in the first stage.</p> <p>Dockerfile:</p> <pre><code>FROM python:3.12 WORKDIR /vpapp COPY . . RUN pip install . EXPOSE 8501 HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health ENTRYPOINT [&quot;streamlit&quot;, &quot;run&quot;, &quot;src/vierpunktmessung/app.py&quot;, &quot;--server.port=8501&quot;, &quot;--server.address=0.0.0.0&quot;, &quot;--browser.serverPort=8501&quot;, &quot;--browser.serverAddress=***** (redacted)&quot;] </code></pre> <p>gitlab-ci.yml:</p> <pre><code>stages: - test - publish - deploy variables: TAG_LATEST: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:latest TAG_COMMIT: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:$CI_COMMIT_SHORT_SHA cache: paths: - .cache/pip - .venv/ test: tags: - runner01 image: python:3.12.1-bookworm stage: test script: - python -m venv .venv - source .venv/bin/activate - pip install -e . - pip install pytest - python -m pytest --junitxml=report.xml artifacts: when: always reports: junit: report.xml publish: tags: - runner01 image: docker:latest stage: publish services: - docker:dind script: - docker build -t $TAG_COMMIT -t $TAG_LATEST . - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY - docker push $TAG_COMMIT - docker push $TAG_LATEST </code></pre> <p>Log:</p> <pre><code>Running with gitlab-runner 16.4.1 (d89a789a) on gitlab-runner-01 ********, system ID: **************** Preparing the &quot;docker&quot; executor 00:37 Using Docker executor with image docker:latest ... Starting service docker:dind ... Pulling docker image docker:dind ... Using docker image sha256:6091c7bd89fd2789606b49815b2b9ea1a9142ee6e8762089ab3975afd6784a6c for docker:dind with digest docker@sha256:1b9844d846ce3a6a6af7013e999a373112c3c0450aca49e155ae444526a2c45e ... Waiting for services to be up and running (timeout 30 seconds)... *** WARNING: Service runner-******-project-54012-concurrent-0-800ab30c6863487b-docker-0 probably didn't start properly. Health check error: service &quot;runner-******-project-54012-concurrent-0-800ab30c6863487b-docker-0-wait-for-service&quot; timeout Health check container logs: 2023-12-18T13:43:57.661670033Z waiting for TCP connection to 172.17.0.2 on [2375 2376]... 2023-12-18T13:43:57.661719769Z dialing 172.17.0.2:2376... 2023-12-18T13:43:57.662046503Z dialing 172.17.0.2:2375... 2023-12-18T13:43:58.662376048Z dialing 172.17.0.2:2375... 2023-12-18T13:43:58.662407600Z dialing 172.17.0.2:2376... 2023-12-18T13:43:59.663019590Z dialing 172.17.0.2:2376... 2023-12-18T13:43:59.663108281Z dialing 172.17.0.2:2375... 2023-12-18T13:44:00.663636106Z dialing 172.17.0.2:2376... 2023-12-18T13:44:00.663681929Z dialing 172.17.0.2:2375... Service container logs: 2023-12-18T13:43:59.664635248Z Certificate request self-signature ok 2023-12-18T13:43:59.664657831Z subject=CN = docker:dind server 2023-12-18T13:43:59.683578956Z /certs/server/cert.pem: OK 2023-12-18T13:44:00.283957810Z Certificate request self-signature ok 2023-12-18T13:44:00.283994910Z subject=CN = docker:dind client 2023-12-18T13:44:00.303875863Z /certs/client/cert.pem: OK 2023-12-18T13:44:00.307856391Z ip: can't find device 'nf_tables' 2023-12-18T13:44:00.309849165Z modprobe: can't change directory to '/lib/modules': No such file or directory 2023-12-18T13:44:00.311224190Z ip: can't find device 'ip_tables' 2023-12-18T13:44:00.312297008Z ip_tables 32768 2 iptable_nat,iptable_filter 2023-12-18T13:44:00.312312542Z x_tables 40960 5 xt_conntrack,xt_MASQUERADE,xt_addrtype,iptable_filter,ip_tables 2023-12-18T13:44:00.312747425Z modprobe: can't change directory to '/lib/modules': No such file or directory 2023-12-18T13:44:00.315481382Z mount: permission denied (are you root?) 2023-12-18T13:44:00.315540711Z Could not mount /sys/kernel/security. 2023-12-18T13:44:00.315546317Z AppArmor detection and --privileged mode might break. 2023-12-18T13:44:00.316745444Z mount: permission denied (are you root?) ********* Pulling docker image docker:latest ... Using docker image sha256:6091c7bd89fd2789606b49815b2b9ea1a9142ee6e8762089ab3975afd6784a6c for docker:latest with digest docker@sha256:1b9844d846ce3a6a6af7013e999a373112c3c0450aca49e155ae444526a2c45e ... Preparing environment 00:00 Running on runner-******-project-54012-concurrent-0 via gitlab-srmuc-01... Getting source from Git repository 00:02 Fetching changes with git depth set to 20... Reinitialized existing Git repository in /builds/oe112/vierpunktmessung/.git/ Checking out def5ed33 as detached HEAD (ref is main)... Removing .pytest_cache/ Removing .venv/ Removing report.xml Removing src/vierpunktmessung/__pycache__/ Removing tests/__pycache__/ Skipping Git submodules setup Restoring cache 00:08 Checking cache for default-protected... cache.zip is up to date WARNING: .venv/bin/python: chmod .venv/bin/python: no such file or directory (suppressing repeats) Successfully extracted cache Executing &quot;step_script&quot; stage of the job script 00:00 Using docker image sha256:6091c7bd89fd2789606b49815b2b9ea1a9142ee6e8762089ab3975afd6784a6c for docker:latest with digest docker@sha256:1b9844d846ce3a6a6af7013e999a373112c3c0450aca49e155ae444526a2c45e ... $ docker build -t $TAG_COMMIT -t $TAG_LATEST . ERROR: error during connect: Get &quot;http://docker:2375/_ping&quot;: dial tcp: lookup docker on 172.16.1.1:53: no such host Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1 </code></pre>
<python><docker><gitlab-ci>
2023-12-18 13:56:43
1
465
Jan
77,679,260
9,766,795
Calculated EMA is lagging compared to Trading View EMA
<p>I'm using the binance connector API in python (<a href="https://binance-connector.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://binance-connector.readthedocs.io/en/latest/</a>) to calculate short, medium and long term EMA on the 1 minute chart. I have access to real time data from binance and so does my trading view account. I'm using the closing prices of candlesticks on both my program and trading view and I'm using the same lengths for the EMAs: 10 20 and 40:</p> <p><a href="https://i.sstatic.net/DqdnU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DqdnU.png" alt="EMA Config" /></a></p> <p>This is an example of one EMA. The other two have 20 and 40 in the length.</p> <p>I'm waiting for the short term EMA to cross over the medium and long term EMA but <strong>the problem that I have</strong> is that my EMA calculations cross over 4 to 5 minutes later compared to the ones on tradingview, even if we use the exact same data.</p> <p>This is the code (STMA, MTMA and LTMA stand for short, medium and long term moving average): I'm using the kline[4] because that's the closing price of the candle stick: <a href="https://binance-docs.github.io/apidocs/spot/en/#compressed-aggregate-trades-list" rel="nofollow noreferrer">https://binance-docs.github.io/apidocs/spot/en/#compressed-aggregate-trades-list</a></p> <pre class="lang-py prettyprint-override"><code> closing_prices: list[float] = [float(kline[4]) for kline in klines] SMALTMA = sum(closing_prices) / self.LTMA SMAMTMA = sum(closing_prices[len(closing_prices)-self.MTMA:]) / self.MTMA SMASTMA = sum(closing_prices[len(closing_prices)-self.STMA:]) / self.STMA EMALTMA = SMALTMA EMAMTMA = SMAMTMA EMASTMA = SMASTMA LTMA_ALPHA = 2 / (1 + self.LTMA) MTMA_ALPHA = 2 / (1 + self.MTMA) STMA_ALPHA = 2 / (1 + self.STMA) for i in range(len(closing_prices)): EMALTMA = (closing_prices[i] * LTMA_ALPHA) + (EMALTMA * (1 - LTMA_ALPHA)) if i &gt;= self.MTMA: EMAMTMA = (closing_prices[i] * MTMA_ALPHA) + (EMAMTMA * (1 - MTMA_ALPHA)) if i &gt;= self.STMA: EMASTMA = (closing_prices[i] * STMA_ALPHA) + (EMASTMA * (1 - STMA_ALPHA)) </code></pre> <p>This is how I calculate the short, medium and long term EMA. <em><strong>Are my calculations wrong?</strong></em> (I've used this : <a href="https://www.steema.com/docs/financialFunctionsRef/expMovingAverageFunction.htm" rel="nofollow noreferrer">https://www.steema.com/docs/financialFunctionsRef/expMovingAverageFunction.htm</a> to get the formula)</p> <p>In this example, as I've said, my EMA lengths have the same lengths as in trading view, so:</p> <pre class="lang-py prettyprint-override"><code>self.STMA = 10 self.MTMA = 20 self.LTMA = 40 </code></pre> <p><strong>What am I doing wrong?</strong></p> <p><strong>EDIT:</strong></p> <p>I've seen that the last value that I get from the klines is the current value of the current kline that hasn't closed yet. I've read that the EMA is, usually, calculated by only using the closing values of the klines, so I thought to ignore the last value that I get because that is not a value from a closed kline, so I will just get the EMA from the last candle:</p> <pre class="lang-py prettyprint-override"><code> closing_prices: list[float] = [float(kline[4]) for kline in klines][:-1] </code></pre> <p>The further calculations are the same as above. <strong>This still doesn't work</strong>. <strong>What else should I try/how should I fix this?</strong></p> <h2>Example of the problem:</h2> <p><a href="https://i.sstatic.net/XF9Kq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XF9Kq.png" alt="enter image description here" /></a></p> <p>My script showed me that the short term moving average went above the medium and long term moving average and the red candle stick I have my cursor on. This is, as you can see from the EMAs on tradingview, not true. <strong>It was late by 5 whole minutes</strong>.</p> <p><em><strong>UPDATE:</strong></em> I've also tried to set the starting point of the EMA to the first value of the closing_prices and to 0 and both of them didn't work. I've also tried to not use the value of the last price in the klines since that is not the closing price of a candle, but the current price of the current candle. It still didn't work.</p>
<python><algorithmic-trading><binance><binance-api-client>
2023-12-18 13:00:55
0
632
David
77,679,151
241,515
Pandas groupby: use data in other columns to create groups (genomic intervals)
<p>As part of a larger data set, I have a <code>DataFrame</code> organized as such:</p> <pre><code>Chromosome arm Start End ratio_median 5 5.5 96100001 96150000 -0.582 5 5.5 96150001 96200000 -0.582 5 5.5 96200001 96250000 -0.582 5 5.5 96250001 96300000 -0.582 5 5.5 96300001 96350000 -0.582 </code></pre> <p>The goal here is to group rows with the same <code>Chromosome</code>, <code>arm</code> and <code>ratio_median</code>, and form larger intervals using the minimum of <code>Start</code> and maximum of <code>End</code>.</p> <p>It looks like a bog-standard problem solvable with <code>groupby</code>:</p> <pre><code>grouped = df.groupby(by=[&quot;Chromosome&quot;, &quot;arm&quot;, &quot;ratio_median&quot;]).agg( {&quot;Chromosome&quot;: &quot;first&quot;, &quot;Start&quot;: &quot;min&quot;, &quot;End&quot;: &quot;max&quot;, &quot;ratio_median&quot;: &quot;first&quot;}) </code></pre> <p>However, since these are coordinates, grouping should only consider consecutive groups with the common grouping keys, not the entire data set. In other words, the group boundaries should be set when there is a change in <code>ratio_median</code> for the same chromosome and arm.</p> <p>The <code>groupby</code> approach works perfectly until you have intervals with the same values which are separated by one or more intervals with different keys (<code>ratio_median</code> being the discriminant element). For example, starting from these data:</p> <pre><code>Chromosome arm Start End ratio_median 5 5.5 96150001 96200000 -0.582 5 5.5 96200001 96250000 -0.582 5 5.5 96250001 96300000 -0.582 5 5.5 96300001 96350000 -0.582 5 5.5 97000001 97050001 -0.582 5 5.5 102600001 102650000 -0.014 5 5.5 102650001 102700000 -0.014 5 5.5 102700001 102750000 -0.014 5 5.5 102750001 102800000 -0.014 5 5.5 102800001 102850000 -0.014 5 5.5 103700001 103750000 -0.582 5 5.5 103750001 103800000 -0.582 5 5.5 103800001 103850000 -0.582 5 5.5 103850001 103900000 -0.582 5 5.5 103900001 103950000 -0.582 </code></pre> <p>There are three separate intervals here: but grouping with <code>groupby</code> will lump (correctly: it's working as intended) the third interval with the first:</p> <pre><code>Chromosome arm Start End ratio_median 5 5.5 96100001 103950000 -0.582 5 5.5 102600001 102850000 -0.014 </code></pre> <p>From the perspective of the coordinates, this is incorrect, because they should not overlap like that: only consecutive rows with the same grouping keys should be aggregated. The correct, expected result should be:</p> <pre><code>Chromosome arm Start End ratio_median 5 5.5 96100001 97050001 -0.582 5 5.5 102600001 102850000 -0.014 5 5.5 103700001 103950000 -0.582 </code></pre> <p>I'm not, however, aware of how to do this properly in pandas, nor with additional, domain-specific libraries like <code>PyRanges</code> or <code>bioframe</code>. I have tried <code>PyRanges.cluster()</code> but that, on the other hand, assigns IDs in a different way and the resulting intervals are smaller.</p> <p>My guess is that some form of iteration is required here, but what would be the best approach? I have tried <code>groupby</code> alone but again that suffers from the problem as above.</p>
<python><pandas><bioinformatics><pyranges>
2023-12-18 12:40:41
2
4,973
Einar
77,678,958
12,131,616
How to change an array using advanced indexing and boolean array indexing without loops in numpy?
<p><strong>Problem:</strong></p> <p><code>A</code> is a multidimensional array of two dimensions <code>(i,j)</code> and <code>B</code> is a boolean array of the same shape that I want to define according to the values of <code>A</code>.</p> <p>I want to define <code>B</code> through two broadcasting indices:</p> <ul> <li><code>i_b</code> is an array that selects the indices of the first coordinate.</li> <li><code>ij_b</code> is a boolean array that selects the indices j given i has already been selected.</li> </ul> <p><strong>Code:</strong></p> <p>The code I programmed:</p> <pre class="lang-py prettyprint-override"><code>A = np.arange(50).reshape(5, 10) #shape: (i, j) B = np.full(A.shape, False) #shape: (i, j) #We pick first dimension i_b = np.array([0, 2, 4]) #We pick second dimension given the first dimension has been chosen ij_b = A[i_b]%2 == 0 #Change B according to i and ij B[i_b][ij_b] = True print(B[i_b][ij_b]) </code></pre> <p>Output: <code>[False False False False False False False False False False False False False False False]</code>.</p> <p><strong>The line <code>B[i_b][ij_b] = True</code> does not seem to change <code>B</code>. Why does it happen? How can I perform this operation to change <code>B</code> in a vectorized way?</strong></p> <hr /> <p>I know I can write a loop that works:</p> <pre class="lang-py prettyprint-override"><code>for k in range(len(i_b)): B[i_b[k]][ij_b[k]] = True print(B[i_b][ij_b]) </code></pre> <p>Output: <code>[ True True True True True True True True True True True True True True True]</code></p> <p>But then it stops being vectorized.</p>
<python><numpy><vectorization><numpy-ndarray><array-broadcasting>
2023-12-18 12:04:52
1
663
Puco4
77,678,899
11,748,924
Extracting X_train and y_train from tabular data where a column is target and another columns are features with its corresponding ID
<p>I have this DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>timestep</th> <th>ID</th> <th>x1</th> <th>x2</th> <th>y</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>2</td> <td>3</td> <td>0</td> </tr> <tr> <td>2</td> <td>1</td> <td>4</td> <td>5</td> <td>0</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <td>24</td> <td>1</td> <td>5</td> <td>5</td> <td>0</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <td>1</td> <td>9</td> <td>2</td> <td>3</td> <td>1</td> </tr> <tr> <td>2</td> <td>9</td> <td>4</td> <td>5</td> <td>1</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <td>24</td> <td>9</td> <td>2</td> <td>2</td> <td>1</td> </tr> </tbody> </table> </div> <p>I expect it converted to the numpy ndarray <code>X_train</code> with shape (9, 24, 2). Where, <code>9</code> represent how many IDs. <code>24</code> represent <code>n-rows</code> aka <code>timestep</code>. <code>2</code> represents how many features (x1 and x2)</p> <p>It same to the <code>y_train</code> with shape <code>(9, 1)</code> where 9 represents how many IDs and 1 represents scalar value since all <code>y</code> will be same for all 24 timesteps</p> <p>The minimal reproducible example for this, when accessing <code>X_train[0,:,:]</code> it will returns table with <code>ID=1</code> with 24 rows (timesteps) like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>x1</th> <th>x2</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> </tr> <tr> <td>...</td> <td>...</td> </tr> <tr> <td>5</td> <td>5</td> </tr> </tbody> </table> </div> <p>(the last 24-th row)</p>
<python><pandas><dataframe><numpy><tabular>
2023-12-18 11:53:29
1
1,252
Muhammad Ikhwan Perwira
77,678,782
4,505,998
Interweave groups in Pandas
<p>I have a DataFrame that I want &quot;intereaved&quot; row-wise by groups.</p> <p>For example, this DataFrame:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Group</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>10</td> </tr> <tr> <td>A</td> <td>9</td> </tr> <tr> <td>A</td> <td>8</td> </tr> <tr> <td>B</td> <td>7</td> </tr> <tr> <td>B</td> <td>6</td> </tr> <tr> <td>B</td> <td>5</td> </tr> </tbody> </table> </div> <p>The desired result would be grabbing the first of A, and the first of B, then the second of A, then the second of B, etc.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Group</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>10</td> </tr> <tr> <td>B</td> <td>7</td> </tr> <tr> <td>A</td> <td>9</td> </tr> <tr> <td>B</td> <td>6</td> </tr> <tr> <td>A</td> <td>8</td> </tr> <tr> <td>B</td> <td>5</td> </tr> </tbody> </table> </div> <p>Any ideas?</p>
<python><pandas><dataframe>
2023-12-18 11:30:43
2
813
David Davó
77,678,640
7,801,777
How can I use variables as part of my bucket path with s3 boto client?
<p>At the moment Im trying to upload to a bucket with the variables as the path name using the boto s3 client and here are the variables I have defined:</p> <pre><code>var1 = A var2 = B var3 = C </code></pre> <p>I am uploading to the bucket like this:</p> <pre><code>client.upload_file('myfile.jpeg', 'bucket', 'directory/{var1}/{var2}/{var3}') </code></pre> <p>However the lambda function I am using is actually creating the variables as part of the file path. How can I actually use the values of var1,var2 and var3? My expected output is this:</p> <pre><code>directory/A/B/C </code></pre> <p>and my current output is this:</p> <pre><code>directory/{var1}/{var2}/{var3} </code></pre> <p>Thanks</p>
<python><amazon-web-services><aws-lambda><boto3>
2023-12-18 11:03:31
1
355
i'i'i'i'i'i'i'i'i'i
77,678,603
11,159,734
Create multiple functions in one Azure Function App
<p>I want to create multiple python Azure Functions within one Azure Functions App using the azure cli/core tools. One http triggered function and one blob triggered function.</p> <p>I have the following folder structure:</p> <pre><code>├── azure-functions │ ├── az-func-blob │ │ ├── .python_packages │ │ ├── .vscode │ │ ├── .gitignore │ │ ├── function_app.py │ │ ├── host.json │ │ ├── local_settings.json │ │ ├── requirements.txt │ ├── az-func-http │ │ ├── .python_packages │ │ ├── .vscode │ │ ├── .gitignore │ │ ├── function_app.py │ │ ├── host.json │ │ ├── local_settings.json │ │ ├── requirements.txt │ ├── README.md </code></pre> <p>Note: I created the individual function directories with the following commands within my project dir &quot;azure-functions&quot;:</p> <ol> <li><p>Blob function:</p> <p><code>func init az-func-blob --worker-runtime python --model V2</code></p> <p><code>cd az-func-blob</code></p> <p><code>func new --template &quot;Blob trigger&quot; --name BlobTrigger</code></p> </li> <li><p>Http function:</p> <p><code>func init az-func-http --worker-runtime python --model V2</code></p> <p><code>cd az-func-http</code></p> <p><code>func new --template &quot;HTTP trigger&quot; --name HTTPTrigger</code></p> </li> </ol> <p>If I navigate to the directory of one of these functions and run the command <code>func azure functionapp publish SPIEFUNC2</code> it works fine. However running this command again in the other function directory will overwrite the Trigger/Function in Azure instead of appending a new one even though the trigger names are different. Apparently that's just how it works in Azure but I don't know how to create multiple functions within one Function app.</p> <p>I saw this post <a href="https://stackoverflow.com/questions/57079549/deploying-multiple-function-under-same-azure-function-app-not-working">here</a> where someone suggested to use the same &quot;host.json&quot; for all functions. I don't know how to do this as every host.json is exactly the same anyway and looks like this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;version&quot;: &quot;2.0&quot;, &quot;logging&quot;: { &quot;applicationInsights&quot;: { &quot;samplingSettings&quot;: { &quot;isEnabled&quot;: true, &quot;excludedTypes&quot;: &quot;Request&quot; } } }, &quot;extensionBundle&quot;: { &quot;id&quot;: &quot;Microsoft.Azure.Functions.ExtensionBundle&quot;, &quot;version&quot;: &quot;[4.*, 5.0.0)&quot; } } </code></pre> <p>Can someone please explain in detail how to get set this up using only one Azure Function App instead of multiple function apps?</p>
<python><azure><azure-functions>
2023-12-18 10:57:35
1
1,025
Daniel
77,678,525
6,498,649
python pandas double aggregation function with nth(0)
<p>The following pandas aggregation:</p> <pre><code>df = pd.DataFrame({ 'a' : [1,1,1,1], 'b' : [1,2,3,4], 'c' : [np.nan,6,7,8], }) r = df.groupby('a').agg({ 'b' : 'mean', 'c' : 'nth(0)', }) </code></pre> <p>obviously gives:</p> <pre><code>AttributeError: 'SeriesGroupBy' object has no attribute 'nth(0)' </code></pre> <p>(I would use <code>'first'</code> for this, but it gives the first non null value and I want to include them).</p> <p>So, how to use the <code>nth</code> aggregation function on <code>c</code> toghether with <code>mean</code> on <code>b</code>?</p> <p>I know that this works but it's not so nice:</p> <pre><code>df.groupby('a').agg({ 'b' : 'mean', 'c' : lambda s:s.iloc[0], }) </code></pre>
<python><pandas><group-by>
2023-12-18 10:42:06
1
403
Dario Colombotto
77,678,414
4,537,160
Reverting pre-processing step on image returned by Pytorch Dataloader leads to unexpected results
<p>I created a Dataset in Pytorch to load images and feed them to a CNN. In the dataset <code>__getitem__</code> method, images are processed using a transform function (normalization on Imagenet avg values) before being returned.</p> <p>I noticed that, if I revert the transformed image inside the dataloader itself, I get back the original image as expected. However, if I do the same with one of the images returned from the dataloader, the image looks different. Isn't the dataloader just stacking the transformed images together?</p> <p>This is an example of the code I'm using (just returning copies of an image for which you have to specify the local path):</p> <pre><code>import cv2 import numpy as np import torch class CustomDataset(torch.utils.data.Dataset): def __init__(self, img_path): # RGB image self.img = cv2.imread(img_path)[:, :, ::-1] def __len__(self): return 100 def transform(self, img: np.array, data_type=np.float32): img = img.astype(data_type) / 255 img[:, :, 0] = (img[:, :, 0] - 0.485) / 0.229 img[:, :, 1] = (img[:, :, 1] - 0.456) / 0.224 img[:, :, 2] = (img[:, :, 2] - 0.406) / 0.225 return img def __getitem__(self, idx): images_raw = [self.img] * 5 # transform images images_transformed = np.array([self.transform(img) for img in images_raw]) images_transformed = torch.tensor(images_transformed) # test reconverting image and saving it here image_reconverted = transform_reverse(images_transformed[0].numpy()) cv2.imwrite(&quot;puppy_00_re_tranformed_in_dataloader.jpg&quot;, image_reconverted[:, :, ::-1]) return images_transformed def main(): img_path = &quot;puppy.jpg&quot; custom_dataset = CustomDataset(img_path) dataloader = torch.utils.data.DataLoader(custom_dataset, batch_size=10, shuffle=True, drop_last=True) for batch_data in dataloader: # take one of the images returned from Dataloader and apply reverse transform re_converted_img = transform_reverse(batch_data[0][0].numpy()) cv2.imwrite(&quot;puppy_01_re_transformed_in_main.jpg&quot;, re_converted_img[:, :, ::-1]) def transform_reverse(img): img[:, :, 0] = img[:, :, 0] * 0.229 + 0.485 img[:, :, 1] = img[:, :, 1] * 0.224 + 0.456 img[:, :, 2] = img[:, :, 2] * 0.225 + 0.406 img = np.round(img * 255).astype(np.uint8) return img if __name__ == &quot;__main__&quot;: main() </code></pre> <p>As a reference, this is the original image:</p> <p><a href="https://i.sstatic.net/sP7YY.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sP7YY.jpg" alt="original" /></a></p> <p>while this is the one after reversing the transformation in main:</p> <p><a href="https://i.sstatic.net/he7eG.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/he7eG.jpg" alt="enter image description here" /></a></p>
<python><pytorch><pytorch-dataloader>
2023-12-18 10:20:37
1
1,630
Carlo
77,678,244
1,394,786
how to discover a class's instance level fields given a class name
<p>Given the following class <strong>Mock</strong>, I want to write a function <strong>get_members</strong> that returns a and b when the input is the class Mock. This task is easy if you are allowed to use an object of Mock as the input of this function to be written ( you can use &quot;_ <em>dict</em>_&quot; or vars or inspect etc), but looks impossible if Mock (the class Mock itself rather than an object of Mock) is used as the input as neither vars, dir or inspect has knowledge on the existence of field a.</p> <pre><code>class Mock: def __init__(self, a): self.a=a def b(): pass def get_members(clz): &quot;&quot;&quot;return all the members of clz and its instance, including static methods, class methods, instance level methods and fields e.g., given Mock, return a and b &quot;&quot;&quot; </code></pre>
<python><member><inspect>
2023-12-18 09:54:20
1
480
Peaceful
77,678,147
1,889,750
Cannot install Python module 'arcgis'
<p>I try to install the module arcgis from the cheese shop and it fails. Here the cli...</p> <pre><code>(base) PS C:\Python311\Scripts&gt; .\pip3.11.exe install arcgis Could not find platform independent libraries &lt;prefix&gt; Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'C:\Python311\python.exe' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = 'C:\Python311\Scripts\Lib' sys._base_executable = 'C:\\Python311\\python.exe' sys.base_prefix = 'C:\\Python311\\Scripts' sys.base_exec_prefix = 'C:\\Python311' sys.platlibdir = 'DLLs' sys.executable = 'C:\\Python311\\python.exe' sys.prefix = 'C:\\Python311\\Scripts' sys.exec_prefix = 'C:\\Python311' sys.path = [ 'C:\\Python311\\python311.zip', 'C:\\Python311\\Scripts\\Lib', 'C:\\Python311\\DLLs', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' </code></pre> <p>Looking for solutions people either point at PYTHONHOME or PYTHONPATH, neither of them are set and this is also no virtual environment. The Python version I use is 3.11 and the module description is pointing at Python &gt;=3.9, &lt;3.12.</p> <p>Any suggestion what the real problem is and how to over com it?</p>
<python><pip><arcgis>
2023-12-18 09:34:40
1
1,355
TomGeo
77,677,960
3,099,733
Is that anyway to update c++ packages when the project is install with `pip install -e .`?
<p>I am working on a Python project that have some C++ packages in it. To make it easier to test, I used to install under developed Python packages with <code>pip install -e .</code>. It works well with pure python packages. But for the project with C++ packages in it this method won't work when the C++ code get updated. In order to it test I have to use <code>pip install .</code> to build wheel and install, which is kind of slow. Is there any solution to just build C++ packages in place to make <code>pip install -e .</code> work for such situation?</p>
<python><c++><pip><python-wheel>
2023-12-18 08:56:13
0
1,959
link89
77,677,826
2,529,125
logger.info throws result = f(record) # assume callable - will raise if not TypeError: 'bool' object is not callable
<p>A basic logger setup can be created using the following python code:</p> <pre><code>import logging # create and configure main logger logger = logging.getLogger(__name__) # create console handler with a higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) # create formatter and add it to the handler formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') secret_filter = False#SecretFilter() handler.setFormatter(formatter) # add the handler to the logger handler.addFilter(secret_filter) # prevent logging of secrets for hdlr in logger.handlers[:]: # remove the existing file handlers if isinstance(hdlr, logging.FileHandler): logger.removeHandler(hdlr) logger.addHandler(handler) logger.setLevel(logging.DEBUG) </code></pre> <p>When saving to the logger using the code snippet:</p> <pre><code>logger.info('setting up logger, done') </code></pre> <p>The output from the console results in :</p> <pre><code>2023-12-18 10:20:45,581 - __main__ - INFO - setting up logger, done 2023-12-18 10:20:45,581 - __main__ - INFO - setting up logger, done 2023-12-18 10:20:45,581 - __main__ - INFO - setting up logger, done 2023-12-18 10:20:45,581 - __main__ - INFO - setting up logger, done 2023-12-18 10:20:45,581 - __main__ - INFO - setting up logger, done Traceback (most recent call last): Cell In[27], line 1 logger.info('setting up logger, done') File ~\AppData\Local\anaconda3\envs\prod-env-shap\Lib\logging\__init__.py:1489 in info self._log(INFO, msg, args, **kwargs) File ~\AppData\Local\anaconda3\envs\prod-env-shap\Lib\logging\__init__.py:1634 in _log self.handle(record) File ~\AppData\Local\anaconda3\envs\prod-env-shap\Lib\logging\__init__.py:1644 in handle self.callHandlers(record) File ~\AppData\Local\anaconda3\envs\prod-env-shap\Lib\logging\__init__.py:1706 in callHandlers hdlr.handle(record) File ~\AppData\Local\anaconda3\envs\prod-env-shap\Lib\logging\__init__.py:974 in handle rv = self.filter(record) File ~\AppData\Local\anaconda3\envs\prod-env-shap\Lib\logging\__init__.py:832 in filter result = f(record) # assume callable - will raise if not TypeError: 'bool' object is not callable </code></pre> <p>I tried many setups and they result in the same issue. Please note im using the following setup:</p> <pre><code>python 3.11.5 pandas 2.1.4 holidays 0.29 scikit-learn 1.3.0 jaydebeapi 1.2.3 boto3 1.29.1 </code></pre>
<python><conda>
2023-12-18 08:27:42
0
511
Sade
77,677,714
6,446,146
gunicorn post_request vs flask.after_request
<p>I'm trying to understand the difference between <a href="https://docs.gunicorn.org/en/stable/settings.html#post-request" rel="nofollow noreferrer">gunicorn</a> <code>post_request()</code> callback and <a href="https://flask.palletsprojects.com/en/3.0.x/api/#flask.Flask.after_request" rel="nofollow noreferrer">flask</a> <code>after_request()</code> callback, and I'm trying to understand when to use each.</p>
<python><flask><gunicorn>
2023-12-18 08:03:21
0
417
yeger
77,677,570
1,190,316
Get the Max value of a row and get its' column name along with an additional column in the output
<p>I have the following data frame:</p> <p><a href="https://i.sstatic.net/I3EAW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/I3EAW.png" alt="enter image description here" /></a></p> <p>I want to get the highest value from each row in the data frame and get it's corresponding column name along with the ItemName column as well like this:</p> <p><a href="https://i.sstatic.net/XoB1u.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XoB1u.png" alt="enter image description here" /></a></p> <p>I was able to get the Max Values using this code:</p> <pre><code>result = new_df.max(axis=1) result.index = new_df.idxmax(axis=1) print(result) </code></pre> <p>Ouput:</p> <p><a href="https://i.sstatic.net/ENxEB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ENxEB.png" alt="enter image description here" /></a></p> <p>How do I include the ItemName Column as well in the output to get the following format?</p> <p><a href="https://i.sstatic.net/k1Tzr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/k1Tzr.png" alt="enter image description here" /></a></p>
<python><pandas><dataframe><max>
2023-12-18 07:32:08
1
1,465
Sindu_
77,677,428
11,141,816
Sympy Dummy symbol in the derivative could not be replaced
<p>I have a very long expression where, after the derivative, the term with the dummy variable <code>_xi_1</code> appeared,</p> <pre><code>Subs(Derivative(eta(_xi_1), _xi_1), _xi_1, 0) type(exp_list[0].args[2].args[2].args[1][0]) sympy.core.symbol.Dummy </code></pre> <p>I tried to replace the dummy variable with the new symbol <code>s</code></p> <pre><code>[e_xi_1 ] = exp_list[0].args[2].args[2].args[1][0].free_symbols </code></pre> <p>it did not work,</p> <pre><code>for ix in exp_list: print( ix.subs(_xi_1 ,s) ) </code></pre> <p>still print out the derivative with respect to <code>_xi_1</code>.</p> <p>This is important because though</p> <pre><code>Subs(Derivative(eta(_xi_1), _xi_1), _xi_1, 0) == Subs(Derivative(eta(s), s), s, 0) True </code></pre> <p>when I tried to substitute the expressions such as <code>Subs(Derivative(eta(s), s), s, 0)</code> from a list, it would not replace <code>Subs(Derivative(eta(_xi_1), _xi_1), _xi_1, 0)</code>.</p> <p>How to replace the dummy variable so that the <code>Subs(Derivative(eta(_xi_1), _xi_1), _xi_1, 0)</code> could be replaced to <code>Subs(Derivative(eta(s), s), s, 0)</code> so that it could be replaced to the numerical values?</p> <hr /> <p>A reproducible example</p> <pre><code>from sympy import Function eta = Function('eta') from sympy import * eta = Function('eta') s, x=symbols('s x',real =True) exp_01=1/eta(s+x)* exp(-2*pi*exp(exp(s) +x))*(1- exp(-2*pi*exp(exp(s) +x)) ) exp_02 = exp_01.diff(s,5).subs(s,0).subs(x,0).expand() dummy_symbol = exp_02.args[9].args[1].args[0].args[1][0] </code></pre> <p>if you compare the expressions in</p> <pre><code>exp_02 </code></pre> <p>and</p> <pre><code>exp_02.subs(dummy_symbol, s) # the dummy symbol won't be replaced exp_02.subs(Subs(Derivative(eta(dummy_symbol), dummy_symbol), dummy_symbol, 0),2) exp_02.subs(Subs(Derivative(eta(s), s), s, 0),2) exp_02.subs(Subs(Derivative(eta(s), (s, 0)), s, 0),2) </code></pre> <p>some derivatives might be substituted, but lots of the expressions that ought to be substituted remained.</p>
<python><sympy>
2023-12-18 07:05:46
1
593
ShoutOutAndCalculate
77,677,227
7,601,346
Passing str as parameter to class definition? Defining a separate class for key for sorted?
<p>I'm learning and Python and am trying to understand the code below</p> <pre><code>class LargerNumKey(str): def __lt__(x, y): return x+y &gt; y+x class Solution: def largestNumber(self, nums): largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey)) return '0' if largest_num[0] == '0' else largest_num </code></pre> <p>What I understand is that we are sorting a list, and we are passing the class LargerNumKey as the comparator.</p> <p>The idea is that we are given a list of ints, and we convert these ints to strings. We are sorting the list of now strings in an order such that the concatenation of all the strings in the list would produce the largest number.</p> <p>Thus, when sorting, a string a is considered larger than string b when ab &gt; ba. However due to my unfamiliarity with Python I have several questions about this code</p> <ol> <li><p>What does it mean to have str as the argument passed to the class definition of LargerNumKey?</p> </li> <li><p>And why is it necessary to define a completely new class rather than just a function to be passed as key to sorted?</p> </li> <li><p>I understand that <code>_lt_</code> is defining the less than operator for the LargerNumKey class. But I usually see <code>__lt__(self, other)</code>. So in this case is x representing self?</p> </li> </ol>
<python>
2023-12-18 06:04:48
1
1,200
Shisui
77,677,226
16,312,980
jupyterlab not detecting installed module: textract and doc2text
<p>I did this in a jupyter lab cell:</p> <pre><code>!pip install textract </code></pre> <p>and i managed to installed it successfully.</p> <p>I also installed textract and doc2text in command line too in my conda environment.</p> <p>But when I tried to import in a jupyter lab cell:</p> <pre><code>import textract </code></pre> <pre><code>ModuleNotFoundError Traceback (most recent call last) Cell In[25], line 1 ----&gt; 1 import textract ModuleNotFoundError: No module named 'textract' </code></pre> <p>I understand there is already some questions on these so I tried the most upvoted answers out without any avail.<br /> <a href="https://stackoverflow.com/questions/50953880/importerror-no-module-named-textract">ImportError: No module named textract</a><br /> <a href="https://stackoverflow.com/questions/44295470/python-textract-importerror">Python textract ImportError</a></p> <p>The funny part is that in python interpreter prompt on command line, I am able to import these.</p>
<python><pip><conda><jupyter-lab><development-environment>
2023-12-18 06:04:22
1
426
Ryan
77,677,185
6,027,759
How can I reference an environment variable for python path in vscode launch configuration?
<p>I am using vscode on my desktop and laptop and each machine would generate a random folder name with a hash for the virtual environment path when creating the virtual environment using poetry. In order to use the same launch.json file in my project for both computers, I'd like to reference an environment variable instead of hard coding the virtual environment path names. I've tried the below but vscode is stating &quot;The Python path in your debug configuration is invalid.&quot; How can I reference the environment variable for the &quot;python&quot; path?</p> <p>my <code>~/.zshrc</code>:</p> <pre><code>export PROJ_VENV=$HOME/.cache/pypoetry/virtualenvs/myproj-NMmw6p6o-py3.12 </code></pre> <p>my <code>launch.json</code>:</p> <pre><code>{ &quot;version&quot;: &quot;0.2.0&quot;, &quot;configurations&quot;: [ { &quot;name&quot;: &quot;Python: Django&quot;, &quot;type&quot;: &quot;python&quot;, &quot;python&quot;: &quot;${env:PROJ_VENV}/bin/python&quot;, &quot;request&quot;: &quot;launch&quot;, &quot;program&quot;: &quot;${workspaceFolder}/src/manage.py&quot;, &quot;args&quot;: [ &quot;runserver&quot;, ], &quot;django&quot;: true } ] } </code></pre>
<python><visual-studio-code><vscode-debugger>
2023-12-18 05:50:30
1
1,729
bayman
77,677,098
5,005,808
keras_nlp.models.from_preset gets Segmentation fault (core dumped)
<p>I'm using <code>keras_nlp</code> and I get <code>Segmentation fault (core dumped)</code> in the following code:</p> <pre><code>import os os.environ[&quot;KERAS_BACKEND&quot;] = &quot;torch&quot; # &quot;jax&quot; or &quot;tensorflow&quot; or &quot;torch&quot; import keras_nlp import keras_core as keras import keras_core.backend as K import torch import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl cmap = mpl.cm.get_cmap('coolwarm') class CFG: verbose = 0 # Verbosity wandb = True # Weights &amp; Biases logging competition = 'llm-detect-ai-generated-text' # Competition name _wandb_kernel = 'awsaf49' # WandB kernel comment = 'DebertaV3-MaxSeq_200-ext_s-torch' # Comment description preset = &quot;deberta_v3_base_en&quot; # Name of pretrained models sequence_length = 200 # Input sequence length device = 'TPU' # Device seed = 42 # Random seed num_folds = 5 # Total folds selected_folds = [0, 1, 2] # Folds to train on epochs = 3 # Training epochs batch_size = 3 # Batch size drop_remainder = True # Drop incomplete batches cache = True # Caches data after one iteration, use only with `TPU` to avoid OOM scheduler = 'cosine' # Learning rate scheduler class_names = [&quot;real&quot;, &quot;fake&quot;] # Class names [A, B, C, D, E] num_classes = len(class_names) # Number of classes class_labels = list(range(num_classes)) # Class labels [0, 1, 2, 3, 4] label2name = dict(zip(class_labels, class_names)) # Label to class name mapping name2label = {v: k for k, v in label2name.items()} # Class name to label mapping keras.utils.set_random_seed(CFG.seed) def get_device(): &quot;Detect and intializes GPU/TPU automatically&quot; try: # Connect to TPU tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # Set TPU strategy strategy = tf.distribute.TPUStrategy(tpu) print(f'&gt; Running on TPU', tpu.master(), end=' | ') print('Num of TPUs: ', strategy.num_replicas_in_sync) device=CFG.device except: # If TPU is not available, detect GPUs gpus = tf.config.list_logical_devices('GPU') ngpu = len(gpus) # Check number of GPUs if ngpu: # Set GPU strategy strategy = tf.distribute.MirroredStrategy(gpus) # single-GPU or multi-GPU # Print GPU details print(&quot;&gt; Running on GPU&quot;, end=' | ') print(&quot;Num of GPUs: &quot;, ngpu) device='GPU' else: # If no GPUs are available, use CPU print(&quot;&gt; Running on CPU&quot;) strategy = tf.distribute.get_strategy() device='CPU' return strategy, device # Initialize GPU/TPU/TPU-VM strategy, CFG.device = get_device() CFG.replicas = strategy.num_replicas_in_sync BASE_PATH = '/some/path/' print(1) preprocessor = keras_nlp.models.DebertaV3Preprocessor.from_preset( preset=CFG.preset, # Name of the model sequence_length=CFG.sequence_length, # Max sequence length, will be padded if shorter ) print(2) </code></pre> <p>The complete log is as follows:</p> <pre><code>$python test.py Using PyTorch backend. /mypath/test.py:22: MatplotlibDeprecationWarning: The get_cmap function was deprecated in Matplotlib 3.7 and will be removed two minor releases later. Use ``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap(obj)`` instead. cmap = mpl.cm.get_cmap('coolwarm') &gt; Running on GPU | Num of GPUs: 1 1 Segmentation fault (core dumped) </code></pre> <p>What's wrong with this? I'm using a Nvidia-A100 with 80GB memory, it should be large enough I guess.</p> <p>Thank you all for helping me!!!</p>
<python><keras><large-language-model>
2023-12-18 05:26:14
0
1,930
pfc
77,676,828
15,845,509
Understand weight in PyTorch convolution layer 1D
<p>I am trying to understand the work of convolution layer 1D in PyTorch. I use Conv1D(750,14,1) with input channels equal to 750, output channels are 14 with kernel size 1. As I understand, the weight in convolution layer is the kernel/filter so in this case, the weight dimension is 14x1. but when I print the weight, the dimension is 14x750x1.</p> <p>Is my understanding about weight for convolution layer wrong?</p>
<python><pytorch><conv-neural-network><convolution>
2023-12-18 03:37:50
2
369
ryan chandra
77,676,757
1,174,378
Run a full Flask server under pytest to handle HTTP requests on a given port
<p>Normally, when testing an endpoint, the <a href="https://flask.palletsprojects.com/en/2.3.x/testing/" rel="nofollow noreferrer">Flask docs</a> recommend doing something like this:</p> <pre class="lang-py prettyprint-override"><code>import pytest from my_project import create_app @pytest.fixture() def app(): app = create_app() yield app @pytest.fixture() def client(app): return app.test_client() </code></pre> <p>and then using the <code>client</code> fixture in a test like so:</p> <pre class="lang-py prettyprint-override"><code>def test_ping(client): response = client.get(&quot;/foobar&quot;) assert response.status_code == 200 </code></pre> <p>However, in some very niche cases, the code which handles the <code>/foobar</code> endpoint might need to make a HTTP call back to the Flask server (imagine it imports a poorly-designed library which needs to fetch some data from an endpoint and it doesn't allow you to inject a custom fetcher, so all you can do is to specify a custom URL). How can I run the entire Flask server in a background thread?</p>
<python><flask><pytest><werkzeug>
2023-12-18 03:09:14
1
8,364
Mihai Todor
77,676,747
9,357,484
Google Colab unable to Hugging Face model
<p>I like to tag parts of speech using the BERT model. I used the <a href="https://huggingface.co/AdapterHub/bert-base-uncased-pf-ud_pos" rel="nofollow noreferrer">Hugging face</a> library for this purpose.</p> <p>When I run the model on Hugging face API I got the output <a href="https://i.sstatic.net/RjeUj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RjeUj.png" alt="enter image description here" /></a></p> <p>However, when I run the code on Google Colab I got errors.</p> <p>My code</p> <pre><code>from transformers import AutoModelWithHeads from transformers import pipeline from transformers import AutoTokenizer model = AutoModelWithHeads.from_pretrained(&quot;bert-base-uncased&quot;) adapter_name = model.load_adapter(&quot;AdapterHub/bert-base-uncased-pf-ud_pos&quot;, source=&quot;hf&quot;) model.active_adapters = adapter_name tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;) token_classification = pipeline(&quot;token-classification&quot;, model=model, tokenizer=tokenizer, aggregation_strategy=&quot;NONE&quot;) res = token_classification(&quot;Take out the trash bag from the bin and replace it.&quot;) print(res) </code></pre> <p>The error is</p> <pre><code> The model 'BertModelWithHeads' is not supported for token-classification. Supported models are ['AlbertForTokenClassification', 'BertForTokenClassification', 'BigBirdForTokenClassification', 'BloomForTokenClassification', 'CamembertForTokenClassification', 'CanineForTokenClassification', 'ConvBertForTokenClassification', 'Data2VecTextForTokenClassification', 'DebertaForTokenClassification', 'DebertaV2ForTokenClassification', 'DistilBertForTokenClassification', 'ElectraForTokenClassification', 'ErnieForTokenClassification', 'EsmForTokenClassification', 'FlaubertForTokenClassification', 'FNetForTokenClassification', 'FunnelForTokenClassification', 'GPT2ForTokenClassification', 'GPT2ForTokenClassification', 'IBertForTokenClassification', 'LayoutLMForTokenClassification', 'LayoutLMv2ForTokenClassification', 'LayoutLMv3ForTokenClassification', 'LiltForTokenClassification', 'LongformerForTokenClassification', 'LukeForTokenClassification', 'MarkupLMForTokenClassification', 'MegatronBertForTokenClassification', 'MobileBertForTokenClassification', 'MPNetForTokenClassification', 'NezhaForTokenClassification', 'NystromformerForTokenClassification', 'QDQBertForTokenClassification', 'RemBertForTokenClassification', 'RobertaForTokenClassification', 'RobertaPreLayerNormForTokenClassification', 'RoCBertForTokenClassification', 'RoFormerForTokenClassification', 'SqueezeBertForTokenClassification', 'XLMForTokenClassification', 'XLMRobertaForTokenClassification', 'XLMRobertaXLForTokenClassification', 'XLNetForTokenClassification', 'YosoForTokenClassification', 'XLMRobertaAdapterModel', 'RobertaAdapterModel', 'AlbertAdapterModel', 'BeitAdapterModel', 'BertAdapterModel', 'BertGenerationAdapterModel', 'DistilBertAdapterModel', 'DebertaV2AdapterModel', 'DebertaAdapterModel', 'BartAdapterModel', 'MBartAdapterModel', 'GPT2AdapterModel', 'GPTJAdapterModel', 'T5AdapterModel', 'ViTAdapterModel']. --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-18-79b43720402e&gt; in &lt;cell line: 12&gt;() 10 tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;) 11 token_classification = pipeline(&quot;token-classification&quot;, model=model, tokenizer=tokenizer, aggregation_strategy=&quot;NONE&quot;) ---&gt; 12 res = token_classification(&quot;Take out the trash bag from the bin and replace it.&quot;) 13 print(res) 4 frames /usr/local/lib/python3.10/dist-packages/transformers/pipelines/token_classification.py in aggregate(self, pre_entities, aggregation_strategy) 346 score = pre_entity[&quot;scores&quot;][entity_idx] 347 entity = { --&gt; 348 &quot;entity&quot;: self.model.config.id2label[entity_idx], 349 &quot;score&quot;: score, 350 &quot;index&quot;: pre_entity[&quot;index&quot;], </code></pre> <p>KeyError: 16</p> <p>I don't understand if the model ran ok in the Hugging Face API then why it was unable to run on Google Colab?</p> <p>Thank you in advance.</p>
<python><nlp><google-colaboratory><huggingface-transformers><bert-language-model>
2023-12-18 03:07:35
2
3,446
Encipher
77,676,735
15,587,184
Resolving Selenium Driver issue on AWS EC2 Linux RedHat
<p>I have a peculiar issue while trying to set up Selenium WebDriver on an AWS EC2 instance running Red Hat. I'm using Google Chrome version 120.0.6099.109 on this instance.</p> <p>I have been trying to install the appropriate ChromeDriver for this Chrome version, but I've encountered an intermittent problem. My Selenium Python script sometimes runs successfully, and other times, it reports that &quot;chrome has crashed.&quot; I have tried multiple versions of ChromeDriver without consistent success.</p> <p>Here's the version of Google Chrome I have:</p> <pre><code>$ google-chrome --version Google Chrome 120.0.6099.109 </code></pre> <p>I've attempted to download the corresponding ChromeDriver version (e.g., 120.0.6099.71), but the issue persists. I've also tried various versions of ChromeDriver with no consistent results.</p> <p>Below is a snippet of the Python script using Selenium:</p> <pre><code>chrome_options = webdriver.ChromeOptions() prefs = { &quot;download.prompt_for_download&quot;: False, &quot;plugins.always_open_pdf_externally&quot;: True, &quot;download.open_pdf_in_system_reader&quot;: False, &quot;profile.default_content_settings.popups&quot;: 0, &quot;download.default_directory&quot;: file_path_descargas_guias } chrome_options.add_experimental_option('prefs', prefs) chrome_options.add_argument(&quot;--headless&quot;) chrome_options.add_argument('--no-sandbox') chrome_options.add_argument(&quot;--disable-dev-shm-usage&quot;) driver = webdriver.Chrome(options=chrome_options) </code></pre> <p>The weird thing is that sometimes IT DOES work, but most of the time it does not the cell on Jupyter Labs keeps &quot;running&quot; until I get this error:</p> <pre><code>--------------------------------------------------------------------------- SessionNotCreatedException Traceback (most recent call last) Cell In[11], line 16 13 chrome_options.add_argument('--no-sandbox') 14 chrome_options.add_argument(&quot;--disable-dev-shm-usage&quot;) ---&gt; 16 driver = webdriver.Chrome(options=chrome_options) File ~/anaconda3/lib/python3.11/site-packages/selenium/webdriver/chrome/webdriver.py:45, in WebDriver.__init__(self, options, service, keep_alive) 42 service = service if service else Service() 43 options = options if options else Options() ---&gt; 45 super().__init__( 46 browser_name=DesiredCapabilities.CHROME[&quot;browserName&quot;], 47 vendor_prefix=&quot;goog&quot;, 48 options=options, 49 service=service, 50 keep_alive=keep_alive, 51 ) File ~/anaconda3/lib/python3.11/site-packages/selenium/webdriver/chromium/webdriver.py:61, in ChromiumDriver.__init__(self, browser_name, vendor_prefix, options, service, keep_alive) 52 executor = ChromiumRemoteConnection( 53 remote_server_addr=self.service.service_url, 54 browser_name=browser_name, (...) 57 ignore_proxy=options._ignore_local_proxy, 58 ) 60 try: ---&gt; 61 super().__init__(command_executor=executor, options=options) 62 except Exception: 63 self.quit() File ~/anaconda3/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py:209, in WebDriver.__init__(self, command_executor, keep_alive, file_detector, options) 207 self._authenticator_id = None 208 self.start_client() --&gt; 209 self.start_session(capabilities) File ~/anaconda3/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py:293, in WebDriver.start_session(self, capabilities) 286 &quot;&quot;&quot;Creates a new session with the desired capabilities. 287 288 :Args: 289 - capabilities - a capabilities dict to start the session with. 290 &quot;&quot;&quot; 292 caps = _create_caps(capabilities) --&gt; 293 response = self.execute(Command.NEW_SESSION, caps)[&quot;value&quot;] 294 self.session_id = response.get(&quot;sessionId&quot;) 295 self.caps = response.get(&quot;capabilities&quot;) File ~/anaconda3/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py:348, in WebDriver.execute(self, driver_command, params) 346 response = self.command_executor.execute(driver_command, params) 347 if response: --&gt; 348 self.error_handler.check_response(response) 349 response[&quot;value&quot;] = self._unwrap_value(response.get(&quot;value&quot;, None)) 350 return response File ~/anaconda3/lib/python3.11/site-packages/selenium/webdriver/remote/errorhandler.py:229, in ErrorHandler.check_response(self, response) 227 alert_text = value[&quot;alert&quot;].get(&quot;text&quot;) 228 raise exception_class(message, screen, stacktrace, alert_text) # type: ignore[call-arg] # mypy is not smart enough here --&gt; 229 raise exception_class(message, screen, stacktrace) SessionNotCreatedException: Message: session not created: DevToolsActivePort file doesn't exist Stacktrace: #0 0x5635242acd33 &lt;unknown&gt; #1 0x563523f69f87 &lt;unknown&gt; #2 0x563523fa5e21 &lt;unknown&gt; #3 0x563523fa1d9f &lt;unknown&gt; #4 0x563523f9e4de &lt;unknown&gt; #5 0x563523feea90 &lt;unknown&gt; #6 0x563523fe30e3 &lt;unknown&gt; #7 0x563523fab044 &lt;unknown&gt; #8 0x563523fac44e &lt;unknown&gt; #9 0x563524271861 &lt;unknown&gt; #10 0x563524275785 &lt;unknown&gt; #11 0x56352425f285 &lt;unknown&gt; #12 0x56352427641f &lt;unknown&gt; #13 0x56352424320f &lt;unknown&gt; #14 0x56352429a028 &lt;unknown&gt; #15 0x56352429a1f7 &lt;unknown&gt; #16 0x5635242abed4 &lt;unknown&gt; #17 0x7f84fd69f802 start_thread </code></pre> <p>or:</p> <p>I did download an dunzip the webdriver and put in PATH but I'm lost right now.</p> <p>I am seeking any insights into the following:</p> <p>The recommended version of ChromeDriver for Google Chrome 120.0.6099.109 on Linux/Red Hat. Any specific configurations or adjustments needed for running Selenium WebDriver in headless mode on an AWS EC2 instance without display hardware. Or what would be the proper way to set the path of the WebDriver?</p>
<python><selenium-webdriver><amazon-ec2><selenium-chromedriver>
2023-12-18 03:03:40
1
809
R_Student
77,676,693
6,396,569
How can I add tabs to this Tk application in Python 3.12.0?
<p>I have an app where there is a <code>main</code> function that looks like this:</p> <pre><code>root = Tk() root.title(&quot;MyApp&quot;) #Set the initial size of the window and make it resizeable root.geometry(&quot;1024x768&quot;) root.resizable(True,True) app = AudioPlayer(master=root) app.pack(fill=&quot;both&quot;, expand=True) app.mainloop() </code></pre> <p>and a class that looks like this:</p> <pre><code>class AudioPlayer(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() #Spawn the GUI </code></pre> <p>Finally, my <code>create_widgets()</code> method looks like this:</p> <pre><code>def create_widgets(self): &quot;&quot;&quot; Creates the individual items in the Tk window, and specifies which handlers to call when they are interacted with &quot;&quot;&quot; # Frame for Sample buttons sample_button_frame = Frame(self) sample_button_frame.pack(side=&quot;top&quot;, fill=&quot;x&quot;, padx=5, pady=5) # Sample Filter Buttons self.button_kick = Button(sample_button_frame, text=&quot;Kick&quot;, command=self.filter_kick) self.button_kick.pack(side=&quot;left&quot;,padx=5) self.button_clap = Button(sample_button_frame,text=&quot;Clap&quot;,command=self.filter_clap) self.button_clap.pack(side=&quot;left&quot;,padx=5) </code></pre> <p>The app currently works fine. The problem is that I need to now after-the-fact, add tabs to this app. I want everything that already exists to be in Tab 1, and I want to add another tab for the new features I am about to introduce. I understand I need to use a <code>Notebook</code>. What I do not understand is how I need to set this class and the instantiation up so that all of the current widgets are attached to Tab 1 rather than the main Tk <code>root</code> Frame. I have attempted to alter <code>main</code> to do the following:</p> <pre><code>root = Tk() root.title(&quot;MyApp&quot;) #Set the initial size of the window and make it resizeable root.geometry(&quot;1024x768&quot;) root.resizable(True,True) notebook = ttk.Notebook(root) tab1 = Frame(notebook) tab2 = Frame(notebook) notebook.add(tab1,text=&quot;Tab 1&quot;) notebook.add(tab2, text=&quot;Tab 2&quot;) app = AudioPlayer(root, notebook) app.pack(fill=&quot;both&quot;, expand=True) app.mainloop() </code></pre> <p>However, this is not working as intended. The <code>AudioPlayer</code> class doesn't seem to properly communicate to the widgets that I need to add the widgets to <code>Tab 1</code> under this configuration. As a final example, I attemped to do this:</p> <p><code>sample_button_frame = Frame(tab1)</code></p> <p>And now when I run the app GUI, the entire <code>sample_button_frame</code> is missing and there are no tabs at the top.</p>
<python><tkinter>
2023-12-18 02:45:29
1
2,567
the_endian
77,676,622
5,058,488
What's wrong with this coin change python implementation?
<p>I'm reading through <a href="https://mitp-content-server.mit.edu/books/content/sectbyfn/books_pres_0/6515/sicp.zip/index.html" rel="nofollow noreferrer">Structure and Interpretation of Computer Programs</a>, and on section 1.2.2 there's a brute force implementation of the coin change problem given:</p> <pre><code>(define (count-change amount) (cc amount 5)) (define (cc amount kinds-of-coins) (cond ((= amount 0) 1) ((or (&lt; amount 0) (= kinds-of-coins 0)) 0) (else (+ (cc amount (- kinds-of-coins 1)) (cc (- amount (first-denomination kinds-of-coins)) kinds-of-coins))))) (define (first-denomination kinds-of-coins) (cond ((= kinds-of-coins 1) 1) ((= kinds-of-coins 2) 5) ((= kinds-of-coins 3) 10) ((= kinds-of-coins 4) 25) ((= kinds-of-coins 5) 50))) </code></pre> <p><a href="https://leetcode.com/problems/coin-change/" rel="nofollow noreferrer">On Leetcode</a>, the same problem is asked as such:</p> <p>Input: coins = [1,2,5], amount = 11</p> <p>Output: 3</p> <p>Explanation: 11 = 5 + 5 + 1</p> <p>I attempted doing a literal translation of the scheme code into Python but I am not getting the result I expected. In particular, I don't understand why this code is not giving me the same results as the SICP code even though both <em>seem</em> so similar! the only big difference I can see here is that, since the coins are given as a list instead of a hash map I can choose from, I iterate over each number by popping each number from the list.</p> <pre><code>def coinChange(self, coins: List[int], amount: int) -&gt; int: if amount == 0: return 1 if amount &lt; 0 or not coins: return 0 # do not choose current coin return (self.coinChange(coins[1:], amount) + self.coinChange(coins, amount - coins[0])) # choose current coin. </code></pre>
<python><scheme><racket>
2023-12-18 02:05:22
2
647
Alejandro