eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I see lots of errors and suggestions about Parent module '' not loaded, ... I don't see any about specifically "out of the box" django 3.5. $ mkvirtualenv foobar -p /usr/bin/python3 Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /home/isaac/.virtualenvs/foobar/bin/python3 Also creating executable in /home/isaac/.virtualenvs/foobar/bin/python Installing setuptools, pkg_resources, pip, wheel...done. [foobar] $ pip install django Collecting django Using cached Django-2.2.15-py3-none-any.whl (7.5 MB) Collecting pytz Using cached pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Installing collected packages: pytz, sqlparse, django Successfully installed django-2.2.15 pytz-2020.1 sqlparse-0.3.1 [foobar] $ python Python 3.5.3 (default, Jul 9 2020, 13:00:10) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 666, in _load_unlocked File "<frozen importlib._bootstrap>", line 577, in module_from_spec File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module return importlib.import_module('._distutils', 'setuptools') File "/home/isaac/.virtualenvs/foobar/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 981, in _gcd_import File "<frozen importlib._bootstrap>", line 931, in _sanity_check SystemError: Parent module 'setuptools' not loaded, cannot perform relative import  As you can see, I installed django using python3.5. It seems to work fine with python2.7... Is anyone else aware of a way around this bug, or something silly I did in my environment? I am using debian stretch instead of buster, but I'm not sure if I'm ready to upgrade yet.

Answer: Something happened in version 50 of setuptools. We could "solve" this problem by downgrading setuptools to 49.3.0 (and maybe pip to 20.2.1) pip install setuptools==49.3.0 and pip install pip==20.2.1 Be aware though that this should only be a temporary solution!
Question: Here I print UTC time zone's current datetime. I want current GMT time zone's datetime by this method. How can I?  import datetime dt_utcnow = datetime.datetime.utcnow() print(dt_utcnow)  Output  2020-08-31 09:06:26.661323 

Answer: You can use the gmtime() of time module to achieve this: from datetime import datetime from time import gmtime, strftime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) print("Your Time Zone is GMT", strftime("%z", gmtime()))
Question: I have made the following graph using matplotlib in python.I have also attached the code I used to make this. The code for the arena import matplotlib.pyplot as plt import matplotlib.patches as patches obs_boundary = [ [0, 0, 10, 600], [0, 600, 900, 10], [10, 0, 900, 10], [900, 10, 10, 600] ] obs_cir_own = [ [50,500,10], [100,300,10], [240,240,10], [300,400,10], [190,50,10] ] obs_cir_opp = [ [700, 420, 10], [460, 200, 10], [550, 500, 10], [670, 70, 10], [800, 230, 10], [600,300,10] ] fig, ax = plt.subplots() for (ox, oy, w, h) in obs_boundary: print(ox, oy, w, h) ax.add_patch( patches.Rectangle( (ox, oy), w, h, edgecolor='black', facecolor='black', fill=True ) ) for (ox, oy,r) in obs_cir_own: ax.add_patch( patches.Circle( (ox, oy), r, edgecolor='black', facecolor='green', fill=True ) ) for (ox, oy, r) in obs_cir_opp: ax.add_patch( patches.Circle( (ox, oy), r, edgecolor='black', facecolor='red', fill=True ) ) plt.plot(50,50, "bs", linewidth=30) plt.plot(870, 550, "ys", linewidth=30) name='arena' plt.title(name) plt.axis("equal")  So, I want to implement a similar arena using C++ and I have no idea how to do it? I researched I got to know something about qtplot again I dont know much about qt. So, is qtplot the only way or there are some easier way. Please tell me how to implement this in C++.

Answer: You could try https://github.com/lava/matplotlib-cpp, which looks like it is just a wrapper around matplotlib anyway, so you are still calling/using Python and matplotlib in the end. With this you probably can copy your code nearly verbatim to "C++".
Question: I was reading the python docs and stumbled upon the following lines:  It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class.  Please, someone explain what does that mean in plain english. I'm going to introduce some shorthand notation: let 'user-defined functions' be denoted by f, let 'class instance' be denoted by ci while class denoted simply by c. Obviously(?), ci = c(), with some abuse of notation. Also, allow membership statements to be recast in simple set notation eg 'user-defined functions which are attributes of a class instance' in shorthand is 'vf: fεa(ci)', where v: 'for all' and where 'a' is the shorthand for (set of) attributes (eg of a class or class instance) and 'ε' denotes the set membership function. Also, the process of binding a function is described in shorthand by ci.f(*args) or c.f(*args) => f(ci, *args) or f(c, *args) (the former referring to an instance method call while the later referring to a class method call) Using the newly introduced shorthand notation, does the quote from the docs imply that vf: fεa(c), c.f(*args) => f(c, *args) is a true statement while vf: fεa(ci), ci.f(*args) => f(ci, *args) is false?

Answer: Setting a User Defined Method to be an Attribute of Class, The Wrong Way Consider the following example class A and function f:  class A: pass def f(self): print("I\'m in user-defined function") a = A()  The function f is defined separately and not inside the class. Let's say you want to add function f to be an instance method for a object. Adding it, by setting f as a attribute, won't work: import types class A: pass def f(self): print("I\'m in user-defined function") a = A() a.f = f # <function f at 0x000002D81F0DED30> print(a.f) # TypeError: f() missing 1 required positional argument: 'self' # a.f()  Because function f is not bound to the object a. That is why when calling a.f() it shall raise an error regarding the missing argument (if f has been bounded to a, that object a was the missing argument self). This part is what the docs referred at:  It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods.  Of course, all this has not to happen if function f has been defined inside class A, that's what the following part from the docs states:  ...this only happens when the function is an attribute of the class.  Setting a User Defined Method to be an Attribute of Class, The Right Way To add function f to object a you should use: import types class A: pass def f(self): print("I\'m in user-defined function") a = A() a.f = types.MethodType( f, a ) # <bound method f of <__main__.A object at 0x000001EDE4768E20>> print(a.f) # Works! I'm in user-defined function a.f()  Which bounds the user-defined method f to instance a.
Question: I have that Code example: from time import sleep import asyncio class bird: def __init__(self, sleeptime=1): self.var = sleeptime def wait_meep(self): sleep(self.var) print("Meep") def do_sth(self): print("Dop Dop Do do ...") class bird_async: def __init__(self, sleeptime=1): self.var = sleeptime async def wait_meep(self): await asyncio.sleep(self.var) print("Meep") def do_sth(self): print("Dop Dop Do do ...")  As you can see, both clients are mostly identical and shall contain the same name (so that everyone knows what to expect). Now I want to be DRY and write bird_async(bird). Because every extension in bird shall be used in bird_async as well. This is possible, but my coworker says, it is not SOLID, because I have overwritten wait_meep. Now I am looking for different soultions and found abstract classes. What I don't know is, if creating an abstract class birdBase(ABC) would be SOLID as well. I would overwrite there as well, because first it was a function and then a couroutine, or am I wrong here? What could be a SOLID and DRY solution to get those both classes together, without renaming the methods?

Answer: The DRY solution is some kind of subclassing as you already did. I think a "SOLID" solution is very hard to achieve under your condition. Fact is, you have two functions wait_meep, which have actually different signature and semantics. Namely, the first one blocks for the sleep interval, which can be arbitrary long. The second one OTOH is async, i.e. needs special calling semantics and runs concurrently. A somewhat comparable case is the Queue class from the standard library. There you have get and get_nowait methods which do the same, in different ways. Second example could be __iter__ and __aiter__ methods. So I think the only "correct" solution would be renaming one of the methods. Which would have the side effect that you could write it all as one class, i.e. reduce number of moving parts.
Question: I have skimmed through the PyPy implementation details and went through the source code as well, but PyPy's execution path is still not totally clear to me.  Sometimes Bytecode is produced, sometimes it is skipped for immediate machine-code compiling (interpreter level/app level code), But I can't figure out when and where exactly is the machine code produced, to be handed to the OS for binary execution through low-level instructions (RAM/CPU). I managed to get that straight in the case of CPython, as there is a giant switch in ceval.c - that is already compiled - which interprets bytecode and runs the corresponding code (in actual C actually). Makes sense.But as far as PyPy is concerned, I did not manage to get a clear view on how this is done, specifically (I do not want to get into the various optimization details of PyPy, that's not what I am after here). I would be satisfied with an answer that points to the PYPY source code, so to avoid "hearsay" and be able to see it "with my eyes" (I spotted the JIT backends part, under /rpython, with the various CPU architectures assemblers)

Answer: Your best guide is the pypy architecture documentation, and the actual JIT documentation. What jumped out the most for me is this:  we have a tracing JIT that traces the interpreter written in RPython, rather than the user program that it interprets.  This is covered in more detail in the JIT overview. It seems to be that the "core" is this (from here):  Once the meta-interpreter has verified that it has traced a loop, it decides how to compile what it has. There is an optional optimization phase between these actions which is covered future down this page. The backend converts the trace operations into assembly for the particular machine. It then hands the compiled loop back to the frontend. The next time the loop is seen in application code, the optimized assembly can be run instead of the normal interpreter.  This paper (PDF) might also be helpful. Edit: Looking at the x86 backend rpython/jit/backend/x86/rx86.py, the backend doesn't so much as compile but spit out machine code directly. Look at the X86_64_CodeBuilder and AbstractX86CodeBuilder classes. One level higher is the Assembler386 class in rpython/jit/backend/x86/assembler.py. This assembler uses the MachineCodeBlockWrapper from rpython/jit/backend/x86/codebuf.py which is based on the X86_64_CodeBuilder for x86-64.
Question: I have a dataframe with blank spaces as missing values, so I have replaced them with NaN values by using a regex. The problem that I have is when I want to use ordinal encoding for replacing categorical values. My code so far is the following:  x=pd.DataFrame(np.array([30,"lawyer","France", 25,"clerk","Italy", 22," ","Germany", 40,"salesman","EEUU", 34,"lawyer"," ", 50,"salesman","France"] ).reshape(6,3)) x.columns=["age","job","country"] x = x.replace(r'^\s*$', np.nan, regex=True) oe=preprocessing.OrdinalEncoder() df.job=oe.fit_transform(df["job"].values.reshape(-1,1))  I got the following error: Input contains NaN  I would like that the job column gets replaced with numbers such as: [1,2,-1,3,1,3].

Answer: You can try with factorize, notice here is category start with 0 x.job.mask(x.job==' ').factorize()[0] Out[210]: array([ 0, 1, -1, 2, 0, 2], dtype=int32)
Question: When I try to import plotly.express I get the error: ImportError: Plotly express requires pandas to be installed.  The installation notes did not mention having to install anything additional. I can import plotly on its own, I only get the error when importing plotly.express. Any ideas on how to fix this?

Answer: Pandas is a dependency that is only used in plotly.express not in plotly. For more you can visit this issue.So you need to install pandas using pip install pandas or conda install -c anaconda pandas
Question: I am following a tutorial and I don't know why I got this error:  <ipython-input-61-d59f7a5a07ab> in extract_featuresets(ticker) 2 tickers, df = process_data_for_labels(ticker) 3 df['{}_target'.format(ticker)] = list(map(buy_sell_hold, ----> 4 df['{}_{}1d'.format(ticker)], 5 df['{}_{}2d'.format(ticker)], 6 df['{}_{}3d'.format(ticker)], IndexError: Replacement index 1 out of range for positional args tuple  Here is my code: tickers, df = process_data_for_labels(ticker) df['{}_target'.format(ticker)] = list(map(buy_sell_hold, df['{}_{}1d'.format(ticker)], df['{}_{}2d'.format(ticker)], df['{}_{}3d'.format(ticker)], df['{}_{}4d'.format(ticker)], df['{}_{}5d'.format(ticker)], df['{}_{}6d'.format(ticker)], df['{}_{}7d'.format(ticker)],))  Here is the link to the tutorial: https://www.youtube.com/watch?v=zPp80YM2v7k

Answer: Your format string need two arguments in format while you are only passing in one ticker as argument. If ticker is a two element list or tuple, you can do this: df['{}_{}1d'.format(*ticker)]  Otherwise remove one curly brackets: df['{}_1d'.format(ticker)]
Question: I made a simple histogram using the following code: a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e'] pd.Series(a).value_counts().plot('bar')   Although this is a concise way to plot frequency histogram, I am not sure how to customize the plot i.e. :  Add Title Add Axis Labels Sort values on x-axis 

Answer: Series.plot (or DataFrame.plot) returns a matplotlib axis object which exposes several methods. For example: a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e'] ax = pd.Series(a).value_counts().sort_index().plot('bar') ax.set_title("my title") ax.set_xlabel("my x-label") ax.set_ylabel("my y-label")   n.b.: pandas uses matplotlib as a dependency here, and is exposing matplotlib objects and api. You can get the same result via import matplotlib.pyplot as plt; ax = plt.subplots(1,1,1). If you ever create more than one plot at a time, you will find the ax.<method> far more convenient than the module level plt.title('my title'), because it defines which plot title you'd like to change and you can take advantage of autocomplete on the ax object.
Question: Is there a convenient way to merge two dataframes with respect to the distance between rows? For the following example, I want to get the color for df1 rows from the closest df2 rows. The distance should be computed as ((x1-x2)**0.5+(y1-y2)**0.5)**0.5. import pandas as pd df1 = pd.DataFrame({'x': [50,16,72,61,95,47],'y': [14,22,11,45,58,56],'size':[1,4,3,7,6,5]}) df2 = pd.DataFrame({'x': [10,21,64,31,25,55],'y': [54,76,68,24,34,19],'color':['red','green','blue','white','brown','black']}) 

Answer: Something from numpy broadcast df1['color']=df2.color.iloc[np.argmin(np.sum(np.abs(df1[['x','y']].values-df2[['x','y']].values[:,None])**0.5,2),0)].values df1 Out[79]: x y size color 0 50 14 1 black 1 16 22 4 white 2 72 11 3 black 3 61 45 7 blue 4 95 58 6 blue 5 47 56 5 red
Question: I'm writing a passion program that will determine the best poker hand given hole cards and community cards. As an ace can go both ways in a straight, I've coded this as [1, 14] for a given 5 card combination. I understand recursion but implementing it is a different story for me. I'm looking for a function that will split all aces recursively, into all possible hand combinations until all nested lists are exhausted. This should obviously work with up to 4 aces, overlooking the fact that you wouldn't care about a straight at that point in all likelihood. hand = [[1, 14], 2, 3, [1, 14], 7] desired_output = [ [1, 2, 3, 1, 7], [1, 2, 3, 14, 7], [14, 2, 3, 1, 7], [14, 2, 3, 14, 7] ]  I'm not proud of what I have so far, especially because it returns a list instead of something like a yield which would build the list I'm looking for: def split_first_ace(hand): aces = [True if isinstance(x, list) else False for x in hand] for i, x in enumerate(aces): if x: ranks_temp = hand.copy() ace = ranks_temp.pop(i) return [[ace[0]] + ranks_temp, [ace[1]] + ranks_temp]  Any help on a solution would be appreciated, mostly because it'll help me understand how to implement recursion. But I'm open to other solutions as well.

Answer: Well, there is an easier way to do this: from itertools import product product(*[i if isinstance(i, list) else [i] for i in hand])  I challenge everybody to come up with a simpler solution
Question: I am trying to plot a world map with all the countries having different risk levels (low, moderate and high). I would like to make each risk level a different color but am not sure how to change the color scheme so that each risk category has a color of my choice. The df.risk variable currently has low as 1, moderate as 2 and high as 3 so that it is a continuous variable, however I would like to use discrete,  fig = go.Figure(data=go.Choropleth( locations = df['code'], z = df['risk'], text = df['COUNTRY'], colorscale = 'Rainbow', autocolorscale=False, reversescale=True, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix = '', colorbar_title = 'Risk level', )) fig.update_layout( title_text='Risk map', geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), annotations = [dict( x=0.55, y=0.15, xref='paper', yref='paper', text='Source: <a href="www.google.com">\ Google</a>', showarrow = False )] ) fig.show()  My sample df is: {'Country': {0: 'Afghanistan', 1: 'Albania', 2: 'Algeria', 3: 'American Samoa', 4: 'Andorra'}, 'code': {0: 'AFG', 1: 'ALB', 2: 'DZA', 3: 'ASM', 4: 'AND'}, 'risk': {0: 'High', 1: 'Moderate', 2: 'High', 3: 'Low', 4: 'High'}} 

Answer: In this case I would rather use plotly.express with color=df['risk'] and then set color_discrete_map={'High':'red', 'Moderate':'Yellow','Low':'Green'}: Plot:  Complete code: import plotly.express as px import pandas as pd fig = px.choropleth(locations=df['Country'], locationmode="country names", color=df['risk'], color_discrete_map={'High':'red', 'Moderate':'Yellow', 'Low':'Green'} #scope="usa" ) fig.show()
Question: I have a dataframe which looks like this pd.DataFrame({'A': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10'], ...: 'B': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C'], ...: 'R': [9, 1, 7, 4, 3, 5, 2, 6, 8, 10]}) Out[3]: A B R 0 C1 A 9 1 C2 A 1 2 C3 A 7 3 C4 B 4 4 C5 B 3 5 C6 B 5 6 C7 B 2 7 C8 C 6 8 C9 C 8 9 C10 C 10  column R is my rank column and I want to get the top 5 ranked items (column A), however, maximum of 3 items per group in column B can be selected. I know I can do the following to select the top 5 ranked items df.sort_values('R').head(5) Out[10]: A B R 1 C2 A 1 6 C7 B 2 4 C5 B 3 3 C4 B 4 5 C6 B 5  But this selects 4 items from group B. how can i restrict it to have only a maximum of 3 items per group selected? my resulting dataframe should look like this  A B R 1 C2 A 1 6 C7 B 2 4 C5 B 3 3 C4 B 4 5 C8 C 6  Logic - item C6 is not selected as it is the 4th item of group B so the next available item to be selected is C8 which has the next best rank and does not breach the group limitation.

Answer: We can try with GroupBy.head new_df = df.sort_values('R').groupby('B', sort=False).head(3).head(5) print(new_df)    A B R 1 C2 A 1 6 C7 B 2 4 C5 B 3 3 C4 B 4 7 C8 C 6
Question: This is a Find All Numbers Disappeared in an Array problem from LeetCode:  Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6]   My code is below - I think its O(N) but interviewer disagrees def findDisappearedNumbers(self, nums: List[int]) -> List[int]: results_list=[] for i in range(1,len(nums)+1): if i not in nums: results_list.append(i) return results_list 

Answer: You can implement an algorithm where you loop through each element of the list and set each element at index i to a negative integer if the list contains the element i as one of the values,. You can then add each index i which is positive to your list of missing items. It doesn't take any additional space and uses at the most 3 for loops(not nested), which makes the complexity O(3*n), which is basically O(n). This site explains it much better and also provides the source code. edit- I have added the code in case someone wants it: #The input list and the output list input = [4, 5, 3, 3, 1, 7, 10, 4, 5, 3] missing_elements = [] #Loop through each element i and set input[i - 1] to -input[i - 1]. abs() is necessary for #this or it shows an error for i in input: if(input[abs(i) - 1] > 0): input[abs(i) - 1] = -input[abs(i) - 1] #Loop through the list again and append each positive value to output list for i in range(0, len(input)): if input[i] > 0: missing_elements.append(i + 1)
Question: I was experimenting around with dunders in python when I found something: Say I created a class: class MyInt: def __init__(self, val): self.val = val def __add__(self, other): return self.val + other a = MyInt(3)  The __add__ works perfectly fine when this is run: >>> print(a + 4) 7  However, when I ran this: >>> print(4 + a) TypeError: unsupported operand type(s) for +: 'int' and 'MyInt'  I know that the int class does not support adding with MyInt, but are there any workarounds for this?

Answer: This is what the __radd__ method is for - if your custom object is on the right side of the operator, and the left side of the operator can't handle it. Note that the left side of the operator will take precedence, if possible. >>> class MyInt: ... def __init__(self, val): ... self.val = val ... def __add__(self, other): ... return self.val + other ... def __radd__(self, other): ... return self + other ... >>> a = MyInt(3) >>> print(a + 4) 7 >>> print(4 + a) 7  The third 'hidden' method you can override, for any given operator, will be __iadd__, which corresponds to the assignment operator +=.
Question: How would I get the current timestamp in python of India? I tried time.ctime() and datetime.utcnow() also datetime.now() but they all return a different time than here it is in india. The codes above return the time that not match the current time on my computer. and the time in my computer is definitely correct.

Answer: from pytz import timezone from datetime import datetime ind_time = datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S.%f') print(ind_time) >>> "2020-08-28 11:56:37.010822"