eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Am studying the difference between those two languages and i was wondering why i can't access the variables in javascript classes without initiating an instance but i can do that in python here is an example of what am talking about: PYTHON CLASS  class Car: all =[] def __init__(self, name): self.name = name Car.all.append(self) def get_car_name(self): return self.name bmw = Car("BMW") mercedez = Car("MERCEDEZ") print(Car.all)  Running this code returns a list of all cars (which are the instance that i have created) [<main.Car object at 0x0000022D667664E0>, <main.Car object at 0x0000022D66766510>] JAVASCRIPT Class  class Car { all = []; constructor(name, miles) { this.name = name; this.miles = miles; this.all.push(this); } } let ford = new Car("ford", 324); let tesla = new Car("tesla", 3433); console.log(Car.all);  if i used this code the console.log will return undefined in javascript if i want to get the value of all i have to use an instance like this console.log(ford.all); this will return only the instance of ford that was created [ Car { all: [Circular *1], name: 'ford', miles: 324 } ] but otherwise in python this if i printed out an instance all it will return this print(bmw.all) [<__main__.Car object at 0x00000199CAF764E0>, <__main__.Car object at 0x00000199CAF76510>] it returns the two instance that is created even if i called the all of one instance

Answer: You need to declare it static, otherwise it's an instance property:   class Car { static all = []; constructor(name, miles) { this.name = name; this.miles = miles; Car.all.push(this); } } let ford = new Car("ford", 324); let tesla = new Car("tesla", 3433); console.log(Car.all);    In Python variables declared outside methods are static (no static keyword is needed).
Question: I'm trying to convert a str column from str to float (it's intended to be a float). However, the string have commas and dots and I'm not being able to correctly replace the values: import polars as pl df = pl.DataFrame({"numbers": ["1.004,00", "2.005,00", "3.006,00"]}) df = df.with_column( df["numbers"].str.replace(".", "").str.replace(",", ".").cast(pl.Float64) ) print(df)  I'm getting:  ComputeError: conversion from str to f64 failed in column 'numbers' for 3 out of 3 values: [".004.00", ".005.00", ".006.00"]  I Also tried just removing the "." with nothing using: df = df.with_columns(df["numbers"].str.replace(".", "")) print(df)  But I'm getting the values without the first number.

Answer: str.replace uses regular expressions, so the dot matches the first character. Just escape it: import polars as pl df = pl.DataFrame({ "numbers": ["1.004,00", "2.005,00", "3.006,00"] }) df = ( df .with_columns( pl.col('numbers').str.replace("\.", "").str.replace(",", ".").cast(pl.Float64) ) ) print(df)  Output: shape: (3, 1) ┌─────────┐ │ numbers │ │ --- │ │ f64 │ ╞═════════╡ │ 1004.0 │ │ 2005.0 │ │ 3006.0 │ └─────────┘
Question: I have an array x and the result of argsorting it i. I need to sort x (and y, irrelevant here) according to i hundreds of times. It is therefore not doable to sort the data twice, everything needs to be achieved via the initial sorting i. If I take x[i] it returns the sorted x as expected. However, I now only want to use certain rows of x via n. So x[n] returns the values of x as expected. My problem is that I need to sort these x[n] via i (and will have to do the same for y[n]. # Example data x = np.array([14, 15, 9, 6, 19, 18, 4, 11, 10, 0]) i = np.argsort(x) n = np.array([2, 5, 7, 8]) #x[n] -> array([ 9, 18, 11, 10])  Desired output: index_sort(x, n, i) = array([ 9, 10, 11, 18]) Some simple (failed) attempts: x[n][i] -> Indexing error, as x is now too small.  x[i[n]] -> array([ 6, 11, 15, 18]), Is sorted, but contains the wrong data  x[i][n] -> Same For more context: I'm creating a specific type of decision tree model. For each layer of the tree I need the above operation a different n. Sorting becomes prohibitively expensive and even checking for set membership via np.isin might be too slow as well already. My intuition (though perhaps wrong) says it should be possible to achieve this via indexing only, without ever having to sort or check for set membership. For all these layers x and i remain the same, but a different n is used each time.

Answer: In [263]: x = np.array([14, 15, 9, 6, 19, 18, 4, 11, 10, 0]) ...: i = np.argsort(x) ...: n = np.array([2, 5, 7, 8])  i and n do different, and unrelated indexing operations. Both make copies (not views), which don't retain any information on the original x: In [264]: x[i] Out[264]: array([ 0, 4, 6, 9, 10, 11, 14, 15, 18, 19]) In [265]: x[n] Out[265]: array([ 9, 18, 11, 10])  Let's try working with a boolean mask: In [266]: m = np.zeros_like(x, dtype=bool) In [267]: m[n] = True; m Out[267]: array([False, False, True, False, False, True, False, True, True, False])  It selects elements from x same as n (though it won't handle duplicates the same): In [268]: x[m] Out[268]: array([ 9, 18, 11, 10])  Now try applying the sort to m: In [269]: mi = m[i]; m Out[269]: array([False, False, True, False, False, True, False, True, True, False])  It does select the desired elements from the sorted x[i]: In [270]: x[i][mi] Out[270]: array([ 9, 10, 11, 18])  We could also convert that boolean mask back to indices: In [272]: ni = np.nonzero(mi)[0]; ni Out[272]: array([3, 4, 5, 8], dtype=int64) In [273]: x[i][ni] Out[273]: array([ 9, 10, 11, 18])
Question: I am using Plotly package for my visualizations. This MWE creates a 10x10 matrix and plots it in a Heatmap. import numpy as np import pandas as pd import plotly.graph_objects as go vals = np.random.rand(10,10)*5 vals = np.around(vals) tick_text = ['A','B','C','D','E'] df = pd.DataFrame(vals) fig = go.Figure(go.Heatmap( z=df.values, x = df.index, y = df.columns )) fig.update_layout( height=500, width=500 ) fig.update_layout( coloraxis_colorbar=dict( tickmode = 'array', tickvals = [i for i in range(5)], ticktext = tick_text, ) ) fig.show()  This is the output  I am trying to change the text displayed next to the colorbar. In this case I want to see A,B,C,D,E instead of 1,2,3,4,5. I followed the documentation and as far as i understood i have to change coloraxis_colorbar but this doesn't seem to work.

Answer: You also need to specify the coloraxis the trace should refer to when building the heatmap.  coloraxis - Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under layout.coloraxis, layout.coloraxis2, etc.  Just add this line, and your code should work as expected : fig = go.Figure(go.Heatmap( z=df.values, x = df.index, y = df.columns, coloraxis='coloraxis' # <- here ))
Question: I want to verify Foo() calls Bar() without actually calling Bar(). And then I want to verify that obj is assigned with whatever Bar() returns. I tried the following: class Bar: def __init__(self, a): print(a) class Foo: def __init__(self): self.obj = Bar(1) ### import pytest from unittest.mock import Mock, patch from mod import Foo, Bar @pytest.fixture # With stdlib def mock_bar(): with patch('mod.Bar') as mock: yield mock def test_foo(mock_bar): result = Foo() mock_bar.assert_called_once_with(1) assert result.obj == mock_bar  But it would fail and say that: E AssertionError: assert <MagicMock na...='5265642864'> == <MagicMock na...='5265421696'> E Full diff: E - <MagicMock name='Bar' id='5265421696'> E ? ^ ^^ E + <MagicMock name='Bar()' id='5265642864'> E ? ++ + ^ ^ 

Answer: This line: assert result.obj == mock_bar  Should be: assert result.obj == mock_bar.return_value  It is the result of calling Bar which gets assigned in self.obj = Bar(1), not Bar itself.
Question: I've tried the code bellow, using new_callable=PropertyMock to mock a property call, and autospec=True to be able to access self in the side effect function: from unittest.mock import PropertyMock def some_property_mock(self): if self.__some_member == "some_value" return "some_different_value" else: return "some_other_value" mocker.patch.object( SomeClass, "some_property", new_callable=PropertyMock, autospec=True, side_effect=some_property_mock)  It throws the following exception: ValueError: Cannot use 'autospec' and 'new_callable' together Is there any alternative to achieve the expected behavior? Edit: I have tried the solution provided in this post https://stackoverflow.com/a/77940234/7217960 but it doesn't seem to work with PropertyMock. Printing result gives MyMock name='my_property()' id='136687332325264' instead of 2 as expected. from unittest import mock class MyClass(object): def __int__(self): self.my_attribute = 10 @property def my_property(self): return self.my_attribute + 1 def unit_under_test(): inst = MyClass() return inst.my_property class MyMock(mock.PropertyMock): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print("MyMock __init__ called.") with mock.patch.object(mock, 'MagicMock', MyMock): with mock.patch.object(MyClass, 'my_property', autospec=True, side_effect=lambda self: 2) as spy: result = unit_under_test() assert result == 2 assert spy.call_count == 1 

Answer: Since the property some_property is patched with MagicMock, which is then patched with MyMock, and you want to set the return value of the property callable when it's called, you should do so on the mock object returned from patching MagicMock with MyMock instead: with mock.patch.object(mock, 'MagicMock', MyMock) as property_mock: with mock.patch.object(MyClass, 'my_property', autospec=True) as spy: property_mock.side_effect = lambda self: 2 # or property_mock.return_value = 2 result = unit_under_test() assert result == 2 assert spy.call_count == 1  Demo: https://ideone.com/rKo8mO
Question: I have a program where I want to use the colorchooser dialog from tkinter. My problem is that the color chooser dialog is always opening on the top left of the root window. For example with the following code I get it as shown in the picture. import tkinter as tk from tkinter import ttk from tkinter.colorchooser import askcolor class App(): def __init__(self, master): self.master = master self.master.geometry('400x200') self.button = ttk.Button(self.master, text='Select a Color', command=self.change_color) self.button.pack(expand=True) def change_color(self): colors = askcolor(title="Tkinter Color Chooser") root.configure(bg=colors[1]) root = tk.Tk() app = App(root) app.master.mainloop()   Is there a possibility to adjust the initial location of the dialog? For example that it is always orientated relatively to the button which opens the dialog?

Answer: It seems it must be at this position relative to parent. So a working trick with a fake hidden parent : import tkinter as tk from tkinter import ttk from tkinter.colorchooser import askcolor class App: def __init__(self, master): self.master = master self.master.geometry('400x200') self.button = ttk.Button(self.master, text='Select a Color', command=self.change_color) self.button.pack(expand=True) self.toplevel = tk.Toplevel(self.master) self.toplevel.withdraw() def change_color(self): x, y = self.button.winfo_rootx(), self.button.winfo_rooty() self.toplevel.geometry(f'+{x}+{y}') colors = askcolor(title="Tkinter Color Chooser", parent=self.toplevel) root.configure(bg=colors[1]) root = tk.Tk() app = App(root) app.master.mainloop()
Question: I am creating small GUI system and I would like to get an image in the form of raw bytes from Python code and then create QImage/QIcon using those raw bytes. For C++/Python interaction I am using Boost Python. On Python code side I printed the raw bytes: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00@\x00\x00\x00@\x08\x02\x00\x00\x00%\x0b\xe6\x89\x00\x00\x00\x03sBIT\x08\x08\x08\xdb\xe1O\xe0\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x06\xabIDATh\x81\xed\x9aOh\x13O\x14\xc7wv\x93\xdd\xfcQ1\xa9\x8d.... I send them as string from python to the C++ code like: data.rawBytes = str(thumbnail._raw_bytes)  On C++ side, I extract these bytes in the form of string as: std::string rawBytes = boost::python::extract<std::string>(obj.attr("rawBytes"));  The above rawBytes received on C++ side is same as the python print above. Now in the UI code, I try to use these raw bytes to create QIcon like: std::string rawbytes = data.rawBytes; QByteArray arr(); arr.append(rawbytes.c_str(), rawbytes.length()); bool flag = pixmap.loadFromData(arr, "PNG"); QStandardItem* item = new QStandardItem(name); item->setIcon(QIcon(pixmap));  The icon doesn't get displayed in the UI and moreover, the 'flag' returned from pixmap.loadFromData is false which means there is some problem in conversion of the raw bytes. Can someone point out if there needs to be some kind of conversion from python to c++ code to properly render this image on the UI?

Answer: Assuming on the Python side you have data.rawBytes = thumbnail._raw_bytes  without the str wrapper, and a C++ variable obj referring to data, you can use the Python Buffer protocol like so: Py_Buffer view = {0}; int ret = PyObject_GetBuffer(obj.attr("rawBytes").ptr(), &view, PyBUF_SIMPLE); if (ret == -1) { // handle error } QByteArray arr = QByteArray::fromRawData(reinterpret_cast<const char *>(view.buf), view.len); bool flag = pixmap.loadFromData(arr, "PNG"); PyObject_ReleaseBuffer(&view);  You can of course skip the copying to a QByteArray and read directly from Python buffer: pixmap.loadFromData(reinterpret_cast<uchar *>(view.buf), view.len, "PNG"));
Question: I have this simple MWE: from numba import njit @njit def add(a, b): return a + b # Now let's inspect the assembly code for the 'add()' function. for k, v in add.inspect_asm().items(): print(k)  when I run it I get no output. What is the right way to inspect the assembly?

Answer: You need to first compile the function to populate .inspect_asm(), either by calling it or by specifying the signature. E.g.: from numba import njit @njit def add(a, b): return a + b # first call add() to compile it add(1, 2) print(add.inspect_asm())  Prints: {(int64, int64): '\t.text\n\t.file\t"<string>"\n\t.globl\t_ZN8__main__3addB2v1B38c8tJTIcFKzyF2ILShI4CrgQElQb6HczSBAA_3dExx\n\t.p2align\t4, ...   OR: from numba import njit # specify the signature first: @njit("int64(int64, int64)") def add(a, b): return a + b print(add.inspect_asm())
Question: I have Clocking table in database. I wanted to count the users' time spent per day. For example 2024-03-21, user 1 spend 6.8 hours, the next day he spends n number of hours and so on (['6.8', 'n', ... 'n'])    user date timein timeout     1 2024-03-21 10:42 AM 12:00 PM   1 2024-03-21 01:10 PM 06:00 PM   1 2024-03-22 01:00 PM 05:47 PM   ... ... ... ...    This is my models.py class Clocking(models.Model): user = models.ForeignKey('User', models.DO_NOTHING) timein = models.CharField(max_length=15, blank=True, null=True) timeout = models.CharField(max_length=15, blank=True, null=True) date = models.DateField(null=False)  I wanted to get the list of hours spent per day, which would be really useful for me in plotting charts.

Answer: Please don't use a CharField to keep track. Imagine that a person enters now, then how will that work? It means you make the number of possible values a lot larger, and also increases disk space usage, altough that last one is probably not that much of an issue. There are essentially two options: working with TimeFields: from django.conf import settings class Clocking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING) date = models.DateField() timein = models.TimeField() timeout = models.TimeField(null=True) or work with two DateTimeFields: from django.conf import settings class Clocking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING) timein = models.DateTimeField() timeout = models.DateTimeField(null=True) The second has three advantages: (1) it will also easily register time correctly on dates where the daylight saving time changes. Although these typically change on a sunday around 2:00 AM so to minimize the amount of problematic bookkeeping, it is still possible that this might happen, for example if the person is working in a different timezone at that time; (2) it also allows to have multiple Clockings on the same date easily, without extra bookkeeping; and (3) finally it also means we can have a Clocking that runs over midnight. Indeed, imagine a person clocking in at 9:00 PM and clocking out at 01:00 AM the next day, then with the old model this will be problematic, it would require first checking if the end time is earlier than the begin time. With this we can generate statistics for the date when the item started with: # second model from django.db.models import F, Sum from django.db.models.functions import TruncDate Clocking.objects.filter(timeout__isnull=False).values( date=TruncDate('timein') ).annotate(total=Sum(F('timeout') - F('timein'))).order_by('date')   Note: Specifying null=False [Django-doc] is not necessary: fields are by default not NULLable.    Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Question: I have a sorted dataframe with a column that represents a group. How do I filter it to remove all the alternate rows by the group. The dataframe length is guaranteed to be an even number if it matters. Sample Input: ┌───────────┬───────────┐ │ group_col ┆ value_col │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════════╪═══════════╡ │ 1 ┆ 10 │ │ 1 ┆ 20 │ │ 1 ┆ 30 │ │ 1 ┆ 40 │ │ 2 ┆ 50 │ │ 2 ┆ 60 │ │ 3 ┆ 70 │ │ 3 ┆ 80 │ └───────────┴───────────┘ Output: ┌───────────┬───────────┐ │ group_col ┆ value_col │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════════╪═══════════╡ │ 1 ┆ 10 │ │ 1 ┆ 30 │ │ 2 ┆ 50 │ │ 3 ┆ 70 │ └───────────┴───────────┘ df = pl.DataFrame({ 'group_col': [1, 1, 1, 1, 2, 2, 3, 3], 'value_col': [10, 20, 30, 40, 50, 60, 70, 80] })  So i would like to retain the odd number rows for every group_col. Polars version is 0.19.

Answer: .gather_every() exists. In order to use it with .over() - you can change the default mapping_strategy= to explode df.select( pl.all().gather_every(2).over("group_col", mapping_strategy="explode") )  shape: (4, 2) ┌───────────┬───────────┐ │ group_col ┆ value_col │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════════╪═══════════╡ │ 1 ┆ 10 │ │ 1 ┆ 30 │ │ 2 ┆ 50 │ │ 3 ┆ 70 │ └───────────┴───────────┘  It's essentially the same as: (df.group_by("group_col", maintain_order=True) .agg(pl.all().gather_every(2)) .explode(pl.exclude("group_col")) )  For the simplified case, i.e. a guaranteed even number of group rows - you could use the frame-level method. df.gather_every(2)  shape: (4, 2) ┌───────────┬───────────┐ │ group_col ┆ value_col │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════════╪═══════════╡ │ 1 ┆ 10 │ │ 1 ┆ 30 │ │ 2 ┆ 50 │ │ 3 ┆ 70 │ └───────────┴───────────┘
Question: Once I get some 3-D point coordinates, what algorithm do I use to fit an optimal cylindrical and get the direction vector and radius of the central axis？  My previous idea was to divide a cylinder into layers, and as the number of layers increased, the figure formed by the dots got closer to the cylinder, but in this case I couldn't get an exact radius of the cylinder. (The central axis is obtained by fitting the center of the circle through each layer)

Answer: Here is a MCVE to regress axis defined by p0 and p1 (vectors) and radius R (scalar). First we create some dummy dataset: import numpy as np import matplotlib.pyplot as plt from scipy import optimize from scipy.spatial.transform import Rotation def cylinder(n=60, m=20, r=2, h=5): t = np.linspace(0, m * 2 * np.pi, m * n) z = np.linspace(0, h, m * n) x = r * np.cos(t) y = r * np.sin(t) return np.stack([x, y, z]).T X = cylinder() rot = Rotation.from_rotvec(np.array([-1, 2, 0.5])) x0 = np.array([1., 2., 0.]) X = rot.apply(X) X = X + x0  Which create a generic use case including origin shift. Now it is sufficient to write down the geometric equation (see equation 10) as residuals and minimize it by least squares. def residuals(p, xyz): return np.power(np.linalg.norm(np.cross((xyz - p[0:3]), (xyz - p[3:6])), axis=1) / np.linalg.norm((p[3:6] - p[0:3])), 2) - p[6] ** 2 p, res = optimize.leastsq(residuals, x0=[0., 0., 0., 1., 1., 1., 0.], args=(X,), full_output=False)  Which in this case returns: # array([ -1.8283916 , -1.65918186, 3.29901757, # p0 # 20.31455462, 26.98786514, -22.52837088, # p1 # 2. ]) # R  Graphically it leads to:
Question: I'm trying to display a two dimensional function on a hexagonal grid with pyplot.hexbin but it only produces a line and ignores the rest of the function. How do I solve this? def func(x,y): return x*2+y*2 x = np.linspace((-0.5)/4*5, (0.5)/4*5, int(2e3)) y = np.linspace(-0.5, 0.5, int(2e3)) plt.hexbin(x, y, func(x,y), gridsize=(8,4), cmap='gnuplot') plt.show()  enter image description here

Answer: The func(x,y) function returns a scalar value for each (x, y) pair, but hexbin expects x and y to be arrays of the same length representing coordinates. Input another array Z with the scalar values which will be the colours of each hex. Try: import numpy as np import matplotlib.pyplot as plt def func(x,y): return x*2+y*2 x = np.linspace((-0.5) / 4 * 5, (0.5) / 4 * 5, int(2e3)) y = np.linspace(-0.5, 0.5, int(2e3)) X, Y = np.meshgrid(x, y) # Evaluate the function for each combination of x and y Z = func(X, Y) plt.hexbin(X.flatten(), # Flatten X and Y to 1D arrays Y.flatten(), C=Z.flatten(), # Flatten Z to 1D array for color values gridsize=(8, 4), cmap='gnuplot') plt.show()  You can also add a colorbar before the show like: plt.colorbar(label='Function Value')
Question: Suppose I have a list of list of numbers that happen to be encoded as strings. import pandas as pd pylist = [['1', '43'], ['2', '42'], ['3', '41'], ['4', '40'], ['5', '39']]  Now I want a dataframe where these numbers are integers. I can see from pandas documentation that I can force a data type via dtype, but when I run the following: pyframe_1 = pd.DataFrame(pylist,dtype=int)  I get the following warning: FutureWarning: Could not cast to int32, falling back to object. This behavior is deprecated. In a future version, when a dtype is passed to 'DataFrame', either all columns will be cast to that dtype, or a TypeError will be raised.  and by inspection via dtypes: pytypes_1 = pyframe_1.dtypes.to_list() # dtype[object_] of numpy module my columns are np.object types. But I can cast my columns to integer via two ways: First one is column by column: pyframe_2 = pd.DataFrame(pylist) pyframe_2[0] = pyframe_2[0].astype(int) pyframe_2[1] = pyframe_1[1].astype(int)  Second one is on the entire dataframe in an one-liner: pyframe_3 = pd.DataFrame(pylist).astype(int)  Both give me a dataframe of integer columns from a list of list of strings. My question is why does the first case, where I explicitly use dtype when creating a dataframe raise a warning (or error) with no conversion for the types? Why even have it as an option in the first place? EDIT: Pandas version I'm running is 1.4.1. EDIT: As per suggestions of @mozway one workaround is using pyframe_1 = pd.DataFrame(pylist,dtype='Int32') Which does convert to integer. I mean, to me it's kinda unnatural using a string (which Int32 is) to force a cast instead of using much more intuitive int. Inspecting dtypes from the method, I get different integer types. Casting with dtype='Int32' at instantiation level gets me Int32Dtype object of pandas.core.arrays.integer module. (Upon closer inspection it has an attribute of numpy_dtype which is dtype[int32] object of numpy module). Casting with .astype(int) gives me dtype[int32] object of numpy module. So there's not much difference, I guess? IDK.

Answer: I would consider it a bug. During instantiation, the input goes though several checks (_homogenize / sanitize_array / _try_cast). I believe an intermediate float dtype is created which triggers the error (on pandas 2.2): ValueError: Trying to coerce float values to integers  A workaround would be to use: pd.DataFrame(pylist, dtype='Int32') 0 1 0 1 43 1 2 42 2 3 41 3 4 40 4 5 39