question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | 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 |
|---|---|---|---|---|---|---|
60,618,896 | 2020-3-10 | https://stackoverflow.com/questions/60618896/how-to-run-tensorflow-inference-for-multiple-models-on-gpu-in-parallel | Do you know any elegant way to do inference on 2 python processes with 1 GPU tensorflow? Suppose I have 2 processes, first one is classifying cats/dogs, 2nd one is classifying birds/planes, each process is running different tensorflow model and run on GPU. These 2 models will be given images from different cameras cont... | OK. I think I've found the solution now. I use tensorflow 2 and there are essentially 2 methods to manage the memory usage of GPU. set memory growth to true set memory limit to some number You can use both methods, ignore all the warning messages about out of memory stuff. I still don't know what it exactly means but... | 13 | 3 |
60,626,517 | 2020-3-10 | https://stackoverflow.com/questions/60626517/use-walrus-operator-in-python-3-7 | Why are future imports limited to only certain functionality? Is there no way to get the walrus operator in Python 3.7? I thought this would work, but it doesn't: from __future__ import walrus It doesn't work because walrus isn't in the list of supported features: __future__.all_feature_names ['nested_scopes', 'genera... | If the version of Python you're using doesn't contain an implementation of a feature, then you cannot use that feature; writing from __future__ import ... cannot cause that feature to be implemented in the version of Python you have installed. The purpose of __future__ imports is to allow an "opt-in" period for new fea... | 19 | 33 |
60,616,802 | 2020-3-10 | https://stackoverflow.com/questions/60616802/how-to-type-hint-a-generic-numeric-type-in-python | Forgive me if this question has been asked before but I could not find any related answer. Consider a function that takes a numerical type as input parameter: def foo(a): return ((a+1)*2)**4; This works with integers, floats and complex numbers. Is there a basic type so that I can do a type hinting (of a real existing... | PEP 3141 added abstract base classes for numbers, so you could use: from numbers import Number def foo(a: Number) -> Number: ... | 68 | 85 |
60,581,677 | 2020-3-7 | https://stackoverflow.com/questions/60581677/experimental-list-devices-attribute-missing-in-tensorflow-core-api-v2-config | Am using tensorflow 2.1 on Windows 10. On running model.add(Conv3D(16, (22, 5, 5), strides=(1, 2, 2), padding='valid',activation='relu',data_format= "channels_first", input_shape=input_shape)) on spyder, I get the this error: { AttributeError: module 'tensorflow_core._api.v2.config' has no attribute 'experimental_list... | I found the answer here - https://github.com/keras-team/keras/issues/13684. I had the same issue for load_model() from keras under Anaconda: AttributeError: module 'tensorflow_core._api.v2.config' has no attribute 'experimental_list_devices' I found source of problem in ...\anaconda3\envs\tf_env\Lib\site-packages\k... | 6 | 16 |
60,610,280 | 2020-3-10 | https://stackoverflow.com/questions/60610280/bertforsequenceclassification-vs-bertformultiplechoice-for-sentence-multi-class | I'm working on a text classification problem (e.g. sentiment analysis), where I need to classify a text string into one of five classes. I just started using the Huggingface Transformer package and BERT with PyTorch. What I need is a classifier with a softmax layer on top so that I can do 5-way classification. Confusin... | The answer to this lies in the (admittedly very brief) description of what the tasks are about: [BertForMultipleChoice] [...], e.g. for RocStories/SWAG tasks. When looking at the paper for SWAG, it seems that the task is actually learning to choose from varying options. This is in contrast to your "classical" classif... | 19 | 17 |
60,517,286 | 2020-3-4 | https://stackoverflow.com/questions/60517286/rolling-apply-function-must-be-real-number-not-nonetype | I'm trying to use rolling and apply function to print window but I got the error says File "pandas/_libs/window.pyx", line 1649, in pandas._libs.window.roll_generic TypeError: must be real number, not NoneType My code is following def print_window(window): print(window) print('==================') def example(): df ... | This behavior appeared in pandas=1.0.0. The function of the apply is now expected to return a single value to affect the corresponding column with. https://pandas.pydata.org/pandas-docs/version/1.0.0/reference/api/pandas.core.window.rolling.Rolling.apply.html#pandas.core.window.rolling.Rolling.apply A workaround for y... | 8 | 7 |
60,604,046 | 2020-3-9 | https://stackoverflow.com/questions/60604046/i-was-wondering-what-is-meant-by-class-state-in-oop-particularly-in-python | Today, someone asked me about static methods and said is that right that static method can't access or modify a class state? | General OO answer: the state of an object is the values of it's attributes. For example, given class Point: def __init__(self, x, y): self.x = x self.y = y p = Point(42, 43) then the state of p is {"x": 42, "y": 43} To modify an object's state, a method need to have access to this object. For ordinary methods, this i... | 7 | 8 |
60,613,233 | 2020-3-10 | https://stackoverflow.com/questions/60613233/what-does-frozen-distribution-mean-in-scipy | In the documentation of scipy, the 'frozen pdf', etc, is mentioned sometimes, but I don't know the meaning of it? Is it a statistical concept or scipy terminology? | I agree that the docs are somewhat unclear on the issue. It seems that the frozen distribution fixes the first n moments for programmer's convenience. I am unaware of the term "forzen distribution" outside of SciPy. SciPy's frozen distribution is perhaps best described here: Passing the loc and scale keywords time and... | 9 | 9 |
60,607,436 | 2020-3-9 | https://stackoverflow.com/questions/60607436/split-django-models-py-into-multiple-files-inside-folder-django-3-0-4 | I'm trying to split the models.py into multiple files inside a folder. what is the proper way to do that ? all the methods in the internet from 8 years ago and it's not working now. UPDATE 1: test1 __init__.py admin.py apps.py tests.py views.py migrations models __init__.py comment.py like.py post.py profile.py insid... | You can do that putting them into a models folder, like: models/ - __init__.py - model_1.py - model_2.py and __init__.py should import all models contained in the other files from .model_1 import Model1 from .model_2 import Model2 It is up to you to split them, depending on if you have a lot of models and if those ar... | 7 | 20 |
60,561,959 | 2020-3-6 | https://stackoverflow.com/questions/60561959/is-returning-a-value-other-than-self-in-enter-an-anti-pattern | Following this related question, while there are always examples of some library using a language feature in a unique way, I was wondering whether returning a value other than self in an __enter__ method should be considered an anti-pattern. The main reason why this seems to me like a bad idea is that it makes wrapping... | TLDR: Returning something other than self from __enter__ is perfectly fine and not bad practice. The introducing PEP 343 and Context Manager specification expressly list this as desired use cases. An example of a context manager that returns a related object is the one returned by decimal.localcontext(). These manager... | 7 | 7 |
60,601,412 | 2020-3-9 | https://stackoverflow.com/questions/60601412/tensorflow-2-0-how-to-transform-from-mapdataset-after-reading-from-tfrecord-t | I've stored my training and validation data on two separate TFRecord files, in which I store 4 values: signal A (float32 shape (150,)), signal B (float32 shape (150,)), label (scalar int64), id (string). My parsing function for reading is: def _parse_data_function(sample_proto): raw_signal_description = { 'label': tf.i... | You can simply do this in the parse function. For example: def _parse_data_function(sample_proto): raw_signal_description = { 'label': tf.io.FixedLenFeature([], tf.int64), 'id': tf.io.FixedLenFeature([], tf.string), } for key, item in SIGNALS.items(): raw_signal_description[key] = tf.io.FixedLenFeature(item, tf.float32... | 9 | 5 |
60,596,102 | 2020-3-9 | https://stackoverflow.com/questions/60596102/selected-kde-bandwidth-is-0-cannot-estimate-density | import pandas as pd import seaborn as sns ser_test = pd.Series([1,0,1,4,6,0,6,5,1,3,2,5,1]) sns.kdeplot(ser_test, cumulative=True) The above code generates the following CDF graph: But when the elements of the series are modified to: ser_test = pd.Series([1,0,1,1,6,0,6,1,1,0,2,1,1]) sns.kdeplot(ser_test, cumulative=T... | What's going on here is that Seaborn (or rather, the library it relies on to calculate the KDE - scipy or statsmodels) isn't managing to figure out the "bandwidth", a scaling parameter used in the calculation. You can pass it manually. I played with a few values and found 1.5 gave a graph at the same scale as your prev... | 13 | 8 |
60,599,469 | 2020-3-9 | https://stackoverflow.com/questions/60599469/typing-restrict-to-a-list-of-strings | This is Python 3.7 I have a dataclass like this: @dataclass class Action: action: str But action is actually restricted to the values "bla" and "foo". Is there a sensible way to express this? | You could use an Enum: from dataclasses import dataclass from enum import Enum class ActionType(Enum): BLA = 'bla' FOO = 'foo' @dataclass class Action: action: ActionType >>> a = Action(action=ActionType.FOO) >>> a.action.name 'FOO' >>> a.action.value 'foo' | 11 | 10 |
60,598,837 | 2020-3-9 | https://stackoverflow.com/questions/60598837/html-to-image-using-python | Here is a variable html_str, it is a string that contains html tags and contents in body. I am created a .html file from this string using the below code in python. html_file = open("filename.html", "w") html_file.write(html_str) html_file.close() now i got html file named file "filename.html". Now i want to convert t... | You can do this by using imgkit import imgkit imgkit.from_file('test.html', 'out.jpg') Or you can also use htmlcsstoimage Api # pip3 install requests import requests HCTI_API_ENDPOINT = "https://hcti.io/v1/image" HCTI_API_USER_ID = 'your-user-id' HCTI_API_KEY = 'your-api-key' data = { 'html': "<div class='box'>Hello, ... | 32 | 36 |
60,588,385 | 2020-3-8 | https://stackoverflow.com/questions/60588385/plotly-how-to-group-data-and-specify-colors-using-go-box-instead-of-px-box | The question: Using plotly express you can group data and assign different colors using color=<group> in px.box(). But how can you do the same thing using plotly.graph_objects and go.box() Some details: Plotly Express is nice but sometimes we need more than the basics. So I tried to use Plotly Go instead but then I can... | Let's jump straight to the answer and shed some light on the details afterwards. In order to set the colors for your go.box figures you'll have to split the dataset in the groups you want to study, and assign a color to each subcategory using line=dict(color=<color>). The code snippet below will show you how you can us... | 8 | 11 |
60,593,624 | 2020-3-9 | https://stackoverflow.com/questions/60593624/modify-trained-model-architecture-and-continue-training-keras | I want to train a model in a sequential manner. That is I want to train the model initially with a simple architecture and once it is trained, I want to add a couple of layers and continue training. Is it possible to do this in Keras? If so, how? I tried to modify the model architecture. But until I compile, the chang... | Without knowing the details of your model, the following snippet might help: from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, Input # Train your initial model def get_initial_model(): ... return model model = get_initial_model() model.fit(...) model.save_weights('initial_model_weight... | 7 | 4 |
60,571,301 | 2020-3-6 | https://stackoverflow.com/questions/60571301/run-localhost-server-in-google-colab-notebook | I am trying to implement Tacotron speech synthesis with Tensorflow in Google Colab using this code form a repo in Github, below is my code and working good till the step of using localhost server, how I can to run a localhost server in a notebook in Google Colab? My code: !pip install tensorflow==1.3.0 import tensorfl... | You can do this by using tools like ngrok or remote.it They give you a URL that you can access from any browser to access your web server running on 8888 Example 1: Tunneling tensorboard running on !wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip !unzip ngrok-stable-linux-amd64.zip get_ipython()... | 17 | 10 |
60,584,948 | 2020-3-8 | https://stackoverflow.com/questions/60584948/pythonic-way-of-doing-composition-aliases | What is the most pythonic and correct way of doing composition aliases? Here's a hypothetical scenario: class House: def cleanup(self, arg1, arg2, kwarg1=False): # do something class Person: def __init__(self, house): self.house = house # aliases house.cleanup # 1. self.cleanup_house = self.house.cleanup # 2. def clean... | There are a number of problems with the first method: The alias won't update when the attribute it refers to changes unless you jump through extra hoops. You could, for example, make house a property with a setter, but that is non-trivial work for something that shouldn't require it. See the end of this answer for a s... | 8 | 8 |
60,582,073 | 2020-3-7 | https://stackoverflow.com/questions/60582073/better-way-to-check-multiple-columns-with-the-same-condition-in-pandas | I got the output but trying to find a more efficient way to do this: (df['budget'] == 0).sum(), (df['revenue'] == 0).sum(),(df['budget_adj'] == 0).sum(), (df['revenue_adj'] == 0).sum() Output is (5674, 5993, 5676, 5993) | You can compare the columns in bulk and sum these up column-wise: (df[['budget', 'revenue', 'budget_adj', 'revenue_adj']] == 0).sum(axis=0) | 8 | 3 |
60,549,865 | 2020-3-5 | https://stackoverflow.com/questions/60549865/what-causes-a-to-overallocate | Apparently list(a) doesn't overallocate, [x for x in a] overallocates at some points, and [*a] overallocates all the time? Here are sizes n from 0 to 12 and the resulting sizes in bytes for the three methods: 0 56 56 56 1 64 88 88 2 72 88 96 3 80 88 104 4 88 88 112 5 96 120 120 6 104 120 128 7 112 120 136 8 120 120 15... | [*a] is internally doing the C equivalent of: Make a new, empty list Call newlist.extend(a) Returns list. So if you expand your test to: from sys import getsizeof for n in range(13): a = [None] * n l = [] l.extend(a) print(n, getsizeof(list(a)), getsizeof([x for x in a]), getsizeof([*a]), getsizeof(l)) Try it online... | 149 | 87 |
60,574,862 | 2020-3-7 | https://stackoverflow.com/questions/60574862/calculating-pairwise-euclidean-distance-between-all-the-rows-of-a-dataframe | How can I calculate the Euclidean distance between all the rows of a dataframe? I am trying this code, but it is not working: zero_data = data distance = lambda column1, column2: pd.np.linalg.norm(column1 - column2) result = zero_data.apply(lambda col1: zero_data.apply(lambda col2: distance(col1, col2))) result.head() ... | To compute the Eucledian distance between two rows i and j of a dataframe df: np.linalg.norm(df.loc[i] - df.loc[j]) To compute it between consecutive rows, i.e. 0 and 1, 1 and 2, 2 and 3, ... np.linalg.norm(df.diff(axis=0).drop(0), axis=1) If you want to compute it between all the rows, i.e. 0 and 1, 0 and 2, ..., 1 ... | 8 | 9 |
60,560,093 | 2020-3-6 | https://stackoverflow.com/questions/60560093/monkey-patching-class-with-inherited-classes-in-python | After reading the answers to the question about monkey-patching classes in Python I tried to apply the advised solution to the following case. Imagine that we have a module a.py class A(object): def foo(self): print(1) class AA(A): pass and let us try to monkey patch it as follows. It works when we monkey patch class ... | You need to explicitly overwrite the tuple of base classes in a.AA, though I don't recommend modifying classes like this. >>> import a >>> class B: ... def foo(self): ... print(2) ... >>> a.AA.__bases__ = (B,) >>> a.AA().foo() 2 This will also be reflected in a.A.__subclasses__() (although I am not entirely sure as to... | 8 | 5 |
60,571,675 | 2020-3-6 | https://stackoverflow.com/questions/60571675/setting-dynamic-folder-and-report-name-in-pytest | I have a problem with setting report name and folder with it dynamically in Python's pytest. For example: I've run all pytest's tests @ 2020-03-06 21:50 so I'd like to have my report stored in folder 20200306 with name report_2150.html. I want it to be automated and triggered right after the tests are finished. I'm wor... | You can customize the plugin options in a custom impl of the pytest_configure hook. Put this example code in a conftest.py file in your project root dir: from datetime import datetime from pathlib import Path import pytest @pytest.hookimpl(tryfirst=True) def pytest_configure(config): # set custom options only if none a... | 9 | 11 |
60,571,475 | 2020-3-6 | https://stackoverflow.com/questions/60571475/install-or-suggest-to-missing-imported-python-modules-on-vs-code-like-pycharm | When we import a module that isn't currently installed on the Python used on the current environment, PyCharm suggest us to 'install missing module', if you click install, it'll install it automatically... Is there any plugin for vscode that does that or something like that? I want to import emoji for example, and like... | I think that your request is already ongoing on vscode-python extension: https://github.com/microsoft/vscode-python/issues/8062 I suggest to follow this issue to see when it's ready for production. | 9 | 5 |
60,567,679 | 2020-3-6 | https://stackoverflow.com/questions/60567679/save-keras-model-weights-directly-to-bytes-memory | Keras allows for saving entire models or just model weights (see thread). When saving the weights, they must be saved to a file, eg: model = keras_model() model.save_weights('/tmp/model.h5') Instead of writing to file, I'd like to just save the bytes into memory. Something like model.dump_weights() Tensorflow doesn't... | Thanks @ddoGas for pointing out the model.get_weights() method, which returns a list of weights that can then be serialized. Just some context for why I am not saving the model in the conventional way: we are working with model wrapper classes that associate a model and custom behavior. For example, before prediction o... | 7 | 0 |
60,564,570 | 2020-3-6 | https://stackoverflow.com/questions/60564570/how-to-subset-list-elements-that-lie-between-two-missing-values | With a list containing some missing values such as this: [10, 11, 12,np.nan, 14, np.nan, 16, 17, np.nan, 19, np.nan] How can you subset the values that are positioned between two missing (nan) values? I know how to do it with a for loop : # imports import numpy as np # input lst=[10,11,12,np.nan, 14, np.nan, 16, 17, n... | Use list comprehension import numpy as np lst=[10,11,12,np.nan, 14, np.nan, 16, 17, np.nan, np.nan, np.nan] subset = [elem for i, elem in enumerate(lst) if i and i < len(lst)-1 and np.isnan(lst[i-1]) and np.isnan(lst[i+1]) and not np.isnan(elem)] print(subset) Corrected the mistakes that were pointed out by other cont... | 7 | 6 |
60,554,339 | 2020-3-5 | https://stackoverflow.com/questions/60554339/find-distance-to-nearest-zero-in-numpy-array | Let's say I have a NumPy array: x = np.array([0, 1, 2, 0, 4, 5, 6, 7, 0, 0]) At each index, I want to find the distance to nearest zero value. If the position is a zero itself then return zero as a distance. Afterward, we are only interested in distances to the nearest zero that is to the right of the current position... | Approach #1 : Searchsorted to the rescue for linear-time in a vectorized manner (before numba guys come in)! mask_z = x==0 idx_z = np.flatnonzero(mask_z) idx_nz = np.flatnonzero(~mask_z) # Cover for the case when there's no 0 left to the right # (for same results as with posted loop-based solution) if x[-1]!=0: idx_z =... | 14 | 10 |
60,553,723 | 2020-3-5 | https://stackoverflow.com/questions/60553723/why-do-queryset0-and-queryset-first-return-different-records | I discovered today that I can access elements in a queryset by referencing them with an index, i.e. queryset[n]. However, immediately after I discovered that queryset[0] does not return the same record as queryset.first(). Why is this, and is one of those more "correct"? (I know that .first() is faster, but other than ... | There is a small semantical difference between qs[0] and qs.first(). If you did not specify an order in the queryset yourself, then Django will order the queryset itself by primary key before fetching the first element. Furthermore .first() will return None if the queryset is empty. Whereas qs[0] will raise an IndexErr... | 7 | 9 |
60,534,999 | 2020-3-4 | https://stackoverflow.com/questions/60534999/how-to-solve-spanish-lemmatization-problems-with-spacy | When trying lemmatize in Spanish a csv with more than 60,000 words, SpaCy does not correctly write certain words, I understand that the model is not 100% accurate. However, I have not found any other solution, since NLTK does not bring a Spanish core. A friend tried to ask this question in Spanish Stackoverflow, howeve... | Unlike the English lemmatizer, spaCy's Spanish lemmatizer does not use PoS information at all. It relies on a lookup list of inflected verbs and lemmas (e.g., ideo idear, ideas idear, idea idear, ideamos idear, etc.). It will just output the first match in the list, regardless of its PoS. I actually developed spaCy's n... | 10 | 21 |
60,551,227 | 2020-3-5 | https://stackoverflow.com/questions/60551227/how-to-check-if-a-python-object-is-a-numpy-ndarray | I have a function that takes an array as input and does some computation on it. The input array may or may not be a numpy ndarray (may be a list, pandas object, etc). In the function, I convert the input array (regardless of its type) to a numpy ndarray. But this step may be computationally expensive for large arrays,... | It is simpler to use asarray: def myfunc(arr): arr = np.asarray(arr) # The computation on array # Do something with array new_array = other_func(arr) return new_array If arr is already an array, asarray does not make a copy, so there's no penalty to passing it through asarray. Let numpy do the testing for you. numpy f... | 8 | 4 |
60,536,592 | 2020-3-5 | https://stackoverflow.com/questions/60536592/how-do-you-model-something-over-time-in-python | I'm looking for a data type to help me model resource availability over fluid time. We're open from 9 til 6 and can handle 5 parallel jobs. In my imaginary programming land, I've just initialised an object with that range with a value of 3 across the board. We have appointments on the books, each with start and end ti... | My approach would be to build the time series, but include the availability object with a value set to the availability in that period. availability: [ { "start": 09:00, "end": 12:00, "value": 4 }, { "start": 12:00, "end": 13:00, "value": 3 } ] data: [ { "start": 10:00, "end": 10:30, } ] Build the time series indexin... | 8 | 8 |
60,521,925 | 2020-3-4 | https://stackoverflow.com/questions/60521925/how-to-detect-the-horizontal-and-vertical-lines-of-a-table-and-eliminate-the-noi | I am trying to get the horizontal and vertical lines of the table in an image in order to extract the texts in cells. Here's a picture I use: I use the code below to extract the vertical and horizontal lines: img = cv2.imread(img_for_box_extraction_path, 0) # Read the image (thresh, img_bin) = cv2.threshold(img, 200, 2... | Here's a simple method: Binary image Detected horizontal Detected vertical Combined masks Lines to be removed in green Result import cv2 import numpy as np # Load image, grayscale, Gaussian blur, Otsu's threshold image = cv2.imread('1.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gr... | 10 | 14 |
60,537,557 | 2020-3-5 | https://stackoverflow.com/questions/60537557/how-to-make-a-simple-python-rest-server-and-client | I'm attempting to make the simplest possible REST API server and client, with both the server and client being written in Python and running on the same computer. From this tutorial: https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask I'm using this for the server: # server.py from flask ... | From help(requests.get): Help on function get in module requests.api: get(url, params=None, **kwargs) Sends a GET request. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments tha... | 10 | 5 |
60,535,139 | 2020-3-4 | https://stackoverflow.com/questions/60535139/using-tuple-as-a-key-in-a-dictionary-in-javascript | In python I have a Random dictionary where I use tuple as a key and each is mapped to some value. Sample Random_Dict = { (4, 2): 1, (2, 1): 3, (2, 0): 7, (1, 0): 8 } example in above key: (4,2) value: 1 I am attempting to replicate this in Javascript world This is what I came up with const randomKeys = [[4, 2], [2, 1]... | You can use a Map to map sets of 2 arbitrary values. In the following snippet the keys can be 'tuples' (1), or any other data type, and the values can be as well: const values = [ [ [4, 2], 1], [ [2, 1], 3], [ [2, 0], 7], [ [1, 0], 9], ]; const map = new Map(values); // Get the number corresponding a specific 'tuple'... | 8 | 5 |
60,528,954 | 2020-3-4 | https://stackoverflow.com/questions/60528954/pandas-read-csv-and-set-index-column | I have a problem when I read a .csv and set the 'Column A' as index column. df = pd.read_csv(index_col = 'Column A') print(df.colums) However, I cannot access 'Column A' anymore. I still want to use it as one column to access its date. Can anyone help? | I found this is very straightforward: just setting index as a column. df['index1'] = df.index | 8 | 5 |
60,528,792 | 2020-3-4 | https://stackoverflow.com/questions/60528792/how-to-combine-javascript-react-frontend-and-python-backend | I'm not quite sure if my question is a duplicate, but I wasn't able to find something helping me in my case. Set Up I've built a frontend webpage which contains a couple of services, for example show some timeseries and other information about my system. The website is build with the react framework and so using javas... | You can expose your Python scripts on a REST API which will be called by your React frontend. Database connection will be made by this API, and the response is sent to your frontend. See Flask (very simple for small projects) or even Django to build Python APIs. | 14 | 11 |
60,524,565 | 2020-3-4 | https://stackoverflow.com/questions/60524565/global-variable-imported-from-a-module-does-not-update-why | I'm having trouble understanding why importing a global variable from another module works as expected when using import, but when using from x import * the global variable doesn't appear to update within its own module Imagine I have 2 files, one.py: def change(value): global x x = value x = "start" and two.py: from ... | You can think of a package as a dict. Every function and variable in a package is listed as a key in that dict which you can view using globals(). When you import an object from another package, you copy a reference to the object into your own package under a name (usually the same, different if you import <var> as <n... | 16 | 14 |
60,499,745 | 2020-3-3 | https://stackoverflow.com/questions/60499745/does-pandas-use-hashing-for-a-single-indexed-dataframe-and-binary-searching-for | I have always been under impression that Pandas uses hashing when indexing the rows in a dataframe such that the operations like df.loc[some_label] is O(1). However, I just realized today that this is not the case, at least for multi-indexed dataframe. As pointed out in the document, "Indexing will work even if the dat... | Does a single-indexed DataFrame use hash-based indexing? No, Pandas does not use hash-based indexing for single-indexed DataFrames. Instead, it relies on array-based lookups or binary search when the index is sorted. If the index is unsorted, Pandas performs a linear scan, which is less efficient. If the DataFrame is... | 11 | 1 |
60,421,475 | 2020-2-26 | https://stackoverflow.com/questions/60421475/dcgan-debugging-getting-just-garbage | Introduction: I am trying to get a CDCGAN (Conditional Deep Convolutional Generative Adversarial Network) to work on the MNIST dataset which should be fairly easy considering that the library (PyTorch) I am using has a tutorial on its website. But I can't seem to get It working it just produces garbage or the model col... | So I solved this issue a while ago, but forgot to post an answer on stack overflow. So I will simply post my code here which should work probably pretty good. Some disclaimer: I am not quite sure if it works since I did this a year ago its for 128x128px Images MNIST It's not a vanilla GAN I used various optimization t... | 31 | 2 |
60,455,830 | 2020-2-28 | https://stackoverflow.com/questions/60455830/can-you-have-an-async-handler-in-lambda-python-3-6 | I've made Lambda functions before but not in Python. I know in Javascript Lambda supports the handler function being asynchronous, but I get an error if I try it in Python. Here is the code I am trying to test: async def handler(event, context): print(str(event)) return { 'message' : 'OK' } And this is the error I get... | Not at all. Async Python handlers are not supported by AWS Lambda. If you need to use async/await functionality in your AWS Lambda, you have to define an async function in your code (either in Lambda files or a Lambda Layer) and call asyncio.get_event_loop().run_until_complete(your_async_handler()) inside your regular ... | 51 | 66 |
60,439,570 | 2020-2-27 | https://stackoverflow.com/questions/60439570/pytorch-runtimeerror-shape-16-400-is-invalid-for-input-of-size-9600 | I'm trying to build a CNN but I get this error: ---> 52 x = x.view(x.size(0), 5 * 5 * 16) RuntimeError: shape '[16, 400]' is invalid for input of size 9600 It's not clear for me what the inputs of the 'x.view' line should be. Also, I don't really understand how many times I should have this 'x.view' function in my cod... | This means that instead the product of the channel and spatial dimensions is not 5*5*16. To flatten the tensor, replace x = x.view(x.size(0), 5 * 5 * 16) with: x = x.view(x.size(0), -1) | 10 | 7 |
60,410,426 | 2020-2-26 | https://stackoverflow.com/questions/60410426/prevent-f-string-from-converting-float-into-scientific-notation | I was struck by this default behavior of f-strings in python 3.7.2: >> number = 0.0000001 >> string = f"Number: {number}" >> print(string) Number: 1e-07 What I expected was: Number: 0.0000001 This is very annoying especially for creation of filenames. How can I disable this automatic conversion into the scientific not... | After checking other sources, I found numpy.format_float_positional which works very nicely here: import numpy as np number = 0.0000001 string = f"Number: {np.format_float_positional(number)}" | 10 | 1 |
60,424,390 | 2020-2-27 | https://stackoverflow.com/questions/60424390/is-there-a-way-to-kill-uvicorn-cleanly | Is there a way to kill uvicorn cleanly? I.e., I can type ^C at it, if it is running in the foreground on a terminal. This causes the uvivorn process to die and all of the worker processes to be cleaned up. (I.e., they go away.) On the other hand, if uvicorn is running in the background without a terminal, then I can't ... | That's because you're running uvicorn as your only server. uvicorn is not a process manager and, as so, it does not manage its workers life cycle. That's why they recommend running uvicorn using gunicorn+UvicornWorker for production. That said, you can kill the spawned workers and trigger it's shutdown using the script... | 42 | 23 |
60,414,753 | 2020-2-26 | https://stackoverflow.com/questions/60414753/how-to-install-githttps-from-setup-py-using-install-requires | I have a project in which I have to install from git+https: I can make it to work in this way: virtualenv -p python3.5 bla . bla/bin/activate pip install numpy # must have numpy before the following pkg... pip install 'git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI' However, I want to use it in ... | install_requires must be a string or a list of strings with names and optionally URLs to get the package from: install_requires=[ 'pycocotools @ git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI' ] See https://pip.pypa.io/en/stable/reference/requirement-specifiers/ and https://www.python.org/dev/pe... | 13 | 27 |
60,430,112 | 2020-2-27 | https://stackoverflow.com/questions/60430112/single-sourcing-package-version-for-setup-cfg-python-projects | For traditional Python projects with a setup.py, there are various ways of ensuring that the version string does not have to be repeated throughout the code base. See PyPA's guide on "Single-sourcing the package version" for a list of recommendations. Many are trying to move away from setup.py to setup.cfg (probably un... | There are a couple of ways to do this (see below for the project structure used in these examples): 1. setup.cfg [metadata] version = 1.2.3.dev4 src/my_top_level_package/__init__.py import importlib.metadata __version__ = importlib.metadata.version('MyProject') 2. setup.cfg [metadata] version = file: VERSION.txt VER... | 26 | 37 |
60,517,190 | 2020-3-3 | https://stackoverflow.com/questions/60517190/are-poetry-lock-files-os-independent | I am creating a poetry.lock file on my Mac. Then, I am using it to build a Docker image based on Debian. My question is the following: is there any guarantee that the exact packages will be found by the Debian image? I might be mistaken but I remember packages might not exist in every version for every OS. That’s seem ... | Broadly, they are portable to any OS, yes. But you must understand this has "nothing" to do with poetry nor pipenv nor pip but with the fact that each package version can be distributed for multiple platforms. It is pip who will pick a particular wheel that matches the compatible platform tags for the system issuing th... | 16 | 11 |
60,509,425 | 2020-3-3 | https://stackoverflow.com/questions/60509425/how-to-use-repeat-function-when-building-data-in-keras | I am training a binary classifier on a dataset of cats and dogs: Total Dataset: 10000 images Training Dataset: 8000 images Validation/Test Dataset: 2000 images The Jupyter notebook code: # Part 2 - Fitting the CNN to the images train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, ho... | Your problem stems from the fact that the parameters steps_per_epoch and validation_steps need to be equal to the total number of data points divided by the batch_size. Your code would work in Keras 1.X, prior to August 2017. Change your model.fit() function to: history = model.fit_generator(training_set, steps_per_epo... | 14 | 24 |
60,448,666 | 2020-2-28 | https://stackoverflow.com/questions/60448666/whats-the-use-of-the-del-method-in-python | From Python documentation: It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits. As far as I understand, there is also no way to guarantee an object stops existing before the interpreter exits, since it's up to the garbage collector to decide if and when an ob... | After reading all of these answers—none of which satisfactorily answered all of my questions/doubts—and rereading Python documentation, I've come to a conclusion of my own. This the summary of my thoughts on the matter. Implementation-agnostic The passage you quoted from the __del__ method documentation says: It is n... | 16 | 6 |
60,513,146 | 2020-3-3 | https://stackoverflow.com/questions/60513146/keras-iterator-with-augmented-images-and-other-features | Say you have a dataset that has images and some data in a .csv for each image. Your goal is to create a NN that has a convolution branch and another one (in my case an MLP). Now, there are plenty of guides (one here, another one) on how to create the network, that's not the problem. The issue here is how do I create an... | Let's say, you have a CSV, such that your images and the other features are in the file. Where id represents the image name, and followed by the features, and followed by your target, (class for classification, number for regression) | id | feat1 | feat2 | feat3 | class | |---------------------|-------|-------|-------|... | 10 | 5 |
60,486,649 | 2020-3-2 | https://stackoverflow.com/questions/60486649/pyspark-how-can-i-suppress-run-output-in-pyspark-cell-when-importing-variables | I am using multiple notebooks in PySpark and import variables across these notebooks using %run path. Every time I run the command, all variables that I displayed in the original notebook are being displayed again in the current notebook (the notebook in which I %run). But I do not want them to be displayed in the curr... | You can use the "Hide Result" option in the upper right toggle of the cell: | 11 | 12 |
60,436,768 | 2020-2-27 | https://stackoverflow.com/questions/60436768/create-a-gzip-file-like-object-for-unit-testing | I want to test a Python function that reads a gzip file and extracts something from the file (using pytest). import gzip def my_function(file_path): output = [] with gzip.open(file_path, 'rt') as f: for line in f: output.append('something from line') return output Can I create a gzip file like object that I can pass t... | You can use the io and gzip libraries to create in-memory file objects. Example: import io, gzip def inmem(): stream = io.BytesIO() with gzip.open(stream, 'wb') as f: f.write(b'spam\neggs\n') stream.seek(0) return stream | 7 | 7 |
60,411,012 | 2020-2-26 | https://stackoverflow.com/questions/60411012/running-apache-beam-python-pipelines-in-kubernetes | This question might seem like a duplicate of this. I am trying to run Apache Beam python pipeline using flink on an offline instance of Kubernetes. However, since I have user code with external dependencies, I am using the Python SDK harness as an External Service - which is causing errors (described below). The kubern... | (You said in a comment that the answer to the referenced post is valid, so I'll just address the specific error you ran into in case someone else hits it.) Your understanding is correct; the logging, artifact, etc. endpoints are essentially hardcoded to use localhost. These endpoints are meant to be only used internall... | 7 | 2 |
60,452,488 | 2020-2-28 | https://stackoverflow.com/questions/60452488/why-cant-arguments-be-passed-explicitly-as-x-and-y-in-pyplot | I am using matplotlib.pyplot module imported as plt for plots. In the plt.plot() statement, if I pass the arguments as "x= array1, "y= array2", I get "TypeError: plot got an unexpected keyword argument 'x' ". The code gets executed correctly if I simple pass "array1 and array2", without explicitly saying they corresp... | If you look at the function definition, https://github.com/matplotlib/matplotlib/blob/9a24fb724331f50baf0da4d17188860357d328a9/lib/matplotlib/axes/_axes.py#L72, you can see the asterisk there, and the use of that doesn't work with using keywords for non-optional parameters. See Python args and kwargs: Demystified for e... | 12 | 5 |
60,414,234 | 2020-2-26 | https://stackoverflow.com/questions/60414234/setting-pre-hook-for-docker-compose-file | I am running a dockerized django app and I am looking for a way to run (a) directive(s) every time before I build a docker container. More concretely, I would like to run docker-compose -f production.yml run --rm django python manage.py check --deploy each time before I either build or up the production.yml file and st... | Currently, this is not possible. There have been multiple requests to add such functionality, but the maintainers do not consider this a good idea. See: https://github.com/docker/compose/issues/468 https://github.com/docker/compose/issues/1341 https://github.com/docker/compose/issues/6736 | 13 | 11 |
60,432,137 | 2020-2-27 | https://stackoverflow.com/questions/60432137/jupyter-notebook-memory-management | I am currently working on a jupyter notebook in kaggle. After performing the desired transformations on my numpy array, I pickled it so that it can be stored on disk. The reason I did that is so that I can free up the memory being consumed by the large array. The memory consumed after pickling the array was about 8.7 ... | There is one basic drawback that you should be aware of: The CPython interpreter actually can actually barely free memory and return it to the OS. For most workloads, you can assume that memory is not freed during the lifetime of the interpreter's process. However, the interpreter can re-use the memory internally. So l... | 10 | 5 |
60,496,204 | 2020-3-2 | https://stackoverflow.com/questions/60496204/webdriverwait-for-multiple-conditions-or-logical-evaluation | Using python, the method WebDriverWait is used to wait for 1 element to be present on the webpage. How can this method be used without multiple try/except? Is there an OR option for multiple cases using this method? https://selenium-python.readthedocs.io/waits.html | Without using multiple try/except{} to induce WebDriverWait for two elements through OR option you can use either of the following solutions: Using CSS_SELECTOR: element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".element_A_class, .element_B_class")) Using XPATH through lambd... | 9 | 13 |
60,440,292 | 2020-2-27 | https://stackoverflow.com/questions/60440292/runtimeerror-expected-scalar-type-long-but-found-float | I can't get the dtypes to match, either the loss wants long or the model wants float if I change my tensors to long. The shape of the tensors are 42000, 1, 28, 28 and 42000. I'm not sure where I can change what dtypes are required for the model or loss. I'm not sure if dataloader is required, using Variable didn't wor... | LongTensor is synonymous with integer. PyTorch won't accept a FloatTensor as categorical target, so it's telling you to cast your tensor to LongTensor. This is how you should change your target dtype: Yt_train = Yt_train.type(torch.LongTensor) This is very well documented on the PyTorch website, you definitely won't r... | 54 | 100 |
60,462,840 | 2020-2-29 | https://stackoverflow.com/questions/60462840/ffmpeg-delay-in-decoding-h264 | I am taking raw RGB frames, encoding them to h264, then decoding them back to raw RGB frames. [RGB frame] ------ encoder ------> [h264 stream] ------ decoder ------> [RGB frame] ^ ^ ^ ^ encoder_write encoder_read decoder_write decoder_read I would like to retrieve the decoded frames as soon as possible. However, it se... | Add -probesize 32 to your decoder arguments. Set decoder command to: cmd = "ffmpeg -probesize 32 -f h264 -i pipe: -f rawvideo -pix_fmt rgb24 -s 224x224 pipe:" I found the solution here: How to minimize the delay in a live streaming with FFmpeg. According to FFmpeg StreamingGuide: Also setting -probesize and -an... | 7 | 10 |
60,439,489 | 2020-2-27 | https://stackoverflow.com/questions/60439489/django-run-tasks-possibly-in-the-far-future | Suppose I have a model Event. I want to send a notification (email, push, whatever) to all invited users once the event has elapsed. Something along the lines of: class Event(models.Model): start = models.DateTimeField(...) end = models.DateTimeField(...) invited = models.ManyToManyField(model=User) def onEventElapsed(... | We're doing something like this in the company i work for, and the solution is quite simple. Have a cron / celery beat that runs every hour to check if any notification needs to be sent. Then send those notifications and mark them as done. This way, even if your notification time is years ahead, it will still be sent. ... | 13 | 9 |
60,488,824 | 2020-3-2 | https://stackoverflow.com/questions/60488824/having-a-hard-time-getting-rabbitmq-server-started-and-wonder-why-keep-getting-t | I keep getting this error when I start Rabbitmq and wonder what's wrong? BOOT FAILED =========== Error description: init:do_boot/3 line 817 init:start_em/1 line 1109 rabbit:start_it/1 line 474 rabbit:broker_start/1 line 350 rabbit:start_loaded_apps/2 line 600 app_utils:manage_applications/6 line 126 lists:foldl/3 line... | I had the same issue on Arch Linux due to a crash dump. It was saying in the logs that it had problem with reverting a WAL file that was 0 bytes in size. After removing the WAL file the service started. Locate the WAL in /var/lib/rabbitmq/mnesia with find /var/lib/rabbitmq/ -name "*.wal" and remove it. Restart the serv... | 9 | 17 |
60,473,359 | 2020-3-1 | https://stackoverflow.com/questions/60473359/scapy-get-set-frequency-or-channel-of-a-packet | I have been trying to capture WIFI packets with Linux and see the frequency/channel at which packet was captured. I tried Wireshark and there was no luck and no help. Though using a sample packets from Wireshark, I can see the frequency/channel. So now I'm experimenting with Scapy. I wanted to figure out the frequency/... | I found out that RadioTab headers are not part of any Dot11 protocol but are merely added by the network interface. And the reason I got the RadioTab headers on sample packets from Wireshark.org and not from my live wireshark capture is because some network adapters do not add RadioTap while others do and the network a... | 11 | 8 |
60,512,207 | 2020-3-3 | https://stackoverflow.com/questions/60512207/partitionby-overwrite-strategy-in-an-azure-datalake-using-pyspark-in-databrick | I have a simple ETL process in an Azure environment blob storage > datafactory > datalake raw > databricks > datalake curated > datwarehouse(main ETL). the datasets for this project are not very big (~1 million rows 20 columns give or take) however I would like to keep them partitioned properly in my datalake as Parq... | I saw that you are using databricks in the azure stack. I think the most viable and recommended method for you to use would be to make use of the new delta lake project in databricks: It provides options for various upserts, merges and acid transactions to object stores like s3 or azure data lake storage. It basically ... | 8 | 16 |
60,416,350 | 2020-2-26 | https://stackoverflow.com/questions/60416350/chrome-80-how-to-decode-cookies | I had a working script for opening and decrypting Google Chrome cookies which looked like: decrypted = win32crypt.CryptUnprotectData(enctypted_cookie_value, None, None, None, 0) It seems that after update 80 it is no longer a valid solution. According to this blog post https://blog.nirsoft.net/2020/02/19/tools-update-... | Since Chrome version 80 and higher, cookies are encrypted using AES-256 in GCM mode. The applied key is encrypted using DPAPI. The details are described here, section Chrome v80.0 and higher. The encrypted key starts with the ASCII encoding of DPAPI (i.e. 0x4450415049) and is Base64 encoded, i.e. the key must first be ... | 14 | 31 |
60,497,516 | 2020-3-2 | https://stackoverflow.com/questions/60497516/django-add-comment-section-on-posts-feed | I want to share a project that currently can create user and each user can create N posts The source is available on github and I has two models users and post and the template layers Currently the feed for each post has a button that send an commenting the post I want to change that to put the comments of the post... | In the book Django 2 by Example we can find a step by step guide to create a comment system, wherein the users will be able to comment on posts. In order to do it, is as simple as the following four steps Create a model to save the comments Create a form to submit comments and validate the input data Add a view that p... | 7 | 12 |
60,515,935 | 2020-3-3 | https://stackoverflow.com/questions/60515935/visual-studio-code-does-not-attach-debugger-to-multi-processes-in-python-using-p | Hi I am trying to debug multi processes in python. This below is a portion of where I run multi-processes using Pool pool = Pool(num_half_logical_cpus) pool_result_dict = pool.starmap(process_batches, lstListSets) However, I can't hit any breakpoints. Can anyone guide me to hit those breakpoints I set up? Thanks! | Add this option to launch.json will let you debug multiple processes. "subProcess": true, Then it will hit the breakpoint then you are able to select which process you want to step through (F10). There will be a list of processes at the lower-left sub-window. | 8 | 22 |
60,422,693 | 2020-2-26 | https://stackoverflow.com/questions/60422693/weird-indexing-using-numpy | I have a variable, x, that is of the shape (2,2,50,100). I also have an array, y, that equals np.array([0,10,20]). A weird thing happens when I index x[0,:,:,y]. x = np.full((2,2,50,100),np.nan) y = np.array([0,10,20]) print(x.shape) (2,2,50,100) print(x[:,:,:,y].shape) (2,2,50,3) print(x[0,:,:,:].shape) (2,50,100) p... | This is how numpy uses advanced indexing to broadcast array shapes. When you pass a 0 for the first index, and y for the last index, numpy will broadcast the 0 to be the same shape as y. The following equivalence holds: x[0,:,:,y] == x[(0, 0, 0),:,:,y]. here is an example import numpy as np x = np.arange(120).reshape(2... | 31 | 24 |
60,516,438 | 2020-3-3 | https://stackoverflow.com/questions/60516438/install-python-modules-in-azure-functions | I am learning how to use Azure functions and using my web scraping script in it. It uses BeautifulSoup (bs4) and pymysql modules. It works fine when I tried it locally in the virtual environment as per this MS guide: https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-azure-function-azure-cl... | You need to check if you have generated the requirements.txt which includes all of the information of the modules. When you deploy the function to azure, it will install the modules by the requirements.txt automatically. You can generate the information of modules in requirements.txt file by the command below in local:... | 8 | 13 |
60,515,794 | 2020-3-3 | https://stackoverflow.com/questions/60515794/mocking-instance-attributes | Please help me understand why the following doesn't work. In particular - instance attributes of a tested class are not visible to Python's unittest.Mock. In the example below bar instance attribute is not accessible. The error returned is: AttributeError: <class 'temp.Foo'> does not have the attribute 'bar' import un... | Patching is used to modify name or attribute lookup. In this case, there is no bar attribute of the class temp.Foo. If the intent is to patch the instance variable, you either need an existing instance to modify def test(self): f = Foo() with patch.object(f, 'bar', 3): self.assertEqual(f.bar, 3) or you may want to pat... | 9 | 15 |
60,513,468 | 2020-3-3 | https://stackoverflow.com/questions/60513468/what-is-the-time-complexity-of-searching-in-dict-if-very-long-strings-are-used-a | I read from python3 document, that python use hash table for dict(). So the search time complexity should be O(1) with O(N) as the worst case. However, recently as I took a course, the teacher says that happens only when you use int as the key. If you use a string of length L as keys the search time complexity is O(L).... | Since a dictionary is a hashtable, and looking up a key in a hashtable requires computing the key's hash, then the time complexity of looking up the key in the dictionary cannot be less than the time complexity of the hash function. In current versions of CPython, a string of length L takes O(L) time to compute the has... | 6 | 10 |
60,512,830 | 2020-3-3 | https://stackoverflow.com/questions/60512830/yield-inside-a-recursive-procedure | Let's say I have a Python list representing ranges for some variables: conditions = [['i', (1, 5)], ['j', (1, 2)]] This represents that variable i ranges from 1 to 5, and inside that loop variable j ranges from 1 to 2. I want a dictionary for each possible combination: {'i': 1, 'j': 1} {'i': 1, 'j': 2} {'i': 2, 'j': 1... | This is a case where it might be easier to take a step back and start fresh. Let's start by getting the keys and the intervals separate, using a well-known trick involving zip: >>> keys, intervals = list(zip(*conditions)) >>> keys ('i', 'j') >>> intervals ((1, 5), (1, 2)) (The correspondence between the two preserves ... | 9 | 6 |
60,510,815 | 2020-3-3 | https://stackoverflow.com/questions/60510815/how-does-np-ndarray-tobytes-work-for-dtype-object | I encountered a strange behavior of np.ndarray.tobytes() that makes me doubt that it is working deterministically, at least for arrays of dtype=object. import numpy as np print(np.array([1,[2]]).dtype) # => object print(np.array([1,[2]]).tobytes()) # => b'0h\xa3\t\x01\x00\x00\x00H{!-\x01\x00\x00\x00' print(np.array([1,... | An array of dtype object stores pointers to the objects it contains. In CPython, this corresponds to the id. Every time you create a new list, it will be allocated at a new memory address. However, small integers are interned, so 1 will reference the same integer object every time. You can see exactly how this works by... | 7 | 3 |
60,509,336 | 2020-3-3 | https://stackoverflow.com/questions/60509336/fatal-error-python-h-no-such-file-or-directory-python-levenshtein-install | Firstly, I'm working on an Amazon EC2 instance, Amazon linux version 2 AMI using Python 3.7. I'm trying to install the python-Levenshtein package using the command: pip3 install python-Levenshtein --user and I'm getting a rather huge error, with the key parts being; gcc -pthread -Wno-unused-result -Wsign-compare -DNDE... | Thanks to Charles, the answer is as follows: sudo yum install python3-devel | 8 | 18 |
60,501,332 | 2020-3-3 | https://stackoverflow.com/questions/60501332/aws-textract-unsupporteddocumentexception-pdf | I'm using boto3 (aws sdk for python) to analyze a document (a pdf) to get the form key:value pairs. import boto3 def process_text_analysis(bucket, document): # Get the document from S3 s3_connection = boto3.resource('s3') s3_object = s3_connection.Object(bucket, document) s3_response = s3_object.get() # Analyze the doc... | AnalyzeDocument is a synchronous API that only supports PNG or JPG images. Since you want to work with PDF files, then you'll need to use Amazon Textract Asynchronous API e.g StartDocumentAnalysis, StartDocumentTextDetection | 6 | 12 |
60,506,508 | 2020-3-3 | https://stackoverflow.com/questions/60506508/get-file-size-creation-date-and-modification-date-in-python | I need to get file info (path, size, dates, etc) and save it in a txt but I don't know where or how to do it. This is what I have: ruta = "FolderPath" os.listdir(path=ruta) miArchivo = open("TxtPath","w") def getListOfFiles(ruta): listOfFile = os.listdir(ruta) allFiles = list() for entry in listOfFile: fullPath = os.pa... | ERROR: type should be string, got "https://docs.python.org/2.7/library/os.path.html#module-os.path os.path.getsize(path) # size in bytes os.path.ctime(path) # time of last metadata change; it's a bit OS specific. Here's a rewrite of your program. I did this: Reformatted with autopep8 for better readability. (That's something you can install to prettify your code your code. But IDEs such as PyCharm Community Edition can help you to do the same, in addition to helping you with code completion and a GUI debugger.) Made your getListofFiles() return a list of tuples. There are three elements in each one; the filename, the size, and the timestamp of the file, which appears to be what's known as an epoch time (time in seconds since 1970; you will have to go through python documentation on dates and times). The tuples is written to your text file in a .csv style format (but note there are modules to do the same in a much better way). Rewritten code: import os def getListOfFiles(ruta): listOfFile = os.listdir(ruta) allFiles = list() for entry in listOfFile: fullPath = os.path.join(ruta, entry) if os.path.isdir(fullPath): allFiles = allFiles + getListOfFiles(fullPath) else: print('getting size of fullPath: ' + fullPath) size = os.path.getsize(fullPath) ctime = os.path.getctime(fullPath) item = (fullPath, size, ctime) allFiles.append(item) return allFiles ruta = \"FolderPath\" miArchivo = open(\"TxtPath\", \"w\") listOfFiles = getListOfFiles(ruta) for elem in listOfFiles: miArchivo.write(\"%s,%s,%s\\n\" % (elem[0], elem[1], elem[2])) miArchivo.close() Now it does this. my-MBP:verynew macbookuser$ python verynew.py; cat TxtPath getting size of fullPath: FolderPath/dir2/file2 getting size of fullPath: FolderPath/dir2/file1 getting size of fullPath: FolderPath/dir1/file1 FolderPath/dir2/file2,3,1583242888.4 FolderPath/dir2/file1,1,1583242490.17 FolderPath/dir1/file1,1,1583242490.17 my-MBP:verynew macbookuser$ " | 8 | 5 |
60,497,198 | 2020-3-2 | https://stackoverflow.com/questions/60497198/python-jupyter-notebook-in-vscode-does-not-use-the-right-environment | The situation I use Anaconda 3 on Windows 10. I have a Visual Studio Code workspace (my_workspace) than contains a Jupyter notebook (my_notebook.ipynb). VSCode has the Python extension installed. The file my_workspace/settings.json contains: { "python.pythonPath": "C:\\Users\\Me\\Anaconda3\\envs\\my_env\\python.exe" } ... | I think there is no parameter right now to control that in the settings.json. I had similar problems with the environments in which the notebook is launched and I was able to fix this modifying the kernelspec section in the IPython notebook. Basically, open the notebook as a JSON file and remove the kernelspec section... | 18 | 19 |
60,497,344 | 2020-3-2 | https://stackoverflow.com/questions/60497344/how-to-use-python-c-on-windows | https://docs.python.org/3/using/cmdline.html This is the option documentation. but it doesn't provide me any useful message I want to execute code in this way python -c "def hello():\n print('hello world')" the error message PS C:\Users\Administrator> python -c "def hello():\n print('hello world')" File "<string>", l... | Try backtick instead of backslash. Error: PS C:\Users\me> python -c "def hello():\n print('hello world')" File "<string>", line 1 def hello():\n print('hello world') ^ SyntaxError: unexpected character after line continuation character PS C:\Users\me> Ok: PS C:\Users\me> python -c "def hello():`n print('hello world')"... | 7 | 4 |
60,458,581 | 2020-2-28 | https://stackoverflow.com/questions/60458581/find-entries-that-do-not-match-between-columns-and-iterate-through-columns | I have two datasets that I need to validate against. All records should match. I am having trouble in determining how to iterate through each different column. import pandas as pd import numpy as np df = pd.DataFrame([['charlie', 'charlie', 'beta', 'cappa'], ['charlie', 'charlie', 'beta', 'delta'], ['charlie', 'charli... | With a bit more comprehensive regex: from itertools import groupby import re for k, cols in groupby(sorted(df.columns), lambda x: x[:-2] if re.match(".+_(1|2)$", x) else None): cols=list(cols) if(len(cols)==2 and k): df[f"{k}_check"]=df[cols[0]].eq(df[cols[1]]) It will pair together only columns which name ends up wit... | 7 | 7 |
60,495,296 | 2020-3-2 | https://stackoverflow.com/questions/60495296/multiple-inheritance-with-kwargs | Problem I came across this code in Object Oriented Programming by Dusty Phillips (simplified for brevity) and I unsure about a specific part of this definition. class A: def __init__(self, a, **kwargs): super().__init__(**kwargs) self.a = a class B: def __init__(self, b, **kwargs): super().__init__(**kwargs) self.b = b... | Since the method resolution order is (__main__.C, __main__.A, __main__.B, object), could class B be defined in the following way instead? No, because then this would fail: class D: def __init__(self, d, **kwargs): self.d = d super().__init__(**kwargs) class E(C, D): def __init__(self, e, **kwargs): self.e = e super()... | 11 | 3 |
60,492,462 | 2020-3-2 | https://stackoverflow.com/questions/60492462/mfcc-python-completely-different-result-from-librosa-vs-python-speech-features | I'm trying to do extract MFCC features from audio (.wav file) and I have tried python_speech_features and librosa but they are giving completely different results: audio, sr = librosa.load(file, sr=None) # librosa hop_length = int(sr/100) n_fft = int(sr/40) features_librosa = librosa.feature.mfcc(audio, sr, n_mfcc=13, ... | There are at least two factors at play here that explain why you get different results: There is no single definition of the mel scale. Librosa implement two ways: Slaney and HTK. Other packages might and will use different definitions, leading to different results. That being said, overall picture should be similar. ... | 13 | 23 |
60,491,544 | 2020-3-2 | https://stackoverflow.com/questions/60491544/pandas-rolling-std-yields-inconsistent-results-and-differs-from-values-std | Using pandas v1.0.1 and numpy 1.18.1, I want to calculate the rolling mean and std with different window sizes on a time series. In the data I am working with, the values can be constant for some subsequent points such that - depending on the window size - the rolling mean might be equal to all the values in the window... | It seems that implementation of std() in pd.rolling prefers high performance over numerical accuracy. However You can apply np version of standard deviation: df.loc[:, 'std'] = df.rolling(window, min_periods=1).apply(np.std) Result: values std 0 1234.0 0.000000 1 4567.0 1666.500000 2 6800.0 2287.053757 3 6810.0 2280.... | 7 | 6 |
60,492,839 | 2020-3-2 | https://stackoverflow.com/questions/60492839/how-to-compare-sentence-similarities-using-embeddings-from-bert | I am using the HuggingFace Transformers package to access pretrained models. As my use case needs functionality for both English and Arabic, I am using the bert-base-multilingual-cased pretrained model. I need to be able to compare the similarity of sentences using something such as cosine similarity. To use this, I fi... | You can use the [CLS] token as a representation for the entire sequence. This token is typically prepended to your sentence during the preprocessing step. This token that is typically used for classification tasks (see figure 2 and paragraph 3.2 in the BERT paper). It is the very first token of the embedding. Alternati... | 30 | 16 |
60,490,169 | 2020-3-2 | https://stackoverflow.com/questions/60490169/maximum-recursion-level-reached-converting-pandas-dataframe-to-json | I have a pandas dataframe which contains thousands of rows, and a few columns. I am getting an error when trying to convert it to a json file. This is the code to convert: sessionAttendance.to_json('SessionAttendance.json') This is the error I'm getting: OverflowError: Maximum recursion level reached _id wondeID sess... | It seems to be related to the way Mongo formats its _id fields which are not correctly processed by the json module. A workaround is to set default_handler=str to force the json formatter to use a string representation for any unwanted type: sessionAttendance.to_json('SessionAttendance.json', default_handler=str) Disc... | 10 | 18 |
60,484,383 | 2020-3-2 | https://stackoverflow.com/questions/60484383/typeerror-scalar-value-for-argument-color-is-not-numeric-when-using-opencv | I'm new to OpenCV. Some weird things happened when I drew a circle. It didn't work when I tried to pass c2 to the circle function, but it worked well when I pass c1 to the color argument. But c1 == c2. Here is my code: import cv2 import numpy as np canvas = np.zeros((300, 300, 3), dtype='uint8') for _ in range(1): r = ... | Convert data type int64 to int. ndarray.tolist() : data items are converted to the nearest compatible builtin Python type, via the item function. Ex. import cv2 import numpy as np canvas = np.zeros((300, 300, 3), dtype='uint8') for _ in range(1): r = np.random.randint(0, 200) center = np.random.randint(0, 300, size=(... | 17 | 21 |
60,480,777 | 2020-3-1 | https://stackoverflow.com/questions/60480777/plotting-already-calculated-confusion-matrix-using-python | How can I plot in Python a Confusion Matrix similar do the one shown here for already given values of the Confusion Matrix? In the code they use the method sklearn.metrics.plot_confusion_matrix which computes the Confusion Matrix based on the ground truth and the predictions. But in my case, I already have calculated m... | If you check the source for sklearn.metrics.plot_confusion_matrix, you can see how the data is processed to create the plot. Then you can reuse the constructor ConfusionMatrixDisplay and plot your own confusion matrix. import matplotlib.pyplot as plt from sklearn.metrics import ConfusionMatrixDisplay cm = [0.612, 0.388... | 7 | 6 |
60,480,686 | 2020-3-1 | https://stackoverflow.com/questions/60480686/pytorch-model-summary-forward-func-has-more-than-one-argument | I am using torch summary from torchsummary import summary I want to pass more than one argument when printing the model summary, but the examples mentioned here: Model summary in pytorch taken only one argument. for e.g.: model = Network().to(device) summary(model,(1,28,28)) The reason is that the forward function t... | You can use the example given here: pytorch summary multiple inputs summary(model, [(1, 16, 16), (1, 28, 28)]) | 11 | 22 |
60,478,373 | 2020-3-1 | https://stackoverflow.com/questions/60478373/rearranging-columns-with-pandas-is-there-an-equivalent-to-dplyrs-select-e | I'm trying to rearrange columns in a DataFrame, by putting a few columns first, and then all the others after. With R's dplyr, this would look like: library(dplyr) df = tibble(col1 = c("a", "b", "c"), id = c(1, 2, 3), col2 = c(2, 4, 6), date = c("1 Feb", "2 Feb", "3 Feb")) df2 = select(df, id, date, everything()) Easy... | You can use df.drop: >>> df = pd.DataFrame({ "col1": ["a", "b", "c"], "id": [1, 2, 3], "col2": [2, 4, 6], "date": ["1 Feb", "2 Feb", "3 Feb"] }) >>> df col1 id col2 date 0 a 1 2 1 Feb 1 b 2 4 2 Feb 2 c 3 6 3 Feb >>> cols_1st = ["id", "date"] >>> df[cols_1st + list(df.drop(cols_1st, 1))] id date col1 col2 0 1 1 Feb a 2 ... | 9 | 5 |
60,441,473 | 2020-2-27 | https://stackoverflow.com/questions/60441473/creating-a-workitem-in-azure-devops-via-python | Trying to create a new workitem in VSTS via Python API access and I cant find anywhere in the documents on how to create a new workitem in Python. I'm sure it's fairly simple but I can't seem to find it in the documentation. https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/create?view=azure-devo... | Please kindly refer this official Azure DevOps Python API doc. It contains Python APIs for interacting with and managing Azure DevOps. These APIs power the Azure DevOps Extension for Azure CLI. To learn more about the Azure DevOps Extension for Azure CLI, visit the Microsoft/azure-devops-cli-extension repo. Here is ... | 6 | 6 |
60,468,385 | 2020-2-29 | https://stackoverflow.com/questions/60468385/is-there-cudnnlstm-or-cudnngru-alternative-in-tensorflow-2-0 | The CuDNNGRU in TensorFlow 1.0 is really fast. But when I shifted to TensorFlow 2.0 i am unable to find CuDNNGRU. Simple GRU is really slow in TensorFlow 2.0. Is there any way to use CuDNNGRU in TensorFlow 2.0? | The importable implementations have been deprecated - instead, LSTM and GRU will default to CuDNNLSTM and CuDNNGRU if all conditions are met: activation = 'tanh' recurrent_activation = 'sigmoid' recurrent_dropout = 0 unroll = False use_bias = True Inputs, if masked, are strictly right-padded reset_after = True (GRU on... | 12 | 24 |
60,466,436 | 2020-2-29 | https://stackoverflow.com/questions/60466436/why-is-a-insert0-0-much-slower-than-a00-0 | Using a list's insert function is much slower than achieving the same effect using slice assignment: > python -m timeit -n 100000 -s "a=[]" "a.insert(0,0)" 100000 loops, best of 5: 19.2 usec per loop > python -m timeit -n 100000 -s "a=[]" "a[0:0]=[0]" 100000 loops, best of 5: 6.78 usec per loop (Note that a=[] is only... | I think it's probably just that they forgot to use memmove in list.insert. If you take a look at the code list.insert uses to shift elements, you can see it's just a manual loop: for (i = n; --i >= where; ) items[i+1] = items[i]; while list.__setitem__ on the slice assignment path uses memmove: memmove(&item[ihigh+d],... | 75 | 71 |
60,459,218 | 2020-2-28 | https://stackoverflow.com/questions/60459218/pandas-passing-list-likes-to-loc-or-with-any-missing-labels-is-no-longer-su | For some reason train_test_split, despite lengths being identical and indexes look the same, triggers this error. from sklearn.model_selection import KFold data = {'col1':[30.5,45,1,99,6,5,4,2,5,7,7,3], 'col2':[99.5, 98, 95, 90,1,5,6,7,4,4,3,3],'col3':[23, 23.6, 3, 90,1,9,60,9,7,2,2,1]} df = pd.DataFrame(data) train, t... | I've tried to create a scenario for your situation. I've created following dataframe: col1 col2 col3 0 1 2 1 1 3 4 0 2 5 6 1 3 7 8 0 4 9 10 1 5 11 12 0 6 13 14 1 7 15 16 0 8 17 18 1 9 19 20 0 10 21 22 1 11 23 24 0 12 25 26 1 13 27 28 0 14 29 30 1 I set col1 and col2 for X and col3 for y. After this I've converted X t... | 10 | 12 |
60,459,641 | 2020-2-28 | https://stackoverflow.com/questions/60459641/how-do-you-get-mypy-to-recognize-a-newer-version-of-python | I just updated my project to Python 3.7 and I'm seeing this error when I run mypy on the project: error: "Type[datetime]" has no attribute "fromisoformat" datetime does have a function fromisoformat in Python 3.7, but not in previous versions of Python. Why is mypy reporting this error, and how can I get it to analyze ... | You are running mypy under an older version of Python. mypy defaults to the version of Python that is used to run it. You have two options: You can change the Python language version with the --python-version command-line option: This flag will make mypy type check your code as if it were run under Python version X.Y... | 13 | 6 |
60,451,472 | 2020-2-28 | https://stackoverflow.com/questions/60451472/how-to-make-a-dict-from-an-enum | How to make a dict from an enum? from enum import Enum class Shake(Enum): VANILLA = "vanilla" CHOCOLATE = "choc" COOKIES = "cookie" MINT = "mint" dct = {} for i in Shake: dct[i]=i.value print(dct) Output: {<Shake.VANILLA: 'vanilla'>: 'vanilla', <Shake.CHOCOLATE: 'choc'>: 'choc', <Shake.COOKIES: 'cookie'>: 'cookie', <S... | you can just use a dictionary comprehension from enum import Enum class Shake(Enum): VANILLA = "vanilla" CHOCOLATE = "choc" COOKIES = "cookie" MINT = "mint" dct = {i.name: i.value for i in Shake} print(dct) OUTPUT {'VANILLA': 'vanilla', 'CHOCOLATE': 'choc', 'COOKIES': 'cookie', 'MINT': 'mint'} | 28 | 41 |
60,432,969 | 2020-2-27 | https://stackoverflow.com/questions/60432969/create-python-c-extension-using-macos-10-15-catalina-that-is-backwards-compati | How can I create a Python C extension wheel for MacOS that is backwards compatible (MacOS 10.9+) using MacOS 10.15? This is what I have so far: export MACOSX_DEPLOYMENT_TARGET=10.9 python -m pip wheel . -w wheels --no-deps python -m pip install delocate for whl in wheels/*.whl; do delocate-wheel -w wheels_fixed -v "$w... | I found the solution to my problem and I will post the answer here in case someone else has the same problem. In order to fix the problem I had to also set export MACOSX_DEPLOYMENT_TARGET=10.9 before I install python using pyenv. Now pip wheel creates my wheel with the tag macosx_10_9_x86_64. Thank you. PS: When insta... | 11 | 6 |
60,423,697 | 2020-2-26 | https://stackoverflow.com/questions/60423697/why-is-performance-so-much-better-with-zarr-than-parquet-when-using-dask | When I run essentially the same calculations with dask against zarr data and parquet data, the zarr-based calculations are significantly faster. Why? Is it maybe because I did something wrong when I created the parquet files? I've replicated the issue with fake data (see below) in a jupyter notebook to illustrate the k... | Glad to see fastparquet, zarr and intake used in the same question! TL;DR here is: use the right data model appropriate for your task. Also, it's worth pointing out that the zarr dataset is 1.5GB, blosc/lz4 compressed in 512 chunks, and the parquet dataset 1.8GB, snappy compressed in 5 chunks, where the compression are... | 12 | 17 |
60,435,907 | 2020-2-27 | https://stackoverflow.com/questions/60435907/pyspark-merge-multiple-columns-into-a-json-column | I asked the question a while back for python, but now I need to do the same thing in PySpark. I have a dataframe (df) like so: |cust_id|address |store_id|email |sales_channel|category| ------------------------------------------------------------------- |1234567|123 Main St|10SjtT |idk@gmail.com|ecom |direct | |4567345|... | Use to_json function to create json object! Example: from pyspark.sql.functions import * #sample data df=spark.createDataFrame([('1234567','123 Main St','10SjtT','idk@gmail.com','ecom','direct')],['cust_id','address','store_id','email','sales_channel','category']) df.select("cust_id","address",to_json(struct("store_id"... | 12 | 32 |
60,435,406 | 2020-2-27 | https://stackoverflow.com/questions/60435406/which-exception-should-be-raised-when-a-required-environment-variable-is-missing | The title pretty much sums it up already. I have a piece of code that calls os.getenv to get both a URL as well as a token in order to connect to a service. The code lives in a module and will only be imported from there, i.e. it's not a script. It's not a huge issue at all, since I really only need to crash and displ... | Well most built in concrete exception classes are for specific use cases, and this one does not really fit in any but RuntimeError. But I would advise you to use a custom Exception subclass. | 34 | 7 |
60,434,664 | 2020-2-27 | https://stackoverflow.com/questions/60434664/automatically-determine-header-row-when-reading-csv-in-pandas | I am trying to collect data from different .csv files, that share the same column names. However, some csv files have their headers located in different rows. Is there a way to determine the header row dynamically based on the first row that contains "most" values (the actual header names)? I tried the following: def... | IMHO the simplest way if to forget pandas for a while: you open the file as a text file for reading you start parsing it line by line, guessing whether the line is metadata header the true header line data lines A simple way is to concatenate all the lines starting from the true header line in a single string (let ... | 9 | 3 |
60,434,320 | 2020-2-27 | https://stackoverflow.com/questions/60434320/shapley-for-logistic-regression | Does shapley support logistic regression models? Running the following code i get: logmodel = LogisticRegression() logmodel.fit(X_train,y_train) predictions = logmodel.predict(X_test) explainer = shap.TreeExplainer(logmodel ) Exception: Model type not yet supported by TreeExplainer: <class 'sklearn.linear_model.logisti... | Shap is model agnostic by definition. It looks like you have just chosen an explainer that doesn't suit your model type. I suggest looking at KernelExplainer which as described by the creators here is An implementation of Kernel SHAP, a model agnostic method to estimate SHAP values for any model. Because it makes not... | 7 | 6 |
60,406,272 | 2020-2-26 | https://stackoverflow.com/questions/60406272/how-to-have-persistent-storage-for-a-pypi-package | I have a pypi package called collectiondbf which connects to an API with a user entered API key. It is used in a directory to download files like so: python -m collectiondbf [myargumentshere..] I know this should be basic knowledge, but I'm really stuck on the question: How can I save the keys users give me in a meani... | Most common operating systems have the concept of an application directory that belongs to every user who has an account on the system. This directory allows said user to create and read, for example, config files and settings. So, all you need to do is make a list of all distros that you want to support, find out wher... | 7 | 5 |
60,408,901 | 2020-2-26 | https://stackoverflow.com/questions/60408901/sklearn-utils-compute-class-weight-function-for-large-dataset | I am training a tensorflow keras sequential model on around 20+ GB text based categorical data in a postgres db and i need to give class weights to the model. Here is what i am doing. class_weights = sklearn.utils.class_weight.compute_class_weight('balanced', classes, y) model.fit(x, y, epochs=100, batch_size=32, class... | You can use the generators and also you can compute the class weights. Let's say you have your generator like this train_generator = train_datagen.flow_from_directory( 'train_directory', target_size=(224, 224), batch_size=32, class_mode = "categorical" ) and the class weights for the training set can be computed like... | 10 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.