eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Making an enum with exactly n many members is trivial if I've defined it myself: class Compass(enum.Enum): NORTH = enum.auto() EAST = enum.auto() SOUTH = enum.auto() WEST = enum.auto() ## or ## Coin = enum.Enum('Coin', 'HEADS TAILS')  But what if this enum will be released into the wild to be subclassed by other users? Let's assume that some of its extra behaviour depends on having the right number of members so we need to enforce that users define them correctly. Here's my desired behaviour: class Threenum(enum.Enum): """An enum with exactly 3 members, a 'Holy Enum of Antioch' if you will. First shalt thou inherit from it. Then shalt though define members three, no more, no less. Three shall be the number thou shalt define, and the number of the members shall be three. Four shalt thou not define, neither define thou two, excepting that thou then proceed to three. Five is right out. Once member three, being the third member, be defined, then employest thou thy Threenum of Antioch towards thy problem, which, being intractible in My sight, shall be solved. """ ... class Triumvirate(Threenum): # success CEASAR = enum.auto() POMPEY = enum.auto() CRASSUS = enum.auto() class TeenageMutantNinjaTurtles(Threenum): # TypeError LEONARDO = 'blue' DONATELLO = 'purple' RAPHAEL = 'red' MICHELANGELO = 'orange' Trinity = Threenum('Trinity', 'FATHER SON SPIRIT') # success Schwartz = Threenum('Schwartz', 'UPSIDE DOWNSIDE') # TypeError  Overriding _generate_next_value_() allows the enforcement of a maximum number of members, but not a minimum.

Answer: An easier approach would be to check the number of Enum members of a subclass in an __init_subclass__ method: class Threenum(enum.Enum): def __init_subclass__(cls): if len(cls) != 3: raise TypeError('Subclass of Threenum must have exactly 3 members.')  Demo here You can also create such a class with a factory function: def exact_enum(number): class _ExactEnum(enum.Enum): def __init_subclass__(cls): if len(cls) != number: raise TypeError( f'This Enum subclass must have exactly {number} members.') return _ExactEnum  Usage: class TeenageMutantNinjaTurtles(exact_enum(3)): # TypeError LEONARDO = 'blue' DONATELLO = 'purple' RAPHAEL = 'red' MICHELANGELO = 'orange'  Demo here
Question: In my project, I need to develop a program in Python to insert a UUID in a device. There will be 1.000 devices produced per day, the UUIDs need to be inserted into each device, and only once. I have a large input file (100.000 lines) containing all the available UUIDs, as follows: str[32] str[32] ... str[32] str[32]  Example: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef coolcafebabecoolcafebabecoolcafecoolcafe ... deadbeefdeadbeefcoolcafebabecoolcafebabe coolcafebabecoolcafebabedeadbeefdeadbeef  My program will be executed and closed every day. I need to make sure I won't use the same UUID twice. I was thinking of two solutions:  Delete the line of the UUID in the input file once I have used it. Then, when I need a UUID, I only have to read the first line.  Change the format of the input file by adding a byte on each line, that is equal to 0 when the UUID is free, and set it to 1 when it has been used. When my program is first executed, I read the file to get the index of the first 0, then I can keep track of the index and set the byte to 1 each time I consume one UUID. For example : deadbeefdeadbeefdeadbeefdeadbeefdeadbeef;1 coolcafebabecoolcafebabecoolcafecoolcafe;1 ... deadbeefdeadbeefcoolcafebabecoolcafebabe;0 coolcafebabecoolcafebabedeadbeefdeadbeef;0    It seems both solution imply having to rewrite the whole content of the file, am I right? Is there a better solution?

Answer: Here: Here's how to remove used UUID to solve your issue: import os def next_uuid(in_file, used_file): used = set() if os.path.exists(used_file): with open(used_file) as f: used = set(l.strip() for l in f) with open(in_file) as f: for l in f: u = l.strip() if u not in used: with open(used_file, 'a') as uf: uf.write(f"{u}\n") return u raise Exception("No more UUIDs") in_file = 'uuids.txt' used_file = 'used.txt' next_u = next_uuid(in_file, used_file) print(f"Next UUID: {next_u}")  This script grabs the next available UUID from a file. It keeps track of used UUIDs in a separate file to avoid duplicates. Basically, it works like this:  Read all the used UUIDs into memory Go through the main UUID file When it finds a UUID that hasn't been used, it:  Marks it as used Returns it   If all UUIDs are used up, it throws an error  The script is pretty quick because it only reads what it needs and just adds to the 'used' file instead of rewriting everything. It should work fine for your daily prod.
Question: I have the ALT text generated just need to add it somehow to the images under the figure tag. A little background - I want to my my pdf accessible to the WCAG 2.1 AA standards and i am using adobe autotag feature to tag the pdf. It tags the images as /figure. I can totally extract the figures and generate alt text but I cant find a way to embed or add that alt text to the image and make it WCAG 2.1 AA compliant. I ultimately also want to add this to a lambda function in AWS. Is there any way I could do so? Thank you! I tried using multiple open source libraries pikepdf,pymupdf, and some more and also tried converting the pdf to html or xml but the issue with that is the pdf cant be converted back exactly to what it was. I also tried adding it directly in code but the file goes corrupt.

Answer: The MCID for Alt text is either allocated at time of PDF generation (so for this WEB.HTML page by the browsers PDF generator), or can be easily be manually assigned in a GUI, when checking for the other human verified content. Thus Acrobat pre-flight is the simplest and easiest point to index Alt Text in the mandatory PDF/AU post production. In a web page there is a 1:1 direct relationship the alt= is directly combined with the img src. That direct association is not maintained in a PDF. <div class="gravatar-wrapper-32"> <img src="https://www.gravatar.com/avatar/f50f5b351c1d07d2a5a8f023e1731768?s=64&amp;d=identicon&amp;r=PG&amp;f=y&amp;so-version=2" alt="Aryan Khanna's user avatar" width="32" height="32" class="bar-sm"></div>  Attempting to add all the production interconnected components inside a PDF stream is usually fraught with problems, since all existing file components need re indexing & renumbering, thus becomes a massive slow internal task.  To add the required object and all it's dependents or ancestors (Parent = 119) and or any children objects midway through a PDF is not easy. This is object 120 of 156. the image can be anywhere in the file as the image and /Alt text are not directly related, but just numbers in a page index. Actually in this case, the image was placed way back as document number 11 object. 120 0 obj <</Type /StructElem /S /Figure /Alt (Aryan Khanna's user avatar) /P 119 0 R /K [ << /Type /MCR /Pg 2 0 R /MCID 34 >> ] /ID (node00000026) >> endobj  How to place the Tag is find the image number and look for it in the page contents here it is added as /X11. /X11 Do  now inject the related Tag /MCID 34 number before it /P<</MCID 34>>BDC /X11 Do  That is where the link to a tag is manually placed before the correct image as a child reference. So it will be seen as a tag for an image.  However since EVERY PDF needs AT LEAST two manual visual checks to verify images, it is easiest to check the image alt data at the same time.
Question: What works: I have a package version_info in which I define a string version_info. When I increment version_info.version_info, the main code prints out the incremented value after the reload. What doesn't work: When I increment the value in version_info_sub.py, it is not updated upon reload. I suspect that the importlib.reload doesn't go accross the from .sub import version_info_sub statement. How can I achieve that also the value from sub.py gets reloaded? Main code: from importlib import reload import version_info ... reload(version_info) print(version_info.version_string) # successfully updated print(version_info.version_info_sub) # stays on the old value  version_info/__init__.py: from .sub import version_info_sub version_string = "6"  version_info/sub.py: version_info_sub = "6" 

Answer: I think I got your problem. I made a reload_package function for you. import inspect def reload_package(package_): modules_names_paths = inspect.getmembers(package_, inspect.ismodule) modules_names = [x[0] for x in modules_names_paths] for module_name in modules_names: module_ = getattr(package_, module_name) reload(module_) reload(package_)  The problem is that you reload the package but the sub module is not reloaded. You could reload the sub also. But in order to be agnostic (I guess the caller does not have to know about "sub") you will have to loop over the modules in the package, reload them and then reload the package. This function will do. Happy Coding
Question: How to plot a similar graph in python?  import matplotlib.pylab as plt import numpy as np from scipy.stats import binom y = binom.rvs(n = 10, p = 0.5, size = 100) counts, bins = np.histogram(y, bins=50) plt.scatter(bins[:len(counts)], counts) plt.grid() plt.show() 

Answer: First off, when the data is discrete, the bin edges should go in between the values. Simply setting bins=50 chops the distance between the lowest and the highest value into 50 equally-sized regions. Some of these regions might get no values if their start and end both lie between the same integers. To show the values in a scatter plot, you can use the centers of the bins as x-position, and the values 1, 2, ... till the count of the bin as the y position. import matplotlib.pyplot as plt import numpy as np from scipy.stats import binom y = binom.rvs(n=10, p=0.5, size=100) counts, bins = np.histogram(y, bins=np.arange(y.min() - 0.5, y.max() + 1, 1)) centers = (bins[:-1] + bins[1:]) / 2 for center, count in zip(centers, counts): plt.scatter(np.repeat(center, count), np.arange(count) + 1, marker='o', edgecolor='blue', color='none') plt.grid(axis='y') plt.ylim(ymin=0) plt.show()   Here is an example with a continuous distribution and using filled squares instead of hollow circles as markers: import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator import numpy as np y = np.random.randn(150).cumsum() counts, bins = np.histogram(y, bins=30) centers = (bins[:-1] + bins[1:]) / 2 for center, count in zip(centers, counts): plt.scatter(np.repeat(center, count), np.arange(count) + 1, marker='s', color='crimson') plt.rc('axes', axisbelow=True) plt.grid(True, axis='y') plt.gca().yaxis.set_major_locator(MultipleLocator(1)) plt.show()
Question: I'm trying to create a text representation of a JSONField that has some data structured as an array of dictionaries like this: [ { "key1":"value1", "key2":"value2" }, { "key3":"value3", "key4":"value4", "key5":"value5" } ]  My goal is to represent this data in the Django template like this:  ( key1=value1 & key2=value2 ) || ( key3=value3 & key4=value4 & key5=value5 )  Now I'd iterate through the array and see if I'm not hitting the last dictionary so I can add an || between the condition representation text since it's already an array list like: {% for dict in data %} // Do stuff with dict {% if data|last != dict %} || {% endif %} {% endfor %}  However, since a dictionary doesn't have a last thing, I'm having a hard time to iterate through the "key,value" when I'm doing stuff with each dictionary object when I've got to append an "&" only if I'm not hitting the end of this dict items. {% for k,v in dict %} k=v // append "&" if this is not the last key being iterated? {% endfor %}  Any suggestions/workarounds/ideas would be much appreciated :)

Answer: Just found it! Silly me, Seems like Django already provides a pretty neat built-in forloop object for templates that works like a charm! Will drop it here for anyone who might have the same problem {% for k,v in dict %} k=v {% if forloop.last != True %} &amp; {% endif %} {% endfor %}
Question: I have a list that looks something like this: data = ['1', '12', '123']  I want to produce a new list, that looks like this: result = ['$1', '1', '$2', '12', '$3', '123']  where the number after the $ sign is the length of the next element. The straightforward way to do this is with a for loop: result = [] for element in data: result += [f'${len(element)}'] + [element]  but I was wondering if it's possible to do it in a more elegant way - with a list comprehension, perhaps? I could do result = [[f'${len(e)}', e] for e in data]  but this results in a list of lists: [['$1', '1'], ['$2', '12'], ['$3', '123']]  I could flatten that with something like result = sum([[f'${len(e)}', e] for e in data], [])  or even result = [x for xs in [[f'${len(e)}', e] for e in data] for x in xs]  but this is getting rather difficult to read. Is there a better way to do this?

Answer: You can do it with two loops: result = [item for s in data for item in (f"${len(s)}", s)]  ['$1', '1', '$2', '12', '$3', '123']
Question: I'm currently working with GridDB for a project involving IoT data, and I'm facing an issue with executing SQL-like queries using GridDB's TQL (Time Series SQL-like Query Language). Here is a brief description of what I am trying to achieve: I have a container in GridDB which stores IoT sensor data. I am trying to query this data using TQL to fetch records based on certain conditions. Here is a sample of my container schema and the data insertion code: import griddb_python as griddb factory = griddb.StoreFactory.get_instance() gridstore = factory.get_store( host='127.0.0.1', port=10001, cluster_name='defaultCluster', username='admin', password='admin' ) # Define container schema conInfo = griddb.ContainerInfo( name="sensorData", column_info_list=[ ["TimeStamp", griddb.Type.TIMESTAMP], ["Sensor_id", griddb.Type.STRING], ["Value", griddb.Type.DOUBLE] ], type=griddb.ContainerType.TIME_SERIES, row_key=True ) # Create container ts = gridstore.put_container(conInfo) ts.set_auto_commit(False) # Insert sample data import datetime ts.put([datetime.datetime.now(), "sensor_1", 25.5]) ts.put([datetime.datetime.now(), "sensor_2", 26.7]) ts.commit()  Now, I am trying to execute the following TQL query to fetch records: query = ts.query("SELECT * FROM sensorData WHERE value > 26") rs = query.fetch() while rs.has_next(): data = rs.next() print(data)  Im getting the following error though: InvalidColumnException: Column (value) not found  I've checked the schema and value exists so i'm not sure if it is talking about some other column or something wrong with value exactly? Any help would be appreciated.

Answer: By default, SQL column names are case insensitive in some languages like MYSQL. TQL is case sensitive though. change value to Value: query = ts.query("SELECT * FROM sensorData WHERE Value > 26")
Question: I was trying to use the set_widget_scale function to resize my widgets based on the resolution of the window, when I resize the widgets on the main page it works fine when the resolution is chosen, when I go to the other page it raises this error: ("_tkinter.TclError: invalid command name ".!ctkoptionmenu.!dropdownmenu"")  import customtkinter as ct class App(ct.CTk): def __init__(self): super().__init__() self.title("Test") self.geometry("640x480") self.Page1() def Page1(self): for i in self.winfo_children(): i.destroy() self.page1 = ct.CTkButton(self , text = "Page 2" , command = lambda: (self.Page2() , self.Resize())) self.page1.pack() self.menu = ct.CTkOptionMenu(self) self.menu.pack() def Page2(self): for i in self.winfo_children(): i.destroy() self.page2 = ct.CTkButton(self , text = "Page 1" , command = lambda: (self.Page1() , self.Resize1())) self.page2.pack() self.menu = ct.CTkOptionMenu(self) self.menu.pack() def Resize(self): ct.set_widget_scaling(2) def Resize1(self): ct.set_widget_scaling(0.5) if __name__ == "__main__": app = App() app.mainloop()  This is an example of my problem that I am facing

Answer: This method avoids using destroy constantly. Instead, it uses frames to separate pages. You can destroy the frames when not used, as demonstrated by the added destroy button. import customtkinter as ct class App(ct.CTk): def __init__(self): super().__init__() self.title("Test") self.geometry("640x480") self.end_button = ct.CTkButton(self, text="DESTROY") self.end_button.pack(padx=10, pady=30) self.page1_frame = ct.CTkFrame(self) self.page1_button = ct.CTkButton(self.page1_frame, text="Page 1", command=self.show_page2) self.page1_button.pack() self.page1_menu = ct.CTkOptionMenu(self.page1_frame) self.page1_menu.pack() self.page2_frame = ct.CTkFrame(self) self.page2_button = ct.CTkButton(self.page2_frame, text="Page 1", command=self.show_page1) self.page2_button.pack() self.page2_menu = ct.CTkOptionMenu(self.page2_frame) self.page2_menu.pack() self.page1_frame.pack() self.end_button.configure(command=lambda: (self.page1_frame.destroy(), self.page2_frame.destroy())) def show_page2(self): ct.set_widget_scaling(0.5) self.page1_frame.pack_forget() self.page2_frame.pack() def show_page1(self): ct.set_widget_scaling(2) self.page2_frame.pack_forget() self.page1_frame.pack() if __name__ == "__main__": app = App() app.mainloop()  I combined the resize and page functions, but it works even when using command=lambda: (self.resize_small(), self.show_page2()) hope this helps
Question: Playwright (Python) save a page as PDF function works fine when there's no customisation in the header or footer. However, when I try to introduce a custom footer, the values don't seem to get injected appropriately. Example code: from playwright.sync_api import sync_playwright def generate_pdf_with_page_numbers(): with sync_playwright() as p: browser = p.chromium.launch() context = browser.new_context() page = context.new_page() # Navigate to the desired page page.goto('https://example.com') # Generate PDF with page numbers in the footer pdf = page.pdf( path="output.pdf", format="A4", display_header_footer=True, footer_template=""" <div style="width: 100%; text-align: center; font-size: 10px;"> Page {{pageNumber}} of {{totalPages}} </div> """, margin={"top": "40px", "bottom": "40px"} ) browser.close() # Run the function to generate the PDF generate_pdf_with_page_numbers()  I was expecting: Page 1 of 1  But actually I get: Page {{pageNumber}} of {{totalPages}}  Do you see any issue with this code?

Answer: From the Playwright docs, header_template (which has the same format as footer_template) provides a number of magic class names you can use to inject certain pieces of data into the page: from playwright.sync_api import sync_playwright # 1.44.0 def generate_pdf_with_page_numbers(): with sync_playwright() as p: browser = p.chromium.launch() context = browser.new_context() page = context.new_page() page.goto("https://example.com") pdf = page.pdf( path="output.pdf", format="A4", display_header_footer=True, footer_template=""" <div style="width: 100%; text-align: center; font-size: 10px;"> Page <span class="pageNumber"></span> of <span class="totalPages"></span> <div class="title"></div> <div class="url"></div> <div class="date"></div> </div> """, margin={"top": "40px", "bottom": "40px"} ) browser.close() if __name__ == "__main__": generate_pdf_with_page_numbers()  Run the code, open output.pdf and observe the title, date, URL and pages injected into the footer.
Question: Given a set of coordination and values like coors=np.array([[0,0],[1,1],[2,2]]) heat_values=[3,2,1]  I would like to generate a matrix like mtx=[[3,0,0], [0,2,0], [0,0,1]]  Any functions can do the jobs?

Answer: I would use numpy.zeros and indexing: mtx = np.zeros(coors.max(0)+1, dtype=int) mtx[tuple(coors.T)] = heat_values  Output: array([[3, 0, 0], [0, 2, 0], [0, 0, 1]])  NB. if heat_values is an array, better use dtype=heat_values.dtype. This should generalize to any dimension of coors: coors=np.array([[1,0,0],[0,1,1],[0,2,3]]) heat_values=[9,8,7] mtx = np.zeros(coors.max(0)+1, dtype=int) mtx[tuple(coors.T)] = heat_values array([[[0, 0, 0, 0], [0, 8, 0, 0], [0, 0, 0, 7]], [[9, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]])  If you want to force a "square" output: coors=np.array([[0,0],[1,1],[2,3]]) heat_values=[1,2,3] mtx = np.zeros((np.max(coors)+1,)*coors.shape[1], dtype=int) mtx[tuple(coors.T)] = heat_values array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 3], [0, 0, 0, 0]])
Question: I am working on a plot where I want to show two groups on one axis and a third group as fill-value. The problem is, that when I plot it, the y-axis shows values in tuples: data_dict = {'major_group': list(np.array([['A']*10, ['B']*10]).flat), 'minor_group': ['q ','r ','s ','t ']*5, 'legend_group':np.repeat(['d','e','f','g','h','i'],[7,3,1,5,1,3])} (pd.DataFrame(data= data_dict) .groupby(['major_group', 'minor_group','legend_group'], observed = True) .size() .unstack() .plot(kind='barh', stacked=True))  Result:  However, I'm looking for something like this:  How can this be achieved? Is there some major and minor axis label that can be set?

Answer: This code will create horizontal stacked bars, grouped hierarchically in the y-axis label: import matplotlib.pyplot as plt import pandas as pd import numpy as np from pandas import DataFrame def create_data() -> DataFrame: data_dict = { 'major_group': list(np.array([['A'] * 10, ['B'] * 10]).flat), 'minor_group': ['q', 'r', 's', 't'] * 5, 'legend_group': np.repeat(['d', 'e', 'f', 'g', 'h', 'i'], [7, 3, 1, 5, 1, 3]) } return pd.DataFrame(data=data_dict).groupby(['major_group', 'minor_group', 'legend_group'], observed=True).size().unstack() def plot_stacked_barh(df: DataFrame) -> None: fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True) for i, major_group in enumerate(df.index.levels[0]): ax = axes[i] df.loc[major_group].plot(kind='barh', stacked=True, ax=ax, width=.8) if i == 0: handles, labels = ax.get_legend_handles_labels() ax.legend_.remove() ax.set_ylabel(major_group, weight='bold') ax.xaxis.grid(visible=True, which='major', color='black', linestyle='--', alpha=.4) ax.set_axisbelow(True) fig.legend(handles, labels, title='Legend Group') plt.tight_layout() fig.subplots_adjust(hspace=0) plt.show() def main() -> None: df = create_data() print(df) plot_stacked_barh(df) if __name__ == "__main__": main()   For a similar vertical equivalent, look here.
Question: I am building a command-line program that uses argparse. In the (assumed-to-be) rare case of a wrong call, argparse will show a description string supplied when creating the ArgumentParser. I want this description to show the version number of my program. I want to extract this from the pyproject.toml file via tomllib. Since this is an expensive operation (and even more so since I want to learn how to do it), I would like the description string to be evaluated lazily: only when it is actually to be printed. I have not yet found a way to do it even though I am willing to build a one-trick-pony object specialized for this particular value:  collections.UserString could provide the lazy evaluation (via overriding __getattribute__ for the data attribute), but, alas, some code in argparse uses re.sub() on it, which appears to check isinstance(x, str), which a UserString does not fulfill. a subclass of str can override any operation done on a string -- but not perform lazy evaluation for a plain use of the entire string. (Is this true?) if ArgumentParser would use str(description) instead of description when it is about to print the description, one could supply an object that performs the lazy evaluation in its __str__ method. But, alas, ArgumentParser does not do this.  Is there any approach that does the job?

Answer: In a roundabout way: don't set description, and only set it just before ArgumentParser would format the help. import argparse import time class MyArgParser(argparse.ArgumentParser): def format_help(self): if not self.description: print("Now thinking hard...") time.sleep(3) self.description = "An application!" return super().format_help() ap = MyArgParser() ap.add_argument("--foo", help="foo") args = ap.parse_args() print(args)  This program is fast when run without arguments, or with --foo=bar, and takes its sweet time when you run with --help.