QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
75,032,110
773,389
How can I use xlsxwriter to create one textbox on a worksheet with multiple formats?
<p>I am using xlswriter to create a textbox in a Excel worksheet as follows:</p> <pre><code>import xlsxwriter text = 'this is line 1 \nthis is line 2 \nthis is line 3' workbook = xlsxwriter.Workbook('c:/tmp/test.xlsx') worksheet = workbook.add_worksheet('Information') options = { 'width':200, 'height':200, 'font': { 'bold': True, 'size': 12 } } worksheet.insert_textbox(1, 1,text,options) workbook.close() </code></pre> <p>the result is:</p> <p><a href="https://i.sstatic.net/MWe7M.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MWe7M.png" alt="enter image description here" /></a></p> <p>What I want is to format lines 1, 2 and 3 differently. I can do it manually on Excel, by selecting the text and changing the font to look as follows:</p> <p><a href="https://i.sstatic.net/GooAL.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GooAL.png" alt="enter image description here" /></a></p> <p>How can I do this in Python? I can achieve this if I write to a cell but how can I do multiple formats in a textbox?</p>
<python><xlsxwriter>
2023-01-06 14:19:19
0
1,843
afshin
75,031,989
2,800,105
Encoding json to bytes
<p>I have a problem that bites its own tail. In the code below I am creating a json element with file-paths, these contain special characters. Encoding results in a unicode-escape characters and the path is not readable server receiving the json. If I try to encode the strings, before the json the json library can't serialize the content.</p> <pre><code>import urllib.request import json SERVER_URL = &quot;The_server_url:80&quot; REPOSITORY = &quot;Dashboards&quot; WORKSPACE = &quot;workspace.fmw&quot; TOKEN = &quot;Here_goes_the_token&quot; # Set up the published parameters as object params = { &quot;publishedParameters&quot; : [ { &quot;name&quot; : &quot;NuvAfvPath&quot;, &quot;value&quot; : 'T:/Projects/362/2021/3622100225 - Høje Gladsaxe Parken - naturlig hydrologi/Stofberegninger/Hestefolden/Hestefolden_afvandingskort_nuværende.tif' }, { &quot;name&quot; : &quot;DestDataset_XLSXW_7&quot;, &quot;value&quot; : '//corp.pbwan.net/dk/Projects/362/2021/3622100225 - Høje Gladsaxe Parken - naturlig hydrologi/Stofberegninger/20230105' }, { &quot;name&quot; : &quot;ProjAfvPath&quot;, &quot;value&quot;: 'T:/Projects/362/2021/3622100225 - Høje Gladsaxe Parken - naturlig hydrologi/Stofberegninger/Hestefolden/Hestefolden_afvandingskort_projekt.tif' }, { &quot;name&quot; : &quot;ProjOmrPath&quot;, &quot;value&quot;: 'T:/Projects/362/2021/3622100225 - Høje Gladsaxe Parken - naturlig hydrologi/Stofberegninger/Hestefolden/Projektområde_Hestefolden.shp' } ] } url = '{0}/fmerest/v2/transformations/commands/submit/{1}/{2}'.format(SERVER_URL, REPOSITORY, WORKSPACE) # Request constructor expects bytes, so we need to encode the string body = json.dumps(params).encode('utf-8') headers = { 'Content-Type' : 'application/json', 'Accept' : 'application/json', 'Authorization' : 'fmetoken token={0}'.format(TOKEN) } print(url) print(body) print(headers) </code></pre> <p>The print of the request body:</p> <pre><code>b'{&quot;publishedParameters&quot;: [{&quot;name&quot;: &quot;NuvAfvPath&quot;, &quot;value&quot;: &quot;T:/Projects/362/2021/3622100225 - H\\u00f8je Gladsaxe Parken - naturlig hydrologi/Stofberegninger/Hestefolden/Hestefolden_afvandingskort_nuv\\u00e6rende.tif&quot;}, {&quot;name&quot;: &quot;DestDataset_XLSXW_7&quot;, &quot;value&quot;: &quot;//corp.pbwan.net/dk/Projects/362/2021/3622100225 - H\\u00f8je Gladsaxe Parken - naturlig hydrologi/Stofberegninger/20230105&quot;}, {&quot;name&quot;: &quot;ProjAfvPath&quot;, &quot;value&quot;: &quot;T:/Projects/362/2021/3622100225 - H\\u00f8je Gladsaxe Parken - naturlig hydrologi/Stofberegninger/Hestefolden/Hestefolden_afvandingskort_projekt.tif&quot;}, {&quot;name&quot;: &quot;ProjOmrPath&quot;, &quot;value&quot;: &quot;T:/Projects/362/2021/3622100225 - H\\u00f8je Gladsaxe Parken - naturlig hydrologi/Stofberegninger/Hestefolden/Projektomr\\u00e5de_Hestefolden.shp&quot;}]}' </code></pre> <p>Declaring the encoding in the top of the code doesn't change anything.</p>
<python><json><encoding>
2023-01-06 14:07:49
1
648
Mathias
75,031,916
825,924
trio.Event(): Which is “better”: setting and initializing a new Event or checking if someone is waiting for it beforehand?
<pre><code>import trio work_available = trio.Event() async def get_work(): while True: work = check_for_work() if not work: await work_available.wait() else: return work def add_work_to_pile(...): ... if work_available.statistics().tasks_waiting: global work_available work_available.set() work_available = trio.Event() </code></pre> <p>In this Python-like code example I get work in bursts via <code>add_work_to_pile()</code>. The workers which get work via <code>get_work()</code> are slow. So most of the time <code>add_work_to_pile()</code> is called there will be no one waiting on <code>work_available</code>.</p> <p><strong>Which is better/cleaner/simpler/more pythonic/more trionic/more intended by the trio developers?</strong></p> <ul> <li>checking if someone is looking for the <code>Event()</code> via <code>statistics().tasks_waiting</code>, like in the example code, ...or...</li> <li>unconditionally <code>set()</code> setting the <code>Event()</code> and creating a new one each time? (Most of them in vain.)</li> </ul> <p>Furthermore... the API does not really seem to expect regular code to check if someone is waiting via this <code>statistics()</code> call...</p> <p>I don’t mind spending a couple more lines to make things clearer. But that goes both ways: a couple CPU cycles more are fine for simpler code...</p>
<python><asynchronous><async-await><python-trio>
2023-01-06 14:00:15
3
35,122
Robert Siemer
75,031,868
13,802,115
resampling .agg/.apply behavior
<p>This question relates to resample <code>.agg/.apply</code> which behaves differently than groupby <code>.agg/.apply</code>.</p> <p>Here is an example df:</p> <pre><code>df = pd.DataFrame({'A':range(0,100),'B':range(0,200,2)},index=pd.date_range('1/1/2022',periods=100,freq='D')) </code></pre> <p>Output:</p> <pre><code> A B 2022-01-01 0 0 2022-01-02 1 2 2022-01-03 2 4 2022-01-04 3 6 2022-01-05 4 8 ... .. ... 2022-04-06 95 190 2022-04-07 96 192 2022-04-08 97 194 2022-04-09 98 196 2022-04-10 99 198 </code></pre> <p>My question is, what does <code>x</code> represent in the apply function below. There are times where it behaves as a series and other times it behaves as a df. By calling <code>type(x)</code> it returns <code>df</code>. However, the below returns an error saying <code>&quot;No axis named 1 for object type Series&quot;</code></p> <pre><code>df.resample('M').apply(lambda x: x.sum(axis=1)) </code></pre> <p>But this does not. There is no stack for a series, so this would imply <code>x</code> represents a <code>df</code>.</p> <pre><code>df.resample('M').apply(lambda x: x.stack()) </code></pre> <p>Also, when you run <code>df.resample('M').apply(lambda x: print(type(x)))</code> the outputs are series, but <code>df.resample('M').apply(lambda x: type(x))</code> outputs dataframe type.</p> <p>So my main question is, what gets passed into apply for <code>resample</code>. a <code>series</code> or a <code>dataframe</code>?</p>
<python><pandas>
2023-01-06 13:56:11
1
8,880
rhug123
75,031,831
1,237,832
How to apply FastAPI Middleware on "non-async def" endpoints?
<p>According to <a href="https://fastapi.tiangolo.com/tutorial/middleware/" rel="nofollow noreferrer">https://fastapi.tiangolo.com/tutorial/middleware/</a>, we could apply a FastAPI Middleware on <code>async def</code> endpoints.</p> <p>Currently I have several <code>non-async def</code> endpoints, how to apply FastAPI Middleware on <code>non-async def</code> endpoint? If I still register an <code>async</code> Middleware, will it work for the <code>non-async def</code> endpoint ?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code> @app.middleware(&quot;http&quot;) async def add_process_time_header(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers[&quot;X-Process-Time&quot;] = str(process_time) return response </code></pre> <p>Will the Middleware work properly if <code>call_next</code> is a non-async def method ?</p> <p>Thank you.</p>
<python><asynchronous><python-asyncio><fastapi><middleware>
2023-01-06 13:53:08
1
2,481
zhfkt
75,031,787
42,446
Refactoring multiple IF statements to something cleaner in Python
<p>Within our codebase, we currently have a bit of code that looks like this. (Python obviously). It's now stretching to some 100 lines long, and feels very much like it is a candidate for refactoring.</p> <p>TOOL_NAME = &quot;tool_name&quot; TOOL_NAME_TWO = &quot;tool_name_two&quot;</p> <p>class DetailRetrievalFactory: def get_detailed_search_tool(self, tool_name):</p> <pre><code> if tool_name == TOOL_NAME: return ToolNameDetailRetrieval() if tool_name == TOOL_NAME_TWO: return ToolNameTwoDetailRetrieval() raise NotImplementedError </code></pre> <p>To give some details on how its used, each subclass has its own start_detailed_search method. Looking for ideas here on how best to refactor the above, or what patterns would potentially be worth looking at to remove the growing if statement within the detail retrieval factory. A switch statement doesn't seem much better.. I was thinking is this a strategy Pattern candidate? Any advice appreciated.</p> <p>data_retrieval = DetailRetrievalFactory().get_detailed_search_tool(tool_name) data_retrieval.start_detailed_search(query_id, request_id)</p>
<python><design-patterns>
2023-01-06 13:49:58
1
4,492
Squiggs.
75,031,707
11,334,393
Can't fetch flask api on react native expo app running on my android phone
<p>I am running my flask application on localhost and created apis using flask-restful library. I am using my network ip address in the api call. When I call api from react native app using expo, the api is not being called and I am not getting any network request failed error. I have added CORS also in my flask app.</p> <p>Here is my flask app.py file.</p> <pre><code>from flask_restful import Api from mobile_resources.events import UserMobile from flask_cors import CORS app = Flask(__name__) api = Api(app) CORS(app, resources={r'/*': {'origins': '*'}}) api.add_resource(UserMobile, '/mobile') if __name__ == '__main__': app.run(port=5000, debug=True) </code></pre> <p>Here is my api method which is simply returning a string</p> <pre><code>from flask import json from flask_restful import Resource class UserMobile(Resource): def get(self): return json.dumps({&quot;data&quot;: &quot;test user&quot;}) </code></pre> <p>my App.js in react native app calling the api</p> <pre><code> const getUser = async () =&gt; { try { const URL = &quot;http://192.168.10.22:5000/mobile&quot; const response = await fetch(URL, { method: &quot;GET&quot;, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', } }) let res = await response.json() response.ok &amp;&amp; res ? setUser(JSON.parse(res).data) : setUser(&quot;&quot;) setIsValidated(true) console.log(&quot;User: &quot;, user) } catch (err) { console.log(&quot;Error &quot;, err) setUser(&quot;&quot;) } } </code></pre> <p>On a side note, with android emulator, using ip address &quot;10.0.2.2&quot; works but with real android phone, none of the ip addresses are working. Please help needed.</p>
<python><android><react-native><flask><expo>
2023-01-06 13:42:40
1
456
za_ali33
75,031,578
11,143,781
Specifying figure size in print_figure function in Matplotlib.FigureCanvasBase
<p>I have a Canvas class that inherits from the FigureCanvas class in Matplotlib.</p> <pre><code>from matplotlib.backends.backend_qt5agg import FigureCanvas class Canvas(FigureCanvas): def __init__(self): fig = Figure(figsize=(5, 3)) super().__init__(fig) </code></pre> <p>And I display canvas figures in the PyQt5 window. The canvas size changes depending on the size of the window. When I print these canvases, it always prints at the current size of the canvas (solutions in <a href="https://stackoverflow.com/questions/332289/how-do-i-change-the-size-of-figures-drawn-with-matplotlib">How do I change the size of figures drawn with Matplotlib?</a> and <a href="https://stackoverflow.com/questions/14708695/specify-figure-size-in-centimeter-in-matplotlib">Specify figure size in centimeter in matplotlib</a> do not work).</p> <p>However, I would like to print them in a fixed size, no matter what the current size is. As far as I could tell from the internet, I cannot specify size in <code>print_figure()</code> function. How can I print all the figures at the fixed size?</p>
<python><matplotlib><pyqt5>
2023-01-06 13:28:50
0
316
justRandomLearner
75,031,577
19,161,462
How to assign default value of the model based on the value of ForeignKey
<p>I have the <code>Account</code> model were I store information about preferred units. However I also want to allow user to change the units for particular exercise which by default should be <code>Account.units</code>.</p> <p>Here are my models:</p> <pre><code>class Account(models.Model): &quot;&quot;&quot;Model to store user's data and preferences.&quot;&quot;&quot; UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False) units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=UNIT_CHOICES[0], null=False, blank=False) weight_metric = models.FloatField(null=True, blank=True) height_metric = models.FloatField(null=True, blank=True) weight_imperial = models.FloatField(null=True, blank=True) height_imperial = models.FloatField(null=True, blank=True) def __str__(self): return self.owner.email </code></pre> <pre><code>class CustomExercise(models.Model): UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False) preferred_units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=owner.units, null=False, blank=False) # &lt;- throws an error that &quot;ForeignKey doesn't have units attribute.&quot; name = models.CharField(max_length=255, null=False, blank=False) measure_time = models.BooleanField(default=False) measure_distance = models.BooleanField(default=False) measure_weight = models.BooleanField(default=False) measure_reps = models.BooleanField(default=False) def __str__(self): return f'{self.owner}:{self.name}' </code></pre> <p>As posted in code sample I tried to get that default value from ForeignKey, which not unexpectedly did not work out.<br/><br/> So my question is: what is the correct solution to implement this kind of feature?</p>
<python><django><django-models><design-patterns>
2023-01-06 13:28:49
2
350
Karol Milewczyk
75,031,570
4,321,525
How can I convert some columns of a numpy structured array to a different time format?
<p>I want to convert a structured NumPy array with datetime64[m] and a timedelta64[m] fields to an equivalent structured array with seconds since the epoch.</p> <p>The field size in an <code>np.array</code> is important for converting an unstructured array into a structured array. (<a href="https://stackoverflow.com/questions/69546473/convert-a-numpy-array-to-a-structured-array">Convert a numpy array to a structured array</a>)</p> <p>Since the current <code>np.datetime64</code> field is longer than an <code>int</code> field for seconds since the epoch converting the array in place is not possible - right? (I would prefer this option.)</p> <p>The simple and wrong approach would be this:</p> <pre><code>import numpy as np import numpy.lib.recfunctions as rf datetime_t = np.dtype([(&quot;start&quot;, &quot;datetime64[m]&quot;), (&quot;duration&quot;, &quot;timedelta64[m]&quot;), (&quot;score&quot;, float)]) seconds_t = np.dtype([(&quot;start&quot;, &quot;int&quot;), (&quot;duration&quot;, &quot;int&quot;), (&quot;score&quot;, float)]) unstructured = np.arange(9).reshape((3, 3)) print(unstructured) datetime_structure = rf.unstructured_to_structured(unstructured, dtype=datetime_t) print(datetime_structure) seconds_structure = datetime_structure.astype(seconds_t) print(seconds_structure.dtype) </code></pre> <p>giving me this output:</p> <pre><code>[[0 1 2] [3 4 5] [6 7 8]] [('1970-01-01T00:00', 1, 2.) ('1970-01-01T00:03', 4, 5.) ('1970-01-01T00:06', 7, 8.)] [(0, 1, 2.) (3, 4, 5.) (6, 7, 8.)] Process finished with exit code 0 </code></pre> <p>Since I specified minutes, I should get multiple of 60 seconds, not single digits.</p> <p>Sidenote: I am confused by the first conversion TO the DateTime format, as the DateTime is not in minutes but in seconds. I specified <code>datetime64[m]</code> and converted 3 (and 0 and 6) into that format, and I would have expected 3 minutes ('1970-01-01T03:00'), not 3 seconds ('1970-01-01T00:03'). Oh well. Perhaps someone could explain?</p> <p>How do I convert a structured array like this elegantly and efficiently? Do I need to iterate over the array manually (my real array has a few more fields than this example), copy the columns one by one, and convert the time fields? Given that I want to convert multiple different structures containing these time formats, a generalized approach to converting these fields in structured arrays would be welcome without needing to specify the fields individually.</p>
<python><numpy><data-structures>
2023-01-06 13:27:43
1
405
Andreas Schuldei
75,031,433
5,224,881
tf.io.GFile with Tensor String Input
<p>I want to have retrieval of GCS object/any S3 object as a part of the Model, as a first layer which will obtain features based on the filename, because it will lower the networking overhead, and I am trying to wrap the download into the <code>tf.function</code>, but no success. Here is MWE:</p> <pre><code>import tensorflow as tf @tf.function def load_file(a): if tf.is_tensor(a): a_path = tf.strings.substr(a, 0, 2) + &quot;/&quot; + a else: a_path = a[0:2] + &quot;/&quot; + a with tf.io.gfile.GFile(&quot;gs://some_bucket&quot; + a_path) as f: return f.read() load_file(tf.constant(&quot;file3&quot;)) </code></pre> <p>which raises error</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In [22], line 9 7 with tf.io.gfile.GFile(&quot;gs://some_bucket&quot; + a_path) as f: 8 return f.read() ----&gt; 9 load_file(tf.constant(&quot;file3&quot;)) File /opt/conda/envs/wanna-hmic/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.&lt;locals&gt;.error_handler(*args, **kwargs) 151 except Exception as e: 152 filtered_tb = _process_traceback_frames(e.__traceback__) --&gt; 153 raise e.with_traceback(filtered_tb) from None 154 finally: 155 del filtered_tb File /opt/conda/envs/wanna-hmic/lib/python3.9/site-packages/tensorflow/python/framework/func_graph.py:1147, in func_graph_from_py_func.&lt;locals&gt;.autograph_handler(*args, **kwargs) 1145 except Exception as e: # pylint:disable=broad-except 1146 if hasattr(e, &quot;ag_error_metadata&quot;): -&gt; 1147 raise e.ag_error_metadata.to_exception(e) 1148 else: 1149 raise TypeError: in user code: File &quot;/tmp/ipykernel_4006/3877294148.py&quot;, line 8, in load_file * return f.read() TypeError: __init__(): incompatible constructor arguments. The following argument types are supported: 1. tensorflow.python.lib.io._pywrap_file_io.BufferedInputStream(filename: str, buffer_size: int, token: tensorflow.python.lib.io._pywrap_file_io.TransactionToken = None) Invoked with: &lt;tf.Tensor 'add_2:0' shape=() dtype=string&gt;, 524288 </code></pre> <p>the code works well in eager mode with <code>load_file(&quot;file3&quot;)</code> but in order to perform well, I need it to work even in the graph mode.</p>
<python><tensorflow>
2023-01-06 13:15:34
1
1,814
Matěj Račinský
75,031,288
822,896
Python Type Hint for Returning Concrete Class
<p>I have some code (attached below) that I'm running with Python 3.10.</p> <p>The code runs fine, but pylance in VS Code flags an error for these lines:</p> <pre class="lang-py prettyprint-override"><code>books: list[SoftBack] = [softback_book_1, softback_book_2] processed_books = BookProcessor(books).process() </code></pre> <p>This is because the <code>BookProcessor</code> class type hints say that it will take a <code>list[Book]</code> and return a <code>list[Book]</code>. Whereas I'm actually giving it a <code>list[SoftBack]</code> and expecting it to return a <code>list[SoftBack]</code>, as <code>SoftBack</code> is a concrete class of <code>Book</code>.</p> <p>The error is:</p> <pre><code>(variable) books: list[SoftBack] Argument of type &quot;list[SoftBack]&quot; cannot be assigned to parameter &quot;books&quot; of type &quot;list[Book]&quot; in function &quot;__init__&quot; &quot;list[SoftBack]&quot; is incompatible with &quot;list[Book]&quot; TypeVar &quot;_T@list&quot; is invariant &quot;SoftBack&quot; is incompatible with &quot;Book&quot; Pylancereport(GeneralTypeIssues) </code></pre> <p>Should I be using a different type hint for returning concrete classes, or is pylance incorrect in flagging this up? (Or am I doing Python wrong?!).</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; Book Testing &quot;&quot;&quot; from abc import ABC, abstractmethod from copy import deepcopy from typing import Any class Book(ABC): &quot;&quot;&quot; A generic book. &quot;&quot;&quot; name: str @abstractmethod def __init__(self, *args: Any | None, **kwargs: Any | None) -&gt; None: &quot;&quot;&quot; Abstract initialiser. &quot;&quot;&quot; raise NotImplementedError class SoftBack(Book): &quot;&quot;&quot; A softback book. &quot;&quot;&quot; name: str def __init__(self, name: str) -&gt; None: self.name = name class BookProcessor: &quot;&quot;&quot; A simple book processor. &quot;&quot;&quot; books: list[Book] def __init__(self, books: list[Book]) -&gt; None: self.books = books def process(self) -&gt; list[Book]: &quot;&quot;&quot; Add the string '_processed' to book names, returning a new list of books. &quot;&quot;&quot; processed_books: list[Book] = [] for book in self.books: new_book = deepcopy(book) new_book.name += '_processed' processed_books.append(new_book) return processed_books def main(): &quot;&quot;&quot; Main function. &quot;&quot;&quot; softback_book_1 = SoftBack(name='book_01') softback_book_2 = SoftBack(name='book_02') books: list[SoftBack] = [softback_book_1, softback_book_2] processed_books = BookProcessor(books).process() for processed_book in processed_books: print(processed_book.name) if __name__ == '__main__': main() </code></pre>
<python><python-3.x><type-hinting><pylance>
2023-01-06 13:03:16
1
1,229
Jak
75,031,228
1,169,220
python attrs inherited field value gets overwritten
<p>I have some <code>attrs</code> classes that inherit from a base class. The parent class has a field that is also an attrs class.</p> <p>If I instantiate two instances of the child classes and set the common inherited field's sub-field, the other instance's field gets overwritten as well.</p> <p>I could work around this by using a <code>factory</code> for the field to specify the required default value with a <code>partial</code> (method 3).</p> <p>As it seems, with methods 1 and 2, the instantiation of <code>MyField</code> for the default value only takes place once, and is somehow shared (?) between the child instances (?)</p> <p>Is there any other way without this hack?</p> <p>Here is the code:</p> <pre class="lang-py prettyprint-override"><code>import functools import attrs def test_attrs_problem(): @attrs.define class MyField: name: str value: int = 0 @attrs.define class Parent: # Test fails with the following two field definitions: # --- method 1 --- # a: MyField = MyField(name=&quot;default_name&quot;) # --- method 2 --- # a: MyField = attrs.field(default=MyField(name=&quot;default_name&quot;)) # Test passes with the following two field definitions: # --- method 3 --- a: MyField = attrs.field( factory=functools.partial( MyField, name=&quot;default_name&quot; ) ) @attrs.define class Child1(Parent): b: int = 42 @attrs.define class Child2(Parent): c: int = 43 # creating an instance of the Child1 class c1 = Child1() c1.a.value = 1 before = c1.a.value print(&quot;before&quot;, c1) # creating a instance of the Child2 class c2 = Child2() # setting the common inherited field's value field for the c2 instance c2.a.value = 2 after = c1.a.value print(&quot;after&quot;, c1) # expecting that the value in the c1 instance is the same assert after == before </code></pre>
<python><inheritance><python-attrs>
2023-01-06 12:57:10
2
480
waszil
75,031,198
6,672,815
Implementing generator throw() method in pybind11
<p>I'm implementing a generator in C++ using pybind11 and the bit I'm having difficulty with is implementing the <code>throw</code> method.</p> <p>In python it has this signature and typical implementation:</p> <pre class="lang-py prettyprint-override"><code>def throw(self, exception_type: type | None = None, exception_message: str | None = None, traceback: Any | None = None) -&gt; None: match exception_type: case None: raise StopIteration() case _: raise exception_type(exception_message) </code></pre> <p>so I could do something like:</p> <pre class="lang-py prettyprint-override"><code>gen = MyGenerator() gen.throw(ValueError, &quot;something went wrong&quot;) </code></pre> <p>to raise a <code>ValueError</code>.</p> <p>To simplify things for SO purposes, on the C++ side I'm ignoring the fact that all arguments are optional. So, my first attempt was this member function implementation:</p> <pre class="lang-cpp prettyprint-override"><code>void throw_(py::type exception_type, py::str exception_message, py::object /*traceback*/) { throw exception_type(exception_message); } </code></pre> <p>but when I run the code it actually throws a <code>RuntimeError</code>: &quot;Caught an unknown exception!&quot;. Next thought was to cast the <code>ValueError</code> to <code>py::value_error</code>:</p> <pre><code> throw py::cast&lt;py::value_error&gt;(exception_type(exception_message)); </code></pre> <p>but it looks like the types are completely unrelated as I get <code>RuntimeError</code>: Unable to cast Python instance to C++ type.</p> <p>So it looks like I need to manually check the type of the incoming python exception, then throw the equivlant pybind11 (or std) exception, which then gets retranslated to a python exception type on its way back to python. I could do something like this:</p> <pre class="lang-cpp prettyprint-override"><code>void throw_(py::type e, py::str msg, py::object traceback) { std::string type_str = py::cast&lt;std::string&gt;(py::str(e)); if (e.is(py::none())) throw py::stop_iteration(msg); else if (type_str == &quot;&lt;class 'ValueError'&gt;&quot;) throw py::value_error(msg); else if (type_str == &quot;&lt;class 'IndexError'&gt;&quot;) throw py::index_error(msg); else if (type_str == &quot;&lt;class 'KeyError'&gt;&quot;) throw py::key_error(msg); else if (type_str == &quot;&lt;class 'RuntimeError'&gt;&quot;) throw std::runtime_error(msg); throw e(msg); } </code></pre> <p>but its really clunky, not least beacuse I have to know which exception types I deal with at compile time, but also using string comparisons to check types. Alternatively, I could exec python code in the function:</p> <pre class="lang-cpp prettyprint-override"><code>void throw_(py::type e, py::str msg, py::object traceback) { auto locals = py::dict(&quot;exception_type&quot;_a=e, &quot;exception_message&quot;_a=msg); py::exec(R&quot;&quot;&quot;( raise exception_type(exception_message) )&quot;&quot;&quot;, py::globals(), locals); } </code></pre> <p>and this would solve the arbitrary exception type issue but again this seems a bit clunky because (I assume) the stack unwinds through pybind11, propagating the python exception type (is it caught and rethrown?), so it seems unnecessarily convoluted.</p> <p>So really my questions are:</p> <ol> <li>Is pybind11 really completely unaware of python exception types such as <code>ValueError</code>?</li> <li>Is there a better way of checking the type than string comparison?</li> <li>Is there another approach to this that is pure pybind11/C++?</li> </ol>
<python><c++><generator><pybind11>
2023-01-06 12:53:52
1
830
virgesmith
75,031,011
14,667,788
full xpath does not math the correct field in python selenium
<p>I have a following problem. On the picture bellow I would like to fill some text into the second (red) field.</p> <p><a href="https://i.sstatic.net/ZSNs6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZSNs6.png" alt="enter image description here" /></a></p> <p>My code:</p> <pre class="lang-py prettyprint-override"><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.common.action_chains import ActionChains def set_scraper(): &quot;&quot;&quot;Function kills running applications and set up the ChromeDriver.&quot;&quot;&quot; options = webdriver.ChromeOptions() options.add_argument(&quot;--start-maximized&quot;) driver = webdriver.Chrome(&quot;/usr/lib/chromium-browser/chromedriver&quot;, options=options) return driver def main() -&gt; None: &quot;&quot;&quot;Main function that is call when the script is run.&quot;&quot;&quot; driver = set_scraper() driver.get(&quot;https://nahlizenidokn.cuzk.cz/VyberBudovu/Stavba/InformaceO&quot;) pokus = driver.find_element(By.XPATH, '/html/body/form/div[5]/div/div/div/div[3]/div/fieldset/div[2]/div[2]/input[1]') driver.implicitly_wait(10) ActionChains(driver).move_to_element(pokus).send_keys(&quot;2727&quot;).perform() </code></pre> <p>The problem is that it sends &quot;2727&quot; into the first field, not into the red one. Although <code>/html/body/form/div[5]/div/div/div/div[3]/div/fieldset/div[2]/div[2]/input[1]</code> is the full xpath of the second field. Do you know why, please?</p>
<python><selenium><selenium-webdriver><xpath><webdriverwait>
2023-01-06 12:34:24
3
1,265
vojtam
75,030,971
8,771,201
Selenium can't find element by class name which needs to be clicked
<p>On this page:</p> <p><a href="https://i.sstatic.net/pG27c.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pG27c.png" alt="enter image description here" /></a></p> <p><a href="https://finance.yahoo.com/quote/AAPL/balance-sheet?p=AAPL" rel="nofollow noreferrer">https://finance.yahoo.com/quote/AAPL/balance-sheet?p=AAPL</a></p> <p>I want to click the &quot;Collapse All button&quot;</p> <p>Which are these classes: <a href="https://i.sstatic.net/g8kA9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/g8kA9.png" alt="enter image description here" /></a></p> <p>I have tried this in a few different ways but it looks like selenium can't the button. What can be the problem with mij code?</p> <pre><code>url = 'https://finance.yahoo.com/quote/AAPL/balance-sheet?p=AAPL' driver.get(url) # driver.find_element(By.CSS_SELECTOR,'expandPf Fz(s) Bd(0) C($linkColor) C($linkActiveColor):h Fw(500) D(n)--print Fl(end) Mt(5px)')#.click() # driver.find_element(By.CLASS_NAME,'expandPf Fz(s) Bd(0) C($linkColor) C($linkActiveColor):h Fw(500) D(n)--print Fl(end) Mt(5px)')#.click() # driver.find_element(By.CLASS_NAME,'expandPf Fz(s)')#.click() showmore_link = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, 'expandPf Fz(s) Bd(0) C($linkColor) C($linkActiveColor):h Fw(500) D(n)--print Fl(end) Mt(5px)'))) showmore_link.click() </code></pre> <p>None of my options seem to work.</p>
<python><selenium><xpath><css-selectors><webdriverwait>
2023-01-06 12:30:07
1
1,191
hacking_mike
75,030,842
778,942
Sorting of simple python dictionary for printing specific value
<p>I have a python dictionary.</p> <pre><code>a = {'1':'saturn', '2':'venus', '3':'mars', '4':'jupiter', '5':'rahu', '6':'ketu'} planet = input('Enter planet : ') print(planet) </code></pre> <p>If user enteres 'rahu', dictionary to be sorted like the following</p> <pre><code>a = {'1':'rahu', '2':'ketu', '3':'saturn', '4':'venus', '5':'mars', '6':'jupiter' } print('4th entry is : ') </code></pre> <p>It should sort dictionary based on next values in the dictionary. If dictionary ends, it should start from initial values of dictionary. It should print 4th entry of the dictionary, it should return</p> <pre><code>venus </code></pre> <p>How to sort python dictionary based on user input value?</p>
<python><python-3.x><dictionary>
2023-01-06 12:17:54
2
19,252
sam
75,030,749
12,396,154
What is the best principle to write files to a folder and delete them after a while within one script in Python?
<p>I query the sql server and then write the result into a separated csv file in a folder every 10 secs. Then I want to delete those files which are older than 3 days and let the script run forever. So What I did is:</p> <pre><code>def write_csv(): # connect to sql server and query the info # write the query result to csv files and store it in folder A def delete_old_csv(): # check the date of the files within a loop # delete files if they are older than 3 days while True: write_csv() delete_old_csv() time.sleep(10) </code></pre> <p>I think it's not a good design that the <code>delete_old_csv()</code> to be called every 10 secs looping through files date. Since this is more of a IO bound task, is multi threading a good approach to design here? If yes, how to call these functions into threads? If my question is wrong here please guide me where to ask this? Thank you for any help.</p>
<python><design-patterns><io>
2023-01-06 12:08:22
2
353
Nili
75,030,715
9,648,374
Reading protobuf Message file in Python
<p>I have a pb file abc.pb file.</p> <p>I need to read the file by retaining its format i.e. dont want to convert pb file to string and then again reconverting it.</p> <p>Currently I m trying options with</p> <pre><code> with open(data, &quot;rb&quot;) as file_handle: data = file_handle.read() </code></pre> <p>But this converts that into bytes. How to read them as Message. Can someone please help?</p>
<python><protocol-buffers>
2023-01-06 12:05:04
1
489
Isha Nema
75,030,573
8,510,149
Count occurrence within a group using different columns for each group
<p>In df below there are three groups in the variable 'group' - 'A', 'AB', 'C'. The other columns in the df is assigned to a specific group by suffix - var1_A relates to group A and so forth.</p> <pre><code>data = pd.DataFrame({'group':['A', 'AB', 'A', 'AB', 'AB', 'C', 'C', 'A', 'A', 'AB'], 'var1_A':['pass', 'fail', 'pass','fail', 'pass']*2, 'var2_A':['pass', 'pass', 'pass','fail', 'pass']*2, 'var1_AB':['pass', 'pass', 'pass','fail', 'pass']*2, 'var2_AB':['pass', 'pass', 'fail','fail', 'pass']*2, 'var1_C':['pass', 'pass', 'pass','fail', 'pass']*2, 'var2_C': ['fail', 'fail', 'fail','fail', 'pass']*2 }) </code></pre> <p>I want for each row count the number of times 'pass' occur. For the instances that belongs to group A I only want to count the variables that are connected to the group A. I want the result in a new column. This would almost do the job.</p> <pre><code>data['new_col'] = data[data['group']=='A']['var1_A, var2_A].isin(['pass']).sum(1) data['new_col'] = data[data['group']=='AB']['var1_AB, var2_AB].isin(['pass']).sum(1) data['new_col'] = data[data['group']=='C']['var1_C, var2_C].isin(['pass']).sum(1) </code></pre> <p>However, I want the result in the same column from all groups. This operation is perhaps possible to do using a groupby and transform? However, I got stuck figuring it out.</p> <p>Target dataframe:</p> <pre><code>pd.DataFrame({'group':['A', 'AB', 'A', 'AB', 'AB', 'C', 'C', 'A', 'A', 'AB'], 'var1_A':['pass', 'fail', 'pass','fail', 'pass']*2, 'var2_A':['pass', 'pass', 'pass','fail', 'pass']*2, 'var1_AB':['pass', 'pass', 'pass','fail', 'pass']*2, 'var2_AB':['pass', 'pass', 'fail','fail', 'pass']*2, 'var1_C':['pass', 'pass', 'pass','fail', 'pass']*2, 'var2_C': ['fail', 'fail', 'fail','fail', 'pass']*2, 'result':[2,2,2,0,2,1,1,2,0,2] }) </code></pre>
<python><pandas>
2023-01-06 11:50:50
2
1,255
Henri
75,030,524
7,093,241
How to write in with its fundamental brute steps?
<p>I was looking to solve the <a href="https://leetcode.com/problems/longest-consecutive-sequence/description/" rel="nofollow noreferrer">longest consecutive sequence question on Leetcode</a> and this is the provided solution.</p> <p>The question lies in the inner loop right after <code> # how to rewrite this part without in?</code></p> <pre><code>class Solution: def longestConsecutive(self, nums): longest_streak = 0 for num in nums: current_num = num current_streak = 1 # how to rewrite this part without in? while current_num + 1 in nums: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streak </code></pre> <p>I wrote a version that of the inner loop doesn't use <code>in</code> like this.</p> <pre><code>while j &lt; n and i != j: if nums[j] == currentSequenceNumber + 1: currentSequenceLength += 1 currentSequenceNumber = nums[j] j += 1 </code></pre> <p>I realized after running <code>pdb</code> that this approach would only work for 2 consecutive numbers but not more. How could I rewrite my original portion to keep checking without using <code>in</code>. I have a feeling that <code>in</code> using a similar approach as <code>find</code> when it comes to sequences. I have seen <a href="https://stackoverflow.com/questions/681649/how-is-string-find-implemented-in-cpython">this link for find in strings</a> but it is not the brute force approach that I would like to write out.</p> <p>I think seeing this how this can be rewritten would clarify why the space complexity is <code>O(n^3)</code> as the solution states. I currently can't understand why with their explanation.</p>
<python><arrays><search>
2023-01-06 11:46:48
1
1,794
heretoinfinity
75,030,513
1,484,601
github actions: how to access badges?
<p>This documentation explains how workflows generate badges, and how to access them:</p> <p><a href="https://docs.github.com/en/actions/monitoring-and-troubleshooting-workflows/adding-a-workflow-status-badge" rel="nofollow noreferrer">https://docs.github.com/en/actions/monitoring-and-troubleshooting-workflows/adding-a-workflow-status-badge</a></p> <p>in short:</p> <blockquote> <p><a href="https://github.com/" rel="nofollow noreferrer">https://github.com/</a>//actions/workflows/&lt;WORKFLOW_FILE&gt;/badge.svg</p> </blockquote> <p>But I have a job that generates two badges. In my particular case:</p> <ul> <li>the &quot;default&quot; workflow badge</li> <li>a test coverage badge, generated by pytest-coverage</li> </ul> <p>Here my pytest.yaml file:</p> <pre><code>name: Unit tests on: push: branches: [&quot;master&quot;] pull_request: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v3 with: python-version-file: '.python-version' cache: 'pip' - name: Install dependencies run: | pip install -r requirements.txt pip install pytest pytest-coverage - name: Test with pytest run: | pytest --cov - name: Coverage Bagdge uses: tj-actions/coverage-badge-py@v1.8 </code></pre> <p>the workflow is successfull, and the github actions page reports:</p> <blockquote> <p>saved badge to /home/runner/work/REPO-NAME/REPO-NAME/coverage.svg</p> </blockquote> <p>Do I need to fix the workflow to move the badge somewhere? Or is there already a link I can use to access coverage.svg ? (I just want to display the badge in the readme of the repository)</p> <p>note: the link to <code>pytest.yaml/badge.svg</code> works fine.</p>
<python><github-actions><badge>
2023-01-06 11:45:55
1
4,521
Vince
75,030,385
25,282
Problem with softPageBreaks when reading a odf file with lxml to create a LaTeX file
<p>I have a Google Doc that I want to convert into a LaTeX file while stripping out some content of the Google Doc. Specifically I want to remove all headlines in the Google Doc. I also currently have four-line paragraphs in the Google Doc where each line ends with a newline character. This means that in Google Doc they aren't seen as one paragraph but four and I want those to be one in my LaTeX file.</p> <p>First I extracted an XML file and parsed it:</p> <pre><code>if not os.path.exists(tempFolder): os.makedirs(tempFolder) # Extract the contents of the ODF file to the &quot;temp&quot; folder with zipfile.ZipFile(fileName, &quot;r&quot;) as zip: zip.extractall(path=tempFolder) # Open the &quot;content.xml&quot; file inside the &quot;temp&quot; folder and parse it into an XML tree doc = etree.parse(contentXml) removeHeadlines(doc) </code></pre> <p>I remove the headlines via:</p> <pre><code>def removeHeadlines(doc): p2 = doc.findall('.//text:p[@text:style-name=&quot;P2&quot;]', namespaces=doc.getroot().nsmap) for p in ( p2 ): p.getparent().remove(p) </code></pre> <p>Then I create the LaTeX file via:</p> <pre><code>elementList = oldDoc.findall( './/text:p[@text:style-name=&quot;Standard&quot;]', namespaces=oldDoc.getroot().nsmap) textList = [element.text for element in elementList] latexDoc = pylatex.Document() section = pylatex.section.Section(fileName) latexDoc.append(section) paragraph = pylatex.section.Paragraph('') paragraphIsNew = True for string in textList: if string: # If the string is not empty, add it to the paragraph paragraph.append(string + &quot;\n&quot;) paragraphIsNew = False else: if not paragraphIsNew: latexDoc.append(paragraph) paragraph = pylatex.section.Paragraph('') paragraphIsNew = True latexDoc.append(paragraph) latexDoc.generate_pdf(newFileName) </code></pre> <p>Unfortunately, some lines don't make it into the LaTeX pdf. Those look like:</p> <pre><code>&lt;text:p text:style-name=&quot;Standard&quot;&gt;&lt;text:soft-page-break/&gt;Sad line that doesn't make it,&lt;/text:p&gt; </code></pre> <p>I tried unsuccessfully tried to remove the softPageBreak elements by doing:</p> <pre><code>softPageBreaks = doc.findall('.//text:soft-page-break', namespaces=doc.getroot().nsmap) # Remove the element, but keep its parent and the text content for element in softPageBreaks: parent = element.getparent() text = element.tail parent.remove(element) parent.text = text </code></pre>
<python><xml-parsing><lxml><odf><pylatex>
2023-01-06 11:31:29
0
26,469
Christian
75,030,342
8,564,860
Apache Beam - ReadFromText safely (pass over errors)
<p>I have a simple Apache Beam pipeline which reads compressed bz2 files and writes them out to text files.</p> <pre><code>import apache_beam as beam p1 = beam.Pipeline() (p1 | 'read' &gt;&gt; beam.io.ReadFromText('bad_file.bz2') | 'write' &gt;&gt; beam.io.WriteToText('file_out.txt') ) p1.run() </code></pre> <p>The problem is when the pipeline encounters a bad file (<a href="https://www.dropbox.com/s/x8mii8jsm1jmqgi/bad_file.bz2?dl=0" rel="nofollow noreferrer">example</a>). In this case, most of my bad files are malformed, not in bz2 format or simply empty, which confuses the decompressor, causing an <code>OSError: Invalid data stream</code>.</p> <p>How can I tell ReadFromText to <code>pass</code> on these?</p>
<python><google-cloud-dataflow><apache-beam>
2023-01-06 11:26:44
1
1,102
John F
75,030,103
6,681,932
Create weekly time series with DARTS from dataframe
<p>How to create a time series with darts having weekly frequency?</p> <p>When having weekly data as follows:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'Date' : [ pd.to_datetime('2022-12-05'), pd.to_datetime('2022-12-12'), pd.to_datetime('2022-12-19'), pd.to_datetime('2022-12-26')], 'Variable': [10,21,23,24]}) </code></pre> <p>I am struggling to get the correct <code>freq</code> as weekly:</p> <pre><code>from darts import TimeSeries # I use freq = day in order to not to get an error. TimeSeries.from_dataframe(df, 'Date', &quot;Variable&quot;, freq=&quot;d&quot;) </code></pre>
<python><time-series><u8darts>
2023-01-06 11:03:01
1
478
PeCaDe
75,030,061
2,583,476
Python OpenCV waitKeyEx() stops picking up arrow keys after mouse click or tab
<p>I'm writing a camera viewer for a lab setup. Much of the display control is done using the keyboard, a couple of things need a mouse. Anyway, even without a mouse event handler, I see the same issue.</p> <p>To nudge the region of interest I use the arrow keys. This works - until I click with the mouse anywhere in the image window (or press tab, but I hadn't noticed that until I started reading about these issues). Other keys are still picked up fine.</p> <p>The following code demonstrates it:</p> <pre><code>import cv2 import numpy as np cv2.namedWindow(&quot;window&quot;, flags=cv2.WND_PROP_AUTOSIZE+cv2.WINDOW_GUI_NORMAL) img=np.zeros((100,100,3), np.uint8) while True: cv2.imshow(&quot;window&quot;, img) key = cv2.waitKeyEx(1) #waitKeyEx returns the ASCII value of the key if there is one, otherwise the key code; 27=Esc. # Key codes depend on the backend hence the &quot;or&quot; for arrow keys &amp; F1. Linux first, Win10 (via VirtualBox) 2nd # process keypresses. if (key==65361 or key==2424832):#left print ('left') elif (key==65364 or key==2621440):#down print ('down') elif (key==65362 or key==2490368):#up print ('up') elif (key==65363 or key==2555904):#right print ('right') elif (key == 27):#Esc break else: if key &gt;0:print (&quot;key with ASCII code %d not understood&quot;%key) cv2.destroyAllWindows() </code></pre> <p>It will display which key you pressed in the parent terminal window - and stop doing so after clicking - but only for the arrow keys.</p> <p>This is the image window I get using the above dummy image (note that I'm using XFCE).<br /> <a href="https://i.sstatic.net/GFjKJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/GFjKJ.png" alt="Screenshot of blank image window" /></a></p> <p>And this with the full viewer and a live image from the camera (as the dummy image makes for a very narrow window): <a href="https://i.sstatic.net/VZo1W.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VZo1W.png" alt="Screenshot of full viewer window" /></a></p> <p>I have rather a lot of key bindings in my real code, but anyway the arrow keys are the most intuitive for the user. Note that there are no error messages, it's a silent failure. Is there some way to restore arrow key functionality after mouse events?</p> <p>Output of <code>print(cv2.getBuildInformation())</code> follows. It appears to be using QT5 not GTK+ (I expected the latter):</p> <pre><code>General configuration for OpenCV 4.6.0 ===================================== Version control: unknown Platform: Timestamp: 2022-06-07T10:28:59Z Host: Linux 5.13.0-1025-azure x86_64 CMake: 3.22.5 CMake generator: Unix Makefiles CMake build tool: /bin/gmake Configuration: Release CPU/HW features: Baseline: SSE SSE2 SSE3 requested: SSE3 Dispatched code generation: SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX requested: SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX SSE4_1 (16 files): + SSSE3 SSE4_1 SSE4_2 (1 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 (0 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX AVX (4 files): + SSSE3 SSE4_1 POPCNT SSE4_2 AVX AVX2 (31 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX512_SKX (5 files): + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX C/C++: Built as dynamic libs?: NO C++ standard: 11 C++ Compiler: /usr/lib/ccache/compilers/c++ (ver 10.2.1) C++ flags (Release): -Wl,-strip-all -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG C++ flags (Debug): -Wl,-strip-all -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG C Compiler: /usr/lib/ccache/compilers/cc C flags (Release): -Wl,-strip-all -fsigned-char -W -Wall -Wreturn-type -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -O3 -DNDEBUG -DNDEBUG C flags (Debug): -Wl,-strip-all -fsigned-char -W -Wall -Wreturn-type -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wno-strict-overflow -fdiagnostics-show-option -Wno-long-long -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -msse -msse2 -msse3 -fvisibility=hidden -g -O0 -DDEBUG -D_DEBUG Linker flags (Release): -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -L/root/ffmpeg_build/lib -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined Linker flags (Debug): -Wl,--exclude-libs,libippicv.a -Wl,--exclude-libs,libippiw.a -L/root/ffmpeg_build/lib -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined ccache: YES Precompiled headers: NO Extra dependencies: /lib64/libopenblas.so Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Test Qt5::Concurrent /usr/local/lib/libpng.so /lib64/libz.so dl m pthread rt 3rdparty dependencies: libprotobuf ade ittnotify libjpeg-turbo libwebp libtiff libopenjp2 IlmImf quirc ippiw ippicv OpenCV modules: To be built: calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching video videoio Disabled: world Disabled by dependency: - Unavailable: java python2 ts Applications: - Documentation: NO Non-free algorithms: NO GUI: QT5 QT: YES (ver 5.15.0 ) QT OpenGL support: NO GTK+: NO VTK support: NO Media I/O: ZLib: /lib64/libz.so (ver 1.2.7) JPEG: libjpeg-turbo (ver 2.1.2-62) WEBP: build (ver encoder: 0x020f) PNG: /usr/local/lib/libpng.so (ver 1.6.37) TIFF: build (ver 42 - 4.2.0) JPEG 2000: build (ver 2.4.0) OpenEXR: build (ver 2.3.0) HDR: YES SUNRASTER: YES PXM: YES PFM: YES Video I/O: DC1394: NO FFMPEG: YES avcodec: YES (58.134.100) avformat: YES (58.76.100) avutil: YES (56.70.100) swscale: YES (5.9.100) avresample: NO GStreamer: NO v4l/v4l2: YES (linux/videodev2.h) Parallel framework: pthreads Trace: YES (with Intel ITT) Other third-party libraries: Intel IPP: 2020.0.0 Gold [2020.0.0] at: /io/_skbuild/linux-x86_64-3.6/cmake-build/3rdparty/ippicv/ippicv_lnx/icv Intel IPP IW: sources (2020.0.0) at: /io/_skbuild/linux-x86_64-3.6/cmake-build/3rdparty/ippicv/ippicv_lnx/iw VA: NO Lapack: YES (/lib64/libopenblas.so) Eigen: NO Custom HAL: NO Protobuf: build (3.19.1) OpenCL: YES (no extra features) Include path: /io/opencv/3rdparty/include/opencl/1.2 Link libraries: Dynamic load Python 3: Interpreter: /opt/python/cp36-cp36m/bin/python3.6 (ver 3.6.15) Libraries: libpython3.6m.a (ver 3.6.15) numpy: /opt/python/cp36-cp36m/lib/python3.6/site-packages/numpy/core/include (ver 1.13.3) install path: python/cv2/python-3 Python (for build): /bin/python2.7 Java: ant: NO JNI: NO Java wrappers: NO Java tests: NO Install to: /io/_skbuild/linux-x86_64-3.6/cmake-install ----------------------------------------------------------------- </code></pre> <p>This is using Python 3.8.10 on Ubuntu 20.04 (though it will end up on Windows eventually, hence the alternative keycodes). OpenCV is 4.6.0.</p>
<python><linux><opencv>
2023-01-06 10:58:47
0
351
Chris H
75,030,007
10,613,037
User object has no attribute 'code', when code is not passed to User.objects.create
<p>Im using Django Rest Framework to create a view that verifies an otp. Currently, it works just fine. models.py</p> <pre class="lang-py prettyprint-override"><code>class User(AbstractUser): phone_number = PhoneNumberField(blank=True) def __str__(self) -&gt; str: return f&quot;{self.username}&quot; </code></pre> <p>views.py</p> <pre class="lang-py prettyprint-override"><code>class VerifyOTPCode(APIView): permission_classes=[AllowAny] def post(self, request): serializer = UserOTPCodeSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors) </code></pre> <p>serializers.py</p> <pre class="lang-py prettyprint-override"><code>class UserOTPCodeSerializer(serializers.ModelSerializer): code = serializers.IntegerField() class Meta: model = User fields = (&quot;first_name&quot;, &quot;last_name&quot;, &quot;email&quot;, &quot;phone_number&quot;, &quot;code&quot;) def validate(self, data): code, phone_number = str(data['code']), data['phone_number'] if is_six_digits(code) and is_otp_approved(code, phone_number): return data raise serializers.ValidationError('Code was not approved') def create(self, validated_data): del validated_data['code'] return User.objects.create(**validated_data) </code></pre> <p>However, I want to use a generic for the view instead, so I tried refactoring it into the following</p> <p>views.py</p> <pre class="lang-py prettyprint-override"><code>class VerifyOTPCode(generics.CreateAPIView): permission_classes= [AllowAny] serializer_class= UserOTPCodeSerializer </code></pre> <p>Now, when I try to hit the endpoint, I get an error at <code>create</code>, that the <code>User</code> object has no attribute <code>code</code>, even though <code>create</code> removes <code>code</code> from <code>validated_data</code>, and another thing is that even with the error, a User object still does get created. Why is this error occurring and how can I fix it?</p> <pre><code>Internal Server Error: /user/register/verify-otp/ Traceback (most recent call last): File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py&quot;, line 457, in get_attribute return get_attribute(instance, self.source_attrs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py&quot;, line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'User' object has no attribute 'code' During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py&quot;, line 47, in inner response = get_response(request) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py&quot;, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py&quot;, line 54, in wrapped_view return view_func(*args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py&quot;, line 70, in view return self.dispatch(request, *args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 509, in dispatch response = self.handle_exception(exc) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 469, in handle_exception self.raise_uncaught_exception(exc) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 480, in raise_uncaught_exception raise exc File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 506, in dispatch response = handler(request, *args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\generics.py&quot;, line 190, in post return self.create(request, *args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\mixins.py&quot;, line 20, in create headers = self.get_success_headers(serializer.data) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py&quot;, line 555, in data ret = super().data File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py&quot;, line 253, in data self._data = self.to_representation(self.instance) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py&quot;, line 509, in to_representation attribute = field.get_attribute(instance) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py&quot;, line 490, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `code` on serializer `UserOTPCodeSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'code'. Internal Server Error: /user/register/verify-otp/ Traceback (most recent call last): File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py&quot;, line 457, in get_attribute return get_attribute(instance, self.source_attrs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py&quot;, line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'User' object has no attribute 'code' During handling of the above exception, another exception occurred: Traceback (most recent call last): File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py&quot;, line 47, in inner response = get_response(request) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py&quot;, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py&quot;, line 54, in wrapped_view return view_func(*args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py&quot;, line 70, in view return self.dispatch(request, *args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 509, in dispatch response = self.handle_exception(exc) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 469, in handle_exception self.raise_uncaught_exception(exc) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 480, in raise_uncaught_exception raise exc File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py&quot;, line 506, in dispatch response = handler(request, *args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\generics.py&quot;, line 190, in post return self.create(request, *args, **kwargs) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\mixins.py&quot;, line 20, in create headers = self.get_success_headers(serializer.data) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py&quot;, line 555, in data ret = super().data File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py&quot;, line 253, in data self._data = self.to_representation(self.instance) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py&quot;, line 509, in to_representation attribute = field.get_attribute(instance) File &quot;C:\Users\61403\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py&quot;, line 490, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `code` on serializer `UserOTPCodeSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'code'. </code></pre>
<python><django><django-models><django-rest-framework>
2023-01-06 10:53:10
1
320
meg hidey
75,029,921
16,978,074
add data in a dictionary and print it with python
<p>hello all I'm just learning python and i have a problem. I want to add the results of a network request inside a dictionary in python and then . I want to download the movie title and id of all the movies on a movie site and put it inside a dictionary. Since the dictionary key must be unique, I thought of creating an &quot;original_title&quot; key where I put all the titles of the movies and another &quot;id&quot; key where I put the id of all the movies. This is my code:</p> <pre><code>dictionary={} for i in range(1,36590): response1 = requests.get(&quot;https://api.themoviedb.org/3/discover/moie?api_key=mykey&amp;language=en-US&amp;sort_by=popularity.desc&amp;include_adult=false&amp;include_video=false&amp;page=&quot;+str(i)+&quot;&amp;with_watch_monetization_types=flatrate&quot;) jsonresponse1=response1.json() results=jsonresponse1[&quot;results&quot;] for result in results: dictionary.setdefault(&quot;original_title&quot;, []) dictionary.setdefault(&quot;id&quot;, []) dictionary['original_title'].append(result[&quot;original_title&quot;]) dictionary['id'].append(result[&quot;id&quot;]) print(dictionary) </code></pre> <p>why doesn't my code work? How can I print the dictionary, after adding the data downloaded from the website?</p>
<python><dictionary><for-loop><setdefault>
2023-01-06 10:45:09
0
337
Elly
75,029,897
353,337
Traverse a Python AST breadth first
<p>I have a <a href="https://docs.python.org/3/library/ast.html" rel="nofollow noreferrer">Python AST</a> that I'd like to traverse breadth first. <a href="https://docs.python.org/3/library/ast.html#ast.walk" rel="nofollow noreferrer"><code>ast.walk</code></a> appears to do the trick, but from its documentation</p> <blockquote> <p><code>ast.walk(node)</code></p> <p>Recursively yield all descendant nodes in the tree starting at <code>node</code> (including <code>node</code> itself), in no specified order. This is useful if you only want to modify nodes in place and don’t care about the context.</p> </blockquote> <p>one might assume that this is merely an implementation detail. Is there a traversal method that guaranteed breadth-first?</p>
<python><abstract-syntax-tree><breadth-first-search>
2023-01-06 10:43:05
0
59,565
Nico Schlömer
75,029,810
19,797,660
Dataframe - How to access datetime properties?
<p>I want to acces <code>datetime</code> object properties like <code>.seconds()</code>, <code>.minutes()</code> etc. <code>Datetime</code> values are stored in <code>Dataframe</code> in column <code>DateTime</code>. I need this acces so I can use <code>np.where()</code> on these values like in a following example but When I run this code I am getting <code>AttributeError: 'Series' object has no attribute 'minutes'</code>:</p> <pre><code>if interval_higher_str == 'seconds': occurances = np.where(price_df_lower_interval['DateTime'].second == interval_higher) elif interval_higher_str == 'minutes': occurances = np.where(price_df_lower_interval['DateTime'].minute() == interval_higher and price_df_lower_interval['DateTime'].second() == 0) elif interval_higher_str == 'hours': occurances = np.where(price_df_lower_interval['DateTime'].hour() == interval_higher and price_df_lower_interval['DateTime'].minute() == 0 and price_df_lower_interval['DateTime'].second() == 0) elif interval_higher_str == 'day': occurances = np.where(price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == 0 and price_df_lower_interval['DateTime'].second() == 0) elif interval_higher_str == 'week': occurances = np.where(price_df_lower_interval['DateTime'].weekday() == 0 and price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == trade_start_minute and price_df_lower_interval['DateTime'].second() == 0) elif interval_higher_str == 'month': occurances = np.where(price_df_lower_interval['DateTime'].day() == 1 and price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == trade_start_minute and price_df_lower_interval['DateTime'].second() == 0) elif interval_higher_str == 'year': occurances = np.where(price_df_lower_interval['DateTime'].month() == 1 and price_df_lower_interval['DateTime'].day() == 1 and price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == trade_start_minute and price_df_lower_interval['DateTime'].second() == 0) </code></pre> <p>I know I can loop through the dataframe and either create an auxilliary columns which will store each parameter, or just loop through it and save index where condition was met to the list, but I can see that except from being extremly slow I have a feeling that it will be overly complicated.</p> <p>How can I achieve the same result my code <em><strong>should</strong></em> give but without looping through the dataframe?</p>
<python><pandas><python-datetime>
2023-01-06 10:35:07
1
329
Jakub Szurlej
75,029,788
16,521,194
Datetime to timestamp (year 1) raises ValueError
<h1>Goal</h1> <p>I want to convert a <code>datetime.datetime</code> object to a timestamp.</p> <h1>Code and output</h1> <pre class="lang-py prettyprint-override"><code>from datetime import datetime dt1: datetime = datetime(year=2023, month=1, day=6) ts1: int = dt1.timestamp() # &gt; 1672959600.0 dt2: datetime = datetime(year=1, month=1, day=2) ts2: int = dt2.timestamp() # &gt; -62135510961.0 dt3: datetime = datetime(year=1, month=1, day=1) ts3: int = dt3.timestamp() # &gt; Traceback (most recent call last): # &gt; File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; # &gt; ValueError: year 0 is out of range </code></pre> <h1>Issue</h1> <p>I don't understand why this error is raised. This error also is raised when trying to set a <code>datetime.datetime</code> object's <code>year</code> attribute to <code>0</code> (<code>dt: datetime = datetime(year=0, ...)</code>), which is here expected.<br /> Does someone have an explanation for this? Thanks a lot!</p>
<python><datetime><timestamp>
2023-01-06 10:32:38
2
1,183
GregoirePelegrin
75,029,605
2,218,321
Python and Matlab differences in linear algebra calculates
<p>I need to write a program for linear algebra calculates. I switched from Matlab to python and worked with numpy and scipy. There are some small differences in precision between Python and Matlab which cause different result in the end. For example for the matrix</p> <pre><code>A =[2 -25, -25 -622] </code></pre> <p>in Matlab <code>det(A) = 627.0</code> while in python it is <code>626.9999999999978</code>. When I check the variables, these tiny differences for all the variables will significantly change the results. what shall I do?</p>
<python><numpy><matlab><scipy><linear-algebra>
2023-01-06 10:16:22
1
2,189
M a m a D
75,029,545
19,797,660
Dataframe - Converting entire column from str object to datetime object - TypeError: strptime() argument 1 must be str, not Series
<p>I want to convert values in entire column from <code>strings</code> to <code>datetime</code> objects, but I can't accomplish it with this code which works on solo strings i.e. (if I add .iloc[] and specify the index):</p> <pre><code>price_df_higher_interval['DateTime'] = datetime.datetime.strptime(price_df_higher_interval['DateTime'], '%Y-%m-%d %H:%M:%S') </code></pre> <p>Also I would like to ommit looping through the dataframe, but I don't know if that won't be necessery.</p> <p>Thank you for your help :)</p>
<python><pandas><python-datetime>
2023-01-06 10:10:18
1
329
Jakub Szurlej
75,029,241
1,866,775
Why does a Flask request in Python fail to deserialize JSON POST data when there is no Content-Type header?
<p>Minimal example:</p> <pre><code>#!/usr/bin/env python3 import json from dataclasses import dataclass from flask import Flask, request, make_response from flask_restful import Resource, Api @dataclass class Foo: bar: int class WebController(Resource): def __init__(self, factor) -&gt; None: self._factor = factor def post(self): foo = Foo(**json.loads(request.data)) return make_response(str(self._factor * foo.bar), 200) def main(): app = Flask(__name__) api = Api(app) api.add_resource(WebController, &quot;/json_post_endpoint&quot;, resource_class_kwargs={&quot;factor&quot;: 2}) app.run(port=8080) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Running it, then sending a <code>curl</code> without the header:</p> <pre><code>curl -X POST --url http://localhost:8080/json_post_endpoint --data '{ &quot;bar&quot;: 42 }' {&quot;message&quot;: &quot;Internal Server Error&quot;} </code></pre> <p>Logs:</p> <pre><code>[2023-01-06 10:34:23,616] ERROR in app: Exception on /json_post_endpoint [POST] Traceback (most recent call last): File &quot;/home/tobias/.local/lib/python3.10/site-packages/flask/app.py&quot;, line 1820, in full_dispatch_request rv = self.dispatch_request() File &quot;/home/tobias/.local/lib/python3.10/site-packages/flask/app.py&quot;, line 1796, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) File &quot;/home/tobias/.local/lib/python3.10/site-packages/flask_restful/__init__.py&quot;, line 467, in wrapper resp = resource(*args, **kwargs) File &quot;/home/tobias/.local/lib/python3.10/site-packages/flask/views.py&quot;, line 107, in view return current_app.ensure_sync(self.dispatch_request)(**kwargs) File &quot;/home/tobias/.local/lib/python3.10/site-packages/flask_restful/__init__.py&quot;, line 582, in dispatch_request resp = meth(*args, **kwargs) File &quot;/home/tobias/Documents/main.py&quot;, line 20, in post foo = Foo(**json.loads(request.data)) File &quot;/usr/lib/python3.10/json/__init__.py&quot;, line 346, in loads return _default_decoder.decode(s) File &quot;/usr/lib/python3.10/json/decoder.py&quot;, line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File &quot;/usr/lib/python3.10/json/decoder.py&quot;, line 355, in raw_decode raise JSONDecodeError(&quot;Expecting value&quot;, s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) </code></pre> <p>But with the header, the <code>curl</code> is fine:</p> <pre><code>curl -X POST --url http://localhost:8080/json_post_endpoint --header 'Content-Type: application/json' --data '{ &quot;bar&quot;: 42 }' 84 </code></pre> <p>What does adding the header to the request change for the server to behave differently?</p>
<python><json><flask><post><http-headers>
2023-01-06 09:41:12
1
11,227
Tobias Hermann
75,029,046
7,104,128
Flexible and customized tables using svg
<p>When representing conditional probabilities (P(X|Y,Z,...), one has to deal with large tables of numbers (aka CPTs). PyAgrum (a python package) use html in notebooks to obtain a quite good representation of these CPTs :</p> <p><a href="https://i.sstatic.net/tyuEd.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tyuEd.png" alt="different CPTs" /></a></p> <p>The size, the number of columns in the headers, bgcolors of cells, etc. have to be very flexible. HTML table are very useful tool to do this job. However HTML representation is not easy to export and to use outside a notebook.</p> <p>I am looking for ideas to do the same job but either in SVG or PDF or other.</p>
<python><html><svg><probability>
2023-01-06 09:24:02
0
551
Pierre-Henri Wuillemin
75,028,761
13,568,193
Replace Nan with previous row value in pandas dataframe
<p>I have a dataframe named <code>purchase_df</code> with columns (<code>purchase_item</code>, <code>purchase_date</code>, <code>purchase_quantity</code>, <code>purchase_price_unit</code>, <code>sales_quantity</code>) and some of the value of <code>purchase_price_unit</code> is <strong>Nan</strong>(empty) and I need to replace <strong>Nan</strong> value with previous month value</p> <p>Note:- I saw this one (<a href="https://stackoverflow.com/questions/71531930/python-pandas-replace-a-nan-on-a-column-with-previous-value-on-the-same-column">Python pandas, replace a NAN on a column with previous value on the same column</a>) but here they haven't used group by which is major problem in this task.</p> <p>For this I tried doing this</p> <pre><code># grouped = purchase_df.groupby('purchase_item') grouped = purchase_df.groupby(['purchase_item','purchase_date']) purchase_df['purchase_price_unit'] = grouped['purchase_price_unit'].apply(lambda x: x.ffill()) </code></pre> <p>Here I group the data by <code>purchase_item</code> and <code>purchase_date</code> and used <code>ffill()</code> which fill value of previous rows but it didn't work even though this method replace <strong>nan</strong> with previous rows if I group by just using <code>purchase_item</code> but here I need to group by according to <code>purchase_item</code> as well as <code>purchase_date</code>. Help me out</p>
<python><pandas><dataframe>
2023-01-06 08:50:58
1
383
Arpan Ghimire
75,028,755
7,905,329
How to unmerge multiple cells and transpose each value into a new column in Pandas dataframe from Excel file
<p>This has 4 to 5 merged cells, blank cells. I need to get them in a format where a column is created for each merged cell.</p> <p>Please find the link for Sample file and also the output required below.</p> <h3>Link : <a href="https://docs.google.com/spreadsheets/d/1fkG9YT9YGg9eXYz6yTkl7AMeuXwmNYQ44oXgA8ByMPk/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1fkG9YT9YGg9eXYz6yTkl7AMeuXwmNYQ44oXgA8ByMPk/edit?usp=sharing</a></h3> <p>Code so far:</p> <pre><code>dfs = pd.read_excel('/Users/john/Desktop/Internal/Raw Files/Med/TVS/sample.xlsx',sheet_name=None, header=[0,4], index_col=[0,1]) df_2 = (pd.concat([df.stack(0).assign(name=n) for n,df in dfs.items()]) .rename_axis(index=['Date','WK','Brand','A_B','Foo_Foos','Cur','Units'], columns=None) .reset_index()) </code></pre> <p>How do I create multiple column in the above code? Right now I'm getting the below error:</p> <pre><code>ValueError: Length of names must match number of levels in MultiIndex. </code></pre>
<python><python-3.x><excel><pandas><dataframe>
2023-01-06 08:49:51
1
364
anagha s
75,028,556
225,262
How to use type hint with SQLAlchemy models?
<p>Let's we have a model defined as a subclass of the declarative base:</p> <pre><code>class User(Base): name = Column(String) </code></pre> <p>Later, I define a function that returned a <code>User</code> and specify the returned type as a type hint:</p> <pre><code>def find_user(name: str) -&gt; User: ... return user </code></pre> <p>When I try to use the <code>name</code> field of returned value as a string, the type system complains that it's a <code>Column</code>, not a string. What can I do to add type hint in such cases?</p>
<python><sqlalchemy>
2023-01-06 08:26:09
2
33,385
satoru
75,028,503
2,707,864
What are the differences between a**b and pow(a,b), in symbolic calculation
<p><strong>EDIT</strong>: added <code>assert</code> as <a href="https://stackoverflow.com/a/75030966/2707864">suggested by Wrzlprmft</a>, which does not raise any exception.</p> <p>I have to write code with many expressions of type <code>a**b</code>, under the following circumstances</p> <pre><code>import sympy as sp a, b = sp.symbols('a,b', real=True, positive=True) expr1 = a**b expr2 = pow(a,b) assert expr1 is expr2 </code></pre> <p><strong>What are the expected/possible differences between <code>a**b</code> and <code>pow(a,b)</code>?</strong> <strong>(e.g., when simplifying, collecting, etc., expressions).</strong> <br> <strong>Should I expect possible wrong results in any case?</strong></p> <p>So far, I found none. <br> I don't think I would use the third argument of <code>pow</code> as my bases will be real (exponents will typically be integers or ratios between one- or two-digit integers), so <a href="https://stackoverflow.com/questions/14133806/why-is-powa-d-n-so-much-faster-than-ad-n">this</a> or <a href="https://stackoverflow.com/a/59143871/2707864">this</a> are not relevant. <br> <a href="https://stackoverflow.com/questions/20969773/exponentials-in-python-xy-vs-math-powx-y">This</a> or <a href="https://stackoverflow.com/questions/10282674/difference-between-the-built-in-pow-and-math-pow-for-floats-in-python">this</a> are focused on comparisons with <code>math.pow</code>, although some answers also include both <code>**</code> and <code>pow</code> in comparisons of performance, showing minor differences. None of the questions / answers deal with <code>sympy</code>.</p> <p>If <code>math.pow</code> or <code>sympy.Pow</code> provide any advantage in any case, I welcome the clarifications. I don't foresee I would perform heavy computations, so minor performance differences will likely not impact my use case.</p>
<python><sympy><pow><exponentiation>
2023-01-06 08:18:35
1
15,820
sancho.s ReinstateMonicaCellio
75,028,348
12,104,604
How to convert from world coordinates to camera coordinates
<p>In the world coordinate system, there are objects with rotation values <code>rx1,ry1,rz1</code> and position values <code>px1,py1,pz1</code>.</p> <p>Similarly, there is an camera in the world coordinate system with rotation values <code>rx2,ry2,rz2</code> and position values <code>px2,py2,pz2</code>.</p> <p>What formula can be used to convert <code>rx1,ry1,rz1,px1,py1,pz1</code> to the camera coordinate system?</p> <p>The up vector of the camera is the Y-axis, always oriented toward the object near the world origin.</p> <p>The camera and the model are supposed to move within the range as shown in the following gif image. <a href="https://i.sstatic.net/EEgj9.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/EEgj9.gif" alt="enter image description here" /></a></p> <p>I would like to use Python to do the calculations, but I am open to any other answers, including other Unity C# or mathematical statements.</p> <p>You are welcome to have commentary in quaternions or in matrices instead of euler angles.</p>
<python><unity-game-engine><3d>
2023-01-06 07:58:15
1
683
taichi
75,028,192
10,748,412
Get a Foreign Key value with django-rest-framework serializers
<p>I'm using the django rest framework to create an API.</p> <p>models.py</p> <pre><code>class DepartmentModel(models.Model): DeptID = models.AutoField(primary_key=True) DeptName = models.CharField(max_length=100) def __str__(self): return self.DeptName class Meta: verbose_name = 'Department Table' class EmployeeModel(models.Model): Level_Types = ( ('Genin', 'Genin'), ('Chunin', 'Chunin'), ('Jonin', 'Jonin'), ) EmpID = models.AutoField(primary_key=True) EmpName = models.CharField(max_length=100) Email = models.CharField(max_length=100,null=True) EmpLevel = models.CharField(max_length=20, default=&quot;Genin&quot;, choices=Level_Types) EmpPosition = models.ForeignKey(DepartmentModel, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = 'EmployeeTable' # Easy readable tablename - verbose_name def __str__(self): return self.EmpName </code></pre> <p>serializer.py</p> <pre><code>from appemployee.models import EmployeeModel,DepartmentModel class EmployeeSerializer(serializers.ModelSerializer): emp_dept = serializers.CharField(source='DepartmentModel.DeptName') class Meta: model = EmployeeModel fields = ('EmpID','EmpName','Email','EmpLevel','emp_dept') </code></pre> <p>views.py</p> <pre><code>class EmployeeTable(APIView): def get(self,request): try: emp_obj = EmployeeModel.objects.all() empserializer = EmployeeSerializer(emp_obj,many=True) except Exception as err: return Response(err) return Response(empserializer.data) </code></pre> <p>this would provide me with:</p> <pre><code>[ { &quot;EmpID&quot;: 1, &quot;EmpName&quot;: &quot;Hashirama Senju&quot;, &quot;Email&quot;: &quot;hashirama.senju@konaha.com&quot;, &quot;EmpLevel&quot;: &quot;Jonin&quot;, &quot;EmpPosition&quot;: 1 }, { &quot;EmpID&quot;: 2, &quot;EmpName&quot;: &quot;Tobirama Senju&quot;, &quot;Email&quot;: &quot;tobirama.senju@konaha.com&quot;, &quot;EmpLevel&quot;: &quot;Jonin&quot;, &quot;EmpPosition&quot;: 2 }, { &quot;EmpID&quot;: 3, &quot;EmpName&quot;: &quot;Hiruzen Sarutobi&quot;, &quot;Email&quot;: &quot;hiruzen.sarutobi@konaha.com&quot;, &quot;EmpLevel&quot;: &quot;Jonin&quot;, &quot;EmpPosition&quot;: 5 } ] </code></pre> <p>what i really want is</p> <pre><code>[ { &quot;EmpID&quot;: 1, &quot;EmpName&quot;: &quot;Hashirama Senju&quot;, &quot;Email&quot;: &quot;hashirama.senju@konaha.com&quot;, &quot;EmpLevel&quot;: &quot;Jonin&quot;, &quot;DeptName&quot;: &quot;Hokage&quot; }, { &quot;EmpID&quot;: 2, &quot;EmpName&quot;: &quot;Tobirama Senju&quot;, &quot;Email&quot;: &quot;tobirama.senju@konaha.com&quot;, &quot;EmpLevel&quot;: &quot;Jonin&quot;, &quot;DeptName&quot;: &quot;Hokage&quot; }, { &quot;EmpID&quot;: 3, &quot;EmpName&quot;: &quot;Hiruzen Sarutobi&quot;, &quot;Email&quot;: &quot;hiruzen.sarutobi@konaha.com&quot;, &quot;EmpLevel&quot;: &quot;Jonin&quot;, &quot;DeptName&quot;: &quot;Hokage&quot; } ] </code></pre> <p>DeptName is in the department model . I want to combaine the results of both serializers and display it.</p> <p>PS: The JSON result is just for an example. Cannot display real data.</p>
<python><django><postgresql><django-rest-framework>
2023-01-06 07:41:02
2
365
ReaL_HyDRA
75,027,919
9,196,825
Python script to set all subtitles for movies and shows in plex to English non forced subtitles
<p><strong>Edit:</strong> This code is working and completed. Thanks to all who helped! Feel free to use this code for your own purposes. I will be running this code periodically on my home server to set preferred subtitles. Cheers!</p> <p>This code was created with the help of <a href="https://chat.openai.com/" rel="nofollow noreferrer">ChatGPT Open AI</a> and further edited and completed by me. It uses <a href="https://github.com/pkkid/python-plexapi" rel="nofollow noreferrer">Plex Python Api</a>. It will set all movies and shows in your local Plex library to English non forced subtitles by default. The subtitle selections will apply to your Plex profile and be remembered on other devices. Assuming your Plex subtitles settings are setup in your server settings Plex will default to Forced Subtitles by default when they are available for a given item. Plex will not allow you to prefer non forced subtitles natively hence why this script was created.</p> <p>See <a href="https://stackoverflow.com/a/75038161/9196825">answer</a> below for the code.</p> <p>Also posted on:</p> <ul> <li><a href="https://github.com/RileyXX/PlexPreferNonForcedSubs" rel="nofollow noreferrer">Github</a></li> <li><a href="https://www.reddit.com/r/PleX/comments/13ttswd/tool_for_setting_default_subtitles_to_english/" rel="nofollow noreferrer">Reddit</a></li> <li><a href="https://forums.plex.tv/t/python-script-to-set-all-movies-and-shows-in-plex-to-use-english-non-forced-subtitles/825871" rel="nofollow noreferrer">Plex Forums</a></li> </ul>
<python><plex>
2023-01-06 07:03:29
1
477
Riley Bell
75,027,840
1,654,229
Convert a python dict to correct python BaseModel pydantic class
<p>My requirement is to convert python dictionary which can take multiple forms into appropriate pydantic BaseModel class instance. Following are details:</p> <pre><code>class ConditionType(str, Enum): EXPRESSION = 'EXPRESSION' CYCLE_DUR_TREND = 'CYCLE_DUR_TREND' class ConditionalExpressionProps(BaseConditionalProps): conditional_expression: str class CycleDurationTrendProps(BaseConditionalProps): direction_up : bool = True n : int = Field(1, ge=1, le=1000) class ConditionalConfig(BaseModel): cond_type: ConditionType = ConditionType.EXPRESSION condition_prop: BaseConditionalProps class SendNotificationChannel(BaseModel): id: str customer_id: str conditional_config: Optional[ConditionalConfig] </code></pre> <p>I want to create a SendNotificationChannel instance with correct <code>conditional_config</code> set such that condition_prop becomes <code>ConditionalExpressionProps</code> or <code>CycleDurationTrendProps</code> based on the structure of dict.</p> <p>For example, if dict is:</p> <pre><code>{ &quot;id&quot; : &quot;1&quot;, &quot;customer_id&quot; : &quot;abc&quot;, &quot;conditional_config&quot; : { &quot;cond_type&quot;: &quot;EXPRESSION&quot;, &quot;conditional_expression&quot; : &quot;.s_num&gt;10&quot; } } </code></pre> <p>then on doing something like <code>SendNotificationChannel(**dict)</code> should make the <code>conditional_config.condition_prop</code> of type <code>ConditionalExpressionProps</code>, and similarly for <code>CycleDurationTrendProps</code>.</p> <p>However when I'm doing this, its taking <code>BaseConditionalProps</code>.</p> <pre><code>&gt;&gt;&gt; channel = {&quot;conditional_config&quot; : {&quot;cond_type&quot;: &quot;EXPRESSION&quot;, &quot;condition_prop&quot;:{&quot;conditional_expression&quot;:&quot;ALPHA&quot;}}} &gt;&gt;&gt; channel_obj = SendNotificationChannel(**channel) &gt;&gt;&gt; channel_obj SendNotificationChannel(conditional_config=ConditionalConfig(cond_type=&lt;ConditionType.EXPRESSION: 'EXPRESSION'&gt;, condition_prop=BaseConditionalProps())) &gt;&gt;&gt; channel_obj.conditional_config.condition_prop BaseConditionalProps() &gt;&gt;&gt; </code></pre> <p>I'd want to know how would someone solve this problem, or if I'm tackling this the incorrect way.</p>
<python><inheritance><pydantic>
2023-01-06 06:53:15
1
1,534
Ouroboros
75,027,635
19,797,660
Python, how to assign boolean comparison operators to variables?
<p>I'd like to asign these operators to variables. I have a flag that if is set to <code>True</code> uses <code>&gt;</code> or <code>&gt;=</code> in certain conditions, but when I set the flag to <code>False</code> I want to use <code>&lt;</code> or <code>&lt;=</code> instead.</p> <p>Example:</p> <pre><code>up_down: bool = True if up_down: flag1 = data['foo'] &gt; data['foo'].shift(x) flag2 = data['foo'] &gt;= data['foo2'] else: flag1 = data['foo'] &lt; data['foo'].shift(x) flag2 = data['foo'] &lt;= data['foo2'] </code></pre> <p>I want to achieve the same without duplicating the code, so the code would look like&amp;work this:</p> <pre><code>if up_down: var1 = &quot;&gt;&quot; var2 = &quot;&gt;=&quot; else: var1 = &quot;&lt;&quot; var2 = &quot;&lt;=&quot; flag1 = data['foo'] var1 data['foo'].shift(x) flag2 = data['foo'] var2 data['foo2'] </code></pre> <p>Is it possible?</p>
<python><boolean-operations>
2023-01-06 06:23:19
0
329
Jakub Szurlej
75,027,483
6,703,592
why sklearn SelectFromModel estimator_.coef_ return a 2d-array
<p>I asked in <a href="https://stats.stackexchange.com/">Cross Validated</a> before but it seems it should be proper to ask here.</p> <p>My data <code>df_X</code> has 11 features, and <code>y</code> is the multi-class label (3,4,5,6,7,8 in samples). I used multi-class SVM to select the importance of features. <code>estimator_.coef_</code> should return the score of each feature (a list of 11 scores). But why here it returns a list of scores? The same case occurred for multi-class <code>LogisticRegression()</code>.</p> <p>By the way, what's the difference between <code>SelectKBest</code> and <code>SelectFromModel</code> for feature selection in sklearn.</p> <p><a href="https://i.sstatic.net/YOe0L.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/YOe0L.png" alt="enter image description here" /></a></p>
<python><scikit-learn><feature-selection>
2023-01-06 06:02:52
1
1,136
user6703592
75,027,285
882,932
Filter pandas frame by values that are already grouped on consecutive rows
<p>Consider a dataframe that would look like this :</p> <pre><code>Col1 Col2 Col3 ABC 00012 Hey! A1C 00012 Hello! AAA 00012 Hello ABC 00033 Hey! A1C 00021 Hi! AAA 00021 Hey... B3Y 00002 Hi. A5I 00002 Hey? EAA 00002 Hey! </code></pre> <p><code>Column2</code> values are already packed together (not necessarily sorted by value, but at least packed together on consecutive lines). My goal is to iterate over smaller dataframes that correspond to the lines with the same values of <code>Column2</code>.</p> <hr /> <p>One way of doing this would be:</p> <pre><code>df = pd.read_csv(myfile, sep = &quot;\t&quot;) keys = pd.unique(df[&quot;Col2&quot;]) for key in keys: subdf = df[df[&quot;Col2&quot;] == key] myfunction(subdf) # Do something with the sub-dataframe </code></pre> <p>However, this would be super inefficient, since a filtering on the whole dataframe would take place at each iteration.</p> <hr /> <p><strong>QUESTION:</strong> How to make that code more efficient and leverage the fact that the values in <code>Column2</code> are already grouped on consecutive lines?</p>
<python><pandas><sorting><optimization><filtering>
2023-01-06 05:34:44
0
61,061
Vincent
75,026,982
1,742,886
python3: conditional import from one of two packages
<p>I have two packages <code>fast</code> and <code>slow</code> which are &quot;api compatible&quot; with each other. If <code>fast</code> is available I want to import from it, else from <code>slow</code>. My current working solution is</p> <pre><code>import imp try: imp.find_module('fast') from fast.UtilityFunctions import UtilityFunctions from fast.Utilities.Log import Log from fast.model.device_driver import DriverModel ... except ImportError: from slow.UtilityFuntions import UtilityFunctions ... # normal code </code></pre> <p>It there a better way to write this? Can I eliminate the copy paste job above? i.e. what would be the pythonic equivalent of this pseudo-code?</p> <pre><code>import imp try: imp.find_module('fast') alias found=fast except ImportError alias found=slow from found.UtilityFuntions import UtilityFunctions ... </code></pre>
<python>
2023-01-06 04:39:15
2
581
vijayvithal
75,026,816
523,612
Why doesn't my "formula" variable update automatically, like in a spreadsheet? How can I re-compute the value?
<p>I have noticed that it's common for beginners to have the following simple logical error. Since they genuinely don't understand the problem, a) their questions can't really be said to be caused by a typo (a full explanation would be useful); b) they lack the understanding necessary to create a proper example, explain the problem with proper terminology, and ask clearly. So, I am asking on their behalf, to make a canonical duplicate target.</p> <p>Consider this code example:</p> <pre><code>x = 1 y = x + 2 for _ in range(5): x = x * 2 # so it will be 2 the first time, then 4, then 8, then 16, then 32 print(y) </code></pre> <p>Each time through the loop, <code>x</code> is doubled. Since <code>y</code> was defined as <code>x + 2</code>, why doesn't it change when <code>x</code> changes? How can I make it so that the value is automatically updated, and I get the expected output</p> <pre><code>4 6 10 18 34 </code></pre> <p>?</p>
<python><function><logic><variable-assignment>
2023-01-06 04:01:08
1
61,352
Karl Knechtel
75,026,813
17,779,615
How to set permission for 3 subfolder backwards after creating the directory in python
<p>I would like to create a folder &quot;C://user//Folder1//Folder2//Folder3//Folder4//Folder5//&quot; in python. &quot;C://user//Folder1//Folder2&quot; exists previously.</p> <p>When I create the desire folder, I want to allow permission to all Folder3, Folder4 and Folder5. While I don't want to affect the python's working directory which is located in another location &quot;C://user1//python_script&quot;.</p> <p>When I write the script, it only give full permission to Folder5 after creating desire__dir.</p> <pre><code>import os desire__dir = &quot;C://user//Folder1//Folder2//Folder3//Folder4//Folder5//&quot; if not os.path.exists(desire__dir): os.makedirs(desire__dir) os.chmod(desire__dir, 0o777) </code></pre>
<python><permissions>
2023-01-06 04:00:51
1
539
Susan
75,026,668
3,976,494
Multiply dataframe column by list of scalars and create a new column for each multiplication
<p>I have a dataframe</p> <pre><code> Date Date.1 SYMBL TF Pattern ... Stop Risk Amount GAP LVL Actual / Back Test Notes 0 00:00:00 2022-12-12 QCOM 5M Buy Setup ... 117.46 0.45 NaN Actual NaN 1 1900-01-01 00:00:00 2022-12-12 QCOM 5M 0.84 ... 117.46 0.45 NaN Back Test NaN 2 1900-01-02 00:00:00 2022-11-29 FUTU 15M Buy Setup ... 58.15 0.63 NaN Actual NaN </code></pre> <p>I want to take the column &quot;Risk Amount&quot; and multiply it by a list <code>l = [2, 3, 4, 5]</code> and store each multiplication in a new column <code>c2</code>, <code>c3</code>, <code>c4</code>, <code>c5</code> corresponding to each digit in the list.</p> <p>For example, column 2 <code>c2</code> should look like:</p> <pre><code>c2 0.9 # 0.45 * 2 0.9 # 0.45 * 2 1.26 # 0.63 * 2 </code></pre> <p>and column 3 <code>c3</code> should look like:</p> <pre><code>c3 1.35 # 0.45 * 3 1.35 # 0.45 * 3 1.89 # 0.63 * 3 </code></pre> <p>What I tried to do:</p> <pre><code># This allows us to iterate over a list of numbers [0.1, 0.2, 0.3, ..., 9.9, 10] steps = [ i for i in np.linspace(0.1, 10, 100) ] for i in np.linspace(0.1, 10, 100): column_title = f&quot;c{i:.1f}&quot; df[column_title] = df_long[&quot;Risk Amount&quot;] * i </code></pre> <p>but this gives the following warning</p> <pre class="lang-bash prettyprint-override"><code> PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()` </code></pre>
<python><pandas><dataframe>
2023-01-06 03:31:20
1
702
Hunter
75,026,592
18,193,889
How to create pandas output for custom transformers?
<p>There are a lot of changes in scikit-learn 1.2.0 where it supports pandas output for all of the transformers but how can I use it in a custom transformer?</p> <p><strong>In [1]:</strong> Here is my custom transformer which is a standard scaler: <br></p> <pre><code>from sklearn.base import BaseEstimator, TransformerMixin import numpy as np class StandardScalerCustom(BaseEstimator, TransformerMixin): def fit(self, X, y=None): self.mean = np.mean(X, axis=0) self.std = np.std(X, axis=0) return self def transform(self, X): return (X - self.mean) / self.std </code></pre> <p><strong>In [2]:</strong> Created a specific <code>scale</code> pipeline</p> <pre><code>scale_pipe = make_pipeline(StandardScalerCustom()) </code></pre> <p><strong>In [3]:</strong> Added in a full pipeline where it may get mixed with scalers, imputers, encoders etc.</p> <pre><code>full_pipeline = ColumnTransformer([ (&quot;imputer&quot;, impute_pipe, ['column_1']) (&quot;scaler&quot;, scale_pipe, ['column_2']) ]) # From documentation full_pipeline.set_output(transform=&quot;pandas&quot;) </code></pre> <p>Got this error: <br></p> <p><strong>ValueError</strong>: Unable to configure output for StandardScalerCustom() because <code>set_output</code> is not available.</p> <hr /> <p>There is a solution and it can be: <code>set_config(transform_output=&quot;pandas&quot;)</code> <br></p> <p>But in <strong>case-to-case basis</strong>, how can I create a function in StandardScalerCustom() class that can fix the error above?</p>
<python><machine-learning><scikit-learn><scikit-learn-pipeline>
2023-01-06 03:14:45
3
347
Armando Bridena
75,026,483
6,814,713
How to sort unbound list of PySpark columns by name?
<p>This seems like it should be pretty simple, but I'm stumped for some reason. I have a list of PySpark columns that I would like to sort by name (including aliasing, as that will be how they are displayed/written to disk). Here's some example tests and things I've tried:</p> <pre class="lang-py prettyprint-override"><code>def test_col_sorting(): from pyspark.sql import SparkSession import pyspark.sql.functions as f # Active spark context needed spark = SparkSession.builder.getOrCreate() # Data to sort cols = [f.col('c'), f.col('a'), f.col('b').alias('z')] # Attempt 1 result = sorted(cols) # This fails with ValueError: Cannot convert column into bool: please use '&amp;' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions. # Attempt 2 result = sorted(cols, key=lambda x: x.name()) # Fails for the same reason, `name()` returns a Column object, not a string # Assertion I want to hold true: assert result = [f.col('a'), f.col('c'), f.col('b').alias('z')] </code></pre> <p>Is there any reasonable way to actually get the string back out of the Column object that was used to initialize it (but also respecting aliasing)? If I could get this from the object I could use it as a key.</p> <p>Note that I am NOT looking to sort the columns on a DataFrame, as answered in this question: <a href="https://stackoverflow.com/questions/42912156/python-pyspark-data-frame-rearrange-columns">Python/pyspark data frame rearrange columns</a>. These Column objects are not bound to any DataFrame. I also do not want to sort the column based on the values of the column.</p>
<python><apache-spark><pyspark>
2023-01-06 02:51:45
2
2,124
Brendan
75,026,447
10,141,914
Memoisation - Bernoulli numbers
<p>I am trying to compute some <a href="https://math.stackexchange.com/questions/2844290/what-is-the-simplest-way-to-get-bernoulli-numbers">Bernoulli numbers</a> and am trying to use <a href="https://towardsdatascience.com/memoization-in-python-57c0a738179a" rel="nofollow noreferrer">memoisation</a>. In the example below, I can get the Bernoulli number for 8 when I run 1-7 before it, but not if the cache is clear. What changes would I need to make to run it when the cache is clear?</p> <pre><code>from fractions import Fraction from scipy.special import comb import numpy as np # memoisation bernoulli_cache = {} def bernoulli(n: float): # check input, if it exists, return value if n in bernoulli_cache: return bernoulli_cache[n] # when input is 0 or 1 if n == 0: value = Fraction(1) else: value = Fraction(1) for k in range(n): value -= Fraction(comb(n, k)) * Fraction(bernoulli(k), (n - k + 1)) # write to cache bernoulli_cache[n] = value # fraction parts for output numerator = value.numerator denominator = value.denominator return numerator, denominator # test this works- bits in cache aleady bernoulli_cache = {} bernoulli(0) # 1 bernoulli(1) # 1/2 bernoulli(2) # 1/6 bernoulli(3) # 0 bernoulli(4) # −1/30 bernoulli(5) # 0 bernoulli(6) # 1/42 bernoulli(7) # 0 bernoulli(8) # -1/30 # this doesn't - bits not in cache bernoulli_cache = {} bernoulli(8) # -1/30 </code></pre>
<python><recursion><memoization>
2023-01-06 02:45:14
1
1,718
william3031
75,026,436
11,171,682
Constructing Tensorflow Dataset and applying TextVectorization layer using map method
<p>I'm attempting to construct input to an embedding layer for an NLP model. However, I am having problems with converting raw text data to the numerical input required by the embedding layer.</p> <p>Here is some example data to illustrate what I wish to feed to the NLP model:</p> <pre><code># 0 = negative # 1 = positive documents = [['topology freaking sucks man, what a waste of time!', 0], ['wow bro you a NLP fan? Tell me more I want to know', 1], ['you know, I will eventually die',0], ['the secret to happiness is to only be depresssed',0], ['what is the floor without feet', 1], ['regicide is permissable only in historical situations',1], ['I do not like delivering wehat based products for I am allergic to wheat', 0], ['Why does he ring the large bell every hour?',0], ['Wisdom comes not from experience but from knowing',1], ['Little is known of the inner workings of the feline mind', 1]] </code></pre> <p>Each document contains one sentence and one label. This data format was inspired by the tutorial prompt I am working on:</p> <blockquote> <p>Your Task Your task in this lesson is to design a small document classification problem with 10 documents of one sentence each and associated labels of positive and negative outcomes and to train a network with word embedding on these data.</p> </blockquote> <p>I utilize the TextVectorization function from the keras library:</p> <pre><code># create preprocessing layer VOCAB_SIZE = 500 # max amount of vocabulary amongst all documents MAX_SEQUENCE_LENGTH = 50 # maximum amount of words/tokens that will be considered in each document # output mode 'int' will assign unique integer per token, so in our example below, 'topology' is assigned the value # 19. Notice that these integers are randomly assigned and essentially acts as a hashmap int_vectorize_layer = TextVectorization( max_tokens=VOCAB_SIZE, output_mode='int', output_sequence_length = MAX_SEQUENCE_LENGTH ) </code></pre> <p>The issue now becomes applying this vectorized layer to the raw data <code>documents</code>. Here is the following code I have to convert the raw data into a tensorflow <code>Dataset</code> object:</p> <pre><code># Applies adapted layer to tensorflow dataset def int_vectorize_text(sentence, label): sentence = tf.expand_dims(sentence, -1) sentence = tf.squeeze(sentence, axis=-1) return int_vectorize_layer(sentence), label # passes raw data as a generator to the Dataset from_generator constructor def generate_data(sentences, labels): for s, l in zip(sentences,labels): yield s, l # split raw data between training and validation set train_docs = documents[:8] val_docs = documents[8:] # separate sentences and labels train_sentences = [d[0] for d in train_docs] train_labels = [d[1] for d in train_docs] val_sentences = [d[0] for d in val_docs] val_labels = [d[1] for d in val_docs] # convert to tensors train_sentences_tensor = tf.convert_to_tensor(train_sentences) train_labels_tensor = tf.convert_to_tensor(train_labels) val_sentences_tensor = tf.convert_to_tensor(val_sentences) val_labels_tensor = tf.convert_to_tensor(val_labels) # build tensorflow Dataset using the above generator function on the newly constructed tensor objects train_dataset = tf.data.Dataset.from_generator( generate_data, (tf.string, tf.int32), args=(train_sentences_tensor, train_labels_tensor)) val_dataset = tf.data.Dataset.from_generator( generate_data, (tf.string, tf.int32), args=(val_sentences_tensor, val_labels_tensor)) # adapt layer using training sentences int_vectorize_layer.adapt(train_sentences) # now here is where the error occurs int_train_df = train_dataset.map(int_vectorize_text) # ERROR int_val_df = val_dataset.map(int_vectorize_text) </code></pre> <p>As you can see, an error occurs when we attempt to map the <code>int_vectorize_text</code> to the tensorflow dataset. Specifically, I get the following error:</p> <pre><code>TypeError Traceback (most recent call last) /home/akagi/Documents/Projects/MLMastery NLP Tutorial/Lesson 5 - Learned Embedding.ipynb Cell 7 in &lt;cell line: 21&gt;() 19 # Use the map method to apply the int_vectorize_text function to each element of the dataset 20 int_vectorize_layer.adapt(train_sentences) ---&gt; 21 int_train_df = train_dataset.map(int_vectorize_text) 22 int_val_df = val_dataset.map(int_vectorize_text) File ~/Documents/Projects/.venv/lib/python3.8/site-packages/tensorflow/python/data/ops/dataset_ops.py:2294, in DatasetV2.map(self, map_func, num_parallel_calls, deterministic, name) 2291 if deterministic is not None and not DEBUG_MODE: 2292 warnings.warn(&quot;The `deterministic` argument has no effect unless the &quot; 2293 &quot;`num_parallel_calls` argument is specified.&quot;) -&gt; 2294 return MapDataset(self, map_func, preserve_cardinality=True, name=name) 2295 else: 2296 return ParallelMapDataset( 2297 self, 2298 map_func, (...) 2301 preserve_cardinality=True, 2302 name=name) File ~/Documents/Projects/.venv/lib/python3.8/site-packages/tensorflow/python/data/ops/dataset_ops.py:5499, in MapDataset.__init__(self, input_dataset, map_func, use_inter_op_parallelism, preserve_cardinality, use_legacy_function, name) 5497 self._use_inter_op_parallelism = use_inter_op_parallelism 5498 self._preserve_cardinality = preserve_cardinality -&gt; 5499 self._map_func = structured_function.StructuredFunctionWrapper( ... '&gt;' not supported between instances of 'NoneType' and 'int' Call arguments received by layer 'text_vectorization' (type TextVectorization): • inputs=tf.Tensor(shape=&lt;unknown&gt;, dtype=string) </code></pre> <p>Which seems to imply that a <code>NoneType</code> is being passed. However, I checked the construction of <code>train_dataset</code> and it appears to be correct. Here is what it looks like:</p> <pre><code>(&lt;tf.Tensor: shape=(), dtype=string, numpy=b'topology freaking sucks man, what a waste of time!'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=0&gt;) (&lt;tf.Tensor: shape=(), dtype=string, numpy=b'wow bro you a NLP fan? Tell me more I want to know'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=1&gt;) (&lt;tf.Tensor: shape=(), dtype=string, numpy=b'you know, I will eventually die'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=0&gt;) (&lt;tf.Tensor: shape=(), dtype=string, numpy=b'the secret to happiness is to only be depresssed'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=0&gt;) (&lt;tf.Tensor: shape=(), dtype=string, numpy=b'what is the floor without feet'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=1&gt;) (&lt;tf.Tensor: shape=(), dtype=string, numpy=b'regicide is permissable only in historical situations'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=1&gt;) (&lt;tf.Tensor: shape=(), dtype=string, numpy=b'I do not like delivering wehat based products for I am allergic to wheat'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=0&gt;) (&lt;tf.Tensor: shape=(), dtype=string, numpy=b'Why does he ring the large bell every hour?'&gt;, &lt;tf.Tensor: shape=(), dtype=int32, numpy=0&gt;) </code></pre> <p>Furthermore, if I apply <code>int_vectorize_text</code> manually in a loop like so:</p> <pre><code>for x in train_dataset: print(int_vectorize_text(x[0], x[1])) </code></pre> <p>No error occurs and I get the desired output. What is going on here?</p>
<python><tensorflow><machine-learning><keras><nlp>
2023-01-06 02:43:49
2
747
hkj447
75,026,410
2,643,864
How to build a Pandas Dataframe with a Numpy Array from Imported CSV data with multiple numbers
<p>I'm a little stumped on this one. I've created a proof of concept where I built a Pandas Dataframe with a static Numpy Array of numbers. I got this working fine, but now I'm taking it a step further and importing a CSV file to build this same Dataframe and Numpy Array. Here is the snippet of the file and what I've written. I want to take the second column of 'numbers' and build an array of 6 numbers per line. For example, [[11],[21],[27],[36],[62],[24]], [[14],[18],[36],[49],[67],[18]], etc.</p> <p>CSV:</p> <pre><code>date,numbers,multiplier 09/26/2020,11 21 27 36 62 24,3 09/30/2020,14 18 36 49 67 18,2 10/03/2020,18 31 36 43 47 20,2 </code></pre> <p>CODE:</p> <pre><code>data = pd.read_csv('pbhistory.csv') data['date'] = pd.to_datetime(data.date, infer_datetime_format=True) data.sort_values(by='date', ascending=True, inplace=True) df = pd.DataFrame(data.numbers).to_numpy() df2 = pd.DataFrame(df, columns=['1', '2', '3', '4', '5', '6']) print(df2.head()) </code></pre> <p>ERROR: I'm expecting 6 columns of data from df2 as I thought it was converted to an array properly after importing the 'numbers' column from the CSV, but I get the following:</p> <p><strong>ValueError: Shape of passed values is (1414, 1), indices imply (1414, 6)</strong></p> <p>So, I change the code to <code>df2 = pd.DataFrame(df, columns=['1'])</code> and get the following output. The problem is, I need it to be in 6 columns, not 1.</p> <pre><code> 1 0 11 21 27 36 62 24 1 14 18 36 49 67 18 2 18 31 36 43 47 20 </code></pre> <p>So, as you can see, I'm only getting one column with all numbers, instead of an array of numbers with 6 columns.</p>
<python><arrays><pandas><dataframe><numpy>
2023-01-06 02:38:28
2
651
user2643864
75,026,352
1,899,433
Thread execution time seems incorrect
<p>I trying to poll an API and then time how long it takes to make a file available</p> <pre class="lang-py prettyprint-override"><code>def main(): pool = ThreadPoolExecutor(max_workers=8) for filename in os.listdir(data_dir): pool.submit(poll_status, filename) def poll_status(filename: str): start_time = perf_counter() for i in range(30): logging.info(f&quot;Attempt {i}&quot;) resp = requests.get(f&quot;https://api/{filename}/statuses&quot;) if resp.status_code == 404: # Wait 3 seconds and try again on next attempt time.sleep(3) elif resp.status_code == 200: end_time = perf_counter() logging.info( f'{filename} took {end_time - start_time: 0.2f} seconds to complete. (Attempt {i})') </code></pre> <p>Printing times taken for each file to become available seem to be increasing while the attempts are not.</p> <pre><code>INFO:root:f1 took 0.19 seconds to complete. (Attempt 0) INFO:root:f2 took 4.79 seconds to complete. (Attempt 0) INFO:root:f3 took 7.43 seconds to complete. (Attempt 0) INFO:root:f4 took 7.99 seconds to complete. (Attempt 0) INFO:root:f5 took 12.11 seconds to complete. (Attempt 0) INFO:root:f6 took 15.84 seconds to complete. (Attempt 0) INFO:root:f7 took 16.54 seconds to complete. (Attempt 0) INFO:root:f8 took 16.35 seconds to complete. (Attempt 0) </code></pre> <p>If an attempt took 16 seconds I would expect it to be Attempt 5? (as there should be a 3 second wait after each attempt)</p> <p>Am I using Thread Pool incorrectly or is there a problem with how I am timing each attempt?</p>
<python>
2023-01-06 02:27:46
0
568
Anon957
75,026,339
597,858
Create a bool list based on a list of float in python
<p>This is a <code>sample_list = [628.6, 628.25, 632.8, 634.65, 634.9, 635.85, 633.55]</code></p> <p>I want to create a bool list of true/false based on the condition that if a list value is greater than the previous value, it should be true, else false. In my case, result should be something like this:</p> <pre><code>mybools = [False,True,True,True,True,False] </code></pre> <p>how do I do that?</p>
<python>
2023-01-06 02:25:14
2
10,020
KawaiKx
75,026,310
597,858
Create a Boolean column based on condition which involves value from a column of the current row and previous row in Pandas
<p>I want to add a Boolean column to this Dataframe.</p> <pre><code> date open high low close volume 1912 2023-01-05 09:15:00+05:30 641.80 644.30 626.35 628.60 615758 1913 2023-01-05 10:15:00+05:30 628.60 634.50 624.15 628.25 313480 1914 2023-01-05 11:15:00+05:30 627.80 633.45 627.40 632.80 193937 1915 2023-01-05 12:15:00+05:30 632.70 636.05 630.80 634.65 223713 1916 2023-01-05 13:15:00+05:30 634.65 635.00 629.45 634.90 224242 1917 2023-01-05 14:15:00+05:30 634.80 637.90 633.35 635.85 310906 1918 2023-01-05 15:15:00+05:30 635.90 637.35 633.50 633.55 101989 </code></pre> <p>Boolean column should show True if the 'close' value of the row is greater than the 'close' value of the previous row, else it should be false.</p> <p>how do I do that?</p>
<python><pandas><dataframe>
2023-01-06 02:19:04
1
10,020
KawaiKx
75,026,218
344,669
Python pytest mock the class method - TypeError: 'str' object is not callable
<p>Based on this blog post <a href="https://changhsinlee.com/pytest-mock/" rel="nofollow noreferrer">https://changhsinlee.com/pytest-mock/</a>, trying to mock the object method call. But its giving the error for me.</p> <pre><code>tests/pytest_samples/test_load_data.py:5 (test_slow_load) mocker = &lt;pytest_mock.plugin.MockerFixture object at 0x10536b940&gt; def test_slow_load(mocker): assert &quot;Data&quot; in slow_load() expected = 'mock load' def mock_load(): return 'mock load' mocker.patch(&quot;python_tools.pytest_samples.load_data.DataSet.load_data&quot;, mock_load()) &gt; actual = slow_load() test_load_data.py:15: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def slow_load(): dataset = DataSet() &gt; return dataset.load_data() E TypeError: 'str' object is not callable ../../src/python_tools/pytest_samples/load_data.py:6: TypeError </code></pre> <p>Here is the file name and test code: module name <code>python_tools</code> folder name <code>pytest_samples</code>. This test needs <code>pytest-mock</code> python module to run the test.</p> <p>slow.py</p> <pre><code>class DataSet: def load_data(self): return 'Loading Data' </code></pre> <p>load_data.py</p> <pre><code>from python_tools.pytest_samples.slow import DataSet def slow_load(): dataset = DataSet() return dataset.load_data() </code></pre> <p>test_load_data.py</p> <pre><code>from python_tools.pytest_samples.load_data import slow_load def test_slow_load(): assert &quot;Data&quot; in slow_load() def test_slow_load(mocker): assert &quot;Data&quot; in slow_load() expected = 'mock load' def mock_load(): return 'mock load' mocker.patch(&quot;python_tools.pytest_samples.load_data.DataSet.load_data&quot;, mock_load()) actual = slow_load() assert actual == expected </code></pre> <p>Can you help me understand why its giving this error message?</p> <p>Thanks</p>
<python><python-3.x><pytest>
2023-01-06 02:02:32
1
19,251
sfgroups
75,026,109
2,178,774
Matplotlib: Shared titles between rows within subplots
<p>Suppose we have the following:</p> <pre class="lang-py prettyprint-override"><code>fig, ax = plt.subplots(nrows=3, ncols=2, figsize=(10,10)) for i in range(0, 3): # Left plot ax[i,0].plot(data1[i].x, data1[i].y) # Right plot ax[i,1].plot(data2[i].x, data2[i].y) </code></pre> <p>Such that there are three rows and two columns with six figures in total. Is it possible to add a shared title for each row of the subplot? I can't think of anything better than adding a title for each axes (e.g. <code>ax[i,0].set_title('Left part of figure')</code>).</p>
<python><matplotlib>
2023-01-06 01:38:59
1
516
There
75,026,031
13,709,317
Preferred way to write audio data to a WAV file?
<p>I am trying to write an audio file using python's <code>wave</code> and <code>numpy</code>. So far I have the following and it works well:</p> <pre class="lang-py prettyprint-override"><code>import wave import numpy as np # set up WAV file parameters num_channels = 1 # mono audio sample_width = 1 # 8 bits(1 byte)/sample sample_rate = 44.1e3 # 44.1k samples/second frequency = 440 # 440 Hz duration = 20 # play for this many seconds num_samples = int(sample_rate * duration) # samples/seconds * seconds # open WAV file and write data with wave.open('sine8bit_2.wav', 'w') as wavfile: wavfile.setnchannels(num_channels) wavfile.setsampwidth(sample_width) wavfile.setframerate(sample_rate) t = np.linspace(0, duration, num_samples) data = (127*np.sin(2*np.pi*frequency*t)).astype(np.int8) wavfile.writeframes(data) # or data.tobytes() ?? </code></pre> <p>My issue is that since I am using a high sampling rate, the <code>num_samples</code> variable might quickly become too large (9261000 samples for a 3 minute 30 seconds track say). Would using a numpy array this large be advisable? Is there a better way of going about this? Also is use of <code>writeframes(.tobytes())</code> needed in this case because my code runs fine without it and it seems like extra overhead (especially if the arrays get too large).</p>
<python><numpy><wav><wave>
2023-01-06 01:20:11
1
801
First User
75,025,990
14,044,486
Logging in python from multiple files
<p>I'm definitely missing something when it comes to logging using the logging module. I can get it to work just fine if I have just 1 file with everything in it, but when I try to split things up into separate files or packages I'm not sure what to do.</p> <p>Suppose I have a package with the following directory tree:</p> <pre><code>mypackage/ ├─ __init__.py ├─ utils.py ├─ my_logger.py main.py </code></pre> <p>In my package I have a logger (in <code>my_logger.py</code>) that is configured nearly to my liking. In my <code>main.py</code> file, I initialize that logger and add a <a href="https://docs.python.org/3/library/logging.handlers.html#logging.FileHandler" rel="nofollow noreferrer">FileHandler</a> to start writing to a file.</p> <p>However, I'd also like to log to this file from other files in my package. Say, for example, the file <code>utils.py</code>. How do I make the instance of logger in <code>utils.py</code> know about the FileHandler?</p> <p>Suppose I have a series of functions in <code>utils.py</code>, say, <code>myfunc1()</code> and <code>myfunc2()</code>, and I'd like each to also log to the same file. I don't want to have to pass my instance of logger to each individual function.</p> <p>There feels like an obvious setting I am missing. What should I have in which file in order to make sure they all know about the <em>same</em> logger instance everywhere in the package?</p> <p>(A detail that may or may not be relevant — I've actually subclassed <code>Logger</code> to give it some custom behaviour. But this shouldn't affect the answer to this question, I don't think.)</p>
<python><logging>
2023-01-06 01:10:36
1
593
Drphoton
75,025,969
1,726,404
How to monkey patch a function using pytest
<p>I am trying to test a function that reads in a csv file with some numbers and calculates the area. I am trying to test it by patching a pandas function using pytest, specifically read_csv function such that it returns the same dataframe every time. For some reason I can't seem to monkeypatch it</p> <p><strong>circle.py</strong></p> <pre><code>import math import pandas as pd def get_area(r): if not type(r) in [int, float]: raise TypeError(&quot;Non numeric value&quot;) return math.pi*(r**2) def read_rads(): df = pd.read_csv('radii.csv', header=None, index_col=None) return( [get_area(x[0]) for x in df.iterrows()]) if __name__ == '__main__': print(get_area(2)) print(read_rads()) </code></pre> <p><strong>test_circle.py</strong></p> <pre><code>import pytest import circle import math import unittest from unittest import mock import pandas as pd def test_get_area(): assert circle.get_area(1) == math.pi * 1**2 assert circle.get_area(3) == math.pi * 3**2 def test_if_get_area_for_string_input(): with pytest.raises(TypeError): circle.get_area('some string') def test_read_radii(monkeypatch): # We have to mock the response of pd.read_csv def mock_read_csv(*args, **kwargs): return pd.DataFrame([0,1,2,3,5]) # apply the monkeypatch for requests.get to mock_get monkeypatch.setattr(pd, &quot;read_csv&quot;, mock_read_csv) res = circle.read_rads() assert res == [0.0, 3.141592653589793, 12.566370614359172, 28.274333882308138, 78.53981633974483] </code></pre> <p>radii is just a csv file with a number on each line, nothing special.</p> <p>I tried following along with <a href="https://docs.pytest.org/en/7.1.x/how-to/monkeypatch.html#monkeypatching-returned-objects-building-mock-classes" rel="nofollow noreferrer">https://docs.pytest.org/en/7.1.x/how-to/monkeypatch.html#monkeypatching-returned-objects-building-mock-classes</a> I understand that they used a class for the test, but why isn't the read_csv function being monkeypatched? And is this the right way to patch in the data for use in the function?</p>
<python><pytest><monkeypatching>
2023-01-06 01:05:10
0
3,259
Kevin
75,025,925
3,276,836
When closing Kivy app settings, UI text changes don't work
<p>When I start the following app and click btn2 I observe the text of the button change as I would expect. When I open settings using btn1, then close settings and then click btn2 the text does not change again, yet the button is pressed (message is printed). I have noticed this happening with other labels as well and I don't understand why. It should be noted that the callback is called as expected and the message printed with the same button instance.</p> <p>While debugging this I also found that the counter keeps incrementing as expected but the text becomes an empty string after the settings are closed and updating it does not reflect onto the app UI.</p> <pre class="lang-py prettyprint-override"><code>from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button class MainLayout(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) btn1 = Button(text=&quot;Settings&quot;, size_hint=(.5, 1), on_press=self.btn1_on_press) btn2 = Button(text=&quot;0&quot;, size_hint=(.5, 1), on_press=self.btn2_on_press) self.add_widget(btn1) self.add_widget(btn2) self.counter = 0 def btn1_on_press(self, btn): app.open_settings() def btn2_on_press(self, btn): print(&quot;btn pressed: &quot;, btn) self.counter += 1 btn.text = str(self.counter) class MyApp(App): def build(self): self.use_kivy_settings = False return MainLayout() def build_config(self, config): config.setdefaults(&quot;settings&quot;, { &quot;dark_mode&quot;: True, }) def build_settings(self, settings): settings.add_json_panel(&quot;settings&quot;, self.config, data=&quot;&quot;&quot;[ { &quot;type&quot;: &quot;bool&quot;, &quot;title&quot;: &quot;Dark mode&quot;, &quot;desc&quot;: &quot;Enable dark mode&quot;, &quot;section&quot;: &quot;settings&quot;, &quot;key&quot;: &quot;dark_mode&quot; } ]&quot;&quot;&quot;) if __name__ == '__main__': app = MyApp() app.run() </code></pre> <p>The current kivy version I use is 2.1.0.</p> <pre><code>$ pip freeze | grep -i kivy Kivy==2.1.0 Kivy-Garden==0.1.5 </code></pre>
<python><kivy>
2023-01-06 00:58:20
1
474
alex10791
75,025,620
1,939,183
get column names from a python dataframe having values as white spaces without using loops
<p>I have a below dataframe, I am trying to get the column names that has empty strings in a most efficient way. The dataframe looks like below after doing df.head().</p> <pre><code>id type check company test 123 A Soft [[1649106820, 100029907158392,,,, 123]] 456 B Hard GMC [[1649106812, 100029907158312,,,, 456]] </code></pre> <p>I am trying to do it without using loops or in an efficient way Appreciate help with it</p> <p>Expected output {company,test}</p>
<python><arrays><pandas><dataframe><numpy>
2023-01-05 23:55:43
2
379
keeplearning
75,025,334
12,357,696
Remove empty space at bottom of QTableWidget
<p>I'm using PySide6 6.4.1 to build a table widget that automatically resizes to the number of rows. Here's a minimal example:</p> <pre class="lang-py prettyprint-override"><code>from PySide6.QtWidgets import * class MW(QWidget): def __init__(self): super().__init__() self.button = QPushButton(&quot;Test&quot;) self.table = QTableWidget(self) self.table.setColumnCount(1) self.table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents) self.setLayout(QVBoxLayout(self)) self.layout().addWidget(self.button) self.layout().addWidget(self.table) self.button.clicked.connect(self.test) return def test(self): self.table.insertRow(0) self.table.setItem(0, 0, QTableWidgetItem(&quot;new item&quot;)) self.table.adjustSize() self.adjustSize() return app = QApplication() mw = MW() mw.show() app.exec() </code></pre> <p>Somehow this always leaves a bit of empty space at the bottom of the table. How do I get rid of this space without doing manual resizing?</p> <p><a href="https://i.sstatic.net/VA4Tv.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VA4Tv.png" alt="enter image description here" /></a></p> <p>(Nevermind the weird font size, it's a known bug when using UI scaling. I've adjusted the font size manually as well and it doesn't get rid of this problem.)</p>
<python><qt><pyside6>
2023-01-05 23:09:21
1
752
Antimon
75,025,330
19,633,374
Compare Two String Arrays
<p>I have two arrays</p> <pre><code>array_1 = [&quot;AAAA&quot;,&quot;BBBB&quot;] array_2 = [&quot;XXX&quot;,&quot;AA&quot;,&quot;AAAA&quot;,&quot;ZZZZ&quot;] </code></pre> <p>I want to compare there both arrays and return true if any element from array_1 matches with one in array_2.</p> <p>How can I do that?</p>
<python><arrays><string>
2023-01-05 23:08:33
4
642
Bella_18
75,025,284
16,978,074
How can I print the original title of the top 50 movies from themoviedatabase.org with python?
<p>hello all i'm learning python recently and i need to analyze the web of themoviedb.org website. I want to extract all the movies in the database and I want to print the original title of the first 50 movies.This is a piece of the json file that i receive as a response following my network request:</p> <pre><code>{&quot;page&quot;:1,&quot;results&quot;:[{&quot;adult&quot;:false,&quot;backdrop_path&quot;:&quot;/5gPQKfFJnl8d1edbkOzKONo4mnr.jpg&quot;,&quot;genre_ids&quot;:[878,12,28],&quot;id&quot;:76600,&quot;original_language&quot;:&quot;en&quot;,&quot;original_title&quot;:&quot;Avatar: The Way of Water&quot;,&quot;overview&quot;:&quot;Set more than a decade after the events of the first film, learn the story of the Sully family (Jake, Neytiri, and their kids), the trouble that follows them, the lengths they go to keep each other safe, the battles they fight to stay alive, and the tragedies they endure.&quot;,&quot;popularity&quot;:5332.225,&quot;poster_path&quot;:&quot;/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg&quot;,&quot;release_date&quot;:&quot;2022-12-14&quot;,&quot;title&quot;:&quot;Avatar: The Way of Water&quot;,&quot;video&quot;:false,&quot;vote_average&quot;:7.7,&quot;vote_count&quot;:3497},{......}],&quot;total_pages&quot;:36589,&quot;total_results&quot;:731777} </code></pre> <p>And this is my code:</p> <pre><code>import requests response = requests.get(&quot;https://api.themoviedb.org/3/discover/movie?api_key=my_key&amp;language=en-US&amp;sort_by=popularity.desc&amp;include_adult=false&amp;include_video=false&amp;page=1&amp;with_watch_monetization_types=flatrate&quot;) jsonresponse=response.json() page=jsonresponse[&quot;page&quot;] results=jsonresponse[&quot;results&quot;] for i in range(50): for result in jsonresponse[&quot;original_title&quot;][i]: print(result) </code></pre> <p>My code don't work. Error: &quot;KeyError: 'original_title'&quot;. How can I print the original title of the top 50 movies?</p>
<python><json><for-loop><themoviedb-api>
2023-01-05 23:02:49
2
337
Elly
75,025,188
458,700
run python app after server restart does not work using crontab
<p>I have a python application and I run it using <code>python app.py</code> but when the machine restart for any reason the application stoped</p> <p>I searched and I found that I can make it run again using corn jobs</p> <p>so I installed crontab and add the following code to it</p> <pre><code>@reboot /home/airnotifier/airnotifier/airnotifier.sh </code></pre> <p>and this is the code in the file <code>airnotifier.sh</code></p> <pre><code>cd /home/airnotifier/airnotifier python ./app.py cd airnotifier python ./app.py cd /home/airnotifier/airnotifier python app.py cd airnotifier python app.py </code></pre> <p>as you can see, I tried all combinations to make the application run again</p> <p>can anyone tell me what did I do wrong?</p>
<python><linux><ubuntu><cron>
2023-01-05 22:49:07
1
9,464
Amira Elsayed Ismail
75,025,117
11,564,487
Quarto ignores ipython output
<p>Consider the following <code>quarto</code> document:</p> <pre><code>--- title: &quot;Untitled&quot; format: pdf jupyter: r-reticulate --- ```{ipython} print('hello1') ``` ```{python} print('hello2') ``` </code></pre> <p>The <code>pdf</code> document does not print <code>hello1</code>, but prints <code>hello2</code>. It seems that <code>quarto</code> ignores <code>ipython</code> output. Is that expected?</p>
<python><quarto>
2023-01-05 22:40:07
0
27,045
PaulS
75,025,087
820,088
Using win32com.client to Read MS Word Table
<p>I have a MS Word document (Microsoft 365) that I want to update via python using the win32com.client module. Within the .docx file, some tables have been inserted and there are cells containing text values within those tables, that I want to update. I've been testing how to read through the table using win32com. For example:</p> <pre><code>import win32com.client word = win32com.client.gencache.EnsureDispatch(&quot;Word.Application&quot;) word.Visible = True doc = word.Documents.Open(r&quot;path_to_my_doc&quot;) doc = word.ActiveDocument table = doc.Tables(2) for row in range(1,table.Rows.Count + 1): for col in range(1,table.Columns.Count + 1): print(table.Cell(Row = row,Column = col).Range.Text) </code></pre> <p>The above code works fine when reading through a table that has equal rows and columns and no merged or split cells. The issue I run into is where a table has merged cells or split cells. The code will start reading through the table, but when it hits a row that has more or less cells than the last row, it produces an error:</p> <pre><code>Traceback (most recent call last): File &quot;W:\em\vic\mtb\Local\MTB_Scripts\Testing_Area\mmacrae\IOR\2022Nov_updates\script\win32com_word.py&quot;, line 41, in &lt;module&gt; table.Cell(Row = row,Column = col).Range.Text = table.Cell(Row = row,Column = col).Range.Text File &quot;E:\sw_nt\Python27\ArcGIS10.6\lib\site-packages\win32com\gen_py\00020905-0000-0000-C000-000000000046x0x8x5\Table.py&quot;, line 50, in Cell , Column) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Word', u'The requested member of the collection does not exist.', u'wdmain11.chm', 25421, -2146822347), None) </code></pre> <p>Here is a screenshot of the word document I have been testing on that contains 3 tables.</p> <p><a href="https://i.sstatic.net/ltZOX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ltZOX.png" alt="enter image description here" /></a></p> <p>The first table has equal columns along each row. When I run the code on that table, it will print our the cells text values with no errors. When I run the code on the second 2 tables, where I had split a few cells so that there are odd numbers of columns for each row, I receive the error.</p> <p>After a lot of testing, I feel like these merged or split cells are causing the issue. I've been googling around to see if this issue has come up and I can't find anything there or here on Stack. Hoping for some suggestions on how to handle these tables and code.</p>
<python><ms-word><office365><win32com><office-automation>
2023-01-05 22:36:35
1
4,435
Mike
75,025,065
6,611,672
Difference between Django `BaseCommand` loggers and `logging.getLogger()`
<p>When writing custom Django management commands, the <a href="https://docs.djangoproject.com/en/4.1/howto/custom-management-commands/" rel="nofollow noreferrer">docs</a> recommend using <code>self.stdout</code> and <code>self.stderr</code>.</p> <pre><code>class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write(&quot;Hello world!&quot;) self.stderr.write(&quot;Something went horribly wrong&quot;) </code></pre> <p>I've typically used the <code>logging</code> module in the past:</p> <pre><code>import logging logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): logging.info(&quot;Hello world!&quot;) logging.error(&quot;Something went horribly wrong&quot;) </code></pre> <p>A few questions:</p> <ul> <li>Is there a difference between the Django <code>BaseCommand</code> loggers and the <code>logging</code> logger?</li> <li>Does the Django <code>BaseCommand</code> logger use the <code>logging</code> module under the hood? If so, what level does <code>self.stdout</code> and <code>self.stderr</code> use?</li> </ul>
<python><django><logging>
2023-01-05 22:32:36
1
5,847
Johnny Metz
75,024,993
12,097,553
S3 presigned url: 403 error when reading a file but OK when downloading
<p>I am working with a s3 presigned url. OK: links works well to download. NOT OK: using the presigned url to read a file in the bucket</p> <p>I am getting the following error in console:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;Error&gt;&lt;Code&gt;AuthorizationQueryParametersError&lt;/Code&gt;&lt;Message&gt;Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.&lt;/Message&gt; </code></pre> <p>and here is how generate the url with <code>boto3</code></p> <pre><code> s3_client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name='eu-west-3') bucket_name = config(&quot;AWS_STORAGE_BUCKET_NAME&quot;) file_name = '{}/{}/{}/{}'.format(user, 'projects', building.building_id, file.file) ifc_url = s3_client.generate_presigned_url( 'get_object', Params={ 'Bucket': bucket_name, 'Key': file_name, }, ExpiresIn=1799 ) </code></pre> <p>I am using IFC.js which allows to load ifc formated models from their urls . Basically the url of the bucket acts as the path to the file. Accessing files in a public bucket has been working well however it won't work with private buckets.</p> <p>Something to note as well is that using the presigned url copied from clipboard from the aws s3 interface works. it looks like this:</p> <pre><code>&quot;https://bucket.s3.eu-west-3.amazonaws.com/om1/projects/1/v1.ifc?response-content-disposition=inline&amp;X-Amz-Security-Token=qqqqzdfffrA%3D&amp;X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Date=20230105T224241Z&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Expires=60&amp;X-Amz-Credential=5%2Feu-west-3%2Fs3%2Faws4_request&amp;X-Amz-Signature=c470c72b3abfb99&quot; </code></pre> <p>the one I obtain with boto3 is the following:</p> <pre><code>&quot;https://bucket.s3.amazonaws.com/om1/projects/1/v1.ifc?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKI230105%2Feu-west-3%2Fs3%2Faws4_request&amp;X-Amz-Date=20230105T223404Z&amp;X-Amz-Expires=3600&amp;X-Amz-SignedHeaders=host&amp;X-Amz-Signature=1b4f277b85639b408a9ee16e&quot; </code></pre> <p>I am fairly new to use s3 buckets so I am not sure what is wrong here, and searching around on SO and online has not been very helpful so far. Could anyone point me in the right direction?</p>
<python><django><amazon-web-services><amazon-s3><boto3>
2023-01-05 22:23:33
0
1,005
Murcielago
75,024,926
11,564,487
Is Quarto able to render documents with ipython magic?
<p>Consider the following document:</p> <pre><code>--- title: &quot;Untitled&quot; format: pdf jupyter: r-reticulate --- ```{python} %load_ext rpy2.ipython ``` </code></pre> <p>when rendered, it produces the following error:</p> <pre><code>An error occurred while executing the following cell: ------------------ %load_ext rpy2.ipython ------------------ </code></pre> <p>So my question is: Is Quarto able to render documents with <code>ipython</code> magic?</p>
<python><quarto>
2023-01-05 22:15:28
1
27,045
PaulS
75,024,865
11,922,765
Python Dataframe categorize values
<p>I have a data coming from the field and I want to categorize it with a gap of specific range. I want to categorize in 100 range. That is, 0-100, 100-200, 200-300 My code:</p> <pre><code>df=pd.DataFrame([112,341,234,78,154],columns=['value']) value 0 112 1 341 2 234 3 78 4 154 </code></pre> <p>Expected answer:</p> <pre><code> value value_range 0 112 100-200 1 341 200-400 2 234 200-300 3 78 0-100 4 154 100-200 </code></pre> <p>My code:</p> <pre><code>df['value_range'] = df['value'].apply(lambda x:[a,b] if x&gt;a and x&lt;b for a,b in zip([0,100,200,300,400],[100,200,300,400,500])) </code></pre> <p>Present solution:</p> <pre><code>SyntaxError: invalid syntax </code></pre>
<python><pandas><dataframe><numpy>
2023-01-05 22:08:08
2
4,702
Mainland
75,024,830
5,437,090
initilize the bash input argument when nothing is given | Error
<p>I have a following bash script which is a REST API for a national library using <code>curl</code> command:</p> <pre><code>#!/bin/bash for ARGUMENT in &quot;$@&quot; do echo &quot;$ARGUMENT&quot; KEY=$(echo $ARGUMENT | cut -f1 -d=) KEY_LENGTH=${#KEY} VALUE=&quot;${ARGUMENT:$KEY_LENGTH+1}&quot; export &quot;$KEY&quot;=&quot;$VALUE&quot; done echo &quot;ARGUMENTS COUNT : &quot; $# echo &quot;ARGUMENTS LIST : &quot; $* out_file_name=&quot;newspaper_info_query_${QUERY// /_}.json&quot; echo &quot;&gt;&gt; Saving DIR: $PWD/$out_file_name&quot; if [ -z &quot;$ORDER_BY&quot; ]; then ORDER_BY=&quot;${ORDER_BY:-}&quot;; fi # returns ERROR when no input is provided! curl \ -v 'https://digi.kansalliskirjasto.fi/rest/binding-search/search/binding?offset=0&amp;count=10000' \ -o $out_file_name \ -H 'Accept: application/json, text/plain, */*' \ -H 'Cache-Control: no-cache' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Pragma: no-cache' \ --compressed \ -d @- &lt;&lt;EOF { &quot;orderBy&quot;:&quot;$ORDER_BY&quot;, &quot;query&quot;:&quot;$QUERY&quot; } EOF </code></pre> <p>Then, I run the aforementioned bash script in python:</p> <pre><code>import subprocess def rest_api(): subprocess.call(['bash', 'my_file.sh', 'QUERY=freedom', # mandatory, always provided! 'ORDER_BY=RELEVANCE', # optional, if comment: ERROR! ]) if __name__ == '__main__': rest_api() </code></pre> <p><code>ORDER_BY</code> argument gets the following inputs: <code>RELEVANCE, TITLE_ASC, TITLE_DESC, AUTHOR_ASC, AUTHOR_DESC, DATE, DATE_DESC</code> or simply nothing.</p> <p>It works when I use either one of those inputs in my python script as the input to the bash script to retrieve a json file with information.</p> <p>To handle no input case, e.g., initialize <code>ORDER_BY</code> as empty or nothing , I have added <code>if [ -z &quot;$ORDER_BY&quot; ]; then ORDER_BY=&quot;${ORDER_BY:-}&quot;; fi</code> to set ORDER_BY with no parameter, e.g., empty! However, It does not work and returns this long error in my saved json <code>out_file_name</code>:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang=&quot;fi&quot;&gt; &lt;head prefix=&quot;og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#&quot;&gt; &lt;title&gt;Digitaaliset aineistot - Kansalliskirjasto&lt;/title&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no&quot;&gt; &lt;meta name=&quot;robots&quot; content=&quot;index, follow&quot;/&gt; &lt;meta name=&quot;copyright&quot; content=&quot;Kansalliskirjasto. Kaikki oikeudet pidätetään.&quot;/&gt; &lt;link rel=&quot;shortcut icon&quot; href=&quot;/favicon.ico&quot; type=&quot;image/x-icon&quot;&gt; &lt;base href=&quot;/&quot;&gt; &lt;meta name=&quot;google-site-verification&quot; content=&quot;fLK4q3SMlbeGTQl-tN32ENsBoaAaTlRd8sRbmTxlSBU&quot; /&gt; &lt;meta name=&quot;msvalidate.01&quot; content=&quot;7EDEBF53A1C81ABECE44A7A666D94950&quot; /&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=DM+Serif+Display&amp;family=Open+Sans:ital,wght@0,300;0,400;0,600;0,700;1,400&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;script&gt; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-10360577-3', 'auto'); &lt;/script&gt; &lt;!-- Global site tag (gtag.js) - Google Analytics --&gt; &lt;script async src=&quot;https://www.googletagmanager.com/gtag/js?id=G-KF8NK1STFH&quot;&gt;&lt;/script&gt; &lt;script&gt; window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); // see google-analytics.service &lt;/script&gt; &lt;!-- Matomo --&gt; &lt;script&gt; var _paq = window._paq = window._paq || []; (function() { var u = &quot;https://tilasto.lib.helsinki.fi/&quot;; _paq.push(['setTrackerUrl', u + 'matomo.php']); _paq.push(['setSiteId', '17']); var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0]; g.async = true; g.src = u + 'matomo.js'; s.parentNode.insertBefore(g, s); } )(); &lt;/script&gt; &lt;noscript&gt;&lt;p&gt;&lt;img src=&quot;https://tilasto.lib.helsinki.fi/matomo.php?idsite=17&amp;amp;rec=1&quot; style=&quot;border:0;&quot; alt=&quot;&quot;/&gt;&lt;/p&gt;&lt;/noscript&gt; &lt;!-- End Matomo Code --&gt;&lt;style type=&quot;text/css&quot;&gt;[ng-cloak] { display: none !important; }&lt;/style&gt; &lt;script&gt; window.errorHandlerUrl = &quot;/rest/js-error-handler&quot;; window.commonOptions = {&quot;localLoginEnabled&quot;:true,&quot;localRegistrationEnabled&quot;:false,&quot;marcOverlayEnabled&quot;:true,&quot;opendataEnabled&quot;:true,&quot;overrideHeader&quot;:&quot;&quot;,&quot;hakaEnabled&quot;:true,&quot;includeExternalResources&quot;:true,&quot;legalDepositWorkstation&quot;:false,&quot;jiraCollectorEnabled&quot;:true,&quot;buildNumber&quot;:&quot;8201672f226078f2cefbe8a0025dc03f5d98c25f&quot;,&quot;searchMaxResults&quot;:10000,&quot;showExperimentalSearchFeatures&quot;:true,&quot;bindingSearchMaxResults&quot;:1000,&quot;excelDownloadEnabled&quot;:true,&quot;giosgEnabled&quot;:true}; &lt;/script&gt; &lt;style type=&quot;text/css&quot;&gt;.external-resource-alt { display: none !important; }&lt;/style&gt; &lt;/head&gt; &lt;body class=&quot;digiweb&quot;&gt; &lt;noscript&gt; &lt;h3&gt;Sovellus vaatii JavaScriptin.&lt;/h3&gt; &lt;p&gt;Ole hyvä ja laita selaimesi JavaScript päälle, jos haluat käyttää palvelua.&lt;/p&gt; &lt;h3&gt;Aktivera Javascript.&lt;/h3&gt; &lt;p&gt;För att kunna använda våra webbaserade system behöver du ha Javascript aktiverat.&lt;/p&gt; &lt;h3&gt;This application requires JavaScript.&lt;/h3&gt; &lt;p&gt;Please turn on JavaScript in order to use the application.&lt;/p&gt; &lt;/noscript&gt;&lt;app-digiweb&gt;&lt;/app-digiweb&gt; &lt;div id=&quot;kk-server-error&quot; style=&quot;display: none;&quot;&gt; &lt;h1 align=&quot;center&quot;&gt;Järjestelmässä tapahtui virhe.&lt;/h1&gt;&lt;/div&gt; &lt;div id=&quot;kk-server-page&quot; style=&quot;display: none;&quot;&gt; &lt;/div&gt; &lt;script type=&quot;text/javascript&quot;&gt; window.language = &quot;fi&quot;; window.renderId = 1672955582793; window.facebookAppId = &quot;465149013631512&quot; window.reCaptchaSiteKey = &quot;6Lf7xuASAAAAANNu9xcDirXyzjebiH4pPpkKVCKq&quot;; &lt;/script&gt; &lt;script src=&quot;/assets/runtime-es2015.f1ac93cb35b9635f0f7e.js&quot; type=&quot;module&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/assets/runtime-es5.f1ac93cb35b9635f0f7e.js&quot; nomodule&gt;&lt;/script&gt; &lt;script src=&quot;/assets/polyfills-es2015.8db02cde19c51f542c72.js&quot; type=&quot;module&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/assets/polyfills-es5.2273af7ef2cf66cdc0de.js&quot; nomodule&gt;&lt;/script&gt; &lt;script src=&quot;/assets/styles-es2015.a539381f703344410705.js&quot; type=&quot;module&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/assets/styles-es5.a539381f703344410705.js&quot; nomodule&gt;&lt;/script&gt; &lt;script src=&quot;&quot; type=&quot;module&quot;&gt;&lt;/script&gt; &lt;script src=&quot;&quot; type=&quot;module&quot;&gt;&lt;/script&gt; &lt;script src=&quot;&quot; nomodule&gt;&lt;/script&gt; &lt;script src=&quot;/assets/main-es2015.b5796f606e925a9d947d.js&quot; type=&quot;module&quot;&gt;&lt;/script&gt; &lt;script src=&quot;/assets/main-es5.b5796f606e925a9d947d.js&quot; nomodule&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Is there any better approach to initialize my <code>ORDER_BY</code> argument in bash to get rid of this error for the case no input is provided (initialize empty)?</p> <p>Cheers,</p>
<python><json><bash><rest><curl>
2023-01-05 22:03:38
1
1,621
farid
75,024,604
6,630,397
Formatting the time slot of a Pylon's deform.widget.DateTimeInputWidget
<h4>Needs</h4> <p>I need to customize a <a href="https://docs.pylonsproject.org/projects/deform/en/latest/api.html#deform.widget.DateTimeInputWidget" rel="nofollow noreferrer"><code>deform.widget.DateTimeInputWidget</code></a>, especially to get rid of the seconds in the input time slot so that the user doesn't need to specify them. By default seconds have to be filled but I'm only interested in hours (24h based) and minutes.</p> <p><a href="https://i.sstatic.net/9emOp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9emOp.png" alt="enter image description here" /></a><br /> <em>Default deform DateTimeInputWidget. How to get rid of those pesky seconds in the time slot?</em></p> <h4>What I found</h4> <p>I was really attracted by the option called <code>time_options</code> in the doc, but it only says:</p> <blockquote> <p>time_options A dictionary of time options passed to pickadate.</p> </blockquote> <p>without any example of such dictionary. This is apparently needed to feed this JavaScript code: <a href="https://github.com/amsul/pickadate.js/blob/master/lib/picker.time.js" rel="nofollow noreferrer">https://github.com/amsul/pickadate.js/blob/master/lib/picker.time.js</a> but I don't really know where and how by looking at this code.</p> <p>Even more confusing is the fact that the default value (<code> default_time_options</code>) which is hard coded is not a dictionary: <a href="https://github.com/Pylons/deform/blob/f4da7dffb0b9235babe4e99596eefd1a6170c640/deform/widget.py#L696" rel="nofollow noreferrer">https://github.com/Pylons/deform/blob/f4da7dffb0b9235babe4e99596eefd1a6170c640/deform/widget.py#L696</a> is a tuple of tuples, which is then converted into a dict: <a href="https://github.com/Pylons/deform/blob/f4da7dffb0b9235babe4e99596eefd1a6170c640/deform/widget.py#L737-L741" rel="nofollow noreferrer">https://github.com/Pylons/deform/blob/f4da7dffb0b9235babe4e99596eefd1a6170c640/deform/widget.py#L737-L741</a></p> <p>And from the example, this <code>((&quot;format&quot;, &quot;h:i A&quot;), (&quot;interval&quot;, 30))</code> is transformed into: <code>{'format': 'h:i A', 'interval': 30}</code>.</p> <p>The thing I don't understand here is the format itself: <code>'h:i A'</code>. It's quite obscure to me as it doesn't seem to rely on any of the standard format for formatting a time string in Python (<a href="https://strftime.org/" rel="nofollow noreferrer">https://strftime.org/</a>).</p> <h4>Question</h4> <p>Hence my question: how could I force the time part of the <code>deform.widget.DateTimeInputWidget</code> to be like: <code>%H:%M</code> ?</p> <p>With <code>%H</code> = hour (24-hour clock) as a zero-padded decimal number and <code>%M</code> = Minute as a zero-padded decimal number, as described in: to <a href="https://strftime.org/" rel="nofollow noreferrer">https://strftime.org/</a></p> <p>Or some format which would lead to the same output, e.g. 00:01, 06:15, 10:10, 18:00 or 23:59.</p>
<python><datetimepicker><pyramid><pylons><deform>
2023-01-05 21:37:22
1
8,371
swiss_knight
75,024,589
13,142,245
Python Xpress get computation time and related statistics
<p>Xpress has some built in logging, including computation time, total memory available and threads used. However, there's quite a bit extraneous information in these logging statements. Is there a method to get this sort of information?</p> <p>What I'm looking for</p> <pre class="lang-py prettyprint-override"><code>xpress_problem.solve(get_time=True, get_memory=True) </code></pre> <p>These aren't real arguments that I've found from <code>solve</code> to be expecting, I just illustrate what I'd like.</p>
<python><mixed-integer-programming><xpress-optimizer>
2023-01-05 21:35:17
1
1,238
jbuddy_13
75,024,416
5,056,347
How to download a pkpass file converted to base64 using HTML?
<p>From my server, I'm reading my pkpass file and converting it to base64. I want to make this file downloadable on my template. Here's what I'm doing.</p> <p><strong>Server/Python (Django)</strong></p> <pre><code>passfile_bytes = passfile.read() passfile_base64 = base64.b64encode(passfile) # This is sent to template </code></pre> <p><strong>Template/HTML</strong></p> <pre><code>&lt;a href=&quot;data:application/vnd.apple.pkpass;base64,{{ passfile_base64 }}&quot; download=&quot;file.pkpass&quot;&gt; Download &lt;/a&gt; </code></pre> <p>I know I'm messing up the <code>href</code> here because the download fails. How do I actually make this ready for download when the link is clicked?</p>
<python><html><apple-wallet><pkpass>
2023-01-05 21:14:01
1
8,874
darkhorse
75,024,361
14,104,321
Linear interpolation of 2D-arrays along one axis
<p>I need to interpolate 2D-arrays along one axis, in this case <code>axis=1</code>. I tried to use <code>scipy.interpolate.interp1d</code> but I cannot make it work.</p> <p>This is what I get with a simple example:</p> <pre><code>import numpy as np import scipy.interpolate xp = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) yp = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]]) x = np.array([[1.5, 4.5, 7.5], [2.5, 6.5, 9.5]]) interpolate = scipy.interpolate.interp1d(xp, yp, axis=1) ValueError: x and y arrays must be equal in length along interpolation axis. </code></pre> <p>The expected result is:</p> <pre><code>[[ 1.5 4.5 7.5] [ 6.5 42.5 90.5]] </code></pre> <p>Of course, the easiest solution would be to iterate along <code>axis=0</code> and make several 1D-array interpolations but since my actual arrays are pretty big, I would like to avoid it. Any idea on how I can solve this? Thanks a lot!</p>
<python><numpy><scipy><interpolation>
2023-01-05 21:07:28
1
582
mauro
75,024,325
18,392,410
Nim: How can I improve concurrent async response time and quota to match cpythons asyncio?
<p>For an upcoming project this year, I wanted to look into some languages that I haven't really used yet, but that repeatedly catch my interest. Nim is one of them 😊.</p> <p>I wrote the following code to make async requests:</p> <pre><code>import asyncdispatch, httpclient, strformat, times, strutils let urls = newHttpClient().getContent(&quot;https://gist.githubusercontent.com/tobealive/b2c6e348dac6b3f0ffa150639ad94211/raw/31524a7aac392402e354bced9307debd5315f0e8/100-popular-urls.txt&quot;).splitLines()[0..99] proc getHttpResp(client: AsyncHttpClient, url: string): Future[string] {.async.} = try: result = await client.getContent(url) echo &amp;&quot;{url} - response length: {len(result)}&quot; except Exception as e: echo &amp;&quot;Error: {url} - {e.name}&quot; proc requestUrls(urls: seq[string]) {.async.} = let start = epochTime() echo &quot;Starting requests...&quot; var futures: seq[Future[string]] for url in urls: var client = newAsyncHttpClient() futures.add client.getHttpResp(&amp;&quot;http://www.{url}&quot;) for i in 0..urls.len-1: discard await futures[i] echo &amp;&quot;Requested {len(urls)} websites in {epochTime() - start}.&quot; waitFor requestUrls(urls) </code></pre> <p><strong>Results doing some loops:</strong></p> <pre><code>Iterations: 10. Total errors: 94. Average time to request 100 websites: 9.98s. </code></pre> <p>The finished application will only request from a single ressource. So for example, when requesting Google search queries (for simplicity just the numbers from 1 to 100), the result look like:<br></p> <pre><code>Iterations: 1. Total errors: 0. Time to request 100 google searches: 3.75s. </code></pre> <hr /> <p>Compared to Python, there are still significant differences:</p> <pre class="lang-py prettyprint-override"><code>import asyncio, time, requests from aiohttp import ClientSession urls = requests.get( &quot;https://gist.githubusercontent.com/tobealive/b2c6e348dac6b3f0ffa150639ad94211/raw/31524a7aac392402e354bced9307debd5315f0e8/100-popular-urls.txt&quot; ).text.split('\n') async def getHttpResp(url: str, session: ClientSession): try: async with session.get(url) as resp: result = await resp.read() print(f&quot;{url} - response length: {len(result)}&quot;) except Exception as e: print(f&quot;Error: {url} - {e.__class__}&quot;) async def requestUrls(urls: list[str]): start = time.time() print(&quot;Starting requests...&quot;) async with ClientSession() as session: await asyncio.gather(*[getHttpResp(f&quot;http://www.{url}&quot;, session) for url in urls]) print(f&quot;Requested {len(urls)} websites in {time.time() - start}.&quot;) # await requestUrls(urls) # jupyter asyncio.run(requestUrls(urls)) </code></pre> <p><strong>Results:</strong></p> <pre><code>Iterations: 10. Total errors: 10. Average time to request 100 websites: 7.92s. </code></pre> <p>When requesting only google search queries:</p> <pre><code>Iterations: 1. Total errors: 0. Time to request 100 google searches: 1.38s. </code></pre> <p>(I'm not big into python, but when using it, it's often impressive what it's C libraries deliver.)</p> <hr /> <p>The difference in response time remains when <strong>just getting the response status code</strong>.</p> <hr /> <p>To improve the Nim code, I thought it might be worth trying to add channels and multiple clients (this is from a still very limited point of view on my second day of programming in Nim + generally not having a lot of experience with concurrent requests). But I haven't really figured out how to get it to work.</p> <p>Doing a lot of request to the same endpoint in the nim example (e.g. when doing the google searches) it also may result in a <code>Too Many Requests</code> error if this amount of Google searches are performed repeatedly. In python this doesn't seem to be the case.</p> <p><strong>So it would be great if you could share your approach on what can be done to improve the response quota and request time!</strong></p> <p>If anyone wants a repo for cloning and tinkering, this one contains the example with the loop: <a href="https://github.com/tobealive/nim-async-requests-example" rel="nofollow noreferrer">https://github.com/tobealive/nim-async-requests-example</a></p>
<python><asynchronous><concurrency><request><nim-lang>
2023-01-05 21:02:19
1
563
tenxsoydev
75,024,310
10,818,367
pandas get first row for each unique value in a column
<p>Given a pandas data frame, how can I get the first row for each unique value in a column?</p> <p>for example, given:</p> <pre><code> a b key 0 1 2 1 1 2 3 1 2 3 3 1 3 4 5 2 4 5 6 2 5 6 6 2 6 7 2 1 7 8 2 1 8 9 2 3 </code></pre> <p>the result when analyzing by column <code>key</code> should be</p> <pre><code> a b key 0 1 2 1 3 4 5 2 8 9 2 3 </code></pre> <hr /> <p>p.s. df src:</p> <pre><code>pd.DataFrame([{'a':1,'b':2,'key':1}, {'a':2,'b':3,'key':1}, {'a':3,'b':3,'key':1}, {'a':4,'b':5,'key':2}, {'a':5,'b':6,'key':2}, {'a':6,'b':6,'key':2}, {'a':7,'b':2,'key':1}, {'a':8,'b':2,'key':1}, {'a':9,'b':2,'key':3}]) </code></pre>
<python><pandas>
2023-01-05 21:00:33
1
1,212
Daniel Warfield
75,024,288
1,448,641
scalar/array multiplication return Any type
<p>I wonder why mypy produces so many &quot;Returning Any from function declared to return ...&quot; errors when it has to deal with numpy. In the example below, <code>a</code> is an array and <code>b</code> is a scalar. As I see it, there is no way in which <code>np.exp(a*x)</code> would return anything else but another array. Even if <code>x</code> was <code>np.inf</code>, the result would still be an array. So why does mypy think the function could return any type?</p> <pre><code>import numpy as np from numpy.typing import NDArray def func(a: NDArray[np.float64], x: float) -&gt; NDArray[np.float64]: return np.exp(a*x) </code></pre> <p>PS: check the above code with <code>mypy --warn-return-any [file name]</code>, then you should see:</p> <blockquote> <p>a.py:5: error: Returning Any from function declared to return &quot;ndarray[Any, dtype[floating[_64Bit]]]&quot; [no-any-return]</p> </blockquote> <ul> <li>python 3.10.8</li> <li>mypy 0.991</li> <li>numpy 1.24.0</li> </ul>
<python><python-3.x><numpy><mypy><typing>
2023-01-05 20:57:56
1
5,519
MaxPowers
75,024,194
4,796,942
dask.compute all values of Dask DataFrame type that are stored as values in a dictionary
<p>I understand that if I store many Dask dataframes in a list I can compute all of them in parallel as</p> <pre><code>result = dask.compute(*container_list) </code></pre> <p>but how would I do something similar if I store the Dask dataframe results as values in a dictionary? (If <code>containe_dict</code> is a dictionary</p> <pre><code>result = dask.compute(*container_dict) </code></pre> <p>would not work.)</p> <p>The best I could do was loop over the dictionary with a container, but this is not ideal since we are now running <code>dask.compute</code> multiple times rather than once.</p> <pre><code>container_dict = {} for index, value in enumerate(comb_dict_stock): container_dict[index] = ddf.loc[index] # index ddf to get the row for index and value in dict # compute all the dask dataframes in container_dict for key, value in container_dict.items(): container_dict[key] = value.compute() </code></pre>
<python><dictionary><dask><dask-dataframe>
2023-01-05 20:47:30
1
1,587
user4933
75,024,139
13,142,245
Multi-Processing nested loops in Python?
<p>I have a multi-nested for loop and I'd like to parallelize this as much as possible, in Python.</p> <p>Suppose I have some arbitrary function, which accepts two arguments <code>func(a,b)</code> and I'd like to compute this function on all combinations of M and N.</p> <p>What I've done so far is 'flatten' the indices as a dictionary</p> <pre class="lang-py prettyprint-override"><code>idx_map = {} count = 0 for i in range(n): for j in range(m): idx_map[count] = (i,j) count += 1 </code></pre> <p>Now that my nested loop is flattened, I can use it like so:</p> <pre class="lang-py prettyprint-override"><code>arr = [] for idx in range(n*m): i,j = idx_map[idx] arr.append( func(M[i], N[j]) ) </code></pre> <p>Can I use this with Python's built in multi-Processing to parallelize? Race conditions should not be an issue because I do not need to aggregate func calls; rather, I just want to arrive at some final array, which evaluates all <code>func(a,b)</code> combinations across M and N. (So Async behavior and complexity should not be relevant here.)</p> <p>What's the best way to accomplish this effect?</p> <p>I see from this related <a href="https://stackoverflow.com/questions/48710255/how-to-parallelize-a-nested-for-loop-in-python">question</a> but I don't understand what the author was trying to illustrate.</p> <pre class="lang-py prettyprint-override"><code>if 1: # multi-threaded pool = mp.Pool(28) # try 2X num procs and inc/dec until cpu maxed st = time.time() for x in pool.imap_unordered(worker, range(data_Y)): pass print 'Multiprocess total time is %4.3f seconds' % (time.time()-st) print </code></pre>
<python><for-loop><parallel-processing><multiprocessing>
2023-01-05 20:42:32
1
1,238
jbuddy_13
75,024,077
18,758,062
Matplotlib+Jupyter stops rendering animation when run inside a function
<p>After getting a <code>matplotlib</code> animation to run successfully inside a Vscode Juypter notebook cell, I decided to refactor the matplotlib animation code into a function but this causes the matplotlib figure to stop showing and display a warning</p> <blockquote> <p>UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. <code>anim</code>, that exists until you output the Animation using <code>plt.show()</code> or <code>anim.save()</code>.</p> </blockquote> <p><strong>Initial working code:</strong></p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import matplotlib.animation import numpy as np plt.rcParams[&quot;animation.html&quot;] = &quot;jshtml&quot; plt.rcParams[&quot;figure.dpi&quot;] = 100 plt.ioff() def animate(frame_num): x = np.linspace(0, 2*np.pi, 100) y = np.sin(x + 2*np.pi * frame_num/100) line.set_data((x, y)) return line fig, ax = plt.subplots() line, = ax.plot([]) ax.set_xlim(0, 2*np.pi) ax.set_ylim(-1.1, 1.1) matplotlib.animation.FuncAnimation( fig, animate, frames=10, blit=True ) </code></pre> <p><a href="https://i.sstatic.net/39Qia.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/39Qia.png" alt="enter image description here" /></a></p> <p><strong>Non-working refactored code:</strong></p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import matplotlib.animation import numpy as np plt.rcParams[&quot;animation.html&quot;] = &quot;jshtml&quot; plt.rcParams[&quot;figure.dpi&quot;] = 100 plt.ioff() def animate(frame_num): x = np.linspace(0, 2*np.pi, 100) y = np.sin(x + 2*np.pi * frame_num/100) line.set_data((x, y)) return line def generate_animation(): fig, ax = plt.subplots() line, = ax.plot([]) ax.set_xlim(0, 2*np.pi) ax.set_ylim(-1.1, 1.1) anim = matplotlib.animation.FuncAnimation( fig, animate, frames=10, blit=True ) plt.show() return anim anim = generate_animation() </code></pre> <p>Also tried adding <code>%matplotlib notebook</code> or <code>%matplotlib widget</code> to the start of the Jupyter notebook cell, but the same error occurs.</p> <p>Is there a way to get the <code>matplotlib.animation.FuncAnimation</code> working when its running from inside a function?</p>
<python><matplotlib><visual-studio-code><jupyter-notebook><matplotlib-animation>
2023-01-05 20:35:17
0
1,623
gameveloster
75,023,945
8,230,132
list AWS SCP policies attached to an account
<p>Is there anyway I can get a list of all scp policies that is attached to particular account. I have many account in AWS organization and wanted make list of scp policies attached to each individual account. Below python function is working but only showing default AWS managed scp policy however there are many custom SCP policies (inherited policies) attached that it is not listing. Am I doing something wrong?</p> <pre><code>session = boto3.Session(profile_name='saml') response = session.client('organizations', region_name='us-east-1') scp = response.list_policies_for_target(TargetId='xxxxxxxxxxxx', Filter='SERVICE_CONTROL_POLICY') </code></pre> <p>With this I am getting only below output.</p> <pre><code>$ python test_lambda.py [{'Arn': 'arn:aws:organizations::aws:policy/service_control_policy/p-FullAWSAccess', 'AwsManaged': True, 'Description': 'Allows access to every operation', 'Id': 'p-FullAWSAccess', 'Name': 'FullAWSAccess', 'Type': 'SERVICE_CONTROL_POLICY'}] </code></pre>
<python><python-3.x><amazon-web-services><boto3>
2023-01-05 20:21:38
0
703
Rio
75,023,913
11,621,983
Python MSS Screenshot monitor sizes different than expected
<p>Using mss, I have taken screenshots of my two monitors: monitor-1 and monitor-2. When I open up monitor-1, I get the image size of 3840x2160. However, when accessing monitors from <code>mss().monitors[1]</code>, I get the size of 1920x1080. They are two completely different sizes! <a href="https://i.sstatic.net/mSd7S.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/mSd7S.jpg" alt="Screenshots from mss" /></a></p> <p>I also checked this on my second monitor, and the size is correct.</p> <p>These are my display settings:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Monitor 1</th> <th>Monitor 2</th> </tr> </thead> <tbody> <tr> <td><a href="https://i.sstatic.net/fYb6c.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fYb6c.png" alt="Display setting - monitor 1" /></a></td> <td><a href="https://i.sstatic.net/OTXGM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OTXGM.png" alt="Display setting - monitor 2" /></a></td> </tr> </tbody> </table> </div> <p>I got the screenshots with the following code:</p> <pre class="lang-py prettyprint-override"><code>import mss sct = mss.mss() for x in sct.save(0): print(x) </code></pre>
<python><macos><python-mss>
2023-01-05 20:18:38
1
382
unfestive chicken
75,023,869
12,596,824
Anonymizing column names
<p>I have a dataframe like so</p> <pre><code>IsCool IsTall IsHappy Target 0 1 0 1 1 1 0 0 0 1 0 0 1 0 1 1 </code></pre> <p>I want to anonymize the column names except for target. How can I do this?</p> <p>Expected output:</p> <pre><code>col1 col2 col3 Target 0 1 0 1 1 1 0 0 0 1 0 0 1 0 1 1 </code></pre> <p><strong>Source dataframe :</strong></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({&quot;IsCool&quot;: [0, 1, 0, 1], &quot;IsTall&quot;: [1, 1, 1, 0], &quot;IsHappy&quot;: [0, 0, 0, 1], &quot;Target&quot;: [1, 0, 0, 1]}) </code></pre>
<python><pandas>
2023-01-05 20:13:24
3
1,937
Eisen
75,023,865
7,932,866
Sphinx auto-documentation doesn't work with classes which improt other classes
<p>I am currently working on a python project and want to automatically generate the documentation for my project</p> <p>In order to automatically generate my documentation, I do:</p> <ol> <li><code>sphinx-apidoc -f -o source ../modules</code></li> <li><code>make html</code></li> </ol> <p>But when I do that, I get the following error:<br /> <code>WARNING: autodoc: failed to import module 'CalculationManager' from module 'model'; the following exception was raised: No module named 'modules'</code></p> <p>I have no idea why this is happening, can anyone help me?</p> <p>My <code>folder structure</code> of the project:<br /> <a href="https://i.sstatic.net/detdz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/detdz.png" alt="enter image description here" /></a></p> <p>The <code>CalculationManager</code> class:</p> <pre class="lang-py prettyprint-override"><code>from modules.model import CalculationPhase from modules.model import ConfigurationManager class CalculationManager: &quot;&quot;&quot; The CalculationManager manages Calculation of the Project. &quot;&quot;&quot; def __init__(self, starting_point: CalculationPhase, configuration_manager: ConfigurationManager): &quot;&quot;&quot; Gets called when we first create an object of this class, it saves all information it needs for starting a calculation. Args: starting_point: Describes in which calculation-phase we want to start the calculation. configuration_manager: Saves all information required to configure the calculation. &quot;&quot;&quot; pass def cancel_calculation(self): &quot;&quot;&quot; This method is used when we want to cancel an ongoing calculation. &quot;&quot;&quot; pass def _validate_starting_point(self) -&gt; bool: &quot;&quot;&quot; Validates the correctness of the Staring Point. Returns: bool: If true then the starting_point is valid, this means every calculation up to this point exist and are saved in the project. &quot;&quot;&quot; pass def _start_calculation(self): &quot;&quot;&quot; Starts the calculation. &quot;&quot;&quot; pass </code></pre> <p>The other classes in the folder modules are empty, they have a class and pass standing in it.</p> <p>My <code>index.rst</code>:</p> <pre><code>.. ExampleProject documentation master file, created by sphinx-quickstart on Mon Dec 19 19:53:45 2022. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to ExampleProject's documentation! ========================================== .. toctree:: :maxdepth: 2 :caption: Contents: modules Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` </code></pre> <p>My <code>conf.py</code>:</p> <pre class="lang-py prettyprint-override"><code># Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../../modules/')) # -- Project information ----------------------------------------------------- project = 'x' copyright = 'x' author = 'x' # The full version, including alpha/beta/rc tags release = '1.0.0' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ &quot;sphinx.ext.autodoc&quot;, &quot;sphinx.ext.autosummary&quot;, 'sphinx.ext.napoleon' # support for google docstring style ] autodoc_default_options = { 'members': True, 'member-order': 'bysource', 'special-members': '__init__', 'undoc-members': True, 'exclude-members': '__weakref__' } # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_book_theme' # html_logo = &quot;../../../pictures/&quot; html_theme_options = { # &quot;external_links&quot;: [], &quot;repository_url&quot;: &quot;https://github.com/LuposX/KonfiguratorFuerOSMDaten&quot;, &quot;repository_branch&quot;: &quot;main&quot;, &quot;path_to_docs&quot;: &quot;pythoncode/docs/&quot;, &quot;use_repository_button&quot;: True, } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named &quot;default.css&quot; will overwrite the builtin &quot;default.css&quot;. # html_static_path = ['_static'] </code></pre> <p>The html site:<br /> <a href="https://i.sstatic.net/xQuWx.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xQuWx.png" alt="enter image description here" /></a></p> <p>You can see that <code>model.CalculationManager module</code>is empty.</p> <p>Full <code>make html</code> description:<br /> <a href="https://i.sstatic.net/PlafR.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PlafR.png" alt="enter image description here" /></a> <strong>EDIT1</strong>:</p> <ul> <li>Misspelled init, wasn't the problem though</li> <li>Added full sphinx build log</li> </ul> <p><strong>EDIT2:</strong><br /> Someone recommended to add <code>__init__.py</code> to the modules folder, I tried this already if I do this I get a circular dependency Issue, look below:</p> <pre class="lang-bash prettyprint-override"><code>Running Sphinx v4.5.0 loading pickled environment... done [autosummary] generating autosummary for: index.rst, modules.rst building [mo]: targets for 0 po files that are out of date building [html]: targets for 1 source files that are out of date updating environment: 3 added, 1 changed, 3 removed reading sources... [100%] modules.view /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst:4: WARNING: duplicated entry found in toctree: modules WARNING: autodoc: failed to import module 'control' from module 'modules'; the following exception was raised: No module named 'modules' WARNING: autodoc: failed to import module 'model.CalculationManager' from module 'modules'; the following exception was raised: No module named 'modules' WARNING: autodoc: failed to import module 'model.CalculationPhase' from module 'modules'; the following exception was raised: No module named 'modules' WARNING: autodoc: failed to import module 'model.ConfigurationManager' from module 'modules'; the following exception was raised: No module named 'modules' WARNING: autodoc: failed to import module 'model' from module 'modules'; the following exception was raised: No module named 'modules' WARNING: autodoc: failed to import module 'view' from module 'modules'; the following exception was raised: No module named 'modules' looking for now-outdated files... none found pickling environment... done checking consistency... /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.control.rst: WARNING: document isn't included in any toctree /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.model.rst: WARNING: document isn't included in any toctree /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.view.rst: WARNING: document isn't included in any toctree done preparing documents... /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: self referenced toctree found. Ignored. done writing output... [100%] modules.view /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules generating indices... genindex /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules done writing additional pages... search /home/lupos/Documents/KonfiguratorFuerOSMDaten/pythoncode/docs/source/modules.rst: WARNING: circular toctree references detected, ignoring: modules &lt;- modules done copying static files... done copying extra files... done dumping search index in English (code: en)... done dumping object inventory... done build succeeded, 20 warnings. The HTML pages are in build/html. </code></pre> <p><strong>EDIT3</strong>:<br /> The problem was the name of my <code>modules</code> folder had the same name as the automatically generated <code>.rst</code> file, so it self referenced itself. After fixing it, I get now the following error:</p> <pre><code>Running Sphinx v4.5.0 loading pickled environment... done [autosummary] generating autosummary for: index.rst, modules.rst building [mo]: targets for 0 po files that are out of date building [html]: targets for 1 source files that are out of date updating environment: 4 added, 1 changed, 3 removed reading sources... [100%] modules WARNING: autodoc: failed to import module 'ConfiguratorOSMData'; the following exception was raised: No module named 'ConfiguratorOSMData' WARNING: autodoc: failed to import module 'control' from module 'ConfiguratorOSMData'; the following exception was raised: No module named 'ConfiguratorOSMData' WARNING: autodoc: failed to import module 'model.CalculationManager' from module 'ConfiguratorOSMData'; the following exception was raised: No module named 'ConfiguratorOSMData' WARNING: autodoc: failed to import module 'model.CalculationPhase' from module 'ConfiguratorOSMData'; the following exception was raised: No module named 'ConfiguratorOSMData' WARNING: autodoc: failed to import module 'model.ConfigurationManager' from module 'ConfiguratorOSMData'; the following exception was raised: No module named 'ConfiguratorOSMData' WARNING: autodoc: failed to import module 'model' from module 'ConfiguratorOSMData'; the following exception was raised: No module named 'ConfiguratorOSMData' WARNING: autodoc: failed to import module 'view' from module 'ConfiguratorOSMData'; the following exception was raised: No module named 'ConfiguratorOSMData' looking for now-outdated files... none found pickling environment... done checking consistency... done preparing documents... done writing output... [100%] modules generating indices... genindex done writing additional pages... search done copying static files... done copying extra files... done dumping search index in English (code: en)... done dumping object inventory... done build succeeded, 7 warnings. The HTML pages are in build/html. </code></pre> <p>The folder structure now looks like this:<br /> <a href="https://i.sstatic.net/RiTcS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RiTcS.png" alt="enter image description here" /></a></p> <p><strong>EDIT4</strong>:<br /> I changed the folder structure to:<br /> <a href="https://i.sstatic.net/RrDI1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RrDI1.png" alt="enter image description here" /></a></p> <p>And added in <code>conf.py</code>:<br /> <code>sys.path.insert(0, os.path.abspath(os.path.join('..', '..', 'src')))</code></p> <p>Which fixed the erros, but now the html looks weird:<br /> <a href="https://i.sstatic.net/lHNEh.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lHNEh.png" alt="enter image description here" /></a></p> <p>It shows the whole path to the classes. How do i fix this?</p>
<python><documentation><python-sphinx><documentation-generation>
2023-01-05 20:13:10
1
907
Lupos
75,023,669
25,282
Read a rtf file and filter out all headline and subtitle elements
<p>I have a Google document that has a lot of headlines and subtitles in addition to its text. Using python I want to read the rtf of the document and afterward use do my own process with the resulting text.</p> <p>How do I import the rtf?</p>
<python><rtf>
2023-01-05 19:51:37
1
26,469
Christian
75,023,581
3,654,588
Sphinx parent class in another package: how to disable single backtick reference warnings
<p>I am working on implementing a Python package that inherits from <a href="https://github.com/networkx/networkx" rel="nofollow noreferrer">networkx</a>. Networkx seems to use <code>numpydoc</code>, but also wraps certain parts of their docstrings in single backtick characters: <code>`</code>. This normally in rst files denotes italics, but in <code>numpydoc</code> this attempts to create a reference.</p> <p>So when I have a file like the following where I use <code>autodoc</code>'s <code>autosummary</code> directive:</p> <pre><code>.. currentmodule:: pywhy_graphs.classes.timeseries .. autosummary:: :toctree: generated/ TimeSeriesGraph TimeSeriesDiGraph TimeSeriesMixedEdgeGraph </code></pre> <p>I get the following errors (I copy-pasted only 3 examples for the sake of space):</p> <pre><code>/Users/adam2392/Documents/pywhy-graphs/pywhy_graphs/classes/timeseries/timeseries.py:docstring of networkx.classes.graph.Graph.to_undirected:33: WARNING: py:obj reference target not found: G = nx.DiGraph(D) /Users/adam2392/Documents/pywhy-graphs/pywhy_graphs/classes/timeseries/timeseries.py:docstring of networkx.classes.graph.Graph.update:25: WARNING: py:obj reference target not found: edges is None /Users/adam2392/Documents/pywhy-graphs/pywhy_graphs/classes/timeseries/timeseries.py:docstring of networkx.classes.graph.Graph.update:25: WARNING: py:obj reference target not found: nodes is None </code></pre> <p>These come for example from docstrings like: <a href="https://github.com/networkx/networkx/blob/83948b6dc61f507adb4cd1a71561eac9ed3b72ec/networkx/classes/graph.py#L1183" rel="nofollow noreferrer">https://github.com/networkx/networkx/blob/83948b6dc61f507adb4cd1a71561eac9ed3b72ec/networkx/classes/graph.py#L1183</a>.</p> <h3>Questions</h3> <ol> <li>If I am using numpydoc, why am I getting this error, but networkx does not when building docs with sphinx?</li> <li>How do I disable, or workaround this error?</li> <li>I don't understand what is going on. If someone can help elaborate what I should do and why, that would be very helpful in learning Sphinx/numpydoc.</li> </ol>
<python><python-sphinx><restructuredtext><numpydoc>
2023-01-05 19:41:54
0
1,302
ajl123
75,023,337
9,721,314
How to extract the index of an element that can be found on several rows
<p>I am looking to extract column name and index of elements from a dataframe</p> <pre><code>import numpy as np import pandas as pd import random lst = list(range(30)) segments = np.repeat(lst, 3) random.shuffle(segments) segments = segments.reshape(10, 9) col_names = ['lz'+str(i) for i in range(95,104)] rows_names = ['con'+str(i) for i in range(0,10)] df = pd.DataFrame(segments, index=rows_names, columns=col_names) lz95 lz96 lz97 lz98 lz99 lz100 lz101 lz102 lz103 con0 6 9 11 7 9 24 18 10 1 con1 24 5 21 15 18 25 24 7 29 con2 17 27 2 0 11 11 18 23 0 con3 16 22 20 22 20 14 14 0 8 con4 10 10 3 13 25 14 9 17 16 con5 3 28 22 2 27 12 16 21 4 con6 26 1 19 7 19 6 29 15 26 con7 26 28 4 13 23 23 1 25 19 con8 28 8 3 6 5 8 4 5 29 con9 2 15 21 27 17 13 12 12 20 </code></pre> <p>For value=12, I am able to extract the column name <code>lz_val = df.columns[df.isin([12]).any()]</code> But not for rows as it extract all indexes</p> <pre><code>con_val = df[df==12].index Index(['con0', 'con1', 'con2', 'con3', 'con4', 'con5', 'con6', 'con7', 'con8', 'con9'], dtype='object') </code></pre>
<python><pandas>
2023-01-05 19:15:16
1
474
Noura
75,023,313
8,551,424
Save kmeans model to future same data clustering
<p>I am currently working on clustering a data set. My question is, is there any way to save the result of the groups so that in the future I can work with new data and know to which group they belong according to the kmeans &quot;model&quot; I made?</p> <p>I have learned to work with Kmeans, it is very interesting, but when I want to know what a new data belongs to, right now I repeat the whole process of analysis. And what I would like is according to the old data (we could call it training data) can I define the group of a new data?</p> <p>This is my code right now.</p> <pre><code>n_clusters = 15 kmeans = KMeans(n_clusters = n_clusters, init = 'k-means++', max_iter = 3000, n_init = 100, random_state = 0) y_kmeans = kmeans.fit_predict(data) data_df['k-means'] = y_kmeans </code></pre> <p>If I plot my current results, I already have the entire data spectrum occupied. Therefore, any new data must belong to one of the current groups.</p> <pre><code>#Visualising the clusters colors = ['blue', 'orange', 'green', 'red', 'yellow', 'cyan', 'brown', 'cadetblue', 'gray',\ 'salmon', 'olive', 'deeppink', 'pink', 'gold', 'lime'] for i in range(n_clusters): plt.scatter(data[y_kmeans == i, 0], data[y_kmeans == i, 1], color=colors[i]) #Plotting the centroids of the clusters plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1], label = 'Centroids') plt.legend() </code></pre> <p><a href="https://i.sstatic.net/efDnQ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/efDnQ.png" alt="enter image description here" /></a></p> <p>Obviously with new data, you will also re-study the data for variations.</p> <p>Thank you very much.</p>
<python><cluster-analysis><k-means>
2023-01-05 19:11:15
1
1,373
Lleims
75,023,226
1,601,580
Why is pip not letting me install torch==1.9.1+cu111 in a new conda env when I have another conda env that has exactly that version?
<p>When I run the pip install in the new conda env:</p> <pre><code>(base) brando9~ $ pip install torch==1.9.1+cu111 torchvision==0.10.1+cu111 torchaudio==0.9.1 -f https://download.pytorch.org/whl/torch_stable.html Looking in links: https://download.pytorch.org/whl/torch_stable.html ERROR: Could not find a version that satisfies the requirement torch==1.9.1+cu111 (from versions: 1.11.0, 1.11.0+cpu, 1.11.0+cu102, 1.11.0+cu113, 1.11.0+cu115, 1.11.0+rocm4.3.1, 1.11.0+rocm4.5.2, 1.12.0, 1.12.0+cpu, 1.12.0+cu102, 1.12.0+cu113, 1.12.0+cu116, 1.12.0+rocm5.0, 1.12.0+rocm5.1.1, 1.12.1, 1.12.1+cpu, 1.12.1+cu102, 1.12.1+cu113, 1.12.1+cu116, 1.12.1+rocm5.0, 1.12.1+rocm5.1.1, 1.13.0, 1.13.0+cpu, 1.13.0+cu116, 1.13.0+cu117, 1.13.0+cu117.with.pypi.cudnn, 1.13.0+rocm5.1.1, 1.13.0+rocm5.2, 1.13.1, 1.13.1+cpu, 1.13.1+cu116, 1.13.1+cu117, 1.13.1+cu117.with.pypi.cudnn, 1.13.1+rocm5.1.1, 1.13.1+rocm5.2) ERROR: No matching distribution found for torch==1.9.1+cu111 </code></pre> <p>the other env with that pytorch version:</p> <pre><code>(metalearning3.9) [pzy2@vision-submit ~]$ pip list Package Version Location ---------------------------------- -------------------- ------------------ absl-py 1.0.0 aiohttp 3.8.3 aiosignal 1.3.1 alabaster 0.7.12 anaconda-client 1.9.0 anaconda-project 0.10.1 antlr4-python3-runtime 4.8 anyio 2.2.0 appdirs 1.4.4 argcomplete 2.0.0 argh 0.26.2 argon2-cffi 20.1.0 arrow 0.13.1 asn1crypto 1.4.0 astroid 2.6.6 astropy 4.3.1 asttokens 2.0.7 astunparse 1.6.3 async-generator 1.10 async-timeout 4.0.2 atomicwrites 1.4.0 attrs 21.2.0 autopep8 1.5.7 Babel 2.9.1 backcall 0.2.0 backports.shutil-get-terminal-size 1.0.0 beautifulsoup4 4.10.0 binaryornot 0.4.4 bitarray 2.3.0 bkcharts 0.2 black 19.10b0 bleach 4.0.0 bokeh 2.4.1 boto 2.49.0 Bottleneck 1.3.2 brotlipy 0.7.0 cached-property 1.5.2 cachetools 5.0.0 certifi 2021.10.8 cffi 1.14.6 chardet 4.0.0 charset-normalizer 2.0.4 cherry-rl 0.1.4 click 8.0.3 cloudpickle 2.0.0 clyent 1.2.2 colorama 0.4.4 conda 4.12.0 conda-content-trust 0+unknown conda-pack 0.6.0 conda-package-handling 1.8.0 conda-token 0.3.0 configparser 5.3.0 contextlib2 0.6.0.post1 cookiecutter 1.7.2 crc32c 2.3 crcmod 1.7 cryptography 3.4.8 cycler 0.10.0 Cython 0.29.24 cytoolz 0.11.0 daal4py 2021.3.0 dask 2021.10.0 debugpy 1.4.1 decorator 5.1.0 defusedxml 0.7.1 diff-match-patch 20200713 dill 0.3.4 distributed 2021.10.0 docker-pycreds 0.4.0 docutils 0.17.1 entrypoints 0.3 et-xmlfile 1.1.0 executing 0.9.1 fairseq 0.12.2 /home/pzy2/fairseq fastcache 1.1.0 fastcluster 1.2.6 fasteners 0.17.3 filelock 3.3.1 flake8 3.9.2 Flask 1.1.2 flatbuffers 2.0.7 fonttools 4.25.0 frozenlist 1.3.0 fsspec 2021.8.1 gast 0.4.0 gcs-oauth2-boto-plugin 3.0 gevent 21.8.0 gitdb 4.0.9 GitPython 3.1.27 glob2 0.7 gmpy2 2.0.8 google-apitools 0.5.32 google-auth 2.6.3 google-auth-oauthlib 0.4.6 google-pasta 0.2.0 google-reauth 0.1.1 gql 0.2.0 graphql-core 1.1 greenlet 1.1.1 grpcio 1.44.0 gsutil 5.9 gym 0.22.0 gym-notices 0.0.6 h5py 3.3.0 HeapDict 1.0.1 higher 0.2.1 html5lib 1.1 httplib2 0.20.4 huggingface-hub 0.5.1 hydra-core 1.0.7 idna 3.2 imagecodecs 2021.8.26 imageio 2.9.0 imagesize 1.2.0 importlib-metadata 4.12.0 inflection 0.5.1 iniconfig 1.1.1 intervaltree 3.1.0 ipykernel 6.4.1 ipython 7.29.0 ipython-genutils 0.2.0 ipywidgets 7.6.5 isort 5.9.3 itsdangerous 2.0.1 jdcal 1.4.1 jedi 0.18.0 jeepney 0.7.1 Jinja2 2.11.3 jinja2-time 0.2.0 joblib 1.1.0 json5 0.9.6 jsonschema 3.2.0 jupyter 1.0.0 jupyter-client 6.1.12 jupyter-console 6.4.0 jupyter-core 4.8.1 jupyter-server 1.4.1 jupyterlab 3.2.1 jupyterlab-pygments 0.1.2 jupyterlab-server 2.8.2 jupyterlab-widgets 1.0.0 keras 2.10.0 Keras-Preprocessing 1.1.2 keyring 23.1.0 kiwisolver 1.3.1 lark-parser 0.12.0 lazy-object-proxy 1.6.0 learn2learn 0.1.7 libarchive-c 2.9 libclang 14.0.6 littleutils 0.2.2 llvmlite 0.37.0 locket 0.2.1 loguru 0.6.0 lxml 4.6.3 Markdown 3.3.6 MarkupSafe 1.1.1 matplotlib 3.4.3 matplotlib-inline 0.1.2 mccabe 0.6.1 mistune 0.8.4 mkl-fft 1.3.1 mkl-random 1.2.2 mkl-service 2.4.0 mock 4.0.3 monotonic 1.6 more-itertools 8.10.0 mpmath 1.2.1 msgpack 1.0.2 multidict 6.0.2 multipledispatch 0.6.0 munkres 1.1.4 mypy-extensions 0.4.3 nbclassic 0.2.6 nbclient 0.5.3 nbconvert 6.1.0 nbformat 5.1.3 nest-asyncio 1.5.1 networkx 2.6.3 nltk 3.6.5 nose 1.3.7 notebook 6.4.5 numba 0.54.1 numexpr 2.7.3 numpy 1.20.3 numpydoc 1.1.0 nvidia-ml-py3 7.352.0 nvidia-smi 0.1.3 oauth2client 4.1.3 oauthlib 3.2.0 olefile 0.46 omegaconf 2.0.6 opencv-python 4.6.0.66 openpyxl 3.0.9 opt-einsum 3.3.0 ordered-set 4.1.0 packaging 21.0 pandas 1.3.4 pandocfilters 1.4.3 parso 0.8.2 partd 1.2.0 path 16.0.0 pathlib2 2.3.6 pathspec 0.7.0 pathtools 0.1.2 patsy 0.5.2 pep8 1.7.1 pexpect 4.8.0 pickleshare 0.7.5 Pillow 8.4.0 pip 22.2.2 pkginfo 1.7.1 plotly 5.7.0 pluggy 0.13.1 ply 3.11 portalocker 2.5.1 poyo 0.5.0 progressbar2 4.0.0 prometheus-client 0.11.0 promise 2.3 prompt-toolkit 3.0.20 protobuf 3.19.6 psutil 5.8.0 ptyprocess 0.7.0 py 1.10.0 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycodestyle 2.7.0 pycosat 0.6.3 pycparser 2.20 pycurl 7.44.1 pydocstyle 6.1.1 pyerfa 2.0.0 pyflakes 2.3.1 Pygments 2.10.0 pylint 2.9.6 pyls-spyder 0.4.0 pyodbc 4.0.0-unsupported pyOpenSSL 21.0.0 pyparsing 3.0.4 pyrsistent 0.18.0 PySocks 1.7.1 pytest 6.2.4 python-dateutil 2.8.2 python-lsp-black 1.0.0 python-lsp-jsonrpc 1.0.0 python-lsp-server 1.2.4 python-slugify 5.0.2 python-utils 3.1.0 pytz 2021.3 pyu2f 0.1.5 PyWavelets 1.1.1 pyxdg 0.27 PyYAML 6.0 pyzmq 22.2.1 QDarkStyle 3.0.2 qpth 0.0.15 qstylizer 0.1.10 QtAwesome 1.0.2 qtconsole 5.1.1 QtPy 1.10.0 regex 2021.8.3 requests 2.26.0 requests-oauthlib 1.3.1 retry-decorator 1.1.1 rope 0.19.0 rsa 4.7.2 Rtree 0.9.7 ruamel-yaml-conda 0.15.100 sacrebleu 2.2.0 sacremoses 0.0.49 scikit-image 0.18.3 scikit-learn 0.24.2 scikit-learn-intelex 2021.20210714.170444 scipy 1.7.1 seaborn 0.11.2 SecretStorage 3.3.1 Send2Trash 1.8.0 sentry-sdk 1.5.9 setproctitle 1.2.2 setuptools 58.0.4 shortuuid 1.0.8 simplegeneric 0.8.1 singledispatch 3.7.0 sip 4.19.13 six 1.16.0 sklearn 0.0 smmap 5.0.0 sniffio 1.2.0 snowballstemmer 2.1.0 sorcery 0.2.2 sortedcollections 2.1.0 sortedcontainers 2.4.0 soupsieve 2.2.1 Sphinx 4.2.0 sphinxcontrib-applehelp 1.0.2 sphinxcontrib-devhelp 1.0.2 sphinxcontrib-htmlhelp 2.0.0 sphinxcontrib-jsmath 1.0.1 sphinxcontrib-qthelp 1.0.3 sphinxcontrib-serializinghtml 1.1.5 sphinxcontrib-websupport 1.2.4 spyder 5.1.5 spyder-kernels 2.1.3 SQLAlchemy 1.4.22 statsmodels 0.12.2 subprocess32 3.5.4 sympy 1.9 tables 3.6.1 TBB 0.2 tblib 1.7.0 tensorboard 2.10.1 tensorboard-data-server 0.6.1 tensorboard-plugin-wit 1.8.1 tensorflow-estimator 2.10.0 tensorflow-gpu 2.10.1 tensorflow-io-gcs-filesystem 0.27.0 termcolor 2.0.1 terminado 0.9.4 testpath 0.5.0 text-unidecode 1.3 textdistance 4.2.1 tfrecord 1.14.1 threadpoolctl 2.2.0 three-merge 0.1.1 tifffile 2021.7.2 timm 0.6.11 tinycss 0.4 tokenizers 0.11.6 toml 0.10.2 toolz 0.11.1 torch 1.9.1+cu111 torchaudio 0.9.1 torchmeta 1.8.0 torchtext 0.10.1 torchvision 0.10.1+cu111 tornado 6.1 tqdm 4.62.3 traitlets 5.1.0 transformers 4.18.0 typed-ast 1.4.3 typing-extensions 3.10.0.2 ujson 4.0.2 ultimate-anatome 0.1.1 ultimate-aws-cv-task2vec 0.0.1 unicodecsv 0.14.1 Unidecode 1.2.0 urllib3 1.26.7 wandb 0.13.5 watchdog 2.1.3 wcwidth 0.2.5 webencodings 0.5.1 Werkzeug 2.0.2 wheel 0.37.0 whichcraft 0.6.1 widgetsnbextension 3.5.1 wrapt 1.12.1 wurlitzer 2.1.1 xlrd 2.0.1 XlsxWriter 3.0.1 xlwt 1.3.0 yapf 0.31.0 yarl 1.7.2 zict 2.0.0 zipp 3.6.0 zope.event 4.5.0 zope.interface 5.4.0 WARNING: You are using pip version 22.2.2; however, version 22.3.1 is available. You should consider upgrading via the '/home/pzy2/miniconda3/envs/metalearning3.9/bin/python -m pip install --upgrade pip' command. (metalearning3.9) [pzy2@vision-submit ~]$ </code></pre> <hr /> <p>I asked a related question because I can't install pytorch with cuda with conda, see details here: <a href="https://stackoverflow.com/questions/75023120/why-does-conda-install-the-pytorch-cpu-version-despite-me-putting-explicitly-to">why does conda install the pytorch CPU version despite me putting explicitly to download the cuda toolkit version?</a></p> <hr /> <p>I think this works:</p> <pre><code># -- Install PyTorch sometimes requires more careful versioning due to cuda, ref: official install instruction https://pytorch.org/get-started/previous-versions/ # you need python 3.9 for torch version 1.9.1 to work, due to torchmeta==1.8.0 requirement if ! python -V 2&gt;&amp;1 | grep -q 'Python 3\.9'; then echo &quot;Error: Python 3.9 is required!&quot; exit 1 fi pip install torch==1.9.1+cu111 torchvision==0.10.1+cu111 torchaudio==0.9.1 -f https://download.pytorch.org/whl/torch_stable.html </code></pre>
<python><pytorch><anaconda><conda>
2023-01-05 19:00:45
2
6,126
Charlie Parker
75,023,208
6,871,867
In a boolean matrix, what is the best way to make every value adjacent to True/1 to True?
<p>I have a numpy boolean 2d array with True/False. I want to make every adjacent cell of a True value to be True. What's the best/fastest of doing that in python?</p> <p>For Eg:</p> <pre><code>#Initial Matrix 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 #After operation 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0 </code></pre>
<python><numpy>
2023-01-05 18:59:22
3
462
Gopal Chitalia
75,023,120
1,601,580
why does conda install the pytorch CPU version despite me putting explicitly to download the cuda toolkit version?
<p>I ran:</p> <pre><code>conda install -y -c pytorch -c conda-forge cudatoolkit=11.1 pytorch torchvision torchaudio </code></pre> <p>but I test if cuda is there:</p> <pre><code>(base) brando9~ $ python -c &quot;import torch; print(torch.__version__); print((torch.randn(2, 4).cuda() @ torch.randn(4, 1).cuda()))&quot; 1.13.1 Traceback (most recent call last): File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt; File &quot;/lfs/ampere4/0/brando9/miniconda/lib/python3.10/site-packages/torch/cuda/__init__.py&quot;, line 221, in _lazy_init raise AssertionError(&quot;Torch not compiled with CUDA enabled&quot;) AssertionError: Torch not compiled with CUDA enabled </code></pre> <p>which doesn't make sense given the command I ran. But if you check the conda list it installed the cpu version for some reason:</p> <pre><code>(base) brando9~ $ conda list # packages in environment at /lfs/ampere4/0/brando9/miniconda: # # Name Version Build Channel _libgcc_mutex 0.1 main _openmp_mutex 5.1 1_gnu blas 1.0 mkl brotlipy 0.7.0 py310h7f8727e_1002 bzip2 1.0.8 h7b6447c_0 ca-certificates 2022.12.7 ha878542_0 conda-forge certifi 2022.12.7 pyhd8ed1ab_0 conda-forge cffi 1.15.1 py310h5eee18b_3 charset-normalizer 2.0.4 pyhd3eb1b0_0 conda 22.11.1 py310hff52083_1 conda-forge conda-content-trust 0.1.3 py310h06a4308_0 conda-package-handling 1.9.0 py310h5eee18b_1 cryptography 38.0.1 py310h9ce1e76_0 cudatoolkit 11.1.1 ha002fc5_10 conda-forge ffmpeg 4.3 hf484d3e_0 pytorch freetype 2.10.4 h0708190_1 conda-forge giflib 5.2.1 h36c2ea0_2 conda-forge gmp 6.2.1 h58526e2_0 conda-forge gnutls 3.6.13 h85f3911_1 conda-forge idna 3.4 py310h06a4308_0 intel-openmp 2021.4.0 h06a4308_3561 jpeg 9e h166bdaf_1 conda-forge lame 3.100 h7f98852_1001 conda-forge lcms2 2.12 h3be6417_0 ld_impl_linux-64 2.38 h1181459_1 lerc 3.0 h295c915_0 libdeflate 1.8 h7f8727e_5 libffi 3.4.2 h6a678d5_6 libgcc-ng 11.2.0 h1234567_1 libgomp 11.2.0 h1234567_1 libiconv 1.17 h166bdaf_0 conda-forge libpng 1.6.37 hbc83047_0 libstdcxx-ng 11.2.0 h1234567_1 libtiff 4.4.0 hecacb30_2 libuuid 1.41.5 h5eee18b_0 libwebp 1.2.4 h11a3e52_0 libwebp-base 1.2.4 h5eee18b_0 lz4-c 1.9.3 h9c3ff4c_1 conda-forge mkl 2021.4.0 h06a4308_640 mkl-service 2.4.0 py310ha2c4b55_0 conda-forge mkl_fft 1.3.1 py310h2b4bcf5_1 conda-forge mkl_random 1.2.2 py310h00e6091_0 ncurses 6.3 h5eee18b_3 nettle 3.6 he412f7d_0 conda-forge numpy 1.23.5 py310hd5efca6_0 numpy-base 1.23.5 py310h8e6c178_0 openh264 2.1.1 h4ff587b_0 openssl 1.1.1s h7f8727e_0 pillow 9.3.0 py310hace64e9_1 pip 22.3.1 py310h06a4308_0 pluggy 1.0.0 py310h06a4308_1 pycosat 0.6.4 py310h5eee18b_0 pycparser 2.21 pyhd3eb1b0_0 pyopenssl 22.0.0 pyhd3eb1b0_0 pysocks 1.7.1 py310h06a4308_0 python 3.10.8 h7a1cb2a_1 python_abi 3.10 2_cp310 conda-forge pytorch 1.13.1 py3.10_cpu_0 pytorch pytorch-mutex 1.0 cpu pytorch readline 8.2 h5eee18b_0 requests 2.28.1 py310h06a4308_0 ruamel.yaml 0.17.21 py310h5eee18b_0 ruamel.yaml.clib 0.2.6 py310h5eee18b_1 setuptools 65.5.0 py310h06a4308_0 six 1.16.0 pyhd3eb1b0_1 sqlite 3.40.0 h5082296_0 tk 8.6.12 h1ccaba5_0 toolz 0.12.0 py310h06a4308_0 torchaudio 0.13.1 py310_cpu pytorch torchvision 0.14.1 py310_cpu pytorch tqdm 4.64.1 py310h06a4308_0 typing_extensions 4.4.0 pyha770c72_0 conda-forge tzdata 2022g h04d1e81_0 urllib3 1.26.13 py310h06a4308_0 wheel 0.37.1 pyhd3eb1b0_0 xz 5.2.8 h5eee18b_0 zlib 1.2.13 h5eee18b_0 zstd 1.5.2 ha4553b6_0 </code></pre> <p>why? What is the right way to install an exact version of pytorch using conda?</p> <hr /> <p>For completness I will print pip list but it shouldn't matter since I've not ran a pip command yet:</p> <pre><code>(base) brando9~ $ pip list Package Version ---------------------- --------- brotlipy 0.7.0 certifi 2022.12.7 cffi 1.15.1 charset-normalizer 2.0.4 conda 22.11.1 conda-content-trust 0.1.3 conda-package-handling 1.9.0 cryptography 38.0.1 idna 3.4 mkl-fft 1.3.1 mkl-random 1.2.2 mkl-service 2.4.0 numpy 1.23.5 Pillow 9.3.0 pip 22.3.1 pluggy 1.0.0 pycosat 0.6.4 pycparser 2.21 pyOpenSSL 22.0.0 PySocks 1.7.1 requests 2.28.1 ruamel.yaml 0.17.21 ruamel.yaml.clib 0.2.6 setuptools 65.5.0 six 1.16.0 toolz 0.12.0 torch 1.13.1 torchaudio 0.13.1 torchvision 0.14.1 tqdm 4.64.1 typing_extensions 4.4.0 urllib3 1.26.13 wheel 0.37.1 </code></pre>
<python><pytorch><anaconda><conda>
2023-01-05 18:51:48
3
6,126
Charlie Parker
75,023,113
7,984,318
Python how to create a new dict by add items to an old dict
<p>I have a dict:</p> <pre><code>d1 = {'name':'William'} </code></pre> <p>Now I want to build another dict that is based on d1:</p> <pre><code>d2 = {'name':'William','age':6} </code></pre> <p>Is there something like:</p> <pre><code>d2 = d1{'age':6} </code></pre> <p>Any friend can help ?</p>
<python><dictionary>
2023-01-05 18:51:13
2
4,094
William
75,023,002
13,488,334
Python - Nested Singleton Classes
<p>Is it possible to nest an arbitrary number Singleton classes within a Singleton class in Python?</p> <p>There's no problem in changing my approach to solving this issue if a simpler alternative exists. I am just using the &quot;tools in my toolset&quot;, if you will. I'm simulating some larger processes so bear with me if it seems a bit far-fetched.</p> <p>An arbitrary number of gRPC servers can be started up and each server will be listening on a different port. So for a client to communicate with these servers, separate channels and thus separate stubs will need to be created for a client to communicate to a given server.</p> <p>You could just create a new channel and a new stub every time a client needs to make a request to a server, but I am trying to incorporate some best practices and reuse the channels and stubs. My idea is to create a Singleton class that is comprised of Singleton subclasses that house a channel and stub pair as instance attributes. I would have to build the enclosing class in a way that allows me to add additional subclasses whenever needed, but I have never seen this type of thing done before.</p> <p>The advantage to this approach is that any module that instantiates the main Singleton class will have access to the existing state of the channel and stub pairs, without having to recreate anything.</p> <p>I should note that I already initialize channels and stubs from within Singleton classes and can reuse them with no problem. But the main goal here is to create a data structure that allows me to reuse/share a variable amount of gRPC channel and stub pairs.</p> <p>The following is code for reusing the gRPC Channel object; the stubs are built in a very similar way, only difference is they accept the channel as an argument.</p> <pre class="lang-py prettyprint-override"><code>class gRPCChannel(object): _instance, _channel = None, None port: int = 50051 def __new__(cls): &quot;&quot;&quot;Subsequent calls to instance() return the singleton without repeating the initialization step&quot;&quot;&quot; if cls._instance is None: cls._instance = super(gRPCChannel, cls).__new__(cls) # The following is any initialization that needs to happen for the channel object cls._channel = grpc.insecure_channel(f'localhost:{cls.port}', options=(('grpc.enable_http_proxy', 0),)) return cls._channel def __exit__(self, cls): cls._channel.close() </code></pre>
<python><design-patterns><singleton><grpc><grpc-python>
2023-01-05 18:41:31
1
394
wisenickel
75,022,952
6,054,404
Appending lines to a txt file on github through pygithub
<p>The following accesses the data from a text file on git hub.</p> <pre><code>repoName = 'repo_url' filePath = 'file.txt' from github import Github g = Github(TOKEN) repo = g.get_repo(repoName) file = repo.get_contents(filePath) data = file.decoded_content.decode(&quot;utf-8&quot;) </code></pre> <p>I want to add a new line to the <code>data</code> and push that to the file github repo.</p> <pre><code>data += &quot;\n A new line&quot; </code></pre> <p>I've been going through the api and googling, but I can't seem to find the best way to do this.</p>
<python><pygithub>
2023-01-05 18:37:13
1
1,993
Spatial Digger