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
75,566,575
2,218,321
How to use the dataset comes from pytorch random_split()?
<p>I'm new to pyTorch and this is my first project. I need to split the dataset and feed the training dataset to model. <strong>The training dataset must be splitted in to features and labels (which I failed to do that)</strong>. Here is what I have tried so far, however, I don't know how to feed the dataset obtained from <code>random_split()</code> to model.</p> <pre><code>import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import SGD import matplotlib.pyplot as plt import seaborn as sns from dataset import DataSet class NeuralNetwork(nn.Module): input_dim = 10 hidden_dim = 4 output_dim = 1 def __init__(self, dataset): super().__init__() self.layers = [ nn.Linear(self.input_dim, self.hidden_dim), nn.Linear(self.hidden_dim, self.output_dim) ] self.train_dataset = dataset[&quot;train_dataset&quot;] self.test_dataset = dataset[&quot;test_dataset&quot;] self.layers = nn.ModuleList(self.layers) def forward(self, x): for layer in self.layers: x = nn.functional.rrelu(layer(x)) dataset = DataSet() model = NeuralNetwork(dataset) model(dataset[&quot;train_dataset&quot;]) </code></pre> <p>and this is <code>dataset.py</code></p> <pre><code>import pandas as pd import torch from torch.utils.data import DataLoader class DataSet: divide_rate = 0.8 file = './pima-indians-diabetes.csv' def __init__(self): data_set = pd.read_csv(self.file) train_size = int(self.divide_rate * len(data_set)) test_size = len(data_set) - train_size self.train_dataset, self.test_dataset = torch.utils.data.random_split(data_set, [train_size, test_size]) self.train_dataset = torch.utils.data.DataLoader(self.train_dataset, shuffle=True) self.test_dataset = torch.utils.data.DataLoader(self.test_dataset, shuffle=True) def __getitem__(self, key): return getattr(self, key) </code></pre> <p>The error is</p> <blockquote> <p>TypeError: linear(): argument 'input' (position 1) must be Tensor, not DataLoader</p> </blockquote>
<python><machine-learning><pytorch><neural-network>
2023-02-25 15:44:45
2
2,189
M a m a D
75,566,545
4,321,525
Problem with matplotlib date formatting and conversion from epoch time: OverlowError: int too big to convert
<p>The time on the x-axis of my plot is in seconds since the epoch, and I want to convert them to &quot;Year-Month-Day Hour:Minute&quot; format. I follow the documentation <a href="https://matplotlib.org/2.0.2/examples/api/date_demo.html" rel="nofollow noreferrer">here</a>, and I get this traceback:</p> <pre><code>Traceback (most recent call last): File &quot;/home/andreas/src/masiri/booking_algorythm/simple_booking.py&quot;, line 277, in &lt;module&gt; main() File &quot;/home/andreas/src/masiri/booking_algorythm/simple_booking.py&quot;, line 273, in main accepted_list_of_bookings, accepted_bookings_a = process_booking_requests(randomized_list_of_bookings) File &quot;/home/andreas/src/masiri/booking_algorythm/simple_booking.py&quot;, line 257, in process_booking_requests price = calculate_price_for_booking(trip_request, sequential_trip_requests, File &quot;/home/andreas/src/masiri/booking_algorythm/simple_booking.py&quot;, line 226, in calculate_price_for_booking old_price = turn_booking_into_charging_plan(start_time, end_time, old_bookings_list) File &quot;/home/andreas/src/masiri/booking_algorythm/simple_booking.py&quot;, line 209, in turn_booking_into_charging_plan plot_solution(sub_metric_v, soc_plot, charge_plot, discharge_plot, bookings_list, instability_ranges) File &quot;/home/andreas/src/masiri/booking_algorythm/simple_booking.py&quot;, line 195, in plot_solution fig.autofmt_xdate() File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/figure.py&quot;, line 249, in autofmt_xdate for label in ax.get_xticklabels(which=which): File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/axes/_base.py&quot;, line 73, in wrapper return get_method(self)(*args, **kwargs) File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/axis.py&quot;, line 1381, in get_ticklabels return self.get_majorticklabels() File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/axis.py&quot;, line 1345, in get_majorticklabels self._update_ticks() File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/axis.py&quot;, line 1191, in _update_ticks major_labels = self.major.formatter.format_ticks(major_locs) File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/ticker.py&quot;, line 233, in format_ticks return [self(value, i) for i, value in enumerate(values)] File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/ticker.py&quot;, line 233, in &lt;listcomp&gt; return [self(value, i) for i, value in enumerate(values)] File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/dates.py&quot;, line 640, in __call__ result = num2date(x, self.tz).strftime(self.fmt) File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/dates.py&quot;, line 533, in num2date return _from_ordinalf_np_vectorized(x, tz).tolist() File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/numpy/lib/function_base.py&quot;, line 2328, in __call__ return self._vectorize_call(func=func, args=vargs) File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/numpy/lib/function_base.py&quot;, line 2411, in _vectorize_call outputs = ufunc(*inputs) File &quot;/home/andreas/src/masiri/venv/lib/python3.10/site-packages/matplotlib/dates.py&quot;, line 354, in _from_ordinalf np.timedelta64(int(np.round(x * MUSECONDS_PER_DAY)), 'us')) OverflowError: int too big to convert </code></pre> <p>This is my code (I will supply a minimal example, but as far as I can see, this is purely time conversion related).</p> <pre><code>def plot_solution(data, soc_plot,charge_plot, discharge_plot, bookings=None, boundaries=None): my_fmt = mdates.DateFormatter('%Y-%m-%d %H:%M') fig, ax_left = plt.subplots() ax_right = ax_left.twinx() ax_left.xaxis.set_major_formatter(my_fmt) ax_right.xaxis.set_major_formatter(my_fmt) time_axis = data[&quot;time&quot;] ax_right.plot(time_axis, soc_plot, label=&quot;State of Charge&quot;) ax_left.plot(time_axis, data[&quot;price&quot;], label=&quot;price (€/kWs)&quot;) ax_left.plot(time_axis, data[&quot;price_co2&quot;], label=&quot;price including CO_2 costs (€/kWs)&quot;) #ax_right.plot(data[&quot;time&quot;], charge_plot, label=&quot;charge&quot;) #ax_right.plot(data[&quot;time&quot;], discharge_plot, label=&quot;discharge&quot;) bookings_flag = True if bookings is not None: for booking in bookings: if bookings_flag: ax_left.axvspan(booking[&quot;start&quot;], booking[&quot;start&quot;] + booking[&quot;duration&quot;], facecolor='0.4', alpha=0.5, label=&quot;booking&quot;) bookings_flag = False else: ax_left.axvspan(booking[&quot;start&quot;], booking[&quot;start&quot;] + booking[&quot;duration&quot;], facecolor='0.4', alpha=0.5, label=&quot;booking&quot;) boundaries_flag = True if boundaries is not None: for boundary in boundaries: if boundaries_flag: ax_left.axvspan(time_axis[boundary[&quot;start&quot;]], time_axis[boundary[&quot;end&quot;]], facecolor='0.9', alpha=0.5, label=&quot;boundary&quot;) boundaries_flag = False else: ax_left.axvspan(time_axis[boundary[&quot;start&quot;]], time_axis[boundary[&quot;end&quot;]], facecolor='0.9', alpha=0.5) ax_left.set_xlabel(&quot;time in seconds&quot;) ax_left.set_ylabel(&quot;price in €/kWs&quot;, color=&quot;blue&quot;) ax_right.set_ylabel(&quot;State of Charge (SoC), normalized&quot;, color=&quot;black&quot;) legend_1 = ax_left.legend(loc=2, borderaxespad=1.) legend_1.remove() ax_right.legend(loc=1, borderaxespad=1.) ax_right.add_artist(legend_1) fig.autofmt_xdate() plt.show(block=True) </code></pre> <p>Here is an example of my time_axis data:</p> <pre><code>&gt;&gt;&gt; time_axis array([1635905700, 1635906600, 1635907500, 1635908400, 1635909300, 1635910200, 1635911100, 1635912000, 1635912900, 1635913800, </code></pre>
<python><matplotlib><datetime-conversion>
2023-02-25 15:40:04
1
405
Andreas Schuldei
75,566,539
21,286,804
mypy doesn't understand class and interface are the same
<pre><code>from abc import ABC, abstractmethod class IState(ABC): &quot;&quot;&quot;Interface para o padrão de projeto State.&quot;&quot;&quot; @abstractmethod def sucesso_ao_pagar(self) -&gt; None: pass @abstractmethod def despachar_pedido(self) -&gt; None: pass @abstractmethod def cancelar_pedido(self) -&gt; None: pass class Pedido: &quot;&quot;&quot;Classe que representa um pedido.&quot;&quot;&quot; def __init__(self) -&gt; None: self.estado_atual = AguardandoPagamentoState(self) def realizar_pagamento(self) -&gt; None: self.estado_atual.sucesso_ao_pagar() def despachar(self) -&gt; None: self.estado_atual.despachar_pedido() def cancelar(self) -&gt; None: self.estado_atual.cancelar_pedido() def set_estado_atual(self, estado_atual: IState) -&gt; None: self.estado_atual = estado_atual def __str__(self) -&gt; str: return str(self.estado_atual) class AguardandoPagamentoState(IState): &quot;&quot;&quot;Estado inicial do pedido.&quot;&quot;&quot; def __init__(self, meu_pedido: Pedido): self.pedido = meu_pedido def sucesso_ao_pagar(self) -&gt; None: print(&quot;Pedido pago com sucesso!&quot;) self.pedido.set_estado_atual(PagoState(self.pedido)) def despachar_pedido(self) -&gt; None: print(&quot;Pedido não pode ser despachado, pois não foi pago!&quot;) def cancelar_pedido(self) -&gt; None: print(&quot;Pedido cancelado com sucesso!&quot;) self.pedido.set_estado_atual(CanceladoState(self.pedido)) </code></pre> <p>This code works fine, but when i run mypy, it states:</p> <p><code>Incompatible types in assignment (expression has type &quot;IState&quot;, variable has type &quot;AguardandoPagamentoState&quot;) [assignment]mypy</code></p> <p>Why is it generating this problem, given that the AguardandoPagamentoState class implements the IState interface?</p> <p>If I put a comment like</p> <pre><code># type: ignore </code></pre> <p>it stops throwing this error, but I want to know how solve this. Mypy should understand the class relation</p>
<python><interface><mypy>
2023-02-25 15:39:44
1
427
Magaren
75,566,400
1,961,574
Celery: memory not released from workers running python code
<p>So this isn't the first time this question is asked here, but it's a slight variation.</p> <p>I have a file conversion task loading in several GB of data files, chopping them up, and writing them into a new format. This task will continously scan for new files and convert them when it finds them.</p> <p>However, the worker thread/processes (what are they actually) just keep on accumulating memory with every run and eventually all the memory is in use and the server starts swap thrashing.</p> <p>The workers execute Python code, so a garbage collector should occasionally free up memory. I also try using <code>del</code> to clear the larger data objects.</p> <ol> <li><p>I know I could run one task per worker and then have celery recycle the worker. But isn't this inefficient?</p> </li> <li><p>If this behaviour is normal, why isn't one task per worker the default option? As workers usually need to remain active, wouldn't any system eventually run out of memory?</p> </li> <li><p>Is there not a way to manually clear the memory from the workers?</p> </li> </ol>
<python><celery>
2023-02-25 15:19:36
0
2,712
bluppfisk
75,566,344
9,133,459
Is there a way to reverse-beautify python code?
<p>A specific unique task I have in mind requires me to read a text file (the text file only consists of python code) and store each line from the file in a list. However, there is one catch. I require each line to be <strong>complete</strong>. What I mean by complete is if a group of sequential lines can be in one line, without addition of any new characters and only the removal of '\n' characters, it should be in one line. Furthermore, it should not change the logic of the code at all. Here is some <strong>non-exhaustive</strong> examples what I mean by complete:</p> <pre class="lang-py prettyprint-override"><code># this is not complete from rl.models import ( Model1, Model2, ) # this is complete from rl.models import ( Model1, Model2,) </code></pre> <pre class="lang-py prettyprint-override"><code># this is not complete print(1, 2) # this is complete print(1,2) </code></pre> <pre class="lang-py prettyprint-override"><code># this is not complete def func2(var1, var2): # this is complete def func2(var1, var2): </code></pre> <p>As you might have guessed it by now, I am not interested in the all of the unnecessary new lines in code which are usually done to improve readability. This is in a sense, uglyfying python code. If I run the uglyfied version of the python code, the same results is expected as the non-uglyfied version. I have tried to search for APIs which can do this but so far I have not come across any.</p>
<python>
2023-02-25 15:11:31
1
2,552
Rajdeep
75,566,328
9,644,490
How to add text AFTER inputs in Django forms
<p>I have a form which ideally would render like this:</p> <pre><code>&lt;label&gt;Price: &lt;/label&gt; &lt;input type=&quot;number&quot; /&gt;USD </code></pre> <p>Visually it would be</p> <pre><code>Price: |___________| USD </code></pre> <p>I know that the <code>label</code> attribute of a form field can add text BEFORE an input, but I want to know if it's possible to add text AFTER an input.</p> <p>(1) I understand if I iterate over fields in the template, I would be able to achieve this with something like</p> <pre><code>{{ field }} {% if field.name == &quot;price&quot; %} &amp;nbsp;USD {% endif %} </code></pre> <p>However I do not want to go this route if possible.</p> <p>(2) I already tried <code>help_text</code>, but it adds an extra <code>&lt;br /&gt;</code> tag between the input and the help text, and it does not render what I want.</p> <pre><code>&lt;label&gt;Price: &lt;/label&gt; &lt;input type=&quot;number&quot; /&gt; &lt;br /&gt; &lt;span&gt;USD&lt;/span&gt; </code></pre> <pre><code>Price: |___________| USD </code></pre>
<python><django>
2023-02-25 15:08:40
1
409
kyuden
75,566,236
6,552,836
Scipy / Mystic - Constraints violated after being specified
<p>I'm trying to optimize a 10x5 matrix to maximize a return value y, using mystic. There are 2 types of constraints that I need to include:</p> <ol> <li>Each element must be in between a min and max range</li> <li>Some elements must equal specific values (provided in a dictionary)</li> </ol> <p>Not sure why the optimized result includes negative values as I have already made a constraint for that (constraint no.1) and the return y value seems to be incredibly small?</p> <pre><code>import random import pandas as pd import numpy as np import mystic.symbolic as ms import mystic as my import scipy.optimize as so # Specifiying constraints element_low_lim = 0 element_hi_lim = 1000 total_matrix_min_sum = 0 total_matrix_max_sum = 220000 # Create an input matrix where the values must equal a specific amount matrix_in = np.zeros((52,5)) matrix_in[0,0] = 100 def constraints_func(element_low_lim, element_hi_lim, total_matrix_min_sum, total_matrix_max_sum,element_vals_dict): var_num = ['x'+str(i) for i in range(260)] #creating element bounds constraints constraint_bound = '' for var in var_num: if var not in element_vals_dict: constraint_bound += var + f' &gt;= {element_low_lim}' + '\n' + var + f' &lt;= {element_hi_lim}' + '\n' #creating sum of all the elements constraint constraint_matrix_sum = ' + '.join(var_num) + f' &lt;= {total_matrix_max_sum}' + '\n' + ' + '.join(var_num) + f' &gt;= {total_matrix_min_sum}' #creating element constraints constraint_elements = '\n'.join([var+' == '+str(element_vals_dict[var]) for var in element_vals_dict]) # bundle all constraints constraint_equations = constraint_bound.lstrip() + constraint_matrix_sum.lstrip() + constraint_column_sum.lstrip() + constraint_elements.lstrip() return constraint_equations equations = constraints_func(element_low_lim, element_hi_lim, total_matrix_min_sum, total_matrix_max_sum, column_sum_min_lst, column_sum_max_lst, element_vals_dict) equations = ms.simplify(equations, all=True) constrain = ms.generate_constraint(ms.generate_solvers(equations), join=my.constraints.and_) # Define Objective function def obj_func(matrix): return np.sum(output_matrix) mon = my.monitors.VerboseMonitor(1) objs = [] def callback(x): kx = constrain(x) y = -obj_func(x) mon(kx, y) objs.append(y) # create a starting matrix start_matrix = [random.randint(0,3) for i in range(200)] # run optimizer solution = so.minimize(obj_func, start_matrix, method='SLSQP', tol=0.01, options={'disp': True, 'maxiter':100}, callback=callback) </code></pre>
<python><optimization><scipy><scipy-optimize><mystic>
2023-02-25 14:55:32
1
439
star_it8293
75,566,105
11,665,178
Authenticate a GET request to Google Play Purchase API with service account python
<p>I need to verify purchases of my android App from my AWS lambda in python.</p> <p>I have seen many posts of how to do so and the <a href="https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.subscriptions/get" rel="nofollow noreferrer">documentation</a> and here is the code I have written :</p> <pre><code>url = f&quot;{google_verify_purchase_endpoint}/{product_id}/tokens/{token}&quot; response = requests.get(url=url) data = response.json() logging.info(f&quot;Response from Google Play API : {data}&quot;) </code></pre> <p>When I do so, it throws a 401 status code not allowed. Alright, I have created a service account to allow the request with OAuth, but how can I use it to allow the request ?</p> <p>Unfortunately I can't use the <code>google-api-python-client</code> as mentioned <a href="https://stackoverflow.com/a/51858290/11665178">here</a> which is too big for my AWS lambda maximum size of 250Mb unzipped package.</p> <p>So my question is to use the service account with a simple GET requests or how can I authenticate automatically without the <code>google-api-python-client</code> ?</p> <p>Thanks in advance</p>
<python><android><in-app-purchase><google-api-python-client><google-play-developer-api>
2023-02-25 14:35:10
2
2,975
Tom3652
75,566,022
13,218,530
pipenv install django=~3.1.0 command giving error
<pre><code>Installing django=~3.1.0... Resolving django=~3.1.0... Traceback (most recent call last): File &quot;/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pipenv/patched/pip/_vendor/packaging/requirements.py&quot;, line 102, in __init__ req = REQUIREMENT.parseString(requirement_string) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pipenv/patched/pip/_vendor/pyparsing/core.py&quot;, line 1141, in parse_string raise exc.with_traceback(None) pipenv.patched.pip._vendor.pyparsing.exceptions.ParseException: Expected string_end, found '=' (at char 6), (line:1, col:7) </code></pre> <p>I am getting above error in command line of mac for <code>pipenv install django=~3.1.0</code></p>
<python><django><pipenv>
2023-02-25 14:20:45
1
1,289
MUHAMMAD SHAHID RAFI C P
75,565,959
2,598,546
Getting region name in SageMaker endpoint
<p>In SageMaker endpoint, hosting my custom container with Python code, I need to access the region name. I tried the AWS_REGION and AWS_DEFAULT_REGION variables but they are not defined. Do you maybe know some way of doing this?</p>
<python><amazon-web-services><amazon-sagemaker>
2023-02-25 14:09:51
1
312
Pawel Faron
75,565,957
5,058,116
Looking up a column name in another data frame
<p>I have the following data frame:</p> <pre><code>import pandas as pd df_1 = pd.DataFrame( { &quot;id_1&quot;: [1, 1, 2, 2], &quot;id_2&quot;: [11, 11, 22, 22], &quot;value_1&quot;: [0.1, 0.1, 0.01, 0.01], &quot;value_2&quot;: [0.2, 0.2, 0.02, 0.02], &quot;value_3&quot;: [0.3, 0.3, 0.03, 0.03], } ) </code></pre> <p>that looks like this:</p> <pre><code> id_1 id_2 value_1 value_2 value_3 0 1 11 0.10 0.20 0.30 1 1 11 0.10 0.20 0.30 2 2 22 0.01 0.02 0.03 3 2 22 0.01 0.02 0.03 </code></pre> <p>and another:</p> <pre><code> df_2 = pd.DataFrame( { &quot;id_1&quot;: [1, 1, 1, 1, 2, 2, 2, 2], &quot;id_2&quot;: [11, 11, 11, 11, 22, 22, 22, 22], &quot;value_name&quot;: [ &quot;value_1&quot;, &quot;value_2&quot;, &quot;value_3&quot;, &quot;value_1&quot;, &quot;value_1&quot;, &quot;value_2&quot;, &quot;value_3&quot;, &quot;value_1&quot;, ], } ) </code></pre> <p>which looks like this:</p> <pre><code> id_1 id_2 value_name 0 1 11 value_1 1 1 11 value_2 2 1 11 value_3 3 1 11 value_1 4 2 22 value_1 5 2 22 value_2 6 2 22 value_3 7 2 22 value_1 </code></pre> <p>How do I get the corresponding <code>value</code> (for a given <code>id_1</code> and <code>id_2</code>) from <code>df_1</code> into <code>df_2</code>, please? i.e. I want a final data frame should look like this:</p> <pre><code> id_1 id_2 value_name value 0 1 11 value_1 0.1 1 1 11 value_2 0.2 2 1 11 value_3 0.3 3 1 11 value_1 0.1 4 2 22 value_1 0.01 5 2 22 value_2 0.02 6 2 22 value_3 0.03 7 2 22 value_1 0.01 </code></pre>
<python><pandas><dataframe><lookup>
2023-02-25 14:09:05
1
3,058
ajrlewis
75,565,777
8,279,172
Sum rows of 2D array with elements of 1D array
<p>I have two ndarrays: <br /> <code>a = [[1, 2], [100, 200]]</code> and <br /> <code>b = [10, 20]</code></p> <p>Is it possible to get such ndarray using numpy: <code>[[1 + 10, 2 + 10], [100 + 20, 200 + 20]]</code></p>
<python><numpy><numpy-ndarray>
2023-02-25 13:37:01
3
1,540
wowonline
75,565,227
1,686,628
matplotlib: get precise point of intersection
<pre><code>import numpy as np import matplotlib.pyplot as plt x = [1,2] y1 = [11, 0] y2 = [0, 5] np_x = np.array(x) np_y1 = np.array(y1) np_y2 = np.array(y2) idx = np.argwhere(np.diff(np.sign(np_y2 - np_y1))).flatten() isect = zip(np_x[idx], np_y1[idx]) for x,y in isect: print(f'({x}, {y})') plt.plot(np_x, np_y1) plt.plot(np_x, np_y2) plt.show() </code></pre> <p>the below is the graph of the above code. however, the intersection being printed is (1,11)<br /> I suppose because it is rounded up to a whole number.<br /> how do i get the precise intersection points? ie something like (1.7, 3.8)</p> <p>thank you</p> <p><a href="https://i.sstatic.net/kdaCY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kdaCY.png" alt="enter image description here" /></a></p>
<python><python-3.x><numpy><matplotlib>
2023-02-25 11:55:10
4
12,532
ealeon
75,565,181
12,945,785
highlighted space display
<p>I have a question concerning vscode. A very simple one. why do I have highlighted text in python code (jupyter) as in the photo joined ? How can I cancel it ? <a href="https://i.sstatic.net/a172n.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/a172n.png" alt="enter image description here" /></a></p>
<python><visual-studio-code>
2023-02-25 11:47:08
1
315
Jacques Tebeka
75,565,121
17,233,433
Django - authenticate() returning None even if user exists in database and the credentials are correct
<p><code>authenticate()</code> returns <code>None</code> for credentials even if the user exists in the database and the credentials are correct.</p> <p>The function for registration, <code>register()</code>:</p> <pre><code>def register(request): registered = False ctx = {} if request.method == 'POST': username = request.POST.get(&quot;username&quot;) full_name = request.POST.get(&quot;fullname&quot;) password = request.POST.get(&quot;password&quot;) email = request.POST.get(&quot;email&quot;) if len(User.objects.filter(username=username)) == 0: ctx[&quot;username_exists&quot;] = False user_form = UserForm(data=request.POST) if user_form.is_valid(): user = User.objects.create_user(username, email, password) user.save() user_profile = UserProfile(user=user, full_name=full_name, email_id=email) user_profile.save() if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse(&quot;Your account was inactive.&quot;) else: print(&quot;Someone tried to login and failed.&quot;) print(&quot;They used username: {} and password: {}&quot;.format(username,password)) return HttpResponse(&quot;Invalid login details given&quot;) else: return HttpResponse(&quot;Contains @&quot;) else: ctx[&quot;username_exists&quot;] = True return render(request,'main/register.html', ctx) elif request.method == &quot;GET&quot;: form = User() ctx[&quot;form&quot;] = form return render(request,'main/register.html', ctx) </code></pre> <p>Looking at the admin, I can see the user exists. The following proves it exists in the database:</p> <pre><code>&gt;&gt;&gt; from django.contrib.auth.models import User &gt;&gt;&gt; user = User.objects.get(username='&lt;username&gt;') &gt;&gt;&gt; print(user) &lt;username&gt; </code></pre> <p>This is what I'm doing -</p> <pre><code>python3 manage.py shell &gt;&gt;&gt; from django.contrib.auth import authenticate &gt;&gt;&gt; user = authenticate(username=&quot;&lt;username&gt;&quot;, password=&quot;&lt;password&gt;&quot;) &gt;&gt;&gt; print(user) None </code></pre> <p>While trying out what @Abdulmajeed said, I found something weird:</p> <pre><code>&gt;&gt;&gt; from django.contrib.auth.models import User &gt;&gt;&gt; from django.contrib.auth import authenticate &gt;&gt;&gt; user = User.objects.get(username='&lt;username&gt;') &gt;&gt;&gt; print(user) &lt;username&gt; &gt;&gt;&gt; user_authenticate = authenticate(username='&lt;username&gt;', password='&lt;password&gt;') &gt;&gt;&gt; print(user_authenticate) None &gt;&gt;&gt; user.set_password('&lt;password&gt;') &gt;&gt;&gt; user.check_password('&lt;password&gt;') True &gt;&gt;&gt; user_authenticate = authenticate(username='&lt;username&gt;', password='&lt;password&gt;') &gt;&gt;&gt; print(user_authenticate) None </code></pre> <p>This is my <code>AUTHENTICATION_BACKENDS</code>: <code>AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',]</code></p> <p>This hasn't ever occurred to me before and I don't know what to do. Help?</p>
<python><django><authentication>
2023-02-25 11:38:01
1
753
Adith Raghav
75,565,077
5,058,116
Getting index counter on a data frame
<p>I have the following data frame:</p> <pre><code>import pandas as pd data = { &quot;id_1&quot;: [1, 1, 1, 2, 2, 2], &quot;id_2&quot;: [1, 1, 1, 2, 2, 2], &quot;foo&quot;: [0.1, 0.1, 0.1, 0.2, 0.2, 0.2], } df = pd.DataFrame(data) df = df.set_index([&quot;id_1&quot;, &quot;id_2&quot;]) </code></pre> <p>which looks like this:</p> <pre><code> foo id_1 id_2 1 1 0.1 1 0.1 1 0.1 2 2 0.2 2 0.2 2 0.2 </code></pre> <p>I want to have another column (<code>index</code>) that starts from <code>1</code> and goes up to the length of the <code>index</code> group, <code>3</code>. The output should look like this:</p> <pre><code> foo index id_1 id_2 1 1 0.1 1 1 0.1 2 1 0.1 3 2 2 0.2 1 2 0.2 2 2 0.2 3 </code></pre> <p>How do I go about this, please?</p>
<python><pandas><multi-index>
2023-02-25 11:28:22
2
3,058
ajrlewis
75,565,030
4,987,739
does python allows elif statement without else statement?
<p>While teaching python to a friend i tried this statement :</p> <pre><code>val = &quot;hi&quot; if (val==&quot;hello&quot;) or (&quot;w&quot; in val): print(&quot;hello&quot;) elif(val==&quot;hi&quot;): print(&quot;hi&quot;) </code></pre> <p>And to my great surprise it worked. I always tought in Python you couldn't do an elif without else. Has it been always like that or the syntax has changed since a particular version?</p>
<python>
2023-02-25 11:20:21
2
899
djohon
75,564,994
3,399,066
Python FastAPI server - Streaming in-memory images to HTML5 <video> element
<h1>Goal</h1> <p>I'm trying to stream in-memory images from a Python backend written in FastAPI to a HTML (Vue3) frontend. However, I cannot get the video element to display the stream of images like a video.</p> <h1>Minimal example attempt</h1> <p>As a minimal example, I create 2 images in memory (red and blue) on the server side, which should be displayed on the frontend alternating each second.</p> <p>I created the following folder and HTML file: <code>templates/index.html</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Streaming JPEG&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Streaming JPEG&lt;/h1&gt; &lt;p&gt;Your IP address is {{ request.client.host }}.&lt;/p&gt; &lt;video src=&quot;http://127.0.0.1:8000/video-stream&quot; width=&quot;256&quot; height=&quot;256&quot; autoplay&gt;&lt;/video&gt; &lt;!-- 0.0.0.0 --&gt; &lt;p&gt;End video&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And I created the following backend file <code>main.py</code>:</p> <pre class="lang-py prettyprint-override"><code>import io from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, StreamingResponse from fastapi.templating import Jinja2Templates from PIL import Image import asyncio app = FastAPI() templates = Jinja2Templates(directory=&quot;templates&quot;) @app.get(&quot;/&quot;, response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse(&quot;index.html&quot;, {&quot;request&quot;: request}) @app.get(&quot;/video-stream&quot;) async def video_stream(): # create a red and a blue image imgs = [ Image.new('RGB', (256, 256), color='red'), Image.new('RGB', (256, 256), color='blue') # .tobytes() ] img_bytes = list() for img in imgs: # Save the image to a BytesIO object as JPEG format with io.BytesIO() as output: img.save(output, format=&quot;JPEG&quot;) img_bytes.append(output.getvalue()) # generator function that will generate JPEG-encoded frames async def generate_frames(): yield b'--frame\r\n' while True: for idx in range(len(img_bytes)): print(f&quot;idx: {idx}&quot;) yield b'Content-Type: image/jpeg\r\n\r\n' + img_bytes[idx] + b'\r\n--frame\r\n' await asyncio.sleep(1) return StreamingResponse(generate_frames(), media_type=&quot;multipart/x-mixed-replace;boundary=frame&quot;) if __name__ == &quot;__main__&quot;: import uvicorn uvicorn.run(app, host=&quot;127.0.0.1&quot;, port=8000) # &quot;0.0.0.0&quot; </code></pre> <p>Which can be started with one of the following commands:</p> <pre class="lang-bash prettyprint-override"><code>uvicorn main:app --reload python main.py </code></pre> <h2>Explanation</h2> <p>While searching online it seemed I had to append <code>Content-Type</code> to a byte version of an image before sending it through <code>StreamingResponse</code>, however it doesn't seem to work for me.</p> <h1>Problems</h1> <p>When navigating to <code>http://127.0.0.1:8000/</code> I see the HTML template with a white area where the video is supposed to play alternating red / blue images.</p> <p>Looking in my Firefox console (also tried with Chromium), I see the following 2 messages:</p> <ul> <li>HTTP “Content-Type” of “multipart/x-mixed-replace” is not supported. Load of media resource <a href="http://127.0.0.1:8000/video-stream" rel="nofollow noreferrer">http://127.0.0.1:8000/video-stream</a> failed.</li> <li>Cannot play media. No decoders for requested formats: multipart/x-mixed-replace</li> </ul> <p>Which seems to indicate it's not properly encoded? Or am I doing something else wrong? Any help is appreciated!</p>
<python><video-streaming><html5-video><jpeg><fastapi>
2023-02-25 11:14:33
0
6,452
NumesSanguis
75,564,864
3,312,274
web2py: Prevent delete action on the A() helper depending on the result of the callback
<p>Is it possible to prevent the delete action on 'tr' depending on the return value of <code>service_record_del_request</code> callback:</p> <pre><code>{{=A('Delete', callback=URL('service_record_del_request', vars={'id':r.id}), delete='tr')}} </code></pre> <p>Example callback:</p> <pre><code>@auth.requires_login() def service_record_del_request(): id = request.vars.id if db(db.service_record.id==id).delete(): #debug return 'true' #--&gt; ok, delete the 'tr' else: return 'false' #--&gt; db delete failed, don't delete 'tr' </code></pre>
<python><ajax><web2py>
2023-02-25 10:47:55
1
565
JeffP
75,564,803
10,940,547
python requests ChunkedEncodingError when receiving and writing some data from a server
<p>I am working on a python script (as a smaller part of a project) that would accept some URLs and receive the data sequentially using the <code>requests</code> module and write it to a file.</p> <p>The thing is, I guess, that the server I am receiving from, does not handle the connection effectively. Consequently, the connection seems to get broken in the middle of the process.</p> <p>For example, I was receiving a video file (~150MB) from the said server (hosted on Heroku) among some other smaller files, but while writing the video, the process ended with about just 40MB of data written <strong>(No runtime errors so far though)</strong>.</p> <p>Here is the code snippet:</p> <pre><code>with open(f&quot;./files/{filename}&quot;, 'wb') as file: size = 0 res = requests.get(url, headers=headers, stream=True) for chunk in res.iter_content(chunk_size=1024): size+=len(chunk) print(f&quot;{round(size/(1024*1024),3)}MB&quot;,end=&quot;\r&quot;) if chunk: file.write(chunk) </code></pre> <p>I tried different values for <code>chunk_size</code> like <code>10240</code>, <code>8192</code> etc. But all seemed to have the same problem and wrote unequal smaller sized files but never complete.</p> <p>This was until I read the docs and tried to set <code>chunk_size=None</code>. This resulted in the following error after about 100MB of data was written:</p> <pre><code>requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(109051904 bytes read, 53405476 more expected)', IncompleteRead(109051904 bytes read, 53405476 more expected)) </code></pre> <p>I know it's obvious from the exception that the connection was broken before all the bytes could be received but I had a hard time all day trying to figure out the fix.</p> <p>Also, I tried <code>try-except</code> for the above exception but that seemed to have corrupted the video as some parts of it were missing.</p> <p>So, my question is, how can I make the script reconnect, or wait for the server (or my computer) to re-establish the connection to receive those missing bytes?</p>
<python><python-requests><chunked-encoding>
2023-02-25 10:37:05
0
554
Jyotirmay
75,564,548
12,319,746
Cannot connect to Azure SQL from Azure functions
<p>I am trying to send some data from an Azure function to an Azure SQL DB, it seems that the function's underlying linux image does not have PYODBC driver 18. I am using a managed identity to connect and it worked fine earlier on a linux function.</p> <pre><code>conn_string = f&quot;Driver={{ODBC Driver 18 for SQL Server}};SERVER=sql-to-dev-.database.windows.net;DATABASE=poc&quot; database_conn = pyodbc.connect(conn_string, attrs_before={SQL_COPT_SS_ACCESS_TOKEN: token_struct}) database_cursor = database_conn.cursor() </code></pre> <p>Error</p> <blockquote> <p>pyodbc.Error: Can't open lib 'ODBC Driver 18 for SQL Server' :azure functions</p> </blockquote>
<python><azure><pyodbc>
2023-02-25 09:48:01
2
2,247
Abhishek Rai
75,564,244
5,676,603
create connected contour lines from set of points
<p>VTK and pyvista.</p> <p>I am trying to implement from scratch (i.e., without using any library functions for contouring or interpolation ) an iso contour algorithm.</p> <p>I am using pyvista to create a custom grid and render it.</p> <p>With iso_contour function i am pushing (x, y, 0) points but i am not able to connect them to make an island of isocontour !!</p> <p>I am here to ask help from you if you could help me achieve this using vtk or any other thing !</p> <p>This is my code</p> <pre><code>import pyvista as pv import numpy as np def f(x, y): return np.sin(10*x)+np.cos(4*y)-np.cos(3*x*y) x = np.arange(0, 1, 0.05) y = np.arange(0, 1, 0.05) XX, YY = np.meshgrid(x, y) data = f(XX, YY) isovalue = 0.15 def iso_contour(array, target_value): contours = [] rows, cols = array.shape # Loop through each cell in the array for i in range(rows-1): for j in range(cols-1): cell_verts = [] # Check each corner of the cell for corner in [(i,j), (i+1,j), (i+1,j+1), (i,j+1)]: x, y = corner cell_verts.append((x, y, array[x,y])) # Check each edge of the cell for k in range(4): p1, p2 = cell_verts[k], cell_verts[(k+1)%4] if (p1[2] &gt;= target_value) != (p2[2] &gt;= target_value): # Calculate intersection point t = (target_value - p1[2]) / (p2[2] - p1[2]) x, y = p1[:2] + t * (np.array(p2[:2]) - np.array(p1[:2])) contours.append((y, x, 0.0)) return contours contour_points = iso_contour(data, isovalue) pl = pv.Plotter() pl.add_mesh(grid, show_edges = True) for i in range(len(contour_points)-1): line = pv.Line(contour_points[i], contour_points[i+1]) pl.add_mesh(line, color='r', line_width=5) pl.show() </code></pre> <p>I am expecting this as an output</p> <p><a href="https://i.sstatic.net/PvRLB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PvRLB.png" alt="enter image description here" /></a></p> <p>but i am getting like this:</p> <p><a href="https://i.sstatic.net/LAwbS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LAwbS.png" alt="enter image description here" /></a> Is there any vtk filter or any thing that i can use or render in vtk that can give me that shape !</p> <p>Thank you</p>
<python><vtk><pyvista>
2023-02-25 08:42:02
1
1,578
Pravin Poudel
75,564,166
3,728,901
What is shadow built-in name 'sum'?
<p>I am learning at <a href="https://github.com/donhuvy/Data-Structures-and-Algorithms-The-Complete-Masterclass/blob/main/1.%20Big%20O%20Notation/2%20-%20bigo-whileloop.py#L11" rel="nofollow noreferrer">https://github.com/donhuvy/Data-Structures-and-Algorithms-The-Complete-Masterclass/blob/main/1.%20Big%20O%20Notation/2%20-%20bigo-whileloop.py#L11</a> .</p> <p>My environment: Python 3.9, PyCharm 2022</p> <pre class="lang-py prettyprint-override"><code>import time t1 = time.time() num = 100 if num &lt; 0: print(&quot;Enter a positive number&quot;) else: sum = 0 while num &gt; 0: sum += num num -= 1 print(&quot;The sum is&quot;, sum) t2 = time.time() print((t2 - t1)) </code></pre> <p><a href="https://i.sstatic.net/jVlb1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jVlb1.png" alt="enter image description here" /></a></p> <p>What is shadow built-in name 'sum'?</p>
<python><pycharm>
2023-02-25 08:26:39
1
53,313
Vy Do
75,564,161
18,583,944
Calculating points along a line between two points using geopy
<p>I am using <strong>geopy</strong> to map the location of a simulated object as it travels between two geographical points. I would like to be able to calculate the lat/lon of this object at any point in its theoretical journey: so for an object travelling between Paris and New York, 0% would be Paris, 100% would be New York and 50% would be half way between the two when the object has travelled half the distance.</p> <p>(I say a theoretical object because I am not interested in adjusting for eg the route that an airplane might take or tracking a real object, I just want to assume a straight line between the two points)</p> <p>My code is as follows:</p> <pre><code>from geopy.distance import geodesic as GD start = (48.8567, 2.3508) # Paris end = (40.7128, 74.0060) # New York distance_between = GD(start, end).km print (f&quot;{distance_between} km between Paris and New York&quot;) pct_travelled = 50 new_lat = start[0] + (end[0] - start[0]) * (int(pct_travelled) / 100) new_lon = start[1] + (end[1] - start[1]) * (int(pct_travelled) / 100) print (f&quot;Your current location is {new_lat}, {new_lon}&quot;) distance_travelled_so_far = GD(start, (new_lat, new_lon)).km distance_still_to_travel = GD((new_lat, new_lon), end).km print (f&quot;You have travelled {distance_travelled_so_far} km&quot;) print (f&quot;You have {distance_still_to_travel} km left to travel&quot;) </code></pre> <p>This code delivers an incorrect answer:</p> <pre><code>5529.689905151459 km between Paris and New York Your current location is 44.78475, 38.178399999999996 You have travelled 2744.973813842307 km You have 2943.5970959509054 km left to travel </code></pre> <p>(It is incorrect because in a correct answer the distance travelled and the distance left to travel at 50% completed would be equal)</p> <p>I presume this is because my code assumes that the distance of a degree of lat and a degree of lon are the same, which is obviously not correct.</p> <p>How can I do this correctly with geopy or other python libraries?</p>
<python><latitude-longitude><geopy>
2023-02-25 08:25:41
1
408
Super
75,563,776
7,521,470
Proper way to make ConversationHandler with both Buttons & Messages handling
<p>I'm building a bot that should handle buttons and messages, this is an example that works:</p> <pre><code>INTRO, GUEST_OR_USER, USERNAME, GUEST = range(4) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -&gt; int: keyboard = [ [InlineKeyboardButton(&quot;YES SIR!&quot;, callback_data='user')], [InlineKeyboardButton(&quot;no&quot;, callback_data='guest')], ] reply_markup = InlineKeyboardMarkup(keyboard) await update.message.reply_text(&quot;Are you a Stack Overflow user?&quot;, reply_markup=reply_markup) return GUEST_OR_USER async def guest_or_user_choice(update: Update, context: ContextTypes.DEFAULT_TYPE) -&gt; int: query = update.callback_query await query.answer() if query.data == 'user': await context.bot.send_message(chat_id=update.effective_chat.id, text=&quot;Cool! What's your username?&quot;) return USERNAME await context.bot.send_message(chat_id=update.effective_chat.id, text=&quot;Oh! Why not?&quot;) return GUEST async def username_entered(update: Update, context: ContextTypes.DEFAULT_TYPE) -&gt; None: await update.message.reply_text(&quot;👍&quot;) return async def guest_conv(update: Update, context: ContextTypes.DEFAULT_TYPE) -&gt; None: await update.message.reply_text(&quot;That's a shame!&quot;) return if __name__ == '__main__': application = ApplicationBuilder().token(TOKEN).build() start_handler = CommandHandler('start', start) application.add_handler(start_handler) conv_handler = ConversationHandler( entry_points=[CallbackQueryHandler(guest_or_user_choice)], states={ USERNAME: [MessageHandler(filters.TEXT &amp; ~filters.COMMAND, username_entered)], GUEST: [MessageHandler(filters.TEXT &amp; ~filters.COMMAND, guest_conv)] }, fallbacks=[], allow_reentry=True ) application.add_handler(conv_handler) application.run_polling() </code></pre> <p>But even such a simple flow shows warnings like</p> <blockquote> <p>PTBUserWarning: If 'per_message=False', 'CallbackQueryHandler' will not be tracked for every message</p> </blockquote> <p>According to those, ConversationHandler should be something like:</p> <pre><code>conv_handler = ConversationHandler( entry_points=[CallbackQueryHandler(guest_or_user_choice)], states={ USERNAME: [CallbackQueryHandler(username_entered)], GUEST: [CallbackQueryHandler(guest_conv)] }, fallbacks=[], allow_reentry=True, per_message=True ) </code></pre> <p>But this doesn't work, username_entered | guest_conv are never started. Is there a way to make it work without warnings? How to use CallbackQueryHandler for handling the user text input? Thanks a lot!</p>
<python><telegram><python-telegram-bot>
2023-02-25 06:52:55
1
321
ElRey777
75,563,735
8,179,876
Text matching visualizations in Python
<p>How could I make an image like this:</p> <p><a href="https://i.sstatic.net/Yh6je.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Yh6je.png" alt="desired" /></a></p> <p>Stuff I have tried: Matplotlib, Seaborn, Plotly, but all are for graphing data and not as much making visualizations given a list of linkages (such as <code>matchings = [('The', 'The'), ('over', 'above'), ('face', 'wall')]</code> for example). However I get stuff like: <a href="https://i.sstatic.net/2Ge1f.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2Ge1f.png" alt="bad" /></a> which is not as aesthetically pleasing as the above example.</p>
<python><matplotlib>
2023-02-25 06:41:28
1
1,264
Coder
75,563,569
8,968,801
GraphQL Queries Per App in Django (Graphene)
<p>I started moving my REST API endpoints to using GraphQL with Graphene. Seems pretty straightforward so far, but one of the things that I like about the REST API (and I cannot figure out in Graphene) is the structure of &quot;endpoints&quot; for each app. I have a lot of apps in my Django application, and I would like to group the Graphene queries and mutations of each app under a single &quot;endpoint&quot; (just like you would do in REST by sending a request to <code>app_1/endpoint</code> and <code>app_2/endpoint</code>).</p> <p>Currently I have a <code>graphql</code> folder inside of each app, with files for my queries and mutations inside. Then, under my main schema file, I just create a giant <code>query</code> and <code>mutation</code> objects that inherit from the elements of all other apps.</p> <pre class="lang-py prettyprint-override"><code># app1/graphql/queries.py class Endpoint1(DjangoObjectType): class Meta: model = Element1 fields = (&quot;id&quot;, &quot;name&quot;, &quot;date&quot;) # app2/graphql/queries.py class Endpoint2(DjangoObjectType): class Meta: model = Element2 fields = (&quot;id&quot;, &quot;name&quot;, &quot;date&quot;) # Place where my main schema is located # django_project/graphql/queries.py class Queries(Endpoint1, Endpoint2): pass </code></pre> <p>Would it be possible to group queries and mutations from a single app and then just inherit from each of the app's mutations and queries in the main schema, and then have the GraphQL request be structured like this?</p> <pre class="lang-json prettyprint-override"><code>query { app1 { endpoint1 { id name } } } query { app2 { endpoint2 { id name } } } </code></pre> <p>With my current approach I currently just get all of the endpoints bunched up into a single set found under query.</p> <pre class="lang-json prettyprint-override"><code>query { endpoint1 { id name } endpoint2 { id name } } </code></pre>
<python><django><graphql><graphene-django>
2023-02-25 05:57:13
1
823
Eddysanoli
75,563,523
12,210,257
regex findall overlapped does not give match if one of them is a prefix of the other
<pre class="lang-py prettyprint-override"><code>import regex product_detail = &quot;yyy target1 target2 xxx&quot;.lower() p1 = r&quot;\btarget1\b|\btarget1 target2\b&quot; p2 = r&quot;\btarget2\b|\btarget1 target2\b&quot; for pattern in [p1, p2]: matches = regex.findall(pattern, product_detail, overlapped=True) print(matches) </code></pre> <p>why does matches from p1 only give <code>['target1']</code> as output, without <code>'target1 target2'</code></p> <p>but matches from p2 can successfully give <code>['target1 target2', 'target2']</code> as output.</p> <p>Also if you can provide a fix, how do i generalise it? i have a list of 10000 target words and its not going to be feasible to hardcode them.</p>
<python><regex><findall>
2023-02-25 05:42:01
1
377
leonardltk1
75,563,382
2,804,160
Locating sublists of one list in another list in Python
<p>I have two lists <code>G3, G333</code>. I want to locate the sublists of <code>G333</code> in <code>G3</code> and print the indices <code>i</code>. For example, <code>[0, 4, 5, 9]</code> occurs at <code>i=0</code> in <code>G3</code>, <code>[10, 14, 15, 19]</code> occurs at <code>i=5</code> in <code>G3</code>. But I am getting an error. I present the expected output.</p> <pre><code>G3=[[0, 4, 5, 9], [1, 5, 6, 10], [2, 6, 7, 11], [3, 7, 8, 12], [9, 13, 14, 18], [10, 14, 15, 19]] G333=[[0, 4, 5, 9], [1, 5, 6, 10], [10, 14, 15, 19]] G3s = set(map(tuple, G3)) G333s = set(map(tuple, G333)) for i in range(0,len(G3s)): if (G3s[i] &amp; G333s[i]): print(i) </code></pre> <p>The error is</p> <pre><code>in &lt;module&gt; if (G3s[i] &amp; G333s[i]): TypeError: 'set' object is not subscriptable </code></pre> <p>The expected output is</p> <pre><code>i=[0,1,5] </code></pre>
<python><list>
2023-02-25 04:54:36
3
930
Wiz123
75,563,190
17,696,880
How to capture all substrings that match this regex pattern, which is based on a repeat range of 2 or more consecutive times?
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;((PERS)Marcos) ssdsdsd sdsdsdsd sdsdsd le ((VERB)empujé) hasta ((VERB)dejarle) en ese lugar. A ((PERS)Marcos) le ((VERB)dijeron) y luego le ((VERB)ayudo)&quot; input_text = re.sub(r&quot;\(\(PERS\)((?:\w\s*)+)\)\s*((?!el)\w+\s+){2,}(le)&quot;, lambda m: print(f&quot;{m[2]}&quot;), input_text, flags = re.IGNORECASE) print(repr(input_text)) # --&gt; output </code></pre> <p>Here I have used repeat quantifiers, such as <code>+</code> (one or more repeats) or <code>*</code> (zero or more repeats), in combination with <code>{}</code> to specify a range of repeats.</p> <p>Why this code gives me as output, only the first word and not all the possible words that the pattern <code>((?!el)\w+\s+){2,}</code> would cover. Since this pattern captures if there are 2 or more words between <code>&quot;((PERS) )&quot;</code> and <code>&quot;el&quot;</code> ?</p> <pre><code>&quot;sdsdsd &quot; </code></pre> <p>And not this output, which is what I want to get</p> <pre><code>&quot; ssdsdsd sdsdsdsd sdsdsd &quot; </code></pre> <p>How could I fix my regex to get this result when I print capturing group 2?</p>
<python><python-3.x><regex><replace><regex-group>
2023-02-25 03:53:12
1
875
Matt095
75,563,183
5,212,614
How can we parse a JSON string and reshape it into a dataframe?
<p>I am playing around with this code.</p> <pre><code>import requests import json import pandas as pd from pandas.io.json import json_normalize url = 'https://stats.nba.com/' headers= {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36', 'Referer': 'https://www.nba.com/'} payload = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0', 'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.5', 'Referer': 'https://www.nba.com/', 'Origin': 'https://www.nba.com', 'Connection': 'keep-alive', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-site', 'If-Modified-Since': 'Fri, 24 Feb 2023 22:32:49 GMT', 'If-None-Match': '1e760c69cdbf7ece59e5733255b8eb25' } response = requests.get('https://cdn.nba.com/static/json/liveData/odds/odds_todaysGames.json', headers=headers) jsonData = response.json() df_nested_list = pd.json_normalize(jsonData) results = [] for item in df_nested_list['games']: print(item) results.append([item['homeTeamId']]) df = pd.DataFrame(results) print(df) </code></pre> <p>I am stuck on the loop part. When I do <code>print(item)</code> I get this.</p> <pre><code>[{'gameId': '0022200898', 'sr_id': 'sr:match:35432417', 'srMatchId': '35432417', 'homeTeamId': '1610612750', 'awayTeamId': '1610612766', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:8072', 'name': 'FrancePari3', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.330', 'opening_odds': '1.300', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '3.200', 'opening_odds': '3.400', 'odds_trend': 'up'}], 'url': 'https://ad.doubleclick.net/ddm/trackclk/N30402.2403113NBA/B25332343.296702000;dc_trk_aid=489395076;dc_trk_cid=146209763;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=?https://www.enligne.parionssport.fdj.fr/paris-basketball/usa/nba?filtre=58557170', 'countryCode': 'FR'}, {'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.380', 'opening_odds': '1.320', 'odds_trend': 'neutral'}, {'odds_field_id': 2, 'type': 'away', 'odds': '3.150', 'opening_odds': '3.450', 'odds_trend': 'up'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.370', 'opening_odds': '1.340', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '3.100', 'opening_odds': '3.400', 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-7.5', 'odds': '1.970', 'opening_odds': '1.900', 'opening_spread': -7.5, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '7.5', 'odds': '1.850', 'opening_odds': '1.920', 'opening_spread': 7.5, 'odds_trend': 'up'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-7.5', 'odds': '2.050', 'opening_odds': '1.900', 'opening_spread': -7.5, 'odds_trend': 'up'}, {'odds_field_id': 12, 'type': 'away', 'spread': '7.5', 'odds': '1.720', 'opening_odds': '1.900', 'opening_spread': 7.5, 'odds_trend': 'down'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200901', 'sr_id': 'sr:match:35431757', 'srMatchId': '35431757', 'homeTeamId': '1610612744', 'awayTeamId': '1610612745', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:8072', 'name': 'FrancePari3', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.230', 'opening_odds': '1.210', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '3.950', 'opening_odds': '4.200', 'odds_trend': 'down'}], 'url': 'https://ad.doubleclick.net/ddm/trackclk/N30402.2403113NBA/B25332343.296702000;dc_trk_aid=489395076;dc_trk_cid=146209763;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=?https://www.enligne.parionssport.fdj.fr/paris-basketball/usa/nba?filtre=58557170', 'countryCode': 'FR'}, {'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.240', 'opening_odds': '1.190', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '4.200', 'opening_odds': '4.750', 'odds_trend': 'up'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.260', 'opening_odds': '1.240', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '3.900', 'opening_odds': '4.200', 'odds_trend': 'down'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-9.5', 'odds': '1.950', 'opening_odds': '1.900', 'opening_spread': -10, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '9.5', 'odds': '1.870', 'opening_odds': '1.920', 'opening_spread': 10, 'odds_trend': 'up'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-9.5', 'odds': '2.000', 'opening_odds': '1.900', 'opening_spread': -9, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '9.5', 'odds': '1.750', 'opening_odds': '1.900', 'opening_spread': 9, 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200899', 'sr_id': 'sr:match:35433317', 'srMatchId': '35433317', 'homeTeamId': '1610612756', 'awayTeamId': '1610612760', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:8072', 'name': 'FrancePari3', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.220', 'opening_odds': '1.270', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '4.100', 'opening_odds': '3.650', 'odds_trend': 'down'}], 'url': 'https://ad.doubleclick.net/ddm/trackclk/N30402.2403113NBA/B25332343.296702000;dc_trk_aid=489395076;dc_trk_cid=146209763;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=?https://www.enligne.parionssport.fdj.fr/paris-basketball/usa/nba?filtre=58557170', 'countryCode': 'FR'}, {'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.240', 'opening_odds': '1.220', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '4.200', 'opening_odds': '4.350', 'odds_trend': 'down'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.230', 'opening_odds': '1.370', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '4.200', 'opening_odds': '3.200', 'odds_trend': 'down'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-7.5', 'odds': '1.750', 'opening_odds': '1.860', 'opening_spread': -8.5, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '7.5', 'odds': '2.100', 'opening_odds': '1.960', 'opening_spread': 8.5, 'odds_trend': 'up'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-7.5', 'odds': '1.650', 'opening_odds': '1.950', 'opening_spread': -7.5, 'odds_trend': 'up'}, {'odds_field_id': 12, 'type': 'away', 'spread': '7.5', 'odds': '2.150', 'opening_odds': '1.800', 'opening_spread': 7.5, 'odds_trend': 'down'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200902', 'sr_id': 'sr:match:35432747', 'srMatchId': '35432747', 'homeTeamId': '1610612746', 'awayTeamId': '1610612758', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:8072', 'name': 'FrancePari3', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.360', 'opening_odds': '1.360', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '3.050', 'opening_odds': '3.050', 'odds_trend': 'up'}], 'url': 'https://ad.doubleclick.net/ddm/trackclk/N30402.2403113NBA/B25332343.296702000;dc_trk_aid=489395076;dc_trk_cid=146209763;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;ltd=?https://www.enligne.parionssport.fdj.fr/paris-basketball/usa/nba?filtre=58557170', 'countryCode': 'FR'}, {'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.410', 'opening_odds': '1.370', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '3.000', 'opening_odds': '3.100', 'odds_trend': 'down'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.420', 'opening_odds': '1.390', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '2.900', 'opening_odds': '3.100', 'odds_trend': 'down'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:27661', 'name': 'Betplay', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-6.5', 'odds': '1.950', 'opening_odds': '1.910', 'opening_spread': -6.5, 'odds_trend': 'up'}, {'odds_field_id': 12, 'type': 'away', 'spread': '6.5', 'odds': '1.870', 'opening_odds': '1.910', 'opening_spread': 6.5, 'odds_trend': 'down'}], 'url': 'https://betplay.com.co/apuestas#filter/basketball/nba', 'countryCode': 'CO'}, {'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-6.5', 'odds': '1.900', 'opening_odds': '1.900', 'opening_spread': -6.5, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '6.5', 'odds': '1.850', 'opening_odds': '1.900', 'opening_spread': 6.5, 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200903', 'sr_id': 'sr:match:35433377', 'srMatchId': '35433377', 'homeTeamId': '1610612765', 'awayTeamId': '1610612761', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '3.100', 'opening_odds': '3.300', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '1.370', 'opening_odds': '1.330', 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '6.5', 'odds': '1.900', 'opening_odds': '1.900', 'opening_spread': 7, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '-6.5', 'odds': '1.900', 'opening_odds': '1.900', 'opening_spread': -7, 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200904', 'sr_id': 'sr:match:35432299', 'srMatchId': '35432299', 'homeTeamId': '1610612766', 'awayTeamId': '1610612748', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '2.600', 'opening_odds': '2.800', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '1.500', 'opening_odds': '1.440', 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '5.5', 'odds': '1.750', 'opening_odds': '1.900', 'opening_spread': 5.5, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '-5.5', 'odds': '2.000', 'opening_odds': '1.900', 'opening_spread': -5.5, 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200905', 'sr_id': 'sr:match:35432307', 'srMatchId': '35432307', 'homeTeamId': '1610612753', 'awayTeamId': '1610612754', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.620', 'opening_odds': '1.700', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '2.350', 'opening_odds': '2.200', 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-2.5', 'odds': '1.750', 'opening_odds': '1.900', 'opening_spread': -2.5, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '2.5', 'odds': '2.000', 'opening_odds': '1.900', 'opening_spread': 2.5, 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200906', 'sr_id': 'sr:match:35431923', 'srMatchId': '35431923', 'homeTeamId': '1610612752', 'awayTeamId': '1610612740', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.650', 'opening_odds': '1.650', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '2.300', 'opening_odds': '2.300', 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-3', 'odds': '1.900', 'opening_odds': '1.900', 'opening_spread': -3, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '3', 'odds': '1.900', 'opening_odds': '1.900', 'opening_spread': 3, 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200907', 'sr_id': 'sr:match:35432501', 'srMatchId': '35432501', 'homeTeamId': '1610612763', 'awayTeamId': '1610612743', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.770', 'opening_odds': '2.000', 'odds_trend': 'down'}, {'odds_field_id': 2, 'type': 'away', 'odds': '2.100', 'opening_odds': '1.850', 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-2.5', 'odds': '1.900', 'opening_odds': '2.250', 'opening_spread': -2.5, 'odds_trend': 'neutral'}, {'odds_field_id': 12, 'type': 'away', 'spread': '2.5', 'odds': '1.900', 'opening_odds': '1.600', 'opening_spread': 2.5, 'odds_trend': 'neutral'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200908', 'sr_id': 'sr:match:35432857', 'srMatchId': '35432857', 'homeTeamId': '1610612755', 'awayTeamId': '1610612738', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '2.000', 'opening_odds': '2.000', 'odds_trend': 'neutral'}, {'odds_field_id': 2, 'type': 'away', 'odds': '1.850', 'opening_odds': '1.850', 'odds_trend': 'neutral'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '3.5', 'odds': '1.620', 'opening_odds': '1.650', 'opening_spread': 3.5, 'odds_trend': 'down'}, {'odds_field_id': 12, 'type': 'away', 'spread': '-3.5', 'odds': '2.200', 'opening_odds': '2.150', 'opening_spread': -3.5, 'odds_trend': 'up'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}, {'gameId': '0022200909', 'sr_id': 'sr:match:35432317', 'srMatchId': '35432317', 'homeTeamId': '1610612762', 'awayTeamId': '1610612759', 'markets': [{'name': '2way', 'odds_type_id': 1, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 1, 'type': 'home', 'odds': '1.180', 'opening_odds': '1.160', 'odds_trend': 'up'}, {'odds_field_id': 2, 'type': 'away', 'odds': '4.800', 'opening_odds': '5.200', 'odds_trend': 'down'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}, {'name': 'spread', 'odds_type_id': 4, 'group_name': 'regular', 'books': [{'id': 'sr:book:35226', 'name': 'TabAustralia', 'outcomes': [{'odds_field_id': 10, 'type': 'home', 'spread': '-12.5', 'odds': '2.200', 'opening_odds': '2.100', 'opening_spread': -12.5, 'odds_trend': 'up'}, {'odds_field_id': 12, 'type': 'away', 'spread': '12.5', 'odds': '1.620', 'opening_odds': '1.680', 'opening_spread': 12.5, 'odds_trend': 'down'}], 'url': 'https://www.tab.com.au/sports/betting/Basketball/competitions/NBA', 'countryCode': 'AU'}]}]}] </code></pre> <p>How can I get that into a dataframe?</p>
<python><json><python-3.x>
2023-02-25 03:50:56
1
20,492
ASH
75,562,903
14,414,944
How can I type hint python-polars dataframe row values?
<p>I would like to be able to provide seamless type hints for a developer API that exposes a <code>polars.DataFrame</code> to the developer. Currently, in every IDE I've checked, if I do something like this...</p> <pre><code>tbl : polars.DataFrame[MyType] = polars.DataFrame([]) row1 = tbl.frame[1, :] </code></pre> <p>... <code>row1</code> is type-checked as <code>DataFrame</code>. Instead, I would like it to be type-checked as <code>MyType</code>. Is this possible? Or, will I need to rewrap this part of the API?</p>
<python><python-typing><python-polars>
2023-02-25 02:15:46
0
1,011
lmonninger
75,562,851
19,411,271
ValueError plotting contourf in Cartopy Azimuthal Equidistant map projection
<p>I would like to use <code>contourf</code> in a Cartopy Azimuth Equidistant map projection. For context, I am trying to plot travel time (in h) of a signal across the globe. Roughly, this is somewhat what I am trying my plot to look like:</p> <p><a href="https://i.sstatic.net/GVoQY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GVoQY.png" alt="fig map" /></a></p> <p>(Image credits to @htonchia, <a href="https://github.com/SciTools/cartopy/issues/1421" rel="nofollow noreferrer">https://github.com/SciTools/cartopy/issues/1421</a>)</p> <p>However, when I try to plot it, it gives the error: <code>line 185, in geos_multipolygon_from_polygons ValueError: Sequences of multi-polygons are not valid arguments</code></p> <p><strong>To reproduce:</strong></p> <pre><code># Data # Longitudes of stations longs = [-171.7827, -171.7827, 179.1966, 179.1966, -159.7733, -159.7733, 174.7043, 174.7043, 172.9229, 172.9229, 159.9475, 159.9475, -157.4457, -157.4457, 146.24998, 146.24998, -169.5292, -169.5292, 166.652, 166.652, -155.5326, -155.5326, -158.0112, -158.0112, -177.3698, -177.3698, 144.8684, 166.7572, 166.7572, 117.239, 117.239, 125.5791, 125.5791, 110.5354, 110.5354, 144.4382, 144.4382, 138.20406, 138.20406, -176.6842, -176.6842, 121.4971, 121.4971, 126.62436, 126.62436, -64.0489, -64.0489, -123.3046, -123.3046, -110.7847, -110.7847, -90.2861, -90.2861, -106.4572, -106.4572, -106.4572, -147.8616, -147.8616, -147.8616, -104.0359, -104.0359, -95.83812, -95.83812, -70.7005, -70.7005, 98.9443, 98.9443, -88.2763, -88.2763, -61.9787, -61.9787, -78.4508, -78.4508, -175.385 ] # Latitudes of stations lats = [-13.9085, -13.9085, -8.5259, -8.5259, -21.2125, -21.2125, -41.3087, -41.3087, 1.3549, 1.3549, -9.4387, -9.4387, 2.0448, 2.0448, -20.08765, -20.08765, 16.7329, 16.7329, 19.2834, 19.2834, 19.7573, 19.7573, 21.42, 21.42, 28.2156, 28.2156, 13.5893, -77.8492, -77.8492, -32.9277, -32.9277, 7.0697, 7.0697, -66.2792, -66.2792, -89.9289, -89.9289, 36.54567, 36.54567, 51.8823, 51.8823, 24.9735, 24.9735, 37.47768, 37.47768, -64.7744, -64.7744, 44.5855, 44.5855, 32.3098, 32.3098, -0.6742, -0.6742, 34.94591, 34.94591, 34.94591, 64.873599, 64.873599, 64.873599, 44.1212, 44.1212, 29.96478, 29.96478, -29.011, -29.011, 18.8141, 18.8141, 20.2263, 20.2263, -38.0568, -38.0568, 0.2376, 0.2376, -20.57 ] # Time (h) signal detected after eruption travel_time_h = [ 0.95296297, 0.95332528, 1.49046297, 1.4905475, 1.67046297, 1.67026972, 2.3705475, 2.37046297, 2.60249194, 2.60240741, 2.7537963, 2.75360306, 3.00943639, 3.00935186, 3.65610306, 3.65601852, 3.93165861, 3.93157408, 16.13526972, 4.43074074, 4.61268519, 4.6130475, 4.6730475, 4.67296297, 5.01026972, 5.01046297, 5.20768519, 5.96546297, 5.9655475, 6.49693639, 6.49685186, 6.40324074, 6.40332528, 6.53740741, 6.53721417, 7.12074074, 7.1205475, 7.34546297, 7.34499194, 7.26157408, 7.26221417, 7.64546297, 7.6455475, 8.13407408, 8.13388083, 7.97693639, 7.97740741, 8.05082528, 8.05101852, 8.00240741, 8.00221417, 8.65943639, 8.65907408, 8.41907408, 8.41776972, 8.42722222, 8.94324074, 8.9430475, 8.94333333, 9.2555475, 9.25601852, 8.99240741, 8.99249194, 9.26851852, 9.26749194, 9.16165861, 9.16185186, 9.41990741, 9.41999194, 9.30851852, 9.31360306, 9.82324074, 9.82332528, 0. ] </code></pre> <p>I then interpolate the data to use in <code>contourf</code></p> <pre><code>import matplotlib.pyplot as plt import numpy as np from cartopy import crs as ccrs from scipy.interpolate import griddata # Interpolate for contour X, Y = np.meshgrid(longs, lats) Z = griddata((longs, lats), travel_time_h, (X, Y), method='linear') </code></pre> <p>And try to plot it using <code>Cartopy</code>:</p> <pre><code># Initialize figure fig = plt.figure(figsize=(10, 8)) projLae = ccrs.AzimuthalEquidistant(central_longitude=-175.385, central_latitude=-20.57) ax = plt.subplot(1, 1, 1, projection=projLae) # Plot contour first as background start_h, end_h, interval_h = 0.0, 10.0, 0.5 levels = np.arange(start=start_h, stop=end_h, step=interval_h) # levels of contour contour = ax.contourf(X, Y, Z, levels=levels, vmin=start_h, vmax=end_h, transform=ccrs.PlateCarree()) # Add colorbar for contour cbar = fig.colorbar(contour, orientation='horizontal') cbar.ax.set_xlabel(f&quot;Time [hr]&quot;) # Plot station locations ax.scatter(longs, lats, s=8, marker='*', color='red', transform=ccrs.PlateCarree()) # Plot map details ax.coastlines() ax.set_global() plt.show() </code></pre> <p>Not sure what is going on, if is a <code>ax.contourf</code> problem and/or a <code>Cartopy</code> Azimuthal Equidistant projection problem. I'm using Cartopy version 0.21.1.</p> <p>I appreciate any help!</p>
<python><matplotlib><cartopy><contourf>
2023-02-25 02:00:23
1
499
just_another_profile
75,562,841
482,819
Avoid explicit `default` keyword in Python's dataclass field
<p><a href="https://peps.python.org/pep-0681/" rel="nofollow noreferrer">PEP 681</a> introduced dataclass transforms. Among it features, it provides “field specifiers, which describe attributes of individual fields that a static type checker must be aware of, such as whether a default value is provided for the field&quot;</p> <p>Is there a way to use <code>default</code> as a positional argument, instead of a keyword argument?</p> <p>I would like that this code:</p> <pre class="lang-py prettyprint-override"><code>@create_model(init=False) class CustomerModel: id: int = model_field(default=3) name: str </code></pre> <p>looks like this:</p> <pre class="lang-py prettyprint-override"><code>@create_model(init=False) class CustomerModel: id: int = model_field(3) name: str </code></pre> <p>without any complains from the type checkers.</p>
<python><field><python-dataclasses>
2023-02-25 01:56:50
1
6,143
Hernan
75,562,763
9,443,671
How to scrape data from a webpage?
<p>There's a webpage which is an interactive version of a dataset where you can view an data example and a few associated labels in boxes. I'm trying to get this data into a pandas dataframe where I extract the example and all the associated labels. The data is divided over multiple pages and has fixed boxes for each label that I want to extract.</p> <p>I have never done such a thing before so I was wondering if there's any way to efficiently do this in Python? What libraries should I be looking at?</p> <p>Here's an example of a sample that I'd like to extract:</p> <p><a href="https://i.sstatic.net/WjrWI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/WjrWI.png" alt="enter image description here" /></a></p>
<python><web-scraping><extract>
2023-02-25 01:26:04
2
687
skidjoe
75,562,668
6,037,395
What is the best way to organize Python import paths for multiple but independent projects?
<p>Say I have three projects A, B and C in my home directory, all written mainly in Python:</p> <pre class="lang-bash prettyprint-override"><code>. ├── project_A │   ├── data │   ├── plot │   ├── result │   └── run.py ├── project_B │   ├── data │   ├── plot │   ├── result │   └── run.py └── project_C    ├── data    ├── plot    ├── result    └── run.py </code></pre> <p>They all have a similar structures: <code>data</code>, <code>result</code> and <code>plot</code> are all directories that contain various scripts. My question is, if I were to export the paths for each of the projects into <code>PYTHONPATH</code> like:</p> <pre class="lang-bash prettyprint-override"><code>export PYTHONPATH=${HOME}/project_A export PYTHONPATH=${HOME}/project_B:${PYTHONPATH} export PYTHONPATH=${HOME}/project_C:${PYTHONPATH} </code></pre> <p>then there will be conflicts/confusions, because all three projects have <code>data</code>, <code>plot</code> as well as <code>result</code>, when I do <code>from data.script import function</code>, I am not sure if am importing from project A, B or C.</p> <p>Given that the three projects are <strong>independent</strong>, can I do the following:</p> <pre class="lang-bash prettyprint-override"><code>export PYTHONPATH=${HOME} </code></pre> <p>and in project A, for example, I imagine that I can safely do:</p> <pre class="lang-py prettyprint-override"><code>from project_A.data.script import function </code></pre> <p>Will anything unexpected happen when I put my home directory into <code>PYTHONPATH</code>? Is there anything I need to be careful with? Is this a good practice at all? If not, what should I be doing instead? Thanks!</p>
<python><path><python-import>
2023-02-25 01:01:22
0
1,654
zyy
75,562,510
1,513,168
How to split string and only assign needed fields
<p>I want to split a string like this. I can do the following.</p> <pre><code>f1, f2, f3, f4, f5 = 'field1_field2_field3_field4_field5'.split('_') </code></pre> <p>However, I only need let's say f1 and f4. I do not want to assign other fields (I do not want to keep the others in the memory). I guess I am looking for something like Perl's array slice notation.</p>
<python>
2023-02-25 00:21:11
3
810
Supertech
75,562,384
9,422,807
How do multiple recursive calls work in Python
<p>Below is a recursion function to decode a string. Can somebody explain to me <strong>step by step</strong> how multiple recursive calls work? Does the func finish the first recursive call and move on to the next recursive call? or does it do a recursive call within a recursive call?</p> <pre><code>def encodings(str, prefix = ''): encs = [] if len(str) &gt; 0: es = encodings(str[1:], (prefix + ',' if prefix else '') + str[0]) encs.extend(es) if len(str) &gt; 1 and int(str[0:2]) &lt;= 26: es = encodings(str[2:], (prefix + ',' if prefix else '') + str[0:2]) encs.extend(es) return encs if len(str) else [prefix] </code></pre> <pre><code>print(encodings(&quot;1234&quot;)) </code></pre> <p>This is what you get. Why?</p> <pre><code>['1,2,3,4', '1,23,4', '12,3,4'] </code></pre>
<python><recursion>
2023-02-24 23:50:56
1
413
Liu Yu
75,562,368
2,328,721
Performance issue with Rust vs Python
<p>After reading an <a href="https://www.gkbrk.com/2022/10/memorable-unique-identifiers-muid/" rel="nofollow noreferrer">article about &quot;Memorable Unique Identifiers&quot;</a> and seeing the author mention that they want to try to rewrite the example Python code to C to achieve better performance, I tried rewriting it to Rust and I was very surprised by the Rust version being considerably <strong>slower</strong> than the Python version.</p> <p>Tested on a 2021 M1 Pro MacBook Pro with <code>Python 3.10.9</code> and <code>nightly-aarch64-apple-darwin, rustc 1.69.0-nightly (07c993eba 2023-02-23)</code>.</p> <p>Python version from the article (sligtly edited from original)</p> <pre class="lang-py prettyprint-override"><code>import json import hashlib import os TARGET_DIFF = 8 prefixes = set() with open(&quot;animals.json&quot;) as f: f = json.load(f) for key in f.keys(): if len(key) == TARGET_DIFF: prefixes.add(key) counter = 0 while counter &lt; 10: buf = os.urandom(16).hex() h = hashlib.sha256(buf.encode(&quot;utf-8&quot;)).digest().hex() if h[:TARGET_DIFF] in prefixes: print(buf, h) counter += 1 </code></pre> <p>This manages to find 10 hashes in about 7 seconds.</p> <pre><code>&gt; time python3 miner.py python3 miner.py 7.60s user 3.00s system 99% cpu 10.626 total </code></pre> <p>My attempt to rewrite this to Rust:</p> <pre class="lang-rust prettyprint-override"><code>use std::{ fs::File, io::{prelude::*, BufReader}, path::Path, fmt::Error, env, process }; use core::fmt::Write; use sha256; use rand_xoshiro::rand_core::SeedableRng; use rand_xoshiro::Xoshiro256PlusPlus; use rand::Rng; const TARGET_DIFF: usize = 8; fn lines_from_file(filename: impl AsRef&lt;Path&gt;) -&gt; Vec&lt;String&gt; { let file = File::open(filename).expect(&quot;no such file&quot;); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect(&quot;could not parse line&quot;)) .filter(|s| s.len() == TARGET_DIFF) .collect() } fn to_hex(input: &amp;mut [u8]) -&gt; Result&lt;String, Error&gt; { let mut s = String::with_capacity(2 * input.len()); for byte in input { write!(s, &quot;{:02x}&quot;, byte)?; } Ok(s) } fn fill_with_random(input: &amp;mut [u8], rng: &amp;mut Xoshiro256PlusPlus) -&gt; Result&lt;(), Error&gt; { for i in 0..input.len() { input[i] = rng.gen::&lt;u8&gt;(); } Ok(()) } fn main() { let args: Vec&lt;String&gt; = env::args().collect(); if args.len() &lt; 2 { println!(&quot;Usage: ./muid &lt;seed&gt;&quot;); process::exit(1); } let seed: i32 = match args[1].parse::&lt;i32&gt;() { Ok(val) =&gt; val, Err(error) =&gt; { println!(&quot;Invalid argument: {:?}&quot;, error); process::exit(1); }, }; let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed.try_into().unwrap()); let lines = lines_from_file(&quot;keywords&quot;); println!(&quot;{0} {1: &gt;31} {2: &gt;61}&quot;, &quot;Private Key&quot;, &quot;Public Key&quot;, &quot;Keyword&quot;); println!(&quot;-----------------------------------------------------------------------------------------------------------&quot;); let mut counter = 0; while counter &lt; 10 { let mut rand: [u8; 16] = [0; 16]; fill_with_random(&amp;mut rand, &amp;mut rng).unwrap(); let rand_str = to_hex(&amp;mut rand).unwrap(); let data_digest = sha256::digest(rand_str.clone()); let head = &amp;data_digest[..TARGET_DIFF]; if lines.contains(&amp;head.to_string()) { println!(&quot;{} {} {}&quot;, rand_str, data_digest, head); counter += 1; } } } </code></pre> <p>Compiled with <code>cargo build --release</code>, it finds 10 hashes in over 44 seconds...</p> <pre><code>&gt; ./target/release/uid 0 ./target/release/muid 0 44.79s user 0.13s system 99% cpu 44.986 total </code></pre> <p>My guess would be either user error because I'm new to Rust or the RNG being slower in Rust for some reason. Can someone please explain why the Rust version is so much slower?</p>
<python><rust><cryptography>
2023-02-24 23:46:23
1
638
Jakub S.
75,562,311
7,519,434
SQLAlchemy get secondary table from relationship
<p>I have the following three tables with irrelevant fields removed:</p> <pre><code>class Users(db.Model): __tablename__ = &quot;users&quot; id = db.Column(db.Integer, primary_key = True) project_memberships = db.relationship(&quot;ProjectMember&quot;, back_populates = &quot;user&quot;) def get_managed_projects(self): return [x.project for x in self.project_memberships if x.is_manager] class Project(db.Model): __tablename__ = &quot;project&quot; id = db.Column(db.Integer, primary_key = True) members = db.relationship(&quot;ProjectMember&quot;, back_populates = &quot;project&quot;) class ProjectMember(db.Model): __tablename__ = &quot;project_member&quot; id = db.Column(db.Integer, primary_key = True) user_id = db.Column(db.Integer, db.ForeignKey(&quot;users.id&quot;), nullable = False) user = db.relationship(&quot;Users&quot;, back_populates = &quot;project_memberships&quot;) project_id = db.Column(db.Integer, db.ForeignKey(&quot;project.id&quot;), nullable = False) project = db.relationship(&quot;Project&quot;, back_populates = &quot;members&quot;) is_manager = db.Column(db.Boolean, nullable = False, default = False) </code></pre> <p>How can I write <code>get_managed_projects</code> using SQLAlchemy methods? I could use</p> <pre><code>db.session.query(Project).join(ProjectMember).filter_by(user = self, is_manager = True).all() </code></pre> <p>but is it possible to make use of <code>project_memberships</code> instead of using <code>user = self</code>?</p>
<python><sqlalchemy><flask-sqlalchemy>
2023-02-24 23:33:32
1
3,989
Henry
75,562,233
2,607,447
Django-guardian has_perm("codename", obj) is False even if group has the permission
<p>I'm trying to implement <code>django-guardian</code> permissions in my project. In the <code>TestCase</code> below, I assigned <code>view_income</code> permission to <code>staff</code> group. That means, also <code>user_c</code> has the permission.</p> <p>The problem is that <code>self.user_c.has_perm(&quot;view_income&quot;, income)</code> returns False.</p> <p>To be clear, I understand how it works and that I can check first the group permission without object. I'm curious if there is a shortcut that will tell me whether a given user has a permission to a given object no matter if it is defined in a group, if it is an object permission or general permission etc...</p> <p>I don't want to write multiple different checks every time I want to check permissions.</p> <pre><code>class IncomePermissionsTestCase(TestCase): def setUp(self): self.user_a = baker.make(settings.AUTH_USER_MODEL) self.user_c = baker.make(settings.AUTH_USER_MODEL) staff_group:Group = baker.make('Group', name='staff') assign_perm('view_income', staff_group) self.user_c.groups.add(staff_group) def test_permissions(self): income = baker.make(&quot;clients.Income&quot;, client=self.user_a) self.assertTrue(self.user_a.has_perm(&quot;view_income&quot;, income)) self.assertTrue(self.user_c.has_perm(&quot;view_income&quot;, income)) </code></pre>
<python><django><django-permissions><django-guardian>
2023-02-24 23:20:40
0
18,885
Milano
75,562,161
20,803,947
Why do programming languages behave this way when there is no precedence?
<p>I realized that in Python and Javascript when we do this kind of conditional the logic doesn't make much sense, because if we put console.log in each condition, we will see that it should return false != true, so we should go inside the if and print the message &quot;Is true&quot; in the terminal, but I would like to understand why this code is printing the log of the else?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const num = 7; if (num &gt;= 5 !== num == 5) { console.log("Is true"); } else { console.log("Is false"); }</code></pre> </div> </div> </p> <p>I know it should take precedence in this code, but I got very confused when I put logs printing separately each condition, for example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const num = 7; console.log(num &gt;= 5); // true console.log(num == 5); // false</code></pre> </div> </div> </p> <p>true != false - should be true and enter if</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const num = 7; console.log(num &gt;= 5 !== num == 5); // false ???</code></pre> </div> </div> </p> <p>Can someone help me with this question?</p>
<javascript><python><logic>
2023-02-24 23:07:10
2
309
Louis
75,562,106
12,870,750
QgraphicsView slow line render
<p>I have been trying to make a line viewer in <code>PyQt5</code>, the main process is to load a geopackage file using geopandas and adding it to a <code>QGrapihcsView</code> scene. The <code>QGrapichsView</code> class is a zoom and pan capable.</p> <p>For this example I used a generic line creator to best represent the actual problem. I used a Voronoi generator that add closed polygons to the scene.</p> <p><strong>Problem</strong></p> <p>The pan and zoom area extremely slow when I do a close up and later a pan action. Also the count line order of magnitude is similar to actual real life examples.</p> <p><strong>What I have tried so far</strong></p> <p>Basically, I have tried to reduce the size of the updated viewport to minimum, also tried rendering using concurrent futures, which turn out to be a very bad idea. Also I united all objects under a <code>QPainterPath</code> but the slow pan and zoom persists.</p> <p>I would appreciate any help, also would be nice to know if QGrapichsView is just not the tool to do this and what would you recommend to do it with that works with <code>PyQt5</code></p> <p>Edit: I have made it a self contained example, although it is very difficult to replicate a contour line from actual topography I do get a similar effect using the voronoi polylines.</p> <p><strong>Code</strong></p> <pre><code>import sys from PyQt5.QtWidgets import QApplication, QGraphicsScene, QGraphicsView, QMainWindow from PyQt5 import QtCore, QtGui, QtWidgets import struct import numpy as np def dummy_generator(num_points, max_points): from scipy.spatial import Voronoi # Define las dimensiones city_width = 8000 city_height = 6000 points = np.random.rand(num_points, 2) * np.array([city_width , city_height]) # Calcula el diagrama de Voronoi de los puntos para generar los bordes de los predios vor = Voronoi(points) # Crea una lista de coordenadas de vértices para cada polilínea que representa los bordes de los predios polylines = [] for ridge in vor.ridge_vertices: if ridge[0] &gt;= 0 and ridge[1] &gt;= 0: x1, y1 = vor.vertices[ridge[0]] x2, y2 = vor.vertices[ridge[1]] if x1 &lt; 0 or x1 &gt; city_width or y1 &lt; 0 or y1 &gt; city_height : continue if x2 &lt; 0 or x2 &gt; city_width or y2 &lt; 0 or y2 &gt; city_height : continue # Genera puntos intermedios en la línea para obtener polilíneas más suaves val = np.random.randint(3, max_points) xs = np.linspace(x1, x2, num=val) ys = np.linspace(y1, y2, num=val) polyline = [(xs[i], ys[i]) for i in range(val)] points = np.array(polyline).T polylines.append(points) return polylines class GraphicsView(QtWidgets.QGraphicsView): def __init__(self, scene): super(GraphicsView, self).__init__(scene) self.pos_init_class = None # &quot;VARIABLES INICIALES&quot; self.scale_factor = 1.5 # &quot;REMOVER BARRAS DE SCROLL&quot; self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # &quot;ASIGNAR ANCLA PARA HACER ZOOM SOBRE EL MISMO PUNTO&quot; self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtWidgets.QGraphicsView.ViewportAnchor.AnchorViewCenter) # Set the item index method to BspTreeIndex scene.setItemIndexMethod(QtWidgets.QGraphicsScene.BspTreeIndex) # &quot;MEJORAR EL RENDER DE VECTORES&quot; self.setRenderHint(QtGui.QPainter.Antialiasing, False) self.setOptimizationFlag(QtWidgets.QGraphicsView.DontAdjustForAntialiasing, True) self.setCacheMode(QtWidgets.QGraphicsView.CacheBackground) self.setViewportUpdateMode(QtWidgets.QGraphicsView.ViewportUpdateMode.MinimalViewportUpdate) def mousePressEvent(self, event): pos = self.mapToScene(event.pos()) if event.button() == QtCore.Qt.MiddleButton: self.pos_init_class = pos QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.ClosedHandCursor) super(GraphicsView, self).mousePressEvent(event) def mouseReleaseEvent(self, event): if self.pos_init_class and event.button() == QtCore.Qt.MiddleButton: self.pos_init_class = None QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor) super(GraphicsView, self).mouseReleaseEvent(event) def mouseMoveEvent(self, event): if self.pos_init_class: delta = self.pos_init_class - self.mapToScene(event.pos()) r = self.mapToScene(self.viewport().rect()).boundingRect() self.setSceneRect(r.translated(delta)) super(GraphicsView, self).mouseMoveEvent(event) def wheelEvent(self, event): self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) old_pos = self.mapToScene(event.pos()) # Determine the zoom factor if event.angleDelta().y() &gt; 0: zoom_factor = self.scale_factor else: zoom_factor = 1 / self.scale_factor # Apply the transformation to the view transform = QtGui.QTransform() transform.translate(old_pos.x(), old_pos.y()) transform.scale(zoom_factor, zoom_factor) transform.translate(-old_pos.x(), -old_pos.y()) # Get the current transformation matrix and apply the new transformation to it current_transform = self.transform() self.setTransform(transform * current_transform) def vector_to_scene(grapchisView): # Get the coordinates of each contour #additional scipy package list_coords = dummy_generator(10000, 500) # Calculate the start and end indices of each contour pos_arr = np.array([max(_.shape) for _ in list_coords]) - 1 fill_arr = np.ones(np.sum(pos_arr)).astype(int) zero_arr = np.zeros(len(pos_arr)).astype(int) c = np.insert(fill_arr, np.cumsum(pos_arr), zero_arr) x, y = np.concatenate(list_coords, axis=1) # Create a QPainterPath to store all the lines path = QtGui.QPainterPath() xy_path = arrayToQPath(x, -y, connect=np.array(c)) path.addPath(xy_path) # Set the pen properties for the lines pen = QtGui.QPen() pen.setColor(QtCore.Qt.black) pen.setWidthF(1) pen.setStyle(QtCore.Qt.SolidLine) # Add the lines to the graphics view grapchisView.scene().addPath(path, pen) def arrayToQPath( x, y, connect='all'): &quot;&quot;&quot;Convert an array of x,y coordinats to QPainterPath as efficiently as possible. The *connect* argument may be 'all', indicating that each point should be connected to the next; 'pairs', indicating that each pair of points should be connected, or an array of int32 values (0 or 1) indicating connections. &quot;&quot;&quot; path = QtGui.QPainterPath() n = x.shape[0] # create empty array, pad with extra space on either end arr = np.empty(n + 2, dtype=[('x', '&gt;f8'), ('y', '&gt;f8'), ('c', '&gt;i4')]) # profiler('allocate empty') byteview = arr.view(dtype=np.ubyte) byteview[:12] = 0 byteview.data[12:20] = struct.pack('&gt;ii', n, 0) # Fill array with vertex values arr[1:-1]['x'] = x arr[1:-1]['y'] = y # decide which points are connected by lines if connect in ['all']: arr[1:-1]['c'] = 1 elif connect in ['pairs']: arr[1:-1]['c'][::2] = 1 arr[1:-1]['c'][1::2] = 0 elif connect in ['finite']: arr[1:-1]['c'] = np.isfinite(x) &amp; np.isfinite(y) elif isinstance(connect, np.ndarray): arr[1:-1]['c'] = connect else: raise Exception('connect argument must be &quot;all&quot;, &quot;pairs&quot;, &quot;finite&quot;, or array') # write last 0 lastInd = 20 * (n + 1) byteview.data[lastInd:lastInd + 4] = struct.pack('&gt;i', 0) # create datastream object and stream into path path.strn = byteview.data[12:lastInd + 4] # make sure data doesn't run away try: buf = QtCore.QByteArray.fromRawData(path.strn) except TypeError: buf = QtCore.QByteArray(bytes(path.strn)) ds = QtCore.QDataStream(buf) ds &gt;&gt; path return path class MainWindow(QMainWindow): def __init__(self): super().__init__() # Create the scene and view self.scene = QGraphicsScene() self.view = GraphicsView(self.scene) self.view.setScene(self.scene) vector_to_scene( self.view) # Set the central widget self.setCentralWidget(self.view) if __name__ == '__main__': app_ = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app_.exec_()) </code></pre>
<python><pyqt5><vispy><qtopengl>
2023-02-24 22:57:35
1
640
MBV
75,562,085
1,627,106
Use connection pooling with python sshfs (fsspec) in Python
<p>I'm using sshfs to fetch video files from a remote SSH storage:</p> <pre><code>@app.get(&quot;/video/{filename}&quot;) async def video_endpoint( filename, range: str = Header(None), db=Depends(get_db) ): # pylint: disable=redefined-builtin &quot;&quot;&quot; Endpoint for video streaming Accepts the UUID and an arbitrary extension &quot;&quot;&quot; # Requesting video with uuid (uuid, extension) = filename.split(&quot;.&quot;) # pylint: disable=unused-variable # Try to get the file info from database file = File.get_by_public_uuid(db, uuid) # Return 404 if file not found if not file: raise HTTPException(404, &quot;File not found&quot;) # Connect with a password ssh_fs = SSHFileSystem( settings.ssh_host, username=settings.ssh_username, password=settings.ssh_password, ) start, end = range.replace(&quot;bytes=&quot;, &quot;&quot;).split(&quot;-&quot;) start = int(start) end = int(end) if end else start + settings.chunk_size with ssh_fs.open(file.path) as video: video.seek(start) data = video.read(end - start) filesize = file.size headers = { &quot;Content-Range&quot;: f&quot;bytes {str(start)}-{str(end)}/{filesize}&quot;, &quot;Accept-Ranges&quot;: &quot;bytes&quot;, } return Response(data, status_code=206, headers=headers, media_type=&quot;video/mp4&quot;) </code></pre> <p>It does work for a few hours after restart, but then subsequent calls yield the error message <code>asyncssh.sftp.SFTPNoConnection: Connection not open</code>. As far as I can tell, even though the <code>SSHFileSystem</code> is initiated during the API call, it is actually cached in the backend.</p> <p>Fsspec creates some asyncio event loop and returns the cached instance. I guess at some point the connection gets dropped by the other side, and for some reason it's not re-established automatically, nor can I find a way to actually use connection pooling.</p> <p>I can avoid the error by calling <code>ssh_fs.clear_instance_cache()</code> at the end, but that means that every time a new connection is established, and this is for every chunk that is fetched, which also doesn't make sense.</p> <p>My question is: How to use <code>SFTPNoConnection</code> connection pooling, in a way that keeps the connection alive and re-establishes it when needed?</p>
<python><sshfs><fsspec>
2023-02-24 22:54:20
1
1,712
Daniel
75,562,024
726,150
Using Comprehension and Data frames to extract data from lists of dictionary's in Python
<p>I sure I should be able to find this but I have looked and I can't seem to fine how to do a few of the user cases I am looking for. I want to search a list of dictionaries and either pull back a subset or count how often a value appears.</p> <p>for example from the below list I want to be able to say</p> <p>return a list of all the dictionaries that contain &quot;WAP1&quot; in the key &quot;AP&quot; or return the number of lists that key &quot;network&quot; = &quot;net1&quot;</p> <p>so return a new list with just the first 2 dictionary items and the number &quot;3&quot;, based on a logical search term</p> <p>I have used, wap = next((item for item in ls_dict if item['AP']=='WAP1'),'none') but this only gets the first item. I was also not sure why this does not work without using &quot;next&quot; and throw's this error. &lt;generator object at 0x7f9146cba0&gt;</p> <p>At the end of the day i want to be able to search a large list for the occurrence of a mac address and either pull out a list of all the dictionary objects that i can use for future operations, or simply count up how many times they appear.</p> <p>Thank you in advance for any guidance, i know this must be simple but have been looking for a while and cant figure it out.</p> <pre><code>&gt; ls_dict = [{'network': 'NET1', 'AP': 'WAP1', 'MAC': 'FF01', 'ap_mac' : 'eeeeeeeeeeee'}, {'network': 'NET1', 'AP': 'WAP1', 'MAC': 'FF02', 'ap_mac' : 'eeeeeeeeeeee'}, {'network': 'NET1', 'AP': 'WAP2', 'MAC': 'FF03', 'ap_mac' : 'eeeeeeeeeeee'}, {'network': 'NET2', 'AP': 'WAP3', 'MAC': 'FF04', 'ap_mac' : 'eeeeeeeeeeee'}] </code></pre>
<python><dictionary>
2023-02-24 22:45:32
2
2,653
DevilWAH
75,561,986
6,410,450
Python detect dates containing commas and remove comma from text file
<p>I have a txt file that contains dates in columns like below. The comma between the day and year is making it hard to import the data into pandas using pd.read_csv(). This is contained within a text file that has other data that should be ignored, so I can't perform some action on the entire document. I need to go through the file, find the dates with this formatting, and remove the commas within the dates, leaving the commas between dates. What's a simple way to accomplish this?</p> <pre><code>May 15, 2023, May 22, 2023 August 14, 2023, August 21, 2023 November 14, 2023, November 21, 2023 February 14, 2024, February 22, 2024 </code></pre>
<python><pandas><python-re>
2023-02-24 22:39:26
2
2,245
Troy D
75,561,834
7,437,143
How to include tests from root project directory in pip package, such that other pip packages can call it?
<h2>Context</h2> <p>After creating a project directory with the following folder structure:</p> <pre class="lang-py prettyprint-override"><code>src/snnalgorithms__main__.py tests/some_test.py tests/some_dir/other_test.py </code></pre> <p>and publishing it as a pip package, I receive the error:</p> <pre><code>from snnalgorithms.tests.sparse.MDSA.test_snn_results import Test_mdsa_snn_results E ModuleNotFoundError: No module named 'snnalgorithms.tests' </code></pre> <p>when I try to call that test file from another pip package/python code/project. I would expect this error, because I did not tell the <code>setup.py</code> (with content) and the <code>setup.cfg</code> that the <code>pip</code> package should include the <code>tests</code> directory.</p> <h2>setup.py</h2> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot;Packaging logic for snnalgorithms.&quot;&quot;&quot; from __future__ import annotations import os import sys import setuptools sys.path.insert(0, os.path.join(os.path.dirname(__file__), &quot;src&quot;)) # sys.path.insert(1, os.path.join(os.path.dirname(__file__), &quot;tests&quot;)) install_requires = [ &quot;lava @ https://github.com/a-t-0/lava/archive/refs/tags/v0.5.1.tar.gz&quot;, ] setuptools.setup() </code></pre> <h2>setup.cfg</h2> <pre><code>[metadata] name = snnalgorithms version = attr: snnalgorithms.__version__ description = compares snn algorithms against neumann algorithms long_description = file: README.md long_description_content_type = text/markdown url = https://github.com/a-t-0/snnalgorithms author = a-t-0 author_email = no-email@no-email.org maintainer = a-t-0 maintainer_email = no-email@no-email.org license = AGPLv3 license_file = licence classifiers = Development Status :: 2 - Pre-Alpha Environment :: Console Intended Audience :: Science/Research License :: OSI Approved :: GNU Affero General Public License v3 Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3.10 Topic :: Scientific/Engineering :: Artificial Intelligence [options] packages = find: package_dir = =src # Dependencies install_requires = jsons&gt;=1.6.3 matplotlib&gt;=3.6.1 networkx&gt;=2.8.7 numpy&gt;=1.23.4 pyannotate&gt;=1.2.0 pytest-cov&gt;=4.0.0 typeguard&gt;=2.13.3 python_requires = &gt;=3.10 [options.packages.find] where = src [options.entry_points] console_scripts = snnalgorithms = snnalgorithms:main [bdist_wheel] universal = 1 [mypy] check_untyped_defs = true disallow_any_generics = true disallow_incomplete_defs = true disallow_untyped_defs = true no_implicit_optional = true warn_unused_ignores = true [mypy-tests.*] disallow_untyped_defs = false </code></pre> <h2>Update based on comments</h2> <p>Based on the comments I learned that it is not desireable/conventional to include the tests in the pip package that is installed by the users. Instead one can differentiate between a <code>wheel</code> and <code>sdist</code> distribution of pip. I believe the <code>wheel</code> contains the MWE pip package for users, whereas the <code>sdist</code> may also include the tests.</p> <h2>Question</h2> <p>How can one include the tests in the root directoy of a repo, into the pip package, such that other pip packages are able to use/import those tests?</p>
<python><pip><setuptools><setup.py><python-packaging>
2023-02-24 22:13:16
0
2,887
a.t.
75,561,783
3,368,667
Pandas rolling command erases column
<p>I'm running into an issues with the pandas <code>.rolling()</code> function and I'm not sure quite how to fix the issue.</p> <p>Here's the dataframe and code</p> <pre><code>dictionary = {'TimeStamp': {0: '2023-02-23 08:01:50.701', 1: '2023-02-23 08:01:50.798', 2: '2023-02-23 08:01:50.798', 3: '2023-02-23 08:01:50.800', 4: '2023-02-23 08:01:50.800'}, 'Delta_TP9': {0: np.nan, 1: 0.8932789112449511, 2: 0.8932789112449511, 3: 0.8932789112449511, 4: 0.8932789112449511}, 'Delta_AF7': {0: np.nan, 1: -0.062321571240896, 2: -0.0734485722420289, 3: -0.0734485722420289, 4: -0.0734485722420289}} df = pd.DataFrame.from_dict(dictionary) df.rolling(3).mean() </code></pre> <p>The problem is, is that the rolling function gets rid of the timeseries column, TimeStamp. I'd like to keep this column. I can't figure out why it's doing this, especially since in the pandas <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html" rel="nofollow noreferrer">tutorial</a> on .rolling, there's an example with a datetime column. It works perfectly well with their example dataframe. If I apply .rolling to the dataframe below, the datatime column is preserved:</p> <pre><code>df_time = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}, index = [pd.Timestamp('20130101 09:00:00'), pd.Timestamp('20130101 09:00:02'), pd.Timestamp('20130101 09:00:03'), pd.Timestamp('20130101 09:00:05'), pd.Timestamp('20130101 09:00:06')]) </code></pre> <p>How do I use rolling so that it preserves all columns? (or add it back into the original dataframe). Thanks for any help!</p>
<python><pandas>
2023-02-24 22:06:42
2
1,077
tom
75,561,763
9,190,503
Django queryset show english translations
<p>This is my Django <code>models.py</code>:</p> <pre><code>from django.db import models class Blog(models.Model): pub_date = models.DateTimeField('date published') def __str__(self): return self.pub_date class LanguagesCode(models.Model): code = models.CharField(max_length=5) def __str__(self): return self.code class BlogTranslation(models.Model): name = models.CharField(max_length=250) content = models.TextField(blank=True, null=True) blog_id = models.ForeignKey(Blog, related_name='translations', on_delete=models.CASCADE) language_code = models.ForeignKey(LanguagesCode, related_name='languages', on_delete=models.DO_NOTHING) class Meta: unique_together = ('blog_id', 'language_code') def __str__(self): return self.name </code></pre> <p>I want to show the list of blogs those have english translation, with name in english. How do I need to write my query to get this data:</p> <pre><code>[ { &quot;name&quot;: &quot;1st Blog name in english&quot;, &quot;content&quot;: &quot;content in english&quot;, &quot;pub_date&quot;: &quot;XXX&quot; }, { &quot;name&quot;: &quot;2nd Blog name in english&quot;, &quot;content&quot;: &quot;content in english&quot;, &quot;pub_date&quot;: &quot;XXX&quot; }, ] </code></pre> <p>I use Django 4 with Django Rest Framework. I want my query to start from Blog model.</p> <p>This is my best try, which doesn't give me the result I want:</p> <pre><code>Blog.objects.filter(translations__id = 2) </code></pre>
<python><django><django-models><django-rest-framework><django-queryset>
2023-02-24 22:03:17
2
1,041
Ulvi
75,561,746
3,123,109
Having both .filter() on query_param and .all() functionality without adding another ViewSet and end-point
<p>I'm trying to avoid making another end-point to handle this query, but thinking there isn't a way around it. Wanted to run it by ya'll before doing so.</p> <p>Basically, I have Documents related to Customers and Products. I want to retrieve only the Documents for a specific Customer and Product.</p> <p>Here are the <code>views.py</code>:</p> <pre><code>class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename', ] queryset = Documents.objects.all() serializer_class = DocumentsSerializer class DocumentToCustomerViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'customer_id', 'document_id' ] queryset = DocumentToCustomer.objects.all() serializer_class = DocumentToCustomerSerializer class DocumentToProductViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filter_fields = [ 'id', 'product_id', 'document_id' ] queryset = DocumentToProduct.objects.all() serializer_class = DocumentToProductSerializer </code></pre> <p>I'm thinking I can do something like this shorthand:</p> <pre><code>class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename' ] queryset = Documents.objects.filter(document_to_product__product_id=id, document_to_customer__customer_id=id) serializer_class = DocumentsSerializer </code></pre> <p>Which does seem to work when I tested it.</p> <p>But then it I think I'd need to make another end-point to accommodate both the <code>.all()</code> and <code>.filter()</code>... I think.</p> <p>Additionally, haven't been able to get the <code>filter_fields = []</code> to work with the relationship either. Trying to do something like <code>/api/documents/?customer_id=123&amp;product_id=123</code>.</p> <p>I get a: <code>TypeError: 'Meta.fields' must not contain non-model field names:</code></p> <p>Here are the models for additional information:</p> <pre><code>class Documents(models.Model): id = models.UUIDField(primary_key=True, null=False) filename = models.CharField(max_length=255, null=False) class Meta: db_table = 'documents' class DocumentToProduct(models.Model): product_id = models.ForeignKey( Product, on_delete=models.CASCADE, db_column='product_id' ) document_id = models.ForeignKey( Documents, on_delete=models.CASCADE, db_column='document_id' ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'document_to_product' unique_together = [['product_id', 'document_id']] class DocumentToCustomer(models.Model): customer_id = models.ForeignKey( Customer, on_delete=models.CASCADE, db_column='customer_id' ) document_id = models.ForeignKey( Documents, on_delete=models.CASCADE, db_column='document_id' ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'document_to_customer' unique_together = [['document_id', 'customer_id']] </code></pre> <p>Any suggestions for how to keeps this clean or will just have to add another end-point to handle this request?</p>
<python><django><django-models><django-rest-framework><django-filter>
2023-02-24 22:01:13
1
9,304
cheslijones
75,561,650
5,203,117
Ranking, ranking, tra la la (ranking in pandas)
<p>I have a pandas dataframe that looks like this:</p> <pre><code> SPX RYH RSP ... RYT RYU EWRE Date ... 2022-03-04 NaN NaN NaN ... NaN NaN NaN 2022-03-11 -0.028774 -0.037115 -0.026436 ... -0.029486 -0.007445 -0.010430 2022-03-18 0.061558 0.059660 0.051164 ... 0.075097 0.003155 0.020566 2022-03-25 0.017911 -0.004760 0.009611 ... 0.003947 0.035678 0.010814 2022-04-01 0.000616 0.016157 0.001266 ... -0.003325 0.040844 0.035427 2022-04-08 -0.012666 0.019052 -0.008406 ... -0.034156 0.019695 -0.006067 2022-04-14 -0.021320 -0.027425 -0.008669 ... -0.027773 -0.008233 -0.007764 2022-04-22 -0.027503 -0.044911 -0.020189 ... -0.026124 -0.013137 0.009547 2022-04-29 -0.032738 -0.038706 -0.032417 ... -0.016110 -0.044835 -0.052401 </code></pre> <p>This is its structure:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; DatetimeIndex: 52 entries, 2022-03-04 to 2023-02-23 Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 SPX 51 non-null float32 1 RYH 51 non-null float32 2 RSP 51 non-null float32 3 RCD 51 non-null float32 4 RYE 51 non-null float32 5 RYF 51 non-null float32 6 RGI 51 non-null float32 7 EWCO 51 non-null float32 8 RTM 51 non-null float32 9 RHS 51 non-null float32 10 RYT 51 non-null float32 11 RYU 51 non-null float32 12 EWRE 51 non-null float32 dtypes: float32(13) memory usage: 3.0 KB </code></pre> <p>I can rank it like so:</p> <pre><code>&gt;&gt;&gt; a.changes.rank(method = &quot;first&quot;, axis = 1) SPX RYH RSP RCD RYE ... RTM RHS RYT RYU EWRE Date ... 2022-03-04 NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN 2022-03-11 6.0 2.0 8.0 3.0 13.0 ... 11.0 1.0 5.0 12.0 10.0 2022-03-18 9.0 8.0 6.0 13.0 1.0 ... 5.0 4.0 12.0 2.0 3.0 2022-03-25 9.0 2.0 5.0 1.0 13.0 ... 12.0 10.0 4.0 11.0 7.0 2022-04-01 8.0 10.0 9.0 5.0 2.0 ... 3.0 11.0 7.0 13.0 12.0 2022-04-08 6.0 10.0 7.0 3.0 12.0 ... 9.0 13.0 1.0 11.0 8.0 2022-04-14 3.0 2.0 5.0 13.0 10.0 ... 12.0 11.0 1.0 6.0 7.0 2022-04-22 5.0 3.0 7.0 9.0 2.0 ... 4.0 12.0 6.0 10.0 13.0 </code></pre> <p>However, that approach only produces ordinal ranks. So ranking [1,2,3] produces [1,2,3] as expected, but so does ranking [1, 9, 10]. What I need are rankings that account for distances. Like this [0.0, 0.888, 1.0]. This function does that.</p> <pre><code>(x - min(row)) / ((max(row) - min(row)) for x in row </code></pre> <p>What I need to know is how to apply that to a dataframe. I tried this:</p> <pre><code>self.ranks2 = self.changes.apply(lambda row: [(x - min(row)) / (max(row) - min(row)) for x in row], axis=1) </code></pre> <p>That works but returns a dataframe of lists when what I need is a modified copy of the original dataframe with ranks instead of values. So my question is this: How to apply that function to a dataframe to generate ranks that respect magnitude as well as order?</p>
<python><pandas>
2023-02-24 21:45:25
1
597
John
75,561,566
6,357,916
Random sampling with numpy works but cupy gives "Unsupported dtype <U20"
<p>I am trying translate my negative sampling code in numpy to cupy.</p> <p>First I have following import in my jupyter notebook:</p> <pre><code>import cupy as cp </code></pre> <p>I have a list of strings my jupyter notebook:</p> <pre><code>In: l = ['aaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbb', 'cccccccccccccccccccc'] </code></pre> <p>I want to randomly sample from these words. So I tried:</p> <pre><code>In: cp.random.choice(l) </code></pre> <p>But it gave following error:</p> <pre><code>Output exceeds the size limit. Open the full output data in a text editor --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-51-ecf4cf343af7&gt; in &lt;module&gt; ----&gt; 1 cp.random.choice(l) /usr/local/lib/python3.8/dist-packages/cupy/random/_sample.py in choice(a, size, replace, p) 188 &quot;&quot;&quot; 189 rs = _generator.get_random_state() --&gt; 190 return rs.choice(a, size, replace, p) 191 192 /usr/local/lib/python3.8/dist-packages/cupy/random/_generator.py in choice(self, a, size, replace, p) 1025 raise ValueError('a must be greater than or equal to 0') 1026 else: -&gt; 1027 a = cupy.array(a, copy=False) 1028 if a.ndim != 1: 1029 raise ValueError('a must be 1-dimensional or an integer') /usr/local/lib/python3.8/dist-packages/cupy/_creation/from_data.py in array(obj, dtype, copy, order, subok, ndmin) 44 45 &quot;&quot;&quot; ---&gt; 46 return _core.array(obj, dtype, copy, order, subok, ndmin) 47 48 ... cupy/_core/core.pyx in cupy._core.core.array() cupy/_core/core.pyx in cupy._core.core._array_default() ValueError: Unsupported dtype &lt;U20 </code></pre> <p>I checked if I can create a cupy list out of this python list:</p> <pre><code>In: words = cp.array(l) </code></pre> <p>But it gave me same error:</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-50-8c7f71b29b1c&gt; in &lt;module&gt; ----&gt; 1 words = cp.array(l) 2 # probs = cp.array(list(noiseDistribution.values())) /usr/local/lib/python3.8/dist-packages/cupy/_creation/from_data.py in array(obj, dtype, copy, order, subok, ndmin) 44 45 &quot;&quot;&quot; ---&gt; 46 return _core.array(obj, dtype, copy, order, subok, ndmin) 47 48 cupy/_core/core.pyx in cupy._core.core.array() cupy/_core/core.pyx in cupy._core.core.array() cupy/_core/core.pyx in cupy._core.core._array_default() ValueError: Unsupported dtype &lt;U20 </code></pre> <p>What I am doing wrong?</p> <hr /> <p>You can try out above code in <a href="https://colab.research.google.com/drive/1UKsrnhAYFJrbg6h4dDPiEOx1qLyLvNs5?usp=sharing" rel="nofollow noreferrer">this colab notebook</a>. Make sure to change runtime to GPU from menu <code>Runtime &gt; Change runtime type</code>. Then only you will be able to import cupy.</p> <p><strong>PS:</strong></p> <p>My list <code>l</code> actually contains real words instead of dummy words shown above:</p> <pre><code>In: l Out: ['emma', 'jane', 'austen', 'woodhouse', 'handsome', 'clever', 'rich', 'comfortable', 'home', 'happy'] </code></pre> <p>I have set it to dummy list of length 20 strings to replicate exact error.</p> <p>Also note that the equivalent numpy sampling works just fine:</p> <pre><code>In: np.random.choice(l) # works Out: 'bbbbbbbbbbbbbbbbbbbb' </code></pre>
<python><numpy><cupy>
2023-02-24 21:33:01
0
3,029
MsA
75,561,489
14,460,824
How to create nested dict with parent children hierachy for streamlit_tree_select from dataframe?
<p>To use <a href="https://github.com/Schluca/streamlit_tree_select" rel="nofollow noreferrer"><code>streamlit_tree_select</code></a> I need to convert a dataframe to its expected structure.</p> <p>I guess to achieve the goal I could use <code>pandas.groupby('parkey')</code> to group the children, but I'm not sure how to apply this to the appropriate parents while iterating the groups.</p> <p>The dataframe holding categories:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = [ {&quot;idnr&quot;: 1,&quot;parkey&quot;: 0,&quot;descr&quot;: &quot;A&quot;,&quot;info&quot;:&quot;string&quot;}, {&quot;idnr&quot;: 2,&quot;parkey&quot;: 0,&quot;descr&quot;: &quot;B&quot;,&quot;info&quot;:&quot;string&quot;}, {&quot;idnr&quot;: 3,&quot;parkey&quot;: 2,&quot;descr&quot;: &quot;B B 1&quot;,&quot;info&quot;:&quot;string&quot;}, {&quot;idnr&quot;: 4,&quot;parkey&quot;: 3,&quot;descr&quot;:&quot;B B B 1&quot;,&quot;info&quot;:&quot;string&quot;}, {&quot;idnr&quot;: 5,&quot;parkey&quot;: 3,&quot;descr&quot;:&quot;B B B 2&quot;,&quot;info&quot;:&quot;string&quot;} ] </code></pre> <p>The expected output:</p> <pre><code>output = [ {&quot;idnr&quot;: 1,&quot;parkey&quot;: 0,&quot;descr&quot;: &quot;A&quot;,&quot;info&quot;:&quot;string&quot;}, {&quot;idnr&quot;: 2,&quot;parkey&quot;: 0,&quot;descr&quot;: &quot;B&quot;,&quot;info&quot;:&quot;string&quot;,&quot;children&quot;:[ {&quot;idnr&quot;: 3,&quot;parkey&quot;: 2,&quot;descr&quot;: &quot;B B 1&quot;,&quot;info&quot;:&quot;string&quot;,&quot;children&quot;:[ {&quot;idnr&quot;: 4,&quot;parkey&quot;: 3,&quot;descr&quot;:&quot;B B B 1&quot;,&quot;info&quot;:&quot;string&quot;}, {&quot;idnr&quot;: 5,&quot;parkey&quot;: 3,&quot;descr&quot;:&quot;B B B 2&quot;,&quot;info&quot;:&quot;string&quot;} ]} ] } ] </code></pre>
<python><pandas><dataframe><dictionary><streamlit>
2023-02-24 21:21:59
1
25,336
HedgeHog
75,561,432
1,062,643
How do I create an extendable bar sprite in PyGame?
<p>I want to use the following asset in my game: <a href="https://i.sstatic.net/ORv9A.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ORv9A.png" alt="bar asset" /></a></p> <p>It has specific pixelated borders and corners. So I want it to scale &quot;extending&quot; the inner part of the asset by repeating it until it matches the desired size. So I can render something like this: <a href="https://i.sstatic.net/xGcMy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xGcMy.png" alt="extended bar sprite" /></a></p> <p>This technique is quite common in UI building world, when you create this simple asset to fit buttons of any size.</p> <p>Is there any way to achieve this with built in PyGame tools?</p>
<python><pygame><sprite><scale><pygame-surface>
2023-02-24 21:13:13
2
2,695
kokoko
75,561,325
4,165,235
How do I scan cards and know when it have been successfully evaluated, without making an API call?
<p>So I have coded this:</p> <pre><code>import cv2 from PIL import Image import pytesseract import re import time vid = cv2.VideoCapture(0) def getText(frame): # TODO Do I really need to convert to PIL from numpy array? im = Image.fromarray(frame).convert('LA') textAreaImage = im.crop((200, 70, 470, 105)) text = pytesseract.image_to_string(textAreaImage , lang = 'eng') newtext = re.sub('[^A-Za-z '',]+', '', text) if(newtext != &quot;&quot;): print(newtext) while(True): ret, frame = vid.read() getText(frame) cv2.rectangle(frame,(200,70),(470,430),(0,255,0),1) cv2.rectangle(frame,(200,70),(470,105),(255,0,0),1) cv2.imshow('frame', frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break vid.release() cv2.destroyAllWindows() </code></pre> <p>This scans and can identify a card perfectly fine theoretically, but when I move the card into place it looks like this</p> <pre><code>Po Rof Roofto Rooftop Storm Rooftop Storm Rooftop Storm Roodkd Rod 0 De Rooftop Saorm Rooftop Storm Drftop ds dd De </code></pre> <p>This is because the detector throws duds at us. In this case I was scanning a card named &quot;Rooftop Storm&quot;</p> <p><a href="https://i.sstatic.net/fnmkP.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fnmkP.jpg" alt="rooftop-storm" /></a></p> <p>How do I actually detect when a genuine word have been entered so I can make an API call with the correct name, and not the noice around it? Because if I called an API with every one of this requests, it would sort of be a DOS attack.... Want a smarter way of doing it but can not figure out a way.</p> <p>Edit: Or possibly make a prediction on if there is words on the sides. Because there is not on playingcards, that would solve my problem</p>
<python><ocr><tesseract><opencv>
2023-02-24 20:58:43
0
788
Salviati
75,561,265
14,385,099
Updating string elements in a list in Python
<p>I have a list of string elements where <code>list = [X, Y, Z]</code>.</p> <p>I want to update the elements in the list such that it becomes <code>[X_AAA, X_BBB, X_CCC, Y_AAA, Y_BBB, Y_CCC, Z_AAA, Z_BBB, Z_CCC]</code>. Essentially, I'm appending AAA, BBB and CCC to every element in this list of strings.</p> <p>What is the most efficient way to do this?</p> <p>Thank you!</p> <p>.</p>
<python><data-wrangling>
2023-02-24 20:50:02
1
753
jo_
75,561,202
12,130,817
Get training specifications for existing yolov5 model such as model version, image size and hyperparameters used during training
<p>I was wondering whether there is a way of getting information about how an existing custom yolov5 model was trained. For example, I would like to know the model version / release, on which image size the model was trained, and the hyperparameters used.</p> <p>I was hoping for something like this:</p> <pre class="lang-py prettyprint-override"><code># load model model = torch.hub.load('./yolov5', 'custom', path='./custom_model.pt', source='local') # get train specifications model.get_train_specs() # Output: # Model version: 6.1 # Trained on image size: 1280 # Hyperparameters used during training: # lr0: 0.01 # lrf: 0.2 # momentum: 0.937 # […] </code></pre>
<python><machine-learning><yolov5>
2023-02-24 20:41:52
0
373
Peter
75,561,168
236,835
Find overlaping area of two images and merge them together with python
<p>I have two images e.g. two screenshots of a web page. The end of one image is the same as the beginning of the second image.</p> <p>How can I use python to find due overlap and merge the two images accordingly?</p> <p>Unfortunately my idea does not work.</p> <ol> <li>load images with pillow</li> <li>convert to grayscale</li> <li>convert to numpy array</li> <li>check lines for equality</li> </ol> <p>Unfortunately no equal lines are found.</p> <p>Does anyone have an idea?</p>
<python><image><numpy><python-imaging-library>
2023-02-24 20:37:34
2
3,179
Marten Bauer
75,561,153
1,504,016
How to generrate odt files from templates in Python
<p>I'm working on a Python program that takes in input data from a database and open document templates (either .ott or .odt files directly) with anchors.</p> <p>I would like the program to be able to generate at output .odt files filled with data from the database.</p> <p>How should I proceed? I saw there were a few libraries that allow to work with opendocument files in python, but most of them are old and no longer maintained. Some suggest to directly modify xml inside documents archives but it seems a bit hacky. I'm surprised that no mainstream library is able to work with opendocument files like so ... am I missing something?</p> <p>Thank you</p>
<python><templates><odt><opendocument>
2023-02-24 20:33:55
1
2,649
ibi0tux
75,560,945
17,696,880
How to perform this replacement on a string only if a sequence of characters is separated from another substring by 2 or more words?
<pre class="lang-py prettyprint-override"><code>import re def person_identification_of_personal_pronouns_le_and_les_func(input_text, number_of_people_involved=&quot;singular&quot;): if number_of_people_involved == &quot;singular&quot;: assumed_subject_of_sentence, personal_pronoun = &quot;(SINGULAR_PERS)&quot;, &quot;le&quot; elif number_of_people_involved == &quot;plural&quot;: assumed_subject_of_sentence, personal_pronoun = &quot;(PLURAL_PERS)&quot;, &quot;les&quot; n_or_more_words = r&quot;\w+\s+\w+\s*&quot; #pattern to match at least two words input_text = re.sub(r&quot;(\(\(PERS\)(?:\w\s*)+\))\s*(&quot; + n_or_more_words + r&quot;)(&quot; + personal_pronoun + r&quot;)\s*\(\(VERB\)&quot;, lambda m: (f&quot;{m[1]} {m[2]} &quot; + assumed_subject_of_sentence + f&quot; {m[3]} ((VERB)&quot;), input_text, flags=re.IGNORECASE) return input_text # input string example: input_text = &quot;le ((VERB)empujé) hasta ((VERB)dejarle) en ese lugar. A ((PERS)Marcos) le ((VERB)dijeron) y luego le ((VERB)ayudo)&quot; input_text = person_identification_of_personal_pronouns_le_and_les_func(input_text, &quot;singular&quot;) print(repr(input_text)) # --&gt; output </code></pre> <p>How do I make this program add <code>&quot;(SINGULAR_PERS)&quot;</code> in front of <code>&quot;le&quot;</code>, if and only if, there is no sequence <code>&quot;(\(\(PERS\)(?:\w\s*)+\))&quot;</code> two or more words before the last occurrence of the string &quot;le&quot; (the same if there is never a sequence <code>&quot;(\(\(PERS\)(?:\w\s*)+\))</code> before <code>&quot;le&quot;</code>, since it is interpreted that there are no less than 2 words in between, if the first condition never appeared).</p> <p>You would need to assign the <code>n_or_more_words</code> variable a regex pattern that indicates that at least 2 or more words are required (a word is understood as a sequence of characters with no spaces in between <code>\w+</code> ) between the last occurrence of a sequence <code>&quot;(\(\(PERS\)(?:\w\s*)+\))&quot;</code> and a <code>&quot;le&quot;</code></p> <p>Although this function does not give an error, for some reason it cannot modify the string since it does not identify the cases where it should make the modifications. What should I change to this function?</p> <p>So after performing the replacement you get this output:</p> <pre><code>&quot;(SINGULAR_PERS) le ((VERB)empujé) hasta ((VERB)dejarle) en ese lugar. A ((PERS)Marcos) le ((VERB)dijeron) y luego (SINGULAR_PERS) le ((VERB)ayudo)&quot; </code></pre>
<python><python-3.x><regex><replace><regex-group>
2023-02-24 20:08:41
1
875
Matt095
75,560,915
11,693,768
Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise only if every column has the same duplicate
<p>This is another extension to my previous questions, <a href="https://stackoverflow.com/questions/75550770/drop-duplicates-in-a-subset-of-columns-per-row-rowwise-only-keeping-the-first/75551691#75551691">Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise</a> and <a href="https://stackoverflow.com/questions/75560780/drop-duplicates-in-a-subset-of-columns-per-row-rowwise-only-keeping-the-first">Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise only if there are 3 or more duplicates</a></p> <p>I have the following dataframe, (actually its around 7 million rows)</p> <pre><code>import pandas as pd data = {'date': ['2023-02-22', '2023-02-21', '2023-02-23'], 'x1': ['descx1a', 'descx1b', 'descx1c'], 'x2': ['ALSFNHF950', 'KLUGUIF615', np.nan], 'x3': [np.nan, np.nan, 24319.4], 'x4': [np.nan, np.nan, 24334.15], 'x5': [np.nan, np.nan, 24040.11], 'x6': [404.29, 75.21, 24220.34], 'x7': [np.nan, np.nan, np.nan], 'v': [np.nan, np.nan, np.nan], 'y': [404.29, 75.33, np.nan], 'ay': [np.nan, np.nan, np.nan], 'by': [np.nan, np.nan, np.nan], 'cy': [np.nan, np.nan, np.nan], 'gy': [np.nan, np.nan, np.nan], 'uap': [404.29, 75.33, np.nan], 'ubp': [404.29, 75.33, np.nan], 'sf': [np.nan, 2.0, np.nan]} df = pd.DataFrame(data) </code></pre> <p>If there are all duplicates in my selection of columns, I want to to delete the duplicates and keep only 1 copy, if and only if every item in the selection is a duplicate.</p> <p>Meaning if my selection has 4 columns, all 4 columns must have the same number for it to be considered a duplicate.</p> <p>If only 2 or 3 of the selection of 4 have duplicates it does not count.</p> <p>So in my example above, if my selection is, <code>['x6', 'y', 'uap', 'ubp']</code>,the output should be,</p> <pre><code>data = {'date': ['2023-02-22', '2023-02-21', '2023-02-23'], 'x1': ['descx1a', 'descx1b', 'descx1c'], 'x2': ['ALSFNHF950', 'KLUGUIF615', np.nan], 'x3': [np.nan, np.nan, 24319.4], 'x4': [np.nan, np.nan, 24334.15], 'x5': [np.nan, np.nan, 24040.11], 'x6': [404.29, 75.21, 24220.34], 'x7': [np.nan, np.nan, np.nan], 'v': [np.nan, np.nan, np.nan], 'y': [np.nan, 75.33, np.nan], 'ay': [np.nan, np.nan, np.nan], 'by': [np.nan, np.nan, np.nan], 'cy': [np.nan, np.nan, np.nan], 'gy': [np.nan, np.nan, np.nan], 'uap': [np.nan, 75.33, np.nan], 'ubp': [np.nan, 75.33, np.nan], 'sf': [np.nan, 2.0, np.nan]} </code></pre> <p>The second row should not be touched because one of the columns are different.</p> <p>How can I achieve this?</p>
<python><pandas><dataframe>
2023-02-24 20:04:42
2
5,234
anarchy
75,560,780
11,693,768
Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise only if there are 3 or more duplicates
<p>This is an extension to my previous question, <a href="https://stackoverflow.com/questions/75550770/drop-duplicates-in-a-subset-of-columns-per-row-rowwise-only-keeping-the-first/75551691#75551691">Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise</a> I also have a similar question here which has a different requirement <a href="https://stackoverflow.com/questions/75560915/drop-duplicates-in-a-subset-of-columns-per-row-rowwise-only-keeping-the-first">Drop duplicates in a subset of columns per row, rowwise, only keeping the first copy, rowwise only if every column has the same duplicate</a></p> <p>I have the following dataframe. (actual one is around 7 million rows)</p> <pre><code>import pandas as pd data = {'date': ['2023-02-22', '2023-02-21', '2023-02-23'], 'x1': ['descx1a', 'descx1b', 'descx1c'], 'x2': ['ALSFNHF950', 'KLUGUIF615', np.nan], 'x3': [np.nan, np.nan, 24319.4], 'x4': [np.nan, np.nan, 24334.15], 'x5': [np.nan, np.nan, 24040.11], 'x6': [np.nan, 75.51, 24220.34], 'x7': [np.nan, np.nan, np.nan], 'v': [np.nan, np.nan, np.nan], 'y': [404.29, np.nan, np.nan], 'ay': [np.nan, np.nan, np.nan], 'by': [np.nan, np.nan, np.nan], 'cy': [np.nan, np.nan, np.nan], 'gy': [np.nan, np.nan, np.nan], 'uap': [404.29, 75.33, np.nan], 'ubp': [404.29, 75.33, np.nan], 'sf': [np.nan, 2.0, np.nan]} df = pd.DataFrame(data) </code></pre> <p>If there are more than 3 or more duplicates of a number in any of the columns x3,x4,x5,x6,x7,v,y,ay,by,cy,gy,uap,ubp, I want to to delete the duplicates and only keep one copy, the first column in which the duplicate appears or the column that I can select if that's possible.</p> <p>The output should look like this,</p> <pre><code> data = {'date': ['2023-02-22', '2023-02-21', '2023-02-23'], 'x1': ['descx1a', 'descx1b', 'descx1c'], 'x2': ['ALSFNHF950', 'KLUGUIF615', np.nan], 'x3': [np.nan, np.nan, 24319.4], 'x4': [np.nan, np.nan, 24334.15], 'x5': [np.nan, np.nan, 24040.11], 'x6': [np.nan, 75.51, 24220.34], 'x7': [np.nan, np.nan, np.nan], 'v': [np.nan, np.nan, np.nan], 'y': [404.29, np.nan, np.nan], 'ay': [np.nan, np.nan, np.nan], 'by': [np.nan, np.nan, np.nan], 'cy': [np.nan, np.nan, np.nan], 'gy': [np.nan, np.nan, np.nan], 'uap': [np.nan, 75.33, np.nan], 'ubp': [np.nan, 75.33, np.nan], 'sf': [np.nan, 2.0, np.nan]} </code></pre> <p>The second row shouldn't be affected because there's only 2 copies of the number.</p> <p>The previous question had the answer,</p> <pre><code>check = ['x3', 'x4', 'x5', 'x6', 'x7', 'v', 'y', 'ay', 'by', 'cy', 'gy', 'uap', 'ubp'] df.loc[:, check] = df.loc[:, check].mask(df.loc[:, check].apply(pd.Series.duplicated, axis=1)) print(df) </code></pre> <p>But if I do that, then one of the 75.33 would be deleted. That's not what I want.</p> <p>I was thinking maybe I can do a for loop per row and then replace the value but I have over 7 million rows of data. Any ideas?</p>
<python><pandas><dataframe>
2023-02-24 19:47:23
1
5,234
anarchy
75,560,602
197,937
YouTube Data API: video.list endpoint returning 400 error invalid filters
<p>I am using YouTube Data Api v3 to fetch video statistics from a YouTube channel. But I am getting the error message below. I searched online, but couldn't figure out the error because I am not using the parameter in the request.</p> <pre><code># Define the YouTube API request to fetch the statistics of the videos videos_stats_request = youtube.videos().list( part='statistics', id=','.join(video_ids), maxResults=50 ) </code></pre> <p>Error message:</p> <pre><code>googleapiclient.errors.HttpError: &lt;HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/videos returned &quot;The request specifies an invalid filter parameter.&quot;. Details: &quot;[{'message': 'The request specifies an invalid filter parameter.', 'domain': 'youtube.parameter', 'reason': 'invalidFilters', 'location': 'parameters.', 'locationType': 'other'}]&quot;&gt; </code></pre>
<python><youtube-api><youtube-data-api><google-api-python-client>
2023-02-24 19:24:23
0
2,571
Karthik
75,560,546
5,489,190
Converting Python.Runtime.PyObject (Pythonnet) to C# native data types - it works for double but not for numpy.array
<p>Let's say that I will call a python 3.0 script from C# using Pythonnet. As long as the return is of type double it is pretty simple:</p> <pre><code>var input1 = new double[] {15, 20, 25}; dynamic test = Py.Import(&quot;Py_file_name&quot;); double r1 = test.function_name(input1); </code></pre> <p>The value returned from <code>function_name()</code> method is converted to double and I can work with it as I want. But with more complicated code, the things go different, lets say, the <code>retun</code> is a <code>numpy.array</code>:</p> <pre><code>double [] r1 = test.function_name(input1); </code></pre> <p>Fails with the error <code>Cannot implicitly convert type 'Python.Runtime.PyObject' to 'double []'</code>. I can get the value to object like this:</p> <pre><code>object r1 = test.ANN1_fun(input1); </code></pre> <p>But this do not solve anything, as I still have variable of type <code>object {Python.Runtime.PyObject}</code> and I cannot (I don't know how) use it in my C# project. How to convert this numpy.array to any C# array?</p>
<python><c#><python-3.x><numpy><python.net>
2023-02-24 19:16:35
1
749
Karls
75,560,514
15,781,591
Creating reverse average calculation with constraints in python
<p>I am trying to work out how to use <code>solver()</code> from SymPy in python to solve my algebra problem with constraints.</p> <p>I have two mystery values XX and YY that need to average to ZZ, where XX and YY both need to be greater than &quot;lower_constraint&quot; and less than &quot;upper_constraint&quot;.</p> <p>I know that if I needed to find XX or YY, if I already knew one of these values and ZZ, I could simply use solver from sympy.</p> <p>For an example where I know XX = 35 and ZZ = 42, I can easily find the correct YY for XX and YY to average to ZZ using basic algebra as so:</p> <pre><code>((35 + x) / 2) = 42 2 * ((35 + x) / 2) = 42 * 2 35 + x = 84 x = 84 - 35 x = 49 </code></pre> <p>and so here XX = 49</p> <p>and now written for SymPy we set the right side of the equation to 0:</p> <p>expr = ((35 + X) / 2) - 42</p> <p>and so writing the whole code as:</p> <pre><code>x = symbols('x') expr = ((35 + X) / 2) - 42 sol = solve(expr) </code></pre> <p>And this solves it. Great.</p> <p>But now I want to do something a little more complicated. Here we had a straightforward solution, because there is only one value to go with 35 to get an exact average of 42.</p> <p>What if we have our ZZ value of 42, but we do not know either of the two values XX and YY that make up this average? There would be an infinite list of value pairs that could average to 42.</p> <p>In my problem, I have two constraints, that I will declare as constraint1 = 2 and constraint 2 = 104</p> <p>And so, then I would solve for all the pairs of values that are both &gt; 2 and less than 104 that average to 42. There may still be many.</p> <p>However, what I am trying to figure out here is from this list of pairs is the widest apart pair, such that I would pull both the lowest and highest possible values as a pair to average to 42 meeting my constraints.</p> <p>How can I augment my code to calculate/print these two values using <code>solver()</code> from <code>SymPy</code>?</p>
<python><sympy><solver>
2023-02-24 19:11:57
1
641
LostinSpatialAnalysis
75,560,495
5,868,293
How to see if in-between two date columns, specific dates fall into, pandas
<p>I have a pandas dataframe that looks like this:</p> <pre><code>import pandas as pd pd.DataFrame({'date_start' : ['2022-12-06', '2022-12-25', '2022-12-16'], 'date_end': ['2022-12-08', '2022-12-26', '2022-12-30']}) date_start date_end 0 2022-12-06 2022-12-08 1 2022-12-25 2022-12-26 2 2022-12-16 2022-12-30 </code></pre> <p>I would like to create an extra column that indicates if <strong>between</strong> <code>date_start</code> and <code>date_end</code> <strong>at least one</strong> of the <code>dates_xmas = ['2022-12-24','2022-12-25']</code> exist</p> <p>The output dataframe should look like this:</p> <pre><code>pd.DataFrame({'date_start' : ['2022-12-06', '2022-12-25', '2022-12-16'], 'date_end': ['2022-12-08', '2022-12-26', '2022-12-30'], 'xmas':[0,1,1]}) date_start date_end xmas 0 2022-12-06 2022-12-08 0 1 2022-12-25 2022-12-26 1 2 2022-12-16 2022-12-30 1 </code></pre> <p>How can I do that ?</p>
<python><pandas>
2023-02-24 19:10:28
2
4,512
quant
75,560,424
7,281,675
transformers refine-tune with different classes
<p>I want to fine-tune a BERT-based already fine-tuned model for classification with 7 classes another time on a 16 class dataset:</p> <pre><code>MODEL_NAME_OR_PATH = 'some pretrained model for 7 class classification on huggingface repo' model = build_model(MODEL_NAME_OR_PATH, learning_rate=LEARNING_RATE) def build_model(model_name, learning_rate=3e-5): model = TFBertForSequenceClassification.from_pretrained(model_name) optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy') model.compile(optimizer=optimizer, loss=loss, metrics=[metric]) return model r = model.fit( train_dataset, validation_data=valid_dataset, steps_per_epoch=train_steps, validation_steps=valid_steps, epochs=EPOCHS, verbose=1) </code></pre> <p>As expected the model expects 7 class at the final layer, and produces the following error:</p> <pre><code>Node: 'sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits' Received a label value of 9 which is outside the valid range of [0, 8). Label values: 6 2 0 6 0 9 6 6 0 6 6 0 7 2 2 2 [[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_43224] </code></pre> <p>How should one edit the structure of the model?</p>
<python><classification><huggingface-transformers><bert-language-model>
2023-02-24 19:03:48
1
4,603
keramat
75,560,404
6,387,095
cron - log file not being written to after a certain time?
<p>I have a <code>script</code> running via <code>crontab</code></p> <p>It runs perfectly till a certain time and <code>print</code> statements show up in the <code>log</code> file. After this particular time, the log file doesn't have any more entries.</p> <p>I checked whether the <code>script</code> is still running:</p> <pre><code>ps aux | grep script_name </code></pre> <p>Shows in the results:</p> <pre class="lang-none prettyprint-override"><code>&gt;ubuntu 19748 0.0 0.0 4636 820 ? Ss 09:15 0:00 /bin/sh -c python3 /home/ubuntu/ib/op_script/process.py &gt; /home/ubuntu/logs/process.log 2&gt;&amp;1 &gt;ubuntu 19751 0.1 9.4 812908 381100 ? Sl 09:15 0:23 python3 /home/ubuntu/ib/op_script/process.py &gt;ubuntu 23161 0.0 0.0 14860 1080 pts/0 S+ 13:57 0:00 grep --color=auto process </code></pre> <p>I checked the free memory:</p> <pre><code>free -h </code></pre> <p>Output:</p> <pre><code> total used free shared buff/cache available Mem: 3.8G 1.4G 208M 12M 2.2G 2.1G Swap: 0B 0B 0B </code></pre> <p>I am not sure how to check what the error might be, or if the script is still doing its functions just not writing to the <code>log</code> file.</p> <p>Note: the functions are repetitive in a <code>while</code> loop and have run multiple times before. I am not sure what would be the reason for no <code>print</code> statements coming</p>
<python><ubuntu><cron>
2023-02-24 19:00:37
1
4,075
Sid
75,560,117
1,577,947
Does Python have a "PYTHONBUFFERED" Environment Variable?
<p>I see many people setting <code>ENV PYTHONBUFFERED=1</code> in their Dockerfile. Just <a href="https://www.google.com/search?q=%22PYTHONBUFFERED%22" rel="nofollow noreferrer">Google it</a>.</p> <p>I know that <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONUNBUFFERED" rel="nofollow noreferrer">PYTHONUNBUFFERED</a> exists (emphasis on the &quot;UN&quot;).</p> <p>So my basic question is, does <code>PYTHONBUFFERED</code> exist, do a lot of people just misspell it, or is it a concept specific to Docker?</p> <p>Example seen in a Dockerfile:</p> <pre><code>FROM --platform=linux/amd64 python:3.10-buster ENV PYTHONBUFFERED=1 ... </code></pre>
<python>
2023-02-24 18:22:48
1
19,182
Jarad
75,560,107
12,210,377
Count Each String In A List with One Character Mismatch
<p>I have a list of strings:</p> <pre><code>my_list = 'AAA AAA BBB BBB DDD DDD DDA'.split() my_list ['AAA', 'AAA', 'BBB', 'BBB', 'DDD', 'DDD', 'DDA'] </code></pre> <p>I need to count every element appearing in the list. However, if two strings have one mismatch, we would count them as the same string and then count.</p> <p>I mostly use the following script to count.</p> <pre><code>my_list.count('AAA') </code></pre> <p>However, not sure about how to implement the mismatch part. I am thinking to run two <code>for loops</code>, compare two strings and then increment the count. It would be O(n^2).</p> <p><em><strong>Desired Output</strong></em></p> <pre><code>AAA 2 BBB 2 DDD 3 DDA 3 </code></pre> <p>What would be the ideal way of getting the desired output? Any suggestions would be appreciated. Thanks!</p>
<python><string><dataframe>
2023-02-24 18:22:08
1
1,084
Roy
75,560,025
1,857,373
Reshape | values (ValueError) for impute transformation interative imputer fit transform on Bayesian Ridge: ValueError Expected 2D array, got 1D array
<p><strong>Problem</strong> <strong>Updated with new Python code and new Error</strong></p> <p>Created new imputer_bayesian_ridge() function not working on 2D requirements for IterativeImputer to impute training data. Sending in data frame training data, then immediately get data.values for numpy array variable, then reshape(1, -1) this data_array variable. This is a training data with many features, but this effort is only seeking to impute on one single feature.</p> <p>I pull the numpy array via data[feature].values, then .reshape(-1, 1) to handle a single feature. Not working as it appears that I have something out of sequence.</p> <p>The feature is simply a single column with many rows, what must I do to send this single column feature as a 2D array for the function interative_imputer_fit.transform()? Perhaps another algorithm works better for single feature column than RepeatedStratifiedKFold, any suggestions.</p> <pre><code>Ex: single feature column data data data </code></pre> <p><strong>Shape of train_data</strong></p> <pre><code>print(train_data.shape) data_array = train_data.values data_array = data_array.reshape(-1, 1) print(data_array.shape) data_array (1460, 250) (365000, 1) array([[-1.73086488], [-0.20803433], [-0.20714171], ..., [-0.11785113], [ 0.4676514 ], [-0.30599503]]) </code></pre> <p><strong>Code function version 1</strong></p> <pre><code>def imputer_regressor_bay_ridge(data, y): data_array = data.values data = data_array.reshape(-1, 1) interative_imputer = IterativeImputer(BayesianRidge()) interative_imputer_fit = interative_imputer.fit(data) data_imputed = interative_imputer_fit.transform(data) cv = linear_model.LinearRegression() scores = cross_val_score(interative_imputer, data, y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise') return scores, data_imputed </code></pre> <pre><code>scores, data_imputed = imputer_bay_ridge(train_data) print('Impute Bay Ridge Mean Accuracy: %.3f (%.3f)' % (mean(scores), std(scores))) </code></pre> <p><strong>Error</strong></p> <pre><code>ValueError Traceback (most recent call last) Cell In[4], line 169 167 #train_data, test_data = minmaxscaler(train_data, test_data) # alternate run for min-max scaler 168 columns, imputed_df = imputer_regressor(train_data) --&gt; 169 scores, data_imputed = imputer_regressor_bay_ridge(train_data, test_data) 171 misTrain = whichColumnsMissing(train_data) 172 misTest = whichColumnsMissing(test_data) Cell In[4], line 110, in imputer_regressor_bay_ridge(data, y) 108 data_imputed = interative_imputer_fit.transform(data) 109 cv = linear_model.LinearRegression() --&gt; 110 scores = cross_val_score(interative_imputer, data, 111 y, scoring='accuracy', cv=cv, n_jobs=-1, error_score='raise') 113 return scores, data_imputed File ~/opt/anaconda3/lib/python3.9/site-packages/sklearn/model_selection/_validation.py:509, in cross_val_score(estimator, X, y, groups, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch, error_score) 506 # To ensure multimetric format is not supported 507 scorer = check_scoring(estimator, scoring=scoring) --&gt; 509 cv_results = cross_validate( 510 estimator=estimator, 511 X=X, 512 y=y, 513 groups=groups, 514 scoring={&quot;score&quot;: scorer}, 515 cv=cv, 516 n_jobs=n_jobs, 517 verbose=verbose, 518 fit_params=fit_params, 519 pre_dispatch=pre_dispatch, 520 error_score=error_score, 521 ) 522 return cv_results[&quot;test_score&quot;] File ~/opt/anaconda3/lib/python3.9/site-packages/sklearn/model_selection/_validation.py:253, in cross_validate(estimator, X, y, groups, scoring, cv, n_jobs, verbose, fit_params, pre_dispatch, return_train_score, return_estimator, error_score) 48 def cross_validate( 49 estimator, 50 X, (...) 62 error_score=np.nan, 63 ): 64 &quot;&quot;&quot;Evaluate metric(s) by cross-validation and also record fit/score times. 65 66 Read more in the :ref:`User Guide &lt;multimetric_cross_validation&gt;`. (...) 251 252 &quot;&quot;&quot; --&gt; 253 X, y, groups = indexable(X, y, groups) 255 cv = check_cv(cv, y, classifier=is_classifier(estimator)) 257 if callable(scoring): File ~/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/validation.py:378, in indexable(*iterables) 359 &quot;&quot;&quot;Make arrays indexable for cross-validation. 360 361 Checks consistent length, passes through None, and ensures that everything (...) 374 sparse matrix, or dataframe) or `None`. 375 &quot;&quot;&quot; 377 result = [_make_indexable(X) for X in iterables] --&gt; 378 check_consistent_length(*result) 379 return result File ~/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/validation.py:332, in check_consistent_length(*arrays) 330 uniques = np.unique(lengths) 331 if len(uniques) &gt; 1: --&gt; 332 raise ValueError( 333 &quot;Found input variables with inconsistent numbers of samples: %r&quot; 334 % [int(l) for l in lengths] 335 ) ValueError: Found input variables with inconsistent numbers of samples: [365000, 1459] </code></pre>
<python><arrays><scikit-learn><bayesian><imputation>
2023-02-24 18:12:12
1
449
Data Science Analytics Manager
75,559,930
10,976,654
How to create nested rec arrays
<p>Given the following arrays:</p> <pre><code>name = np.array(['a', 'b', 'c']) val = np.array([0.4, 0.5, 0.6]) alt = np.array([1.1, 2.1, 3.1]) b = np.array([17.2]) </code></pre> <p>How can I combine them into a recarray (or structured array, same thing) that looks like this: <code>[('a', 'b', 'c'), (0.4, 0.5, 0.6), (1.1, 2.1, 3.1), (17.2)]</code>. And where <code>print(arr[&quot;name&quot;])</code> returns <code>('a', 'b', 'c')</code>.</p> <p>The actual data has a dozen arrays. There is always one array (<code>b</code>) that only has size of one; the others all have the same size, but that size will vary. So, I'm looking for a solution that is extensible to these conditions. Thank you.</p>
<python><arrays><numpy><tuples><recarray>
2023-02-24 18:01:43
2
3,476
a11
75,559,776
9,072,753
How to wait on multiple multiprocess.Process to finish execution when they exec()?
<p>I need to wait for multiple processes to finish execution. I am using multiprocess.Process, because I want to adjust oom score of the subprocesses before executing them. After research, I wanted to use multiprocessing.connection.wait and sentinel values of subprocesses to wait on them.</p> <p>Consider the following code:</p> <pre><code>import multiprocessing import multiprocessing.connection import os from datetime import datetime def adj_oom_score_exec(*command: str): with open(&quot;/proc/{}/oom_score_adj&quot;.format(os.getpid()), &quot;w&quot;) as f: f.write(&quot;500&quot;) os.execv(command[0], command) exit(198) pp = multiprocessing.Process(target=adj_oom_score_exec, args=[&quot;/usr/bin/sleep&quot;, &quot;1&quot;]) pp.start() print(datetime.now()) multiprocessing.connection.wait([pp.sentinel]) print(datetime.now()) </code></pre> <p>The code outputs two timestamps with difference in milliseconds. <code>multiprocessing.connection.wait()</code> does <strong>not</strong> wait for the command to finish execution. How to make it wait? Note that <code>pp.join()</code> does work and because subprocess is not a daemon, Python will actually wait for the process to finish.</p>
<python><python-3.x><linux><python-multiprocessing>
2023-02-24 17:43:54
1
145,478
KamilCuk
75,559,726
2,811,074
RuntimeError: numel: integer multiplication overflow
<p>I am trying to build a generative recurrent GAN architecture for a multi-variate time-series data. Here is the discriminator of my model:</p> <pre><code>from torchgan.models import Generator, Discriminator import torch import torch.nn as nn class RGANDiscriminator(Discriminator): def __init__(self, sequence_length, input_size, hidden_size=None, num_layers=1, dropout=0, last_layer=None, device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;), **kwargs): hidden_size = hidden_size or input_size self.device = device self.input_size = input_size self.sequence_length = sequence_length self.hidden_size = hidden_size self.num_layers = num_layers self.dropout = dropout self.label_type =&quot;none&quot; # Set kwargs (might overried above attributes) for key, value in kwargs.items(): setattr(self, key, value) super(RGANDiscriminator, self).__init__(self.input_size, self.label_type) # Build RNN layer self.rnn = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True) self.dropout = nn.Dropout(dropout) self.linear = nn.Linear(hidden_size, 1) self.last_layer = last_layer # Initialize all weights. self.rnn.apply(init_weights) nn.init.xavier_normal_(self.linear.weight) def forward(self, x): h0 = torch.randn((self.num_layers, x.size(0), self.hidden_size)).to(self.device) c0 = torch.randn((self.num_layers, x.size(0), self.hidden_size)).to(self.device) print(f&quot;input {x.shape}&quot;) print(f&quot;x: {x}&quot;) length = torch.LongTensor([torch.max((x[i,:,0]!=0).nonzero()).item()+1 for i in range(x.shape[0])]) packed = nn.utils.rnn.pack_padded_sequence( x, length, batch_first=True, enforce_sorted=False ) out_packed, (_, _) = self.rnn(packed, (h0, c0)) y, _ = nn.utils.rnn.pad_packed_sequence(out_packed, batch_first=True) y = self.dropout(y) y = self.linear(y) return y if self.last_layer is None else self.last_layer(y) </code></pre> <p>This is the training module of my model:</p> <pre><code>def train(self, epochs, writer_frequency=1, saver_frequency=20): avg_mmd = [] for epoch in range(epochs): mmd = [] for batch_idx, (data_attribute, data_feature) in enumerate(self.real_train_dl): data_attribute = data_attribute.to(self.device) input_feature = data_feature.to(self.device) batch_size = data_attribute.shape[0] ### Train Discriminator: max log(D(x)) + log(1 - D(G(z))) noise = gen_noise((batch_size, self.sequence_length[0], self.noise_dim)).to(self.device) print(f&quot;Noise:{noise.shape}&quot;) print(f&quot;data attribute {data_attribute.shape}&quot;) noise = torch.cat((data_attribute, noise), dim=2) print(f&quot;noise again : {noise.shape}&quot;) input_feature = torch.cat((data_attribute, input_feature), dim=2) print(f&quot;input_feature : {input_feature.shape}&quot;) fake = self.generator(noise) print(f&quot;fake :{fake.shape}&quot;) x = fake.clone() x = x.permute(0,2,1) padded = nn.ConstantPad1d((0, input_feature.shape[1] - fake.shape[1]), 0)(x) x = padded.permute(0,2,1) print(f&quot;new fake :{x.shape}&quot;) mmd.append(calculate_mmd_rbf(torch.mean(fake, dim=0).detach().cpu().numpy(), torch.mean(data_feature, dim=0).detach().cpu().numpy())) fake = torch.cat((data_attribute, x), dim=2) disc_real = self.discriminator(input_feature).view(-1) lossD_real = self.criterion(disc_real, torch.ones_like(disc_real)) disc_fake = self.discriminator(fake).view(-1) lossD_fake = self.criterion(disc_fake, torch.zeros_like(disc_fake)) lossD = (lossD_real + lossD_fake) / 2 self.discriminator.zero_grad() lossD.backward(retain_graph=True) self.optimizer_dis.step() ### Train Generator: min log(1 - D(G(z))) &lt;-&gt; max log(D(G(z)) output = self.discriminator(fake).view(-1) lossG = self.criterion(output, torch.ones_like(output)) self.generator.zero_grad() lossG.backward() self.optimizer_gen.step() </code></pre> <p>This the error message</p> <pre><code>INFO:config_logger:Batch Size: 40 INFO:config_logger:Noise Dimension: 5 INFO:config_logger:d_rounds: 1 INFO:config_logger:g_rounds: 1 INFO:config_logger:Device: cuda:0 INFO:config_logger:Input Dimension: 14 INFO:config_logger:Output Dimension: 12 INFO:config_logger:Sequence Length: (382,) Noise:torch.Size([40, 382, 5]) data attribute torch.Size([40, 382, 14]) noise again : torch.Size([40, 382, 19]) input_feature : torch.Size([40, 382, 26]) fake :torch.Size([40, 340, 12]) new fake :torch.Size([40, 382, 12]) input torch.Size([40, 382, 26]) input torch.Size([40, 382, 26]) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-2-5cea213d3975&gt; in &lt;module&gt; 676 time_logging_file=time_logging_file, batch_size=batch_size, 677 config_logging_file=config_logging_file) --&gt; 678 trainer.train(epochs=epoch, writer_frequency=1, saver_frequency=save_frequency) 8 frames &lt;ipython-input-2-5cea213d3975&gt; in train(self, epochs, writer_frequency, saver_frequency) 592 disc_real = self.discriminator(input_feature).view(-1) 593 lossD_real = self.criterion(disc_real, torch.ones_like(disc_real)) --&gt; 594 disc_fake = self.discriminator(fake).view(-1) 595 lossD_fake = self.criterion(disc_fake, torch.zeros_like(disc_fake)) 596 lossD = (lossD_real + lossD_fake) / 2 /usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1193 or _global_forward_hooks or _global_forward_pre_hooks): -&gt; 1194 return forward_call(*input, **kwargs) 1195 # Do not call functions when jit is used 1196 full_backward_hooks, non_full_backward_hooks = [], [] &lt;ipython-input-2-5cea213d3975&gt; in forward(self, x) 370 c0 = torch.randn((self.num_layers, x.size(0), self.hidden_size)).to(self.device) 371 print(f&quot;input {x.shape}&quot;) --&gt; 372 print(f&quot;x: {x}&quot;) 373 length = torch.LongTensor([torch.max((x[i,:,0]!=0).nonzero()).item()+1 for i in range(x.shape[0])]) 374 packed = nn.utils.rnn.pack_padded_sequence( /usr/local/lib/python3.8/dist-packages/torch/_tensor.py in __format__(self, format_spec) 857 if self.dim() == 0 and not self.is_meta and type(self) is Tensor: 858 return self.item().__format__(format_spec) --&gt; 859 return object.__format__(self, format_spec) 860 861 @_handle_torch_function_and_wrap_type_error_to_not_implemented /usr/local/lib/python3.8/dist-packages/torch/_tensor.py in __repr__(self, tensor_contents) 425 ) 426 # All strings are unicode in Python 3. --&gt; 427 return torch._tensor_str._str(self, tensor_contents=tensor_contents) 428 429 def backward( /usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py in _str(self, tensor_contents) 635 with torch.no_grad(): 636 guard = torch._C._DisableFuncTorch() --&gt; 637 return _str_intern(self, tensor_contents=tensor_contents) /usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py in _str_intern(inp, tensor_contents) 566 tensor_str = _tensor_str(self.to_dense(), indent) 567 else: --&gt; 568 tensor_str = _tensor_str(self, indent) 569 570 if self.layout != torch.strided: /usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py in _tensor_str(self, indent) 326 ) 327 else: --&gt; 328 formatter = _Formatter(get_summarized_data(self) if summarize else self) 329 return _tensor_str_with_formatter(self, indent, summarize, formatter) 330 /usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py in __init__(self, tensor) 113 114 else: --&gt; 115 nonzero_finite_vals = torch.masked_select( 116 tensor_view, torch.isfinite(tensor_view) &amp; tensor_view.ne(0) 117 ) RuntimeError: numel: integer multiplication overflow </code></pre> <p>I will appreciate if anyone coould help me to understand why I am getting this error.</p>
<python><lstm><recurrent-neural-network><tensor><generative-adversarial-network>
2023-02-24 17:38:44
2
4,378
Dalek
75,559,703
2,610,522
Is bilinear resampling to a coarser resolution is similar to weighted spatial averaging?
<p>I am using the <a href="https://xesmf.readthedocs.io/en/latest/index.html#" rel="nofollow noreferrer">xESMF</a> python package to resample NDVI (greeness) data from 500 * 500 m to 1 * 1 degree.To clarify, I'm increasing the scale of the data. The package offers several techniques, including bilinear and conservative. I'm wondering if resampling from a higher resolution to a lower resolution using bilinear interpolation is analogous to weighted spatial averaging, where the weights correspond to the finer resolution pixel areas.</p> <p>They have an example <a href="https://xesmf.readthedocs.io/en/latest/notebooks/Compare_algorithms.html" rel="nofollow noreferrer">here</a>, which shows most methods produce similar results when upscaling. However, there is no weighted averaging. I should mention that my data is very smooth.</p>
<python><python-xarray><resampling>
2023-02-24 17:36:17
1
810
Ress
75,559,699
4,981,251
Currency pair strength list based on dataframe row values
<p>Based on the following currency strength rankings dataframe:</p> <pre><code> EUR USD GBP JPY AUD CHF CAD NZD 2023-02-24 12:00:00 5.0 8.0 4.0 3.0 2.0 7.0 6.0 1.0 2023-02-24 13:00:00 6.0 8.0 4.0 3.0 2.0 7.0 5.0 1.0 2023-02-24 14:00:00 7.0 8.0 4.0 3.0 2.0 6.0 5.0 1.0 2023-02-24 15:00:00 7.0 8.0 6.0 2.0 3.0 5.0 4.0 1.0 </code></pre> <p>How to calculate and return a list of strongest to weakest currency pairs for each row?</p> <p><strong>Desired output</strong></p> <p>For example on the last row the strongest currency pair would be &quot;USD_NZD&quot; as USD has the highest rank and NZD the lowest.</p> <pre><code>['USD_NZD', 'USD_JPY'] then all other currency pairs </code></pre> <p><strong>Data</strong></p> <pre><code>{'EUR': {Timestamp('2023-02-24 12:00:00'): 5.0, Timestamp('2023-02-24 13:00:00'): 6.0, Timestamp('2023-02-24 14:00:00'): 7.0, Timestamp('2023-02-24 15:00:00'): 7.0}, 'USD': {Timestamp('2023-02-24 12:00:00'): 8.0, Timestamp('2023-02-24 13:00:00'): 8.0, Timestamp('2023-02-24 14:00:00'): 8.0, Timestamp('2023-02-24 15:00:00'): 8.0}, 'GBP': {Timestamp('2023-02-24 12:00:00'): 4.0, Timestamp('2023-02-24 13:00:00'): 4.0, Timestamp('2023-02-24 14:00:00'): 4.0, Timestamp('2023-02-24 15:00:00'): 6.0}, 'JPY': {Timestamp('2023-02-24 12:00:00'): 3.0, Timestamp('2023-02-24 13:00:00'): 3.0, Timestamp('2023-02-24 14:00:00'): 3.0, Timestamp('2023-02-24 15:00:00'): 2.0}, 'AUD': {Timestamp('2023-02-24 12:00:00'): 2.0, Timestamp('2023-02-24 13:00:00'): 2.0, Timestamp('2023-02-24 14:00:00'): 2.0, Timestamp('2023-02-24 15:00:00'): 3.0}, 'CHF': {Timestamp('2023-02-24 12:00:00'): 7.0, Timestamp('2023-02-24 13:00:00'): 7.0, Timestamp('2023-02-24 14:00:00'): 6.0, Timestamp('2023-02-24 15:00:00'): 5.0}, 'CAD': {Timestamp('2023-02-24 12:00:00'): 6.0, Timestamp('2023-02-24 13:00:00'): 5.0, Timestamp('2023-02-24 14:00:00'): 5.0, Timestamp('2023-02-24 15:00:00'): 4.0}, 'NZD': {Timestamp('2023-02-24 12:00:00'): 1.0, Timestamp('2023-02-24 13:00:00'): 1.0, Timestamp('2023-02-24 14:00:00'): 1.0, Timestamp('2023-02-24 15:00:00'): 1.0}} </code></pre>
<python><pandas>
2023-02-24 17:35:42
1
5,548
nipy
75,559,640
89,092
How can I make pandas.read_sql_query ignore the datetime datatype of a column in the source database?
<p><strong>The error that I get is &quot;ValueError: month must be in 1..12&quot;</strong></p> <p>I know that there is &quot;weird&quot; data in that column and I want pandas to treat it as text or ignore the rows with errors and populate the df with the remainder.</p> <p>(Not a big deal but would be good to avoid having to code an exception for this column in this table when hundreds of others work just fine)</p> <pre><code>query = 'SELECT troubledDateCol FROM table' data = pd.read_sql_query(query, cnxn, dtype={'troubledDateCol': pd.StringDtype}) </code></pre> <p>How can I make pandas.read_sql_query ignore the datetime datatype of a column in the source database?</p> <p><strong>I have tried all sorts to work around this:</strong></p> <ul> <li>parse_dates={&quot;troubledDateCol&quot;: {&quot;errors&quot;: &quot;ignore&quot;, &quot;format&quot;: &quot;various%formats%that&amp;might&amp;work&quot;}}</li> <li>parse_dates={&quot;troubledDateCol&quot;: {&quot;errors&quot;: &quot;coerce&quot;, &quot;format&quot;: &quot;various%formats%that&amp;might%work&quot;}}</li> <li>parse_dates={&quot;troubledDateCol&quot;: {&quot;errors&quot;: &quot;coerce&quot;, &quot;date_parser&quot;: myCustomParser&quot;}} <ul> <li>Debugging and putting a breakpoint here shows that the error occurs before the custom parser is invoked</li> </ul> </li> <li>CASTing and CONVERTing troubledDateCol to VARCHAR in the query <ul> <li>This doesn't work because the database is a pernickety, proprietary, flat file DB developed by Sage accounts, based on Pervasive SQL and these fail on execution of the query before pandas tried to load the data</li> </ul> </li> <li>Trying to use SQLalchemy and pyOdbc <ul> <li>I wasn't able to successfully connect using these despite extensive efforts and found a fair amount of other people having had the same issues</li> </ul> </li> </ul>
<python><pandas><datetime><sage><pervasive>
2023-02-24 17:28:47
0
1,704
RobD
75,559,596
1,739,681
Is there a way to import every submodule using --hidden-import in pyinstaller?
<p>We are using Pyinstaller and we have a module that has several hidden &quot;submodules&quot;. So, currently, we need to use --hiden-import module.submodule1 --hiden-import module.submodule2 and so on.</p> <p>I've tried --hiden-import module, but it didn't work.</p> <p>Is there a way to import all the submodules in a single statement?</p>
<python><pyinstaller>
2023-02-24 17:24:04
2
305
julianofischer
75,559,484
14,678,213
IndexError: list index out of range in pypdf2 extract_text in specific pdf file
<p>I have tried:</p> <pre><code>from PyPDF2 import PdfReader input_pdf = PdfReader(open(&quot;pdfFile.pdf&quot;, &quot;rb&quot;)) thispage = input_pdf.pages[0] print(thispage.extract_text()) </code></pre> <p>And I got the following error:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\Usuario\Desktop\pypdf.py&quot;, line 5, in &lt;module&gt; print(thispage.extract_text()) File &quot;C:\Users\Usuario\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\_page.py&quot;, line 1851, in extract_text return self._extract_text( File &quot;C:\Users\Usuario\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\_page.py&quot;, line 1342, in _extract_text cmaps[f] = build_char_map(f, space_width, obj) File &quot;C:\Users\Usuario\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\_cmap.py&quot;, line 28, in build_char_map map_dict, space_code, int_entry = parse_to_unicode(ft, space_code) File &quot;C:\Users\Usuario\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\_cmap.py&quot;, line 196, in parse_to_unicode process_rg, process_char, multiline_rg = process_cm_line( File &quot;C:\Users\Usuario\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\_cmap.py&quot;, line 264, in process_cm_line multiline_rg = parse_bfrange(l, map_dict, int_entry, multiline_rg) File &quot;C:\Users\Usuario\AppData\Local\Programs\Python\Python310\lib\site-packages\PyPDF2\_cmap.py&quot;, line 278, in parse_bfrange nbi = max(len(lst[0]), len(lst[1])) IndexError: list index out of range </code></pre> <p>This happens only with a specific pdf file that is NOT encrypted. I could get it text with pdfminer but I read that it is slower so I want to use pypdf2 Do anyone know the solution?</p>
<python><python-3.x><pdf><pypdf>
2023-02-24 17:12:15
1
567
Tomás Gomez Pizarro
75,559,402
5,110,870
Python: using try/except for a multi-step flow
<p>Let's assume that we have the following flow:</p> <pre class="lang-py prettyprint-override"><code>def flow(input_val: Any) -&gt; Any: result1 = function1(input_val) result2 = function2(result1) result3 = function3(result2) return result3 </code></pre> <p>And let's say that I want to be able to catch exceptions for each of these three steps:</p> <pre class="lang-py prettyprint-override"><code>def flow(input_val: Any) -&gt; Any: try: result1 = function1(input_val) except Exception as ex: print(&quot;Function 1 error: &quot;+str(ex)) try: result2 = function2(result1) except Exception as ex: print(&quot;Function 2 error: &quot;+str(ex)) try: result3 = function3(result2) except Exception as ex: print(&quot;Function 3 error: &quot;+str(ex)) return result3 </code></pre> <p>This doesn't look like the best way of handling exceptions in a flow like this, because if the first exception is caught, then <code>result1</code> won't be defined. Also, if the third exception is caught, there won't be anything to return.</p> <p>What's the best way of handling these situations?</p>
<python><error-handling><try-except>
2023-02-24 17:03:18
5
7,979
FaCoffee
75,559,166
75,103
How do I add system_platform specifiers to pyproject.toml?
<p>I have a bare-bones pyproject.toml file in an empty directory:</p> <pre><code>[build-system] requires = [&quot;setuptools&quot;] build-backend = &quot;setuptools.build_meta&quot; [project] name = &quot;test-virtualenvwrapper&quot; version = &quot;0.1.0&quot; dependencies = [ 'virtualenvwrapper ; system_platform == &quot;linux&quot;', 'virtualenvwrapper-win ; system_platform == &quot;win32&quot;', ] </code></pre> <p>When I run <code>pip install -e .</code> I get the following error:</p> <pre><code>(dev38) go|c:\srv\tmp\pyprojplat&gt; pip install -e . Looking in indexes: https://pypi.org/simple, http://pypi.norsktest.xyz Obtaining file:///C:/srv/tmp/pyprojplat Installing build dependencies ... done Checking if build backend supports build_editable ... done Getting requirements to build editable ... error error: subprocess-exited-with-error × Getting requirements to build editable did not run successfully. │ exit code: 1 ╰─&gt; [48 lines of output] configuration error: `project.dependencies[{data__dependencies_x}]` must be pep508 DESCRIPTION: Project dependency specification according to PEP 508 GIVEN VALUE: &quot;virtualenvwrapper ; system_platform == \&quot;linux\&quot;&quot; OFFENDING RULE: 'format' DEFINITION: { &quot;$id&quot;: &quot;#/definitions/dependency&quot;, &quot;title&quot;: &quot;Dependency&quot;, &quot;type&quot;: &quot;string&quot;, &quot;format&quot;: &quot;pep508&quot; } Traceback (most recent call last): File &quot;C:\srv\venv\dev38\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py&quot;, line 353, in &lt;module&gt; main() File &quot;C:\srv\venv\dev38\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py&quot;, line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File &quot;C:\srv\venv\dev38\lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py&quot;, line 132, in get_requires_for_build_editable return hook(config_settings) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\build_meta.py&quot;, line 447, in get_requires_for_build_editable return self.get_requires_for_build_wheel(config_settings) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\build_meta.py&quot;, line 338, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\build_meta.py&quot;, line 320, in _get_build_requires self.run_setup() File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\build_meta.py&quot;, line 335, in run_setup exec(code, locals()) File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt; File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\__init__.py&quot;, line 108, in setup return distutils.core.setup(**attrs) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\_distutils\core.py&quot;, line 159, in setup dist.parse_config_files() File &quot;C:\srv\venv\dev38\lib\site-packages\_virtualenv.py&quot;, line 21, in parse_config_files result = old_parse_config_files(self, *args, **kwargs) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\dist.py&quot;, line 885, in parse_config_files pyprojecttoml.apply_configuration(self, filename, ignore_option_errors) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\config\pyprojecttoml.py&quot;, line 62, in apply_configuration config = read_configuration(filepath, True, ignore_option_errors, dist) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\config\pyprojecttoml.py&quot;, line 126, in read_configuration validate(subset, filepath) File &quot;C:\Users\me\AppData\Local\Temp\pip-build-env-2lncmkj6\overlay\Lib\site-packages\setuptools\config\pyprojecttoml.py&quot;, line 51, in validate raise ValueError(f&quot;{error}\n{summary}&quot;) from None ValueError: invalid pyproject.toml config: `project.dependencies[{data__dependencies_x}]`. configuration error: `project.dependencies[{data__dependencies_x}]` must be pep508 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build editable 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. (dev38) go|c:\srv\tmp\pyprojplat&gt; </code></pre> <p>I believe the system_platform specifiers are correct according to PEP508, so what am I doing wrong..?</p>
<python>
2023-02-24 16:41:09
1
27,572
thebjorn
75,559,153
11,269,090
Python ProcessPoolExecutor pas-in single and multiple arg
<p>It is possible to pass in multiple arguments to <code>ProcessPoolExecutor</code> to execute a function that takes in multiple parameters with multiple processes:</p> <pre><code>def fn(a, b, c): print(f&quot;{a}, {b}, {c}&quot;) with ProcessPoolExecutor(max_workers=5) as exe: entries_to_print = exe.map(fn, [1, 2, 3], [2, 3, 4], [3, 4, 5]) </code></pre> <p>This will print:</p> <pre><code>1, 2, 3 2, 3, 4 3, 4, 5 </code></pre> <p>But what if I would like the parameter <code>a</code> to be fixed, and only <code>b</code> changes, and <code>c</code> stays fixed too. So the output is</p> <pre><code>1, 2, 3 1, 3, 3 1, 4, 3 </code></pre> <p>I tried <code>entries_to_print = exe.map(fn, [1], [2, 3, 4], [3])</code>. This does not work, since it only prints <code>1, 2, 3</code>. The only way I was able to make it work was <code>entries_to_print = exe.map(fn, [1, 1, 1], [2, 3, 4], [3, 3, 3])</code>.</p> <p>But what if the parameter <code>a</code> is a large data, and I do not want to make 3 copies of it. Is there another way than just copy the fixed parameters multiple times to make a list?</p>
<python><multiprocessing>
2023-02-24 16:40:08
2
1,010
Chen
75,559,122
4,072,043
Embedded external URL breaks Sphinx?
<p>I am trying to document some Python code with Sphinx, and I've added the following doc comment to a constant.</p> <pre><code>#: `RFC 8415 §7.6 &lt;https://www.rfc-editor.org/rfc/rfc8415.html#section-7.6&gt;`_ _SOL_TIMEOUT = 1 </code></pre> <p>This appears to break Sphinx; it considers anything before the colon to be a type identifier, so the result is something like:</p> <blockquote> <p><strong>pkg.module._SOL_TIMEOUT</strong>=1</p> <p>/www.rfc-editor.org/rfc/rfc8415.html#section-7.6&gt;`_</p> <p><strong>Type::</strong> `RFC 8415 §7.6 &lt;https</p> </blockquote> <p>(That's as close as I can get with Markdown.)</p> <p>Is there any way to make embedded external URLs work with Sphinx, or am I stuck with the named URL syntax?</p> <p>(Just for the record, I have tried replacing the non-ASCII '§' with an simple 'S'; the change had no effect on the behavior that I'm seeing.)</p>
<python><python-sphinx><autodoc>
2023-02-24 16:37:05
1
1,628
Ian Pilcher
75,558,835
16,853,253
I'm getting raise AttributeError(key) error in Flask
<p>In flask, I'm using <code>marshmallow_sqlalchemy</code> package to serialize and de-serialize model data. I have two models, <code>Account</code> and <code>Address</code>. I have Account foreign key to Address model. My model details are listed below.</p> <p><code>models.py</code></p> <pre><code>class Account(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(length=30), nullable=False) username = db.Column(db.String(length=15), nullable=False, unique=True) email = db.Column(db.String(length=100), nullable=False, unique=True) password = db.Column(db.String(), nullable=False) image = db.Column(db.String()) address = db.relationship( &quot;Address&quot;, cascade=&quot;all, delete, delete-orphan&quot;, backref=&quot;account&quot;, lazy=True, ) class AccountSchema(SQLAlchemyAutoSchema): class Meta: model = Account exclude = [&quot;password&quot;] include_relationships = True load_instance = True </code></pre> <pre><code>class Address(db.Model): id = db.Column(db.Integer, primary_key=True) address = db.Column(db.Text) phone = db.Column(db.Integer) city = db.Column(db.String(length=35)) state = db.Column(db.String(length=25)) account_id = db.Column(db.Integer, db.ForeignKey(&quot;account.id&quot;), nullable=False) class AddressSchema(SQLAlchemyAutoSchema): class Meta: model = Address include_fk = True load_instance = True </code></pre> <p>So here I have two schemas created also, so when I try to run the app and create database i get this error</p> <pre><code>Traceback (most recent call last): File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/flask/cli.py&quot;, line 897, in run_command app = info.load_app() File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/flask/cli.py&quot;, line 308, in load_app app = locate_app(import_name, name) File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/flask/cli.py&quot;, line 218, in locate_app __import__(module_name) File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/app.py&quot;, line 1, in &lt;module&gt; from flaskproject import create_app File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/flaskproject/__init__.py&quot;, line 4, in &lt;module&gt; from flaskproject.database import load_database File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/flaskproject/database.py&quot;, line 7, in &lt;module&gt; from .user import models File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/flaskproject/user/__init__.py&quot;, line 1, in &lt;module&gt; from . import views File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/flaskproject/user/views.py&quot;, line 10, in &lt;module&gt; from .models import Account, AccountSchema File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/flaskproject/user/models.py&quot;, line 62, in &lt;module&gt; class AccountSchema(SQLAlchemyAutoSchema): File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/marshmallow/schema.py&quot;, line 121, in __new__ klass._declared_fields = mcs.get_declared_fields( File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/marshmallow_sqlalchemy/schema.py&quot;, line 91, in get_declared_fields fields.update(mcs.get_declared_sqla_fields(fields, converter, opts, dict_cls)) File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/marshmallow_sqlalchemy/schema.py&quot;, line 130, in get_declared_sqla_fields converter.fields_for_model( File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/marshmallow_sqlalchemy/convert.py&quot;, line 154, in fields_for_model field = base_fields.get(key) or self.property2field(prop) File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/marshmallow_sqlalchemy/convert.py&quot;, line 193, in property2field field_class = field_class or self._get_field_class_for_property(prop) File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/marshmallow_sqlalchemy/convert.py&quot;, line 275, in _get_field_class_for_property column = _base_column(prop.columns[0]) File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py&quot;, line 1329, in __getattr__ return self._fallback_getattr(key) File &quot;/home/jackson/Learning/Python/flask-learning/FlaskLearn02/env007/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py&quot;, line 1298, in _fallback_getattr raise AttributeError(key) AttributeError: columns </code></pre> <p>I'm unable to find the solution for it, but one thing I understood lately is that the schemas I have created is causing the issue because when I comment out the <code>AccountSchema</code> there is no error at all. I can't seem to understand why. Please help me on this</p>
<python><sqlalchemy><marshmallow><marshmallow-sqlalchemy>
2023-02-24 16:10:26
1
387
Sins97
75,558,714
1,503,669
How to use python selenium to locate the scrollbar on the right and then scroll down continuously to fully load all items content?
<p>I want to scrape all the items' information from this page <a href="https://allinone.pospal.cn/m#/categories" rel="nofollow noreferrer">https://allinone.pospal.cn/m#/categories</a>, refer to the screenshot.</p> <p>the content is loading dynamically when I scroll down the right side of the page to the bottom and this webpage has two scrollbars. I tried a few times; however, I still failed to scroll it, so I can't get the item information on the next pages (next scroll), only able to extract the first 20 items, but it has about 1500+ items.</p> <p>please kindly help me with this.</p> <p>my code is as below:</p> <pre><code>import time import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Load the webpage url = 'https://allinone.pospal.cn/m#/categories' driver = webdriver.Chrome() driver.get(url) # Wait for the promotion image to load and click it promotion_image = WebDriverWait(driver, 10).until( EC.presence_of_element_located( (By.XPATH, '//img[@src=&quot;//imgw.pospal.cn/we/westroe/img/categories/discount.png&quot;]')) ) promotion_image.click() # get focus on the right side of the page (two scroll bar, focus on the right) # Wait for the div to load and get focus on the element items_div = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'div.yb-scrollable')) ) #items_div.send_keys(Keys.NULL) items_div.click() # Do something with the div, e.g. get its text content #@print(items_div.text) #- #### attempt 1 - to scroll ##Scroll to the bottom of the page # scroll_pause_time = 1 # scroll_step = 500 # scroll_height = driver.execute_script(&quot;return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );&quot;) # while True: # driver.execute_script(f&quot;window.scrollTo(0, {scroll_height});&quot;) # scroll_height_new = driver.execute_script(&quot;return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );&quot;) # if scroll_height_new == scroll_height: # break # scroll_height = scroll_height_new # time.sleep(scroll_pause_time) # - # - #### attempt 2 # &quot;&quot;&quot;A method for scrolling to the bottom of the page.&quot;&quot;&quot; # # Get scroll height. # last_height = driver.execute_script(&quot;return document.body.scrollHeight&quot;) # while True: # # Scroll down to the bottom. # driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);&quot;) # # Wait to load the page. # time.sleep(2) # # Calculate new scroll height and compare with last scroll height. # new_height = driver.execute_script(&quot;return document.body.scrollHeight&quot;) # if new_height == last_height: # break # last_height = new_height #### attempt 3 lenOfPage = driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;&quot;) match=False while(match==False): lastCount = lenOfPage time.sleep(3) lenOfPage = driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;&quot;) if lastCount==lenOfPage: match=True # Extract the content of the yb-item tags soup = BeautifulSoup(driver.page_source, 'html.parser') yb_items = soup.find_all('div', {'class': 'yb-item'}) for yb_item in yb_items: print(yb_item.text.strip()) # Close the browser window driver.quit() </code></pre> <p><a href="https://i.sstatic.net/dhBBb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dhBBb.png" alt="enter image description here" /></a></p>
<python><selenium-webdriver><web-scraping><beautifulsoup><infinite-scroll>
2023-02-24 15:59:56
1
513
Panco
75,558,702
2,600,161
DataFrame.apply() to column with list values
<p>I am drawing a blank on how to do this properly, I have a dataframe containing bounding box coordinates as a <code>list</code> type. ex:</p> <pre><code> bb_box 0 [4, 565, 1088, 591] 1 [17, 820, 1092, 949] 2 [5, 746, 1084, 796] 3 [32, 240, 1104, 263] 4 [0, 187, 1111, 212] ... </code></pre> <p>I need to apply normalization coordinates to each value in the list of the <code>bb_box</code> column. I want to use a vectorized approach to this by applying the following function:</p> <p>Rough code outline:</p> <pre><code>def align_coordinates(align_coord, box): &quot;&quot;&quot; align_coordinates align_coord A list of 4 values to add to the box coordinates box The box coordinates that need to be aligned &quot;&quot;&quot; for idx, v in enumerate(align_coord): box[idx] = box[idx] + v return box offset_coords = [10,10,10,10] df['bb_box'] = np.vectorize(align_coordinates)(offset_coords, df['bb_box']) </code></pre> <p>When I run this I get the following error:</p> <pre><code>ValueError: operands could not be broadcast together with shapes (4,) (5,) </code></pre> <p>I think its because I have a list of 4x values that I am trying to apply to a column of 5 rows with a list of 4 values in each row.</p> <p>Is there a better approach to do this? How do I apply a constant list of offset values to the dataframe column?</p> <p>Edit 1: This is my current approach, not using any &quot;vectorization&quot;:</p> <pre><code>offset_coords = [10,10,10,10] for i, v in df.iterrows(): r_box = df.at[i,'bb_box'] r_box = np.add(r_box, offset_coords) df.at[i,'bb_box'] = r_box </code></pre>
<python><pandas><dataframe><numpy>
2023-02-24 15:58:34
1
504
Zexelon
75,558,575
11,422,610
How do I switch users with their groups groups in Python?
<p>How do I switch to an admin-user account from this python script named <code>root_and_user.py </code> that was run with <code>doas</code> or <code>sudo</code>?</p> <pre><code>#!/usr/bin/env python3 from os import geteuid, seteuid from subprocess import run from sys import argv, exit def touch(fname): with open(fname, 'a') as f: pass #run this doas ./root_and_user.py if geteuid() == 0: touch(&quot;1.owned-by-root&quot;) touch(&quot;2.owned-by-root&quot;) seteuid(1000) touch(&quot;1.owned-by-admin-user&quot;) touch(&quot;2.owned-by-admin-user&quot;) </code></pre> <p>I've written my own custom function, also called <code>touch()</code> that creates an empty file. <code>1000</code> is the id of <code>admin_user</code>. When I run the script with <code>sudo</code> or <code>doas</code> the files <code>1.owned-by-admin-user</code> and <code>2.owned-by-admin-user</code> are created but they still belong to the group <code>root</code> - although being owned by <code>admin_user</code>. My aim is to accomplish that <code>1.owned-by-admin-user</code> and <code>2.owned-by-admin-user</code> are not only owned by <code>admin_user</code> but also have a group <code>admin_user</code>. How might I accomplish that?</p>
<python><argv><sys>
2023-02-24 15:45:53
0
937
John Smith
75,558,567
15,613,309
What are the names associated with Python Tkinter get_focus()?
<p>I have a Tkinter script that has multiple Entry widgets. I have a method that gets the Entry widget that has &quot;focus&quot;: i.e. <code>focused = self.root.focus_get()</code> This will return something like this: <code>.!labelframe2.!entry</code></p> <p>What I really need to know is</p> <ol> <li>The name of the <code>tk.StringVar()</code> used for the <code>textvariable</code> in the Entry widget</li> <li>The name of the <code>tk.Entry</code> widget</li> </ol> <p>If you try this code, simply mouse click in any of the Entry widgets and the click the &quot;Who Has Focus&quot; button.</p> <pre><code># focus_get.py import tkinter as tk class Focus_Get: def __init__(self): #Create the root window self.root = tk.Tk() self.root.geometry('300x800') self.root.title('Focus_Get') #Create a frame self.f1 = tk.LabelFrame(self.root,text='This Is The First Frame') self.f1.pack(pady=10) self.f1e1 = tk.StringVar() self.f1e2 = tk.StringVar() self.f1e1_label = tk.Label(self.f1,text='Frame 1 Entry 1',).pack(padx=5,pady=5) self.f1e1_entry = tk.Entry(self.f1,textvariable=self.f1e1,width='7') self.f1e1_entry.pack(pady=5) self.f1e2_label = tk.Label(self.f1,text='Frame 1 Entry 2').pack(padx=5,pady=5) self.f1e2_entry = tk.Entry(self.f1,textvariable=self.f1e2,width='7') self.f1e2_entry.pack(pady=5) self.f2 = tk.LabelFrame(self.root,text='This Is The Second Frame') self.f2.pack(pady=10) self.f2e1 = tk.StringVar() self.f2e2 = tk.StringVar() self.f2e1_label = tk.Label(self.f2,text='Frame 2 Entry 1').pack(padx=5,pady=5) self.f2e1_entry = tk.Entry(self.f2,textvariable=self.f2e1,width='7') self.f2e1_entry.pack(pady=5) self.f2e2_label = tk.Label(self.f2,text='Frame 2 Entry 2').pack(padx=5,pady=5) self.f2e2_entry = tk.Entry(self.f2,textvariable=self.f2e2,width='7') self.f2e2_entry.pack(pady=5) self.f3 = tk.LabelFrame(self.root,text='This Is The Button Frame') self.f3.pack(pady=10) self.btn1 = tk.Button(self.f3,text='Who Has Focus',command=self.show_focus).pack(pady=5) self.btn2 = tk.Button(self.f3,text='Clear',command=self.clear_focus).pack(pady=5) self.btn3 = tk.Button(self.f3,text='Exit',command=self.close_it,).pack(pady=5) self.who_text = tk.Listbox(self.root,width=18,height=8,font=('Arial',16)) self.who_text.pack(pady=5) self.root.protocol('WM_DELETE_WINDOW', self.close_it) self.root.mainloop() def show_focus(self): focused = self.root.focus_get() self.who_text.insert(tk.END,focused) # What I really need to know is # 1) The name of the tk.StringVar() used for the textvariable in the Entry widget (i.e. self.f1e1....self.f2e2) # 2) The name of the tl.Entry widget (i.e. self.f1e1_entry.....self.f2e2_entry) def clear_focus(self): self.root.focus() self.who_text.delete(0,tk.END) def close_it(self): self.root.destroy() if __name__ == '__main__': Focus_Get() </code></pre>
<python><tkinter>
2023-02-24 15:45:11
1
501
Pragmatic_Lee
75,558,553
11,546,773
Fastest operation to combine 2 dataframes with 1D array in each cell to 1 dataframe with 2D array in each cell
<p>I need to create a dataframe with in each cell a 2D array. This 2D array is a combination of one array from dataframe A and one array from dataframe B.</p> <p>I tried applying a function on dataframe A in which I tried to combine those array combination with numpy. However I'm not sure that this is the fastest/most elegant way. Since I need to combine 2 dataframes of about 200GB this way, I really need the fastest/most elegant solution.</p> <p>Any suggestions of how to speed this up or to make this a more elegant solution?</p> <p><strong>Dataframe A:</strong></p> <pre><code> col1 col2 0 [1, 2, 3, 4] [9, 10, 11, 12] 1 [5, 6, 7, 8] [13, 14, 15, 16] </code></pre> <p><strong>Dataframe B:</strong></p> <pre><code> col1 col2 0 [17, 18, 19, 20] [25, 26, 27, 28] 1 [21, 22, 23, 24] [29, 30, 31, 32] </code></pre> <p><strong>Desired result:</strong></p> <pre><code> col1 col2 0 [[1, 2, 3, 4], [17, 18, 19, 20]] [[9, 10, 11, 12], [25, 26, 27, 28]] 1 [[5, 6, 7, 8], [21, 22, 23, 24]] [[13, 14, 15, 16], [29, 30, 31, 32]] </code></pre> <p><strong>Code I used</strong>:</p> <pre><code>import numpy as np import pandas as pd def function(x): a[x.name] = pd.Series(np.stack([x, b[x.name]], axis=1).tolist(), name=x.name) data_a = {'col1': [[1, 2, 3, 4], [5, 6, 7, 8]], 'col2': [[9, 10, 11, 12], [13, 14, 15, 16]]} a = pd.DataFrame(data=data_a) data_b = {'col1': [[17, 18, 19, 20], [21, 22, 23, 24]], 'col2': [[25, 26, 27, 28], [29, 30, 31, 32]]} b = pd.DataFrame(data=data_b) print(a) print() print(b) a.apply(function) print(a) </code></pre>
<python><pandas><dataframe><numpy>
2023-02-24 15:44:31
1
388
Sam
75,558,482
5,489,190
How to use Pythonnet in C# app deployment? It still requires python to be locally installed on any user machine
<p><strong>Background</strong></p> <p>I was looking for something like IronPython for my C# app, but supporting numpy packages. I decided to give a try to Pythonnet. Everything works fine as long as I'm on my machine with Python installed. But when I deploy my app, and try to start it on another machine, it crashes. My idea is that, Pythonnet is not deployed inside generated exe. This mean that it is usless for me.</p> <p><strong>Here an MWE:</strong></p> <pre><code>var input1 = new double[,] { { 15 }, { 274.5 } }; Runtime.PythonDLL = @&quot;C:\pythonx86.3.11.2\tools\python311.dll&quot;; PythonEngine.Initialize(); dynamic os = Py.Import(&quot;os&quot;); dynamic sys = Py.Import(&quot;sys&quot;); sys.path.append(os.getcwd()); dynamic test = Py.Import(&quot;Test&quot;); int r1 = test.Test_fun(input1); PythonEngine.Shutdown(); </code></pre> <p><strong>And Test.py</strong></p> <pre><code>import numpy as np import numpy.matlib def Test_fun(x1): Q = np.size(x1,1) # samples return Q </code></pre> <p><strong>Question:</strong></p> <p>Is there any way to makes the deployed .exe work on machine without python installed?</p>
<python><c#><python-3.x><python.net>
2023-02-24 15:38:01
1
749
Karls
75,558,210
2,167,717
How to find the smallest maximum of a column with pandas after filtering?
<p>I have a dataframe:</p> <pre><code>import pandas as pd df = pd.DataFrame( {'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], 'variable': [8, 9, 10, 11, 2, 3, 4, 5], 'another_variable': [1, 1, 1, 2, 1, 1, 2, 2]} ) </code></pre> <p>I would like to find the largest value of <code>variable</code> (which is counting upwards) where <code>another_variable</code> is still equal to 1.</p> <p>I can group the data frame and filter the relevant rows:</p> <pre><code>df.groupby(['team']).apply(lambda g: g[g['another_variable'] == 1]) # Output: # team variable another_variable #team #A 0 A 8 1 # 1 A 9 1 # 2 A 10 1 #B 4 B 2 1 # 5 B 3 1 </code></pre> <p>But if I add <code>.variable.min()</code>, I only get a single value, instead of one value for each group (which I then could calculate the maximum of). What am I doing wrong?</p>
<python><pandas><group-by><max><min>
2023-02-24 15:12:06
2
365
Maxim Moloshenko
75,558,054
6,409,572
Is there a "bookmark/headline" Syntax for a document outline in Python/pyCharm, like #### works in R/RStudio?
<p>Coding R in RStudio allows you to bracket comments in <code>####</code> to generate a &quot;table of contents&quot; that one can use to jump back and forth to different code sections. I love the lean and quick way tis allows for structuring my code (like Markdown does for text documents). An example is shown below.</p> <p>Is there a similar feature for python using pyCharm?</p> <p>How it works in R is really comfortable:</p> <pre><code>#-------------------------# #### MY CODE CHAPTER #### #-------------------------# do = this if(this == lengthy) { print(&quot;structuring code with the ####-elements can be really handy to have &quot;Bookmarks&quot; to jump to&quot;) } else return #-------------------------# #### NEXT CODE CHAPTER #### #-------------------------# do = something_else </code></pre> <p>Which generates &quot;bookmarks&quot; or simply entries as shown in the following picture: <img src="https://i.sstatic.net/GAN58.png" alt="RStudio #### entries become outline-entries1" /></p> <p>I was hoping the &quot;Structure&quot; tab in pyCharm would be useful in a similar fashion, but I'd like to create my own structure independent of functions, fields and classes (with fields somehow always being alphabetically ordered, even though the feature is turned off). <a href="https://i.sstatic.net/53lKF.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/53lKF.png" alt="Structure tab in PyCharm, alphabetical ordering turned off" /></a></p>
<python><pycharm>
2023-02-24 14:58:21
1
3,178
Honeybear
75,557,939
11,001,493
How to find number of days in a year column?
<p>I have a dataframe like this:</p> <pre><code>df = pd.DataFrame({&quot;Index&quot;:[0, 1, 2, 3, 4, 5], &quot;Year&quot;:[2019, 2020, 2021, 2022, 2023, 2024]}) df Out[12]: Index Year 0 0 2019 1 1 2020 2 2 2021 3 3 2022 4 4 2023 5 5 2024 </code></pre> <p>I would like to create a new column with the total number of days on that year. Could you help me?</p> <p>I tried <code>df[&quot;Days&quot;] = pd.to_datetime(df[&quot;Year&quot;]).dt.days</code> but I got the following error:</p> <p>AttributeError: 'DatetimeProperties' object has no attribute 'days'</p> <p>The output should be:</p> <pre><code> Index Year Days 0 0 2019 365 1 1 2020 366 2 2 2021 365 3 3 2022 365 4 4 2023 365 5 5 2024 366 </code></pre>
<python><pandas><date>
2023-02-24 14:48:18
4
702
user026
75,557,918
8,108,089
How to pass use sync_to_async with a chain of methods
<p>I have a case like the following:</p> <pre class="lang-py prettyprint-override"><code>async def handler(self): await sync_to_async(Stock.objects.filter)(id__in=product_stock).update(is_filled=False) </code></pre> <p>Where I am trying to pass the product_stock to the filter method then call the update on the filtered queryset. I understand that I can wrap the logic in another method and just pass it the arg as in the following:</p> <pre class="lang-py prettyprint-override"><code>@classmethod def update_stocks( cls, product_stock: List[uuid.UUID] ) -&gt; None: &quot;&quot;&quot;Update stocks for order products.&quot;&quot;&quot; cls.objects.filter(id__in=product_stock).update(is_filled=False) async def handler(self): await sync_to_async(Stock.update_stocks)(product_stock=product_stock) </code></pre> <p>But is is possible to do it all as in my attempt above which doesn't work of course since the result is a courotine and not a django queryset? I want to avoid having to use another method just for this if it is possible.</p>
<python><django><python-asyncio>
2023-02-24 14:46:01
1
878
coredumped0x
75,557,880
19,130,803
proper way to handle max line length python
<p><strong>Que-1</strong> Break flake8 and black cycle</p> <pre><code>class TaskInfo(StrEnum): ABCDEFG_HELLOO_TASK_WELCOMEE_VALUE: str = &quot;abcdefg_helloo_task_welcomee_value&quot; </code></pre> <p>A message from Flake8 gives line too long (82 &gt; 79 characters)</p> <p>so I edit as below</p> <pre><code>class TaskInfo(StrEnum): ABCDEFG_HELLOO_TASK_WELCOMEE_VALUE: str = (&quot;abcdefg_helloo_task&quot; + &quot;_welcomee_value&quot;) </code></pre> <p>Now I get message as Black would make changes. On running black, it reformat the string to original state.</p> <p><strong>Que-2</strong> Designing web pages</p> <p>As above issue is with script code, I am also designing the web dashboard using dash plotly, Here there are Rows and Columns inside each other(bootstrap way) which holds the different components like button etc this makes line goes upto 150 characters.</p> <p>what is right way to handle both Que-1 and Que-2?</p>
<python>
2023-02-24 14:41:28
3
962
winter
75,557,864
2,774,885
how do I map/assign a list of format strings to a list of values when printing?
<p>Scenario: I've got a large list of mixed-type values: strings, floats, ints, etc. I want to print these in various different output formats. It would be much easier if I could keep a separate list of formats and then map the list of formats to the list of values.<br /> As a simple, specific example imagine that I have three values</p> <pre><code>vals = [45.6789, 155.01, &quot;purple&quot;] </code></pre> <p>and I want to print the first number as a float of width 2 rounded to two decimal places, the second number as width of four rounded to a whole number, and the third string as left-justified with a width of 10 chars. The corresponding f-strings formats would be:</p> <pre><code>list_of_formats = [':2.2f', ':4.0f', ':10'] </code></pre> <p>The equivalent behavior I want would be if I did:</p> <pre><code>print(f'{vals[0]:2.2f}') print(f'{vals[1]:4.0f}') print(f'{vals[2]:10}') </code></pre> <p>Now... how do I go about assigning / mapping / zipping / lambda-ing these things together in some kind of loop or comprehension? I'm 99% sure this capability exists (because python does EVERYTHING like this, right?) but I'm struggling with the syntax and figuring out whether these formatting codes are treated as strings, or some special type, or something else, and where to put the 'f' and the quotes and the brackets and all that. I looked for an example of this and couldn't find one, but totally possible that's because I don't know the right nouns to use...</p>
<python><string-formatting>
2023-02-24 14:40:37
3
1,028
ljwobker
75,557,840
3,783,002
SCONS PDB unable to find my file, even after I explicitly append it to the system path
<p>I'm trying to debug a scons file as follows: <code>scons --debug=pdb</code>. When I try to set a breakpoint in <code>SConstruct</code> using <code>b SConstruct:24</code> I get an error:</p> <blockquote> <p>*** 'SConstruct' not found from sys.path</p> </blockquote> <p>My SConstruct file is in the current directory. I tried to append the current directory to <code>sys.path</code>. using <code>sys.path.append(os.getcwd())</code> and then rerunning the <code>b SConstruct:24</code> command but I still get the same error. Any idea why this might occur?</p>
<python><debugging><scons><pdb>
2023-02-24 14:38:26
1
6,067
user32882
75,557,453
5,235,665
Pandas dataframe duplicate checking and error handling
<p>Brand new to <a href="https://pandas.pydata.org/" rel="nofollow noreferrer">Pandas</a>, and fairly new to Python. I have the following snippet of Pandas code:</p> <pre><code># Check for Duplicates in Mapping Fields , throw error if True map_df[right] = map_df[right].astype(&quot;str&quot;) input_df[left] = input_df[left].astype(&quot;str&quot;) map_df['Concat'] = map_df[right].apply(lambda x: ''.join(x), axis=1) input_df['Concat'] = input_df[left].apply(lambda x: ''.join(x), axis=1) error = map_df[map_df.duplicated(subset=['Concat'])] if error.shape[0] == 0: logger.info(&quot;pass&quot;) else: error_list = error['Concat'].unique() string_io_logger.error(&quot;Duplicates values in {} , Mapping Columns shouldn't have duplicate values : \n {}&quot;.format( 'Mapping Columns', map_df[map_df['Concat'].isin(error_list)].to_string())) </code></pre> <p>I'm not understanding the comment &quot;<em>throw error if True</em>&quot; and not seeing where any error gets <strong>thrown</strong>.</p> <p>If I'm understanding the snippet correctly:</p> <ul> <li>it's adding a <code>Concat</code> column to both the <code>map_df</code> and <code>input_df</code> dataframes</li> <li>then its checking for duplicates, but I'm not following what <code>error = map_df[map_df.duplicated(subset=['Concat'])]</code> accomplishes</li> <li>then it checks to see if <code>error</code> is populated with any dupes <ul> <li>if not, then we're all good</li> <li>if it has dupes, I just see it logging the error but not actually throwing anything that would disrupt flow</li> </ul> </li> </ul> <p>Looking more at the <code>striing_io_logger</code> I see it defined as:</p> <pre><code>def get_string_io_logger(log_stringio_obj, logger_name): # create string_io_logger string_io_logger = logging.getLogger(logger_name) formatter = logging.Formatter( &quot;%(asctime)s %(levelname)s \t[%(filename)s:%(lineno)s - %(funcName)s()] %(message)s&quot;) string_io_logger.setLevel(logger_level) # add normal steam handler to display logs on screen io_log_handler = logging.StreamHandler() io_log_handler.setFormatter(formatter) string_io_logger.addHandler(io_log_handler) # create stream handler and initialise it with string io buffer string_io_log_handler = logging.StreamHandler(log_stringio_obj) string_io_log_handler.setFormatter(formatter) # add stream handler to string_io_logger string_io_logger.addHandler(string_io_log_handler) return string_io_logger log_stringio_obj = io.StringIO() # log_handler = logging.StreamHandler(log_stringio_obj) # Create logger object and define s3 log path string_io_logger = get_string_io_logger(log_stringio_obj, logger_name='my_s3_logger') </code></pre> <p>So I ask: how is this duplicate checking working, and if an error isn't actually thrown from this code snippet, is there a way to add a handler so that when <code>string_io_logger</code> gets an error logged, it actually disrupts codeflow execution and <em>throws</em> the error/message?</p>
<python><pandas>
2023-02-24 13:58:27
1
845
hotmeatballsoup
75,557,245
8,913,402
Create a decision tree with a custom node logic
<p>I want to estimate a human level performance of a certain classification task.</p> <p>Let's say I have the following fixed logic:</p> <pre><code>def classify(feature_1, feature_2): if feature_1 &lt;= threshold_1: return 0 if feature_2 &lt;= threshold_2: return 1 return 2 </code></pre> <p>How can I import or rewrite this logic to form a fully eligible <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier" rel="nofollow noreferrer">DecisionTreeClassifier</a> with attributes (<code>classes_</code>, <code>n_classes_</code>, <code>tree_</code>, ect.), methods (<code>fit</code>, <code>decision_path</code>, <code>set_params</code>, ect.) and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.export_text.html#sklearn.tree.export_text" rel="nofollow noreferrer"><code>sklearn.tree.export_text</code></a> possibility?</p> <pre><code>|--- feature_1 &lt;= threshold_1 | |--- class: 0 |--- feature_1 &gt; threshold_1 | |--- feature_2 &lt;= threshold_2 | | |--- class: 1 | |--- feature_2 &gt; threshold_2 | | |--- class: 2 </code></pre> <p>This <a href="https://stackoverflow.com/questions/59935395/is-it-possible-to-use-a-custom-defined-decision-tree-classifier-in-scikit-learn">answer</a> suggest to build a custom (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.base.BaseEstimator.html#sklearn-base-baseestimator" rel="nofollow noreferrer">BaseEstimator</a>, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.base.ClassifierMixin.html#sklearn-base-classifiermixin" rel="nofollow noreferrer">ClassifierMixin</a>) but not the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier" rel="nofollow noreferrer">DecisionTreeClassifier</a>.</p>
<python><machine-learning><scikit-learn>
2023-02-24 13:38:40
1
1,383
Grzegorz
75,557,241
6,225,526
How to execute a python wheel developed using Poetry?
<p>I have a poetry application and in poetry, one can set any python version in pyproject.toml. Once a wheel is built using poetry, I would like to share this to our users.Then, my users can execute this wheel similar to how they execute an exe in windows.</p> <p>I checked pyinstaller but it generates a bulky exe.</p> <p>I could see <code>pipx</code> has a command to run any wheel by creating a tmp environment using below command,</p> <pre><code>pipx run --spec C:\dev\poetry-demo\dist\poetry_demo-0.1.0-py3-none-any.whl start </code></pre> <p>However, this throws an error when the python version used in Poetry (pyproject.toml) is different from the python version the pipx was installed.</p> <p>Is there any alternative solution?</p>
<python><python-poetry><pipx>
2023-02-24 13:38:22
0
1,161
Selva