eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I need to make different amounts of line plots with Matplotlib, but I have not been able to find a colormap that makes it easy to distinguish between the line plots. I have used the brg colormap like this: colors=brg(np.linspace(0,1,num_plots))  with for i in range(num_plots): ax.step(x,y,c=colors[i])  With four plots, this could look like this:  Notice how hard it is to distinguish the colors of the top and bottom plots, which is especially bad if a legend is used. I've tried a lot of different colormaps like rainbow and jet, but with this setup, brg seems to give the best result for num_plots between 1 and 12. I did find this How to get 10 different colors that are easily recognizable and this Wiki page Help:Distinguishable colors, but I don't know if this can be used in any way.. Is there an easy fix to this, or will I have to make do with this?

Answer: I would use the tab10 or tab20 colormaps. See Colormap reference  However, I believe you will always have trouble distinguishing hues when the number of lines becomes large (I would say >5 and certainly >10). In this case, you should combine hues with other distinguishing features like different markers or linestyles. colors = matplotlib.cm.tab20(range(20)) markers = matplotlib.lines.Line2D.markers.keys() x = np.linspace(0,1,100) fig, axs = plt.subplots(2,4, figsize=(4*4,4*2)) for nlines,ax0 in zip(np.arange(5,21,5), axs.T): ax0[0].set_title('{:d} lines'.format(nlines)) for n,c,m in zip(range(nlines),colors,markers): y = x*np.random.random()+np.random.random() ax0[0].plot(x,y) ax0[1].plot(x,y, marker=m, markevery=10) axs[0,0].set_ylabel('only hues', fontsize=16, fontweight='bold') axs[1,0].set_ylabel('hues+markers', fontsize=16, fontweight='bold') fig.tight_layout()
Question:  df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'], index=['excellent', 'excellent', 'excellent', 'good', 'good', 'good', 'ok', 'ok', 'ok', 'poor', 'poor']) df.rename(columns={0: 'Grades'}, inplace=True) df  I am trying to create an ordered category from the above dataframe using the following code - df = df['Grades'].astype('category',categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'],ordered=True)  However it gives the error : astype() got an unexpected keyword argument 'categories'.

Answer: From pandas 0.25+ are removed these arguments:  Removed the previously deprecated ordered and categories keyword arguments in astype (GH17742)   In newer pandas versions is necesary use CategoricalDtype and pass to astype: from pandas.api.types import CategoricalDtype cats = ['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'] cat_type = CategoricalDtype(categories=cats, ordered=True) df['Grades'] = df['Grades'].astype(cat_type) print (df) Grades excellent A+ excellent A excellent A- good B+ good B good B- ok C+ ok C ok C- poor D+ poor D  Or use Categorical: df['Grades'] = pd.Categorical(df['Grades'], categories=cats, ordered=True) print (df) Grades excellent A+ excellent A excellent A- good B+ good B good B- ok C+ ok C ok C- poor D+ poor D
Question: I have developed a small code in Python to generate a PPTX file. But I would like also to generate a picture in PNG or JPEG of the slide. from pptx import Presentation from pptx.util import Inches img_path = 'monty-truth.png' prs = Presentation() blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout) left = top = Inches(1) pic = slide.shapes.add_picture(img_path, left, top) left = Inches(5) height = Inches(5.5) pic = slide.shapes.add_picture(img_path, left, top, height=height) prs.save('test.pptx')  Is there a way to transform a PPTX file (including just one slide) into a PNG or JPEG picture ?

Answer: On Windows once you have installed pywin32 pip install pywin32 You can then use the following code : import win32com.client Application = win32com.client.Dispatch("PowerPoint.Application") Presentation = Application.Presentations.Open(r"your_path") Presentation.Slides[0].Export(r"the_new_path-file.jpg", "JPG") Application.Quit() Presentation = None Application = None  With this line, you can change the number of the slide you want to export (for example below, for slide number 6) : Presentation.Slides[5].Export(r"the_new_path-file.jpg", "JPG")
Question: I'm distributing a module which can be imported and used as a library. It also comes with an executable—installed via console_scripts—for people to use. That executable can also be started as a systemd service (Type=simple) to provide a daemon to the system. systemd services need to refer to absolute paths in their ExecStart lines, so I need to figure out where the console_script got installed to. With other build systemd like CMake, autotools or Meson, I can directly access the prefix and then use something like configure_file (meson) to substitute @PREFIX@ in foo.service.in, and then install the generated unit to $prefix/lib/systemd/system/. I just can't figure out how to do this with setuptools. Inside setup.py, sys.prefix is set to python's prefix, which isn't the same thing. I have tried overriding install_data and install, but these approaches all have various problems like breaking when building a wheel via pip, or leaving the file around when uninstalling. (I'd be OK just not installing the service when we're not being installed system-wide; systemd wouldn't be able to find it if the prefix is not /usr or /usr/local anyway.) Someone pointed me at a website which says that you're not supposed to do this with setuptools:  Note, by the way, that this encapsulation of data files means that you can't actually install data files to some arbitrary location on a user's machine; this is a feature, not a bug.  Which sounds like I'm just going against the grain here. I'm really looking for pointers or examples to tell me what I'm supposed to be doing here. If that's "don't use setuptools", fine - but then advice on what the preferred thing is would be welcome.

Answer: I would say don't use setuptools for this, it's not what it's made for. Instead use the package manager for the target distribution (apt, yum, dnf, pacman, etc.). I believe systemd and such things that are specific to the operating system (Linux distribution, Linux init system) are out of scope for Python packaging, pip, setuptools, etc. Keep as much as reasonably possible under setuptools's responsibility, so that the project stays pip-installable, and so that the project itself provides easy way to get access to systemd specific files but don't install them (maybe with a command my-thing-generate-systemd-files --target path/to/output for example, that would simplify the task for the users of the project). And on the other side provide Linux-distribution-specific packages (deb, rpm, etc.), if I am not mistaken there are tools that allow to build such packages starting from the Python project (a sdist or the source code repository). Some ideas (quick search without testing, not recommendations):  https://pypi.org/project/pyp2rpm/ (from Fedora) https://src.fedoraproject.org/rpms/pyproject-rpm-macros (from Fedora) https://pypi.org/project/stdeb/ (unmaintained?) https://pypi.org/project/py2deb/ (unmaintained?) https://snapcraft.io/docs/python-apps (from Ubuntu, new standard?) https://fpm.readthedocs.io/ https://briefcase.readthedocs.io/en/stable/reference/platforms/linux/appimage.html etc.
Question: I have a dictionary like this: my_dict = {'Southampton': '33.7%', 'Cherbourg': '55.36%', 'Queenstown': '38.96%'}  How can I have a simple plot with 3 bars showing the values of each key in a dictionary? I've tried: sns.barplot(x=my_dict.keys(), y = int(my_dict.values()))  But I get :  TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict_values' 

Answer: There are several issues in your code:  You are trying to convert each value (eg "xx.xx%") into a number. my_dict.values() returns all values as a dict_values object. int(my_dict.values())) means converting the set of all values to a single integer, not converting each of the values to an integer. The former, naturally, makes no sense. Python can't interpret something like "12.34%" as an integer or a float. You need to remove the percentage sign, ie float("12.34%"[:-1]). Dictionaries are not ordered. Therefore, my_dict.keys() and my_dict.values() are not guaranteed to return keys and values in the key-value pairs in the same order, for example, the keys you get may be ['Southampton', 'Cherbourg', 'Queenstown'] and the values you get may be "55.36%", "33.7", "38.96%". This is no longer a problem in Python >= 3.7 and CPython 3.6; see @AmphotericLewisAcid's comment below.  With all these issues fixed: keys = list(my_dict.keys()) # get values in the same order as keys, and parse percentage values vals = [float(my_dict[k][:-1]) for k in keys] sns.barplot(x=keys, y=vals)  You get:
Question: I am using piptools to compile requirements.in to generate requirements.txt. I also have some index url written in my .pip/pip.conf file which I store my credentials to our python artifactory repo. So whenever I do pip-compile requirements.in the generated requirements.txt will contain a line reflecting that index url such as the following. I don't want this line to be there, is there a configuration where we can configure pip-tools to not generate this line to requirements.txt? --extra-index-url https://pli:credentials@mydomain.jfrog.io/api/pypi/pypi-virtual/simple 

Answer: add the --no-emit-index-url flag to the pip-compile command, or --no-index for pre-5.2.0 versions. EDIT: Official docs for this flag are here.
Question: I am trying to find whether there is a way to take an installed package and version and check whether it satisfies a requirements spec. For example, if I have the package pip==20.0.2, I want the program to do the following: CheckReqSpec("pip==20.0.2", "pip>=19.0.0") -> True CheckReqSpec("pip==20.0.2", "pip<=20.1") -> True CheckReqSpec("pip==20.0.2", "pip~=20.0.0") -> True CheckReqSpec("pip==20.0.2", "pip>20.0.2") -> False  I found that pkg_resources.extern.packaging has version.parse, which is useful for comparing different versions greater than or less than, but requirement specs can be very complex, and there are operators like ~= that are not standard mathematical operators. The setuptools docs has this example: PickyThing<1.6,>1.9,!=1.9.6,<2.0a0,==2.4c1  Is there an existing way to do this check, or an easy way to make my own? edit: The ~= in particular is difficult, especially if the specs are input as a variable. * in the version requirement is also hard to figure out, since   version.parse("20.0.*") == version.parse("20.0.1") # False version.parse("20.0.*") < version.parse("20.0.0") # True version.parse("20.0.*") < version.parse("20.1.1") # True version.parse("20.0.*") >= version.parse("20.0.0") # False 

Answer: Using pkg_resources (from setuptools) as an API is now deprecated, and will cause warnings at import time: $ python3 -W always -c 'from pkg_resources import Requirement' <string>:1: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html  Instead, we can parse a requirement using packaging (which pkg_resources was using internally anyway). Check requirement name is matching with an equality comparison, and check requirement version is within a specifier set using in: >>> from packaging.requirements import Requirement >>> req = Requirement("pip~=20.0.0") >>> pin = "pip==20.0.2" >>> name, version = pin.split("==") >>> name == req.name and version in req.specifier True  Post releases work. Pre-releases have to be opted in for explicitly. >>> "20.0.0post1" in req.specifier True >>> req.specifier.contains("20.0.1b3") False >>> req.specifier.contains("20.0.1b3", prereleases=True) True  Note: a top-level packaging installation may be at a different version than the packaging version which pip vendors and uses internally. If you need to guarantee the packaging APIs are matching pip's behavior exactly, you could import the Requirement type from pip's vendored subpackage directly: from pip._vendor.packaging.requirements import Requirement  Or, if importing from a private submodule scares you, then install packaging at top-level to the exact same version which your pip version is currently vendoring. Check your pip version (with pip --version) and then check the corresponding packaging version which pip vendors. For example, if your pip version is 23.2.1 you may check in: https://github.com/pypa/pip/blob/23.2.1/src/pip/_vendor/vendor.txt Here you will see that pip==23.2.1 vendors an older version at packaging==21.3.
Question: I want to click the "OK" button in this pop up dialog  I tried: driver.switchTo().alert().accept();  but it doesn't work

Answer: To click on the OK button within the alert you need to induce WebDriverWait for the desired alert_is_present() and you can use the following solution: WebDriverWait(driver, 10).until(EC.alert_is_present()) driver.switch_to.alert.accept()  Note : You have to add the following imports : from selenium.webdriver.common.alert import Alert from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC   Reference You can find a couple of relevant discussions in:  Python click button on alert How to read the text from the alert box using Python + Selenium Why switching to alert through selenium is not stable? Would like to understand why switch_to_alert() is receiving a strikethrough and how to fix
Question: When i try to save my model as hdf5 path = 'path.h5' model.save(path)  then load the model again my_reloaded_model = tf.keras.models.load_model(path)  I get the following error ValueError: Unknown layer: KerasLayer  Any help ? I'm using tensorflow version: 2.2.0 keras version: 2.3.0-tf 

Answer: I just found a solution that worked for me my_reloaded_model = tf.keras.models.load_model( (path), custom_objects={'KerasLayer':hub.KerasLayer} )
Question: I have a simple graph and I am using Plotly Express Library to draw it. The image is as follows which have two legends overlapping 'Rank' and 'Genre'.  px.scatter_ternary(data_frame = data, a='Length.', b='Beats.Per.Minute', c='Popularity', color = 'Rank', symbol = 'Genre', labels = {'Length.': 'Len', 'Beats.Per.Minute':'Beats'}, color_continuous_midpoint = 15, symbol_sequence = ['circle-open-dot', 'cross-open','triangle-ne'])  What can be done to avoid overlapping?

Answer: Short answer: You can move the colorbar with: fig.update_layout(coloraxis_colorbar=dict(yanchor="top", y=1, x=0, ticks="outside"))   The details: Since you haven't provided a fully executable code snippet with a sample of your data, I'm going to have to base a suggestion on a dataset and an example that's at least able to reproduce a similar problem. Take a look:  This seems to be the exact same problem that you're facing. To make the plot readable, I would simply move the colorbar using fig.update_layout(coloraxis_colorbar() like this:  Complete code: # imports import plotly.express as px # data df = px.data.election() # figure setup fig = px.scatter_ternary(df, a="Joly", b="Coderre", c="Bergeron", hover_name="district", color="total", size="total", size_max=15, symbol ='Coderre', color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"}, ) # move colorbar fig.update_layout(coloraxis_colorbar=dict(yanchor="top", y=1, x=0, ticks="outside", ticksuffix=" bills")) fig.show()  I hope this solves your real-world problem. Don't hesitate to let me know if not!
Question: I am new to poetry and want to get it set-up with pytest. I have a package mylib in the following set-up ├── dist │ ├── mylib-0.0.1-py3-none-any.whl │ └── mylib-0.0.1.tar.gz ├── poetry.lock ├── mylib │ ├── functions.py │ ├── __init__.py │ └── utils.py ├── pyproject.toml ├── README.md └── tests └── test_functions.py  in test_functions I have import mylib  However, when I run poetry run pytest  it complains about mylib not being included. I can run pip install dist/mylib-0.0.1-py3-none-any.whl  but that clutters my python environment with mylib. I want to use that environment as well for other packages. My question is: What is the proper way to work with poetry and pytest? My underlying python environment is a clean pyenv python 3.8. Using pyproject.toml I create a project based virtual environment for mylib.

Answer: You need to run poetry install to set up your dev environment. It will install all package and development requirements, and once that is done it will do a dev-install of your source code. You only need to run it once, code changes will propagate directly and do not require running the install again.  If you have set up the virtual env that you want already, take care that it is activated when you run the install command. If you don't, poetry will try to create a new virtual env and use that, which is probably not what you want.
Question: I'm trying to use multiple inputs in custom layers in Tensorflow-Keras. Usage can be anything, right now it is defined as multiplying the mask with the image. I've search SO and the only answer I could find was for TF 1.x so it didn't do any good. class mul(layers.Layer): def __init__(self, **kwargs): super().__init__(**kwargs) # I've added pass because this is the simplest form I can come up with. pass def call(self, inputs): # magic happens here and multiplications occur return(Z) 

Answer: EDIT: Since TensorFlow v2.3/2.4, the contract is to use a list of inputs to the call method. For keras (not tf.keras) I think the answer below still applies. Implementing multiple inputs is done in the call method of your class, there are two alternatives:  List input, here the inputs parameter is expected to be a list containing all the inputs, the advantage here is that it can be variable size. You can index the list, or unpack arguments using the = operator:  def call(self, inputs): Z = inputs[0] * inputs[1] #Alternate input1, input2 = inputs Z = input1 * input2 return Z   Multiple input parameters in the call method, works but then the number of parameters is fixed when the layer is defined:  def call(self, input1, input2): Z = input1 * input2 return Z    Whatever method you choose to implement this depends if you need fixed size or variable sized number of arguments. Of course each method changes how the layer has to be called, either by passing a list of arguments, or by passing arguments one by one in the function call. You can also use *args in the first method to allow for a call method with a variable number of arguments, but overall keras' own layers that take multiple inputs (like Concatenate and Add) are implemented using lists.
Question: My doc is like this:  def segments(self, start_time=1, end_time=9223372036854775806, offset=0, size=20): """Get segments of the model :parameter offset: - optional int size: - optional int start_time: - optional string，Segments end_time: - optional string，Segments :return: Segments Object """  When I make html, it turns out:  WARNING: Definition list ends without a blank line; unexpected unindent.  I have no idea where I should add a blank line? I searched SO, but can not find any similar case as mine. 

Answer: The Question was already answered by jonrsharpe in a comment, but i want to complete it here. You are using the default Sphinx Style "reStructuredText" You have to add ":parameter" on every line:  """Get segments of the model :parameter offset: optional int :parameter size: optional int :parameter start_time: optional string，Segments :parameter end_time: optional string，Segments :return: Segments Object """  If you had created a dedicated definition list, then you would need an empty line after the last definition. In this case, you can do it, but don't always have to.
Question: In my application am trying to place my button,text and input at the center of the window.I am using PySimpleGUI for designing buttons.For aligning to the center i used justification='center' attribute on my code.But still it is not fitting to the center of the window. The code am working with is import PySimpleGUI as sg from tkinter import * sg.theme('DarkAmber') layout = [ [sg.Text('Enter the value',justification='center')], [sg.Input(justification='center')], [sg.Button('Enter','center')] ] window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True) while True: event, values = window.read() # Read the event that happened and the values dictionary print(event, values) if event == sg.WIN_CLOSED or event == 'Exit': # If user closed window with X or if user clicked "Exit" button then exit break if event == 'Button': print('You pressed the button') window.close()  The above code outputs  How can i make the text,button and input to the center of the window?

Answer: this code make the text, button and input to the center of the window. import PySimpleGUI as sg sg.theme('DarkAmber') layout = [ [sg.Text('Enter the value',justification='center',size=(100,1))], [sg.Input(justification='center',size=(100,1))], [sg.Button('Enter','center',size=(100,1))] ] window = sg.Window('My new window', layout, size=(500,300), grab_anywhere=True) while True: event, values = window.read() # Read the event that happened and the values dictionary print(event, values) if event == None or event == 'Exit': # If user closed window with X or if user clicked "Exit" button then exit break if event == 'Button': print('You pressed the button') window.close()
Question: I recently spent couple hours making tkinter and IDLE work on my pyenv Python installation (macOS). Why you are here?  You manage Python versions with pyenv on macOS and ( You want IDLE - the development environment for Python - work on your macOS or you want tkinter module work )  What's wrong? You get one of the following errors:  Python may not be configured for Tk on import tkinter import _tkinter # If this fails your Python may not be configured for Tk RuntimeError: tk.h version (8.6) doesn't match libtk.a version (8.5) ModuleNotFoundError: No module named '_tkinter' 

Answer: Here is step by step guide to make IDLE and tkinter work:  install tcl-tk with Homebrew. In shell run brew install tcl-tk in shell run echo 'export PATH="/usr/local/opt/tcl-tk/bin:$PATH"' >> ~/.zshrc reload shell by quitting Terminal app or run source ~/.zshrc after reloaded check that tck-tk is in $PATH. Run echo $PATH | grep --color=auto tcl-tk. As the result you should see your $PATH contents with tcl-tk highlighted now we run three commands from Homebrew's output from step #1  in shell run export LDFLAGS="-L/usr/local/opt/tcl-tk/lib" in shell run export CPPFLAGS="-I/usr/local/opt/tcl-tk/include" in shell run export PKG_CONFIG_PATH="/usr/local/opt/tcl-tk/lib/pkgconfig"   if you have your Python version already installed with pyenv then uninstall it with pyenv uninstall <your python version>. E.g. pyenv uninstall 3.8.2 set environment variable that will be used by python-build. In shell run export PYTHON_CONFIGURE_OPTS="--with-tcltk-includes='-I/usr/local/opt/tcl-tk/include' --with-tcltk-libs='-L/usr/local/opt/tcl-tk/lib -ltcl8.6 -ltk8.6'" Note: in future use tck-tk version that actually installed with Homebrew. At the moment of posting 8.6 was the actual finally install Python with pyenv with pyenv install <version>. E.g. pyenv install 3.8.2  Test  in shell run pyenv global <verion that you've just installed> now check IDLE. In shell run idle. You should see IDLE window without any warnings and "text printed in red".    now check tkinter. In shell run python -m tkinter -c "tkinter._test()". You should see test window like on the image:   That's it! My environment: check this is something went wrong executing steps above:  macOS Catalina zsh (included in macOS Catalina) = "shell" above Homebrew (installed with instructions from Homebrew official website) pyenv (installed with Homebrew and PATH updated according to pyenv official readme from GitHub) Python 3.8.x - 3.9.x (installed with pyenv install <version> command)