eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I tried my attempt at finding the smallest number that is divisible by numbers from 1 to n, and now I'm looking for advice on ways to further compact/make my solution more efficient. It would be pretty cool if there was an O(1) solution too. def get_smallest_number(n): """ returns the smallest number that is divisible by numbers from 1 to n """ divisors = range(1, n+1) check_divisible = lambda x: all([x % y == 0 for y in divisors]) i = 1 while True: if check_divisible(i): return i i += 1 

Answer: Mathematically, you are computing the least common multiple of 1, 2, ..., n. lcm is easily derived from gcd, and lcm is an associative operation. reduce is useful for applying an associative operation to an interable. We can combine these ideas (as well as improvements due to Mark Dickinson and Eric Postpischil in the comments) to get a very fast solution: from math import gcd from functools import reduce def lcm(a,b): return a // gcd(a,b) * b def get_smallest_number2(n): return reduce(lcm,range(1 + n//2,n+1),1)  Some quick %timeit results in IPython: %timeit get_smallest_number2(15) 2.07 µs ± 26.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %timeit get_smallest_number(15) 443 ms ± 5.75 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)  For n = 15 it is thus over 200,000 times faster. Your function fails to produce any output long before n = 100, but get_smallest_number2(100) evaluates to 69720375229712477164533808935312303556800 almost instantly.
Question: I'm trying to draw a network diagram using Python Networkx package. I would like to vary the thickness of the edges based on the weights given to the edges. I am using the following code which draws the diagram, but I cannot get the edge to vary its thickness based on the weight. Can someone help me with this problem? Thanks in advance. df = pd.DataFrame({ 'from':['D', 'A', 'B', 'C','A'], 'to':['A', 'D', 'A', 'E','C'], 'weight':['1', '5', '8', '3','20']}) G=nx.from_pandas_edgelist(df, 'from', 'to', edge_attr='weight', create_using=nx.DiGraph() ) nx.draw_shell(G, with_labels=True, node_size=1500, node_color='skyblue', alpha=0.3, arrows=True, weight=nx.get_edge_attributes(G,'weight').values()) 

Answer: In order to set the widths for each edge, i.e with an array-like of edges, you'll have to use nx.draw_networkx_edges through the width parameter, since nx.draw only accepts a single float. And the weights can be obtaind with nx.get_edge_attributes. Also you can draw with a shell layout using nx.shell_layout and using it to position the nodes instead of nx.draw_shell: import networkx as nx from matplotlib import pyplot as plt widths = nx.get_edge_attributes(G, 'weight') nodelist = G.nodes() plt.figure(figsize=(12,8)) pos = nx.shell_layout(G) nx.draw_networkx_nodes(G,pos, nodelist=nodelist, node_size=1500, node_color='black', alpha=0.7) nx.draw_networkx_edges(G,pos, edgelist = widths.keys(), width=list(widths.values()), edge_color='lightblue', alpha=0.6) nx.draw_networkx_labels(G, pos=pos, labels=dict(zip(nodelist,nodelist)), font_color='white') plt.box(False) plt.show()
Question: When I started to use Django, I was using FBVs ( Function Based Views ) for pretty much everything including signing up for new users. But as I delved deep more into projects, I realized that Class-Based Views are usually better for large projects as they are more clean and maintainable but this is not to say that FBVs aren't. Anyway, I migrated most of my whole project's views to Class-Based Views except for one that was a little confusing, the SignUpView.

Answer: In order to make SignUpView in Django, you need to utilize CreateView and SuccessMessageMixin for creating new users as well as displaying a success message that confirms the account was created successfully. Here's the code : views.py: from .forms import UserRegisterForm from django.views.generic.edit import CreateView class SignUpView(SuccessMessageMixin, CreateView): template_name = 'users/register.html' success_url = reverse_lazy('login') form_class = UserRegisterForm success_message = "Your profile was created successfully"  and, the forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'first_name']
Question: I have two peaces of code that produce sameme result, so any could be used for answer. First: import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Bar( name='Group 1', x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4], error_y=dict(type='data', array=[1, 0.5, 1.5]), width=0.15 )) fig.add_trace(go.Bar( name='Group 2', x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3], error_y=dict(type='data', array=[0.5, 1, 2]), width=0.15 )) fig.update_layout(barmode='group') fig.show()  Second: import plotly.graph_objects as go fig = go.Figure(data=[ go.Bar( name='Group 1', x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4], error_y=dict(type='data', array=[1, 0.5, 1.5]), width=0.15), go.Bar( name='Group 2', x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3], error_y=dict(type='data', array=[0.5, 1, 2]), width=0.15) ]) # Change the bar mode fig.update_layout(barmode='group') fig.show()  They both look like:   Question: How can I control the distance between bars of different groups and bars of different Vars?

Answer: There are 2 properties that you are asking for. They are as follows:  bargap - gap between bars of adjacent location coordinates. bargroupgap - gap between bars of the same location coordinate.  But there is a catch here, if you set width then both the properties are ignored. So, remove the width value from the code and setting the above properties should work. import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Bar( name='Group 1', x=['Var 1', 'Var 2', 'Var 3'], y=[3, 6, 4], error_y=dict(type='data', array=[1, 0.5, 1.5]) )) fig.add_trace(go.Bar( name='Group 2', x=['Var 1', 'Var 2', 'Var 3'], y=[4, 7, 3], error_y=dict(type='data', array=[0.5, 1, 2]) )) fig.update_layout(barmode='group', bargap=0.30,bargroupgap=0.0) fig.show()
Question: I'm unclear how to style a line in a plotly express figure, altering color and width. The plotly documentation offers suggestions to style lines using go, but I do not see information for px. Example import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color='country') fig.show()  I tried putting line=dict(color='firebrick', width=4) as an argument of px.line but that throws the error line() got an unexpected keyword argument 'line' as it is code for go rather than px.

Answer: Plotly px line styles can be updated with update_traces function see documentation for further information. The following example modifies the prior figure making all of the lines black and thin. import plotly.express as px df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color='country') # This styles the line fig.update_traces(line=dict(color="Black", width=0.5)) fig.show()
Question: I have a pandas dataframe that looks something like this:  brand description former_price discounted_price 0 A icecream 1099.0 855.0 1 A cheese 469.0 375.0 2 B catfood 179.0 119.0 3 C NaN 699.0 399.0 4 NaN icecream 769.0 549.0 5 A icecream 769.0 669.0  I want to create a column that will assign a unique value for each brand & description combination. Note that either the brand or the description can be missing from the dataset (notified by NaN value). Also, note that if the brand and the description is the same (duplicated) I still want the unique value to be the same for the row. The output should look like this:  product_key brand description former_price discounted_price 0 1 A icecream 1099.0 855.0 1 2 A cheese 469.0 375.0 2 3 B catfood 179.0 119.0 3 4 C NaN 699.0 399.0 4 5 NaN icecream 769.0 549.0 5 1 A icecream 769.0 669.0  The values in product_key can be anything, I just want them to be unique based on brand and description columns. Any help is immensely appreciated! Thanks a lot!

Answer: You could try with pd.Series.factorize: df.set_index(['brand','description']).index.factorize()[0]+1  Output: 0 1 1 2 2 3 3 4 4 5 5 1   So you could try this, to assign it to be the first column: df.insert(loc=0, column='product_key', value=df.set_index(['brand','description']).index.factorize()[0]+1)  Output: df product_key brand description former_price discounted_price 0 1 A icecream 1099.0 855.0 1 2 A cheese 469.0 375.0 2 3 B catfood 179.0 119.0 3 4 C NaN 699.0 399.0 4 5 NaN icecream 769.0 549.0 5 1 A icecream 769.0 669.0
Question: I have a dataframe which has timestamp and its datatype is object. 0 2020-07-09T04:23:50.267Z 1 2020-07-09T11:21:55.536Z 2 2020-07-09T11:23:18.015Z 3 2020-07-09T04:03:28.581Z 4 2020-07-09T04:03:33.874Z Name: timestamp, dtype: object  I am not aware of the format of the datetime in the above dataframe. I applied pd.to_datetime to the above column where the datatype is changed as datetime64[ns, UTC]. df['timestamp'] = pd.to_datetime(df.timestamp)  Now the dataframe looks in this way, 0 2020-07-09 04:23:50.267000+00:00 1 2020-07-09 11:21:55.536000+00:00 2 2020-07-09 11:23:18.015000+00:00 3 2020-07-09 04:03:28.581000+00:00 4 2020-07-09 04:03:33.874000+00:00 Name: timestamp, dtype: datetime64[ns, UTC]  I want to convert the above datetime64[ns, UTC] format to normal datetime. For example, 2020-07-09 04:23:50.267000+00:00 to 2020-07-09 04:23:50  Can anyone explain me what is the meaning of this 2020-07-09T04:23:50.267Z representation and also how to convert this into datetime object?

Answer: To remove timezone, use tz_localize: df['timestamp'] = pd.to_datetime(df.timestamp).dt.tz_localize(None)  Output:  timestamp 0 2020-07-09 04:23:50.267 1 2020-07-09 11:21:55.536 2 2020-07-09 11:23:18.015 3 2020-07-09 04:03:28.581 4 2020-07-09 04:03:33.874
Question: I want to use query() to filter rows in a panda dataframe that appear in a given list. Similar to this question, but I really would prefer to use query() import pandas as pd df = pd.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]}) mylist =[5,3]  I tried: df.query('A.isin(mylist)') 

Answer: You could try this, using @, that allows us to refer a variable in the environment: df.query('A in @mylist')  Or this: df.query('A.isin(@mylist)',engine='python')
Question: Is there any workaround to create sub-cells in Spyder? E.g. I know that with #%% Cell 1  I can create a new cell. But is there a way to create a sub-cell which is grouped under the cell as in # Cell 1.1  ? I have found this discussion which didn't look encouraging. But I wanted to give it a try and ask here.

Answer: As per the post linked, the feature you are asking has been implemented. I just tried it on my Spyder IDE version 4.1.3 and it works by using an increasing number of %. For instance #%% Section 1 some code #%%% Sub-Section 1.1 some more code #%% Section 2 and so on
Question: My work:  Scan the paper Check horizontal and vertical line Detect checkbox How to know checkbox is ticked or not  At this point, I thought I could find it by using Hierarchical and Contours: Below is my work for i in range (len( contours_region)): #I already have X,Y,W,H of the checkbox through #print(i) #cv2.connectedComponentsWithStats x = contours_region[i][0][1] #when detecting checkbox x_1 = contours_region[i][2][1] y = contours_region[i][0][0] y_1 = contours_region[i][2][0] image_copy= image.copy() X,Y,W,H = contours_info[i] cv2.drawContours(image_copy, [numpy.array([[[X,Y]],[[X+W,Y]],[[X+W,Y+H]],[[X,Y+H]]])], 0, (0,0,255),2) gray = cv2.cvtColor(image_copy, cv2.COLOR_BGR2GRAY) ret,bw = cv2.threshold(gray,220,255,cv2.THRESH_BINARY_INV) contours,hierarchy = cv2.findContours(bw[x:x_1, y:y_1], cv2.RETR_CCOMP,1) print('-----Hierarchy-----') print(hierarchy) print('-----Number of Contours : '+ str(len(contours))) cv2.imshow('a', image_copy) cv2.waitKey(0)   I got this result (some high contours, some high hierarchy)  -----Hierarchy----- [[[-1 -1 1 -1] [ 2 -1 -1 0] [ 3 1 -1 0] [ 4 2 -1 0] [ 5 3 -1 0] [ 6 4 -1 0] [ 7 5 -1 0] [-1 6 -1 0]]] -----Number of Contours : 8    Another result:  Low Contours, Low Hierarchy  -----Hierarchy----- [[[-1 -1 1 -1] [ 2 -1 -1 0] [-1 1 -1 0]]] -----Number of Contours : 3    However, it's not perfect some case where it's not ticked but still got a really high result  [[[-1 -1 1 -1] [ 2 -1 -1 0] [ 3 1 -1 0] [ 4 2 -1 0] [ 5 3 -1 0] [-1 4 -1 0]]] -----Number of Contours : 6     In general, After review the whole data, the gap is not convincing between ticked and not ticked. Around 30% of boxes, giving the wrong result. Therefore, really wish to have a better method.

Answer: I think erode function help you. Use erosion to make the ticks bigger then count the non zero pixels. Here You can find the basics: import cv2 import numpy as np from google.colab.patches import cv2_imshow img = cv2.imread("image.png"); cv2_imshow(img) kernel = np.ones((3, 3), np.uint8) better_image = cv2.erode(img,kernel) cv2_imshow(better_image)
Question: In PyTorch, what is the difference between the following two methods in sending a tensor (or model) to GPU: Setup: X = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]]) # X = model() X = torch.DoubleTensor(X)      Method 1 Method 2     X.cuda() device = torch.device("cuda:0")X = X.to(device)     (I don't really need a detailed explanation of what is happening in the backend, just want to know if they are both essentially doing the same thing)

Answer: There is no difference between the two. Early versions of pytorch had .cuda() and .cpu() methods to move tensors and models from cpu to gpu and back. However, this made code writing a bit cumbersome: if cuda_available: x = x.cuda() model.cuda() else: x = x.cpu() model.cpu()  Later versions introduced .to() that basically takes care of everything in an elegant way: device = torch.device('cuda') if cuda_available else torch.device('cpu') x = x.to(device) model = model.to(device)
Question: I faced the difficulty of testing api using postman. Through swagger file upload functionality works correctly, I get a saved file on my hard disk. I would like to understand how to do this with Postman. I use the standard way to work with files which I use when working with Django and Flask: Body -> form-data: key=file, value=image.jpeg  But with FastAPI, I get an error: 127.0.0.1:54294 - "POST /uploadfile/ HTTP/1.1" 422 Unprocessable Entity  main.py @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): img = await file.read() if file.content_type not in ['image/jpeg', 'image/png']: raise HTTPException(status_code=406, detail="Please upload only .jpeg files") async with aiofiles.open(f"{file.filename}", "wb") as f: await f.write(img) return {"filename": file.filename}  I also tried body -> binary: image.jpeg, but got the same result: 

Answer: My code: from fastapi import FastAPI, UploadFile, File app = FastAPI() @app.post("/file/") async def create_upload_file(file: UploadFile = File(...)): return {"filename": file.filename}  Setup in Postman:  As stated in https://github.com/tiangolo/fastapi/issues/1653, the parameter name for the file is the key value that you have to use. Before you were using key=file and value=image.png (or whatever). Instead, FastAPI accepts file=image.png. Thus the error, since the file is necessary, but it is not present (at least, the key with that name is not present). P.S. I tested it with Postman v7.16.1
Question: Trying to test editable installs out and I'm not sure how to interpret the results. I intentionally made a typo in the egg= portion but it was still able to locate the egg without any help from me: root@6be8ee41b6c9:/# pip3 install -e git+https://gitlab.com/jame/clientapp.git Could not detect requirement name for 'git+https://gitlab.com/jame/clientapp.git', please specify one with #egg=your_package_name root@6be8ee41b6c9:/# pip3 install -e git+https://gitlab.com/jame/clientapp.git#egg= Could not detect requirement name for 'git+https://gitlab.com/jame/clientapp.git#egg=', please specify one with #egg=your_package_name root@6be8ee41b6c9:/# pip3 install -e git+https://gitlab.com/jame/clientapp.git#egg=e Obtaining e from git+https://gitlab.com/jame/clientapp.git#egg=e Cloning https://gitlab.com/jame/clientapp.git to /src/e Running setup.py (path:/src/e/setup.py) egg_info for package e produced metadata for project name clientapp. Fix your #egg=e fragments. Installing collected packages: clientapp Found existing installation: ClientApp 0.7 Can't uninstall 'ClientApp'. No files were found to uninstall. Running setup.py develop for clientapp Successfully installed clientapp root@6be8ee41b6c9:/# pip3 freeze asn1crypto==0.24.0 -e git+https://gitlab.com/jame/clientapp.git@5158712c426ce74613215e61cab8c21c7064105c#egg=ClientApp cryptography==2.6.1 entrypoints==0.3 keyring==17.1.1 keyrings.alt==3.1.1 pycrypto==2.6.1 PyGObject==3.30.4 pyxdg==0.25 SecretStorage==2.3.1 six==1.12.0  So if I could mess the egg name up so bad, why is it considered an error to either leave it blank or set to something empty

Answer: This is outdated notation. Nowadays one should use the following notation whenever possible: python -m pip install 'ProjectName @ git+https://example.local/repository.git@1.3.1'   My guess, the name matters if the project is a dependency of another project. For example in a case where one wants to install A from PyPI and Z from git, but Z is a dependency of A. python -m pip install 'A' 'git+https://example.local/repository.git#egg=Z'  or with new notation: python -m pip install 'A' 'Z @ git+https://example.local/repository.git
Question: I am trying to edit a python library and build it from source. Can someone explain what does the following instruction do and why is this method different from pip install package-name done normally? pip install --verbose --no-build-isolation --editable 

Answer: You can read all the usage options here: https://pip.pypa.io/en/stable/cli/pip_install/   -v, --verbose  Give more output. Option is additive, and can be used up to 3 times.    --no-build-isolation  Disable isolation when building a modern source distribution. Build dependencies specified by PEP 518 must be already installed if this option is used.  It means pip won't install the dependencies, so you have to install the dependencies if any by yourself first or the command will fail.   -e, --editable <path/url>  Install a project in editable mode (i.e. setuptools “develop mode”) from a local project path or a VCS url.  Here you have to input a path/url argument to install from an external source.
Question: I installed PyInstaller via pip, but when I try to run it I get pyinstaller: command not found After installation of the package the following warning was displayed: WARNING: The scripts pyi-archive_viewer, pyi-bindepend, pyi-grab_version, pyi-makespec, pyi-set_version and pyinstaller are installed in '/home/kevinapetrei/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.  Do you know how can I make it so pip installs everything straight to PATH?

Answer: Rather than messing with existing entires in PATH, consider appending to it the location from pip. It usually is ~/.local/bin (consistent with systemd's file-hierarchy). Good place to add/modify environmental variables is ~/.profile file. You do it by adding the following line: export PATH="$HOME/.local/bin:$PATH"  You may also consider ~/.pam_environment (but it has slightly different syntax).  For those wondering about the actual answer to the question: It used to be somewhat possible in old versions of Python 3, but the option got patched away.
Question: Here is the code: fig=plt.figure(figsize=(14,8)) sns.lineplot(x='season', y='team_strikerate', hue='batting_team', data=overall_batseason) plt.legend(title = 'Teams', loc = 1, fontsize = 12) plt.xlim([2008,2022])  And here is the image  Just to let you know, I've already drawn another similar lineplot above this one.

Answer: There is line shadow showing the confidence interval, because the dataset contains multiple y(team_strikerate) values for each x(season) value. By default, sns.lineplot() will estimate the mean by aggregating over multiple y values at each x value. After aggregation, the mean of y values at each x value will be plotted as a line. The line shadow represents the 95% confidence interval of the estimate.  To remove the line shadow, you can pass the argument ci=None to sns.lineplot(). (credit to @JohanC for providing this idea in this question's comment) To change the confidence interval, you can pass the argument errorbar=('ci', <int>) to sns.lineplot().
Question: I'm using Python & okta-aws tools and in order to fetch correct credentials on aws I need to run okta-aws init. But got an error message of Could not read roles from Okta and the system prompted that"Your Pipfile requires python_version 3.7, but you are using 3.8.3 (/usr/local/Cellar/o/1.1.4/l/.venv/bin/python). I've tried to search all the Pipfiles on the mac and it seems that the Pipflie under my ~/Pipfile and /usr/local/Cellar/python@3.8/3.8.3_2/libexec/bin/Pipfile all have the same python version of 3.8, while the Pipfile under my /usr/local/Cellar/okta-aws-tools/1.1.4/libexec/Pipfile has required python_version = 3.7. I've been struggling with this for a while and really not sure how I can fix this.

Answer: Consider installing pyenv with Homebrew on macOS brew update brew install pyenv  OR Clone the repository to get the latest version of pyenv  git clone https://github.com/pyenv/pyenv.git ~/.pyenv  Define your environment variables (For a recent MacOS you may want to replace ~/.bash_profile with ~/.zshrc as that is the default shell) echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile echo 'eval "$(pyenv init -)"' >> ~/.bash_profile source ~/.bash_profile  Restart your shell so the path changes take effect exec "$SHELL"  Verify the installation and check the available python versions pyenv install --list  Install the required python version pyenv install 3.7  Set it as your global version after installation pyenv global 3.7  eval pyenv path eval "$(pyenv init --path)"  Verify your current python version the system is using python3 --version