QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
76,741,926
18,739,908
How do you set a checkbox to true using pypdf?
<p>I'm trying to programmatically fill out a fillable pdf with python using pypdf. Here are the <a href="https://pypdf.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">docs</a>. I already have it working with normal text boxes:</p> <pre><code>writer.update_page_form_field_values(writer.pages[i], {key: &quot;Jeff Willams&quot;}) </code></pre> <p>Now I'm trying to figure out how to deal with checkboxes. I've tried all of the following with no success:</p> <pre><code>writer.update_page_form_field_values(writer.pages[i], {key: True}) writer.update_page_form_field_values(writer.pages[i], {key: &quot;True&quot;}) writer.update_page_form_field_values(writer.pages[i], {key: &quot;true&quot;}) writer.update_page_form_field_values(writer.pages[i], {key: &quot;On&quot;}) writer.update_page_form_field_values(writer.pages[i], {key: &quot;/On&quot;}) writer.update_page_form_field_values(writer.pages[i], {key: &quot;Yes&quot;}) writer.update_page_form_field_values(writer.pages[i], {key: &quot;/Yes&quot;}) </code></pre> <p>Is this even the right method to use for this? Please let me know if anyone has experience with this. Thanks.</p>
<python><python-3.x><pdf><pypdf>
2023-07-22 00:53:57
0
494
Cole
76,741,844
22,212,435
Glitches happen when using "place" method too often
<p>I am trying to make Visual programming system using tkinter. That is what I have for now: <a href="https://i.sstatic.net/P8CBJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/P8CBJ.png" alt="" /></a></p> <p>I need to be able to move nodes by mouse. All nodes have a main frame, that I am moving using place method. I have created a funcion with place method and attached it to the &quot;Motion&quot; event. But then if I move nodes too fast, I can see the temporary &quot;path&quot; made of last positions of a node: <a href="https://i.sstatic.net/BGxK9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BGxK9.png" alt="" /></a> I am not sure why this happens. My guess is that it may be hard to complete lots of place function at small time, so just can't update screen too fast. Or maybe that is somehow related to the bindtags. Parts from code. From <strong>init</strong>:</p> <pre><code>[widget.bind(&quot;&lt;Button-1&gt;&quot;, self.start_motion) for (name, widget) in self.base_f.children.items()] [widget.bind(&quot;&lt;ButtonRelease-1&gt;&quot;, self.stop_motion) for (name, widget) in self.base_f.children.items()] </code></pre> <p>Then start, stop motion and move node functions:</p> <pre><code>def start_motion(self, e: tk.Event): [widget.bind(&quot;&lt;Motion&gt;&quot;, self.move_node) for (name, widget) in self.base_f.children.items()] def stop_motion(self, e: tk.Event): [widget.unbind(&quot;&lt;Motion&gt;&quot;) for (name, widget) in self.base_f.children.items()] def move_node(self, e): m_pos_x = root.winfo_pointerx() - root.winfo_rootx() m_pos_y = root.winfo_pointery() - root.winfo_rooty() self.base_f.place(x=m_pos_x, y=m_pos_y) </code></pre> <p>Some explanation: All widgets from &quot;node&quot; class are children from a main_base_frame(base_f). I want binding happens only on specific widgets touched by a mouse (that is where that lists come from, only touched children of base_f will make node to be able to move). Move node just move node to position of cursor. Here is a simple code example to try:</p> <pre><code>import tkinter as tk class SimpleClass: def __init__(self): self.frame = tk.Frame(width=200, height=100, bg=&quot;black&quot;) self.frame.place(x=0, y=0) self.frame.bind(&quot;&lt;Button-1&gt;&quot;, self.pressed) self.frame.bind(&quot;&lt;ButtonRelease-1&gt;&quot;, self.release) def pressed(self, e): self.frame.bind(&quot;&lt;Motion&gt;&quot;, self.move) def release(self, e): self.frame.unbind(&quot;&lt;Motion&gt;&quot;) def move(self, event: tk.Event): m_pos_x = root.winfo_pointerx() - root.winfo_rootx() m_pos_y = root.winfo_pointery() - root.winfo_rooty() self.frame.place(x=m_pos_x, y=m_pos_y) root = tk.Tk() root.geometry('1200x1000') cl = SimpleClass() root.mainloop() </code></pre> <p>I am really interested why this happens and how can I fix this. Maybe there is a function that will freeze place method until window has finished all updates or something like this. Thanks.</p> <p>P.S. Don't hate me for using the tkinter library for purposes it was not intended for.</p>
<python><python-3.x><tkinter>
2023-07-22 00:08:32
2
610
Danya K
76,741,815
270,638
Using Selenium to download PDFs from relative links
<p>I'm using Selenium Chrome WebDriver to try to capture and download a bunch of files on a website for my community organization. The website has about 2,700 PDF files uploaded over many years in various places. They are linked to from various pages on the site, e.g. here is an example</p> <p><a href="https://i.sstatic.net/zEzNd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zEzNd.png" alt="Sample Link to PDF" /></a></p> <p>Note a couple of things:</p> <ul> <li>The URL to the file is always relative.</li> <li>If I try to use the full URL in a Selenium script, e.g.</li> </ul> <p><code>driver.get(&quot;https://engage.goenumerate.com/s/bpha/files/1118/dyn291835/Bill%20Point%20Water%20System%20Replacement%20Drawings.pdf&quot;) </code></p> <p>I get a 404 from the website. It appears they have in some server-side filter blocked direct download of the URLs.</p> <p>If in an interactive session, I click on the link it opens the PDF in a new tab (<code>target=_blank</code>).</p> <p>I would like to capture the contents of the PDF in my Python code and save the PDF to a local directory, and then move on to the next file.</p> <p>I have a CSV list of these:</p> <p><a href="https://i.sstatic.net/VQXdh.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VQXdh.png" alt="CSV of files to download" /></a></p> <p>I can write Selenium code to find and click the links on the pages with the links to the files, but that will just open the PDFs in the Chrome WebDriver browser - not give me the PDF.</p> <p>Thanks for any tips.</p>
<python><selenium-webdriver><selenium-chromedriver>
2023-07-21 23:57:07
2
1,029
Mike Kelly
76,741,531
5,652,080
How does multi-dimensional matrix indexing actually work under the hood?
<p>Hard to write that title, sorry.</p> <p>I'm following a video and see that I can Index matrix C (below) with matrix X. But I don't understand the mechanic here. Given my lack of understanding, I tried to reproduce it with smaller matrices just to visualize it for myself...but I can't.</p> <p>What is different about <code>C</code> and <code>X</code> matrices here vs <code>nums</code> and <code>indexers</code> matrices? In both cases, the sizes are different, the indexing matrix is larger than the one being indexed, and the values in the indexing matrix are different than those in the indexed matrix:</p> <p><a href="https://i.sstatic.net/LadVa.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/LadVa.png" alt="[[1,2,3],[4,5,6],[7,8,9]]" /></a></p>
<python><pytorch>
2023-07-21 22:15:35
1
690
Sam Dillard
76,741,498
361,742
Odoo 14 periodic actions are failing with stack trace
<p>Odoo 14's scheduled actions are failing after upgrade from 13th version. Can somebody suggest a way to debug it deeper or even fix?</p> <p>Just one example of the error:</p> <pre><code>Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3.8/threading.py&quot;, line 890, in _bootstrap Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self._bootstrap_inner() Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3.8/threading.py&quot;, line 932, in _bootstrap_inner Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self.run() Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3.8/threading.py&quot;, line 870, in run Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self._target(*self._args, **self._kwargs) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/service/server.py&quot;, line 432, in target Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self.cron_thread(i) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/service/server.py&quot;, line 413, in cron_thread Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: ir_cron._acquire_job(db_name) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_cron.py&quot;, line 274, in _acquire_job Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: cls._process_jobs(db_name) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_cron.py&quot;, line 238, in _process_jobs Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: registry[cls._name]._process_job(job_cr, job, lock_cr) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_cron.py&quot;, line 148, in _process_job Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: cron._callback(job['cron_name'], job['ir_actions_server_id'], job['id']) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_cron.py&quot;, line 110, in _callback Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self.env['ir.actions.server'].browse(server_action_id).run() Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_actions.py&quot;, line 632, in run Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: res = runner(run_self, eval_context=eval_context) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/base/models/ir_actions.py&quot;, line 501, in _run_action_code_multi Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: safe_eval(self.code.strip(), eval_context, mode=&quot;exec&quot;, nocopy=True) # nocopy allows to return 'action' Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/tools/safe_eval.py&quot;, line 331, in safe_eval Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: return unsafe_eval(c, globals_dict, locals_dict) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;&quot;, line 1, in &lt;module&gt; Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/stock/models/stock_rule.py&quot;, line 555, in run_scheduler Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self._run_scheduler_tasks(use_new_cursor=use_new_cursor, company_id=company_id) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/point_of_sale/models/pos_session.py&quot;, line 1184, in _run_scheduler_tasks Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: super(ProcurementGroup, self)._run_scheduler_tasks(use_new_cursor=use_new_cursor, company_id=company_id) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/product_expiry/models/production_lot.py&quot;, line 129, in _run_scheduler_tasks Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: super(ProcurementGroup, self)._run_scheduler_tasks(use_new_cursor=use_new_cursor, company_id=company_id) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/stock/models/stock_rule.py&quot;, line 526, in _run_scheduler_tasks Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: orderpoints.sudo()._procure_orderpoint_confirm(use_new_cursor=use_new_cursor, company_id=company_id, raise_user_error=False) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/stock/models/stock_orderpoint.py&quot;, line 500, in _procure_orderpoint_confirm Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self.env['procurement.group'].with_context(from_orderpoint=True).run(procurements, raise_user_error=raise_user_error) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/stock/models/stock_rule.py&quot;, line 426, in run Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: rule = self._get_rule(procurement.product_id, procurement.location_id, procurement.values) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/stock/models/stock_rule.py&quot;, line 482, in _get_rule Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: result = self._search_rule(values.get('route_ids', False), product_id, values.get('warehouse_id', False), domain) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/addons/stock/models/stock_rule.py&quot;, line 470, in _search_rule Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: res = Rule.search(expression.AND([[('route_id', 'in', warehouse_routes.ids)], domain]), order='route_sequence, sequence', limit=1) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/models.py&quot;, line 1709, in search Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: return res if count else self.browse(res) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/models.py&quot;, line 4990, in browse Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: if not ids: Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/osv/query.py&quot;, line 172, in __bool__ Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: return bool(self._result) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/tools/func.py&quot;, line 26, in __get__ Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: value = self.fget(obj) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/osv/query.py&quot;, line 165, in _result Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: self._cr.execute(query_str, params) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;&lt;decorator-gen-3&gt;&quot;, line 2, in execute Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/sql_db.py&quot;, line 101, in check Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: return f(self, *args, **kwargs) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: File: &quot;/usr/lib/python3/dist-packages/odoo/sql_db.py&quot;, line 301, in execute Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: res = self._obj.execute(query, params) Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: 2023-07-21 21:58:19,127 112133 INFO ? odoo.service.server: Initiating server reload Jul 21 21:58:19 ip-172-31-33-59 odoo[112133]: 2023-07-21 21:58:19,299 112133 INFO ? odoo.sql_db: ConnectionPool(used=0/count=0/max=80): Closed 6 connections </code></pre> <p>But it is failing constantly and reloads every minute, which makes server close to impossible to use.</p>
<python><odoo-14>
2023-07-21 22:07:06
2
409
onorua
76,741,410
2,195,440
How to invoke Github Copilot programmatically?
<p>I am currently exploring GitHub Copilot, and I am interested in using it programmatically, i.e., invoking it from code. As I understand, GitHub Copilot is an IDE plugin, which makes me wonder how it can be automated or controlled programmatically. We know Copilot uses OpenAI models behind the scene as an LLM.</p> <p>GitHub Copilot does not provide API access to control it programmatically.</p> <p>Clarification:</p> <ul> <li><p>It's important to note that the plugin, once downloaded and installed, completes my code automatically. Copilot used the OpenAI models such as gpt-3.5 or gpt-4 behind the scene. I know very well the OpenAI chat or text completion models.<strong>So that's not my question</strong></p> </li> <li><p>My question is how to <strong>capture the top three suggestions provided by Copilot</strong> in an automated fashion.</p> </li> <li><p>For example, for any given autocomplete task to Copilot, the task is to record the code suggestions and save them into a file.</p> </li> </ul>
<python><github-copilot>
2023-07-21 21:45:43
4
3,657
Exploring
76,741,275
11,131,433
Python Tuple vs List vs Array memory consumption
<p>I've been reading Fluent code by Luciano Ramalho and in the chapter 'Overview of Built-in Sequences' when describing C struct behind float he states:</p> <blockquote> <p>&quot;.. That's why an array of floats is much more compact than a tuple of floats: the array is a single object holding the raw values of a float, while the tuple consists of several objects - the tuple itself and each float object contained in it&quot;.</p> </blockquote> <p>So I decided to confirm this and wrote a simple script.</p> <pre><code>import sys import array array_obj = array.array(&quot;d&quot;, []) list_obj = [] tuple_obj = tuple() arr_delta = [] tuple_delta = [] list_delta = [] for i in range(16): s1 = sys.getsizeof(array_obj) array_obj.append(float(i)) s2 = sys.getsizeof(array_obj) arr_delta.append(s2-s1) s1 = sys.getsizeof(tuple_obj) tuple_obj = tuple([j for j in range(i+1)]) s2 = sys.getsizeof(tuple_obj) tuple_delta.append(s2-s1) s1 = sys.getsizeof(list_obj) list_obj.append(i) s2 = sys.getsizeof(list_obj) list_delta.append(s2-s1) print(&quot;Float size: &quot;, sys.getsizeof(1.0)) print(&quot;Array size: &quot;, sys.getsizeof(array_obj)) print(&quot;Tuple size: &quot;, sys.getsizeof(tuple_obj)) print(&quot;List size: &quot;, sys.getsizeof(list_obj)) print(&quot;Array allocations: &quot;, arr_delta) print(&quot;Tuple allocations: &quot;, tuple_delta) print(&quot;List allocations: &quot;, list_delta) </code></pre> <p>Which produces the following output on my system (python 3.11.4, 64 bit):</p> <pre><code>Float size: 24 Array size: 208 Tuple size: 168 List size: 184 Array allocations: [32, 0, 0, 0, 32, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0] Tuple allocations: [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8] List allocations: [32, 0, 0, 0, 32, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0] </code></pre> <p>Allocations lists is how size of object was changing over time after appending new float (tuple recreates each time)</p> <p>So, my questions are:<br /> Aren't lists and tuples supposed to hold pointers to PyFloatObjects when arrays hold pointers to floats?<br /> Or is it peculiarity of sys.getsizeof?<br /> As can be seen <a href="https://stackoverflow.com/questions/46664007/why-do-tuples-take-less-space-in-memory-than-lists">in this SO question</a>, C structs behind tuple and list contains arrays of pointers to PyFloatObject.</p> <p>Thanks!</p>
<python><arrays><list><tuples><python-internals>
2023-07-21 21:12:18
1
338
Andrey
76,741,210
17,274,113
df.rename() appears to be altering the values stored in the associated column
<p>I have two dataframes ['stations_live'] and ['stations_master']. They have columns containing the same information type (station name, latitude, longitude etc..) but named differently. I am trying to rename the column headers of station_live to match those in stations_master:</p> <pre><code>stations_live_df.rename(columns={'full_station_name':'Station', 'lat':'Latitude', 'lon':'Longitude', 'is_charging_station':'E-Station?'}, inplace = True) </code></pre> <p>However, this seems to result in the actual values in the &quot;full_station_name&quot; column being altered (&quot;1st &amp; Main&quot; instead of &quot;0001 1st &amp; Main&quot;). Here, the #### station code is important to generate a match with the other dataframe.</p> <p>This (station_id + station_name) format was achieved by combining two columns within the dataset</p> <pre><code>stations_live_df['station_id'] = stations_live_df['station_id'].astype(str) stations_live_df['full_station_name'] = stations_live_df['station_id'] + &quot; &quot; + stations_live_df['name'] </code></pre> <p>Imedaitiely before running the <code>df.rename()</code> command, the 1st item in the &quot;full_station_names&quot; column is &quot;0001 1st &amp; Main&quot; as it should be. Immediately after that command, it reverts to &quot;1st &amp; Main&quot; and therefore I get 0 matched to the other dataframe.</p> <p>Please let me know what is going on here if you know. I am VERY confused.</p> <p>#------------------------------------------------------------------------</p> <p>Attempt to reproduce outside of script here DOES NOT reproduce the issue but is the method I use in the real script but with made up dfs.</p> <pre><code> #dfs stations_live_df = pd.DataFrame({&quot;station_id&quot;: [&quot;0001&quot;, &quot;0002&quot;, &quot;0003&quot;], &quot;name&quot;: [&quot;1st &amp; Main&quot;, &quot;2nd &amp; Main&quot;, &quot;3rd &amp; Main&quot;]}) stations_master = pd.DataFrame({&quot;Station&quot;: [&quot;0001 1st &amp; Main&quot;, &quot;0002 2nd &amp; Main&quot;, &quot;0003 3rd &amp; Main&quot;]}) #merge id and name in live df stations_live_df['full_station_name'] = stations_live_df['station_id'] + &quot; &quot; + stations_live_df['name'] #rename stations_live_df columns to reflect those in stations master stations_live_df.rename(columns = {'full_station_name':'Station'}, inplace = True) # Get the values in the specified column from both DataFrames live_stations = stations_live_df['Station'].tolist() master_stations = stations_master['Station'].tolist() # Find the values in df1 that do not have a match in df2 new_stations = [value for value in live_stations if value not in master_stations] print(len(new_stations)) </code></pre>
<python><pandas><rename>
2023-07-21 21:00:40
0
429
Max Duso
76,741,158
7,082,205
Python regex.findall not finding all matches of shorter length
<p>How can I find all matches that don't necessarily consume all characters with <code>*</code> and <code>+</code> modifiers?</p> <pre class="lang-py prettyprint-override"><code>import regex as re matches = re.findall(&quot;^\d+&quot;, &quot;123&quot;) print(matches) # actual output: ['123'] # desired output: ['1', '12', '123'] </code></pre> <p>I need the matches to be anchored to the start of the string (hence the <code>^</code>), but the <code>+</code> doesn't even seem to be considering shorter-length matches. I tried adding <code>overlapped=True</code> to the <code>findall</code> call, but that does not change the output.</p> <p>Making the regex non-greedy (<code>^\d+?</code>) makes the output <code>['1']</code>, <code>overlapped=True</code> or not. Why does it not want to keep searching further?</p> <p>I could always make shorter substrings myself and check those with the regex, but that seems rather inefficient, and surely there must be a way for the regex to do this by itself.</p> <pre class="lang-py prettyprint-override"><code>s = &quot;123&quot; matches = [] for length in range(len(s)+1): matches.extend(re.findall(&quot;^\d+&quot;, s[:length])) print(matches) # output: ['1', '12', '123'] # but clunky :( </code></pre> <p><strong>Edit: the <code>^\d+</code> regex is just an example, but I need it to work for any possible regex. I should have stated this up front, my apologies.</strong></p>
<python><regex><findall>
2023-07-21 20:50:39
4
476
Artie Vandelay
76,741,102
320,437
Type narrowing by a generic function in Python
<p>I need to narrow type of a class attribute. It is typed as <code>MyType | None</code> and it is expected not be <code>None</code> in a specific part of the code. I am using this attribute in a generator expression so I cannot directly use a condition with <code>raise</code> or <code>assert</code> to narrow it.</p> <p>Is the code below the correct way to define a generic type-narrowing function? I.e. define argument as a generic type in union with <code>None</code> but the return type just as the generic type.</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar ValueT = TypeVar('ValueT') def fail_if_none(value: ValueT | None) -&gt; ValueT: &quot;&quot;&quot;Raises an exception if the value is None. Args: value: The value to check. Raises: ValueError: If the value is None. Returns: The value, guaranteed to not be None. &quot;&quot;&quot; if value is None: raise ValueError(&quot;Value cannot be None.&quot;) return value </code></pre> <p>Does the code guarantee that the return type <code>ValueT</code> will always be seen as not including <code>None</code>? Is not there a better way?</p> <hr /> <p>Here is an example showing how to use the type-narrowing function:</p> <pre class="lang-py prettyprint-override"><code>def takes_int(value: int) -&gt; int: &quot;&quot;&quot;Take an int and return it.&quot;&quot;&quot; return value sequence: list[int | None] = [1, 2, 3, 4, None, 5] values1 = (takes_int(value) for value in sequence) # error: Argument 1 to &quot;takes_int&quot; has incompatible type &quot;int | None&quot;; # expected &quot;int&quot; [arg-type] values2 = (takes_int(fail_if_none(value)) for value in sequence) # OK, no type-checker errors </code></pre> <p>I have tested the code with mypy and Pyright. In both type-checkers it seems to work the way I wanted.</p>
<python><generics><python-typing><type-narrowing>
2023-07-21 20:40:50
0
1,573
pabouk - Ukraine stay strong
76,740,952
4,865,723
Move QDialog after second resizeEvent in PyQt
<h1>Introduction and short problem description</h1> <p>The example contains resizing a <code>QScrollArea</code> and moving a <code>QDialog</code> the the screens centere. This two things work well in isolation. But combining them is the problem I can not solve.</p> <p>While creating the dialog I want to center it to the screen but before that the dialog need &quot;time&quot; to dynamically readjust its (content) size. Technically this are two <code>resizeEvents()</code> I need to wait before centering the <code>QDialog</code>.</p> <h1>Detailed description of the problem</h1> <p>I want to the <code>QDialog</code> be centered on screen when it is created. It don't need to stick there. After creation the user is free to place it elsewhere.</p> <p>I do resize the width of the <code>QScrollArea</code> to make it fit to its content and prevent the need for horizontal scrolling. Only the (usual) vertical scrollbar should appear. Keep in mind that resizing the <code>QScrollArea</code> also resize the whole <code>QDialog</code>. The needed width is calculated based on the child widgets in that scroll area. Before calculation they need to be shown. That is why I do it in <code>showEvent()</code> handler. Maybe there is a better solution for this aspect?</p> <p>While building the <code>QDialog</code> two resize events happen. The first happens when the dialog is drawn the first time (the <code>show()</code> or <code>exec()</code> call). The second happens when I modify the width of the <code>QScrollArea</code> which also affects the width of the <code>QDialog</code>.</p> <p>Where and how should I call the <code>QDialog.move()</code>?</p> <p>Because of my explanation I'm able to use <code>showEvent()</code> handler for this. It has no effect because the dialog is not yet resized by its <code>QScrollArea</code> child. The center of the <code>QDialog</code> can't be calculated at this point in the programm flow because its size is not yet finished.</p> <p>It works when using <code>resizeEvent()</code>. But the shortcomming is that centering the <code>QDialog</code> do happen every time even when the user just resize the window via its mouse.</p> <h1>Workarounds</h1> <p>I have two workarounds in mind that might work but I don't like them because they are not elegant not real solutions.</p> <ol> <li>Use a flag or counter in <code>resizeEvent()</code> if and how often the <code>_center_to_screen()</code> was called to prevent multiple calls to it.</li> <li>Use a single shot <code>QTime()</code> guessing some milliseconds and call <code>_center_to_screen()</code> really only once.</li> </ol> <p>Thank you so much for reading so far.</p> <h1>Minimal working example</h1> <pre><code>#!/usr/bin/env python3 import sys from PyQt5.QtCore import * from PyQt5.QtWidgets import * class CenteredDialog(QDialog): def __init__(self): super().__init__() # Scroll area with language widget scroll = QScrollArea(self) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scroll.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) scroll.setWidget(self._widget()) self._scroll = scroll # Button &quot;Apply&quot; button = QDialogButtonBox(QDialogButtonBox.Apply) button.clicked.connect(self.accept) # Dialog layout layout = QVBoxLayout(self) layout.addWidget(scroll) layout.addWidget(button) def _widget(self): &quot;&quot;&quot;Widget with 4 x 25 grid layouted labels&quot;&quot;&quot; grid = QGridLayout() wdg = QWidget(self) wdg.setLayout(grid) for col in range(1, 5): for row in range(1, 26): grid.addWidget( QLabel(f'{col} x {row} | Lorem ipsum dolor sit', self), row, col) return wdg def showEvent(self, e): print('Event: show') super().showEvent(e) # Width of the scroll area is expanded to fit its content. widget_width = self._scroll.widget().sizeHint().width() scrollbar_width = self._scroll.verticalScrollBar().sizeHint().width() # This cause resizeEvent self._scroll.setMinimumWidth(widget_width + scrollbar_width) # This don't work here. # self._center_to_screen() def resizeEvent(self, e): print('Event: resize') # Works somehow but Is called multiple times self._center_to_screen() def _center_to_screen(self): &quot;&quot;&quot;Move the dialog to the screens center. Credits: https://pythonprogramminglanguage.com/pyqt5-center-window &quot;&quot;&quot; geo = QApplication.primaryScreen().availableGeometry() rec = self.frameGeometry() rec.moveCenter(geo.center()) self.move(rec.topLeft()) class Window(QMainWindow): def __init__(self, parent=None): super().__init__(parent) def showEvent(self, e): dlg = CenteredDialog() dlg.exec() if __name__ == &quot;__main__&quot;: app = QApplication(sys.argv) win = Window() win.show() sys.exit(app.exec()) </code></pre>
<python><qt><pyqt>
2023-07-21 20:08:30
0
12,450
buhtz
76,740,846
4,244,609
Poetry refuses to install wheel file while pip installs
<p>I'm trying to install local wheel file using Poetry v 1.5.1 by adding the following line to pyproject.toml in [tool.poetry.dependencies] section:</p> <pre><code>my_package = {file = &quot;/home/user/package.whl&quot;} </code></pre> <p>and it ends up with the following error:</p> <pre><code>Because my_package (0.1.0) @ file:///home/user/package.whl depends on shapely (&gt;=2.0.1,&lt;3.0.0) which doesn't match any versions, my_package is forbidden. </code></pre> <p>If to run</p> <pre><code>poetry add shapelly==2.0.1 </code></pre> <p>It works well. If to re-create environment it starts to complain on another package (not shapely) in the same fashon. And finally,</p> <pre><code>pip install /home/user/package.whl </code></pre> <p>works well without any problems.</p> <p>What is wrong with Poetry here?</p>
<python><pip><python-poetry>
2023-07-21 19:46:33
0
1,483
Ivan Sudos
76,740,827
2,147,331
Why do parentheses here result in an error?
<p>I was getting an error</p> <pre><code>cv.imwrite(f'spidershow{i+1}.png',canvas[i*height:i*(height+1)-1,0:500]) cv2.error: OpenCV(4.8.0) /Users/runner/work/opencv-python/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:787: error: (-215:Assertion failed) !_img.empty() in function 'imwrite' </code></pre> <p>from the code</p> <pre><code>import cv2 as cv height = 2048 canvas = np.zeros((height*30,500,3), dtype=np.uint8) for i in range(30): cv.imwrite(f'spidershow{i+1}.png',canvas[i*height:i*(height+1)-1,0:500]) </code></pre> <p>when I changed the last line to</p> <pre><code>cv.imwrite(f'spidershow{i+1}.png',canvas[i*height:i*height+height-1,0:500]) </code></pre> <p>my code worked correctly.</p> <p>Why did removing the parentheses fix my code? I'm running the latest version of python.</p> <p>Thank you</p>
<python><python-3.x>
2023-07-21 19:43:50
1
1,101
jfa
76,740,695
1,585,652
Why does my connection to a Kafka server running on Linux fail when the client is running on Windows?
<p>I am running Apache Kafka version 3.1.0 on a Linux server (currently only a single-server setup).</p> <p>The server.properties looks like this (comments stripped out for brevity):</p> <pre><code>broker.id=0 num.network.threads=3 num.io.threads=8 socket.send.buffer.bytes=102400 socket.receive.buffer.bytes=102400 socket.request.max.bytes=104857600 log.dirs=/var/lib/kafka num.partitions=1 num.recovery.threads.per.data.dir=1 offsets.topic.replication.factor=1 transaction.state.log.replication.factor=1 transaction.state.log.min.isr=2 log.retention.hours=24 log.segment.bytes=1073741824 log.retention.check.interval.ms=300000 zookeeper.connect=server.dev.company.local:2181 zookeeper.connection.timeout.ms=6000 group.initial.rebalance.delay.ms=3 auto.create.topics.enable=false inter.broker.protocol.version=3.1 </code></pre> <p>I can connect and interact successfully from another Linux server on the network, using kafka-python:</p> <pre><code>&gt;&gt;&gt; from kafka import KafkaClient &gt;&gt;&gt; client = KafkaClient(bootstrap_servers=['server.dev.company.local:9092']) &gt;&gt;&gt; client.cluster.brokers() set([BrokerMetadata(nodeId='bootstrap-0', host='server.dev.company.local', port=9092, rack=None)]) </code></pre> <p>If I attempt the same connection from a Windows server on the network, this is what I see (I can't even successfully create the KafkaClient):</p> <pre><code>&gt;&gt;&gt; from kafka import KafkaClient &gt;&gt;&gt; client = KafkaClient(bootstrap_servers=['server.dev.company.local:9092']) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;D:\python\Lib\site-packages\kafka\client_async.py&quot;, line 244, in __init__ self.config['api_version'] = self.check_version(timeout=check_timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;D:\python\Lib\site-packages\kafka\client_async.py&quot;, line 909, in check_version version = conn.check_version(timeout=remaining, strict=strict, topics=list(self.config['bootstrap_topics_filter'])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;D:\python\Lib\site-packages\kafka\conn.py&quot;, line 1254, in check_version selector.register(self._sock, selectors.EVENT_READ) File &quot;D:\python\Lib\selectors.py&quot;, line 299, in register key = super().register(fileobj, events, data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;D:\python\Lib\selectors.py&quot;, line 238, in register key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;D:\python\Lib\selectors.py&quot;, line 225, in _fileobj_lookup return _fileobj_to_fd(fileobj) ^^^^^^^^^^^^^^^^^^^^^^^ File &quot;D:\python\Lib\selectors.py&quot;, line 39, in _fileobj_to_fd raise ValueError(&quot;Invalid file object: &quot; ValueError: Invalid file object: None </code></pre> <p>Similarly, if I try to create a Producer to send to the server using the Confluent.Kafka .NET library, I get the following output as soon as the code to build the Producer runs:</p> <pre><code>%6|1689966866.156|FAIL|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Disconnected while requesting ApiVersion: might be caused by incorrect security.protocol configuration (connecting to a SSL listener?) or broker version is &lt; 0.10 (see api.version.request) (after 0ms in state APIVERSION_QUERY) %3|1689966866.157|ERROR|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: 1/1 brokers are down %3|1689966866.157|ERROR|CLIENT-MACHINE#producer-1| [thrd:app]: CLIENT-MACHINE#producer-1: server.dev.company.local:9092/bootstrap: Disconnected while requesting ApiVersion: might be caused by incorrect security.protocol configuration (connecting to a SSL listener?) or broker version is &lt; 0.10 (see api.version.request) (after 0ms in state APIVERSION_QUERY) </code></pre> <p>There is an obvious problem with this output...I am not connecting to an SSL listener, and the broker is &gt; 0.10 (it's 3.1.0).</p> <p>I'm not sure how to even begin debugging this.</p> <p>One thing that was suggested elsewhere was to explicitly set advertised.listeners in server.properties (although why that would only affect clients running on Windows, I have no idea). So I did try that:</p> <pre><code>advertised.listeners=PLAINTEXT://server.dev.company.local:9092 </code></pre> <p>It did not make a difference.</p> <p><strong>Edit</strong>:</p> <p>I have the exact same server setup on another Linux server, which I <strong>can</strong> connect to from the Windows client.</p> <p>I have verified via Telnet that I can connect to the server/port from the Windows machine (it's not a firewall issue).</p> <p>It seems like there must be something going wrong with the bootstrap, but I can't figure out a good way to actually debug it.</p> <p><strong>Edit 2</strong>:</p> <p>Here is the client output with full debug:</p> <pre><code>%7|1690243709.297|BROKER|CLIENT-MACHINE#producer-1| [thrd:app]: server.dev.company.local:9092/bootstrap: Added new broker with NodeId -1 %7|1690243709.297|BRKMAIN|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Enter main broker thread %7|1690243709.297|CONNECT|CLIENT-MACHINE#producer-1| [thrd:app]: server.dev.company.local:9092/bootstrap: Selected for cluster connection: bootstrap servers added (broker has 0 connection attempt(s)) %7|1690243709.297|BRKMAIN|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Enter main broker thread %7|1690243709.297|CONNECT|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Received CONNECT op %7|1690243709.297|INIT|CLIENT-MACHINE#producer-1| [thrd:app]: librdkafka v2.2.0 (0x20200ff) CLIENT-MACHINE#producer-1 initialized (builtin.features gzip,snappy,ssl,sasl,regex,lz4,sasl_gssapi,sasl_plain,sasl_scram,plugins,zstd,sasl_oauthbearer,http,oidc, SSL ZLIB SNAPPY ZSTD CURL SASL_SCRAM SASL_OAUTHBEARER PLUGINS HDRHISTOGRAM, debug 0xfffff) %7|1690243709.297|STATE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker changed state INIT -&gt; TRY_CONNECT %7|1690243709.297|CONF|CLIENT-MACHINE#producer-1| [thrd:app]: Client configuration: %7|1690243709.297|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: Broadcasting state change %7|1690243709.297|CONF|CLIENT-MACHINE#producer-1| [thrd:app]: client.id = CLIENT-MACHINE %7|1690243709.297|CONNECT|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: broker in state TRY_CONNECT connecting %7|1690243709.297|CONF|CLIENT-MACHINE#producer-1| [thrd:app]: client.software.name = confluent-kafka-dotnet %7|1690243709.297|STATE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker changed state TRY_CONNECT -&gt; CONNECT %7|1690243709.297|CONF|CLIENT-MACHINE#producer-1| [thrd:app]: client.software.version = 2.2.0 %7|1690243709.297|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: Broadcasting state change %7|1690243709.297|CONF|CLIENT-MACHINE#producer-1| [thrd:app]: metadata.broker.list = server.dev.company.local:9092 %7|1690243709.297|CONF|CLIENT-MACHINE#producer-1| [thrd:app]: debug = generic,broker,topic,metadata,feature,queue,msg,protocol,cgrp,security,fetch,interceptor,plugin,consumer,admin,eos,mock,assignor,conf,all %7|1690243709.297|CONF|CLIENT-MACHINE#producer-1| [thrd:app]: dr_msg_cb = 00007FFA5ED733A4 %7|1690243709.300|CONNECT|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Connecting to ipv4#10.100.224.29:9092 (plaintext) with socket 1160 %7|1690243709.313|CONNECT|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Connected to ipv4#10.100.224.29:9092 %7|1690243709.313|CONNECTED|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Connected (#1) %7|1690243709.313|FEATURE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Updated enabled protocol features +ApiVersion to ApiVersion %7|1690243709.313|STATE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker changed state CONNECT -&gt; APIVERSION_QUERY %7|1690243709.313|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: Broadcasting state change %7|1690243709.314|SEND|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Sent ApiVersionRequest (v3, 51 bytes @ 0, CorrId 1) %7|1690243709.315|FAIL|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Disconnected while requesting ApiVersion: might be caused by incorrect security.protocol configuration (connecting to a SSL listener?) or broker version is &lt; 0.10 (see api.version.request) (after 1ms in state APIVERSION_QUERY) (_TRANSPORT) %6|1690243709.315|FAIL|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Disconnected while requesting ApiVersion: might be caused by incorrect security.protocol configuration (connecting to a SSL listener?) or broker version is &lt; 0.10 (see api.version.request) (after 1ms in state APIVERSION_QUERY) %7|1690243709.315|FEATURE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Updated enabled protocol features -ApiVersion to %7|1690243709.315|STATE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker changed state APIVERSION_QUERY -&gt; DOWN %3|1690243709.315|ERROR|CLIENT-MACHINE#producer-1| [thrd:app]: CLIENT-MACHINE#producer-1: server.dev.company.local:9092/bootstrap: Disconnected while requesting ApiVersion: might be caused by incorrect security.protocol configuration (connecting to a SSL listener?) or broker version is &lt; 0.10 (see api.version.request) (after 1ms in state APIVERSION_QUERY) %3|1690243709.315|ERROR|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: 1/1 brokers are down %7|1690243709.317|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: Broadcasting state change %7|1690243709.317|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Purging bufq with 1 buffers %7|1690243709.318|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Purging bufq with 0 buffers %7|1690243709.318|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Updating 0 buffers on connection reset %7|1690243709.318|STATE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker changed state DOWN -&gt; INIT %7|1690243709.319|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: Broadcasting state change %7|1690243709.319|DESTROY|CLIENT-MACHINE#producer-1| [thrd:app]: Terminating instance (destroy flags none (0x0)) %7|1690243709.319|STATE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker changed state INIT -&gt; TRY_CONNECT %7|1690243709.319|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: Broadcasting state change %7|1690243709.319|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:app]: Interrupting timers %7|1690243709.320|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:app]: Sending TERMINATE to internal main thread %7|1690243709.320|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:app]: Joining internal main thread %7|1690243709.321|RECONNECT|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Delaying next reconnect by 192ms %7|1690243709.320|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:main]: Internal main thread terminating %7|1690243709.321|DESTROY|CLIENT-MACHINE#producer-1| [thrd:main]: Destroy internal %7|1690243709.321|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:main]: Broadcasting state change %7|1690243709.321|DESTROY|CLIENT-MACHINE#producer-1| [thrd:main]: Removing all topics %7|1690243709.322|DESTROY|CLIENT-MACHINE#producer-1| [thrd:main]: Sending TERMINATE to server.dev.company.local:9092/bootstrap %7|1690243709.322|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:main]: Purging reply queue %7|1690243709.322|TERM|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Received TERMINATE op in state TRY_CONNECT: 2 refcnts, 0 toppar(s), 0 active toppar(s), 0 outbufs, 0 waitresps, 0 retrybufs %7|1690243709.322|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:main]: Decommissioning internal broker %7|1690243709.322|FAIL|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Client is terminating (after 2ms in state TRY_CONNECT) (_DESTROY) %7|1690243709.323|STATE|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker changed state TRY_CONNECT -&gt; DOWN %7|1690243709.323|BROADCAST|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: Broadcasting state change %7|1690243709.322|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:main]: Join 2 broker thread(s) %7|1690243709.322|TERM|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Received TERMINATE op in state INIT: 2 refcnts, 0 toppar(s), 0 active toppar(s), 0 outbufs, 0 waitresps, 0 retrybufs %7|1690243709.323|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Purging bufq with 0 buffers %7|1690243709.324|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Purging bufq with 0 buffers %7|1690243709.323|FAIL|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Client is terminating (after 27ms in state INIT) (_DESTROY) %7|1690243709.324|STATE|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Broker changed state INIT -&gt; DOWN %7|1690243709.324|BROADCAST|CLIENT-MACHINE#producer-1| [thrd::0/internal]: Broadcasting state change %7|1690243709.324|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Updating 0 buffers on connection reset %7|1690243709.325|BRKTERM|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: terminating: broker still has 2 refcnt(s), 0 buffer(s), 0 partition(s) %7|1690243709.325|BUFQ|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Purging bufq with 0 buffers %7|1690243709.325|FAIL|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Broker handle is terminating (after 2ms in state DOWN) (_DESTROY) %7|1690243709.326|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Purging bufq with 0 buffers %7|1690243709.325|BUFQ|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Purging bufq with 0 buffers %7|1690243709.327|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Purging bufq with 0 buffers %7|1690243709.327|BUFQ|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Updating 0 buffers on connection reset %7|1690243709.328|BRKTERM|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: terminating: broker still has 2 refcnt(s), 0 buffer(s), 0 partition(s) %7|1690243709.327|BUFQ|CLIENT-MACHINE#producer-1| [thrd:server.dev.company.local:9092/bootstrap]: server.dev.company.local:9092/bootstrap: Updating 0 buffers on connection reset %7|1690243709.328|TERMINATE|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Handle is terminating in state DOWN: 1 refcnts (0000025AA5DD5C70), 0 toppar(s), 0 active toppar(s), 0 outbufs, 0 waitresps, 0 retrybufs: failed 0 request(s) in retry+outbuf %7|1690243709.328|FAIL|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Broker handle is terminating (after 3ms in state DOWN) (_DESTROY) %7|1690243709.328|BUFQ|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Purging bufq with 0 buffers %7|1690243709.329|BUFQ|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Purging bufq with 0 buffers %7|1690243709.329|BUFQ|CLIENT-MACHINE#producer-1| [thrd::0/internal]: :0/internal: Updating 0 buffers on connection reset %7|1690243709.329|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:main]: Internal main thread termination done %7|1690243709.329|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:app]: Destroying op queues %7|1690243709.330|TERMINATE|CLIENT-MACHINE#producer-1| [thrd:app]: Termination done: freeing resources </code></pre>
<python><linux><apache-kafka>
2023-07-21 19:21:42
0
1,997
jceddy
76,740,522
5,370,631
Get all subarrays of a list in a circle
<p>How to get all the sub arrays from a list where the last element continues with the first element as a circular list?</p> <pre><code>Array = [0,1,1,0,0,1] </code></pre> <p>Sub arrays of length 3</p> <pre><code>[0,1,1], [1,1,0], [1,0,0], [0,0,1], [0,1,0], [1,0,1] </code></pre>
<python>
2023-07-21 18:49:47
6
1,572
Shibu
76,740,449
713,200
How to grab a substring from a given string?
<p>Basically I have following strings and I want to grab a sub-string from them.</p> <pre class="lang-none prettyprint-override"><code>input: RT4_MANGO_AF output: MANGO input: RT4_DF5_WE_APPLE_AF output: APPLE input: TF_WE_BANANA_AF output: BANANA input: RT4_DF5_ORANGE_AF output: ORANGE </code></pre> <p>Note the hint here is that, the last 3 chars will remain <code>_AF</code> and I want to grab the sub-string before <code>_AF</code> and after the last-but-one <code>_</code> symbol.</p> <p>I have the following code which does the same, but I feel it's not optimal. Is there a way to optimize this code? or can I get optimized code?</p> <pre><code>sd = 'ER5_WE_APPLE_AF' m = sd[:-3] for i in range(len(m)): if m[i] == &quot;_&quot;: si = i else: continue m = m[si+1:] print(m) </code></pre>
<python><string><slice><string-operations>
2023-07-21 18:36:33
1
950
mac
76,740,401
4,873,885
What defines the import statement of python package?
<p>I have plenty of home-developed packages on Gitlab. Many of these package have setup.py but many of them don't.</p> <p>I also have projects on Gitlab that use these packages.</p> <p>My duty is to map the imports in all of these projects to the corresponding package. The problem is that most of the time, the packages that don't have setup.py have a project name slightly different from the statement used in the import</p> <p>Example:</p> <ul> <li>project called: abc-def, or abc def</li> <li>when installing: pip install company-name-abc-def</li> <li>when importing: abc_def</li> </ul> <p>Sometimes the name could be further (not only a dash or space)</p> <p>Is there a way to know the import name for each project? or the project name from the import statement?</p> <p>Could it be something set in the pyproject.toml? I read these files but there wasn't something obvious of this.</p>
<python><python-import><python-packaging><pyproject.toml>
2023-07-21 18:28:35
1
699
The Maestro
76,740,313
6,447,563
How to tell CMake to loosen the requirement for Python version?
<p>When I build OpenCV-dnn with CMake along this lines:</p> <p><a href="https://towardsdev.com/installing-opencv-4-with-cuda-in-ubuntu-20-04-fde6d6a0a367" rel="nofollow noreferrer">https://towardsdev.com/installing-opencv-4-with-cuda-in-ubuntu-20-04-fde6d6a0a367</a></p> <p>at the stage of cmake command I get</p> <pre><code>Could NOT find PythonLibs: Found unsuitable version “3.8.14”, but required is exact version “3.8.13”. </code></pre> <p>How can I change the requirement to “3.8.13-14” to try if it works? I don’t want to break the dev server just to try building the artefact. Or is this hardwired inside of the library?</p> <hr /> <p>Update. After installing conda with Python 3.8.13 I get</p> <p>After creating and activating Python 3.8.13 Anaconda environment I get</p> <pre><code>– Found PythonInterp: /home/sam/anaconda3/envs/cvdnn/bin/python3 (found suitable version “3.8.13”, minimum required is “3.2”) – Could NOT find PythonLibs: Found unsuitable version “3.8.14”, but required is exact version “3.8.13” (found /usr/lib/x86_64-linux-gnu/libpython3.8.so) </code></pre> <p>So PythonInterp finds the required version 3.8.13, but PythonLibs falls back to system version and cmake fails there.</p>
<python><cmake>
2023-07-21 18:12:31
1
1,233
sixtytrees
76,740,235
2,751,433
Decode non-ascii characters from numpy object
<pre><code>import numpy as np sentence = ['世界'] a = np.array(sentence, dtype=object).reshape(-1) b = [sentence for sentence in np.char.decode(a.astype(np.bytes_), 'UTF-8')] </code></pre> <p>I was trying to convert a <code>numpy.object</code> back to string, but it didn't work for non-ascii characters. Error was</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) </code></pre>
<python><numpy><unicode><decode><encode>
2023-07-21 17:59:54
1
673
flexwang
76,740,103
1,023,390
bitwise array manipulation with numpy
<p>I want to translate the following C++ expression</p> <pre><code>(i0?8:0) | (i1?4:0) | (i2?2:0) | (i3?1:0) </code></pre> <p>to python, where <code>i0</code>, <code>i1</code>, <code>i2</code>, and <code>i3</code> are <code>numpy.ndarray</code>s of bool (obtained via expressions like <code>i0 = x &lt; y</code>). What is the most efficient way to achieve that? My naive approach is</p> <pre><code>np.where(i0,8,0) | np.where(i1,4,0) | np.where(i2,2,0) | np.where(i3,1,0) </code></pre> <p>but is there are faster way?</p>
<python><numpy>
2023-07-21 17:40:17
3
45,824
Walter
76,739,991
8,160,293
Airflow Callbacks Not Initiating
<p>I have a yaml file that is processed in DagFactory to create a DAG to be executed in Airflow 2.5.1. It is setup to load a python file and execute a function based on the callbacks for <code>Start</code>, <code>Finish</code>, and <code>Failuer</code> based on <a href="https://github.com/ajbosco/dag-factory/blob/master/examples/example_dag_factory.yml" rel="nofollow noreferrer">this example</a>. The python file has these notifications sent to Slack. At this point I am only receiving this message in the logs at the start</p> <pre><code>{cli_action_loggers.py:65} DEBUG - Calling callbacks: [&lt;function default_action_log at 0x7ff073bd19d0&gt;] </code></pre> <p>and this at the end</p> <pre><code>{cli_action_loggers.py:83} DEBUG - Calling callbacks: [] </code></pre> <p>I would expect to see the message in the logs but I may be wrong. Also, the notifications do not reach Slack.</p> <p>Looking for help with either my python code or yaml based on the example on why Airflow will not execute the callback correctly or send to slack.</p> <p>YAMl</p> <pre><code>dag: default_args: owner: &quot;me&quot; depends_on_past: False retries: 0 retry_dely: datetime.timedelta(minutes=3) on_execute_callback_name: slack_notification_start_operator on_execute_callback_file: /home/airflow/provider/dags/dependencies/slack_notification.py on_success_callback_name: slack_notification_finish on_success_callback_file: //home/airflow/provider/dags/dependencies/slack_notification.py on_failure_callback_name: slack_notification_failed_callback on_failure_callback_file: /home/airflow/provider/dags/dependencies/slack_notification.py provide_context: True wait_for_downstream: True </code></pre> <p>Slack Python code</p> <pre><code>from datetime import datetime from airflow.hooks.base_hook import BaseHook from airflow.contrib.operators.slack_webhook_operator import SlackWebhookOperator from slack_sdk.webhook import WebhookClient SLACK_CONN_ID = &quot;my_slack_connection_id&quot; def slack_notification_start(**context): SLACK_WEBHOOK_TOKEN = BaseHook.get_connection(SLACK_CONN_ID).password SLACK_MSG = f&quot;&quot;&quot; :stopwatch: Airflow DAG initiated. *Dag*: {context['task_instance'].dag_id} *Execution Time*: {context['execution_date']} *Log Url*: {context['task_instance'].log_url} &quot;&quot;&quot; slack_notification_start_operator = SlackWebhookOperator( task_id='slack_notification_start', http_conn_id=SLACK_CONN_ID, webhook_token=SLACK_WEBHOOK_TOKEN, message=SLACK_MSG, username='airflow') return slack_notification_start_operator.execute(context=context) def slack_notification_failed_callback(context): SLACK_WEBHOOK_TOKEN = BaseHook.get_connection(SLACK_CONN_ID).password current_time = datetime.now() SLACK_MSG = f&quot;&quot;&quot; :red_circle: Task Failed. *Task*: {context['task_instance'].task_id} *Dag*: {context['task_instance'].dag_id} *Failure Time*: {current_time} *Log Url*: {context['task_instance'].log_url} &quot;&quot;&quot; slack_notification_fail_operator = SlackWebhookOperator( task_id='slack_notification_fail', http_conn_id=SLACK_CONN_ID, webhook_token=SLACK_WEBHOOK_TOKEN, message=SLACK_MSG, username='airflow') return slack_notification_fail_operator.execute(context=context) def slack_notification_finish(**context): SLACK_WEBHOOK_TOKEN = BaseHook.get_connection(SLACK_CONN_ID).password current_time = datetime.now() SLACK_MSG = f&quot;&quot;&quot; :white_check_mark: Airflow DAG finished. *Dag*: {context['task_instance'].dag_id} *Completion Time*: {current_time} *Log Url*: {context['task_instance'].log_url} &quot;&quot;&quot; slack_notification_finish_operator = SlackWebhookOperator( task_id='slack_notification_finish', http_conn_id=SLACK_CONN_ID, webhook_token=SLACK_WEBHOOK_TOKEN, message=SLACK_MSG, username='airflow') return slack_notification_finish_operator.execute(context=context) </code></pre>
<python><airflow><slack>
2023-07-21 17:21:27
0
559
Prof. Falken
76,739,894
13,944,524
Cancelling a Task in asyncio internals
<p>I know that <code>task.cancel()</code> doesn't do anything except setting a flag which says the task should be cancelled(<a href="https://github.com/python/cpython/blob/3.11/Lib/asyncio/tasks.py#L226C9-L226C33" rel="nofollow noreferrer">here</a>), so that in the next iteration of the event loop, a <code>CancelledError</code> gets thrown into the wrapped coroutine.</p> <p>Also I know that throwing exceptions into coroutines only happens at <code>await</code> statement calls. The coroutine has to be in that state.</p> <p>Now take a look at this:</p> <pre class="lang-py prettyprint-override"><code>import asyncio async def coro_1(): print(&quot;inside coro_1&quot;) try: await asyncio.sleep(0) except asyncio.CancelledError: print(&quot;cancellation error occurred&quot;) raise async def main(): print(&quot;inside main&quot;) new_task = asyncio.create_task(coro_1()) print(&quot;finishing main&quot;) asyncio.run(main()) </code></pre> <p>output:</p> <pre class="lang-none prettyprint-override"><code>inside main finishing main inside coro_1 cancellation error occurred </code></pre> <p>In <code>main()</code> coroutine, I created a new task, but I didn't give it opportunity to run. (I didn't await on anything). The <code>main()</code> coroutine finishes but the <code>coro_1</code> executes!</p> <p>Ok I know that this happened because I used <code>asyncio.run()</code> but after I went through the source code, I couldn't understand why and where. I must be definitely wrong in one of the following steps.</p> <ol> <li><p>when <code>coro_1()</code> task is created in <code>main</code>, it schedules a new callback(<code>self.__step</code>) in the event loop for the next cycle. (in <code>self._ready</code> queue).</p> </li> <li><p>the <code>main</code> is finished, execution goes into the <code>__exit__</code> method of the <code>Runner</code> object(<a href="https://github.com/python/cpython/blob/3.11/Lib/asyncio/runners.py#L62" rel="nofollow noreferrer">here</a>).</p> </li> <li><p>it then <code>.cancel()</code>s all remaining tasks <a href="https://github.com/python/cpython/blob/3.11/Lib/asyncio/runners.py#L193" rel="nofollow noreferrer">here</a>. Now we have our <code>coro_1</code> task. It's <code>_must_cancel</code> flag is set and its <code>__step</code> is waiting to be executed in the next iteration with that exception set.</p> </li> <li><p>Since the <code>exc</code> is set, we reach at <a href="https://github.com/python/cpython/blob/3.11/Lib/asyncio/tasks.py#L269" rel="nofollow noreferrer">this line</a>:</p> <pre class="lang-py prettyprint-override"><code>... else: result = coro.throw(exc) ... </code></pre> </li> </ol> <p>Now how is that possible? our <code>coro_1</code> is not in the state that we can throw exception to it. Someone must have executed it until the line <code>await asyncio.sleep(0)</code> in the past. who and where?</p> <p>I use Python 3.11.</p> <p>Thanks in advance.</p>
<python><python-3.x><asynchronous><task><python-asyncio>
2023-07-21 17:04:08
1
17,004
S.B
76,739,759
8,849,755
Getting i-th element of branch with uproot
<p>I am using <a href="https://uproot.readthedocs.io" rel="nofollow noreferrer">uproot</a> to read <a href="https://root.cern/manual/root_files/" rel="nofollow noreferrer">root files</a> in Python. My files are such that I am doing this:</p> <pre class="lang-py prettyprint-override"><code>ifile = uproot.open(path_to_root_file) metadata = ifile['Metadata'] waveforms = ifile['Waveforms'] waveforms.show() waveforms_of_event_50 = waveforms['voltages'].array()[50] print(waveforms_of_event_50) </code></pre> <p>and I get as output</p> <pre><code>name | typename | interpretation ---------------------+--------------------------+------------------------------- event | int32_t | AsDtype('&gt;i4') producer | std::string | AsStrings() voltages | std::vector&lt;std::vect... | AsObjects(AsVector(True, As... [[0.00647, 0.00647, 0.00671, 0.00647, ..., 0.00769, 0.00769, 0.00647], ...] </code></pre> <p>Since the <code>waveforms['voltages']</code> is an array of array of waveforms, it is heavy and, consequently, the line <code>waveforms_of_event_50 = waveforms['voltages'].array()[50]</code> takes long, because it has to load all the waveforms into memory only to discard all of them but the 50th. Even more, for some of the files this is not even possible because they simply don't fit in memory. What I want to do is instead to get the <code>i</code>th waveform without loading all of them into memory, which I understand is one of the things root files are good for, i.e. something like <code>waveforms['voltages'].get_element_number(50)</code>. Is this possible? How?</p>
<python><uproot>
2023-07-21 16:37:16
1
3,245
user171780
76,739,729
16,727,569
Workflow instructions not followed when deploying Azure web app via github
<p>I am using <strong>GitHub to deploy a streamlit app into Azure web app</strong>. I discovered the workflow file that is created under the .github/workflows folder as part of the CI/CD pipeline.</p> <p>In it, I modified it to add some extra commands to upgrade pip and install wheel before the dependencies. But when deploying to Azure web app it doesn't follow it.</p> <p>Is it Azure or am I missing out on something here? (I commented out the install for libgl)</p> <p>Here is my workflow file:</p> <pre><code># Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy # More GitHub Actions for Azure: https://github.com/Azure/actions # More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions name: Build and deploy Python app to Azure Web App - axxxxxxxxx on: push: branches: - master workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: submodules: true - name: Set up Python version uses: actions/setup-python@v1 with: python-version: '3.9' - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate # - name: Install libgl1 # run: | # sudo apt-get update # sudo apt-get install -y libgl1-mesa-dev # sudo apt-get install -y libglib2.0-0 - name: Upgrade pip run: python -m pip install --upgrade pip - name: Install wheel and setuptools run: pip install -U wheel setuptools - name: Install dependencies run: pip install -r requirements.txt # Optional: Add step to run tests here (PyTest, Django test suites, etc.) - name: Upload artifact for deployment jobs uses: actions/upload-artifact@v2 with: name: python-app path: | . !venv/ deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: python-app path: . - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 id: deploy-to-webapp with: app-name: 'axxxxxxxxxxxxxxxx' slot-name: 'Production' publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_xxxxxxxxxxxxxxxxxxxxxxxxxxx }} </code></pre> <p>I had tried</p>
<python><github><azure-web-app-service>
2023-07-21 16:32:34
1
472
Gaurav Hazra
76,739,726
6,552,666
How to pass data through a redirect in flask
<p>I want the user to be able to enter a list of changes into one page, then be redirected to a validation page where they can press accept or reject, and then be redirected back to the original page with the changes made. My first attempt to do this looks like:</p> <p>view_event:</p> <pre><code>@bp.route('/&lt;int:event_id&gt;/view_event', methods=('GET', 'POST')) @login_required def view_event(event_id): #...# return redirect(url_for('event.validate_event', event_id=event_id, event_name=event_name, change_list=change_list)) </code></pre> <p>validate_event:</p> <pre><code>@bp.route('/&lt;int:event_id&gt;/validate_event', methods=('GET', 'POST')) @login_required def validate_event(event_id = None, event_name = None, change_list = None): event_id = request.args['event_id'] event_name = request.args['event_name'] change_list = request.args['change_list'] #...# </code></pre> <p>However, when I follow this redirect, I get a 400 Bad Request error. I don't know if I'm using this correctly or how parameters are supposed to be passed through a redirect. I'm looking for a solution, as well as how to diagnose the problem in general.</p>
<python><flask>
2023-07-21 16:32:12
1
673
Frank Harris
76,739,649
8,796,340
Retrieve column names created by pandas get_dummies
<p>Is there a good way to get the column names created when you run <code>get_dummies</code> on a dataframe. For example,</p> <pre><code>import pandas as pd # set up a dataframe with one numeric and two categocial columns df = pd.DataFrame({ &quot;numeric_1&quot;: [1, 2, 3, 4], &quot;cat_1&quot;: ['high', 'low', 'high', 'low'], &quot;cat_2&quot;: ['blue', 'blue', 'green', 'green'] }) # identify the categorical columns categorical_colnames = ['cat_1', 'cat_2'] # get dummies df = pd.get_dummies(df, categorical_colnames) </code></pre> <p>For this dataframe, I'd want to see:</p> <blockquote> <p>['cat_1_high', 'cat_1_low', 'cat_2_blue', 'cat_2_green']</p> </blockquote> <p>The code I use to do this is clunky, and I'm wondering if there is anything better. I searched the docs and it doesn't seem like there is an option to return this when you run <code>pd.get_dummies</code>. Here is the code I use:</p> <pre><code>nominal_prefixes = [s + &quot;_&quot; for s in categorical_colnames] nominal_colnames = [] for x in nominal_prefixes: cols_x = [col for col in df if col.startswith(x)] nominal_colnames.append(cols_x) nominal_colnames = [item for sublist in nominal_colnames for item in sublist] </code></pre> <p>With <code>nominal_colnames</code>, I create the list that I want, but this is clunky and I was hoping for something better. I have to do this pretty often in my code and I assume other pandas users do too. I think <a href="https://stackoverflow.com/questions/37077254/is-it-possible-to-get-feature-names-from-pandas-get-dummies">this question</a> is similar, but it does not address my question.</p>
<python><pandas><dataframe>
2023-07-21 16:20:23
3
1,260
mikey
76,739,537
14,037,055
Append the column names corresponding to the minimum row values of a dataframe to create a new dataframe
<p>I have the following dataframe</p> <pre><code>import pandas as pd data = [[5,4,3,2,6,8], [9,1,5,4,8,6], [7,6,8,1,2,4], [9,6,5,4,8,3]] df = pd.DataFrame(data, columns=['Col1','Col2','Col3','Col4','Col5','Col6']) df </code></pre> <p>I am trying to display the minimum value of each row along with the column name.</p> <pre><code>df=df.min(axis=1) df </code></pre> <p>output:</p> <pre><code>2 1 1 3 </code></pre> <p>But how can I append the column names corresponding to those minimum value of rows?</p> <p>My expected output is</p> <pre><code>2 col4 1 col2 1 col4 3 col6 </code></pre>
<python><python-3.x><pandas><dataframe><python-2.7>
2023-07-21 16:02:16
1
469
Pranab
76,739,461
17,530,552
Equivalence test for paired samples with "statsmodels weightstats.ttost_paired" – why does the test always turn out non-significant?
<p>I am interested in running a equivalence test between two paired samples, namely <code>group1</code> and <code>group2</code>. I use <code>statsmodels.stats.weightstats.ttost_paired</code> (<a href="https://www.statsmodels.org/stable/generated/statsmodels.stats.weightstats.ttost_paired.html" rel="nofollow noreferrer">https://www.statsmodels.org/stable/generated/statsmodels.stats.weightstats.ttost_paired.html</a>) as equivalence test.</p> <p>The test’s null and alternative hypotheses are:</p> <ul> <li>H0: The difference between the means is outside the equivalence interval</li> <li>H1: The difference between the means is inside the equivalence interval</li> </ul> <p><strong>Problem:</strong> My problem, given a specific dataset, is that the test turns out non-significant even though the difference between the two tested samples is so small that thest should turn out significant (p &lt; 0.05), given the boundary I chose (plus minus 5% from the difference between both sample means).</p> <p>I am not sure if my &quot;problem&quot; is related to my code or the actual data. Therefore, I wrote a simple reproducible code below with two samples (<code>group1</code> and <code>group2</code>). The samples are almost identical as can be seen in the script, and therefore share almost the same mean. The difference between both sample means is <code>md = 0.1428571428571428</code>.</p> <p>I set the maximum difference to be 10% via the following part of the code:</p> <pre><code># Max percent change percent = (md/100) * 10 # md minus and plus threshold lower = md - percent upper = md + percent </code></pre> <p>As far as my understanding goes, the equivalence test should turn out significant (p &lt; 0.05) for this dummy dataset.</p> <p>However, the resulting p-value is <code>0.46180097594939595</code>, hence the H0 is not rejectet.</p> <pre><code>import statsmodels as sm from statsmodels.stats import weightstats import numpy as np group1 = [0, 1, 2, 3, 4, 5, 7] group2 = [0, 1, 2, 3, 4, 5, 6] mean1 = np.mean(group1) mean2 = np.mean(group2) md = mean1-mean2 # Max percent change percent = (md/100) * 10 # md minus and plus threshold lower = md - percent upper = md + percent # Test test = sm.stats.weightstats.ttost_paired( x1=np.array(group1), x2=np.array(group2), low=lower, upp=upper, weights=None, transform=None) print(f&quot;md = {md}&quot;) print(test) </code></pre> <p><strong>Question:</strong> I wonder if I am doing something wrong in the code itself. For example, the <code>lower</code> and <code>upper</code> range should correspond to the difference <code>md</code> between <code>group1</code> and <code>group2</code>, plus/minus 10%, respectively. I cannot understand why the test still turns out non-significant? Is there a mistake in my code?</p>
<python><statsmodels><equivalent>
2023-07-21 15:50:58
0
415
Philipp
76,739,451
11,648,332
GET Request works with terminal curl but doesn't work with python request library
<p>This curl request works perfectly fine if made from the terminal:</p> <pre><code>curl -kg 'https://website.com/wellview/api/tablename?filter[where][id]=123456' -H &quot;Authorization: Bearer sjfjkdjskdfjlsdflks12313123&quot; </code></pre> <p>But if I try to replicate it with the python request library, I receive a 403, Forbidden, response:</p> <pre><code>s = requests.Session() path=u'https://website.com/wellview/api/tablename?filter[where][id]=123456' bearer_token=&quot;sjfjkdjskdfjlsdflks12313123&quot; headers = {&quot;Authorization&quot;: f&quot;Bearer {bearer_token}&quot;} r= s.get(path, headers = headers, verify = False) </code></pre> <p>I had to mask the real URL and bearer token since they're sensible information. I get the following response:</p> <pre><code>2023-07-21 17:43:32,267 :: DEBUG :: urllib3.connectionpool :: Starting new HTTPS connection (1): website.com:443 2023-07-21 17:43:32,370 :: DEBUG :: urllib3.connectionpool :: https://website.com:443 &quot;GET /wellview/api/tablename?filter%5Bwhere%5D%5Bid%5D=123456 HTTP/1.1&quot; 403 146 </code></pre> <p>I think the problem might reside with the square brackets being percent encoded by the request library, I don't know how to overcome this problem though, any ideas?</p> <p>I get the same result even if I set the filter as a parameter in the params argument for the request:</p> <pre><code>base_url = &quot;https://website.com/wellview/api/tablename&quot; bearer_token=&quot;sjfjkdjskdfjlsdflks12313123&quot; headers = {&quot;Authorization&quot;: f&quot;Bearer {bearer_token}&quot;} params = {'filter[where][id]': '123456'} response = requests.get(base_url, headers=headers, params=params,verify=False) </code></pre> <p>[EDIT] I notice now, the request object shows a comment:</p> <pre><code>2023-07-23 12:58:39,059 :: DEBUG :: charset_normalizer :: Encoding detection: ascii is most likely the one. </code></pre>
<python><curl><python-requests>
2023-07-21 15:49:10
0
447
9879ypxkj
76,739,339
7,694,287
how to understand the structure of a neural network
<p>I have a deep learning structure designed for the critic within the actor critic reinforcement learning as follows:</p> <pre><code>class Critic_MLP(nn.Module): def __init__(self, args, critic_input_dim): super(Critic_MLP, self).__init__() self.fc1 = nn.Linear(critic_input_dim, args.mlp_hidden_dim) self.fc2 = nn.Linear(args.mlp_hidden_dim, args.mlp_hidden_dim) self.fc3 = nn.Linear(args.mlp_hidden_dim, 1) self.activate_func = [nn.Tanh(), nn.ReLU()][args.use_relu] def forward(self, critic_input): x = self.activate_func(self.fc1(critic_input)) x = self.activate_func(self.fc2(x)) value = self.fc3(x) return value </code></pre> <p>where <code>args.use_relu</code> has value <code>False</code>. Could anyone tell me how to understand <code>self.acivate_func</code> where two activation functions are included with a Boolean value outside the bracket? Thank you for your help.</p>
<python><deep-learning><neural-network>
2023-07-21 15:32:58
1
402
Mingming
76,739,166
10,416,012
How to migrate pandas code to pandas arrow?
<p>Recently pandas 2.0 supported arrow datatypes, which seem to have many advantages over the standard datatypes, both in speed and with nan support.</p> <p>I need to migrate a large code base to pandas arrow and I was wondering which kind of problems I may face, I didn´t find any migration guide or similar.</p> <p>I imagine I will need to change all the functions that load data so they use the arrow back-end. Now integer columns will support NA, that is not a big deal, but my questions are:</p> <ul> <li>I'm missing something, possible issues or incompatibilities?</li> <li>Are common data-types interoperable?</li> <li>Is such a migration feasible?</li> <li>which other problems may I face?</li> </ul> <p>I hope these questions are not to broad for SO.</p>
<python><pandas><apache-arrow>
2023-07-21 15:08:05
2
2,235
Ziur Olpa
76,739,146
1,136,450
Python decorator that resolves some expressions in a function
<p>I want to write a decorator that &quot;pre-resolves&quot; some expressions in a function. That is,</p> <pre><code>CONSTS = {'pos': 1} @resolve(CONSTS) def f(x: list): return x[CONSTS['pos']] </code></pre> <p>should be the same as if I had written</p> <pre><code>def f(x: list): return x[1] </code></pre> <p>The only use will be to substitute string expressions from a single dict with numerical values.</p> <p>Is it possible to do this, perhaps using <code>ast</code>?</p> <p>(Reason: the transformed function is being passed to another decorator that performs further <code>ast</code> magic, and does not support the usage of <code>dict</code>.)</p>
<python><metaprogramming><abstract-syntax-tree>
2023-07-21 15:05:42
1
1,550
nth
76,739,120
16,383,578
How to accelerate the convergence of Leibniz Series?
<p>The <a href="https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80" rel="nofollow noreferrer">Leibniz series</a> is the following infinite series that is used to approximate π. It does indeed converge to π but it does so in a notoriously slow way.</p> <p><img src="https://wikimedia.org/api/rest_v1/media/math/render/svg/b702b40ec6c3f81e02a697312d2939a1068b467d" alt="" /></p> <p>A few years ago I wrote many Python functions to calculate π, and of course I wrote a function using it (because it is in many online tutorials), but finding it inefficient, I wrote much more efficient functions that approximate π much faster, the fastest I have tested was <a href="https://en.wikipedia.org/wiki/Ramanujan%E2%80%93Sato_series" rel="nofollow noreferrer">Ramanujan's π formula</a>, it gives 15 correct decimal places in 3 iterations (at this point double underflows).</p> <p>A while back I watched this <a href="https://www.youtube.com/watch?v=ypxKzWi-Bwg" rel="nofollow noreferrer">video</a> about accelerating Leibniz Series by using correction terms, and I was intrigued, so I wrote some Python functions for the correction terms to check the video's veracity, I found that using 1 correction term the series yields 10 correct decimal places for 2048 iterations, 2 correction terms yields 15 correct decimal places for 638 iterations, 3 correction terms yields 15 correct decimal places in 131 iterations, but 4 correction terms makes the series converge slower, makes the underflow occur at 154th iteration.</p> <p>I read that Leibniz Series can be accelerated:</p> <blockquote> <p>However, the Leibniz formula can be used to calculate π to high precision (hundreds of digits or more) using various <a href="https://en.wikipedia.org/wiki/Convergence_acceleration" rel="nofollow noreferrer">convergence acceleration</a> techniques.</p> </blockquote> <p>So I wanted to implement the algorithms myself, as a self-imposed programming challenge, to improve my skills (if anyone's wondering, no this is not homework), but my math isn't that good, so I put off doing it, until very recently when I read <a href="https://www.codeproject.com/Articles/5353031/Summation-of-Series-with-Convergence-Acceleration" rel="nofollow noreferrer">this</a>.</p> <p>I tried to implement some algorithms but I found that while they need less terms for more precise result, the computation for the same number of terms is much more expensive, so that they end up taking longer time to execute. Below is my code, I want to know, what programming techniques and convergence acceleration methods (limited to ones found on the Leibniz series Wikipedia page) I can use, to speed up the calculation of π using the Leibniz Series, both making it use less number of terms, and take less time to execute?</p> <p>(Using compiled libraries is OK, but I don't want to cheat, by caching for example)</p> <pre class="lang-py prettyprint-override"><code>import math from itertools import cycle from math import factorial def Ramanujan(n): def term(k): return factorial(4 * k) * (1103 + 26390 * k) / \ (factorial(k) ** 4 * 396 ** (4 * k)) s = sum(term(i) for i in range(n)) return 1 / (2 * 2 ** 0.5 * s / 9801) sign = [1, -1] def Leibniz_Series(n): return [1/i*s for i, s in zip(range(1, 2*n+1, 2), cycle(sign))] def Leibniz_0(n): return 4 * sum(Leibniz_Series(n)) def Leibniz_1(n): correction = 1 / n*sign[n % 2] return Leibniz_0(n) + correction def Leibniz_2(n): correction = 1 / ( n + 1 / ( 4 * n ) )*sign[n % 2] return Leibniz_0(n) + correction def Leibniz_3(n): correction = 1 / ( n + 1 / ( 4 * n + 4 / n ) )*sign[n % 2] return Leibniz_0(n) + correction def Leibniz_4(n): correction = 1 / ( n + 1 / ( 4 * n + 4 / ( n + 9 / n ) ) )*sign[n % 2] return Leibniz_0(n) + correction def bincoeff(n, k): r = 1 if (k &gt; n): return 0 for d in range(1, k + 1): r = r * n / d n -= 1 return r def abs(n): return n * (-1) ** (n &lt; 0) def Euler(arr): out = [] for i in range(len(arr)): delta = 0 for j in range(i + 1): coeff = bincoeff(i, j) delta += (-1) ** j * coeff * abs(arr[j]) out.append(0.5 ** (i + 1) * delta) return out def Leibniz_Euler(n): return 4 * sum(Euler(Leibniz_Series(n))) def Leibniz_Aitken(n): series = Leibniz_Series(n) s0, s1, s2 = (sum(series[:n-i]) for i in (2, 1, 0)) return 4 * (s2 * s0 - s1 * s1) / (s2 - 2*s1 + s0) def LCP(s1, s2): i = 0 for a, b in zip(s1, s2): if a != b: break i += 1 return i for func in (Ramanujan, Leibniz_Euler, Leibniz_Aitken, Leibniz_4, Leibniz_3, Leibniz_2, Leibniz_1, Leibniz_0): i = 12 last = 0 while (pi := func(i)) != math.pi: i += 1 if i == 2048: if abs(pi - math.pi) &lt;= 1e-6: print('the calculated result is close') else: print('the method is too slow') break if pi == last: print('float underflow') break last = pi print( f'function: {func.__name__}, iterations: {i}, correctness: {LCP(str(pi), str(math.pi))}') </code></pre> <p>Performance:</p> <pre><code>function: Ramanujan, iterations: 12, correctness: 17 float underflow function: Leibniz_Euler, iterations: 52, correctness: 16 the calculated result is close function: Leibniz_Aitken, iterations: 2048, correctness: 11 function: Leibniz_4, iterations: 154, correctness: 17 function: Leibniz_3, iterations: 131, correctness: 17 function: Leibniz_2, iterations: 638, correctness: 17 the calculated result is close function: Leibniz_1, iterations: 2048, correctness: 12 the method is too slow function: Leibniz_0, iterations: 2048, correctness: 4 In [2]: %timeit Ramanujan(3) 3.7 µs ± 229 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) In [3]: %timeit Leibniz_3(131) 17.4 µs ± 123 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) In [4]: %timeit Leibniz_Aitken(2048) 295 µs ± 10.8 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) In [5]: %timeit Leibniz_Euler(52) 3.81 ms ± 430 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) </code></pre>
<python><python-3.x><algorithm><performance><pi>
2023-07-21 15:01:00
1
3,930
Ξένη Γήινος
76,739,003
354,051
Create multiple functions in python dynamically and register them with module in a way that they can be imported
<p>Although I have found many posts related to the title but none of them was able to clarify things. Here is a simple function in dynamic.py</p> <pre class="lang-py prettyprint-override"><code># dynamic.py def FUNC(funcName, data): func_code = createCode(funcName, data) compiled_code = compile(func_code, &quot;&lt;string&gt;&quot;, &quot;exec&quot;) exec(compiled_code) func = types.FunctionType(compiled_code , globals(), funcName) return func hello = FUNC('hello', {'A':10, 'B':30}) hello2 = FUNC('hello2', {'A':8}) hello3 = FUNC('hello3', {'A':10, 'B':30, 'C':45}) </code></pre> <p><strong>createCode</strong> function creates a valid string representation of a Python function based on data. Depending on the data, a function either receive no argument or multiple arguments. It may return some value or no return at all. The code above is not working. When I call a dynamic module in another file:</p> <pre class="lang-py prettyprint-override"><code># another.py import dynamic dynamic.hello() v = dynamic.hello2(2) </code></pre> <p>The error is:</p> <pre><code>v = dynamic.hello2(2) TypeError: &lt;module&gt;() takes 0 positional arguments but 1 was given </code></pre> <p>But the <strong>hello2</strong> function is having a single argument and I am surprised it didn't warn about the first call which actually receives no argument. I am also having a doubt that if this code is working, should I return the function and assign to some variable in order to use the function or they are already registered at the module level? if the answer is 'yes' then I believe this code is fine:</p> <pre class="lang-py prettyprint-override"><code>FUNC('hello', {'A':10, 'B':30}) FUNC('hello2', {'A':8}) FUNC('hello3', {'A':10, 'B':30, 'C':45}) </code></pre> <p>The bottom line is I need access to all the dynamics function outside in another module.</p>
<python>
2023-07-21 14:46:09
1
947
Prashant
76,738,869
15,112,773
The group is not included in different clusters in networkx graph clustering
<p>I have a symmetrical square matrix. The rows contain weights (they are not normalized, but the greater the weight, the closer it is to 1). I want to cluster groups, and i use networks:</p> <pre><code> from networkx.algorithms.community import girvan_newman matrix = pd.DataFrame({ 'group': ['g1', 'g2', 'g3', 'g4'], 'g1': [2, 1, 0, 1], 'g2': [1, 2, 0, 0], 'g3': [0, 0, 2, 2], 'g4': [1, 0, 2, 3]} G = nx.Graph() for group1 in matrix.index: for group2 in matrix.index: weight = matrix.loc[group1, group2] if group1 != group2 else 0 if weight &gt; 0: G.add_edge(group1, group2, weight=weight) communities = girvan_newman(G) first_communities = tuple(sorted(c) for c in next(communities)) print(&quot;Groups girvan_newman:&quot;, first_communities) Groups girvan_newman: (['g1', 'g2', 'g4'], ['g3']) </code></pre> <p>The problem is that for some reason the 'g4' group is not combined with the 'g3' group. It turns out that a group can only be a member of one cluster. But 'g4' has more weight with 'g3' than with 'g1' and 'g2'. I don't know how to improve it</p>
<python><pandas><networkx><graph-theory>
2023-07-21 14:27:38
1
383
Rory
76,738,753
10,620,003
Change the dataframe based on the date and the values between two window
<p>I have a df which has 4 columns. I want to stick the rows of each id based on the date and the start_time and end_time.</p> <p>I want to change the 15 interval between two times and change them to 1. And then stick them for each ids. For example, for id 1, <code>'2022-07-21 12:15:00 13:00:00'</code> I want to create 1,1,1,0 for 12-13 and all of the other values should be zero.</p> <p>I provide a df as follow and you can see that. For example for id=1 and 2. We dont have anything for 2022-07-20, so I put all the values as zero. And same for the other ids and date. Here is the df:</p> <pre><code>df = pd.DataFrame() df['id'] = [1, 1, 2, 2, 3] df['date'] = ['2022-07-21','2022-07-22','2022-07-21','2022-07-22', '2022-07-20' ] df['time_start'] = ['12:15:00','12:45:00','12:45:00','12:00:00','12:30:00' ] df['end_start'] = ['13:00:00','13:00:00','13:00:00','13:00:00','13:00:00' ] id date time_start end_start 1 2022-07-21 12:15:00 13:00:00 1 2022-07-22 12:45:00 13:00:00 2 2022-07-21 12:45:00 13:00:00 2 2022-07-22 12:00:00 13:00:00 3 2022-07-20 12:30:00 13:00:00 </code></pre> <p>and here is the df that I want:</p> <pre><code>df = pd.DataFrame() df['id'] = [1, 2, 3] df['d112:00:00'] = [ 0,0,0] df['d112:15:00'] = [0,0,0] df['d112:30:00'] = [0,0,1] df['d112:45:00'] = [0,0, 1] df['d113:00:00'] = [0,0,0] df['d212:00:00'] = [ 0,0,0] df['d212:15:00'] = [1,0,0] df['d212:30:00'] = [ 1,0,0] df['d212:45:00'] = [ 1,1,0] df['d213:00:00'] = [ 0,0,0] df['d312:00:00'] = [ 0,1,0] df['d312:15:00'] = [ 0,1,0] df['d312:30:00'] = [ 0,1,0] df['d312:45:00'] = [ 1,1,0] df['d313:00:00'] = [ 0,0,0] id d112:00:00 d112:15:00 d112:30:00 d112:45:00 d113:00:00 d212:00:00 d212:15:00 d212:30:00 d212:45:00 d213:00:00 d312:00:00 d312:15:00 d312:30:00 d312:45:00 d313:00:00 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0 2 0 0 0 0 0 0 0 0 1 0 1 1 1 1 0 3 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>Could you please help me with that? Thanks</p>
<python><pandas><dataframe>
2023-07-21 14:11:57
1
730
Sadcow
76,738,484
22,221,987
How to convert Ctypes structure with nested structures and arrays to python dict
<p>I have a <a href="https://stackoverflow.com/questions/76730751/c-sizeofsome-structure-returns-different-value-in-compare-with-python-struct-c?noredirect=1#comment135277012_76730751">structure</a> (by Mark Tolonen, great thanks to him!). (I've decided to not rewrite it here, to avoid code duplication with that post). The feature of this structure is that structure may include another structures and arrays and even array with structures.</p> <p>I've tried to create a function, which will convert this structure to python dict. Here is the trying:</p> <pre><code> def _process_ctypes(self, ctypes_obj): if isinstance(ctypes_obj, ctypes.Structure): data_dict = {} for field_name, field_type in ctypes_obj.get_fields(): field_value = getattr(ctypes_obj, field_name) if isinstance(field_value, (ctypes.Structure, ctypes.Array)): data_dict[field_name] = self._process_ctypes(field_value) else: data_dict[field_name] = field_value return data_dict elif isinstance(ctypes_obj, ctypes.Array): data_list = [] for element in ctypes_obj: if isinstance(element, (ctypes.Structure, ctypes.Array)): data_list.append(self._process_ctypes(element)) else: data_list.append(element) return data_list </code></pre> <p>But, it looks kinda ugly-complicated imho. And it's not possible to add some data to the final output, only outside a function.</p> <p>Do you have any ideas how to simplify and refactor this function, which will recursively go through the entire C structure and collect a dictionary of all nested structures and arrays of values? Input - always ctypes.Structure, output - always python.dictionary.</p> <p>In addition, it would be great to convert every array into the dictionary too, just using some specific strings as keys.</p>
<python><c><algorithm><serialization><ctypes>
2023-07-21 13:34:41
1
309
Mika
76,738,456
4,335,600
How to pass a list of tuples for a VALUES clause?
<p>I am trying to run a query with a CTE of the following desired format:</p> <pre><code>SELECT * FROM ( VALUES (1, 'A'), (2, 'B') ) temp_table(column_a, column_b) </code></pre> <p>Using SQLalchemy, I want to dynamically populate the data (1, 'A', etc.) in this table. I have tried the following:</p> <pre><code>import sqlalchemy as sa q = &quot;&quot;&quot; SELECT * FROM ( VALUES (:column_a, :column_b) ) temp_table(column_a, column_b) &quot;&quot;&quot; params = [ {'column_a': 1, 'column_b': 'A'}, {'column_a': 2, 'column_b': 'B'} ] conn.execute(sa.text(q), parameters=params) </code></pre> <p>However, because I am providing a list of parameters, this uses <code>execute_many</code> under the hood (as I understand it) and ends up running the query twice, with the first query being eg:</p> <pre><code>SELECT * FROM ( VALUES (1, 'A') ) temp_table(column_a, column_b) </code></pre> <p>How do I properly parametrize this so that all of my tuples are inserted into the query in one go?</p>
<python><sqlalchemy>
2023-07-21 13:29:35
1
644
bsauce
76,738,391
662,285
find particular key in json and insert parent object to it using python
<p>I am trying to insert parent object in the json but it inserts it on the top but I want to insert after particular key present in the json. I tried adding below code but it insert parent at the top (I understand since it is parent it will be inserted on the top but i want to insert before particular key in this case key is &quot;pattern&quot; :</p> <pre><code>with open (&quot;myfile.json&quot;, 'r') as f: myjson = json.load(f) myjson = {'Main Parent': myjson} </code></pre> <p>Basically I want to insert &quot;versions&quot;: before &quot;pattern&quot;</p> <pre><code>&quot;versions&quot;:{ &quot;pattern&quot;: { &quot;provider&quot;: &quot;abc&quot;, &quot;schema&quot;: &quot;xyz&quot; }, &quot;baseline&quot;:{ &quot;version&quot; : &quot;dev&quot; } } </code></pre> <p>Input json file</p> <pre><code> { &quot;target&quot;: { &quot;Name&quot;: &quot;abc&quot;, &quot;Occupation&quot;: &quot;xyz&quot; }, &quot;properties&quot;:{ &quot;env&quot; : &quot;dev&quot; }, &quot;use_it&quot;: &quot;xyz&quot;, &quot;pattern&quot;: { &quot;provider&quot;: &quot;abc&quot;, &quot;schema&quot;: &quot;xyz&quot; }, &quot;baseline&quot;:{ &quot;version&quot; : &quot;dev&quot; } } </code></pre> <p>Expected output json file</p> <p>Input json file</p> <pre><code> { &quot;target&quot;: { &quot;Name&quot;: &quot;abc&quot;, &quot;Occupation&quot;: &quot;xyz&quot; }, &quot;properties&quot;:{ &quot;env&quot; : &quot;dev&quot; }, &quot;use_it&quot;: &quot;xyz&quot;, &quot;versions&quot;:{ &quot;pattern&quot;: { &quot;provider&quot;: &quot;abc&quot;, &quot;schema&quot;: &quot;xyz&quot; }, &quot;baseline&quot;:{ &quot;version&quot; : &quot;dev&quot; } } } </code></pre>
<python><json>
2023-07-21 13:20:35
2
4,564
Bokambo
76,738,358
8,113,138
ModuleNotFoundError: No module named 'src' - Jupyter Notebook
<p>Why do I have this error in interactive visual studio?</p> <p>My Python version is 3.10.6</p> <p>My Ipython is 8.14.0</p> <p>My system is Ubuntu 22</p> <p>I have folders as follows:</p> <pre><code>code-&gt; -&gt; test test.ipynb -&gt; src util.py </code></pre> <p>Then inside test/test.ipynb, I have &quot;</p> <pre><code>from src.util import read_file </code></pre> <p>So I am running test.ipynb and I get that error.</p> <pre><code>ModuleNotFoundError: No module named 'src' - Jupyter Notebook </code></pre>
<python><ubuntu><visual-studio-code>
2023-07-21 13:17:15
1
858
Jalil Nourmohammadi Khiarak
76,738,308
1,916,917
How do you get AnyStr.join(Iterable[AnyStr]) to pass type checks?
<p>The simplest example of what I'm trying to do is</p> <pre class="lang-py prettyprint-override"><code>from typing import AnyStr, Iterable def joiner(delim: AnyStr, objs: Iterable[AnyStr]) -&gt; AnyStr: return delim.join(objs) </code></pre> <p>MyPy doesn't have a problem with this by pyright flags it as an error</p> <pre><code>/tmp/type_demo.py /tmp/type_demo.py:7:27 - error: Argument of type &quot;Iterable[AnyStr@joiner]&quot; cannot be assigned to parameter &quot;__iterable_of_bytes&quot; of type &quot;Iterable[ReadableBuffer]&quot; in function &quot;join&quot;   &quot;Iterable[AnyStr@joiner]&quot; is incompatible with &quot;Iterable[ReadableBuffer]&quot;     TypeVar &quot;_T_co@Iterable&quot; is covariant       Type &quot;str* | bytes*&quot; cannot be assigned to type &quot;ReadableBuffer&quot;         &quot;str*&quot; is incompatible with protocol &quot;ReadableBuffer&quot;           &quot;__buffer__&quot; is not present (reportGeneralTypeIssues) /tmp/type_demo.py:9:27 - error: Argument of type &quot;Iterable[AnyStr@joiner]&quot; cannot be assigned to parameter &quot;__iterable&quot; of type &quot;Iterable[str]&quot; in function &quot;join&quot;   &quot;Iterable[AnyStr@joiner]&quot; is incompatible with &quot;Iterable[str]&quot;     TypeVar &quot;_T_co@Iterable&quot; is covariant       Type &quot;str* | bytes*&quot; cannot be assigned to type &quot;str&quot;         &quot;bytes*&quot; is incompatible with &quot;str&quot; (reportGeneralTypeIssues) 2 errors, 0 warnings, 0 informations </code></pre> <p>As far as I can make out, the error comes from trying to pass <code>Iterable[bytes]</code> to something that expects <code>Iterable[ReadableBuffer]</code>. Is there any way to declare this function that doesn't get reported as an error?</p> <p>(<code>ReadableBuffer</code> is defined as an alias of <code>Buffer</code> defined <a href="https://github.com/python/typeshed/blob/main/stdlib/typing_extensions.pyi#L402" rel="nofollow noreferrer">here</a>)</p>
<python><python-typing><pyright><type-variables>
2023-07-21 13:09:07
0
7,537
Holloway
76,738,101
489,088
Why an object instantiated in one Pytest impacts another instantiated in a different Pytest?
<p>I am testing a class that contains a few methods for handling performance counters. It's a normal Python class:</p> <pre><code>class S3Db: data = {} fs = None s3_path = None def __init__(self, s3_api_key, s3_api_secret, bucket_name, filename, bucket_path='/'): if s3_api_key != 'test': self.fs = s3fs.S3FileSystem(s3_api_key, secret=s3_api_secret) self.s3_path = f's3://{bucket_name}{bucket_path}{filename}' self.data = read_json_s3_path(self.fs, self.s3_path) pass def increment_timed_counter(self, counter_name: str): ... </code></pre> <p>My tests look like this (note the tested object is created again at the beginning of each test):</p> <pre><code>def test_can_increment_timed_counter(): s3db = S3Db('test', 'testsecret', 'bucket', 'filename') s3db.init_timed_counter('Test Counter 1', 1000) val = s3db.increment_timed_counter('Test Counter 1') assert val == 1 assert s3db.get_timed_counter('Test Counter 1') == 1 def test_can_init_timed_counters(): # NOTE I CREATE A NEW INSTANCE HERE, SHOULD BE BRAND NEW? s3db = S3Db('test', 'testsecret', 'bucket', 'filename') s3db.init_timed_counter('Test Counter 2', 1000) assert s3db.data == { 'timed_counters': { 'Test Counter 2': { 'name': 'Test Counter 2', 'expiration_ms': 1000, 'values': [] } } } </code></pre> <p>But the second test fails with:</p> <pre><code>E 'timed_counters': {'Test Counter 2': {'expiration_ms': 1000, E 'name': 'Test Counter 2', E - 'values': []}}, E ? - E + 'values': []}, E + 'Test Counter 1': {'expiration_ms': 1000, E + 'name': 'Test Counter 1', E + 'values': [854055045839803]}}, E } </code></pre> <p>Indicating the counter created on the first test remains on the object being tested on the second test.</p> <p>Why is this happening if I create a new object on the second test? Shouldn't that first object be garbage collected and the second one be a brand new instance of that class?</p> <p>I'm on Python 3.9</p> <p>Thank you!</p>
<python><python-3.x><pytest>
2023-07-21 12:40:04
1
6,306
Edy Bourne
76,738,086
1,785,661
How to store a subset of Xaray data into Zarr?
<h2>Context</h2> <p>In the section <a href="https://docs.xarray.dev/en/stable/user-guide/io.html?appending-to-existing-zarr-stores=#appending-to-existing-zarr-stores" rel="nofollow noreferrer">Appending to existing Zarr stores</a>, the example is as follows</p> <pre class="lang-py prettyprint-override"><code>import xarray as xr import dask.array # Write zarr with empty structure dummies = dask.array.zeros(30, chunks=10) ds = xr.Dataset({&quot;foo&quot;: (&quot;x&quot;, dummies)}) path = &quot;path/to/directory.zarr&quot; ds.to_zarr(path, compute=False) # Append ds = xr.Dataset({&quot;foo&quot;: (&quot;x&quot;, np.arange(30))}) ds.isel(x=slice(0, 10)).to_zarr(path, region={&quot;x&quot;: slice(0, 10)}) </code></pre> <h2>Question</h2> <p>The example works fine as long as I know the integer slices of the array.</p> <p><strong>How do I append if I do not know the required <code>region</code>?</strong> That is, if I'm given the result of <code>ds.isel(x=slice(0, 10))</code> without knowing the region <code>slice(0, 10)</code>?</p> <h2>Possible solutions</h2> <p>In theory, I have all the information from the coordinates. For example, for <code>float</code> coordinates, I could do something like</p> <pre class="lang-py prettyprint-override"><code>start_index = (ds['x']&gt;=start).argmax().values.item() end_index = (ds['x']&lt;=end).argmin().values.item() # region is slice(start_index, end_index) </code></pre> <p>to determine the <code>isel</code>/zarr indices.</p> <p>However, this gets fairly involved when dealing with a dataset with many dimensions and coordinates of various types (float, string, datetime). This makes me wonder if there is a more straightforward way.</p>
<python><python-xarray><zarr>
2023-07-21 12:37:58
1
1,677
Dahn
76,738,015
14,838,954
Interactive choropleth map not rendering properly in Streamlit app when changing filters
<p>I have developed an interactive choropleth map using Streamlit and folium. The map allows users to filter data using dropdowns for the year and region, as well as sliders for other parameters (Image 1). However, I've noticed that sometimes, when I change the year, region, or rank filters, the map doesn't render properly within the Streamlit app (Image 2). Image 1 <a href="https://i.sstatic.net/eJQa2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eJQa2.png" alt="Image 1" /></a></p> <p>Image 2 <a href="https://i.sstatic.net/qz00A.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/qz00A.png" alt="Image 2" /></a></p> <p>This function displays the folium map:</p> <pre class="lang-py prettyprint-override"><code>def display_map(year, region, start, end, _geo_data, data): df = filter_data(data, year, region, start, end, 'Happiness Score') if df.empty: st.warning(&quot;No data available for the selected filters.&quot;) return &quot;&quot;, &quot;&quot;, &quot;&quot; myscale = get_scale(df, 'Happiness Score') map = display_choropleth_map(_geo_data, df, myscale) st_map = st_folium(map, width=700, height=450) country = '' happiness_rank = '' happiness_score = '' if st_map['last_active_drawing']: properties = st_map['last_active_drawing']['properties'] country = properties.get('name', '') happiness_score = properties.get('happiness_score', '') happiness_rank = properties.get('happiness_rank', '') else: country = df[&quot;Country&quot;].iloc[0] happiness_rank = df.loc[df[&quot;Country&quot;] == country, &quot;Happiness Rank&quot;].iat[0] happiness_score = round(df.loc[df[&quot;Country&quot;] == country, &quot;Happiness Score&quot;].iat[0],2) return country, happiness_rank, happiness_score </code></pre> <p>Here choropleth layer is added:</p> <pre class="lang-py prettyprint-override"><code>@st.cache_resource(hash_funcs={folium.Map: lambda _: None}) def display_choropleth_map(_geo_data, df, myscale): x_map = 17.51 y_map = 22 map = folium.Map(location=[x_map, y_map], zoom_start=1, tiles=None, scrollWheelZoom=False) folium.TileLayer('CartoDB positron', name=&quot;Light Map&quot;, control=False).add_to(map) choropleth = folium.Choropleth( geo_data=_geo_data, name='Choropleth', data=df, columns=['Country', 'Happiness Score'], key_on=&quot;feature.properties.name&quot;, fill_color='YlGnBu', threshold_scale=myscale, fill_opacity=1, line_opacity=0.2, legend_name='Happiness Score', smooth_factor=0 ).add_to(map) def style_function(x): return {'fillColor': '#ffffff', 'color': '#000000', 'fillOpacity': 0.1, 'weight': 0.1} def highlight_function(x): return {'fillColor': '#000000', 'color': '#000000', 'fillOpacity': 0.50, 'weight': 0.1} df_indexed = df.set_index('Country') for feature in choropleth.geojson.data['features']: country = feature[&quot;properties&quot;]['name'] feature['properties']['happiness_score'] =round(df_indexed.loc[country, 'Happiness Score'],2) if country in list(df_indexed.index) else 'N/A' feature['properties']['happiness_rank'] = int( df_indexed.loc[country, 'Happiness Rank']) if country in list(df_indexed.index) else 'N/A' NIL = folium.features.GeoJson( choropleth.geojson.data, style_function=style_function, control=False, highlight_function=highlight_function, tooltip=folium.features.GeoJsonTooltip( fields=['name', 'happiness_rank', 'happiness_score'], aliases=['Country: ', 'Happiness Rank', 'Happiness Score'], style=( &quot;background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;&quot;) ) ) map.add_child(NIL) map.keep_in_front(NIL) return map </code></pre> <p>The error in console when the issue is happening this: <a href="https://i.sstatic.net/kHcyf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kHcyf.png" alt="Console" /></a></p> <p>The full code of the project is added here: <a href="https://github.com/NirmalSankalana/happiness-insights/blob/main/home.py" rel="nofollow noreferrer">https://github.com/NirmalSankalana/happiness-insights/blob/main/home.py</a></p> <p>I suspect this issue might be related to caching, but I'm not entirely sure. Can someone help me understand why this is happening and how to resolve it?</p>
<python><streamlit><folium><choropleth>
2023-07-21 12:29:06
0
485
Nirmal Sankalana
76,737,958
6,946,246
regex to check whether json objects contains two specific KV pairs
<p>I'm trying to check whether a JSON object contains two particular KV pairs, irrespective of the order.</p> <p>For example, in the JSON object below:</p> <pre><code>{&quot;color&quot;:&quot;red&quot;,&quot;animal&quot;:&quot;dog&quot;,&quot;drink&quot;:&quot;water&quot;,&quot;food&quot;:&quot;pizza&quot;,&quot;fish&quot;:&quot;tuna&quot;,&quot;foo&quot;:&quot;bar&quot;} </code></pre> <p>I want to check whether it contains <strong>both</strong> <code>&quot;animal&quot;:&quot;dog&quot;</code> <strong>AND</strong> <code>&quot;fish&quot;:&quot;tuna&quot;</code>.</p> <p>The following regex works only if the order of the KV pairs are as provided above.</p> <pre><code>^.*((&quot;animal&quot;:&quot;dog&quot;).*(&quot;fish&quot;:&quot;tuna&quot;)).*$ </code></pre> <p>It does not work for when the order is changed as follows:</p> <p><code>{&quot;color&quot;:&quot;red&quot;,&quot;drink&quot;:&quot;water&quot;,&quot;food&quot;:&quot;pizza&quot;,&quot;fish&quot;:&quot;tuna&quot;,&quot;foo&quot;:&quot;bar&quot;,&quot;animal&quot;:&quot;dog&quot;}</code></p> <p>How can I check for any order of KV pairs?</p>
<python><json>
2023-07-21 12:21:03
2
325
jsammut
76,737,830
6,278,424
Python, ADO GetRows(): When reading from sql numeric values comes with comma as a decimal seperator
<p>I have written Python code to get data from sql server similar to this example shown here: <a href="https://mail.python.org/pipermail/python-list/2002-March/131737.html" rel="nofollow noreferrer">https://mail.python.org/pipermail/python-list/2002-March/131737.html</a></p> <p>However, when I read data into Python for numerical values it uses comma as a decimal seperator, so all my numerical columns turns into string. When I acces data from Microsoft SQL Server Management Studio it shows period mark / dot / '.' as decimal seperator which is the desired way. Also, it shows that data is saved correctly. How do I fix this problem?</p> <p>My computer language is Swedish maybe that is part of the probem? I have tried to see if I can find the answer here but without luck: <a href="https://stackoverflow.com/questions/2693062/iis-7-floats-returning-with-commas-instead-of-periods">IIS 7 - floats returning with commas instead of periods</a></p> <p>If you want to see the exact code then it is:</p> <pre><code>import win32com.client import pandas as pd def msql2pandas(query_,datasource_): adoConn = win32com.client.Dispatch('ADODB.Connection') adoConn.Open(&quot;Provider = SQLOLEDB; Data Source = {}; Integrated Security = SSPI&quot;.format(datasource_)) (adoRS, succes) = adoConn.Execute(query_) adoRS.MoveFirst() data = [] cols = [] data_type = [] n_col = adoRS.Fields.Count for i in range(n_col): cols.append(adoRS.Fields.Item(i).Name) data_type.append(adoRS.Fields.Item(i).Type) while not adoRS.EOF: temp = [[i[0] for i in adoRS.GetRows(1)]] assert len(temp[0]) == n_col data.extend(temp) return {'data': pd.DataFrame(data = data, columns = cols), 'data_type': data_type} </code></pre>
<python><sql-server><ado><pywin32><win32com>
2023-07-21 12:03:27
1
530
k.dkhk
76,737,790
459,633
FileNotFoundError using gcsfs and pandas, but only on my machine
<p>I have used pandas and gcsfs regularly in the past. Recently, I have been getting errors when trying to do so. I cannot reproduce the error on other systems. On my system, I get the error using both python 3.9.16 and 3.11.1. As you can see from the error message below, it has been hard for me to google for an answer. Any thoughts on what is causing this?</p> <pre><code>import gcsfs import pandas as pd x = pd.read_table(&quot;gs://MYBUCKET/clinvar/gene_specific_summary.txt&quot;) </code></pre> <p>And the stack trace:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py&quot;, line 1242, in read_table return _read(filepath_or_buffer, kwds) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py&quot;, line 577, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py&quot;, line 1407, in __init__ self._engine = self._make_engine(f, self.engine) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/pandas/io/parsers/readers.py&quot;, line 1661, in _make_engine self.handles = get_handle( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/pandas/io/common.py&quot;, line 716, in get_handle ioargs = _get_filepath_or_buffer( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/pandas/io/common.py&quot;, line 414, in _get_filepath_or_buffer file_obj = fsspec.open( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/fsspec/core.py&quot;, line 134, in open return self.__enter__() File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/fsspec/core.py&quot;, line 102, in __enter__ f = self.fs.open(self.path, mode=mode) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/fsspec/spec.py&quot;, line 1241, in open f = self._open( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 1343, in _open return GCSFile( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 1502, in __init__ super().__init__( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/fsspec/spec.py&quot;, line 1597, in __init__ self.size = self.details[&quot;size&quot;] File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 1538, in details self._details = self.fs.info(self.path, generation=self.generation) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/fsspec/asyn.py&quot;, line 121, in wrapper return sync(self.loop, func, *args, **kwargs) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/fsspec/asyn.py&quot;, line 106, in sync raise return_result File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/fsspec/asyn.py&quot;, line 61, in _runner result[0] = await coro File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 809, in _info out = await self._ls(path, **kwargs) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 846, in _ls for entry in await self._list_objects( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 545, in _list_objects items, prefixes = await self._do_list_objects( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 580, in _do_list_objects page = await self._call( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 430, in _call status, headers, info, contents = await self._request( File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/decorator.py&quot;, line 221, in fun return await caller(func, *(extras + args), **kw) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/retry.py&quot;, line 114, in retry_request return await func(*args, **kwargs) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/core.py&quot;, line 423, in _request validate_response(status, contents, path, args) File &quot;/Users/seandavis/Documents/git/infra/jupyterlab/venv/lib/python3.9/site-packages/gcsfs/retry.py&quot;, line 83, in validate_response raise FileNotFoundError(path) FileNotFoundError: b/MYBUCKET/o </code></pre>
<python><python-3.x><pandas><google-cloud-storage><fsspec>
2023-07-21 11:58:30
1
2,988
seandavi
76,737,789
6,282,500
Rolling Mean with filter condition per row
<p>How do I compute the rolling mean only for the next values that specify a row-wise condition. More specifically, I have the following dataframe and I only want to compute the rolling mean for the values that fulfill the condition <em>finished_time &lt; created_time</em></p> <pre><code> created_time finished_time target 0 2023-07-21 00:10:00 2023-07-21 00:20:00 75 1 2023-07-21 00:25:00 2023-07-21 00:41:00 73 2 2023-07-21 00:40:00 2023-07-21 01:05:00 64 3 2023-07-21 00:55:00 2023-07-21 01:00:00 45 4 2023-07-21 01:10:00 2023-07-21 01:27:00 62 5 2023-07-21 01:25:00 2023-07-21 01:42:00 49 6 2023-07-21 01:40:00 2023-07-21 02:05:00 85 7 2023-07-21 01:55:00 2023-07-21 01:59:00 60 8 2023-07-21 02:10:00 2023-07-21 02:39:00 21 9 2023-07-21 02:25:00 2023-07-21 02:28:00 77 </code></pre> <p>You can rebuild this dataframe using the following code</p> <pre><code>import numpy as np import pandas as pd np.random.seed(21) created_time = pd.to_datetime('2023-07-21 00:10:00') + pd.timedelta_range(start='0 minutes', periods=10, freq='15T') finished_time = created_time + pd.to_timedelta(np.random.randint(1, 30, size=10), unit='minutes') target = np.random.randint(1,100, size=10) df = pd.DataFrame(data={'created_time': created_time, 'finished_time': finished_time, 'target': target}) </code></pre> <p>As a comparison, I have this chunk of code which does what I want, but is super inefficient O(n^2):</p> <pre><code>def custom_roll(row, df, window): rolling_mean = ( df.target [df.finished_time &lt; row.created_time] .iloc[:window] .mean() ) return rolling_mean df.apply(lambda row: custom_roll(row, df, window=3), axis=1) </code></pre> <p>Can I make this code more efficient for large dataframes?</p>
<python><pandas><dataframe><numpy><rolling-computation>
2023-07-21 11:57:49
1
674
malwin
76,737,768
4,865,723
ScrollArea intervers with expand dialog to full width
<p>This picture illustrate the problem. It is a dialog with a <code>QScrollArea</code> in it. The area has a <code>QWidget</code>, using a <code>QGridLayout</code> with 3 columns containing mutliple <code>QRadioButtons</code>. But you see only 2 columns not 3. <a href="https://i.sstatic.net/zm0dn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zm0dn.png" alt="enter image description here" /></a></p> <p>But I want to have it look like this. The dialog and its child do expand to its &quot;full width&quot; defined by its content (the three columns of radio buttons). No need to horizontal scroll anymore. The vertical scrolling is OK and I want to keep it that way.</p> <p><a href="https://i.sstatic.net/kgMMl.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/kgMMl.png" alt="enter image description here" /></a></p> <p>Here is an MWE reproducing the first picture.</p> <pre><code>#!/usr/bin/env python3 import sys from PyQt5.QtCore import * from PyQt5.QtWidgets import * class LanguageDialog(QDialog): def __init__(self): super().__init__() # Language widget wdg_lang = self._language_widget() # Scroll area scroll = QScrollArea(self) # scroll.setWidgetResizable(True) # scroll.setFrameStyle(QFrame.NoFrame) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Here I'm not sure what to do. # scroll.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) scroll.setWidget(wdg_lang) # Button &quot;Apply&quot; button = QDialogButtonBox(QDialogButtonBox.Apply) button.clicked.connect(self.accept) # Dialog layout layout = QVBoxLayout(self) layout.addWidget(scroll) layout.addWidget(button) def _language_widget(self): &quot;&quot;&quot; nativ | ownlocal -&gt; tooltip: english (code) &quot;&quot;&quot; grid = QGridLayout() wdg = QWidget(self) wdg.setLayout(grid) for col in range(1, 4): for row in range(1, 24): r = QRadioButton(f'{col} x {row} | Lorem ipsum dolor sit amet', self) r.toggled.connect(self.slot_radio) r.mydata = (col, row) grid.addWidget(r, row, col) # ??? # wdg.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) return wdg def slot_radio(self, val): btn = self.sender() if btn.isChecked(): print(f'{btn.mydata=}') class Window(QMainWindow): def __init__(self, parent=None): &quot;&quot;&quot;Initializer.&quot;&quot;&quot; super().__init__(parent) def showEvent(self, e): dlg = LanguageDialog() dlg.exec() if __name__ == &quot;__main__&quot;: app = QApplication(sys.argv) win = Window() win.show() sys.exit(app.exec()) </code></pre>
<python><qt><pyqt>
2023-07-21 11:55:10
1
12,450
buhtz
76,737,705
11,749,309
How to calculate a growing/expanding percentile in Polars using cumulative_eval?
<p>I'm trying to calculate a growing percentile for a column in my Polars DataFrame. The goal is to calculate the percentile from the beginning of the column up until the current observation.</p> <p>Example Data:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl data = pl.DataFrame({ &quot;premia_pct&quot;: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] }) </code></pre> <p>I want to create a new column &quot;premia_percentile&quot; that calculates the percentile of &quot;premia_pct&quot; from the start of the column up to the current row.</p> <p>I tried using the cumulative_eval function in Polars as follows:</p> <pre class="lang-py prettyprint-override"><code>df = data.with_columns( pl.col(&quot;premia_pct&quot;).cumulative_eval( lambda group: (group.rank() / group.len()).last(), min_periods=1 ).alias(&quot;premia_percentile&quot;) ) </code></pre> <p>However, I get the following error: <code>AttributeError: 'function' object has no attribute '_pyexpr' </code></p> <p>I have also tried a for loop:</p> <pre><code> for i in range(1, data.shape[0] + 1): data[&quot;premia_percentile&quot;][:i] = data[&quot;premia_pct&quot;][:i].rank() / i return data </code></pre> <p>but this is not how poalrs is supposed to be used, and it doesn't work either. Even if I use <code>pl.slice(1,i)</code> instead of <code>[:i]</code></p> <p>Maybe you could use something similar to the <code>pandas.expanding()</code>?</p> <p>This is what I expect the output to be:</p> <pre><code> def _calculate_growing_percentile( self, data, column_name: str = &quot;premia_percentile&quot; ): &quot;&quot;&quot; Calculate a growing percentile of a column in a DataFrame. Parameters: df (pl.DataFrame): The DataFrame. column_name (str): The name of the column. Returns: pl.DataFrame: The DataFrame with the new column. &quot;&quot;&quot; # Initialize a pandas df data = data.to_pandas() # Calculate the growing percentile data[f&quot;{column_name}&quot;] = data[&quot;premia_pct&quot;].expanding().rank(pct=True) data = pl.from_pandas(data) return data </code></pre> <p>Is there a way to calculate a growing percentile in Polars using cumulative_eval or any other function? Any help would be greatly appreciated.</p> <p>Here is a similar post <a href="https://stackoverflow.com/questions/72244984/expanding-apply-in-polars">SO Question</a></p>
<python><pandas><dataframe><python-polars><percentile>
2023-07-21 11:46:47
1
373
JJ Fantini
76,737,681
7,857,466
How do I decouple lamp from button using the dependency inversion principle?
<p>As per figure 5 in <a href="https://web.archive.org/web/20150905081103/http://www.objectmentor.com/resources/articles/dip.pdf" rel="nofollow noreferrer">DIP</a> I wrote the following code. How do I write it to conform to figure 6 in the same document?</p> <pre><code>class Lamp: def __init__(self): self.state = &quot;off&quot; def turn_on(self): self.state = &quot;on&quot; def turn_off(self): self.state = &quot;off&quot; class Button: def __init__(self, lamp): self.lamp = lamp self.state = &quot;off&quot; self.lamp.state = &quot;off&quot; def on(self): self.state = &quot;on&quot; self.lamp.turn_on() def off(self): self.state = &quot;off&quot; self.lamp.turn_off() lamp = Lamp() button = Button(lamp) assert lamp.state == &quot;off&quot; button.on() assert lamp.state == &quot;on&quot; </code></pre> <p>I am thinking of using the bridge pattern, but I am not sure how to write it. I am trying the following code but it still feels wrong to me despite the asserts running ok:</p> <pre><code>from abc import ABC, abstractmethod class AbstractButton(ABC): def __init__(self, button_client): self.button_client = button_client @abstractmethod def on(self): pass @abstractmethod def off(self): pass class Button(AbstractButton): def on(self): self.button_client.on() def off(self): self.button_client.off() class ButtonClient(ABC): @abstractmethod def on(self): pass @abstractmethod def off(self): pass class Lamp(ButtonClient): def __init__(self): self.state = &quot;off&quot; def on(self): self.state = &quot;on&quot; def off(self): self.state = &quot;off&quot; lamp = Lamp() button = Button(lamp) assert lamp.state == &quot;off&quot; button.on() assert lamp.state == &quot;on&quot; button.off() assert lamp.state == &quot;off&quot; </code></pre> <p>Now inspired by Python protocols, and <a href="https://stackoverflow.com/questions/74312739/if-condition-not-working-as-expected-in-java-class">here</a> I can write the following simpler code, that gets me a Button containing a Lamp Switchable device. There is only one place where the state is stored (the Lamp device) and I get controls on both for free. But is this code decoupled?</p> <pre><code>class Switchable: def __init__(self, device): self.device = device self.device.state = 'off' def turn_on(self): self.device.state = 'on' def turn_off(self): self.device.state = 'off' class Lamp(Switchable): def __init__(self): super().__init__(self) def __str__(self): return f&quot;Lamp {self.state}&quot; lamp = Lamp() button = Switchable(lamp) assert str(lamp) == &quot;Lamp off&quot; button.turn_on() assert str(lamp) == &quot;Lamp on&quot; button.turn_off() assert str(lamp) == &quot;Lamp off&quot; lamp.turn_on() assert str(lamp) == &quot;Lamp on&quot; lamp.turn_off() assert str(lamp) == &quot;Lamp off&quot; assert button.device.state == &quot;off&quot; </code></pre>
<python><oop><design-patterns><bridge><dependency-inversion>
2023-07-21 11:43:30
1
4,984
progmatico
76,737,441
6,487,788
Best way to store embeddings
<p>I have a dataset which is a CSV file which I open and analyse as a Pandas dataframe. I am now generating 'embeddings' based on some of this data, which I want to analyse as well. The dataset is rather big (millions of rows), so I noticed that appending and storing the embeddings as part of the pandas dataframe makes me run out of RAM memory. Aside from that storing and saving numpy arrays in a dataframe is also a bit 'awkward'.</p> <p>Since I want to analyze the whole dataset including embeddings storing them in so-called embedding stores doesn't make a lot of sense, since I always want to loop over the whole set anyways.</p> <p>Are there any best practices or recommendations for how to work with this data?</p>
<python><pandas><dataframe>
2023-07-21 11:10:04
2
4,461
rmeertens
76,737,276
3,445,378
How to sind a binary string with a python swagger client
<p>From an OpenAPI definition file I generated a Swagger client for Python using Swagger-UI. I'm having trouble using a POST function that requires a request body. What would be the correct approach here?</p> <p>The definition defines the following:</p> <pre><code>&quot;/xyz&quot; : { &quot;post&quot; : { &quot;tags&quot; : [ &quot;xyz&quot; ], &quot;operationId&quot; : &quot;xyz&quot;, &quot;requestBody&quot; : { &quot;content&quot; : { &quot;multipart/form-data&quot; : { &quot;schema&quot; : { &quot;required&quot; : [ &quot;d1&quot;, &quot;d2&quot; ], &quot;type&quot; : &quot;object&quot;, &quot;properties&quot; : { &quot;d1&quot; : { &quot;format&quot; : &quot;binary&quot;, &quot;type&quot; : &quot;string&quot; }, &quot;d2&quot; : { &quot;format&quot; : &quot;email&quot;, &quot;type&quot; : &quot;string&quot;, &quot;nullable&quot; : false } } } } }, &quot;required&quot; : true }, </code></pre> <p>The method exists:</p> <pre><code>my_api.xyz(...) </code></pre> <p>But I dont know how to use the paramters. I found out, the the method needs a <code>body</code> parameter:</p> <pre><code>my_api.xyz(body) </code></pre> <p><code>d1</code> have to be the content of a xml-file.</p>
<python><swagger><swagger-codegen>
2023-07-21 10:44:59
1
1,280
testo
76,737,178
9,718,879
Prevent Prettier from breaking Python code
<p>I am writing some conditions in my django html file and upon every save, vs code Prettier rearranges my code but it's doing it the wrong way hence creating errors. Here's an example of what it is doing.</p> <pre><code>{% if messages %} {% for message in messages %} {% if message.tags == 'error' %} &lt;div class=&quot;error-message&quot;&gt;{{ message }}&lt;/div&gt; {% elif message.tags == 'success' %} &lt;div class=&quot;success-message&quot;&gt;{{ message }}&lt;/div&gt; {% else %} &lt;div class=&quot;text-center mb-3&quot;&gt;{{ message }}&lt;/div&gt; {% endif %} {% endfor %} {% endif %} </code></pre> <p>I tried modifying the <em><strong>settings.json</strong></em> with the following</p> <pre><code>&quot;git.confirmSync&quot;: false, &quot;editor.formatOnPaste&quot;: true, &quot;python.formatting.provider&quot;: &quot;autopep8&quot;, &quot;explorer.confirmDelete&quot;: false, &quot;python.showStartPage&quot;: false, &quot;explorer.confirmDragAndDrop&quot;: false, &quot;python.linting.pylintArgs&quot;: [&quot;--load-plugins=pylint_django&quot;], &quot;[python]&quot;: { &quot;editor.defaultFormatter&quot;: &quot;ms-python.python&quot; } </code></pre> <p>But it's still doing the same thing</p>
<python><django><visual-studio-code><prettier>
2023-07-21 10:29:15
0
1,121
Laspeed
76,737,160
15,893,581
scipy.optimize.minimize to find intersection of curves
<p>to find intersection between 2 polynomials I tried to minimize <em>sum of least-squares</em> like in <a href="https://stackoverflow.com/a/72154674/15893581">this code</a> - first plotted correct solution, then printed result of minimization.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,1,100) # ???????? [0,1] def polyD(x): return 1.115355004199118 - 1.597163991790283* x**1 + 0.6539311181514963* x**2 def polyS(x): return -0.03070291735792586 + 0.1601011622660309* x**1 + 0.8530319920733438* x**2 root= 0.61 # x - suppose found somewhere earlier... y_root= polyD(root) # y print(root, y_root) # x=0.61 y=0.38441273827121725 plt.plot(root, y_root, 'yo', x, polyD(x), 'r-', x, polyS(x), 'b-', ms=20, ) plt.show() #################### from scipy.optimize import minimize x0= 0 res= minimize(lambda t: sum((polyD(x) - polyS(x))**2), x0) print(res) print(res.fun) # 36.59096676853359 ???????????? </code></pre> <p>I can assume a little difference due to the algorithm, but here I see the difference of 10^2 order.</p> <p>What is my mistake?? How can I correct it? If I should define some constraints to x=[0,1]? or how to get correct result about the intersection_point?</p> <p>P.S. or, perhaps, it will be easier to solve with derivatives (minimizing to find extremum)? EDIT: partial_derivatives of constrained function(s) (Jacobian matrix) can be used to speed-up the code execution - <a href="https://docs.scipy.org/doc/scipy/tutorial/optimize.html#defining-bounds-constraints" rel="nofollow noreferrer">here</a></p>
<python><scipy-optimize>
2023-07-21 10:26:51
3
645
JeeyCi
76,736,934
13,469,674
Stacking a grouped bar chart individually with pandas and matplotlib
<p>Consider this dataframe:</p> <pre><code>data = { 'Categories': ['Opel', 'Audi', 'Lamborgini', 'McLaren'], 'Sale1': [60, 50, 40, 10], 'Sale2': [70, 10, 5, 30], 'Sale3': [5, 12, 20, 50], 'Month': [1, 1, 2, 2], } </code></pre> <p>I was able to produce this by pivoting the table and adding a shift of the bar positions for each phase: <a href="https://i.sstatic.net/7SZIq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7SZIq.png" alt="enter image description here" /></a></p> <p>However my goal is to still have this grouped bar chart, however there should be 3 bars per category, and they should be stacked. So I can see tha month 1 and 2 proportions in each bar. How can I do this? If I dont shift them, they will overlap each other which is simialr to the stacking, but not quite the correct way to go.</p> <p>Here is the code I wrote to do the above plot:</p> <pre><code>df = pd.DataFrame(data) # Create a colormap with the desired colors for Month 1 and Month 2 colors_month1 = sns.color_palette(&quot;pastel&quot;, 3) # Use seaborn's &quot;pastel&quot; colormap for Month 1 colors_month2 = [(r, g, b, 0.2) for r, g, b in colors_month1] # Adjust alpha for Month 2 # Plot the bar chart fig, ax = plt.subplots(figsize=(10, 6)) bar_width = 0.4 for i, month_group in df.groupby('Month'): if i == 1: colors = colors_month1 x_offset = 0 else: colors = colors_month2 x_offset = bar_width # Shift the x positions for Month 2 bars to the right month_group.pivot(index='Categories', columns='Month').plot.bar( rot=0, ax=ax, width=bar_width, color=colors, position=x_offset ) </code></pre>
<python><pandas><matplotlib>
2023-07-21 09:56:10
1
955
DPM
76,736,623
3,579,151
Merging, droping and combining rows in python
<p>My original formula for merging two dataframes looks like this</p> <pre><code>GES1 = pd.merge(db1, db2, on = 'KO-STA', how = 'left') </code></pre> <p>db1 looks like</p> <pre><code> ,EID_STAVBA,ST_STAVBE,PLIN,LETO_IZGRA,LETO_OBNOV,LETO_OBNO0,BRUTO_TLOR,EID_OBCINA,SIFKO,EID_DEL_STAVBE,VRSTA_DEJANSKE_RABE_DEL_ST_ID,LETO_OBNOVE_INSTALACIJ,LETO_OBNOVE_OKEN,POVRSINA,ST_DELA_STAVBE,VRSTA_STANOVANJA_ID,UPORABNA_POVRSINA,KO-STA,EID_PARCEL,KO_ID,ST_PARCELE,KO-PAR 0,100200000250868938,4645,0.0,1980.0,,,,110200000110277170,1722,100200000250868958,1,,,37.8,1,,37.8,1722-4645,100100000210682339,1722,903,1722-903 </code></pre> <p>db2</p> <pre><code> ,KO-STA,STA-PAR,KO-PAR,Ukrep_Opis,Ukrep_Kolicina,Ukrep_Enota,UkrepES_Fasada,UkrepES_Streha,UkrepES_Okna,UkrepES_TC,UkrepES_TC_tip,UkrepES_Biomasa,UkrepES_Biomasa_tip,UkrepES_Prezracevanje,UkrepES_PV,UkrepES_SSE 0,1722-4645,0.0,1722-903,Zamenjava oken,0.0,0.0,0.0,0.0,2022.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 1,1722-4645,0.0,1722-903,TI fasade,0.0,0.0,2022.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 2,1722-4645,0.0,1722-903,SSE,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2022.0 3,1722-4645,0.0,1722-903,PV,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,2022.0,0.0 </code></pre> <p>The output looks like this</p> <pre><code> EID_STAVBA ST_STAVBE ... UkrepES_PV UkrepES_SSE 0 100200000250868938 4645 ... 0.0 0.0 1 100200000250868938 4645 ... 0.0 2022.0 2 100200000250868938 4645 ... 0.0 0.0 3 100200000250868938 4645 ... 2022.0 0.0 </code></pre> <p>In between are 10 identical colums for all rows. The main id is <code>EID_STAVBA</code></p> <p>How can I rewrite formula so all data for <code>EID_STAVBA</code> would be presented in 1 row, e.g.</p> <pre><code>,EID_STAVBA,ST_STAVBE,PLIN,LETO_IZGRA,LETO_OBNOV,LETO_OBNO0,BRUTO_TLOR,EID_OBCINA,SIFKO,EID_DEL_STAVBE,VRSTA_DEJANSKE_RABE_DEL_ST_ID,LETO_OBNOVE_INSTALACIJ,LETO_OBNOVE_OKEN,POVRSINA,ST_DELA_STAVBE,VRSTA_STANOVANJA_ID,UPORABNA_POVRSINA,KO-STA,EID_PARCEL,KO_ID,ST_PARCELE,index,STA-PAR,KO-PAR,Ukrep_Opis,Ukrep_Kolicina,Ukrep_Enota,UkrepES_Fasada,UkrepES_Streha,UkrepES_Okna,UkrepES_TC,UkrepES_TC_tip,UkrepES_Biomasa,UkrepES_Biomasa_tip,UkrepES_Prezracevanje,UkrepES_PV,UkrepES_SSE 0,100200000250868938,4645,0.0,1980.0,,,,110200000110277170,1722,100200000250868958,1,,,37.8,1,,37.8,1722-4645,100100000210682339,1722,903,0,0.0,1722-903,Zamenjava oken,0.0,0.0,0.0,0.0,2022.0,0.0,2022.0,0.0,0.0,0.0,2022.0,2022.0 </code></pre> <p>?</p> <p>Do i have to use <code>groupby</code>?</p>
<python><pandas><merge>
2023-07-21 09:12:33
2
419
energyMax
76,736,466
1,338,588
Is there a way that I can convert a parquet file to avro (directly or indirectly)?
<p>I'm quite new to this and currently exploring ways of converting parquet file to avro. This is mainly due to the requirement of deserialising the avro file and get the schema.</p> <p>I tried to read the parquet file first as a Dataframe through pandas and then writing it as an avro (not sure whether this is the optimal way), and finally get the schema from it. But did not succeed</p> <pre><code>import pandas as pd df = pd.read_parquet('local_output-00000-of-00001.parquet', engine='pyarrow') df.write.format(&quot;avro&quot;).save(&quot;deserialize.avro&quot;) </code></pre> <p>was getting this error:</p> <blockquote> <p>AttributeError: 'DataFrame' object has no attribute 'write'</p> </blockquote> <p>I assume the above approach is not the right way to do it. Tried to find ways on the web, but couldn't find a constructive answer, thus decided to post it. Would really appreciate to hear from anyone who has done this before, or have different approaches to achieve this.</p>
<python><python-3.x><parquet><avro>
2023-07-21 08:47:08
2
9,532
Kulasangar
76,736,460
1,035,897
Automatic token fetching with OAuth2 client_credentials flow with Python Requests
<p>I want to use an API that is authenticated with the <code>OAuth2</code> <strong>client_credentials</strong> flow from <em>Python</em>.</p> <p>In pyhton the most widely used HTTP client is <a href="https://pypi.org/project/requests/" rel="nofollow noreferrer">Requests</a>, and <code>Requests</code> has many advanced features and extensions, some of which revolve around using it with <code>OAuth2</code>.</p> <p>However, Oauth2 is a complex beast that support 4 different flows, of which <strong>client_credentials</strong> is the simplest. Try as I might, I have not found a simple to-the-point example of using <code>Requests</code> with the <strong>client_credentials</strong> flow. It is always mentioned at the end of the article as a sidenote or afterthought after explaining all the othe flows in intricated detail.</p> <p>In <strong>client_credentials</strong> flow, the following will happen:</p> <h2>1. POST the following encoded as <strong>x-www-form-urlencoded</strong> to the &quot;token endpoint&quot;:</h2> <pre><code>{ &quot;grant_type&quot;: &quot;client_credentials&quot;, &quot;client_id&quot;: client_id, &quot;client_secret&quot;: client_secret, &quot;scope&quot;: &quot;all&quot;, # Or whatever scope you care about } </code></pre> <p>where the <strong>client_id</strong> and <strong>client_secret</strong> are provided by the service you are accessing.</p> <h2>2. The following will be returned as <strong>json</strong> (given the auth was successful):</h2> <pre><code>{ &quot;token_type&quot;:&quot;Bearer&quot;, &quot;scope&quot;:&quot;openid email profile offline_access roles read:tickets read:customers ...&quot;, &quot;access_token&quot;:&quot;XXX_THIS_TOKEN_IS_VERY_SECRET_XXX&quot; } </code></pre> <h2>3. Use &quot;access_token&quot; from returned data to access protected resources:</h2> <p>You use it by setting it in the <code>Authorization:</code> Bearer header in all requests to protected resources in the following way:</p> <pre><code>Authorization: Bearer XXX_THIS_TOKEN_IS_VERY_SECRET_XXX </code></pre> <p>The token will last <strong>1 hour</strong> from being generated and when a resource request returns 401 auth errors, simply repeat steps #1 and #2 to generate a new token to use.</p> <p>My current code manually requests a token from the token endpoint, parses the token from the resulting json and stuffs that into subsequent requests' HTTP headers. I then proceed to detect 401 errors and re-authenticate. This works but it is very tediouos. I now have to wrap every request usage with this ugly mess.</p> <p>I was hoping there would be a way to do it similar to this:</p> <pre><code>client = MagicRequestsWrapper(client_id=client_id, client_secret=client_secret, token_endpoint=token_endpoint, scope=scope) res = client.get(protected_resource_endpoint) </code></pre> <p>where all the oauth stuff is now hidden and client behaves exactly like a normal Requests client.</p> <p>How can I do that?</p>
<python><oauth-2.0><python-requests><wrapper><clientcredential>
2023-07-21 08:46:23
1
9,788
Mr. Developerdude
76,736,432
6,734,243
How to use admonitions in nbsphinx?
<p>I'm currently using the <code>jupyter-sphinx</code> extention in my documentation to execute code. I'm dealing at the same time with Google services authentication which have proven to be dificult using this extention. I tested it with <code>nbsphinx</code> which have proven being more reliable when dealing with .config parameters. The only thing I'm missing from my rst file is the admonitions.</p> <p>Given the following paragraph wriiten in rst:</p> <pre><code>.. warning:: The names of countries are all unique but not the smaller administrative layers. </code></pre> <p>How could I write down the same thing in a notebook markdown cell to be correctly interpreted by <code>nbsphinx</code> ?</p>
<python><python-sphinx><nbsphinx>
2023-07-21 08:41:20
1
2,670
Pierrick Rambaud
76,736,387
11,162,983
AssertionError: Mismatch in batch_size and euler_angles shape
<p>I tried to compute the Euler angles from the quaternion using this code:</p> <pre><code>def compute_euler_angles_from_quaternion(quaternions, sequence='xyz'): &quot;&quot;&quot; Convert a batch of quaternions to Euler angles. Args: quaternions: Tensor of shape (batch_size, 4). Batch of quaternions. sequence: String specifying the rotation sequence. Default is 'xyz'. Returns: euler_angles: Tensor of shape (batch_size, 3). Batch of Euler angles. &quot;&quot;&quot; batch_size = quaternions.shape[0] q = quaternions.detach().cpu().numpy() # Convert to NumPy array rotations = Rotation.from_quat(q) euler_angles = rotations.as_euler(sequence, degrees=False) euler_angles = torch.tensor(euler_angles, device=quaternions.device) euler_angles = euler_angles.view(batch_size, 3) return euler_angles </code></pre> <p>but I got this issue:</p> <pre><code>RuntimeError: shape '[4, 3]' is invalid for input of size 3 </code></pre> <p>I tried to fix it using this code as I found some solution <a href="https://stackoverflow.com/a/60439832/11162983">here</a>:</p> <pre><code>def compute_euler_angles_from_quaternion(quaternions, sequence='xyz'): batch_size = quaternions.shape[0] # Ensure that batch_size is correctly calculated print(&quot;Batch size:&quot;, batch_size) q = quaternions.detach().cpu().numpy() # Convert to NumPy array rotations = Rotation.from_quat(q) euler_angles = rotations.as_euler(sequence, degrees=False) print(&quot;Shape of euler_angles:&quot;, euler_angles.shape) if batch_size == 1: euler_angles = euler_angles.reshape(1, -1) # Reshape single quaternion to (1, 3) euler_angles = torch.tensor(euler_angles, device=quaternions.device) assert batch_size == euler_angles.shape[0], &quot;Mismatch in batch_size and euler_angles shape&quot; euler_angles = euler_angles.view(batch_size, 3) # Reshape to [batch_size, 3] return euler_angles </code></pre> <p>I got this issue when I input some batch sizes only for example 1 or 2 or 16:</p> <pre><code>Batch size: 4 Shape of euler_angles: (3,) Traceback (most recent call last): File &quot;test_quat.py&quot;, line 147, in &lt;module&gt; euler = utils.compute_euler_angles_from_quaternion( File &quot;/home/redhwan/2/HPE/quat/utils.py&quot;, line 318, in compute_euler_angles_from_quaternion assert batch_size == euler_angles.shape[0], &quot;Mismatch in batch_size and euler_angles shape&quot; AssertionError: Mismatch in batch_size and euler_angles shape </code></pre>
<python><numpy><scipy><touch>
2023-07-21 08:34:58
1
987
Redhwan
76,736,361
10,666,991
Llama QLora error: Target modules ['query_key_value', 'dense', 'dense_h_to_4h', 'dense_4h_to_h'] not found in the base model
<p>I tried to load <code>Llama-2-7b-hf</code> LLM with <code>QLora</code> with the following code:</p> <pre><code>model_id = &quot;meta-llama/Llama-2-7b-hf&quot; tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=True) # I have permissions. model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, quantization_config=bnb_config, device_map=&quot;auto&quot;, use_auth_token=True) model.gradient_checkpointing_enable() model = prepare_model_for_kbit_training(model) config = LoraConfig( r=8, lora_alpha=32, target_modules=[ &quot;query_key_value&quot;, &quot;dense&quot;, &quot;dense_h_to_4h&quot;, &quot;dense_4h_to_h&quot;, ], lora_dropout=0.05, bias=&quot;none&quot;, task_type=&quot;CAUSAL_LM&quot; ) model = get_peft_model(model, config) # got the error here </code></pre> <p>I got this error:</p> <pre><code> File &quot;/home/&lt;my_username&gt;/.local/lib/python3.10/site-packages/peft/tuners/lora.py&quot;, line 333, in _find_and_replace raise ValueError( ValueError: Target modules ['query_key_value', 'dense', 'dense_h_to_4h', 'dense_4h_to_h'] not found in the base model. Please check the target modules and try again. </code></pre> <p>How can I solve this? Thank you!</p>
<python><quantization><large-language-model><peft>
2023-07-21 08:31:55
2
781
Ofir
76,736,359
14,072,456
Is there an option to set the box-shadow of QMenu?
<p>I'm creating an app in PyQt5 in Python and i'm trying to customize the way the <code>QMenu()</code> looks. With setting some Window Flags and styling, I was able to make the menu look like this:</p> <p><a href="https://i.sstatic.net/xZcOY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xZcOY.png" alt="Modified QMenu" /></a></p> <p>And this is my code:</p> <pre><code>def main(): app = QApplication(sys.argv) win = QMainWindow() app.setStyleSheet(''' QMenu { background: #2b2b2b; color: white; border-radius: 5px; border: 1px solid #3e3e3e; } QMenu::item { border-radius: 3px; padding: 4px 25px; margin: 2px 5px; } QMenu::item:selected { background: #353535; } ''') menubar = QMenuBar() settingsmenu = QMenu(menubar) settingsmenu.setTitle(&quot;Settings&quot;) settingsmenu.setWindowFlags(settingsmenu.windowFlags() | QtCore.Qt.FramelessWindowHint) settingsmenu.setWindowFlags(settingsmenu.windowFlags() | QtCore.Qt.NoDropShadowWindowHint) settingsmenu.setAttribute(QtCore.Qt.WA_TranslucentBackground) run_on_start = QAction(text=&quot;Run On Startup&quot;, checkable=True) start_minimized = QAction(text=&quot;Start Minimized&quot;, checkable=True) settingsmenu.addAction(run_on_start) settingsmenu.addAction(start_minimized) menubar.addAction(settingsmenu.menuAction()) win.setMenuBar(menubar) win.show() sys.exit(app.exec_()) main() </code></pre> <p>I got rid of the default PyQt5 box-shadow, because I think it's ugly and too harsh.</p> <p>This is exactly how I want it to look, except I want it to have some sort of a shadow around it (just not the default one). Menu's from other applications all seem to have exactly the same shadow, which means that Windows itself probably applies these shadows to them as seen below:</p> <p>The menu from VS Code with a subtle drop-shadow</p> <p><a href="https://i.sstatic.net/6YFM4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6YFM4.png" alt="VS Code Menu" /></a></p> <p>The (tray)menu from Spotify with that same drop-shadow (A little harder to see)</p> <p><a href="https://i.sstatic.net/25fwV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/25fwV.png" alt="Spotify Menu" /></a></p> <p>And this is my menu with the default shadow (the app is called 'Playtimer')</p> <p><a href="https://i.sstatic.net/HggHr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/HggHr.png" alt="My Menu" /></a></p> <p>So my question is: Is there a way to let Windows know that the menu needs a shadow, just not the default one.</p> <p>Let me know if you need to know anything else to answer my question.</p>
<python><pyqt5><dropshadow>
2023-07-21 08:31:38
0
339
Itsjul1an
76,736,152
8,986,622
Pandas split only columns with complex data into real- and imaginary part
<p>I am new to pandas and am trying to work with Dataframes containing a mix of complex-valued numerical data and some other stuff (strings etc.)</p> <p>A stripped down version of what I am talking about:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd a = np.array([ [0.1 + 1j, 0.2 + 0.2j, 0.2, 0.1j, &quot;label_a&quot;, 1], [0.1 + 1j, 0.5 + 1.2j, 0.5, 1.0j, &quot;label_b&quot;, 3], ]) columns = np.array([-12, -10, 10, 12, &quot;label&quot;, &quot;number&quot;]) df = pd.DataFrame(data=a, columns=columns) </code></pre> <p>For the purpose of saving and reading to disk persistently, I need to split the complex values into their real- and imaginary, since apparently none of the relevant disk formats (hdf5, parquet, etc.) support complex numbers.</p> <p>Now if the dataframe were to contain <em>only</em> complex numbers, I could do this by introducing a multi-index, which is what other questions already cover (e.g. <a href="https://stackoverflow.com/questions/44720253/modify-dataframe-with-complex-values-into-a-new-multiindexed-dataframe-with-real">Modify dataframe with complex values into a new multiindexed dataframe with real and imaginary parts using pandas</a>).</p> <pre class="lang-py prettyprint-override"><code># save to file pd.concat( [df.apply(np.real), df.apply(np.imag)], axis=1, keys=(&quot;R&quot;, &quot;I&quot;), ).swaplevel(0, 1, 1).sort_index(axis=1).to_parquet(file) # read from file df = pd.read_parquet(file) real = df.loc[:, (slice(None), &quot;R&quot;)].droplevel(1, axis=1) imag = df.loc[:, (slice(None), &quot;I&quot;)].droplevel(1, axis=1) df = real + 1j * imag </code></pre> <p>However this approach breaks down in the presence of e.g. string fields.</p> <p>I am currently doing this by splitting the dataframe into one containing only complex numbers (i.e. the first four columns here) and the rest. Then I apply the above approach on the former, merge with the latter and save to file. This works, but isn't particularly nice, especially when the columns aren't ordered that neatly.</p> <p>I was hoping that someone with more pandas experience would have a simpler way of achieving that. In case it matters: In terms of performance, I don't care about writes, but I do care about reading from file back into a dataframe.</p>
<python><pandas><dataframe><complex-numbers>
2023-07-21 07:56:26
2
1,187
Banana
76,735,989
11,238,061
How to remove multiple Dataframe header suffices that start with \?
<p>I have a Dataframe <code>data</code>, whose headers contain multiple different suffices. The common feature among all headers is that the suffix begins with ;</p> <pre><code>Column-A\foo Column-B\bar some data some data </code></pre> <p>I'm trying to get the output to look like;</p> <pre><code>Column-A Column-B some data some data </code></pre> <p>I have tried;</p> <pre><code>data.columns = data.columns.str.replace(r'\$', '') </code></pre> <p>But this does not work.</p> <p>Is there a nice way to do this or should I specify the full name of each suffix?</p>
<python>
2023-07-21 07:31:39
2
419
Iceberg_Slim
76,735,757
3,952,274
'Task got bad yield' when wrapping streaming response to use as a normal generator
<p>I have a FastAPI backend with a POST endpoint that response with a streaming response and I need to wrap the call to the endpoint in a way that I can use the response as a normal (not async) iterator. I try to achieve this by wrapping the call with asyncio's <code>run_until_complete</code> in a seperate thread and providing a queue to be filled, so that the main thread can pull out the elements of the response as they appear in the queue.</p> <p>When doing so the queue seems to be filled just fine, however when pulling the elements from the queue and yielding them I get <code>RuntimeError: Task got bad yield 'something'</code>. I hope the idea is clear. A minimal example of the code:</p> <pre><code>import queue import httpx from threading import Thread import asyncio def process_stream(input): q = queue.Queue() job_done = object() def task(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(process_stream_async(input, q)) loop.close() q.put(job_done) t = Thread(target=task) t.start() while True: try: next_token = q.get(True, timeout=1) if next_token is job_done: break yield next_token # &lt;-- here I get the error except queue.Empty: continue async def process_stream_async(input, q): payload = { &quot;input&quot;: input } async with httpx.AsyncClient(timeout=None) as client: async with client.stream(&quot;POST&quot;, url=BACKEND + &quot;/process-stream&quot;, json=payload) as stream: async for item in stream.aiter_raw(): q.put(item) </code></pre> <p>In another place I then want to use <code>process_stream</code> as a generator like so:</p> <pre><code>for token in process_stream(&quot;some input&quot;): print(token) </code></pre> <p>I already did some extensive google and SO searches and couldn't find anything that helps me solve my problem. Or maybe I'm just stupid and/or blind. Relevant results with an accepted answer are:</p> <p><a href="https://stackoverflow.com/questions/30172821/python-asyncio-task-got-bad-yield">Python asyncio task got bad yield</a></p> <p><a href="https://stackoverflow.com/questions/68732435/python-task-got-bad-yield">python: Task got bad yield:</a></p> <p>I hope the problem is clear.</p> <p>Thanks in advance.</p>
<python><python-asyncio><generator><httpx>
2023-07-21 06:58:23
1
644
thomas
76,735,735
625,350
Xarray don't append dimension when concatenating datasets
<p>I've got two datasets that I want to concatenate. They each contain two arrays, a two dimensional <em>intensity</em> array (dims = time * wavelength) and an unrelated 1D array with <em>channel names</em>, which is the same in both datasets. When I concatenate along the time dimension, an extra time dimension is added to the channel names array. This makes somewhat sense, and is also mentioned in the documentation, but I would like the channel names to remain the same in the result. How can I prevent this extra dimension?</p> <p>The following example demonstrates what I want.</p> <pre><code>import numpy as np import xarray as xr DIM_TIME = &quot;time&quot; DIM_CHANNEL_NR = 'channel_number' DIM_WAVELENGTH = &quot;wavelength&quot; def create_ds(intensity, time_local): wavelength = np.linspace(700.0, 800.0, 8) da_wav = xr.DataArray(wavelength, dims=[DIM_WAVELENGTH]) da_time = xr.DataArray(time_local, dims=[DIM_TIME]) da_chan_nr = xr.DataArray(np.array([1, 2]), dims=[DIM_CHANNEL_NR]) da_intensity = xr.DataArray( intensity, name='intensity', dims=[DIM_TIME, DIM_WAVELENGTH], coords={DIM_TIME: da_time, DIM_WAVELENGTH: da_wav}) da_chan_name = xr.DataArray( data = np.array(['UV', 'VIS']), name = 'chan_name', dims = [DIM_CHANNEL_NR]) ds = xr.Dataset( data_vars={da_intensity.name: da_intensity}, coords={ DIM_TIME: da_time, DIM_WAVELENGTH: da_wav, DIM_CHANNEL_NR: da_chan_nr}) ds[da_chan_name.name] = da_chan_name return ds def main(): ds1 = create_ds( intensity=np.arange(24).reshape((3, 8)), time_local = np.array([1e17, 2e17, 3e17]).astype('datetime64[ns]')) ds2 = create_ds( intensity=np.arange(24).reshape((3, 8)) + 24, time_local = np.array([4e17, 5e17, 6e17]).astype('datetime64[ns]')) print(&quot;---- concat ----\n{}\n&quot;.format(xr.concat([ds1, ds2], dim=DIM_TIME))) print(&quot;---- merged ----\n{}\n&quot;.format(xr.merge([ds1, ds2]))) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>When I run this, the concatenated dataset looks like this.</p> <pre><code>---- concat ---- &lt;xarray.Dataset&gt; Dimensions: (time: 6, wavelength: 8, channel_number: 2) Coordinates: * time (time) datetime64[ns] 1973-03-03T09:46:40 ... 1989-01-05T... * wavelength (wavelength) float64 700.0 714.3 728.6 ... 771.4 785.7 800.0 * channel_number (channel_number) int32 1 2 Data variables: intensity (time, wavelength) int32 0 1 2 3 4 5 6 ... 42 43 44 45 46 47 chan_name (time, channel_number) &lt;U3 'UV' 'VIS' 'UV' ... 'UV' 'VIS' </code></pre> <p>As you can see, the <code>chan_name</code> array is now two dimensional; the <code>time</code> dimension has been prepended.</p> <p>When I merge the datasets, the result is exactly as I want it:</p> <pre><code>---- merged ---- &lt;xarray.Dataset&gt; Dimensions: (time: 6, wavelength: 8, channel_number: 2) Coordinates: * time (time) datetime64[ns] 1973-03-03T09:46:40 ... 1989-01-05T... * wavelength (wavelength) float64 700.0 714.3 728.6 ... 771.4 785.7 800.0 * channel_number (channel_number) int32 1 2 Data variables: intensity (time, wavelength) float64 0.0 1.0 2.0 ... 45.0 46.0 47.0 chan_name (channel_number) &lt;U3 'UV' 'VIS' </code></pre> <p>Here the <code>chan_name</code> array remains the same as in the original datasets, a one-dimensional array.</p> <p>Unfortunately, <code>xr.merge</code> is much slower than <code>xr.concat</code>. It there a way to concatenate that leaves unrelated arrays in tact?</p>
<python><numpy><python-xarray>
2023-07-21 06:53:23
1
5,596
titusjan
76,735,392
4,603,642
Using ParamSpec with Protocol instead of with Callable in Python 3.11
<p>In the following code, I define a function type using either <code>Protocol</code> or <code>Callable</code>.</p> <p><em>mypy</em> complains about my use of <code>Protocol</code>. I added <em>mypy</em>'s error as a comment directly in the code.</p> <p><em>Pylance</em> finds no errors.</p> <pre class="lang-py prettyprint-override"><code>from typing import Protocol, TypeVar, ParamSpec, Callable, Concatenate P = ParamSpec('P') R = TypeVar('R', covariant=True) class FuncType(Protocol[P, R]): def __call__(self, x: int, s: str, *args: P.args, **kw_args: P.kwargs) -&gt; R: ... def forwarder1(fp: FuncType[P, R], *args: P.args, **kw_args: P.kwargs) -&gt; R: return fp(0, '', *args, **kw_args) def forwarder2(fp: Callable[Concatenate[int, str, P], R], *args: P.args, **kw_args: P.kwargs) -&gt; R: return fp(0, '', *args, **kw_args) def my_f(x: int, s: str, d: float) -&gt; str: return f&quot;{x}, {s}, {d}&quot; # Argument 1 to &quot;forwarder1&quot; has incompatible type &quot;Callable[[int, str, float], str]&quot;; # expected &quot;FuncType[&lt;nothing&gt;, &lt;nothing&gt;]&quot; # Argument 2 to &quot;forwarder1&quot; has incompatible type &quot;float&quot;; # expected &lt;nothing&gt; forwarder1(my_f, 1.2) # no errors here forwarder2(my_f, 1.2) </code></pre> <p>Have I come across a bug in <em>mypy</em>, or is there really something wrong with my use of <code>Protocol</code>?</p>
<python><python-3.x><mypy>
2023-07-21 05:46:33
0
478
Kiuhnm
76,735,298
10,194,070
python + how to verify which python wheel or rpm installed that equivalent to import XXXX
<p>in some python script we can see the import of some python modules as</p> <pre><code>import yum import rpm . . . </code></pre> <p>can we find exactly the rpm or wheel that actually installed the yum or the rpm ?</p> <p>for example by <code>pip list | grep yum</code></p> <p>I not sure that I get the wheel that represent the &quot;<code>yum import</code>&quot;</p> <p>and from <code>rpm -qa | grep yum</code> I get long list</p> <p>so how to know the specific package that installed ? that related to <code>import yum</code> ?</p>
<python><linux><pip><rpm><python-wheel>
2023-07-21 05:20:34
1
1,927
Judy
76,735,254
1,912,104
Error after installing Matlab integration for Jupyter
<p>I'm trying to integrate MATLAB into Jupyter to use markdown features in Jupyter notebooks. I've follow this guide on github for the proxy installation to Anaconda environment: <a href="https://github.com/mathworks/jupyter-matlab-proxy#matlab-kernel-create-a-jupyter-notebook-using-matlab-kernel-for-jupyter" rel="nofollow noreferrer">https://github.com/mathworks/jupyter-matlab-proxy#matlab-kernel-create-a-jupyter-notebook-using-matlab-kernel-for-jupyter</a></p> <p>The installation appears OK and I can start a MATLAB kernel. However, I can't execute any commands with a message saying: <code>Error connecting to MATLAB. Check the status of MATLAB by clicking the &quot;Open MATLAB&quot; button. Retry after ensuring MATLAB is running successfully</code> as seen below.</p> <p>The problem is I don't see such &quot;Open MATLAB&quot; button on the kernel. I've tried restarting both Anaconda and the computer but it doesn't work. Is there a solution for this issue?</p> <p><a href="https://i.sstatic.net/Onf0t.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Onf0t.png" alt="enter image description here" /></a></p>
<python><matlab><jupyter-notebook><anaconda>
2023-07-21 05:07:47
1
851
NonSleeper
76,735,115
4,671,619
How can I get a closed trade data from Kucoin Futures account using ccxt?
<p>I have a Python script to get past trades, gives me the order info but I'm looking to get data for a closed position, like closed price, leverage entry etc., and as a bonus if available PnL.</p> <p>Here is the Python script to get my trades:</p> <pre><code>import ccxt import json import sys key = 'key' secret = 'secret' password = 'password' symbol = 'BTC/USDT:USDT' ku = ccxt.kucoinfutures({ 'adjustForTimeDifference': True, 'apiKey': key, 'secret': secret, 'password': password, 'enableRateLimit': True, }) # Call the API to get all trades all_trades = ku.fetch_my_trades(symbol) #show all trades but doesn't include the closed order data print(all_trades) </code></pre> <p>I've gone through the ccxt docs but don't see anything about the data about the trades closed price or other relevant data.</p> <p><a href="https://docs.ccxt.com/#/" rel="nofollow noreferrer">https://docs.ccxt.com/</a></p>
<python><ccxt><kucoin>
2023-07-21 04:24:30
0
751
Ryan D
76,734,956
11,163,122
raise_for_status equivalent for http.client.HTTPResponse?
<p>Python's third party <a href="https://requests.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>requests</code></a> library has the convenient method <a href="https://requests.readthedocs.io/en/latest/api/#requests.Response.raise_for_status" rel="nofollow noreferrer"><code>raise_for_status</code></a> to auto-raise an <code>HTTPError</code>.</p> <p>What is an equivalent function for the built-in <a href="https://docs.python.org/3/library/http.client.html#http.client.HTTPResponse" rel="nofollow noreferrer"><code>http.client.HTTPResponse</code></a>?</p> <hr /> <p>I made the below snippet up, and it seems pretty manual. Is there a simple built-in function I can call, equivalent to <code>raise_for_status</code>?</p> <pre class="lang-py prettyprint-override"><code>import http.client from urllib.error import HTTPError def raise_for_status(response: http.client.HTTPResponse) -&gt; None: if response.status != 200: raise HTTPError( url=response.url, code=response.status, msg=response.reason, hdrs=response.headers, fp=response.fp, ) </code></pre>
<python><python-requests><http-error>
2023-07-21 03:34:06
0
2,961
Intrastellar Explorer
76,734,723
1,914,781
python merge xml files
<p>Say input a.xml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;permissions&gt; &lt;privapp-permissions package=&quot;a&quot;&gt; &lt;permission name=&quot;x&quot;/&gt; &lt;permission name=&quot;y&quot;/&gt; &lt;/privapp-permissions&gt; &lt;/permissions&gt; </code></pre> <p>And b.xml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;permissions&gt; &lt;privapp-permissions package=&quot;a&quot;&gt; &lt;permission name=&quot;x&quot;/&gt; &lt;permission name=&quot;z&quot;/&gt; &lt;/privapp-permissions&gt; &lt;/permissions&gt; </code></pre> <p>Expected output c.xml:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;permissions&gt; &lt;privapp-permissions package=&quot;a&quot;&gt; &lt;permission name=&quot;x&quot;/&gt; &lt;permission name=&quot;y&quot;/&gt; &lt;permission name=&quot;z&quot;/&gt; &lt;/privapp-permissions&gt; &lt;/permissions&gt; </code></pre> <p>I write below code but it just append it not merge:</p> <pre><code>import xml.etree.ElementTree as ET fname1 = &quot;a.xml&quot; fname2 = &quot;b.xml&quot; fname3 = &quot;c.xml&quot; tree1 = ET.parse(fname1) root1 = tree1.getroot() tree2 = ET.parse(fname2) root2 = tree2.getroot() merged_tree = ET.ElementTree(ET.Element('root')) merged_tree.getroot().append(root1) merged_tree.getroot().append(root2) merged_tree.write(fname3, encoding='utf-8') </code></pre>
<python><xml>
2023-07-21 02:10:42
2
9,011
lucky1928
76,734,679
6,495,199
async httpx requests fails when using redis cache backend
<p>I'm running a FastAPI that makes some external calls to fetch data and it use the cache decorator to store the auth tokens; The app works with in-memory and Redis Backend (usually in-memory for local dev, but I tried to test the code for both backends)</p> <p>Now, recently I'm moving from sync calls to async calls; I mean, from <code>requests</code> to <code>httpx</code> but I did notice the <code>httpx</code> calls fails when I use redis as cache Backend but works properly when in-memory.</p> <p>Any ideas to troubleshoot this problem?</p>
<python><python-3.x><redis><fastapi><httpx>
2023-07-21 01:54:47
1
354
Carlos Rojas
76,734,672
5,113,584
Insert a tabular data in x,y position in a pdf using python
<p>I need to insert tabular data into an existing pdf at a particular position(an x,y position). How can I implement it? Which Python pdf library is best for the use case? Table format data should be formattable like bold, coloring, etc.</p>
<python><html-table><pdf-generation><pypdf>
2023-07-21 01:53:43
1
526
akhil viswam
76,734,643
1,361,885
Python unit test failing in Docker
<p>I am trying to run a Python unit test within a docker image.</p> <p>This is the Dockerfile used to create the image</p> <pre><code>FROM python:3.8-alpine COPY lambda/ /app WORKDIR /app RUN pip install -r requirements.txt RUN pip install unittest-xml-reporting CMD [] </code></pre> <p>and I try to run with</p> <pre><code> docker run -i --rm \ -v ${WORK_DIR}/lambda/junit-reports:/app/junit-reports \ eng-metrics:test_python38 \ python -m xmlrunner --output-file junit-reports/test-file.xml *_test.py </code></pre> <p>The error I get is</p> <pre><code>Running tests... ---------------------------------------------------------------------- E ====================================================================== ERROR [0.002s]: *_test (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: *_test Traceback (most recent call last): File &quot;/usr/local/lib/python3.8/unittest/loader.py&quot;, line 154, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module named '*_test' ---------------------------------------------------------------------- Ran 1 test in 0.002s FAILED (errors=1) </code></pre> <p>But, if I enter the running Image and manually trigger the test it works</p> <pre><code>docker run -it eng-metrics:test_python38 /bin/sh /app # python -m xmlrunner --output-file junit-reports/test-file.xml *_test.py Running tests... Ran 15 tests in 0.024s OK Generating XML reports </code></pre> <p>Any idea what could be wrong here?</p> <p><strong>EDIT</strong>: I found a way to make it work, it doesn't answer the question though.</p> <p>Changing the command line to the following works</p> <pre><code>python -m xmlrunner --output-file junit-reports/test-file.xml discover -s /app -p &quot;*_test.py&quot; </code></pre>
<python><docker><unit-testing><python-unittest>
2023-07-21 01:45:15
2
385
Eduardo Rodrigues
76,734,537
398,670
Install setuptools options.extras_require with pipenv
<p>When I use <code>pipenv</code> to set up a venv for my project, it doesn't install any of the development and test dependencies from the <code>setuptools</code> <code>setup.cfg</code> 's <code>options.extras_require</code> clause, so tools like <code>pytest</code> and <code>pyhamcrest</code> aren't available within <code>pipenv shell</code>.</p> <p>My <code>Pipfile</code> <code>[packages]</code> directive was created with <code>pipenv install -e .</code> and contains:</p> <pre><code>[packages] my-package = {editable = true, path = &quot;.&quot;} </code></pre> <p>The corresponding project's <code>setup.cfg</code> has</p> <pre><code>[options.extras_require] test = pytest pytest-cov pyhamcrest debug = ipython ipdb </code></pre> <p>But <code>pipenv install</code>, <code>pipenv sync --dev</code>, etc seem to ignore this.</p>
<python><setuptools><pipenv>
2023-07-21 01:13:22
1
328,701
Craig Ringer
76,734,430
3,842,788
Long lines in python are not getting reformatted in vscode
<p>.vscode/settings.json</p> <pre class="lang-json prettyprint-override"><code>{ &quot;python.linting.pylintEnabled&quot;: false, &quot;python.linting.enabled&quot;: true, &quot;python.linting.pylintArgs&quot;: [ &quot;-d&quot;, &quot;C0301&quot; ], &quot;python.testing.unittestArgs&quot;: [ &quot;-v&quot;, &quot;-s&quot;, &quot;.&quot;, &quot;-p&quot;, &quot;test_*.py&quot; ], &quot;python.testing.pytestEnabled&quot;: false, &quot;python.testing.unittestEnabled&quot;: true, &quot;[python]&quot;: { &quot;editor.defaultFormatter&quot;: &quot;ms-python.autopep8&quot; }, // &quot;python.formatting.provider&quot;: &quot;none&quot;, &quot;python.formatting.provider&quot;: &quot;autopep8&quot;, &quot;python.formatting.autopep8Args&quot;: [ &quot;--max-line-length&quot;, &quot;79&quot;, &quot;--experimental&quot; ] } </code></pre> <p>code:</p> <pre class="lang-py prettyprint-override"><code>if (1 == 10192310928301928301928301928301923 and rx_resp == 'aosidjaoisdjaoisdjaoisjdaoisjdaoisjdaoisjd' and 44 == 11111): print('aoisjdoaijsdoiajsdoaisjdoaijsdoaisjdoaisjdaoisjdiasjdoajaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') </code></pre> <p>No error shown on these long lines. When I click on format I should see some error saying line too long or linter should automatically break lines into shorter format.</p>
<python><visual-studio-code>
2023-07-21 00:30:14
2
6,957
Aseem
76,734,333
7,910,304
Pydantic V2 - @field_validator `values` argument equivalent
<p>I'm migrating from v1 to v2 of Pydantic and I'm attempting to replace all uses of the deprecated @validator with @field_validator.</p> <p>Previously, I was using the <code>values</code> argument to my validator function to reference the values of other previously validated fields. As the <a href="https://docs.pydantic.dev/1.10/usage/validators/#field-checks" rel="noreferrer">v1 docs say</a>:</p> <blockquote> <p>You can also add any subset of the following arguments to the signature (the names must match):</p> <ul> <li>values: a dict containing the name-to-value mapping of any previously-validated fields</li> </ul> </blockquote> <p>It seems this <code>values</code> argument is no longer passed as the <code>@field_validator</code> signature has <a href="https://docs.pydantic.dev/latest/migration/#changes-to-validators-allowed-signatures" rel="noreferrer">changed</a>. However, the migration docs don't mention a <code>values</code> equivalent in v2 and the v2 validator documentation page has not yet been updated for v2.0.</p> <p>Does anyone know the preferred approach for v2?</p> <p>V1 validator:</p> <pre class="lang-py prettyprint-override"><code>@validator('password2') def passwords_match(cls, v, values, **kwargs): if 'password1' in values and v != values['password1']: raise ValueError('passwords do not match') return v </code></pre>
<python><pydantic>
2023-07-20 23:53:19
1
1,748
Daniel Long
76,734,236
7,910,304
Pydantic V2 - field_validator() got an unexpected keyword argument 'pre'
<p>I'm migrating from v1 to v2 of Pydantic and I'm attempting to replace all uses of the <a href="https://docs.pydantic.dev/dev-v2/migration/#validator-and-root_validator-are-deprecated" rel="noreferrer">deprecated</a> <code>@validator</code> with <code>@field_validator</code>.</p> <p>However, I was previously using the <code>pre</code> <a href="https://docs.pydantic.dev/1.10/usage/validators/#pre-and-per-item-validators" rel="noreferrer">validator argument</a> and after moving to <code>@field_validator</code>, I'm receiving the following error:</p> <pre><code>TypeError: field_validator() got an unexpected keyword argument 'pre' </code></pre> <p>Has the use of pre also been deprecated in V2? It seems it's still referenced in the <a href="https://docs.pydantic.dev/2.0/usage/validators/#pre-and-per-item-validators" rel="noreferrer">V2 validator documentation</a> though with the top-of-page warning:</p> <blockquote> <p>This page still needs to be updated for v2.0.</p> </blockquote> <p>Hoping somebody else has already worked through this and can suggest the best route forward. Thanks!</p>
<python><pydantic>
2023-07-20 23:20:46
1
1,748
Daniel Long
76,733,935
1,361,752
Can you use xarray inside of dask delayed functions
<p>I want to use <code>dask.delayed</code> in my work. Some of the functions I want to apply it to will work with <code>xarray</code> based data. I know <code>xarray</code> itself can use dask under the hood. For dask itself, it is recommended you don't pass dask arrays to delayed functions. I want to make sure that I don't hit any similar pitfalls by passing xarray objects to delayed function.</p> <p>My current assumption is I should avoid creating dask-backed xarray datasets, which I think will be achieved by avoiding the <code>chunk</code> keyword and not using <code>open_mfdataset</code>. My question is ifs this restriction necessary and sufficient to avoid problems?</p> <p>To give a concrete (but heavily simplified) example of the type of code I'm thinking to write, I'm thinking of something like this. The idea is that <code>dask.delayed</code> handles the parallelism, not <code>xarray</code>.</p> <pre class="lang-py prettyprint-override"><code>@dask.delayed def pow2(ds): return ds**2 delayed_ds = dask.delayed(xr.open_dataset)('myfile.nc') delayed_ds_squared = pow2(delayed_ds) ds_squared = dask.compute(delayed_ds) </code></pre>
<python><dask><python-xarray><dask-delayed>
2023-07-20 21:52:22
1
4,167
Caleb
76,733,841
9,795,817
Include groups that are excluded after grouping in PySpark
<p>For the sake of this question, suppose I'm counting all the values per day and hour in some silly dataframe <code>df</code>.</p> <p>Imagine there are no observations on <code>2023-07-19</code>. In this case, a simple <code>df.groupBy('date', 'hour').count()</code> will return a PySpark dataframe that is missing all day-hour combinations for the day that's missing.</p> <p>Is there a built-in function/method to complete the result of the <code>groupBy</code> with all possible group combinations? I can vaguely recall a <code>complete</code> or <code>expand</code> function in <code>dyplyr</code> (an R library) and I was hoping PySpark had something similar so as to avoid manually building a full catalog of combinations.</p> <p>In this example, the result would look as follows:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>hour</th> <th>count</th> </tr> </thead> <tbody> <tr> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <td>2023-07-18</td> <td>22</td> <td>3</td> </tr> <tr> <td>2023-07-18</td> <td>23</td> <td>2</td> </tr> <tr> <td>2023-07-20</td> <td>1</td> <td>1</td> </tr> <tr> <td>2023-07-20</td> <td>2</td> <td>3</td> </tr> <tr> <td>2023-07-20</td> <td>3</td> <td>3</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> </tr> </tbody> </table> </div> <p>As you can see, the combinations (2023-07-19, 1), (2023-07-19, 2), ... (2023-07-19, 22), (2023-07-19, 23) are missing.</p> <p>The result I'm looking for is:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>hour</th> <th>count</th> </tr> </thead> <tbody> <tr> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <td>2023-07-18</td> <td>22</td> <td>3</td> </tr> <tr> <td>2023-07-18</td> <td>23</td> <td>2</td> </tr> <tr> <td>2023-07-19</td> <td>1</td> <td>0</td> </tr> <tr> <td>2023-07-19</td> <td>2</td> <td>0</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <td>2023-07-19</td> <td>22</td> <td>0</td> </tr> <tr> <td>2023-07-19</td> <td>23</td> <td>0</td> </tr> <tr> <td>2023-07-20</td> <td>1</td> <td>1</td> </tr> <tr> <td>2023-07-20</td> <td>2</td> <td>3</td> </tr> <tr> <td>2023-07-20</td> <td>3</td> <td>3</td> </tr> <tr> <td>...</td> <td>...</td> <td>...</td> </tr> </tbody> </table> </div> <p>My real problem involves grouping by a few more columns, so manually building a full catalog will be tedious.</p>
<python><apache-spark><pyspark><group-by><left-join>
2023-07-20 21:33:56
1
6,421
Arturo Sbr
76,733,820
17,323,241
Tensorflow Object Detection Api (pip) Installation Error
<p>I'm trying to install the TensorFlow Object Detection API on Google Colab:</p> <pre><code>!git clone https://github.com/tensorflow/models.git %cd /content/models/research/ !protoc object_detection/protos/*.proto --python_out=. !cp object_detection/packages/tf2/setup.py . !python -m pip install . </code></pre> <p>And I get this error:</p> <pre><code>Collecting pyyaml&lt;6.0,&gt;=5.1 (from tf-models-official&gt;=2.5.1-&gt;object-detection==0.1) Using cached PyYAML-5.4.1.tar.gz (175 kB) Installing build dependencies ... done error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─&gt; See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. Getting requirements to build wheel ... error error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─&gt; See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. </code></pre> <p>I tried many things, including:</p> <ol> <li>Installing without cache:</li> </ol> <pre><code>!python -m pip install . --no-cache-dir </code></pre> <ol start="2"> <li>Resetting/deleting runtime</li> <li>Uninstalled all pip packages (hundreds):</li> </ol> <pre><code>!pip freeze &gt; requirements.txt !pip uninstall -r requirements.txt -y </code></pre> <ol start="4"> <li><p>Installing pyyaml separately (installs latest version successfully; the above script still fails)</p> </li> <li><p><code>!pip install tf-models-official&gt;=2.5.1</code></p> </li> <li><p><code>!pip install --upgrade pip setuptools</code></p> </li> </ol>
<python><tensorflow><pip><google-colaboratory><tensorflow2.0>
2023-07-20 21:30:18
1
857
ela16
76,733,815
293,003
How do I yield a custom object from a native Python coroutine?
<p>When using generator functions to implement coroutines (as it was common in Python 3.4 and earlier), it was easy to yield custom objects:</p> <pre class="lang-py prettyprint-override"><code>class CustomObject: pass def coroutine2(): yield CustomObject() return 'the result' def coroutine1(): return (yield from coroutine2()) it = coroutine1() while True: try: io_req = next(it) except StopIteration as exc: assert exc.value == 'the result' break assert isinstance(io_req, CustomObject) </code></pre> <p>How do I do the same thing using native co-routines? The naive approach fails, because there seems to be no equivalent to <code>yield</code> (<code>await</code> replaces <code>yield from</code>), and <code>yield</code> itself is not allowed in native coroutine:</p> <pre class="lang-py prettyprint-override"><code>class CustomObject: pass async def coroutine2(): # This gives: TypeError: CustomObject can't be used in 'await' expression #await CustomObject() # And this gives: TypeError: object async_generator can't be used in 'await' expression #yield CustomObject() # So what needs to go here? magic_keyword CustomObject() return 'the result' async def coroutine1(): return await coroutine2() it = coroutine1().__await__() while True: try: io_req = next(it) except StopIteration as exc: assert exc.value == 'the result' break assert isinstance(io_req, CustomObject) </code></pre>
<python><python-asyncio>
2023-07-20 21:29:07
2
2,489
Nikratio
76,733,588
13,287,930
Calculate mean of consecutive repititions of values in pandas dataframe / numpy array
<p>I have the following dataframe / numpy array:</p> <pre><code>a = np.array([ 55, 55, 69, 151, 151, 151, 103, 151, 151, 103]) df = pd.DataFrame([ 55, 55, 69, 151, 151, 151, 103, 151, 151, 103], columns = [&quot;AOI&quot;]) </code></pre> <ol> <li>The values in this array can range from 1 to 151. I need to calculate the average consecutive repetition of the values. This involves the following logic:</li> </ol> <ul> <li>55 occurs 2 time</li> <li>then 69 occurs 1 time</li> <li>then 151 occurs 3 times</li> <li>then 103 occurs 1 time</li> <li>then 151 occurs 2 times</li> <li>then 103 occurs 1 time.</li> </ul> <ol start="2"> <li>So I have the following occurences for each value:</li> </ol> <ul> <li>55: 2</li> <li>69: 1</li> <li>151: 3, 2</li> <li>103: 1, 1</li> </ul> <ol start="3"> <li>Now I need to calculate the mean of the occurences:</li> </ol> <ul> <li>55: 2</li> <li>69: 1</li> <li>151: 2.5 ((3+2)/2)</li> <li>103: 1 ((1+1)/2)</li> </ul> <p>Ideally, in the end I have a numpy array with 151 entries. Each entry is zero and at index 55 I have the value 2, at index 69 the value 1, at index 151 the value 2.5 and at index 103 the value 1:</p> <pre><code>[0,0,0,0,...,2,0,0,...,1,0,0,0,...,1,0,0,0,....,2.5] </code></pre> <p>How can this be achieved? Unfortunately, I am not even able to perform step 1. A simple groupby and count the rows does not work, as I need the count of consecutive occurences.</p>
<python><arrays><pandas><numpy>
2023-07-20 20:44:01
4
323
thyhmoo
76,733,560
2,274,981
Decoding Binary Data in Python
<p>I am attempting to decode some binary from an old document I have got hold of and I'm struggling.</p> <p>This is what I have:</p> <pre><code>FBE80YlsYgAIhjELHyhxUyQsNyQrawAMOgAQEAAQEAAIDwAUrgARCQAQHAATiAAY1QcwGQ AMMCbJCAARIgAMc4qUV4iRIgAUuAARtAAUV4iRUgAMPAAJKQ9sRoiRtAAUOCbBSJf0OwAJ jYIJjYIChhCq+v1bS0tHR0Y= </code></pre> <p>This code I then decode via Base64 to get this binary</p> <pre><code>0001010000010001001111001101000110001001011011000110001000000000000010 0010000110001100010000101100011111001010000111000101010011001001000010 1100001101110010010000101011011010110000000000001100001110100000000000 0100000001000000000000000100000001000000000000000010000000111100000000 0001010010101110000000000001000100001001000000000001000000011100000000 0000010011100010000000000000011000110101010000011100110000000110010000 0000000011000011000000100110110010010000100000000000000100010010001000 0000000000110001110011100010101001010001010111100010001001000100100010 0000000000010100101110000000000000010001101101000000000000010100010101 1110001000100100010101001000000000000011000011110000000000000010010010 1001000011110110110001000110100010001001000110110100000000000001010000 1110000010011011000001010010001001011111110100001110110000000000001001 1000110110000010000010011000110110000010000000101000011000010000101010 101111101011111101010110110100101101001011010001110100011101000110 </code></pre> <p>Then the only information I have is the following:</p> <pre><code>(length = 2, value = 2) (length = 1, value = 0) 00010 10 00001 0 </code></pre> <p>And somehow the resulting and this binary <code>00100 1111</code> the document states equals <code>15</code> I have no idea how it came to this.</p> <p>I did this in python but kind of got lost?</p> <pre><code>def getDivision(code): if not code: return &quot;Unknown division code&quot; base64data = base64.b64decode(code) binaryData = &quot;&quot; for x in base64data: a = bin(x)[2:] while len(a) &lt; 8: a = &quot;0&quot; + a binaryData = binaryData + a header = int(binaryData[12:17], 2) code = binaryData[17:17 + header] print(code) </code></pre> <p>Help explaining how this come about would be fantastic.</p>
<python>
2023-07-20 20:40:10
1
1,149
Lynchie
76,733,442
8,588,359
Python SyntaxError on fstring in the __repr__ method of the class
<p>My code:</p> <pre><code>class Book: all = [] def __init__(self, ISBN, title, subject, publisher, language, number_of_pages): self.__ISBN = ISBN self.__title = title self.__subject = subject self.__publisher = publisher self.__language = language self.__number_of_pages = number_of_pages self.__authors = [] Book.all.append(self) def __repr__(self): return f&quot;Title {self.__title} Subject {self.__subject}&quot; b = Book(23498723,&quot;this&quot;,&quot;fiction&quot;,&quot;penguin&quot;,&quot;en&quot;,196) </code></pre> <p>Error:</p> <pre><code> return f&quot;Title {self.__title} Subject {self.__subject}&quot; ^ SyntaxError: invalid syntax </code></pre> <p>Could anyone explain why this is an error?</p>
<python><python-3.x><syntax-error><f-string>
2023-07-20 20:18:48
1
4,129
Raj
76,733,426
6,032,140
Sed out matching the partial string from a full string in linux
<ol> <li><p>I have a full string as given below</p> <pre><code>&quot;^aloha_lang.maui_island_A_rams.blue.lagoon$&quot; </code></pre> </li> <li><p>And I have partial string to search to match</p> <pre><code>&quot;maui_.*_rams&quot; </code></pre> </li> <li><p>And if that partial string matches the full string, I wanted to sed out all the string until the matching string. For eg. the output wanted is</p> <pre><code>&quot;^maui_island_A_rams.blue.lagoon$&quot; </code></pre> </li> </ol> <p>Tried like this and other ways, buts its not sed'ing out correctly:</p> <pre><code>echo &quot;^aloha_lang.maui_island_A_rams.blue.lagoon$&quot; | sed 's/^[^maui_.*_rams]*//;p' </code></pre> <p>Any simple oneliner or basic step that I am missing ? Or a regular expression way in python</p>
<python><linux><awk><sed>
2023-07-20 20:15:58
3
1,163
Vimo
76,733,414
3,155,240
Can not get correct bounding box on svg to trim white space
<p>Quick note before the question: at this current time, <code>svgelements</code> (the Python library) is not a tag on SO, so I can not include it in this question. This being said, a solution doesn't have to exclusively use <code>svgelements</code>, nor use it at all.</p> <hr /> <p>I am trying to use the <code>svgelements</code> library to load a svg, get the bounding box that contains all of the elements with respect to their transformations, then set the viewBox of the svg to be that bounding box, as a method to trim all the white space around the elements. Here is what I have so far:</p> <pre><code>from pathlib import Path import svgelements as se def get_bbox(svg_file): svg_file = Path(svg_file) print(svg_file.name) svg = se.SVG.parse(str(svg_file)) bb = svg.bbox() minx, miny, maxx, maxy = bb width = maxx - minx height = maxy - miny # set the height and width of the physical size of the svg # I just make it the same as the viewbox width and height view_box = se.Viewbox(f&quot;{minx} {miny} {width} {height}&quot;) svg.values[&quot;attributes&quot;][&quot;height&quot;] = str(view_box.height) svg.values[&quot;height&quot;] = str(view_box.height) svg.values[&quot;attributes&quot;][&quot;width&quot;] = str(view_box.width) svg.values[&quot;width&quot;] = str(view_box.width) svg.viewbox = view_box # add a border around the svg to see if the contents are in the right place. if &quot;style&quot; not in svg.values[&quot;attributes&quot;]: svg.values[&quot;attributes&quot;][&quot;style&quot;] = &quot;&quot; if &quot;border&quot; not in svg.values[&quot;attributes&quot;][&quot;style&quot;]: svg.values[&quot;attributes&quot;][&quot;style&quot;] += &quot;border: solid black 1px;&quot; svg.write_xml(str(svg_file.with_stem(svg_file.stem + &quot;-new&quot;))) </code></pre> <p><a href="https://freesvg.org/gravure-link-not-afraid-geek-nintendo" rel="nofollow noreferrer">This</a> is the svg that I am having problems with.</p> <p>I've only tested this method out on 1 other svg, that seemed more basic with its mark-up, and it worked <em>well</em>. This one is more complicated, and I'd like to get it to work. Is there something that I am overlooking or is it just the svg? I've been able to successfully use chrome and the inspector to get the actual bounding box and set it to the viewBox (of course, those numbers are different than what is returned from the <code>svgelements</code> library).</p>
<python><svg>
2023-07-20 20:13:33
1
2,371
Shmack
76,733,283
782,152
confluent-kafka Python package in Snowpark
<p>I am looking for a way to connect to Confluent Platform to consume messages into Snowflake directly. I do not believe the Confluent Snowflake Sink Connector will work, as we are using Confluent Platform, not cloud.</p> <p>I tried importing the confluent-kafka packages into Snowpark via a .zip file in S3, since it's not in Snowpark's Anaconda build, and I keep getting this error on the import statement in Python in Snowpark via the constructor method of this package. AttributeError: module 'os' has no attribute 'add_dll_directory'</p> <p>I'm not sure if this package is just not able to be imported into Snowpark, or if I am missing something simple. The 3 folders I have in the zip are confluent_kafka, confluent_kafka.libs, confluent_kafka-2.2.0.dist-info</p> <p>Even if I comment out this line in the constructor, it then starts throwing errors on finding package refs like can't find confluent_kafka.cimpl</p> <p>Not sure what I'm doing wrong here.</p>
<python><apache-kafka><snowflake-cloud-data-platform><confluent-kafka-python>
2023-07-20 19:48:45
1
3,761
mameesh
76,733,277
4,718,335
Python Json Grouping with individuals
<p>Here is some demo data</p> <pre><code>[ { &quot;id&quot;: 1, &quot;first_name&quot;: &quot;John&quot;, &quot;last_name&quot;: &quot;Doe&quot;, &quot;company&quot;: &quot;ABC Corporation&quot;, &quot;email&quot;: &quot;john.doe@example.com&quot; }, { &quot;id&quot;: 2, &quot;first_name&quot;: &quot;Jane&quot;, &quot;last_name&quot;: &quot;Smith&quot;, &quot;company&quot;: &quot;ABC Corporation&quot;, &quot;email&quot;: &quot;jane.smith@example.com&quot; }, { &quot;id&quot;: 3, &quot;first_name&quot;: &quot;Michael&quot;, &quot;last_name&quot;: &quot;Johnson&quot;, &quot;company&quot;: &quot;ABC Corporation&quot;, &quot;email&quot;: &quot;michael.johnson@example.com&quot; }, { &quot;id&quot;: 4, &quot;first_name&quot;: &quot;Emily&quot;, &quot;last_name&quot;: &quot;Brown&quot;, &quot;company&quot;: &quot;BestCo&quot;, &quot;email&quot;: &quot;emily.brown@example.com&quot; }, { &quot;id&quot;: 5, &quot;first_name&quot;: &quot;David&quot;, &quot;last_name&quot;: &quot;Lee&quot;, &quot;company&quot;: &quot;BestCo&quot;, &quot;email&quot;: &quot;david.lee@example.com&quot; }, { &quot;id&quot;: 6, &quot;first_name&quot;: &quot;Sophia&quot;, &quot;last_name&quot;: &quot;Wang&quot;, &quot;company&quot;: &quot;Innovate Solutions&quot;, &quot;email&quot;: &quot;sophia.wang@example.com&quot; } ] </code></pre> <p>I want to group with individuals until it finished grouping by companies single item only. Like its output below</p> <pre><code>{ &quot;group1&quot;: [ { &quot;id&quot;: 1, &quot;first_name&quot;: &quot;John&quot;, &quot;last_name&quot;: &quot;Doe&quot;, &quot;company&quot;: &quot;ABC Corporation&quot;, &quot;email&quot;: &quot;john.doe@example.com&quot; }, { &quot;id&quot;: 4, &quot;first_name&quot;: &quot;Emily&quot;, &quot;last_name&quot;: &quot;Brown&quot;, &quot;company&quot;: &quot;BestCo&quot;, &quot;email&quot;: &quot;emily.brown@example.com&quot; }, { &quot;id&quot;: 6, &quot;first_name&quot;: &quot;Sophia&quot;, &quot;last_name&quot;: &quot;Wang&quot;, &quot;company&quot;: &quot;Innovate Solutions&quot;, &quot;email&quot;: &quot;sophia.wang@example.com&quot; } ], &quot;group2&quot;: [ { &quot;id&quot;: 2, &quot;first_name&quot;: &quot;Jane&quot;, &quot;last_name&quot;: &quot;Smith&quot;, &quot;company&quot;: &quot;ABC Corporation&quot;, &quot;email&quot;: &quot;jane.smith@example.com&quot; }, { &quot;id&quot;: 5, &quot;first_name&quot;: &quot;David&quot;, &quot;last_name&quot;: &quot;Lee&quot;, &quot;company&quot;: &quot;BestCo&quot;, &quot;email&quot;: &quot;david.lee@example.com&quot; } ], &quot;group3&quot;: [ { &quot;id&quot;: 3, &quot;first_name&quot;: &quot;Michael&quot;, &quot;last_name&quot;: &quot;Johnson&quot;, &quot;company&quot;: &quot;ABC Corporation&quot;, &quot;email&quot;: &quot;michael.johnson@example.com&quot; } ] } </code></pre> <p>in python</p>
<python>
2023-07-20 19:47:50
1
1,864
Russell
76,733,270
11,420,295
Avoid inner loop while iterating through nested data (performance improvement)?
<p>I am working with a large dataset (1 million + rows) and am tasked with counting up each truthy value for each ID and generating a new dict.</p> <p>The solution I came up with works, but does very poor in regards to performance.</p> <p>I have a dictionary as follow:</p> <pre><code> &quot;data&quot;: { &quot;employees&quot;: [ { &quot;id&quot;: 274, &quot;report&quot;: true }, { &quot;id&quot;: 274, &quot;report&quot;: false }, { &quot;id&quot;: 276, &quot;report&quot;: true }, { &quot;id&quot;: 276, &quot;report&quot;: true }, { &quot;id&quot;: 278, &quot;report&quot;: true }, { &quot;id&quot;: 278, &quot;report&quot;: false } ] } </code></pre> <p>I am looking to create a new dictionary with each individual employee ID with a count of each true value.</p> <p>Something like this:</p> <pre><code>{274: {'id': 274, 'count': 1}, 276: {'id': 276, 'count': 2}, 278: {'id': 278, 'count': 1}} </code></pre> <p>My current code:</p> <pre><code> final_dict = {} for employee in result[&quot;data&quot;][&quot;employees&quot;]: if employee[&quot;id&quot;] not in final_dict.keys(): final_dict[employee[&quot;id&quot;]] = {&quot;id&quot;: employee[&quot;id&quot;]} grouped_results = [res for res in result[&quot;data&quot;][&quot;employees&quot;] if employee[&quot;id&quot;] == res['id']] final_dict[employee[&quot;id&quot;]][&quot;count&quot;] = len( [res for res in grouped_results if res[&quot;report&quot;]] ) return final_dict </code></pre> <p>This does what it needs to do, but with the amount of data that is being processed it does very poorly.</p> <p>I am looking for some advice on how to avoid the multiple loops, in order to improve performance. Any advice helps!</p>
<python><python-3.x><dictionary>
2023-07-20 19:46:10
4
415
master_j02
76,733,253
18,313,588
Keep the data frame rows containing a value in one column which has multiple matches in another column
<p>Keep the data frame rows containing a value in one column which has multiple matches in another column.</p> <p>If <code>number</code> column has more than one matches in <code>letter</code> column, keep the rows.</p> <pre><code>number, letter 1, A 2, B 5, D 2, D 2, D 5, D </code></pre> <p>Expected Output:</p> <pre><code>number, letter 2, B 2, D 2, D </code></pre>
<python><python-3.x><pandas>
2023-07-20 19:42:17
1
493
nerd
76,733,134
3,091,161
Why slots=True makes a dataclass to ignore its default values?
<p>This code works as expected:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass @dataclass(slots=False, init=False) class Test: field: str = &quot;default value&quot; print(Test()) # outputs &quot;Test(field='default value')&quot; </code></pre> <p>However, if I change <code>slots</code> to <code>True</code>, it throws an AttributeError:</p> <pre><code>AttributeError: 'Test' object has no attribute 'field' </code></pre> <p>To fix the issue, I have to either use the generated <code>__init__</code> method or initialize all the fields within a custom <code>__init__</code> method explicitly. What is the reasoning behind this behavior?</p>
<python><python-dataclasses><slots>
2023-07-20 19:24:35
1
1,693
enkryptor
76,733,040
11,197,957
An up to date Python function for deleting files securely?
<p>I am trying to write an up to date <strong>Python</strong> function for removing files <strong>securely</strong>. This quest led me to <a href="https://stackoverflow.com/questions/17455300/python-securely-remove-file#:%7E:text=You%20can%20use%20srm%20to,()%20function%20to%20call%20srm.">this Stack Overflow question</a>, the answers to which, as I understand it, give me two options:</p> <ol> <li>Install the <code>srm</code> command, and call that using <code>subprocess</code> or something similar.</li> <li>Use a given custom function.</li> </ol> <p>I have to reject option (1) because, although I am using Linux myself, I am writing code destined for a custom PIP package, which needs to be as lightweight and portable as possible.</p> <p>As for option (2): I have distilled the various functions supplied in the answers to the aforementioned question into one function:</p> <pre class="lang-py prettyprint-override"><code>def secure_delete(path_to_file, passes=1): length = os.path.getsize(path_to_file) with open(path, &quot;br+&quot;, buffering=-1) as file_to_overwrite: for _ in range(passes): file_to_overwrite.seek(0) file_to_overwrite.write(os.urandom(length)) os.remove(path_to_file) </code></pre> <p>Now this looks like we could be getting somewhere, but I still have some queries:</p> <ul> <li>I believe that the <code>os.path</code> stuff has largely been superceded by <code>pathlib</code>. Is that correct?</li> <li>But what about that <code>os.urandom(length)</code> call? Is that the most efficient, up to date way of doing that?</li> <li>I understand what that <code>passes</code> variable is doing, but I do not understand what the point of it is. Is there really all the much to be gain, from a security point of view, by overwriting multiple times?</li> </ul>
<python><file><security>
2023-07-20 19:08:38
1
734
Tom Hosker
76,733,005
5,256,563
Time printed but image not loaded
<p>I created a dummy function to let me know which image is loading and how long it takes:</p> <pre><code>from PIL import Image from timeit import default_timer as timer def ImageLoad(path: str): print(&quot;Loading '&quot; + path + &quot;'... &quot;, end='') start = timer() im = Image.open(path) print(&quot;successfully (%.2fs).&quot; % (timer()-start)) return im </code></pre> <p>But when I use it, it always indicate 0 second even though the images are huge (about 20K x 60K pixels):</p> <pre><code>Loading 'Image0.png'... successfully (0.00s). Loading 'Image1.png'... successfully (0.00s). </code></pre> <p>I added another print after the function is called:</p> <pre><code>image = ImageLoad(path) print(&quot;Image loaded&quot;). </code></pre> <p>I see the second print being displayed at least 40 seconds after, which makes perfect sense.</p> <p>Why am I getting the the message immediately displayed despite the fact that the image is not loaded?</p>
<python><python-imaging-library><timeit>
2023-07-20 19:02:38
1
5,967
FiReTiTi
76,732,729
19,675,781
How to pivot a dataframe without aggregation?
<p>I have a dataframe like this:</p> <pre><code>l1 = ['a','b','c','d','a','b','c','d','e','f'] l2 = ['a1','b1','c1','d1','a1','b1','c1','d1','e1','f1'] l3 = ['a2','b2','c2','d2','a2','b2','c2','d2','e2','f2'] l4 = [1,2,3,4,5,6,7,8,9,10] df = pd.DataFrame({'Col1':l1,'Col2':l2,'Col3':l3,'Col4':l4}) </code></pre> <p><a href="https://i.sstatic.net/eaoTo.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eaoTo.png" alt="enter image description here" /></a></p> <p>I am trying to pivot the dataframe using pivot_table() but its aggregating to mean and returning only single row per index.</p> <pre><code>pd.pivot_table(df,columns='Col3',values='Col4',index=['Col1','Col2']) </code></pre> <p><a href="https://i.sstatic.net/fLTmO.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fLTmO.png" alt="enter image description here" /></a></p> <p>I want to display all the rows grouped by index without aggregation. So, the output has repeated index.</p> <p>Can anynoe help me withthis?</p>
<python><pandas><dataframe><pivot>
2023-07-20 18:21:43
0
357
Yash
76,732,708
6,525,082
How to do centering for a 2D numpy array?
<p>Is there an easy way compute the following array?</p> <pre><code>uc(i,j) = 0.25d0*(u(i,j+1)+u(i+1,j+1)+u(i+1,j)+u(i,j)) </code></pre> <p>I tried</p> <pre><code> from scipy.ndimage import generic_filter generic_filter(A, np.nanmean, mode='constant', cval=np.nan, size=2) </code></pre> <p>But this does not work. For example</p> <pre><code> A= np.array([[3, 4, 5], [5, 6, 7], [7, 8, 9]]) </code></pre> <p>then the result of generic filter is:</p> <pre><code> array([[3, 3, 4], [4, 4, 5], [6, 6, 7]]) </code></pre> <p>I am expecting the first element to be =(3+4+5+6)/4 =4.5</p> <p>How to do zone averaging in numpy?</p>
<python><numpy><scipy>
2023-07-20 18:17:52
2
1,436
wander95
76,732,496
22,212,435
Don't know how to create a class correctly
<p>I want to create a class from an Entry widget. The thing is that I want to add a frame to it, and it should be a parent for the entry. That is like to create an entry that will not be the main in its class, which is weird. So I just have no idea how to do that. If I inherits from a frame, I will have a functionality of a frame, not Entry. If I did from Entry, I have no idea of how to put A frame to be the main. There is a simple try, which is not working:</p> <pre><code>class AdvancedEntry(tk.Entry): def __init__(self, parent=None, *args, **kwargs): self.main_frame = tk.Frame(parent, width=300, height=50, background=&quot;black&quot;) self.main_frame.pack() super().__init__(master=self.main_frame, *args, **kwargs) </code></pre> <p>But then if I will pack this Entry, it will only pack it itself, but it should actually pack a frame. That is not working for obvious reasons, but I just don't know how to do that.</p> <p>Here is an example of what I am trying to achive without classes:</p> <pre><code>main_frame = tk.Frame(width=300, height=30, background=&quot;black&quot;) main_frame.pack_propagate(False) main_frame.pack() entry = tk.Entry(main_frame) entry.pack(fill=&quot;both&quot;, expand=True) </code></pre>
<python><python-3.x><tkinter>
2023-07-20 17:49:22
1
610
Danya K
76,732,403
3,347,814
How to sum x number of rows in Pandas without using iterrows()?
<p>I have a database and I want to create a column has the sum of that row and the next 3 rows of a given column. I have manage to accomplish this result using interrows(), however, I know this is not the ideal way to do this. I have tried using apply() and lambda functions in multiple ways, but I could not make it work.</p> <p>Here is the code that I wrote, which gets the desired result:</p> <pre><code>import pandas as pd mpg_df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv') sum_results = [] for index, row in mpg_df.iterrows(): inital_range = index final_range = index+4 if index+4 &lt;= mpg_df.shape[0] else mpg_df.shape[0] sum_result = mpg_df['mpg'].iloc[inital_range:final_range].sum() sum_results.append(sum_result) mpg_df[&quot;special_sum&quot;] = sum_results mpg_df </code></pre> <p>My question is, how can I get the same result, there is the &quot;special_sum&quot; column, without using interrows()?</p> <p>Edit: Personally, I do not have anything against interrrows(), however, I am trying to learn Pandas and best practices and according to this answer (<a href="https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas">How to iterate over rows in a DataFrame in Pandas</a>), I should not be using interrows(), they are quite explicit about that. I do not want to create a debate, I just want to know if there is a better way to accomplish the same task.</p>
<python><pandas>
2023-07-20 17:37:55
2
1,143
user3347814