Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
1,908,700
69,734,821
proper implementation of pandas concat
<pre><code>concat = pd.concat([data_1, data_2]) </code></pre> <p>above code works on multiple CSVs but it duplicates the column tried reset_index and axis=0 but no good.</p> <p>all CSVs have 21 columns but the code gives me 42 columns after concat</p> <p>Any suggestions, ideas, comments are much appreciated.</p> <p>Thanks</p>
<p>Have you tried using <code>axis=1</code> . It will concatenate column wise.</p> <pre><code>concat = pd.concat([data_1, data_2], axis =1) </code></pre>
python|pandas|concatenation
0
1,908,701
69,973,528
Error trying to install matplotlib in Windows
<p>I'm trying to install matplotlib for Python 3.10 in Windows. Im using pip: <code>pip install matplotlib</code> I've already installed NumPy, Cython, Pillow and other libraries needed. But it shows this error:</p> <pre><code>error: Failed to download any of the following: ['http://www.qhull.org/download/qhull-2020-src-8.0.2.tgz']. Please download one of these urls and extract it into 'build/' at the top-level of the source repository. </code></pre> <p>I've downloaded the said library and copied it in <code>.cache/matplotlib/build</code> but it doesnt work.</p> <p>Any idea?</p>
<p>So as @FlyingTeller commented, there are no stable realeses of matplotlib so using <code>--pre</code> fixed the problem.</p>
python|windows|matplotlib|pip|qhull
0
1,908,702
18,098,061
Change the ticklabel orientation and legend position of plot
<p>I am plotting a bar graph by reading data from a CSV using pandas in Python. I read a CSV into a <code>DataFrame</code> and plot them using matplotlib. </p> <p>Here is how my CSV looks like:</p> <pre><code>SegmentName Sample1 Sample2 Sample3 Loop1 100 100 100 Loop2 100 100 100 </code></pre> <hr> <pre><code>res = DataFrame(pd.read_csv("results.csv", index_col="SegmentName")) </code></pre> <p>I plot and set the legend to be outside. </p> <pre><code>plt.figure() ax = res.plot(kind='bar') ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig("results.jpg") </code></pre> <p>However, the x-axis ticklabels are orientated vertically and hence I can't read the text. Also my legend outside is cut off.</p> <p>Can I change the orientation of the ticklabels to be horizontal, and then adjust the entire figure so that the legend is visible?</p> <p><img src="https://i.stack.imgur.com/2qHkM.jpg" alt="enter image description here"></p>
<p>Try using the 'rotation' keyword when you set the label. E.g.:</p> <pre><code>plt.xlabel('hi',rotation=90) </code></pre> <p>Or if you need to rotate the tick labels, try:</p> <pre><code>plt.xticks(rotation=90) </code></pre> <p>As for the positioning of the legend etc., it is probably worth taking a look at the <a href="http://matplotlib.org/users/tight_layout_guide.html" rel="noreferrer">tight layout guide</a></p>
python|matplotlib|pandas
10
1,908,703
60,774,191
Change Date/Timestamp Format from Excel object datatype to Pandas Dataframe (String)
<p>So I have managed to extract a specific cell from the Excel but now I have gotten this instead:</p> <p><strong>2020-01-30T00:00:00.000000000</strong> </p> <p>I removed the characters after the 'T' by using split function:</p> <pre><code>d1 = d.str.split("T",n=1, expand=True)[0] </code></pre> <p>and the result is: <strong>2020-01-30</strong></p> <p>My question is how do I change the date format to dd/mm/yyyy.</p> <p>I am aware of the strftime function by I failed to get a result from that. The errors always show that the series does not have series attribute or date.datetime is not an attribute of the string. </p> <p>Here is the working code:</p> <pre><code> import pandas as pd import datetime df = pd.read_csv('test1.xlsx', #header=None, #names = headers, dtype = dtypes, parse_dates = pdate, date_parser=None) d = df['AA'] d1 = d.str.split("T",n=1, expand=True)[0] d2 = d1[0] print(d2) AA Num 0 2020-01-01 5 1 2020-02-01 10 2 2020-03-01 15 3 2020-04-01 20 4 2020-05-01 25 </code></pre>
<p>First idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>:</p> <pre><code>df['AA'] = pd.to_datetime(df['AA']) </code></pre> <p>If need remove values after <code>T</code> your solution should be changed to:</p> <pre><code>df['AA'] = pd.to_datetime(df['AA'].str.split("T").str[0]) </code></pre>
python|excel|pandas
0
1,908,704
61,174,906
Pandas new column as result of sum in date range
<p>having this dataframe:</p> <pre><code> provincia contagios defunciones fecha 0 distrito nacional 11 0 18/3/2020 1 azua 0 0 18/3/2020 2 baoruco 0 0 18/3/2020 3 dajabon 0 0 18/3/2020 4 barahona 0 0 18/3/2020 </code></pre> <p>How can I have a new dataframe like this:</p> <pre><code> provincia contagios_from_march1_8 defunciones_from_march1_8 0 distrito nacional 11 0 1 azua 0 0 2 baoruco 0 0 3 dajabon 0 0 4 barahona 0 0 </code></pre> <p>Where the 'contagios_from_march1_8' and 'defunciones_from_march1_8' are the result of the sum of the 'contagios' and 'defunciones' in the date range 3/1/2020 to 3/8/2020.</p> <p>Thanks.</p>
<p>Can use df.sum on a condition. Eg.:</p> <pre><code> df[df["date"]&lt;month]["contagios"].sum() </code></pre> <p>refer to this for extracting month out of date: <a href="https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column">Extracting just Month and Year separately from Pandas Datetime column</a></p>
python|pandas|dataframe
0
1,908,705
66,027,707
Python Mutagen tag KeyError, how to pass when tag does not exists
<p>In Mutagen i read tags form an audiofile but when the tag don't exist, i get an error of course.</p> <pre><code>audio = ID3(musicfile) print(audio['TXXX:SERIES'].text[0]) KeyError: 'TXXX:SERIES' </code></pre> <p>how to move on if tag don't exist?</p> <p>i have tried:</p> <pre><code> if audio['TXXX:SERIES'].text[0] is None: print('No series') else: </code></pre> <p>also</p> <pre><code>if not audio['TXXX:SERIES'].text[0]: print('No series') else: </code></pre> <p>still gives an error.</p> <pre><code>Traceback (most recent call last): File &quot;D:\xxxxx\all_the_program.py&quot;, line 163, in &lt;module&gt; if audio['TXXX:SERIES'].text[0] is None: File &quot;D:\xxxxx\venv\lib\site-packages\mutagen\_util.py&quot;, line 537, in __getitem__ return self.__dict[key] Traceback (most recent call last): File &quot;D:\xxxxx\all_the_program.py&quot;, line 163, in &lt;module&gt; if not audio['TXXX:SERIES'].text[0]: File &quot;D:\xxxxxx\venv\lib\site-packages\mutagen\_util.py&quot;, line 537, in __getitem__ return self.__dict[key] KeyError: 'TXXX:SERIES' </code></pre>
<p>You have to use try/except:</p> <pre><code>try: print(audio['TXXX:SERIES'].text[0]) except: print('An exception occurred') </code></pre> <p>And if you want that nothing happens when an exception occurs, just use pass:</p> <pre><code>try: print(audio['TXXX:SERIES'].text[0]) except: pass </code></pre> <p>You can learn more about catching exceptions / exceptions handling here: <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/errors.html</a></p>
python|mutagen
1
1,908,706
66,086,978
Using Python to access outlook with win32com
<p>I'm struggling with python integration with outlook using win32com.client.</p> <p>All I am trying to do is get the most recent email from outlook and (at the moment) retrieve and print the name of the attachment</p> <p><strong>The code I'm trying to use:</strong></p> <pre class="lang-py prettyprint-override"><code>import win32com.client outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).GetNamespcae(&quot;MAPI&quot;) inbox = outlook.GetDefaultFolder(6) message = inbox.GetLast() att = message.Attachmets print (att.filename) </code></pre> <p><strong>Output</strong></p> <p><code>com_error: (-2147221005, 'Invalid class string', None, None)</code></p> <p>Any help would really be appreciated.</p>
<p><em>The error is Outlook can't be found on the system but You have also misspelled <strong><code>GetNamespace</code></strong>, you have <strong><code>GetNamespcae</code></strong></em></p> <p><em>Change <code>inbox.GetLast()</code>, to <code>messages = inbox.Items</code> then <code>message = messages.GetLast()</code></em></p> <p><em>Example</em></p> <pre><code>import win32com.client outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;).GetNamespace(&quot;MAPI&quot;) inbox = outlook.GetDefaultFolder(6) messages = inbox.Items messages.Sort('[ReceivedTime]', False) message = messages.GetLast() for attachment in message.Attachments: print(attachment.FileName) </code></pre> <p><em>Here is another example with filter <a href="https://stackoverflow.com/a/57931132/4539709">https://stackoverflow.com/a/57931132/4539709</a></em></p>
python|email|outlook|attachment|win32com
1
1,908,707
69,187,362
why is my flask app not connecting to the right room
<p>I was trying to make a multiroom app with flask and flask socket-io integration but i think something is offset as if I try to join another room on another tab it sends the info to all rooms and other rooms show someone has joined in that room and after that if I send message it also don't work. here's my code</p> <pre><code>from flask_socketio import SocketIO, join_room from colorama import Fore, Style app = Flask(__name__) socketio = SocketIO(app) @app.route(&quot;/&quot;) def home(): return render_template(&quot;index.html&quot;) @app.route(&quot;/chat&quot;) def chat(): username = request.args.get(&quot;username&quot;) room = request.args.get(&quot;room&quot;) if username and room: return render_template(&quot;chat.html&quot;, username=username, room=room) else: return redirect(url_for(&quot;home&quot;)) @socketio.on('join_room') def handle_join_room(data): info = &quot;[INFO] &quot;+f&quot;[ROOM: {data['room']}]: &quot;+f&quot;User {data['username']} has joined&quot; print(Fore.CYAN+info) join_room(data['room']) socketio.emit('join_room_ann', data) Style.RESET_ALL @socketio.on('send_mess') def handle_mess(data): info = f&quot;[MESSAGE][ROOM: {data['room']}][USER:{data['username']}]: {data['message']}&quot; print(info) if __name__ == &quot;__main__&quot;: socketio.run(app, debug=True)}``` and html side client [{% extends &quot;common.html&quot; %} {% block index %} &lt;div class=&quot;log left&quot;&gt; &lt;p&gt;Username:&lt;/p&gt; &lt;p class=&quot;cls&quot;&gt;{{username}}&lt;/p&gt; &lt;p&gt;Room:&lt;/p&gt; &lt;p class=&quot;cls&quot;&gt;{{room}}&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;messages&quot; class='bottoml log'&gt; &lt;p&gt;in room:&lt;/p&gt; &lt;/div&gt; &lt;form action=&quot;&quot; id=&quot;inp_form&quot;&gt; &lt;div class=&quot;log chat&quot;&gt; &lt;div class=&quot;in&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;inp_box&quot; class=&quot;chat_in&quot; placeholder=&quot;Type your text&quot;&gt; &lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; {% endblock %} {% block chat %} &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.2.0/socket.io.js&quot;&gt;&lt;/script&gt; &lt;script&gt; const socket = io.connect(&quot;http://127.0.0.1:5000&quot;); socket.on('connect', function(){ socket.emit(&quot;join_room&quot;,{ username:&quot;{{username}}&quot;, room:&quot;{{room}}&quot; }); let inp_box = document.getElementById('inp_box'); document.getElementById('inp_form').onsubmit = function (e){ e.preventDefault(); mes = inp_box.value.trim(); if (mes.length){ socket.emit('send_mess', { username:&quot;{{username}}&quot;, room:&quot;{{room}}&quot;, message:mess }) } inp_box.value=''; inp_box.focus(); } }); socket.on('join_room_ann', function(data){ console.log(data); const newnode = document.createElement('div'); newnode.innerHTML = `${data.username}`; newnode.className+=&quot;newn&quot; document.getElementById('messages').appendChild(newnode); }) &lt;/script&gt; {% endblock %}] </code></pre>
<p>If you want to send the join room announcement just to the room in question, you have to indicate that in the <code>emit</code> call:</p> <pre><code>socketio.emit('join_room_ann', data, room=data['room']) </code></pre> <p>Without the <code>room</code> argument, the emit goes to all connected clients, regardless of what room they're in.</p>
python|flask|flask-socketio
0
1,908,708
69,001,856
Fix " Could not find a version that satisfies the requirement boto3 (from versions: ) No matching distribution found for boto3"
<p>I'm struggling installing installing Boto3 library.</p> <ul> <li><strong>Python version: 3.6.12</strong></li> <li><strong>pip version 9.0.1</strong></li> <li><strong>Server: Redhat 7.9 (Maipo) , Fedora.</strong></li> </ul> <p>I tried different comibnation to get the boto3 library:</p> <ul> <li>pip3 install boto3</li> <li>pip3 install boto</li> <li>pip3 install --extra-index-url <a href="https://pypi.python.org/simple" rel="nofollow noreferrer">https://pypi.python.org/simple</a> boto3</li> </ul> <p>but always I have the same error.</p> <p>Any idea?</p> <p>My code:</p> <pre><code>sla82716:/home/pa009999/scriptDirectory $ pip3 install boto Collecting boto Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f8fb0f74e10&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f8fb0f74208&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f8fb0f742b0&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f8fb0f74320&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f8fb0f743c8&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto/ Could not find a version that satisfies the requirement boto (from versions: ) No matching distribution found for boto sla82716:/home/pa009999/scriptDirectory $ pip3 install boto3 Collecting boto3 Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f08a5642f98&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f08a5642438&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f08a5642400&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f08a56420b8&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f08a5642630&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Could not find a version that satisfies the requirement boto3 (from versions: ) No matching distribution found for boto3 sla82716:/home/pa009999/scriptDirectory $ pip3 install --extra-index-url https://pypi.python.org/simple boto3 Collecting boto3 Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f5456b85358&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f5456b85828&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f5456b85898&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f5456b85ef0&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f5456b85198&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)': /simple/boto3/ Could not find a version that satisfies the requirement boto3 (from versions: ) No matching distribution found for boto3 </code></pre>
<p>It looks like you cannot resolve the hostname. Try adding the following line (Google nameserver)</p> <pre><code>nameserver 8.8.8.8 </code></pre> <p>to the <code>/etc/resolv.conf</code> file (e.g., by using <code>nano /etc/resolv.conf</code>). You can only add three nameservers, so you might have to delete/change one line if there are already three nameservers in the file.</p> <p>Afterwards, <code>ping google.com</code> should work and <code>pip install boto3</code> as well.</p>
python|linux|amazon-web-services|boto3
0
1,908,709
69,222,791
I'm getting this error when trying to run a django aplication: django.db.utils.OperationalError: unsupported file format
<p>The program was quite running well a few minutes ago, after adding <strong>SlugField</strong> to my post URLs <em>which I feel like it has nothing to do with the error</em>, this is what I get when I run <code>Python3 manage.py runserver</code> in my terminal.</p> <pre><code>System check identified some issues: WARNINGS: base.Post.tags: (fields.W340) null has no effect on ManyToManyField. System check identified 1 issue (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py&quot;, line 84, in _execute return self.cursor.execute(sql) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py&quot;, line 394, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: unsupported file format The above exception was the direct cause of the following exception: Traceback (most recent call last): File &quot;/usr/lib/python3.6/threading.py&quot;, line 916, in _bootstrap_inner self.run() File &quot;/usr/lib/python3.6/threading.py&quot;, line 864, in run self._target(*self._args, **self._kwargs) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/utils/autoreload.py&quot;, line 53, in wrapper fn(*args, **kwargs) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py&quot;, line 120, in inner_run self.check_migrations() File &quot;/home/peace/.local/lib/python3.6/site-packages/django/core/management/base.py&quot;, line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/executor.py&quot;, line 18, in __init__ self.loader = MigrationLoader(self.connection) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/loader.py&quot;, line 49, in __init__ self.build_graph() File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/loader.py&quot;, line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py&quot;, line 76, in applied_migrations if self.has_table(): File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py&quot;, line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/base/introspection.py&quot;, line 48, in table_names return get_names(cursor) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/base/introspection.py&quot;, line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/introspection.py&quot;, line 73, in get_table_list ORDER BY name&quot;&quot;&quot;) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py&quot;, line 100, in execute return super().execute(sql, params) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py&quot;, line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py&quot;, line 77, in _execute_with_wrappers return executor(sql, params, many, context) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py&quot;, line 86, in _execute return self.cursor.execute(sql, params) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/utils.py&quot;, line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py&quot;, line 84, in _execute return self.cursor.execute(sql) File &quot;/home/peace/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py&quot;, line 394, in execute return Database.Cursor.execute(self, query) django.db.utils.OperationalError: unsupported file format </code></pre> <p>I'm just not really sure if I should change something since there is an unsupported file format. Just not even sure about the file it's talking about :( Is it a bug or there is something I'm doing wrong?</p>
<p>I would recommend deleting your sqlite3 and migrations folders and then run the following:</p> <pre><code>python3 manage.py makemigrations &lt;app&gt; python3 manage.py migrate python3 manage.py runserver </code></pre> <p>You may refer to this link for deleting migration: <a href="https://riptutorial.com/django/example/29416/resetting-django-migration--deleting-existing-database-and-migrating-as-fresh" rel="nofollow noreferrer">https://riptutorial.com/django/example/29416/resetting-django-migration--deleting-existing-database-and-migrating-as-fresh</a></p>
python|django|compiler-errors
2
1,908,710
68,094,079
Wrap text in .txt file with Python3?
<p>Hello I explain my problem, I try to wrap my text in several lines, it's cool the methods work in the terminal, I have a wrap, but the problem is writing in my text file, impossible to wrap the text, I had to turn the function in all directions, I did not succeed, then I post the initial method if someone has an idea I am a taker</p> <pre><code>phrase = &quot;bla bla bla ceci est une phrase beaucoup trop longue pour ce que je doit réellement dire, en fait je peux même dire qu'elle ne sert a rien, mais du coup je doit quand même la tester&quot; # lim=40 # line = [] # with open(&quot;test.txt&quot;, &quot;w&quot;) as fiche: # for s in phrase.split(&quot;\n&quot;): # if s == &quot;&quot;: # break # word=0 # for d in s.split(): # if word + len(d) + 1 &lt;= lim: # line.append(d) # word += len(d) + 1 # else: # print(&quot; &quot;.join(line)) # fiche.write(&quot; &quot;.join(line)) # line = [d] # word = len(d) # if (len(line)): # print(&quot; &quot;.join(line)) # fiche.write(&quot; &quot;.join(line)) attempt n°2 : my_wrap = textwrap.TextWrapper(width = 40) wrap_list = my_wrap.wrap(text=phrase) with open(&quot;test.txt&quot;, &quot;w&quot;) as fiche: for line in wrap_list: print(line) fiche.write(&quot; &quot;.join(line)) </code></pre>
<p>You can use <a href="https://docs.python.org/3/library/textwrap.html#textwrap.fill" rel="nofollow noreferrer"><code>textwrap.fill</code></a> that automatically places newlines for you and you can write it directly to file:</p> <pre><code>with open(&quot;test.txt&quot;, &quot;w&quot;) as fiche: fiche.write(my_wrap.fill(phrase)) </code></pre> <p>and the content of <em>test.txt</em> will be:</p> <pre class="lang-none prettyprint-override"><code>bla bla bla ceci est une phrase beaucoup trop longue pour ce que je doit réellement dire, en fait je peux même dire qu'elle ne sert a rien, mais du coup je doit quand même la tester </code></pre>
python|text|txt
1
1,908,711
62,342,813
Can you loop input() to store multiple variables?
<p>e.g I want to the user to assign numbers to 3 variables </p> <pre><code>a = input() b = input() c = input() </code></pre> <p>I know you can do it like this;</p> <pre><code>a,b,c = input() &gt;&gt;&gt;1,2,3 </code></pre> <p>but I need it to be asked on separate lines like the first example. </p> <p>Is there a way to do something like this;</p> <pre><code>a,b,c = input() for range(3) </code></pre>
<p>This will work:</p> <pre><code>a,b,c = (input() for _ in range(3)) </code></pre> <p>repl.it link: <a href="http://repl.it/@HarunYlmaz/input-comprehension" rel="nofollow noreferrer">http://repl.it/@HarunYlmaz/input-comprehension</a> (Thanks to @Harun Yimaz in the comments below)</p>
python|python-3.x|input
4
1,908,712
59,733,678
Validation and Evaluation Metric Issues in TensorFlow when Transfer Learning
<p>I have come across some odd behaviours when training CNNs with Tensorflow 2.0 and would appreciate any help in solving them. I am doing transfer learning (just training the classification head) using the pre-trained networks available in 'tensorflow.keras.applications' and have noticed the following:</p> <ol> <li>For the first epoch, validation metrics are always zero, no matter what I do. </li> <li>When training after the first epoch, the training metrics improve as you would expect, but the validation metrics essentially are random guesses, even when the EXACT same dataset is used as a training and a validation dataset. It is like it isn't using the model being trained to do its evaluation.</li> </ol> <p>I have tried, VGG16, MobileNetV2, and ResNet50V2, and they all exhibit the same behaviours. </p> <p>The configurations I am able to reproduce this on are:</p> <ul> <li>Ubuntu 18.04LTS, Nvidia RTX2080ti with driver version 430.50, CUDA10.0, TensorFlow-gpu==2.0.0 </li> <li>MacBook Pro, TensorFlow==2.0.0 (cpu)</li> </ul> <p>Both are running in Conda environments and I have installed TensorFlow with pip. I have put some sample code to show the essence of my workflow down below just in case I am doing anything obviously stupid.Any help would be very appreciated as I am at a loss as to how to fix it. </p> <pre><code>def parse_function(example_proto): image_feature_description = { 'label': tf.io.FixedLenFeature([], tf.int64), 'image_raw': tf.io.FixedLenFeature([], tf.string) } parsed_example = tf.io.parse_single_example(example_proto, image_feature_description) image = tf.io.decode_image( parsed_example['image_raw'], channels = 3, dtype = tf.float32, expand_animations = False ) image = tf.image.per_image_standardization(image) label = tf.one_hot(parsed_example['label'], 24, dtype=tf.float32) return (image, label) def load_dataset(TFRecord_dir, record_name): record_files = tf.io.matching_files(os.path.join(TFRecord_dir, record_name + '.tfrecords-????')) shards = tf.data.TFRecordDataset(record_files) shards = shards.shuffle(tf.cast(tf.shape(record_files)[0], tf.int64)) dataset = shards.map(map_func=parse_function) dataset = dataset.batch(batch_size=16, drop_remainder = True) dataset = dataset.prefetch(16) return dataset base_model = tf.keras.applications.ResNet50V2( input_shape=(224,224,3), weights='imagenet', include_top = False ) base_model.trainable = False model = tf.keras.Sequential([ base_model, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(24, activation = 'softmax') ]) model.compile( optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.CategoricalCrossentropy(), metrics=[ tf.keras.metrics.CategoricalAccuracy(), tf.keras.metrics.TopKCategoricalAccuracy(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall() ]) train_dataset = load_dataset(train_dir, 'train') model.fit(train_dataset, verbose = 1, epochs= 5, validation_data = train_dataset) model.evaluate(train_dataset) </code></pre>
<p>I no longer have this problem since started using the docker images provided instead. There must have been something installed incorrectly but I don't know what. </p> <p>Also, for anyone in the same position, I found out during debugging that if you are normalising your images using <code>image = (image/127.5) - 1</code> as in <a href="https://www.tensorflow.org/tutorials/images/transfer_learning" rel="nofollow noreferrer">transfer learning with pre-trained CNN turtorial</a> change to <code>image = tf.image.per_image_standardization(image)</code> as it exhibits the same behaviour, even in the docker container, i.e.training metrics would improve, but the validation metrics would remain random on the same dataset used to train.</p>
python|tensorflow|machine-learning|keras|deep-learning
0
1,908,713
59,848,712
Variable storing only one value, python
<p>so while trying to make some updates at local database, having issues the loop is just getting last row values. </p> <ul> <li>The variables <code>id_value and cost_value</code> is getting only the last row value </li> <li>How to get all the values? to be able to update old research records</li> </ul> <p>Data:</p> <pre><code>df = pd.DataFrame({ 'id': ['09999900795', '00009991136', '000094801299', '000099900300', '0075210657'], 'Cost': ['157.05974458228403', '80.637745302714', '7', '13', '65.5495495'] }) </code></pre> <p>My code:</p> <pre><code>for index, row in df.iterrows(): id_value = [row['id']] cost_value = [row['Cost']] # this row updates the data, however the variables is getting only the last value #table.update().where(table.c.id== id_value).values(Cost=cost_value) print(id_value) print(cost_value) out[12]: ['0075210657'] ['65.5495495'] </code></pre> <p>Desired output:</p> <pre><code> ['09999900795', '00009991136', '000094801299', '000099900300', '0075210657'] ['157.05974458228403', '80.637745302714', '7', '13', '65.5495495'] </code></pre>
<p>You need to <em>append</em> values to each list; you are simply defining a new list in each iteration.</p> <pre><code>id_values = [] cost_values = [] for _, row in df.iterrows(): id_values.append(row['id']) cost_values.append(row['Cost']) </code></pre>
python|pandas
3
1,908,714
49,176,585
How to create an entry_points with setuptools with a class method?
<p>If I wrote a function like this :</p> <pre><code>def my_function(): # do something </code></pre> <p>I can create a command that run this function using :</p> <pre><code>entry_points = { 'console_scripts': [ 'my_command = module:my_function', ], }, </code></pre> <p>Suppose I have the following class:</p> <pre><code>class MyPackage: def __init__(self): # manage something with argparse and others ... def main(self): # do the job </code></pre> <p>Is there a way to use the main method of the class <code>MyPackage</code> or must I write a basic function ?</p>
<p>I believe it can be a class method or a static method but not an instance method.</p> <pre><code>class MyPackage: def __init__(self): # manage something with argparse and others ... @classmethod def main_classm(cls): # do the job @staticmethod def main_stat(): # do the job entry_points = { 'console_scripts': [ 'command1 = module:MyPackage.main_classm', 'command2 = module:MyPackage.main_stat', ], }, </code></pre>
python|setuptools
2
1,908,715
49,158,493
lazylinker_c import Error Theano
<p>I'm getting an annoying error. </p> <blockquote> <p>You can find the C code in this temporary file: /tmp/theano_compilation_error_ppkcgkmi Traceback (most recent call last): File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 75, in raise ImportError() ImportError</p> <p>During handling of the above exception, another exception occurred:</p> <p>Traceback (most recent call last): File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 92, in raise ImportError() ImportError</p> <p>During handling of the above exception, another exception occurred:</p> <p>Traceback (most recent call last): File "", line 1, in File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/<strong>init</strong>.py", line 110, in from theano.compile import ( File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/compile/<strong>init</strong>.py", line 12, in from theano.compile.mode import * File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/compile/mode.py", line 11, in import theano.gof.vm File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/vm.py", line 673, in from . import lazylinker_c File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 127, in preargs=args) File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/cmodule.py", line 2359, in compile_str (status, compile_stderr.replace('\n', '. '))) Exception: Compilation failed (return status=1): /home/ubuntu/.theano/compiledir_Linux-4.4--aws-x86_64-with-Ubuntu-16.04-xenial-x86_64-3.6.4-64/lazylinker_ext/mod.cpp:1:20: fatal error: Python.h: No such file or directory. compilation terminated..</p> </blockquote> <p>I'm using a P2 Instance from AWS where I installed Ubuntu 16.04. </p> <p>I'm just trying to <code>import theano</code> on python3.6.4</p> <p>I've re-installed theano many times, also I installed <strong>MANY</strong> other stuff and it's not working. </p> <p>I have a virtual environment and I'm using the GPU. </p> <p>I assume my GPU-CUDA-CuNN is well installed</p> <pre><code>&gt;&gt;&gt; sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) 2018-03-07 17:56:48.738855: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2018-03-07 17:56:51.390598: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:898] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2018-03-07 17:56:51.390927: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1212] Found device 0 with properties: name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235 pciBusID: 0000:00:1e.0 totalMemory: 11.17GiB freeMemory: 11.10GiB 2018-03-07 17:56:51.390955: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1312] Adding visible gpu devices: 0 2018-03-07 17:56:51.656494: I tensorflow/core/common_runtime/gpu/gpu_device.cc:993] Creating TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10764 MB memory) -&gt; physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7) Device mapping: /job:localhost/replica:0/task:0/device:GPU:0 -&gt; device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7 2018-03-07 17:56:51.787214: I tensorflow/core/common_runtime/direct_session.cc:297] Device mapping: /job:localhost/replica:0/task:0/device:GPU:0 -&gt; device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7 </code></pre> <p>In my local machine everything is working perfectly, but on the aws instance it stocks there, and it's the first time I got that error. </p> <p>I hope someone has seen aleady this kind of error. </p> <p><strong>EDIT</strong></p> <p>I solved the problem for my project, because I just need Tensorflow and somehow someone imported <code>np</code>from <code>theano</code> and not from <code>numpy</code>. However, it still a weird problem I would like to know how to fix it. Could it be a version problem with numpy? </p> <p>the line <code>75</code> from <code>lazylinker_c.py</code> is just about comparing two versions. I don't know. </p>
<p>I had the same problem for a while with Ubuntu 16.04 when I tried to move on to Python 3.6 from Python 3.5. Finally I discovered that Ubuntu 16.04 does not include the C header files for Python 3.6 by standard, so they need to be installed separately. The theano library somehow uses C for certain calculations. Running the this command:</p> <pre><code>sudo apt-get install python3.6-dev </code></pre> <p>resolved the problem for me.</p>
python|ubuntu|tensorflow|amazon-ec2|theano
9
1,908,716
49,308,068
Python replace "" to \" in text
<p>I want to manipulate my text in python. I will use this text to embed as JavaScript data. I need the text in my text file to display exactly as follows. It should have the format I mention below, not only when it prints. </p> <p>I have text:</p> <p><code>""text""</code></p> <p>and I want:</p> <p><code>\"text\"</code></p> <pre><code>with open('phase2.2.1.csv', 'w', newline='') as csvFile: writer = csv.writer(csvFile) for b in batches: writer.writerow([b.replace('\n', '').replace('""', '\\"')]) </code></pre> <p>Unfortunately, the above yields </p> <pre><code>\""text\"" </code></pre> <p>Any help will be much appreciated. </p>
<p>I would suggest:</p> <pre><code>.replace('""', '\\"') </code></pre> <p>And it really works, see:</p> <pre><code>In [8]: x = '""text""' In [9]: print(x.replace('""', '\\"')) \"text\" </code></pre>
python|string
6
1,908,717
70,896,836
How to load custom MNIST dataset using pytorch
<p>I am working on a task related to adversarial training and attacks in machine learning. I am fairly new to python/ML stuff so please bear with me. I am using code from <a href="https://github.com/as791/Adversarial-Example-Attack-and-Defense/blob/master/Adversarial_Example_(Attack_and_defense).ipynb" rel="nofollow noreferrer">this</a> repo which is working fine.</p> <p>What I want to do: I want to load custom adversarial MNIST dataset instead of simple MNIST dataset using pyTorch like they are doing here (<em>dataset = datasets.MNIST(root = './data', train=True, transform = transform, download=True)</em>). And on that data I want to run the training procedures like they are running now. Basically, I want to train the model on already created adversarial examples of the MNIST dataset.</p> <p>What I've tried: I've tried <a href="https://glassboxmedicine.com/2022/01/21/building-custom-image-data-sets-in-pytorch-tutorial-with-code/" rel="nofollow noreferrer">this</a>, and it does gives a general idea on how to load a custom dataset using pytroch but I'm stuck on how I should apply this to my case.</p> <p>My Questions:</p> <ol> <li>How exactly should I approach this?</li> <li>Can I get adversarial(fgsm,ifgsm or whatever) data of MNIST that I could use or I have to create those myself and then load it. If yes, then how?</li> </ol> <p>Below is the relevant part of the code:</p> <pre><code>import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import transforms,datasets # In[2]: np.random.seed(42) torch.manual_seed(42) # In[3]: transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.0,), (1.0,))]) dataset = datasets.MNIST(root = './data', train=True, transform = transform, download=True) train_set, val_set = torch.utils.data.random_split(dataset, [50000, 10000]) test_set = datasets.MNIST(root = './data', train=False, transform = transform, download=True) train_loader = torch.utils.data.DataLoader(train_set,batch_size=1,shuffle=True) val_loader = torch.utils.data.DataLoader(val_set,batch_size=1,shuffle=True) test_loader = torch.utils.data.DataLoader(test_set,batch_size=1,shuffle=True) # In[4]: print(&quot;Training data:&quot;,len(train_loader),&quot;Validation data:&quot;,len(val_loader),&quot;Test data: &quot;,len(test_loader)) # In[5]: use_cuda=True device = torch.device(&quot;cuda&quot; if (use_cuda and torch.cuda.is_available()) else &quot;cpu&quot;) # Full code link is attached. </code></pre>
<p>For creating creating Adversarial example :</p> <p><a href="https://www.tensorflow.org/tutorials/generative/adversarial_fgsm" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/generative/adversarial_fgsm</a></p> <p>I think the best way to implement training with adversarial network is to create adversarial data while training (see <a href="https://github.com/cleverhans-lab/cleverhans/blob/master/tutorials/tf2/mnist_tutorial.py" rel="nofollow noreferrer">https://github.com/cleverhans-lab/cleverhans/blob/master/tutorials/tf2/mnist_tutorial.py</a> for an exemple).</p>
python|tensorflow|machine-learning|pytorch|mnist
0
1,908,718
67,739,279
Distribution with Seaborn
<p>I have a pandas dataframe that is composed like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>User_id</th> <th>Calls</th> <th>Index</th> </tr> </thead> <tbody> <tr> <td>7A</td> <td>8</td> <td>19-05-2020</td> </tr> <tr> <td>10B</td> <td>5</td> <td>19-05-2020</td> </tr> <tr> <td>7A</td> <td>2</td> <td>20-05-2020</td> </tr> <tr> <td>10B</td> <td>6</td> <td>20-05-2020</td> </tr> </tbody> </table> </div> <p>With in index the dates and times at which they make their calls even if here I put it on the right under pandas say that the dates are the index on the left.</p> <p>I would like to make the distribution of the users of their number of calls that they make in the year.</p> <p>Currently there are more than 400 different users so I will not do all of them only those who have the largest number of calls that I find easily with this: <code>ret.groupby(['user_id'])['calls'].sum().sort_values(ascending=False).head(10)</code></p> <p>I try to make a loop that takes the first 10 users who have the most calls and makes their distribution of calls in the year (so we have on the x-axis the months of the year written in number or not, on the y-axis the density or the number of calls, and we would have a title to say of which users we made the graph)</p> <p>How can I do it?</p>
<p>IIUC try <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html#pandas-dataframe-resample" rel="nofollow noreferrer"><code>resample sum</code></a> to get total calls per month then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html#pandas-dataframe-plot" rel="nofollow noreferrer"><code>plot</code></a>:</p> <p>*Note the provided data contains only a single month, so I added a second month to make the graph more clear:</p> <pre><code>import pandas as pd from matplotlib import pyplot as plt df = pd.DataFrame({'User_id': ['7A', '10B', '7A', '10B'], 'Calls': [8, 5, 2, 6], 'Index': ['19-05-2020', '19-05-2020', '20-06-2020', '20-06-2020']}).set_index('Index') df.index = pd.to_datetime(df.index, format='%d-%m-%Y') users = ','.join(df['User_id'].unique()) plot_df = df.resample('1M')['Calls'].sum() ax = plot_df.plot(kind='bar', rot=0, title=users, ylabel='Calls', xlabel='Months') ax.set_xticklabels(plot_df.index.strftime(&quot;%Y-%m&quot;)) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/LseYE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LseYE.png" alt="graph" /></a></p> <hr/> <p><code>df</code>:</p> <pre><code> User_id Calls Index 2020-05-19 7A 8 2020-05-19 10B 5 2020-06-20 7A 2 2020-06-20 10B 6 </code></pre> <p><code>users</code>:</p> <pre><code>7A,10B </code></pre> <p><code>plot_df</code>:</p> <pre><code>Index 2020-05-31 13 2020-06-30 8 Freq: M, Name: Calls, dtype: int64 </code></pre>
python|pandas|seaborn
0
1,908,719
67,889,852
Re-synchronizing timestamps of InfluxDB values
<p>I have several values being put into an InfluxDB under different topics. They are provided via MQTT/JSON and processed by Telegraf. Each JSON record results in a tuple of entries in different series that have <em>slightly</em> different timestamps. The ∆ is typically below 1 millisecond whereas the JSON events are several seconds apart, so detecting should be manageable.</p> <p>For further analysis it is necessary to re-group the entries so that the tuples are united again. Simply rounding the timestamp would do in most cases, but of course not generally because a boundary may lie just in between such a tuple.</p> <p>Any ideas? I am accessing data via Python, so either an appropriate Influx query or processing in Python will do. Of course I can scan through the data in a loop and decide how to put them together, but I wonder if there is an elegant solution already at hand, maybe using one of the common Python libraries such as NumPy or Pandas. I assume I am not the only person who is faced with this kind of problem.</p>
<p>Ok, I opted for processing my data in Python. This is what I came up with. It can handle arbitrary granularity intervals. It's fast enough for the data volume I am handling; apart from the sort, it's O(n).</p> <pre><code># input is res: dictionary of {timestamp: (topic, value)} DELTA = timedelta(seconds=0.5) # granularity; adjust to needs t = datetime(dt.MINYEAR, 1, 1, tzinfo=dt.timezone.utc) # init running tstamp var t_group = t # timestamp for sample group outlist = [] # output list group = None # current sample group for key, (topic, val) in sorted(res.items()): if (key - t) &gt; DELTA: # new group t_group = key if group: outlist.append(group) # save previous group to output list group = {&quot;time&quot;: t_group} # init new group with 1st timestamp print(f&quot;{t_group}\t{key}\t{topic} = {val}\t∆={key-t}&quot;) group[topic] = val # add to group t = key print(f&quot;\n{len(outlist)} entries extracted.\n&quot;) </code></pre>
python|pandas|numpy|influxdb|telegraf
1
1,908,720
67,688,178
Updateing multi-plot matplotlib
<p>I have a problem witch updateing matplotlib chart. The problem is that i have many curve's on it, and after update the number of them may change. In example code I have 2 sets of data, 1st with 90 curves, and 2nd with 80, and i wish I could plot 1st set, and then 2nd, in the same matplotlib window.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.transforms import Bbox import numpy as np from numpy.lib.polynomial import RankWarning import pandas as pd import sys fig, ax = plt.subplots() fig.subplots_adjust(right=0.78) _x = [] _y = [] _y1 = [] _x1 = [] for x in range(90): _x.append(np.linspace(0, 10*np.pi, 100)) _y.append(np.sin(_x[x])+x) for x in range(80): _x1.append(np.linspace(0, 10*np.pi, 150)) _y1.append(np.tan(_x1[x]+x)) def narysuj(__x, __y): p = [] # p-pomiar f = [] # f-czestotliwosc for x in range(len(__x)): p.append([]) f.append([]) ax.set_prop_cycle(color=plt.cm.gist_rainbow(np.linspace(0, 1, len(__x)))) for x in range(len(__x)): for line in range(len(__x[x])): #print(len(_y[x]), line) p[x].append(__y[x][line]) f[x].append(__x[x][line]) ax.plot(f[x], p[x], label=f&quot;Label {x}&quot;) plt.show() narysuj(_x, _y) narysuj(_x1, _y1) </code></pre> <p>PS I know the way I'm drawing those charts is highly ineffective.</p>
<p>I found what was the problem. I had to add plt.ion() at the start of program and ax.clear() before drawing.</p>
python|matplotlib
0
1,908,721
30,283,629
Adding items to an existing dictionary using loops in python
<p>I want the output to be in the form:</p> <pre><code>dic = {size1:file/path1, size2:file/path2} </code></pre> <p>But what I am getting in individual dictionaries for each combination, like:</p> <pre><code>{size1:file/path1} {size2:file/path2, size1:file/path1, ...} </code></pre> <p>This is the code I came up with, can anyone correct my code.</p> <pre><code>import os, subprocess, re, sys records = {} out = sys.stdout with open('PythonFilesInMac.txt', 'w') as outfile: sys.stdout = outfile for cdir, dir, files in os.walk(r'/Users'): for file in files: if file.endswith('.py'): filename = os.path.join(cdir, file) size = os.path.getsize(filename) records[size] = filename #records = {size:filename} print records #how do I use dict.update() here? sys.stdout = out </code></pre>
<p>there are two problems in your code. the first is you should put print outside your loop. the second is there may be two files with same size, better to put them in a list.</p> <pre><code>import os, subprocess, re, sys records = {} out = sys.stdout with open('PythonFilesInMac.txt', 'w') as outfile: sys.stdout = outfile for cdir, dir, files in os.walk(r'/Users'): for file in files: if file.endswith('.py'): filename = os.path.join(cdir, file) size = os.path.getsize(filename) records.setdefault(size, []).append(filename) print records sys.stdout = out </code></pre>
python
1
1,908,722
66,937,439
Why is there no Iterable in the bases of the range class but its object is Iterable instance?
<p>If the object is an instance of a class, then the class should be found in the inheritance relationship of the class.</p> <p>I didn't find it.In the following code, you can see clearly that in the tuple of the base class, there are only a object of class'object', and nothing else.</p> <p>Is my understanding wrong?</p> <pre><code>rangeObject = range(3) rangeClass = type(rangeObject) class range(unittest.TestCase): def test_bases_of_range(self): self.assertEqual(rangeClass.__bases__,(object,)) def test_range_instance(self): self.assertIsInstance(rangeObject,collections.Iterable) </code></pre>
<p><code>range</code> is registered as a &quot;virtual subclass&quot; of <code>Sequence</code> (which is a subclass of <code>Iterable</code>) via <a href="https://docs.python.org/3/library/abc.html#abc.ABCMeta.register" rel="nofollow noreferrer"><code>ABC.register</code></a> in order for <code>isinstance</code> or <code>issubclass</code> to work; its not actually a real subclass of Iterable.</p> <p>You can see it in the <a href="https://github.com/python/cpython/blob/35715d1e72b7e15e337087863c75af447199e0fb/Lib/_collections_abc.py#L1030" rel="nofollow noreferrer">Python source code</a>.</p> <p>This also applies for most of the other builtin collections.</p>
python|python-3.x
2
1,908,723
66,898,793
discord,py: AttributeError: 'Context' object has no attribute 'reference'
<p>(Insert greetings)</p> <p>I wanted to make the discord bot reply to a message which was replied to in the command message,below is the code so far:</p> <pre><code>@bot.command(brief=&quot;Iri? Bilang Bos!&quot;, description=&quot;Iri? Bilang Bos!&quot;) async def iri(ctx): ref = ctx.reference x=['https://i.imgur.com/8mfw6Nv.jpg', 'https://tenor.com/view/iri-bilang-bos-spell-power-up-skill-gif-17176211', 'https://i.imgur.com/hOvruLZ.jpg'] await ctx.delete() await ctx.send(random.choice(x), reference=ref) </code></pre> <p>This raises the exception AttributeError: 'Context' object has no attribute 'reference'</p> <p>How do i solve this? Thanks.</p>
<p>You have the right idea but didn't look into documentation enough. Usually if you don't know what attribute you need to use it's helpful to search in the <a href="https://discordpy.readthedocs.io/en/latest/" rel="nofollow noreferrer">documentation</a>.</p> <ol> <li><a href="https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=context#discord.ext.commands.Context" rel="nofollow noreferrer"><code>Context</code></a> doesn't have attribute <code>reference</code>. That is because <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.reference" rel="nofollow noreferrer"><code>reference</code></a> is an attribute of our <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Message" rel="nofollow noreferrer"><code>message</code></a>. Luckily for us context (<code>ctx</code>) has a <code>message</code> attribute: <a href="https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=context#discord.ext.commands.Context.message" rel="nofollow noreferrer"><code>ctx.message</code></a>. We use this to to get the <code>message</code> object which we then use to get the <code>reference</code> attribute: <code>ctx.message.reference</code>.</li> <li>The same goes for the <code>delete</code> method. <code>Context</code> object doesn't have <code>delete</code> method so we first need to get the <code>message</code> object: <code>ctx.message</code> and then use the <a href="https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.delete" rel="nofollow noreferrer"><code>delete</code></a> method of the <code>message</code> object: <code>await ctx.message.delete()</code> (We have to use await because the <code>delete</code> method is asynchronous)</li> </ol> <p><em>Note: It's usually good practise to give your variables meaningful names. It improves the readability of your code. That's why I changed your <code>x</code> variable to <code>choices</code></em></p> <p>So the end result should be something like this:</p> <pre class="lang-py prettyprint-override"><code>@bot.command(brief=&quot;Iri? Bilang Bos!&quot;, description=&quot;Iri? Bilang Bos!&quot;) async def iri(ctx): ref = ctx.message.reference choices = ['https://i.imgur.com/8mfw6Nv.jpg', 'https://tenor.com/view/iri-bilang-bos-spell-power-up-skill-gif-17176211', 'https://i.imgur.com/hOvruLZ.jpg'] await ctx.message.delete() await ctx.send(random.choice(choices), reference = ref) </code></pre> <p>Hopefully this answers your question :)</p>
python|python-3.x|discord.py
0
1,908,724
43,016,102
boxplot error: 1 ndim Categorical are not supported at this time
<p>I have two numpy arrays as follows</p> <pre><code>clf_scores = numpy.array( [[ 0.66333666, 0.65634366, 0.63836164, 0.64435564, 0.658 , 0.641 , 0.67167167, 0.66066066, 0.67167167, 0.65165165], [ 0.6983017 , 0.70629371, 0.70529471, 0.68331668, 0.702 , 0.688 , 0.71371371, 0.69269269, 0.70770771, 0.6996997 ], [ 0.65934066, 0.68531469, 0.65834166, 0.66333666, 0.677 , 0.668 , 0.68568569, 0.68668669, 0.6996997 , 0.68168168], .... .... .... .... .... [ 0.68731269, 0.71928072, 0.7002997 , 0.70929071, 0.723 , 0.697 , 0.68968969, 0.71271271, 0.72672673, 0.6996997 ], [ 0.68731269, 0.72027972, 0.6973027 , 0.70729271, 0.726 , 0.695 , 0.68568569, 0.71271271, 0.72572573, 0.6996997 ], [ 0.69030969, 0.71728272, 0.6983017 , 0.70929071, 0.725 , 0.698 , 0.68668669, 0.71371371, 0.72572573, 0.6996997 ]]) </code></pre> <p>and</p> <pre><code>Trees = numpy.array( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]) </code></pre> <p>These arrays have shapes (100,10) and (100,)</p> <p><strong>How do I Plot these two arrays using seaborn.boxplot ?</strong></p> <p>I tried to boxplot these two numpy arrays as follows</p> <pre><code>sns.boxplot(clf_scores,Trees) </code></pre> <p>however I got following error</p> <pre><code>NotImplementedError: &gt; 1 ndim Categorical are not supported at this time </code></pre> <p>Please tell how do I correct it to get appropriate boxplot ?</p> <p><strong>PS</strong>: data set is obtained by finding <code>cross_val_score</code> of <code>RandomForestClassifier</code> with <code>nTrees = 100</code></p> <p>Correct output is somewhat as follows<a href="https://i.stack.imgur.com/mIozQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mIozQ.png" alt="enter image description here"></a></p>
<p>The easiest to me is to convert your data to a pandas dataframe first and then plot it using seaborn:</p> <pre><code> import numpy as np import pandas as pd import seaborn as sns df = pd.DataFrame(np.transpose(clf_scores)) sns.boxplot(data=df) </code></pre> <p>The dataframe <code>df</code> corresponds to the 'wide-form Dataframe' as described in the <a href="http://seaborn.pydata.org/generated/seaborn.boxplot.html" rel="nofollow noreferrer">boxplot documentation</a>. In your approach, seaborn got the format of the data wrong and assumed it to be a categorical, which is not the case.</p>
pandas|numpy|machine-learning|scikit-learn|seaborn
2
1,908,725
65,722,495
Python code to to extract contents between multiple "start" and "end"
<p>I am an absolute newbie to python. I have multiple news articles within one text file and there are 2000+ text files. Each news article starts with &quot;Dow Jones Newswires DJDN&quot; and ends with &quot;(END) Dow Jones Newswires&quot;.</p> <p>There is a set of code extracting every contents between multiple &quot;start&quot; and &quot;end&quot; like this:</p> <pre><code>with open('./news_txt/A_2013.txt') as infile, open('./news_txt/A_2013_a.txt', 'w') as outfile: copy = False for line in infile: if line.strip() == &quot;Dow Jones Newswires DJDN&quot;: copy = True continue elif line.strip() == &quot;(END) Dow Jones Newswires&quot;: copy = False continue elif copy: outfile.write(line) </code></pre> <p>However, this code only applies to the situation in which 1) there is only one txt file; 2) all the extracted contents are store in a new txt file.</p> <p>But what I want is 1) loop every txt files in a path; 2) each extracted content is being saved in a new txt file.</p> <p>For example, if there are 10 news in a txt, after running the code I should get 10 new txt files storing each news.</p> <p>Cheers!!</p>
<p>Do yourself a favor and use a regular expression instead:</p> <pre><code>^Dow Jones Newswires DJDN.+?^\(END\) Dow Jones Newswires </code></pre> <p>With the modifiers <code>m</code> and <code>s</code>, see <a href="https://regex101.com/r/sWBWGO/1/" rel="nofollow noreferrer"><strong>a demo on regex101.com</strong></a>.</p>
python
0
1,908,726
3,615,630
Why is there so many Pythons installed in /usr/bin for my Snow Leopard? What decides which one is the System Python?
<p>Why is there so many Pythons installed in /usr/bin for my Snow Leopard? What decides which one is the System Python?</p> <p>When I simply type "python" it is 2.6.1 ~ but this doesn't seem to be the "System Python", why not? How does one change system Python and what are the drawbacks?</p>
<p>My snow leopard only has python 2.5 and 2.6 installed, so it's not that many. You may have additional pythons installed (i.e. python3.0), either system wide (in /usr/bin/) or through macports (/opt/local). </p> <p>The default system python is defined through a setting,</p> <pre><code>defaults write com.apple.versioner.python Version 2.5 </code></pre> <p>will change the default to 2.5. You can also use an environment variable, i.e. for bash:</p> <pre><code>export VERSIONER_PYTHON_VERSION=2.5 </code></pre> <p>All of this is documented in the python manpage,</p> <pre><code>man python </code></pre> <p>Overall, it's better not to change the system default. It's what OSX may depend on for certain scripts, and you never know if these scripts work as expected on different versions. Especially Python 3 is different, and may really break your whole system.</p> <p>If you want a different python to be used for your own scripts, either</p> <ol> <li>Use virtualenv (always good) </li> <li>Change your PATH and make sure your preferred python is included before the /usr/sbin one</li> <li>Be explicit, invoke the script using /my/preferred/python</li> </ol>
python|macos|osx-snow-leopard|system
3
1,908,727
3,499,791
How do I prevent fixtures from conflicting with django post_save signal code?
<p>In my application, I want to create entries in certain tables when a new user signs up. For instance, I want to create a userprofile which will then reference their company and some other records for them. I implemented this with a post_save signal:</p> <pre><code>def callback_create_profile(sender, **kwargs): # check if we are creating a new User if kwargs.get('created', True): user = kwargs.get('instance') company = Company.objects.create(name="My Company") employee = Employee.objects.create(company=company, name_first=user.first_name, name_last=user.last_name) profile = UserProfile.objects.create(user=user, employee=employee, partner=partner) # Register the callback post_save.connect(callback_create_profile, sender=User, dispatch_uid="core.models") </code></pre> <p>This works well when run. I can use the admin to create a new user and the other three tables get entries with sensible as well. (Except that is, the employee since the user.first_name and user.last_name aren't filled out in the admin's form when it saves. I still don't understand why it is done like that)</p> <p>The problem came when I ran my test suite. Before this, I had created a bunch of fixtures to create these entries in the tables. Now I get an error that states:</p> <pre><code>IntegrityError: duplicate key value violates unique constraint "core_userprofile_user_id_key" </code></pre> <p>I think this is because I have already created a company,employee and profile records in the fixture with id "1" and now the post_save signal is trying to recreate it.</p> <p>My questios are: can I disable this post_save signal when running fixtures? Can I detect that I am running as part of the test suite and not create these records? Should I delete these records from the fixtures now (although the signal only sets defaults not the values I want to be testing against)? Why doesn't the fixture loading code just overwrite the created records?</p> <p>How do people do this?</p>
<p>I think I figured out a way to do this. There is a 'raw' parameter in the kwargs passed in along with signals so I can replace my test above with this one:</p> <pre><code>if (kwargs.get('created', True) and not kwargs.get('raw', False)): </code></pre> <p>Raw is used when loaddata is running. This seems to do the trick.</p> <p>It is mentioned here: <a href="http://code.djangoproject.com/ticket/13299" rel="noreferrer">http://code.djangoproject.com/ticket/13299</a></p> <p>Would be nice if this was documented: <a href="http://docs.djangoproject.com/en/1.2/ref/signals/#django.db.models.signals.post_save" rel="noreferrer">http://docs.djangoproject.com/en/1.2/ref/signals/#django.db.models.signals.post_save</a></p>
python|django|signals|fixtures|django-signals
80
1,908,728
50,553,698
Pandas plot bar order categories
<p>I have a dataset with a categorical variable that contains three unique values, "low", "medium" and "high":</p> <pre><code>df.CatVar.value_counts() Out[93]: Medium 35832 Low 25311 High 12527 Name: CatVar, dtype: int64 </code></pre> <p>I am trying to plot the number of unique values as a bar-plot. However, the following code gives me the bars in the order ["Medium", "Low", "High"]</p> <pre><code>df.CatVar.value_counts().plot(kind="bar") </code></pre> <p>How do I change the order of the bars in the plot?</p>
<p>There are 2 possible solutions - change order of <code>index</code> before plot - by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="noreferrer"><code>reindex</code></a> or <code>loc</code>:</p> <pre><code>df.CatVar.value_counts().reindex(["Low", "Medium", "High"]).plot(kind="bar") </code></pre> <pre><code>df.CatVar.value_counts().loc[["Low", "Medium", "High"]].plot(kind="bar") </code></pre> <p>Or use <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="noreferrer"><code>ordered categorical</code></a>, so after <code>value_counts</code> get order by <code>categories</code> parameter:</p> <pre><code>df.CatVar = pd.Categorical(df.CatVar, categories=["Low", "Medium", "High"], ordered=True) df.CatVar.value_counts(sort=False).plot(kind="bar") </code></pre> <hr> <p><strong>Sample</strong>:</p> <pre><code>df = pd.DataFrame({'CatVar':['Low','Medium','Low','Low','Medium','High']}) print (df) CatVar 0 Low 1 Medium 2 Low 3 Low 4 Medium 5 High df.CatVar.value_counts().reindex(["Low", "Medium", "High"]).plot(kind="bar") </code></pre> <p><a href="https://i.stack.imgur.com/ouHqm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ouHqm.png" alt="pic"></a></p>
python|pandas|plot|categories
14
1,908,729
50,670,644
Loop for Drawing Lines
<p>I appreciate anyone's help on this as I am new to Python. The script below will draw a triangle with 3 mouse clicks. I want to alter this script with a loop to allow unlimited mouse clicks. Can someone help me on the next steps? A picture of what I want it to do is provided below the script.</p> <pre><code>import graphics as g def main(): win=g.GraphWin("Draw a Triangle") win.setCoords(0.0,0.0,100.0,100.0) message=g.Text(g.Point(50,50),"Click on three points") message.draw(win) p1=win.getMouse() p1.draw(win) p2=win.getMouse() p2.draw(win) p3=win.getMouse() p3.draw(win) triangle=g.Polygon(p1,p2,p3) triangle.setFill("Red") triangle.setOutline("cyan") triangle.draw(win) message.setText("click anywhere to quit.") win.getMouse() main() print(main) </code></pre> <p>Below is what I would like it to do. On my 2nd mouse click it will automatically draw the point and a line between the first and second point. Then the same for point 3, point 4, etc.with the option for unlimited points.</p> <p><a href="https://i.stack.imgur.com/PpmC5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PpmC5.png" alt="Polygon Example"></a></p>
<p>The main idea is to keep track of the points the user has clicked, and to clear the canvas when re-drawing the objects.</p> <p>The <code>graphics.py</code> file you are using seems to be from <a href="http://mcsp.wartburg.edu/zelle/python/graphics.py" rel="nofollow noreferrer">here</a>. The code in turn is just a wrapper around <a href="https://wiki.python.org/moin/TkInter" rel="nofollow noreferrer">TkInter</a>. </p> <p>Therefore, just familiarise yourself with how TkInter handles mouse and keypresses and you should be able to do what you want. For e.g., rather than use <code>win.getMouse()</code>, the preferred way to use a GUI framework is to bind functions (event handlers) to specific events as I demonstrate below.</p> <pre><code>import graphics as g def main(): win = g.GraphWin("Draw a polygon") win.setCoords(0.0, 0.0, 100.0, 100.0) message = g.Text(g.Point(50, 50), "Click to add point to polygon") message.draw(win) # Set of points clicked so far points = [] def onClick(pt): x, y = win.toWorld(pt.x, pt.y) points.append(g.Point(x, y)) poly = g.Polygon(*points) # Clear all objects on canvas. # You can choose to delete only current polygon by associating a label with it. # See Tkinter's documentation for details win.delete("all") poly.setFill("Red") poly.setOutline("Cyan") poly.draw(win) win.setMouseHandler(onClick) # This is not idea as we are wasting cycles doing polling # I believe Tkinter should have a better approach to avoid this. while not win.checkKey() == 'q': pass if __name__ == "__main__": main() </code></pre>
python|python-3.x
0
1,908,730
50,310,148
ElementNotVisibleException: Python + Selenium, login credentials on web
<p>I'm close to losing my mind if someone can help keep my sanity. I cannot get past this "ElementNotVisibleException:" error. I've tried multiple techniques I've read through the web and nothing works. This one seems pretty straightforward with a <code>.send_keys</code> used with a <code>WebDriverWait</code> until the presence of ID is located. What am I missing?</p> <p>When I step through it line by line it works.</p> <pre><code>import os from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By chromedriver = "/Users/username/.conda/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("url") delay = 3 username = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'login_username'))).send_keys("username") password = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'login_password'))).send_keys("password") </code></pre>
<p>Use the <code>visibility_of_element_located</code>expected condition for your case.</p> <p>Hope it helps you!</p>
python|html|selenium|selenium-webdriver|sendkeys
1
1,908,731
50,497,642
python: split and create json data from csv
<p>How do I create a nested field from csv to json? I looked at the other stackoverflow, but they are not quite what I am trying to format. I have a data set with 1 column that I have to convert into a nested field. </p> <p>Data:</p> <pre><code>ID, NAME 1, "Smith, Mr. Adams" 2, "McAdams, Mrs. Audrey" 3, "McAdams, Doctor John" 4, "Missing Value" </code></pre> <p>CODE: </p> <pre><code>with open('test.csv', 'r') as file: headers = next(file) #skip the headers fieldnames = headers.rstrip().split(",") csv_reader = csv.DictReader(file, fieldnames) #creating a dictionary import datetime for row_dict in csv_reader: row_dict['name'] = row_dict['name'].split(",") json_data = json.dumps(row_dict) print(json_data) </code></pre> <p>I am getting output in a list but it is not nested.</p> <pre><code>{"id": "1", "name": ["Smith", " Mr. Adams"]} {"id": "2", "name": ["McAdams", " Mrs. Audrey"]} {"id": "3", "name": ["McAdams", " Doctor John"]} {"id": "4", "name": ["Missing Value"]} </code></pre> <p>Final output: Is there any way to do this?</p> <pre><code>{"id": "1", "name": [{"last_name": "Smith", "prefix": "Mr.", "first_name": "Adams"}]} {"id": "1", "name": [{"last_name": "McAdams", "prefix": "Mrs.", "first_name": "Audrey"}]} {"id": "1", "name": [{"last_name": "McAdams", "prefix": "Dr.", "first_name": "John"}]} {"id": "1", "name": [{"last_name": "Missing Value", "prefix": "Missing Value", "first_name": "Missing Value"}]} </code></pre>
<p>Just use <code>.split()</code> some times and create a new dict.</p> <pre><code>import json csv = '''1, "Smith, Mr. Adams" 2, "McAdams, Mrs. Audrey" 3, "McAdams, Doctor John" 4, "Missing Value"''' csv_lines = csv.split('\n') for line in csv_lines: id = line.split(',')[0] name = line[len(id)+3:-1] split = name.split(', ') last_name = split[0] if len(split) &lt; 2: first_name = last_name prefix = last_name else: prefix = split[1].split(' ')[0] first_name = split[1][len(prefix)+1:] row_dict = {'id': id, 'name': {'last_name': last_name, 'prefix': prefix, 'first_name': first_name}} json_data = json.dumps(row_dict) print(json_data) </code></pre> <p>Output:</p> <pre><code>{"id": "1", "name": {"last_name": "Smith", "prefix": "Mr.", "first_name": "Adams"}} {"id": "2", "name": {"last_name": "McAdams", "prefix": "Mrs.", "first_name": "Audrey"}} {"id": "3", "name": {"last_name": "McAdams", "prefix": "Doctor", "first_name": "John"}} {"id": "4", "name": {"last_name": "Missing Value", "prefix": "Missing Value", "first_name": "Missing Value"}} </code></pre>
python|json
1
1,908,732
26,858,358
A recursive function to sort a list of ints
<p>I want to define a recursive function can sort any list of ints:</p> <pre><code>def sort_l(l): if l==[]: return [] else: if len(l)==1: return [l[-1]] elif l[0]&lt;l[1]: return [l[0]]+sort_l(l[1:]) else: return sort_l(l[1:])+[l[0]] </code></pre> <p>Calling this function on a list [3, 1, 2,4,7,5,6,9,8] should give me:</p> <pre><code>[1,2,3,4,5,6,7,8,9] </code></pre> <p>But I get:</p> <pre><code>print(sort_l([3, 1, 2,4,7,5,6,9,8]))--&gt; [1, 2, 4, 5, 6, 8, 9, 7, 3] </code></pre> <p>Please help me to fix the problem, actual code would be appreciated. Thanks!</p>
<p>The <a href="http://en.wikipedia.org/wiki/Quicksort" rel="noreferrer">quick sort</a> is recursive and easy to implement in Python:</p> <pre><code>def quick_sort(l): if len(l) &lt;= 1: return l else: return quick_sort([e for e in l[1:] if e &lt;= l[0]]) + [l[0]] +\ quick_sort([e for e in l[1:] if e &gt; l[0]]) </code></pre> <p>will give:</p> <pre><code>&gt;&gt;&gt; quick_sort([3, 1, 2, 4, 7, 5, 6, 9, 8]) [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre>
python|recursion
7
1,908,733
61,351,828
How do i resolve this ildoonet / tf-pose-estimation installing issue for windows 10
<p><a href="https://i.stack.imgur.com/Lzz7y.png" rel="nofollow noreferrer">enter image description here</a>I was installing the packages on my conda environment in order to run the pose estimation according to the tutorial from <a href="https://www.youtube.com/watch?v=nUjGLjOmF7o&amp;list=PLX-LrBk6h3wQ17z1axCOAS1QVS1dvTEvR" rel="nofollow noreferrer">https://www.youtube.com/watch?v=nUjGLjOmF7o&amp;list=PLX-LrBk6h3wQ17z1axCOAS1QVS1dvTEvR</a> and the github page <a href="https://github.com/ildoonet/tf-pose-estimation" rel="nofollow noreferrer">https://github.com/ildoonet/tf-pose-estimation</a> where u have to run the requirement.txt file to install the 3rd party packages for it to run in the end <code>$ pip3 install -r requirements.txt</code>.</p> <p>I had 3 errors. the first was missing Cython package that I already found and installed. The 2nd was an error: <code>Error Microsoft Visual C++ 14.0 is required</code> that i resolved going here <a href="https://medium.com/@jacky_ttt/day060-fix-error-microsoft-visual-c-14-0-is-required-629413e798cd" rel="nofollow noreferrer">https://medium.com/@jacky_ttt/day060-fix-error-microsoft-visual-c-14-0-is-required-629413e798cd</a> and installing the necessary packages in the visual studio c++ build tools. But i came across a new error that even i can solve. I would appreciate any help. The error came on my anaconda prompt: </p> <pre><code>Building wheels for collected packages: pycocotools, tensorpack Building wheel for pycocotools (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\M S Tiwana\.conda\envs\tfposee\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\MSTIWA~1\\AppData\\Local\\Temp\\pip-install-vjk9vvy3\\pycocotools\\setup.py'"'"'; __file__='"'"'C:\\Users\\MSTIWA~1\\AppData\\Local\\Temp\\pip-install-vjk9vvy3\\pycocotools\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\MSTIWA~1\AppData\Local\Temp\pip-wheel-fdystmqn' cwd: C:\Users\MSTIWA~1\AppData\Local\Temp\pip-install-vjk9vvy3\pycocotools\ Complete output (19 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\pycocotools copying pycocotools\coco.py -&gt; build\lib.win-amd64-3.7\pycocotools copying pycocotools\cocoeval.py -&gt; build\lib.win-amd64-3.7\pycocotools copying pycocotools\mask.py -&gt; build\lib.win-amd64-3.7\pycocotools copying pycocotools\__init__.py -&gt; build\lib.win-amd64-3.7\pycocotools running build_ext building 'pycocotools._mask' extension creating build\temp.win-amd64-3.7 creating build\temp.win-amd64-3.7\Release creating build\temp.win-amd64-3.7\Release\pycocotools creating build\temp.win-amd64-3.7\Release\common C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD "-IC:\Users\M S Tiwana\.conda\envs\tfposee\lib\site-packages\numpy\core\include" -Icommon "-IC:\Users\M S Tiwana\.conda\envs\tfposee\include" "-IC:\Users\M S Tiwana\.conda\envs\tfposee\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.25.28610\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcpycocotools/_mask.c /Fobuild\temp.win-amd64-3.7\Release\pycocotools/_mask.obj -Wno-cpp -Wno-unused-function -std=c99 cl : Command line error D8021 : invalid numeric argument '/Wno-cpp' error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.25.28610\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2 ---------------------------------------- ERROR: Failed building wheel for pycocotools Running setup.py clean for pycocotools Building wheel for tensorpack (setup.py) ... done Created wheel for tensorpack: filename=tensorpack-0.10-py2.py3-none-any.whl size=291265 sha256=85cc191f624cecba1af9d7bfeff01bd6fd592c8763010a1468abc0c6ccedfeac Stored in directory: C:\Users\MSTIWA~1\AppData\Local\Temp\pip-ephem-wheel-cache-cjd1_8p6\wheels\8f\c4\7d\b7ca213c76a0b78c772c6d3173364b8102d262acda1ec45207 Successfully built tensorpack Failed to build pycocotools Installing collected packages: pycocotools, slidingwindow, tabulate, msgpack, msgpack-numpy, tensorpack Running setup.py install for pycocotools ... error </code></pre> <p>Is there a visual studio c++ build tool install error ?</p>
<p>pycocotools is for linux, since you're using windows 10</p> <p>instead of using: <code>pip install pycocotools</code></p> <p>use this: <code>pip install pycocotools-windows</code></p> <p><a href="https://pypi.org/project/pycocotools-windows/" rel="nofollow noreferrer">https://pypi.org/project/pycocotools-windows/</a></p>
python|tensorflow|cmd|computer-vision|anaconda
2
1,908,734
60,619,695
Depending on field value change nested serializer
<p>I am currently trying to implement the following serializer to the Profile serializer. But I would like to add a condition to it. Profile serializer</p> <pre><code>class UserProfileSerializer(serializers.ModelSerializer): role = serializers.ChoiceField(choices=(('Reader', u'Reader'), ('Author', u'Author'), ('Admin', u'Admin'))) role_display = serializers.SerializerMethodField() class Meta: model = Profile fields = ('gender', 'birthday', 'icon', 'role', 'role_display') depth = 1 </code></pre> <p>Author serializer</p> <pre><code>class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' </code></pre> <p>Reader serializer</p> <pre><code>class ReaderSerializer(serializers.ModelSerializer): class Meta: model = Reader fields = '__all__' </code></pre> <p>Both author and reader table has a one-to-one relationship towards profile table. Depending on the role option I would like to show a specific nested serializer. </p> <p>Example:</p> <pre><code>{ "id": 19, "username": "maoji1", "password": "pbkdf2_sha256$180000$YhzDiqzJ4OyC$syzkwR5X3/H2p5NTB0JEK2zS5nvYu5ddHrTgy3cYU/E=", "email": "pbkdf2_sha256$180000$YhzDiqzJ4OyC$syzkwR5X3/H2p5NTB0JEK2zS5nvYu5ddHrTgy3cYU/E=", "profile": { "gender": "male", "birthday": "2020-03-10", "icon": null, "role": { is_vip:True, validate_date:... } } } </code></pre> <p>Reader model</p> <pre><code>class Reader(models.Model): user = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='reader', verbose_name='user') is_user_vip = models.CharField(choices=(('normal', u'Normal'), ('vip', u'VIP')), default='normal', max_length=10, verbose_name=u'Vip status') vip_validate = models.DateField(verbose_name=u"Validate Until", auto_now_add=True, null=True, editable=False) </code></pre> <p>Author model</p> <pre><code>class Author(models.Model): user = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='author') book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='Book', null=True) contract_number = models.IntegerField(verbose_name='Contact number', null=True, blank=True) </code></pre> <p>Profile model</p> <pre><code>class Profile(models.Model): role_choice = ( ('Reader', u'Reader'), ('Author', u'Author'), ('Editor', u'Editor'), ('Admin', u'Admin') ) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', verbose_name='user') gender = models.CharField(choices=(("male", u"Male"), ("female", u"Female")), default="Female", max_length=150, verbose_name='Gender') birthday = models.DateField(null=True, blank=True, verbose_name="Birthday") icon = models.ImageField(upload_to="media/image/%Y/%m", default=u"media/image/default.png", max_length=1000, verbose_name=u"User icon", null=True) role = models.CharField(choices=role_choice, max_length=150, default='Admin', verbose_name='Role') </code></pre>
<p>You can use SerializerMethodField and decide which serializer you must use inside it's method:</p> <pre><code>class UserSerializer(serializers.ModelSerializer): profile = serializers.MethodField() class Meta: model = Profile fields = ('id', 'username', 'password', 'email','profile') def get_profile(self,obj): return ProfileSerializer(obj.profile).data class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields ='__all__' class ReaderSerializer(serializers.ModelSerializer): class Meta: model = Reader fields ='__all__' class ProfileSerializer(serializers.ModelSerializer): role = serializers.MethodField() class Meta: model = Profile fields = ('gender', 'birthday', 'icon', 'role') def get_role(self,obj): if hasattr(obj, 'author') serializer = AuthorSerializer(obj.author) return serializer.data elif hasattr(self,'reader'): serializer = ReaderSerializer(obj.reader) return serializer.data return {} # if your profile doesn't have any relation with author or reader class UserSerializer(serializers.ModelSerializer): profile = serializers.MethodField() class Meta: model = User fields = ('id', 'username', 'password', 'email','profile') def get_profile(self,obj): return ProfileSerializer(obj.profile).data </code></pre>
python|django|django-rest-framework
0
1,908,735
57,903,954
How to create a stacked bar chart out of two lists: considering one is as cluster, and other one is flag
<p>Let's say I have following code piece:</p> <pre><code>x = [1,1,1,1,2,3,3,3] y = [1,1,0,0,1,1,1,0] import matplotlib.pyplot as plt from collections import Counter freqs = Counter(x) plt.bar(freqs.keys(), freqs.values(), width=0.5) plt.xticks(list(freqs.keys())) </code></pre> <p>I want to come with a stacked bar chart by coloring above bar chart by <code>y</code> values as below:</p> <p><a href="https://i.stack.imgur.com/V0VqH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V0VqH.png" alt="desired stacked bar chart image"></a></p> <p>How can I integrate <code>y</code> values into this bar chart?</p>
<p>The most straightforward stacked bar chart can be achieved using Matplotlib.</p> <pre><code>import matplotlib.pyplot as plt dataset= [(1, 1), (1, 1), (1, 0), (1, 0), (2, 1), (3, 1), (3, 1), (3, 0)] y_1 = [len([1 for data in dataset if (data[0] == cat) and (data[1] == 1)])for cat in [1,2,3]] y_0 = [len([1 for data in dataset if (data[0] == cat) and (data[1] == 0)])for cat in [1,2,3]] plt.bar(x=['1','2','3'], height=y_1, label='1', bottom=y_0) plt.bar(x=['1','2','3'], height=y_0, label='0') plt.legend() plt.xlabel('Category') plt.ylabel('Frequency') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/uH8aN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uH8aN.png" alt="enter image description here"></a></p> <p>Or if you are familiar with Pandas, you can use the built-in plotting function as well, which gives a similar plot:</p> <pre><code>import pandas as pd dataset= [(1, 1), (1, 1), (1, 0), (1, 0), (2, 1), (3, 1), (3, 1), (3, 0)] x = [tup[0] for tup in dataset] y = [tup[1] for tup in dataset] df = pd.DataFrame({'x':x, 'y':y, 'freq_y':0}) ax = df.groupby(['x','y']).count().unstack(1).plot(y='freq_y',kind='bar', stacked=True) ax.set_ylabel('Frequency') ax.set_xlabel('Category') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/mtJCk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mtJCk.png" alt="enter image description here"></a></p>
python|tuples|stacked-chart
1
1,908,736
58,153,717
Segment text from bad lightining images using python
<p>I have three types of images and want to segment text from them. So I get a clean binarized img like the first image below. The three types of images are below </p> <p>I've tried various techniques but it always have some cases to fail. I tried first to threshold the img using <code>otsu</code> algorithm but it gave bad results in images below</p> <p>I tried <code>Guassian</code>, <code>bilateral</code> and normal blur kernel but didn't enhance the results too much </p> <p>Any one can provide help!</p> <p>Code as the best I got results from </p> <pre><code>import cv2 gray = cv2.imread("/home/shrouk/Pictures/f2.png", 0) thresholded = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] cv2.imshow("img", thresholded) </code></pre> <p>This is the final result I need <a href="https://i.stack.imgur.com/POYfp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/POYfp.png" alt="enter image description here"></a></p> <p>This the first type of images that fail. It fails because the text grey level it lighter in the right of the image </p> <p><a href="https://i.stack.imgur.com/aagkX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aagkX.png" alt="enter image description here"></a></p> <p>The result of otsu on it is here, I just need a way to enhance the words in the third line from right: </p> <p><a href="https://i.stack.imgur.com/SNofu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SNofu.png" alt="enter image description here"></a></p> <p>Second type that fails because the darker background</p> <p><a href="https://i.stack.imgur.com/MjfmM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MjfmM.png" alt="enter image description here"></a></p> <p>otsu result is not very good as the words to the left look like dilated words</p> <p><a href="https://i.stack.imgur.com/5SsAl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5SsAl.png" alt="enter image description here"></a></p> <p>This is the type that correctly thresholded by otsu as there is no noise </p> <p><a href="https://i.stack.imgur.com/Lv2f2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lv2f2.png" alt="enter image description here"></a></p>
<p>Try using <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html#adaptive-thresholding" rel="nofollow noreferrer"><code>cv2.adaptiveThreshold()</code></a></p> <p><a href="https://i.stack.imgur.com/da4Ij.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/da4Ij.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/hdcNb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hdcNb.png" alt="enter image description here"></a></p> <pre><code>import cv2 image = cv2.imread("2.png", 0) adaptive = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,5) cv2.imshow("adaptive", adaptive) cv2.waitKey() </code></pre>
python|opencv|image-processing|image-segmentation|text-segmentation
2
1,908,737
58,154,156
how to ingest non-one-minute data in zipline
<p>when I try to ingest data into zipline bundles, since I could not get one-minute data, and only have 5-minutes klines data. Looks like standard zipline does not support it? cited from <a href="http://www.zipline.io/bundles.html" rel="nofollow noreferrer">http://www.zipline.io/bundles.html</a></p> <p>ingest(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress, output_dir)</p> <p>minute_bar_writer minute_bar_writer is an instance of BcolzMinuteBarWriter. This writer is used to convert data to zipline’s internal bcolz format to later be read by a BcolzMinuteBarReader. If minute data is provided, users should call write() with an iterable of (sid, dataframe) tuples. The show_progress argument should also be forwarded to this method. If the data source does not provide minute level data, then there is no need to call the write method. It is also acceptable to pass an empty iterator to write() to signal that there is no minutely data.</p> <p>Anyway, I use this interface to ingest the 5 minutes klines into zipline. but when I call run_algorithm, whatever the data_frequency I input, it prompt errors.</p> <pre><code>data = run_algorithm(start=start, end=end, initialize=initialize, capital_base=100000, handle_data=handle_data, bundle="poloniex_csv", data_frequency='60min', trading_calendar=PoloniexExchangeCalendar()) </code></pre> <p>AssertionError: All readers must share target trading_calendar. Reader= for type= uses calendar= which does not match the desired shared calendar= </p> <p>How to fix this issue? for instance let BcolzMinuteBarReader support 5minutes data. I am ok with deal the 5 minutes data in zipline handle_data functions. Thank you!</p>
<p>The answer to this is that one shouldn't use the calendar class directly, <code>PoloniexExchangeCalendar()</code> here, but they should invoke <code>get_calendar(calendar_name)</code> to get an instance of the calendar from the calendar factory instead. In theory, this would guarantee that there is only one instance of the calendar used by the framework and therefore the line</p> <pre><code>assert trading_calendar == r.trading_calendar </code></pre> <p>in the dispatch_bar_reader.py would always resolve to true. In my case and for some reason, even when using <code>get_calendar(calendar_name)</code> wasn't exactly sufficient and I was getting a comparison of two different instances of the same calendar class which inevitably resolved to <code>False</code>. Hence I was getting the same error. I went around the issue by having my calendar class implementing its own equality comparison by adding the following lines inside the custom calendar class</p> <pre><code>__hash__ = ExchangeCalendar.__hash__ def __eq__(self, other): return all(self.all_sessions == other.all_sessions) if isinstance(other, CoinbaseExchangeCalendar) else False </code></pre> <p>This did the trick for me by bypassing the technicalities of comparing the two instances but admittedly without actually ever figuring out why <code>get_calendar(cal_name)</code> didn't return the singleton instance of the custom calendar class.</p>
python|zipline
0
1,908,738
56,086,303
Python function keeps returning nan?
<p>I am currently learning python by rewriting some of the old programs I wrote using other languages. But for some reason, I keep running into an issue where a function call keeps returning a nan. Below is a code snippet. </p> <p>The function theta0PartialDerivative returns a number if I call it outside the gradient descent function, but returns a nan otherwise. I am unsure what the issue is?</p> <pre><code>def theta0PartialDerivative(): multBy=40.0 total=temp=0 for i in range(40): temp+=theta0 temp+=theta1*sepalWidth[i] temp+=theta2*petalLength[i] temp+=theta3*petalWidth[i] temp-=sepalLength[i] total=total+temp temp=0 return (multBy*total) def gradientDescent(): alpha=0.5 global theta0,theta1,theta2,theta3 theta0After=theta1After=theta2After=theta3After=1 while(theta0After!=theta0 and theta1After!=theta1 and theta2After!=theta2 and theta3After!=theta3): theta0=theta0After theta1=theta1After theta2=theta2After theta3=theta3After theta0After=theta0 - (alpha * theta0PartialDerivative()) theta1After=theta1 - (alpha * theta1PartialDerivative()) theta2After=theta2 - (alpha * theta2PartialDerivative()) theta3After=theta3 - (alpha * theta3PartialDerivative()) theta0=theta1=theta2=theta3=accuracy=0 gradientDescent() </code></pre> <p>Full file here: <a href="https://github.com/MohamedMoustafaNUIG/Linear-Regression-Gradient-Descent-First-Project/blob/master/Linear-Regression-I.py" rel="nofollow noreferrer">https://github.com/MohamedMoustafaNUIG/Linear-Regression-Gradient-Descent-First-Project/blob/master/Linear-Regression-I.py</a></p> <p>EDIT: Really? No one knows what the issue is?</p>
<p>Found the problem. Alpha, the step variable, was too large (for the dataset I was dealing with) and caused the partial derivatives to diverge instead of converge. I changed alpha from 0.5 to 0.13 and it works</p>
python|nan
0
1,908,739
18,427,782
seven segment display with width
<p>I'm in the process of making a seven segment display emulator in python and have run into a small problem. What I have done is make a list for each number that has a series of numbers representing a character, like so <code>["000", "001", "000", "001", "000"]</code> This represents the number 1, with 0 been a space, 1 been a pipe character (|) and 2 been a dash.</p> <p>This works fine for a width of 1 but I want it to be able to go to any width. I've tried doing this by multiplying the character count by the width e.g the number one with a width of two would look like <code>["000000", "000011", "000000", "000011", "000000"]</code> </p> <p>The problem I am having is when it encounters a pipe character it will print it on the same line rather than underneath it. Like so '| |' when it should be like </p> <p>|<br> |</p> <p>I've tried using <code>\n</code> to print it on a new line but this messes everything else up.</p> <p>Any suggestions on how do this in a better way or how to fix my problem would be appreciated. </p> <p>Here is my code.</p> <pre><code> uno = ["000", "001", "000", "001", "000"] temp = "" width = 2 for line in uno: temp = "" for char in line: temp += char * width temp = temp.replace('0', ' ').replace("1", "|").replace('2', '-') print(temp) </code></pre> <p>Example Output</p> <pre><code>|| || </code></pre> <p>Wanted Output</p> <pre><code>| | | | </code></pre> <p>Thanks</p>
<p>It took me a bit to grasp your input format. It's a bit silly to use 15 characters than can take any of three values to represent what is, almost by definition a seven bit output. It does make rendering easy, I guess.</p> <p>If I understand your question correctly, you want to be able to turn your current <code>width=1</code> output, where an <code>8</code> looks like this:</p> <pre><code> - | | - | | - </code></pre> <p>To a scaled up version, where for <code>width=2</code> an <code>8</code> would look like:</p> <pre><code> -- | | | | -- | | | | -- </code></pre> <p>Currently, a single-width <code>8</code> requires the input <code>['020', '101', '020', '101', '020']</code>. If you want to use the same rendering method (where you simply replace the numbers with characters), you need to translate this to: <code>['0220', '1001', '1001', '0220', '1001', '1001', '0220']</code> to increase the size.</p> <p>Notice that the lines with the <code>1</code>s get repeated as a whole and the middle character is repeated on every line.</p> <p>Here's a function that translates from width 1 to any other width:</p> <pre><code>def scale(code, factor): if factor == 1: return code result = ["{}{}{}".format(line[0], line[1:-1]*factor, line[-1]) # widen for line in code] for i in range(len(result)-2, 0, -2): result[i:i+1] = result[i:i+1]*factor # stretch vertically return result def render(code): for line in code: print(line.replace('0', ' ').replace('1', '|').replace('2', '-')) </code></pre> <p>Example output:</p> <pre><code>&gt;&gt;&gt; render(['020', '101', '020', '101', '020']) - | | - | | - &gt;&gt;&gt; render(scale(['020', '101', '020', '101', '020'], 2)) -- | | | | -- | | | | -- &gt;&gt;&gt; render(scale(['020', '101', '020', '101', '020'], 3)) --- | | | | | | --- | | | | | | --- </code></pre>
python|python-2.7|python-3.x
1
1,908,740
57,315,783
feeding annotations as ground truth along with the images to the model
<p>I am working on an object detection model. I have annotated images whose values are stored in a data frame with columns (filename,x,y,w,h, class). I have my images inside /drive/mydrive/images/ directory. I have saved the data frame into a CSV file in the same directory. So, now I have annotations in a CSV file and images in the images/ directory. </p> <p>I want to feed this CSV file as the ground truth along with the image so that when the bounding boxes are recognized by the model and it learns contents of the bounding box.</p> <p>How do I feed this CSV file with the images to the model so that I can train my model to detect and later on use the same to predict bounding boxes of similar images?</p> <p>I have no idea how to proceed.</p> <p>I do not get an error. I just want to know how to feed the images with bounding boxes so that the network can learn those bounding boxes.</p>
<p>We need to feed the bounding boxes to the loss function. We need to design a custom loss function, preprocess the bounding boxes and feed it back during back propagation.</p>
python|tensorflow|keras|computer-vision|object-detection
0
1,908,741
57,537,863
To ignore pylint(import-error) sometimes is the best solution?
<p>I have switched from PyCharm to VSCode for Django development. I cannot get rid of the pylint "Unable to import XXXXX pylint(import-error)" errors for my development modules that are not packaged into my venv.</p> <p>I have gone through about 20+ discussions from google, most of which are stackoverflow. I have tried all the suggestions and think I now know what the problem is - or at least what the workable solution is.</p> <p>My setup is as follows. I have a venv where I have pip installed various packages. This is what I use for development work with 2 projects. This works fine and VSCode can see it and use it.</p> <p>My library code sits in a VSCode project and this can be seen and used from my web project because of:</p> <pre><code>{ "python.pythonPath": "/home/XXXXX/.virtualenvs/YYYYY/bin/python", "python.autoComplete.extraPaths": [ "/home/XXXXX/dev/VisualStudioCode/repositories/my-library" ] </code></pre> <p>}</p> <p>So far so good. But after trying all the suggestions for pylint to find this code, I have come to the conclusion that pylint requires my library to be installed in the venv and I don't want to do that while I am still developing. So basically, all my code works fine and pylint works fine for intellisense and debugging. BUT I have to put up with these pylint errors when I have particular files open. Luckily, when I close the relevant file, the pylint error disappears from the problems list in the VSCode terminal.</p> <p>Has anybody else reached the same working conclusion?</p>
<p>I found the answer after more google trawling. It's actually in this [<a href="https://stackoverflow.com/questions/1899436/pylint-unable-to-import-error-how-to-set-pythonpath]">PyLint &quot;Unable to import&quot; error - how to set PYTHONPATH?</a> stackoverflow post.</p> <p>I created the file .pylintrc in my home user folder, and added the lines :</p> <pre><code>[MASTER] init-hook='import sys; sys.path.append("/home/XXXXX/dev/VisualStudioCode/repositories/my-library") </code></pre> <p>to this file. PyLint now finds my library code from my website project.</p> <p>Thanks to Brian M. Hunt, June 2017.</p>
python|visual-studio-code|pylint
1
1,908,742
42,143,096
Alternative to catching and rethrowing exception
<p>I came across the need to do this:</p> <pre><code>try: prop_file = next(file for file in os.listdir(data_folder) if 'property' in file) except StopIteration: raise StopIteration('The property file could not be found in the specified folder ({})!'.format(data_folder)) </code></pre> <p>which seems kinda silly because I am catching an exception only to re-throw it but this time with a more <em>information-rich</em> feedback.</p> <p>Are there alternatives to this, or is this considered a standard practice?</p>
<p><code>StopIteration</code> doesn't look like the right thing to throw.</p> <p>In this case you can make <code>next</code> return <code>None</code>.</p> <pre><code>prop_file = next((file for file in os.listdir(data_folder) if 'property' in file), None) if not prop_file: message = 'The property file could not be found in the specified folder ({})!' raise AppropriateException(message.format(data_folder)) </code></pre>
python|python-3.x|exception-handling
3
1,908,743
42,489,081
Python - 'if not'
<p>The following codes</p> <pre><code>multiples = [] for i in range(1,1000): if i % 3 == 0 or i % 5 == 0: multiples.append(i) addition = sum(multiples) print addition </code></pre> <p>and</p> <pre><code>print(sum([i for i in range(1, 1000) if not (i%3 and i%5)])) </code></pre> <p>do the same thing.</p> <p>Now how does the <code>if not</code> part compute in the second code?</p> <p>What I'm saying is, in the first code the <code>i % 3 == 0 or i % 5 == 0</code> had to be exclusively stated whereas the same thing is achieved on the second code without the <code>== 0</code>.</p>
<p>Using <a href="https://en.wikipedia.org/wiki/De_Morgan%27s_laws" rel="nofollow noreferrer">De Morgan's laws</a>:</p> <pre><code>i % 3 == 0 or i % 5 == 0 </code></pre> <p>is the same as:</p> <pre><code>not (i % 3 != 0 and i % 5 != 0) </code></pre> <p>And in python, when converting a number to a boolean, any non-zero value becomes <code>True</code>.</p> <p>So instead of doing <code>i % 3 != 0</code> in the <code>if</code>, you can just use <code>i % 3</code>, because if it's <code>0</code> it'll be <code>False</code> and if it's non-zero it'll be <code>True</code>.</p> <p>Here's python's truth table: <a href="https://docs.python.org/3.6/library/stdtypes.html#truth" rel="nofollow noreferrer">https://docs.python.org/3.6/library/stdtypes.html#truth</a></p> <p>P.S. <code>sum()</code> can take a generator as an argument, so you can actually just do:</p> <pre><code>sum(i for i in range(1, 1000) if not (i%3 and i%5)) </code></pre>
python
12
1,908,744
42,287,354
OpenCV - How to mask match picture in Python?
<p>I want to match pictures from my a.jpg and b.jpg.</p> <p>But there is some of that area I don't want to match.</p> <p>How should I mask it?</p> <p>(PS: If transfer these area to black, it will effect <code>cv2.matchTemplate</code>)</p> <pre><code>import cv2 import numpy as np img1 = cv2.imread("a.jpg") img2 = cv2.imread("b.jpg") myROI = img2[183:374,293:408] # here I want to mask a part of myROI .. # It means that I don't want to match something in my picture... # How should I do ? res = cv2.matchTemplate(img1,myROI,method= eval('cv2.TM_CCOEFF_NORMED')) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) print max_val*100 # score </code></pre> <p>a.jpg <a href="https://i.stack.imgur.com/ki36n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ki36n.png" alt="enter image description here"></a></p> <p>b.jpg</p> <p><a href="https://i.stack.imgur.com/G29J7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G29J7.jpg" alt="enter image description here"></a></p>
<pre><code># -*- coding: utf-8 -*- import cv2 import numpy as np img1 = cv2.imread("a.jpg") img2 = cv2.imread("b.jpg") mymask = cv2.imread("mask.jpg") # mask shape must = template # mask only run in method = CV_TM_SQDIFF and CV_TM_CCORR_NORMED. me= eval('cv2.TM_CCORR_NORMED') res1 = cv2.matchTemplate(img1,img2,method= me, mask = mymask) res2 = cv2.matchTemplate(img1,img2,method= eval('cv2.TM_CCORR_NORMED')) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res1) print max_val*100 # score 1 -&gt; 62 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res2) print max_val*100 # score 2 -&gt; 99 </code></pre> <hr> <p>a <a href="https://i.stack.imgur.com/TsqA9.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/TsqA9.jpg</a></p> <p>b <a href="https://i.stack.imgur.com/6BemF.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/6BemF.jpg</a></p> <p>mask <a href="https://i.stack.imgur.com/T2DZI.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/T2DZI.jpg</a></p>
python|opencv|image-processing
0
1,908,745
54,121,864
Psycopg2 is not only accepts None (Nonetype) as a cell entry that can be Null when using %s but not with f-strings
<p>I am inserting data into a Postgres DB using Psycopg2 using:</p> <pre><code>params = "ts, price, volume" entry = (1234567, None, 3) cur.execute(f"INSERT INTO stock_data ({params}) VALUES {entry};") </code></pre> <p>I have used this pattern of f-string with params and a tuple entry countless times with no issue. </p> <p>For additional information, the <code>price</code> column does not have any constraints and is a <code>numeric(5)</code>.</p> <p>For this particular instance, it is giving me the error:</p> <p><code>psycopg2.ProgrammingError: column "none" does not exist</code></p> <p>Everything I tried resulted in this error. What did end up working was not using an f-string. The following entry worked:</p> <p><code>cur.execute(f"INSERT INTO stock_data ({params}) VALUES (%s, %s, %s);", entry)</code></p> <p>My understanding is that these are identical. Why would the latter work, but including the entry directly into the <code>INSERT</code> statement not work?</p>
<p>Format just inserts the value into a string:</p> <pre><code>&gt;&gt;&gt; x = None &gt;&gt;&gt; f"What should I expect here? {x}" 'What should I expect here? None' </code></pre> <p>You pass already formatted string to <code>cur.execute()</code>. When you pass a query text with placeholders and arguments, the function <em>knows</em> how to convert them.</p> <pre><code>&gt;&gt;&gt; cur.mogrify(f"INSERT INTO stock_data ({params}) VALUES {entry};") b'INSERT INTO stock_data (ts, price, volume) VALUES (1234567, None, 3);' &gt;&gt;&gt; cur.mogrify(f"INSERT INTO stock_data ({params}) VALUES (%s, %s, %s);", entry) b'INSERT INTO stock_data (ts, price, volume) VALUES (1234567, NULL, 3);' </code></pre> <p>You should always use placeholders and arguments in cursor.execute(), also for your own safety. Read <a href="http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries" rel="noreferrer">Passing parameters to SQL queries</a>, where you can find this</p> <blockquote> <p>Warning</p> <p>Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint. </p> </blockquote>
python|python-3.x|postgresql|psycopg2
7
1,908,746
58,186,805
Python: run multiple scripts from a parent script where you can also set the variable values
<p>I have a few Python files that I want to execute sequentially in order to get an output and now would like to automate this process. So I would like to have a parent script from which I can execute all my child scrips in the right order. Also, I would like to execute one of the files twice but with two different date variables and would like to store the outputs in two different folders. How do I create such a parent script in Python?</p> <p>For example I want to execute <code>file1.py</code> first and the date (a variable in <code>file1.py</code>) should be <code>date1</code> and the output should be stored in <code>dir1</code> and then I want to execute <code>file1.py</code> again but this time the date should be <code>date2</code> and the output should be in <code>dir2</code>. And the I want to execute <code>file2.py</code>. How would I do this?</p>
<p>You can easily run python scripts from another python scripts using subprocesses. Something like:</p> <pre><code>import subprocess subprocess.Popen("script2.py some_argument") </code></pre> <p>Problem with using subprocesses - it's quite annoying to get results from it (you can print results from the script and then get them in the parent file, but still). </p> <p>Better solution - save middle results in some database (like simple SQLite file), so you use your main script to initiate child scripts, but get arguments from the database and write child script results to the database too. It's quite easy and could solve your problems (<a href="https://docs.python.org/3/library/sqlite3.html" rel="nofollow noreferrer">https://docs.python.org/3/library/sqlite3.html</a>).</p> <p>For example, to save some variable in the SQLite database, all you need is:</p> <pre><code>import sqlite3 conn = sqlite3.connect("mydatabase.db") cursor = conn.cursor() # Create table (no need if it was created before) cursor.execute("""CREATE TABLE example_table (variable_name, variable_value) """) # Save changes conn.commit() # Insert data cursor.execute("""INSERT INTO example_table VALUES ('some_variable', 'some_value')""" # Save changes conn.commit() </code></pre>
python|file|execution
0
1,908,747
65,150,837
Appending an array to an array using a function in python
<p>I'm trying to append an array to an array using a function but it seems to return None.</p> <p>Code (now works):</p> <pre class="lang-py prettyprint-override"><code>import random arr = [] def randomarr(): t = [] for i in range(3): r = random.randint(1,9) t.append(r) return t for i in range(3): arr.append(randomarr()) print(matrix) </code></pre> <p>Edit: Solved by adding a return. Shame on me for forgetting to put a return statement in my code.</p>
<p>Your funtion <code>randomarr</code> needs a <code>return</code> staterment.</p> <p>try:</p> <pre><code>def randomarr(): t = [] for i in range(3): r = random.randint(1,9) t.append(r) return t </code></pre>
python|arrays
3
1,908,748
45,436,960
Detect field change using post_save instead of pre_save signal
<p>I need to do some actions when one field has changed. </p> <p>Since this action needs to work with already saved object, I can't use <code>pre_save</code> signal like this:</p> <pre><code>@receiver(pre_save, sender=reservation_models.Reservation) def generate_possible_pairs(sender, instance, **kwargs): try: reservation_old = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed, but you may want to do something else here. else: if not reservation_old.datetime == instance.datetime: # Field has changed do_something(instance) # It would be better to be sure instance has been saved </code></pre> <p>Is it possible to use <code>post_save</code> signal for this? </p> <p>I would like to avoid adding temporary attributes to this model.</p>
<p>Using the post_save signal you won't be able to retrieve the previous state from db - But why use a signal at all ?</p> <pre><code>class Reservation(models.Model): def save(self, *args, **kw): old = type(self).objects.get(pk=self.pk) if self.pk else None super(Reservation, self).save(*args, **kw) if old and old.datetime != self.datetime: # Field has changed do_something(self) </code></pre> <p>You may also want to read this : <a href="https://lincolnloop.com/blog/django-anti-patterns-signals/" rel="noreferrer">https://lincolnloop.com/blog/django-anti-patterns-signals/</a></p>
python|django|django-models|django-signals|django-database
11
1,908,749
14,421,347
python regex pattern doesn't match in string even matching in testers (re-try, regex coach, http://ksamuel.pythonanywhere.com)
<p>I've build a regex pattern to my target: a string with data obtained from a CSV file. I'm an almost completely newbie in programming, but i'm really stuck in this step, and i've tried hard to fix the problem, as regular expressions are the (i think...) best choice from my problem, that is a search in data from CSV files with some differences betwen them but with a pattern that obeys a formal protocol (MIAME files, from the bioinformatics field). This is my code</p> <pre><code>import re ficheiro=open(raw_input('write the name of the file (formato CSV):'), 'r') lista_file=ficheiro.readlines() str_file=str(lista_file) list_spr=[] value_spr=[] for a in str_file: regex_spr = re.search(r"(spr[0-9]{4})[^\t.]*\t([0-9.]+)", a, re.I|re.M) print regex_spr.group() list_spr +=regex_spr.group(1) value_spr +=regex_spr.group(2) </code></pre> <p>but the result is always something with <code>'NoneType'</code>, like</p> <pre><code>Traceback (most recent call last): File "C:\EDPython27\test\put_words_in_dict.py", line 112, in &lt;module&gt; print regex_spr.group() AttributeError: 'NoneType' object has no attribute 'group' </code></pre> <p>Next is some of the range of str_file that i used to test the pattern:</p> <pre><code>('Reporter Identifier\tVALUE\n', 'spr0320060100000320\t4.784064198\n', 'spr0963060100000963\t3.646246197\n', 'spr1586060100001584\t5.755770215\n', 'spr1102060100001101\t5.794439261\n', 'spr1727060100001725\t6.452100774\n', 'spr0552060100000552\t6.816527711\n', 'spr0807060100000807\t3.185267941\n', 'spr0322060100000322\t5.889496662\n', 'spr0971060100000971\t3.112604228\n', 'spr0490060100000490\t6.608164616\n', 'spr0471060100000471\t6.807244139\n', 'spr0321060100000321\t5.331036948\n', 'spr1070060100001069\t6.408937689\n', 'spr1585060100001583\t6.157044216\n', 'spr1189060100001188\t3.481847857\n', 'spr1191060100001190\t3.523784616\n', 'spr1081060100001080\t6.708517655\n', 'spr1071060100001070\t7.092586967\n', 'spr1101060100001100\t6.294650154\n', 'spr0561060100000561\t7.52495517\n', 'spr0802060100000802\t8.299020685\n', 'spr1195060100001194\t6.143485258\n', 'spr0470060100000470\t5.869271803\n', 'spr1944060100001941\t7.060765363\n', 'spr0968060100000968\t6.276636704\n', 'spr1072060100001071\t7.267895537\n', 'spr0972060100000972\t5.535911422\n', 'spr1821060100001819\t7.660640949\n', 'spr0316060100000316\t6.399083059\n', 'spr0129060100000129\t6.693897057\n', 'spr0966060100000966\t6.208969299\n', 'spr0323060100000323\t6.230187159\n', 'spr1466060100001465\t7.609506586\n', 'spr0964060100000964\t6.286528191\n', 'spr1665060100001663\t5.597969101\n', 'spr0969060100000969\t5.122425278\n', 'spr1394060100001393\t7.310099682\n', 'spr0683060100000683\t7.397780719\n', 'spr1649060100001647\t6.121430945\n', 'spr0536060100000536\t7.936838283\n', 'spr1020060100001020\t7.339227818\n', 'spr0682060100000682\t7.435907739\n', 'spr0606060100000606\t6.251491879\n', 'spr0491060100000491\t5.400560984\n', 'spr0939060100000939\t6.928170725\n', 'spr1492060100001491\t7.451461913\n', 'spr0965060100000965\t5.610110186\n', 'spr1188060100001187\t3.384989187\n', 'spr1296060100001295\t5.927021756\n') </code></pre> <p>To all advisers i thank in advance.</p>
<p>From the <a href="http://docs.python.org/2/library/re.html#re.search" rel="nofollow"><code>docs</code></a> on <code>re.search()</code>:</p> <blockquote> <p>Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return <strong>None</strong> if no position in the string matches the pattern</p> </blockquote> <p>Hence the workaround here will be to check whether <code>regex_spr</code> is <code>None</code> or not.</p> <pre><code>for a in str_file: regex_spr = re.search(r"(spr[0-9]{4})[^\t.]*\t([0-9.]+)", a, re.I|re.M) if regex_spr is not None: print regex_spr.group() list_spr +=regex_spr.group(1) value_spr +=regex_spr.group(2) else: #do something else </code></pre>
python|regex|pattern-matching
1
1,908,750
14,370,066
Reading a CSV-file with repetitive headers
<p>I have not used the <code>csv module</code> in <code>python</code> before, but it seems handy enough to use.</p> <p>The problem is that the CSV file I am trying to read includes the header (indexes) every now and then in the file as well.</p> <p>Something like this:</p> <pre><code>A, B, C, D, E, F 1, 2, 3, 4, 5, 6 1, 2, 3, 4, 5, 6 1, 2, 3, 4, 5, 6 A, B, C, D, E, F 1, 2, 3, 4, 5, 6 1, 2, 3, 4, 5, 6 A, B, C, D, E, F 1, 2, 3, 4, 5, 6 1, 2, 3, 4, 5, 6 1, 2, 3, 4, 5, 6 1, 2, 3, 4, 5, 6 </code></pre> <p>Can I use the <code>csv module</code> as is, or do I have to parse this myself.</p>
<p>You can use it as-is by just checking if you just read a header line. For example, using <code>DictReader</code>, you might do:</p> <pre><code>with open('file.csv') as f: reader = csv.DictReader(f) lines = [row for row in reader if not all(k == v for k, v in row.iteritems())] </code></pre> <p>The way this would work on your example file is:</p> <ol> <li>The <code>DictReader</code> constructor reads the first header row, determining that the fields are named <code>"A", "B", "C", "D", "E", "F"</code>.</li> <li>Iterating over <code>reader</code> then returns dictionaries like <code>{"A": "1", "B": "2", ...}</code>.</li> <li>The list comprehension in <code>lines</code> looks at each row dictionary. It'll first see a dictionary like <code>{"A": "1", ...}</code>. <code>all(k == v for k, v in row.iteritems())</code> loops over the keys and values of the row, setting e.g. <code>k = "A"</code> and <code>v = "1"</code>. Whichever one it sees first depending on how the dictionary decides to iterate, it'll see <code>k != v</code>, and so the <code>all()</code> call will be <code>False</code>, meaning that the row makes it into the list <code>lines</code>.</li> <li>When it gets to a repeated header row, it'll see a dictionary like <code>{"A": "A", "B": "B", ...}</code>. Then, since the key is equal to the value for each dictionary element, the <code>all()</code> call will return <code>True</code>, and the condition in the list comprehension will be <code>False</code>, meaning that row doesn't make it into the final list. Note that if your header rows might have different spacing in them, you'll want to call <code>.strip()</code> on the keys/values before comparing them in the <code>all()</code> call.</li> <li>At the end, <code>lines</code> for your sample file would be equal to <code>[{"A": 1, "B": 2, ...}] * 9</code>; the repeated header rows have been removed.</li> </ol> <p>If you want to process the file line-by-line rather than reading it into one list all at once, just change the list comprehension for <code>lines</code> into a generator expression, by changing the <code>[row for row ...]</code> into <code>(row for row ...)</code>. Then you can loop over <code>lines</code>, but after you loop each line will be forgotten (like if you did <code>for row in reader</code> in the first place).</p>
python|parsing|csv
6
1,908,751
41,404,638
Django Template Tag for Boolean Value
<p>I'm new to Django, and I'm stuck on a template tag that I can't figure out how to get working. I know I'm missing something in my view but I have written it in several different ways and can't seem to find the right way to do this. I have a Morris chart in my app that I am trying to provide information to. I want to show the percentage of operators that are available. In my model, I have a Boolean value that says if the operator is_available. When I pass it back to the template I want the template tag to run the percentage and pass back the value to the morris pie chart.</p> <p>Here is my view:</p> <pre><code> @login_required(login_url='login/') def operator(request): operators = Operator.objects.all() operator_status = Operator.objects.values_list('is_available', flat=True) context = { 'operators': operators, 'operators_available': operator_status, } return render(request, 'content/operator.html', context) </code></pre> <p>This is the template tag in use: </p> <pre><code>&lt;div class="widget-detail-1"&gt; &lt;h2 class="p-t-10 m-b-0"&gt; {{ operators_available | percentage_of:True }} &lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and finally my template tag:</p> <pre><code>@register.filter(name='percentage_of') def percentage_of(part, whole): try: return "%d"[2:] % (float(part) / whole * 100) except (ValueError, ZeroDivisionError): return "Division by Zero" </code></pre>
<p>Its still a bit confusing what you actually want to achieve and how your <code>Operators</code> model actually look like and what values your variables contain. But I will try to make some guesses of what you want to do and try to give you an answer.</p> <p>It seems as if you mix together the use of <code>operators</code> and <code>operators_available</code> and also you mix the usage of data types such as floats and booleans. </p> <p>Lets go through your code...</p> <pre><code># This returns all Model Instances of Operators. operators = Operator.objects.all() # This only returns a list of Booleans. E.g. [True, True, False, True, True] operator_status = Operator.objects.values_list('is_available', flat=True) </code></pre> <p>In your Template you write the following</p> <pre><code>&lt;h2 class="p-t-10 m-b-0"&gt; {{ operators_available | percentage_of:True }} &lt;/h2&gt; </code></pre> <p>This equals to a function call of <code>percentage_of(operators_available, True)</code>. Remember also that <code>operators_available</code> comes from your <code>.valus_list('is_available')</code> and is a boolean. So what you're actually doing is something like <code>percentage_of(True, True)</code>.</p> <p>Inside <code>percentage_of</code> you then try to apply math to these boolean values with <code>(float(part) / whole * 100)</code>, or actually more like <code>float(True) / True * 100</code>.</p> <p><strong>The Solution</strong></p> <p>Make sure that the values that you pass to the context is in the format you expect it to. It currently look like you think that you're passing float values, but actually are passing boolean values. Try to debug or print the values before applying your template tag to them.</p>
django|python-2.7|templates|django-templates|templatetags
0
1,908,752
41,533,873
python crypto encryption/decryption - can't deal with unicode replacement chars
<p>I have a problem with AES encryption/decryption in Python - after decryption I'm receiving unicode replacement characters and I don't know how to do it correctly. From other answers I've found out what my mistake was (I'm working with encrypted text, which are bytes, not string) and I wanted to use <code>base64</code>, but I'm getting an error. Here's my try:</p> <pre><code>with open ('pub.key', 'rt') as pub_key: public_key = RSA.importKey(pub_key.read()) base64.b64encode(public_key.encrypt(file_content, key_size)) </code></pre> <p>And the error:</p> <pre><code>TypeError: b2a_base64() argument 1 must be string or buffer, not tuple </code></pre> <p>It's probably easy to fix, but I can't find a way to.</p> <p><strong>EDIT:</strong></p> <p>I've been trying to do as suggested by @Jean-François Fabre, but then I'm still having problems with decoding, I mean I get unicode replacement chars in return. Here's how I've decoded:</p> <pre><code>with open ('priv.key', 'rt') as priv_key: private_key = RSA.importKey(priv_key.read()) return private_key.decrypt(base64.b64decode(content)) </code></pre> <p>And the result is:</p> <pre><code>g��q@~w%8����[��P��"�����?�)���&amp;�q���1�g�}�w��d[�`�0j^y���4p </code></pre> <p>for the input <code>file_content</code> having fake structure catalog (<code>key_size</code> is <strong>16</strong>):</p> <pre><code>file_content = "---------------------------------------------------------------------------------------------------- /home/pawel/custom_folder/documentA.md ---------------------------------------------------------------------------------------------------- /home/pawel/custom_folder/catalogA/documentA.md ---------------------------------------------------------------------------------------------------- /home/pawel/custom_folder/catalogA/documentB.md ---------------------------------------------------------------------------------------------------- /home/pawel/custom_folder/catalogB/documentA.md Zawartosc katalogu A! ---------------------------------------------------------------------------------------------------- /home/pawel/custom_folder/catalogB/other.json { "bank": "ING Online", "user": "franek0057", "pswd": "fauDA41" } ----------------------------------------------------" </code></pre>
<p>from the <a href="https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA._RSAobj-class.html" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>encrypt(self, plaintext, K)</p> <p>Encrypt a piece of data with RSA.</p> <p>Parameters:</p> </blockquote> <p>...</p> <blockquote> <p>Returns: <strong>A tuple with two items</strong>. The first item is the ciphertext of the same type as the plaintext (string or long). <strong>The second item is always None.</strong> Overrides: pubkey.pubkey.encrypt</p> </blockquote> <p>So you just have to drop the second item of the tuple to get the encrypted message:</p> <pre><code>base64.b64encode(public_key.encrypt(file_content, key_size)[0]) </code></pre>
python|cryptography
0
1,908,753
69,854,879
FastAPI GET gives 422 Unprocessable Entity error
<p>I am new using FastAPI python and I am right now just trying to GET all the appointments in the database. The models.py is autogenerated with sqlacodegen. So it is one-to-one with the database and we have connection to the database.</p> <p>But the problem is that when I try to go to <a href="http://127.0.0.1:8000/appointments" rel="nofollow noreferrer">http://127.0.0.1:8000/appointments</a> it gives this data:</p> <pre><code>{&quot;detail&quot;:[{&quot;loc&quot;:[&quot;query&quot;,&quot;self&quot;],&quot;msg&quot;:&quot;field required&quot;,&quot;type&quot;:&quot;value_error.missing&quot;}]} </code></pre> <p>and the server gives this &quot;GET /appointments HTTP/1.1&quot; 422 Unprocessable Entity&quot;</p> <p>but I don't know what is wrong..</p> <p>in the database the data looks like this: (dummy data) <a href="https://i.stack.imgur.com/aIEf4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aIEf4.png" alt="data in database" /></a></p> <p>i have uploaded all my code under here:</p> <p>Models.py</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code># coding: utf-8 from sqlalchemy import Column, DateTime, ForeignKey, String, Table from sqlalchemy.dialects.mysql import INTEGER from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from .database import Base Base = declarative_base() metadata = Base.metadata class Customer(Base): __tablename__ = 'Customer' CPR = Column(INTEGER(11), primary_key=True) Name = Column(String(45)) Email = Column(String(45)) PhoneNumber = Column(INTEGER(11)) class Producer(Base): __tablename__ = 'Producer' CVR = Column(INTEGER(11), primary_key=True) Name = Column(String(45)) PhoneNumber = Column(INTEGER(11)) Adress = Column(String(45)) Supplier = relationship('Supplier', secondary='Producer_has_Supplier') class Statistic(Base): __tablename__ = 'Statistics' idStatistics = Column(INTEGER(11), primary_key=True) CustomerCount = Column(INTEGER(11)) ArtistCustomerCount = Column(INTEGER(11)) SessionCount = Column(INTEGER(11)) AppliedInkColorCount = Column(INTEGER(11)) class Supplier(Base): __tablename__ = 'Supplier' CVR = Column(INTEGER(11), primary_key=True) Name = Column(String(45)) PhoneNumber = Column(String(45)) Adress = Column(String(45)) class Ink(Base): __tablename__ = 'Ink' BatchNumber = Column(INTEGER(11), primary_key=True, nullable=False) Brand = Column(String(45)) ColorCode = Column(String(15)) ExperationDate = Column(DateTime) Price = Column(INTEGER(11)) Producer_CVR = Column(ForeignKey('Producer.CVR'), primary_key=True, nullable=False, index=True) Producer = relationship('Producer') Tattoo = relationship('Tattoo', secondary='Tattoo_has_Ink') t_Producer_has_Supplier = Table( 'Producer_has_Supplier', metadata, Column('Producer_CVR', ForeignKey('Producer.CVR'), primary_key=True, nullable=False, index=True), Column('Supplier_CVR', ForeignKey('Supplier.CVR'), primary_key=True, nullable=False, index=True) ) class Tattooparlor(Base): __tablename__ = 'Tattooparlor' CVR = Column(INTEGER(11), primary_key=True, nullable=False) Name = Column(String(75)) Adress = Column(String(45)) PhoneNumber = Column(INTEGER(11)) Email = Column(String(45)) Statistics_idStatistics = Column(ForeignKey('Statistics.idStatistics'), primary_key=True, nullable=False, index=True) Supplier_CVR = Column(ForeignKey('Supplier.CVR'), primary_key=True, nullable=False, index=True) Statistic = relationship('Statistic') Supplier = relationship('Supplier') class Artist(Base): __tablename__ = 'Artist' CPR = Column(INTEGER(11), primary_key=True) Name = Column(String(45)) PhoneNumber = Column(INTEGER(11)) Email = Column(String(45)) Price = Column(INTEGER(11)) Tattooparlor_CVR = Column(ForeignKey('Tattooparlor.CVR'), nullable=False, index=True) Tattooparlor = relationship('Tattooparlor') t_Parlor_has_Ink = Table( 'Parlor_has_Ink', metadata, Column('Ink_batchnumber', ForeignKey('Ink.BatchNumber'), index=True), Column('Parlor_storageID', ForeignKey('Tattooparlor.CVR'), index=True), Column('Quantity', INTEGER(11)) ) class Appointment(Base): __tablename__ = 'Appointment' id = Column(INTEGER(11), primary_key=True, nullable=False) DateTime = Column(DateTime) SessionLenght = Column(INTEGER(11)) Customer_CPR = Column(ForeignKey('Customer.CPR'), primary_key=True, nullable=False, index=True) Tattooparlor_CVR = Column(ForeignKey('Tattooparlor.CVR'), primary_key=True, nullable=False, index=True) Artist_CPR = Column(ForeignKey('Artist.CPR'), nullable=False, index=True) Artist = relationship('Artist') Customer = relationship('Customer') Tattooparlor = relationship('Tattooparlor') class Tattoo(Base): __tablename__ = 'Tattoo' idTattoo = Column(INTEGER(11), primary_key=True, nullable=False) Description = Column(String(200)) PlacementOnBody = Column(String(45)) Appointment_idAppointment = Column(ForeignKey('Appointment.idAppointment'), primary_key=True, nullable=False, index=True) Appointment = relationship('Appointment') t_Tattoo_has_Ink = Table( 'Tattoo_has_Ink', metadata, Column('Tattoo_idTattoo', ForeignKey('Tattoo.idTattoo'), primary_key=True, nullable=False, index=True), Column('Ink_BatchNumber', ForeignKey('Ink.BatchNumber'), primary_key=True, nullable=False, index=True) )</code></pre> </div> </div> </p> <p>Schemas.py</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from typing import List from sqlalchemy.orm import Session from .models import Appointment from .schemas import AppointmentBase # Function to get list of car info def get_all_apointments(session: Session) -&gt; List[Appointment]: print(List[Appointment]) return session.query(Appointment).all()</code></pre> </div> </div> </p> <p>crud.py</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from typing import List, Optional from pydantic import BaseModel import datetime # TO support creation and update APIs class AppointmentBase(BaseModel): DateTime = str(datetime) SessionLenght = int # TO support list and get APIs class Appointment(AppointmentBase): Appointment_id = int Customer_CPR = int Tattooparlor_CVR =int Artist_CPR = int class Config: orm_mode = True arbitrary_types_allowed = True # To support list API class PaginatedAppointmentInfo(BaseModel): data: List[Appointment] = [] class Config: orm_mode = True arbitrary_types_allowed = True</code></pre> </div> </div> </p> <p>main.py</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from pydantic import BaseModel import uvicorn from . import models from .database import SessionLocal, engine from .schemas import Appointment, AppointmentBase, PaginatedAppointmentInfo from .crud import get_all_apointments # Initialize the app app = FastAPI() models.Base.metadata.create_all(bind=engine) app = FastAPI() # Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() # API to get the list of car info @app.get("/appointments", response_model=PaginatedAppointmentInfo) def list_apointments(self): apointments_list = get_all_apointments(self.session) response = {"data": apointments_list} return response # GET operation at route '/' @app.get('/') def root_api(): return {"message": "Welcome to Balasundar's Technical Blog"}</code></pre> </div> </div> </p>
<p>The error message is telling you that you have defined a <em>required</em> query argument named <code>self</code> that isn't being submitted:</p> <pre><code>{&quot;detail&quot;:[{&quot;loc&quot;:[&quot;query&quot;,&quot;self&quot;],&quot;msg&quot;:&quot;field required&quot; ^ ^ type name </code></pre> <p>If you look at the function you're calling, you'll see that you have a definition that mentions that specific name:</p> <pre><code># API to get the list of car info @app.get(&quot;/appointments&quot;, response_model=PaginatedAppointmentInfo) def list_apointments(self): ^ </code></pre> <p>Since there is no implicit first argument for regular functions (only for methods inside a class), FastAPI expects a <code>self</code> argument to be supplied to the function. Since you're not including that - I'm guessing you have extracted this from a class, since you're also using <code>self.session</code> further down - FastAPI gives an error.</p> <p>As you have defined a <code>get_db</code> dependency to get the session, you should probably use that instead (since <code>self</code> outside of a class context doesn't have any particular meaning):</p> <pre><code># API to get the list of car info @app.get(&quot;/appointments&quot;, response_model=PaginatedAppointmentInfo) def list_apointments(session = Depends(get_db)): apointments_list = get_all_apointments(session) response = {&quot;data&quot;: apointments_list} return response </code></pre> <p>There is no longer any required arguments for the function - the session gets retrieved from <code>get_db</code> and there are no other arguments to the function.</p>
python|sqlalchemy|fastapi
0
1,908,754
73,069,427
How to fix:ValueError: not enough values to unpack (expected 2, got 1)
<p>I'm trying to plot a graph and keep getting the error ValueError: not enough values to unpack (expected 2, got 1)</p> <pre><code>#turning csv into array ``AL_Force=data1[&quot;Force (kN)&quot;].to_numpy() `Al_Strain_p=data1[&quot;Tensile strain (Strain 1)(%)&quot;] #strain in % ``#Calculating Stress=Force/Area AL_stress=AL_Force/AL_a #changing strain % into a fraction AL_Strain=Al_Strain_p/100 #High Carbon Steel data# #turning csv into an array HC_Force=data3[&quot;Force(kN)&quot;].to_numpy() HC_Strain_p=data3[&quot;Tensile strain (Strain 1)(%)&quot;].to_numpy() #calcuting stress HC_Stress=HC_Force/HC_a #changing strain % into a fraction HC_Strain=HC_Strain_p/100 #Low Carbon Steel Data# LC_Force=data2[&quot;Force(kN)&quot;].to_numpy() LC_Strain_p=data2[&quot;Tensile strain (Strain 1)(%)&quot;] #calculating stress LC_Stress=LC_Force/LC_a #changing strain % into a fraction LC_Strain=LC_Strain_p/100 #plotting graph fig,ax1=plt.plot(AL_stress,AL_Strain,linestyle='-',color='black') </code></pre>
<p>Your issue is your final line. plt.plot() returns a single object but you are setting it to two variables: <code>fig</code> and <code>ax1</code>. Change to:</p> <pre><code>fig = plt.plot(AL_stress, AL_Strain, linestyle='-',color='black') </code></pre> <p>If you want to investigate how subplots (why you would use ax) are used check out this <a href="https://stackoverflow.com/questions/34162443/why-do-many-examples-use-fig-ax-plt-subplots-in-matplotlib-pyplot-python">other answer</a>.</p>
python|arrays|pandas|numpy
0
1,908,755
55,981,347
How to split and duplicate rows according to string in one column with python / pandas?
<p>I have a df where some values are added to the same row like this fake df: </p> <pre><code> [['Apple, Kiwi, Clementine', np.nan , 'Cycling', 5], ['Kiwi', 'Blue', np.nan , 20], ['Banana, Clementine', np.nan , 'Hockey', 12], ['Apple', 'Purple', 'Triathlon', 15], ['Kiwi', np.nan, 'Swimming', 8]]), columns=['fruit', 'colour', 'sport', 'wins']) </code></pre> <p>What I would like is to duplicate the rows with multiple fruits while splitting the first entry to contain only one fruit. <a href="https://i.stack.imgur.com/OK64T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OK64T.png" alt="enter image description here"></a> In the end I want to plot the average wins per fruit. So if there is a way of grouping where each fruit mentioned is grouped with the correct fruit so to speak that would also work. </p> <p>I have tried some string manipulation but then it is simply split up and the values in the other columns not duplicated. It is quite frustrating since I know how to do it in r but am a beginner in python.</p>
<p>Use @Wen-Ben's solution from <a href="https://stackoverflow.com/questions/53218931/how-to-unnest-explode-a-column-in-a-pandas-dataframe/53218939#53218939">here</a>:</p> <pre><code>s=pd.DataFrame([[x] + [z] for x, y in zip(df.index,df.fruit.str.split(',')) for z in y], columns=[0,'Fruit']) df_new=s.merge(df,left_on=0,right_index=True).drop(0,1) print(df_new) </code></pre> <hr> <pre><code> Fruit fruit colour sport wins 0 Apple Apple, Kiwi, Clementine NaN Cycling 5 1 Kiwi Apple, Kiwi, Clementine NaN Cycling 5 2 Clementine Apple, Kiwi, Clementine NaN Cycling 5 3 Kiwi Kiwi Blue NaN 20 4 Banana Banana, Clementine NaN Hockey 12 5 Clementine Banana, Clementine NaN Hockey 12 6 Apple Apple Purple Triathlon 15 7 Kiwi Kiwi NaN Swimming 8 </code></pre> <p><strong><em>Note</em></strong> You can chose to drop the <code>fruit</code> column if you want.</p>
python|string|pandas
3
1,908,756
55,605,023
How to get Big O time complexity of code?
<p>I have a good understanding of Big O notation, but I am very confused about this question: </p> <blockquote> <p>Given a Sorted List with N elements, and that the key being searched is repeated R times in the list, what is the complexity of my_search() in terms of O notation?</p> </blockquote> <pre><code>def my_search( data, key ): found = False low = 0 count = 0 high=len(data)-1 while ( not found and low&lt;=high): guess = (high+low)//2 print('guess: ', guess) if ( key == data[guess] ): found = True count = 1 k = guess - 1 while k&gt;=0 and data [k] == key: count += 1 k -= 1 k = guess + 1 while k &lt; len(data) and data [k] == key: count += 1 k += 1 else: if (key &lt; data[guess]): high=guess-1 else: low = guess+1 print('count:', count) return count </code></pre> <p>The passed arguments for this function is a list and a key, the function calculates how many times the key appears in the list, for example <code>my_search([1,1,2,2,3,3,3,3,3,3,6,7], 1)</code>. The answer key says that the time complexity for this code is <a href="https://i.stack.imgur.com/NlTmi.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NlTmi.gif" alt="this"></a> , how did they come up with this answer?</p>
<p>searching in an ordered list is O(log(N)) (<a href="https://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow noreferrer">binary search</a>). once you have found the element you are looking for you need to check (at least) R elements against the item you have searched for. so in total O(log(N)) + R.</p>
python|time-complexity|big-o
1
1,908,757
50,099,600
abstract classes without abstract methods creating objects in python
<p>Basically, I knew that abstract base classes are used as skeleton classes just like regular classes, but enforces that abstract methods should be overridden by the child/inherited classes if it has one like below</p> <pre><code>Class AbstractClass(object): __metaclass__ = abc.ABCMeta @abstractmethod def absmethod(self): pass class ChildClass(AbstractClass): def absmethod(self): print "Yeah!" obj = ChildClass() </code></pre> <p>So we can create an object of <code>ChildClass</code> as above</p> <p>We know we can't instantiate an abstract class as it meant to be just skeleton and we will get an error if we try to instantiate it as below</p> <pre><code>obj = AbstractClass() *** TypeError: Can't instantiate abstract class AbstractClass with abstract methods absmethod </code></pre> <p>But what my actual query about posting this <code>StackOverflow</code> is if we create an abstract class by using <code>abc.ABCMeta</code>, without abstract methods, I can able to create an instance of the abstract class which should not be the case(correct me if I am wrong)</p> <pre><code>Class AbstractClass(object): __metaclass__ = abc.ABCMeta obj = AbstractClass() </code></pre> <p><strong>OOOPPPSS</strong> it worked, we can actually create an object of abstract classes without abstract methods? So please let me know the key points behind this</p>
<p>From <a href="https://docs.python.org/3/library/abc.html#abc.abstractmethod" rel="noreferrer">the docs</a>:</p> <blockquote> <p>A class that has a metaclass derived from <code>ABCMeta</code> cannot be instantiated unless all of its abstract methods and properties are overridden.</p> </blockquote> <p>Conversely, this means that any class with no abstract methods or properties like your <code>AbstractClass</code> <em>can</em> be instantiated.</p> <hr> <p>If you want to disallow instantiation of the topmost parent class, you can write a custom class that performs a type check in its <a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="noreferrer"><code>__new__</code></a> method:</p> <pre><code>class SubclassOnlyABC(object): __metaclass__ = abc.ABCMeta def __new__(cls, *args, **kwargs): if cls.__bases__ == (SubclassOnlyABC,): msg = 'Abstract class {} cannot be instantiated'.format(cls.__name__) raise TypeError(msg) return super(SubclassOnlyABC, cls).__new__(cls, *args, **kwargs) </code></pre> <pre><code>class AbstractClass(SubclassOnlyABC): pass class ChildClass(AbstractClass): pass ChildClass() # works because it's a child class of an abstract class AbstractClass() # throws TypeError because its parent class is "object" </code></pre> <hr> <p>You can also write a <code>__new__</code> method that prevents instantiation of classes with no abstract methods:</p> <pre><code>class NonEmptyABC(object): __metaclass__ = abc.ABCMeta def __new__(cls, *args, **kwargs): # check if ANY abstractmethod exists for parentcls in cls.__mro__: if any(getattr(attr, '__isabstractmethod__', False) for attr in vars(parentcls).values()): break else: msg = 'Abstract class {} cannot be instantiated'.format(cls.__name__) raise TypeError(msg) return super(NonEmptyABC, cls).__new__(cls, *args, **kwargs) </code></pre> <pre><code>class EmptyAbstractClass(NonEmptyABC): pass class NonemptyAbstractClass(NonEmptyABC): @abc.abstractmethod def foo(self): pass class NonemptyChild(NonemptyAbstractClass): def foo(self): pass NonemptyChild() # works because "foo" is an abstractmethod EmptyAbstractClass() # throws TypeError because there are no abstractmethods </code></pre>
python|abstract-class
10
1,908,758
49,997,804
Python - check if values are inside objects in list
<p>In something like this</p> <pre><code>class Obj: def __init__(self, x, y): self.x = x self.y = y li = [Obj(0, 0), Obj(0, 1), Obj(2, 3)] print(Obj(2,3) in li) </code></pre> <p>I have a False output because even if x and y are the same it counts the object as a different instance. I can remedy using a loop inside the list and checking</p> <pre><code>if(2==o.x and 3==o.y): return True </code></pre> <p>Is there some cleaner way to get this without using a loop ?</p>
<p>Implement a function <code>__eq__</code> like below in your class.</p> <pre><code>def __eq__(self, x,y): if self.x==x and self.y==y: return True </code></pre> <p>After that use list comprehension to traverse over the <code>list</code> of objects.</p> <p><code>result = any(Obj(2,3) == i for i in obj_list )</code></p>
python
0
1,908,759
66,573,105
Cannot import modules from other folders
<p>I am currently having an issue with importing files from other directories in my python project.</p> <p>My current file structure is</p> <pre><code>Project - Backend - Config + __init__.py + databaseConfig.py - DataAccess + __init__.py + sqlConns.py - __init__.py - api.py - main.py - setup.py </code></pre> <p>What I am trying to do is import /Config/databaseConfig.py file into /DataAccess/sqlConns.py file. I get the following error when trying to run the sqlConns.py file</p> <pre><code>PS C:\source\repos\aaStats\aaStats&gt; py .\Backend\DataAccess\sqlConns.py Traceback (most recent call last): File &quot;C:\source\repos\aaStats\aaStats\Backend\DataAccess\sqlConns.py&quot;, line 2, in &lt;module&gt; import Config.databaseConfig ModuleNotFoundError: No module named 'Config' </code></pre> <p>I have also tried using relative imports, but I am met with another error.</p> <pre><code>PS C:\source\repos\aaStats\aaStats&gt; py .\Backend\DataAccess\sqlConns.py Traceback (most recent call last): File &quot;C:\source\repos\aaStats\aaStats\Backend\DataAccess\sqlConns.py&quot;, line 2, in &lt;module&gt; from ..Config import databaseConfig as dbcfg ImportError: attempted relative import with no known parent package </code></pre> <p>Config/databaseConfig.py contains database configuration parameters that I want to reference is various places in my project. It isn't a huge deal if I had to move this single file in order to get it to be referenced properly, but I will want to use structures like this for files later on in my project.</p> <p>Here are some details about my files:</p> <p>/Config/__init__.py</p> <pre><code>from . import databaseConfig </code></pre> <p>/DataAccess/__init__.py</p> <pre><code>from . import sqlConns </code></pre> <p>Backend/__init__.py</p> <pre><code>from . import DataAccess from . import Config </code></pre> <p>Backend/setup.py</p> <pre><code>from setuptools import setup, find_packages setup( name='aaStatsApi', version='0.1.0', packages= ['DataAccess','Config'], install_requires=[ 'fastapi==0.63.0', 'uvicorn==0.13.4', 'requests==2.25.1', 'pyodbc==4.0.30', ] ) </code></pre>
<ol> <li>Check out <a href="https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python">this post</a>.</li> <li>The fact that you can't perform relative imports so easily is by design, for better or for worse. The ideal way is have your main script in the root (<code>Backend</code>) directory and do all your calls from there. The function that has <code>__name__ == __main__</code> is your calling function. If you do not <em>directly</em> call <code>Calls.py</code> or <code>Configs.py</code> from a console, but are calling them from another <em>main</em> function within your root directory, you should be able to place the following into <code>Conns.py</code>:</li> </ol> <pre class="lang-py prettyprint-override"><code># FILE: DataAcess\sqlConns.py from Config.dataBaseConfig import * # or whatever you need to import </code></pre> <p>Again, the key is to ensure that your starting point in from your root project directory.</p> <ol start="3"> <li><em><strong>NOT RECOMMENDED:</strong></em> For risk of getting downvoted, and I do not recommend this, but <em>you could append the relative path to your calling class</em>:</li> </ol> <pre class="lang-py prettyprint-override"><code>import sys, os sys.path.append(os.path.abspath(&quot;../Config&quot;)) from sqlConns import * # or whatever sys.path.pop() # clear sys.path </code></pre>
python|import|python-import
0
1,908,760
64,736,835
Pandas: resample categorical index data
<p>Assume some measurement data (in reality given about every minute) named <code>logData</code>:</p> <pre><code>import pandas as pd, numpy as np idxData = pd.to_datetime(['08:00', '08:15', '08:30', '08:45', '09:00']) logData = pd.DataFrame(np.array([1.0, 2.0, 3.0, 4.0, 5.0]), columns=['val'], index=idxData) idxRng = pd.interval_range(idxData[0], idxData[-1], freq='30min') avgData = logData.groupby( pd.cut(logData.index, idxRng) ).mean() </code></pre> <p>The data is grouped into <code>avgData</code> e.g. looking like this:</p> <pre><code> val (08:00:00, 08:30:00] 2.5 (08:30:00, 09:00:00] 4.5 </code></pre> <p>This downsampled <code>avgData</code> should now (after performing some other calculations) be upsampled again, e.g. to a frequency of <code>freq='10min'</code> for further calculations. Since <code>avgData.resample('10min')</code> throws the following error, the question is how to <strong>resample categorical data</strong>?</p> <pre><code>TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'CategoricalIndex' </code></pre> <p>Many thanks in advance!</p>
<p>In order for a resample to work, your index needs to have a datatype of datetime64[ns] Check the datatype of your index by running the code below.</p> <pre><code>avgData.index.dtype </code></pre>
python|pandas|pandas-groupby|pandas-resample
0
1,908,761
64,873,067
Interactive matplotlib drawing not working in some environments
<p>I have an interactive manual line/plot drawing solution using matplotlib and canvas.mpl_connect working on my Mac with PyCharm but it's completely non-interactive when the same script is run on my Linux box with either PyCharm or Sypder. The drawing canvas simply isn't waiting for the user to do any manual drawing whereas it does running the exact same script on my Mac. Is there something in my script that can be tweaked so that this solution is a bit more universal?</p> <pre><code>import pandas as pd import os from pathlib import Path from matplotlib.widgets import TextBox import matplotlib.gridspec as gridspec from sqlalchemy import create_engine from sqlalchemy.types import INTEGER, VARCHAR, DATETIME,TEXT import mysql.connector def onclick(event): xcoords.append(event.xdata) ycoords.append(event.ydata) # Update plotted coordinates graph_2.set_xdata(xcoords) graph_2.set_ydata(ycoords) # Refresh the plot fig.canvas.draw() if event.dblclick: row = [xcoords[0], ycoords[0]] list_of_rows.append(row) xcoords.clear() ycoords.clear() elif len(xcoords) == 2: row = [xcoords[0], ycoords[0], xcoords[1], ycoords[1]] list_of_rows.append(row) xcoords.clear() ycoords.clear() # Get info up fron we we don't have to later playerid = input('Enter player ID: ') matchid= input('Please enter match ID: ') event_type = input('Please enter event type: ') teamid = input('Please enter team ID: ') phase_type = input('Please enter phase type (return for OpenPlay: ') if len(phase_type)&lt;3: phase_type = 'OpenPlay' fig,ax = plt.subplots() plt.ylim(-3650, 3650) plt.xlim(-5300, 5300) data_folder = Path(&quot;&quot;) filename = os.path.join(os.getcwd(), data_folder,'Pitch.png') im = plt.imread(filename) #implot = plt.imshow(im) #fig = plt.figure() #ax = fig.add_subplot(111) # Plot some random data #values = np.random.rand(4,1); #graph_1, = ax.plot(values, label='original curve') graph_2, = ax.plot([], marker='.') # Keep track of x/y coordinates xcoords = [] ycoords = [] list_of_rows = [] x0,x1 = ax.get_xlim() y0,y1 = ax.get_ylim() ax.imshow(im, extent=[x0, x1, y0, y1], aspect='auto', zorder=0) fig.canvas.mpl_connect('button_press_event', onclick) plt.show() print(list_of_rows) # Create empty dataframe to hold values once clicked on image if event_type in ['Pass','Cross', 'SetPlay']: column_names = ['location_x', 'location_y', 'target_x', 'target_y'] elif event_type == 'Shot': column_names = ['location_x', 'location_y']``` Thanks in advance for any input/recommendations! </code></pre>
<p>plt.show(block=True) works like a charm. Waits for the window to be manually closed before proceeding. Not clear why this wasn't needed in my Mac environment.</p>
python|pandas|matplotlib|onclick
0
1,908,762
64,999,887
How do I handle different date format in a pandas column?
<p>In the date column of some dataset, I have the date column written in different formats. Not the usual number formats style, but with the days of the week and months spelt out. Some rows have the months spelt short, others have theirs spelt in full. Making it difficult to do a simple <code>pd.to_datetime(df,format)</code>. I thought about running a for loop. I split each row by '-':</p> <pre><code>for x in df['Date']: if len(i.split('-')[1])&lt;=6: </code></pre> <p>But then I realized this wasn't a great condition. I am thinking the solution would be regex? What do I do?</p> <p><a href="https://i.stack.imgur.com/9SQaB.png" rel="nofollow noreferrer">A sample of the dataset</a></p>
<p>You don't need to iterate, you can use <code>.loc</code> with <code>.str</code> accessor splits:</p> <pre><code>df.loc[df['Date'].str.split('-',expand=True)[6].str.len()&lt;=6,'Date'] </code></pre> <p>You can assign anything if you like, or just get it.</p>
python|pandas
0
1,908,763
64,989,375
Doing a collection find in PyMongo and has no effect
<p>Hi I was facing a problem when I doing PyMongo.</p> <p>keywords is a user input by <code>list(input().split())</code></p> <p>When I doing the <code>results = post_collection.find()</code></p> <p>I tried four different statement after the find bracket,</p> <ol> <li><code>{&quot;Title&quot;: keyword} or {&quot;Body&quot;: keyword} or {&quot;Tags&quot;: keyword}</code></li> <li><code>{&quot;title&quot;: keyword} or {&quot;body&quot;: keyword} or {&quot;tags&quot;: keyword}</code></li> <li><code>&quot;Title&quot;: {&quot;$in&quot;: keywords}} or {&quot;Body&quot;: {&quot;$in&quot;: keywords}} or {&quot;Tags&quot;: {&quot;$in&quot;: keywords}</code></li> <li><code>{}</code></li> </ol> <p>1,2,3 gives me no response, the <code>results.count()</code> return 0 to me , and it will never goes into next <code>'for posts in results'</code> loop, it will just skip the for loop and keep going to the next input section. 4 returns me all the posts in my json file opened in the beginning.</p> <p>I was wondering why I was having that problem, and I am struggling about it the whole day.</p> <p>Thank you for your time</p> <p>Below is part of my code. <a href="https://i.stack.imgur.com/N5jMd.png" rel="nofollow noreferrer">part of code</a></p> <p>Part of document { &quot;Id&quot;: &quot;1&quot;, &quot;PostTypeId&quot;: &quot;1&quot;, &quot;AcceptedAnswerId&quot;: &quot;9&quot;, &quot;CreationDate&quot;: &quot;2010-08-17T19:22:37.890&quot;, &quot;Score&quot;: 16, &quot;ViewCount&quot;: 28440, &quot;Body&quot;: &quot;<p>What is the hardware and software differences between Intel and PPC Macs?</p>\n&quot;, &quot;OwnerUserId&quot;: &quot;10&quot;, &quot;LastEditorUserId&quot;: &quot;15&quot;, &quot;LastEditDate&quot;: &quot;2010-09-08T15:12:04.097&quot;, &quot;LastActivityDate&quot;: &quot;2017-09-21T12:16:56.790&quot;, &quot;Title&quot;: &quot;What is the difference between Intel and PPC?&quot;, &quot;Tags&quot;: &quot;&quot;, &quot;AnswerCount&quot;: 9, &quot;CommentCount&quot;: 0, &quot;FavoriteCount&quot;: 6, &quot;ContentLicense&quot;: &quot;CC BY-SA 2.5&quot; },</p>
<p>The problem in your code is under <code>print(3)</code>. In your mongo request, the way you are passing the <code>keyword</code> is actually invalid, because this one is blocked in the scope of <code>for loop</code> on top of it. So the mongo request can't reach the correct keyword. The solution is to push all the code under <code>print(keyword)</code>, in the first <code>for loop</code>. Like this:</p> <pre><code>for keyword in keywords: print(keyword) print(3) results = posts_collection.find({&quot;$or&quot;: [{&quot;Title&quot;: keyword}, {&quot;Body&quot;: keyword}, {&quot;Tags&quot;: keyword}]}) print(results) print(results.count()) print(4) for posts in results: print(5) if posts['PostTypeId'] == 1: print(posts['titlse']) # ... else: print(1) continue </code></pre>
python|mongodb|pymongo
0
1,908,764
63,978,057
Secure raw SQL query in Django with psycopg2
<p>I am creating a web application using django framework. In one of the SQL queries I had to join multiple tables and use the user input as part of the &quot;where&quot; clause to fetch the results. Since the query was rather complex, I chose to use raw SQL instead of django framework.</p> <p>A simplified form of the query is :</p> <pre><code>select * from table where {where_clause} </code></pre> <p><code>where_clause</code> would be something of the form <code>col1&gt;100 and col2&gt;50 and col3 &lt;40</code> and so on This part is created on the front end based on the user input (sort of like a stock screener).</p> <p>To make the query secure against SQL injection, I decided to use <code>psycopg2</code> which builds the query as :</p> <pre><code>query = sql.SQL(&quot;select {field} from {table} where {pkey} = %s&quot;).format( field=sql.Identifier('my_name'), table=sql.Identifier('some_table'), pkey=sql.Identifier('id')) </code></pre> <p>Even if I separate all the parts of <code>where_clause</code> into identifiers and literals, I do not know what all columns are there beforehand to write in this way. There could potentially be many columns which are chosen by the user to filter on.</p> <p>How can I go about making the query secure ?</p>
<p>Letting a user define (or even know) your tables/columns names seems not secure at the first place.</p> <p>I would create some dict of allowed values a user can filter by that map to actual tables in your db (so user doesn’t know your db column names).</p> <p>Then instead of letting a user write ‘&gt;’, ‘&lt;‘ etc operators directly I’d provide a user with a dropdown of comparison operators to use.</p> <p>So in the end a user would send to your backend a followind filter object:</p> <pre class="lang-json prettyprint-override"><code>{ “Field name 1”: {“value”: “some value”, “comparison_operator”: “greater_than”, “Filed name 2”: ... } </code></pre> <p>Then on your backend convert these values to the sql where clause</p>
python|sql|django|security|sql-injection
0
1,908,765
53,087,559
Pandas + sqlalchemy: extracting multiple specific columns from csv to sqlite via pandas
<p>I have a .csv file with > 100 columns and several thousands of rows:</p> <pre><code>&gt; Datetime A B C D E ... FA FB &gt; 01.01.2014 00:00 15,15 15,15 32,43 15,15 33,27 82,59 1,38 &gt; 01.01.2014 01:00 12,96 12,96 32,49 12,96 30,07 82,59 1,38 &gt; 01.01.2014 02:00 12,09 12,09 28,43 12,09 23,01 82,59 1,38 &gt; 01.01.2014 03:00 11,7 11,7 27,63 11,7 11,04 82,59 1,38 &gt; 01.01.2014 04:00 11,66 11,66 25,99 11,66 9,09 82,59 1,38 &gt; ... ... ... ... ... ... ... ... &gt; 01.10.2018 23:00 9,85 9,85 17,2 9,85 10,44 92,15 1,09 </code></pre> <p>Now I need to extract this data column-wise and export it into a sqlite3 database like this:</p> <pre><code>Datetime and A Datetime and B Datetime and C ... Datetime and FB </code></pre> <p>In order to get a database table that looks like this:</p> <pre><code>Datetime Value ID &gt; 01.01.2014 00:00 15,15 A &gt; 01.01.2014 01:00 12,96 A &gt; 01.01.2014 02:00 12,09 A &gt; ... ... ... &gt; 01.01.2014 00:00 15,15 FB &gt; 01.01.2014 01:00 12,96 FB &gt; 01.01.2014 02:00 12,09 FB </code></pre> <p>I manage to write some data by using the following code:</p> <pre><code>import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Numeric, DateTime from sqlalchemy.orm import sessionmaker from datetime import datetime import pandas as pd Base = declarative_base() # Declaration of the class in order to write into the database. This structure is standard and should align with SQLAlchemy's doc. class Values_1(Base): __tablename__ = 'Timeseries_Values' ID = Column(Integer, primary_key=True) Date = Column(DateTime, primary_key=True) Value = Column(Numeric) def main(fileToRead): # Set up of the table in db and the file to import fileToRead = r'data.csv' tableToWriteTo = 'Timeseries_Values' df = pd.read_csv(fileToRead, sep=';', decimal=',', parse_dates=['Date'], dayfirst=True) df.columns = ['Datetime', 'A'] engine = create_engine('sqlite:///data.db') conn = engine.connect() metadata = sqlalchemy.schema.MetaData(bind=engine, reflect=True) table = sqlalchemy.Table(tableToWriteTo, metadata, autoload=True) # Open the session Session = sessionmaker(bind=engine) session = Session() conn.execute(table.insert(), listToWrite) session.commit() session.close() </code></pre> <p>So this works for a single combination ("Datetime and A"), but how can I automatically add all the other combinations?</p> <p>thx much in advance.</p>
<p>This is a partial answer, but it looks like the crux of this is problem that you need to <code>melt</code> the dataframe:</p> <p><strong>df</strong></p> <pre><code> A B C D E Datetime 2014-01-01 00:00:00 15,15 15,15 32,43 15,15 33,27 2014-01-01 01:00:00 12,96 12,96 32,49 12,96 30,07 2014-01-01 02:00:00 12,09 12,09 28,43 12,09 23,01 2014-01-01 03:00:00 11,7 11,7 27,63 11,7 11,04 2014-01-01 04:00:00 11,66 11,66 25,99 11,66 9,09 </code></pre> <p><strong>Reset and melt:</strong></p> <pre><code>df1 = df.reset_index().melt('Datetime', var_name='ID', value_name='Value' ) Datetime ID Value 0 2014-01-01 00:00:00 A 15,15 1 2014-01-01 01:00:00 A 12,96 2 2014-01-01 02:00:00 A 12,09 3 2014-01-01 03:00:00 A 11,7 4 2014-01-01 04:00:00 A 11,66 5 2014-01-01 00:00:00 B 15,15 6 2014-01-01 01:00:00 B 12,96 7 2014-01-01 02:00:00 B 12,09 8 2014-01-01 03:00:00 B 11,7 9 2014-01-01 04:00:00 B 11,66 10 2014-01-01 00:00:00 C 32,43 11 2014-01-01 01:00:00 C 32,49 12 2014-01-01 02:00:00 C 28,43 13 2014-01-01 03:00:00 C 27,63 14 2014-01-01 04:00:00 C 25,99 15 2014-01-01 00:00:00 D 15,15 16 2014-01-01 01:00:00 D 12,96 17 2014-01-01 02:00:00 D 12,09 18 2014-01-01 03:00:00 D 11,7 19 2014-01-01 04:00:00 D 11,66 20 2014-01-01 00:00:00 E 33,27 21 2014-01-01 01:00:00 E 30,07 22 2014-01-01 02:00:00 E 23,01 23 2014-01-01 03:00:00 E 11,04 24 2014-01-01 04:00:00 E 9,09 </code></pre>
python|pandas|sqlalchemy
0
1,908,766
65,385,245
Altair scatter plot to bar chart single select row of data frame
<p>A newbie question for Altair visualization lib in Python. I have a pandas dataframe, all columns are numeric but one column is a string label (see below). I am trying to build interactive chart, binding scatter plot single selection to bar chart. The bar chart will show rest of the numeric values, X axis will be column name, Y axis will be numeric values. All examples are related to aggregation. How can visualize it in Altair? See representative data below. The label value will be used to select the row.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Label</th> <th>Score 1</th> <th>Score 2</th> <th>Score 3</th> </tr> </thead> <tbody> <tr> <td>red</td> <td>0.22</td> <td>0.55.</td> <td>0.44</td> </tr> <tr> <td>blue</td> <td>0.45</td> <td>0.66.</td> <td>0.33</td> </tr> <tr> <td>green</td> <td>0.45</td> <td>0.66.</td> <td>0.33</td> </tr> <tr> <td>black</td> <td>0.45</td> <td>0.66.</td> <td>0.33</td> </tr> </tbody> </table> </div> <p>What I try to do similar to following but no aggregation: <a href="https://altair-viz.github.io/gallery/scatter_with_layered_histogram.html" rel="nofollow noreferrer">https://altair-viz.github.io/gallery/scatter_with_layered_histogram.html</a></p>
<p>It's not clear what you want shown in the interactive scatter plot mentioned in the description, but I can answer your question about the bar chart.</p> <p>If you want column names on the x-axis of a chart, the way to do this is to use a <a href="https://altair-viz.github.io/user_guide/transform/fold.html" rel="nofollow noreferrer">Fold Transform</a>, which folds together several columns into a column of keys and a column of values.</p> <p>For your data, it might look like this (using color <code>scale=None</code> so that the actual colors in the data are used):</p> <pre class="lang-python prettyprint-override"><code>import altair as alt import pandas as pd df = pd.DataFrame({ 'Label': ['red', 'blue', 'green', 'black'], 'Score 1': [0.22, 0.45, 0.45, 0.45], 'Score 2': [0.55, 0.66, 0.66, 0.66], 'Score 3': [0.44, 0.33, 0.33, 0.33], }) alt.Chart(df).transform_fold( ['Score 1', 'Score 2', 'Score 3'], as_=['column', 'value'] ).mark_bar().encode( x='column:N', y='value:Q', color=alt.Color('Label:N', scale=None) ) </code></pre> <p><a href="https://i.stack.imgur.com/obzWF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/obzWF.png" alt="enter image description here" /></a></p> <p>(Side note: in the future, consider presenting your representative data in the form of executable code like the pandas DataFrame I used above, rather than in the form of a formatted table).</p>
python|pandas|visualization|interactive|altair
1
1,908,767
65,469,608
How to label colored bars on matplotlib?
<p>I'm trying to plot a bar graph in which certain bars need to be highlighted. How do I include a legend that explains what the colored bars are?</p> <p>Below is my code. I want the legend to indicate that &quot;Relevant bars&quot; are blue (not gray, as it says at the moment).</p> <pre><code>import matplotlib.pyplot as plt data = range(1,6) labels = ['a','b','c','d','e'] relevant_bars = ['b','e'] bars = plt.bar(data, data, color='gray') for i in range(len(bars)): if labels[i] in relevant_bars: bars[i].set_color('blue') plt.xticks(pos, labels) plt.legend(['Relevant bars']); </code></pre> <p><a href="https://i.stack.imgur.com/8HvvP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8HvvP.png" alt="enter image description here" /></a></p>
<p>change</p> <pre><code> plt.legend(['Relevant bars']); </code></pre> <p>to</p> <pre><code> legend_elements = [Line2D([0], [0], color='b', lw=4, label='Relevant bars')] plt.legend(handles=legend_elements); </code></pre>
python|matplotlib|bar-chart
2
1,908,768
71,450,655
Devstack installation error : CryptographyDeprecationwarning: int_from_bytes is deprecated, use int.from_bytes instead
<p>Hello I am trying to install devstack on ubuntu 20.04 and I keep getting error</p> <p>Cryptographydepricationwarning : int_from_bytes is deprecated use int.from_bytes instead</p> <p>Does anyone knows how to solve it?</p> <p>Thanks in advance</p> <p><a href="https://i.stack.imgur.com/S472F.jpg" rel="nofollow noreferrer">CryptographyDepricationWarning</a></p>
<p>you need to pin an older version of cryptography, e.g. cryptography&lt;3.4, that will satisfy SecretStorage's dependency and not throw deprecation warnings. That means you should install cryptography&lt;3.4 into your environment, and this version of cryptography should be picked up.</p> <p>To Do so:</p> <pre><code>pip freeze | grep &quot;cryptography&quot; #show current version of cryptography sudo pip uninstall cryptography #uninstall it sudo pip install cryptography==3.3 #install new version &lt;3.4 (here I chose 3.3) </code></pre> <p>I referred to <a href="https://github.com/matrix-org/synapse/issues/9454" rel="nofollow noreferrer">this</a> similar issue</p>
python|linux|cryptography|devstack
0
1,908,769
10,587,240
Multiple matches of regular expressions with different strings
<p>It's quite difficult to describe (especially as a non-native speaker), but I'll do my best:</p> <p>In my python program, I have a database of, let's say, news articles and one of the users wanting to be informed about a subset of them. Every news object has multiple strings like <em>Author</em>, <em>Title</em> or <em>Text</em>.</p> <p>I want to save the user's interests as an expression which allows me to match the different string attributes and combine those matches with logical operators like this (The syntax doesn't really matter):</p> <pre class="lang-none prettyprint-override"><code>attribute author matches pattern (\w*\sSmith) and attribute text doesn't contain pattern (financ(e|ial)) </code></pre> <p>Then, I have to iterate, for every user, over all articles and if the expression is valid, inform him/her.</p> <p>My problem is that I don't really know what language to use. I'd like to avoid creating my own and writing my own parser with all the usual problems (security, escaping, etc.) because I'm sure this is a fairly common problem and there has to be a better solution than I'm able to create.</p> <p>I've searched the web for some time now, but haven't found anything. Every help is very appreciated; thanks in advance!</p> <p><strong>[Edit:]</strong> Reformat pseudo-code as RabbidRabbit suggested.</p>
<p>There are several ways to approach this problem. They range from a list of <code>(attribute, regexp)</code> tuples that you apply in a per-object basis to more complex things.</p> <p>One option is to find some kind of declarative "language" with which you can specify simple queries such as the one you mention. This can be something that would be stored in a JSON or YAML structure, it all depends on how complex/extensible you want it to be.</p> <p>If you want it to be really extensible, you may event want to have a DSL (domain-specific language):</p> <p><a href="http://www.slideshare.net/Siddhi/creating-domain-specific-languages-in-python" rel="nofollow noreferrer">http://www.slideshare.net/Siddhi/creating-domain-specific-languages-in-python</a></p> <p>Here is a past StackOverflow post that may be helpful.</p> <p><a href="https://stackoverflow.com/questions/140026/writing-a-domain-specific-language-for-selecting-rows-from-a-table">Writing a Domain Specific Language for selecting rows from a table</a></p> <p>The simplest solution I can see (to parse, generate and store) is a LISP-style prefix list of tuples, such as:</p> <pre><code>[('and', ('body', '.*to be or not.*'), ('author', (not, '.*shakespeare.*'))), ...] </code></pre> <p>If all you need is basic boolean operators and RegExs, that should be enough.</p> <p><strong>[Edit]</strong> Added example</p>
python|regex
1
1,908,770
10,403,305
Boost.Python: Fill in a passed in buffer in Python
<p>I was wondering whether it's possible to fill in a buffer (with the following conditions) in Python and if so how? </p> <p>I have a buffer in C++ that I need to fill in Python. The Address of the buffer is obtained through the <code>GetAddress</code> method which returns a <strong>void pointer</strong> to the buffer's address. </p> <pre><code>#include &lt;boost/smart_ptr/shared_ptr.hpp&gt; class Foo { public: Foo(const unsigned int length) { m_buffer = boost::shared_ptr&lt; unsigned char &gt;( new unsigned char[ length ] ); } ~Foo(){} void* GetAddress( ) const { // cast for the sake of this question return reinterpret_cast&lt; void* &gt;( m_buffer.get() ); } private: boost::shared_ptr&lt; unsigned char &gt; m_buffer; Foo(); Foo(const Foo&amp;); }; </code></pre> <p>Using Py++ I can generate the Boost.Python wrapper to export the class to Python as follows:</p> <pre><code>#include "boost/python.hpp" #include "foo.hpp" namespace bp = boost::python; BOOST_PYTHON_MODULE(MyWrapper){ { //::Foo typedef bp::class_&lt; Foo, boost::noncopyable &gt; Foo_exposer_t; Foo_exposer_t Foo_exposer = Foo_exposer_t( "Foo", bp::init&lt; unsigned int &gt;(( bp::arg("length") )) ); bp::scope Foo_scope( Foo_exposer ); bp::implicitly_convertible&lt; unsigned int const, Foo &gt;(); { //::Foo::GetAddress typedef void * ( ::Foo::*GetAddress_function_type )( ) const; Foo_exposer.def( "GetAddress" , GetAddress_function_type( &amp;::Foo::GetAddress ) , bp::return_value_policy&lt; bp::return_opaque_pointer &gt;() ); } } } </code></pre> <p>In Python, the output of the GetAddress is a void * to the memory address:</p> <pre><code>&gt;&gt;&gt; import MyWrapper &gt;&gt;&gt; foo = MyWrapper.Foo(100) &gt;&gt;&gt; address = foo.GetAddress() &gt;&gt;&gt; print address &lt;void * object at 0x01E200B0&gt; &gt;&gt;&gt; </code></pre> <p>Problem is Python doesn't let me do anything with the void * address object. If I try to access the second element in buffer, none of the following work:</p> <pre><code>&gt;&gt;&gt; address + 1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for +: 'void *' and 'int' &gt;&gt;&gt; address[1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'void *' object is unsubscriptable &gt;&gt;&gt; </code></pre> <p>Environment: Visual Studio 2008, Boost 1.44, gcc-xml 0.9.0, py++ 1.0.0, pygccxml 1.1.0, Python 2.6.6</p>
<p>Python does not really deal with pointers. You can export one as a opaque cookie, but you can never <strong>do</strong> anything with it (except pass it back to c++). </p> <p>What I would do in your case, is to reverse it. Instead of returning to pointer to python, have a function in c++ that takes a "buffer" from python.</p> <pre><code>namespace bp = boost::python void FillBuffer(Foo&amp; this, bp::list buff) { unsigned char* addr = reinterpret_cast&lt; unsigned char* &gt;( this.GetAddress() ); for(int i = 0; i &lt; bp::len(buff); i++) addr[i] = bp::extract&lt; unsigned char &gt;( buff[i] ); } Foo_exposer.def("FillBuffer", &amp;FillBuffer); </code></pre> <p>Now you can pass a list <strong>in</strong> to fill the buffer. You can create an similar function to stuff a buffer into a list and return it python. You will, of course, want to be much more careful about buffer overruns and such, but this should give you the right idea. </p>
python|buffer|boost-python|void-pointers|py++
2
1,908,771
5,158,447
Matplotlib pyplot show() doesn't work once closed
<p>I have a loop like this</p> <pre><code>#!/usr/bin/env python import matplotlib.pyplot as p for i in xrange(N): # Create my_image here # Display this image p.figure() p.imshow(my_image) p.show() p.close() </code></pre> <p>This works fine when i=0. For the program to continue, I need to close the new figure created by pyplot. For all other loop iterations (i&gt;0), another new figure is not created, a plot is not presented and the program just moves on. Why does closing a figure making pyplot unable to open new one (like MATLAB)?</p> <p>The behavior which I expect is:</p> <ol> <li>Execution stops at <code>p.show()</code></li> <li>When I close the figure, execution continues</li> <li>When <code>p.show()</code> is encountered again, the new image is displayed.</li> <li>Repeat step 2 until no more plot to show</li> </ol>
<p>There might be a better way to animate imshow's, but this should work in a pinch. It's a lightly modified version of an <a href="http://matplotlib.sourceforge.net/examples/animation/animation_blit_tk.html" rel="noreferrer">animation example from the docs</a>.</p> <pre><code># For detailed comments on animation and the techniqes used here, see # the wiki entry http://www.scipy.org/Cookbook/Matplotlib/Animations import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import matplotlib.mlab as mlab import matplotlib.cm as cm import sys import numpy as np import time ax = plt.subplot(111) canvas = ax.figure.canvas delta=0.025 x=y= np.arange(-3.0, 3.0, delta) x,y=np.meshgrid(x, y) z1=mlab.bivariate_normal(x, y, 1.0, 1.0, 0.0, 0.0) z2=mlab.bivariate_normal(x, y, 1.5, 0.5, 1, 1) z=z2-z1 # difference of Gaussians def run(z): fig=plt.gcf() for i in range(10): plt.imshow(z, interpolation='bilinear', cmap=cm.gray, origin='lower', extent=[-3,3,-3,3]) canvas.draw() plt.clf() z**=2 manager = plt.get_current_fig_manager() manager.window.after(100, run, z) plt.show() </code></pre>
python|matplotlib
5
1,908,772
62,503,966
PyQt5 splash screen before main window
<p>I am trying to create a splash screen that shows for 5 seconds before showing the main screen. However, I want the splash screen to be the same window as the main window just with a different image in the middle.</p> <p>I have looked at <a href="https://stackoverflow.com/questions/55842776/how-to-change-ui-in-same-window-using-pyqt5">How to change UI in same window using PyQt5?</a> but it still was not working...</p> <p>I have also tried using the QSplashScreen class but I could not get it to work properly. If there is any confusion, please feel free to comment and I will clarify.</p> <p>Here is my code script:</p> <pre><code># importing libraries from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5 import QtCore, QtGui from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() self.setStyleSheet(&quot;background-color: black;&quot;) self.setWindowTitle(&quot;key&quot;) self.setGeometry(100, 100, 350, 500) self.UiComponents() self.show() def UiComponents(self): lockButton = QPushButton(self) lockButton.setGeometry(60, 200, 100, 70) lockButton.setStyleSheet(&quot;border-radius : 10; border : 1px solid white; background-color : #3A3535&quot;) lockButton.setIcon(QIcon('lock.png')) size = QSize(40, 40) lockButton.setIconSize(size) lockButton.clicked.connect(self.clickme) def clickme(self): print(&quot;pressed&quot;) App = QApplication(sys.argv) window = Window() sys.exit(App.exec()) </code></pre>
<p>Try it:</p> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5 import QtCore, QtGui from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() self.setStyleSheet(&quot;background-color: black;&quot;) self.setWindowTitle(&quot;key&quot;) # self.setGeometry(100, 100, 350, 500) self.resize(350, 500) self.UiComponents() self.show() def UiComponents(self): lockButton = QPushButton(self) lockButton.setGeometry(60, 200, 100, 70) lockButton.setStyleSheet(&quot;border-radius : 10; border : 1px solid white; background-color : #3A3535&quot;) lockButton.setIcon(QIcon('im.png')) # ! 'lock.png' size = QSize(40, 40) lockButton.setIconSize(size) lockButton.clicked.connect(self.clickme) def clickme(self): print(&quot;pressed&quot;) App = QApplication(sys.argv) # +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv import time splash = QSplashScreen() splash.setPixmap(QPixmap('images/splash_.jpg').scaled(366, 568)) splash.show() splash.showMessage('&lt;h1 style=&quot;color:white;&quot;&gt;Welcome to use this PyQt5-SplashScreen&lt;/h1&gt;', Qt.AlignTop | Qt.AlignHCenter, Qt.white) time.sleep(5) # +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ window = Window() splash.finish(window) # +++ sys.exit(App.exec()) </code></pre> <p><a href="https://i.stack.imgur.com/e2nfK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e2nfK.png" alt="enter image description here" /></a></p> <hr /> <blockquote> <p>that just loads the image and then the window. Is it possible to have the image load on the same window (just the plain black screen), and then the main window loads?</p> </blockquote> <pre><code>from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5 import QtCore, QtGui from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() self.setStyleSheet(&quot;background-color: black;&quot;) self.setWindowTitle(&quot;key&quot;) # self.setGeometry(100, 100, 350, 500) self.resize(350, 500) # ++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv self.label = QLabel(self) self.label.resize(350, 500) self.label.setPixmap(QPixmap('images/splash_.jpg').scaled(350, 500)) QTimer.singleShot(5000, self.UiComponents) # ++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ self.show() def UiComponents(self): self.label.hide() # +++ lockButton = QPushButton(self) lockButton.setGeometry(60, 200, 100, 70) lockButton.setStyleSheet(&quot;border-radius : 10; border : 1px solid white; background-color : #3A3535&quot;) lockButton.setIcon(QIcon('im.png')) # ! 'lock.png' size = QSize(40, 40) lockButton.setIconSize(size) lockButton.clicked.connect(self.clickme) lockButton.show() # +++ def clickme(self): print(&quot;pressed&quot;) App = QApplication(sys.argv) window = Window() sys.exit(App.exec()) </code></pre> <p><a href="https://i.stack.imgur.com/7vEzo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7vEzo.png" alt="enter image description here" /></a></p>
python|pyqt5
0
1,908,773
62,597,014
Failed to install pyorc on alpine docker container
<p>Getting compilation error - which is dependent on ORC binaries.</p> <pre><code>In file included from src/_pyorc/_pyorc.cpp:1: src/_pyorc/Reader.h:7:10: fatal error: 'orc/OrcFile.hh' file not found #include &quot;orc/OrcFile.hh&quot; ^~~~~~~~~~~~~~~~ 1 error generated. error: command 'clang' failed with exit status 1 </code></pre> <p>If I compile <strong>apache-orc</strong> separately then too, how can I give reference of it to PyOrc Pip Installation?</p> <p>Anyone has any solution or idea how can we install <strong>pyorc</strong> package inside alpine container.</p> <p>I'm having trouble with alpine image with ubuntu and normal python docker image its working well.</p> <p>Docker Image: <code>FROM python:3.7-alpine</code></p>
<p>I used Docker multi-stage builds:</p> <pre><code># Dockerfile FROM python:3.7.3 WORKDIR /app RUN pip install pyorc -t . FROM python:3.7.3-alpine WORKDIR /app RUN apk add --no-cache --virtual .build-deps g++ musl-dev gcompat COPY --from=0 /app . </code></pre> <p>and it seems working:</p> <pre><code>$ docker build -t test . $ docker run -it --rm test python Python 3.7.3 (default, Jun 27 2019, 22:53:21) [GCC 8.3.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import pyorc &gt;&gt;&gt; &gt;&gt;&gt; with open(&quot;./new_data.orc&quot;, &quot;wb&quot;) as data: ... with pyorc.Writer(data, &quot;struct&lt;col0:int,col1:string&gt;&quot;) as writer: ... writer.write((1, &quot;ORC from Python&quot;)) ... &gt;&gt;&gt; from pathlib import Path &gt;&gt;&gt; Path(&quot;./new_data.orc&quot;).read_bytes() b'ORC\x1d\x00\x00\n\x0c\n\x04\x00\x00\x.....' </code></pre>
python|docker|compiler-errors|alpine-linux|orc
2
1,908,774
61,812,634
Matlab - How to illustrate the percentage growth by background colour ? [of a timeseries chart]
<p>I want to plot a timeseries chart:</p> <p>Sample data:</p> <pre><code>datetime = pd.date_range(start = '01/03/2019', periods = 60) #60 days = 2 months data = [2000] for i in range (29): data.append(data[-1]*1.05) #first 30 days - growth 5% for i in range(30): data.append(data[-1]*1.15) #last 30 days - growth 15% plt.plot(datetime, data) plt.show() </code></pre> <p>We got the figure below: <a href="https://i.stack.imgur.com/E2LdV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E2LdV.png" alt="enter image description here"></a></p> <p>So I want to have a background colour cutting in two 2 regions (2 rectangles) </p> <ul> <li>The first one covers region with 5% growth</li> <li>The second region covers region with 15% growth</li> </ul> <p>I tried to do it but the difficulty is that <code>date</code> is converted into delta time by <code>matlab</code> so I could not cut it by input the day I want to cut</p> <pre><code>plt.xlim() (737059.05, 737123.95) #delta time plt.ylim() (-25153.66313846143, 572226.92590769) </code></pre> <p>Please help me in an easy way so in future I could cut in any area like 5 days, 10 days , 15 days depending on the data.</p>
<p>You can work with <code>DateTime</code> objects, as long as you are not trying to mix and match the internal representation used by <code>matplotlib</code> (the one you see when you do <code>plt.xlim()</code>) and <code>DateTime</code> values.</p> <pre><code>d = pd.date_range(start = '01/03/2019', periods = 60) #60 days = 2 months data = [2000] for i in range (29): data.append(data[-1]*1.05) #first 30 days - growth 5% for i in range(30): data.append(data[-1]*1.15) #last 30 days - growth 15% cutoff = 30 cutoff_date = d[0]+cutoff*d.freq plt.figure() plt.plot(d, data) plt.axvline(cutoff_date,ls='--',color='k') plt.axvspan(xmin=d[0],xmax=cutoff_date, facecolor='r', alpha=.5) plt.axvspan(xmin=cutoff_date,xmax=d[-1], facecolor='g', alpha=.5) plt.gcf().autofmt_xdate() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/t400i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t400i.png" alt="enter image description here"></a></p>
python|pandas|matplotlib
0
1,908,775
60,620,691
How can I export results from a Pyomo variable to a Pandas dataframe and excel?
<p>I have a few Pyomo variables in a model, some with three indices. For the purpose of explaining, one of my variables is </p> <pre><code>model.E_grid = Var(model.i, model.m, model.p, within = NonNegativeReals) </code></pre> <p>and the three indices are i, m and p. After running the model, I would like to see the final values of E_grid with respect to each i, m and p in an pandas dataframe (which will then allow me to export it to excel). So for example, something like <em>[i1, m1, p1, 21.00], [i1, m1, p2, 22.00]</em>, and so on. I have already seen the "block" method which tries to export all the variables in one go (e.g. <a href="https://or.stackexchange.com/questions/2708/pyomo-looping-over-a-variable-method">https://or.stackexchange.com/questions/2708/pyomo-looping-over-a-variable-method</a>) but it doesn't work for me because some of the variables have just 1 index. Any help with this would be much appreciated!</p> <p>Edit: this is specifically what I have tried</p> <pre><code>results_df = pd.DataFrame() for v in model.component_objects(model.E_grid, active=True): for i, m, p in v: results_df.at[i,m,p, v.name] = value(v[i,m,p]) print(results_df) </code></pre> <p>But I get the error <em>ValueError: Not enough indexers for scalar access (setting)!</em></p>
<p>The first argument to <code>component_objects()</code> should be a component type (eg. <code>Var</code>), not a component (ie <code>model.E_grid</code>). You can use <code>.items()</code> to iterate over an <code>IndexedComponent</code>.</p> <p>Secondly, the error you're seeing is due to the way of indexing the dataframe and setting the value on the fly. If you're just wanting to build a dataframe from the variable values it may be much simpler to just use dict comprehension and then one of <code>pandas</code>' dataframe constructors:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from pyomo.core import ConcreteModel, Set, NonNegativeReals, Var, value model = ConcreteModel() model.i = Set(initialize=[1, 2, 3]) model.m = Set(initialize=[4, 5, 6]) model.p = Set(initialize=[7, 8, 9]) model.E_grid = Var(model.i, model.m, model.p, within=NonNegativeReals, initialize=1) E_grid_data = {(i, m, p, v.name): value(v) for (i, m, p), v in model.E_grid.items()} df = pd.DataFrame.from_dict(E_grid_data, orient="index", columns=["variable value"]) print(df) # variable value # (1, 4, 7, E_grid[1,4,7]) 1 # (1, 4, 8, E_grid[1,4,8]) 1 # (1, 4, 9, E_grid[1,4,9]) 1 # (1, 5, 7, E_grid[1,5,7]) 1 # (1, 5, 8, E_grid[1,5,8]) 1 # (1, 5, 9, E_grid[1,5,9]) 1 </code></pre> <p>You can now post-process the dataframe if you want to split out the index into a multiindex.</p>
python|pandas|dataframe|pyomo
1
1,908,776
71,386,879
Python recursive function is not using argument correctly
<p>Just can not wrap my head why this code would not work:</p> <pre class="lang-py prettyprint-override"><code>def list_flatten(a_list): for item in a_list: if isinstance(item, list): list_flatten(item) else: yield item print(list(list_flatten([[&quot;A&quot;]]))) print(list(list_flatten([&quot;A&quot;, [&quot;B&quot;], &quot;C&quot;]))) </code></pre> <p>Expecting:</p> <ul> <li>[&quot;A&quot;] and</li> <li>[&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]</li> </ul> <p>Getting</p> <ul> <li>[] and</li> <li>[&quot;A&quot;, &quot;C&quot;]</li> </ul> <p>Side note: Do not want to use chain.from_iterable, because it will breakdown the strings too, like [&quot;123&quot;] might end up [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;]</p>
<p>You're not doing anything with the result of your recursive call.</p> <p>Change</p> <pre><code>list_flatten(item) </code></pre> <p>to</p> <pre><code>yield from list_flatten(item) </code></pre> <p>and you should be good to go. (See <a href="https://docs.python.org/3/reference/expressions.html#yieldexpr" rel="nofollow noreferrer">the docs</a> for <code>yield from</code>.)</p>
python|python-3.x
3
1,908,777
64,552,383
I have just started learning super basic Python this week. Look at my basic code for entry ticket in a park
<p>Ticket price depends on age. I am getting an error &quot;invalid literal for value with base 10&quot; in the line</p> <pre><code>age=int(age) </code></pre> <p>What does this error mean and how can I solve it? please fix indentation error (if any)</p> <pre><code>name=&quot;\t\n\n WHAT IS YOUR NAME?\t\n\t\t\t&quot; input(name) name=str(name) gender = &quot;\nWhat is your GENDER (M/F) \t\n\t\t\t&quot; input(gender) gender=str(gender) age = &quot;\t\n\tWhat is your age\t\n\t\t\t&quot; input(age) age= int(age) if gender == 'm ': gd=&quot;Mr. &quot; elif gender == 'f': gd=&quot;Ms. &quot; else : gd = &quot;_&quot; price = ['free for kid $0' , '$ 10' , '$15'] if age&lt;=3: print(&quot;Hello &quot; + gd + name.title() + &quot; your Ticket fee is &quot; + price[0]) elif age &lt;= 12: print(&quot;Hello &quot;+gd+ name.title() + &quot; your Ticket fee is &quot; + price[1]) else: print(&quot;Hello &quot;+gd+ name.title() + &quot; your Ticket fee is &quot; + price[2]) </code></pre>
<p>Your code is wrong from the basics. input is the keyword that takes the input from the user as well as shows the input message to the user. You need to store the value to a variable.</p> <p>So your code should be like that,</p> <pre><code>name_prompet = &quot;\t\n\n WHAT IS YOUR NAME?\t\n\t\t\t&quot; name = input(name_prompet) </code></pre> <p>same it should be with the age,</p> <pre><code>age_prompet = &quot;\t\n\tWhat is your age\t\n\t\t\t&quot; age = input(age) </code></pre> <p>SO at age = int(age) technically you are trying to convert a string into int that's why it's an error.</p> <p>Tell me if you need anything else.</p>
python
0
1,908,778
64,355,923
Is there a pythonic way of referring to the current object (self-reference) we are declaring with (some) Pythons built-in types?
<p>With (some) Pythons built-in types, is it possible to refer to the object we are declaring ? By &quot;(some) built-in types&quot; I think about, for example, sequence types, mapping types or set types, obviously not numeric types.</p> <p>I mean, without creating a class myself and adding this functionality (without creating a subclass).</p> <p>So, something like the <code>this</code> keyword as used in the examples below.</p> <p>For example, for the &quot;dict&quot; Python built-in type, something like this:</p> <pre><code>a_dictionary = { &quot;key_1&quot;: &quot;value_1&quot;, &quot;key_2&quot;: &quot;value_2&quot;, &quot;key_3&quot;: this[&quot;key_1&quot;] + &quot;_&quot; + this[&quot;key_2&quot;] # == &quot;value_1_value_2&quot; } </code></pre> <p>or even:</p> <pre><code>a_dictionary = { &quot;sub_dict_1&quot;: { &quot;key_1&quot;: &quot;value_1_1&quot;, &quot;key_2&quot;: &quot;value_1_2&quot;, &quot;key_3&quot;: this[&quot;key_1&quot;] + &quot;_&quot; + this[&quot;key_2&quot;] # == &quot;value_1_1_value_1_2&quot; }, &quot;sub_dict_2&quot;: { &quot;key_1&quot;: &quot;value_2_1&quot;, &quot;key_2&quot;: &quot;value_2_2&quot;, &quot;key_3&quot;: this[&quot;key_1&quot;] + &quot;_&quot; + this[&quot;key_2&quot;] # == &quot;value_2_1_value_2_2&quot; } } </code></pre> <p>I've read :</p> <p><a href="https://stackoverflow.com/questions/42101911/when-doing-function-chaining-in-python-is-there-a-way-to-refer-to-the-current">When doing function chaining in python, is there a way to refer to the &quot;current&quot; object?</a></p> <p><a href="https://stackoverflow.com/questions/3738381/what-do-i-do-when-i-need-a-self-referential-dictionary">What do I do when I need a self referential dictionary?</a></p> <p><a href="https://stackoverflow.com/questions/38254969/reference-a-dictionary-within-itself">Reference a dictionary within itself</a></p> <p><a href="https://stackoverflow.com/questions/3877947/self-referencing-classes-in-python">Self-referencing classes in python?</a></p> <p><a href="https://stackoverflow.com/questions/16821879/is-there-a-way-to-refer-to-the-current-function-in-python">Is there a way to refer to the current function in python?</a></p> <p><a href="https://stackoverflow.com/questions/21112814/is-it-possible-to-access-current-object-while-doing-list-dict-comprehension-in-p">Is it possible to access current object while doing list/dict comprehension in Python?</a></p> <p>and some others, but it doesn't match up the requirements described at the begining of my question.</p> <p>Thanks a lot for your help!</p>
<p>Python provides no way to refer to an object under construction by a literal or a display*. You can (ab)use the assignment expression in Python 3.8 or later to simulate this:</p> <pre><code>a_dictionary = { &quot;key_1&quot;: (x := &quot;value_1&quot;), &quot;key_2&quot;: (y := &quot;value_2&quot;), &quot;key_3&quot;: x + &quot;_&quot; + y } </code></pre> <p>It requires some planning ahead, as you are not referring to a key value directly, rather a pre-defined variable. Notice that <code>x</code> and <code>y</code> remain in scope after the assignment to <code>a_dictionary</code>, so this is just a questionable equivalent of</p> <pre><code>x = &quot;value_1&quot; y = &quot;value_2&quot; a_dictionary = { &quot;key_1&quot;: x, &quot;key_2&quot;: y, &quot;key_3&quot;: x + &quot;_&quot; + y } </code></pre> <p>A custom class would really be more appropriate:</p> <pre><code>class Thing: def __init__(self, v1, v2): self.key_1 = v1 self.key_2 = v2 self.key_3 = v1 + &quot;_&quot; + v2 a_thing = Thing(&quot;value_1&quot;, &quot;value_2&quot;) </code></pre> <hr /> <ul> <li>A display is a construct like a literal, but could contain non-literal references. For example, list displays include <code>[1, x, y]</code> and <code>[int(x) for x in foo]</code>.</li> </ul>
python
8
1,908,779
64,449,274
How do i make a user profile so that i will input the name, mail etc. and then it saves, so i can login
<pre><code>class User: def __init__(self, username, email, date_of_birth, password): self.username = username self.email = email self.date_of_birth = date_of_birth self.password = password @staticmethod def login_or_register(): userinput = input(&quot;login or register&quot;) def register(self): pass def login(self, login_reg): self.login_reg = login_reg </code></pre> <p>How do i make a user profile so that i will input the name, mail etc. and then it saves so i can login</p>
<p>heres a really simple way to do it:</p> <pre><code>import hashlib db = {} hash = lambda x: hashlib.md5(x.encode()).hexdigest() def register(user, password, mail): db[user] = {&quot;password&quot;: hash(password), &quot;mail&quot;: mail} def login(user, password): if db[user][&quot;password&quot;] == hash(password): print(&quot;success!&quot;) else: print(&quot;fail&quot;) register(&quot;ironkey&quot;, &quot;password123&quot;, &quot;example@example.com&quot;) login(&quot;ironkey&quot;, &quot;password&quot;) login(&quot;ironkey&quot;, &quot;password123&quot;) # get credentials for the user ironkey print(db[&quot;ironkey&quot;]) </code></pre> <pre><code>fail success! {'password': '482c811da5d5b4bc6d497ffa98491e38', 'mail': 'example@example.com'} </code></pre>
python|oop
0
1,908,780
63,610,094
Could not install ChatterBot. Raises errors
<p>i tried to install chatterbot but i got the following error I tried downgrading to chatterbot==1.0.5 still it raises errors Gives errors while Installing dependencies</p> <p>Please help me No Silly answers Thank you in Advance! AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</p> <p>Junk As to remove problems while posting this XD</p> <pre><code>ERROR: Command errored out with exit status 1: command: 'c:\users\anubhab\appdata\local\programs\python\python38-32\python.exe' 'c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\Anubhab\AppData\Local\Temp\pip-build-env-23bg67bo\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools 'wheel&gt;0.32.0,&lt;0.33.0' Cython 'cymem&gt;=2.0.2,&lt;2.1.0' 'preshed&gt;=2.0.1,&lt;2.1.0' 'murmurhash&gt;=0.28.0,&lt;1.1.0' 'thinc&gt;=7.0.8,&lt;7.1.0' cwd: None Complete output (217 lines): Collecting setuptools Using cached https://files.pythonhosted.org/packages/c3/a9/5dc32465951cf4812e9e93b4ad2d314893c2fa6d5f66ce5c057af6e76d85/setuptools-49.6.0-py3-none-any.whl Collecting wheel&lt;0.33.0,&gt;0.32.0 Using cached https://files.pythonhosted.org/packages/ff/47/1dfa4795e24fd6f93d5d58602dd716c3f101cfd5a77cd9acbe519b44a0a9/wheel-0.32.3-py2.py3-none-any.whl Collecting Cython Using cached https://files.pythonhosted.org/packages/17/60/d7c00073e239e9650e38a17f03beca3480b538bd7a6921d7042cfb6bda43/Cython-0.29.21-cp38-cp38-win32.whl Collecting cymem&lt;2.1.0,&gt;=2.0.2 Using cached https://files.pythonhosted.org/packages/ce/8d/d095bbb109a004351c85c83bc853782fc27692693b305dd7b170c36a1262/cymem-2.0.3.tar.gz Collecting preshed&lt;2.1.0,&gt;=2.0.1 Using cached https://files.pythonhosted.org/packages/0b/14/c9aa735cb9c131545fc9e23031baccb87041ac9215b3d75f99e3cf18f6a3/preshed-2.0.1.tar.gz Collecting murmurhash&lt;1.1.0,&gt;=0.28.0 Using cached https://files.pythonhosted.org/packages/22/e9/411be1845f1ac07ae3bc40a4b19ba401819baed4fa63b4f5ef28b2300eb4/murmurhash-1.0.2.tar.gz Collecting thinc&lt;7.1.0,&gt;=7.0.8 Using cached https://files.pythonhosted.org/packages/92/39/ea2a3d5b87fd52fc865fd1ceb7b91dca1f85e227d53e7a086d260f6bcb93/thinc-7.0.8.tar.gz ERROR: Command errored out with exit status 1: command: 'c:\users\anubhab\appdata\local\programs\python\python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '&quot;'&quot;'C:\\Users\\Anubhab\\AppData\\Local\\Temp\\pip-install-rwdl_zm9\\thinc\\setup.py'&quot;'&quot;'; __file__='&quot;'&quot;'C:\\Users\\Anubhab\\AppData\\Local\\Temp\\pip-install-rwdl_zm9\\thinc\\setup.py'&quot;'&quot;';f=getattr(tokenize, '&quot;'&quot;'open'&quot;'&quot;', open)(__file__);code=f.read().replace('&quot;'&quot;'\r\n'&quot;'&quot;', '&quot;'&quot;'\n'&quot;'&quot;');f.close();exec(compile(code, __file__, '&quot;'&quot;'exec'&quot;'&quot;'))' egg_info --egg-base pip-egg-info cwd: C:\Users\Anubhab\AppData\Local\Temp\pip-install-rwdl_zm9\thinc\ Complete output (195 lines): Processing numpy/random\_bounded_integers.pxd.in Processing numpy/random\bit_generator.pyx Processing numpy/random\mtrand.pyx Processing numpy/random\_bounded_integers.pyx.in Processing numpy/random\_common.pyx Processing numpy/random\_generator.pyx Processing numpy/random\_mt19937.pyx Processing numpy/random\_pcg64.pyx Processing numpy/random\_philox.pyx Processing numpy/random\_sfc64.pyx Cythonizing sources Could not locate executable g77 Could not locate executable f77 Could not locate executable ifort Could not locate executable ifl Could not locate executable f90 Could not locate executable DF Could not locate executable efl Could not locate executable gfortran Could not locate executable f95 Could not locate executable g95 Could not locate executable efort Could not locate executable efc Could not locate executable flang don't know how to compile Fortran code on platform 'nt' non-existing path in 'numpy\\distutils': 'site.cfg' Running from numpy source directory. C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\setup.py:470: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates run_build = parse_setuppy_commands() C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\system_info.py:1914: UserWarning: Optimized (vendor) Blas libraries are not found. Falls back to netlib Blas library which has worse performance. A better performance should be easily gained by switching Blas library. if self._calc_info(blas): C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\system_info.py:1914: UserWarning: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. if self._calc_info(blas): C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\system_info.py:1914: UserWarning: Blas (http://www.netlib.org/blas/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [blas_src]) or by setting the BLAS_SRC environment variable. if self._calc_info(blas): C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\system_info.py:1748: UserWarning: Lapack (http://www.netlib.org/lapack/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [lapack]) or by setting the LAPACK environment variable. return getattr(self, '_calc_info_{}'.format(name))() C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\system_info.py:1748: UserWarning: Lapack (http://www.netlib.org/lapack/) sources not found. Directories to search for the sources can be specified in the numpy/distutils/site.cfg file (section [lapack_src]) or by setting the LAPACK_SRC environment variable. return getattr(self, '_calc_info_{}'.format(name))() c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros' warnings.warn(msg) Traceback (most recent call last): File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py&quot;, line 489, in _find_latest_available_vc_ver return self.find_available_vc_vers()[-1] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\core.py&quot;, line 148, in setup dist.run_commands() File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\dist.py&quot;, line 966, in run_commands self.run_command(cmd) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\dist.py&quot;, line 985, in run_command cmd_obj.run() File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\bdist_egg.py&quot;, line 163, in run self.run_command(&quot;egg_info&quot;) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\cmd.py&quot;, line 313, in run_command self.distribution.run_command(command) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\dist.py&quot;, line 985, in run_command cmd_obj.run() File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\command\egg_info.py&quot;, line 24, in run File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\cmd.py&quot;, line 313, in run_command self.distribution.run_command(command) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\dist.py&quot;, line 985, in run_command cmd_obj.run() File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\command\build_src.py&quot;, line 144, in run File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\command\build_src.py&quot;, line 155, in build_sources File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\command\build_src.py&quot;, line 288, in build_library_sources File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\command\build_src.py&quot;, line 378, in generate_sources File &quot;numpy\core\setup.py&quot;, line 650, in get_mathlib_info File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\command\config.py&quot;, line 241, in try_link self._check_compiler() File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\command\config.py&quot;, line 52, in _check_compiler File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\_msvccompiler.py&quot;, line 253, in initialize vc_env = _get_vc_env(plat_spec) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py&quot;, line 185, in msvc14_get_vc_env return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env() File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py&quot;, line 843, in __init__ self.si = SystemInfo(self.ri, vc_ver) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py&quot;, line 485, in __init__ self.vc_ver = vc_ver or self._find_latest_available_vc_ver() File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\msvc.py&quot;, line 492, in _find_latest_available_vc_ver raise distutils.errors.DistutilsPlatformError(err) distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with &quot;Microsoft Visual C++ Build Tools&quot;: https://visualstudio.microsoft.com/downloads/ During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 154, in save_modules yield saved File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 195, in setup_context yield File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 250, in run_setup _execfile(setup_script, ns) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 45, in _execfile exec(code, globals, locals) File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\setup.py&quot;, line 499, in &lt;module&gt; File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\setup.py&quot;, line 491, in setup_package File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\core.py&quot;, line 169, in setup File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\__init__.py&quot;, line 145, in setup return distutils.core.setup(**attrs) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\core.py&quot;, line 163, in setup raise SystemExit(&quot;error: &quot; + str(msg)) SystemExit: error: Microsoft Visual C++ 14.0 is required. Get it with &quot;Microsoft Visual C++ Build Tools&quot;: https://visualstudio.microsoft.com/downloads/ During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py&quot;, line 1144, in run_setup run_setup(setup_script, args) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 253, in run_setup raise File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\contextlib.py&quot;, line 131, in __exit__ self.gen.throw(type, value, traceback) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 195, in setup_context yield File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\contextlib.py&quot;, line 131, in __exit__ self.gen.throw(type, value, traceback) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 166, in save_modules saved_exc.resume() File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 141, in resume six.reraise(type, exc, self._tb) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\_vendor\six.py&quot;, line 685, in reraise raise value.with_traceback(tb) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 154, in save_modules yield saved File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 195, in setup_context yield File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 250, in run_setup _execfile(setup_script, ns) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\sandbox.py&quot;, line 45, in _execfile exec(code, globals, locals) File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\setup.py&quot;, line 499, in &lt;module&gt; File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\setup.py&quot;, line 491, in setup_package File &quot;C:\Users\Anubhab\AppData\Local\Temp\easy_install-b61r_j0_\numpy-1.19.1\numpy\distutils\core.py&quot;, line 169, in setup File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\__init__.py&quot;, line 145, in setup return distutils.core.setup(**attrs) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\distutils\core.py&quot;, line 163, in setup raise SystemExit(&quot;error: &quot; + str(msg)) SystemExit: error: Microsoft Visual C++ 14.0 is required. Get it with &quot;Microsoft Visual C++ Build Tools&quot;: https://visualstudio.microsoft.com/downloads/ During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt; File &quot;C:\Users\Anubhab\AppData\Local\Temp\pip-install-rwdl_zm9\thinc\setup.py&quot;, line 261, in &lt;module&gt; setup_package() File &quot;C:\Users\Anubhab\AppData\Local\Temp\pip-install-rwdl_zm9\thinc\setup.py&quot;, line 201, in setup_package setup( File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\__init__.py&quot;, line 144, in setup _install_setup_requires(attrs) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\__init__.py&quot;, line 139, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\dist.py&quot;, line 716, in fetch_build_eggs resolved_dists = pkg_resources.working_set.resolve( File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources\__init__.py&quot;, line 780, in resolve dist = best[req.key] = env.best_match( File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources\__init__.py&quot;, line 1065, in best_match return self.obtain(req, installer) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\pkg_resources\__init__.py&quot;, line 1077, in obtain return installer(requirement) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\dist.py&quot;, line 786, in fetch_build_egg return cmd.easy_install(req) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py&quot;, line 679, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py&quot;, line 705, in install_item dists = self.install_eggs(spec, download, tmpdir) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py&quot;, line 890, in install_eggs return self.build_and_install(setup_script, setup_base) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py&quot;, line 1158, in build_and_install self.run_setup(setup_script, setup_base, args) File &quot;c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\easy_install.py&quot;, line 1146, in run_setup raise DistutilsError(&quot;Setup script exited with %s&quot; % (v.args[0],)) distutils.errors.DistutilsError: Setup script exited with error: Microsoft Visual C++ 14.0 is required. Get it with &quot;Microsoft Visual C++ Build Tools&quot;: https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. WARNING: You are using pip version 19.2.3, however version 20.2.2 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\anubhab\appdata\local\programs\python\python38-32\python.exe' 'c:\users\anubhab\appdata\local\programs\python\python38-32\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\Anubhab\AppData\Local\Temp\pip-build-env-23bg67bo\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools 'wheel&gt;0.32.0,&lt;0.33.0' Cython 'cymem&gt;=2.0.2,&lt;2.1.0' 'preshed&gt;=2.0.1,&lt;2.1.0' 'murmurhash&gt;=0.28.0,&lt;1.1.0' 'thinc&gt;=7.0.8,&lt;7.1.0' Check the logs for full command output. </code></pre>
<p>did you try to install Microsoft Visual C++ 14.0?</p> <p>SystemExit: error: Microsoft Visual C++ 14.0 is required. Get it with &quot;Microsoft Visual C++ Build Tools&quot;: <a href="https://visualstudio.microsoft.com/downloads/" rel="nofollow noreferrer">https://visualstudio.microsoft.com/downloads/</a></p>
python|python-3.x|pip|blas|chatterbot
1
1,908,781
56,588,156
Python .format() added to an url but throws a KeyError
<p>I want to add a variable with .format() to an url but python throws a KeyError.</p> <p>The error I get:</p> <pre class="lang-py prettyprint-override"><code>KeyError: '"page"' </code></pre> <p>I have added .format() and {} to the url see the url below. At the end of url .format() is added.</p> <pre class="lang-py prettyprint-override"><code>url with .format() / {"page":{}}'.format(valuetest) url = 'https://nl.soccerway.com/a/block_competition_matches_summary?block_id=page_competition_1_block_competition_matches_summary_5&amp;callback_params={"page":"-1","block_service_id":"competition_summary_block_competitionmatchessummary","round_id":"50855","outgroup":"","view":"2","competition_id":"34"}&amp;action=changePage&amp;params={"page":{}}'.format(valuetest) original url: url = 'https://nl.soccerway.com/a/block_competition_matches_summary?block_id=page_competition_1_block_competition_matches_summary_5&amp;callback_params={"page":"-1","block_service_id":"competition_summary_block_competitionmatchessummary","round_id":"50855","outgroup":"","view":"2","competition_id":"34"}&amp;action=changePage&amp;params={"page":1}' </code></pre> <p>Below is what I want in a simple example:</p> <pre class="lang-py prettyprint-override"><code>valuetest = '1' urltest = 'https://www.testing.com{}'.format(valuetest) print(urltest) </code></pre> <p>result: <a href="https://www.testing.com1" rel="nofollow noreferrer">https://www.testing.com1</a></p> <p>How can I create the url so I can add a variable to the url?</p>
<p>You need to <em>escape</em> any braces that are not part of a replacement field.</p> <pre><code>url = 'https://nl.soccerway.com/a/block_competition_matches_summary?block_id=page_competition_1_block_competition_matches_summary_5&amp;callback_params={{"page":"-1","block_service_id":"competition_summary_block_competitionmatchessummary","round_id":"50855","outgroup":"","view":"2","competition_id":"34"}}&amp;action=changePage&amp;params={{"page":{}}}' </code></pre> <hr> <p><a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow noreferrer">https://docs.python.org/3/library/string.html#format-string-syntax</a></p>
python
1
1,908,782
69,775,315
Minimum moves of a knight with bishop
<p>The question is minimum moves of a knight from point A to B in an n*n chessboard(knights can move two steps in the horizontal direction and one step in the vertical direction or two in vertical one in horizontal). There is a bishop on the chess board that travels diagonally and the knight cannot travel to positions threatened by the bishop unless the bishop is dead or the position is point B. The knight can choose to kill the bishop (if it is in a position that it can travel to) and free all the previously threatened positions.</p> <p>I got this question in an online assessment that I took, but only got 10 out of 15 test cases correct. I figured I might need to add a boolean value to the tuples in the queue of whether the bishop is alive in the latest step but it was too late.</p> <p>How can I modify this?</p> <pre><code>from collections import deque import math n = 5 startRow = 0 startCol = 0 endRow = 4 endCol = 3 bishopRow = 3 bishopCol = 0 from collections import deque import math # # Complete the 'moves' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER n # 2. INTEGER startRow # 3. INTEGER startCol # 4. INTEGER endRow # 5. INTEGER endCol # 6. INTEGER bishopRow # 7. INTEGER bishopCol # def isBishopAlive(n, bishopRow, bishopCol): if bishopRow &lt; n and bishopCol &lt; n: return True else: return False def moves(n, startRow, startCol, endRow, endCol, bishopRow, bishopCol): # Write your code here x, y = abs(endRow), abs(endCol) res = 0 moves = ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1)) visited = [] queue = deque() queue.append((startRow, startCol, 0)) while queue: i, j, steps = queue.popleft() if i == x and j == y: return res + steps for di, dj in moves: cr = i + di cc = j + dj if isBishopAlive(n, bishopRow, bishopCol) == True: if abs(cr-bishopRow) == abs(cc-bishopCol): if cc != y and cr != x: continue if (cr == bishopRow) and (cc == bishopCol): bishopRow, bishopCol = math.inf, math.inf if abs(cr) &gt; n-1 or abs(cc) &gt; n-1: continue if (cr, cc) in visited: continue if isBishopAlive(n, bishopRow, bishopCol) == True: bishop = True else: bishop = False if ((x-i) * di) &gt; 0 or ((y-j) * dj) &gt; 0: queue.append([cr, cc, steps+1]) visited.append((cr, cc)) return -1 </code></pre>
<p>There are the following issues in your code:</p> <ul> <li><p>The bishop can never be captured, because when that square is reached with <code>cr</code> and <code>cc</code>, then first the <code>if abs(cr-bishopRow) == abs(cc-bishopCol)</code> condition will be evaluated -- and found true -- followed by a <code>continue</code>.</p> </li> <li><p>When the bishop would have been captured, your code never puts it back when looking at other paths that did not capture the bishop. Instead, the items on the queue should include whether or not that state was achieved by capturing the bishop or not.</p> </li> <li><p>Items in the <code>visited</code> list do not indicate whether the visit happened when the bishop was still alive or not. Yet this is important, because if you visited a square first with the bishop still alive, but then visit it again when the bishop is captured, that second visit could lead to a better solution. So include the alive-status in the tuples when marking a square as visited.</p> </li> <li><p>The code allows negative coordinates for <code>cr</code> or <code>cc</code> to be pushed unto the queue. This should be avoided.</p> </li> <li><p>This exclusion of moves that move away from the target is too optimistic:</p> <pre><code>if ((x-i) * di) &gt; 0 or ((y-j) * dj) &gt; 0 </code></pre> <p>Take for instance this board, where &quot;N&quot; is the knight, &quot;B&quot; the bishop and &quot;e&quot; the end square:</p> <pre class="lang-none prettyprint-override"><code>┌───┬───┬───┬───┬───┐ │ │ │ │ │ │ ├───┼───┼───┼───┼───┤ │ │ │ │ │ B │ ├───┼───┼───┼───┼───┤ │ │ │ N │ │ │ ├───┼───┼───┼───┼───┤ │ │ │ │ │ │ ├───┼───┼───┼───┼───┤ │ │ │ │ │ e │ └───┴───┴───┴───┴───┘ </code></pre> <p>The bishop must be taken on the first move, and then the knight must move away to the top row for the optimal solution.</p> <p>I would suggest to just remove this condition or else make sure it is not too strict and will never exclude an optimal path.</p> </li> </ul> <p>Not a problem, but:</p> <ul> <li><code>res</code> is never assigned another value than 0: this variable is not needed</li> <li><code>bishop</code> is only <em>set</em>, but never <em>read</em>: this variable (and the <code>if...else</code> block around it) is not needed</li> <li><code>visited</code> should better be a set than a list, so to have a better time complexity.</li> <li><code>endRow</code> and <code>endCol</code> will never be negative, so it is not useful to copy their absolute values in <code>x</code> and <code>y</code>. Just use the original parameter variables.</li> <li>As you mark squares as visited at the moment you put them on the queue, you should also do the same with the start square before entering the loop.</li> <li>There is a nested <code>if</code> that leads to a <code>continue</code>. These <code>if</code> conditions can be combined into one <code>if</code> condition using <code>and</code></li> <li>Two <code>if</code> conditions at the same level that both lead to <code>continue</code> can be combined into one <code>if</code> condition using <code>or</code></li> <li>The parentheses around <code>(cr == bishopRow)</code> are not necessary.</li> <li>You could save some execution time by checking the target was reached when performing a move, instead of waiting until that move is popped from the queue. This just means you have to have an initial check to see whether the starting position is equal to the end position, but it is worth it.</li> </ul> <p>Here is a corrected version:</p> <pre><code>def moves(n, startRow, startCol, endRow, endCol, bishopRow, bishopCol): if startRow == endRow and startCol == endCol: # Deal with trivial case return 0 moves = ((2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1)) queue = deque() queue.append((startRow, startCol, True, 0)) # Include that bishop is alive # Let visited be a set. Mark start as visited and include alive-status visited = set([(startRow, startCol, True)]) while queue: i, j, alive, steps = queue.popleft() for di, dj in moves: cr = i + di cc = j + dj if cr == endRow and cc == endCol: # When found, don't bother about queuing it return steps + 1 # No need for a res variable # Update alive-state, just for current path stillalive = alive and (cr != bishopRow or cc != bishopCol) # Neither cr/cc should be negative if 0 &lt;= cr &lt; n and 0 &lt;= cc &lt; n and (cr, cc, stillalive) not in visited and ( not stillalive or abs(cr - bishopRow) != abs(cc - bishopCol)): queue.append((cr, cc, stillalive, steps + 1)) # Append alive-status too visited.add((cr, cc, stillalive)) # Visited should depend on alive return -1 </code></pre>
python|queue|depth-first-search
3
1,908,783
60,977,585
receiving comma separated bytes from python sockets udp
<p>I am working with python 3.7.4 trying to use data I am receiving via udp using python sockets. I need the data in an array. Everything I have tried either gives error or changes the data making it useless.</p> <pre><code>import socket import select sockets = [] for port in range(5201,5202): server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_socket.bind(('127.0.0.1', port)) sockets.append(server_socket) empty = [] while True: readable, writable, exceptional = select.select(sockets, empty, empty) for s in readable: (client_data, client_address) = s.recvfrom(1024) rport=(s.getsockname()[1]) print (client_data) for s in sockets: s.close() </code></pre> <p>The output is:</p> <p>b'[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]'</p> <p>I am trying to get this data into an array so I can select individual bytes like client_data[2]. </p>
<p>That format is basically JSON:</p> <pre><code>&gt;&gt;&gt; s = b'[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]' &gt;&gt;&gt; import json &gt;&gt;&gt; json.loads(s) [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255] &gt;&gt;&gt; a = json.loads(s) &gt;&gt;&gt; a[0] 255 &gt;&gt;&gt; len(a) 128 </code></pre>
python|arrays|sockets|udp
1
1,908,784
66,097,814
merge two or more lists get unique combinations with same length and statistics
<pre><code>l1=[1,1,2,3,5,6,6] l2 = [2,2,1,1,5,6] </code></pre> <p>then return one of the possibility [(1,2),(1,1),(2,2),(3,2),(5,1),(6,5),(6,6) ] so same statistics of l1 and l2 used with unique combinations. Number of lists can be 2 or more</p> <p>length of l1 and l2 is 6 length of final result also 6</p> <p>i thought of using itertools module , but maintaining same statistics in each list is difficult.</p>
<pre><code>import itertools l1 = [1,1,2,3,5,6] l2 = [2,2,1,1,5,6] found = {} for perm in itertools.permutations(l1, len(l1)): pairs = set(zip(perm, l2)) if len(pairs) == len(l1): found = pairs break print(found if found else &quot;not found&quot;) </code></pre>
python-3.x|itertools
0
1,908,785
65,940,759
Importing package in another package's module?
<p>I am building a package (and then going to upload it on pypi). I have 3 modules in this package. These packages have a few dependencies like numpy, cv2, and more.</p> <p>So, I mentioned my dependencies in the setup.py file.</p> <pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*- import setuptools setuptools.setup( name='StyleTransferTensorFlow', url='https://github.com/LordHarsh/Neural_Style_Transfer', author='Hash Banka', author_email='harshbanka321@gmail.com', packages=setuptools.find_packages(), # Needed for dependencies install_requires=['matplotlib','tensorflow','os-win','ffmpy','glob2', 'pytest-shutil', 'pytube', 'opencv-python', 'pillow', 'numpy', 'tensorflow_hub'], version='0.0.8', # The license can be anything you like license='MIT', description=&quot;Package to apply style transfer on different frames of a video&quot;, # We will also need a readme eventually (there will be a warning) # long_description=open('README.txt').read(), python_requires='&gt;=3.6', ) </code></pre> <p>I have also imported them in the <strong>init</strong>.py file present in same directory as the modules.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_hub as hub import numpy as np from pytube import YouTube import os import cv2 from PIL import Image import shutil import glob import ffmpy </code></pre> <p>But still i am getting error when I execute code in the module</p> <pre><code>NameError: name 'cv2' is not defined </code></pre> <p>I am not sure why my imports are not running. I have used cv2 inside a module to do the task. So I am not sure what I am doing wrong. Please help me out.</p>
<p>I am not sure you fully understand what <code>install_requires</code> and <code>packages</code> are for.</p> <ul> <li><code>install_requires</code> specifies libraries that are <em>required</em> for your <em>installation</em> through <code>setup.py</code> to work. E.g. when installing it with <code>pip</code> or <code>python setup.py install</code>. You are specifying what should be on your computer <em>before</em> installing for the installation to work. No package will be installed: if a package listed here is missing, it will simply throw you an error during installation. A very common package to include there is <code>numpy</code>, as you may import it in the <code>setup.py</code>, for example if you have some C or FORTRAN code which needs to compile upon installation.</li> <li><code>packages</code> argument shows which packages are needed for your <em>library</em> to work, so basically which packages to install along with the library. It will check if the package is not already installed on your machine, and if not install it along the library.</li> </ul> <p>What I would do is empty entirely the <code>install_requires</code> argument. Don't even specify it if you are importing none of these packages in the <code>setup.py</code>. If it still doesn't work, I would replace <code>setuptools.find_packages()</code> with the list you are currently providing to <code>install_requires</code>.</p>
python|python-3.x|package
0
1,908,786
69,083,312
Convert nested JSON to CSV or table
<p>I know this question has been asked many times but none of the answers satisfy my requirement. I want to dynamically convert <strong>any nested JSON</strong> to a CSV file or Dataframe. Some sample examples are:</p> <pre><code>input : {&quot;menu&quot;: { &quot;header&quot;: &quot;SVG Viewer&quot;, &quot;items&quot;: [ {&quot;id&quot;: &quot;Open&quot;}, {&quot;id&quot;: &quot;OpenNew&quot;, &quot;label&quot;: &quot;Open New&quot;}, null, {&quot;id&quot;: &quot;ZoomIn&quot;, &quot;label&quot;: &quot;Zoom In&quot;}, {&quot;id&quot;: &quot;ZoomOut&quot;, &quot;label&quot;: &quot;Zoom Out&quot;}, {&quot;id&quot;: &quot;OriginalView&quot;, &quot;label&quot;: &quot;Original View&quot;}, null, {&quot;id&quot;: &quot;Quality&quot;}, {&quot;id&quot;: &quot;Pause&quot;}, {&quot;id&quot;: &quot;Mute&quot;}, null, {&quot;id&quot;: &quot;Find&quot;, &quot;label&quot;: &quot;Find...&quot;}, {&quot;id&quot;: &quot;FindAgain&quot;, &quot;label&quot;: &quot;Find Again&quot;}, {&quot;id&quot;: &quot;Copy&quot;}, {&quot;id&quot;: &quot;CopyAgain&quot;, &quot;label&quot;: &quot;Copy Again&quot;}, {&quot;id&quot;: &quot;CopySVG&quot;, &quot;label&quot;: &quot;Copy SVG&quot;}, {&quot;id&quot;: &quot;ViewSVG&quot;, &quot;label&quot;: &quot;View SVG&quot;}, {&quot;id&quot;: &quot;ViewSource&quot;, &quot;label&quot;: &quot;View Source&quot;}, {&quot;id&quot;: &quot;SaveAs&quot;, &quot;label&quot;: &quot;Save As&quot;}, null, {&quot;id&quot;: &quot;Help&quot;}, {&quot;id&quot;: &quot;About&quot;, &quot;label&quot;: &quot;About Adobe CVG Viewer...&quot;} ] }} </code></pre> <p>Output: <a href="https://i.stack.imgur.com/juPFE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/juPFE.png" alt="enter image description here" /></a></p> <pre><code>input 2 : {&quot;menu&quot;: { &quot;id&quot;: &quot;file&quot;, &quot;value&quot;: &quot;File&quot;, &quot;popup&quot;: { &quot;menuitem&quot;: [ {&quot;value&quot;: &quot;New&quot;, &quot;onclick&quot;: &quot;CreateNewDoc()&quot;}, {&quot;value&quot;: &quot;Open&quot;, &quot;onclick&quot;: &quot;OpenDoc()&quot;}, {&quot;value&quot;: &quot;Close&quot;, &quot;onclick&quot;: &quot;CloseDoc()&quot;} ] } }} </code></pre> <p>Output 2: <a href="https://i.stack.imgur.com/lP26S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lP26S.png" alt="enter image description here" /></a></p> <p>So far I have tried below code, which works fine but it explodes the list type data into columns, but I want it be exploded in rows.</p> <pre><code>from pandas.io.json import json_normalize import pandas as pd def flatten_json(y): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '.') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '.') i += 1 else: out[str(name[:-1])] = str(x) flatten(y) return out def start_explode(data): if type(data) is dict: df = pd.DataFrame([flatten_json(data)]) else: df = pd.DataFrame([flatten_json(x) for x in data]) df = df.astype(str) return df complex_json = {&quot;menu&quot;: { &quot;id&quot;: &quot;file&quot;, &quot;value&quot;: &quot;File&quot;, &quot;popup&quot;: { &quot;menuitem&quot;: [ {&quot;value&quot;: &quot;New&quot;, &quot;onclick&quot;: &quot;CreateNewDoc()&quot;}, {&quot;value&quot;: &quot;Open&quot;, &quot;onclick&quot;: &quot;OpenDoc()&quot;}, {&quot;value&quot;: &quot;Close&quot;, &quot;onclick&quot;: &quot;CloseDoc()&quot;} ] } }} df = start_explode(complex_json['menu']) display(df) </code></pre> <p>It gives output like below for one the above inputs:</p> <p><a href="https://i.stack.imgur.com/VPu94.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VPu94.png" alt="enter image description here" /></a></p>
<ul> <li>standard techniques for dealing with nested json <ol> <li><code>json_normalize()</code></li> <li><code>explode()</code></li> <li><code>apply(pd.Series)</code></li> </ol> </li> <li>finally some cleanup, drop unwanted rows and replace <code>nan</code> with empty string</li> </ul> <pre><code>import json js = &quot;&quot;&quot;{&quot;menu&quot;: { &quot;header&quot;: &quot;SVG Viewer&quot;, &quot;items&quot;: [ {&quot;id&quot;: &quot;Open&quot;}, {&quot;id&quot;: &quot;OpenNew&quot;, &quot;label&quot;: &quot;Open New&quot;}, null, {&quot;id&quot;: &quot;ZoomIn&quot;, &quot;label&quot;: &quot;Zoom In&quot;}, {&quot;id&quot;: &quot;ZoomOut&quot;, &quot;label&quot;: &quot;Zoom Out&quot;}, {&quot;id&quot;: &quot;OriginalView&quot;, &quot;label&quot;: &quot;Original View&quot;}, null, {&quot;id&quot;: &quot;Quality&quot;}, {&quot;id&quot;: &quot;Pause&quot;}, {&quot;id&quot;: &quot;Mute&quot;}, null, {&quot;id&quot;: &quot;Find&quot;, &quot;label&quot;: &quot;Find...&quot;}, {&quot;id&quot;: &quot;FindAgain&quot;, &quot;label&quot;: &quot;Find Again&quot;}, {&quot;id&quot;: &quot;Copy&quot;}, {&quot;id&quot;: &quot;CopyAgain&quot;, &quot;label&quot;: &quot;Copy Again&quot;}, {&quot;id&quot;: &quot;CopySVG&quot;, &quot;label&quot;: &quot;Copy SVG&quot;}, {&quot;id&quot;: &quot;ViewSVG&quot;, &quot;label&quot;: &quot;View SVG&quot;}, {&quot;id&quot;: &quot;ViewSource&quot;, &quot;label&quot;: &quot;View Source&quot;}, {&quot;id&quot;: &quot;SaveAs&quot;, &quot;label&quot;: &quot;Save As&quot;}, null, {&quot;id&quot;: &quot;Help&quot;}, {&quot;id&quot;: &quot;About&quot;, &quot;label&quot;: &quot;About Adobe CVG Viewer...&quot;} ] }}&quot;&quot;&quot; df = pd.json_normalize(json.loads(js)).explode(&quot;menu.items&quot;).reset_index(drop=True) df.drop(columns=[&quot;menu.items&quot;]).join(df[&quot;menu.items&quot;].apply(pd.Series)).dropna(subset=[&quot;id&quot;]).fillna(&quot;&quot;) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: left;">menu.header</th> <th style="text-align: left;">id</th> <th style="text-align: left;">label</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">0</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">Open</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: right;">1</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">OpenNew</td> <td style="text-align: left;">Open New</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">ZoomIn</td> <td style="text-align: left;">Zoom In</td> </tr> <tr> <td style="text-align: right;">4</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">ZoomOut</td> <td style="text-align: left;">Zoom Out</td> </tr> <tr> <td style="text-align: right;">5</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">OriginalView</td> <td style="text-align: left;">Original View</td> </tr> <tr> <td style="text-align: right;">7</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">Quality</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: right;">8</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">Pause</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: right;">9</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">Mute</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: right;">11</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">Find</td> <td style="text-align: left;">Find...</td> </tr> <tr> <td style="text-align: right;">12</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">FindAgain</td> <td style="text-align: left;">Find Again</td> </tr> <tr> <td style="text-align: right;">13</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">Copy</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: right;">14</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">CopyAgain</td> <td style="text-align: left;">Copy Again</td> </tr> <tr> <td style="text-align: right;">15</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">CopySVG</td> <td style="text-align: left;">Copy SVG</td> </tr> <tr> <td style="text-align: right;">16</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">ViewSVG</td> <td style="text-align: left;">View SVG</td> </tr> <tr> <td style="text-align: right;">17</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">ViewSource</td> <td style="text-align: left;">View Source</td> </tr> <tr> <td style="text-align: right;">18</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">SaveAs</td> <td style="text-align: left;">Save As</td> </tr> <tr> <td style="text-align: right;">20</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">Help</td> <td style="text-align: left;"></td> </tr> <tr> <td style="text-align: right;">21</td> <td style="text-align: left;">SVG Viewer</td> <td style="text-align: left;">About</td> <td style="text-align: left;">About Adobe CVG Viewer...</td> </tr> </tbody> </table> </div><h3>utility function</h3> <ul> <li>if you don't want to name columns, but take first list column</li> <li>identify first column that contains lists</li> <li><code>explode()</code> and <code>apply(pd.Series)</code> to that column</li> <li>provided option to expand all lists</li> </ul> <pre><code>def normalize(js, expand_all=False): df = pd.json_normalize(json.loads(js) if type(js)==str else js) # get first column that contains lists col = df.applymap(type).astype(str).eq(&quot;&lt;class 'list'&gt;&quot;).all().idxmax() # explode list and expand embedded dictionaries df = df.explode(col).reset_index(drop=True) df = df.drop(columns=[col]).join(df[col].apply(pd.Series), rsuffix=f&quot;.{col}&quot;) # any lists left? if expand_all and df.applymap(type).astype(str).eq(&quot;&lt;class 'list'&gt;&quot;).any(axis=1).all(): df = normalize(df.to_dict(&quot;records&quot;)) return df js = &quot;&quot;&quot;{ &quot;id&quot;: &quot;0001&quot;, &quot;type&quot;: &quot;donut&quot;, &quot;name&quot;: &quot;Cake&quot;, &quot;ppu&quot;: 0.55, &quot;batters&quot;: { &quot;batter&quot;: [ { &quot;id&quot;: &quot;1001&quot;, &quot;type&quot;: &quot;Regular&quot; }, { &quot;id&quot;: &quot;1002&quot;, &quot;type&quot;: &quot;Chocolate&quot; }, { &quot;id&quot;: &quot;1003&quot;, &quot;type&quot;: &quot;Blueberry&quot; }, { &quot;id&quot;: &quot;1004&quot;, &quot;type&quot;: &quot;Devil's Food&quot; } ] }, &quot;topping&quot;: [ { &quot;id&quot;: &quot;5001&quot;, &quot;type&quot;: &quot;None&quot; }, { &quot;id&quot;: &quot;5002&quot;, &quot;type&quot;: &quot;Glazed&quot; }, { &quot;id&quot;: &quot;5005&quot;, &quot;type&quot;: &quot;Sugar&quot; } ] }&quot;&quot;&quot; normalize(js, expand_all=True) </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: right;"></th> <th style="text-align: right;">id</th> <th style="text-align: left;">type</th> <th style="text-align: left;">name</th> <th style="text-align: right;">ppu</th> <th style="text-align: right;">id.topping</th> <th style="text-align: left;">type.topping</th> <th style="text-align: right;">id.batters.batter</th> <th style="text-align: left;">type.batters.batter</th> </tr> </thead> <tbody> <tr> <td style="text-align: right;">0</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5001</td> <td style="text-align: left;">None</td> <td style="text-align: right;">1001</td> <td style="text-align: left;">Regular</td> </tr> <tr> <td style="text-align: right;">1</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5001</td> <td style="text-align: left;">None</td> <td style="text-align: right;">1002</td> <td style="text-align: left;">Chocolate</td> </tr> <tr> <td style="text-align: right;">2</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5001</td> <td style="text-align: left;">None</td> <td style="text-align: right;">1003</td> <td style="text-align: left;">Blueberry</td> </tr> <tr> <td style="text-align: right;">3</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5001</td> <td style="text-align: left;">None</td> <td style="text-align: right;">1004</td> <td style="text-align: left;">Devil's Food</td> </tr> <tr> <td style="text-align: right;">4</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5002</td> <td style="text-align: left;">Glazed</td> <td style="text-align: right;">1001</td> <td style="text-align: left;">Regular</td> </tr> <tr> <td style="text-align: right;">5</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5002</td> <td style="text-align: left;">Glazed</td> <td style="text-align: right;">1002</td> <td style="text-align: left;">Chocolate</td> </tr> <tr> <td style="text-align: right;">6</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5002</td> <td style="text-align: left;">Glazed</td> <td style="text-align: right;">1003</td> <td style="text-align: left;">Blueberry</td> </tr> <tr> <td style="text-align: right;">7</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5002</td> <td style="text-align: left;">Glazed</td> <td style="text-align: right;">1004</td> <td style="text-align: left;">Devil's Food</td> </tr> <tr> <td style="text-align: right;">8</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5005</td> <td style="text-align: left;">Sugar</td> <td style="text-align: right;">1001</td> <td style="text-align: left;">Regular</td> </tr> <tr> <td style="text-align: right;">9</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5005</td> <td style="text-align: left;">Sugar</td> <td style="text-align: right;">1002</td> <td style="text-align: left;">Chocolate</td> </tr> <tr> <td style="text-align: right;">10</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5005</td> <td style="text-align: left;">Sugar</td> <td style="text-align: right;">1003</td> <td style="text-align: left;">Blueberry</td> </tr> <tr> <td style="text-align: right;">11</td> <td style="text-align: right;">0001</td> <td style="text-align: left;">donut</td> <td style="text-align: left;">Cake</td> <td style="text-align: right;">0.55</td> <td style="text-align: right;">5005</td> <td style="text-align: left;">Sugar</td> <td style="text-align: right;">1004</td> <td style="text-align: left;">Devil's Food</td> </tr> </tbody> </table> </div><h3>consider each list independent</h3> <ul> <li>copy way this works <a href="https://data.page/json/csv" rel="nofollow noreferrer">https://data.page/json/csv</a></li> <li>this is a limited use case, it does not honor general data modelling principles</li> </ul> <pre><code>def n2(js): df = pd.json_normalize(json.loads(js)) # columns that contain lists cols = [i for i, c in df.applymap(type).astype(str).eq(&quot;&lt;class 'list'&gt;&quot;).all().iteritems() if c] # use list from first row return pd.concat( [df.drop(columns=cols)] + [pd.json_normalize(df.loc[0, c]).pipe(lambda d: d.rename(columns={c2: f&quot;{c}.{c2}&quot; for c2 in d.columns})) for c in cols], axis=1, ).fillna(&quot;&quot;) </code></pre>
python|json|pandas|dataframe|pyspark
1
1,908,787
68,425,345
How to isolate a single digit in a decimal?
<p>I am trying to isolate a single digit inside of a decimal in order to display a formatted percentage.</p> <p>I am getting:</p> <pre><code>result = 8 / 10 print(result) #Output: 0.8 </code></pre> <p>I want to solely isolate the 8 so I can print:</p> <pre><code>print(f&quot;The answer is {result}%&quot;) #Output: The answer is 80% </code></pre> <p>How would I do this?</p>
<p>Do you mean strip the &quot;0.&quot;? If so, you can use:</p> <pre class="lang-py prettyprint-override"><code>print(str(result * 100) + '%') </code></pre> <p>P.S. 0.8 means 80%, not 8%.</p>
python|python-3.x
2
1,908,788
59,154,920
Indexing Pytorch tensor
<p>I have a Pytorch code which generates a Pytorch tensor in each iteration of for loop, all of the same size. I want to assign each of those tensors to a row of new tensor, which will include all the tensors at the end. In other works something like this</p> <pre><code>for i=1:N: X = torch.Tensor([[1,2,3], [3,2,5]]) #Y is a pytorch tensor Y[i] = X </code></pre> <p>I wonder how I can implement this with Pytorch.</p>
<p>You can concatenate the tensors using <a href="https://pytorch.org/docs/stable/torch.html#torch.cat" rel="nofollow noreferrer"><code>torch.cat</code></a>:</p> <pre class="lang-py prettyprint-override"><code>tensors = [] for i in range(N): X = torch.tensor([[1,2,3], [3,2,5]]) tensors.append(X) Y = torch.cat(tensors, dim=0) # dim 0 is the rows of the tensor </code></pre>
pytorch|tensor
1
1,908,789
59,391,806
PyQt5: How to place a QPixmap on top of another QPixmap?
<p>I would like to place a QPixmap on another QPixmap. Both have the same size, so I would just like to make an overlay. The overlay image has a transparent elipse in the middle. I figure they should be QPixmap format, however I dont know how to place them on top of each other and keep them in place when resizing the window. This is my code displaying how my background images are placed. I have attached a image explaining what i want.</p> <pre><code>import sys from PyQt5 import QtGui ,QtWidgets, uic from PyQt5.QtCore import Qt class Ergolab(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super(Ergolab, self).__init__(*args, **kwargs) # Load the UI Page self.ui = uic.loadUi("mainwindow.ui",self) self.pixmap1 = QtGui.QPixmap('C:/Users/Frede/Desktop/img1.jpg') self.shoflexLLabel.setPixmap(self.pixmap1.scaled(self.shoflexLLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) self.shoflexLLabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.shoflexLLabel.setMinimumSize(150, 150) self.shoflexLLabel.resize(800, 600) self.pixmap2 = QtGui.QPixmap('C:/Users/Frede/Desktop/img2.jpg') self.shoflexRLabel.setPixmap(self.pixmap2.scaled(self.shoflexRLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) self.shoflexRLabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.shoflexRLabel.setMinimumSize(150, 150) self.shoflexRLabel.resize(800, 600) def resizeEvent(self, event): scaledSize = self.shoflexLLabel.size() if not self.shoflexLLabel.pixmap() or scaledSize != self.shoflexLLabel.pixmap().size(): self.updateLabel() def updateLabel(self): self.shoflexLLabel.setPixmap(self.pixmap1.scaled( self.shoflexLLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) self.shoflexRLabel.setPixmap(self.pixmap2.scaled( self.shoflexRLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) def main(): app = QtWidgets.QApplication(sys.argv) main = Ergolab() main.show() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p>This is the result I would like: <a href="https://i.stack.imgur.com/XEtE3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XEtE3.jpg" alt="enter image description here"></a></p>
<p>You must use QPainter by setting the circle as a clip path:</p> <pre class="lang-py prettyprint-override"><code>import sys from PyQt5 import QtCore, QtGui, QtWidgets class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) label = QtWidgets.QLabel() self.setCentralWidget(label) base_pixmap = QtGui.QPixmap("background.png") overlay_pixmap = QtGui.QPixmap("overlay.png") radius = 300 r = QtCore.QRectF() r.setSize(radius * QtCore.QSizeF(1, 1)) r.moveCenter(base_pixmap.rect().center()) path = QtGui.QPainterPath() path.addEllipse(r) painter = QtGui.QPainter(base_pixmap) painter.setRenderHints( QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform ) painter.setClipPath(path, QtCore.Qt.IntersectClip) painter.drawPixmap(QtCore.QPoint(), overlay_pixmap) painter.end() label.setPixmap(base_pixmap) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) </code></pre> <p><img src="https://i.stack.imgur.com/Em0V0t.png" width="320" /> <img src="https://i.stack.imgur.com/FDmxW.png" width="320" /></p> <p><img src="https://i.stack.imgur.com/UzQjq.png" width="640" /></p>
python|pyqt5|qpixmap
5
1,908,790
59,109,259
Python + SqlAlchemy: Add Parent/Child Records When Both Parent & Child are New
<p>I've asked a <a href="https://stackoverflow.com/q/59097167/2144390">similar question</a> already, but I think it would be much clearer if, rather than provide samples of what I've already coded, I simply state the goal of the case I have. Here goes:</p> <p>I have a table that is in a self-referential one-to-many relationship. I.e., it is a hierarchical table in the classic parent/child set-up. Nothing fancy about it, just a basic parent has many children, child has one parent.</p> <p>I can create the table just fine in ORM. From there, however, I want to <strong>load the table with data from a JSON file</strong>. My JSON, of course, represents such that there are top-level "parent" entries which then, each, have n-number of "children," and each of those my have children, also, etc. For all those children records, I obviously can't refer back to a specific "parent.id," because parent is not yet persisted in the DB. And, also obviously, this problem exists in any case I want to add a wholly new graph of parent/child records (i.e., not just for the load-from-JSON example).</p> <p>Accomplishing this feat in Entity Framework has always been pretty simple. So long as the relationships are correctly defined, it simply <em>works</em>, with all the proper sequencing of record adds.</p> <p>In SqlAlchemy, it also seems to be entirely possible, but there's something wrong (I think) with the way I've been defining the relationships. In any way I've tried thus far, what I get is this error:</p> <p><code>Class 'MyTableClass' is mapped, but this instance lacks instrumentation. This occurs when the instance is created before sqlalchemy.orm.mapper(MyTableClass) was called.</code></p> <p>I don't know precisely how to read that, but what I think it's telling me is that it's trying to create child objects before parent is created. But I don't know, and it doesn't help me discover where my relationships are ill-defined.</p> <p>Any guidance appreciated!</p>
<p>Based on the answers and comments from <a href="https://stackoverflow.com/q/2638217/2144390">this question</a> the following seems to work for me:</p> <pre class="lang-python prettyprint-override"><code>from sqlalchemy import create_engine, Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relation, sessionmaker connection_url = &quot;mssql+pyodbc://@localhost,49242/myDb?driver=ODBC+Driver+17+for+SQL+Server&quot; engine = create_engine(connection_url) Base = declarative_base() class Person(Base): __tablename__ = 'person' id = Column(Integer, autoincrement=True, primary_key=True) name = Column(String(50)) _parent_id = Column(Integer, ForeignKey('person.id')) parent = relation('Person', remote_side=[id]) children = relation('Person', remote_side=[_parent_id], uselist=True) def __repr__(self): return f&quot;&lt;Person(id={self.id}, name='{self.name}'&gt;)&quot; Base.metadata.drop_all(engine, checkfirst=True) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() parent = Person(name='Homer') child = Person(name='Bart') parent.children.append(child) child = Person(name='Lisa') parent.children.append(child) print(f&quot;{parent.name}'s (unpersisted) children: {parent.children}&quot;) # Homer's (unpersisted) children: [&lt;Person(id=None, name='Bart'&gt;), &lt;Person(id=None, name='Lisa'&gt;)] session.add(parent) session.commit() print(f&quot;{parent.name}'s (persisted) children: {parent.children}&quot;) # Homer's (persisted) children: [&lt;Person(id=2, name='Bart'&gt;), &lt;Person(id=3, name='Lisa'&gt;)] child = session.query(Person).filter(Person.name=='Lisa').first() print(f&quot;{child.name}'s parent: {child.parent}&quot;) # Lisa's parent: &lt;Person(id=1, name='Homer'&gt;) with engine.begin() as conn: print(conn.execute(&quot;SELECT * FROM person&quot;).fetchall()) # [(1, 'Homer', None), (2, 'Bart', 1), (3, 'Lisa', 1)] </code></pre>
python|python-3.x|entity-framework|orm|sqlalchemy
2
1,908,791
59,122,550
How do you create a live template in Intellij with a variable name inside the abbreviation?
<p>I am trying to create a live template in Intellij by using an abbreviation like:</p> <pre><code>for$index_name$ </code></pre> <p>to create the template text:</p> <pre><code>for $index_name$ in </code></pre> <p>For example, I want the abbreviation <code>forj</code> to produce <code>for j in</code>. I have not found anything regarding this in Intellij's <a href="https://www.jetbrains.com/help/idea/template-variables.html" rel="nofollow noreferrer">live template documentation</a>. If such a thing is possible how would it be done?</p>
<p>Somebody from <a href="https://youtrack.jetbrains.com/issue/IDEA-228054" rel="nofollow noreferrer">JetBrains</a> has said that </p> <blockquote> <p>"Such functionality is currently not available and not very likely to be added in near future, sorry."</p> </blockquote>
python|intellij-idea|live-templates
0
1,908,792
35,501,714
Cannot install modules via pip running on python 3.4
<p>I have been trying to install various modules that I need to have to run this script:</p> <p><a href="https://github.com/austingandy/slack-evernote/blob/master/slackwriter.py" rel="nofollow">https://github.com/austingandy/slack-evernote/blob/master/slackwriter.py</a></p> <p>I am working off a Mac, and my <code>python --version</code> is:</p> <pre><code>Python 3.4.3 :: Anaconda 2.3.0 (x86_64) </code></pre> <p>And I have for <code>python -m pip --version</code>:</p> <pre><code>pip 8.0.2 from /Users/dhruv/anaconda/lib/python3.4/site-packages (python 3.4) </code></pre> <p>However, for example when I run <code>pip install evernote</code> I get errors like:</p> <pre><code>Collecting evernote Using cached evernote-1.25.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/cj/5gs43w4n2tz313rrnz9_htf00000gn/T/pip-build-0y7hm202/evernote/setup.py", line 6 exec x ^ SyntaxError: Missing parentheses in call to 'exec' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/cj/5gs43w4n2tz313rrnz9_htf00000gn/T/pip-build-0y7hm202/evernote </code></pre> <p>I have a feeling that these errors are because the <code>setup.py</code> code that <code>pip</code> has is in python 2.7 format, and my environment is 3.4, but how can I overall install all the packages I need to run this script? Would I change to python 2.7, install in that environment, and then repackage the setup of evernote into python 3.4 format? If so, how?</p>
<p>AFAIK, Evernote SDK for Python 3 is not yet supported. </p> <p><a href="https://github.com/evernote/evernote-sdk-python3" rel="nofollow">https://github.com/evernote/evernote-sdk-python3</a></p> <blockquote> <p>This is a test SDK! The official Evernote SDK for Python doesn't support Python 3 yet; this repository is an experiment as we try to migrate.</p> </blockquote> <p>You can try installing manually from the link above or downgrade to python2 in your virtual env.</p>
python|python-2.7|python-3.x|pip
3
1,908,793
31,378,424
How to set up a continuously running processes along with Django?
<p>I am setting up backend for an application, with Django and MySQL.</p> <p>As a part of the set up, I need to keep on fetching latest content from Facebook and Twitter Graph APIs and keep updating my database with that.</p> <p>The user of my application would pull this latest available data from the database. </p> <p>Now,how and where I implant this code? Shall I put it somewhere in the Django project, if yes, then where?</p> <p>Or shall I use it as an independent script i.e. not attached to Django in anyway, and update the DB directly with that.</p> <p>Also since this would be a continuous process, I need it to run as background task. It should not eat consume any resources that might be needed by the foreground tasks. </p>
<p>The recommended way is using <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a>. If you want don't want to use async task handling you can also just create a <a href="https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/" rel="nofollow">custom management command</a> and run it via cron. Both of them should work with the whole projects context (e.g. what your defined in your settings), so you can use the Django ORM to connect to your DB etc..</p>
python|mysql|django
1
1,908,794
15,493,342
Have Emacs edit Python docstrings using rst-mode
<p>How to I get Emacs to use <code>rst-mode</code> inside of docstrings in Python files? I vaguely remember that different modes within certain regions of a file is possible, but I don't remember how it's done. </p>
<p>The Emacs package that supports that is <code>mmm-mode</code>. Ensure that's installed, and then code like this as part of your Emacs startup should do it:</p> <pre><code>(require 'mmm-mode) (setq mmm-global-mode 'maybe) (mmm-add-classes '((python-rst :submode rst-mode :front "^ *[ru]?\"\"\"[^\"]*$" :back "^ *\"\"\"" :include-front t :include-back t :end-not-begin t))) (mmm-add-mode-ext-class 'python-mode nil 'python-rst) </code></pre> <p>I tested this with some Python programs and it seems to work properly.</p> <p>Note that this will switch to rst-mode for every triple-quoted string, not just the ones at the start of a function definition. You could probably restrict it to just the ones at the start of a function definition with a more complex front regex, but I'm not completely sure how to handle it since I think mmm-mode definitions by default match a line at a time.</p> <p><strong>Edit</strong>: My original version would put Emacs into rst-mode at the point of a single line docstring and then leave it in that mode up until the start of the next docstring. This version avoids putting Emacs into rst-mode if there is another double quote on the same line as the start of the docstring, which still isn't perfect but should be closer.</p>
python|emacs|restructuredtext
16
1,908,795
59,583,091
WinError 87 Trying to install Kivy
<p>Working on Windows</p> <p>I'm using these instructions: <a href="https://kivy.org/doc/stable/installation/installation-windows.html#install-win-dist" rel="nofollow noreferrer">https://kivy.org/doc/stable/installation/installation-windows.html#install-win-dist</a></p> <p>On step 3. Install kivy: </p> <pre><code>python -m pip install kivy==1.11.1 </code></pre> <p>I receive this error in CMD:</p> <pre><code>ERROR: Error [WinError 87] The parameter is incorrect while executing command python setup.py egg_info ERROR: Could not install packages due to an EnvironmentError: [WinError 87] The parameter is incorrect </code></pre> <p>It's not the first time that I am encountering this error. I have never been able to solve it.</p>
<p>Try the following first and then check whether the env is getting activated or not.</p> <p>Open command prompt and execute the following:- type the extension of activate i.e bat. Don't end without extension </p> <pre><code>kivy_venv\Scripts\activate.bat </code></pre> <p>After this run:- </p> <pre><code>PathofVenv\scripts\pip.exe install kivy </code></pre>
python|cmd|kivy
0
1,908,796
59,848,008
TensorFlow Blas GEMM launch failed
<p>I am trying to run a simple CNN, and i get the error message "Blas GEMM launch failed". TensorFlow 2.1.0 is set up correctly on my machine, i am able to execute tensorflow examples successfully. However, TensorRT is not installed and creates some warnings:</p> <pre><code>python -c 'import tensorflow as tf; print(tf.__version__)' 2020-01-21 20:26:39.850967: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory 2020-01-21 20:26:39.851030: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory 2020-01-21 20:26:39.851040: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:30] Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly. 2.1.0 </code></pre> <p>This is the error I get:</p> <pre><code>2020-01-21 20:21:11.549012: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10 2020-01-21 20:21:11.549233: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:11.549266: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:11.549347: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:11.549370: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:11.549452: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:11.549467: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:11.552664: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7 2020-01-21 20:21:12.266456: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:12.319531: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:12.350929: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:12.351077: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED 2020-01-21 20:21:12.351089: W tensorflow/stream_executor/stream.cc:2041] attempting to perform BLAS operation using StreamExecutor without BLAS support 2020-01-21 20:21:12.351114: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Internal: Blas GEMM launch failed : a.shape=(32, 50176), b.shape=(50176, 32), m=32, n=32, k=50176 [[{{node sequential/dense/MatMul}}]] 32/32 [==============================] - 1s 33ms/sample Traceback (most recent call last): File "xcnn.py", line 27, in &lt;module&gt; history = model.fit(images, labels, epochs=1) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training.py", line 819, in fit use_multiprocessing=use_multiprocessing) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 342, in fit total_epochs=epochs) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2.py", line 128, in run_one_epoch batch_outs = execution_function(iterator) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py", line 98, in execution_function distributed_function(input_fn)) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py", line 568, in __call__ result = self._call(*args, **kwds) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/eager/def_function.py", line 632, in _call return self._stateless_fn(*args, **kwds) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 2363, in __call__ return graph_function._filtered_call(args, kwargs) # pylint: disable=protected-access File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1611, in _filtered_call self.captured_inputs) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 1692, in _call_flat ctx, args, cancellation_manager=cancellation_manager)) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/eager/function.py", line 545, in call ctx=ctx) File "/home/marc/tf_2/lib/python3.6/site-packages/tensorflow_core/python/eager/execute.py", line 67, in quick_execute six.raise_from(core._status_to_exception(e.code, message), None) File "&lt;string&gt;", line 3, in raise_from tensorflow.python.framework.errors_impl.InternalError: Blas GEMM launch failed : a.shape=(32, 50176), b.shape=(50176, 32), m=32, n=32, k=50176 [[node sequential/dense/MatMul (defined at xcnn.py:27) ]] [Op:__inference_distributed_function_932] Function call stack: distributed_function </code></pre> <p>I created a minimal example that reproduces my problem:</p> <pre><code>import numpy as np from tensorflow.keras import layers, models IMAGE_WIDTH = 128 IMAGE_HEIGHT = 128 model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH,IMAGE_HEIGHT,3))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.Flatten()) model.add(layers.Dense(32, activation='relu')) model.add(layers.Dense(4, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) BATCH_SIZE = 32 images = np.zeros((BATCH_SIZE, IMAGE_WIDTH, IMAGE_HEIGHT, 3)) labels = np.zeros((BATCH_SIZE, 4)) history = model.fit(images, labels, epochs=1) </code></pre>
<p>I don't think the TensorRT warnings are related, probably just warning you that you can't use tensorflow.python.compiler.tensorrt* without TensorRT installed.</p> <p>Regarding the CUBLAS errors, seems like it could be one of several solutions on this thread: <a href="https://github.com/tensorflow/tensorflow/issues/9489" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues/9489</a></p> <ul> <li>OOM error - limit GPU memory growth</li> <li>Removing cache folder (~/.nv)</li> <li>Configuration mismatch with CUDA/CUDNN version</li> </ul>
tensorflow|keras|tensorflow2.0
1
1,908,797
48,919,935
Parsing stray text with Scrapy
<p>Any idea how to extract 'TEXT TO GRAB' from this piece of markup:</p> <pre><code>&lt;span class="navigation_page"&gt; &lt;span&gt; &lt;a itemprop="url" href="http://www.example.com"&gt; &lt;span itemprop="title"&gt;LINK&lt;/span&gt; &lt;/a&gt; &lt;/span&gt; &lt;span class="navigation-pipe"&gt;&amp;gt;&lt;/span&gt; TEXT TO GRAB &lt;/span&gt; </code></pre>
<p>Not ideal:</p> <pre><code>text_to_grab = response.xpath('//span[@class="navigation-pipe"]/following-sibling::text()[1]').extract_first() </code></pre>
python|web-scraping|scrapy|scrapy-spider
2
1,908,798
70,826,674
How to flatten a column of nested json objects in an already flattened dataframe
<p>I have a json file with nested objects which is flattened in a pandas dataframe. There is a single column with nested json objects that I find hard the flatten.</p> <p>I have tried many approaches, this is the approach that got me the furthest.</p> <p>Help would be greatly appreciated, thank you.</p> <p><em>Unfortunately I was unable to find a jsfiddle like alternative for python to provide a working example.</em></p> <p>I understand that with the meta parameter of json_normalize I can add columns to my dataframe. But that approach does not work on the unflat column because I only got json_normalize to work well in my setup by setting record_path to 'markets' which is the main json object in my file. So in this setup I am unable to record_path to 'marketStats' and add any relevant columns via the meta parameter.</p> <p><strong>Goal</strong></p> <p>The goal is to transform one or all json objects in the marketStats object in to columns of the dataframe.</p> <p><strong>Code</strong></p> <pre><code>with open('Data/20012022.json') as file: data = json.loads(file.read()) # Flatten data df0 = pd.json_normalize( data, record_path =['markets'] ) df0.head(3) </code></pre> <p><strong>Screenshot</strong></p> <p>This is a screenshot of what the table currently looks like, the marketStats column contains nested json.</p> <p><a href="https://i.stack.imgur.com/ssTdz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ssTdz.png" alt="enter image description here" /></a></p> <p><strong>Data</strong></p> <p>This a snippet from the json file. `</p> <pre><code>{ &quot;markets&quot;: [ { &quot;id&quot;: 335, &quot;baseCurrency&quot;: &quot;eth&quot;, &quot;quoteCurrency&quot;: &quot;btc&quot;, &quot;exchangeName&quot;: &quot;Binance&quot;, &quot;exchangeCode&quot;: &quot;BINA&quot;, &quot;longName&quot;: &quot;BTC-ETH&quot;, &quot;marketName&quot;: &quot;btc-eth&quot;, &quot;symbol&quot;: &quot;ETHBTC&quot;, &quot;volume&quot;: &quot;40624.5823&quot;, &quot;quoteVolume&quot;: &quot;3026.13646935&quot;, &quot;btcVolume&quot;: &quot;3026.13646935&quot;, &quot;usdVolume&quot;: &quot;127009429.050524367&quot;, &quot;currentPrice&quot;: 0.074681, &quot;latestBase&quot;: { &quot;id&quot;: 161774475, &quot;time&quot;: 1639576800, &quot;date&quot;: &quot;2021-12-15T14:00:00.000+00:00&quot;, &quot;price&quot;: &quot;0.077653&quot;, &quot;lowestPrice&quot;: &quot;0.0729&quot;, &quot;bounce&quot;: &quot;6.283&quot;, &quot;currentDrop&quot;: &quot;-3.8272829124438206&quot;, &quot;crackedAt&quot;: &quot;2022-01-07T03:00:00.000Z&quot;, &quot;respectedAt&quot;: &quot;2022-01-15T15:00:00.000Z&quot;, &quot;isLowest&quot;: false }, &quot;marketStats&quot;: [ { &quot;algorithm&quot;: &quot;original&quot;, &quot;ratio&quot;: &quot;50.0&quot;, &quot;medianDrop&quot;: &quot;-4.08&quot;, &quot;medianBounce&quot;: &quot;5.51&quot;, &quot;hoursToRespected&quot;: 106, &quot;crackedCount&quot;: 2, &quot;respectedCount&quot;: 1 }, { &quot;algorithm&quot;: &quot;day_trade&quot;, &quot;ratio&quot;: &quot;100.0&quot;, &quot;medianDrop&quot;: &quot;-6.12&quot;, &quot;medianBounce&quot;: &quot;6.28&quot;, &quot;hoursToRespected&quot;: 204, &quot;crackedCount&quot;: 1, &quot;respectedCount&quot;: 1 }, { &quot;algorithm&quot;: &quot;conservative&quot;, &quot;ratio&quot;: &quot;100.0&quot;, &quot;medianDrop&quot;: &quot;-6.12&quot;, &quot;medianBounce&quot;: &quot;8.38&quot;, &quot;hoursToRespected&quot;: 204, &quot;crackedCount&quot;: 1, &quot;respectedCount&quot;: 1 }, { &quot;algorithm&quot;: &quot;position&quot;, &quot;ratio&quot;: &quot;50.0&quot;, &quot;medianDrop&quot;: &quot;-6.12&quot;, &quot;medianBounce&quot;: &quot;6.19&quot;, &quot;hoursToRespected&quot;: 204, &quot;crackedCount&quot;: 2, &quot;respectedCount&quot;: 1 }, { &quot;algorithm&quot;: &quot;hodloo&quot;, &quot;ratio&quot;: &quot;50.0&quot;, &quot;medianDrop&quot;: &quot;-3.29&quot;, &quot;medianBounce&quot;: &quot;0.0&quot;, &quot;hoursToRespected&quot;: 225, &quot;crackedCount&quot;: 4, &quot;respectedCount&quot;: 2 } ] }, { &quot;id&quot;: 337, &quot;baseCurrency&quot;: &quot;ltc&quot;, &quot;quoteCurrency&quot;: &quot;btc&quot;, &quot;exchangeName&quot;: &quot;Binance&quot;, &quot;exchangeCode&quot;: &quot;BINA&quot;, &quot;longName&quot;: &quot;BTC-LTC&quot;, &quot;marketName&quot;: &quot;btc-ltc&quot;, &quot;symbol&quot;: &quot;LTCBTC&quot;, &quot;volume&quot;: &quot;68309.637&quot;, &quot;quoteVolume&quot;: &quot;223.79294524&quot;, &quot;btcVolume&quot;: &quot;223.79294524&quot;, &quot;usdVolume&quot;: &quot;9392773.4219378968&quot;, &quot;currentPrice&quot;: 0.003275, &quot;latestBase&quot;: { &quot;id&quot;: 163982984, &quot;time&quot;: 1642374000, &quot;date&quot;: &quot;2022-01-16T23:00:00.000+00:00&quot;, &quot;price&quot;: &quot;0.003346&quot;, &quot;lowestPrice&quot;: &quot;0.00322&quot;, &quot;bounce&quot;: &quot;3.839&quot;, &quot;currentDrop&quot;: &quot;-2.1219366407650926&quot;, &quot;crackedAt&quot;: &quot;2022-01-18T23:00:00.000Z&quot;, &quot;respectedAt&quot;: null, &quot;isLowest&quot;: false }, &quot;marketStats&quot;: [ { &quot;algorithm&quot;: &quot;original&quot;, &quot;ratio&quot;: &quot;57.14&quot;, &quot;medianDrop&quot;: &quot;-3.28&quot;, &quot;medianBounce&quot;: &quot;3.84&quot;, &quot;hoursToRespected&quot;: 186, &quot;crackedCount&quot;: 7, &quot;respectedCount&quot;: 4 }, { &quot;algorithm&quot;: &quot;day_trade&quot;, &quot;ratio&quot;: &quot;0.0&quot;, &quot;medianDrop&quot;: &quot;0.0&quot;, &quot;medianBounce&quot;: &quot;5.68&quot;, &quot;hoursToRespected&quot;: 0, &quot;crackedCount&quot;: 1, &quot;respectedCount&quot;: 0 }, { &quot;algorithm&quot;: &quot;conservative&quot;, &quot;ratio&quot;: &quot;0.0&quot;, &quot;medianDrop&quot;: &quot;0.0&quot;, &quot;medianBounce&quot;: &quot;5.68&quot;, &quot;hoursToRespected&quot;: 0, &quot;crackedCount&quot;: 1, &quot;respectedCount&quot;: 0 }, { &quot;algorithm&quot;: &quot;position&quot;, &quot;ratio&quot;: &quot;0.0&quot;, &quot;medianDrop&quot;: &quot;0.0&quot;, &quot;medianBounce&quot;: &quot;8.16&quot;, &quot;hoursToRespected&quot;: 0, &quot;crackedCount&quot;: 1, &quot;respectedCount&quot;: 0 }, { &quot;algorithm&quot;: &quot;hodloo&quot;, &quot;ratio&quot;: &quot;75.0&quot;, &quot;medianDrop&quot;: &quot;-3.7&quot;, &quot;medianBounce&quot;: &quot;0.0&quot;, &quot;hoursToRespected&quot;: 35, &quot;crackedCount&quot;: 4, &quot;respectedCount&quot;: 3 } ] }, { &quot;id&quot;: 339, &quot;baseCurrency&quot;: &quot;bnb&quot;, &quot;quoteCurrency&quot;: &quot;btc&quot;, &quot;exchangeName&quot;: &quot;Binance&quot;, &quot;exchangeCode&quot;: &quot;BINA&quot;, &quot;longName&quot;: &quot;BTC-BNB&quot;, &quot;marketName&quot;: &quot;btc-bnb&quot;, &quot;symbol&quot;: &quot;BNBBTC&quot;, &quot;volume&quot;: &quot;154576.177&quot;, &quot;quoteVolume&quot;: &quot;1724.66664804&quot;, &quot;btcVolume&quot;: &quot;1724.66664804&quot;, &quot;usdVolume&quot;: &quot;72385673.4448901928&quot;, &quot;currentPrice&quot;: 0.01099, &quot;latestBase&quot;: { &quot;id&quot;: 163753765, &quot;time&quot;: 1642068000, &quot;date&quot;: &quot;2022-01-13T10:00:00.000+00:00&quot;, &quot;price&quot;: &quot;0.01093&quot;, &quot;lowestPrice&quot;: &quot;0.01093&quot;, &quot;bounce&quot;: &quot;3.102&quot;, &quot;currentDrop&quot;: &quot;0.5489478499542543&quot;, &quot;crackedAt&quot;: null, &quot;respectedAt&quot;: null, &quot;isLowest&quot;: false }, &quot;marketStats&quot;: [ { &quot;algorithm&quot;: &quot;original&quot;, &quot;ratio&quot;: &quot;100.0&quot;, &quot;medianDrop&quot;: &quot;-7.18&quot;, &quot;medianBounce&quot;: &quot;4.34&quot;, &quot;hoursToRespected&quot;: 62, &quot;crackedCount&quot;: 2, &quot;respectedCount&quot;: 2 }, { &quot;algorithm&quot;: &quot;day_trade&quot;, &quot;ratio&quot;: &quot;100.0&quot;, &quot;medianDrop&quot;: &quot;-6.19&quot;, &quot;medianBounce&quot;: &quot;4.3&quot;, &quot;hoursToRespected&quot;: 63, &quot;crackedCount&quot;: 1, &quot;respectedCount&quot;: 1 }, { &quot;algorithm&quot;: &quot;conservative&quot;, &quot;ratio&quot;: &quot;66.67&quot;, &quot;medianDrop&quot;: &quot;-3.15&quot;, &quot;medianBounce&quot;: &quot;4.05&quot;, &quot;hoursToRespected&quot;: 62, &quot;crackedCount&quot;: 3, &quot;respectedCount&quot;: 2 }, { &quot;algorithm&quot;: &quot;position&quot;, &quot;ratio&quot;: &quot;100.0&quot;, &quot;medianDrop&quot;: &quot;-3.15&quot;, &quot;medianBounce&quot;: &quot;4.46&quot;, &quot;hoursToRespected&quot;: 60, &quot;crackedCount&quot;: 2, &quot;respectedCount&quot;: 2 }, { &quot;algorithm&quot;: &quot;hodloo&quot;, &quot;ratio&quot;: &quot;100.0&quot;, &quot;medianDrop&quot;: &quot;-7.46&quot;, &quot;medianBounce&quot;: &quot;0.0&quot;, &quot;hoursToRespected&quot;: 62, &quot;crackedCount&quot;: 5, &quot;respectedCount&quot;: 5 } ] } ] } </code></pre>
<p>You can apply some post-processing to <code>df0</code> to achieve what you want. Here you can apply <code>explode</code> followed by <code>apply(pf.Series)</code> applied to <code>'marketStats'</code> column:</p> <pre><code>df1 = df0.explode('marketStats')['marketStats'].apply(pd.Series) </code></pre> <p><code>df1</code> looks like this:</p> <pre><code> algorithm ratio medianDrop medianBounce hoursToRespected crackedCount respectedCount -- ------------ ------- ------------ -------------- ------------------ -------------- ---------------- 0 original 50 -4.08 5.51 106 2 1 0 day_trade 100 -6.12 6.28 204 1 1 0 conservative 100 -6.12 8.38 204 1 1 0 position 50 -6.12 6.19 204 2 1 0 hodloo 50 -3.29 0 225 4 2 1 original 57.14 -3.28 3.84 186 7 4 1 day_trade 0 0 5.68 0 1 0 1 conservative 0 0 5.68 0 1 0 1 position 0 0 8.16 0 1 0 1 hodloo 75 -3.7 0 35 4 3 2 original 100 -7.18 4.34 62 2 2 2 day_trade 100 -6.19 4.3 63 1 1 2 conservative 66.67 -3.15 4.05 62 3 2 2 position 100 -3.15 4.46 60 2 2 2 hodloo 100 -7.46 0 62 5 5 </code></pre> <p>if you want it combined with all the other columns you can use <code>join</code>:</p> <pre><code>df0.join(df1) </code></pre> <p>I am not going to post the output of this command as it is rather large</p>
python|json|pandas|dictionary|json-normalize
2
1,908,799
70,826,801
sort a nested list of dicts by key in python
<p>Below is an example nested list of dictionaries. I want to order the lists by the number of points that Charlie has.</p> <pre><code>l = [[{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20 }, {'Name': 'Charlie', 'Age': 30, 'Point': 10}], [{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20 }, {'Name': 'Charlie', 'Age': 30, 'Point': 30}], [{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20 }, {'Name': 'Charlie', 'Age': 30, 'Point': 20}]] </code></pre> <p>The output should look like this.</p> <pre><code>l = [[{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20 }, {'Name': 'Charlie', 'Age': 30, 'Point': 10}], [{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20 }, {'Name': 'Charlie', 'Age': 30, 'Point': 20}], [{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20 }, {'Name': 'Charlie', 'Age': 30, 'Point': 30}]] </code></pre> <p>I think I should be able to use sorted() with the right arguments, but I'm not sure what the syntax would be.</p> <pre><code>sorted(l, key=lambda x: x[ ????? ]) </code></pre> <p>Charlie is always the third dict in the sublists.</p>
<p>Use a lambda to search for Charlie's point in the nested lists:</p> <pre><code>l.sort(key=lambda lst: next(d.get('Point', 0) for d in lst if d.get('Name')=='Charlie')) print(l) </code></pre> <p>If you want a new list:</p> <pre><code>out = sorted(l, key=lambda lst: next(d.get('Point', 0) for d in lst if d.get('Name')=='Charlie')) </code></pre> <p>Output:</p> <pre><code>[[{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20}, {'Name': 'Charlie', 'Age': 30, 'Point': 10}], [{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20}, {'Name': 'Charlie', 'Age': 30, 'Point': 20}], [{'Name': 'Alice', 'Age': 40, 'Point': 80}, {'Name': 'Bob', 'Age': 20}, {'Name': 'Charlie', 'Age': 30, 'Point': 30}]] </code></pre>
python|list
3