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,278,725
1,034,153
can I use LoadTestShape to specify a custom parameter in my Locust.io tasks? (Python)
<p>I am finding Locust.io awesome for tweaking certain parameters that will trigger specific implementation behavior in my web application. I want to measure how performance changes based on different config parameters in my web application. Adopting <code>LoadTestShapes</code> and <code>ticks</code> to simulate K6-style stages seemed the obvious solution. I could tinker with my custom parameter at each stage and get my test to show system response side by side. Alas, the tick definition only seems to allow changing specific Locust parameters (#users, #spawns and which user classes).</p> <p>At that point, I figured I could use <code>get_run_time()</code>, and code the expected behavior within my <code>HttpUser</code> subclass. Alas, I couldn't find a way to access that method directly from within my task. So, still no joy.</p> <p>Any ideas?</p>
<python><load-testing><locust>
2023-01-29 22:05:58
1
1,081
Luca P.
75,278,688
836,026
I have nii.gz volume and I need to display it as one image
<p>I have nii.gz volume and I need to display it as one image. I could display one slice as shown below.</p> <pre><code>mri_file = '/tmp/out_img/case0001_gt.nii.gz' img = nib.load(mri_file) mg_data = img.get_fdata() mid_slice_x = img_data[ :, :,119] plt.imshow(mid_slice_x.T, cmap='gray', origin='lower') plt.xlabel('First axis') plt.ylabel('Second axis') plt.colorbar(label='Signal intensity') plt.show() </code></pre> <p><a href="https://i.sstatic.net/HPT3R.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HPT3R.png" alt="enter image description here" /></a></p> <p>But I need to display the whole volume as one image with different color maps as show below.</p> <p><a href="https://i.sstatic.net/8hAbK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/8hAbK.png" alt="enter image description here" /></a></p>
<python><pytorch><medical-imaging>
2023-01-29 21:59:03
1
11,430
user836026
75,278,649
8,026,274
plotting a grouped bar chart with bins
<p>I have a dataframe similar to like this:</p> <pre><code>Create Date count1 count2 count3 count4 2018-01 12 21 12 123 2018-02 11 25 12 145 2018-08 12 26 12 145 2019-03 13 28 12 334 2019-06 15 22 12 345 2019-07 16 25 12 165 2020-01 12 25 12 178 2020-02 12 23 12 178 2020-03 12 26 12 187 2021-01 11 28 12 146 2021-02 12 29 12 123 2021-03 11 22 12 189 2022-01 17 21 12 167 2022-02 18 23 12 166 2022-03 19 23 12 123 </code></pre> <p>I want a grouped bar chart where x axis is a year. For example 2018, 2019, 2020, 2021, 2022. In each of those year I want the sum of a column in that year as 1 bar and so on.</p> <p>What I tried</p> <pre><code> df_combined.plot.bar(logy=True) plt.xticks(rotation=0) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left') plt.show() </code></pre> <p>What I am getting is a crowded bar chart like this<a href="https://i.sstatic.net/GWz5Q.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GWz5Q.png" alt="enter image description here" /></a></p>
<python><dataframe><plot>
2023-01-29 21:52:26
1
339
Mikasa
75,278,638
6,577,503
Finding basis of affine space in python?
<p>Suppose I am given an affine space as some conjunction of equalities say:</p> <pre><code>x + y + z = 2 &amp;&amp; x - 3z = 4 </code></pre> <p>which I represent in python as:</p> <pre><code>[ [1,1,1,2] , [1,0,-3,4] ] </code></pre> <p>I would like to find the basis of this affine set. Does python have any such library?</p> <p><strong>Little bit of mathematics</strong>:</p> <p>Let the affine space be given by the matrix equation Ax = b. Let the k vectors {x_1, x_2, .. x_k } be the basis of the nullspace of A i.e. the space represented by Ax = 0. Let y be any particular solution of Ax = b. Then the basis of the affine space represented by Ax = b is given by the (k+1) vectors {y, y + x_1, y + x_2, .. y + x_k }. If there is no particular solution for Ax = b, then return some error message, as the set represented is empty.</p> <p>For the above equation the matrix equation is:</p> <p>Ax = b where</p> <p>A = [[1, 1 , 1] , [1, 0 , -3]]</p> <p>x = [x , y , z]^T</p> <p>b = [2, 4]^T</p>
<python><numpy><scipy><computational-geometry>
2023-01-29 21:50:57
2
441
Anon
75,277,911
20,947,319
Django and AWS S3 returns This backend doesn't support absolute paths
<p>I am working on a Django project whereby when users register their profiles get automatically created using the signals.py. Everything works fine in the localhost, but now I want to migrate to the AWS S3 bucket before deploying my project to Heroku. After configuring my AWS settings in settings.py, I get the error <code>NotImplementedError: This backend doesn't support absolute paths.</code> after trying to create a superuser through the <code>python manage.py createsuperuser</code> command.</p> <p>Here is my models.py:</p> <pre><code>class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', null=True, blank=True) bio = models.TextField() resume= models.FileField('Upload Resumes', upload_to='uploads/resumes/', null=True, blank=True,default='resume.docx') </code></pre> <p>Here is the signals.py:</p> <pre><code>@receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() </code></pre> <p>And here is my settings.py;</p> <pre><code># S3 BUCKETS CONFIG AWS_ACCESS_KEY_ID='' AWS_SECRET_ACCESS_KEY='' AWS_STORAGE_BUCKET_NAME='' # Storages configuration AWS_S3_FILE_OVERWRITE= False # AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Only public read for now AWS_QUERYSTRING_AUTH = False AWS_DEFAULT_ACL='public-read' STATIC_URL = '/static/' </code></pre> <p>Inside the s3 bucket, I have the default.jpg and resume.docx in the root folder. Any assistance will be highly appreciated. Thanks.</p>
<python><django><amazon-web-services><amazon-s3><django-models>
2023-01-29 19:51:25
1
446
victor
75,277,797
11,825,717
How do I set padding on a convolutional decoder?
<p>I'm building a convolutional decoder that takes an input Tensor of size <code>1x96x4x4</code> and feeds it into three convolutional tranpose layers. How do I set <code>padding</code> and <code>output_padding</code> so that the output is of size <code>1x9x30x30</code>?</p> <pre><code>import torch # Input. x = torch.rand(1, 9, 30, 30) # input tensor of size 1x9x30x30 # Encoder. encoder = torch.nn.Sequential( torch.nn.Conv2d(9, 24, kernel_size=5, stride=2, padding=2), torch.nn.ReLU(), torch.nn.Conv2d(24, 48, kernel_size=5, stride=2, padding=2), torch.nn.ReLU(), torch.nn.Conv2d(48, 96, kernel_size=3, stride=2, padding=1), torch.nn.ReLU() ) z = encoder(x) # encoded tensor of size 1x96x4x4 # Decoder. decoder = torch.nn.Sequential( torch.nn.ConvTranspose2d(96, 48, kernel_size=3, stride=2), torch.nn.ReLU(), torch.nn.ConvTranspose2d(48, 24, kernel_size=5, stride=2), torch.nn.ReLU(), torch.nn.ConvTranspose2d(24, 9, kernel_size=5, stride=2), torch.nn.Sigmoid() ) x_hat = decoder(z) # how do I make this 1x9x30x30? </code></pre>
<python><pytorch><conv-neural-network><autoencoder>
2023-01-29 19:35:39
0
2,343
Jeff Bezos
75,277,647
2,091,247
Transform table into smaller table (animation)
<p>I wrote a short animation in Manim library, that first highlight two rows and then transform the table into a smaller one only with these two rows. I'm using the following lib versions:</p> <ul> <li><p>python 3.10.7</p> </li> <li><p>manim 0.17.2</p> <pre><code> from manim import * # creeate map dictionary map = {&quot;SELECT&quot; : GOLD, &quot;FROM&quot; : GOLD, &quot;WHERE&quot; : GOLD} class tablesSelect(Scene): def construct(self): origin_data = [[&quot;Pavel&quot;, &quot;23&quot;, &quot;pavel@seznam.cz&quot;], [&quot;Radim&quot;, &quot;21&quot;, &quot;radim@gmail.com&quot;], [&quot;Jane&quot;, &quot;22&quot;, &quot;jane@yahoo.com&quot;], [&quot;Mike&quot;, &quot;20&quot;, &quot;mike@post.com&quot;]] column_labels1 = [Text(&quot;Name&quot;), Text(&quot;Age&quot;), Text(&quot;Email&quot;)] # create a table with 3 columns and 4 rows that is 20 units wide and 10 units tall table1 = Table( table = origin_data, col_labels=column_labels1) table1.set_width(5) # set the width of the table table1.move_to(ORIGIN) # set the position of the table to the center of the screen for i in range(0,3): table1.add_highlighted_cell((1, i), color=BLUE) # highlight the first row table2 = table1.copy() for i in range(0,3): table2.add_highlighted_cell((2, i), color=RED) # highlight the first row for i in range(0,3): table2.add_highlighted_cell((4, i), color=RED) # highlight the first row filtered_data = [row for row in origin_data if int(row[1]) &gt; 21] column_labels2 = [Text(&quot;Name&quot;), Text(&quot;Age&quot;), Text(&quot;Email&quot;)] table3 = Table( table = filtered_data, col_labels=column_labels2) table3.set_width(5) # set the width of the table table3.move_to(ORIGIN) # set the position of the table to the center of the screen for i in range(0,3): table3.add_highlighted_cell((1, i), color=BLUE) # highlight the first row for i in range(0,3): table3.add_highlighted_cell((2, i), color=RED) # highlight the second row for i in range(0,3): table3.add_highlighted_cell((3, i), color=RED) # highlight the third row self.play(Create(table1)) # show the table on the screen self.wait(2) # wait for 2 seconds self.play(TransformMatchingShapes(table1, table2)) self.wait(2) # wait for 2 seconds self.play(TransformMatchingShapes(table2, table3)) self.wait(2) # wait for 2 seconds` with tempconfig({&quot;quality&quot;: &quot;medium_quality&quot;, &quot;preview&quot;: True}): scene = tablesSelect() scene.render() </code></pre> </li> </ul> <p>I have two questions regarding the code:</p> <ol> <li>I was unable to do the transitions just updating one <code>Table</code> object, therefore, I create three tables for each transition. Is this a correct approach?</li> <li>The third table is created from scratch. Is there a way to remove two rows from table data if I create a copy of the second table?</li> </ol> <p>Any other comments to the code are welcomed.</p>
<python><manim>
2023-01-29 19:12:30
0
10,731
Radim Bača
75,277,556
1,922,589
Can't load env variable path properly in crontab environment
<p>If I ran manually on my terminal, working fine.</p> <pre><code>/usr/bin/python3 /home/myproject/handler.py </code></pre> <p>My command in crontab -e is</p> <pre><code>* * * * * . /home/&lt;user&gt;/.bashrc; /usr/bin/python3 /home/myproject/handler.py &gt; /home/&lt;user&gt;/testfile.txt 2&gt;&amp;1 </code></pre> <p>I got this error message in text file</p> <pre><code>Traceback (most recent call last): File &quot;/home/myproject/handler.py&quot;, line 9, in &lt;module&gt; env = json.load(open(os.environ.get('my_env_path'), encoding='utf-8')) TypeError: expected str, bytes or os.PathLike object, not NoneType </code></pre> <p>.bashrc</p> <pre><code>export my_env_path=&quot;/home/myproject/env.json&quot; </code></pre> <p>It showing cant load successfully from bashrc file</p>
<python><ubuntu><cron>
2023-01-29 18:57:14
0
24,027
Nurdin
75,277,260
18,758,062
Gunicorn logging gets AttributeError: 'NoneType' object has no attribute 'write'
<p>I'm trying to get gunicorn 20.1.0 with flask 2.2.2 to write log messages to file. When writing a log message, gunicorn is throwing the error:</p> <pre><code>Traceback (most recent call last): File &quot;/usr/lib/python3.10/logging/__init__.py&quot;, line 1103, in emit stream.write(msg + self.terminator) File &quot;/root/test/venv/lib/python3.10/site-packages/gunicorn/http/wsgi.py&quot;, line 62, in write stream.write(data) AttributeError: 'NoneType' object has no attribute 'write' </code></pre> <p>Is there an issue with my <code>configDict</code>? Hope to get some help to fix this. Thanks!</p> <p>Here's how I have configured logging:</p> <p><strong>wsgi.py</strong></p> <pre><code>from server import app if __name__ == &quot;__main__&quot;: app.run() </code></pre> <p><strong>server.py</strong></p> <pre><code>import logging from flask import Flask, jsonify, request from flask.logging import default_handler configDict = { &quot;version&quot;: 1, &quot;formatters&quot;: { &quot;default&quot;: { &quot;format&quot;: &quot;[%(asctime)s] %(levelname)s in %(module)s: %(message)s&quot;, } }, &quot;handlers&quot;: { &quot;wsgi&quot;: { &quot;class&quot;: &quot;logging.StreamHandler&quot;, &quot;stream&quot;: &quot;ext://flask.logging.wsgi_errors_stream&quot;, &quot;formatter&quot;: &quot;default&quot;, } }, &quot;root&quot;: {&quot;level&quot;: &quot;INFO&quot;, &quot;handlers&quot;: [&quot;wsgi&quot;]}, } app = Flask(__name__) logging.config.dictConfig(configDict) app.logger.removeHandler(default_handler) log = logging.getLogger(__name__) @app.route(&quot;/&quot;, methods=[&quot;GET&quot;]) def home(): log.info('hello') return jsonify({&quot;hello&quot;: &quot;world&quot;}) </code></pre> <p>Gunicorn is started on Ubuntu bash terminal using</p> <pre><code>gunicorn wsgi:app --log-file api.log </code></pre> <hr /> <p>The errors do not get raised if <code>configDict</code> is not loaded.</p> <pre><code>app = Flask(__name__) # logging.config.dictConfig(configDict) # app.logger.removeHandler(default_handler) log = logging.getLogger(__name__) </code></pre> <p>and still start <code>gunicorn</code> the same way</p> <pre><code>gunicorn wsgi:app --log-file api.log </code></pre> <p>But the log messages from calling <code>log.info</code> do not get written to <code>api.log</code>. I am trying to have the log messages appear in both stdout and in the log file <code>api.log</code>.</p>
<python><flask><logging><gunicorn><python-logging>
2023-01-29 18:12:54
0
1,623
gameveloster
75,277,258
7,713,770
api call method and viewset
<p>I try to create a api call:</p> <pre><code>class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() @action(methods=['get'], detail=False) def mainGroups(self,request): mainGroups = Category.objects.filter(category_id__isnull=True) serializer = self.get_serializer_class()(mainGroups) return Response(serializer.data) </code></pre> <p>serializer:</p> <pre><code>class CategorySerializer(serializers.ModelSerializer): animals = AnimalSerializer(many=True) class Meta: model = Category fields = ['id','category_id','name', 'description', 'animals'] </code></pre> <p>So the main url works: <a href="http://127.0.0.1:8000/djangoadmin/groups/" rel="nofollow noreferrer">http://127.0.0.1:8000/djangoadmin/groups/</a></p> <p>But if I go to: <a href="http://127.0.0.1:8000/djangoadmin/groups/maingGroups/" rel="nofollow noreferrer">http://127.0.0.1:8000/djangoadmin/groups/maingGroups/</a></p> <p>I get this error:</p> <pre><code> AttributeError at /djangoadmin/groups/mainGroups/ Got AttributeError when attempting to get a value for field `name` on serializer `CategorySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'name'. </code></pre> <p>urls.py:</p> <pre><code>router = routers.DefaultRouter() router.register('groups', CategoryViewSet) urlpatterns = [ path('', include(router.urls)) ] </code></pre> <p>and urls.py of admin looks:</p> <pre><code>from django.contrib import admin from django.urls import path, include urlpatterns = [ path(&quot;djangoadmin/&quot;, include('djangoadmin.urls')), path(&quot;admin/&quot;, admin.site.urls), ] </code></pre> <p>Category model:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) description = models.TextField(max_length=1000) images = models.ImageField(upload_to=&quot;photos/categories&quot;) category = models.ForeignKey( &quot;Category&quot;, on_delete=models.CASCADE, related_name='part_of', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) class Meta: verbose_name = &quot;category&quot; verbose_name_plural = &quot;categories&quot; def __str__(self): return self.name </code></pre> <p>Question: how to create api method in main url?</p>
<python><django><django-rest-framework>
2023-01-29 18:12:40
1
3,991
mightycode Newton
75,277,154
14,391,210
Is this bad programming? Dictionary key instead of if statement for calling class methods
<p>I'm making a game in python with a UI in the terminal where the user has to navigate by pressing keys.</p> <p>I have my Game() class being the following.</p> <pre><code>class Game(): def __init__(self, config='default', **kwargs): print('\n'*20) # self.game_settings = self.set_game_settings(config, kwargs) self.main_menu() def main_menu(self): '''Menu the player sees when playing the game''' print('Welcome to pyFastType!\n') print('Please dont use your mouse but only keyboard keys when prompt too to keep the window active or it wont detect your key presses afterwards.\nHave fun!\n\n') choice = self.propose_menu(question = 'Press the letter on the left to navigate through the menu:', choices = ['Play game', 'Leaderboard', 'Settings']) {0: self.confirm_game_settings_before_game(), 1: self.leaderboard(), 2: self.settings()}[choice] def propose_menu(self, question: list, choices: list) -&gt; int: '''Print a new menu with question/answers with key pressed parameters ---------- question str: question to ask to the player choices list: list of choices fo the user to answer returns ---------- Index of the list corresponding to the choice of the user ''' print(question.capitalize()) choices_first_letter = [] for choice in choices: print(f'\t{choice[0].upper()} - {choice}') choices_first_letter.append(choice[0].lower()) key = dk.next_key_pressed()[0].lower() return choices_first_letter.index(key) </code></pre> <p>In the main_menu method, I'm calling other method from a dictionary instead of if statement. Should I wrote all if/elifs instead? I'm new and see both working but I don't know which is best practice or better for readability.</p>
<python><class><dictionary><if-statement>
2023-01-29 18:00:34
2
621
Marc
75,277,011
19,600,130
how to call a function as a context in django
<pre><code>class User(AbstractUser): GENDER_STATUS = ( ('M', 'Male'), ('F', 'Female') ) address = models.TextField(null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) description = models.TextField(null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_STATUS, null=True, blank=True) phone = models.CharField(max_length=15, null=True, blank=True) def get_full_name(self): return f'{self.first_name} {self.last_name}' </code></pre> <p>I declare a function <code>get_full_name</code> and then I want to call it in my view and show it in my template.</p> <p>views.py:</p> <pre><code>from django.shortcuts import render from accounts.models import User def about_us(request): fullname = User.get_full_name context = { 'fullname': fullname } return render(request, 'about_us.html', context=context) </code></pre> <p>and this is my template as you can see i used a loop for my context</p> <pre><code>&lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;d-flex flex-wrap justify-content-around&quot;&gt; {% for foo in fullname %} &lt;p&gt;{{ foo }}&lt;/p&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But I can't get the <code>get_full_name</code> parameters in my template as value to show.</p>
<python><django><django-models><django-views><django-templates>
2023-01-29 17:40:33
2
983
HesamHashemi
75,276,979
6,077,239
Polars message: eval_binary_same_type!(left_aexpr, +, right_aexpr) = None
<p>I have encountered a message as in the title when running some simple polars code. Example code and its outputs are provided below:</p> <pre><code>import datetime import polars as pl df = pl.DataFrame( { &quot;a&quot;: [datetime.date(2022, 12, 1), datetime.date(2022, 1, 1)], &quot;b&quot;: [datetime.date(2021, 12, 1), datetime.date(2000, 1, 1)], } ) &gt;&gt;&gt; df.with_columns([(pl.col(&quot;a&quot;).dt.year() + pl.col(&quot;b&quot;).dt.month()).alias(&quot;diff&quot;)]) [/home/runner/work/polars/polars/polars/polars-lazy/polars-plan/src/logical_plan/optimizer/simplify_expr.rs:456] eval_binary_same_type!(left_aexpr, +, right_aexpr) = None [/home/runner/work/polars/polars/polars/polars-lazy/polars-plan/src/logical_plan/optimizer/simplify_expr.rs:456] eval_binary_same_type!(left_aexpr, +, right_aexpr) = None shape: (2, 3) ┌────────────┬────────────┬──────┐ │ a ┆ b ┆ diff │ │ --- ┆ --- ┆ --- │ │ date ┆ date ┆ i64 │ ╞════════════╪════════════╪══════╡ │ 2022-12-01 ┆ 2021-12-01 ┆ 2034 │ │ 2022-01-01 ┆ 2000-01-01 ┆ 2023 │ └────────────┴────────────┴──────┘ &gt;&gt;&gt; df.with_columns([(pl.col(&quot;a&quot;).dt.year().cast(pl.Int32) + pl.col(&quot;b&quot;).dt.month().cast(pl.Int32)).alias(&quot;diff&quot;)]) [/home/runner/work/polars/polars/polars/polars-lazy/polars-plan/src/logical_plan/optimizer/simplify_expr.rs:456] eval_binary_same_type!(left_aexpr, +, right_aexpr) = None shape: (2, 3) ┌────────────┬────────────┬──────┐ │ a ┆ b ┆ diff │ │ --- ┆ --- ┆ --- │ │ date ┆ date ┆ i32 │ ╞════════════╪════════════╪══════╡ │ 2022-12-01 ┆ 2021-12-01 ┆ 2034 │ │ 2022-01-01 ┆ 2000-01-01 ┆ 2023 │ └────────────┴────────────┴──────┘ &gt;&gt;&gt; df.with_columns([(pl.col(&quot;a&quot;).dt.year() - pl.col(&quot;b&quot;).dt.month()).alias(&quot;diff&quot;)]) shape: (2, 3) ┌────────────┬────────────┬──────┐ │ a ┆ b ┆ diff │ │ --- ┆ --- ┆ --- │ │ date ┆ date ┆ i64 │ ╞════════════╪════════════╪══════╡ │ 2022-12-01 ┆ 2021-12-01 ┆ 2010 │ │ 2022-01-01 ┆ 2000-01-01 ┆ 2021 │ └────────────┴────────────┴──────┘ </code></pre> <p>I am curious about what is the meaning of this message.</p> <ul> <li>The first expression gives me two such messages. And I suspect it should be somehow related to type differences.</li> <li>So, in the second expression, I cast them to the same type, but this time I still get one such message (less then 2 in the first time though).</li> <li>However, in the third expression, I get no message, and the only difference between the first one is minus instead of plus. So, it makes me more confusing.</li> </ul> <p>It would be great if someone could help me understand this message and what is the implications of it.</p> <p>Thanks for your help.</p>
<python><python-polars>
2023-01-29 17:37:31
1
1,153
lebesgue
75,276,860
6,499,765
Cannot assign "OrderItem.product" must be a "Product" instance
<p>I am trying to create a &quot;create order&quot; endpoint, i keep getting</p> <pre><code>Cannot assign &quot;&lt;django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.&lt;locals&gt;.ManyRelatedManager object at 0x7f50dad00f70&gt;&quot;: &quot;OrderItem.product&quot; must be a &quot;Product&quot; instance. </code></pre> <p>heres my models</p> <pre><code>def product_images(instance, filename): return f&quot;product/{instance.product_name}/{filename}&quot; class Product(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField( storage=MediaRootS3BotoStorage(), upload_to=&quot;product_images&quot;, null=True, blank=True, ) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f&quot;{self.name}&quot;) super(Product, self).save(*args, **kw) # Ecommerce Models Store and Product def store_images(instance, filename): return f&quot;{instance.store_name}/{filename}&quot; class Store(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, null=True, blank=True) description = models.TextField() date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) image = models.ImageField(upload_to=&quot;store_images&quot;, null=True, blank=True) delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) address = models.CharField(max_length=100, null=True, blank=True) phone_number = models.CharField(max_length=100, null=True, blank=True) products = models.ManyToManyField(&quot;Product&quot;, through=&quot;StoresProduct&quot;) def __str__(self): return self.name def save(self, *args, **kw): self.slug = slugify(f&quot;{self.name}&quot;) super(Store, self).save(*args, **kw) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField(&quot;Product&quot;, through=&quot;StoresProduct&quot;) quantity = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.email def get_total(self): return self.product.price * self.quantity class StoresProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) seller = models.ForeignKey(Store, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) quantity = models.IntegerField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) cart = models.ForeignKey( Cart, on_delete=models.CASCADE, related_name=&quot;products&quot;, default=None, null=True, blank=True, ) product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name=&quot;+&quot;, default=None, null=True, blank=True, ) def __str__(self): return f&quot;{self.product.name} - {self.seller.name}&quot; class Meta: unique_together = [&quot;product&quot;, &quot;seller&quot;] OrderStatus = ( (&quot;Pending&quot;, &quot;Pending&quot;), (&quot;Delivered&quot;, &quot;Delivered&quot;), (&quot;Cancelled&quot;, &quot;Cancelled&quot;), (&quot;Processing&quot;, &quot;Processing&quot;), ) class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=100, choices=OrderStatus, default=&quot;Pending&quot;) delivery_fee = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) order_id = models.CharField(max_length=100, null=True, blank=True) order_items = models.ManyToManyField(&quot;Product&quot;, through=&quot;OrderItem&quot;) store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.email + &quot; - &quot; + self.order_id def get_random_order_id(self): order_id = str(uuid.uuid4()).replace(&quot;-&quot;, &quot;&quot;).upper()[:10] return order_id # create order id with random string def save(self, *args, **kwargs): if not self.order_id: self.order_id = self.get_random_order_id() super(Order, self).save(*args, **kwargs) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.product.name </code></pre> <p>and my views.py</p> <pre><code>#create order with orderitems @swagger_auto_schema(method=&quot;post&quot;, request_body=OrderSerializer) @api_view([&quot;POST&quot;]) @permission_classes((permissions.AllowAny,)) @authentication_classes([TokenAuthentication]) def create_order(request): &quot;&quot;&quot; Creates an order then creates an orderitem &quot;&quot;&quot; user = request.user serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user) order_id = serializer.data[&quot;id&quot;] order = Order.objects.get(pk=order_id) cart = user.cart_set.all() for item in cart: OrderItem.objects.create( order=order, product=item.product, quantity=item.quantity, ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @swagger_auto_schema(method=&quot;post&quot;, request_body=AddToCartSerializer) @api_view([&quot;POST&quot;]) @permission_classes((permissions.AllowAny,)) @authentication_classes([TokenAuthentication]) def add_to_cart(request): &quot;&quot;&quot; Adds a product to cart &quot;&quot;&quot; user = request.user serializer = AddToCartSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p>Basically, users should be able to add products from various stores to their cart and when they are done they should be able to order. I can't seem to figure out what i am doing wrongly, if there's a better way to do this do tell.I'm guessing my approach is problematic</p>
<python><django>
2023-01-29 17:20:46
0
431
blockhead
75,276,583
18,758,062
Serving over HTTPS with Gunicorn/Flask: ERR_CERT_AUTHORITY_INVALID
<p>Looking for a quick way to serve an API over HTTPS for testing purposes. The API app is created using <code>flask</code> and being served on port 443 using <code>gunicorn</code>.</p> <pre><code>gunicorn --certfile=server.crt --keyfile=server.key --bind 0.0.0.0:443 wsgi:app </code></pre> <p>When my React app (served over HTTPS) sends a <code>POST</code> request to one of the routes via HTTPS, the browser console is showing</p> <pre><code>POST https://1.2.3.4/foo net::ERR_CERT_AUTHORITY_INVALID </code></pre> <p>My key and certs are created using</p> <pre><code>openssl genrsa -aes128 -out server.key 2048 openssl rsa -in server.key -out server.key openssl req -new -days 365 -key server.key -out server.csr openssl x509 -in server.csr -out server.crt -req -signkey server.key -days 365 </code></pre> <p>Is there a solution to solve <code>ERR_CERT_AUTHORITY_INVALID</code> raised by the browser, without using a reverse proxy like nginx/caddy? And without each user having to manually trust the self-signed cert?</p>
<python><flask><https><openssl><gunicorn>
2023-01-29 16:43:01
2
1,623
gameveloster
75,276,563
12,349,101
Tkinter - Scroll with touchpad / mouse gestures / two fingers scrolling in tkinter?
<p>I wanted to implement two finger scrolling in tkinter. Here is the result of my own attempt:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk class Scene: def __init__(self, canvas): self.canvas = canvas self.elements = [ { &quot;type&quot;: &quot;rect&quot;, &quot;x&quot;: canvas.winfo_width() / 2, &quot;y&quot;: canvas.winfo_height() / 2, &quot;width&quot;: 200, &quot;height&quot;: 200, &quot;color&quot;: (55 / 255, 55 / 255, 10 / 255), }, { &quot;type&quot;: &quot;rect&quot;, &quot;x&quot;: 100, &quot;y&quot;: 300, &quot;width&quot;: 200, &quot;height&quot;: 200, &quot;color&quot;: (155 / 255, 200 / 255, 10 / 255), }, ] def update_scene(self, offset): for element in self.elements: element[&quot;x&quot;] -= offset[0] element[&quot;y&quot;] -= offset[1] self.render_scene() def render_scene(self): self.canvas.delete(&quot;all&quot;) for element in self.elements: if element[&quot;type&quot;] == &quot;rect&quot;: self.canvas.create_rectangle( element[&quot;x&quot;], element[&quot;y&quot;], element[&quot;x&quot;] + element[&quot;width&quot;], element[&quot;y&quot;] + element[&quot;height&quot;], fill=f&quot;#{int(element['color'][0] * 255):02x}{int(element['color'][1] * 255):02x}{int(element['color'][2] * 255):02x}&quot;, ) else: print(f&quot;Error: type {element['type']} is not supported.&quot;) root = tk.Tk() root.geometry(&quot;{}x{}&quot;.format(800, 600)) canvas = tk.Canvas(root) canvas.pack(fill=&quot;both&quot;, expand=True) canvas_scroll = [0, 0] scene = Scene(canvas) scene.render_scene() def on_mouse_scroll(event): canvas_scroll[0] = event.delta canvas_scroll[1] = event.delta scene.update_scene(canvas_scroll) canvas.bind(&quot;&lt;MouseWheel&gt;&quot;, on_mouse_scroll) root.mainloop() </code></pre> <p>The above only works in one diagonal/direction, instead of any direction (up, down, left, right, and all four diagonals)</p> <p>The above was inspired by a Javascript snippet I found <a href="https://ryandi.site/1-infinite-canvas-in-excalidraw" rel="nofollow noreferrer">here</a>: <a href="https://jsfiddle.net/qmyho24r/" rel="nofollow noreferrer">https://jsfiddle.net/qmyho24r/</a></p> <p>I know using <code>Shift-MouseWheel</code> works, but then I have to also press the shift key, instead of just using the trackpad and two fingers (like in the Javascript example).</p> <p>How can I use two fingers scrolling in Tkinter?</p>
<python><tkinter><scroll><tk-toolkit><tkinter-canvas>
2023-01-29 16:40:29
1
553
secemp9
75,276,554
9,476,917
FastAPI: How to post dictionary with String and Bytes object to an endpoint?
<p>I want to post a <code>payload</code> dict to my FastAPI endpoint that holds metadata like a file name and a bytesObject.</p> <p>I accomplished to send the bytes object stand-alone using the <code>File()</code> Class of Fast API, but not in a dict structure.</p> <p>For my FastAPI Endpoint I tried two approches.</p> <p><strong>Approach 1</strong></p> <pre><code>@app.post(&quot;/process_file/&quot;, tags=[&quot;File porcessing&quot;]) def process_excel_file(payload_dict: dict): file_name = payload_dict[&quot;file_name&quot;] pyld = payload_dict[&quot;payload&quot;] data = FlatFileParser(file_name, pyld) logger.debug(f&quot;Received: {data}&quot;) return {&quot;Validator Response&quot;: data} </code></pre> <p><strong>Approach 2</strong></p> <pre><code>from fastapi import FastAPI, File, Request @app.post(&quot;/process_file/&quot;, tags=[&quot;File porcessing&quot;]) def process_excel_file(payload_dict: Request): file_name = payload_dict.body()[&quot;file_name&quot;] payload = payload_dict.body()[&quot;payload&quot;] data = FlatFileParser(file_name, payload) logger.debug(f&quot;Received: {data}&quot;) data = strip_cols(data) data = clean_columns(data) data = prep_schema_cols(data) data = drop_same_name_columns(data) return {&quot;Validator Response&quot;: data} </code></pre> <p>My Post request looks the following:</p> <pre><code>url = &quot;http://localhost:8000/process_file/&quot; file_path = r'sample_file.xlsx' with open(file_path, 'rb') as f: file = f.read() payload = { &quot;file_name&quot;: file_path, &quot;payload&quot;: file } response = requests.post(url, data=payload) </code></pre> <p>But I receive following error for <strong>Approach 1</strong>:</p> <blockquote> <p>Out[34]: b'{&quot;detail&quot;:[{&quot;loc&quot;:[&quot;body&quot;],&quot;msg&quot;:&quot;value is not a valid dict&quot;,&quot;type&quot;:&quot;type_error.dict&quot;}]}'</p> </blockquote> <p>And for <strong>Approach 2</strong> i am unable to parse the body() in a way to retrieve the necessary data.</p> <p>Any suggestions or advice?</p>
<python><python-requests><fastapi>
2023-01-29 16:39:27
0
755
Maeaex1
75,276,523
470,081
Truly dynamic DateField values in Django
<p>Some of my app models define date ranges (e.g. of contracts), where the current instance has no fixed end date (i.e. it should always evaluate to today). Setting the <code>default</code> parameter on the <code>end</code> field –</p> <pre><code>class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(default=datetime.date.today) </code></pre> <p>– will populate the field with a fixed value. A property to work around the problem –</p> <pre><code>class Contract(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) begin = models.DateField() end = models.DateField(blank=True) @property def get_end(self): if not self.end: return datetime.date.today() return self.end </code></pre> <p>– does not work with querysets. Is there any way to implement a truly dynamic value on the database level using Django's ORM?</p>
<python><django><postgresql><django-models>
2023-01-29 16:35:51
1
461
janeden
75,276,400
11,170,350
Input and output shape to GRU layer in PyTorch
<p>I am getting confused about the input shape to GRU layer. I have a batch of 128 images and I extracted 9 features from each images. So now my shape is <code>(1,128,9)</code>.</p> <p>This is the GRU layer</p> <pre><code>gru=torch.nn.GRU(input_size=128,hidden_size=8,batch_first=True) </code></pre> <p><strong>Question 1: Is the <code>input_size=128</code> correctly defined</strong>?<br /> Here is the code of forward function</p> <pre><code>def forward(features): features=features.permute(0,2,1)#[1, 9, 128] x2,_=self.gru(features) </code></pre> <p><strong>Question 2: Is the `code in forward function is correctly defined</strong>?</p> <p>Thanks</p>
<python><pytorch><gated-recurrent-unit>
2023-01-29 16:16:15
1
2,979
Talha Anwar
75,276,238
6,063,706
Sum of specific indices in pytorch?
<p>I have a neural network that outputs a tensor of size 12. After applying some calculations to this tensor, I need to reduce it to size 8 by adding the first four pairs and turning those into 1 dimension.</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] -&gt; [3, 7, 11, 15, 9, 10, 11, 12] </code></pre> <p>Is there an operation like this in pytorch that would still allow me to apply gradients?</p>
<python><pytorch>
2023-01-29 15:52:11
1
1,035
Tob
75,276,204
9,879,869
How to write to Django FileField from a tempfile?
<p>I am processing an image within a Django app. I used rasterio to process the geospatial image. I want to save the output directly to a FileField in a Model. I used a tempfile to write the output from rasterio, and used the method <code>Model.FileField.save</code> to hopefully write it with a reference to my Model instance.</p> <p>I have a simple model:</p> <pre><code>class MaskedLayer(models.Model): name = models.CharField(max_length=250, blank=True) file = models.FileField( upload_to='masked', null=True, max_length=500) </code></pre> <p>In my tasks, however this is an example:</p> <pre><code>from celery import shared_task import rasterio import tempfile from app.models import MaskedLayer @shared_task def process_image(): mask_layer_name = 'processed_image.tif' masked_layer = MaskedLayer.objects.create() with rasterio.open('example.tif') as dataset: # only example of reading/processing of image out_image = dataset.read() with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write(out_image) with rasterio.open(tmpfile.name) as dataset: masked_layer.file.save(mask_layer_name, File(dataset)) pass </code></pre> <p>I get this response. I am not sure of the error. Feel free to use the <strong><a href="https://drive.google.com/drive/folders/12p_XBz1WvNXeUCCGptnvjgnT3-9AluUe?usp=share_link" rel="nofollow noreferrer">example file</a></strong>.</p> <blockquote> <p>Fatal Python error: Segmentation fault</p> <p>Current thread 0x00007f453b463740 (most recent call first): File &quot;/usr/local/lib/python3.11/site-packages/django/views/debug.py&quot;, line 232 in get_traceback_frame_variables File &quot;/usr/local/lib/python3.11/site-packages/django/views/debug.py&quot;, line 544 in get_exception_traceback_frames File &quot;/usr/local/lib/python3.11/site-packages/django/views/debug.py&quot;, line 490 in get_traceback_frames File &quot;/usr/local/lib/python3.11/site-packages/django/views/debug.py&quot;, line 320 in get_traceback_data File &quot;/usr/local/lib/python3.11/site-packages/django/views/debug.py&quot;, line 403 in get_traceback_text File &quot;/usr/local/lib/python3.11/site-packages/django/utils/log.py&quot;, line 125 in emit File &quot;/usr/local/lib/python3.11/logging/<strong>init</strong>.py&quot;, line 978 in handle File &quot;/usr/local/lib/python3.11/logging/<strong>init</strong>.py&quot;, line 1706 in callHandlers File &quot;/usr/local/lib/python3.11/logging/<strong>init</strong>.py&quot;, line 1644 in handle File &quot;/usr/local/lib/python3.11/logging/<strong>init</strong>.py&quot;, line 1634 in _log<br /> File &quot;/usr/local/lib/python3.11/logging/<strong>init</strong>.py&quot;, line 1518 in error File &quot;/usr/local/lib/python3.11/site-packages/django/utils/log.py&quot;, line 241 in log_response File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 143 in response_for_exception File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 57 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py&quot;, line 136 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 55 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py&quot;, line 136 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 55 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py&quot;, line 136 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 55 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py&quot;, line 136 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 55 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py&quot;, line 136 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 55 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py&quot;, line 136 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 55 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py&quot;, line 136 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py&quot;, line 55 in inner File &quot;/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py&quot;, line 140 in get_response File &quot;/usr/local/lib/python3.11/site-packages/rest_framework/test.py&quot;, line 258 in get_response File &quot;/usr/local/lib/python3.11/site-packages/django/test/client.py&quot;, line 153 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/site-packages/django/test/client.py&quot;, line 805 in request File &quot;/usr/local/lib/python3.11/site-packages/rest_framework/test.py&quot;, line 238 in request File &quot;/usr/local/lib/python3.11/site-packages/rest_framework/test.py&quot;, line 286 in request File &quot;/usr/local/lib/python3.11/site-packages/django/test/client.py&quot;, line 541 in generic File &quot;/usr/local/lib/python3.11/site-packages/rest_framework/test.py&quot;, line 234 in generic File &quot;/usr/local/lib/python3.11/site-packages/rest_framework/test.py&quot;, line 210 in post File &quot;/usr/local/lib/python3.11/site-packages/rest_framework/test.py&quot;, line 296 in post File &quot;/usr/src/app/data_management/tests/test_data_management.py&quot;, line 18 in test_solar_pot File &quot;/usr/local/lib/python3.11/unittest/case.py&quot;, line 579 in _callTestMethod File &quot;/usr/local/lib/python3.11/unittest/case.py&quot;, line 623 in run File &quot;/usr/local/lib/python3.11/unittest/case.py&quot;, line 678 in <strong>call</strong><br /> File &quot;/usr/local/lib/python3.11/site-packages/django/test/testcases.py&quot;, line 416 in _setup_and_call File &quot;/usr/local/lib/python3.11/site-packages/django/test/testcases.py&quot;, line 381 in <strong>call</strong> File &quot;/usr/local/lib/python3.11/unittest/suite.py&quot;, line 122 in run File &quot;/usr/local/lib/python3.11/unittest/suite.py&quot;, line 84 in <strong>call</strong><br /> File &quot;/usr/local/lib/python3.11/unittest/runner.py&quot;, line 217 in run<br /> File &quot;/usr/local/lib/python3.11/site-packages/django/test/runner.py&quot;, line 980 in run_suite File &quot;/usr/local/lib/python3.11/site-packages/django/test/runner.py&quot;, line 1058 in run_tests File &quot;/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py&quot;, line 68 in handle File &quot;/usr/local/lib/python3.11/site-packages/django/core/management/base.py&quot;, line 448 in execute File &quot;/usr/local/lib/python3.11/site-packages/django/core/management/base.py&quot;, line 402 in run_from_argv File &quot;/usr/local/lib/python3.11/site-packages/django/core/management/commands/test.py&quot;, line 24 in run_from_argv File &quot;/usr/local/lib/python3.11/site-packages/django/core/management/<strong>init</strong>.py&quot;, line 440 in execute File &quot;/usr/local/lib/python3.11/site-packages/django/core/management/<strong>init</strong>.py&quot;, line 446 in execute_from_command_line File &quot;/usr/src/app/manage.py&quot;, line 18 in main File &quot;/usr/src/app/manage.py&quot;, line 22 in </p> <p>Extension modules: psycopg2._psycopg, numpy.core._multiarray_umath, numpy.core._multiarray_tests, numpy.linalg._umath_linalg, numpy.fft._pocketfft_internal, numpy.random._common, numpy.random.bit_generator, numpy.random._bounded_integers, numpy.random._mt19937, numpy.random.mtrand, numpy.random._philox, numpy.random._pcg64, numpy.random._sfc64, numpy.random._generator, rasterio._version, rasterio._err, rasterio._filepath, rasterio._env, rasterio._transform, rasterio._base, rasterio.crs, rasterio._features, rasterio._warp, rasterio._io, fiona._err, fiona._geometry, fiona._shim, fiona._env, fiona.schema, fiona.ogrext, fiona._crs (total: 31)</p> </blockquote>
<python><django><temporary-files><rasterio>
2023-01-29 15:45:40
1
1,572
Nikko
75,276,170
1,538,049
Conda cannot see Cuda version
<p>I am trying to install the newest Tensorflow GPU version to an Ubuntu environment. The Cuda drivers are correctly installed and working, which I can confirm with the following commands:</p> <pre><code>nvcc --version </code></pre> <p>With output:</p> <pre><code>nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2022 NVIDIA Corporation Built on Tue_May__3_18:49:52_PDT_2022 Cuda compilation tools, release 11.7, V11.7.64 Build cuda_11.7.r11.7/compiler.31294372_0 </code></pre> <p>Also, <code>nvidia-smi</code> returns a valid result:</p> <pre><code>+-----------------------------------------------------------------------------+ | NVIDIA-SMI 515.43.04 Driver Version: 515.43.04 CUDA Version: 11.7 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 Tesla V100-SXM2... On | 00000000:06:00.0 Off | 0 | | N/A 40C P0 68W / 300W | 9712MiB / 16384MiB | 7% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ </code></pre> <p>It seems I have the Cuda Version 11.7. Creating an empty Conda environment for Python 3.9, I want to install cudatoolkit and cudnn as instructed at <a href="https://www.tensorflow.org/install/pip?hl=en" rel="nofollow noreferrer">https://www.tensorflow.org/install/pip?hl=en</a>:</p> <pre><code>conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0 </code></pre> <p>However it complains that I do not have the correct Cuda version and won't install:</p> <pre><code> - cudatoolkit=11.2 -&gt; __cuda[version='&gt;=11.2.1|&gt;=11|&gt;=11.2|&gt;=11.2.2'] Your installed CUDA driver is: 11.7 </code></pre> <p>Obviously, my Cuda version meets the requirements, but somehow Conda would not see it. This seems to be a rare error, I didn't saw many similar issues on my search and turned to here. What can be wrong here?</p>
<python><tensorflow><cudnn>
2023-01-29 15:40:16
1
3,679
Ufuk Can Bicici
75,276,168
2,321,643
VS Code + Pylance does not find venv-installed modules while venv is activated
<p>I use VS Code Version: 1.74.3 on MacOS 13.2. <code>python -V</code> returns <code>Python 3.11.1</code>.</p> <p>I get the following error message: <code>Import &quot;django.shortcuts&quot; could not be resolved from source Pylance(reportMissingModuleScource)</code>.</p> <p><a href="https://i.sstatic.net/s0VFK.png" rel="noreferrer"><img src="https://i.sstatic.net/s0VFK.png" alt="enter image description here" /></a></p> <p>As you can see in the screenshot, the correct <code>venv</code> is activated and includes <code>Django</code>.</p> <p><a href="https://i.sstatic.net/4DE3V.png" rel="noreferrer"><img src="https://i.sstatic.net/4DE3V.png" alt="enter image description here" /></a></p> <p>I also tried or checked:</p> <ol> <li><a href="https://stackoverflow.com/q/68486207/2321643">Import could not be resolved/could not be resolved from source Pylance in VS Code using Python 3.9.2 on Windows 10</a></li> <li><a href="https://stackoverflow.com/a/65802367/2321643">https://stackoverflow.com/a/65802367/2321643</a> but</li> <li>the suggested solution with reloading the windows did not help.</li> <li>reinstallation the virtual environment within VSCode and installing Django again</li> <li>re-selecting the venv.</li> <li>deleting all python-specific settings in <code>user/settings.json</code> as well as <code>.vcode/settings.json</code>.</li> <li>Reinstallation python and associated extensions.</li> </ol> <p>Using Debug I can safely run my Django-application without any import issues. What do I need to do that Pylance does not issues these problems?</p>
<python><django><visual-studio-code><pylance>
2023-01-29 15:39:58
4
6,116
tjati
75,275,702
1,654,143
Bits per channel in Python
<p>In Photoshop I can find the number of bits per channel of an image with:</p> <pre><code>// BitsPerChannelType var bits = app.activeDocument.bitsPerChannel </code></pre> <p>What is the Pythonic equivalent to this and what modules are needed?</p> <p>bits = ??? # where the returned result is 8, 16 or 24</p>
<python><image><photoshop>
2023-01-29 14:33:52
1
7,007
Ghoul Fool
75,275,604
13,309,379
(Theoreticaly) Fast performing Routine for tensor manipulation going slower than not optimized version
<p>The goal of this implementation is to manipulate a 4 dimensional tensor in order to contact it with himself and then truncate the inflated indexes back to their original length.</p> <p>I have two routines that differ in the following point:</p> <ul> <li><strong>Routine One</strong> memory complexity scales with the dimension of the tensor to the power of 5, since the <code>tensorB2</code> and <code>tensorC</code>, which have shape <code>(dimension,dimension,dimesion,dimension,dimension)</code> have to be computed. for <code>dimension = 60</code> this takes about <em>66s</em>.</li> <li><strong>Routine Two</strong> computes exactly the same thing, but the computations of <code>tensorB2</code> and <code>tensorC</code> have been split in order to never compute a tensor that is bigger than <code>(dimension,dimension,dimesion,dimension)</code> thus scaling with dimension^4, but takes about <em>30min</em>.</li> </ul> <p>Again I want to underline that <strong>This routines compute exactly the same result</strong>, and, in the theory, routine 2 computational complexity should be even better than the one of routine 1.</p> <p><strong>I want to optimize Routine2</strong></p> <p>My guess is that I am using numpy`s ndarrays wrong, therefore repeating useless operation like copying Tensors in memory when not need.</p> <p><strong>Imports and functions</strong></p> <pre class="lang-py prettyprint-override"><code>import numpy as np from ncon import ncon def truncate_matrix(matrix,index,dim): shape=list(matrix.shape) shape[index]=dim newMatrix= matrix[0:shape[0],0:shape[1]] return newMatrix </code></pre> <p><strong>Routine 1</strong> (memory scaling dimension^5)</p> <pre class="lang-py prettyprint-override"><code>dimension = 60 myTensor = np.random.rand(dimension,dimension,dimension,dimension) tensorA = ncon([myTensor,myTensor],[[-1,1,2,-3],[-2,1,2,-4]]) tensorB = ncon([myTensor,myTensor],[[-1,1,-3,2],[-2,1,-4,2]]) tensorQ = ncon([tensorA,tensorB],[[-1,-3,1,2],[-2,-4,1,2]]) del tensorA,tensorB #Finding Utr Qshape = tensorQ.shape tensorQ = tensorQ.reshape((Qshape[0]*Qshape[1],Qshape[2]*Qshape[3])) Ul, deltaL, _ = np.linalg.svd(tensorQ) Utr = np.array(truncate_matrix(Ul, 1, dimension)) Utr = Utr.reshape((Qshape[0],Qshape[1],dimension)) del tensorQ,Ul,Qshape #Recontructing T tensorB2 = ncon([Utr,myTensor],[[1,-5,-1],[1,-4,-2,-3]]) tensorC = ncon([tensorB2,myTensor],[[-1,-2,1,-4,2],[2,-5,1,-3]]) del tensorB2 newTensor1 = ncon([Utr,tensorC],[[1,2,-2],[-1,-3,-4,1,2]]) del tensorC </code></pre> <p><strong>Routine 2</strong> (memory scaling dimension^4)</p> <pre class="lang-py prettyprint-override"><code>dimension = 60 myTensor = np.random.rand(dimension,dimension,dimension,dimension) tensorA = ncon([myTensor,myTensor],[[-1,1,2,-3],[-2,1,2,-4]]) tensorB = ncon([myTensor,myTensor],[[-1,1,-3,2],[-2,1,-4,2]]) tensorQ = ncon([tensorA,tensorB],[[-1,-3,1,2],[-2,-4,1,2]]) #Finding Utr Qshape = tensorQ.shape tensorQ = tensorQ.reshape((Qshape[0]*Qshape[1],Qshape[2]*Qshape[3])) Ul, deltaL, _ = np.linalg.svd(tensorQ) Utr = np.array(truncate_matrix(Ul, 1, dimension)) Utr = Utr.reshape((Qshape[0],Qshape[1],dimension)) courrentShape = myTensor.shape newTensor2 = np.zeros((dimension,dimension,courrentShape[2],courrentShape[3])) #Recontructing T for xf in range(0,newTensor2.shape[0]): for yu in range(0,dimension): #Slice courrent tensor tensorSlice = myTensor[:,:,yu,:] # T_iy1y'1 # Slice truncation matrix matrixSlice = Utr[:,:,xf] # Uy1y2 tensorB2 = ncon([matrixSlice,tensorSlice],[[1,-3],[1,-2,-1]]) for yb in range(0,newTensor2.shape[3]): tensorSlice = myTensor[:,:,:,yb] tensorC = ncon([tensorB2,tensorSlice],[[1,-1,2],[2,-2,1]]) newTensor2[xf,:,yu,yb] = ncon([Utr,tensorC],[[1,2,-1],[1,2]]) </code></pre>
<python><numpy><performance><tensor>
2023-01-29 14:19:35
0
712
Indiano
75,275,563
1,497,139
AttributeError: module 'sqlalchemy' has no attribute '__all__'
<p>In my GitHub CI I get errors like the one below since today:</p> <pre class="lang-none prettyprint-override"><code>File &quot;/home/runner/.local/lib/python3.8/site-packages/fb4/login_bp.py&quot;, line 12, in &lt;module&gt; from fb4.sqldb import db File &quot;/home/runner/.local/lib/python3.8/site-packages/fb4/sqldb.py&quot;, line 8, in &lt;module&gt; db = SQLAlchemy() File &quot;/home/runner/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py&quot;, line 758, in __init__ _include_sqlalchemy(self, query_class) File &quot;/home/runner/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py&quot;, line 112, in _include_sqlalchemy for key in module.__all__: AttributeError: module 'sqlalchemy' has no attribute '__all__' CRITICAL: Exiting due to uncaught exception &lt;class 'ImportError'&gt; </code></pre> <p>without being aware of any significant commit that might cause this. My local tests and my Jenkins CI still work.</p> <p>I changed the matrix to stick to python 3.8 instead of also trying 3.9, 3.10 and 3.11 also taking into account that a similar problem in <a href="https://stackoverflow.com/questions/66659283/python-3-9-attributeerror-module-posix-has-no-attribute-all">python 3.9 AttributeError: module &#39;posix&#39; has no attribute &#39;__all__&#39;</a> was due to missing 3.9 support.</p> <p><strong>How can the above error could be debugged and mitigated?</strong></p> <p>My assumption is that the problem is in the setup/environment or some strange behaviour change of GitHub actions, Python, pip or the test environment or whatever.</p> <p>I am a committer of the projects involved which are:</p> <ul> <li><a href="https://github.com/WolfgangFahl/pyOnlineSpreadSheetEditing" rel="noreferrer">https://github.com/WolfgangFahl/pyOnlineSpreadSheetEditing</a> and potentially</li> <li><a href="https://github.com/WolfgangFahl/pyFlaskBootstrap4" rel="noreferrer">https://github.com/WolfgangFahl/pyFlaskBootstrap4</a></li> </ul> <p><strong>Update:</strong> After following the suggestions by @snakecharmerb the logs Now show a version conflict</p> <pre><code>RROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts The conflict is caused by: The user requested Flask~=2.0.2 bootstrap-flask 1.8.0 depends on Flask flask-dropzone 1.6.0 depends on Flask flask-login 0.6.2 depends on Flask&gt;=1.0.4 flask-httpauth 1.0.0 depends on Flask flask-sqlalchemy 3.0.2 depends on Flask&gt;=2.2 </code></pre> <p>Which is interesting since i am trying to avoid the ~ notation ... and indeed it was a typo ... let's see whether the fix to upgrade Flask-SQLAlchemy&gt;=3.0.2 works now.</p> <p>I have accepted the answer after setting the version as suggested. There are followup problems but the question is answered.</p>
<python><sqlalchemy>
2023-01-29 14:15:01
3
15,707
Wolfgang Fahl
75,275,547
1,307,905
Determine currently selected Outlook profile
<p>I'm dealing with several Office installations that have two profiles, primarily in order for the Exchange connection in one profile not to break normal (caldav) based calendars in the other profile.</p> <p>There are some actions that only should only be applied when a particular profile is active. I detect if Outlook is running (using <code>psutil</code>), and if Outlook is not running, things are easy: start outlook with the appropriate profile and then execute the actions.</p> <p>However if outlook is already running, it could be that the &quot;wrong&quot; profile has been selected on startup. How can I use Python to query the selected profile on a already opened Outlook?</p> <p>I tried to look in <code>%APPDATA%\Microsoft\Outlook</code> (that is the one under <code>roaming</code>) There is a <code>xyz.xml</code> for the appropriate profile <code>xyz</code>, but it doesn't get touched until Outlook exits. There is a file ending in <code>.srs</code> that gets touched immediately when Outlook opens, but there seems to be no fixed relationship with the name of the profiles (sometimes <code>xyz.srs</code> exists sometimes it does not).</p>
<python><outlook><win32com><profile><office-automation>
2023-01-29 14:12:29
1
78,248
Anthon
75,275,534
6,762,755
Polars equivalent to SQL `COUNT(DISTINCT expr,[expr...])`, or other method of checking uniqueness
<p>When processing data, I often add a check after each step to validate that the data still has the unique key I think it does. For example, I might check that my data is still unique on <code>(a, b)</code>. To accomplish this, I would typically check that the number of distinct combinations of columns <code>a</code> and <code>b</code> equals the total number of rows.</p> <p>In polars, to get a <code>COUNT(DISTINCT ...)</code> I can do</p> <pre class="lang-py prettyprint-override"><code>( df .select('a', 'b') .unique() .height ) </code></pre> <p>But <code>height</code> does not work on <code>LazyFrame</code>s, so I need to actually materialize the entire data with this method, I think (?). Is there a better way?</p> <p>For reference, in R's data.table library I would do</p> <pre><code>mtc_dt &lt;- data.table::as.data.table(mtcars) stopifnot(data.table::uniqueN(mtc_dt[, .(mpg, disp)]) == nrow(mtc_dt)) </code></pre> <p>To any contributors reading:</p> <p>Thanks for the great package! Has sped up many of my workflows to a fraction of the time.</p>
<python><dataframe><python-polars>
2023-01-29 14:09:22
3
28,795
IceCreamToucan
75,275,508
6,658,422
Is it possible to separate menu entry and event string in PySimpleGui right-click menus?
<p>Is it possible to separate the menu entry in a <a href="https://www.pysimplegui.org/en/latest/#right-click-menus" rel="nofollow noreferrer">right-click menu</a> from the event string that is assigned when the event is thrown?</p> <p>E.g., when adding a right-click menu to a list box via</p> <pre class="lang-py prettyprint-override"><code>sg.Listbox( &quot;&quot;, key=&quot;-eventListbox-&quot;, size=(50, 10), right_click_menu = ['&amp;Right', ['Open']], select_mode=sg.LISTBOX_SELECT_MODE_EXTENDED, enable_events=True, ), </code></pre> <p>the right-click on an item will trigger an event &quot;Open&quot;. I would prefer the event to be named &quot;-eventOpen-&quot; (or something similar), but not necessarily the string in the menu item.</p>
<python><pysimplegui>
2023-01-29 14:05:49
0
2,350
divingTobi
75,275,485
1,169,091
Why does the y-intercept from the model not match the graph?
<p>This code generates a graph of the regression line but the y-intercept taken from the LR model does not match the y-intercept on the graph. What am I missing? The script prints the y-intercept, taken from the model, as 152 but the graph shows it to be less than 100.</p> <pre><code># Adapted from https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py # Code source: Jaques Grobler # License: BSD 3 clause import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y = True) diabetes_X = diabetes_X[:, np.newaxis, 2] diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] diabetes_y_train = diabetes_y[:-20] diabetes_y_test = diabetes_y[-20:] regr = linear_model.LinearRegression() regr.fit(diabetes_X_train, diabetes_y_train) diabetes_y_pred = regr.predict(diabetes_X_test) # The y-intercept print(&quot;y-intercept: \n&quot;, regr.intercept_) plt.scatter(diabetes_X_test, diabetes_y_test, color=&quot;black&quot;) plt.plot(diabetes_X_test, diabetes_y_pred, color=&quot;blue&quot;, linewidth=3) plt.xlabel('x') plt.ylabel('y') plt.show() </code></pre> <p>Ouptut of the script:</p> <pre><code>y-intercept: 152.91886182616167 </code></pre> <p><a href="https://i.sstatic.net/unWFS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/unWFS.png" alt="Here is the graph. The y-intercept appears to be about 80." /></a></p>
<python><matplotlib><scikit-learn><linear-regression>
2023-01-29 14:01:59
1
4,741
nicomp
75,275,434
10,781,096
Django testing fails with object not found in response.context even though it works when actually running
<p>I'm trying to test if my <code>PlayerPoint</code> model can give me the top 5 players in regards to their points. This is the <code>Player</code> model:</p> <pre class="lang-py prettyprint-override"><code>class Player(AbstractUser): phone_number = models.CharField( max_length=14, unique=True, help_text=&quot;Please ensure +251 is included&quot; ) </code></pre> <p>and this is the <code>PlayerPoint</code> model:</p> <pre class="lang-py prettyprint-override"><code>class PlayerPoint(models.Model): OPERATION_CHOICES = (('ADD', 'ADD'), ('SUB', 'SUBTRACT'), ('RMN', 'REMAIN')) points = models.IntegerField(null=False, default=0) operation = models.CharField( max_length=3, null=False, choices=OPERATION_CHOICES, default=OPERATION_CHOICES[2][0] ) operation_amount = models.IntegerField(null=False) operation_reason = models.CharField(null=False, max_length=1500) player = models.ForeignKey( settings.AUTH_USER_MODEL, null=False, on_delete=models.PROTECT, to_field=&quot;phone_number&quot;, related_name=&quot;player_points&quot; ) points_ts = models.DateTimeField(auto_now_add=True, null=False) class Meta: get_latest_by = ['pk', 'points_ts'] </code></pre> <p>I also have a pre-save signal handler:</p> <pre class="lang-py prettyprint-override"><code>@receiver(signals.pre_save, sender=PlayerPoint) def pre_save_PlayerPoint(sender, instance, **_): if sender is PlayerPoint: try: current_point = PlayerPoint.objects.filter(player=instance.player).latest() except PlayerPoint.DoesNotExist as pdne: if &quot;new player&quot; in instance.operation_reason.lower(): print(f&quot;{pdne} {instance.player} must be a new&quot;) instance.operation_amount = 100 instance.points = int(instance.points) + int(instance.operation_amount) else: raise pdne except Exception as e: print(f&quot;{e} while trying to get current_point of the player, stopping execution&quot;) raise e else: if instance.operation == PlayerPoint.OPERATION_CHOICES[0][0]: instance.points = int(current_point.points) + int(instance.operation_amount) elif instance.operation == PlayerPoint.OPERATION_CHOICES[1][0]: if int(current_point.points) &lt; int(instance.operation_amount): raise ValidationError( message=&quot;not enough points&quot;, params={&quot;points&quot;: current_point.points}, code=&quot;invalid&quot; ) instance.points = int(current_point.points) - int(instance.operation_amount) </code></pre> <p>As you can see there is a foreign key relation. Before running the tests, in the <code>setUp()</code> I create points for all the players as such:</p> <pre class="lang-py prettyprint-override"><code>class Top5PlayersViewTestCase(TestCase): def setUp(self) -&gt; None: self.player_model = get_user_model() self.test_client = Client(raise_request_exception=True) self.player_list = list() for i in range(0, 10): x = self.player_model.objects.create_user( phone_number=f&quot;+2517{i}{i}{i}{i}{i}{i}{i}{i}&quot;, # first_name=&quot;test&quot;, # father_name=&quot;user&quot;, # grandfather_name=&quot;tokko&quot;, # email=f&quot;test_user@tokko7{i}.com&quot;, # age=&quot;29&quot;, password=&quot;password&quot; ) PlayerPoint.objects.create( operation=&quot;ADD&quot;, operation_reason=&quot;new player&quot;, player=x ) self.player_list.append(x) counter = 500 for player in self.player_list: counter += int(player.phone_number[-1:]) PlayerPoint.objects.create( operation=&quot;ADD&quot;, operation_amount=counter, operation_reason=&quot;add for testing&quot;, player=player ) PlayerPoint.objects.create( operation=&quot;ADD&quot;, operation_amount=counter, operation_reason=&quot;add for testing&quot;, player=player ) return super().setUp() def test_monthly_awarding_view_displays_top5_players(self): for player in self.player_list: print(player.player_points.latest()) # self.test_client.post(&quot;/accounts/login/&quot;, self.test_login_success_data) test_results = self.test_client.get(&quot;/points_app/monthly_award/&quot;, follow=True) self.assertEqual(test_results.status_code, 200) self.assertTemplateUsed(test_results, &quot;points_app/monthlytop5players.html&quot;) self.assertEqual(len(test_results.context.get('results')), 5) top_5 = PlayerPoint.objects.order_by('-points')[:5] for pt in top_5: self.assertIn(pt, test_results.context.get('results')) </code></pre> <p>The full traceback is this after running <code>coverage run manage.py test points_app.tests.test_views.MonthlyAwardingViewTestCase.test_monthly_awarding_view_displays_top5_players -v 2</code>:</p> <pre class="lang-py prettyprint-override"><code>Traceback (most recent call last): File &quot;/home/gadd/vscodeworkspace/websites/25X/twenty_five_X/points_app/tests/test_views.py&quot;, line 358, in test_monthly_awarding_view_displays_top5_players self.assertIn(pt, test_results.context.get('results')) AssertionError: &lt;PlayerPoint: 1190 -- +251799999999&gt; not found in [&lt;User25X: +251700000000&gt;, &lt;User25X: +251711111111&gt;, &lt;User25X: +251722222222&gt;, &lt;User25X: +251733333333&gt;, &lt;User25X: +251744444444&gt;] </code></pre> <p>This is the view being tested:</p> <pre class="lang-py prettyprint-override"><code>def get(request): all_players = get_user_model().objects.filter(is_staff=False).prefetch_related('player_points') top_5 = list() for player in all_players: try: latest_points = player.player_points.latest() except Exception as e: print(f&quot;{player} -- {e}&quot;) messages.error(request, f&quot;{player} {e}&quot;) else: if all( [ latest_points.points &gt;= 500, latest_points.points_ts.year == current_year, latest_points.points_ts.month == current_month ] ): top_5.append(player) return render(request, &quot;points_app/monthlytop5players.html&quot;, {&quot;results&quot;: top_5[:5]}) </code></pre> <p>What am I doing wrong?</p>
<python><django><django-testing><django-tests>
2023-01-29 13:55:09
2
488
NegassaB
75,275,429
15,154,700
How to comment on clickup with python?
<p>I want to comment on a specific task in clickup but it responses 401 error.</p> <pre><code>url = &quot;https://api.clickup.com/api/v2/task/861m8wtw3/comment&quot; headers = { &quot;Authorization&quot;: &quot;Bearer &lt;my api key&gt;&quot;, &quot;Content-Type&quot;: &quot;application/json&quot; } # comment = input('Type your comment text: \n') comment = 'test comment' data = { &quot;content&quot;: f&quot;{comment}&quot; } response = requests.post(url, headers=headers, json=data) </code></pre> <p>and the output is:</p> <p><code>&lt;Response [401]&gt;</code></p> <p>what is the problem?</p> <p>i tried to add mozilla headers as the user agent key:</p> <pre><code>'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' </code></pre> <p>but still get the 401 error!</p>
<python><python-requests><clickup-api>
2023-01-29 13:54:17
2
545
Sadegh Pouriyan Zadeh
75,275,393
9,776,466
Processing multiple columns in the dataset into one column for modeling
<p>I want to predict spatio-temporal data and I found STNN (Spatio Temporal Neural Network) research with the github repository here (<a href="https://github.com/edouardelasalles/stnn" rel="nofollow noreferrer">https://github.com/edouardelasalles/stnn</a>), at the end of the repo description, it is explained regarding the dataset but I have difficulty understanding how a data spatial with its attributes transformed into only 1 dimension and then crossed with the time dimension into only 2 dimensions?</p> <p>my question is how to convert dataset with multiple columns for example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>x</th> <th>y</th> <th>a</th> <th>b</th> <th>c</th> </tr> </thead> <tbody> <tr> <td>101</td> <td>1</td> <td>9</td> <td>8</td> <td>7</td> </tr> <tr> <td>122</td> <td>3</td> <td>8</td> <td>7</td> <td>9</td> </tr> <tr> <td>312</td> <td>2</td> <td>8</td> <td>9</td> <td>7</td> </tr> </tbody> </table> </div> <p>to:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>formulated</th> </tr> </thead> <tbody> <tr> <td>0,123</td> </tr> <tr> <td>0,412</td> </tr> <tr> <td>0,213</td> </tr> </tbody> </table> </div> <p>is there any way and formula to do that? Thankyou!</p>
<python><pandas><machine-learning><statistics><data-preprocessing>
2023-01-29 13:48:43
0
561
Hermawan Wiwid
75,274,940
10,654,410
peewee.OperationalError: (3995, "Character set 'utf8mb4_unicode_ci' cannot be used in conjunction with 'binary' in call to regexp_like.")
<p>I had a peewee query (against a mysql 8.0 server) working a few months ago, and now it gives me the following error:</p> <pre><code>peewee.OperationalError: (3995, &quot;Character set 'utf8mb4_unicode_ci' cannot be used in conjunction with 'binary' in call to regexp_like.&quot;) </code></pre> <p>The line of code producing the error is:</p> <pre><code>words = (Word .select(Word.word, Word.points) .where(Word.word.regexp('^[aeiou]+$')) .order_by(fn.CHAR_LENGTH(Word.word).desc(), Word.word) </code></pre> <p>a) I'm 99% sure it was working a few weeks, b) I can't see anything I might have changed, c) I'm pretty sure the resolution will be simple but I can't put my finger on it.</p> <p>versions are peewee==3.15.4 and Python==3.10.9</p>
<python><mysql><peewee>
2023-01-29 12:36:13
1
399
SimonB
75,274,655
20,078,696
Why does plt.cla() only work on one of the plots?
<p>I am trying to create a program that has two different plots at the same time:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np plt.ion() for i in range(100): x = np.arange(i, i + 50, 0.2) plt.cla() for subplotId in range(1, 3): plt.subplot(2, 1, subplotId) plt.ylim(-100, 100) y = np.tan(x) plt.plot(x, y) plt.pause(0.1) </code></pre> <p>However, <code>plt.cla()</code> only seems to work on the second plot. The first plot seems to get 'squished': <a href="https://i.sstatic.net/Gcpb4m.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Gcpb4m.png" alt="Plots" /></a> How do I clear both plots?</p>
<python><matplotlib><plot>
2023-01-29 11:51:31
1
789
sbottingota
75,274,484
10,924,836
Change variable on the basis of last character
<p>I need to change the text variable in the data set below. Namely, each row has categorical values in the object format that need to be changed, depending on the <code>last character</code> in the data set. Below you can see my dataset.</p> <pre><code>import pandas as pd import numpy as np data = { 'stores': ['Lexinton1','ROYAl2','Mall1','Mall2','Levis1','Levis2','Shark1','Shark','Lexinton'], 'quantity':[1,1,1,1,1,1,1,1,1] } df = pd.DataFrame(data, columns = ['stores', 'quantity' ]) df </code></pre> <p>Now I want to change this data depending on the last character. For example, if the last charter is number <code>1</code> then I want to put the word <code>open</code>, if is number <code>2</code> then I want to put <code>closed</code>.If is not a number then I don't put anything and the text will be the same. Below you can output that is desirable</p> <p><a href="https://i.sstatic.net/efcHL.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/efcHL.jpg" alt="enter image description here" /></a></p>
<python><pandas>
2023-01-29 11:22:59
2
2,538
silent_hunter
75,274,455
1,276,022
Pass a variable to macro in Jinja
<p>I am trying to pass a variable to a macro in jinja but every time I try to do that I get an error message saying</p> <blockquote> <p>jinja2.exceptions.TemplateSyntaxError: unexpected '}', expected ')'</p> </blockquote> <p>Here is my code:</p> <pre><code>{{ my_macro(value='{{var1}} - {{var2}}') }} </code></pre> <p>Its documented in Jinja documentation that when using a variable within a double bracket literal {{ }} then the variable does not need an additional double bracket for it and Jinja would resolve it correctly. However, when the variable is within a quote literal, the variable does not seem to resolve to its value and rather it name would be passed as a string which is not right.</p> <pre><code>{{ my_macro(value='var1 - var2') }} </code></pre> <p>This would make value equal to a string without resolving var1 and var2 to their values. There should be a way to use a variable inside a quite literal which is within an outer double bracket. A possible scenario where this happens is when a macro with a parameter is called and a value of the argument is a variable.</p>
<python><flask><jinja2>
2023-01-29 11:18:48
1
634
Youstanzr
75,274,446
12,709,265
Limit volume to a certain range
<p>I have a certain program which changes the volume of a computer using the <code>pulsectl</code> module in python. The following is the code:</p> <pre><code>if(distance &gt; self.threshold): self.pulse.volume_change_all_chans(self.sink, 0.02) else: self.pulse.volume_change_all_chans(self.sink, -0.02) </code></pre> <p>Using this code leads to a minimum value of 0 and a maximum value can go up to infinity. What I would like to do is that the maximum value of volume should be set at one. It shouldn't increase even a bit beyond one.</p> <p>For ex, if my current volume is <code>0.99</code> and the condition in <code>if</code> statement is <code>True</code>, then, my volume changes to <code>1.1</code>. This shouldn't happen. It should increase maximum to <code>1.0</code>. Never beyond it.</p> <p>Also, the current value of value of volume can be obtained by <code>self.pulse.volume_get_all_chans(self.sink)</code></p> <p>How can i do this without writing too many if else conditions in python.</p>
<python><python-3.x>
2023-01-29 11:17:30
1
1,428
Shawn Brar
75,274,334
11,381,978
Automatically converting .py file to .pyx using python type hints
<p>Recently I had to convert a module written in pure python to pyx in in order to compile with cython. The procedure for converting from py to pyx was very straight forward since the all the variables and functions were type hinted. So it was a just a matter of looking up the cython static type for each types in python.</p> <p>What are the current options available for automating the conversion of a module written in pure Python to Cython, specifically for converting .py files to .pyx files, taking into account the use of Python type hints in the original code? Are there any existing modules or tools that can facilitate this process? if NO, is it theoretically possible to develop a module that can automatically convert Python type hints to Cython static types, and if so, what challenges may arise in the development of such a module?</p>
<python><cython>
2023-01-29 10:58:47
1
324
Samm Flynn
75,274,332
16,383,578
How to draw Android lock screen patterns using Python
<p>This may seem trivial but I Googled it and found no relevant results. And I don't have access to ChatGPT because unfortunately I was born in China.</p> <p>I want to find out all the ways a polyline can pass through n*n evenly spaced lattice points without crossing itself.</p> <p>Basically like a typical Android lock screen pattern, in which there are 9 points situated at the vertices of 4 adjacent congruent squares. And you can draw polylines that goes from vertices to other vertices.</p> <p>I want to programmatically generate all such polylines that passes through all n*n (n &gt;= 3 and n is integer) lattice points without intersecting itself, but to do that I need to first manually draw such polylines to find the mathematical pattern.</p> <p>I can handle all the logics but I really don't know how to code GUI, basically I want a window that displays n*n lattice points arranged in a square, and you use mouse pointer to draw the polyline, the pointer auto-snaps to the grid, and you click and hold from one lattice to another to draw the lines.</p> <p>How can I do that?</p>
<python><user-interface>
2023-01-29 10:58:09
1
3,930
Ξένη Γήινος
75,274,241
3,054,437
t() expects a tensor with <= 2 dimensions, but self is 3D
<p>I'm new to <strong>PyTorch</strong> and wrote a simple code as following to classify some inputs. The model input has 8*2 with batch size of 2 and the input layer in the model has 2 nodes. I don't know what is wrong!</p> <pre><code>X1=np.array([[2,1],[3,2],[-4,-1],[-1,-3],[2,-1],[3,-3],[-2,1],[-4,-2]]) Y1=np.array([0,0,0,0,1,1,1,1]) X=torch.tensor(X1) Y=torch.tensor(Y1) BATCH_SIZE=2 trainset= torch.utils.data.TensorDataset(X, Y) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=1) from torch.nn.modules import flatten learning_rate = 0.01 num_epochs = 20 device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;) model = MyModel() model = model.to(device) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) ## compute accuracy def get_accuracy(logit, target, batch_size): ''' Obtain accuracy for training round ''' corrects = (torch.max(logit, 1)[1].view(target.size()).data == target.data).sum() accuracy = 100.0 * corrects/batch_size return accuracy.item() model = MyModel() # Commented out IPython magic to ensure Python compatibility. for epoch in range(num_epochs): train_running_loss = 0.0 train_acc = 0.0 ## training step for inputs, labels in trainloader: #inputs=torch.flatten(inputs) inputs,labels=inputs.to(device), labels.to(device) #inputs = inputs.to(device) #labels = labels.to(device) optimizer.zero_grad() ## forward + backprop + loss print(inputs) outputs = model.forward(inputs) loss = criterion(outputs, labels) loss.backward() ## update model params optimizer.step() train_running_loss += loss.detach().item() train_acc += get_accuracy(outputs, labels, BATCH_SIZE) #model.train() model.eval() print('Epoch: %d | Loss: %.4f | Train Accuracy: %.2f'%(epoch, train_running_loss / i, train_acc/i)) </code></pre> <p>And my model is as below:</p> <pre><code>class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.d1 = nn.Linear(2,3) self.d2 = nn.Linear(3,1) self.init_weights() def init_weights(self): k1=torch.tensor([0.1,-0.72,0.94,-0.29,0.12,0.44]) k1=torch.unsqueeze(torch.unsqueeze(k1,0),0) self.d1.weight.data=k1 k2=torch.tensor([1,-1.16,-0.26]) k2=torch.unsqueeze(torch.unsqueeze(k2,0),0) self.d2.weight.data=k2 def forward(self, x): x = self.d1(x) x = F.tanh(x) x = self.d2(x) out = F.sigmoid(x) return out </code></pre> <p>Then I got an error:</p> <pre><code>--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-27-196d819d3ccd&gt; in &lt;module&gt; 101 print(inputs) 102 --&gt; 103 outputs = model.forward(inputs) 104 loss = criterion(outputs, labels) 105 2 frames /usr/local/lib/python3.8/dist-packages/torch/nn/modules/linear.py in forward(self, input) 112 113 def forward(self, input: Tensor) -&gt; Tensor: --&gt; 114 return F.linear(input, self.weight, self.bias) 115 116 def extra_repr(self) -&gt; str: RuntimeError: t() expects a tensor with &lt;= 2 dimensions, but self is 3D </code></pre> <p>I flatten the input but nothing changed. What should I do to fix it?</p>
<python><machine-learning><deep-learning><pytorch><runtime-error>
2023-01-29 10:38:06
1
500
mohammad
75,274,070
2,552,108
Super Resolution using OpenCV and Python appears to have no effect
<p>I am trying to follow the code shown in this <a href="https://learnopencv.com/super-resolution-in-opencv/" rel="nofollow noreferrer">link</a> to apply Super Rez using OpenCV <code>cv2.dnn_superres.DnnSuperResImpl_create()</code> function.</p> <p>I have downloaded the super res models from each repo (<a href="https://github.com/fannymonori/TF-LAPSRN" rel="nofollow noreferrer">LapSRN</a>, <a href="https://github.com/Saafke/FSRCNN_Tensorflow/tree/master/models" rel="nofollow noreferrer">FSRCNN</a>, and <a href="https://github.com/fannymonori/TF-ESPCN/tree/master/export" rel="nofollow noreferrer">ESPCN</a> )</p> <p>I was expecting to have the same results from the source blog</p> <p><a href="https://i.sstatic.net/SvKXW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/SvKXW.png" alt="enter image description here" /></a></p> <p>Instead, what I got was basically the image resized with tiny detail changes</p> <p><a href="https://i.sstatic.net/PtA06.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PtA06.png" alt="enter image description here" /></a></p> <p>Below is the code I used</p> <pre><code>sr = cv2.dnn_superres.DnnSuperResImpl_create() path = &quot;models/ESPCN_x3.pb&quot; sr.readModel(path) sr.setModel(&quot;espcn&quot;,3) result = sr.upsample(img) cv2.imwrite('results/ss_ESPCN_x3.jpg', result) # Resized image resized = cv2.resize(img,dsize=None,fx=3,fy=3) cv2.imwrite('results/ss_fx3.jpg', resized) plt.figure(figsize=(12,8)) plt.subplot(1,3,1) # Original image plt.imshow(img[:,:,::-1]) plt.subplot(1,3,2) # SR upscaled plt.imshow(result[:,:,::-1]) plt.subplot(1,3,3) # OpenCV upscaled plt.imshow(resized[:,:,::-1]) plt.show() </code></pre> <p>I also made sure to install the latest OpenCV contrib package</p> <p><a href="https://i.sstatic.net/rMD6h.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/rMD6h.png" alt="enter image description here" /></a></p> <p>Is there something that I am missing?</p>
<python><opencv><deep-learning><neural-network><conv-neural-network>
2023-01-29 10:03:57
0
1,170
user2552108
75,273,915
1,591,921
Prefer binary package in setup.cfg
<p>My project (<a href="https://github.com/locustio/locust" rel="nofollow noreferrer">https://github.com/locustio/locust</a>) depends on <code>greenlet</code>, but whenever there is a new release of that, there is a brief period when no binary version is available, and many of my users have issues with installing from source.</p> <p>Is there a way to prefer an older binary version instead of the latest and greatest source version? E.g. prefer 2.0.1 that has a binary version over 2.0.2 that doesn't (or at least didn't at the time)</p> <p>Considered alternate solutions:</p> <ul> <li>Set <code>--prefer-binary</code> from the pip command line, but it is somewhat hard to explain that to people.</li> <li>I could just lock it to 2.0.1, but that is overly rigid.</li> </ul>
<python><pip><setuptools><python-packaging><greenlets>
2023-01-29 09:37:36
0
11,630
Cyberwiz
75,273,852
2,833,774
How to list objects of one depth level without listing sub-objects by GCP Cloud Storage Python API?
<p>The Cloud Storage Python API allows to list objects using prefix, which limits the listing to certain sub-branches of objects in the bucket.</p> <pre><code>bucket_name = &quot;my-bucket&quot; folders = &quot;logs/app&quot; storage_client.list_blobs(bucket_name, prefix=folders) </code></pre> <p>This operations will return all objects which names start from &quot;logs/app&quot;. But it will return absolutely all objects, including those which lay on deeper levels of hierarchy. For example, I've got many applications <code>app=1</code>, <code>app=2</code>, etc. So that the output will be like this:</p> <pre><code>logs/app=1 logs/app=1/module=1 logs/app=1/module=1/log_1.txt logs/app=1/module=1/log_2.txt logs/app=2 logs/app=2/module=1 logs/app=2/module=1/log_1.txt logs/app=2/module=1/log_2.txt </code></pre> <p>and etc. This operation of listing objects as it is mentioned above is scanning everything and because of that it's slow. For example, if I've got 80K or 1M files stored in those folders, all of them will be scanned and returned.</p> <p>I would like to get only result only for one depth level. For example, I would like to get only this:</p> <pre><code>logs/app=1 logs/app=2 </code></pre> <p>And I don't want the SDK to scan everything. Is there a way to achieve this? Maybe not with this API, maybe there is another Python SDK which could be used for this?</p>
<python><google-cloud-storage>
2023-01-29 09:26:09
1
374
Alexander Goida
75,273,603
6,218,173
python index [-1] shows wrong element
<p>As I learned, in python index -1 is the last number. for instant in:</p> <pre><code>values = [1, 2 , 3, 4, 5, 6, 7, 8, 9, 10] print(value[-1]) </code></pre> <p>returns 10 in output.</p> <p>Now, if I want to insert a number in the last position with insert method, I do:</p> <pre><code>value.insert(-1,11) </code></pre> <p>and I expect to have:</p> <pre><code>[1, 2,3, 4, 5, 6, 7, 8, 9, 10, 11] </code></pre> <p>but, this is what I get in output:</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 10] </code></pre>
<python><python-3.x><indexing><methods>
2023-01-29 08:38:50
3
491
Majid
75,273,498
9,576,988
How to pivot a column's values, making new, enumerated columns with pandas dataframe
<p>I have a dataframe like:</p> <pre class="lang-py prettyprint-override"><code> id diag a_date 0 1 d1 55 1 1 d2 88 2 2 d5 22 3 2 d3 44 4 2 d4 88 5 2 d4 89 6 3 d1 11 7 3 d1 13 8 3 d1 15 9 3 d5 27 10 3 d5 28 11 3 d5 29 </code></pre> <p><code>df = pd.read_clipboard() # copy the above text and run this to set df</code></p> <p>And I want to reshape it so that the <code>diag</code> values become enumerated columns with <code>a_date</code> values like:</p> <pre class="lang-py prettyprint-override"><code> id d1_1 d1_2 d1_3 d2_1 d3_1 d4_1 d4_2 d5_1 d5_2 d5_3 0 1 55 88 1 2 44 88 89 22 2 3 11 13 15 27 28 29 </code></pre>
<python><pandas><dataframe><pivot><reshape>
2023-01-29 08:20:10
2
594
scrollout
75,273,422
12,875,740
Requests in multiprocessing fail python
<p>I'm trying to query data from a website, but it takes 6 seconds to query. For all 3000 of my queries, I'd be sitting around for 5 hours. I heard there was a way to parallelize this stuff, so I tried using multiprocessing to do it. It didn't work, and I tried asyncio, but it gave much the same result. Here's the multiprocessing code since that's simpler.</p> <p>I have 5+ urls in a list I want to request tables from:</p> <p><a href="https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=1&amp;btime=2014+01+17+18:38:41&amp;etime=2014+01+18+18:38:41&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd" rel="nofollow noreferrer">https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=1&amp;btime=2014+01+17+18:38:41&amp;etime=2014+01+18+18:38:41&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd</a> <a href="https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=2&amp;btime=2014+05+18+23:10:01&amp;etime=2014+05+19+23:10:01&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd" rel="nofollow noreferrer">https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=2&amp;btime=2014+05+18+23:10:01&amp;etime=2014+05+19+23:10:01&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd</a> <a href="https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=3&amp;btime=2014+11+04+06:01:27&amp;etime=2014+11+05+06:01:27&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd" rel="nofollow noreferrer">https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=3&amp;btime=2014+11+04+06:01:27&amp;etime=2014+11+05+06:01:27&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd</a> <a href="https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=4&amp;btime=2014+07+14+10:01:45&amp;etime=2014+07+15+10:01:45&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd" rel="nofollow noreferrer">https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=4&amp;btime=2014+07+14+10:01:45&amp;etime=2014+07+15+10:01:45&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd</a> <a href="https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=5&amp;btime=2014+07+04+20:17:01&amp;etime=2014+07+05+20:17:01&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd" rel="nofollow noreferrer">https://irsa.ipac.caltech.edu/cgi-bin/Gator/nph-query?outfmt=1&amp;searchForm=MO&amp;spatial=cone&amp;catalog=neowiser_p1bs_psd&amp;moradius=5&amp;mobj=smo&amp;mobjstr=5&amp;btime=2014+07+04+20:17:01&amp;etime=2014+07+05+20:17:01&amp;selcols=w1mpro,w1sigmpro,w1snr,w1rchi2,w1flux,w1sigflux,w1sky,w1mag_2,w1sigm,mjd</a></p> <p>Here's my request code:</p> <pre><code>from astropy.io import fits from astropy.io import ascii as astro_ascii from astropy.time import Time def get_real_meta(url): df = astro_ascii.read(url) df=df.to_pandas() print(df) return df import multiprocessing as mp pool = mp.Pool(processes=10) results = pool.map(get_real_meta, urls) </code></pre> <p>When I run this, some of the results are failed requests.</p> <p>Why is this happening?</p> <p>This is the full result from the run:</p> <pre><code> col1 \ 0 [struct stat=&quot;ERROR&quot; col2 \ 0 msg=&quot;ERROR: Cannot process Moving Object Correctly. &quot; col3 0 logfile=&quot;https://irsa.ipac.caltech.edu:443/workspace/TMP_1YL1MV_20034/Gator/irsa/20034/log.20034.html&quot;] col1 \ 0 [struct stat=&quot;ERROR&quot; col2 \ 0 msg=&quot;ERROR: Cannot process Moving Object Correctly. &quot; col3 0 logfile=&quot;https://irsa.ipac.caltech.edu:443/workspace/TMP_gteaoW_20031/Gator/irsa/20031/log.20031.html&quot;] col1 \ 0 [struct stat=&quot;ERROR&quot; col2 \ 0 msg=&quot;ERROR: Cannot process Moving Object Correctly. &quot; col3 0 logfile=&quot;https://irsa.ipac.caltech.edu:443/workspace/TMP_yWl2vY_20037/Gator/irsa/20037/log.20037.html&quot;] cntr_u dist_x pang_x ra_u dec_u ra \ 0 1 2.338323 -43.660587 153.298036 13.719689 153.297574 1 2 1.047075 96.475058 153.337711 13.730126 153.338009 2 3 1.709365 -159.072115 153.377399 13.740497 153.377224 3 4 0.903435 84.145005 153.377439 13.740491 153.377696 4 5 0.800164 99.321042 153.397283 13.745653 153.397509 5 6 0.591963 16.330683 153.417180 13.750790 153.417228 6 7 0.642462 63.761302 153.437090 13.755910 153.437255 7 8 1.020182 -123.497531 153.457013 13.761012 153.456770 8 9 1.051963 130.842143 153.476909 13.766102 153.477137 9 11 1.007540 -55.156815 153.516820 13.776216 153.516583 10 12 0.607295 118.463910 153.556744 13.786265 153.556897 11 13 0.227240 -79.964079 153.556784 13.786259 153.556720 12 14 1.526454 -113.268004 153.596760 13.796237 153.596359 dec clon clat w1mpro w1sigmpro w1snr w1rchi2 \ 0 13.720159 10h13m11.42s 13d43m12.57s 7.282 0.014 78.4 307.90 1 13.730093 10h13m21.12s 13d43m48.34s 6.925 0.018 59.8 82.35 2 13.740054 10h13m30.53s 13d44m24.19s 6.354 0.012 91.3 203.90 3 13.740517 10h13m30.65s 13d44m25.86s 6.862 0.015 70.3 61.03 4 13.745617 10h13m35.40s 13d44m44.22s 7.005 0.016 68.0 62.28 5 13.750948 10h13m40.13s 13d45m03.41s 6.749 0.015 70.4 26.35 6 13.755989 10h13m44.94s 13d45m21.56s 7.031 0.019 57.5 37.56 7 13.760856 10h13m49.62s 13d45m39.08s 6.729 0.013 84.9 66.91 8 13.765911 10h13m54.51s 13d45m57.28s 6.944 0.022 49.0 44.22 9 13.776376 10h14m03.98s 13d46m34.95s 7.049 0.022 49.1 20.63 10 13.786185 10h14m13.66s 13d47m10.26s 6.728 0.018 58.9 14.40 11 13.786270 10h14m13.61s 13d47m10.57s 6.773 0.024 45.3 10.65 12 13.796069 10h14m23.13s 13d47m45.85s 7.126 0.015 72.2 219.50 w1flux w1sigflux w1sky w1mag_2 w1sigm mjd 0 248830.0 3173.5 24.057 7.719 0.013 56795.965297 1 345700.0 5780.5 27.888 8.348 0.006 56796.096965 2 584870.0 6406.8 24.889 7.986 0.006 56796.228504 3 366210.0 5206.7 27.876 7.653 0.006 56796.228632 4 321210.0 4725.7 26.150 7.867 0.009 56796.294338 5 406400.0 5771.4 25.240 7.711 0.006 56796.360172 6 313360.0 5449.7 26.049 7.988 0.006 56796.426005 7 414100.0 4877.9 25.581 8.022 0.006 56796.491839 8 339610.0 6935.9 25.564 8.029 0.007 56796.557545 9 308370.0 6285.2 25.491 8.331 0.006 56796.689212 10 414410.0 7035.5 27.656 7.851 0.007 56796.820752 11 397500.0 8773.4 27.628 8.015 0.006 56796.820880 12 287270.0 3980.2 24.825 8.310 0.006 56796.952419 cntr_u dist_x pang_x ra_u dec_u ra dec \ 0 1 0.570817 137.605512 128.754979 4.242103 128.755086 4.241986 1 2 0.852021 14.819525 128.791578 4.225474 128.791639 4.225703 2 3 1.099000 -4.816139 128.828083 4.208860 128.828057 4.209164 3 4 1.207022 9.485091 128.864456 4.192260 128.864511 4.192591 4 5 0.323112 107.976317 128.882608 4.183966 128.882694 4.183938 5 6 0.627727 99.373708 128.882645 4.183967 128.882817 4.183939 6 7 0.489166 19.732971 128.900773 4.175676 128.900819 4.175804 7 8 0.231292 -139.425350 128.918877 4.167389 128.918835 4.167340 8 9 0.393206 -28.705753 128.936958 4.159106 128.936905 4.159202 9 10 0.466548 -35.199460 128.936995 4.159107 128.936920 4.159213 10 11 1.153921 -100.879703 128.955053 4.150828 128.954737 4.150767 11 12 1.078232 -38.005043 128.973087 4.142552 128.972902 4.142788 12 13 1.172329 -27.290606 128.991097 4.134280 128.990947 4.134569 13 15 1.399220 54.717544 129.027083 4.117750 129.027401 4.117974 clon clat w1mpro w1sigmpro w1snr w1rchi2 w1flux \ 0 08h35m01.22s 04d14m31.15s 6.768 0.018 58.9 60.490 395130.0 1 08h35m09.99s 04d13m32.53s 6.706 0.018 59.1 30.780 418160.0 2 08h35m18.73s 04d12m32.99s 6.754 0.024 45.4 20.520 400280.0 3 08h35m27.48s 04d11m33.33s 6.667 0.024 44.9 34.090 433390.0 4 08h35m31.85s 04d11m02.18s 6.782 0.023 47.8 9.326 389870.0 5 08h35m31.88s 04d11m02.18s 6.710 0.035 31.4 11.360 416570.0 6 08h35m36.20s 04d10m32.89s 6.880 0.021 52.7 7.781 356410.0 7 08h35m40.52s 04d10m02.42s 6.653 0.023 46.8 18.900 439130.0 8 08h35m44.86s 04d09m33.13s 6.986 0.023 47.2 8.576 323350.0 9 08h35m44.86s 04d09m33.17s 6.917 0.019 58.5 25.720 344400.0 10 08h35m49.14s 04d09m02.76s 6.782 0.015 70.1 173.800 390170.0 11 08h35m53.50s 04d08m34.04s 6.671 0.016 69.6 70.490 431820.0 12 08h35m57.83s 04d08m04.45s 7.152 0.016 66.6 131.100 277440.0 13 08h36m06.58s 04d07m04.71s 6.436 0.017 63.3 86.350 536630.0 w1sigflux w1sky w1mag_2 w1sigm mjd 0 6711.7 21.115 7.988 0.008 56965.251016 1 7070.1 23.748 7.830 0.007 56965.382556 2 8812.6 20.930 8.456 0.007 56965.514096 3 9649.6 21.350 8.120 0.008 56965.645509 4 8161.1 19.988 7.686 0.007 56965.711215 5 13264.0 22.180 7.902 0.016 56965.711343 6 6769.0 22.962 8.023 0.008 56965.777049 7 9382.2 22.355 8.030 0.007 56965.842755 8 6847.6 23.531 8.024 0.007 56965.908462 9 5882.5 21.256 7.654 0.007 56965.908589 10 5568.7 21.926 8.051 0.007 56965.974295 11 6202.3 23.497 7.950 0.007 56966.040002 12 4165.8 20.094 8.091 0.010 56966.105708 13 8482.9 22.436 8.191 0.008 56966.237248 </code></pre>
<python><multithreading><python-requests><parallel-processing><multiprocessing>
2023-01-29 08:04:34
0
896
James Huang
75,273,413
17,696,880
How to prevent the capture groups of this regex from overlapping so that they cannot capture the substrings correctly?
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;En esta alejada ciudad por la tarde circulan muchos camiones con aquellos acoplados rojos, grandes y bastante pesados, llevándolos por esos trayectos bastante empedrados, polvorientos, y un tanto arenosos. Y incluso bastante desde lejos ya se les puede ver.&quot; #example string list_verbs_in_this_input = [&quot;serías&quot;, &quot;serían&quot;, &quot;sería&quot;, &quot;ser&quot;, &quot;es&quot;, &quot;llevándoles&quot;, &quot;llevándole&quot;, &quot;llevándolos&quot;, &quot;llevándolo&quot;, &quot;circularías&quot;, &quot;circularía&quot;, &quot;circulando&quot;, &quot;circulan&quot;, &quot;circula&quot;, &quot;consiste&quot;, &quot;consistían&quot;, &quot;consistía&quot;, &quot;consistió&quot;, &quot;visualizar&quot;, &quot;ver&quot;, &quot;empolvarle&quot;, &quot;empolvar&quot;, &quot;verías&quot;, &quot;vería&quot;, &quot;vieron&quot;, &quot;vió&quot;, &quot;vio&quot;, &quot;ver&quot;, &quot;podrías&quot; , &quot;podría&quot;, &quot;puede&quot;] exclude = rf&quot;(?!\b(?:{'|'.join(list_verbs_in_this_input)})\b)&quot; direct_subject_modifiers, noun_pattern = exclude + r&quot;\w+&quot; , exclude + r&quot;\w+&quot; modifier_connectors = r&quot;(?:(?:a[úu]n|todav[íi]a|incluso)\s+|)\s*(?:de|)\s*(?:gran|bastante\s*(?:m[áa]s|menos|)|(?:un\s*(?:tanto|poco)|)\s*(?:m[áa]s|menos)|)&quot; #its occurrence is optional #enumeration_of_noun_modifiers = direct_subject_modifiers + &quot;(?:&quot; + modifier_connectors + direct_subject_modifiers + &quot;){2,}&quot; enumeration_of_noun_modifiers = r&quot;(?:&quot; + &quot;(?:(?:,\s*|)y|,)\s*&quot; + modifier_connectors + r&quot;\s*&quot; + direct_subject_modifiers + r&quot;\s*&quot; + r&quot;)*&quot; #sentence_capture_pattern = r&quot;(?:aquellas|aquellos|aquella|aquel|los|las|el|la|esos|esas|este|ese|otros|otras|otro|otra)\s+&quot; + noun_pattern + r&quot;\s+&quot; + enumeration_of_noun_modifiers sentence_capture_pattern = r&quot;(?:aquellas|aquellos|aquella|aquel|los|las|el|la|esos|esas|este|ese|otros|otras|otro|otra)\s+&quot; + noun_pattern + r&quot;\s+&quot; + modifier_connectors + r&quot;\s+&quot; + direct_subject_modifiers + r&quot;\s+&quot; + r&quot;(?:&quot; + enumeration_of_noun_modifiers + r&quot;|)&quot; input_text = re.sub(sentence_capture_pattern, r&quot;((NOUN)'\g&lt;0&gt;')&quot;, input_text, flags=re.I|re.U) print(repr(input_text)) # --&gt; output </code></pre> <p>This pattern manages to make some captures only when in the pattern in <code>sentence_capture_pattern</code> change <code>r&quot;\s+&quot;</code> to <code>r&quot;\s*&quot;</code>. I think it's a problem where the substrings that the capturing groups should capture &quot;overlap&quot;, although I'm not sure how to avoid that.</p> <p>The mechanism that the capture groups must follow to assign the identified information should be the following:</p> <p><a href="https://i.sstatic.net/fTvna.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fTvna.png" alt="enter image description here" /></a></p> <p>Note that what should always capture the pattern stored in the <code>modifier_connectors</code> variable is totally optional, since it may or may not appear.</p> <p>In this case, this type of coincidence occurs 2 times, although it could occur more, so it performs 2 information reorganizations. So you get this <strong>correct output</strong> string:</p> <pre><code>&quot;En esta alejada ciudad por la tarde circulan muchos camiones con ((NOUN)'aquellos acoplados rojos, grandes y bastante pesados'), llevándolos por ((NOUN)'esos trayectos bastante empedrados, polvorientos, y un tanto arenosos'). Y incluso bastante desde lejos ya se les puede ver.&quot; </code></pre>
<python><regex>
2023-01-29 08:03:01
0
875
Matt095
75,272,945
14,037,055
How can i convert images into grayscale?
<p>I have 1000 of images. Now I like to convert those images into grayscale?</p> <pre><code>import tensorflow as tf from tensorflow.keras.utils import img_to_array #df['image_name'] = df['image_name'].apply(str) df_image = [] for i in tqdm(range(df.shape[0])): img = image.load_img('/content/drive/MyDrive/Predict DF from Image of Chemical Structure/2D image/'+df['image_name'][i]+'.png',target_size=(100,100,3)) img = image.img_to_array(img) img = img/255 df_image.append(img) X = np.array(df_image) </code></pre>
<python><tensorflow><image-processing><conv-neural-network><grayscale>
2023-01-29 06:13:48
1
469
Pranab
75,272,857
3,247,006
Cannot reduce "SELECT" queries with "select_related()" and "prefetch_related()" in one-to-one relationship in Django
<p>I have <code>Person</code> and <code>PersonDetail</code> models in <strong>one-to-one relationship</strong> as shown below. *I use <strong>Django 3.2.16</strong>:</p> <pre class="lang-py prettyprint-override"><code>class Person(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class PersonDetail(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE) # Here age = models.IntegerField() gender = models.CharField(max_length=20) def __str__(self): return str(self.age) + &quot; &quot; + self.gender </code></pre> <p>Then, I have 5 objects for <code>Person</code> and <code>PersonDetail</code> models each:</p> <p><a href="https://i.sstatic.net/F5GE4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/F5GE4.png" alt="enter image description here" /></a></p> <p><a href="https://i.sstatic.net/T7QAw.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/T7QAw.png" alt="enter image description here" /></a></p> <p>Then, I iterate <code>PersonDetail</code> model from <code>Person</code> model as shown below:</p> <pre class="lang-py prettyprint-override"><code>for obj in Person.objects.all(): print(obj.persondetail) </code></pre> <p>Or, I iterate <code>PersonDetail</code> model from <code>Person</code> model with <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.select_related" rel="nofollow noreferrer">select_related()</a> as shown below:</p> <pre class="lang-py prettyprint-override"><code>for obj in Person.objects.select_related().all(): print(obj.persondetail) </code></pre> <p>Or, I iterate <code>PersonDetail</code> model from <code>Person</code> model with <a href="https://docs.djangoproject.com/en/4.0/ref/models/querysets/#prefetch-related" rel="nofollow noreferrer">prefetch_related()</a> as shown below:</p> <pre class="lang-py prettyprint-override"><code>for obj in Person.objects.prefetch_related().all(): print(obj.persondetail) </code></pre> <p>Then, these below are outputted on console:</p> <pre class="lang-none prettyprint-override"><code>32 Male 26 Female 18 Male 27 Female 57 Male </code></pre> <p>Then, 6 <code>SELECT</code> queries are run as shown below for all 3 cases of the code above. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see <a href="https://stackoverflow.com/questions/722221/how-to-log-postgresql-queries#answer-75031321">my answer</a> explaining how to enable and disable the query logs on PostgreSQL:</p> <p><a href="https://i.sstatic.net/ZpNCo.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZpNCo.png" alt="enter image description here" /></a></p> <p>So, I cannot reduce 5 <code>SELECT</code> queries with <code>select_related()</code> and <code>prefetch_related()</code> in <strong>one-to-one relationship</strong> in Django.</p> <p>So, is it impossible to reduce <code>SELECT</code> queries with <code>select_related()</code> and <code>prefetch_related()</code> in one-to-one relationship in Django?</p>
<python><django><django-models><django-select-related><django-prefetch-related>
2023-01-29 05:48:46
1
42,516
Super Kai - Kazuya Ito
75,272,803
6,025,866
Error when importing tensorflow even when tensorflow is installed on MacOS M1 Pro
<p>I am getting the following error after I have installed tensorflow using conda. The error is as follows</p> <pre><code> Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/lib/python3.10/site-packages/tensorflow/__init__.py&quot;, line 440, in &lt;module&gt; _ll.load_library(_plugin_dir) File &quot;/opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/lib/python3.10/site-packages/tensorflow/python/framework/load_library.py&quot;, line 151, in load_library py_tf.TF_LoadLibrary(lib) tensorflow.python.framework.errors_impl.NotFoundError: dlopen(/opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/lib/python3.10/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): Symbol not found: _OBJC_CLASS_$_MPSGraphRandomOpDescriptor Referenced from: /opt/homebrew/Caskroom/miniforge/base/envs/tensorflow/lib/python3.10/site-packages/tensorflow-plugins/libmetal_plugin.dylib Expected in: /System/Library/Frameworks/MetalPerformanceShadersGraph.framework/Versions/A/MetalPerformanceShadersGraph </code></pre> <p>I used the installation guide presented in the link attached which caters to the installation process for MacOS -&gt; <a href="https://github.com/jeffheaton/t81_558_deep_learning/blob/master/install/tensorflow-install-mac-metal-jan-2023.ipynb" rel="nofollow noreferrer">https://github.com/jeffheaton/t81_558_deep_learning/blob/master/install/tensorflow-install-mac-metal-jan-2023.ipynb</a> and created a separate conda environment where I did the library installations. <strong>This error is displayed in the same environment</strong></p> <p>When using the command <code>conda list</code>, I was able to see the tensorflow libraries that have been installed as shown in the screenshot below. In spite of this, I am getting the above error. I also tried restarting my computer and it is throwing the same error.</p> <p>My system is as follows</p> <ul> <li>Apple M1 Pro Chip</li> <li>MacOS Monterey</li> <li>Python version : 3.10.8</li> </ul> <p><a href="https://i.sstatic.net/bavR2.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bavR2.jpg" alt="enter image description here" /></a></p> <p>Please do let me know if I have to make any other changes/install any other software to make tensorflow work. Thank you in advance for your help!</p>
<python><tensorflow><keras>
2023-01-29 05:32:56
0
441
adhok
75,272,745
13,359,498
Grad Cam outputs for all the images are the same
<p>I am using grad cam to see which regions of the test images are most important for the prediction of <code>resnet50</code>. The output I got has some errors.</p> <p>Code Snippets:</p> <pre><code>from tensorflow.keras.models import Model import tensorflow as tf import numpy as np import cv2 class GradCAM: def __init__(self, model, classIdx, layerName=None): # store the model, the class index used to measure the class # activation map, and the layer to be used when visualizing # the class activation map self.model = model self.classIdx = classIdx self.layerName = layerName # if the layer name is None, attempt to automatically find # the target output layer if self.layerName is None: self.layerName = self.find_target_layer() def find_target_layer(self): # attempt to find the final convolutional layer in the network # by looping over the layers of the network in reverse order for layer in reversed(self.model.layers): # check to see if the layer has a 4D output if len(layer.output_shape) == 4: return layer.name # otherwise, we could not find a 4D layer so the GradCAM # algorithm cannot be applied raise ValueError(&quot;Could not find 4D layer. Cannot apply GradCAM.&quot;) def compute_heatmap(self, image, eps=1e-8): # construct our gradient model by supplying (1) the inputs # to our pre-trained model, (2) the output of the (presumably) # final 4D layer in the network, and (3) the output of the # softmax activations from the model gradModel = Model( inputs=[self.model.inputs], outputs=[self.model.get_layer(self.layerName).output, self.model.output]) # record operations for automatic differentiation with tf.GradientTape() as tape: # cast the image tensor to a float-32 data type, pass the # image through the gradient model, and grab the loss # associated with the specific class index inputs = tf.cast(image, tf.float32) (convOutputs, predictions) = gradModel(inputs) loss = predictions[:, tf.argmax(predictions[0])] # use automatic differentiation to compute the gradients grads = tape.gradient(loss, convOutputs) # compute the guided gradients castConvOutputs = tf.cast(convOutputs &gt; 0, &quot;float32&quot;) castGrads = tf.cast(grads &gt; 0, &quot;float32&quot;) guidedGrads = castConvOutputs * castGrads * grads # the convolution and guided gradients have a batch dimension # (which we don't need) so let's grab the volume itself and # discard the batch convOutputs = convOutputs[0] guidedGrads = guidedGrads[0] # compute the average of the gradient values, and using them # as weights, compute the ponderation of the filters with # respect to the weights weights = tf.reduce_mean(guidedGrads, axis=(0, 1)) cam = tf.reduce_sum(tf.multiply(weights, convOutputs), axis=-1) # grab the spatial dimensions of the input image and resize # the output class activation map to match the input image # dimensions (w, h) = (image.shape[2], image.shape[1]) heatmap = cv2.resize(cam.numpy(), (w, h)) # normalize the heatmap such that all values lie in the range # [0, 1], scale the resulting values to the range [0, 255], # and then convert to an unsigned 8-bit integer numer = heatmap - np.min(heatmap) denom = (heatmap.max() - heatmap.min()) + eps heatmap = numer / denom heatmap = (heatmap * 255).astype(&quot;uint8&quot;) # return the resulting heatmap to the calling function return heatmap def overlay_heatmap(self, heatmap, image, alpha=0.5, colormap=cv2.COLORMAP_VIRIDIS): # apply the supplied color map to the heatmap and then # overlay the heatmap on the input image heatmap = cv2.applyColorMap(heatmap, colormap) output = cv2.addWeighted(image, alpha, heatmap, 1 - alpha, 0) # return a 2-tuple of the color mapped heatmap and the output, # overlaid image return (heatmap, output) </code></pre> <p>Code Snippet for visualising heatmap:</p> <pre><code>import random num_images = 5 random_indices = random.sample(range(len(X_test)), num_images) for idx in random_indices: image = X_test[idx] #assuming the image array is the first element in the tuple # print(image) # image = cv2.resize(image, (224, 224)) image1 = image.astype('float32') / 255 image1 = np.expand_dims(image1, axis=0) preds = model.predict(image1) i = np.argmax(preds[0]) icam = GradCAM(model, i, 'conv5_block3_out') heatmap = icam.compute_heatmap(image1) heatmap = cv2.resize(heatmap, (224, 224)) (heatmap, output) = icam.overlay_heatmap(heatmap, image, alpha=0.5) fig, ax = plt.subplots(1, 3) ax[0].imshow(heatmap) ax[1].imshow(image) ax[2].imshow(output) </code></pre> <p>The output:</p> <p><a href="https://i.sstatic.net/KDI7z.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KDI7z.png" alt="enter image description here" /></a></p> <p>The problem I am facing is, here in the output you can see the original images are different but the heatmaps, images, and grad cam are the same for all the images. I don't know whats the reason behind this.</p>
<python><tensorflow><keras><conv-neural-network><visualization>
2023-01-29 05:15:53
1
578
Rezuana Haque
75,272,443
8,888,469
Issue while pattern replacement in column value in pandas dataframe
<p>I have a dataframe <code>new_df</code> as shown below .</p> <p>I have issue that my current code contain replace if numeric value or special character value comes after character value in column in dataframe like <code>70317380CH71</code> or <code>70317380CH%(</code></p> <p><strong>Current output Dataframe</strong></p> <pre><code>riskID locationCode locationCity locationCountryCode 70317380CH71 CH71 PRATTELN CH 70520366HONGKONGHK EU_LL1_H_HONG_KONG_HKG HONG KONG HK 70729363MIDDLETOWNUS US_06457_MAZ_000023 MIDDLETOWN US 70317380CH&amp;? CH&amp;? GALE CH </code></pre> <p><strong>Current Code</strong></p> <pre><code># find rows with value in country and city m1 = new_df[['locationCity', 'locationCountryCode']].notna().all(axis=1) # find rows with a &quot;_&quot; m2 = new_df['riskID'].str.contains('-|_', na=False) #m3= new_df['locationCode'].str.contains('_') # both conditions above m = m1&amp;m2 #n =m1&amp;m3 # replace matching rows by number + city + country new_df.loc[m, 'riskID'] = (new_df.loc[m, 'riskID'].str.extract('^(\d+)', expand=False) +new_df.loc[m, 'locationCity'].str.replace(' ', '')+new_df.loc[m, 'locationCountryCode']) </code></pre> <p><strong>Expected Output</strong></p> <pre><code>riskID locationCode locationCity locationCountryCode 70317380PRATTELNCH CH71 PRATTELN CH 70520366HONGKONGHK EU_LL1_H_HONG_KONG_HKG HONG KONG HK 70729363MIDDLETOWNUS US_06457_MAZ_000023 MIDDLETOWN US 70317380GALECH CH&amp;? GALE CH </code></pre> <p>How can this be done in pythin</p>
<python><pandas><regex><dataframe>
2023-01-29 03:26:46
1
933
aeapen
75,272,295
6,114,832
Shapely smoothing with dilate and erode
<p>I am trying to implement a polygon smoothing operation with shapely. I am doing this with the combination of erode and dilate (polygon.buffer function with positive and negative numbers). The specification of my smooth function goes something like this:</p> <ol> <li>The operation must be conservative. There must not be any part of the original shape that is not covered by the smoothed shape</li> <li>any protrusion must be preserved</li> <li>any concavity must be smoothed out</li> <li>Topology must be preserved</li> </ol> <p>dilate followed by erode solves this with shapely in cases where the topology does not change with the operation. See example code below.</p> <pre><code>from shapely.geometry import Polygon import numpy as np from descartes import PolygonPatch from matplotlib import pyplot as plt # create a large square x = np.array([-5,-5,5,5]) y = np.array([5,-5,-5,5]) poly1 = Polygon(zip(x,y)) # smaller square to cut away from first x = np.array([-4,-4,4,4]) y = np.array([4,-4,-4,4]) poly2 = Polygon(zip(x,y)) # small shape to cut away from left side x = np.array([-11,-11,0,0]) y = np.array([1,-1,0,0]) poly3 = Polygon(zip(x,y)) poly_t=poly1.difference(poly2) poly4 = poly_t.difference(poly3) poly5= poly4.buffer(0.45) poly5= poly5.buffer(-0.45) fig = plt.figure() ax = fig.add_subplot(121) plt.axis([-5.5, 5.5, -5.5, 5.5]) patch = PolygonPatch(poly5) ax.add_patch(patch) plt.show() </code></pre> <p>Visualized below is the before and after smoothing operation applied. the change of topology of the dilate operation is the cause of the unintended behaviour. Shapely polygons can be in a state where they are self intersecting, where they are &quot;invalid&quot; in some sence. I would like this to be the case for the intermediate polygon (the one where dilate has been applied, awaiting the erode). However, it seems the buffer function in shapely has no such feature.</p> <p>Do you have a suggestion on how to solve this problem with Shapely still being the geometry engine? worst case, a solution with another framework.</p> <p><a href="https://i.sstatic.net/yOn9R.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yOn9R.png" alt="before and after" /></a></p>
<python><polygon><shapely><mathematical-morphology>
2023-01-29 02:41:09
1
1,117
Stefan Karlsson
75,272,189
2,392,151
Python pandas dataframe ne method issue
<p>I have 2 dataframes like</p> <p>here is the original data: dataframe:1</p> <pre><code> coverage_level_identifier data_status_code last_change_date last_change_user_name creation_date creation_user_name minimum_coverage_level_percentage erp_factor 0 1 I 2022-05-10 07:37:49.997 28200310169021034302-Admin 2022-04-12 14:05:36.897 Initial Load 0.50 0.200 1 2 A 2022-05-10 07:37:41.320 28200310169021034302-Admin 2022-04-12 14:05:36.897 Initial Load 0.55 0.250 2 3 A 2022-05-09 16:14:58.997 28200310160021016916-Admin 2022-04-12 14:05:36.897 Initial Load 0.60 0.825 3 4 A 2022-05-09 14:29:20.603 28200310169021034302-Admin 2022-04-12 14:05:36.897 Initial Load 0.65 0.850 </code></pre> <p>dataframe 2:</p> <pre><code> coverage_level_identifier data_status_code last_change_date last_change_user_name creation_date creation_user_name minimum_coverage_level_percentage erp_factor 0 1 I 2022-05-10 07:37:49.997 28200310169021034302-Admin 2022-04-12 14:05:36.897 Initial Load 0.50 0.200 1 2 A 2022-05-10 07:37:41.320 28200310169021034302-Admin 2022-04-12 14:05:36.897 Initial Load 0.55 0.250 2 3 A 2022-05-09 16:14:58.997 28200310160021016916-Admin 2022-04-12 14:05:36.897 Initial Load 0.60 0.825 3 4 A 2022-05-09 14:29:20.603 28200310169021034302-Admin 2022-04-12 14:05:36.897 Initial Load 0.65 0.850 </code></pre> <p>this code returns</p> <pre><code>neDF=dataframe1.drop_duplicates(keep=&quot;first&quot;).reset_index(drop=True).ne(dataframe2.drop_duplicates(keep=&quot;first&quot;).reset_index(drop=True), axis=1) </code></pre> <p>neDF:</p> <pre><code> coverage_level_identifier data_status_code last_change_date last_change_user_name creation_date creation_user_name minimum_coverage_level_percentage erp_factor 0 False False False False False False False False 1 False False False False False False False False 2 False False False False False False False True 3 False False False False False False False False </code></pre> <p>why is there a TRUE in erp_factor column after &quot;ne&quot; ?, not sure where anything is wrong, Please advice</p>
<python><pandas>
2023-01-29 02:04:38
0
363
Bill
75,272,097
5,551,722
Set z-order of Edges in Pandas Dataframe
<p>I'm using OSMnx to create some plots of road networks with data shown by colour, below is an example which produces an image with colour showing betweenness centrality. The problem I'm having is that, due to the zordering, some of the lighter regions are covered by other edges, especially around junctions with lots of nodes.</p> <p>The <code>OSMnx.plot_graph</code> method calls <code>gdf.plot</code> from GeoPandas, which in turn uses <code>PlotAccessor</code> from Pandas. I've been reading the OSMnx documentation, and can't seem to find a way to pass a z-ordering, so my question is: is there a way I can directly plot the graph, either with GeoPandas, pandas, or even matplotlib directly, such that I can specify a z-ordering of the edges?</p> <pre class="lang-py prettyprint-override"><code>import networkx as nx import osmnx as ox place = 'Hornsea' G = ox.graph_from_place(place, network_type=&quot;drive&quot;) # Digraph removes parallel edges # Line graph swaps nodes and edges line_graph = nx.line_graph(ox.get_digraph(G)) betweenness_centrality = nx.betweenness_centrality(line_graph, weight='travel_time') for edge in G.edges: if edge not in betweenness_centrality: nx.set_edge_attributes(G, {edge: 0}, 'betweenness_centrality') betweenness_centrality = {(k[0], k[1], 0): v for k, v in betweenness_centrality.items()} nx.set_edge_attributes(G, betweenness_centrality, &quot;betweenness_centrality&quot;) ec = ox.plot.get_edge_colors_by_attr(G, 'betweenness_centrality', cmap='plasma') # &quot;RdYlGn_r&quot; ew = [G.get_edge_data(*edge).get('betweenness_centrality', 0) * 10 + 0.25 for edge in G.edges] fig, ax = ox.plot_graph(G, edge_color=ec, edge_linewidth=ew, node_size=0) fig.savefig(f&quot;images/{place}_betweenness_centrality.png&quot;, facecolor=&quot;w&quot;, dpi=1000, bbox_inches=&quot;tight&quot;) </code></pre> <p><a href="https://i.sstatic.net/6MkzC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6MkzC.png" alt="hornsea_betweenness_centrality.png" /></a></p>
<python><pandas><matplotlib><networkx><osmnx>
2023-01-29 01:39:19
2
673
George Willcox
75,272,008
14,593,213
No performance bonus using multithreading with pytube
<p>I am using the pytube library to retrieve stream information for a list of YouTube videos. I have implemented the retrieval of streams using a simple loop, as well as using the concurrent.futures and multiprocessing libraries for multithreading. However, I am not seeing the performance boost I was expecting and all methods take around 130 seconds to run.</p> <p>The code I am using is as follows:</p> <pre><code>def _get_streams(self, yt: pytube.YouTube): return yt.streams @print_execution_time def get_streams_futures(self): with concurrent.futures.ThreadPoolExecutor() as executor: future_results = [executor.submit(self._get_streams, yt) for yt in self._create_yt_obj()] result = [future.result() for future in concurrent.futures.as_completed(future_results)] return result @print_execution_time def get_streams_linear(self): return [yt.streams for yt in self._create_yt_obj()] @print_execution_time def get_streams_multiprocessing(self): with multiprocessing.Pool() as pool: result = pool.map(self._get_streams, self._create_yt_obj()) return result </code></pre> <p><code>@print_execution_time</code> is a simple decorator to calculate the run time of the function</p> <p>I expected the multithreading methods to run much faster than the loop method, but this is not the case. Can anyone explain why this is happening and what can be done to achieve the desired performance boost?</p> <p>There are no errors being raised</p>
<python><multithreading><python-multithreading><concurrent.futures><pytube>
2023-01-29 01:05:45
0
355
Davi A. Sampaio
75,271,947
583,044
Version number in pyinstaller and application
<p>I have an application that I want to include some version information within, and only have it defined in one location. I am running on Windows, so want to set the executable version resource, and am using pyinstaller to build the executable, but also want to be able to access the version infomration within the application itself.</p> <p>So far I have followed the same kind of path that I could achieve in C - create a header with the values, include that header in both the application code and resource script, and then be able use use the single definition from the preprocessor symbol. I thought I could do something similar in python.</p> <p>So far I have created a version_info.py file with the values for the version numbers:</p> <pre><code>MYAPPLICATION_VERSION_MAJOR = 4 MYAPPLICATION_VERSION_MINOR = 2 MYAPPLICATION_VERSION_PATCH = 0 MYAPPLICATION_VERSION_BUILD = 0 </code></pre> <p>I can then include that in my application source code no problem (cut down for brevity as this is not the issue):</p> <pre><code>import version_info print(f'{version_info.MYAPPLICATION_VERSION_MAJOR}.{version_info.MYAPPLICATION_VERSION_MINOR}.{version_info.MYAPPLICATION_VERSION_PATCH}') </code></pre> <p>I can use a 'file_version_info' type file with hardcoded values and it works OK to include the Windows version resource.</p> <pre><code># UTF-8 # # For more details about fixed file info 'ffi' see: # http://msdn.microsoft.com/en-us/library/ms646997.aspx VSVersionInfo( ffi=FixedFileInfo( # filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4) # Set not needed items to zero 0. filevers=(1, 2, 0, 0), prodvers=(1, 2, 0, 0), # Contains a bitmask that specifies the valid bits 'flags'r mask=0x3f, # Contains a bitmask that specifies the Boolean attributes of the file. flags=0x0, # The operating system for which this file was designed. # 0x4 - NT and there is no need to change it. OS=0x4, # The general type of file. # 0x1 - the file is an application. fileType=0x1, # The function of the file. # 0x0 - the function is not defined for this fileType subtype=0x0, # Creation date and time stamp. date=(0, 0) ), kids=[ StringFileInfo( [ StringTable( '080904b0', # 0809 = en-GB, 04b0 = Unicode [StringStruct('CompanyName', 'My company'), StringStruct('FileDescription', 'Application file description.'), StringStruct('FileVersion', '1.2.0.0'), StringStruct('InternalName', 'MyApplication.exe'), StringStruct('LegalCopyright', 'Copyright (C) 2021-2023 My Company, All rights reserved.'), StringStruct('OriginalFilename', 'MyApplication.exe'), StringStruct('ProductName', 'My product'), StringStruct('ProductVersion', '1.2.0.0')]) ]), VarFileInfo([VarStruct('Translation', [0x0809, 1200])]) ] ) </code></pre> <p>I have a pyinstaller spec file for my application that pulls in a version information definition to set the Windows version details:</p> <pre><code># -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['MyApplication/main.py'], pathex=['MyApplication'], binaries=[], datas=[], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=['sqlite', 'tbb'], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) splash = Splash( 'splash.png', binaries=a.binaries, datas=a.datas, text_pos=None, text_size=12, minify_script=True, always_on_top=False, ) exe = EXE( pyz, a.scripts, splash, [], exclude_binaries=True, name='MyApplication', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=False, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, version='MyApplication/file_version_info.py', ) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, splash.binaries, strip=False, upx=True, upx_exclude=[], name='MyApplication', ) </code></pre> <p>The problem I have is when I try to use the version number definitions in the <code>file_version_info</code> file for the pyinstaller spec file. I cannot figure out how to include those definitions and use them. I have tried variations of import, and found out that pyinstaller uses <code>eval()</code> for the version information so the closest I got was:</p> <pre><code># UTF-8 # # For more details about fixed file info 'ffi' see: # http://msdn.microsoft.com/en-us/library/ms646997.aspx exec(&quot;import version_info&quot;) VSVersionInfo( ffi=FixedFileInfo( # filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4) # Set not needed items to zero 0. filevers=(1, 2, 0, 0), prodvers=(1, 2, 0, 0), # Contains a bitmask that specifies the valid bits 'flags'r mask=0x3f, # Contains a bitmask that specifies the Boolean attributes of the file. flags=0x0, # The operating system for which this file was designed. # 0x4 - NT and there is no need to change it. OS=0x4, # The general type of file. # 0x1 - the file is an application. fileType=0x1, # The function of the file. # 0x0 - the function is not defined for this fileType subtype=0x0, # Creation date and time stamp. date=(0, 0) ), kids=[ StringFileInfo( [ StringTable( '080904b0', # 0809 = en-GB, 04b0 = Unicode [StringStruct('CompanyName', 'My company'), StringStruct('FileDescription', 'Application file description.'), StringStruct('FileVersion', '1.2.0.0'), StringStruct('InternalName', 'MyApplication.exe'), StringStruct('LegalCopyright', 'Copyright (C) 2021-2023 My Company, All rights reserved.'), StringStruct('OriginalFilename', 'MyApplication.exe'), StringStruct('ProductName', 'My product'), StringStruct('ProductVersion', '1.2.0.0')]) ]), VarFileInfo([VarStruct('Translation', [0x0809, 1200])]) ] ) </code></pre> <p>But in this case I ultimately get the error:</p> <pre><code> File &quot;&lt;string&gt;&quot;, line 8 VSVersionInfo( ^^^^^^^^^^^^^ SyntaxError: invalid syntax </code></pre> <p>Which seems odd to me because I can perform an <code>eval('exec(&quot;import version_info.py&quot;)')</code> on the command line and it is OK.</p> <p>So my question is: how do I define the version number in a single place that the python code and pyinstaller version resource can use that common definition.</p>
<python><version><pyinstaller>
2023-01-29 00:48:49
1
6,651
tinman
75,271,720
9,576,988
Sorting enumerated elements in a list using another list as an order
<p>I have a master list:</p> <pre class="lang-py prettyprint-override"><code>l = ['gala_apple', 'gala_lime', 'fuji_apple', 'fuji_lime'] </code></pre> <p>Through some manipulation, I end up with a variant of <code>l</code>:</p> <pre class="lang-py prettyprint-override"><code>r = [ 'fuji_apple_1', 'fuji_apple_2', 'fuji_lime_1', 'fuji_lime_2', 'gala_apple_1', 'gala_apple_2', 'gala_apple_3', 'gala_lime_1', 'gala_lime_2', 'gala_lime_3', ] </code></pre> <p>Using the master list <code>l</code> as a reference, I want the list <code>r</code> to be ordered like:</p> <pre class="lang-py prettyprint-override"><code>r = [ 'gala_apple_1', 'gala_lime_1', 'gala_apple_2', 'gala_lime_2', 'gala_apple_3', 'gala_lime_3', 'fuji_apple_1', 'fuji_lime_1', 'fuji_apple_2', 'fuji_lime_2', ] </code></pre> <p>I.e. <code>(gala_apple_X, gala_lime_X, gala_apple_Y, gala_lime_Y, ...), (fuji_apple_X, fuji_lime_X, fuji_apple_Y, fuji_lime_Y, ...)</code></p>
<python><list><sorting>
2023-01-28 23:53:47
2
594
scrollout
75,271,606
1,380,285
How do I display matplotlib.pyplot plots from a remote Ubuntu platform on a local Windows machine?
<p>There are alot of similar questions and answers to this one on this site. But nothing that I find is working. If I try the default backend, I get an error when I load <code>matplotlib.pyplot</code> to the effect that there is no <code>_tkinter</code> module. I'm told to solve this by installing <code>python-tk</code>, but <code>pip</code> would not install it because &quot; <code>Could not find a version that satisfies the requirement python-tk. No matching distribution found for python-tk</code>&quot; (Really?) If I try the <code>&quot;agg&quot;</code> backend (<code>matplotlib.use('agg')</code>) everything looks fine until I try to display a plot, and nothing shows up -- no error message at all, just no display. I have tried the <code>GTK</code> backend and am told that I have to install the <code>pygtk</code> package. But <code>pip</code> won't install it in Ubuntu because &quot;<code>Building PyGTK using distutils is only supported on windows</code>.&quot; I read somewhere about the <code>nbagg</code> backend, but it looks like it is going to need <code>IPython.display</code>, which <code>pip</code> won't install because, again, it can't find a version that satisfies .... Is it really so hard to get <code>matplotlib</code> and <code>pyplot</code> working on a remote Ubuntu platform? Anyone know what I can do?</p> <p>UPDATE: Am working with Ubuntu 18.04.6 and python 2.7. I don't believe I will be able to change either one.</p>
<python><matplotlib><ubuntu><backend>
2023-01-28 23:24:36
0
6,713
bob.sacamento
75,271,441
12,242,085
How to make loop with features selection by features importance where deleted features with imp = 0 or below mean imp in each iteration in Python?
<p>I have DataFrame in Python Pandas like below:</p> <p><strong>Input data:</strong></p> <ul> <li>Y - binary target</li> <li>X1...X5 - predictors</li> </ul> <p><strong>Source code of DataFrame:</strong></p> <pre><code>import pandas as pd import numpy as np from xgboost import XGBClassifier df = pd.DataFrame() df[&quot;Y&quot;] = [1,0,1,0] df[&quot;X1&quot;] = [111,12,150,270] df[&quot;X2&quot;] = [22,33,44,55] df[&quot;X3&quot;] = [1,1,0,0] df[&quot;X4&quot;] = [0,0,0,1] df[&quot;X5&quot;] = [150, 222,230,500] Y | X1 | X2 | X3 | X4 | X5 | ... | Xn ----|-----|-----|-------|-------|-----|------|------- 1 | 111 | 22 | 1 | 0 | 150 | ... | ... 0 | 12 | 33 | 1 | 0 | 222 | ... | ... 1 | 150 | 44 | 0 | 0 | 230 | ... | ... 0 | 270 | 55 | 0 | 1 | 500 | ... | ... </code></pre> <p>And I make features selection by deleting features with importance = 0 in each iteration or if the are not features with imporance = 0 I delete features with importance below mean importance in that iteraton:</p> <p><strong>First iteration:</strong></p> <pre><code>model_importance = XGBClassifier() model_importance.fit(X = df.drop(labels=[&quot;Y&quot;], axis=1), y = df[&quot;Y&quot;]) importances = pd.DataFrame({&quot;Feature&quot;:df.drop(labels=[&quot;Y&quot;], axis=1).columns, &quot;Importance&quot;:model_importance.feature_importances_}) importances_to_drop_1 = importances[importances[&quot;Importance&quot;]==0].index.tolist() df.drop(columns = importances_to_drop_1, axis = 1, inplace = True) </code></pre> <p><strong>Second iteration:</strong></p> <pre><code>model_importance_2 = XGBClassifier() model_importance_2.fit(X = df.drop(labels=[&quot;Y&quot;], axis=1), y = df[&quot;Y&quot;]) importances_2 = pd.DataFrame({&quot;Feature&quot;:df.drop(labels=[&quot;Y&quot;], axis=1).columns, &quot;Importance&quot;:model_importance_2.feature_importances_}) importances_to_drop_2 = importances_2[importances_2[&quot;Importance&quot;]&lt;importances_2.Importance.mean()].index.tolist() df.drop(columns = importances_to_drop_2, axis = 1, inplace = True) </code></pre> <p><strong>Requirements:</strong></p> <ul> <li>I need to create loop where in each iteration will be deleted features with importance = 0 or if there are not features with importance = 0 is some iteration delete features with importance below mean importance in that iteration</li> <li>At the end I need to have at least 150 features</li> <li>I need that in one loop (one segment of code) not like now in a few segments of code</li> </ul> <p>How can I do that in Python ?</p>
<python><loops><for-loop><machine-learning><feature-selection>
2023-01-28 22:47:52
1
2,350
dingaro
75,271,424
215,761
Select / browse to a file / folder from a cgi (python) form invoking the system dialog (a Finder on Mac)
<p>I am trying to implement (in Python) something like a browser's &quot;File/Open...&quot; or &quot;Select to upload&quot; functionality:</p> <p>that is, - with help of a system dialog (specifically Finder on MAC), - browse to a file / a folder, select it, press a button and get the file/folder name (path) back into my cgi script. Or into any script / python function.</p> <p>I was hoping that something as simple as using a subprocess with /usr/bin/open should do the job.</p> <p>However, if I invoke /usr/bin/open, it only ~shows~ the contents of the file system, there is no button to &quot;select and return back the path&quot;.</p> <p>So how do they (Google, Mozilla, Smugmug...) do it? Am I asking for too much?</p> <p>Thank you! (Sorry if this question looks ridiculous, but strangely enough Google search did not help).</p>
<python><cgi><finder>
2023-01-28 22:43:54
0
320
Vlad K.
75,271,373
1,019,129
Normalize vectors in the complex space : mean=0 and std-dev=1/sqrt(n)
<p>I have a Vector Or bunch of vectors (stored in 2D array, by rows)</p> <p>The vectors are generated as :</p> <blockquote> <p>MEAN=0, STD-DEV=1/SQRT(vec_len)</p> </blockquote> <p>and before or after operations have to be normalized in the same form</p> <p>I want to normalize them in the complex space. Here is the wrapper of a function:</p> <pre><code>@staticmethod def fft_normalize(x, dim=DEF_DIM): cx = rfft(x, dim=dim) .... rv = irfft(cx_proj, dim=dim) return rv </code></pre> <p><strong>help me fill the dots.</strong></p> <p>Here is the real-value normalization that I use.</p> <pre><code>@staticmethod def normalize(a, dim=DEF_DIM): norm=torch.linalg.norm(a,dim=dim) # if torch.eq(norm,0) : return torch.divide(a,st.MIN) if dim is not None : norm = norm.unsqueeze(dim) return torch.divide(a,norm) </code></pre> <hr /> <pre><code>In [70]: st.normalize(x + 3) Out[70]: ([[0.05, 0.04, 0.05, ..., 0.04, 0.04, 0.04], [0.04, 0.04, 0.05, ..., 0.05, 0.04, 0.05], [0.05, 0.04, 0.05, ..., 0.04, 0.05, 0.04]]) In [71]: st.normalize(x + 5) Out[71]: ([[0.05, 0.04, 0.05, ..., 0.04, 0.04, 0.04], [0.04, 0.04, 0.05, ..., 0.05, 0.04, 0.04], [0.05, 0.04, 0.04, ..., 0.04, 0.05, 0.04]]) In [73]: st.normalize(x + 5).len() Out[73]: ([1.00, 1.00, 1.00]) In [74]: st.normalize(x + 3).len() Out[74]: ([1., 1., 1.]) In [75]: st.normalize(x).len() Out[75]: ([1.00, 1.00, 1.00]) #bad, need normalization In [76]: (x + 3).len() Out[76]: ([67.13, 67.13, 67.13]) @staticmethod def len(a,dim=DEF_DIM): return torch.linalg.norm(a,dim=dim) </code></pre> <hr /> <p>I did not want to post this so not to influence possible better solution.. So here is one my attempts .. parts I borrowed from what I found.</p> <p>This only works for 1D vectors ;(</p> <pre><code>@staticmethod def fft_normalize(x, dim=DEF_DIM):# Normalize a vector x in complex domain. c = rfft(x,dim=dim) ri = torch.vstack([c.real, c.imag]) norm = torch.abs(c) print(norm.shape, ri.shape) # norm = torch.linalg.norm(ri, dim=dim) # if dim is not None : norm = norm.unsqueeze(dim) if torch.any(torch.eq(norm,0)): norm[torch.eq(norm,0)] = st.MIN #!fixme ri= torch.divide(ri,norm) #2D fails here c_proj = ri[0,:] + 1j * ri[1,:] rv = irfft(c_proj, dim=dim) return rv </code></pre> <hr /> <p>adapted the solution of Thibault Cimic ... seems to work for 1D vectors, but not for 2D</p> <pre><code>@staticmethod def fft_normalize(x, dim=DEF_DIM, dot_dim=None):# Normalize a vector x in complex domain. c = rfftn(x,dim=dim) c_conj = torch.conj(c) if dot_dim is None : dot_dim = st.dot_dims(c, c_conj) c_norm = torch.sqrt(torch.tensordot(c, c_conj, dims=dot_dim)) c_proj = torch.divide(c, c_norm) rv = irfftn(c_proj, dim=dim) return rv </code></pre>
<python><fft><normalization><complex-numbers>
2023-01-28 22:35:04
1
7,536
sten
75,271,285
14,256,643
Fastapi how to convert string to list when calling get methos?
<p>I am using mysql database and it's doesn't support list if I stored sting like &quot;apple&quot;,&quot;banana&quot; in my mysql database then when using get method fastapi how to convert theme from string to list like [&quot;apple&quot;,&quot;banana&quot;]. I tried this but didn't work and also not getting the image fields until I remove @property.</p> <pre><code>class Shop_page(BaseModel): product_title: str product_image: str class Config(): orm_mode = True @property def product_image(self): return self.product_image.split(&quot;,&quot;) </code></pre> <p>here is my get method</p> <pre><code>@router.get(&quot;/shop_page&quot;, response_model=List[schemas.Shop_page],status_code=status.HTTP_200_OK) async def create_variations(db: Session = Depends(get_db)): parent_item = db.query(models.ParentProduct).all() return parent_item </code></pre> <p>my result look like now</p> <pre><code>[ { &quot;product_title&quot;: &quot;DEMO PRODUCT&quot;, &quot;product_image&quot;: &quot;image1_url,image2_url&quot; } ] </code></pre> <p>my expected result will be look like this</p> <pre><code>[ { &quot;product_title&quot;: &quot;DEMO PRODUCT&quot;, &quot;product_image&quot;: [&quot;image1_url,image2_url&quot;] } ] </code></pre>
<python><mysql><arrays><python-3.x><fastapi>
2023-01-28 22:15:10
2
1,647
boyenec
75,271,262
16,332,690
Converting timezone aware datetime column to string with UTC time offset
<p><strong>Update:</strong> This was fixed by <a href="https://github.com/pola-rs/polars/pull/6673" rel="nofollow noreferrer">pull/6673</a></p> <hr /> <p>I have the following dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = ( pl.DataFrame( { &quot;int&quot;: [1, 2, 3], &quot;date&quot;: [&quot;2010-01-31T23:00:00+00:00&quot;,&quot;2010-02-01T00:00:00+00:00&quot;,&quot;2010-02-01T01:00:00+00:00&quot;] } ) .with_columns( pl.col(&quot;date&quot;).str.to_datetime() .dt.convert_time_zone(&quot;Europe/Amsterdam&quot;) ) ) </code></pre> <p>which gives:</p> <pre><code>┌─────┬────────────────────────────────┐ │ int ┆ date │ │ --- ┆ --- │ │ i64 ┆ datetime[μs, Europe/Amsterdam] │ ╞═════╪════════════════════════════════╡ │ 1 ┆ 2010-02-01 00:00:00 CET │ │ 2 ┆ 2010-02-01 01:00:00 CET │ │ 3 ┆ 2010-02-01 02:00:00 CET │ └─────┴────────────────────────────────┘ </code></pre> <p>I would like to convert this datetime type to a string with a time zone designator, e.g. <code>2010-02-01 00:00:00+01:00</code></p> <p>I tried the following:</p> <pre class="lang-py prettyprint-override"><code>df.with_columns(pl.col(&quot;date&quot;).dt.to_string(&quot;%Y-%m-%d %H:%M:%S%z&quot;)) </code></pre> <p>which gives the following error:</p> <pre><code>pyo3_runtime.PanicException: a formatting trait implementation returned an error: Error </code></pre> <p>My desired output is stated below, which is what you get when you convert a datetime column to a string type in pandas with the <code>&quot;%Y-%m-%d %H:%M:%S%z&quot;</code> as the format:</p> <pre><code>┌─────┬──────────────────────────┐ │ int ┆ date │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪══════════════════════════╡ │ 1 ┆ 2010-02-01 00:00:00+0100 │ │ 2 ┆ 2010-02-01 01:00:00+0100 │ │ 3 ┆ 2010-02-01 02:00:00+0100 │ └─────┴──────────────────────────┘ </code></pre> <p>Is there any way to realize this result? Leaving out the <code>%z</code> at the end when specifying the format works but the UTC time offset is something I need.</p>
<python><datetime><timezone><strftime><python-polars>
2023-01-28 22:11:34
1
308
brokkoo
75,271,187
523,612
How can I fix a TypeError that says an operator (<, <=, >, >=) is not supported between x and y?
<p>I often see error messages that look like any of:</p> <pre><code>TypeError: '&lt;' not supported between instances of 'str' and 'int' </code></pre> <p>The message can vary quite a bit, and I guess that it has many causes; so rather than ask again every time for every little situation, I want to know: <strong>what approaches or techniques can I use to find the problem, when I see this error message</strong>? (I have already read <a href="https://stackoverflow.com/questions/73631401/">I&#39;m getting a TypeError. How do I fix it?</a>, but I'm looking for advice specific to the individual pattern of error messages I have identified.)</p> <p>So far, I have figured out that:</p> <ul> <li><p>the error will show some kind of operator (most commonly <code>&lt;</code>; sometimes <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code> or <code>+</code>) is &quot;not supported between instances of&quot;, and then two type names (could be any types, but usually they are not the same).</p> </li> <li><p>The highlighted code will almost always have that operator in it somewhere, but the version with <code>&lt;</code> can also show up if I am trying to sort something. (Why?)</p> </li> </ul>
<python><python-3.x><debugging><typeerror>
2023-01-28 21:57:37
1
61,352
Karl Knechtel
75,271,184
19,916,174
Space Complexity with no variables defined
<p>Suppose I had some code:</p> <pre class="lang-py prettyprint-override"><code>def foo(forest: list[list[int]]) -&gt; int: return sum([1 for tree in forest for leaf in tree]) </code></pre> <p>In this code, no variables are defined. Everything is evaluated in one line, which means to my knowledge the data isn't being stored anywhere. Does that mean this program has a space complexity of O(1)?</p> <p>Thanks for your time.</p>
<python><time-complexity><list-comprehension><nested-lists><space-complexity>
2023-01-28 21:57:20
1
344
Jason Grace
75,271,150
6,552,836
Apply a function to a dataframe which includes the previous row
<p>I have an input data frame for daily grocery spend which looks like this:</p> <p><code>input_df1</code></p> <pre><code>Date Potatoes Spinach Lettuce 01/01/22 10 47 0 02/01/22 0 22 3 03/01/22 11 0 3 04/01/22 3 9 2 ... </code></pre> <p>I need to apply a function that takes <code>input_df1 + (previous inflated_df2 row * inflation%)</code> to get <code>inflated_df2</code> (excepted for the first row - the first day of the month does not have any inflation effect, will just be the same as <code>input_df1</code>).</p> <p><code>inflated_df2</code></p> <pre><code>inflation% 0.01 0.05 0.03 Date Potatoes Spinach Lettuce 01/01/22 10 47 0 02/01/22 0.10 24.35 3 03/01/22 11.0 1.218 3.09 04/01/22 3.11 9.06 2.093 ... </code></pre> <p>This is what I attempted to get <code>inflated_df2</code></p> <pre><code>inflated_df2.iloc[2:3,:] = input_df1.iloc[0:1,:] inflated_df2.iloc[3:,:] = inflated_df2.apply(lambda x: input_df1[x] + (x.shift(periods=1, fill_value=0)) * x['inflation%']) </code></pre>
<python><python-3.x><pandas><dataframe><data-wrangling>
2023-01-28 21:51:36
1
439
star_it8293
75,271,146
3,968,048
pip - is it possible to preinstall a lib, so that any requirements.txt that is run containing that lib won't need to re-build it?
<p>So my scenario is that I'm trying to create a Dockerfile that I can build on my Mac for running Spacy in production. The production server contains a Nvidia GPU with CUDA. To get Spacy to use GPU, I need the lib <code>cupy-cuda117</code>. That lib won't build on my Mac because it can't find the CUDA GPU. So what I'm trying to do is create an image from the Linux server that has the CUDA GPU, that's already pre-build <code>cupy-cuda117</code> on it. I'll then use that as the parent image for Docker, as all other libs in my requirements.txt will build on my Mac.</p> <p>My goal at the moment is to build that lib into the server, but I'm not sure the right path forward. Is it <code>sudo pip3 intall cupy-cuda117</code>? Or should I create a venv, and <code>pip3 install cupy-cuda117</code>? Basically my goal is later to add all the other app code and full requirements.txt, and when <code>pip3 install -r requirements.txt</code> is run by Docker, it'll download/build/install everything, but not <code>cupy-cuda117</code>, because hopefully it'll see that it's already been built.</p> <p>FYI the handling of using GPU on the prod server and CPU on the dev computer i've already got sorted, it's just the building of that one package I'm stuck on. I basically just need it not to try and rebuild on my Mac. Thanks!</p> <pre><code>FROM &quot;debian:bullseye-20210902-slim&quot; as builder # install build dependencies RUN apt-get update -y &amp;&amp; apt-get install --no-install-recommends -y build-essential git locales \ &amp;&amp; apt-get clean &amp;&amp; rm -f /var/lib/apt/lists/*_* # Set the locale RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen &amp;&amp; locale-gen ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US.UTF-8 WORKDIR &quot;/app&quot; RUN apt update -y &amp;&amp; apt upgrade -y &amp;&amp; apt install -y sudo # Install Python 3.9 reqs RUN sudo apt install -y --no-install-recommends wget libxml2 libstdc++6 zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev curl libbz2-dev # Install Python 3.9 RUN wget --no-check-certificate https://www.python.org/ftp/python/3.9.1/Python-3.9.1.tgz &amp;&amp; \ tar -xf Python-3.9.1.tgz &amp;&amp; \ cd Python-3.9.1 &amp;&amp; \ ./configure --enable-optimizations &amp;&amp; \ make -j $(nproc) &amp;&amp; \ sudo make altinstall &amp;&amp; \ cd .. &amp;&amp; \ sudo rm -rf Python-3.9.1 &amp;&amp; \ sudo rm -rf Python-3.9.1.tgz # Install CUDA RUN wget --no-check-certificate https://developer.download.nvidia.com/compute/cuda/11.7.1/local_installers/cuda_11.7.1_515.65.01_linux.run &amp;&amp; \ sudo chmod +x cuda_11.7.1_515.65.01_linux.run &amp;&amp; \ sudo ./cuda_11.7.1_515.65.01_linux.run --silent --override --toolkit --samples --toolkitpath=/usr/local/cuda-11.7 --samplespath=/usr/local/cuda --no-opengl-libs &amp;&amp; \ sudo ln -s /usr/local/cuda-11.7 /usr/local/cuda &amp;&amp; \ sudo rm -rf cuda_11.7.1_515.65.01_linux.run ## Add NVIDIA CUDA to PATH and LD_LIBRARY_PATH ## RUN echo 'case &quot;:${PATH}:&quot; in\n\ *:&quot;/usr/local/cuda-11.7/lib64&quot;:*)\n\ ;;\n\ *)\n\ if [ -z &quot;${PATH}&quot; ] ; then\n\ PATH=/usr/local/cuda-11.7/bin\n\ else\n\ PATH=/usr/local/cuda-11.7/bin:$PATH\n\ fi\n\ esac\n\ case &quot;:${LD_LIBRARY_PATH}:&quot; in\n\ *:&quot;/usr/local/cuda-11.7/lib64&quot;:*)\n\ ;;\n\ *)\n\ if [ -z &quot;${LD_LIBRARY_PATH}&quot; ] ; then\n\ LD_LIBRARY_PATH=/usr/local/cuda-11.7/lib64\n\ else\n\ LD_LIBRARY_PATH=/usr/local/cuda-11.7/lib64:$LD_LIBRARY_PATH\n\ fi\n\ esac\n\ export PATH LD_LIBRARY_PATH\n\ export GLPATH=/usr/lib/x86_64-linux-gnu\n\ export GLLINK=-L/usr/lib/x86_64-linux-gnu\n\ export DFLT_PATH=/usr/lib\n'\ &gt;&gt; ~/.bashrc ENV PATH=&quot;$PATH:/usr/local/cuda-11.7/bin&quot; ENV LD_LIBRARY_PATH=&quot;/usr/local/cuda-11.7/lib64&quot; ENV GLPATH=&quot;/usr/lib/x86_64-linux-gnu&quot; ENV GLLINK=&quot;-L/usr/lib/x86_64-linux-gnu&quot; ENV DFLT_PATH=&quot;/usr/lib&quot; RUN python3.9 -m pip install -U wheel setuptools RUN sudo pip3.9 install torch torchvision torchaudio RUN sudo pip3.9 install -U 'spacy[cuda117,transformers]' # set runner ENV ENV ENV=&quot;prod&quot; CMD [&quot;bash&quot;] </code></pre> <p>My local Dockerfile is this:</p> <pre><code>FROM myacct/myimg:latest ENV ENV=prod WORKDIR /code COPY ./requirements.txt /code/requirements.txt COPY ./requirements /code/requirements RUN pip3 install --no-cache-dir -r /code/requirements.txt COPY ./app /code/app ENV ENV=prod CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;80&quot;] </code></pre>
<python><pip>
2023-01-28 21:51:05
0
3,536
Peter R
75,271,094
386,861
How to split a pandas dataframe based on regex string
<p>I have a CSV of questions and results. Built a simple bit of code to turn into a a list of dataframes for analysis.</p> <p>But last one refused to split out , I think because simple startswith and endswith couldn't handle the fact that the startswith on every question startswith &quot;&lt;Q&quot;</p> <pre><code>def start_and_finish_points(df): df_indices_start = [] df_indices_end = [] rows = df.iloc[:, 0].to_list() for i, row in enumerate(rows): if str(row).startswith('&lt;Q'): df_indices_start.append(i) if str(row).endswith('++'): df_indices_end.append(i) return df_indices_start, df_indices_end start, finish = start_and_finish_points(df) </code></pre> <p>The problem one is code can't handle &quot; &lt;Q&quot;</p> <pre><code> question 698 &lt;Q8&gt; To what extent are you concerned about of the following.................Climate change ... Some data 700 &lt;Q11e&gt; How often d... </code></pre> <p>Can I generalise the startswith to cope with a space at the start of the string? I'm sure it is regex but I can't see it. UPDATE:</p> <pre><code>The dataframe column that I want to extract from is this: 698 &lt;Q8&gt; To what extent are you concerned about of the following.................Climate change 699 700 All respondents 704 Unweighted row 705 Effective sample size 706 Total 707 1: Not at all concerned 710 2 713 3 716 4 719 5: Very concerned 722 Not applicable 725 Total: Concerned 728 Total: Not Concerned 731 Net % concerned 733 95% lower case or +, 99% UPPER CASE or ++ 735 &lt;Q11e&gt; How often do you access local greenspaces (e.g. parks, community gardens)? 736 737 All respondents 741 Unweighted row 742 Effective sample size 743 Total 744 Hardly ever or never 747 Some of the time 750 Often 753 (Prefer not to say) Name: nan, dtype: object </code></pre> <p>[34]</p>
<python><pandas><dataframe><split>
2023-01-28 21:40:14
1
7,882
elksie5000
75,270,910
12,242,085
How to modify loop builing ML models and generated DataFrame with column presented variable removed in each iteration of for-loop in Python?
<p>I have Pandas DataFrame like below:</p> <p><strong>Input data:</strong></p> <ul> <li>Y - binary target</li> <li>X1...X5 - predictors</li> </ul> <p><strong>Source code of DataFrame:</strong></p> <pre><code>import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import roc_curve, roc_auc_score from sklearn.metrics import accuracy_score from sklearn.metrics import recall_score from sklearn.metrics import precision_score from sklearn.metrics import roc_auc_score from sklearn import metrics from xgboost import XGBClassifier df = pd.DataFrame() df[&quot;Y&quot;] = [1,0,1,0] df[&quot;X1&quot;] = [111,12,150,270] df[&quot;X2&quot;] = [22,33,44,55] df[&quot;X3&quot;] = [1,1,0,0] df[&quot;X4&quot;] = [0,0,0,1] df[&quot;X5&quot;] = [150, 222,230,500] Y | X1 | X2 | X3 | X4 | X5 ----|-----|-----|-------|-------|----- 1 | 111 | 22 | 1 | 0 | 150 0 | 12 | 33 | 1 | 0 | 222 1 | 150 | 44 | 0 | 0 | 230 0 | 270 | 55 | 0 | 1 | 500 </code></pre> <p><strong>My code:</strong> -&gt; I Run XGBClassifier() model, where in each successive iteration of the loop one variable is removed So, each successive model is built with 1 less variable than the previous one, the last model in the iteration is built with only 1 predictor</p> <pre><code>X_train, X_test, y_train, y_test = train_test_split(df.drop(&quot;Y&quot;, axis=1) , df.Y , train_size = 0.70 , test_size=0.30 , random_state=1 , stratify = df.Y) results = [] list_of_models = [] Num_var_in = [] predictors = X_train.columns.tolist() Var_out = [] for i in X_train.columns: #model building model = XGBClassifier() model.fit(X_train, y_train) list_of_models.append(model) #evaluation results.append({&quot;AUC_train&quot;: round(metrics.roc_auc_score(y_train, model.predict_proba(X_train)[:,1]), 5), &quot;AUC_test&quot;: round(metrics.roc_auc_score(y_test, model.predict_proba(X_test)[:,1]), 5),}) #Num_var_in - number of predictors which was used to create model during that iteration Num_var_in.append(len(X_train.columns.tolist())) #Var_out - name of variable which was removed during that iteration if sorted(predictors) == sorted(X_train.columns.tolist()): Var_out.append(np.nan) else: Var_out.append(set(predictors) - set(X_train.columns.tolist())) #drop 1 predictor after each loop iteration X_train = X_train.drop(i, axis=1) X_test = X_test.drop(i, axis=1) #save results to DataFrame results = pd.DataFrame(results) results[&quot;Num_var_in&quot;] = Num_var_in results[&quot;Var_out&quot;] = Var_out results.reset_index(inplace = True) results.rename(columns = {&quot;index&quot;:&quot;Model&quot;}, inplace = True) results </code></pre> <p><strong>Current output:</strong></p> <p><a href="https://i.sstatic.net/23Y9E.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/23Y9E.png" alt="enter image description here" /></a></p> <p><strong>Requirements:</strong></p> <ol> <li>In output in column &quot;Var_out&quot; I need to have one variable that has been discarded in a given iteration, not all that have been discarded so far</li> </ol> <p><strong>Desire output:</strong></p> <pre><code>Model | AUC_train | AUC_test | Num_var_in | Var_out ------|------------|------------|-------------|--------- 0 | 0.5 | 0.5 | 5 | NaN 1 | 0.5 | 0.5 | 4 | X1 2 | 0.5 | 0.5 | 3 | X2 3 | 0.5 | 0.5 | 2 | X3 4 | 0.5 | 0.5 | 1 | X4 </code></pre> <p>How can I modify my code in Python so as to have output in Var_out like in &quot;Desire output&quot; ?</p>
<python><loops><for-loop><machine-learning>
2023-01-28 21:10:18
1
2,350
dingaro
75,270,603
5,156,025
Type checking error: views.py:24: error: "HttpRequest" has no attribute "tenant"
<p>I am creating a Django application which is multi-tenanted. The custom middleware I use attaches a <code>tenant</code> object to the request.</p> <p>My issue is when type checking, my views are not aware of extra attribute on the <code>HttpRequest</code> class.</p> <p>I have tried creating a <code>TenantHttpClass</code> which extends <code>HttpRequest</code> and adds the tenant attribute.</p> <p>Edit: Forgot to say I am using mypy to type check.</p> <p>How do I make my views aware of this. My code is below:</p> <p><code>middleware/main.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from typing import Type from django.db import connection from django.http import Http404 from django.utils.deprecation import MiddlewareMixin from apps.tenants.custom_request import TenantHttpRequest as HttpRequest from apps.tenants.models import Domain, Tenant from apps.tenants.utils import get_public_schema_name, get_tenant_domain_model, remove_www from vastdesk import settings class TenantMainMiddleware(MiddlewareMixin): TENANT_NOT_FOUND_EXCEPTION: Type[Http404] = Http404 &quot;&quot;&quot; This middleware should be placed at the very top of the middleware stack. Selects the proper database schema using the request host. Can fail in various ways which is better than corrupting or revealing data. &quot;&quot;&quot; @staticmethod def hostname_from_request(request: HttpRequest) -&gt; str: &quot;&quot;&quot;Extracts hostname from request. Used for custom requests filtering. By default removes the request's port and common prefixes. &quot;&quot;&quot; return remove_www(request.get_host().split(&quot;:&quot;)[0]) def get_tenant(self, domain_model: Domain, hostname: str) -&gt; Tenant: domain = domain_model.objects.select_related(&quot;tenant&quot;).get(domain=hostname) return domain.tenant def process_request(self, request: HttpRequest) -&gt; None: # Connection needs first to be at the public schema, as this is where # the tenant metadata is stored. connection.set_schema_to_public() hostname = self.hostname_from_request(request) domain_model = get_tenant_domain_model() try: tenant = self.get_tenant(domain_model, hostname) except domain_model.DoesNotExist: self.no_tenant_found(request, hostname) return tenant.domain_url = hostname request.tenant = tenant connection.set_tenant(request.tenant) self.setup_url_routing(request) def no_tenant_found(self, request: HttpRequest, hostname: str) -&gt; None: &quot;&quot;&quot;What should happen if no tenant is found. This makes it easier if you want to override the default behavior&quot;&quot;&quot; if ( hasattr(settings, &quot;SHOW_PUBLIC_IF_NO_TENANT_FOUND&quot;) and settings.SHOW_PUBLIC_IF_NO_TENANT_FOUND ): self.setup_url_routing(request=request, force_public=True) else: raise self.TENANT_NOT_FOUND_EXCEPTION('No tenant for hostname &quot;%s&quot;' % hostname) @staticmethod def setup_url_routing(request: HttpRequest, force_public: bool = False) -&gt; None: &quot;&quot;&quot; Sets the correct url conf based on the tenant :param request: :param force_public &quot;&quot;&quot; # Do we have a public-specific urlconf? if hasattr(settings, &quot;PUBLIC_SCHEMA_URLCONF&quot;) and ( force_public or request.tenant.schema_name == get_public_schema_name() ): request.urlconf = settings.PUBLIC_SCHEMA_URLCONF </code></pre> <p><code>custom_request.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from typing import Union, TYPE_CHECKING from django.http import HttpRequest if TYPE_CHECKING: from apps.tenants.models import Tenant class TenantHttpRequest(HttpRequest): tenant: Union[&quot;Tenant&quot;, None] </code></pre> <p><code>views.py</code>:</p> <pre class="lang-py prettyprint-override"><code>from typing import Any, Dict from django.views.generic import TemplateView from apps.tenants.models import Tenant as Realm from apps_tenants.ticket_system.models import Ticket class StaffDashboardView(TemplateView): template_name = &quot;dashboard/dash-staff/dash.html&quot; def get_context_data(self, **kwargs: Dict[str, Any]) -&gt; Dict[str, Any]: context = super(StaffDashboardView, self).get_context_data(**kwargs) context[&quot;logo_url&quot;] = Realm.objects.get( schema_name=self.request.tenant.schema_name ).logo_url context[&quot;profile_image_url&quot;] = &quot;&quot; context[&quot;tickets&quot;] = Ticket.objects.all() return context class CustomerDashboardView(TemplateView): template_name = &quot;dashboard/dash-customer/dash.html&quot; def get_context_data(self, **kwargs: Dict[str, Any]) -&gt; Dict[str, Any]: context = super(CustomerDashboardView, self).get_context_data(**kwargs) context[&quot;logo_url&quot;] = Realm.objects.get( schema_name=self.request.tenant.schema_name ).logo_url context[&quot;profile_image_url&quot;] = &quot;&quot; context[&quot;tickets&quot;] = Ticket.objects.all() return context </code></pre>
<python><django><python-typing><mypy>
2023-01-28 20:21:05
2
494
Adam Birds
75,270,582
123,654
Unexpected Apache Beam (Dataframe API) behavior gives tuples instead of dictionaries, breaking BigQuery upload
<p>Learning Apache Beam with the dataframe API at the moment and coming across some unexpected behavior that I was hoping an expert could explain to me.</p> <p>Here's the simplest version of my issue I could drill it down to (in the real version the dataframe transform is something more complex):</p> <pre><code>class LocationRow(NamedTuple): h3_index: str with beam.Pipeline(options=beam_options) as pipeline: (pipeline | ReadFromBigQuery( query=f'SELECT h3_index FROM {H3_INDEX_TABLE} LIMIT 100', use_standard_sql=True) .with_output_types(LocationRow) | DataframeTransform(lambda df: df) | WriteToBigQuery( schema='h3_index:STRING', table=OUTPUT_TABLE)) </code></pre> <p>Running this with <code>DirectRunner</code> (or <code>DataflowRunner</code>) crashes with the following:</p> <pre><code>message: 'Error while reading data, error message: JSON table encountered too many errors, giving up. Rows: 1; errors: 1. Please look into the errors[] collection for more details. File: gs://analysis-dataflow-temp/temp/bq_load/0163282c2bbc47ba8ec368b158aefe2e/core-modules-development.analysis.fake_grid_power_price/5a1fc783-dcdc-44bd-9855-faea6151574f' </code></pre> <p>So, I looked into that file and it's just a json list per line:</p> <pre><code>$ cat 5a1fc783-dcdc-44bd-9855-faea6151574f [&quot;8800459aedfffff&quot;] [&quot;88004536c5fffff&quot;] [&quot;8800418237fffff&quot;] [&quot;8800422b39fffff&quot;] [&quot;8800432451fffff&quot;] [&quot;88004175d7fffff&quot;] ... </code></pre> <p>I figured out that BigQuery is expecting an object per line (like <code>{&quot;h3_index&quot;: &quot;88004175d7fffff&quot;}</code>), and if I remove the <code>DataframeTransform</code> in the pipeline it works. So I tried using print to figure out what's happening, and changed the pipeline to this:</p> <pre><code>with beam.Pipeline(options=beam_options) as pipeline: (pipeline | ReadFromBigQuery( query=f'SELECT h3_index FROM {H3_INDEX_TABLE} LIMIT 5', use_standard_sql=True) .with_output_types(LocationRow) | DataframeTransform(lambda df: df) | beam.Map(print) </code></pre> <p>Which gives this output:</p> <pre><code>BeamSchema_574444a4_ae3e_4bb2_9cca_4867670ef2bb(h3_index='8806b00819fffff') BeamSchema_574444a4_ae3e_4bb2_9cca_4867670ef2bb(h3_index='8806ab98d3fffff') BeamSchema_574444a4_ae3e_4bb2_9cca_4867670ef2bb(h3_index='8806accd45fffff') BeamSchema_574444a4_ae3e_4bb2_9cca_4867670ef2bb(h3_index='8806ac60a7fffff') BeamSchema_574444a4_ae3e_4bb2_9cca_4867670ef2bb(h3_index='8806acb409fffff') </code></pre> <p>If I remove the <code>DataframeTransform</code> and keep the <code>Map(print)</code> I get this instead:</p> <pre><code>{'h3_index': '88012db281fffff'} {'h3_index': '88012ea527fffff'} {'h3_index': '88012e38c5fffff'} {'h3_index': '88012e2135fffff'} {'h3_index': '88012ea949fffff'} </code></pre> <p>So it looks like the <code>DataframeTransform</code> is returning collections of NamedTuples (or similar) rather than dictionaries, and the <code>WriteToBigQuery</code> fails with these tuples. I can fix it by adding a <code>Map</code> after the <code>DataframeTransform</code> to change this explicitly:</p> <pre><code>with beam.Pipeline(options=beam_options) as pipeline: (pipeline | ReadFromBigQuery( query=f'SELECT h3_index FROM {H3_INDEX_TABLE} LIMIT 100', use_standard_sql=True) .with_output_types(LocationRow) | DataframeTransform(lambda df: df) | beam.Map(lambda row: {'h3_index': row.h3_index}) | WriteToBigQuery( schema='h3_index:STRING', table=OUTPUT_TABLE)) </code></pre> <p>But this feels unnecessary, and I don't really understand what's happening here. What's the difference between a collection of tuples and one of dictionaries? Hoping a Beam expert can shed some light on this!</p>
<python><dataframe><google-cloud-dataflow><apache-beam>
2023-01-28 20:18:34
1
1,631
Will
75,270,546
4,507,231
Running pyinstaller on code containing relative paths
<p>I have a large Python codebase developed inside PyCharm. I want to use PyInstaller for obvious reasons; however, I'm struggling with relative paths for data files due to the project code file hierarchy.</p> <p>The file hierarchy was a usual top-down structure, i.e., the point of execution is within a file found in the project root folder, with the additional Python files stored in a sensible folder, <strong>(please pay particular attention to the version.txt file on the same level as the Main.py file)</strong> e.g.,</p> <pre><code>Project/ --Main.py --version.txt --Engines/ ----somefile.py --Controllers/ ----somefile.py --Entities/ ----somefile.py </code></pre> <p>A year ago, I built a GUI front end whilst maintaining the console-based point of execution. The GUI point of execution is within MainGUI.py. But that file is not at the project root. It looks a bit like this:</p> <pre><code>Project/ --Main.py --version.txt --GUI/ ----MainGUI.py --Engines/ ----somefile.py --Controllers/ ----somefile.py --Entities/ ----somefile.py </code></pre> <p>Inside MainGUI.py, I have the code to open the &quot;../version.txt&quot; file:</p> <pre><code>with open(&quot;../version.txt&quot;) as file: version = file.readline().strip() </code></pre> <p>I navigate to the Project/GUI folder in the PyCharm Terminal and execute <code>pyinstaller MainGUI.py --onefile</code> It seems to work until I try and execute the built MainGUI.exe. I'm given the error:</p> <pre><code>Traceback (most recent call last): File &quot;MainGUI.py&quot;, line 10, in &lt;module&gt; FileNotFoundError: [Errno 2] No such file or directory: '../version.txt' [17232] Failed to execute script 'MainGUI' due to unhandled exception! </code></pre> <p>I could move the <code>version.txt</code> file to be on the same level as MainGUI.py, but this was a reduced example. There are lots of data files referenced using relative paths.</p>
<python><pyinstaller>
2023-01-28 20:08:45
0
1,177
Anthony Nash
75,270,261
6,273,451
Pandas .iloc indexing coupled with boolean indexing in a Dataframe
<p>I looked into existing threads regarding indexing, none of said threads address the present use case.</p> <p>I would like to alter specific values in a <code>DataFrame</code> based on their position therein, ie., I'd like the values in the second column from the first to the 4th row to be <code>NaN</code> and values in the third column, first and second row to be <code>NaN</code> say we have the following `DataFrame`:</p> <pre><code>df = pd.DataFrame(np.random.standard_normal((7,3))) print(df) 0 1 2 0 -1.102888 1.293658 -2.290175 1 -1.826924 -0.661667 -1.067578 2 1.015479 0.058240 -0.228613 3 -0.760368 0.256324 -0.259946 4 0.496348 0.437496 0.646149 5 0.717212 0.481687 -2.640917 6 -0.141584 -1.997986 1.226350 </code></pre> <p>And I want alter <code>df</code> like below with the least amount of code:</p> <pre><code> 0 1 2 0 -1.102888 NaN NaN 1 -1.826924 NaN NaN 2 1.015479 NaN -0.228613 3 -0.760368 NaN -0.259946 4 0.496348 0.437496 0.646149 5 0.717212 0.481687 -2.640917 6 -0.141584 -1.997986 1.226350 </code></pre> <p>I tried using boolean indexing with <code>.loc</code> but resulted in an error:</p> <pre><code>df.loc[(:2,1:) &amp; (2:4,1)] = np.nan # exception message: df.loc[(:2,1:) &amp; (2:4,1)] = np.nan ^ SyntaxError: invalid syntax </code></pre> <p>I also thought about converting the <code>DataFrame</code> object to a numpy <code>narray</code> object but then I wouldn't know how to use boolean in that case.</p>
<python><pandas><numpy><indexing>
2023-01-28 19:23:12
1
334
Mehdi Rezzag Hebla
75,269,939
1,001,938
Have a result be both a class and destructurable as a tuple
<p>I came across a method in Python that returns a class, but can be destructured as if it's a tuple.</p> <p>How can you define a result of a function to be both an instance of a class AND use destructure assignment as if it's a tuple?</p> <p>An example where you see this behavior:</p> <pre><code>import scipy.stats as stats res = stats.ttest_ind(data1, data2) print(type(res)) # &lt;class 'scipy.stats.stats.Ttest_indResult'&gt; # One way to assign values is by directly accessing the instance's properties. p = res.pvalue t = res.statistic # A second way is to treat the result as a tuple, and assign to variables directly. But how is this working? # We saw above that the type of the result is NOT a tuple but a class. How would Python know the order of the properties here? (It's not like we're destructuring based on named properties) t, p = stats.ttest_ind(data1, data2) </code></pre>
<python>
2023-01-28 18:30:29
2
64,248
Don P
75,269,700
6,203,472
pre-commit fails to install isort 5.11.4 with error "RuntimeError: The Poetry configuration is invalid"
<p><a href="https://pre-commit.com/" rel="noreferrer">pre-commit</a> suddenly started to fail installing the <a href="https://github.com/pycqa/isort" rel="noreferrer">isort</a> hook in our builds today with the following error</p> <pre><code>[INFO] Installing environment for https://github.com/pycqa/isort. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: CalledProcessError: command: ('/builds/.../.cache/pre-commit/repo0_h0f938/py_env-python3.8/bin/python', '-mpip', 'install', '.') return code: 1 expected return code: 0 [...] stderr: ERROR: Command errored out with exit status 1: [...] File &quot;/tmp/pip-build-env-_3j1398p/overlay/lib/python3.8/site-packages/poetry/core/masonry/api.py&quot;, line 40, in prepare_metadata_for_build_wheel poetry = Factory().create_poetry(Path(&quot;.&quot;).resolve(), with_groups=False) File &quot;/tmp/pip-build-env-_3j1398p/overlay/lib/python3.8/site-packages/poetry/core/factory.py&quot;, line 57, in create_poetry raise RuntimeError(&quot;The Poetry configuration is invalid:\n&quot; + message) RuntimeError: The Poetry configuration is invalid: - [extras.pipfile_deprecated_finder.2] 'pip-shims&lt;=0.3.4' does not match '^[a-zA-Z-_.0-9]+$' </code></pre> <p>It seems to be related with poetry configuration..</p>
<python><pre-commit><pre-commit.com><isort>
2023-01-28 17:54:09
5
6,474
bagerard
75,269,696
10,842,351
Fast creation of 2d+ memory views in Cython
<p>We are developing a project where we create a lot of typed memory views as numpy arrays but we often have to deal with arrays of small size so that the creation of memory views as np.ndarray is impacting a lot because it has lots of interactions with Python. I found that there are some “tricks” to improve the initialization step with Cpython arrays and the clone function for 1d numeric arrays (found on <a href="https://stackoverflow.com/questions/18462785/what-is-the-recommended-way-of-allocating-memory-for-a-typed-memory-view">What is the recommended way of allocating memory for a typed memory view?</a>), but we are stuck in generalizing it for numeric 2d arrays, is it possible to do that? If not, what can be another way to create 2d arrays faster than using np.ndarrays? We tried Cython arrays but they were even slower to initialize than numpy ones. Is it manually managing the memory the only solution? If so, can you give me some tips to do that in the 2d case? I found that the <a href="https://cython.readthedocs.io/en/latest/src/tutorial/memory_allocation.html" rel="nofollow noreferrer">documentation</a> on this is a bit limited in this respect for me since my knowledge of C is very little (but I'm trying to improve on this matter!). Thanks for the help in advance.</p>
<python><arrays><c><cython>
2023-01-28 17:53:34
0
665
Tortar
75,269,596
11,607,243
Unable to run NumPy on VS Code
<p>I have installed Anaconda (with Python 3.9) and Python (3.11) separately. After installing VS Code, I have also created a separated Anaconda environment <code>Env01</code> . Now, when I open a VS Code file, I have three available environments to choose from</p> <p>a) base Python 3.11</p> <p>b) base Conda 3.9</p> <p>c) <code>Env01</code></p> <p>I've chosen <code>Env01</code> as my interpreter using <code>Ctrl+Shift+P</code> since I understand Anaconda comes with <code>NumPy</code>, <code>Pandas</code>, <code>SciPy</code> and <code>MatPlotlib</code>.</p> <p>However, when I try to run</p> <pre><code>import numpy as np </code></pre> <p>I still get an error that reads</p> <pre><code>ModuleNotFoundError: No module named 'numpy' </code></pre> <p>How do I resolve this?</p>
<python><numpy><visual-studio-code><anaconda3>
2023-01-28 17:38:46
1
525
newtothis
75,269,487
1,953,475
Pass in any variable while guaranteeing predefined relationship
<p>I have a simple formula taking basic arithmetic calculations given several inputs.</p> <pre><code>a = 1 b = 2 c = a + b #3=1+2 d = 4 e = c + d #7=3+4 </code></pre> <p><a href="https://i.sstatic.net/RPoL8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RPoL8.png" alt="graph of relationship" /></a></p> <p>In theory, the relationships should always hold true. And I want to write a function that user can modify any variable and the rest will be auto updated (update priority has been predefined if there are more than one alternative eg. update the most right node first).</p> <pre><code>def f(): #default state state = {'a':1, 'b':2, 'c':3, 'd':4, 'e':7} ... return state f(a=0) == {'a':0, 'b':2, 'c':2, 'd':4, 'e':6} f(c=4) == {'a':1, 'b':3, 'c':4, 'd':4, 'e':8} f(b=2, c=4) == {'a':2, 'b':2, 'c':4, 'd':4, 'e':8} </code></pre> <p><a href="https://i.sstatic.net/DnvnH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DnvnH.png" alt="graph of modified relationship for c=4" /></a></p> <p>I tried to use <code>**kwargs</code> and <code>*args</code> to allow the user to pass in any variable but have to hard code the update logic based on which variable got modified. Any better ideas?</p> <p>P.S.: this example is for demonstration purpose; the real problem involves much more variables and the mathematical relationship is also more difficult (logarithm, exponential, ..)</p>
<python><sympy>
2023-01-28 17:24:24
3
19,728
B.Mr.W.
75,269,387
871,910
dataclasses.asdict doesn't work on Python 3.11?
<p>I tried the following code:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import asdict, dataclass @dataclass class DC: a: int b: int c = DC(a=10, b=5) dc = asdict(c) print(dc) </code></pre> <p>On Python 3.10 it works as expected, printing a dictionary as expected. When I try the same with Python 3.11 I get the following error:</p> <pre class="lang-none prettyprint-override"><code>File &quot;C:\Sources\IAA\python-utils\tests\test_dict.py&quot;, line 11, in &lt;module&gt; dc = asdict(c) ^^^^^^^^^ File &quot;C:\Python\311\Lib\dataclasses.py&quot;, line 1272, in asdict if not _is_dataclass_instance(obj): ^^^^^^^^^^^^^^^^^^^^^^ NameError: name '_is_dataclass_instance' is not defined. Did you mean: 'config_is_dataclass_instance'? </code></pre> <p>I checked the Python 3.11 documentation, <code>dataclasses.asdict</code> is there and should work. Am I doing something wrong, or is this a Python 3.11.1 bug?</p> <p>The solution for Python 3.11.1 is to add the following lines to my module:</p> <pre class="lang-py prettyprint-override"><code>import dataclasses dataclasses._is_dataclass_instance = dataclasses.config_is_dataclass_instance </code></pre> <p>But it's really not a good solution.</p>
<python><python-dataclasses><python-3.11>
2023-01-28 17:10:16
1
39,097
zmbq
75,269,244
156,180
Is a loop in a loop really the best way to output nested dict items in Python?
<p>I have a dict from a json API call that looks like this:</p> <pre><code>{ 'id': '63d08d5c57abd98fdeea7985', 'pageName': 'Some Page Name', 'bodyContent': [{ 'children': [{ 'alpha': 'foo foo foo', 'beta': 'bar bar bar' }] }], 'date': '2023-01-25T02:01:00.965Z' } </code></pre> <p>To reference the nested items inside <em>bodyContent</em>, I'm doing a loop within a loop (to get <em>alpha</em>):</p> <pre><code>{% for item in items.get('bodyContent') %} {% for i in item.get('children') %} {{ i['alpha'] }} {% endfor %} {% endfor %} </code></pre> <p>I see these nested for loops in a lot of example code, but is this really the best way - a loop within a loop? I can't help but feel like it's a bit dirty and am used to other languages where a loop within a loop isn't necessary for a structure that is this basic.</p> <p><strong>Edit:</strong> What other languages am I referring to, where nested loops wouldn't be necessary? Things like array_map or array_reduce in PHP to simplify data structures (when you can't alter how they're stored, like the data in my example from an API). If nested loops are A-OK in Python then that's cool too. I'm just not sure what the common wisdom is with them in Python.</p>
<python><for-loop><jinja2><nested-loops><nested-for-loop>
2023-01-28 16:46:17
1
2,872
Jeff
75,269,161
2,036,464
Python: import docx Error: " from exceptions import PendingDeprecationWarning "
<p>I want to convert multiple txt files to docx. I use this code:</p> <pre><code>from docx import Document import re import os path = 'd://2022_12_02' direct = os.listdir(path) for i in direct: document = Document() document.add_heading(i, 0) myfile = open('d://2022_12_02'+i).read() myfile = re.sub(r'[^\x00-\x7F]+|\x0c',' ', myfile) # remove all non-XML-compatible characters p = document.add_paragraph(myfile) document.save('d://2022_12_02'+i+'.docx') </code></pre> <p><strong>After RUN I get this error:</strong></p> <pre><code>Traceback (most recent call last): File &quot;D:\convert txt to docs.py&quot;, line 4, in &lt;module&gt; from docx import Document File &quot;C:\Users\Castel\AppData\Roaming\Python\Python310\site-packages\docx.py&quot;, line 30, in &lt;module&gt; from exceptions import PendingDeprecationWarning ModuleNotFoundError: No module named 'exceptions' &gt;&gt;&gt; </code></pre> <p>ALSO, in docx module, I see this line underlined with red colour:</p> <p><em>from exceptions import PendingDeprecationWarning</em></p>
<python><python-3.x>
2023-01-28 16:31:45
1
1,065
Just Me
75,268,750
1,938,410
How to print line number of error that is inside a function using except in Python?
<p>I want to print an error's line number and error message in a nicely displayed way. The follow is my code, which uses <em>linecache</em>:</p> <pre><code>import linecache def func(): if xx == 1: print('ok') try: func() except: exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) print_('ERROR - (LINE {} &quot;{}&quot;): {}'.format(lineno, line.strip(), exc_obj)) </code></pre> <p>However, this only gives where the <code>func()</code> is called:</p> <p><code>ERROR - (LINE 8 &quot;&quot;): name 'xx' is not defined</code></p> <p>Is there a way to print the line number where the error actually occured, which should be Line 4? Or even better, can I print Line 8 and then trace back to line 4? For example, if I do not use <code>try - except</code>, the code:</p> <pre><code>def func(): if xx == 1: print('ok') func() </code></pre> <p>will give me the following error message, which is much better to locate the error:</p> <pre><code> File &quot;&lt;input&gt;&quot;, line 5, in &lt;module&gt; File &quot;&lt;input&gt;&quot;, line 2, in func NameError: name 'xx' is not defined. Did you mean: 'xxx'? </code></pre>
<python><exception>
2023-01-28 15:30:55
3
507
SamTest
75,268,748
210,867
How to introspect a Click application?
<p>I have a Click app called &quot;DC&quot; starting with click.Group <code>cli()</code>, which has many subcommands. I'm trying to produce a text file with a list of all commands, arguments, options, and help text as a convenient reference. How do I introspect a Click application?</p> <p>I experimented using the <a href="https://click.palletsprojects.com/en/8.1.x/api/#commands" rel="nofollow noreferrer">API reference</a>, but it's confusing. Some of Command's methods (like <code>get_usage()</code>) require a &quot;context&quot; object as the first arg, and I only know two ways to get one:</p> <ol> <li>Be inside a command with <code>@pass_context</code> decorator. <em>(Not always the case.)</em></li> <li>Call <code>click.get_current_context()</code> to get the &quot;current&quot; context, which seems to be the one attached to the bottom-level command that is currently being executed.</li> </ol> <p>That <em>seemed</em> to work:</p> <pre><code>from dc.__main__ import cli current_ctx = click.get_current_context() click.echo(cli.get_usage(current_ctx)) </code></pre> <p>This prints the docstring from the <code>cli()</code> function. However, if I try to inspect the list of subcommands:</p> <pre><code>click.echo(cli.commands) </code></pre> <p>I get an empty dict. After more exploring, I finally managed to find my way to the real data by doing this:</p> <pre><code>current_ctx.find_root().command.commands </code></pre> <p>which returned a dict with all the top-level commands I expected to see.</p> <p>Is that the preferred method?</p>
<python><python-click>
2023-01-28 15:30:37
1
8,548
odigity
75,268,657
18,749,472
preserve multiple GET parameters in Django URL
<p>In my django project I have a page displaying a list of times. On this page there is 3 GET forms which are for:</p> <ul> <li><p>Parsing through pages</p> </li> <li><p>Selecting graph data</p> </li> <li><p>Sorting items</p> </li> </ul> <p>If a user is to select a field in all of these forms the URL should look something like this:</p> <p><code>http://127.0.0.1:8000/watchlist/?page=1&amp;graph_data=price&amp;sort=quantity_desc</code></p> <p>But when a user submits one of these forms it only saves that GET parameter in the URL. eg:</p> <p><em>selects page = 2</em></p> <p><code>http://127.0.0.1:8000/watchlist/?page=2</code></p> <p><em>selects sort = quantity_asc</em></p> <p><code>http://127.0.0.1:8000/watchlist/?sort=quantity_asc</code></p> <p>The page parameter is over written when both parameters should be present in the URL. How can i preserve multiple GET parameters in the URL?</p> <p><em>views.py</em></p> <pre><code>def watchlist(request): #get requests graph_metric = request.GET.get(&quot;graph-data-options&quot;, &quot;avg_price&quot;) page = int(request.GET.get(&quot;page&quot;, 1)) sort_field = request.GET.get(&quot;sort-field&quot;, &quot;avg_price-asc&quot;) return render(request, &quot;App/watchlist.html&quot;, context=context) </code></pre> <p><em>html</em></p> <pre><code>&lt;!-- Page number --&gt; &lt;form id=&quot;page-buttons-form&quot; action=&quot;{% url 'watchlist' %}&quot; method=&quot;GET&quot;&gt; {% for page_button in num_pages %} &lt;input name=&quot;page&quot; type=&quot;submit&quot; value=&quot;{{page_button}}&quot;&gt; {% endfor %} &lt;/form&gt; &lt;!-- Sort items --&gt; &lt;form id=&quot;sort-form&quot; action=&quot;{% url 'watchlist' %}&quot; method=&quot;GET&quot;&gt; &lt;label for=&quot;sort-field&quot;&gt;Sort:&lt;/label&gt; &lt;select onchange=&quot;this.form.submit()&quot; name=&quot;sort-field&quot;&gt; {% for sort in sort_options %} &lt;option value=&quot;{{sort.value}}&quot;&gt;{{sort.text}}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;/form&gt; &lt;!-- Graph data --&gt; &lt;form action=&quot;{% url 'watchlist' %}&quot; method=&quot;GET&quot;&gt; &lt;label for=&quot;graph-data-options&quot;&gt;Graph Data&lt;/label&gt; &lt;select onchange=&quot;this.form.submit()&quot; name=&quot;graph-data-options&quot;&gt; {% for graph_option in graph_options %} &lt;option value=&quot;{{graph_option.value}}&quot;&gt;{{graph_option.text}}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;/form&gt; </code></pre>
<python><html><django><request><get>
2023-01-28 15:16:54
1
639
logan_9997
75,268,571
10,220,116
Decorating with arguments a Class Declaration
<p>I'm trying to create a Class representing a regex to execute for my application. For each regex I have a link to the regex101.com page where users can find unit tests. I wanna use this solution to have near the class declaration this link but without having them in the class code. The code I think about has to look like this:</p> <pre class="lang-py prettyprint-override"><code>class TestUrl(object): def __init__(self, url) -&gt; None: self.url = url def __call__(self, cls) -&gt; Any: functools.update_wrapper(self, cls) cls.url = self.url def wrapper(*args: Any, **kwds: Any): return cls(*args, **kwds) return wrapper def test_url(url): def wrapper_class(cls): cls.test_url = url @functools.wraps(cls) def wrapper(*args, **kwargs): return cls(*args, **kwargs) return wrapper return wrapper_class class Regex: def __init__(self, pattern, repl, flags) -&gt; None: self.exp = re.compile(pattern, flags=flags) self.repl = repl self.flags = flags def sub(self, string: str): return self.exp.sub(self.repl, string) @test_url(&quot;https://regex101.com/r/.../...&quot;) class SubRegex(Regex): def __init__(self): super().__init__(r'...', r'...', re.MULTILINE | re.DOTALL) </code></pre> <p>But my problem is that when I wanns cycle on all classes in the module using this code:</p> <pre class="lang-py prettyprint-override"><code>def test_all_regexs(regex): module = importlib.import_module(&quot;...&quot;) print(f&quot;Looking at {module}&quot;) for name, obj in inspect.getmembers(module): if inspect.isclass(obj): print(f&quot;Class: {name}, {obj}&quot;) if inspect.isfunction(obj): print(f&quot;Func: {name}, {obj}&quot;) </code></pre> <p>The output is always:</p> <pre><code>Func: SubRegex, &lt;function SubRegex at ...&gt; Class: Regex, &lt;class '....Regex'&gt; Class: TestUrl, &lt;class '....TestUrl'&gt; Func: test_url, &lt;function test_url at ...&gt; </code></pre> <p>I can't figure out how obtain SubRegex as Class, not as Func. How can I get this?</p> <p>P.S.: Do you have another way to don't mix application logic like regex patterns with the url I use only for documentation?</p>
<python><design-patterns><python-decorators>
2023-01-28 15:04:03
1
310
Daniele Tentoni
75,268,498
518,012
ModuleNotFoundError: No module named 'delta.tables'; 'delta' is not a package
<p>I'm trying to get my PySpark to work with Delta table.</p> <p>I did &quot;pip install delta&quot; as well as &quot;pip install delta-spark&quot;</p> <p>This is my delta.py script:</p> <pre><code>from delta.tables import * from pyspark.sql.functions import * deltaTable = DeltaTable.forPath(spark, &quot;/tmp/delta-table&quot;) # Update every even value by adding 100 to it deltaTable.update( condition = expr(&quot;id % 2 == 0&quot;), set = { &quot;id&quot;: expr(&quot;id + 100&quot;) }) # Delete every even value deltaTable.delete(condition = expr(&quot;id % 2 == 0&quot;)) # Upsert (merge) new data newData = spark.range(0, 20) deltaTable.alias(&quot;oldData&quot;) \ .merge( newData.alias(&quot;newData&quot;), &quot;oldData.id = newData.id&quot;) \ .whenMatchedUpdate(set = { &quot;id&quot;: col(&quot;newData.id&quot;) }) \ .whenNotMatchedInsert(values = { &quot;id&quot;: col(&quot;newData.id&quot;) }) \ .execute() deltaTable.toDF().show() </code></pre> <p>Here is my spark-submit command:</p> <pre><code>spark-submit --packages io.delta:delta-core_2.12:0.7.0 --master local[*] --executor-memory 2g delta.py </code></pre> <p>Here is the output containing the error:</p> <pre><code>:: loading settings :: url = jar:file:/mnt/spark/jars/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml Ivy Default Cache set to: /home/eugene/.ivy2/cache The jars for the packages stored in: /home/eugene/.ivy2/jars io.delta#delta-core_2.12 added as a dependency :: resolving dependencies :: org.apache.spark#spark-submit-parent-c6184f38-2d95-498c-b711-ead1c4e98cdc;1.0 confs: [default] found io.delta#delta-core_2.12;0.7.0 in central found org.antlr#antlr4;4.7 in central found org.antlr#antlr4-runtime;4.7 in central found org.antlr#antlr-runtime;3.5.2 in central found org.antlr#ST4;4.0.8 in central found org.abego.treelayout#org.abego.treelayout.core;1.0.3 in central found org.glassfish#javax.json;1.0.4 in central found com.ibm.icu#icu4j;58.2 in central :: resolution report :: resolve 1363ms :: artifacts dl 24ms :: modules in use: com.ibm.icu#icu4j;58.2 from central in [default] io.delta#delta-core_2.12;0.7.0 from central in [default] org.abego.treelayout#org.abego.treelayout.core;1.0.3 from central in [default] org.antlr#ST4;4.0.8 from central in [default] org.antlr#antlr-runtime;3.5.2 from central in [default] org.antlr#antlr4;4.7 from central in [default] org.antlr#antlr4-runtime;4.7 from central in [default] org.glassfish#javax.json;1.0.4 from central in [default] --------------------------------------------------------------------- | | modules || artifacts | | conf | number| search|dwnlded|evicted|| number|dwnlded| --------------------------------------------------------------------- | default | 8 | 0 | 0 | 0 || 8 | 0 | --------------------------------------------------------------------- :: retrieving :: org.apache.spark#spark-submit-parent-c6184f38-2d95-498c-b711-ead1c4e98cdc confs: [default] 0 artifacts copied, 8 already retrieved (0kB/16ms) 23/01/28 14:44:02 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Traceback (most recent call last): File &quot;/home/eugene/dev/pyspark/delta.py&quot;, line 1, in &lt;module&gt; from delta.tables import * File &quot;/home/eugene/dev/pyspark/delta.py&quot;, line 1, in &lt;module&gt; from delta.tables import * ModuleNotFoundError: No module named 'delta.tables'; 'delta' is not a package 23/01/28 14:44:02 INFO ShutdownHookManager: Shutdown hook called 23/01/28 14:44:02 INFO ShutdownHookManager: Deleting directory /tmp/spark-a8e1196f-83c5-4c81-865e-9522d4d0c056 </code></pre> <p>Is there a solution for this?</p>
<python><apache-spark><pyspark><delta-lake>
2023-01-28 14:50:35
0
15,684
Eugene Goldberg
75,268,393
3,885,446
YOLOV8 how does it handle different image sizes
<p>Yolov8 and I suspect Yolov5 handle non-square images well. I cannot see any evidence of cropping the input image, i.e. detections seem to go to the enge of the longest side. Does it resize to a square 640x604 which would change the aspect ratio of objects making them more difficult to detect?</p> <p>When training on a custom dataset starting from a pre-trained model, what does the <code>imgsz</code> (image size) parameter actually do?</p>
<python><deep-learning><conv-neural-network><yolo>
2023-01-28 14:33:43
1
575
Alan Johnstone
75,268,350
10,411,973
Tosca parser ImportError: "No modules named". The modules already installed in dist-packages success
<p>I have gone through similar questions but I still cant resolve the problem I have install the package and success but when I run my script it will always return no module name error.</p> <p>I suspect something todo with the python path where the module may not in python path This is my code</p> <pre><code>from toscaparser.tosca_template import ToscaTemplate path_to_yaml_file = 'cvx.yaml' template = ToscaTemplate(path_to_yaml_file) print(template.inputs) </code></pre> <p>error</p> <pre><code>from tosca_parser import ToscaTemplate ModuleNotFoundError: No module named 'tosca_parser' </code></pre> <p>My python</p> <pre><code>python Python 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/cube1/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist- packages', '/usr/local/lib/python3.8/dist-packages/pytosca-0.2.1-py3.8.egg', '/usr/lib/python3/dist-packages'] </code></pre> <p>Package is success install using pip</p> <pre><code>Requirement already satisfied: attrs&gt;=16.3.0 in /usr/lib/python3/dist-packages (from cmd2&gt;=1.0.0-&gt;cliff!=2.9.0,&gt;=2.8.0-&gt;tosca-parser) (19.3.0) </code></pre> <p>Pip version</p> <pre><code>pip --version pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8) </code></pre> <p>Run echo $PYTHONPATH only return blank line I did run the script in tosca-parser dir and it work. Thus, something is not right with tosca parser module and python path outside the dir. Need some help and advise how can I fix this. Thank you</p>
<python><path><tosca>
2023-01-28 14:27:14
0
565
chenoi
75,268,283
16,332,690
How to extract date from datetime column in polars
<p>I am trying to move from pandas to polars but I am running into the following issue.</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame( { &quot;integer&quot;: [1, 2, 3], &quot;date&quot;: [ &quot;2010-01-31T23:00:00+00:00&quot;, &quot;2010-02-01T00:00:00+00:00&quot;, &quot;2010-02-01T01:00:00+00:00&quot; ] } ) df = df.with_columns( pl.col(&quot;date&quot;).str.to_datetime().dt.convert_time_zone(&quot;Europe/Amsterdam&quot;) ) </code></pre> <p>Yields the following dataframe:</p> <pre><code>shape: (3, 2) ┌─────────┬────────────────────────────────┐ │ integer ┆ date │ │ --- ┆ --- │ │ i64 ┆ datetime[μs, Europe/Amsterdam] │ ╞═════════╪════════════════════════════════╡ │ 1 ┆ 2010-02-01 00:00:00 CET │ │ 2 ┆ 2010-02-01 01:00:00 CET │ │ 3 ┆ 2010-02-01 02:00:00 CET │ └─────────┴────────────────────────────────┘ </code></pre> <p>As you can see, I transformed the datetime string from UTC to CET succesfully.</p> <p>However, if I try to cast to <code>pl.Date</code> (as suggested <a href="https://stackoverflow.com/questions/73212628/retrieve-date-from-datetime-column-in-polars/73212748#73212748">here</a>), it seems to extract the date from the UTC string even though it has been transformed, e.g.:</p> <pre class="lang-py prettyprint-override"><code>df = df.with_columns( pl.col(&quot;date&quot;).cast(pl.Date).alias(&quot;valueDay&quot;) ) </code></pre> <pre><code>shape: (3, 3) ┌─────────┬────────────────────────────────┬────────────┐ │ integer ┆ date ┆ valueDay │ │ --- ┆ --- ┆ --- │ │ i64 ┆ datetime[μs, Europe/Amsterdam] ┆ date │ ╞═════════╪════════════════════════════════╪════════════╡ │ 1 ┆ 2010-02-01 00:00:00 CET ┆ 2010-01-31 │ # &lt;- NOT OK │ 2 ┆ 2010-02-01 01:00:00 CET ┆ 2010-02-01 │ │ 3 ┆ 2010-02-01 02:00:00 CET ┆ 2010-02-01 │ └─────────┴────────────────────────────────┴────────────┘ </code></pre> <p>The <code>valueDay</code> should be 2010-02-01 for all 3 values.</p> <p>Can anyone help me fix this? A pandas dt.date like way to approach this would be nice.</p> <p>By the way, what is the best way to optimize this code? Do I constantly have to assign everything to <code>df</code> or is there a way to chain all of this?</p>
<python><date><datetime><timezone><python-polars>
2023-01-28 14:17:20
2
308
brokkoo
75,268,174
8,958,754
pygame maintain a points position around a rotated image
<p>In pygame I have an image object of a frigate at 0 degrees of rotation. On it i have turrets, i need to calculate their new position if the frigate rotates by say 90 degrees.</p> <p>After rotating the image like so,</p> <pre><code>rotatedFrigate = pygame.transform.rotate(gui.frigate[0], facingAngle) </code></pre> <p>I have tried various ways such as rotating the point,</p> <pre><code>point = pygame.math.Vector2(turretx, turretY) rotated_point = point.rotate(facingAngle) </code></pre> <p>Even adding on the original x,y coords still has it far off</p> <pre><code>t1x,t1y = rotated_point[0]+point[0], rotated_point[1]+point[1] </code></pre> <p>I have also tried rotation matrix approach using midpoint and adding new adjusted dims.</p> <pre><code>xm,ym = self.x + 0.5*self.w,self.y + 0.5*self.h a = math.radians(facingAngle) # Convert to radians xr = (x - xm) * math.cos(a) - (y - ym) * math.sin(a) + xm yr = (x - xm) * math.sin(a) + (y - ym) * math.cos(a) + ym rotatedFrigate = pygame.transform.rotate(gui.frigate[0], facingAngle) t1x,t1y = xr + 0.5*rotatedFrigate.get_width(),yr+ 0.5*rotatedFrigate.get_height() </code></pre> <p>For the turret :</p> <pre><code>turretx, turretY = self.x,self.y+0.05*self.h </code></pre> <p>Self refers to the frigate coords prior to rotation</p> <p>Frigate image center coordinates are calculated using</p> <pre><code>xm,ym = self.x + 0.5*self.w,self.y + 0.5*self.h </code></pre> <p>Where w &amp; h are used on the frigate image <code>get_width() get_height()</code> methods.</p> <p>Again prior to rotation.</p> <p>Both approaches don't seem to work, sometimes they are close but most of the times they are far out.</p> <p><strong>Additional Info</strong></p> <p>Picture is if i use <code>rotated_point = (point - pivot).rotate(-facingAngle) + pivot</code></p> <p><a href="https://i.sstatic.net/0zy3T.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0zy3T.jpg" alt="enter image description here" /></a></p>
<python><image><pygame><pygame-surface>
2023-01-28 13:58:27
1
855
Murchie85
75,268,149
20,266,647
Read parquet in MLRun, "Unable to infer schema for Parquet. It must be specified manually."
<p>I got this issue, when I ingested/wrote data to FeatureSet (part of MLRun FeatureStore) and than I read the data via PySpark (it seems as invalid parquet). See exception:</p> <pre><code>AnalysisException Traceback (most recent call last) &lt;ipython-input-8-a8c688f9ceb5&gt; in &lt;module&gt; ----&gt; 1 newDF1 = spark.read.parquet(f&quot;v3io://projects/{project_name}/FeatureStore/FS-ingest&quot;) 2 newDF1.show() /spark/python/pyspark/sql/readwriter.py in parquet(self, *paths, **options) 299 int96RebaseMode=int96RebaseMode) 300 --&gt; 301 return self._df(self._jreader.parquet(_to_seq(self._spark._sc, paths))) 302 303 def text(self, paths, wholetext=False, lineSep=None, pathGlobFilter=None, /spark/python/lib/py4j-0.10.9.3-src.zip/py4j/java_gateway.py in __call__(self, *args) 1320 answer = self.gateway_client.send_command(command) 1321 return_value = get_return_value( -&gt; 1322 answer, self.gateway_client, self.target_id, self.name) 1323 1324 for temp_arg in temp_args: /spark/python/pyspark/sql/utils.py in deco(*a, **kw) 115 # Hide where the exception came from that shows a non-Pythonic 116 # JVM exception message. --&gt; 117 raise converted from None 118 else: 119 raise AnalysisException: Unable to infer schema for Parquet. It must be specified manually. </code></pre> <p>See the key part of source code (which generated the exception):</p> <pre><code>... feature_set1=fstore.FeatureSet(name=&quot;FS-ingest&quot;,entities=[fstore.Entity('app'),fstore.Entity('id')],engine=&quot;spark&quot;,timestamp_key='time') feature_set1.set_targets(targets=[ParquetTarget(name=&quot;s1&quot;,partitioned=False),NoSqlTarget(name=&quot;s2&quot;)],with_defaults=False) feature_set1.save() fstore.ingest(f&quot;store://feature-sets/{project_name}/FS-ingest&quot;, sparkDF,spark_context=spark, overwrite=True) ... newDF1 = spark.read.parquet(f&quot;v3io://projects/{project_name}/FeatureStore/FS-ingest&quot;) newDF1.show() </code></pre> <p>Did you see similar issue?</p> <p>NOTE: Parquet path contains parquet files (all files are valid), it means the ingestion was succesful.</p>
<python><pyspark><parquet><feature-store><mlrun>
2023-01-28 13:54:14
1
1,390
JIST
75,267,907
4,576,519
How to import a cached numba function without a Python definition
<p>Consider the following function in <code>numba</code>, which just serves as an example:</p> <pre class="lang-py prettyprint-override"><code>import numba as nb import numpy as np @nb.njit('float64(float64[::1])', cache=True) def total (x): ''' Sum the elements of an array. ''' total = 0 for i in range(x.shape[0]): total += x[i] return total x = np.arange(100,dtype=np.float64) print(total(x)) </code></pre> <p>Since I have specified the <code>cache=True</code> option, two files are created in the <code>__pycache__</code> folder, one <code>.nbc</code> file and one <code>.nbi</code> file. I assume that these files contain all (compiled) information about the function. Let's say I delete the Python file that defines the function (i..e, the above code).</p> <p><strong>Can I still use compiled/cached functions? In other words, can I import them without having the original .py file that defined them?</strong></p>
<python><caching><import><numba><jit>
2023-01-28 13:12:57
1
6,829
Thomas Wagenaar
75,267,745
20,520
How can I share a large data structure among forked Python processes?
<p>I'm creating a 58 GB graph in a Python program, which I then want to process through multiple (Linux) processes. For that I'm using a <code>ProcessPoolExecutor</code> with a <code>fork</code> context, passing to each process just an integer associated with the chunk associated with it.</p> <pre class="lang-py prettyprint-override"><code> with concurrent.futures.ProcessPoolExecutor(mp_context=mp.get_context('fork')) as executor: futures = [] for start in range(0, len(vertices_list), BATCH_SIZE): future = executor.submit(process_batch, start) futures += [future] </code></pre> <p>The <code>process_batch</code> function calculates a metric of the graph's vertices, and returns a small list of results. Both <code>vertices_list</code> and <code>graph</code> are global variables. The <code>graph</code> variable is bound to a <a href="https://github.com/dspinellis/fast-cdindex/" rel="nofollow noreferrer">C++ Python extension module</a> that implements the required data structure and calculation.</p> <pre class="lang-py prettyprint-override"><code>def process_batch(start): results = [] for v in vertices_list[start:start + BATCH_SIZE]: results.append((v, graph.some_metric(v))) return results </code></pre> <p>This works fine with small samples, but when I run it on the 58 GB structure, the machine grinds to a halt, with memory getting swapped out to allow the forked processes to bring in more memory in ¼ MB chunks. (Using <em>strace(1)</em> I saw a few such <em>mmap(2)</em> calls.) I saw two comments (<a href="https://stackoverflow.com/questions/64095876/multiprocessing-fork-vs-spawn#comment124419772_66113051">here</a> and <a href="https://stackoverflow.com/questions/5549190/is-shared-readonly-data-copied-to-different-processes-for-multiprocessing#comment14269453_5550156">here</a>) indicating that on Python <em>fork(2)</em> actually means copy on access, because just accessing an object will change its ref-count. This seems consistent with the behavior I'm observing: the forked processes probably attempting to create their own private copy of the data structure.</p> <p>So my question is: does Python offer a way to share an arbitrary data structure among forked Python processes? I know about <a href="https://docs.python.org/3/library/multiprocessing.shared_memory.html" rel="nofollow noreferrer">multiprocessing.shared_memory</a> and the <a href="https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow noreferrer">corresponding facilities</a>, but these concern the built-in <code>Array</code> and <code>Value</code> types.</p>
<python><concurrency><fork>
2023-01-28 12:41:46
0
19,463
Diomidis Spinellis
75,267,719
20,646,427
Trying to get and update or create model from json in Django
<p>Im trying to get and update or create object in model from json list of dicts but i got an error btw my code is creating objects but cant update them:</p> <p>&quot;TypeError: Tried to update field authentication.CounterParty.GUID with a model instance, &lt;CounterParty: CounterParty object (3)&gt;. Use a value compatible with UUIDField. &quot;</p> <p>models.py</p> <pre><code>class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150) customer = models.BooleanField(default=False) contractor = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Counter Party' </code></pre> <p>tasks.py</p> <pre><code>def create_counter_party(): response = [ { &quot;CounterpartyGUID&quot;: &quot;e58ed763-928c-4155-bee9-fdbaaadc15f3&quot;, &quot;CounterpartyName&quot;: &quot;name1&quot;, &quot;Customer&quot;: False, &quot;Contractor&quot;: True }, { &quot;CounterpartyGUID&quot;: &quot;123e4567-e89b-42d3-a456-556642440000&quot;, &quot;CounterpartyName&quot;: &quot;name2&quot;, &quot;Customer&quot;: False, &quot;Contractor&quot;: False }, ] rep = response for item in rep: try: counter_party = CounterParty.objects.get(GUID=item['CounterpartyGUID']) updated_counter_party = CounterParty.objects.update(GUID=counter_party, name=item['CounterpartyName'], customer=item['Customer'], contractor=item['Contractor']) updated_counter_party.save() except CounterParty.DoesNotExist: counter_party = CounterParty.objects.create(GUID=item['CounterpartyGUID'], name=item['CounterpartyName'], customer=item['Customer'], contractor=item['Contractor']) counter_party.save() </code></pre> <p>errors:</p> <pre><code>[2023-01-28 15:29:31,894: ERROR/ForkPoolWorker-8] Task authentication.tasks.create_counter_party[a86333d9-e039-479e-8d35-37fa6b17dbfa] raised unexpected: TypeError('Tried to update field authentication.CounterParty.GUID with a model instance, &lt;CounterParty: CounterParty object (3)&gt;. Use a value compatible with UUIDField.') Traceback (most recent call last): File &quot;/home/zesshi/.local/lib/python3.9/site-packages/celery/app/trace.py&quot;, line 451, in trace_task R = retval = fun(*args, **kwargs) File &quot;/home/zesshi/.local/lib/python3.9/site-packages/celery/app/trace.py&quot;, line 734, in __protected_call__ return self.run(*args, **kwargs) File &quot;/mnt/c/Users/Shalltear/Desktop/Python/unica_django/authentication/tasks.py&quot;, line 27, in create_counter_party counter_party = CounterParty.objects.update(GUID=counter_party, name=item['CounterpartyName'], File &quot;/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/manager.py&quot;, line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File &quot;/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/query.py&quot;, line 1191, in update rows = query.get_compiler(self.db).execute_sql(CURSOR) File &quot;/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/sql/compiler.py&quot;, line 1822, in execute_sql cursor = super().execute_sql(result_type) File &quot;/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/sql/compiler.py&quot;, line 1385, in execute_sql sql, params = self.as_sql() File &quot;/home/zesshi/.local/lib/python3.9/site-packages/django/db/models/sql/compiler.py&quot;, line 1782, in as_sql raise TypeError( TypeError: Tried to update field authentication.CounterParty.GUID with a model instance, &lt;CounterParty: CounterParty object (3)&gt;. Use a value compatible with UUIDField. </code></pre>
<python><django>
2023-01-28 12:37:21
0
524
Zesshi
75,267,643
1,045,755
ScatterGeo vs ScatterMapbox in Plotly.JS (Performance vs. coloring options)
<p>I have a little conundrum I was hoping someone could shed a bit of light on.</p> <p>Basically I have a bunch of paired coordinates (roughly 3000), i.e. two points that needs to be connected with a line. Depending on some value, this line (plus the two data points) needs to have a certain color. In my situation, I need to plot maybe 2-300 of those pairs with different color, and some kind of text attached to it, where the rest can have the same color, width, etc.</p> <p>In Plotly JS you can give a whole list of coordinates, separated by a None for each pair, and then it draws a line between each pair. For example:</p> <pre><code>lon = [50.2, 51.2, None, 51.8, 49.6, None, 53.1, 53.6] lat = [10.2, 11.2, None, 12.8, 13.6, None, 12.1, 11.6] </code></pre> <p>The problem is that it seems like I can't change the color of the line for each individual pair. I can do it for the markers by just adding:</p> <pre><code>color = [&quot;red&quot;, &quot;red&quot;, None, &quot;blue&quot;, blue&quot;, None, &quot;purple&quot;, &quot;purple&quot;] </code></pre> <p>But lines, I haven't been able to find anything that helps me. Again, this is not an issue for the remaining pairs (2800 pairs left). They can be all the same color. However, the 200 that needs different colors and stuff, well, you can't (at least not to my knowledge).</p> <p>In order to fix this, well, I can do it as <code>traces</code> instead. So for each coordinate pair that needs coloring, I can just create a <code>trace</code> with a line color, marker color, etc. The problem there is, that when I reach something like a few hundred, <code>scattermapbox</code> gets really poor performance.</p> <p>I can then try to use <code>scattergeo</code> instead, which is more tolerant towards <code>traces</code> (in my experience). However, <code>scattergeos</code> problem seems to be that if I then plot the remaining 2800 pairs, even with one list like for <code>scattermapbox</code> (so not 2800 new traces) then IT gets really low performance. So I'm kind of stuck between this annoying middle where none of the options can fully complete my task without it missing some key feature such as performance or coloring.</p> <p>Am I just missing something, or is that just how it is ?</p>
<python><reactjs><plotly><mapbox><plotly.js>
2023-01-28 12:24:30
0
2,615
Denver Dang
75,267,629
10,613,037
Create a view that accepts a post request and performs an action regardless of if the instance has been created or not
<p>I've got a view that takes in a phone number, and if the phone number isn't created, it'll send an SMS otp with <code>send_otp</code>. Now I want to also implement it so that if a phone number is sent to the endpoint but has already been registered to a user, then the view will send an otp all the same.</p> <p>Right now, I get an error <code>&quot;phone_number&quot;: [&quot;user with this phone number already exists.&quot;]</code> when I try pass in a phone number for a user that already exists. How can I override this behaviour so the view doesn't check if the phone number is already registered to a user or not and just returns a <code>phone_number</code> json.</p> <p>I have added breakpoints to <code>perform_create</code> , <code>save</code>, <code>create</code>, <code>update</code> methods but none of them get hit when I try pass in a phone number for a user that's already created</p> <p>views.py</p> <pre class="lang-py prettyprint-override"><code>class SendOTPCode(generics.CreateAPIView): permission_classes= [AllowAny] serializer_class= PhoneNumberSerializer </code></pre> <p>serializers.py</p> <pre class="lang-py prettyprint-override"><code>class PhoneNumberSerializer(serializers.ModelSerializer): class Meta: model = User fields = (&quot;phone_number&quot;,) def save(self, *args, **kwargs): phone_number = self.validated_data['phone_number'] send_otp(to_phone_number=phone_number) return None </code></pre> <p>models.py</p> <pre class="lang-py prettyprint-override"><code>class User(AbstractBaseUser): phone_number = PhoneNumberField(blank=True, unique = True, null = True) </code></pre>
<python><django-rest-framework>
2023-01-28 12:22:37
1
320
meg hidey
75,267,623
5,567,893
How to set the DGL node features from networkx graph
<p>I'd like to convert the networkx graph to dgl data. <br /> But when I tried using <code>dgl.from_networkx</code> like tutorial, there was unexpected result.</p> <pre class="lang-py prettyprint-override"><code>import dgl import networkx as nx import numpy as np import torch #Construct the networkx graph G containing three nodes, 2 undirected edges, #and three node attributes (i.e., 3-dimension of node features) G = nx.Graph() G.add_nodes_from([ (1, {&quot;x_0&quot;: 0.1, &quot;x_1&quot;: 0.3, &quot;x_2&quot;: 0.7}), (2, {&quot;x_0&quot;: 0.1, &quot;x_1&quot;: 0.3, &quot;x_2&quot;: 0.7}), (3, {&quot;x_0&quot;: 0.1, &quot;x_1&quot;: 0.3, &quot;x_2&quot;: 0.7}), ]) G.add_edges_from([(1, 2), (2, 1), (1, 3), (3,1)]) #Additionally, I add this code because the original dataset is called from .csv file. #So, the below code means the list of features #.csv file: node(row) x features(colum) cols = list([&quot;x_0&quot;, &quot;x_1&quot;, &quot;x_2&quot;]) #Convert networkx from dgl dgl_graph = dgl.from_networkx(G, node_attrs=cols) #DGL Result #Graph(num_nodes=3, num_edges=4, # ndata_schemes={'x_0': Scheme(shape=(), dtype=torch.float32), 'x_1': Scheme(shape=(), dtype=torch.float32), 'x_2': Scheme(shape=(), dtype=torch.float32)} # edata_schemes={}) </code></pre> <p>When I run this in pytorch geometric, it returns what I think.</p> <pre class="lang-py prettyprint-override"><code>from torch_geometric.utils.convert import from_networkx pyg_graph = from_networkx(G, group_node_attrs=all) pyg_graph #PyG Result #Data(edge_index=[2, 4], x=[3, 3]) </code></pre> <p>Does DGL result has the same meaning with PyG result? If not, how can I move the node attributes to DGL node feature?</p>
<python><networkx><directed-graph><pytorch-geometric><dgl>
2023-01-28 12:21:55
1
466
Ssong
75,267,582
11,944,499
Python environment setup seems complicated and unsolvable
<p>I've been a developer for about three years, primarily working in TypeScript and Node.js. I'm trying to broaden my skillset by learning Python (and eventually expanding my learning of <a href="https://en.wikipedia.org/wiki/Computer_vision" rel="nofollow noreferrer">computer vision</a>, <a href="https://en.wikipedia.org/wiki/Machine_learning" rel="nofollow noreferrer">machine learning</a> (ML), etc.), but I feel incredibly frustrated by trying to get Python to work consistently on my machine. Surely I'm doing something wrong, but I just can't really understand what it is.</p> <p>I've run into these problems mostly when using ML packages (<a href="https://en.wikipedia.org/wiki/TensorFlow" rel="nofollow noreferrer">TensorFlow</a>, <a href="https://github.com/openai/whisper" rel="nofollow noreferrer">Whisper</a>, <a href="https://en.wikipedia.org/wiki/OpenCV" rel="nofollow noreferrer">OpenCV</a> (although I was eventually able to resolve this), so I don't know if it's related to <a href="https://en.wikipedia.org/wiki/Apple_M1" rel="nofollow noreferrer">M1</a> support of one of the common dependencies, etc.</p> <p>My current understanding of Python is that:</p> <ul> <li>M1 support of Python is version-dependent at best.</li> <li><a href="https://docs.python.org/3/library/venv.html" rel="nofollow noreferrer">venv</a> is the only environment manager I should need to use</li> <li>I should use <a href="https://github.com/pyenv/pyenv" rel="nofollow noreferrer">pyenv</a> to install Python versions so as to not conflict with OS-installed python (<a href="https://en.wikipedia.org/wiki/MacOS" rel="nofollow noreferrer">macOS</a> dependencies)</li> </ul> <p>I'll use the latest project I'm working on as an example.</p> <h3>My machine and environment</h3> <blockquote> <p><a href="https://en.wikipedia.org/wiki/MacBook_Pro#Sixth_generation_(M1)" rel="nofollow noreferrer">Mac Pro M1</a>, <a href="https://en.wikipedia.org/wiki/MacOS_Monterey" rel="nofollow noreferrer">macOS v12.6</a> (Monterey) <br /> pyenv 2.3.9 <br /> Python 3.7.13 <br /> <a href="https://en.wikipedia.org/wiki/Fish_(Unix_shell)" rel="nofollow noreferrer">Fish</a> shell version 3.5.1</p> </blockquote> <p>My general workflow to get a project started:</p> <ol> <li>Create a virtual environment using venv <code>python3 -m venv &lt;some_environment_name&gt;</code></li> <li>Open created directory using Visual Studio Code, and activate the virtual environment</li> </ol> <ul> <li>Here is where I encounter my first issue, which seems to be persistent.</li> </ul> <pre class="lang-none prettyprint-override"><code>source /Users/paal/src/whisper_transcription </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>/bin/activate.fish functions: Function '_old_fish_prompt' does not exist ~/src/whisper_transcription/bin/activate.fish (line 18): functions -c _old_fish_prompt fish_prompt ^ in function 'deactivate' with arguments 'nondestructive' called on line 30 of file ~/src/whisper_transcription/bin/activate.fish from sourcing file ~/src/whisper_transcription/bin/activate.fish (Type 'help functions' for related documentation) functions: Function 'fish_prompt' does not exist ~/src/whisper_transcription/bin/activate.fish (line 47): functions -c fish_prompt _old_fish_prompt ^ from sourcing file ~/src/whisper_transcription/bin/activate.fish (Type 'help functions' for related documentation) fish: Unknown command: _old_fish_prompt ~/src/whisper_transcription/bin/activate.fish (line 71): _old_fish_prompt ^ in function 'fish_prompt' in command substitution (whisper_transcription) </code></pre> <p>So, to resolve this, I add the following <em>if</em> statement to the <em>fish.config</em> file.</p> <pre class="lang-none prettyprint-override"><code>if type -q $program _old_fish_prompt end </code></pre> <p>Looking at GitHub issues, this seems to be a persistent issue for the Fish shell and this seems to at least temporarily resolve it.</p> <p>Or, I just switch to <a href="https://en.wikipedia.org/wiki/Z_shell" rel="nofollow noreferrer">Z shell</a> (executable <code>zsh</code>).</p> <p>OK, so with that resolved I move on. The environment is activated, I'm using Z shell now, and I can successfully run a Python script that prints &quot;hello world&quot; to the console.</p> <p>Then comes the nightmare of installing any packages. It seems like any project I start has some weird edge case of compatibility issues. Between M1 processors, Python versions, builds not working correctly, etc.</p> <p>For example,</p> <pre><code>import whisper ... # The rest of the file </code></pre> <p>This with any other code or even <em>by itself</em> throws the following error:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File &quot;main.py&quot;, line 1, in &lt;module&gt; import whisper File &quot;/Users/paal/src/whisper_transcription/lib/python3.7/site-packages/whisper/__init__.py&quot;, line 12, in &lt;module&gt; from .decoding import DecodingOptions, DecodingResult, decode, detect_language File &quot;/Users/paal/src/whisper_transcription/lib/python3.7/site-packages/whisper/decoding.py&quot;, line 514 if prefix := self.options.prefix: ^ SyntaxError: invalid syntax </code></pre> <p>This appears to be some problem with the Python version. From what I understand, the <code>:=</code> operator isn't valid syntax until Python 3.8. However, dependencies of Whisper (PyTorch) <a href="https://stackoverflow.com/questions/56239310/could-not-find-a-version-that-satisfies-the-requirement-torch-1-0-0">only seems to be supported up to version 3.7.9</a>.</p> <p>So, you can see, it seems like I just end up in these bizarre circular problems where some dependency of some package I want to use isn't supported by either the platform or the current Python version, and they seem basically unsolvable (at least with my current knowledge of Python).</p> <p>Why is this seemingly so complicated? I'm clearly doing something wrong here, and obviously I'm out of my comfort and knowledge zone, but these issues feel very daunting and opaque, and difficult to actually troubleshoot this in any consistent or clear way.</p> <p>Is there a resource that makes this stuff more clear? Is Python development on M1 chips just this broken at the moment? How can I get past these seemingly basic issues to start actually learning?</p> <p>I'm not necessarily looking for a solution to this specific problem here, but if there’s general advice about environment management and how to make things work somewhat reliably, I'm fine troubleshooting. I just feel like every time I start trying to learn, I end up in these rabbit holes that take hours and hours to fix and sometimes don't even really resolve things.</p>
<python><python-3.x>
2023-01-28 12:16:11
3
351
this