question_id
int64
59.5M
79.4M
creation_date
stringlengths
8
10
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
65,539,129
2021-1-2
https://stackoverflow.com/questions/65539129/how-does-inheritance-work-in-python-metaclass
Suppose, I have a custom metaclass and a class linked to it: class Meta(type): pass class A(metaclass=Meta): pass From my understanding that at the end of the class A statement, the following steps are executed: Call Meta('A', (), {}). Because step 1 is a built-in call, it means that type.__call__(...) will be invoked. This is because type is linked to the Meta.__class__. type.__call__(...) in turn run two other methods (a __new__ and a __init__). If Meta defined either or both of these methods, then inside of type.__call__ these methods will be invoked as Meta.__new__(...) and/or Meta.__init__(...). class A is created and linked to the Meta (A.__class__). Now, suppose I have a subclass of A: class Meta(type): pass class A(metaclass=Meta): pass class B(A): pass At the end of class B statement, are the following steps correct? Call type('B', (), {}) instead of Meta, because B.__class__ is type. Invoke type.__call__(...) which in turn run two other methods (__new__ and __init__). type.__new__(type, 'B', (A,), {}). type.__init__(cls, 'B', (A,), {}). Suppose the above steps is correct (which I doubt), shouldn't B.__class__ give type instead of Meta? My reasoning is that B is created with default type metaclass. But print out B.__class__ gives Meta instead of type. print(B.__class__) #<class '__main__.Meta'> Also if I manually create a class with A as parent, again the created class is linked to the Meta. C = type.__call__(type, 'C', (A,), {}) print(C.__class__) #<class '__main__.Meta'> #or D = type.__new__(type, 'D', (A,), {}) print(D.__class__) #<class '__main__.Meta'> My question is how Python create the class B/C and how B/C is linked to the Meta?
So --- a somewhat confusing question that can be answered,and somethat simplified by simply running some examples in the interactive mode. But to start, when you state: type.__call__(...) in turn run two other methods (a __new__ and a __init__). It is a simplification of what takes place. When we create new class, like in resolving a class statement class A:, type.__call__ is invoked alright. But is this call is searched in the class of Meta itself. That is, the "metaclass" of "Meta" - which by default is type. Bear with me: When we are talking about an ordinary class E with no custom metaclass, and you create an instance by doing E() - Python searches for the __call__ method in the class of which E is an instance: that is, its metaclass. As it is type, then type.__call__ is called. It is type.__call__ which calls the __new__ and __init__ methods, as you stated, but not only for metaclasses: it orchestrates these calls in any object instantiation - the exact same mechanism is used in any object instantiation in Python: both ordinary objects and classes: In [178]: class MetaMeta(type): ...: def __call__(metacls, *args, **kw): ...: print("Now at the meta-meta class") ...: return super().__call__(*args, **kw) ...: In [179]: class EmptyMeta(type, metaclass=MetaMeta): ...: def __call__(cls, *args, **kw): ...: print("At the metaclass __call__") ...: return super().__call__(*args, **kw) ...: ...: ...: In [180]: class A(metaclass=EmptyMeta): ...: pass ...: Now at the meta-meta class In [181]: a = A() At the metaclass __call__ In [182]: class Direct(metaclass=MetaMeta): pass In [183]: Direct() Now at the meta-meta class Out[183]: <__main__.Direct at 0x7fa66bc72c10> So, in short: when creating a class A, which is an instance of Meta, the __call__ method of the class of Meta is called. That will call __init__ and __new__ in the metaclass Meta. If those are not defined, ordinary attribute lookup will call these methods in the superclass of Meta, which happens to also be "type". Now, moving on on your question: when one inherits from a class with a custom metaclass, like your B class, Python takes the most derived metaclass in its superclasses as its own metaclass, not type. No need to explicitly declare a custom metaclass. That, in practical means, is what makes metaclass needed instead of just Class decorators: these affect only the class where they are declared, and have no effect in further subclasses. In [184]: class B(A): pass Now at the meta-meta class In [185]: B() At the metaclass __call__ Out[185]: <__main__.B at 0x7fa6682ab3a0> In [186]: B.__class__ Out[186]: __main__.EmptyMeta Even in an explicit call to type instead of the class statement, the derived class' metaclass will be the metaclass of the superclass. Note, however, that in this case we are hardcoding the call to the "metameta" class to type.__new__ and the "custom metaclass of the metaclass" is ignored: In [187]: C = type("C", (A, ), {}) In [188]: C() At the metaclass __call__ Out[188]: <__main__.C at 0x7fa653cb0d60> If you want to programmaticaly create a class that has a custom "meta meta class" (God forbid one needing this in anything but learning purposes), there is a special call in the types module that does that: In [192]: import types In [193]: D = types.new_class("D", (A,), {}) Now at the meta-meta class In [194]: D() At the metaclass __call__ Out[194]: <__main__.D at 0x7fa6682959a0> And to wrap it up, note that if the superclasses of a class have diverging metaclasses, Python will refuse to create a class at all. That is somewhat common in "real world" code, when people try to create Abstract classes (wich usea custom metaclass) with a base class in some framework with an ORM, which typically also have a custom metaclass: In [203]: class Meta1(type): pass In [204]: class Meta2(type): pass In [205]: class A(metaclass=Meta1): pass In [206]: class B(metaclass=Meta2): pass In [207]: class C(A, B): pass --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-207-1def53cc27f4> in <module> ----> 1 class C(A, B): pass TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Which is fixable by producing a derived metaclass that inherits from the metaclasses in both ancestor branches (this requires that both metaclasses are well behaved, using the super() instead of hardcoding calls to type - but that is the case with well maintained and popular frameworks): In [208]: class Meta3(Meta1, Meta2): pass In [209]: class C(A, B, metaclass=Meta3): pass In [210]:
5
6
65,539,313
2021-1-2
https://stackoverflow.com/questions/65539313/combine-two-dictionaries-with-preference-to-one-of-them
I have two dictionaries One: default = {"val1": 10, "val2": 20, "val3": 30, "val4": 40} Two: parsed = {"val1": 60, "val2": 50} Now, I want to combine these two dictionaries in such a way that values for the keys present in both the dictionaries are taken from the parsed dictionary and for rest of the keys in default and their values are put in to the new dictionary. For the above given dictionary the newly created dictionary would be, updated = {"val1": 60, "val2": 50, "val3": 30, "val4": 40} The obvious way to code up this would be to loop through the keys in default and check if that is present in parsed and put then into a new list updated, and in the else clause of the same check we can use values from default. I am not sure if this is a pythonic way to do it or a much cleaner method. Could someone help on this?
You can create a new dict with {**dict1,**dict2} where dict2 is the one that should have priority in terms of values >>> updated = {**default, **parsed} >>> updated {'val1': 60, 'val2': 50, 'val3': 30, 'val4': 40}
19
21
65,533,684
2021-1-1
https://stackoverflow.com/questions/65533684/python-3-9-and-pycharm-htmlparser-attributeerror
When trying to create new python 3.9 Virtualenv Environment in Pycharm I got such error AttributeError: 'HTMLParser' object has no attribute 'unescape' Traceback (most recent call last): File "/var/folders/6g/vnvmvlf51gv49m22rzj9zdtw0000gn/T/tmpifdsjw6lpycharm-management/setuptools-40.8.0/setup.py", line 11, in <module> import setuptools File "/private/var/folders/6g/vnvmvlf51gv49m22rzj9zdtw0000gn/T/tmpifdsjw6lpycharm-management/setuptools-40.8.0/setuptools/__init__.py", line 20, in <module> from setuptools.dist import Distribution, Feature File "/private/var/folders/6g/vnvmvlf51gv49m22rzj9zdtw0000gn/T/tmpifdsjw6lpycharm-management/setuptools-40.8.0/setuptools/dist.py", line 35, in <module> from setuptools.depends import Require File "/private/var/folders/6g/vnvmvlf51gv49m22rzj9zdtw0000gn/T/tmpifdsjw6lpycharm-management/setuptools-40.8.0/setuptools/depends.py", line 7, in <module> from .py33compat import Bytecode File "/private/var/folders/6g/vnvmvlf51gv49m22rzj9zdtw0000gn/T/tmpifdsjw6lpycharm-management/setuptools-40.8.0/setuptools/py33compat.py", line 55, in <module> unescape = getattr(html, 'unescape', html_parser.HTMLParser().unescape) AttributeError: 'HTMLParser' object has no attribute 'unescape' What can be done with it?
Based on Matthias comment To fix this error I have to update both pycharm (>=2020) and setuptools (>=41). Hope this will help somebody
8
8
65,529,808
2021-1-1
https://stackoverflow.com/questions/65529808/undetected-chromedriver-not-loading-correctly
I'm attempting to use a headless chrome browser with selenium that also bypasses the bot detection test and currently using the the following project https://github.com/ultrafunkamsterdam/undetected-chromedriver Every time I try to implement the code it doesn't recognise the driver. Here is the link for you to understand Here is the code # # UNDETECTED chromedriver (headless,even) # import undetected_chromedriver as uc options = uc.ChromeOptions() options.headless=True options.add_argument('--headless') chrome = uc.Chrome(options=options) chrome.get('https://datadome.co/customers-stories/toppreise-ends-web-scraping-and-content-theft-with-datadome/') chrome.save_screenshot('datadome_undetected_webddriver.png') So when I use chrome.get() I receive an error as chrome has no get() member. I've installed the project using the pip command as well. So I was thinking do I need to direct the path to the chromedriver and where would that be because I doubt it'll be the normal driver and the documentation never mentioned the PATH for the driver. Okay so when I run the program I get the following in terminal DevTools listening on ws://127.0.0.1:55903/devtools/browser/ef3a54cf-35b9-400f-972c-2b54ca227eb8 [0102/000855.199:INFO:CONSOLE(2)] "JQMIGRATE: Migrate is installed, version 1.4.1", source: https://datadome.co/wp-content/cache/busting/1/wp-includes/js/jquery/jquery-migrate.min-1.4.1.js (2) [0102/000856.946:INFO:CONSOLE(1)] "Messaging child iframes", source: https://track.gaconnector.com/gaconnector.js (1) [0102/000856.946:INFO:CONSOLE(1)] "https://track.gaconnector.com/track_pageview?gaconnector_id=ddade4fc-93d0-20a3-79fa-39648d8e6629&account_id=6dd3433635353fd00f486550bcd5b157&referer=&GA_Client_ID=183291439.1609510136&page_url=https%3A%2F%2Fdatadome.co%2Fcustomers-stories%2Ftoppreise-ends-web-scraping-and-content-theft-with-datadome%2F&gclid=&utm_campaign=&utm_term=&utm_content=&utm_source=&utm_medium=", source: https://track.gaconnector.com/gaconnector.js (1) PS D:\Programming\Python> [0102/000902.158:INFO:CONSOLE(0)] "The resource https://js.driftt.com/core/assets/js/runtime~main.a73a2727.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source: https://js.driftt.com/core?embedId=2rce7xnshapc&forceShow=false&skipCampaigns=false&sessionId=98163ad1-ed91-459e-9473-3f8861aa717e&sessionStarted=1609510138&campaignRefreshToken=107a7fd5-edb4-499b-9f39-5306c189cdb6&pageLoadStartTime=1609510135613 (0) [0102/000902.272:ERROR:web_contents_delegate.cc(224)] WebContentsDelegate::CheckMediaAccessPermission: Not supported. [0102/000902.272:ERROR:web_contents_delegate.cc(224)] WebContentsDelegate::CheckMediaAccessPermission: Not supported. [0102/000902.475:INFO:CONSOLE(0)] "The resource https://js.driftt.com/core/assets/js/runtime~main.a73a2727.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source: https://js.driftt.com/core/chat (0) [0102/000906.041:INFO:CONSOLE(0)] "The resource https://js.zohocdn.com/ichat/js/73291e5e_wmsbridge.js was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.", source: https://datadome.co/customers-stories/toppreise-ends-web-scraping-and-content-theft-with-datadome/ (0)
ChromeOptions() is defined within selenium.webdriver.chrome.options but not within undetected_chromedriver. Solution You can use the following solution: Code Block: import undetected_chromedriver as uc from selenium import webdriver options = webdriver.ChromeOptions() options.headless = True driver = uc.Chrome(options=options) driver.get('https://datadome.co/customers-stories/toppreise-ends-web-scraping-and-content-theft-with-datadome/') driver.save_screenshot('datadome_undetected_webddriver.png') driver.quit() print("Program Ended") Console Output: Screenshot: References You canfind a couple of relevant detailed discussions in: Is there any possible ways to bypass cloudflare security checks?
7
14
65,534,384
2021-1-1
https://stackoverflow.com/questions/65534384/django-jsonfield-doesnt-accept-value
I add a JSONField for one of my models. I want to create an instance of that model in admin panel but that JSONField returns a validation error (Enter a valid JSON.) how I can fix this?? model: class Product(models.Model): category = models.ManyToManyField(Category, related_name='products') name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, allow_unicode=True, unique=True) image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) attribute = models.JSONField(default={}) price = models.PositiveIntegerField() discount = models.PositiveIntegerField(null=True, blank=True) available = models.BooleanField(default=True) popular = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comments = GenericRelation(Comment) class Meta: ordering = ('-created',) def __str__(self): return self.name I add products in admin panel. I want to have multiple attributes for my products like color , size and ... . is it true to use json fiels for that?? this is the error:
This is not valid JSON. The strings in JSON are wrapped with double quotes. Indeed, you can verify this for example with JSONLint.com. It is a valid Python dictionary, but not valid JSON. You thus should enter: { "key": "value" } For more information, see the JSON specifications. I add products in admin panel. I want to have multiple attributes for my products like color , size and ... . is it true to use json fiels for that?? If the fields are fixed (are attributes of all Products), then you should use individual fields, since that is more convenient to fielter, make forms, etc. If the data is more dynamic, it is often better to make use of a JSON field.
5
9
65,532,002
2021-1-1
https://stackoverflow.com/questions/65532002/how-to-enable-code-folding-in-jupyter-lab
Running JupyterLab version 3.0.0 and would like to enable code folding (collapse classes, functions etc in Python). I have followed the instructions in this Jupyter Lab github post: Under Settings / Text Editor, I have these User preferences (right pane): { "editorConfig": { "lineNumbers": true, "codeFolding": true } } And I do not see any triangles appearing on the left side of the cells. What else do I need to do in order to enable code folding? For abundance of clarity, this question pertains to JupyterLab specifically.
Those instructions are specifically for the text editor, not the notebook interface. Try this instead, in Settings / Notebook: { "codeCellConfig": { "codeFolding": true } } If you want to enable code folding for Markdown or raw cells, see markdownCellConfig and rawCellConfig respectively.
22
27
65,531,537
2021-1-1
https://stackoverflow.com/questions/65531537/returning-true-if-a-value-is-present-in-an-enum-returning-false-if-not
I apologise if I'm missing anything obvious; is there a way to see if a value is in an enum which returns True if it is, False if not? For example, if I take the following enum from the python documentation, from enum import Enum class Colour(Enum): RED = 1 GREEN = 2 BLUE = 3 is there any way to do the following action, or an equivalent, without an exception being raised: colour_test = "YELLOW" if Colour[colour_test]: print("In enum") else: print("Not in enum") ## Output wanted - "Not in enum" ## Actual output - KeyError: "YELLOW" I know that I can use try;except statements, but I'd prefer not to in this situation as I'd like to use this conditional with some others.
Enums have a __members__ dict that you can check: if colour_test in Colour.__members__: print("In enum") else: print("Not in enum") You can alternatively use a generalized approach with hasattr, but this returns wrong results for some non-members like "__new__": if hasattr(Colour, colour_test): print("In enum") else: print("Not in enum")
5
8
65,527,272
2021-1-1
https://stackoverflow.com/questions/65527272/how-does-the-following-expression-work-in-python
How does the following expression work in python? >>> 1 ++++++++++++++++++++ 1 2 >>> 1 ++++++++++++++++++++-+ 1 0 I thought this would raise a SyntaxError but that was not the case.
You have to use the logic of brackets and arithmetic operations for this kind of calculation. 1--2 becomes, 1-(-(2)) = 1-(-2) = 1+2 = 3 1+++1 becomes, 1+(+(+1)) = 2 1++-1 becomes, 1+(+(-1)) = 0
17
12
65,516,999
2020-12-31
https://stackoverflow.com/questions/65516999/how-to-programmatically-open-an-application-by-name-on-macos
I'm writing a cross-platform Python application that acts as a frontend for DOSBox. It needs to call the DOSBox executable with a number of command line arguments. I don't want to hardcode a specific path to DOSBox because it might depend on where the user has installed it. On Linux, I can simply do: import subprocess subprocess.run(['dosbox'] + args) On macOS, however, I currently use the following code: import subprocess subprocess.run(['/Applications/dosbox.app/Contents/MacOS/DOSBox'] + args) Which seems awfully specific and I'm not even sure whether it works, since I don't have a mac to test on. What is the correct way to open an application by name on macOS? (NB: I have also asked this sibling question for Windows.)
I don't know DOSBox or want it on my Mac, but in general, when you install an application on macOS it has a "property list" file, or plist or "info.plist" in it. In there, the developer is supposed to put a "bundle identifier" key called CFBundleIdentifier. This must be unique across all applications, so for DOSBox it should be something like: <key>CFBundleIdentifier</key> <string>com.dosboxinc.dosbox</string> Get one of your users to find that, then you can use the bundle identifier to open it like this regardless of installation location: open -b BUNDLEIDENTIFIER --args arg1 arg2 arg3 where arg1, arg2 and arg3 get passed on to DOSBox. You may be able to get the bundle identifier by running this in Terminal: osascript -e 'id of app "DOSBox"' Note, however, that if this command works, it means I have correctly guessed the app name "DOSBox", which means that you could just use the app name with open, rather than the bundle identifier like this: open -a DOSBox --args arg1 arg2 arg3
6
5
65,518,787
2020-12-31
https://stackoverflow.com/questions/65518787/how-to-retrieve-minimum-unique-values-from-list
I have a list of dictionary. I wish to have only one result for each unique api and the result need to show according to priority: 0, 1, 2. May I know how should I work on it? Data: [ {'api':'test1', 'result': 0}, {'api':'test2', 'result': 1}, {'api':'test3', 'result': 2}, {'api':'test3', 'result': 0}, {'api':'test3', 'result': 1}, ] Expected output: [ {'api':'test1', 'result': 0}, {'api':'test2', 'result': 1}, {'api':'test3', 'result': 0}, ]
data = [ {'api': 'test1', 'result': 0}, {'api': 'test3', 'result': 2}, {'api': 'test2', 'result': 1}, {'api': 'test3', 'result': 1}, {'api': 'test3', 'result': 0} ] def find(data): step1 = sorted(data, key=lambda k: k['result']) print('step1', step1) step2 = {} for each in step1: if each['api'] not in step2: step2[each['api']] = each print('step2', step2) step3 = list(step2.values()) print('step3', step3) print('\n') return step3 find(data) Try this, it will give you step1 [{'api': 'test1', 'result': 0}, {'api': 'test3', 'result': 0}, {'api': 'test2', 'result': 1}, {'api': 'test3', 'result': 1}, {'api': 'test3', 'result': 2}] step2 {'test1': {'api': 'test1', 'result': 0}, 'test3': {'api': 'test3', 'result': 0}, 'test2': {'api': 'test2', 'result': 1}} step3 [{'api': 'test1', 'result': 0}, {'api': 'test3', 'result': 0}, {'api': 'test2', 'result': 1}] Sort all first, then find first for each "api", and there goes your result.
17
7
65,512,500
2020-12-30
https://stackoverflow.com/questions/65512500/how-to-get-current-logging-formatter
I'm using the logging module from the python standard library and would like to obtain the current Formatter. The reason is that I'm using multiprocessing module and for each process I'd like to assign its logger another file handler to log to its own log file. When I do this in the following way logger = logging.getLogger('subprocess') log_path = 'log.txt' with open(log_path, 'a') as outfile: handler = logging.StreamHandler(outfile) logger.addHandler(handler) the messages in log.txt have no formatting at all, but I would like the message to be in the same format as my typical logging format. My typical logging setup is shown below logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s - %(process)d | %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), ) logger = logging.getLogger(__name__) Since it looks like the Formatter object is associated with the Handler object, I tried to obtain handler from the main Logger object which has the correct formatting. So I called logger.handlers but I got an empty list []. So my question is, where do I get the Formatter object which has the same format that my main logger has? For the record, I'm using python 3.8 on macOS but the code will be deployed to Linux (but still python 3.8).
Judging by the cpython source code on logging.basicConfig, it appears that the formatter object which contains your formatting string is eventually added to a handler that is passed to the root logger (see: here ). So you can obtain the handler (and therefore the formatter) from the root logger object by doing logging.root.handlers[0].formatter In particular, to achieve the subprocess logging handler in the question, you can do this instead handler = logging.StreamHandler(outfile) handler.setFormatter(logging.root.handlers[0].formatter) handler.setLevel(logging.root.level) logger.addHandler(handler) which will set your handler to the same logging format (and level as well!) as that of your usual logger object.
7
5
65,505,336
2020-12-30
https://stackoverflow.com/questions/65505336/plotly-add-trace-vs-append-trace
Is there any difference between add_trace and append_trace in Plotly? Is the latter a legacy of the former? In the Plotly.py GitHub, there are 88 markdown + 21 Python instances of add_trace and 9 markdowbn + 7 Python instances of append_trace. The latter are mainly coming from doc and packages/python/plotly/plotly/figure_factory. In the Plotly subplots documentation, there are 4 instances of append_trace while all other 52 instances are add_trace. Here is an example extracted from there: from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots(rows=3, cols=1) fig.append_trace(go.Scatter( x=[3, 4, 5], y=[1000, 1100, 1200], ), row=1, col=1) fig.append_trace(go.Scatter( x=[2, 3, 4], y=[100, 110, 120], ), row=2, col=1) fig.append_trace(go.Scatter( x=[0, 1, 2], y=[10, 11, 12] ), row=3, col=1) fig.update_layout(height=600, width=600, title_text="Stacked Subplots") fig.show() I have tried replacing the append_trace instances in this code snippets to add_trace and did not observe any apparent differences.
I don't have the technical background to explain it to you, but the official reference has the following explanation New traces can be added to a graph object figure using the add_trace() method. This method accepts a graph object trace (an instance of go.Scatter, go.Bar, etc.) and adds it to the figure. This allows you to start with an empty figure, and add traces to it sequentially. The append_trace() method does the same thing, although it does not return the figure.
15
10
65,503,864
2020-12-30
https://stackoverflow.com/questions/65503864/django-makemigrations-is-creating-migrations-for-model-with-managed-false
While Django documentation https://docs.djangoproject.com/en/3.1/ref/models/options/#managed mentions the use of managed = False field in meta is used to not create migrations I am still getting migrations when I call makemigrations. This is the meta of the model: class FieldOpsBooking(models.Model): . . class Meta: managed = False db_table = 'field_ops_booking' And I am getting this after makemigrations python manage.py makemigrations Migrations for 'user_analysis': user_analysis/migrations/0001_initial.py - Create model FieldOpsBooking - Create model RewardManagementLeads Migrations for 'od_engagement': od_engagement/migrations/0001_initial.py - Create model NormalisedTonnage And it creates 0001_initial.py file with all migrations to apply as well. Any help is appreciated
I checked my own projetcs with models having managed=False: YES there is an entry in migrations file like: operations = [ migrations.CreateModel( name='xyz', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'db_table': 'xyz_table', 'managed': False, }, ), BUT: this will not create a new table on database level when you execute "makemigration". Sorry if a insiste but your original solution was absolutely correct!! this is from django documentation about abtract base class: " ... since it is an abstract base class. .... and cannot be instantiated or saved directly."
12
14
65,501,827
2020-12-30
https://stackoverflow.com/questions/65501827/python-avoid-ugly-nested-for-loop
I'm new to python programming. I have tried a lot to avoid these nested for loops, but no success. My data input like: [ { "province_id": "1", "name": "HCM", "districts": [ { "district_id": "1", "name": "Thu Duc", "wards": [ { "ward_id": "1", "name": "Linh Trung" }, { "ward_id": "2", "name": "Linh Chieu" } ] }, { "district_id": "2", "name": "Quan 9", "wards": [ { "ward_id": "3", "name": "Hiep Phu" }, { "ward_id": "4", "name": "Long Binh" } ] } ] }, { "province_id": "2", "name": "Binh Duong", "districts": [ { "district_id": "3", "name": "Di An", "wards": [ { "ward_id": "5", "name": "Dong Hoa" }, { "ward_id": "6", "name": "Di An" } ] }, { "district_id": "4", "name": "Thu Dau Mot", "wards": [ { "ward_id": "7", "name": "Hiep Thanh" }, { "ward_id": "8", "name": "Hiep An" } ] } ] } ] And my code is: for province in data: for district in province['districts']: for ward in district['wards']: # Excute my function print('{}, {}, {}'.format(ward['name'], district['name'], province['name'])) Output Linh Trung, Thu Duc, HCM Linh Chieu, Thu Duc, HCM Hiep Phu, Quan 9, HCM ... Even though my code is working it looks pretty ugly. How can I avoid these nested for loops?
Your data structure is naturally nested, but one option you have for neatening your code is to write a generator function for iterating over it: def all_wards(data): for province in data: for district in province['districts']: for ward in district['wards']: yield province, district, ward This function has the same triply-nested loop in it as you currently have, but everywhere else in your code, you can now iterate over the data structure with a single non-nested loop: for province, district, ward in all_wards(data): print('{}, {}, {}'.format(ward['name'], district['name'], province['name'])) If you prefer to avoid having too much indentation, here's an equivalent way to write the function, similar to @adarian's answer but without creating a temporary list: def all_wards(data): return ( province, district, ward for province in data for district in province['districts'] for ward in district['wards'] )
6
9
65,439,214
2020-12-24
https://stackoverflow.com/questions/65439214/what-are-the-differences-between-python-playwright-sync-vs-async-apis
I've started learning playwright-python and the package playwright has the two submodules async_api and sync_api. However I could not find any deeper description or discussion on their respective benefits and drawbacks. From their names I assume that the synchronous API calls are blocking and the asynchronous ones run in the background? Are they different in their capabilities, i.e. are there scenarios in which the sync_api cannot accomplish something you can do using the async_api (or vice versa)?
The sync_api is simply a wrapper around the async_api that abstracts asyncio usage away from you. As such, the capabilities are largely the same, but the async_api may afford some more flexibility in complex scenarios. I would suggest using async in case you need the flexibility in the future, or sync for ease of use.
10
12
65,421,561
2020-12-23
https://stackoverflow.com/questions/65421561/how-can-i-check-if-an-user-is-superuser-in-django
I'm listing registered users on a ListView page and I'm trying to show if user is superuser or not. My main user is created with python manage.py createsuperuser command and I'm sure it is a superuser beacuse I've checked from admin panel too. When I try to print if it is superuser or not my code always shows a False output. Here are my codes: views.py @method_decorator(staff_member_required, name='dispatch') class Uyeler(ListView): model = User paginate_by = 40 ordering = ['-pk'] template_name = "panel/uyeler.html" and in template file: {% for obj in object_list %} {% if obj.is_superuser %} SuperUser {% else %} Not SuperUser {{ obj.is_superuser }} {% endif %} {% endfor %} And my html output is "Not SuperUser False" for all users including my superuser account. Any ideas?
I tried in my code and it's working maybe there's issue in your data this is how my code looks like views.py def user_detail(request): user_detail = CustomUser.objects.filter(id=id) return(request, 'user_datail.html', {'user_detail': user_detail}) user_datail.html {% for i in user_detail %} {% if i.is_superuser %} <td class="text-center"><span class="btn btn-success">You</span> </td> {% else %} <td class="text-center"><span class="btn btn-info">Agent</span> </td> {% endif %} {% endfor %} output
10
2
65,447,992
2020-12-25
https://stackoverflow.com/questions/65447992/pytorch-how-to-apply-the-same-random-transformation-to-multiple-image
I am writing a simple transformation for a dataset which contains many pairs of images. As a data augmentation, I want to apply some random transformation for each pair but the images in that pair should be transformed in the same way. For example, given a pair of two images A and B, if A is flipped horizontally, B must be flipped horizontally as A. Then the next pair C and D should be differently transformed from A and B but C and D are transformed in the same way. I am trying that in the way below import random import numpy as np import torchvision.transforms as transforms from PIL import Image img_a = Image.open("sample_ajpg") # note that two images have the same size img_b = Image.open("sample_b.png") img_c, img_d = Image.open("sample_c.jpg"), Image.open("sample_d.png") transform = transforms.RandomChoice( [transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip()] ) random.seed(0) display(transform(img_a)) display(transform(img_b)) random.seed(1) display(transform(img_c)) display(transform(img_d)) Yet、 the above code does not choose the same transformation and as I tested, it is dependent on the number of times transform is called. Is there any way to force transforms.RandomChoice to use the same transform when specified?
Usually a workaround is to apply the transform on the first image, retrieve the parameters of that transform, then apply with a deterministic transform with those parameters on the remaining images. However, here RandomChoice does not provide an API to get the parameters of the applied transform since it involves a variable number of transforms. In those cases, I usually implement an overwrite to the original function. Looking at the torchvision implementation, it's as simple as: class RandomChoice(RandomTransforms): def __call__(self, img): t = random.choice(self.transforms) return t(img) Here are two possible solutions. You can either sample from the transform list on __init__ instead of on __call__: import random import torchvision.transforms as T class RandomChoice(torch.nn.Module): def __init__(self): super().__init__() self.t = random.choice(self.transforms) def __call__(self, img): return self.t(img) So you can do: transform = RandomChoice([ T.RandomHorizontalFlip(), T.RandomVerticalFlip() ]) display(transform(img_a)) # both img_a and img_b will display(transform(img_b)) # have the same transform transform = RandomChoice([ T.RandomHorizontalFlip(), T.RandomVerticalFlip() ]) display(transform(img_c)) # both img_c and img_d will display(transform(img_d)) # have the same transform Or better yet, transform the images in batch: import random import torchvision.transforms as T class RandomChoice(torch.nn.Module): def __init__(self, transforms): super().__init__() self.transforms = transforms def __call__(self, imgs): t = random.choice(self.transforms) return [t(img) for img in imgs] Which allows to do: transform = RandomChoice([ T.RandomHorizontalFlip(), T.RandomVerticalFlip() ]) img_at, img_bt = transform([img_a, img_b]) display(img_at) # both img_a and img_b will display(img_bt) # have the same transform img_ct, img_dt = transform([img_c, img_d]) display(img_ct) # both img_c and img_d will display(img_dt) # have the same transform
15
11
65,424,771
2020-12-23
https://stackoverflow.com/questions/65424771/how-to-convert-one-hot-vector-to-label-index-and-back-in-pytorch
How to transform vectors of labels to one-hot encoding and back in Pytorch? The solution to the question was copied to here after having to go through the entire forum discussion, instead of just finding an easy one from googling.
From the Pytorch forums import torch import numpy as np labels = torch.randint(0, 10, (10,)) # labels --> one-hot one_hot = torch.nn.functional.one_hot(labels) # one-hot --> labels labels_again = torch.argmax(one_hot, dim=1) np.testing.assert_equals(labels.numpy(), labels_again.numpy())
17
24
65,464,463
2020-12-27
https://stackoverflow.com/questions/65464463/importerror-cannot-import-name-keras-tensor-from-tensorflow-python-keras-eng
I'm getting this error while loading the tensorflow addons library import tensorflow_addons as tfa ImportError: cannot import name 'keras_tensor' from 'tensorflow.python.keras.engine'
This error is because you have incompatibility issues between your TensorFlow, Python and tensorflow-addons. Uninstall the tensorflow-addons and install the version based on the table below. Refer the Github repo for more information.
10
41
65,446,464
2020-12-25
https://stackoverflow.com/questions/65446464/how-to-convert-a-video-in-numpy-array
Program to convert a video file into a NumPy array and vice-versa. I had searched for many search engines but was unable to find the answer.
There are multiple libraries people use for this (i.e. PyAV, decord, opencv); I personally use Python OpenCV for this a lot (mostly with PyTorch, but it's a similar principle), so I'll speak about my experience there. You can use cv2.VideoCapture to load a video file into a numpy array; in theory, you can also use cv2.VideoWriter to write it back, but in practice, I've had a hard time getting that to work in my own projects. Video to Numpy Array tl;dr: Create a cv2.VideoCapture wrapper; iteratively load images (i.e. frames) from the video. frames = [] path = "/path/to/my/video/file.mp4" cap = cv2.VideoCapture(path) ret = True while ret: ret, img = cap.read() # read one frame from the 'capture' object; img is (H, W, C) if ret: frames.append(img) video = np.stack(frames, axis=0) # dimensions (T, H, W, C) Do note that the images will be returned in BGR channel format rather than the more common RGB; if you need to convert it to the RGB colorspace, img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) will be sufficient. Numpy Array to Video In theory, the examples I've seen for using cv2.VideoWriter go something like # let `video` be an array with dimensionality (T, H, W, C) num_frames, height, width, _ = video.shape filename = "/path/where/video/will/be/saved.mp4" codec_id = "mp4v" # ID for a video codec. fourcc = cv2.VideoWriter_fourcc(*codec_id) out = cv2.VideoWriter(filename, fourcc=fourcc, fps=20, frameSize=(width, height)) for frame in np.split(video, num_frames, axis=0): out.write(frame) You can also save the frames to temporary images (there exist many np.ndarray -> image pipelines; I personally use Pillow), then use ffmpeg (a command-line utility) to encode the frames into a video file. This takes up significantly more space though, and I use this method when I need to inspect the individual frames of my video array (in that case, I use ffmpeg, but that's a different conversation). And on another note -- you may want to change the codec_id variable depending on how you want to encode the video (if this means nothing to you, don't worry -- it probably won't matter for your application); this is simply a four-byte code used to identify the video codec used to generate the video (see this page; availability may vary by platform(. H.264 is the most common one in use today AFAIK, which is given by code "H264" or "X264", but I've had trouble getting this to work with OpenCV (more details here); however, the array -> images -> video file approach works seamlessly with ffmpeg from the command line.
6
8
65,498,782
2020-12-29
https://stackoverflow.com/questions/65498782/how-to-dump-confusion-matrix-using-tensorboard-logger-in-pytorch-lightning
The official doc only states >>> from pytorch_lightning.metrics import ConfusionMatrix >>> target = torch.tensor([1, 1, 0, 0]) >>> preds = torch.tensor([0, 1, 0, 0]) >>> confmat = ConfusionMatrix(num_classes=2) >>> confmat(preds, target) This doesn't show how to use the metric with the framework. My attempt (methods are not complete and only show relevant parts): def __init__(...): self.val_confusion = pl.metrics.classification.ConfusionMatrix(num_classes=self._config.n_clusters) def validation_step(self, batch, batch_index): ... log_probs = self.forward(orig_batch) loss = self._criterion(log_probs, label_batch) self.val_confusion.update(log_probs, label_batch) self.log('validation_confusion_step', self.val_confusion, on_step=True, on_epoch=False) def validation_step_end(self, outputs): return outputs def validation_epoch_end(self, outs): self.log('validation_confusion_epoch', self.val_confusion.compute()) After the 0th epoch, this gives Traceback (most recent call last): File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\trainer.py", line 521, in train self.train_loop.run_training_epoch() File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\training_loop.py", line 588, in run_training_epoch self.trainer.run_evaluation(test_mode=False) File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\trainer.py", line 613, in run_evaluation self.evaluation_loop.log_evaluation_step_metrics(output, batch_idx) File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\evaluation_loop.py", line 346, in log_evaluation_step_metrics self.__log_result_step_metrics(step_log_metrics, step_pbar_metrics, batch_idx) File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\evaluation_loop.py", line 350, in __log_result_step_metrics cached_batch_pbar_metrics, cached_batch_log_metrics = cached_results.update_logger_connector() File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 378, in update_logger_connector batch_log_metrics = self.get_latest_batch_log_metrics() File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 418, in get_latest_batch_log_metrics batch_log_metrics = self.run_batch_from_func_name("get_batch_log_metrics") File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 414, in run_batch_from_func_name results = [func(include_forked_originals=False) for func in results] File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 414, in <listcomp> results = [func(include_forked_originals=False) for func in results] File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 122, in get_batch_log_metrics return self.run_latest_batch_metrics_with_func_name("get_batch_log_metrics", *args, **kwargs) File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 115, in run_latest_batch_metrics_with_func_name for dl_idx in range(self.num_dataloaders) File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 115, in <listcomp> for dl_idx in range(self.num_dataloaders) File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\trainer\connectors\logger_connector\epoch_result_store.py", line 100, in get_latest_from_func_name results.update(func(*args, add_dataloader_idx=add_dataloader_idx, **kwargs)) File "C:\code\EPMD\Kodex\Templates\Testing\venv\lib\site-packages\pytorch_lightning\core\step_result.py", line 298, in get_batch_log_metrics result[dl_key] = self[k]._forward_cache.detach() AttributeError: 'NoneType' object has no attribute 'detach' It does pass the sanity validation check before training. The failure happens on the return in validation_step_end. Makes little sense to me. The exact same method of using mertics works fine with accuracy. How to get a correct confusion matrix?
Updated answer, August 2022 class IntHandler: def legend_artist(self, legend, orig_handle, fontsize, handlebox): x0, y0 = handlebox.xdescent, handlebox.ydescent text = plt.matplotlib.text.Text(x0, y0, str(orig_handle)) handlebox.add_artist(text) return text class LightningClassifier(LightningModule): ... def _common_step(self, batch, batch_nb, stage: str): assert stage in ("train", "val", "test") logger = self._logger augmented_image, labels = batch outputs, aux_outputs = self(augmented_image) loss = self._criterion(outputs, labels) return outputs, labels, loss def validation_step(self, batch, batch_nb): stage = "val" outputs, labels, loss = self._common_step(batch, batch_nb, stage=stage) self._common_log(loss, stage=stage) return {"loss": loss, "outputs": outputs, "labels": labels} def validation_epoch_end(self, outs): # see https://github.com/Lightning-AI/metrics/blob/ff61c482e5157b43e647565fa0020a4ead6e9d61/docs/source/pages/lightning.rst # each forward pass, thus leading to wrong accumulation. In practice do the following: tb = self.logger.experiment # noqa outputs = torch.cat([tmp['outputs'] for tmp in outs]) labels = torch.cat([tmp['labels'] for tmp in outs]) confusion = torchmetrics.ConfusionMatrix(num_classes=self.n_labels).to(outputs.get_device()) confusion(outputs, labels) computed_confusion = confusion.compute().detach().cpu().numpy().astype(int) # confusion matrix df_cm = pd.DataFrame( computed_confusion, index=self._label_ind_by_names.values(), columns=self._label_ind_by_names.values(), ) fig, ax = plt.subplots(figsize=(10, 5)) fig.subplots_adjust(left=0.05, right=.65) sn.set(font_scale=1.2) sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}, fmt='d', ax=ax) ax.legend( self._label_ind_by_names.values(), self._label_ind_by_names.keys(), handler_map={int: IntHandler()}, loc='upper left', bbox_to_anchor=(1.2, 1) ) buf = io.BytesIO() plt.savefig(buf, format='jpeg', bbox_inches='tight') buf.seek(0) im = Image.open(buf) im = torchvision.transforms.ToTensor()(im) tb.add_image("val_confusion_matrix", im, global_step=self.current_epoch) output: Also based on this
9
5
65,468,026
2020-12-27
https://stackoverflow.com/questions/65468026/norm-ppf-vs-norm-cdf-in-pythons-scipy-stats
so i have pasted my complete code for your reference, i want to know what's the use of ppf and cdf here? can you explain it? i did some research and found out that ppf(percent point function) is an inverse of CDF(comulative distribution function) if they really are, shouldn't this code work if i replaced ppf and cdf as 1/cdf and 1/ppf respectively? please explain this to me, the difference between the two. and how to and when to use which this is, btw, hypothesis testing. and sorry for so many comments, just a habit of explaining everything for my future reference.(do point me out if any of my comments is wrong regarding the same) ball_bearing_radius = [2.99, 2.99, 2.70, 2.92, 2.88, 2.92, 2.82, 2.83, 3.06, 2.85] import numpy as np from math import sqrt from scipy.stats import norm # h1 : u != U_0 # h0 : u = u_0 #case study : ball bearing example, claim is that radius = 3, do hypothesis testing mu_0 = 3 sigma = 0.1 #collect sample sample = ball_bearing_radius #compute mean mean = np.mean(sample) #compute n n = len(sample) #compute test statistic z = (mean - mu_0) /(sigma/sqrt(n)) #set alpha a = 0.01 #------------------------- #calculate the z_a/2, by using percent point function of the norm of scipy #ppf = percent point function, inverse of CDF(comulative distribution function) #also, CDF = pr(X<=x), i.e., probability to the left of the distribution z_critical = norm.ppf(1-a/2) #this returns a value for which the probab to the left is 0.975 p_value = 2*(1 - norm.cdf(np.abs(z))) p_value = float("{:.4f}".format(p_value)) print('z : ',z) print('\nz_critical :', z_critical) print('\nmean :', mean, "\n\n") #test the hypothesis if (np.abs(z) > z_critical): print("\nREJECT THE NULL HYPOTHESIS : \n p-value = ", p_value, "\n Alpha = ", a ) else: print("CANNOT REJECT THE NULL HYPOTHESIS. NOT ENOUGH EVIDENCE TO REJECT IT: \n p-value = ", p_value, "\n Alpha = ", a )
The .cdf() function calculates the probability for a given normal distribution value, while the .ppf() function calculates the normal distribution value for which a given probability is the required value. These are inverse of each other in this particular sense. To illustrate this calculation, check the below sample code. from scipy.stats import norm print(norm.ppf(0.95)) print(norm.cdf(1.6448536269514722)) This image with the code above should make it clear for you. Thanks!
8
23
65,445,174
2020-12-25
https://stackoverflow.com/questions/65445174/what-is-the-difference-between-an-embedding-layer-with-a-bias-immediately-afterw
I am reading the "Deep Learning for Coders with fastai & PyTorch" book. I'm still a bit confused as to what the Embedding module does. It seems like a short and simple network, except I can't seem to wrap my head around what Embedding does differently than Linear without a bias. I know it does some faster computational version of a dot product where one of the matrices is a one-hot encoded matrix and the other is the embedding matrix. It does this to in effect select a piece of data? Please point out where I am wrong. Here is one of the simple networks shown in the book. class DotProduct(Module): def __init__(self, n_users, n_movies, n_factors): self.user_factors = Embedding(n_users, n_factors) self.movie_factors = Embedding(n_movies, n_factors) def forward(self, x): users = self.user_factors(x[:,0]) movies = self.movie_factors(x[:,1]) return (users * movies).sum(dim=1)
Embedding [...] what Embedding does differently than Linear without a bias. Essentially everything. torch.nn.Embedding is a lookup table; it works the same as torch.Tensor but with a few twists (like possibility to use sparse embedding or default value at specified index). For example: import torch embedding = torch.nn.Embedding(3, 4) print(embedding.weight) print(embedding(torch.tensor([1]))) Would output: Parameter containing: tensor([[ 0.1420, -0.1886, 0.6524, 0.3079], [ 0.2620, 0.4661, 0.7936, -1.6946], [ 0.0931, 0.3512, 0.3210, -0.5828]], requires_grad=True) tensor([[ 0.2620, 0.4661, 0.7936, -1.6946]], grad_fn=<EmbeddingBackward>) So we took the first row of the embedding. It does nothing more than that. Where is it used? Usually when we want to encode some meaning (like word2vec) for each row (e.g. words being close semantically are close in euclidean space) and possibly train them. Linear torch.nn.Linear (without bias) is also a torch.Tensor (weight) but it does operation on it (and the input) which is essentially: output = input.matmul(weight.t()) every time you call the layer (see source code and functional definition of this layer). Code snippet The layer in your code snippet does this: creates two lookup tables in __init__ the layer is called with input of shape (batch_size, 2): first column contains indices of user embeddings second column contains indices of movie embeddings these embeddings are multiplied and summed returning (batch_size,) (so it's different from nn.Linear which would return (batch_size, out_features) and perform dot product instead of element-wise multiplication followed by summation like here) This is probably used to train both representations (of users and movies) for some recommender-like system. Other stuff I know it does some faster computational version of a dot product where one of the matrices is a one-hot encoded matrix and the other is the embedding matrix. No, it doesn't. torch.nn.Embedding can be one hot encoded and might also be sparse, but depending on the algorithms (and whether those support sparsity) there might be performance boost or not.
16
23
65,492,317
2020-12-29
https://stackoverflow.com/questions/65492317/copy-file-in-python-with-copy-on-write-cow
My filesystem (FS) (ZFS specifically) supports copy-on-write (COW), i.e. a copy (if done right) is a very cheap constant operation, and does not actually copy the underlying content. The content is copied only once I write/modify the new file. Actually, I just found out, ZFS-on-Linux actually has not implemented that for userspace yet (right?). But e.g. BTRFS or XFS has. (See here, here, here, here.) For the (GNU) cp utility, you would pass --reflink=always option (see here.) cp calls ioctl (dest_fd, FICLONE, src_fd) (see here, here). How would I get this behavior (if possible) in Python? I assume that "zero-copy" (e.g. here via os.sendfile) would not result in such behavior, right? Because looking at shutils _fastcopy_sendfile implementation (here), it is still a loop around os.sendfile using some custom byte count (supposed to be the block size, max(os.fstat(infd).st_size, 2 ** 23)). Or would it? The COW, is this on a file level, or block level? If possible, I want this to be generic and cross-platform as well, although my question here is somewhat Linux focused. A related question specifically about Mac seems to be this. The MacOSX cp has the -c option to clone a file.
While searching further, I actually found the answer, and a related issue report. Issue 37157 (shutil: add reflink=False to file copy functions to control clone/CoW copies (use copy_file_range)) is exactly about that, which would use FICLONE/FICLONERANGE on Linux. So I assume that shutil would support this in upcoming Python versions (maybe starting with Python 3.9?). There is os.copy_file_range (since Python 3.8), which wraps copy_file_range (Linux). However, according to issue 37159 (Use copy_file_range() in shutil.copyfile() (server-side copy)), Giampaolo Rodola: Nope, [copy_file_range] doesn't [support CoW] (see man page). We can simply use FICLONE (cp does the same). However, I'm not sure this is correct, as the copy_file_range man page says: copy_file_range() gives filesystems an opportunity to implement "copy acceleration" techniques, such as the use of reflinks (i.e., two or more inodes that share pointers to the same copy- on-write disk blocks) or server-side-copy (in the case of NFS). Issue 26826 (Expose new copy_file_range() syscall in os module) has this comment by Giampaolo Rodola: I think data deduplication / CoW / reflink copy is better implemented via FICLONE. "cp --reflink" uses it, I presume because it's older than copy_file_range(). ... Again, as noted already in the question, this does not work on ZFS yet, see this issue.
5
3
65,461,962
2020-12-27
https://stackoverflow.com/questions/65461962/tkinter-ttk-see-custom-theme-settings
After using ttk.Style().theme_create('name', settings={}) is it possible to see the settings of that theme? The reason I'm asking is that when I'm creating a new theme and I add ttk.Notebook(root) to my code, the tabs have rounded corners, which I do not want. Here is an example: import tkinter as tk import tkinter.ttk as ttk root = tk.Tk() root.title("Tab Example") root.geometry('270x270') background = '#ffffff' background_dark = '#f2f2f2' style = ttk.Style() style.theme_create('white', settings={ 'TLabel': {'configure': {'background': background}}, 'TFrame': {'configure': {'background': background}}, 'TNotebook': { 'configure': {'background': background_dark, 'tabmargins': [0, 7, 2, 0], 'padding': [7, 2]}}, 'TNotebook.Tab': { 'configure': {'background': background_dark, 'padding': [7, 2], 'focuscolor': 'clear'}, 'map': {'background': [('selected', background)]}}}) style.theme_use('white') tab = ttk.Notebook(root) tab1 = ttk.Frame(tab) tab2 = ttk.Frame(tab) tab.add(tab1, text='Tab 1') tab.add(tab2, text='Tab 2') tab.pack(expand=1, fill="both") ttk.Label(tab1, text="example").pack(padx=36, pady=36) ttk.Label(tab2, text="example 2").pack(padx=36, pady=36) root.mainloop() If you remove style.theme_create() / style.theme_use() then the tabs no longer have rounded corners so the program must be adding that style in by default. If there isn't a way to see the theme settings (can't seem to find it in the docs) is there a list of possible settings that I can use? Something specifically for tab borders? On that note, there's a similar question, Is there a Tkinter/ttk style reference? however the first link in the provided answer doesn't list anything for border corners or border styles under ttk::notebook while the second link is unresponsive. EDIT Expanding upon Atlas435's answer, style_name = ttk.Notebook(None).winfo_class() # print(style_name) -> 'TNotebook' print(style.layout('TNotebook')) # -> [('Notebook.client', {'sticky': 'nswe'})] print(style.element_options('Notebook.client')) # -> ('borderwidth', 'background') Except for 'background', I'm not able to see the names of the custom settings I used above for 'TNotebook': style.theme_create('white', settings={ 'TNotebook': {'configure': {'background': background_dark, 'tabmargins': [0, 7, 2, 0], 'padding': [7, 2]}}}) If I instead do this, I get closer to what I'm looking for but still not quite: print(style.layout('Tab')) # -> [('Notebook.tab', {'sticky': 'nswe', 'children': [('Notebook.padding', {'sticky': 'nswe', 'children': [('Notebook.label', {'sticky': 'nswe'})]})]})] print(style.element_options('Notebook.tab')) # -> ('borderwidth', 'background') Cycling through the other element_options (Notebook.padding and Notebook.label) doesn't provide the values I'm looking for either :( EDIT 2 Some styling options aren't listed anywhere including the Tcl/Tk docs. An example of this is 'focuscolor' for 'TNotebook.Tab' which changes the color of the dashed lines around the Tab when it is in focus. Another example is when using ttk.Style().theme_use('default') or .theme_use('classic'), the Tab's in Notebook have rounded edges. If you use .theme_use('clam') or .theme_use('vista'), the Tab's in Notebook don't have rounded edges. I'm unable to find that style option in any documentation, and I cannot get it to print through the program (see above Edit section). For now I'm accepting the current best answer (Atlas435) for helping me come to this conclusion. A temporary solution for anyone else stumbling upon this could be to set either 'clam' or 'vista' as a parent when using ttk.Style().theme_create() or to create a picture that looks like a Tab with the styling you want and use tab.add(tab1, image=img) FINAL A full list is available, check out Atlas 435's answer
Offical list of all options by ttk finally found a list that includes all coloration options to style with ttk. https://wiki.tcl-lang.org/page/Changing+Widget+Colors ttk.Button ttk::style configure TButton -background color ttk::style configure TButton -foreground color ttk::style configure TButton -font namedfont ttk::style configure TButton -focuscolor color ttk::style map TButton -background \ [list active color disabled color readonly color] ttk::style map TButton -foreground \ [list active color disabled color readonly color] ttk::style configure TButton -bordercolor color ttk::style configure TButton -lightcolor color ttk::style configure TButton -darkcolor color ttk.Checkbutton ttk::style configure TCheckbutton -background color ttk::style configure TCheckbutton -foreground color ttk::style configure TCheckbutton -font namedfont ttk::style map TCheckbutton -background \ [list active color disabled color readonly color] ttk::style map TCheckbutton -foreground \ [list active color disabled color readonly color] ttk::style configure TCheckbutton -indicatorcolor color ttk::style map TCheckbutton -indicatorcolor \ [list selected color pressed color] ttk::style configure TCheckbutton -indicatorrelief relief ttk::style configure TCheckbutton -indicatormargin padding ttk::style configure TCheckbutton -indicatordiameter size ttk::style configure TCheckbutton -borderwidth size ttk::style configure TCheckbutton -focuscolor color ttk.Combobox ttk::style configure TCombobox -background color ttk::style configure TCombobox -foreground color ttk::style configure TCombobox -fieldbackground color ttk::style configure TCombobox -darkcolor color ttk::style configure TCombobox -lightcolor color ttk::style configure TCombobox -selectbackground color ttk::style configure TCombobox -selectforeground color ttk::style configure TCombobox -bordercolor color ttk::style configure TCombobox -insertcolor color ttk::style configure TCombobox -insertwidth color ttk::style configure TCombobox -arrowsize size ttk::style configure TCombobox -arrowcolor color ttk::style map TCombobox -background \ [list disabled color readonly color] ttk::style map TCombobox -foreground \ [list disabled color readonly color] ttk::style map TCombobox -fieldbackground \ [list disabled color readonly color] option add *TCombobox*Listbox.background color option add *TCombobox*Listbox.foreground color option add *TCombobox*Listbox.selectBackground color option add *TCombobox*Listbox.selectForeground color ttk.Entry ttk::style configure TEntry -background color ttk::style configure TEntry -foreground color ttk::style configure TEntry -fieldbackground color ttk::style configure TEntry -selectbackground color ttk::style configure TEntry -selectforeground color ttk::style configure TEntry -bordercolor color ttk::style configure TEntry -lightcolor color ttk::style configure TEntry -insertcolor color ttk::style configure TEntry -insertwidth color ttk::style map TEntry -background \ [list disabled color readonly color] ttk::style map TEntry -foreground \ [list disabled color readonly color] ttk::style map TEntry -fieldbackground \ [list disabled color readonly color] .entry configure -font namedfont ttk.Labelframe ttk::style configure TLabelframe -background color ttk::style configure TLabelframe -bordercolor color ttk::style configure TLabelframe -lightcolor color ttk::style configure TLabelframe -darkcolor color ttk::style configure TLabelframe.Label -background color ttk::style configure TLabelframe.Label -foreground color ttk::style configure TLabelframe.Label -font namedfont ttk.Listbox .listbox configure -background color .listbox configure -foreground color .listbox configure -disabledforeground color .listbox configure -selectbackground color .listbox configure -selectforeground color .listbox configure -font namedfont .listbox configure -borderwidth size .listbox configure -relief relief .listbox configure -highlightthickness size .listbox configure -highlightcolor color .listbox configure -highlightbackground color menu .menu configure -background color .menu configure -foreground color .menu configure -activebackground color .menu configure -activeforeground color .menu configure -disabledforeground color .menu configure -font namedfont .menu configure -selectcolor color .menu configure -activeborderwidth size .menu configure -relief relief ttk.Menubutton ttk::style configure TMenubutton -background color ttk::style configure TMenubutton -foreground color ttk::style configure TMenubutton -font namedfont ttk::style configure TMenubutton -arrowcolor color ttk::style map TMenubutton -background \ [list active color disabled color] ttk::style map TMenubutton -foreground \ [list active color disabled color] ttk::style map TMenubutton -arrowcolor \ [list active color disabled color] ttk.Notebook ttk::style configure TNotebook -background color ttk::style configure TNotebook -bordercolor color ttk::style configure TNotebook -darkcolor color ttk::style configure TNotebook -lightcolor color ttk::style configure TNotebook.Tab -background color ttk::style configure TNotebook.Tab -foreground color ttk::style configure TNotebook.Tab -bordercolor color ttk::style configure TNotebook -focuscolor color ttk::style configure TNotebook -focusthickness size ttk::style configure TNotebook.Tab -focuscolor color ttk::style map TNotebook.Tab -background \ [list selected color active color disabled color] ttk::style map TNotebook.Tab -foreground \ [list selected color active color disabled color] ttk::style map TNotebook.Tab -lightcolor \ [list selected color {} color] ttk::style configure TNotebook.Tab -font namedfont ttk::style map TNotebook.Tab -font \ [list selected namedfont active namedfont disabled namedfont] ttk.Panedwindow ttk::style configure TPanedwindow -background color ttk::style configure Sash -sashthickness 5 ttk::style configure Sash -sashrelief relief ttk::style configure Sash -sashpad 2 ttk::style configure Sash -handlesize 5 ttk::style configure Sash -handlepad 5 ttk::style configure Sash -background color ttk::style configure Sash -lightcolor color ttk::style configure Sash -bordercolor color ttk.Progressbar ttk::style configure TProgressbar -background color ttk::style configure TProgressbar -troughcolor color ttk::style configure TProgressbar -lightcolor color ttk::style configure TProgressbar -darkcolor color ttk::style configure TProgressbar -bordercolor color ttk::style configure TProgressbar -barsize size ttk::style configure TProgressbar -pbarrelief relief ttk::style configure TProgressbar -borderwidth size ttk.radiobutton ttk::style configure TRadiobutton -background color ttk::style configure TRadiobutton -foreground color ttk::style configure TRadiobutton -font namedfont ttk::style map TRadiobutton -background \ [list active color disabled color readonly color] ttk::style map TRadiobutton -foreground \ [list active color disabled color readonly color] ttk::style configure TRadiobutton -indicatorcolor color ttk::style map TRadiobutton -indicatorcolor \ [list selected color pressed color] ttk.Scale ttk::style configure TScale -background color ttk::style configure TScale -troughcolor color ttk::style map TScale -background \ [list active color] ttk::style configure TScale -troughrelief relief ttk::style configure TScale -sliderrelief relief ttk::style configure TScale -sliderlength size ttk::style configure TScale -sliderthickness size ttk::style configure TScale -lightcolor color ttk::style configure TScale -darkcolor color ttk::style configure TScale -bordercolor color ttk.Scrollbar ttk::style configure TScrollbar -background color ttk::style configure TScrollbar -troughcolor color ttk::style configure TScrollbar -arrowcolor color ttk::style configure TScrollbar -bordercolor color ttk::style configure TScrollbar -darkcolor color ttk::style configure TScrollbar -lightcolor color ttk::style configure TScrollbar -sliderrelief relief ttk::style map TScrollbar -background \ [list active color disabled color] ttk::style map TScrollbar -foreground \ [list active color disabled color] ttk::style map TScrollbar -arrowcolor \ [list disabled color] ttk.Seperator ttk::style configure TSeparator -background color ttk.Sizegrip ttk::style configure TSizegrip -background color ttk.Spinbox ttk::style configure TSpinbox -background color ttk::style configure TSpinbox -foreground color ttk::style configure TSpinbox -darkcolor color ttk::style configure TSpinbox -lightcolor color ttk::style configure TSpinbox -fieldbackground color ttk::style configure TSpinbox -selectbackground color ttk::style configure TSpinbox -selectforeground color ttk::style configure TSpinbox -arrowsize size ttk::style configure TSpinbox -arrowcolor color ttk::style configure TSpinbox -bordercolor color ttk::style configure TSpinbox -insertcolor color ttk::style configure TSpinbox -insertwidth color ttk::style map TSpinbox -background \ [list active color disabled color readonly color] ttk::style map TSpinbox -foreground \ [list active color disabled color readonly color] ttk::style map TSpinbox -fieldbackground \ [list active color disabled color readonly color] ttk::style map TScrollbar -arrowcolor \ [list disabled color] .spinbox configure -font namedfont ttk.Text .text configure -background color .text configure -foreground color .text configure -selectforeground color .text configure -selectbackground color .text configure -inactiveselectbackground color .text configure -insertbackground color .text configure -font namedfont .text configure -relief relief .text configure -borderwidth size .text configure -highlightcolor color .text configure -highlightthickness size .text configure -highlightbackground color ttk.Treeview ttk::style configure Treeview -background color ttk::style configure Treeview -foreground color ttk::style configure Treeview -font namedfont ttk::style configure Treeview -fieldbackground color ttk::style map Treeview -background \ [list selected color] ttk::style map Treeview -foreground \ [list selected color] ttk::style configure Treeview -rowheight [expr {[font metrics namedfont -linespace] + 2}] ttk::style configure Heading -font namedfont ttk::style configure Heading -background color ttk::style configure Heading -foreground color ttk::style configure Heading -padding padding ttk::style configure Item -foreground color ttk::style configure Item -focuscolor color
6
8
65,491,184
2020-12-29
https://stackoverflow.com/questions/65491184/ratelimit-in-fastapi
How to ratelimit API endpoint request in Fastapi application ? I need to ratelimit API call 5 request per second per user and exceeding that limit blocks that particular user for 60 seconds. In main.py def get_application() -> FastAPI: application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION) application.add_event_handler( "startup", create_start_app_handler(application)) application.add_event_handler( "shutdown", create_stop_app_handler(application)) return application app = get_application() In events.py def create_start_app_handler(app: FastAPI) -> Callable: async def start_app() -> None: redis = await aioredis.create_redis_pool("redis://localhost:8080") FastAPILimiter.init(redis) return start_app In endpoint @router.post('/user', tags=["user"], name="user:user", dependencies=[Depends(RateLimiter(times=5, seconds=60))]) ***code**** Run from this file test.py. import uvicorn from app.main import app if __name__ == "__main__": uvicorn.run("test:app", host="0.0.0.0", port=8000, reload=True) I edited as above but got following error. File "****ite-packages\starlette\routing.py", line 526, in lifespan async for item in self.lifespan_context(app): File "****site-packages\starlette\routing.py", line 467, in default_lifespan await self.startup() File "****site-packages\starlette\routing.py", line 502, in startup await handler() File "****app\core\services\events.py", line 15, in start_app redis = await aioredis.create_redis_pool("redis://localhost:8080") File "****\site-packages\aioredis\commands\__init__.py", line 188, in create_redis_pool pool = await create_pool(address, db=db, File "****site-packages\aioredis\pool.py", line 58, in create_pool await pool._fill_free(override_min=False) File "C****\site-packages\aioredis\pool.py", line 383, in _fill_free conn = await self._create_new_connection(self._address) File "****site-packages\aioredis\connection.py", line 111, in create_connection reader, writer = await asyncio.wait_for(open_connection( File "****\asyncio\tasks.py", line 455, in wait_for return await fut File "****\site-packages\aioredis\stream.py", line 23, in open_connection transport, _ = await get_event_loop().create_connection( File "****\asyncio\base_events.py", line 1033, in create_connection raise OSError('Multiple exceptions: {}'.format( OSError: Multiple exceptions: [Errno 10061] Connect call failed ('::1', 8080, 0, 0), [Errno 10061] Connect call failed ('127.0.0.1', 8080)
Best option is using a library since FastAPI does not provide this functionality out-of-box. slowapi is great, and easy to use. You can use ut like this. from fastapi import FastAPI from slowapi.errors import RateLimitExceeded from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote_address limiter = Limiter(key_func=get_remote_address) app = FastAPI() app.state.limiter = limiter app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) @app.get("/home") @limiter.limit("5/minute") async def homepage(request: Request): return PlainTextResponse("test") @app.get("/mars") @limiter.limit("5/minute") async def homepage(request: Request, response: Response): return {"key": "value"}
23
47
65,451,457
2020-12-25
https://stackoverflow.com/questions/65451457/how-can-i-update-class-members-in-processes
I have looked for other questions, and this un-accepted-answered question is the only one I could find that somehow covers this issue and is not really helpful. Also, I need this to work with processes, and not threads. So from the ground up I wrote a sample program to show my issue, you should be able to paste it and it will run: import multiprocessing import time class Apple: def __init__(self, color): self.color = color def thinkAboutApple(apple): while True: print(apple.color) time.sleep(2) my_apple = Apple("red") new_process = multiprocessing.Process(target=thinkAboutApple, args=(my_apple,)) new_process.start() time.sleep(4) print("new: brown") my_apple.color = "brown" #so that the program doesn't exit after time.sleep(4) while True: pass # actual output | # wanted output red | red red | red new: brown | new: brown red | brown red | brown This tells me that either the apple is in a weird supposition where it is two colours at the same time, OR that the new_process' apple is in another position in ram and separated from the apple in the main process. So the question is: Is there a way to have the pointer of the apple in the process point to the same apple, or what is the pythonic way to keep all instances of the apple in all processes the same? What if I have the same apple in many processes and even more processes without the apple, how do I make sure they area always the same?
You can derive a specialized version of a Proxy class used by multiprocessing.BaseManager from the (undocumented) multiprocessing.managers.NamespaceProxy class that, unlike the base class, exposes all of its methods and attributes. This is similar to @shtse8's answer to the linked duplicate question, but I'm posting a runnable answer to it here to make clear how it can be done. from multiprocessing import Process from multiprocessing.managers import BaseManager, NamespaceProxy import time import types class MyManager(BaseManager): pass # Avoid namespace pollution. class Apple: def __init__(self, color): self.color = color def Proxy(target): """ Create a derived NamespaceProxy class for `target`. """ def __getattr__(self, key): result = self._callmethod('__getattribute__', (key,)) if isinstance(result, types.MethodType): def wrapper(*args, **kwargs): self._callmethod(key, args) return wrapper return result dic = {'types': types, '__getattr__': __getattr__} proxy_name = target.__name__ + "Proxy" ProxyType = type(proxy_name, (NamespaceProxy,), dic) # Create subclass. ProxyType._exposed_ = tuple(dir(target)) return ProxyType AppleProxy = Proxy(Apple) def thinkAboutApple(apple): while True: print(f"apple.color: {apple.color}") time.sleep(1) if __name__ == '__main__': MyManager.register('Apple', Apple, AppleProxy) manager = MyManager() manager.start() my_apple = manager.Apple("red") new_process = Process(target=thinkAboutApple, args=(my_apple,)) new_process.start() time.sleep(2) # Allow other process to run a short while. my_apple.color = "brown" # Change shared class instance. time.sleep(2) # Allow other process to run at little while longer. new_process.terminate()
6
6
65,470,807
2020-12-27
https://stackoverflow.com/questions/65470807/how-to-add-a-new-dimension-to-a-pytorch-tensor
In NumPy, I would do a = np.zeros((4, 5, 6)) a = a[:, :, np.newaxis, :] assert a.shape == (4, 5, 1, 6) How to do the same in PyTorch?
a = torch.zeros(4, 5, 6) a = a[:, :, None, :] assert a.shape == (4, 5, 1, 6)
51
68
65,426,515
2020-12-23
https://stackoverflow.com/questions/65426515/how-to-resolve-attempted-relative-import-with-no-known-parent-package
I have a bare bones project structure with mostly empty python files for the sake of testing a concept from an online tutorial: project |--package1 | |--__init__.py | |--module1.py | |--package2 | |--__init__.py | |--module2.py | |--__init__.py module1.py: from .package2.module2 import function2 module2.py: def function2(): return 0 Running module1.py directly results in this error: Traceback (most recent call last): File "c:\"blahblahblah"\project\package1\module1.py", line 1, in <module> from .package2.module2 import function2 ImportError: attempted relative import with no known parent package I've tried reducing the complexity of the issue by placing module2.py into the project folder itself and modifying the import as my tutorial suggests it would work (from .module2 import function2) but this yields the same error. side note: I am under the impression the init files are unnecessary for my version of python, but I've added them to keep all my bases covered. Python version 3.9.1 Any hints would be much appreciated.
The relative imports failed to work because module1.py could not look into it's parent folder for more packages when executed directly. The correct call required the -m parameter to signify that module1 was a module within a package. My terminal also needed to go up one directory: PS C:\...\"parent of project folder"> python -m project.package1.module1 Also, module1.py needed to be modified: from ..package2.module2 import function2
8
4
65,452,383
2020-12-25
https://stackoverflow.com/questions/65452383/macos-11-or-later-required-error-on-pycharm
I am learning how to use python by watching some online videos. When I run the code below using PyCharm, I get the following: macOS 11 or later required! Process finished with exit code 134 (interrupted by signal 6: SIGABRT) I have an M1 Mac mini with macOS Big Sur 11.1. This was happening when I had Python 3.8.2. Then, I installed Python 3.9.1. I keep getting the same error. How can I fix this? import turtle bob = turtle.Turtle() print(bob)
If you used Homebrew to do your Python installation, there have been some reported issues with Python3 installs via brew (Source 1, Source 2). Updates are always in the works though, so you could try remedying your problem first with a brew update. If the issue persists, the current recommendation is to actually install Python directly from their site (Similar issue with fix reported). In conclusion, if using brew, try a brew update first, if that doesn't fix your issue, install Python directly! brew update && brew upgrade
6
5
65,473,454
2020-12-28
https://stackoverflow.com/questions/65473454/what-is-difference-between-python-pylance-vs-code-extensions
I just shifted from my old bud Sublime to VSCode. I really liked the way it works and the features it has. I'm a newbie python developer. I found two popular python extensions for VSCode: Python, and PyLance. My question is, What is the difference between Python and Pylance extension? I searched a lot but didn't find a good comparison.
As an editor, VSCode cannot recognize all languages and many functions cannot be implemented independently. Therefore, when we use Python code in VSCode, we need to install the 'Python' extension, which provides us with functions such as code completion, support for Jupyter notebooks, debugging Python code, etc. Therefore, the Python extension is one of the necessary dependencies for using Python in VSCode. The extension 'Pylance' needs to be used in conjunction with the Python extension. It cannot be used independently in VSCode. It mainly provides outstanding Python language services (other Python language services such as "Microsoft", "Jedi", don't need to install specific extensions, they can be used as-is after installation). At the same time, it also provides functions such as docstrings. Therefore, the Pylance extension is not a necessary condition, but a recommended extension. It is recommended that you install and use these two extensions. They are not opposite extensions, they are VSCode extensions that cooperate with each other (To be precise, the 'Pylance' extension relies on the 'Python' extension to use). And for more related information, you could refer to the VS Code docs on: Using Python in VSCode and Python and Pylance.
30
40
65,439,154
2020-12-24
https://stackoverflow.com/questions/65439154/pytorch-doesnt-work-with-cuda-in-pycharm-intellij
I have just downloaded PyTorch with CUDA via Anaconda and when I type into the Anaconda terminal: import torch if torch.cuda.is_available(): print('it works') then he outputs that; that means that it worked and it works with PyTorch. But when I go to my IDE (PyCharm and IntelliJ) and write the same code, it doesn't output anything. Could someone please explain to me how I can somehow get this to work in the IDE?
It was driving me mad as well... What finally helped me was the first link that says to use PyCharm "Terminal" to run the pip install command (from the PyTorch website). That fixed all my problems. (I had installed pytorch 3 times by that time and tried different interpreters...) https://www.datasciencelearner.com/how-to-install-pytorch-in-pycharm/ pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio===0.8.0 -f https://download.pytorch.org/whl/torch_stable.html I hope this helps save someone hours of headache. :)
4
9
65,498,975
2020-12-29
https://stackoverflow.com/questions/65498975/forward-method-error-in-dnn-module-of-opencv-ptyhon-using-onnx-model
I wanted to test a pretrained model downloaded from here to perform an ocr task. Link to download, its name is CRNN_VGG_BiLSTM_CTC.onnx. This model is extracted from here. The sample-image.png can be download from here (see the code bellow). When I do the forward of the neural network to predict (ocr) in the blob I get the following error: error: OpenCV(4.4.0) /tmp/pip-req-build-xgme2194/opencv/modules/dnn/src/layers/convolution_layer.cpp:348: error: (-215:Assertion failed) ngroups > 0 && inpCn % ngroups == 0 && outCn % ngroups == 0 in function 'getMemoryShapes' Feel free to read the code bellow. I tried many things, it's weird because this model does not require a predetermined input shape. If you know any way to read this model and do the forward it is also going to be helpful but I'd rather solve using OpenCV. import cv2 as cv # The model is downloaded from here https://drive.google.com/drive/folders/1cTbQ3nuZG-EKWak6emD_s8_hHXWz7lAr # model path modelRecognition = os.path.join(MODELS_PATH,'CRNN_VGG_BiLSTM_CTC.onnx') # read net recognizer = cv.dnn.readNetFromONNX(modelRecognition) # Download sample_image.png from https://i.ibb.co/fMmCB7J/sample-image.png (image host website) sample_image = cv.imread('sample-image.png') # Height , Width and number of channels of the image H, W, C = sample_image.shape # Create a 4D blob from cropped image blob = cv.dnn.blobFromImage(sample_image, size = (H, W)) recognizer.setInput(blob) # Here is where i get the errror that I mentioned before result = recognizer.forward() Thank you so much in advance.
Your problem is actually that the input data you feed to your model doesn't match the shape of the data the model was trained on. I used this answer to inspect your onnx model and it appears that it expects an input of shape (1, 1, 32, 100). I modified your code to reshape the image to 1 x 32 x 100 pixels and the inference actually runs without error. EDIT I've added some code to interpret the result of the inference. We now display the image and the inferred OCR text. This doesn't seem to be working, but reading the tutorial on OpenCV, there should be two models: one that detects where there is text in the image. This network accepts images of various sizes, it returns the locations of text within the image and then cropped parts of the image, of sizes 100x32 are passed to the second one that actually does the "reading" and given patches of image, returns the characters. For this, there a file alphabet_36.txt that is provided together with the pre-trained models. It isn't clear to me though which network to use for text detection. Hope the edited code below helps you develop your application further. import cv2 as cv import os import numpy as np import matplotlib.pyplot as plt # The model is downloaded from here https://drive.google.com/drive/folders/1cTbQ3nuZG-EKWak6emD_s8_hHXWz7lAr # model path MODELS_PATH = './' modelRecognition = os.path.join(MODELS_PATH,'CRNN_VGG_BiLSTM_CTC.onnx') # read net recognizer = cv.dnn.readNetFromONNX(modelRecognition) # Download sample_image.png from https://i.ibb.co/fMmCB7J/sample-image.png (image host website) sample_image = cv.imread('sample-image.png', cv.IMREAD_GRAYSCALE) sample_image = cv.resize(sample_image, (100, 32)) sample_image = sample_image[:,::-1].transpose() # Height and Width of the image H,W = sample_image.shape # Create a 4D blob from image blob = cv.dnn.blobFromImage(sample_image, size=(H,W)) recognizer.setInput(blob) # network inference result = recognizer.forward() # load alphabet with open('alphabet_36.txt') as f: alphabet = f.readlines() alphabet = [f.strip() for f in alphabet] # interpret inference results res = [] for i in range(result.shape[0]): ind = np.argmax(result[i,0]) res.append(alphabet[ind]) ocrtxt = ''.join(res) # show image and detected OCR characters plt.imshow(sample_image) plt.title(ocrtxt) plt.show() Hope it helps. Cheers
5
4
65,429,877
2020-12-23
https://stackoverflow.com/questions/65429877/aws-lambda-container-running-selenium-with-headless-chrome-works-locally-but-not
I am currently developing a Python program which has a segment which uses a headless version of Chrome and Selenium to perform a repetitive process. I am aiming to run the program on Lambda. The overall program has around 1GB of dependencies so the option to use the standard method of using a .zip archive, containing all my function code and dependencies is not an option as the total unzipped size of the function and all layers can't exceed the unzipped deployment package size limit of 250 MB. So, that is where the new AWS Lambda – Container Image Support (I used this linked tutorial to develop this whole implementation so please read if you need more info) comes in. This allows me to package and deploy my Lambda function as container images of up to 10 GB in size. I am using the base image hosted in ECR Public provided by AWS which runs Amazon Linux 2. Firstly - in my Dockerfile I: Download the base image. Define some global variables. Copy my files over. Install my pip appendices Use yum to install some packages. and finally - I install both Chrome (87.0.4280.88 at the time of reading) and Chromedriver (87.0.4280.88) Finally download install both latest versions of Chrome and Chromedriver there is a possibility this could be where the problem lies, but I highly doubt this as both are the same version - ChromeDriver uses the same version number scheme as Chrome. This is my Dockerfile: # 1) DOWNLOAD BASE IMAGE. FROM public.ecr.aws/lambda/python:3.8 # 2) DEFINE GLOBAL ARGS. ARG MAIN_FILE="main.py" ARG ENV_FILE="params.env" ARG REQUIREMENTS_FILE="requirements.txt" ARG FUNCTION_ROOT="." ARG RUNTIME_VERSION="3.8" # 3) COPY FILES. # Copy The Main .py File. COPY ${MAIN_FILE} ${LAMBDA_TASK_ROOT} # Copy The .env File. COPY ${ENV_FILE} ${LAMBDA_TASK_ROOT} # Copy The requirements.txt File. COPY ${REQUIREMENTS_FILE} ${LAMBDA_TASK_ROOT} # Copy Helpers Folder. COPY helpers/ ${LAMBDA_TASK_ROOT}/helpers/ # Copy Private Folder. COPY priv/ ${LAMBDA_TASK_ROOT}/priv/ # Copy Source Data Folder. COPY source_data/ ${LAMBDA_TASK_ROOT}/source_data/ # 4) INSTALL DEPENDENCIES. RUN --mount=type=cache,target=/root/.cache/pip python3.8 -m pip install --upgrade pip RUN --mount=type=cache,target=/root/.cache/pip python3.8 -m pip install wheel RUN --mount=type=cache,target=/root/.cache/pip python3.8 -m pip install urllib3 RUN --mount=type=cache,target=/root/.cache/pip python3.8 -m pip install -r requirements.txt --default-timeout=100 # 5) DOWNLOAD & INSTALL CHROMEIUM + CHROMEDRIVER. #RUN yum -y upgrade RUN yum -y install wget unzip libX11 nano wget unzip xorg-x11-xauth xclock xterm # Install Chrome RUN wget https://intoli.com/install-google-chrome.sh RUN bash install-google-chrome.sh # Install Chromedriver RUN wget https://chromedriver.storage.googleapis.com/87.0.4280.88/chromedriver_linux64.zip RUN unzip ./chromedriver_linux64.zip RUN rm ./chromedriver_linux64.zip RUN mv -f ./chromedriver /usr/local/bin/chromedriver RUN chmod 755 /usr/local/bin/chromedriver # 5) SET CMD OF HANDLER. CMD [ "main.lambda_handler" ] This image always builds without a problem and creates my image as expected. and my docker-compose.yml file: version: "3.7" services: lambda: image: tbg-lambda:latest build: . ports: - "8080:8080" env_file: - ./params.env So - now that the image is build I can test locally with cURL. Here, I am passing an empty JSON payload: curl -XPOST "http://localhost:8080/2015-03-31/functions/function/invocations" -d '{}' which runs the whole program perfectly start to end using Chrome headless mode with no errors. So great - the Docker container works locally and as expected. Lets upload it to ECR so I can use it with my Lambda Function (ECR URL changed for security): aws ecr create-repository --repository-name tbg-lambda:latest --image-scanning-configuration scanOnPush=true docker tag tbg-lambda:latest 123412341234.dkr.ecr.sa-east-1.amazonaws.com/tbg-lambda:latest aws ecr get-login-password | docker login --username AWS --password-stdin 123412341234.dkr.ecr.sa-east-1.amazonaws.com docker push 123412341234.dkr.ecr.sa-east-1.amazonaws.com/tbg-lambda:latest Everything pushes up as expected - I then create my new lambda function, choosing "Container Image" as the function option and attach the IAM role with all the permissions I need: I have the memory set the max value just to ensure this isn't the problem: Ok - so lets to get to the point of failure: I use a test event to invoke the function through the console: Everything runs perfectly until it hits the code which creates the webdriver driver with Chrome: options = Options() options.add_argument('--no-sandbox') options.add_argument('--headless') options.add_argument('--single-process') options.add_argument('--disable-dev-shm-usage') options.add_argument('--remote-debugging-port=9222') options.add_argument('--disable-infobars') driver = webdriver.Chrome( service_args=["--verbose", "--log-path={}".format(logPath)], executable_path=f"/usr/local/bin/chromedriver", options=options ) PS: logPath is just another folder in the project directory - the logs output here as expected, the logs are shown below. Heres is the part of the Cloudwatch Logs where the error is highlighted: Caught WebDriverException Error: unknown error: Chrome failed to start: crashed. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) END RequestId: 7c933bca-5f0d-4458-9529-db28da677444 REPORT RequestId: 7c933bca-5f0d-4458-9529-db28da677444 Duration: 59104.94 ms Billed Duration: 59105 ms Memory Size: 10240 MB Max Memory Used: 481 MB RequestId: 7c933bca-5f0d-4458-9529-db28da677444 Error: Runtime exited with error: exit status 1 Runtime.ExitError And here is the full Chromedriver log file: [1608748453.064][INFO]: Starting ChromeDriver 87.0.4280.88 (89e2380a3e36c3464b5dd1302349b1382549290d-refs/branch-heads/4280@{#1761}) on port 54581 [1608748453.064][INFO]: Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. [1608748453.064][INFO]: /dev/shm not writable, adding --disable-dev-shm-usage switch [1608748453.679][SEVERE]: CreatePlatformSocket() failed: Address family not supported by protocol (97) [1608748453.679][INFO]: listen on IPv6 failed with error ERR_ADDRESS_UNREACHABLE [1608748454.432][INFO]: [13826d22c628514ca452d1f2949eb011] COMMAND InitSession { "capabilities": { "alwaysMatch": { "browserName": "chrome", "goog:chromeOptions": { "args": [ "--no-sandbox", "--headless", "--single-process", "--disable-dev-shm-usage" ], "extensions": [ ] }, "platformName": "any" }, "firstMatch": [ { } ] }, "desiredCapabilities": { "browserName": "chrome", "goog:chromeOptions": { "args": [ "--no-sandbox", "--headless", "--single-process", "--disable-dev-shm-usage" ], "extensions": [ ] }, "platform": "ANY", "version": "" } } [1608748454.433][INFO]: Populating Preferences file: { "alternate_error_pages": { "enabled": false }, "autofill": { "enabled": false }, "browser": { "check_default_browser": false }, "distribution": { "import_bookmarks": false, "import_history": false, "import_search_engine": false, "make_chrome_default_for_user": false, "skip_first_run_ui": true }, "dns_prefetching": { "enabled": false }, "profile": { "content_settings": { "pattern_pairs": { "https://*,*": { "media-stream": { "audio": "Default", "video": "Default" } } } }, "default_content_setting_values": { "geolocation": 1 }, "default_content_settings": { "geolocation": 1, "mouselock": 1, "notifications": 1, "popups": 1, "ppapi-broker": 1 }, "password_manager_enabled": false }, "safebrowsing": { "enabled": false }, "search": { "suggest_enabled": false }, "translate": { "enabled": false } } [1608748454.433][INFO]: Populating Local State file: { "background_mode": { "enabled": false }, "ssl": { "rev_checking": { "enabled": false } } } [1608748454.433][INFO]: Launching chrome: /usr/bin/google-chrome --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-dev-shm-usage --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --enable-automation --enable-blink-features=ShadowDOMV0 --enable-logging --headless --log-level=0 --no-first-run --no-sandbox --no-service-autorun --password-store=basic --remote-debugging-port=0 --single-process --test-type=webdriver --use-mock-keychain --user-data-dir=/tmp/.com.google.Chrome.xgjs0h data:, mkdir: cannot create directory β€˜/.local’: Read-only file system touch: cannot touch β€˜/.local/share/applications/mimeapps.list’: No such file or directory /usr/bin/google-chrome: line 45: /dev/fd/62: No such file or directory /usr/bin/google-chrome: line 46: /dev/fd/62: No such file or directory prctl(PR_SET_NO_NEW_PRIVS) failed [1223/183429.578846:FATAL:zygote_communication_linux.cc(255)] Cannot communicate with zygote Failed to generate minidump.[1608748469.769][INFO]: [13826d22c628514ca452d1f2949eb011] RESPONSE InitSession ERROR unknown error: Chrome failed to start: crashed. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) [1608748469.769][DEBUG]: Log type 'driver' lost 0 entries on destruction [1608748469.769][DEBUG]: Log type 'browser' lost 0 entries on destruction One thing that I might think could be the problem would the way lambda is running this container vs how I am running it locally. Alot of people reccomend NOT to not run chrome as root - so is Lambda running the container as root and thats what is causing this? If so how can I tell Lambda or Docker to run the code as a non-root user. This is mentioned here: https://github.com/heroku/heroku-buildpack-google-chrome/issues/46#issuecomment-484562558 I have been fighting with this error pretty much since AWS announced the lambda containers so any help with this would be brilliant πŸ™ Please ask for any more info if I missed something! Thanks in advance.
Python v3.6 works great. I have a bin directory with chromedriver v2.41 (https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip) and headless-chrome v68.0.3440.84 (https://github.com/adieuadieu/serverless-chrome/releases/download/v1.0.0-53/stable-headless-chromium-amazonlinux-2017-03.zip). Below is my Dockerfile where I copy chromedriver and headless-chrome from source bin directory to the destination bin directory. The reason for having the destination bin directory is mentioned below. FROM public.ecr.aws/lambda/python:3.6 COPY app.py ${LAMBDA_TASK_ROOT} COPY requirements.txt ${LAMBDA_TASK_ROOT} RUN --mount=type=cache,target=/root/.cache/pip python3.6 -m pip install --upgrade pip RUN --mount=type=cache,target=/root/.cache/pip python3.6 -m pip install -r requirements.txt RUN mkdir bin ADD bin bin/ CMD [ "app.handler" ] In my python script, I will copy the files in bin directory (Docker Container) to /tmp/bin directory (Amazon Linux 2) with 775 permission because tmp is the only directory where we can write files in Amazon linux 2 as the lambda will be executed here. BIN_DIR = "/tmp/bin" CURR_BIN_DIR = os.getcwd() + "/bin" def _init_bin(executable_name): if not os.path.exists(BIN_DIR): logger.info("Creating bin folder") os.makedirs(BIN_DIR) logger.info("Copying binaries for " + executable_name + " in /tmp/bin") currfile = os.path.join(CURR_BIN_DIR, executable_name) newfile = os.path.join(BIN_DIR, executable_name) shutil.copy2(currfile, newfile) logger.info("Giving new binaries permissions for lambda") os.chmod(newfile, 0o775) In the handler function, use the below options to avoid few exceptions raised by chrome driver. def handler(event, context): _init_bin("headless-chromium") _init_bin("chromedriver") options = Options() options.add_argument("--headless") options.add_argument("--disable-gpu") options.add_argument("--no-sandbox") options.add_argument('--disable-dev-shm-usage') options.add_argument('--disable-gpu-sandbox') options.add_argument("--single-process") options.add_argument('window-size=1920x1080') options.add_argument( '"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"') options.binary_location = "/tmp/bin/headless-chromium" browser = webdriver.Chrome( "/tmp/bin/chromedriver", options=options)
16
7
65,491,229
2020-12-29
https://stackoverflow.com/questions/65491229/python-http-module-cannot-parse-response-if-the-server-answers-before-the-put
I'm using the requests (which uses urllib3 and the Python http module under the hood) library to upload a file from a Python script. My backend starts by inspecting the headers of the request and if it doesn't comply with the needed prerequisites, it stops the request right away and respond with a valid 400 response. This behavior works fine in Postman, or with Curl; i.e. the client is able to parse the 400 response even though it hasn't completed the upload and the server answers prematurely. However, while doing so in Python with requests/urllib3, the library is unable to process the backend response : Traceback (most recent call last): File "C:\Users\Neumann\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\urllib3\connectionpool.py", line 670, in urlopen httplib_response = self._make_request( File "C:\Users\Neumann\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\urllib3\connectionpool.py", line 392, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 1255, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 1301, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 1250, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 1049, in _send_output self.send(chunk) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 971, in send self.sock.sendall(data) ConnectionResetError: [WinError 10054] Une connexion existante a dΓ» Γͺtre fermΓ©e par l’hΓ΄te distant Because the server answers before the transfer is complete, it mistakenly considers that the connection has been aborted, even though the server DOES return a valid response. Is there a way to avoid this and parse the response nonetheless ? Steps to reproduce the issue : Download minIO : https://min.io/download#/ Run minIO : export MINIO_ACCESS_KEY=<access_key> export MINIO_SECRET_KEY=<secret_key> .\minio.exe server <data folder> Run the following script : import os import sys import requests from requests_toolbelt.multipart.encoder import MultipartEncoder def fatal(msg): print(msg) sys.exit(1) def upload_file(): mp_encoder = MultipartEncoder(fields={'file': (open('E:/Downloads/kek.mp3', 'rb'))}) headers = { "Authorization": "invalid" } print('Uploading file with headers : ' + str(headers)) upload_endpoint = 'http://localhost:9000/mybucket/myobject' try: r = requests.put(upload_endpoint, headers=headers, data=mp_encoder, verify=False) except requests.exceptions.ConnectionError as e: print(e.status) for property, value in vars(e).items(): print(property, ":", value) fatal(str(e)) if r.status_code != 201: for property, value in vars(r).items(): print(property, ":", value) fatal('Error while uploading file. Status ' + str(r.status_code)) print('Upload successfully completed') if __name__ == "__main__": upload_file() If you change the request line with this, it will work (i.e. the server returns 400 and the client is able to parse it) : r = requests.put(upload_endpoint, headers=headers, data='a string', verify=False) EDIT : I updated the traceback and changed the question title to reflect the fact that it's neither requests or urllib3 fault, but the Python http module that is used by both of them.
This problem should be fixed in urllib3 v1.26.0. What version are you running? The problem is that the server closes the connection after it responds with 400, so the socket is closed when urllib3 tries to keep sending data to it. So it isn't really mistakenly thinking that the connection is closed, it just mishandles that situation. Your example code works fine on my machine with urllib3==1.26.0 . But I notice that you get a different exception on your Windows machine, so it might be that the fix doesn't work. In that case, I would just catch the exception and file a bug report to the maintainers of urllib3.
9
2
65,451,045
2020-12-25
https://stackoverflow.com/questions/65451045/cnn-model-conditional-layer-in-keras
I am trying to build a conditional CNN model. The model is, At the first stage of my model, I feed my data to Model 1 then, based on the prediction of Model 1, I want to train the model to Conditional Cat model or Conditional Dog model and finally, give the output from Conditional Cat model or Conditional Dog model. How Can I do this? Note: My effort is, import keras from keras.layers import * from keras.models import * from keras.utils import * img_rows,img_cols,number_of_class = 256,256,2 input = Input(shape=(img_rows,img_cols,3)) #----------- main model (Model 1) ------------------------------------ conv_01 = Convolution2D(64, 3, 3, activation='relu',name = 'conv_01') (input) conv_02 = Convolution2D(64, 3, 3, activation='relu',name = 'conv_02') (conv_01) skip_dog = conv_02 conv_03 = Convolution2D(64, 3, 3, activation='relu',name = 'conv_03') (conv_02) skip_cat = conv_03 conv_04 = Convolution2D(64, 3, 3, activation='relu',name = 'conv_04') (conv_03) flatten_main_model = Flatten() (conv_04) Output_main_model = Dense(units = number_of_class , activation = 'softmax', name = "Output_layer")(flatten_main_model) #----------- Conditional Cat model ------------------------------------ conv_05 = Convolution2D(64, 3, 3, activation='relu',name = 'conv_05') (skip_cat) flatten_cat_model = Flatten() (conv_05) Output_cat_model = Dense(units = number_of_class , activation = 'softmax', name = "Output_layer_cat")(flatten_cat_model) #----------- Conditional Dog model ------------------------------------ conv_06 = Convolution2D(64, 3, 3, activation='relu',name = 'conv_06') (skip_dog) flatten_dog_model = Flatten() (conv_06) Output_dog_model = Dense(units = number_of_class , activation = 'softmax', name = "Output_layer_dog")(flatten_dog_model) #----------------------------- My discrete 3 models -------------------------------- model_01 = Model(inputs = input , outputs = Output_main_model,name = 'model_main') model_02_1 = Model(inputs = input , outputs = Output_cat_model ,name = 'Conditional_cat_model') model_02_2 = Model(inputs = input , outputs = Output_dog_model ,name = 'Conditional_dog_model') How can I merge these 3 models (model_01, model_02_1, model_02_2) based on these conditions? **Conditions are: ** Feed data to model model_01 Based on model_01 result feed data to model_02_1 or model_02_2 Next, predict the final output from model_02_1 or model_02_2
The problem with conditionals in neural networks The issue with a switch or conditionals (like if-then-else) as part of a neural network is that conditionals are not differentiable everywhere. Therefore the automatic differentiation methods would not work directly and solving this is super complex. Check this for more details. A shortcut is you can end up training 3 separate models independently, and then during inference uses a control flow of conditionals to infer from them. #Training - model1 = model.fit(all images, P(cat/dog)) model2 = model.fit(all images, P(cat)) model3 = model.fit(all images, P(dog)) final prediction = argmax(model2, model3) #Inference - if model1.predict == Cat: model2.predict else: model3.predict But I don't think you are looking for that. I think you are looking to include conditionals as part of the computation graph itself. Sadly, there is no direct way for you to build an if-then condition as part of a computation graph as per my knowledge. The keras.switch that you see allows you to work with tensor outputs but not with layers of a graph during training. That's why you will see it being used as part of loss functions and not in computation graphs (throws input errors). A possible Solution - Skip connections & soft-switching You can, however, try to build something similar with skip connections and soft switching. A skip connection is a connection from a previous layer to another layer that allows you to pass information to the subsequent layers. This is quite common in very deep networks where information from the original data is subsequently lost. Check U-net or Resnet for example, which uses skip connections between layers to pass information to future layers. The next issue is the issue of switching. You want to switch between 2 possible paths in the graph. What you can do is a soft-switching method which I took as inspiration from this paper. Notice that in order to switch between 2 distribution of words (one from the decoder and another from the input), the authors multiply them with p and (1-p) to get a cumulative distribution. This is a soft-switch that allows the model to pick the next predicted word from either the decoder or from the input itself. (helps when you want your chatbot to speak the words that were input by the user as part of its response to them!) With an understanding of these 2 concepts, let's try to intuitively build our architecture. First we need a single-input multi-output graph since we are training 2 models Our first model is a multi-class classification that predicts individual probabilities for Cat and Dog separately. This will be trained with the activation of softmax and a categorical_crossentropy loss. Next, let's take the logit which predicts the probability of Cat, and multiply the convolution layer 3 with it. This can be done with a Lambda layer. And similarly, let's take the probability of Dog and multiply it with the convolution layer 2. This can be seen as the following - If my first model predicts a cat and not a dog, perfectly, then the computation will be 1*(Conv3) and 0*(Conv2). If the first model predicts a dog and not a cat, perfectly, then the computation will be 0*(Conv3) and 1*(Conv2) You can think of this as either a soft-switch OR a forget gate from LSTM. The forget gate is a sigmoid (0 to 1) output that multiplies the cell state to gate it and allow the LSTM to forget or remember previous time-steps. Similar concept here! These Conv3 and Conv2 can now be further be processed, flattened, concatenated, and passed to another Dense layer for the final prediction. This way if the model is not sure about a dog or a cat, both conv2 and conv3 features participate in the second model's predictions. This is how you can use skip connections and soft switch inspired mechanism to add some amount of conditional control flow to your network. Check my implementation of the computation graph below. from tensorflow.keras import layers, Model, utils import numpy as np X = np.random.random((10,500,500,3)) y = np.random.random((10,2)) #Model inp = layers.Input((500,500,3)) x = layers.Conv2D(6, 3, name='conv1')(inp) x = layers.MaxPooling2D(3)(x) c2 = layers.Conv2D(9, 3, name='conv2')(x) c2 = layers.MaxPooling2D(3)(c2) c3 = layers.Conv2D(12, 3, name='conv3')(c2) c3 = layers.MaxPooling2D(3)(c3) x = layers.Conv2D(15, 3, name='conv4')(c3) x = layers.MaxPooling2D(3)(x) x = layers.Flatten()(x) out1 = layers.Dense(2, activation='softmax', name='first')(x) c = layers.Lambda(lambda x: x[:,:1])(out1) d = layers.Lambda(lambda x: x[:,1:])(out1) c = layers.Multiply()([c3, c]) d = layers.Multiply()([c2, d]) c = layers.Conv2D(15, 3, name='conv5')(c) c = layers.MaxPooling2D(3)(c) c = layers.Flatten()(c) d = layers.Conv2D(12, 3, name='conv6')(d) d = layers.MaxPooling2D(3)(d) d = layers.Conv2D(15, 3, name='conv7')(d) d = layers.MaxPooling2D(3)(d) d = layers.Flatten()(d) x = layers.concatenate([c,d]) x = layers.Dense(32)(x) out2 = layers.Dense(2, activation='softmax',name='second')(x) model = Model(inp, [out1, out2]) model.compile(optimizer='adam', loss='categorical_crossentropy', loss_weights=[0.5, 0.5]) model.fit(X, [y, y], epochs=5) utils.plot_model(model, show_layer_names=False, show_shapes=True) Epoch 1/5 1/1 [==============================] - 1s 1s/step - loss: 0.6819 - first_loss: 0.7424 - second_loss: 0.6214 Epoch 2/5 1/1 [==============================] - 0s 423ms/step - loss: 0.6381 - first_loss: 0.6361 - second_loss: 0.6400 Epoch 3/5 1/1 [==============================] - 0s 442ms/step - loss: 0.6137 - first_loss: 0.6126 - second_loss: 0.6147 Epoch 4/5 1/1 [==============================] - 0s 434ms/step - loss: 0.6214 - first_loss: 0.6159 - second_loss: 0.6268 Epoch 5/5 1/1 [==============================] - 0s 427ms/step - loss: 0.6248 - first_loss: 0.6184 - second_loss: 0.6311
15
15
65,487,601
2020-12-29
https://stackoverflow.com/questions/65487601/how-to-deal-with-lat-lon-arrays-with-multiple-dimensions
I'm working with Pygrib trying to get surface temperatures for particular lat/lon coordinates using the NBM grib data (available here if it helps). I've been stuck trying to get an index value to use with representative data for a particular latitude and longitude. I was able to derive an index, but the problem is the latitude and longitude appear to have 2 coordinates each. I'll use Miami, FL (25.7617Β° N, 80.1918Β° W) as an example to illustrate this. Formatted to be minimum reproducible IF a grib file is provided. def get_grib_data(self, gribfile, shortName): grbs = pygrib.open(gribfile) # Temp needs level specified if shortName == '2t': grib_param = grbs.select(shortName=shortName, level=2) # Convention- use short name for less than 5 chars # Else, use name elif len(shortName) < 5: grib_param = grbs.select(shortName=shortName) else: grib_param = grbs.select(name=shortName) data_values = grib_param[0].values # Need varying returns depending on parameter grbs.close() if shortName == '2t': return data_values, grib_param else: return data_values # This function is used to find the closest lat/lon value to the entered one def closest(self, coordinate, value): ab_array = np.abs(coordinate - value) smallest_difference_index = np.amin(ab_array) ind = np.unravel_index(np.argmin(ab_array, axis=None), ab_array.shape) return ind def get_local_value(data, j, in_lats, in_lons, lats, lons): lat_ind = closest(lats, in_lats[j]) lon_ind = closest(lons, in_lons[j]) print(lat_ind[0]) print(lat_ind[1]) print(lon_ind[0]) print(lon_ind[1]) if len(lat_ind) > 1 or len(lon_ind) > 1: lat_ind = lat_ind[0] lon_ind = lon_ind[0] dtype = data[lat_ind][lon_ind] else: dtype = data[lat_ind][lon_ind] return dtype if __name__ == '__main__': tfile = # Path to grib file temps, param = grib_data.get_grib_data(tfile, '2t') lats, lons = param[0].latlons() j = 0 in_lats = [25.7617, 0 , 0] in_lons = [-80.198, 0, 0] temp = grib_data.get_local_value(temps, j, in_lats, in_lons, lats, lons) When I do the print listed, I get the following for indices: lat_ind[0]: 182 lat_ind[1]: 1931 lon_ind[0]: 1226 lon_ind[1]: 1756 So if my lat/lon were 1 dimensional, I would just do temp = data[lat[0]][lon[0]], but in this case that would give non-representative data. How would I go about handling the fact that lat/lon are in 2 coordinates? I have verified that lats[lat_ind[0][lat_ind1] gives the input latitude and the same for longitude.
You cannot evaluate "closeness" of latitudes independently of longitudes - you have to evaluate how close the pair of coordinates is to your input coordinates. Lat/Lon are really just spherical coordinates. Given two points (lat1,lon1) (lat2,lon2), closeness (in terms of great circles) is given by the angle between the spherical vectors between those two points (approximating the Earth as a sphere). You can compute this by constructing cartesian vectors of the two points and taking the dot product, which is a * b * cos(theta) where theta is what you want. import numpy as np def lat_lon_cartesian(lats,lons): lats = np.ravel(lats) #make both inputs 1-dimensional lons = np.ravel(lons) x = np.cos(np.radians(lons))*np.cos(np.radians(lats)) y = np.sin(np.radians(lons))*np.cos(np.radians(lats)) z = np.sin(np.radians(lats)) return np.c_[x,y,z] def closest(in_lats,in_lons,data_lats,data_lons): in_vecs = lat_lon_cartesian(in_lats,in_lons) data_vecs = lat_lon_cartesian(data_lats,data_lons) indices = [] for in_vec in in_vecs: # if input lats/lons is small list then doing a for loop is ok # otherwise can be vectorized with some array gymnastics dot_product = np.sum(in_vec*data_vecs,axis=1) angles = np.arccos(dot_product) # all are unit vectors so a=b=1 indices.append(np.argmin(angles)) return indices def get_local_value(data, in_lats, in_lons, data_lats, data_lons): raveled_data = np.ravel(data) raveled_lats = np.ravel(data_lats) raveled_lons = np.ravel(data_lons) inds = closest(in_lats,in_lons,raveled_lats,raveled_lons) dtypes = [] closest_lat_lons = [] for ind in inds: #if data is 2-d with same shape as the lat and lon meshgrids, then #it should be raveled as well and indexed by the same index dtype = raveled_data[ind] dtypes.append(dtype) closest_lat_lons.append((raveled_lats[ind],raveled_lons[ind])) #can return the closes matching lat lon data in the grib if you want return dtypes Edit: Alternatively use interpolation. import numpyp as np from scipy.interpolate import RegularGridInterpolator #assuming a grb object from pygrib #see https://jswhit.github.io/pygrib/api.html#example-usage lats, lons = grb.latlons() #source code for pygrib looks like it calls lons,lats = np.meshgrid(...) #so the following should give the unique lat/lon sequences lat_values = lats[:,0] lon_values = lons[0,:] grb_values = grb.values #create interpolator grb_interp = RegularGridInterpolator((lat_values,lon_values),grb_values) #in_lats, in_lons = desired input points (1-d each) interpolated_values = grb_interp(np.c_[in_lats,in_lons]) #the result should be the linear interpolation between the four closest lat/lon points in the data set around each of your input lat/lon points. Dummy data interpolation example: >>> import numpy as np >>> lats = np.array([1,2,3]) >>> lons = np.array([4,5,6,7]) >>> lon_mesh,lat_mesh = np.meshgrid(lons,lats) >>> lon_mesh array([[4, 5, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7]]) >>> lat_mesh array([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]) >>> z = lon_mesh + lat_mesh #some example function of lat/lon (simple sum) >>> z array([[ 5, 6, 7, 8], [ 6, 7, 8, 9], [ 7, 8, 9, 10]]) >>> from scipy.interpolate import RegularGridInterpolator >>> lon_mesh[0,:] #should produce lons array([4, 5, 6, 7]) >>> lat_mesh[:,0] #should produce lats array([1, 2, 3]) >>> interpolator = RegularGridInterpolator((lats,lons),z) >>> input_lats = np.array([1.5,2.5]) >>> input_lons = np.array([5.5,7]) >>> input_points = np.c_[input_lats,input_lons] >>> input_points array([[1.5, 5.5], [2.5, 7. ]]) >>> interpolator(input_points) array([7. , 9.5]) >>> #7 = 1.5+5.5 : correct ... #9.5 = 2.5+7 : correct ... >>>
5
5
65,453,234
2020-12-26
https://stackoverflow.com/questions/65453234/twint-criticalroottwint-feedfollowindexerror-for-any-call
import twint import os, requests, re, time c = twint.Config() c.Username = <anyusername> #Replace with an actual uname in quotes c.Store_object = True c.Limit = 10 try: twint.run.Followers(c) except: print("Unexpected error:", sys.exc_info()[0]) f = twint.output.follows_list print(f) Output CRITICAL:root:twint.feed:Follow:IndexError [] Have done pip install twint pip install --upgrade -e git+https://github.com/twintproject/twint.git@origin/master#egg=twint Googling, a lot of people have faced this error - but I cannot really find a solution Running the twint command line also gives the same error twint -u <uname> --followers CRITICAL:root:twint.feed:Follow:IndexError This is not only followers. Anything I try, I get a similar error. Running Python 3.8.1 on Windows 10 Twint - latest version - 2.1.21
Legacy mobile Twitter version will shut down on December 15th 2020. (M2 mobile web) That's the headline of a reddit thread talking about the recent shutdown of the M2 Mobile Web ("Legacy") Twitter version; from this date on Twitter will only support these browsers. If you take a look at the GitHub repository of Twint: _usr.followers = int(ur['data']['user']['legacy']['followers_count']) ... it uses the legacy attribute and therefore won't work from the 15th of December 2020. A contributor to the GitHub repo, namely @himanshudabas, also mentioned this in a reply to an identical issue: That's because twitter killed the no js (mobile version) version of twitter on 15th December. Followers were scraped using that version. You're not the only one facing this problem (obviously), and unfortunately with the Twint module there is no workaround (currently?). Speaking of the current situation you would need to either use the official Twitter API or alternative wrappers / unofficial APIs.
5
14
65,480,162
2020-12-28
https://stackoverflow.com/questions/65480162/how-to-remove-repititve-pattern-from-an-image-using-fft
I have image of skin colour with repetitive pattern (Horizontal White Lines) generated by a scanner that uses a line of sensors to perceive the photo. My Question is how to denoise the image effectively using FFT without affecting the quality of the image much, somebody told me that I have to suppress the lines that appears in the magnitude spectrum manually, but I didn't know how to do that, can you please tell me how to do it? My approach is to use Fast Fourier Transform(FFT) to denoise the image channel by channel. I have tried HPF, and LPF in Fourier domain, but the results were not good as you can see: My Code: from skimage.io import imread, imsave from matplotlib import pyplot as plt import numpy as np img = imread('skin.jpg') R = img[...,2] G = img[...,1] B = img[...,0] f1 = np.fft.fft2(R) fshift1 = np.fft.fftshift(f1) phase_spectrumR = np.angle(fshift1) magnitude_spectrumR = 20*np.log(np.abs(fshift1)) f2 = np.fft.fft2(G) fshift2 = np.fft.fftshift(f2) phase_spectrumG = np.angle(fshift2) magnitude_spectrumG = 20*np.log(np.abs(fshift2)) f3 = np.fft.fft2(B) fshift3 = np.fft.fftshift(f3) phase_spectrumB = np.angle(fshift3) magnitude_spectrumB = 20*np.log(np.abs(fshift2)) #=============================== # LPF # HPF magR = np.zeros_like(R) # = fshift1 # magR[magR.shape[0]//4:3*magR.shape[0]//4, magR.shape[1]//4:3*magR.shape[1]//4] = np.abs(fshift1[magR.shape[0]//4:3*magR.shape[0]//4, magR.shape[1]//4:3*magR.shape[1]//4]) # =0 # resR = np.abs(np.fft.ifft2(np.fft.ifftshift(magR))) resR = R - resR #=============================== magnitude_spectrumR plt.subplot(221) plt.imshow(R, cmap='gray') plt.title('Original') plt.subplot(222) plt.imshow(magnitude_spectrumR, cmap='gray') plt.title('Magnitude Spectrum') plt.subplot(223) plt.imshow(phase_spectrumR, cmap='gray') plt.title('Phase Spectrum') plt.subplot(224) plt.imshow(resR, cmap='gray') plt.title('Processed') plt.show()
Here is a simple and effective linear filtering strategy to remove the horizontal line artifact: Outline: Estimate the frequency of the distortion by looking for a peak in the image's power spectrum in the vertical dimension. The function scipy.signal.welch is useful for this. Design two filters: a highpass filter with cutoff just below the distortion frequency and a lowpass filter with cutoff near DC. We'll apply the highpass filter vertically and the lowpass filter horizontally to try to isolate the distortion. We'll use scipy.signal.firwin to design these filters, though there are many ways this could be done. Compute the restored image as "image βˆ’ (hpf βŠ— lpf) βˆ— image". Code: # Copyright 2021 Google LLC. # SPDX-License-Identifier: Apache-2.0 import numpy as np from scipy.ndimage import convolve1d from scipy.signal import firwin, welch def remove_lines(image, distortion_freq=None, num_taps=65, eps=0.025): """Removes horizontal line artifacts from scanned image. Args: image: 2D or 3D array. distortion_freq: Float, distortion frequency in cycles/pixel, or `None` to estimate from spectrum. num_taps: Integer, number of filter taps to use in each dimension. eps: Small positive param to adjust filters cutoffs (cycles/pixel). Returns: Denoised image. """ image = np.asarray(image, float) if distortion_freq is None: distortion_freq = estimate_distortion_freq(image) hpf = firwin(num_taps, distortion_freq - eps, pass_zero='highpass', fs=1) lpf = firwin(num_taps, eps, pass_zero='lowpass', fs=1) return image - convolve1d(convolve1d(image, hpf, axis=0), lpf, axis=1) def estimate_distortion_freq(image, min_frequency=1/25): """Estimates distortion frequency as spectral peak in vertical dim.""" f, pxx = welch(np.reshape(image, (len(image), -1), 'C').sum(axis=1)) pxx[f < min_frequency] = 0.0 return f[pxx.argmax()] Examples: On the portrait image, estimate_distortion_freq estimates that the frequency of the distortion is 0.1094 cycles/pixel (period of 9.14 pixels). The transfer function of the filtering "image βˆ’ (hpf βŠ— lpf) βˆ— image" looks like this: Here is the filtered output from remove_lines: On the skin image, estimate_distortion_freq estimates that the frequency of the distortion is 0.08333 cycles/pixel (period of 12.0 pixels). Filtered output from remove_lines: The distortion is mostly removed on both examples. It isn't perfect: on the portrait image, a couple ripples are still visible near the top and bottom borders, a typical defect when using large filters or Fourier methods. Still, it's a good improvement over the original images.
8
9
65,489,705
2020-12-29
https://stackoverflow.com/questions/65489705/transcribing-mp3-to-text-python-riff-id-error
I am trying to turn mp3 file to text, but my code returns the error outlined below. Any help is appreciated! This is a sample mp3 file. And below is what I have tried: import speech_recognition as sr print(sr.__version__) r = sr.Recognizer() file_audio = sr.AudioFile(r"C:\Users\Andrew\Podcast.mp3") with file_audio as source: audio_text = r.record(source) print(type(audio_text)) print(r.recognize_google(audio_text)) The full error I get. Appears to be: Error: file does not start with RIFF id Thank you for your help!
You need to first convert the mp3 to wav, and then you can transcribe it, below is the modified version of your code. import speech_recognition as sr from pydub import AudioSegment # convert mp3 file to wav src=(r"C:\Users\Andrew\Podcast.mp3") sound = AudioSegment.from_mp3(src) sound.export("C:\Users\Andrew\podcast.wav", format="wav") file_audio = sr.AudioFile(r"C:\Users\Andrew\Podcast.wav") # use the audio file as the audio source r = sr.Recognizer() with file_audio as source: audio_text = r.record(source) print(type(audio_text)) print(r.recognize_google(audio_text)) In above modified code, first mp3 file being converted into wav and then transcribing processes.
6
5
65,492,399
2020-12-29
https://stackoverflow.com/questions/65492399/gradient-descent-using-tensorflow-is-much-slower-than-a-basic-python-implementat
I'm following a machine learning course. I have a simple linear regression (LR) problem to help me get used to TensorFlow. The LR problem is to find parameters a and b such that Y = a*X + b approximates an (x, y) point cloud (which I generated myself for the sake of simplicity). I am solving this LR problem using a 'fixed step size gradient descent (FSSGD)'. I implemented it using TensorFlow and it works but I noticed that it is really slow both on GPU and CPU. Because I was curious I implemented the FSSGD myself in Python/NumPy and as expected this runs much faster, about: 10x faster than TF@CPU 20x faster than TF@GPU If TensorFlow is this slow, I cannot imagine that so many people are using this framework. So I must be doing something wrong. Can anyone help me so I can speedup my TensorFlow implementation. I'm NOT interested in the difference between the CPU and GPU performance. Both performance indicators are merely provided for completeness and illustration. I'm interested in why my TensorFlow implementation is so much slower than a raw Python/NumPy implementation. As reference, I add my code below. Stripped to a minimal (but fully working) example. Using Python v3.7.9 x64. Used tensorflow-gpu==1.15 for now (because the course uses TensorFlow v1) Tested to run in both Spyder and PyCharm. My FSSGD implementation using TensorFlow (execution time about 40 sec @CPU to 80 sec @GPU): #%% General imports import numpy as np import timeit import tensorflow.compat.v1 as tf #%% Get input data # Generate simulated input data x_data_input = np.arange(100, step=0.1) y_data_input = x_data_input + 20 * np.sin(x_data_input/10) + 15 #%% Define tensorflow model # Define data size n_samples = x_data_input.shape[0] # Tensorflow is finicky about shapes, so resize x_data = np.reshape(x_data_input, (n_samples, 1)) y_data = np.reshape(y_data_input, (n_samples, 1)) # Define placeholders for input X = tf.placeholder(tf.float32, shape=(n_samples, 1), name="tf_x_data") Y = tf.placeholder(tf.float32, shape=(n_samples, 1), name="tf_y_data") # Define variables to be learned with tf.variable_scope("linear-regression", reuse=tf.AUTO_REUSE): #reuse= True | False | tf.AUTO_REUSE W = tf.get_variable("weights", (1, 1), initializer=tf.constant_initializer(0.0)) b = tf.get_variable("bias", (1,), initializer=tf.constant_initializer(0.0)) # Define loss function Y_pred = tf.matmul(X, W) + b loss = tf.reduce_sum((Y - Y_pred) ** 2 / n_samples) # Quadratic loss function # %% Solve tensorflow model #Define algorithm parameters total_iterations = 1e5 # Defines total training iterations #Construct TensorFlow optimizer with tf.variable_scope("linear-regression", reuse=tf.AUTO_REUSE): #reuse= True | False | tf.AUTO_REUSE opt = tf.train.GradientDescentOptimizer(learning_rate = 1e-4) opt_operation = opt.minimize(loss, name="GDO") #To measure execution time time_start = timeit.default_timer() with tf.Session() as sess: #Initialize variables sess.run(tf.global_variables_initializer()) #Train variables for index in range(int(total_iterations)): _, loss_val_tmp = sess.run([opt_operation, loss], feed_dict={X: x_data, Y: y_data}) #Get final values of variables W_val, b_val, loss_val = sess.run([W, b, loss], feed_dict={X: x_data, Y: y_data}) #Print execution time time_end = timeit.default_timer() print('') print("Time to execute code: {0:0.9f} sec.".format(time_end - time_start)) print('') # %% Print results print('') print('Iteration = {0:0.3f}'.format(total_iterations)) print('W_val = {0:0.3f}'.format(W_val[0,0])) print('b_val = {0:0.3f}'.format(b_val[0])) print('') My own python FSSGD implementation (execution time about 4 sec): #%% General imports import numpy as np import timeit #%% Get input data # Define input data x_data_input = np.arange(100, step=0.1) y_data_input = x_data_input + 20 * np.sin(x_data_input/10) + 15 #%% Define Gradient Descent (GD) model # Define data size n_samples = x_data_input.shape[0] #Initialize data W = 0.0 # Initial condition b = 0.0 # Initial condition # Compute initial loss y_gd_approx = W*x_data_input+b loss = np.sum((y_data_input - y_gd_approx)**2)/n_samples # Quadratic loss function #%% Execute Gradient Descent algorithm #Define algorithm parameters total_iterations = 1e5 # Defines total training iterations GD_stepsize = 1e-4 # Gradient Descent fixed step size #To measure execution time time_start = timeit.default_timer() for index in range(int(total_iterations)): #Compute gradient (derived manually for the quadratic cost function) loss_gradient_W = 2.0/n_samples*np.sum(-x_data_input*(y_data_input - y_gd_approx)) loss_gradient_b = 2.0/n_samples*np.sum(-1*(y_data_input - y_gd_approx)) #Update trainable variables using fixed step size gradient descent W = W - GD_stepsize * loss_gradient_W b = b - GD_stepsize * loss_gradient_b #Compute loss y_gd_approx = W*x_data_input+b loss = np.sum((y_data_input - y_gd_approx)**2)/x_data_input.shape[0] #Print execution time time_end = timeit.default_timer() print('') print("Time to execute code: {0:0.9f} sec.".format(time_end - time_start)) print('') # %% Print results print('') print('Iteration = {0:0.3f}'.format(total_iterations)) print('W_val = {0:0.3f}'.format(W)) print('b_val = {0:0.3f}'.format(b)) print('')
The actual answer to my question is hidden in the various comments. For future readers, I will summarize these findings in this answer. About the speed difference between TensorFlow and a raw Python/NumPy implementation This part of the answer is actually quite logically. Each iteration (= each call of Session.run()) TensorFlow performs computations. TensorFlow has a large overhead for starting each computation. On GPU, this overhead is even worse than on CPU. However, TensorFlow executes the actual computations very efficient and more efficiently than the above raw Python/NumPy implementation does. So, when the number of data points is increased, and therefore the number of computations per iteration you will see that the relative performances between TensorFlow and Python/NumPy shifts in the advantage of TensorFlow. The opposite is also true. The problem described in the question is very small meaning that the number of computation is very low while the number of iterations is very large. That is why TensorFlow performs so badly. This type of small problems is not the typical use case for which TensorFlow was designed. To reduce the execution time Still the execution time of the TensorFlow script can be reduced a lot! To reduce the execution time the number of iterations must be reduced (no matter the size of the problem, this is a good aim anyway). As @amin's pointed out, this is achieved by scaling the input data. A very briefly explanation why this works: the size of the gradient and variable updates are more balanced compared to the absolute values for which the values are to be found. Therefore, less steps (= iterations) are required. Followings @amin's advise, I finally ended up by scaling my x-data as follows (some code is repeated to make the position of the new code clear): # Tensorflow is finicky about shapes, so resize x_data = np.reshape(x_data_input, (n_samples, 1)) y_data = np.reshape(y_data_input, (n_samples, 1)) ### START NEW CODE ### # Scale x_data x_mean = np.mean(x_data) x_std = np.std(x_data) x_data = (x_data - x_mean) / x_std ### END NEW CODE ### # Define placeholders for input X = tf.placeholder(tf.float32, shape=(n_samples, 1), name="tf_x_data") Y = tf.placeholder(tf.float32, shape=(n_samples, 1), name="tf_y_data") Scaling speed up the convergence by a factor 1000. Instead of 1e5 iterations, 1e2 iterations are needed. This is partially because a maximum step size of 1e-1 can be used instead of a step size of 1e-4. Please note that the found weight and bias are different and that you must feed scaled data from now on. Optionally, you can choose to unscale the found weight and bias so you can feed unscaled data. Unscaling is done using this code (put somewhere at the end of the code): #%% Unscaling W_val_unscaled = W_val[0,0]/x_std b_val_unscaled = b_val[0]-x_mean*W_val[0,0]/x_std
6
1
65,462,220
2020-12-27
https://stackoverflow.com/questions/65462220/how-to-create-custom-eval-metric-for-catboost
Similar SO questions: Python Catboost: Multiclass F1 score custom metric Catboost tutorials https://catboost.ai/docs/concepts/python-usages-examples.html#user-defined-loss-function Question In this question, I have a binary classification problem. After modelling we get the test model predictions y_pred and we already have true test labels y_true. I would like to get the custom evaluation metric defined by following equation: profit = 400 * truePositive - 200*fasleNegative - 100*falsePositive Also, since higher profit is better I would like to maximize the function instead of minimize it. How to get this eval_metric in catboost? Using sklearn def get_profit(y_true, y_pred): tn, fp, fn, tp = sklearn.metrics.confusion_matrix(y_true,y_pred).ravel() loss = 400*tp - 200*fn - 100*fp return loss scoring = sklearn.metrics.make_scorer(get_profit, greater_is_better=True) Using catboost class ProfitMetric(object): def get_final_error(self, error, weight): return error / (weight + 1e-38) def is_max_optimal(self): return True def evaluate(self, approxes, target, weight): assert len(approxes) == 1 assert len(target) == len(approxes[0]) approx = approxes[0] error_sum = 0.0 weight_sum = 0.0 ** I don't know here** return error_sum, weight_sum Question How to complete the custom eval metric in catboost? UPDATE My update so far import numpy as np import pandas as pd import seaborn as sns import sklearn from catboost import CatBoostClassifier from sklearn.model_selection import train_test_split def get_profit(y_true, y_pred): tn, fp, fn, tp = sklearn.metrics.confusion_matrix(y_true,y_pred).ravel() profit = 400*tp - 200*fn - 100*fp return profit class ProfitMetric: def is_max_optimal(self): return True # greater is better def evaluate(self, approxes, target, weight): assert len(approxes) == 1 assert len(target) == len(approxes[0]) approx = approxes[0] y_pred = np.rint(approx) y_true = np.array(target).astype(int) output_weight = 1 # weight is not used score = get_profit(y_true, y_pred) return score, output_weight def get_final_error(self, error, weight): return error df = sns.load_dataset('titanic') X = df[['survived','pclass','age','sibsp','fare']] y = X.pop('survived') X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100) model = CatBoostClassifier(metric_period=50, n_estimators=200, eval_metric=ProfitMetric() ) model.fit(X, y, eval_set=(X_test, y_test)) # this fails
The main difference from yours is: @staticmethod def get_profit(y_true, y_pred): y_pred = expit(y_pred).astype(int) y_true = y_true.astype(int) #print("ACCURACY:",(y_pred==y_true).mean()) tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() loss = 400*tp - 200*fn - 100*fp return loss It's not obvious from the example you linked what are the predictions, but after inspecting it turns out catboost treats predictions internally as raw log-odds (hat tip @Ben). So, to properly use confusion_matrix you need to make it sure both y_true and y_pred are integer class labels. This is done via: y_pred = scipy.special.expit(y_pred) y_true = y_true.astype(int) So the full working code is: import seaborn as sns from catboost import CatBoostClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from scipy.special import expit df = sns.load_dataset('titanic') X = df[['survived','pclass','age','sibsp','fare']] y = X.pop('survived') X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100) class ProfitMetric: @staticmethod def get_profit(y_true, y_pred): y_pred = expit(y_pred).astype(int) y_true = y_true.astype(int) #print("ACCURACY:",(y_pred==y_true).mean()) tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() loss = 400*tp - 200*fn - 100*fp return loss def is_max_optimal(self): return True # greater is better def evaluate(self, approxes, target, weight): assert len(approxes) == 1 assert len(target) == len(approxes[0]) y_true = np.array(target).astype(int) approx = approxes[0] score = self.get_profit(y_true, approx) return score, 1 def get_final_error(self, error, weight): return error model = CatBoostClassifier(metric_period=50, n_estimators=200, eval_metric=ProfitMetric() ) model.fit(X, y, eval_set=(X_test, y_test))
8
6
65,499,535
2020-12-29
https://stackoverflow.com/questions/65499535/how-to-create-an-asyncio-task-that-return-value
I'm figuring out how to return a list[] in asyncio I know asyncio.gather could help me but there are so many ways I'm now confused. How Do I return value from main() ? Thank async def wait_until(dt): # sleep until the specified datetime now = datetime.now() await asyncio.sleep((dt - now).total_seconds()) async def run_at(dt, coro): await wait_until(dt) return await coro async def main(): test=[] async for message in client.iter_messages(channel): test.append(message) return test loop = asyncio.get_event_loop() loop.create_task(run_at(datetime(2020, 12, 29, 19, 17),main())) loop.run_until_complete(asyncio.gather(*[main()])) # How to get test[] or How to pass it to another task? loop.run_forever()
From the asyncio.gather documentation: If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws. From the asyncio.loop.run_until_complete documentation: Return the Future’s result or raise its exception. So gather is an async def that returns all the results passed, and run_until_complete runs the loop "converting" the awaitable into the result. Basically, the return values are passed through: results = loop.run_until_complete(asyncio.gather(*[main()])) tests = results[0] Note that gather with just one item is redundant, as it's equivalent to just using that one item: tests = loop.run_until_complete(main()) If you want to communicate two independent tasks without using global variables, you probably want to use an asyncio.Queue, and give the same queue instance to both async def as input parameters. One will put "messages", and the other will get them. You can combine this with wait, gather, create_task, etc. to pretty much do everything you need.
6
7
65,437,506
2020-12-24
https://stackoverflow.com/questions/65437506/how-to-get-raw-html-with-absolute-links-paths-when-using-requests-html
When making a request using the requests library to https://stackoverflow.com page = requests.get(url='https://stackoverflow.com') print(page.content) I get the following: <!DOCTYPE html> <html class="html__responsive html__unpinned-leftnav"> <head> <title>Stack Overflow - Where Developers Learn, Share, &amp; Build Careers</title> <link rel="shortcut icon" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196"> <link rel="apple-touch-icon" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a"> <link rel="image_src" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a"> .......... These source code here have the absolute paths, but when running the same URL using requests-html with js rendering with HTMLSession() as session: page = session.get('https://stackoverflow.com') page.html.render() print(page.content) I get the following: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>StackOverflow.org</title> <script type="text/javascript" src="lib/jquery.js"></script> <script type="text/javascript" src="lib/interface.js"></script> <script type="text/javascript" src="lib/window.js"></script> <link href="lib/dock.css" rel="stylesheet" type="text/css" /> <link href="lib/window.css" rel="stylesheet" type="text/css" /> <link rel="icon" type="image/gif" href="favicon.gif"/> .......... The links here are relative paths, How can I get the source code with absolute paths like requests when using requests-html with js rendering?
This should probably a feature request for the request-html developers. However for now we can achieve this with this hackish solution: from requests_html import HTMLSession from lxml import etree with HTMLSession() as session: html = session.get('https://stackoverflow.com').html html.render() # iterate over all links for link in html.pq('a'): if "href" in link.attrib: # Make links absolute link.attrib["href"] = html._make_absolute(link.attrib["href"]) # Print html with only absolute links print(etree.tostring(html.lxml).decode()) We change the html-objects underlying lxml tree, by iterating over all links and changing their location to absolute using the html-object's private _make_absolute function.
5
2
65,420,550
2020-12-23
https://stackoverflow.com/questions/65420550/python-string-occurence-count-regex-performance
I was asked to find the total number of substring (case insensitive with/without punctuations) occurrences in a given string. Some examples: count_occurrences("Text with", "This is an example text with more than +100 lines") # Should return 1 count_occurrences("'example text'", "This is an 'example text' with more than +100 lines") # Should return 1 count_occurrences("more than", "This is an example 'text' with (more than) +100 lines") # Should return 1 count_occurrences("clock", "its 3o'clock in the morning") # Should return 0 I chose regex over .count() as I needed an exact match, and ended up with: def count_occurrences(word, text): pattern = f"(?<![a-z])((?<!')|(?<='')){word}(?![a-z])((?!')|(?=''))" return len(re.findall(pattern, text, re.IGNORECASE)) and I've got every matching count but my code took 0.10secs while expected time is 0.025secs. Am I missing something? is there any better (performance optimised) way to do this?
OK, I was struggling to make it work without regexes, as we all know that regexes are slow. Here is what I came up with: def count_occurrences(word, text): spaces = [' ', '\n', '(', 'Β«', '\u201d', '\u201c', ':', "''", "__"] endings = spaces + ['?', '.', '!', ',', ')', '"', 'Β»'] s = text.lower().split(word.lower()) l = len(s) return sum(( (i == 0 and (s[0] == '' or any(s[i].endswith(t) for t in spaces)) and (s[1] == '' or any(s[i+1].startswith(t) for t in endings))) or (i == l - 2 and any(s[i].endswith(t) for t in spaces) and (s[i+1] == '' or any(s[i+1].startswith(t) for t in endings))) or (i != 0 and i != l - 2 and any(s[i].endswith(t) for t in spaces) and any(s[i+1].startswith(t) for t in endings)) ) for i in range(l - 1)) The whole file runs in ideone: Ran 1 test in 0.025s OK Which is what the question is asking for. The logic is pretty simple. Let's split the text by word, both lower cased. Now let's look at each couple of neighbours. If, for example index 0 finished with a valid delimiter, and index 1 starts with a valid delimiter, let's count it as an occurrence. Let's do that up to the last couple of the split. Since performance is important here, we have to be aware to the order of spaces and endings. We are basically looking for the first in the list to fulfil the condition. So it is important to locate the variables that are more common first. For example, If I declare: spaces = ['(', 'Β«', '\u201d', '\u201c', ':', "''", "__", '\n', ' '] instead of what I have in my solution, I get a run of 0.036 seconds. If for example I declare one array: spaces = [' ', '\n', '(', 'Β«', '\u201d', '\u201c', ':', "''", "__", '?', '.', '!', ',', ')', '"', 'Β»'] which has all delimiters and use only that, I get 0.053 seconds. Which is 60% more than my solution. It is probably possible that there is a better solution with declaring the delimiters in another order.
7
3
65,487,163
2020-12-29
https://stackoverflow.com/questions/65487163/python-sphinx-autodoc-not-rendering-on-readthedocs
I have a Python package hosted on Github called spike2py. I have prepared my docs using Sphinx and .rst files. These files are hosted on GitHub here. I am able to successfully run make html locally and obtain the desired output. That is, the Reference Guide part of the documentation contains the API automatically generated using the docstring I have included in my code, and referenced using calls to autoclass and autofunction (reference_guide.rst). For example, here is what the first part of the Reference Guide looks like when I render it locally: However, when the documentation is rendered on readthedocs (see here), the Reference Guide does not contain the extracted doctrings; just the headers found in the .rst file. Expected behaviour I expected the docs rendered on readthedocs to be same as those rendered locally. However, this is not happening. By looking here, I have confirmed that the version being presented on readthedocs in the current version of my documentation. But when I try to download PDF or HTML versions of the documentation, the Reference Guide does not include the docstrings. Other info According to the readthedocs documentation, the local builds should not be pushed to GitHub; only the source files. This is somewhat related to this issue, but I was not able to make the proposed solution work. UPDATE I followed the solution recommended by Steve Piercy and this solved part of the problem. I added a docs/requirements.txt file as well as a .readthedocs.yml file. Next I noticed that the build was using Python 3.7.9. Given that I was using type hints from Python >= 3.8, I had to specify the version of Python in the .readthedocs.yml file. Then I was stuck with the RTD build telling me it can't find my index.rst file. Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/cmd/build.py", line 280, in build_main app.build(args.force_all, filenames) File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/application.py", line 348, in build self.builder.build_update() File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 297, in build_update self.build(to_build, File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 311, in build updated_docnames = set(self.read()) File "/home/docs/checkouts/readthedocs.org/user_builds/spike2py/envs/latest/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 421, in read raise SphinxError('master file %s not found' % sphinx.errors.SphinxError: master file /home/docs/checkouts/readthedocs.org/user_builds/spike2py/checkouts/latest/docs/index.rst not found Sphinx error: master file /home/docs/checkouts/readthedocs.org/user_builds/spike2py/checkouts/latest/docs/index.rst not found But I then solved this by specifying the following in my .readthedocs.yml: # Build documentation in the docs/ directory with Sphinx sphinx: configuration: docs/source/conf.py After this fix, the docs are built with what appears to be no errors and includes the following: generating indices... genindex py-modindexdone highlighting module code... [ 20%] spike2py.channels highlighting module code... [ 40%] spike2py.plot highlighting module code... [ 60%] spike2py.read highlighting module code... [ 80%] spike2py.sig_proc highlighting module code... [100%] spike2py.trial And yes, the doctrings appeared on RTD.
Your project's dependencies are not specified on RTD, but you have installed the dependencies locally. You can verify this in the build log. Visit your project's Builds, click a build, and click "view raw". WARNING: autodoc: failed to import class 'trial.TrialInfo' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'trial.Trial' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import function 'trial.load' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'channels.ChannelInfo' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'channels.Channel' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'channels.Event' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'channels.Keyboard' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'channels.Waveform' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'channels.Wavemark' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import class 'sig_proc.SignalProcessing' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import function 'plot.plot_channel' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import function 'plot.plot_trial' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) WARNING: autodoc: failed to import function 'read.read' from module 'spike2py'; the following exception was raised: cannot import name 'Literal' from 'typing' (/home/docs/.pyenv/versions/3.7.9/lib/python3.7/typing.py) To remedy the situation, you must specify that your project's dependencies must be installed. See Specifying Dependencies. You must either: Create a pip requirements file that specifies requirements, or Create a file that specifies a pip install option which will install requirements that are already defined elsewhere, such as in a setup.py docs_requires stanza. See an example in the Pyramid repository with its rtd.txt and setup.py. rtd.txt -e .[docs] setup.py docs_extras = [ 'Sphinx >= 3.0.0', # Force RTD to use >= 3.0.0 'docutils', 'pylons-sphinx-themes >= 1.0.8', # Ethical Ads 'pylons_sphinx_latesturl', 'repoze.sphinx.autointerface', 'sphinxcontrib-autoprogram', ] # ... extras_require={'testing': testing_extras, 'docs': docs_extras}, One you have defined your project requirements in this file, then you must configure Read the Docs to recognize this file to install dependencies. The preferred method is to use a configuration file, but you can also do this through the project's Admin Dashboard.
11
7
65,491,369
2020-12-29
https://stackoverflow.com/questions/65491369/how-to-specify-mypy-type-pytest-configure-fixtures
I am trying to specify mypy type hints for the pytest native fixtures I am using in my test project e.g.: import pytest def pytest_configure(config): # Do something useful here The config fixture returns a _pytest.config.Config object. If I try to model this naively: import pytest def pytest_configure(config: Config) -> None: # Do something useful here I receive a mypy error: conftest.py:3: error: Name 'Config' is not defined [name-defined] I could do from _pytest.config import Config, but this doesn't seem to be a good way, because _pytest is private. Another option would be to ignore the type with # type: ignore. If this is the recommended way I would of course do this, but I wonder if there is a better option. I have the same issues in with any kind of pytest native fixtures I use, e.g. request which is used for parameterized fixtures. This would be a _pytest.fixtures.FixtureRequest.
Importing from _pytest.config Since pytest doesn't currently export Config (as of 6.2), the only way for typing is to use from _pytest.config import Config. This is how I also type config, as can be seen e.g. in this question of mine: from _pytest.config import Config def pytest_configure(config: Config) -> None: ... You can track the typing progress in this pytest issue: #7469. Custom type stubs You can also introduce a small custom type stub that hides the reexport. It's questionable whether it will be useful here, only worth to mention for an alternative solution. If you create a file _typeshed/pytest.pyi with the following contents: from typing import Any from _pytest.config import Config as Config def __getattr__(name: str) -> Any: ... # incomplete and make it accessible to mypy in mypy.ini: [mypy] mypy_path = _typeshed Now you can import from pytest import Config at least in type checking mode - the runtime import will still fail. So the imports would look like from typing import Any, TYPE_CHECKING if TYPE_CHECKING: from pytest import Config else: Config = Any def pytest_configure(config: Config) -> None: pass The only benefit of that solution is that the private import is now hidden; I'd still go with the private import though.
9
6
65,496,688
2020-12-29
https://stackoverflow.com/questions/65496688/how-can-i-get-the-line-of-the-text-where-an-xml-tag-is-found-in-python-using-bs4
I have an XML document and I want to get the line at which the tag extracted by BeautifulSoup or lxml is found. Is there a way to do that?
For BeautifulSoup this attribute is stored in the sourceline attribute of the Tag class, and is being populated in the parsers here and here. For lxml this is also possible through the sourceline attribute. Here is an example: #!/usr/bin/python3 from lxml import etree xml = ''' <a> <b> <c> </c> </b> <d> </d> </a> ''' root = etree.fromstring(xml) for e in root.iter(): print(e.tag, e.sourceline) Output: a 2 b 3 c 4 d 7 If you want to look at the implementation of the sourceline method it's actually calling xmlGetLineNo which is a binding of xmlGetLineNo from libxml2 that is a wrapper for xmlGetLineNoInternal (where the actual logic for this lives inside libxml2). You can find the line number of the closing tag as well by checking how many line endings there are in the text representation of the subtree of that tag. xml.etree.ElementTree can also be extended to provide the line numbers where the elements have been found by the parser (the parser being xmlparser from the module xml.parsers.expat ).
5
4
65,486,981
2020-12-29
https://stackoverflow.com/questions/65486981/what-is-peg-parser-in-python
I was using the keyword built-in module to get a list of all the keywords of the current Python version. And this is what I did: >>> import keyword >>> print(keyword.kwlist) ['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] And in the keyword.kwlist list there is __peg_parser__. So to see what it does, I type __peg_parser__ in a Python 3.9 interpreter on Windows (you'll get the same output on Mac OS and Linux as well), and this is what is get: >>> __peg_parser__ File "<stdin>", line 1 __peg_parser__ ^ SyntaxError: You found it! So my question is, what is __peg_parser__ and why do I get SyntaxError: You found it!?
It was an easter egg related to the rollout of the new PEG parser. The easter egg, along with the old LL(1) parser, will be removed in 3.10.
62
39
65,483,030
2020-12-28
https://stackoverflow.com/questions/65483030/notch-reject-filtering-in-python
I'm trying to implement notch-reject filtering in python for an assignment. I have tried using the notch reject filter formula from Rafael Gonzales book and all I got was a edge detected image. Then I tried ideal notch rejecting and here are the results: Input image--Output of my program -- Expected output Here is my code: import cv2 import numpy as np import matplotlib.pyplot as plt def notch_reject_filter(shape, d0=9, u_k=0, v_k=0): P, Q = shape # Initialize filter with zeros H = np.zeros((P, Q)) # Traverse through filter for u in range(0, P): for v in range(0, Q): # Get euclidean distance from point D(u,v) to the center D_uv = np.sqrt((u - P / 2 + u_k) ** 2 + (v - Q / 2 + v_k) ** 2) D_muv = np.sqrt((u - P / 2 - u_k) ** 2 + (v - Q / 2 - v_k) ** 2) if D_uv <= d0 or D_muv <= d0: H[u, v] = 0.0 else: H[u, v] = 1.0 return H img = cv2.imread('input.png', 0) img_shape = img.shape original = np.fft.fft2(img) center = np.fft.fftshift(original) NotchRejectCenter = center * notch_reject_filter(img_shape, 32, 50, 50) NotchReject = np.fft.ifftshift(NotchRejectCenter) inverse_NotchReject = np.fft.ifft2(NotchReject) # Compute the inverse DFT of the result plot_image = np.concatenate((img, np.abs(inverse_NotchReject)),axis=1) plt.imshow(plot_image, "gray"), plt.title("Notch Reject Filter") plt.show()
all I got was a edge detected image because your implementation was High pass filter which is a black circle in the middle, and that works as Edge detector. Then I tried ideal notch rejecting This is correct if you applied that correctly. The main concept is to filter the undesired Noise in the frequency domain, the noise can be seen as white spots, and your role is to suppress that white spots by multiplying them by black circles in frequency domain(known as filtering). to improve this result add more notch filters (H5, H6, ...) to suppress the noise. import cv2 import numpy as np import matplotlib.pyplot as plt #------------------------------------------------------ def notch_reject_filter(shape, d0=9, u_k=0, v_k=0): P, Q = shape # Initialize filter with zeros H = np.zeros((P, Q)) # Traverse through filter for u in range(0, P): for v in range(0, Q): # Get euclidean distance from point D(u,v) to the center D_uv = np.sqrt((u - P / 2 + u_k) ** 2 + (v - Q / 2 + v_k) ** 2) D_muv = np.sqrt((u - P / 2 - u_k) ** 2 + (v - Q / 2 - v_k) ** 2) if D_uv <= d0 or D_muv <= d0: H[u, v] = 0.0 else: H[u, v] = 1.0 return H #----------------------------------------------------- img = cv2.imread('input.png', 0) f = np.fft.fft2(img) fshift = np.fft.fftshift(f) phase_spectrumR = np.angle(fshift) magnitude_spectrum = 20*np.log(np.abs(fshift)) img_shape = img.shape H1 = notch_reject_filter(img_shape, 4, 38, 30) H2 = notch_reject_filter(img_shape, 4, -42, 27) H3 = notch_reject_filter(img_shape, 2, 80, 30) H4 = notch_reject_filter(img_shape, 2, -82, 28) NotchFilter = H1*H2*H3*H4 NotchRejectCenter = fshift * NotchFilter NotchReject = np.fft.ifftshift(NotchRejectCenter) inverse_NotchReject = np.fft.ifft2(NotchReject) # Compute the inverse DFT of the result Result = np.abs(inverse_NotchReject) plt.subplot(222) plt.imshow(img, cmap='gray') plt.title('Original') plt.subplot(221) plt.imshow(magnitude_spectrum, cmap='gray') plt.title('magnitude spectrum') plt.subplot(223) plt.imshow(magnitude_spectrum*NotchFilter, "gray") plt.title("Notch Reject Filter") plt.subplot(224) plt.imshow(Result, "gray") plt.title("Result") plt.show()
6
9
65,480,707
2020-12-28
https://stackoverflow.com/questions/65480707/how-to-solve-symbolic-equations-on-numpy-arrays
I try to solve an equation with solve from Sympy. But my approach doesn't work as desired. My equation : 0.00622765954483725 = (x * 24.39 * 0.921107170819325) / 143860432.178345. My code : from sympy import symbols, solve import numpy as np x = symbols('x') sol = solve((np.array([[x],[x]]) * np.array([[24.39],[293.6]]) * np.array([[0.921107170819325],[1]])) / np.array([[143860432.178345],[143860432.178345]]) - np.array([[0.00622765954483725],[0.0089267519953503]])) I had success with a linear expression, but I have a DataFrame and I want to solve all data at the same time. from sympy import symbols, solve x = symbols('x') sol = solve((x * 24.39 * 0.921107170819325) / 143860432.178345 - 0.00622765954483725)
Numpy doesn't understand about sympy's symbols, nor does sympy understand about numpy arrays. The only way to make them work together, is with sympy's lambdify which can convert a symbolic sympy expression to a numpy function. In your case, you first need to create a symbolic solution, lambdify it, and call it on your arrays: from sympy import symbols, solve, Eq, lambdify a, b, c, d = symbols('a b c d', real=True) x = symbols('x') sol = solve(Eq(x * a * b / c, d), x) # solve returns a list of solutions, in this case a list with just one element np_sol = lambdify((a, b, c, d), sol[0]) # convert the first solution to a (numpy) function # everything before is only sympy, everything from here is only numpy import numpy as np a_np = np.array([[24.39], [293.6]]) b_np = np.array([[0.921107170819325], [1]]) c_np = np.array([[143860432.178345], [143860432.178345]]) d_np = np.array([[0.00622765954483725], [0.0089267519953503]]) np_sol(a_np, b_np, c_np, d_np) Result: array([[39879.], [ 4374.]])
5
4
65,479,238
2020-12-28
https://stackoverflow.com/questions/65479238/how-to-install-python-packages-in-a-virtual-environment-without-downloading-them
It's a great hassle when installing some packages in a VE and conda or pip downloads them again even when I already have it in my base environment. Since I have limited internet bandwidth and I'm assuming I'll work with many different VE's, it will take a lot of time to download basic packages such as OpenCV/Tensorflow.
By default, pip caches anything it downloads, and will used the cached version whenever possible. This cache is shared between your base environment and all virtual environments. So unless you pass the --no-cache-dir option, pip downloading a package means it has not previously downloaded a compatible version of that package. If you already have that package installed in your base environment or another virtual environment and it downloads it anyway, this probably means one or more of the following is true: You installed your existing version with a method other than pip. There is a newer version available, and you didn't specify, for example, pip install pandas=1.1.5 (if that's the version you already have elsewhere). Pip will install the newest compatible version for your environment, unless you tell it otherwise. The VE you're installing to is a different Python version (e.g. created with Pyenv), and needs a different build. I'm less familiar with the specifics of conda, and I can't seem to find anything in its online docs that focuses on the default caching behavior. However, a how-to for modifying the cache location seems to assume that the default behavior is similar to how pip works. Perhaps someone else with more Anaconda experience can chime in as well. So except for the caveats above, as long as you're installing a package with the same method you did last time, you shouldn't have to download anything. If you want to simplify the process of installing all the same packages (that were installed via pip) in a new VE that you already have in another environment, pip can automate that too. Run pip freeze > requirements.txt in the first environment, and copy the resulting file to your newly created VE. There, run pip install -r requirements.txt and pip will install all the packages that were installed (via pip) in the first environment. (Note that pip freeze records version numbers as well, so this won't install newer versions that may be available -- whether this is a good or bad thing depends on your needs.)
6
4
65,481,308
2020-12-28
https://stackoverflow.com/questions/65481308/argsort-dataframe-according-to-columns
I have the following DataFrame: userId column_1 column_2 column_3 A 4.959 3.231 1.2356 B 0.632 0.963 2.4556 C 3.234 7.445 5.3435 D 1.454 0.343 2.2343 I would like to argsort w.r.t columns from the previous one: userId first second third A column_3 column_2 column_1 B column_1 column_2 column_3 C column_1 column_3 column_2 D column_2 column_1 column_3
You can use np.argsort over axis 1. Then convert df.columns to numpy array using pd.Index.to_numpy and use numpy indexing. df = df.set_index('userId') # If userId is not index already. idx = df.values.argsort(axis=1) out = pd.DataFrame(df.columns.to_numpy()[idx], index=df.index) 0 1 2 userId A column_3 column_2 column_1 B column_1 column_2 column_3 C column_1 column_3 column_2 D column_2 column_1 column_3
5
9
65,481,013
2020-12-28
https://stackoverflow.com/questions/65481013/how-to-import-analysisexception-in-pyspark
I can't find how to import AnalysisException in PySpark so I can catch it. For example: df = spark.createDataFrame([[1, 2], [1, 2]], ['A', 'A']) try: df.select('A') except AnalysisException as e: print(e) Error message: NameError: name 'AnalysisException' is not defined
You can import it here: from pyspark.sql.utils import AnalysisException This is shown in the error traceback like Traceback (most recent call last): ... File "<string>", line 3, in raise_from pyspark.sql.utils.AnalysisException: cannot resolve ...
12
17
65,469,173
2020-12-27
https://stackoverflow.com/questions/65469173/matplotlib-add-border-around-group-of-bins-with-most-frequent-values-in-hexbin
I am making a hexbin plot with the following Python script: pitch = Pitch( line_color="#747474", pitch_color="#222222", orientation="vertical", half=True, plot_arrow=False ) fig, ax = pitch.create_pitch() ## color-map cmap = [ "#222222", "#3A2527", "#52282B", "#6A2B30", "#762C32", "#822D34", "#8E2F37", "#9A3039", "#B2323D", "#BE3440", "#CA3542", "#E13746" ] cmap = colors.ListedColormap(cmap) hexbin = ax.hexbin( 68 - shots_data['Y'], shots_data['X'], zorder=3, cmap=cmap, extent=(0, 68, 52, 104), gridsize=22, bins=13, ec="#222222", lw=3 ) The above code produces the following output: Now I want to add borders around the hexagons with the most frequent values, which will look something like this. Note that in the below image the white borders are hand drawn to show how the result will look like. I don't know how to do this. What should I add in the code to produce such result. Edit: I am getting some results but they are not perfect, here is the updated script: ## Pitch obejct pitch = Pitch( line_color="#747474", pitch_color="#222222", orientation="vertical", half=True, plot_arrow=False ) ## create-pitch fig, ax = pitch.create_pitch() ## colormap cmap = [ "#3A2527", "#52282B", "#6A2B30", "#822D34", "#822D34","#882E36", "#8E2F37", "#9A3039", "#B2323D", "#E13746" ] cmap = colors.ListedColormap(cmap) ## extent extent = ( shots_data['Y'].min(), shots_data['Y'].max(), shots_data['X'].min(), shots_data['X'].max(), ) ## main hexbin hexbin = ax.hexbin( 68 - shots_data['Y'], shots_data['X'], zorder=3, cmap=cmap, extent=extent, gridsize=22, ec="#222222", lw=1, bins="log", mincnt=1 ) ## hexbin with mincnt=6 cmap = [ "#822D34", "#882E36", "#8E2F37", "#9A3039", "#B2323D", "#E13746" ] cmap = colors.ListedColormap(cmap) ax.hexbin( 68 - shots_data['Y'], shots_data['X'], zorder=3, cmap=cmap, extent=extent, gridsize=22, ec="#bce7ef", lw=1, bins="log", mincnt=6 ) ## add rectangle rect = plt.Rectangle( xy=(-0.1, 104), width=68.1, height=1, zorder=3, fc="#222222" ) ax.add_patch(rect) This is producing the following result:
I worked out two versions for plotting a contour line for the hexagons. (header) import numpy as np, matplotlib.pyplot as plt, matplotlib.colors # color-map cmap = [ "#222222", "#3A2527", "#52282B", "#6A2B30", "#762C32", "#822D34", "#8E2F37", "#9A3039", "#B2323D", "#BE3440", "#CA3542", "#E13746"] cmap = matplotlib.colors.ListedColormap(cmap) #prepare data np.random.seed(10) shotsX = np.random.randn(1000)*20+10 shotsY = np.random.randn(1000)*15+50 #original plot cfg = dict(x=shotsX, y=shotsY, cmap=cmap, gridsize=22, extent=[0,100,0,100]) h = plt.hexbin( ec="#222222",lw=2,zorder=-3,**cfg) plt.axis('off'); 1) white glow This approach is similar to your edit. Call plt.hexbin multiple time with different lines styles as well as with the parameter mincnt: #draw thick white contours + overlay previous style cfg = {**cfg,'vmin':h.get_clim()[0], 'vmax':h.get_clim()[1]} plt.hexbin( ec="white" ,lw=5,zorder=-2,mincnt=10,**cfg) plt.hexbin( ec="#222222",lw=2,zorder=-1,mincnt=10,**cfg) plt.xlim(-3,103) #required as second call of plt.hexbin() plt.ylim(-3,103) #strangely affects the limits ... Strictly speaking the "glow" adds a highlight to hexagons with many counts. 2) Contours Drawing only white contour lines on top of the original hexagons is more complicated. You can solve this by finding the vertices (ie center) of the hexagons for each vertex calculate the segment lines extract outer lines draw def hexLines(a=None,i=None,off=[0,0]): '''regular hexagon segment lines as `(xy1,xy2)` in clockwise order with points in line sorted top to bottom for irregular hexagon pass both `a` (vertical) and `i` (horizontal)''' if a is None: a = 2 / np.sqrt(3) * i; if i is None: i = np.sqrt(3) / 2 * a; h = a / 2 xy = np.array([ [ [ 0, a], [ i, h] ], [ [ i, h], [ i,-h] ], [ [ i,-h], [ 0,-a] ], [ [-i,-h], [ 0,-a] ], #flipped [ [-i, h], [-i,-h] ], #flipped [ [ 0, a], [-i, h] ] #flipped ]) return xy+off; #get hexagon centers that should be highlighted verts = h.get_offsets() cnts = h.get_array() highl = verts[cnts > .5*cnts.max()] #create hexagon lines a = ((verts[0,1]-verts[1,1])/3).round(6) i = ((verts[1:,0]-verts[:-1,0])/2).round(6) i = i[i>0][0] lines = np.concatenate([hexLines(a,i,off) for off in highl]) #select contour lines and draw uls,c = np.unique(lines.round(4),axis=0,return_counts=True) for l in uls[c==1]: plt.plot(*l.transpose(),'w-',lw=2,scalex=False,scaley=False) Note: Finding matching contour lines depends on the float accuracy np.unique(lines.round(5),...), here a rounded to 4 decimals. Depending on input data this might have to be adjusted.
5
2
65,473,257
2020-12-28
https://stackoverflow.com/questions/65473257/ftpshook-airflow-522-ssl-tls-required-on-the-data-channel
I'm trying to use FTPSHook to send file through FTP TLS/SSL Explicit Encryption. Here's my code remote_filepath=pathfile local_filepath=pathfile2 hook = FTPSHook(ftp_conn_id='ftp_test') hook.store_file(remote_filepath, local_filepath) and I'm getting this error when I run the DAG: 522 SSL/TLS required on the data channel Does anyone ever done this before? How can I secure the connection with FTPSHook?
The ftplib (the underlying implementation of FTP(S) for the FTPSHook) does not encrypt the FTP data connection by default. To enable it, you have to call FTP_TLS.prot_p(). With FTPSHook API, you do it like this: hook = FTPSHook(ftp_conn_id='ftp_test') hook.get_conn().prot_p()
5
4
65,459,632
2020-12-26
https://stackoverflow.com/questions/65459632/cannot-import-pywinauto-on-windows-10
I installed pywinauto using pip install pywinauto. OS: Windows 10 Python: 3.6.2 When I run python and try to import pywinauto, I get the error: Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pywinauto.application import Application Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\__init__.py", line 89, in <module> from . import findwindows File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\findwindows.py", line 42, in <module> from . import controls File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\controls\__init__.py", line 36, in <module> from . import uiawrapper # register "uia" back-end (at the end of uiawrapper module) File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\controls\uiawrapper.py", line 47, in <module> from ..uia_defines import IUIA File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\uia_defines.py", line 181, in <module> pattern_ids = _build_pattern_ids_dic() File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\uia_defines.py", line 169, in _build_pattern_ids_dic if hasattr(IUIA().ui_automation_client, cls_name): File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\uia_defines.py", line 50, in __call__ cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs) File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\pywinauto\uia_defines.py", line 60, in __init__ self.UIA_dll = comtypes.client.GetModule('UIAutomationCore.dll') File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\comtypes\client\_generate.py", line 118, in GetModule mod = _CreateWrapper(tlib, pathname) File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\comtypes\client\_generate.py", line 183, in _CreateWrapper generate_module(tlib, ofi, pathname) File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\comtypes\tools\tlbparser.py", line 750, in generate_module gen.generate_code(list(items.values()), filename=pathname) File "C:\Users\John\AppData\Roaming\Python\Python36\site-packages\comtypes\tools\codegenerator.py", line 261, in generate_code tlib_mtime = os.stat(self.filename).st_mtime FileNotFoundError: [WinError 2] The system cannot find the file specified: 'UIAutomationCore.dll' Any ideas how to fix this?
I have the same issue today and fixed it by pip install comtypes==1.1.7. It caused by comtypes library which release a new version 1.1.8 at Dec.26. Downgrade to previous version, it works well now.
12
24
65,471,540
2020-12-27
https://stackoverflow.com/questions/65471540/get-monthly-average-in-pandas
I have the following time series: Date Value 0 2006-01-03 18 1 2006-01-04 12 2 2006-01-05 11 3 2006-01-06 10 4 2006-01-09 22 ... ... ... 3510 2019-12-23 47 3511 2019-12-24 46 3512 2019-12-26 35 3513 2019-12-27 35 3514 2019-12-30 28 I want to calculate the average values per month. So the pseudocode for each month is as follows: Sum all the values for each day present in that month Divide by the number of days with data for that month. The desired output would be something similar to: Date Value 0 2006-01 17.45 1 2006-02 18.23 2 2006-04 16.79 3 2006-05 17.98 ... ... ... 166 2019-11 37.89 167 2019-12 36.34 I have tried this without success: data = data.set_index('Date') data.resample('M') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-435afe449f1f> in <module> 47 data = pd.DataFrame(dataList, columns=('Date', 'Value')) 48 data = data.set_index('Date') ---> 49 data.resample('M')
We can convert your datetime column into a PeriodIndex on monthly frequency, then take the mean using GroupBy.mean: df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['Value'].mean() Date 2006-01 14.6 2019-12 38.2 Freq: M, Name: Value, dtype: float64 df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['Value'].mean().reset_index() Date Value 0 2006-01 14.6 1 2019-12 38.2 One caveat of this approach is that missing months are not shown. If that's important, use set_index and resample.mean in the same way.
9
14
65,467,349
2020-12-27
https://stackoverflow.com/questions/65467349/pandas-data-frame-filtering-multiple-conditions
I have the following data frame df = pd.DataFrame([[1990,7,1000],[1990,8,2500],[1990,9,2500],[1990,9,1500],[1991,1,250],[1991,2,350],[1991,3,350],[1991,7,450]], columns = ['year','month','data1']) year month data1 1990 7 1000 1990 8 2500 1990 9 2500 1990 9 1500 1991 1 250 1991 2 350 1991 3 350 1991 7 450 I would like to filter the data such that it won't contain data with month/year 07/1990, 08/1990 and 01/1991. I can do for each combination month/year as follow: df = df.loc[(df.year != 1990) | (df.month != 7)] But it is not efficient if there are many combinations month/year. Is there any more efficient way of doing this? Many thanks.
You could do: mask = ~df[['year', 'month']].apply(tuple, 1).isin([(1990, 7), (1990, 8), (1991, 1)]) print(df[mask]) Output year month data1 2 1990 9 2500 3 1990 9 1500 5 1991 2 350 6 1991 3 350 7 1991 7 450
11
11
65,463,794
2020-12-27
https://stackoverflow.com/questions/65463794/valueerror-unknown-label-type-continuous-in-decisiontreeclassifier
I am trying to create a model which predicts results column below: Date Open High Close Result 1/22/2010 25.95 31.29 30.89 0.176104 2/19/2010 23.98 24.22 23.60 -0.343760 3/19/2010 21.46 23.16 22.50 0.124994 4/23/2010 21.32 21.77 21.06 -0.765601 5/21/2010 55.41 55.85 49.06 0.302556 The code I am using is: import pandas from sklearn.tree import DecisionTreeClassifier dataset = pandas.read_csv('data.csv') X = dataset.drop(columns=['Date','Result']) y = dataset.drop(columns=['Date', 'Open', 'High', 'Close']) model = DecisionTreeClassifier() model.fit(X, y) But I am getting an error: ValueError: Unknown label type: 'continuous' Suggestion for using other algorithms are also welcome.
In ML, it's important as a first step to consider the nature of your problem. Is it a regression or classification problem? Do you have target data (supervised learning) or is this a problem where you don't have a target and want to learn more about your data's inherent structure (such as unsupervised learning). Then, consider what steps you need to take in your pipeline to prepare your data (preprocessing). In this case, you are passing floats (floating point numbers) to a Classifier (DecisionTreeClassifier). The problem with this is that a classifier generally separates distinct classes, and so this classifier expects a string or an integer type to distinguish different classes from each other (this is known as the "target"). You can read more about this in an introduction to classifiers. The problem you seek to solve is to determine a continuous numerical output, Result. This is known as a regression problem, and so you need to use a Regression algorithm (such as the DecisionTreeRegressor). You can try other regression algorithms out once you have this simple one working, and this is a good place to start as it is a fairly straight forward one to understand, it is fairly transparent, it is fast, and easily implemented - so decision trees were a great choice of starting point! As a further note, it is important to consider preprocessing your data. You have done some of this simply by separating your target from your input data: X = dataset.drop(columns=['Date','Result']) y = dataset.drop(columns=['Date', 'Open', 'High', 'Close']) However, you may wish to look into preprocessing further, particularly standardisation of your data. This is often a required step for whichever ML algorithm you implement to be able to interpret your data. There's a saying that goes: "Garbage in, garbage out". Part of preprocessing sometimes requires you to change the data type of a given column. The error posted in your question, at face value, leads one to think that the issue on hand is that you need to change data types. But, as explained, in the case of your problem, it wouldn't help to do that, given that you seek to use regression to determine a continuous output.
5
12
65,463,877
2020-12-27
https://stackoverflow.com/questions/65463877/pyspark-illegal-reflective-access-operation-when-executed-in-terminal
I've installed Spark and components locally and I'm able to execute PySpark code in Jupyter, iPython and via spark-submit - however receiving the following WARNING's: WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/ayubk/spark-3.0.1-bin-hadoop3.2/jars/spark-unsafe_2.12-3.0.1.jar) to constructor java.nio.DirectByteBuffer(long,int) WARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release 20/12/27 07:54:01 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties The .py file executes but should I be worried about these warnings? Don't want to start writing some code to later find that it doesn't execute down the line. FYI installed PySpark locally. Here's the code: test.txt: This is a test file This is the second line - TEST This is the third line this IS THE fourth LINE - tEsT test.py: import pyspark sc = pyspark.SparkContext.getOrCreate() # sc = pyspark.SparkContext(master='local[*]') # or 'local[2]' ? lines = sc.textFile("test.txt") llist = lines.collect() for line in llist: print(line) print("SparkContext version:\t", sc.version) # return SparkContext version print("python version:\t", sc.pythonVer) # return python version print("master URL:\t", sc.master) # master URL to connect to print("path where spark is installed on worker nodes:\t", sc.sparkHome) # path where spark is installed on worker nodes print("name of spark user running SparkContext:\t", sc.sparkUser()) # name of spark user running SparkContext PATHs: export SPARK_HOME=/Users/ayubk/spark-3.0.1-bin-hadoop3.2 export PATH=$SPARK_HOME:$PATH export PYTHONPATH=$SPARK_HOME/python:$PYTHONPATH export PYSPARK_DRIVER_PYTHON="jupyter" export PYSPARK_DRIVER_PYTHON_OPTS="notebook" export PYSPARK_PYTHON=python3 bash terminal: $ spark-3.0.1-bin-hadoop3.2/bin/spark-submit test.py WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/ayubk/spark-3.0.1-bin-hadoop3.2/jars/spark-unsafe_2.12-3.0.1.jar) to constructor java.nio.DirectByteBuffer(long,int) WARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release 20/12/27 08:00:00 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties 20/12/27 08:00:01 INFO SparkContext: Running Spark version 3.0.1 20/12/27 08:00:01 INFO ResourceUtils: ============================================================== 20/12/27 08:00:01 INFO ResourceUtils: Resources for spark.driver: 20/12/27 08:00:01 INFO ResourceUtils: ============================================================== 20/12/27 08:00:01 INFO SparkContext: Submitted application: test.py 20/12/27 08:00:01 INFO SecurityManager: Changing view acls to: ayubk 20/12/27 08:00:01 INFO SecurityManager: Changing modify acls to: ayubk 20/12/27 08:00:01 INFO SecurityManager: Changing view acls groups to: 20/12/27 08:00:01 INFO SecurityManager: Changing modify acls groups to: 20/12/27 08:00:01 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(ayubk); groups with view permissions: Set(); users with modify permissions: Set(ayubk); groups with modify permissions: Set() 20/12/27 08:00:02 INFO Utils: Successfully started service 'sparkDriver' on port 51254. 20/12/27 08:00:02 INFO SparkEnv: Registering MapOutputTracker 20/12/27 08:00:02 INFO SparkEnv: Registering BlockManagerMaster 20/12/27 08:00:02 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information 20/12/27 08:00:02 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up 20/12/27 08:00:02 INFO SparkEnv: Registering BlockManagerMasterHeartbeat 20/12/27 08:00:02 INFO DiskBlockManager: Created local directory at /private/var/folders/11/13mml0s91q39ckbt584szkp00000gn/T/blockmgr-a99e3df1-6d15-4158-8e09-568910c2b045 20/12/27 08:00:02 INFO MemoryStore: MemoryStore started with capacity 434.4 MiB 20/12/27 08:00:02 INFO SparkEnv: Registering OutputCommitCoordinator 20/12/27 08:00:02 INFO Utils: Successfully started service 'SparkUI' on port 4040. 20/12/27 08:00:02 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://192.168.1.101:4040 20/12/27 08:00:02 INFO Executor: Starting executor ID driver on host 192.168.1.101 20/12/27 08:00:02 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 51255. 20/12/27 08:00:02 INFO NettyBlockTransferService: Server created on 192.168.1.101:51255 20/12/27 08:00:02 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy 20/12/27 08:00:02 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 192.168.1.101, 51255, None) 20/12/27 08:00:02 INFO BlockManagerMasterEndpoint: Registering block manager 192.168.1.101:51255 with 434.4 MiB RAM, BlockManagerId(driver, 192.168.1.101, 51255, None) 20/12/27 08:00:02 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 192.168.1.101, 51255, None) 20/12/27 08:00:03 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, 192.168.1.101, 51255, None) 20/12/27 08:00:03 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 175.8 KiB, free 434.2 MiB) 20/12/27 08:00:03 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 27.1 KiB, free 434.2 MiB) 20/12/27 08:00:03 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on 192.168.1.101:51255 (size: 27.1 KiB, free: 434.4 MiB) 20/12/27 08:00:03 INFO SparkContext: Created broadcast 0 from textFile at NativeMethodAccessorImpl.java:0 20/12/27 08:00:04 INFO FileInputFormat: Total input files to process : 1 20/12/27 08:00:04 INFO SparkContext: Starting job: collect at /Users/ayubk/test.py:9 20/12/27 08:00:04 INFO DAGScheduler: Got job 0 (collect at /Users/ayubk/test.py:9) with 2 output partitions 20/12/27 08:00:04 INFO DAGScheduler: Final stage: ResultStage 0 (collect at /Users/ayubk/test.py:9) 20/12/27 08:00:04 INFO DAGScheduler: Parents of final stage: List() 20/12/27 08:00:04 INFO DAGScheduler: Missing parents: List() 20/12/27 08:00:04 INFO DAGScheduler: Submitting ResultStage 0 (test.txt MapPartitionsRDD[1] at textFile at NativeMethodAccessorImpl.java:0), which has no missing parents 20/12/27 08:00:04 INFO MemoryStore: Block broadcast_1 stored as values in memory (estimated size 4.0 KiB, free 434.2 MiB) 20/12/27 08:00:04 INFO MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 2.3 KiB, free 434.2 MiB) 20/12/27 08:00:04 INFO BlockManagerInfo: Added broadcast_1_piece0 in memory on 192.168.1.101:51255 (size: 2.3 KiB, free: 434.4 MiB) 20/12/27 08:00:04 INFO SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1223 20/12/27 08:00:04 INFO DAGScheduler: Submitting 2 missing tasks from ResultStage 0 (test.txt MapPartitionsRDD[1] at textFile at NativeMethodAccessorImpl.java:0) (first 15 tasks are for partitions Vector(0, 1)) 20/12/27 08:00:04 INFO TaskSchedulerImpl: Adding task set 0.0 with 2 tasks 20/12/27 08:00:04 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, 192.168.1.101, executor driver, partition 0, PROCESS_LOCAL, 7367 bytes) 20/12/27 08:00:04 INFO TaskSetManager: Starting task 1.0 in stage 0.0 (TID 1, 192.168.1.101, executor driver, partition 1, PROCESS_LOCAL, 7367 bytes) 20/12/27 08:00:04 INFO Executor: Running task 0.0 in stage 0.0 (TID 0) 20/12/27 08:00:04 INFO Executor: Running task 1.0 in stage 0.0 (TID 1) 20/12/27 08:00:04 INFO HadoopRDD: Input split: file:/Users/ayubk/test.txt:52+52 20/12/27 08:00:04 INFO HadoopRDD: Input split: file:/Users/ayubk/test.txt:0+52 20/12/27 08:00:04 INFO Executor: Finished task 1.0 in stage 0.0 (TID 1). 956 bytes result sent to driver 20/12/27 08:00:04 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 1003 bytes result sent to driver 20/12/27 08:00:04 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 156 ms on 192.168.1.101 (executor driver) (1/2) 20/12/27 08:00:04 INFO TaskSetManager: Finished task 1.0 in stage 0.0 (TID 1) in 142 ms on 192.168.1.101 (executor driver) (2/2) 20/12/27 08:00:04 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool 20/12/27 08:00:04 INFO DAGScheduler: ResultStage 0 (collect at /Users/ayubk/test.py:9) finished in 0.241 s 20/12/27 08:00:04 INFO DAGScheduler: Job 0 is finished. Cancelling potential speculative or zombie tasks for this job 20/12/27 08:00:04 INFO TaskSchedulerImpl: Killing all running tasks in stage 0: Stage finished 20/12/27 08:00:04 INFO DAGScheduler: Job 0 finished: collect at /Users/ayubk/test.py:9, took 0.296115 s This is a test file This is the second line - TEST This is the third line this IS THE fourth LINE - tEsT SparkContext version: 3.0.1 python version: 3.7 master URL: local[*] path where spark is installed on worker nodes: None name of spark user running SparkContext: ayubk 20/12/27 08:00:04 INFO SparkContext: Invoking stop() from shutdown hook 20/12/27 08:00:04 INFO SparkUI: Stopped Spark web UI at http://192.168.1.101:4040 20/12/27 08:00:04 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped! 20/12/27 08:00:04 INFO MemoryStore: MemoryStore cleared 20/12/27 08:00:04 INFO BlockManager: BlockManager stopped 20/12/27 08:00:04 INFO BlockManagerMaster: BlockManagerMaster stopped 20/12/27 08:00:04 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped! 20/12/27 08:00:04 INFO SparkContext: Successfully stopped SparkContext 20/12/27 08:00:04 INFO ShutdownHookManager: Shutdown hook called 20/12/27 08:00:04 INFO ShutdownHookManager: Deleting directory /private/var/folders/11/13mml0s91q39ckbt584szkp00000gn/T/spark-eb41b5d5-16e2-4938-8049-8f923e6cb46c 20/12/27 08:00:04 INFO ShutdownHookManager: Deleting directory /private/var/folders/11/13mml0s91q39ckbt584szkp00000gn/T/spark-76d186fb-cf42-4898-92db-050a73f9fcb7 20/12/27 08:00:04 INFO ShutdownHookManager: Deleting directory /private/var/folders/11/13mml0s91q39ckbt584szkp00000gn/T/spark-eb41b5d5-16e2-4938-8049-8f923e6cb46c/pyspark-ee1fe6ab-a27f-4be6-b8d8-06594704da12 Edit: Tried to install Java8: brew update brew tap adoptopenjdk/openjdk brew search jdk brew install --cask adoptopenjdk8 Although when typing this java -version, I'm getting this: openjdk version "13" 2019-09-17 OpenJDK Runtime Environment (build 13+33) OpenJDK 64-Bit Server VM (build 13+33, mixed mode, sharing)
Install Java 8 instead of Java 11, which is known to give this sort of warnings with Spark.
14
8
65,463,062
2020-12-27
https://stackoverflow.com/questions/65463062/azure-functions-parameters-are-declared-in-python-but-not-in-function-json
I cannot understand what is going on. I literally follow all Microsoft docs and in fact don't even use any of my own scripts/codes. Firstly, I followed their docs to create Python function. It worked. https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-python?tabs=azure-cli%2Ccmd%2Cbrowser Second docs to connect Azure Functions to Azure Storage using command line tools. Are not reproducible. https://learn.microsoft.com/en-us/azure/azure-functions/functions-add-output-binding-storage-queue-cli?pivots=programming-language-python&tabs=bash%2Cbrowser I literally follow every step, yet receive error. What is more surprising is that they end up showing me different codes from first article. I tried both versions --none worked. These are the codes literally from their docs. This is their code for python script (init.py) import logging import azure.functions as func def main(req: func.HttpRequest, msg: func.Out[func.QueueMessage]) -> str: name = req.params.get('name') if not name: try: req_body = req.get_json() except ValueError: pass else: name = req_body.get('name') if name: msg.set(name) return func.HttpResponse(f"Hello {name}!") else: return func.HttpResponse( "Please pass a name on the query string or in the request body", status_code=400 ) And this is JSON function code: { "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" }, { "type": "queue", "direction": "out", "name": "msg", "queueName": "outqueue", "connection": "AzureWebJobsStorage" } ] } Since they didn't post full version of code I added stuff like brackets. If you want docs citation that's what they say: Although a function can have only one trigger, it can have multiple input and output bindings, which let you connect to other Azure services and resources without writing custom integration code. You declare these bindings in the function.json file in your function folder. From the previous quickstart, your function.json file in the HttpExample folder contains two bindings in the bindings collection: "scriptFile": "__init__.py", "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" } Each binding has at least a type, a direction, and a name. In the example above, the first binding is of type httpTrigger with the direction in. For the in direction, name specifies the name of an input parameter that's sent to the function when invoked by the trigger. The second binding in the collection is of type http with the direction out, in which case the special name of $return indicates that this binding uses the function's return value rather than providing an input parameter. To write to an Azure Storage queue from this function, add an out binding of type queue with the name msg, as shown in the code below: "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" }, { "type": "queue", "direction": "out", "name": "msg", "queueName": "outqueue", "connection": "AzureWebJobsStorage" } ] In this case, msg is given to the function as an output argument. For a queue type, you must also specify the name of the queue in queueName and provide the name of the Azure Storage connection (from local.settings.json) in connection. So even though this code was posted in docs it doesn't seem to work properly. OR their python code is not working. I don't know. I tried to just follow their steps. I also tried to copy-paste their new version of code (that varied a little from original) But nothing works I still get this error (I changed few elements that I suspect to be sensitive) (.venv) C:\Users\usr\LocalFunctionProj>func start Found Python version 3.8.5 (py). Azure Functions Core Tools Core Tools Version: 3.0.3160 Commit hash: 00aa7f49cc5c5f15241a5e6e5363256f19ceb980 Function Runtime Version: 3.0.14916.0 Functions: HttpExample: [GET,POST] http://localhost:8072/api/HttpExample For detailed output, run func with --verbose flag. [2020-12-27T08:45:11.912Z] Worker process started and initialized. [2020-12-27T08:45:12.048Z] Worker failed to function id ebece17c-3077-4f78-bcca-d46565cef86c. [2020-12-27T08:45:12.050Z] Result: Failure Exception: FunctionLoadError: cannot load the HttpExample function: the following parameters are declared in Python but not in function.json: {'msg'} Stack: File "D:\Program Files\Microsoft\Azure Functions Core Tools\workers\python\3.8\WINDOWS\X64\azure_functions_worker\dispatcher.py", line 272, in _handle__function_load_request self._functions.add_function( File "D:\Program Files\Microsoft\Azure Functions Core Tools\workers\python\3.8\WINDOWS\X64\azure_functions_worker\functions.py", line 112, in add_function raise FunctionLoadError( . [2020-12-27T08:45:16.457Z] Host lock lease acquired by instance ID '000000000000000000000000AF616381'. I really cannot understand how their own code doesn't work. All I wanted to do is to learn how to deploy my python scripts to Azure, I didn't expect it to be such a big challenge. This is how my updated python init.py code looks like after example answer: This is how updated function.json code looks like after example answer: This is how location.setting looks like (with sensitive info changed) This is how host.js look like
Try below and it will works fine: host.json { "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[1.*, 2.0.0)" } } __init__.py import logging import azure.functions as func def main(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse: msg.set("This is test. 1227") return func.HttpResponse("This is a test.") function.json { "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "$return" }, { "type": "queue", "direction": "out", "name": "msg", "queueName": "outqueue", "connection": "AzureStorageQueuesConnectionString" } ] } local.settings.json { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "", "FUNCTIONS_WORKER_RUNTIME": "python", "AzureStorageQueuesConnectionString":"DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx==;EndpointSuffix=core.windows.net" } }
10
4
65,462,266
2020-12-27
https://stackoverflow.com/questions/65462266/find-out-skipped-values-in-a-series-of-integers
I have a column in my dataframe being the customer ids which contains no repetitions. The id series starts at integer 1, and ends at 4003. As the following output shows, there are 4 id numbers being skipped. I would like some help in finding out what they are. Thanks in advance! df['customer_id'].describe() Out[150]: count 3999 unique 3999 top 4003 freq 1 Name: customer_id, dtype: int64
Assuming the dtype is int (which appears to be the case), it looks like we can use setdiff1d here from numpy: c_id = df['customer_id'] missing_ids = np.setdiff1d(np.arange(c_id.min(), c_id.max()+1), c_id)
5
4
65,461,959
2020-12-27
https://stackoverflow.com/questions/65461959/calling-a-static-method-with-self-vs-class-name
Calling Python static methods using the class name is more common, but can be a real eye sore for long class names. Sometimes I use self within the same class to call the static methods, because I find it looks cleaner. class ASomewhatLongButDescriptiveClassName: def __init__(self): # This works, but it's an eyesore ASomewhatLongButDescriptiveClassName.do_something_static() # This works too and looks cleaner. self.do_something_static() @staticmethod def do_something_static(): print('Static method called.') My understanding is that calling a static method with self gets interpreted as ClassName.static_method(self), where self would be ignored by the static method. (EDIT: The above statement is only true for instance methods, not static methods) Are there any concrete reasons why I should not use self to call static methods within the same class? FWIW This is a sister question to Difference between calling method with self and with class name?, which deals with non-static methods.
You make a few statements that aren't entirely correct: Calling Python static methods using the class name is more common It's not more common, it's the only way to do so from outside the class. i.e.: class MyClass: @staticmethod def a_method(): pass MyClass.a_method() In this example, self.a_method() would not work, as self would not refer to an instance of MyClass. calling a static method with self is the same as ClassName.static_method(self), where self would be ignored by the static method That's not actually the case, for example: class MyClass: @staticmethod def a_method(): pass def another_method(self): # this is fine self.a_method() # this causes an error, as .a_method expects no arguments MyClass.a_method(self) self simply refers to the instance of the class that called an instance method (which has the self argument, which doesn't even have to be called self - it's just whatever the first parameter is called, self is the convention. You can call static methods on self, because self is an instance of the class that has the static method, and thus has the method. You can also call static methods on classes directly, because a static method doesn't require an object instance as a first argument - which is the point of the static method. You're fine using self.a_method() where you like, just keep in mind that self will refer to an object of the class the object was instanced as, not the specific class you mention. For example: class ClassA: @staticmethod def a_method(): print('a') def another_method(self): # prints whatever a_method for the class of self prints self.a_method() # always prints 'a', as a_method for ClassA prints 'a' ClassA.a_method() class ClassB(ClassA): @staticmethod def a_method(): print('b') a = ClassA() a.another_method() b = ClassB() b.another_method() The output: a a b a So, you see, there is a difference between calling from self. and from Class.
15
32
65,456,517
2020-12-26
https://stackoverflow.com/questions/65456517/join-two-dataframes-on-common-columns-only-if-the-difference-in-a-separate-colum
I have two data frames df1 and df2 as shown below: df1 Date BillNo. Amount 10/08/2020 ABBCSQ1ZA 878 10/09/2020 AADC9C1Z5 11 10/12/2020 AC928Q1ZS 3998 10/14/2020 AC9268RE3 198 10/16/2020 AA171E1Z0 5490 10/19/2020 BU073C1ZW 3432 df2 Date BillNo. Amount 10/08/2020 ABBCSQ1ZA 876 10/11/2020 ATRC95REW 115 10/14/2020 AC9268RE3 212 10/16/2020 AA171E1Z0 5491 10/25/2020 BPO66W2LO 344 My final answer should be: final Date BillNo. Amount 10/08/2020 ABBCSQ1ZA 876 10/16/2020 AA171E1Z0 5491 How do I find common rows from both the data frame using Date BillNo. Amount when the difference in value range is between [-5,5]? I know how to find common rows by using: df_all = df1.merge(df2.drop_duplicates(), on=['Date', 'BillNo.', 'Amount'], how='outer', indicator=True) However, this doesn't give the rows which are in range. Anyone who could help? Edit: We can see in df1: 10/14/2020,AC9268RE3,198 and df2: 10/14/2020,AC9268RE3,212 the difference is 14, hence this should not be included in common rows
We can merge, then perform a query to drop rows not within the range: (df1.merge(df2, on=['Date', 'BillNo.']) .query('abs(Amount_x - Amount_y) <= 5') .drop('Amount_x', axis=1)) Date BillNo. Amount_y 0 10/08/2020 ABBCSQ1ZA 876 1 10/16/2020 AA171E1Z0 5491 This works well as long as there is only one row that corresponds to a specific (Date, BillNo) combination in each frame.
7
8
65,451,000
2020-12-25
https://stackoverflow.com/questions/65451000/python-command-not-found-on-linux
I have a problem while running python on linux, I have python3 already installed. When type python3 on the terminal i got: python 3.9.0 When I run any program I made with for example python I got this error bash: python: command not found And this happen to every python program I try to install on my machine.
Place the below line in ~/.bashrc file: alias python=python3 After inserting run the below command: source ~/.bashrc .bashrc is the configuration file for bash, a linux shell/command interpreter. An alias is a substitute for a (complete) command. It can be thought of as a shortcut. By adding the above line, an alias is created for python3 in the name of python. Now the programs using python instead of python3 should work fine without any error.
9
8
65,453,576
2020-12-26
https://stackoverflow.com/questions/65453576/diference-between-os-getcwd-and-os-path-dirname-file
In a previous project, I used the first version of the following two lines. Now that I found getcwd() I thought this would be the shorter alternative. print(os.path.dirname(__file__)) # D:/Personal_Software/my_project print(os.getcwd()) # D:\Personal_Software\my_project I already read this post, but the thing I'm curious about is the use of "/" vs. "\". I'm using Windows 10 if that's relevant.
There is a difference, though you wouldn't be able to tell from a single script. __file__ is the full filename of a loaded module or script, so getting the parent directory of it with os.path.dirname(__file__) gets you the directory that script is in. Note: on Linux (and similar OSes), such a filename can be a symbolic link to the actual file which may reside somewhere else. You can use os.path.realpath() to resolve through any such links, if needed, although you can typically use the symlink equivalently. On Windows these are less common, but similarly, you can resolve symbolic links through realpath(). os.getcwd() gets you the current working directory. If you start a script from the directory the script is in (which is common), the working directory will be the same as the result from the call from os.path.dirname(__file__). But if you start the script from another directory (i.e. python d:\some\path\script.py), or if you change the working directory during the script (e.g. with os.chdir()), the current working directory has changed, but the directory part of the script filename has not. So, it depends on what you need: Need the directory your script file is in? Use os.path.dirname(__file__) Need the directory your script is currently running in? use os.getcwd() You'll see / in some results and \ in others. Sadly, MS Windows uses \ to separate parts of a path (e.g. C:\Program Files\App\), while pretty much all other operating systems use / (e.g. /home/user/script.py) Python will often convert those automatically, so you can use paths like C:/Program Files/App in Python on Windows as well, but it tends to be a good idea to be safe and use os.path.sep. Note: if you're on Python 3, you may be better off just using pathlib's Path instead of os.path. It automatically resolves symbolic links (although you can still resolve to the link if you prefer) and has other nice conveniences as well.
11
3
65,444,396
2020-12-25
https://stackoverflow.com/questions/65444396/how-can-i-combine-two-dataframes-based-on-a-column-of-lists-in-pandas
import pandas as pd Reproducible setup I have two dataframes: df=\ pd.DataFrame.from_dict({'A':['xy','yx','zy','zz'], 'B':[[1, 3],[4, 3, 5],[3],[2, 6]]}) df2=\ pd.DataFrame.from_dict({'B':[1,3,4,5,6], 'C':['pq','rs','pr','qs','sp']}) df looks like: A B 0 xy [1, 3] 1 yx [4, 3, 5] 2 zy [3] 3 zz [2, 6] df2 looks like: B C 0 1 pq 1 3 rs 2 4 pr 3 5 qs 4 6 sp Aim I would like to combine these two to form res: res=\ pd.DataFrame.from_dict({'A':['xy','yx','zy','zz'], 'C':['pq','pr','rs','sp']}) ie A C 0 xy pq 1 yx pr 2 zy rs 3 zz sp The row with xy in df has the lsit [1,3]. There is a row with value 1 in column B in df2. The C column has value pq in that row, so I combine xy with pq. Same for the next two rows. Last row: there is no value with 2 in column B in df2, so I go for the value 6 (the last row in df has the list [2,6]). Question How can I achieve this without iterating through the dataframe? A very similar post in Spanish SO, which inspired this post.
You can explode "B" into separate rows, then merge on "B" and drop duplicates. Big thanks to Asish M. in the comments for pointing out a potential bug with the ordering. (df.explode('B') .merge(df2, on='B', how='left') .dropna(subset=['C']) .drop_duplicates('A')) A B C 0 xy 1 pq 2 yx 4 pr 5 zy 3 rs 7 zz 6 sp Ideally, the following should have worked: df.explode('B').merge(df2).drop_duplicates('A') However, pandas (as of writing, version 1.2dev) does not preserve the ordering of the left keys on a merge which is a bug, see GH18776. In the meantime, we can use the workaround of a left merge as shown above.
5
8
65,438,156
2020-12-24
https://stackoverflow.com/questions/65438156/tensorflow-keras-error-unknown-image-file-format-one-of-jpeg-png-gif-bmp-re
i'm training a classifier and i made sure all the pictures are jpg but still, this error occurs: InvalidArgumentError: Unknown image file format. One of JPEG, PNG, GIF, BMP required. [[{{node decode_image/DecodeImage}}]] [[IteratorGetNext]] [Op:__inference_train_function_1481] i tried training on a smaller dataset and also they were all jpg and there was no problem this is the code: import numpy as np import tensorflow as tf from tensorflow import keras dataset = keras.preprocessing.image_dataset_from_directory( '/content/drive/MyDrive/fi_dataset/train', batch_size=64, image_size=(200, 200)) dense = keras.layers.Dense(units=16) inputs = keras.Input(shape=(None, None, 3)) from tensorflow.keras import layers x = CenterCrop(height=150, width=150)(inputs) x = Rescaling(scale=1.0 / 255)(x) x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(x) x = layers.MaxPooling2D(pool_size=(3, 3))(x) x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(x) x = layers.MaxPooling2D(pool_size=(3, 3))(x) x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu")(x) x = layers.GlobalAveragePooling2D()(x) num_classes = 1 outputs = layers.Dense(num_classes, activation="sigmoid")(x) model = keras.Model(inputs=inputs, outputs=outputs) data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype("float32") processed_data = model(data) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[keras.metrics.binary_accuracy],) history=model.fit(dataset, epochs=10)
When you say you made sure they were jpg's how did you verify that? Just because the extension is .jpg does not mean the file is a true jpg image. I suggest you run the code below to see which image may be defective. import os import cv2 def check_images( s_dir, ext_list): bad_images=[] bad_ext=[] s_list= os.listdir(s_dir) for klass in s_list: klass_path=os.path.join (s_dir, klass) print ('processing class directory ', klass) if os.path.isdir(klass_path): file_list=os.listdir(klass_path) for f in file_list: f_path=os.path.join (klass_path,f) index=f.rfind('.') ext=f[index+1:].lower() if ext not in ext_list: print('file ', f_path, ' has an invalid extension ', ext) bad_ext.append(f_path) if os.path.isfile(f_path): try: img=cv2.imread(f_path) shape=img.shape except: print('file ', f_path, ' is not a valid image file') bad_images.append(f_path) else: print('*** fatal error, you a sub directory ', f, ' in class directory ', klass) else: print ('*** WARNING*** you have files in ', s_dir, ' it should only contain sub directories') return bad_images, bad_ext source_dir =r'c:\temp\people\storage' good_exts=['jpg', 'png', 'jpeg', 'gif', 'bmp' ] # list of acceptable extensions bad_file_list, bad_ext_list=check_images(source_dir, good_exts) if len(bad_file_list) !=0: print('improper image files are listed below') for i in range (len(bad_file_list)): print (bad_file_list[i]) else: print(' no improper image files were found') even this might not be enough because it checks the file's extension name. Actually it might have an extension name jpg but be in say a tiff format. To take it a stepfurther you can add some code that if the extension is not in the good extension list you could read the image and if it is valid use cv2 to convert it to say a jpg and then write it back to the file.
8
9
65,443,086
2020-12-24
https://stackoverflow.com/questions/65443086/django-psycopg2-errors-stringdatarighttruncation-value-too-long-for-type-charac
Facing the above error when running the django app. What exactly needs to be changed though? The comment_body = models.TextField() aspect most probably is the culprit since it stores reddit comments which can be of varying lengths. When i do a git clone and run it on my local, strangely it works. Models.py from django.db import models # Create your models here. class Subreddit(models.Model): # Field for storing the name of a subreddit subreddit_name = models.CharField(max_length=200, unique=True) # Field for storing the time the model object was last saved last_updated = models.DateTimeField(auto_now=True) class Submission(models.Model): subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) # The Reddit submission id of the object submission_id = models.CharField(max_length=200, unique=True) # Reddit Submission URL url = models.URLField(max_length=200) # Reddit Submission Title title = models.CharField(max_length=200) class SubmissionComment(models.Model): # Parent submission object submission = models.ForeignKey(Submission, on_delete=models.CASCADE) # Text of the comment comment_body = models.TextField() class Meme(models.Model): memeurl = models.URLField(max_length=200) EDIT: New error post char changed to 300, and migrations run locally and on heroku.
Given the error: value too long for type character varying(200) you should look for model fields that have a max_length of 200. Since you have multiple fields with a max_length set to 200, you need to determine which model and field are throwing the error. Check the stacktrace, run a debugger and/or insert some debugging print(instance.__dict__)s. Once you find the culprit, extend that field's max_length to something larger or turn it into a TextField.
7
2
65,436,017
2020-12-24
https://stackoverflow.com/questions/65436017/minimizing-this-error-function-using-numpy
Background I've been working for some time on attempting to solve the (notoriously painful) Time Difference of Arrival (TDoA) multi-lateration problem, in 3-dimensions and using 4 nodes. If you're unfamiliar with the problem, it is to determine the coordinates of some signal source (X,Y,Z), given the coordinates of n nodes, the time of arrival of the signal at each node, and the velocity of the signal v. My solution is as follows: For each node, we write (X-x_i)**2 + (Y-y_i)**2 + (Z-z_i)**2 = (v(t_i - T)**2 Where (x_i, y_i, z_i) are the coordinates of the ith node, and T is the time of emission. We have now 4 equations in 4 unknowns. Four nodes are obviously insufficient. We could try to solve this system directly, however that seems next to impossible given the highly nonlinear nature of the problem (and, indeed, I've tried many direct techniques... and failed). Instead, we simplify this to a linear problem by considering all i/j possibilities, subtracting equation i from equation j. We obtain (n(n-1))/2 =6 equations of the form: 2*(x_j - x_i)*X + 2*(y_j - y_i)*Y + 2*(z_j - z_i)*Z + 2 * v**2 * (t_i - t_j) = v**2 ( t_i**2 - t_j**2) + (x_j**2 + y_j**2 + z_j**2) - (x_i**2 + y_i**2 + z_i**2) Which look like Xv_1 + Y_v2 + Z_v3 + T_v4 = b. We try now to apply standard linear least squares, where the solution is the matrix vector x in A^T Ax = A^T b. Unfortunately, if you were to try feeding this into any standard linear least squares algorithm, it'll choke up. So, what do we do now? ... The time of arrival of the signal at node i is given (of course) by: sqrt( (X-x_i)**2 + (Y-y_i)**2 + (Z-z_i)**2 ) / v This equation implies that the time of arrival, T, is 0. If we have that T = 0, we can drop the T column in matrix A and the problem is greatly simplified. Indeed, NumPy's linalg.lstsq() gives a surprisingly accurate & precise result. ... So, what I do is normalize the input times by subtracting from each equation the earliest time. All I have to do then is determine the dt that I can add to each time such that the residual of summed squared error for the point found by linear least squares is minimized. I define the error for some dt to be the squared difference between the arrival time for the point predicted by feeding the input times + dt to the least squares algorithm, minus the input time (normalized), summed over all 4 nodes. for node, time in nodes, times: error += ( (sqrt( (X-x_i)**2 + (Y-y_i)**2 + (Z-z_i)**2 ) / v) - time) ** 2 My problem: I was able to do this somewhat satisfactorily by using brute-force. I started at dt = 0, and moved by some step up to some maximum # of iterations OR until some minimum RSS error is reached, and that was the dt I added to the normalized times to obtain a solution. The resulting solutions were very accurate and precise, but quite slow. In practice, I'd like to be able to solve this in real time, and therefore a far faster solution will be needed. I began with the assumption that the error function (that is, dt vs error as defined above) would be highly nonlinear-- offhand, this made sense to me. Since I don't have an actual, mathematical function, I can automatically rule out methods that require differentiation (e.g. Newton-Raphson). The error function will always be positive, so I can rule out bisection, etc. Instead, I try a simple approximation search. Unfortunately, that failed miserably. I then tried Tabu search, followed by a genetic algorithm, and several others. They all failed horribly. So, I decided to do some investigating. As it turns out the plot of the error function vs dt looks a bit like a square root, only shifted right depending upon the distance from the nodes that the signal source is: Where dt is on horizontal axis, error on vertical axis And, in hindsight, of course it does!. I defined the error function to involve square roots so, at least to me, this seems reasonable. What to do? So, my issue now is, how do I determine the dt corresponding to the minimum of the error function? My first (very crude) attempt was to get some points on the error graph (as above), fit it using numpy.polyfit, then feed the results to numpy.root. That root corresponds to the dt. Unfortunately, this failed, too. I tried fitting with various degrees, and also with various points, up to a ridiculous number of points such that I may as well just use brute-force. How can I determine the dt corresponding to the minimum of this error function? Since we're dealing with high velocities (radio signals), it's important that the results be precise and accurate, as minor variances in dt can throw off the resulting point. I'm sure that there's some infinitely simpler approach buried in what I'm doing here however, ignoring everything else, how do I find dt? My requirements: Speed is of utmost importance I have access only to pure Python and NumPy in the environment where this will be run EDIT: Here's my code. Admittedly, a bit messy. Here, I'm using the polyfit technique. It will "simulate" a source for you, and compare results: from numpy import poly1d, linspace, set_printoptions, array, linalg, triu_indices, roots, polyfit from dataclasses import dataclass from random import randrange import math @dataclass class Vertexer: receivers: list # Defaults c = 299792 # Receivers: # [x_1, y_1, z_1] # [x_2, y_2, z_2] # [x_3, y_3, z_3] # Solved: # [x, y, z] def error(self, dt, times): solved = self.linear([time + dt for time in times]) error = 0 for time, receiver in zip(times, self.receivers): error += ((math.sqrt( (solved[0] - receiver[0])**2 + (solved[1] - receiver[1])**2 + (solved[2] - receiver[2])**2 ) / c ) - time)**2 return error def linear(self, times): X = array(self.receivers) t = array(times) x, y, z = X.T i, j = triu_indices(len(x), 1) A = 2 * (X[i] - X[j]) b = self.c**2 * (t[j]**2 - t[i]**2) + (X[i]**2).sum(1) - (X[j]**2).sum(1) solved, residuals, rank, s = linalg.lstsq(A, b, rcond=None) return(solved) def find(self, times): # Normalize times times = [time - min(times) for time in times] # Fit the error function y = [] x = [] dt = 1E-10 for i in range(50000): x.append(self.error(dt * i, times)) y.append(dt * i) p = polyfit(array(x), array(y), 2) r = roots(p) return(self.linear([time + r for time in times])) # SIMPLE CODE FOR SIMULATING A SIGNAL # Pick nodes to be at random locations x_1 = randrange(10); y_1 = randrange(10); z_1 = randrange(10) x_2 = randrange(10); y_2 = randrange(10); z_2 = randrange(10) x_3 = randrange(10); y_3 = randrange(10); z_3 = randrange(10) x_4 = randrange(10); y_4 = randrange(10); z_4 = randrange(10) # Pick source to be at random location x = randrange(1000); y = randrange(1000); z = randrange(1000) # Set velocity c = 299792 # km/ns # Generate simulated source t_1 = math.sqrt( (x - x_1)**2 + (y - y_1)**2 + (z - z_1)**2 ) / c t_2 = math.sqrt( (x - x_2)**2 + (y - y_2)**2 + (z - z_2)**2 ) / c t_3 = math.sqrt( (x - x_3)**2 + (y - y_3)**2 + (z - z_3)**2 ) / c t_4 = math.sqrt( (x - x_4)**2 + (y - y_4)**2 + (z - z_4)**2 ) / c print('Actual:', x, y, z) myVertexer = Vertexer([[x_1, y_1, z_1],[x_2, y_2, z_2],[x_3, y_3, z_3],[x_4, y_4, z_4]]) solution = myVertexer.find([t_1, t_2, t_3, t_4]) print(solution)
It seems like the Bancroft method applies to this problem? Here's a pure NumPy implementation. # Implementation of the Bancroft method, following # https://gssc.esa.int/navipedia/index.php/Bancroft_Method M = np.diag([1, 1, 1, -1]) def lorentz_inner(v, w): return np.sum(v * (w @ M), axis=-1) B = np.array( [ [x_1, y_1, z_1, c * t_1], [x_2, y_2, z_2, c * t_2], [x_3, y_3, z_3, c * t_3], [x_4, y_4, z_4, c * t_4], ] ) one = np.ones(4) a = 0.5 * lorentz_inner(B, B) B_inv_one = np.linalg.solve(B, one) B_inv_a = np.linalg.solve(B, a) for Lambda in np.roots( [ lorentz_inner(B_inv_one, B_inv_one), 2 * (lorentz_inner(B_inv_one, B_inv_a) - 1), lorentz_inner(B_inv_a, B_inv_a), ] ): x, y, z, c_t = M @ np.linalg.solve(B, Lambda * one + a) print("Candidate:", x, y, z, c_t / c)
6
2
65,439,688
2020-12-24
https://stackoverflow.com/questions/65439688/pandas-rows-multiple-rows-as-one-adding-specific-column
import pandas as pd training_data = pd.DataFrame() training_data['a'] = [401,401.2,410,420,425,426, 426.1] training_data['b'] = [1,1,2,2,2,3,3] training_data['condition'] = [True, False, True, True, True,False, False] My training data: a b condition 401 1 True 401.2 1 False 410 2 True 420 2 True 425 2 True 426 3 False 426.1 3 False Desired output: a b condition 401 2 True (1+1) 410 2 True 420 2 True 425 8 True (2+3+3) All False conditions have been deleted and column 'b' has been added with the amended values. How can I get this desired output? I am aware of using .cumsum() with training_data.query('condition').groupby('grp').agg()
Here we go with cumsum out = training_data.groupby(training_data['condition'].cumsum()).agg({'a':'first','b':'sum','condition':'first'}) Out[271]: a b condition condition 1 401.0 2 True 2 410.0 2 True 3 420.0 2 True 4 425.0 8 True
6
7
65,438,868
2020-12-24
https://stackoverflow.com/questions/65438868/difference-between-re-split-string-and-re-split-s-string
I'm currently studying regular expressions and have come across an inquiry. So the title of the question is what I'm trying to find out. I thought since \s represents a white space, re.split(" ", string) and re.split("\s+", string) would give out same values, as shown next: >>> import re >>> a = re.split(" ", "Why is this wrong") >>> a ["Why", "is", "this", "wrong"] >>> import re >>> a = re.split("\s+", "Why is this wrong") >>> a ["Why", "is", "this", "wrong"] These two give out the same answers so I thought that they were the same thing. However, it turns out that these are different. In what case would it be different? And what am I missing here that is blinding me?
This only look similar based on your example. A split on ' ' (a single space) does exactly that - it splits on a single space. Consecutive spaces will lead to empty "matches" when you split. A split on '\s+' will also split on multiple occurences of those characters and it includes other whitespaces then "pure spaces": import re a = re.split(" ", "Why is this \t \t wrong") b = re.split("\s+", "Why is this \t \t wrong") print(a) print(b) Output: # re.split(" ",data) ['Why', '', '', '', 'is', 'this', '', '\t', '\t', '', 'wrong'] # re.split("\s+",data) ['Why', 'is', 'this', 'wrong'] Documentation: \s Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v]. (https://docs.python.org/3/howto/regex.html#matching-characters)
4
13
65,428,255
2020-12-23
https://stackoverflow.com/questions/65428255/how-is-pythons-iterator-unpacking-star-unpacking-implemented-or-what-magic
I am writing a class that defines __iter__ and __len__, where the value of __len__ depends on the iterator returned by __iter__. I am getting an interesting RecursionError. Language versions: Python 3.8.6, 3.7.6. Examples are for illustrating the error only. In the following example, Iter.__len__() attempts to unpack self, store the result in a list, and then attempts to call the built-in list.__len__() on that list to get the length. >>> class Iter: ... def __iter__(self): ... return range(5).__iter__() ... def __len__(self): ... return list.__len__([*self]) ... >>> len(Iter()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __len__ File "<stdin>", line 5, in __len__ File "<stdin>", line 5, in __len__ [Previous line repeated 993 more times] File "<stdin>", line 3, in __iter__ RecursionError: maximum recursion depth exceeded in comparison However, if I define the class Iter as the following, where Iter.__len__() explicitly unpacks the iterator as returned by Iter.__iter__(): >>> class Iter: ... def __iter__(self): ... return range(5).__iter__() ... def __len__(self): ... return list.__len__([*self.__iter__()]) ... >>> len(Iter()) 5 Then there is no error. From the traceback, it seems that list.__len__() is trying to call Iter.__len__(), even thought the argument provided is supposedly already a native list object. What is the reason for the RecursionError? According to schwobaseggl, using set instead of list will not cause a RecursionError: >>> class Iter: ... def __iter__(self): ... return range(5).__iter__() ... def __len__(self): ... return set.__len__({*self}) ... >>> len(Iter()) 5
It has little to do with unpacking as such, but with the implementations of different collection types, their constructors in particular. [*iterable] # list (*iterable,) # tuple {*iterable} # set all trigger calls to their classes' respective constructors. From the current C implementation for list(iterable): list___init___impl(PyListObject *self, PyObject *iterable) { /* ... */ if (iterable != NULL) { if (_PyObject_HasLen(iterable)) { Py_ssize_t iter_len = PyObject_Size(iterable); if (iter_len == -1) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) { return -1; } PyErr_Clear(); } if (iter_len > 0 && self->ob_item == NULL && list_preallocate_exact(self, iter_len)) { return -1; } } PyObject *rv = list_extend(self, iterable); /* ... */ } As can be seen (even with such limited C knowledge as mine), the iterable is tested for its size in order to allocate the right amount of memory which is what triggers the calls to __len__ of the passed iterable. Unsurprisingly, it can be verified that set does no such thing. After all, the relation between the size of the passed iterable and the size of the resulting set is nowhere near as direct as it is for lists or tuples. For instance, think of set([1] * 10**5). It would be foolish to use the size information of the passed list to allocate memory for the set. On a side note, as has been pointed out in the comments and many other questions/answers on this site (e.g. here): If you want to determine the length of an iterable, there are more (mainly space-)efficient ways than to collect all items into a Sized collection, e.g.: def __len__(self): return sum(1 for _ in self)
7
7
65,432,087
2020-12-23
https://stackoverflow.com/questions/65432087/is-there-a-way-to-use-the-secrets-python-module-with-a-seed
Random.seed() Is less secure than secrets, but I can't find any documentation on using a seed with secrets? or is random.seed just as fine?
No, there isn't. secrets uses random's SystemRandom class, which reads from the operating system's random device, such as /dev/urandom on Linux. This OS randomness is based off hardware entropy, which is what gives it its security, and there is no way to seed it.
8
11
65,431,837
2020-12-23
https://stackoverflow.com/questions/65431837/transformers-v4-x-convert-slow-tokenizer-to-fast-tokenizer
I'm following the transformer's pretrained model xlm-roberta-large-xnli example from transformers import pipeline classifier = pipeline("zero-shot-classification", model="joeddav/xlm-roberta-large-xnli") and I get the following error ValueError: Couldn't instantiate the backend tokenizer from one of: (1) a `tokenizers` library serialization file, (2) a slow tokenizer instance to convert or (3) an equivalent slow tokenizer class to instantiate and convert. You need to have sentencepiece installed to convert a slow tokenizer to a fast one. I'm using Transformers version '4.1.1'
According to Transformers v4.0.0 release, sentencepiece was removed as a required dependency. This means that "The tokenizers that depend on the SentencePiece library will not be available with a standard transformers installation" including the XLMRobertaTokenizer. However, sentencepiece can be installed as an extra dependency pip install transformers[sentencepiece] or pip install sentencepiece if you have transformers already installed.
37
62
65,428,535
2020-12-23
https://stackoverflow.com/questions/65428535/why-does-this-solution-work-in-javascript-but-not-in-python-dynamic-programmin
I'm following this tutorial about dynamic programming and I'm struggling to implement memoization in the following problem: *Write a function called canSum(targetSum, numbers) that returns True only if the numbers in the array can sum to the target sum. All the numbers in the array are positive integers and you can use them more than once for the solution. Example: canSum(7, [2, 4]) -> False because you can't form 7 by adding 2 and 4. * My brute force solution was the following one: def canSum(targetSum, numbers): if targetSum == 0: return True if targetSum < 0: return False for n in numbers: remainder = targetSum - n if canSum(remainder, numbers): return True return False print(canSum(7, [2, 3])) # True print(canSum(7, [5, 3, 4, 7])) # True print(canSum(7, [2, 4])) # False print(canSum(8, [2, 3, 5])) # True Works well, but it'd be faster if we memoized the solutions of the remainders (this is explained at minute 1:28:03 in the video). I did the following with Python, which is exactly what the instructor is doing, but it only returns True and I can't figure out why... def canSum(targetSum, numbers, memo={}): if targetSum in memo: return memo[targetSum] if targetSum == 0: return True if targetSum < 0: return False for n in numbers: remainder = targetSum - n if canSum(remainder, numbers, memo): memo[targetSum] = True return True memo[targetSum] = False return False print(canSum(7, [2, 3])) print(canSum(7, [5, 3, 4, 7])) print(canSum(7, [2, 4])) print(canSum(8, [2, 3, 5])) # All of them return True
Thanks to the article shared by @Jared Smith I was able to figure it out. The problem is caused by how python handles default arguments. From the article: In Python, when passing a mutable value as a default argument in a function, the default argument is mutated anytime that value is mutated. My memo dictionary was being mutated every call. So I simply changed memo=None and added a check to see if it was the first call of the function: def canSum(targetSum, numbers, memo=None): if memo == None: memo = {} if targetSum in memo: return memo[targetSum] if targetSum == 0: return True if targetSum < 0: return False for n in numbers: remainder = targetSum - n if canSum(remainder, numbers, memo): memo[targetSum] = True return True memo[targetSum] = False return False print(canSum(7, [2, 3])) # True print(canSum(7, [5, 3, 4, 7])) # True print(canSum(7, [2, 4])) # False print(canSum(8, [2, 3, 5])) # True print(canSum(3000, [7, 14])) # False -> Works fast with large inputs!
7
4
65,426,069
2020-12-23
https://stackoverflow.com/questions/65426069/use-of-mathbb-in-matplotlib
I have recently (i.e., yesterday) discovered matplotlib as a much better alternative to Matlab for plots. Unfortunately, my knowledge of python is close to zero. I would like to use \mathbb{} in the legend and/or axes (for example, to denote expected value or variance) and it seems that this requires the additional STIX fonts (see, e.g., here and here). However, I haven't been able to include these fonts in my code so far. In the following example, I would like to replace \mathrm{E} --> \mathbb{E} and \mathrm{V} --> \mathbb{V}. Is there a simple way to do it? import numpy as np import scipy.io from matplotlib import pyplot as plt plt.figure(figsize=[3.3, 3.3]) plt.rcParams.update({'font.size': 8, 'text.usetex': True}) plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathrm{E}[x]$') plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathrm{V}[x]$') plt.grid() plt.xlabel('x') plt.legend(loc='upper left') plt.savefig('filename.pdf', format='pdf') plt.show()
\mathbb is provided by the LaTeX package amsfonts, so you have to load this package for the figure to compile properly. You can load packages using the text.latex.preamble setting, as follows: import numpy as np import scipy.io from matplotlib import pyplot as plt plt.figure(figsize=[3.3, 3.3]) plt.rcParams.update({ 'font.size': 8, 'text.usetex': True, 'text.latex.preamble': r'\usepackage{amsfonts}' }) plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathbb{E}[x]$') plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathbb{V}[x]$') plt.grid() plt.xlabel('x') plt.legend(loc='upper left') plt.savefig('filename.pdf', format='pdf') plt.show() Alternatively, to use the STIX fonts you refer to in your question, you can use matplotlib's built in TeX parser, not using LaTeX at all for your text handling (test.usetex can be False). In this case, however, note that \mathbb{} produces italic text by default, and you need to combine it with \mathrm{} as \mathrm{\mathbb{}} to get upright text (as in the example you linked). A possible version of your code is then: import numpy as np import scipy.io from matplotlib import pyplot as plt plt.figure(figsize=[3.3, 3.3]) plt.rcParams.update({'font.size': 8}) plt.plot([1,2,3,4], [1,2,3,4], label=r'$\mathrm{\mathbb{E}}[x]$') plt.plot([1,2,3,4], [1,4,9,16], label=r'$\mathrm{\mathbb{V}}[x]$') plt.grid() plt.xlabel('x') plt.legend(loc='upper left') plt.savefig('filename.pdf', format='pdf') plt.show() In this case, this is the result. (posted as a link to limit the height of this answer)
6
7
65,424,114
2020-12-23
https://stackoverflow.com/questions/65424114/in-playwright-for-python-how-do-i-retrieve-a-handle-for-elements-from-within-an
I have successfully used Playwright in python to get elements from a page. I now ran into to challenge of getting elements from a document embedded within an iframe. As an example, I used the w3schools page explaining the <option> element, which displays the result in an iframe. I am trying to retrieve a handle for this <option> element from the iframe. The 'normal' way of getting the an element on the page with page.querySelector() fails to get an elementHandle, this just prints <class 'NoneType'>: with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch(headless=False) page = browser.newPage() page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_option') element = page.querySelector('select') print(type(element)) browser.close() I tried explicitly getting a handle for the iframe first, but this yields the same result (<class 'NoneType'>): with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch(headless=False) page = browser.newPage() page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_option') iframe = page.querySelector('iframe') element = iframe.querySelector('select') print(type(element)) browser.close() How can I get content from within the iframe?
Turns out I was close, but to get the iframe correctly, I needed to call the contentFrame() method. Returns the content frame for element handles referencing iframe nodes, or null otherwise Then, querySelector() will return the respective elementHandle just fine: with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch(headless=False) page = browser.newPage() page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_option') iframe = page.querySelector('iframe').contentFrame() element = iframe.querySelector('select') print(type(element)) print(element.innerHTML()) browser.close() successfully prints <class 'playwright.sync_api.ElementHandle'> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> Note: if there are multiple iframes, you can just use an attribute when retrieving the handle. To get the iframe by its id in the above example, e.g. use iframe = page.querySelector('iframe[id=\"iframeResult\"]').contentFrame()
6
4
65,422,225
2020-12-23
https://stackoverflow.com/questions/65422225/how-to-solve-keyerrorfnone-of-key-are-in-the-axis-name-in-this-case
I have a CSV file for example like this : id name email physics chemistry maths 1 Sta [email protected] 67 78 90 2 Danny [email protected] 77 98 89 3 Elle [email protected] 77 67 90 Now I want to output a new CSV file using pandas which has new columns too for example like this : id name grade address physics chemistry attendance maths total I want to create new columns in random places and I want to place the value as blank in the new columns. I have tried using : import pandas as pd df = pd.read_csv("sample.csv") final_df = df.loc[['id','name','grade','address','physics','chemistry','attendance','maths','total']] When I did this I got an error : KeyError(fβ€œNone of [{key}] are in the [{axis_name}]”) Any ideas or suggestions to arrange this.
If you want to add new columns you should try reindex with axis=1: import pandas as pd df = pd.read_csv("sample.csv") final_df = df.reindex(['id','name','grade','address','physics','chemistry','attendance','maths','total'], axis=1)
8
1
65,420,853
2020-12-23
https://stackoverflow.com/questions/65420853/pandas-appending-a-row-of-boolean-values-to-df-using-loc-changes-to-int
Consider df: In [2098]: df = pd.DataFrame({'a': [1,2], 'b':[3,4]}) In [2099]: df Out[2099]: a b 0 1 3 1 2 4 Now, I try to append a list of values to df: In [2102]: df.loc[2] = [3, 4] In [2103]: df Out[2103]: a b 0 1 3 1 2 4 2 3 4 All's good so far. But now when I try to append a row with list of boolean values, it converts it into int: In [2104]: df.loc[3] = [True, False] In [2105]: df Out[2105]: a b 0 1 3 1 2 4 2 3 4 3 1 0 I know I can convert my df into str and can then append boolean values, like: In [2131]: df = df.astype(str) In [2133]: df.loc[3] = [True, False] In [2134]: df Out[2134]: a b 0 1 3 1 2 4 3 True False But, I want to know the reason behind this behaviour. Why is it not automatically changing the dtypes of columns to object when I append boolean to it? My Pandas version is: In [2150]: pd.__version__ Out[2150]: '1.1.0'
Why is it not automatically changing the dtypes of columns to object when I append boolean to it? Because the type are being upcasted (see upcasting), from the documentation: Types can potentially be upcasted when combined with other types, meaning they are promoted from the current type (e.g. int to float). Upcasting works according to numpy rules: Upcasting is always according to the numpy rules. If two different dtypes are involved in an operation, then the more general one will be used as the result of the operation. To understand how the numpy rules are applied you can use the function find_common_type, as below: res = np.find_common_type([bool, np.bool], [np.int32, np.int64]) print(res) Output int64
6
3
65,420,399
2020-12-23
https://stackoverflow.com/questions/65420399/unable-to-read-mp4-and-avi-files-in-opencv-python
I want to just read and display an MP4 video using OpenCV, I wrote the following basic code for it: import cv2 input_video_path = './Input Video/Input_video1.mp4' cap = cv2.VideoCapture(input_video_path) while(cap.isOpened()): ret, frame = cap.read() print(frame, ret) cv2.imshow("frame", frame) cap.release() cv2.destroyAllWindows() When I run it, it reads 1st few frames and then all other frames are None: [[[ 7 14 27] [ 7 14 27] [ 7 14 27] ... ... [ 60 57 64] [ 70 62 64] [ 72 64 66]]] True None False Traceback (most recent call last): File "D:/Project/ML IP and Coding/Cynapto_Task/exploring_face_detection_methods.py", line 10, in <module> cv2.imshow("frame", frame) cv2.error: OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow' I also printed the ret variable which confirms the same behavior. I tried with 2-3 different videos and even with .avi format but got the same result. I searched online for a solution but could only find about codecs and installing codecs in my virtual environment. I don't have much knowledge about video file formats and codecs. Can someone help me with this? I am using: Python 3.7, OS: Windows, environment: conda, OpenCV v4.5.0
If you recieved ret as False it means that video reach end frame. If video isn't finished but you recieved False, it probably broken. Try this code: import cv2 input_video_path = './Input Video/Input_video1.mp4' cap = cv2.VideoCapture(input_video_path) while(cap.isOpened()): ret, frame = cap.read() print(frame, ret) if ret: cv2.imshow("frame", frame) cv2.waitKey(1) else: break cap.release() cv2.destroyAllWindows()
6
7
65,418,722
2020-12-23
https://stackoverflow.com/questions/65418722/what-is-in-julia-and-its-equivalent-in-python
I'm new to julia and I'm working on to rewrite julia code to python code. And I saw the some codes using .== expression. I couldn't understand what this means. So I searched it on web but couldn't find an answer. Can someone tell me what is .== in julia and its equivalent in python? fyi, it was written like below. x = sum(y .== 0) # y is array
That's a Vectorized dot operation and is used to apply the operator to an array. You can do this for one dimensional lists in python via list comprehensions, but here it seems like you are just counting all zeroes, so >>> y = [0,1,1,1,0] >>> sum(not bool(v) for v in y) 2 Other packages like numpy or pandas will vectorize operators, so something like this will do >>> import numpy as np >>> y = np.array([0,1,1,1,0]) >>> (y == 0).sum() 2 >>> >>> import pandas as pd >>> df=pd.DataFrame([[0,1,2,3], [1,2,3,0], [2,3,4,0]]) >>> (df==0).sum() 0 1 1 0 2 0 3 2 dtype: int64 >>> (df==0).sum().sum() 3
15
13
65,417,166
2020-12-22
https://stackoverflow.com/questions/65417166/how-to-make-discord-py-bot-delete-its-own-message-after-some-time
I have this code in Python: import discord client = commands.Bot(command_prefix='!') @client.event async def on_voice_state_update(member): channel = client.get_channel(channels_id_where_i_want_to_send_message)) response = f'Hello {member}!' await channel.send(response) client.run('bots_token') And I want the bot to delete its own message. For example, after one minute, how do I do it?
There is a better way than what Dean Ambros and Dom suggested, you can simply add the key-word argument delete_after in .send await ctx.send('whatever', delete_after=60.0) reference
6
15
65,327,247
2020-12-16
https://stackoverflow.com/questions/65327247/load-pytorch-dataloader-into-gpu
Is there a way to load a pytorch DataLoader (torch.utils.data.Dataloader) entirely into my GPU? Now, I load every batch separately into my GPU. CTX = torch.device('cuda') train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=0, ) net = Net().to(CTX) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=LEARNING_RATE) for epoch in range(EPOCHS): for inputs, labels in test_loader: inputs = inputs.to(CTX) # this is where the data is loaded into GPU labels = labels.to(CTX) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() print(f'training accuracy: {net.validate(train_loader, device=CTX)}/{len(train_dataset)}') print(f'validation accuracy: {net.validate(test_loader, device=CTX)}/{len(test_dataset)}') where the Net.validate() function is given by def validate(self, val_loader, device=torch.device('cpu')): correct = 0 for inputs, labels in val_loader: inputs = inputs.to(device) labels = labels.to(device) outputs = torch.argmax(self(inputs), dim=1) correct += int(torch.sum(outputs==labels)) return correct I would like to improve the speed by loading the entire dataset trainloader into my GPU, instead of loading every batch separately. So, I would like to do something like train_loader.to(CTX) Is there an equivalent function for this? Because torch.utils.data.DataLoader does not have this attribute .to(). I work with an NVIDIA GeForce RTX 2060 with CUDA Toolkit 10.2 installed.
you can put your data of dataset in advance train_dataset.train_data.to(CTX) #train_dataset.train_data is a Tensor(input data) train_dataset.train_labels.to(CTX) for example of minst import torch from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transforms batch_size = 64 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) train_data = datasets.MNIST( root='./dataset/minst/', train=True, download=False, transform=transform ) train_loader = DataLoader( dataset=train_data, shuffle=True, batch_size=batch_size ) train_data.train_data = train_data.train_data.to(torch.device("cuda:0")) # put data into GPU entirely train_data.train_labels = train_data.train_labels.to(torch.device("cuda:0")) # edit note for newer versions: use train_data.data and train_data.targets instead I got this solution by using debugger...
16
14
65,319,009
2020-12-16
https://stackoverflow.com/questions/65319009/how-to-add-a-timezone-to-a-datetime-object
I have a variable which is grabbing a date object from a file. My aim is to add a timezone to this object so that it automatically changes the time based on the date its it then. So I expected it to add +1hour to it for dates in summertime (between march and october) and add +0hour in wintertime (between october and march). dt_object = '20200901-01u30m30s' dt_object = datetime.datetime.strptime(dt_object, '%Y%m%d-%Hu%Mm%Ss') >>>print(dt_object) >>> 2020-09-01 01:30:30 timezone= 'Europe/Amsterdam' dt_object_tz = pytz.utc.localize(dt_object).astimezone(pytz.timezone(timezone)) timeDiff = dt_object_tz.utcoffset().total_seconds() official_time = pytz.utc.localize(dt_object_tz+datetime.timedelta(seconds=timeDiff)) >>>print(official_time) >>> 2020-09-01 03:30:30+00:00 As you can see this is a datetime object of september (so summertime!), I literally have no clue why it adds +2hours instead of 1 hour.... Can someone explain it and tell me what went wrong? I just want my datetime object to be timezone-aware so it autmatically changes from summer to wintertime based on the date in grabs.
Regarding pytz, note that there is zoneinfo in the standard lib. No need for a third party library for time zone handling with Python >= 3.9. Example usage. Then, if your input represents wall time in some time zone, you can just localize. If the input represents UTC, you can set the tzinfo to UTC a bit more easily and then convert to local time using astimezone: from datetime import datetime, timezone import pytz s = '20200901-01u30m30s' local_tz = 'Europe/Amsterdam' # if s represents local time, just localize: dtobj_tz = pytz.timezone(local_tz).localize(datetime.strptime(s, '%Y%m%d-%Hu%Mm%Ss')) # datetime.datetime(2020, 9, 1, 1, 30, 30, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>) # if s represents UTC, set it directly: dtobj_utc = datetime.strptime(s, '%Y%m%d-%Hu%Mm%Ss').replace(tzinfo=timezone.utc) # ...and convert to desired tz: dtobj_tz = dtobj_utc.astimezone(pytz.timezone(local_tz)) # datetime.datetime(2020, 9, 1, 3, 30, 30, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)
10
17
65,407,999
2020-12-22
https://stackoverflow.com/questions/65407999/how-to-make-setup-py-for-standalone-python-application-in-a-right-way
I have read several similar topics but haven't succeeded yet. I feel I miss or misunderstand some fundamental thing and this is the reason of my failure. I have an 'application' written in a python which I want to deploy with help of standard setup.py. Due to complex functionality it consists of different python modules. But there is no sense in separate release of this modules as they are too specific. Expected result is to have package installed in a system with help of pip install and be available from OS command line with simple app command. Simplifying long story to reproducible example - I have following directory structure: <root> β”œβ”€ app | β”œβ”€ aaa | | └── module_a.py | β”œβ”€ bbb | | └── module_b.py | └── app.py β”œβ”€ docs | └── ..... β”œβ”€ tests | └── ..... └─ setup.py Below is code of modules: app.py #!/usr/bin/python from aaa.module_a import method1 from bbb.module_b import method2 def main(): print("APP main executed") method1() method2() if __name__ == '__main__': main() module_a.py def method1(): print("A1 executed") module_b.py def method2(): print("B2 executed") When I run app.py from console it works fine and gives expected output: APP main executed A1 executed B2 executed So, this simple 'application' works fine and I want to distribute it with help of following setup.py from setuptools import setup setup( name="app", version="1.0", packages=['app', 'app.aaa', 'app.bbb'], package_dir={'app': 'app'}, entry_points={ 'console_scripts': ['app=app.app:main', ] } ) Again, everything looks good and test installation looks good: (venv) [user@test]$ pip install <root> Processing /home/user/<root> Using legacy 'setup.py install' for app, since package 'wheel' is not installed. Installing collected packages: app Running setup.py install for app ... done Successfully installed app-1.0 (venv) [user@test]$ And now comes the problem. With aforementioned entry_points from setup.py I expect to be able execute my application with ./app command. Indeed it works. But application itself fails with error message: File "/test/venv/lib/python3.9/site-packages/app/app.py", line 3, in <module> from aaa.module_a import method1 ModuleNotFoundError: No module named 'aaa' I understand the reason of the error - it is because pip install put directories aaa and bbb together with app.py in one directory app. I.e. from this point of view app.py should use import app.aaa instead of import aaa. But if I do so then my app during development runs with error: ModuleNotFoundError: No module named 'app.aaa'; 'app' is not a package that is also logical as there are no app package available at that time... (it is under development and isn't installed in the system...) Finally. The question is - what is a correct way to create directory structure and setup.py for standalone python application that consist of several own modules? UPD The most promising result (but proved to be wrong after discussion in coments) that I have now came after following changes: moved app.py from <root>/app into <root> itself I referenced it in setup.py by py_modules=['app'] I changed imports from import aaa.method1 to import app.aaa.method1 etc. This way package works both in my development environment and after installation. But I got a problem with entry_points - I see no way how to configure entry point to use main() from app.py that is not a part of app package but is a separate module.... I.e. new structure is <root> β”œβ”€ app | β”œβ”€ aaa | | └── module_a.py | β”œβ”€ bbb | | └── module_b.py | └──__init__.py β”œβ”€ docs | └── ..... β”œβ”€ tests | └── ..... β”œβ”€ app.py └─ setup.py I.e. the logic here - to have 2 separate entities: An empty package app (consists of init.py only) with subpackages aaa, bbb etc. A script app.py that uses functions from subpackages app.aaa, app.bbb But as I wrote - I see no way how to define entry point for app.py to allow it's run from OS command line directly.
With that directory (package) structure, in your app.py you should import as one of the following: from app.aaa.module_a import method1 from .aaa.module_a import method1 Then make sure to call you application like one of the following: app (this should work thanks to the console entry point) python -m app.app (this should work even without the console entry point) I try to recreate the complete project here Directory structure: . β”œβ”€β”€ app β”‚ β”œβ”€β”€ aaa β”‚ β”‚ └── module_a.py β”‚ β”œβ”€β”€ app.py β”‚ └── bbb β”‚ └── module_b.py └── setup.py setup.py import setuptools setuptools.setup( name="app", version="1.0", packages=['app', 'app.aaa', 'app.bbb'], entry_points={ 'console_scripts': ['app=app.app:main', ] }, ) app/app.py #!/usr/bin/env python from .aaa.module_a import method1 from .bbb.module_b import method2 def main(): print("APP main executed") method1() method2() if __name__ == '__main__': main() app/aaa/module_a.py def method1(): print("A1 executed") app/bbb/module_b.py def method2(): print("B2 executed") Then I run following commands: $ python3 -V Python 3.6.9 $ python3 -m venv .venv $ .venv/bin/python -m pip install -U pip setuptools wheel # [...] $ .venv/bin/python -m pip list Package Version ------------- ------------------- pip 20.3.3 pkg-resources 0.0.0 setuptools 51.1.0.post20201221 wheel 0.36.2 $ .venv/bin/python -m pip install . # [...] $ .venv/bin/python -m app.app APP main executed A1 executed B2 executed $ .venv/bin/app APP main executed A1 executed B2 executed $ .venv/bin/python -m pip uninstall app # [...] $ .venv/bin/python -m pip install --editable . # [...] $ .venv/bin/python -m app.app APP main executed A1 executed B2 executed $ .venv/bin/app APP main executed A1 executed B2 executed
7
4
65,318,382
2020-12-16
https://stackoverflow.com/questions/65318382/expected-browser-binary-location-but-unable-to-find-binary-in-default-location
from selenium import webdriver; browser= webdriver.Firefox(); browser.get('http://www.seleniumhq.org'); When I try to run this code, it gives me an error message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line. Any thoughts-highly appreciated!
This error message... Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line. ...implies that the GeckoDriver was unable to find the Firefox binary at the default location. Additionally you haven't passed the moz:firefoxOptions.binary capability. Solution Possibly within your system firefox is installed in a custom location and these cases you need to pass the absolute path of the Firefox binary through the moz:firefoxOptions.binary capability as follows: from selenium import webdriver from selenium.webdriver.firefox.options import Options options = Options() options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe' driver = webdriver.Firefox(executable_path=r'C:\WebDrivers\geckodriver.exe', options=options) driver.get('http://google.com/') References You can find a couple of relevant detailed discussion in: SessionNotCreatedException: Message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' InvalidArgumentException: Message: binary is not a Firefox executable error using GeckoDriver Firefox Selenium and Python Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided
45
78
65,371,837
2020-12-19
https://stackoverflow.com/questions/65371837/my-on-member-join-event-is-not-working-i-tried-intents-but-it-gives-this-error
Consider: st recent call last): File "randomgg.py", line 1271, in \u003cmodule\u003e client.run(token) File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 708, in run return future.result() File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 687, in runner await self.start(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 651, in start await self.connect(reconnect=reconnect) File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 586, in connect raise PrivilegedIntentsRequired(exc.shard_id) from None discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead. \ My code was import aiohttp import discord import asyncio from collections import Counter import typing from discord.ext import commands import os from discord.ext.commands import has_permissions import random import json from discord import Status from asyncio import gather from discord.utils import get import datetime from discord.utils import get intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix='.', intents=intents) client.remove_command('help') def check_if_it_is_me(ctx): return ctx.message.author.id == 465946367622381578 @client.event async def status_task(): while True: await client.change_presence(status=discord.Status.idle, activity=discord.Game('status1')) await asyncio.sleep(4) await client.change_presence(status=discord.Status.idle, activity=discord.Game('status2')) await asyncio.sleep(4) await client.change_presence(status=discord.Status.idle, activity=discord.Game('status3')) await asyncio.sleep(4) @client.event async def on_ready(): print(f'{client.user.name} is ready') client.loop.create_task(status_task()) @client.event async def on_member_join(member): mem_join = member.joined_at guild_create = member.created_at join_days = (mem_join - guild_create).days role = discord.utils.get(member.guild.roles, id=714805001918349344) channel = discord.utils.get(member.guild.channels, id=771081754038501376) if join_days < 10: await channel.send(f'{role.mention} {member} is suspicious of being an alt, he joined {join_days} after creating his account. Pls keep an eye on him') @client.event async def on_member_remove(member): pass How can I fix this?
The error tells you exactly what to do. Go to https://discord.com/developers/applications Navigate to your application Go to the Bot section Scroll down and enable SERVER MEMBERS INTENT
10
24
65,326,080
2020-12-16
https://stackoverflow.com/questions/65326080/python-setup-config-install-requires-good-practices
My question here may seem really naive but I never found any clue about it on web resources. The question is, concerning install_requires argument for setup() function or setup.cfg file, is it a good practice to mention every package used, even python built-in ones such as os for example ? One can assume that any python environment has those common packages, so is it problematic to explicitly mention them in the setup, making it potentially over-verbose ? Thanks
install_requires should include non-standard library requirements, and constraints on their versions (as needed). For example, this would declare minimal versions for numpy and scipy, but allow any version of scikit-learn: setup( # ... install_requires=["numpy>=1.13.3", "scipy>=0.19.1", "scikit-learn"] ) Packages such as os, sys are part of Python's standard library, so should not be included. As @sinoroc mentioned, only direct 3rd party dependencies should be declared here. Dependencies-of-your-dependencies are handled automatically. (For example, scikit-learn depends on joblib; when the former is required, the latter will be installed). A list of standard library packages are listed here: https://docs.python.org/3/library/ I've found it helpful to read other packages and see how their setup.py files are defined. imbalanced-learn pandas
9
10
65,381,244
2020-12-20
https://stackoverflow.com/questions/65381244/how-to-check-if-a-tensor-is-on-cuda-or-send-it-to-cuda-in-pytorch
I have a tensor t = torch.zeros((4, 5, 6)) How to check if it is on gpu or not, and send it to gpu and back?
From the pytorch forum use t.is_cuda, t.cuda(), t.cpu() t = torch.randn(2,2) t.is_cuda # returns False t = torch.randn(2,2).cuda() t.is_cuda # returns True t = t.cpu() t.is_cuda # returns False When passing to and from gpu and cpu, new arrays are allocated on the relevant device.
24
43
65,400,809
2020-12-21
https://stackoverflow.com/questions/65400809/in-playwright-for-python-how-do-i-get-elements-relative-to-elementhandle-child
In playwright-python I know I can get an elementHandle using querySelector(). Example (sync): from playwright import sync_playwright with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch() page = browser.newPage() page.goto('https://duckduckgo.com/') element = page.querySelector('input[id=\"search_form_input_homepage\"]') How do I get the an element relative to this based on this elementHandle? I.e. the parent, grandparent, siblings, children handles?
Original answer: Using querySelector() / querySelectorAll with XPath (XML Path Language) lets you retrieve the elementHandle (respectively a collection of handles). Generally speaking, XPath can be used to navigate through elements and attributes in an XML document. from playwright import sync_playwright with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch(headless=False) page = browser.newPage() page.goto('https://duckduckgo.com/') element = page.querySelector('input[id=\"search_form_input_homepage\"]') parent = element.querySelector('xpath=..') grandparent = element.querySelector('xpath=../..') siblings = element.querySelectorAll('xpath=following-sibling::*') children = element.querySelectorAll('xpath=child::*') browser.close() Update (2022-07-22): It seems that browser.newPage() is deprecated, so in newer versions of playwright, the function is called browser.new_page() (note the different function name). Optionally create a browser context first (and close it afterwards) and call new_page() on that context. The way the children/parent/grandparent/siblings are accessed stays the same. from playwright import sync_playwright with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch(headless=False) context = browser.new_context() page = context.new_page() page.goto('https://duckduckgo.com/') element = page.querySelector('input[id=\"search_form_input_homepage\"]') parent = element.querySelector('xpath=..') grandparent = element.querySelector('xpath=../..') siblings = element.querySelectorAll('xpath=following-sibling::*') children = element.querySelectorAll('xpath=child::*') context.close() browser.close()
7
10
65,361,686
2020-12-18
https://stackoverflow.com/questions/65361686/websockets-bridge-for-audio-stream-in-fastapi
Objective My objective is to consume an audio stream. Logically, this is my objective: Audio stream comes through WebSocket A (FastAPI endpoint) Audio stream is bridged to a different WebSocket, B, which will return a JSON (Rev-ai's WebSocket) Json results are sent back through WebSocket A, in real-time. Thus, while the audio stream is still coming in. Possible solution To solve this problem, I've had quite a few ideas, but ultimately I've been trying to bridge WebSocket A to WebSocket B. My attempt so far involves a ConnectionManager class, which contains a Queue.queue. The chunks of the audio stream are added to this queue so that we do not consume directly from WebSocket A. The ConnectionManager also contains a generator method to yield all values from the queue. My FastAPI implementation consumes from websocket A like this: @app.websocket("/ws") async def predict_feature(websocket: WebSocket): await manager.connect(websocket) try: while True: chunk = await websocket.receive_bytes() manager.add_to_buffer(chunk) except KeyboardInterrupt: manager.disconnect() Concurrent to this ingestion, I'd like to have a task that would bridge our audio stream to WebSocket B, and send the obtained values to WebSocket A. The audio stream could be consumed through the aforementioned generator method. The generator method is necessary due to how WebSocket B consumes messages, as shown in Rev-ai's examples: streamclient = RevAiStreamingClient(access_token, config) response_generator = streamclient.start(MEDIA_GENERATOR) for response in response_generator: # return through websocket A this value print(response) This is one of the biggest challenges, as we need to be consuming data into a generator and getting the results in real-time. Latest attempts I've been trying my luck with asyncio; from what i'm understanding, a possibility would be to create a coroutine that would run in the background. I've been unsuccessful with this, but it sounded promising. I've thought about triggering this through the FastAPI startup event, but I'm having trouble achieving concurrency. I tried to use event_loops, but it gave me a nested event loop related error. Caveat FastAPI can be optional if your insight deems so, and in a way so is WebSocket A. At the end of the day, the ultimate objective is to receive an audio stream through our own API endpoint, run it through Rev.ai's WebSocket, do some extra processing, and send the results back.
Bridge for websocket <-> websocket Below is a simple example of websocket proxy, where websocket A and websocket B are both endpoints in the FastAPI app, but websocket B can be located in something else, just change its address ws_b_uri. For websocket client, websockets library is used. To perform data forwarding, the code of A endpoint starts two tasks forward and reverse, and waits for their completion by means of asyncio.gather(). Data transfer for both directions occurs in a parallel manner. import asyncio from fastapi import FastAPI from fastapi import WebSocket import websockets app = FastAPI() ws_b_uri = "ws://localhost:8001/ws_b" async def forward(ws_a: WebSocket, ws_b: websockets.WebSocketClientProtocol): while True: data = await ws_a.receive_bytes() print("websocket A received:", data) await ws_b.send(data) async def reverse(ws_a: WebSocket, ws_b: websockets.WebSocketClientProtocol): while True: data = await ws_b.recv() await ws_a.send_text(data) print("websocket A sent:", data) @app.websocket("/ws_a") async def websocket_a(ws_a: WebSocket): await ws_a.accept() async with websockets.connect(ws_b_uri) as ws_b_client: fwd_task = asyncio.create_task(forward(ws_a, ws_b_client)) rev_task = asyncio.create_task(reverse(ws_a, ws_b_client)) await asyncio.gather(fwd_task, rev_task) @app.websocket("/ws_b") async def websocket_b(ws_b_server: WebSocket): await ws_b_server.accept() while True: data = await ws_b_server.receive_bytes() print("websocket B server recieved: ", data) await ws_b_server.send_text('{"response": "value from B server"}') Update (Bridge websocket <-> sync generator) Considering the last update of the question, the issue is that WebSocket B is hidden behind a synchronous generator (in fact there are two of them, one for the input and the other for the output) and in fact, the task turns into how to make a bridge between the WebSocket and the synchronous generator. And since I never worked with the rev-ai library, I made a stub function stream_client_start for streamclient.start that takes a generator (MEDIA_GENERATOR in original) and returns a generator (response_generator in original). In this case, I start the processing of generators in a separate thread through the run_in_executor, and in order not to reinvent the wheel, for communication I use a queue from the janus library, which allows you to bind synchronous and asynchronous code through a queue. Accordingly, there are also two queues, one for A -> B, the other for B -> A. import asyncio import time from typing import Generator from fastapi import FastAPI from fastapi import WebSocket import janus import queue app = FastAPI() # Stub generator function (using websocket B in internal) def stream_client_start(input_gen: Generator) -> Generator: for chunk in input_gen: time.sleep(1) yield f"Get {chunk}" # queue to generator auxiliary adapter def queue_to_generator(sync_queue: queue.Queue) -> Generator: while True: yield sync_queue.get() async def forward(ws_a: WebSocket, queue_b): while True: data = await ws_a.receive_bytes() print("websocket A received:", data) await queue_b.put(data) async def reverse(ws_a: WebSocket, queue_b): while True: data = await queue_b.get() await ws_a.send_text(data) print("websocket A sent:", data) def process_b_client(fwd_queue, rev_queue): response_generator = stream_client_start(queue_to_generator(fwd_queue)) for r in response_generator: rev_queue.put(r) @app.websocket("/ws_a") async def websocket_a(ws_a: WebSocket): loop = asyncio.get_event_loop() fwd_queue = janus.Queue() rev_queue = janus.Queue() await ws_a.accept() process_client_task = loop.run_in_executor(None, process_b_client, fwd_queue.sync_q, rev_queue.sync_q) fwd_task = asyncio.create_task(forward(ws_a, fwd_queue.async_q)) rev_task = asyncio.create_task(reverse(ws_a, rev_queue.async_q)) await asyncio.gather(process_client_task, fwd_task, rev_task)
9
16
65,324,352
2020-12-16
https://stackoverflow.com/questions/65324352/pandas-df-equals-returning-false-on-identical-dataframes
Let df_1 and df_2 be: In [1]: import pandas as pd ...: df_1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) ...: df_2 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) In [2]: df_1 Out[2]: a b 0 1 4 1 2 5 2 3 6 We add a row r to df_1: In [3]: r = pd.DataFrame({'a': ['x'], 'b': ['y']}) ...: df_1 = df_1.append(r, ignore_index=True) In [4]: df_1 Out[4]: a b 0 1 4 1 2 5 2 3 6 3 x y We now remove the added row from df_1 and get the original df_1 back again: In [5]: df_1 = pd.concat([df_1, r]).drop_duplicates(keep=False) In [6]: df_1 Out[6]: a b 0 1 4 1 2 5 2 3 6 In [7]: df_2 Out[7]: a b 0 1 4 1 2 5 2 3 6 While df_1 and df_2 are identical, equals() returns False. In [8]: df_1.equals(df_2) Out[8]: False Did reseach on SO but could not find a related question. Am I doing somthing wrong? How to get the correct result in this case? (df_1==df_2).all().all() returns True but not suitable for the case where df_1 and df_2 have different length.
Use pandas.testing.assert_frame_equal(df_1, df_2, check_dtype=True), which will also check if the dtypes are the same. (It will pick up in this case that your dtypes changed from int to 'object' (string) when you appended, then deleted, a string row; pandas did not automatically coerce the dtype back down to less expansive dtype.) AssertionError: Attributes of DataFrame.iloc[:, 0] (column name="a") are different Attribute "dtype" are different [left]: object [right]: int64
6
7
65,318,931
2020-12-16
https://stackoverflow.com/questions/65318931/stratifiedkfold-vs-kfold-in-scikit-learn
I use this code to test KFold and StratifiedKFold. import numpy as np from sklearn.model_selection import KFold,StratifiedKFold X = np.array([ [1,2,3,4], [11,12,13,14], [21,22,23,24], [31,32,33,34], [41,42,43,44], [51,52,53,54], [61,62,63,64], [71,72,73,74] ]) y = np.array([0,0,0,0,1,1,1,1]) sfolder = StratifiedKFold(n_splits=4,random_state=0,shuffle=False) floder = KFold(n_splits=4,random_state=0,shuffle=False) for train, test in sfolder.split(X,y): print('Train: %s | test: %s' % (train, test)) print("StratifiedKFold done") for train, test in floder.split(X,y): print('Train: %s | test: %s' % (train, test)) print("KFold done") I found that StratifiedKFold can keep the proportion of labels, but KFold can't. Train: [1 2 3 5 6 7] | test: [0 4] Train: [0 2 3 4 6 7] | test: [1 5] Train: [0 1 3 4 5 7] | test: [2 6] Train: [0 1 2 4 5 6] | test: [3 7] StratifiedKFold done Train: [2 3 4 5 6 7] | test: [0 1] Train: [0 1 4 5 6 7] | test: [2 3] Train: [0 1 2 3 6 7] | test: [4 5] Train: [0 1 2 3 4 5] | test: [6 7] KFold done It seems that StratifiedKFold is better, so should KFold not be used? When to use KFold instead of StratifiedKFold?
I think you should ask "When to use StratifiedKFold instead of KFold?". You need to know what "KFold" and "Stratified" are first. KFold is a cross-validator that divides the dataset into k folds. Stratified is to ensure that each fold of dataset has the same proportion of observations with a given label. So, it means that StratifiedKFold is the improved version of KFold Therefore, the answer to this question is we should prefer StratifiedKFold over KFold when dealing with classification tasks with imbalanced class distributions. FOR EXAMPLE Suppose that there is a dataset with 16 data points and imbalanced class distribution. In the dataset, 12 of data points belong to class A and the rest (i.e. 4) belong to class B. The ratio of class B to class A is 1/3. If we use StratifiedKFold and set k = 4, then, in each iteration, the training sets will include 9 data points from class A and 3 data points from class B while the test sets include 3 data points from class A and 1 data point from class B. As we can see, the class distribution of the dataset is preserved in the splits by StratifiedKFold while KFold does not take this into consideration.
28
52
65,411,519
2020-12-22
https://stackoverflow.com/questions/65411519/typeerror-object-of-type-natype-is-not-json-serializable
Thank you in advance for your help. My python code reads json input file and loads the data into a data frame, masks or changes on the data frame column specified by configuration and in the last stage, creates json output file. read json into data frame --> mask/change the df column ---> generate json Input json: [ { "BinLogFilename": "mysql.log", "Type": "UPDATE", "Table": "users", "ServerId": 1, "BinLogPosition": 2111 }, { { "BinLogFilename": "mysql.log", "Type": "UPDATE", "Table": "users", "ServerId": null, "BinLogPosition": 2111 }, ... ] when I load the above json into data frame, the data frame column "ServerId" has float values because it has null in few blocks of json input. The main central logic converts/fakes "ServerId" into another number, however the output contains float numbers. Output json: [ { "BinLogFilename": "mysql.log", "Type": "UPDATE", "Table": "users", "ServerId": 5627.0, "BinLogPosition": 2111 }, { "BinLogFilename": "mysql.log", "Type": "UPDATE", "Table": "users", "ServerId": null, "BinLogPosition": 2111 }, .... ] masking logic df['ServerId'] = [fake.pyint() if not(pd.isna(df['ServerId'][index])) else np.nan for index in range(len(df['ServerId']))] The challenge is, the output "ServerId" should contain only integers but unfortunately it contains floats. df['ServerId'] 0 9590.0 1 NaN 2 1779.0 3 1303.0 4 NaN I found a answer to this problem, to use 'Int64' df['ServerId'] = df['ServerId'].astype('Int64') 0 8920 1 <NA> 2 9148 3 2434 4 <NA> However using 'Int64', it converts NaN to NA and while writing back to json, i get an error as, TypeError: Object of type NAType is not JSON serializable with gzip.open(outputFile, 'w') as outfile: outfile.write(json.dumps(json_objects_list).encode('utf-8')) Is it possible to keep NaN after converting to 'Int64' data type? If this is not possible, how can i fix the error?
Indeed, Pandas NA and NaT are not JSON serialisable by the built-in Python json library. But the Pandas DataFrame to_json() method will handle those values for you and convert them to JSON null. from pandas import DataFrame, Series, NA, NaT df = DataFrame({"ServerId" : Series([8920, NA, 9148, 2434, NA], dtype="Int64") }) s = df.to_json() # -> {"ServerId":{"0":8920,"1":null,"2":9148,"3":2434,"4":null}}
10
4
65,324,466
2020-12-16
https://stackoverflow.com/questions/65324466/typeerror-invalid-shape-3-32-32-for-image-data-showing-a-colored-image-in
I have an array of images where each image is stored as the following dimension (3, 32, 32) if I wanted to show an image using plt.imshow(img) then I am getting the following error: TypeError: Invalid shape (3, 32, 32) for image data I understand why I am getting this error, because according to imshow documentation, it takes an array of shape (M, N), or (M, N, 3), or (M, N, 4) How can I convert the image such that it has the required dimensions without losing any of its data? Thanks!
Try transposing: img.T This will reverse the order of the dimensions, making it (M,N,3).
14
15
65,390,129
2020-12-21
https://stackoverflow.com/questions/65390129/venv-activate-doesnt-not-change-my-python-path
I create a virtual environment (test_venv) and I activate it. So far, successful. HOWEVER, the path of the Python Interpreter doesn't change. I have illustrated the situation below. For clarification, the python path SHOULD BE ~/Desktop/test_venv/bin/python. >>> python3 -m venv Desktop/test_venv >>> source Desktop/test_venv/bin/activate (test_venv) >>> which python /usr/bin/python
It is not an answer specifically to your question, but it corresponds the title of the question. I faced similar problem and couldn't find solution on Internet. Maybe someone use my experience. I created virtual environment for my python project. Some time later my python interpreter also stopped changing after virtual environment activation. Similar to how you described. My problem was that I moved the project folder to a different directory some time ago. And if I return the folder to its original directory, then everything starts working again. There is following problem resolution. You save all package requirements (for example, using 'pip freeze' or 'poetry') and remove 'venv'-folder (or in your case 'test_venv'-folder). After that we create virtual environment again, activate it and install all requirements. This approach resolved my problem.
18
22
65,348,890
2020-12-17
https://stackoverflow.com/questions/65348890/python-was-not-found-run-without-arguments-to-install-from-the-microsoft-store
I was trying to download a GUI, but the terminal kept giving me this error: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. I'm trying to install it using this command: python -m pip install --upgrade pip setuptools virtualenv
You need to download Python from https://python.org. When in the installation, be sure to check the option that adds Python to PATH.
246
32
65,383,338
2020-12-20
https://stackoverflow.com/questions/65383338/zsh-illegal-hardware-instruction-python-when-installing-tensorflow-on-macbook
I'm trying to get tensorflow working on my MacBook pro M1. However, I keep getting the following error when trying to import: zsh: illegal hardware instruction python I have downloaded and installed tensorflow via this link. These were my installation steps: install a venv: python3 -m venv venv. drag the install_venv.sh (which is located within the downloaded folder) file to the terminal, add -p at the end. select the directory of the venv as the location where tensorflow should be installed. activate the venv. type "python". try to import tensorflow: import tensorflow as tf. I'm using Python 3.8.2.
This worked for me after trying a bunch of solutions to no avail. Step 1 Using pyenv install python version 3.8.5 and set it as your default python version. This tutorial(https://realpython.com/intro-to-pyenv/) is helpful for getting pyenv configured properly. Step 1.1 Use this post(https://github.com/pyenv/pyenv/issues/1446) if you have troubles running pyenv in zsh. Step 1.2 Once you have python version 3.8.5 running which you can check by running python -V which should output: Python 3.8.5 Step 2 Install virtualenv via pip install virtualenv Step 2.1 Create a virtual environment by running virtualenv ENV Step 2.2 Activate that virtual environment by running source ENV/bin/activate Step 3 Install the tensorflow wheel called tensorflow-2.4.1-py3-none-any.whl located at this public google drive link https://drive.google.com/drive/folders/1oSipZLnoeQB0Awz8U68KYeCPsULy_dQ7 Step 3.1 Assuming you simply installed the wheel to downloads run pip install ~/Downloads/tensorflow-2.4.1-py3-none-any.whl in your activated virtual environment Step 4 Type python which will bring up >>>in your terminal and type >>> import tensorflow >>> If there is no 'zsh illegal hardware instruction" error you should be good to go. Note: If you are using anaconda, the above will also work. You can skip the virtual env steps (assuming you have a virtual env activated through Conda) and just go straight to the pip install as mentioned above (steps 3 and later).
47
41