eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm struggling to hide the legend for some but not all of the lines in my line plot. Here is what the plot looks like now. Plot:  Essentially I want to hide the legend for the light grey lines while keeping it in place for the coloured lines. Here's my code: import plotly.graph_objects as go fig = go.Figure() fig.update_layout(autosize=False, width=800, height=500, template='none') fig.update_layout(title = 'Title', xaxis_title = 'Games', yaxis_title = 'Profit') for team in rest_teams: fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = {'color': '#F5F5F5'})) for team in big_eight: line_dict = {'color': cmap[team]} fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = line_dict)) fig.show()  I can update layout with fig.update_layout(showlegend=False)  which hides the whole thing and isn't optimal. Help would be appreciated.

Answer: If I understand your desired output correctly, you can use showlegend = False for the traces where you've set a grey color with color = #F5F5F5: for c in cols1: fig.add_trace(go.Scatter(x = df.index, y = df[c], line_color = '#F5F5F5', showlegend = False))  And then leave that out for the lines you'd like colors assigned to, and make sure to include name = c in: for c in cols2: fig.add_trace(go.Scatter(x = df.index, y = df[c], name = c))  Plot:  Complete code: import plotly.graph_objects as go import plotly.express as px import pandas as pd df = px.data.stocks() df = df.set_index('date') fig = go.Figure() cols1 = df.columns[:2] cols2 = df.columns[2:] for c in cols1: fig.add_trace(go.Scatter(x = df.index, y = df[c], line_color = '#F5F5F5', showlegend = False)) for c in cols2: fig.add_trace(go.Scatter(x = df.index, y = df[c], name = c)) fig.update_layout(template=template fig.show()
Question: I'm trying to parse an XML from a string in Python with no success. The string I'm trying to parse is: <?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:573a453c-72c0-4185-8c54-9010593dd102"> <data> <config xmlns="http://www.calix.com/ns/exa/base"> <profile> <policy-map> <name>ELINE_PM_1</name> <class-map-ethernet> <name>Eth-match-any-1</name> <ingress> <meter-type>meter-mef</meter-type> <eir>1000000</eir> </ingress> </class-map-ethernet> </policy-map> <policy-map> <name>ELINE_PM_2</name> <class-map-ethernet> <name>Eth-match-any-2</name> <ingress> <meter-type>meter-mef</meter-type> <eir>10000000</eir> </ingress> </class-map-ethernet> </policy-map> </profile> </config> </data> </rpc-reply>  I'm trying to use xml.etree.ElementTree library to parse the xml and I also tried to remove the first line related to xml version and encoding with no results. The code snippet to reproduce the issue I'm facing is: import xml.etree.ElementTree as ET reply_xml=''' <data> <config> <profile> <policy-map> <name>ELINE_PM_1</name> <class-map-ethernet> <name>Eth-match-any-1</name> <ingress> <meter-type>meter-mef</meter-type> <eir>1000000</eir> </ingress> </class-map-ethernet> </policy-map> <policy-map> <name>ELINE_PM_2</name> <class-map-ethernet> <name>Eth-match-any-2</name> <ingress> <meter-type>meter-mef</meter-type> <eir>10000000</eir> </ingress> </class-map-ethernet> </policy-map> </profile> </config> </data> ''' root = ET.fromstring(reply_xml) for child in root: print(child.tag, child.attrib)  reply_xml is a string containing the above mentioned xml so it should work but if I inspect the root variable using the debugger I see that it is not being populated correctly. It seems that the first xml tag (<?xml version="1.0" encoding="UTF-8"?>) creates some problems but even if I manually remove it I am not able to parse the xml correctly. Any clue to parse that xml?

Answer: Your original XML has namespaces. You need to honor them in your XPath queries. import xml.etree.ElementTree as ET reply_xml '''<?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:573a453c-72c0-4185-8c54-9010593dd102"> <data> <config xmlns="http://www.calix.com/ns/exa/base"> <!-- ... the rest of it ... --> </config> </data> </rpc-reply>''' ns = { 'calix': 'http://www.calix.com/ns/exa/base' } root = ET.fromstring(reply_xml) for eir in root.findall('.//calix:eir', ns): print(eir.text)  prints  1000000 10000000
Question: I wanted to avoid double evaluation of a mean in a dict comprehension, and I tried using the walrus operator: >>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]} >>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}  but this gave me the following error: Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65} File "<pyshell#2>", line 1, in <dictcomp> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65} NameError: name 'mean' is not defined  This error only happens when I try to use the variable, no problem while defining it: >>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if (sum(dic[x]) // len(dic[x])) > 65} >>> mean 86 >>> q {'B': 77, 'C': 87, 'D': 86}  Why? Where did I get it wrong?

Answer: Your code is roughly equivalent to q = {} for x in dic: if mean > 65: mean := ... q[x] = mean  which means you are using mean before assigning it. You need to move the definition to the if-clause-section of the dict-comprehension. >>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]} >>> q = {x: mean for x in dic if (mean := (sum(dic[x]) // len(dic[x]))) > 65} >>> q {'B': 77, 'C': 87, 'D': 86}  This translates to q = {} for x in dic: if (mean := ...) > 65: q[x] = mean
Question: I have a string like a = "X1+X2*X3*X1" b = {"X1":"XX0","X2":"XX1","X0":"XX2"}  I want to replace the substring 'X1,X2,X3' using dict b. However, when I replace using the below code, for x in b: a = a.replace(x,b[x]) print(a)   'XXX2+XX1*X3'  Expected result is  XX0 + XX1*X3*XX0 I know it is because the substring is replaced in a loop, but I don't know how to solve it.

Answer: You can create a pattern with '|' then search in dictionary transform like below. Try this: import re a = "X1+X2*X3*X1" b = {"X1":"XX0","X2":"XX1","X0":"XX2"} pattern = re.compile("|".join(b.keys())) out = pattern.sub(lambda x: b[re.escape(x.group(0))], a)  Output: >>> out 'XX0+XX1*X3*XX0'
Question: Now that Python 3.10 has been released, is there any preference when indicating that a parameter or returned value might be optional, i.e., can be None. So what is preferred: Option 1: def f(parameter: Optional[int]) -> Optional[str]:  Option 2: def f(parameter: int | None) -> str | None:  Also, is there any preference between Type | None and None | Type?

Answer: PEP 604 covers these topics in the specification section.  The existing typing.Union and | syntax should be equivalent. int | str == typing.Union[int, str]    The order of the items in the Union should not matter for equality. (int | str) == (str | int) (int | str | float) == typing.Union[str, float, int]  Optional values should be equivalent to the new union syntax None | t == typing.Optional[t]   As @jonrsharpe comments, Union and Optional are not deprecated, so the Union and | syntax are acceptable.  Łukasz Langa, a Python core developer, replied on a YouTube live related to the Python 3.10 release that Type | None is preferred over Optional[Type] for Python 3.10+.
Question: i have array like below arr = [1,2,3]  how can i convert it to '1,2,3' using python i have a usecase where i want to add a filter parameter to url like below url = some_url?id__in=1,2,3  i was initially thinking to pass it like so url = some_url?id__in={arr}  but this is incorrect. i am new to python and i have browsed how to do this. " ".join(str(x) for x in arr)  but this will give output '1 2 3' how can i fix this. could someone help me with this. thanks.

Answer: This gives you the 1,2,3 that you asked for. ",".join(str(x) for x in arr)
Question: I have a project, with some modules each of which contains a class doing their respective thing. Then I have an API class for the user. The API class instantiate those classes, and should forward/redirect to those who are doing the actual processing. I have the following questions:  How do I do the forwarding without rewriting what seems to me redundant code? For example, say Foo is the API class, Bar is a module class, then now I am writing something like: class Foo: def __init__(self, bar: Bar): self.bar = bar def name(self): return self.bar.name()  I explicitly wrote name method in Foo, which just returns name() of Bar. Isn't this redundant? Is there an "automatic" way to forward the call?  In the bar class I'd write some docstrings. Is there a way to "port" these docstrings to the API class Foo? Writing them again in Foo would be redundant and difficult to maintain.  

Answer: Try redirecting the __getattr__ magic method: class Foo: def __init__(self, bar: Bar): self.bar = bar def __getattr__(self, attr): return getattr(self.bar, attr)  This would redirect all functions to the bar variable. For multiple classes: class Foo: def __init__(self, bar: Bar, foo: Foo, blah: Blah): self.bar = bar self.foo = foo self.blah = blah def __getattr__(self, attr): if hasattr(self.bar, attr): return getattr(self.bar, attr) elif hasattr(self.foo, attr): return getattr(self.foo, attr) else: return getattr(self.blah, attr)
Question: class MyStreamListener(tweepy.StreamListener): def on_status(self, status): print(status.text) # prints every tweet received def on_error(self, status_code): if status_code == 420: # end of monthly limit rate (500k) return False  I use Python 3.9 and installed Tweepy via pip. I get the AttributeError on the class line. My import is just import tweepy. Authentication gets correctly handled. In the streaming.py file, I have the class Stream. But using this class ends in that. There is for example no status.text, even if there is the on_status function. I am a little bit confused.

Answer: Tweepy v4.0.0 was released recently and it merged StreamListener into Stream. I recommend updating your code to subclass Stream instead. Alternatively, you can downgrade to v3.10.0.
Question: I want to use vmap to vectorise this code for performance. def matrix(dataA, dataB): return jnp.array([[func(a, b) for b in dataB] for a in dataA]) matrix(data, data)  I tried this: def f(x, y): return func(x, y) mapped = jax.vmap(f) mapped(data, data)  But this only gives the diagonal entries. Basically I have a vector data = [1,2,3,4,5] (example), I want to get a matrix such that each entry (i, j) of the matrix is f(data[i], data[j]). Thus, the resulting matrix shape will be (len(data), len(data)).

Answer: jax.vmap maps across one set of axes at a time. If you want to map across two independent sets of axes, you can do so by nesting two vmap transformations: mapped = jax.vmap(jax.vmap(f, in_axes=(None, 0)), in_axes=(0, None)) result = mapped(data, data)
Question: I can draw a line with OpenCV Python but I can't make the line transparent def draw_from_pitch_to_image(image, reverse_output_points): for i in range(0, len(reverse_output_points), 2): x1, y1 = reverse_output_points[i] x2, y2 = reverse_output_points[i + 1] x1 = int(x1) y1 = int(y1) x2 = int(x2) y2 = int(y2) color = [255, 0, 0] if i < 1 else [0, 0, 255] cv2.line(image, (x1, y1), (x2, y2), color, 2)  I changed the code but the line is still not transparent. I don't know why, could someone please help me to solve this problem?  def draw_from_pitch_to_image(image, reverse_output_points): for i in range(0, len(reverse_output_points), 2): x1, y1 = reverse_output_points[i] x2, y2 = reverse_output_points[i + 1] alpha = 0.4 # Transparency factor. overlay = image.copy() x1 = int(x1) y1 = int(y1) x2 = int(x2) y2 = int(y2) color = [255, 0, 0] if i < 1 else [0, 0, 255] cv2.line(overlay, (x1, y1), (x2, y2), color, 2) cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output) 

Answer: One approach is to create a mask "overlay" image (copy of input image), draw a line onto this overlay image, and then perform the weighted addition of the two images using cv2.addWeighted() to mimic an alpha channel. Here's an example: Line with no transparency -> Result with alpha=0.5   Result with alpha=0.25    This method to apply transparency could be generalized to work with any other drawing function. Here's an example with cv2.rectangle() and cv2.circle() using an alpha=0.5 transparency value. No transparency -> Result with alpha=0.5     Code import cv2 # Load image and create a "overlay" image (copy of input image) image = cv2.imread('2.jpg') overlay = image.copy() original = image.copy() # To show no transparency # Test coordinates to draw a line x, y, w, h = 108, 107, 193, 204 # Draw line on overlay and original input image to show difference cv2.line(overlay, (x, y), (x + w, x + h), (36, 255, 12), 6) cv2.line(original, (x, y), (x + w, x + h), (36, 255, 12), 6) # Could also work with any other drawing function # cv2.rectangle(overlay, (x, y), (x + w, y + h), (36, 255, 12), -1) # cv2.rectangle(original, (x, y), (x + w, y + h), (36, 255, 12), -1) # cv2.circle(overlay, (x, y), 80, (36, 255, 12), -1) # cv2.circle(original, (x, y), 80, (36, 255, 12), -1) # Transparency value alpha = 0.50 # Perform weighted addition of the input image and the overlay result = cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0) cv2.imshow('result', result) cv2.imshow('original', original) cv2.waitKey()
Question: I am trying to use the sklearn function RocCurveDisplay.from_predictions as presented in https://scikit-learn.org/stable/modules/generated/sklearn.metrics.RocCurveDisplay.html#sklearn.metrics.RocCurveDisplay.from_predictions. I run the function like this: from sklearn.metrics import RocCurveDisplay true = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) prediction = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 0., 0.]) RocCurveDisplay.from_predictions(true,prediction) plt.show()  I get the error message "AttributeError: type object 'RocCurveDisplay' has no attribute 'from_predictions' ". Is this a version problem? I am using the latest one, 0.24.1

Answer: Your version 0.24.1 is not the latest version, You'll need to upgrade to scikit-learn 1.0 as from_predictions is supported in 1.0 You can upgrade using: pip install --upgrade scikit-learn
Question: I have been working with the Bybit API for the last week when I encountered the title problem yesterday. I have started a new env and installed only the bybit wrapper again and the issue still arises. From what I can see I have jsonschema installed and in my env PATH. It was working a few days ago, so I do believe this to be separate from whatever API I am trying to use. Included is a picture of the response when run in an interpreter. Any help would be greatly appreciated. ModuleNotFoundError: No module named 'jsonschema.compat' is the error that comes up. 

Answer: That module was removed in jsonschema 4.0. Your packages haven't been pinned to only use jsonschema 3.x, so that might happen. For now, you can downgrade to version 3.x of the jsonschema package with pip install -U 'jsonschema<4.0'  and things should work.
Question: Let's suppose to have a class Bag that contains a list of item. What we know about item is just that it has a method called : printDescription(). Now I want to define a method printAllItemsDescription inside Bag, that invokes the method printDescription() on each item inside items list. This should be the code (it's wrong but I think should looks like this) : class Bag: items:list[item] = [] . . . def printAllItemsDescription(this): for item in this.items: item.printDescription()  My problem is that I don't know how to tell python that my items is a list of item. I know I can do something like item:Item but don't know how to do it with lists. Then while iterating on items it will know that each item contains a method called printDescription(), but on this moment item is just a variable of undefined type. P.S. : I tried also to do something like x:list[item] but I got this error : Subscript for class "list" will generate runtime exception; enclose type annotation in quotes 

Answer: Python's type hinting is ever-evolving, and they've made some changes over time. Older versions of Python don't support subscripting list as in list[item]. Fortunately, we can get around all of this using a future import. The annotations import from __future__ works in all Python versions starting from 3.7 and effectively pretends that all type signatures are wrapped in quotes so they don't cause issues at runtime. from __future__ import annotations class Bag: items: list[Item] def __init__(self): self.items = [] def printAllItemsDescription(self): for item in self.items: item.printDescription()  Also, I've made a few minor changes to fit with Python's style. Instance methods should generally have their first argument called self for consistency, and classes (like item) should be written starting with a capital letter, so if you have control over the class item, I would recommend changing it to class Item.
Question: I have this running well, however am unable to avoid the loop, how can I get an only True if present or False if not present without having to loop through the list using a for loop? my_list = [[1, 2], [4, 6], [8, 3]] combined = [3, 8] for value in my_list: print(value) if set(combined) == set(value): print("present") else: print("absent") 

Answer: To avoid the multiple absent printing, you can use a for/else construct: for value in my_list: if set(combined) == set(value): print("present") break else: print("absent")  But if you're looking to optimize/reduce the loop, you can "hide" the loop inside an any call: any(set(combined) == set(value) for value in my_list)  Or alternatively use a list comprehension to convert all sub-lists to sets: set(combined) in [set(sublist) for sublist in my_list]  But as you can see, some sort of looping is necessary. I believe that by removing the loop you meant to reduce its code size.
Question: I have two decorated classes using attrs package as follows: @attr.s(kw_only=True) class Entity: """ base class of all entities """ entity_id = attr.ib(type=str) # ... @attr.s(kw_only=True) class Customer(Entity): customer_name = attr.ib(type=Name) # ...  I get Unexpected keyword argument "entity_id" for "Customer" for code like this: def register_customer(customer_name: str): return Customer( entity_id=unique_id_generator(), customer_name=Name(full_name=customer_name), )  So how can I make Mypy aware of the __init__ method of my parent class. I should mention that the code works perfectly and there is (at least it seems) no runtime error.

Answer: Your code is correct and should work. If I run the following simplified version: import attr @attr.s(kw_only=True) class Entity: """ base class of all entities """ entity_id = attr.ib(type=str) # ... @attr.s(kw_only=True) class Customer(Entity): customer_name = attr.ib(type=str) def register_customer(customer_name: str) -> Customer: return Customer( entity_id="abc", customer_name=customer_name, ) # ...  through Mypy 0.910 with attrs 21.2.0 on Python 3.9.7 I get: Success: no issues found in 1 source file   My theories:  Old Mypy (there's a lot of changes all times, sometimes it takes time for the attrs plugin to be updated with new features). Old attrs (we try to keep up with the changes in attrs and the features provided by Mypy). Python 2 (since you're using the old syntax). kw_only used to be Python 3-only and I wouldn't be surprised if mypy has some resident logic around it?
Question: Am loving ease of ax.bar_label in recent matpolotlib update. I'm keen to hide low-value data labels for readability in the final plot to avoid overlapping labels. How would I hide labels less than a predefined value (here, let's say less than 0.025) in the code below?  df_plot = pd.crosstab(df['Yr_Lvl_Cd'], df['Achievement_Cd'], normalize='index') ax = df_plot.plot(kind = 'bar', stacked = True, figsize= (10,12)) for c in ax.containers: ax.bar_label(c, label_type='center', color = "white") 

Answer: You can filter the container's datavalues attribute (requires matplotlib >= 3.4.0) using your threshold: threshold = 0.025 for c in ax.containers: # Filter the labels labels = [v if v > threshold else "" for v in c.datavalues] ax.bar_label(c, labels=labels, label_type="center")
Question: hello I need help to drop some rows by the condition: if the estimated price minus price is more than 1500 (positive) drop the row  price estimated price 0 13295 13795 1 19990 22275 2 7295 6498  for example only the index 1 would be drop thank you!

Answer: You can use pd.drop() in which you can drop specific rows by index. : >>> df.drop(df[(df['estimated price']-df['price'] >= 1500)].index) price estimated price 0 13295 13795 2 7295 6498  index 1 is dropped. Note that this method assumes that your index is unique. If otherwise, boolean indexing is the better solution.
Question: I would like to create a Python class with 3 functions.  Function 1 will ask the user to input one number. Function 2 will ask the user to input another number. Function 3 will multiply function 1 * function 2 and return to the product.  Here is the code I have so far: class Product: def __init__(self, x, y): self.x = x self.y = y def get_x(self): x = int(input('What is the first number?: ') def get_y(self): y = int(input('What is the second number?: ') def mult_XY(self): return x * y  When I try calling on the class I get 'y' is not defined. I tried using the following code: num = Product(x, y) print(num.mult_XY) 

Answer: Here is a working solution. Compare it to your current solution and spot the differences. After the following code snippet, I will highlight concepts you need to research in order to understand this program better. Here is a correct version of your code (note: there is potentially more than one solution): class Product: def __init__(self): return def get_x(self): self.x = int(input('What is the first number?: ')) return self.x def get_y(self): self.y = int(input('What is the second number?: ')) return self.y def mult_XY(self): return self.x * self.y p = Product() x = p.get_x() y = p.get_y() result = p.mult_XY() print('RESULT of {} * {} = {}'.format(x, y, result))  Is this the best answer? No. Depending on the specifics of your program, the structure of the code could be different. You have gaps of knowledge on the following concepts:  Objects and classes in Python Functions in Python Variables and scoping in Python  In order to understand better, you need to learn more about the fundamentals of Python. Here is a good resource to get you started: https://python-textbok.readthedocs.io/en/1.0/Introduction.html After reading that, you will be able to not only answer this question, but also set the foundation for your programming knowledge. Don't give up and wish you the best.