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 |
|---|---|---|---|---|---|---|
68,903,084 | 2021-8-24 | https://stackoverflow.com/questions/68903084/pydantic-validation-does-not-happen | I am quite new to using Pydantic. The Issue I am facing right now is that the Model Below is not raising the Expected Exception when the value is out of range. For example, if you pass -1 into this model it should ideally raise an HTTPException. but nothing happens I am not sure where I might be going wrong. Any Advice... | class GetInput(BaseModel): rank: Optional[int]=None interval: Optional[int]=None @validator("*") def check_range(cls, v): if v: if not 0 < v < 1000001: raise HTTPException(status_code=400, detail="Value Must be within range (0,1000000)") return v the validator was not working due to not Inheriting the BaseModel Class... | 6 | 5 |
68,902,555 | 2021-8-24 | https://stackoverflow.com/questions/68902555/visual-studio-code-pylance-search-folders | I have a project with some python in it - the python is part of a larger thing - there are several programs in several directories inside a root git - and there is some common code in yet another directory. Running works fine - but pylance in visual studio code sees all of the dependencies as errors, even though most a... | You may search for settings about additional import search resolution paths: "python.analysis.extraPaths": [ "path1", "path2", ], Please have a try. More information view Pylance Settings and Customization. | 5 | 8 |
68,902,836 | 2021-8-24 | https://stackoverflow.com/questions/68902836/what-is-the-difference-between-client-side-based-sessions-and-server-side-sessio | I'm learning about sessions in Flask and in the documentation it says: "Besides the default client-side based sessions, if you want to handle sessions on the server-side instead, there are several Flask extensions that support this." https://flask.palletsprojects.com/en/2.0.x/quickstart/#sessions What is the different ... | In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically. What this means is that the user could look at the contents of you... | 7 | 15 |
68,901,119 | 2021-8-24 | https://stackoverflow.com/questions/68901119/module-aioredis-has-no-attribute-create-redis | Using python 3.6.12 and aioredis 2.0.0, asyncio 3.4.3 Tried to use the snippet from the aioredis for testing pub/sub: import asyncio import aioredis async def reader(ch): while (await ch.wait_message()): msg = await ch.get_json() print("Got Message:", msg) async def main(): pub = await aioredis.create_redis( 'redis://:... | aioredis as of version 2.0 now follows the public API implementation of the library redis-py. From the aioredis doc page aioredis v2.0 is now a completely compliant asyncio-native implementation of redis-py. The entire core and public API has been re-written to follow redis-py‘s implementation as closely as possible. ... | 8 | 13 |
68,899,057 | 2021-8-23 | https://stackoverflow.com/questions/68899057/can-one-add-a-custom-error-in-enum-to-show-valid-values | Let's say I have from enum import Enum class SomeType(Enum): TYPEA = 'type_a' TYPEB = 'type_b' TYPEC = 'type_c' If I now do SomeType('type_a') I will get <SomeType.TYPEA: 'type_a'> as expected. When I do SomeType('type_o') I will receive ValueError: 'type_o' is not a valid SomeType which is also expected. My ques... | Use the _missing_ method: from enum import Enum class SomeType(Enum): TYPEA = 'type_a' TYPEB = 'type_b' TYPEC = 'type_c' @classmethod def _missing_(cls, value): raise ValueError( '%r is not a valid %s. Valid types: %s' % ( value, cls.__name__, ', '.join([repr(m.value) for m in cls]), )) and in use: >>> SomeType('type_... | 5 | 10 |
68,891,213 | 2021-8-23 | https://stackoverflow.com/questions/68891213/how-to-decode-jwt-token-with-jwk-in-python | I am developing an application where all the API's are protected by OAuth. I have received the access token from the client, but could not decode and validate the token. I have JWK in the below format { "keys": [ { "kty": "RSA", "x5t#S256": "Some value", "e": "Some Value", "x5t": "Some Value", "kid": "SIGNING_KEY", "x5... | Fast check of your jwt token https://jwt.io/ otherwise you can try this, but you should know the algorithm used to generate the token (e.g. : HS256) and the key used for signing the token) (e.g. :super_secretkey) import jwt # pip install pyjwt[crypto] to install the package jwt.decode(token, key='super_secretkey', alg... | 10 | 24 |
68,877,761 | 2021-8-22 | https://stackoverflow.com/questions/68877761/recaptcha-wasnt-solving-by-anticaptcha-plugin-in-selenium-python | I've recently started using selenium for a project I've been working on for a while that involves automation. One of the roadblocks in the plan was the ReCaptcha system, so I decided to use anti-captcha as the service that would solve the captchas when my bot encountered it. I properly installed the plugin and found so... | I've finally managed to resolve this myself. In case anyone else is struggling with a similar issue, here was my solution: Open the console and execute the following cmd: ___grecaptcha_cfg.clients Find the path which has the callback function, in my case it's ___grecaptcha_cfg.clients[0].R.R Use the following code: dr... | 7 | 7 |
68,884,610 | 2021-8-22 | https://stackoverflow.com/questions/68884610/vs-code-jupyter-notebook-doesnt-automatically-select-the-default-kernel | I have created a simple jupyter notebook in VS Code and selected it to use my default python3 kernel (/usr/local/bin/python3). Everything works great. Then, I close VS Code and re-open the notebook, it asks me to select the kernel every time. Is there a way to default the kernel of this notebook to my python3 interpret... | It's not available for now, but they think it is a reasonable request, and considering it. You can refer to this page. | 8 | 4 |
68,843,444 | 2021-8-19 | https://stackoverflow.com/questions/68843444/handle-permission-cache-in-django-user-model | I stumbled upon a weird behaviour: I add a permission to a user object but the permission check fails. permission = Permission.objects.get_by_natural_key(app_label='myapp', codename='my_codename', model='mymodel') user.user_permissions.add(permission) user.has_permission('myapp.my_codename') # this is False! I found s... | You can force the recalculation by deleting the user object's _perm_cache and _user_perm_cache. permission = Permission.objects.get_by_natural_key(app_label='myapp', codename='my_codename', model='mymodel') user.user_permissions.add(permission) user.has_permission('myapp.my_codename') # returns False del user._perm_cac... | 8 | 7 |
68,883,042 | 2021-8-22 | https://stackoverflow.com/questions/68883042/how-can-i-document-methods-inherited-from-a-metaclass | Consider the following metaclass/class definitions: class Meta(type): """A python metaclass.""" def greet_user(cls): """Print a friendly greeting identifying the class's name.""" print(f"Hello, I'm the class '{cls.__name__}'!") class UsesMeta(metaclass=Meta): """A class that uses `Meta` as its metaclass.""" As we know... | The help() function relies on dir(), which currently does not always give consistent results. This is why your method gets lost in the generated interactive documentation. There's a open python issue on this topic which explains the problem in more detail: see bugs 40098 (esp. the first bullet-point). In the meantime, ... | 7 | 6 |
68,851,505 | 2021-8-19 | https://stackoverflow.com/questions/68851505/installing-sqlalchemy-with-poetry-causes-an-attributeerrorr | When installing with pip, pip install sqlalchemy all is ok. When installing with poetry I am getting the error ➜ backend poetry add sqlalchemy Using version ^1.4.23 for SQLAlchemy Updating dependencies Resolving dependencies... (0.1s) AttributeError 'EmptyConstraint' object has no attribute 'allows' at ~/.poetry/lib/po... | Try poetry self update, then poetry update. | 15 | 13 |
68,878,031 | 2021-8-22 | https://stackoverflow.com/questions/68878031/is-multiprocessing-pool-not-allowed-in-airflow-task-assertionerror-daemonic | Our airflow project has a task that queries from BigQuery and uses Pool to dump in parallel to local JSON files: def dump_in_parallel(table_name): base_query = f"select * from models.{table_name}" all_conf_ids = range(1,10) n_jobs = 4 with Pool(n_jobs) as p: p.map(partial(dump_conf_id, base_query = base_query), all_con... | Airflow 2 uses different processing model under the hood to speed up processing, yet to maintain process-based isolation between running tasks. That's why it uses forking and multiprocessing under the hook to run Tasks, but this also means that if you are using multiprocessing, you will hit the limits of Python multipr... | 10 | 9 |
68,877,915 | 2021-8-22 | https://stackoverflow.com/questions/68877915/airflow-alembic-util-exc-commanderror-cant-locate-revision-identified-by-a1 | webserver_1 | The above exception was the direct cause of the following exception: webserver_1 | webserver_1 | Traceback (most recent call last): webserver_1 | File "/usr/local/bin/airflow", line 8, in <module> webserver_1 | sys.exit(main()) webserver_1 | File "/usr/local/lib/python3.7/site-packages/airflow/__main__.py... | You should wipe your database and recreate it from scratch (airflow db reset). Apparently the database you have have been corrupted - this could have happened if you used some development version of Arirflow or run some older version airflow 1.10 on Airflow 2 or the other way round. I presume (since you are talking abo... | 7 | 16 |
68,876,560 | 2021-8-21 | https://stackoverflow.com/questions/68876560/issue-installing-python-3-8-using-pyenv | I tried installing python using the command pyenv install 3.8.11 Please let me know if you need more info. Thank you for looking. output: BUILD FAILED (Ubuntu 20.04 using python-build 20180424) Inspect or clean up the working tree at /tmp/python-build.20210821132713.23441 Results logged to /tmp/python-build.202108211... | pyenv requires some packages to build Python from source. For Ubuntu, from pyenv wiki: suggested build environment sudo apt-get install make build-essential libssl-dev zlib1g-dev \ libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \ libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-d... | 5 | 15 |
68,869,020 | 2021-8-20 | https://stackoverflow.com/questions/68869020/valueerror-y-must-be-a-structured-array-with-the-first-field-being-a-binary-cla | It appears that I have my code in the same form as the scikit-survival documentation. data_y = df[['sensored', 'sensored_2']].to_numpy() data_x = df.drop(['sensored', 'sensored_2'], axis = 1) data_y array([[True, 481], [True, 424], [True, 519], ..., [True, 13], [True, 96], [True, 6]], dtype=object) From the scikit-sur... | The fit method expects the y data to be a structured array. In our case, this is an array of Tuples, where the first element is the status and second one is the survival in days. To put our data in the format the fit method expects, we need first transform the elements of the array from lists (e.g. [True, 424]) to tupl... | 7 | 4 |
68,873,111 | 2021-8-21 | https://stackoverflow.com/questions/68873111/how-do-i-pull-the-last-modified-time-of-each-file-within-a-directory-in-python | I have been tasked with creating a small application that allows the user to: browse and choose a specific folder that will contain the files to be checked daily, browse and choose a specific folder that will receive the copied files, and manually initiate the 'file check' process that is performed by the script. In or... | The os.listdir() method lists the files of the given path excluding the path, hence you will need to concatenate the path yourself: for file in os.listdir('../File Transfer/Old Files/'): if file.endswith('.txt'): time_mod = os.path.getmtime('../File Transfer/Old Files/' + file) print(time_mod) The glob.glob() method w... | 5 | 4 |
68,872,321 | 2021-8-21 | https://stackoverflow.com/questions/68872321/how-to-run-shell-script-on-specific-git-commit | I want to run run.sh to check the results of my codes, which takes about 30 hours. But I can't wait to add other features to my codes. However, I found there are some potential dangers: Edit shell script while it's running Edit shell script and python script while it's running In my case, I want run.sh running with a... | This is one use case for which git worktree is well suited. You basically create a new branch at the desired commit and make a copy of the working directory at that branch. For example, if you're at the top-level of your working tree and want to run the script on the current HEAD, just do: $ git worktree add ../bar Pre... | 5 | 7 |
68,869,535 | 2021-8-21 | https://stackoverflow.com/questions/68869535/numpy-accumulate-greater-operation | I'm trying to write a function that would detect all rising edges - indexes in a vector where value exceeds certain threshold. Something similar is described here: Python rising/falling edge oscilloscope-like trigger, but I want to add hysteresis, so that trigger won't fire unless the value goes below another limit. I ... | I am not sure what the issue with np.greater.accumulate is (it does not seem to behave as advertised indeed), but the following should work: import numpy as np import numpy as np arr = np.linspace(-10, 10, 60) sample_values = np.sin(arr) + 0.6 * np.sin(arr*3) above_trigger = sample_values > 0.6 below_deadband = sample_... | 5 | 2 |
68,869,633 | 2021-8-21 | https://stackoverflow.com/questions/68869633/error-message-received-when-trying-to-import-turtle-python-3-9-m1-mac | When I try to import the python 3 graphical library, turtle, on my m1 MacBook, I get an error message: david@Davids-MacBook-Air Python Coding Files % /opt/homebrew/bin/python3 "/Users/david/Desktop/Python Coding Files/hello.py" Traceback (most recent call last): File "/Users/david/Desktop/Python Coding Files/hello.py"... | Python 3's turtle module has always used tkinter. Your other Mac must have tkinter installed. It used to be shipped with Python, but now you need to install it. Assuming you use HomeBrew: brew install python-tk | 5 | 6 |
68,864,939 | 2021-8-20 | https://stackoverflow.com/questions/68864939/s3fs-suddenly-stopped-working-in-google-colab-with-error-attributeerror-module | Yesterday the following cell sequence in Google Colab would work. (I am using colab-env to import environment variables from Google Drive.) This morning, when I run the same code, I get the following error. It appears to be a new issue with s3fs and aiobotocore. I have some experience with Google Colab and library ve... | Indeed, the breakage was with the release of aiobotocore 1.4.0 (today, 20 Aug 2021), which is fixed in release 2021.08.0 of s3fs, also today. | 14 | 16 |
68,860,457 | 2021-8-20 | https://stackoverflow.com/questions/68860457/fitfailedwarning-estimator-fit-failed-the-score-on-this-train-test-partition-f | I'm trying to optimize the parameters learning rate and max_depth of a XGB regression model: from sklearn.model_selection import GridSearchCV from sklearn.model_selection import cross_val_score from xgboost import XGBRegressor param_grid = [ # trying learning rates from 0.01 to 0.2 {'eta ':[0.01, 0.05, 0.1, 0.2]}, # an... | I was able to reproduce the problem and the code fails to fit because there is an extra space in your eta parameter! Instead of this: {'eta ':[0.01, 0.05, 0.1, 0.2]},... Change it to this: {'eta':[0.01, 0.05, 0.1, 0.2]},... The error message was unfortunately not very helpful. | 5 | 4 |
68,864,520 | 2021-8-20 | https://stackoverflow.com/questions/68864520/pandas-cell-frequency-count-by-index | My dataframe is a long list of 4 letters, 'A', 'T', 'G','C', I need to count the frequency of each letter by index df = pd.DataFrame({'cases': ['ACCTTGTAGTGTATTTTATGACCAAATGACTTTTTCCCCCCAGTGGCTAATTTGTCTCAGGCCTGCGTCTTAAAGAGACACGGTAATGAGTAGGAAGTCCAGCGTGGTCTGGA','ACCTTGTACTGTATCTTATGACCAGATGACTTTTTCCACCCAGTGGCTAATTTGTCTCA... | Use collections.Counter: from collections import Counter df['cases'].apply(lambda x: pd.Series(Counter(x))) output: A C T G 0 27 24 34 28 1 29 26 33 25 2 30 25 33 25 3 29 25 33 26 The other way around it not as sexy: pd.DataFrame([Counter(i) for i in list(zip(*df['cases'].apply(list).values))] ).fillna(0).astype(int... | 9 | 2 |
68,863,050 | 2021-8-20 | https://stackoverflow.com/questions/68863050/pyinstaller-loading-splash-screen | Pyinstaller recently added a splash screen option (yay!) but the splash stays open the entire time the exe is running. I need it because my file opens very slowly and I want to warn the user not to close the window. Is there a way I can get the splash screen to close when the gui opens? | from pyinstaller docs: import pyi_splash # Update the text on the splash screen pyi_splash.update_text("PyInstaller is a great software!") pyi_splash.update_text("Second time's a charm!") # Close the splash screen. It does not matter when the call # to this function is made, the splash screen remains open until # this ... | 12 | 5 |
68,860,386 | 2021-8-20 | https://stackoverflow.com/questions/68860386/how-can-we-get-token-holders-from-token | I have created my own ERC-20 token (AJR) and deploy on Ethereum private node, Now I want to list all the transaction by Token name. Also, I need to list down all the token holders by using contract address or token name. I try to fetch using web3 but I get only symbol, name, total supply, etc. but not token holders or ... | Token holders are not directly available through the RPC protocol and RPC wrappers such as Web3. Information about token holders is stored on the blockchain in the token contract (or some of its dependencies), usually in the form of a mapping. Which means that you can't just loop through all of the holders, but you nee... | 8 | 19 |
68,861,402 | 2021-8-20 | https://stackoverflow.com/questions/68861402/how-to-change-size-of-confusion-matrix-in-fastai | I am drawing a Confusion Matrix in fastai with following code: interp = ClassificationInterpretation.from_learner(learn) interp.plot_confusion_matrix() But I end up with a super small matrix because I have around 20 categories: I have found the related question for sklearns but don't know how to apply it to fastai (b... | If you check the code of the function ClassificationInterpretation.plot_confusion_matrix (in file fastai / interpret.py), this is what you see: def plot_confusion_matrix(self, normalize=False, title='Confusion matrix', cmap="Blues", norm_dec=2, plot_txt=True, **kwargs): "Plot the confusion matrix, with `title` and usi... | 5 | 6 |
68,850,172 | 2021-8-19 | https://stackoverflow.com/questions/68850172/token-indices-sequence-length-issue | I am running a sentence transformer model and trying to truncate my tokens, but it doesn't appear to be working. My code is from transformers import AutoModel, AutoTokenizer model_name = "sentence-transformers/paraphrase-MiniLM-L6-v2" model = AutoModel.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrain... | You need to add the max_length parameter while creating the tokenizer like below: text_tokens = tokenizer(text, padding=True, max_length=512, truncation=True, return_tensors="pt") Reason: truncation=True without max_length parameter takes sequence length equal to maximum acceptable input length by the model. It is 1e30... | 5 | 6 |
68,854,033 | 2021-8-19 | https://stackoverflow.com/questions/68854033/repeat-list-elements-based-on-values-in-another-list | I have two lists: nums = [2, 3, 5] mylist = ["aaa", "bbb", "ccc"] What I am trying to achieve is repeat each element in mylist as many times as the corresponding values in nums. Expected output is: ["aaa", "aaa", "bbb", "bbb", "bbb", "ccc", "ccc", "ccc", "ccc", "ccc"] | Let us do repeat import pandas as pd pd.Series(mylist).repeat(nums).tolist() Out[554]: ['aaa', 'aaa', 'bbb', 'bbb', 'bbb', 'ccc', 'ccc', 'ccc', 'ccc', 'ccc'] Or try numpy import numpy as np np.repeat(mylist,nums) Out[556]: array(['aaa', 'aaa', 'bbb', 'bbb', 'bbb', 'ccc', 'ccc', 'ccc', 'ccc', 'ccc'], dtype='<U3') | 5 | 4 |
68,847,659 | 2021-8-19 | https://stackoverflow.com/questions/68847659/pyspark-sorting-array-of-struct | This is a dummy sample of my dataframe data = [ [3273, "city y", [["ids", 27], ["smf", 13], ["tlk", 35], ["thr", 24]]], [3213, "city x", [["smf", 23], ["tlk", 15], ["ids", 17], ["thr", 34]]], ] df = spark.createDataFrame( data, "city_id:long, city_name:string, cel:array<struct<carr:string, subs:int>>" ) df.show(2, Fals... | You can do it using some SQL lambda functions : df = df.withColumn( "cel", F.expr( "reverse(array_sort(transform(cel,x->struct(x['subs'] as subs,x['carr'] as carr))))" ), ) df.show() +-------+---------+--------------------------------------------+ |city_id|city_name|cel | +-------+---------+----------------------------... | 7 | 7 |
68,832,550 | 2021-8-18 | https://stackoverflow.com/questions/68832550/python-apscheduler-fails-only-timezones-from-the-pytz-library-are-supported-e | I am trying to run a python async app with an asyncioscheduler scheduled job but the APScheduler fails during build because of this error: 'Only timezones from the pytz library are supported' error I do include pytz in my app and i am passing the timezone. What is causing the error? I am calling the asyncioscheduler ... | The tzlocal library switched from pytz to zoneinfo timezones in 3.0 and APScheduler 3.x is not compatible with those. Due to this, APScheduler 3.7.0 has tzlocal pinned to v2.x. If you're getting tzlocal 3.0 installed through APScheduler, you're using an old version. Please upgrade. | 6 | 7 |
68,842,475 | 2021-8-19 | https://stackoverflow.com/questions/68842475/single-column-fetch-returning-in-list-in-python-postgresql | Database: id trade token 1 abc 5523 2 fdfd 5145 3 sdfd 2899 Code: def db_fetchquery(sql): conn = psycopg2.connect(database="trade", user='postgres', password='jps', host='127.0.0.1', port= '5432') cursor = conn.cursor() conn.autocommit = True cursor.execute(sql) row = cursor.rowcount if row >= 1: data =... | Not sure if you are able to do that without further processing but I would do it like this: data = [x[0] for x in data] which convert the list of tuples to a 1D list | 6 | 8 |
68,837,536 | 2021-8-18 | https://stackoverflow.com/questions/68837536/how-to-use-a-different-colormap-for-different-rows-of-a-heatmap | I am trying to change 1 row in my heatmap to a different color here is the dataset: m = np.array([[ 0.7, 1.4, 0.2, 1.5, 1.7, 1.2, 1.5, 2.5], [ 1.1, 2.5, 0.4, 1.7, 2. , 2.4, 2. , 3.2], [ 0.9, 4.4, 0.7, 2.3, 1.6, 2.3, 2.6, 3.3], [ 0.8, 2.1, 0.2, 1.8, 2.3, 1.9, 2. , 2.9], [ 0.9, 1.3, 0.8, 2.2, 1.8, 2.2, 1.7, 2.8], [ 0.7, ... | You can split in two, mask the unwanted parts, and plot separately: # Reds data1 = data.copy() data1.loc[7] = float('nan') ax = sns.heatmap(data1, annot=True, cmap="Reds") # Greens data2 = data.copy() data2.loc[:6] = float('nan') sns.heatmap(data2, annot=True, cmap="Greens") output: NB. you need to adapt the loc[…] p... | 5 | 5 |
68,835,895 | 2021-8-18 | https://stackoverflow.com/questions/68835895/how-to-supress-all-warnings-when-running-pytest | Some warning can cause problems when running tests with pytest. It might be desirable to ignore all warnings. I could not find a clear way to suppress all warnings. | This is the solution I found: pytest -W ignore test_script.py | 6 | 3 |
68,820,085 | 2021-8-17 | https://stackoverflow.com/questions/68820085/how-to-convert-geojson-to-shapely-polygon | i have a geoJSON geo = {'type': 'Polygon', 'coordinates': [[[23.08437310100004, 53.15448536100007], [23.08459767900007, 53.15448536100007], [23.08594514600003, 53.153587050000056], (...) [23.08437310100004, 53.15448536100007]]]} and i want to use these coordinates as an input to shapely.geometry.Polygon. The problem i... | A generic solution is to use the shape function: Returns a new, independent geometry with coordinates copied from the context. This works for all geometries not just polygons. from shapely.geometry import shape from shapely.geometry.polygon import Polygon geo: dict = {'type': 'Polygon', 'coordinates': [[[23.084373101... | 16 | 39 |
68,807,958 | 2021-8-16 | https://stackoverflow.com/questions/68807958/pytorch-nn-crossentropyloss-indexerror-target-2-is-out-of-bounds | I'm creating a simple 2 class sentiment classifier using bert, but i'm getting an error related to output and label size. I cannot figure out what I'm doing wrong. Below are the required code snippets. My custom dataset class: class AmazonReviewsDataset(torch.utils.data.Dataset): def __init__(self, df): self.df = df se... | You have two classes, which means the maximum target label is 1 not 2 because the classes are indexed from 0 (see official documentation). You essentially have to subtract 1 to your labels tensor, such that class n°1 is assigned the value 0, and class n°2 value 1. In turn the labels of the batch you printed would look ... | 5 | 5 |
68,737,130 | 2021-8-11 | https://stackoverflow.com/questions/68737130/error-while-import-keras-attributeerror-module-tensorflow-compat-v2-interna | I want to import keras after I did pip install keras, but it shows message as shown below. I even can't call any function from keras library. Can anyone know about this? import keras Error: AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'register_clear_session_function' | you should use import tensorflow.keras instead of import keras. More info here. | 7 | 11 |
68,822,660 | 2021-8-17 | https://stackoverflow.com/questions/68822660/how-do-you-ignore-specific-pyright-type-checks-by-project-file-line | I cannot quite find clear documentation on how to ignore one or more specific Pyright checks: Using a config file at the root of your project. At the top of a file, function, or method. Each ligne as a trailing comment. Thanks in advance for sharing this information. | The usual mypy in-line comments like # type: ignore should work (see details), and for pyright specific config, you can put a pyrightconfig.json in your project root. You can find available config options here. It's just a JSON file, so it looks something like this: { "venvPath": "/home/username/.virtualenvs/", "venv":... | 21 | 17 |
68,768,384 | 2021-8-13 | https://stackoverflow.com/questions/68768384/how-to-send-message-to-telegram-as-code | Sending the output of Prettytable to Telegram This question is a followup to an earlier question. The code which i have is this: import telegram from prettytable import PrettyTable def send_msg(text): token = "*******:**************" chat_id = "***********" bot = telegram.Bot(token=token) bot.sendMessage(chat_id=chat_i... | You have already solved it yourself: you used three backticks in the title of your question. In Markdown (including here on SO), you can put three backticks around a block of code, and that makes it use the code block formatting. ``` this is inside a code block ``` You can just add a line containing the three backtic... | 29 | 44 |
68,792,897 | 2021-8-15 | https://stackoverflow.com/questions/68792897/how-can-repetitive-rows-of-data-be-collected-in-a-single-row-in-pandas | I have a dataset that contains the NBA Player's average statistics per game. Some player's statistics are repeated because of they've been in different teams in season. For example: Player Pos Age Tm G GS MP FG 8 Jarrett Allen C 22 TOT 28 10 26.2 4.4 9 Jarrett Allen C 22 BRK 12 5 26.7 3.7 10 Jarrett Allen C 22 CLE 16 ... | You can groupby and use agg to get the mean. For the non numeric columns, let's take the first value: df.groupby('Player').agg({k: 'mean' if v in ('int64', 'float64') else 'first' for k,v in df.dtypes[1:].items()}) output: Pos Age Tm G GS MP FG Player Jarrett Allen C 22 TOT 18.666667 6.666667 26.266667 4.333333 NB. ... | 16 | 49 |
68,769,247 | 2021-8-13 | https://stackoverflow.com/questions/68769247/how-do-i-write-an-asgi-compliant-middleware-while-staying-framework-agnostic | We're currently maintaining code written in several HTTP frameworks (Flask, aiohttp and FastAPI). Rewriting them so they all use the same framework is currently not feasible. There's some code that I'd like to share across those applications and that would be very well suited for middleware (logging-config, monitoring,... | Flask is a WSGI framework. Starlette is an ASGI framework. aiohttp neither supports WSGI nor ASGI. https://github.com/aio-libs/aiohttp/issues/2902 There is no way to have the same middleware support all three frameworks. | 6 | 2 |
68,804,209 | 2021-8-16 | https://stackoverflow.com/questions/68804209/how-to-do-an-else-default-in-match-case | Python recently has released match-case in version 3.10. The question is how can we do a default case in Python? I can do if/elif but don't know how to do else. Below is the code: x = "hello" match x: case "hi": print(x) case "hey": print(x) default: print("not matched") I added this default myself. I want to know the... | You can define a default case in Python. For this you use a wild card (_). The following code demonstrates it: x = "hello" match x: case "hi": print(x) case "hey": print(x) case _: print("not matched") | 72 | 115 |
68,819,790 | 2021-8-17 | https://stackoverflow.com/questions/68819790/read-write-parquet-files-without-reading-into-memory-using-python | I looked at the standard documentation that I would expect to capture my need (Apache Arrow and Pandas), and I could not seem to figure it out. I know Python best, so I would like to use Python, but it is not a strict requirement. Problem I need to move Parquet files from one location (a URL) to another (an Azure stor... | Great post, based on @Micah's answer, I put my 2 cents in it, in case you don't want to read the docs. A small snippet is the following: import pandas as pd import numpy as np from pyarrow.parquet import ParquetFile # create a random df then save to parquet df = pd.DataFrame({ 'A': np.arange(10000), 'B': np.arange(1000... | 9 | 9 |
68,745,309 | 2021-8-11 | https://stackoverflow.com/questions/68745309/how-to-make-mediapipe-pose-estimation-faster-python | I'm making a pose estimation script for my game. However, it's working at 20-30 fps and not using the whole CPU even if there is no fps limit. It's not using whole GPU too. Can someone help me? Here is resource usage while playing a dance video: https://i.sstatic.net/6L8Rj.jpg Here is my code: import cv2 import mediapi... | Set the model_complexity of mp.Pose to 0. As the documentation states: MODEL_COMPLEXITY Complexity of the pose landmark model: 0, 1 or 2. Landmark accuracy as well as inference latency generally go up with the model complexity. Default to 1. This is the best solution I've found, also use this. | 7 | 3 |
68,783,157 | 2021-8-14 | https://stackoverflow.com/questions/68783157/python-3-requests-how-to-force-use-a-new-connection-for-each-request | I have written a pausable multi-thread downloader using requests and threading, however the downloads just can't complete after resuming, long story short, due to special network conditions the connections can often die during downloads requiring refreshing the connections. You can view the code here in my previous que... | I guess that your problem isn't server related. Probably servers are behaving correctly and the problem are the threads. Considering the code from the related question, if it is up to date, when PAUSE is set to true, which happens during 50% of the time when first argv argument is set to 1, dozens of threads are create... | 10 | 1 |
68,768,017 | 2021-8-13 | https://stackoverflow.com/questions/68768017/how-to-ignore-field-repr-in-pydantic | When I want to ignore some fields using attr library, I can use repr=False option. But I cloud't find a similar option in pydantic Please see example code import typing import attr from pydantic import BaseModel @attr.s(auto_attribs=True) class AttrTemp: foo: typing.Any boo: typing.Any = attr.ib(repr=False) class Temp(... | It looks like this feature has been requested and also implemented not long ago. However, it seems like it hasn't made it into the latest release yet. I see two options how to enable the feature anyway: 1. Use the workaround provided in the feature request Define a helper class: import typing from pydantic import BaseM... | 6 | 7 |
68,789,213 | 2021-8-15 | https://stackoverflow.com/questions/68789213/i-am-getting-an-error-code-is-unreachable-pylance-what-that-mean-or-am-i-doing | def percent(marks): return (marks[0]+marks[1]+marks[2]+marks[3]/400)*100 marks1=[54,65,85,54] percent1=percent(marks1) marks2=[54,52,65,85] percent2 = percent(marks2) print(percent1,percent2) | The lines after return will not be executed anytime. So you can delete them and nothing will change. The message told you about it, because it is very unusual to have such code. I think you wanted this: def percent(marks): return (marks[0]+marks[1]+marks[2]+marks[3]/400)*100 marks1 = [54, 65, 85, 54] percent1 = percent... | 9 | 7 |
68,772,211 | 2021-8-13 | https://stackoverflow.com/questions/68772211/fake-useragent-module-not-connecting-properly-indexerror-list-index-out-of-ra | I tried to use fake_useragent module with this block from fake_useragent import UserAgent ua = UserAgent() print(ua.random) But when the execution reached this line ua = UserAgent(), it throws this error Traceback (most recent call last): File "/home/hadi/Desktop/excel/gatewayform.py", line 191, in <module> gate = Gat... | There is a solution for this, from Github pull request #110. Basically, all you need to do is change one character in one line of the fake_useragent/utils.py source code. To do this on your system, open /usr/local/lib/python3.9/dist-packages/fake_useragent/utils.py† in your favorite text editor using admin privileges. ... | 6 | 15 |
68,744,612 | 2021-8-11 | https://stackoverflow.com/questions/68744612/how-do-i-annotate-a-function-whose-return-type-depends-on-its-argument | In Python, I often write functions that filter a collection to find instances of specific subtypes. For example I might look for a specific kind of nodes in a DOM or a specific kind of events in a log: def find_pre(soup: TagSoup) -> List[tags.pre]: """Find all <pre> nodes in `tag_soup`.""" … def filter_errors(log: List... | Okay, here we go. It passes MyPy --strict, but it isn't pretty. What's going on here For a given class A, we know that the type of an instance of A will be A (obviously). But what is the type of A itself? Technically, the type of A is type, as all python classes that don't use metaclassses are instances of type. Howeve... | 5 | 3 |
68,803,511 | 2021-8-16 | https://stackoverflow.com/questions/68803511/mypy-error-incompatible-types-in-assignment-expression-has-type-dictnothing | I tried to instantiate an empty dictionary on the second level of an existing dict, then assign a key-value pair to it, but MyPy throws an error. Here is a minimal example, which will reproduce it when MyPy checking is activated: result = {"Test": "something"} result['key'] = {} result['key']['sub_key'] = ["some string... | The problem Right, so let's look at the first two lines here. First, you define your dictionary result. You define it like so: result = {"Test": "something"} You don't declare what types you expect the keys and values of result to have, so MyPy is left to work it out for itself. Alright, it says, I can do this — you'v... | 8 | 25 |
68,779,189 | 2021-8-13 | https://stackoverflow.com/questions/68779189/why-do-i-get-this-dbeaver-error-when-importing-data-from-a-csv-file | I'm a student, and I'm working on a project. The premise is that this program I'm working on takes as input the days (M-F) on which a student is enrolled, the number of hours per day they are enrolled, and which course they are enrolled in. Then, it queries a PostgreSQL database for the amount of progress hours (the "p... | I've upgraded to DDeaver version 21.2.0 and everything is working now. I was getting the error trying to export a query to a SQLite table. So the solution is to upgrade DBeaver. | 6 | 3 |
68,779,350 | 2021-8-13 | https://stackoverflow.com/questions/68779350/pylance-reportmissingmodulesource-with-docker | I'm getting the error of missing import when doing import in my Django project, I think it's because it's installed in a Docker Container. But how can I make it so VSCode somehow knows that the packages are installed? If I select an interpreter of a venv in which I have installed django or other packages it doesn't giv... | It's recommended to install the packages individually, but if you want to reuse them, you can add the paths of them into the PYTHONPATH. You can do this to modify the PYTHONPATH: Add these in the settings.json file to Modify the PYTHONPATH in the terminal: "terminal.integrated.env.windows": { "PYTHONPATH": "xxx/site-p... | 7 | 0 |
68,806,714 | 2021-8-16 | https://stackoverflow.com/questions/68806714/determining-exactly-what-is-pickled-during-python-multiprocessing | As explained in the thread What is being pickled when I call multiprocessing.Process? there are circumstances where multiprocessing requires little to no data to be transferred via pickling. For example, on Unix systems, the interpreter uses fork() to create the processes, and objects which already exist when multiproc... | Multiprocessing isn't exactly a simple library, but once you're familiar with how it works, it's pretty easy to poke around and figure it out. You usually want to start with context.py. This is where all the useful classes get bound depending on OS, and... well... the "context" you have active. There are 4 basic contex... | 6 | 6 |
68,780,808 | 2021-8-14 | https://stackoverflow.com/questions/68780808/xml-to-srt-conversion-not-working-after-installing-pytube | I have installed pytube to extract captions from some youtube videos. Both the following code give me the xml captions. from pytube import YouTube yt = YouTube('https://www.youtube.com/watch?v=4ZQQofkz9eE') caption = yt.captions['a.en'] print(caption.xml_captions) and also as mentioned in the docs yt = YouTube('http:/... | This is a bug in the library itself. Everything below is done in pytube 11.01. In the captions.py file on line 76 replace: for i, child in enumerate(list(root)): to: for i, child in enumerate(list(root.findall('body/p'))): Then on line 83, replace: duration = float(child.attrib["dur"]) to: duration = float(child.att... | 5 | 7 |
68,817,652 | 2021-8-17 | https://stackoverflow.com/questions/68817652/why-my-python-code-is-extracting-the-same-data-for-all-the-elements-in-my-list | My project consists of making a competitive watch table for hotel rates for an agency. It is a painful action that I wanted to automate, the code extract correctly the name of hotels and the prices I want to extract but it's working correctly only for the first hotel and I don't know where is the problem. I provide you... | The problem was that it can't access to the element listing arrangements for the rest of the hotels in the list i've added a function that tests the presence of the data and it workod for url in urls: driver.get(url) def existsElement(xpath): try: driver.find_element_by_id(xpath); except NoSuchElementException: return ... | 5 | 2 |
68,823,021 | 2021-8-17 | https://stackoverflow.com/questions/68823021/groupby-roll-up-or-roll-down-for-any-kind-of-aggregates | TL;DR: How can we achieve something similar to Group By Roll Up with any kind of aggregates in pandas? (Credit to @Scott Boston for this term) I have following dataframe: P Q R S T 0 PLAC NR F HOL F 1 PLAC NR F NHOL F 2 TRTB NR M NHOL M 3 PLAC NR M NHOL M 4 PLAC NR F NHOL F 5 PLAC R M NHOL M 6 TRTA R F HOL F 7 TRTA NR... | Building on the idea of @ScottBoston (progressive aggregation, i.e., repeatedly aggregating on the previous aggregate result), we can do something that is relatively generic with regard to the aggregation function, if that function can be expressed as a composition of functions ((f3 ∘ f2 ∘ f2 ∘ ... ∘ f1)(x), or in othe... | 12 | 4 |
68,742,863 | 2021-8-11 | https://stackoverflow.com/questions/68742863/error-while-trying-to-fine-tune-the-reformermodelwithlmhead-google-reformer-enw | I'm trying to fine-tune the ReformerModelWithLMHead (google/reformer-enwik8) for NER. I used the padding sequence length same as in the encode method (max_length = max([len(string) for string in list_of_strings])) along with attention_masks. And I got this error: ValueError: If training, make sure that config.axial_pos... | First of all, you should note that google/reformer-enwik8 is not a properly trained language model and that you will probably not get decent results from fine-tuning it. enwik8 is a compression challenge and the reformer authors used this dataset for exactly that purpose: To verify that the Reformer can indeed fit lar... | 6 | 3 |
68,762,104 | 2021-8-12 | https://stackoverflow.com/questions/68762104/plotly-adding-scatter-geo-points-and-traces-on-top-of-density-mapbox | I am trying to add a Scattergeo trace or overlay on top of a white-bg density mapbox to get a heat map over a generic USA states outline. The reason for my use of scattergeo is I'd like to plot a star symbol on top of the density mapbox, and the only symbol accepted via add_scattermapbox is a dot. If you choose the sta... | tile maps and layer maps do not work together. Hence you cannot use markers from geo on mapbox thinking laterally, you can add your own geojson layers onto mapbox plots generate geometry. Have provided two options for this a simple triangle get_geom(df["long"], df["lat"], marker=None, size=k) https://labs.mapbox... | 6 | 2 |
68,749,370 | 2021-8-11 | https://stackoverflow.com/questions/68749370/what-is-the-correct-way-to-update-an-slqalchemy-orm-column-from-a-pandas-datafra | I've loaded some data and modified one column in the dataframe and would like to update the DB to reflect the changes. I tried: db.session.query(sqlTableName).update({sqlTableName.sql_col_name: pdDataframe.pd_col_name}) But that just wiped out the column in the database (set every value to '0', the default). I tried a ... | For uploading the DataFrame to a temporary table and then performing an UPDATE you don't need to write the SQL yourself, you can have SQLAlchemy Core do it for you: import pandas as pd import sqlalchemy as sa def update_table_columns_from_df(engine, df, table_name, cols_to_update): metadata = sa.MetaData() main_table =... | 7 | 1 |
68,770,788 | 2021-8-13 | https://stackoverflow.com/questions/68770788/how-to-check-the-convergence-when-fitting-a-distribution-in-scipy | Is there a way to check the convergence when fitting a distribution in SciPy? My goal is to fit a SciPy distribution (namely Johnson S_U distr.) to dozens of datasets as a part of an automated data-monitoring system. Mostly it works fine, but a few datasets are anomalous and clearly do not follow the Johnson S_U distri... | The johnsonu.fit method comes from scipy.stats.rv_continuous.fit. Unfortunately from the documentation it does not appear that it is possible to get any more information about the fit from this method. However, looking at the source code, it appears the actual optimization is done with fmin, which does return more desc... | 7 | 5 |
68,769,968 | 2021-8-13 | https://stackoverflow.com/questions/68769968/google-document-ai-giving-different-outputs-for-the-same-file | I was using Document OCR API to extract text from a pdf file, but part of it is not accurate. I found that the reason may be due to the existence of some Chinese characters. The following is a made-up example in which I cropped part of the region that the extracted text is wrong and add some Chinese characters to repro... | Posting this Community Wiki for better visibility. One of features of DocumentAI is OCR - Optical Character Recognition which allows recognizing text from various files. OP in this scenario received difference outputs using Try it function and Client Libraries - Python. Why are there discrepancies between Try it and Py... | 5 | 1 |
68,807,896 | 2021-8-16 | https://stackoverflow.com/questions/68807896/how-to-disable-logging-from-pytorch-lightning-logger | Logger in PyTorch-Lightning prints information about the model to be trained (or evaluated) and the progress during the training, However, in my case I would like to hide all messages from the logger in order not to flood the output in Jupyter Notebook. I've looked into the API of the Trainer class on the official docs... | I am assuming that two things are particularly bothering you in terms of flooding output stream: One, The "weight summary": | Name | Type | Params -------------------------------- 0 | l1 | Linear | 100 K 1 | l2 | Linear | 1.3 K -------------------------------- ... Second, the progress bar: Epoch 0: 74%|███████████ | ... | 10 | 7 |
68,815,761 | 2021-8-17 | https://stackoverflow.com/questions/68815761/how-to-customize-fastapi-request-body-documentation | I'm using FastAPI to serve ML models. My endpoint receives and sends JSON data of the form: [ {"id": 1, "data": [{"code": "foo", "value": 0.1}, {"code": "bar", "value": 0.2}, ...]}, {"id": 2, "data": [{"code": "baz", "value": 0.3}, {"code": "foo", "value": 0.4}, ...]}, ... ] My models and app look as follows: from typ... | You can always accept the raw request, load the request.body() data as bytes and do your own decoding. The schema of the request body should then be documented as a (partial) raw OpenAPI Operation structure using the openapi_extra argument to the @app.post() decorator: @app.post( "/score", response_model=List[Sample], ... | 6 | 5 |
68,811,220 | 2021-8-17 | https://stackoverflow.com/questions/68811220/handling-the-token-expiration-in-fastapi | I'm new with fastapi security and I'm trying to implement the authentication thing and then use scopes. The problem is that I'm setting an expiration time for the token but after the expiration time the user still authenticated and can access services import json from jose import jwt,JWTError from typing import Optiona... | I had pretty much the same confusion when I started out with FastAPI. The access token you created will not expire on its own, so you will need to check if it is expired while validating the token at get_current_user. You could modify your TokenData schema to the code below: class TokenData(BaseModel): username: Option... | 5 | 5 |
68,814,074 | 2021-8-17 | https://stackoverflow.com/questions/68814074/how-to-save-parameters-just-related-to-classifier-layer-of-pretrained-bert-model | I fine tuned the pretrained model here by freezing all layers except the classifier layers. And I saved weight file with using pytorch as .bin format. Now instead of loading the 400mb pre-trained model, is there a way to load the parameters of the just Classifier layer I retrained it? By the way, I know that I have to ... | You can do it like this import torch # creating a dummy model class Classifier(torch.nn.Module): def __init__(self): super(Classifier, self).__init__() self.first = torch.nn.Linear(10, 10) self.second = torch.nn.Linear(10, 20) self.last = torch.nn.Linear(20, 1) def forward(self, x): pass # Creating its object model = C... | 5 | 6 |
68,812,647 | 2021-8-17 | https://stackoverflow.com/questions/68812647/how-to-add-vertical-line-to-legends-created-via-add-vline-method-in-plotly-pyth | Using Python 3.8, Plotly 4.13. Within my scatterplot, I've added multiple vertical lines using add_vline() method in plotly. However I cannot add it to legend allowing me to turn on/off vertical lines. How can add vertical lines to the legend? Here is example of how I've created my plot: fig = go.Figure() fig.add_trace... | The vertical line is just a decoration of the graph, not a graph object, so it is not included in the legend. So if you want to use the ON/OFF function in the legend, you can add a new one in go.Scatter and use it for the function to select in the legend. I modified the example from the official reference to create the... | 7 | 11 |
68,813,246 | 2021-8-17 | https://stackoverflow.com/questions/68813246/can-anyone-please-explain-why-set-is-behaving-like-this-with-boolean-in-it | Please explain the behavior of the set in the image. I know that set is unordered but where are the other elements from the set a & b ? | True and 1 are the same: >>> True == 1 True >>> Since sets can't have duplicate values, it only takes the one that appears first. You can see that if you convert True to int: >>> int(True) 1 >>> The output is 1. | 5 | 6 |
68,808,298 | 2021-8-16 | https://stackoverflow.com/questions/68808298/typeerror-scatter-got-an-unexpected-keyword-argument-trendline-options-plo | I'm getting the error: TypeError: scatter() got an unexpected keyword argument 'trendline_options' When trying to adjust the smoothing of the lowess tendline using plotly express. Here is my code for the graph: fig = px.scatter(dfg, x="Yr_Mnth", y="Episode_Count", color = "Target", labels={"Episode_Count": tally + " p... | As Henry helpfully pointed out this was just a version problem, easily addressed by updating plotly using: pip install plotly==5.2.1 | 5 | 5 |
68,759,330 | 2021-8-12 | https://stackoverflow.com/questions/68759330/python-appending-dataframe-to-exsiting-excel-file-and-sheet | I have a question about appending a dataframe to existing sheet on existing file. I tried to write the code by myself writer = pd.ExcelWriter('existingFile.xlsx', engine='openpyxl', mode='a') df.to_excel(writer, sheet_name="existingSheet", startrow=writer.sheets["existingSheet"].max_row, index=False, header=False) and... | It seems this function is broken in pandas 1.3.0 Just look at this document , when trying to append to existing sheet it will either raise an error, create a new one or replace it if_sheet_exists{‘error’, ‘new’, ‘replace’}, default ‘error’ How to behave when trying to write to a sheet that already exists (append mode ... | 10 | 6 |
68,803,345 | 2021-8-16 | https://stackoverflow.com/questions/68803345/syntax-for-creating-a-new-empty-geodataframe | I have a GeoDataFrame (let's call it Destinations) that was made from a point shapefile using GeoPandas. For every feature (correct me if the terminology is wrong) in Destinations, I need to find the nearest node on a graph and save that node to another GeoDataFrame (let's call it Destination_nodes, it will be used lat... | For a GeoDataFrame you need to say which column will be the geometry, i.e. contain features as you say. So you could simply specify the columns of your empty dataframe at creation, without specifying any data: >>> dest = geopandas.GeoDataFrame(columns=['id', 'distance', 'feature'], geometry='feature') >>> dest Empty Ge... | 8 | 9 |
68,736,735 | 2021-8-11 | https://stackoverflow.com/questions/68736735/django-prints-error-when-permissiondenied-exception-raises | In our project, we have used django SessionMiddleware to handle users sessions and it's working fine. The only problem here is when PermissionDenied exceptions happens, an error and its traceback will be printed out in the console! However as expected, by raising that exception, the 403 page will show to the user, but ... | From this comment In this example the exception is raised from permission_required decorator in django.contrib.auth.decorators. I passed raise_exception=True to this decorator to make it raise exception instead of redirecting to login page So, it is clear that you have set raise_exception=True in your decorator. and ... | 5 | 3 |
68,796,752 | 2021-8-16 | https://stackoverflow.com/questions/68796752/whats-the-difference-between-spark-sql-and-spark-read-formatjdbc-option | I assumed that spark.sql(query) is used when we are using spark sql and that spark.read.format("jdbc").option("query", "") is used when we are using oracle sql syntax. Would I be right in assuming so? | Yes and Spark does more than that too! Spark-Jdbc: From Spark docs Jdbc(Java Database connectivity) is used to read/write data from other databases (oracle, mysql, sqlserver, postgres, db2..etc). spark.read.format("jdbc").option("query", "(select * from <db>.<tb>)e") Spark-Sql: From docs Spark's module for working with... | 5 | 4 |
68,796,549 | 2021-8-16 | https://stackoverflow.com/questions/68796549/how-to-calculate-ratio-of-values-in-a-pandas-dataframe-column | I'm new to pandas and decided to learn it by playing around with some data I pulled from my favorite game's API. I have a dataframe with two columns "playerId" and "winner" like so: playerStatus: ______________________ playerId winner 0 1848 True 1 1988 False 2 3543 True 3 1848 False 4 1988 False ... Each row represen... | We can take advantage of the way that Boolean values are handled mathematically (True being 1 and False being 0) and use 3 aggregation functions sum, count and mean per group (groupby aggregate). We can also take advantage of Named Aggregation to both create and rename the columns in one step: df = ( df.groupby('player... | 8 | 6 |
68,766,563 | 2021-8-13 | https://stackoverflow.com/questions/68766563/fastapi-response-not-formatted-correctly-for-sqlite-db-with-a-json-column | I have a fast api app with sqlite, I am trying to get an output as json which is valid. One of the columns in sqlite database is a list stored in Text column and another column has json data in Text column. code sample below database = Database("sqlite:///db/database.sqlite") app = FastAPI() @app.get("/flow_json") asyn... | Expanding on this answer I would use the Json datatype for entities and json_col: class ApiFlowJson(BaseModel): id: int customer_name: str response_name: str entities: Json abstract: str json_col: Json revision: int disabled: bool customer_id: int id2: int auth: bool class Config: orm_mode = True Sample from typing im... | 5 | 5 |
68,774,700 | 2021-8-13 | https://stackoverflow.com/questions/68774700/subset-multi-indexed-dataframe-based-on-multiple-level-1-columns | I have a multi=indexed DataFrame, but I want to keep only two columns per level 1, for each of the level 0 variables (i.e. columns 'one' and 'two'). I can subset them separately, but I would like to do it together so I can keep the values side by side Here is the DataFrame index = pd.MultiIndex.from_tuples(list(zip(*[[... | Here's one way using pd.IndexSlice: idnx = pd.IndexSlice[:, ['one', 'two']] df.loc[:, idnx] Output: bar1 bar3 foo1 foo2 one one two two 0 0.589999 0.261224 -0.106588 -2.309628 1 0.646201 -0.491110 0.430724 1.027424 Another way using a little known argument, axis, of pd.DataFrame.loc: df.loc(axis=1)[:, ['one', 'two'... | 6 | 11 |
68,781,379 | 2021-8-14 | https://stackoverflow.com/questions/68781379/how-do-i-change-the-terminal-inside-visual-studio-code-to-use-the-non-rosetta-on | I am new to python and am trying to run a python 2.7 script. Got pip for python 2.7 and installed a dependency of pyCrypto from the mac terminal shell. The downloaded python script, I want to try, runs fine in the terminal app when I execute it using python2. Now I open it in vscode and try to run the script in its ter... | I'm not familiar with VSCode, but you can manually force the chosen architecture slice of anything you launch with the arch command (see man arch). If you have a script that you'd normally launch like: ./script.py Then you can force either architecture like so: arch -x86_64 ./script.py arch -arm64 ./script.py | 6 | 8 |
68,778,470 | 2021-8-13 | https://stackoverflow.com/questions/68778470/python-mysql-error-1-failed-executing-the-operation-could-not-process-para | I am using following code to update many on for my table. However that's fine working on Windows with Python but not working on my Ubuntu machine. Update many keep saying MySQL Error [-1]: Failed executing the operation; Could not process parameters. Is there are any solution to trace what's exact causing this error? d... | You should use one pattern for building queries: if not query: columns = ', '.join('`{0}`'.format(k) for k in data_dict) duplicates = ', '.join('{0}=VALUES({0})'.format(k) for k in data_dict) place_holders = ', '.join('`{0}`'.format(k) for k in data_dict) Truly, you shouldn't string-build queries. It's unsafe, error-... | 5 | 2 |
68,774,082 | 2021-8-13 | https://stackoverflow.com/questions/68774082/why-does-pythons-exceptions-repr-keep-track-of-passed-objects-to-init | Please see the below code snippet: In [1]: class A(Exception): ...: def __init__(self, b): ...: self.message = b.message ...: In [2]: class B: ...: message = "hello" ...: In [3]: A(B()) Out[3]: __main__.A(<__main__.B at 0x14af96790>) In [4]: class A: ...: def __init__(self, b): ...: self.message = b.message ...: In [5]... | When a Python object is created, it is the class's __new__ method that is called, and __init__ is then called on the new instance that the __new__ method returns (assuming it returned a new instance, which sometimes it doesn't). Your overridden __init__ method doesn't keep a reference to b, but you didn't override __ne... | 7 | 9 |
68,775,783 | 2021-8-13 | https://stackoverflow.com/questions/68775783/pythons-requests-library-removing-appending-question-mark-from-url | Goal Make request to http://example.com/page? using requests.get() Problem The question mark ("?") is automatically stripped from the request if it is the last character in the URL (eg. http://example.com/page?1 and http://example.com/page?! work, http://example.com/page? does not) Sample code import requests endpoint ... | This is not possible with the requests library. URLs passed into requests are parsed by urllib3.util.url.parse_url() into separate parts: scheme auth host port path query fragment The logic for getting the query part of a URL assumes that the querystring starts after ?, but since there is nothing after the question ma... | 6 | 8 |
68,765,846 | 2021-8-13 | https://stackoverflow.com/questions/68765846/combining-rows-in-a-geopandas-dataframe | TLDR: I'm trying to combine rows of a GeoPandas Dataframe into one row where their shapes are combined into one. I'm currently working on a little project that requires me to create interactive choropleth plots of Canadian health regions using a few different metrics. I had merged two Dataframes, one containing populat... | Turns out it was actually simpler than I had imagined, and I was just confused about some additional columns in the dataframe that weren't actually necessary for the mapping. I'm new to Geopandas and mapping in general, so I hadn't realized the SHAPE_AREA and SHAPE_LEN weren't actually needed. Here was the code I used ... | 5 | 3 |
68,765,137 | 2021-8-12 | https://stackoverflow.com/questions/68765137/displacy-custom-colors-for-custom-entities-using-displacy | I have a list of words, noun-verb phrases and I want to: Search dependency patterns, words, in a corpus of text identify the paragraph that matches appears in extract the paragraph highlight the matched words in the paragraph create a snip/jpeg of the paragraph with matched words highlighted save the image in an excel... | I just copy/pasted your code and it works fine here. I'm using spaCy v3.1.1. What does the HTML output source look like? I was able to reproduce your issue on spaCy 2.3.5. I was able to fix it by making the labels upper-case (GOOD and BAD). I can't find a bug about this but since the models normally only use uppercas... | 5 | 7 |
68,766,136 | 2021-8-13 | https://stackoverflow.com/questions/68766136/including-special-character-in-basemodel-for-pydantic | I am trying to create a Pydantic basemodel with a key including a '$' sign. It looks like this: class someModel(BaseModel): $something:Optional[str] = None Then I get SyntaxError: invalid syntax. But I need to keep the key name $something to use in other parts. Is there a way to allow the dollar sign in this case? | You can use Field(alias=...) to use a different (valid) variable name. from pydantic import BaseModel, Field class SomeModel(BaseModel): something: Optional[str] = Field(alias="$something", default=None) I've also added a default value of None since you had that in your code. Here's a working example (EDIT: Updated to... | 5 | 9 |
68,766,331 | 2021-8-13 | https://stackoverflow.com/questions/68766331/how-to-apply-predict-to-xgboost-cross-validation | After some time searching google I feel this might be a nonsensical question, but here it goes. If I use the following code I can produce an xgb regression model, which I can then use to fit on the training set and evaluate the model xgb_reg = xgb.XGBRegressor(objective='binary:logistic', gamme = .12, eval_metric = 'lo... | kfold cv doesn't make the model more accurate per se. In your example with xgb, there are many hyper parameters eg(subsample, eta) to be specified, and to get a sense of how the parameters chosen perform on unseen data, we use kfold cv to partition the data into many training and test samples and measure out-of-sample ... | 11 | 16 |
68,763,671 | 2021-8-12 | https://stackoverflow.com/questions/68763671/running-async-code-from-a-sync-function-with-an-event-loop-already-running | I know, it's a mouthful. I am using pytest-asyncio, which gives you an async event loop for running async code in your tests. I want to use factory-boy with an async ORM. The only problem is that factory-boy does not support async whatsoever. I want to override the _create function on a factory (which is a synchronous ... | You can't await anything in an ordinary function, of course. But there are ways that ordinary functions and async code can interact. An ordinary function can create tasks and return awaitables, for example. Look at this little program: import asyncio import time async def main(): print("Start", time.asctime()) awaitabl... | 8 | 3 |
68,763,357 | 2021-8-12 | https://stackoverflow.com/questions/68763357/strange-behaviour-when-mixing-abstractmethod-classmethod-and-property-decorator | I've been trying to see whether one can create an abstract class property by mixing the three decorators (in Python 3.9.6, if that matters), and I noticed some strange behaviour. Consider the following code: from abc import ABC, abstractmethod class Foo(ABC): @classmethod @property @abstractmethod def x(cls): print(cls... | This looks like a bug in the logic that checks for inherited abstract methods. An object in a class dict is considered abstract if retrieving its __isabstractmethod__ attribute produces True. When Bar subclasses Foo, Python needs to determine whether Bar overrides the abstract Foo.x, and if so, whether the override is ... | 6 | 5 |
68,760,228 | 2021-8-12 | https://stackoverflow.com/questions/68760228/is-there-something-in-python-that-is-similar-to-want-in-perl | In Perl there is a way to find out what context a function is called in - whether it's a list or scalar context - or even finer granularity. See wantarray and the want module. Is there something similar in Python? | No, Python doesn't have the scalar/array distinction that Perl does. Values are simply bound to names with no regard for the type of the value. The closest analogy I can think of would be something like x += y This is desugared as x.__iadd__(y), so the method __iadd__ could examine the type of its argument y if it wan... | 5 | 5 |
68,746,351 | 2021-8-11 | https://stackoverflow.com/questions/68746351/using-pydantic-to-deserialize-sublasses-of-a-model | I'm using data that follows a class inheritance pattern... I'm having trouble getting pydantic to deserialize it correctly for some use cases. Given the code below, it appears that the validators are not called when using the parse_* methods. The type for "fluffy" and "tiger" are Animal, however when deserializing the ... | Answer from pydantic project discussion: You can simply add class Animal(BaseModel): ... @classmethod def parse_obj(cls, obj): return cls._convert_to_real_type_(obj) | 5 | 3 |
68,753,693 | 2021-8-12 | https://stackoverflow.com/questions/68753693/mqtt-subscribing-does-not-work-properly-in-multithreading | I have code like below threads = [] t = threading.Thread(target=Subscribe('username', "password", "topic", "host",port).start) t1 = threading.Thread(target=Subscribe('username2', "password2", "topic2", "host",port).start) threads.append(t) threads.append(t1) for thread in threads: thread.start() for thread in threads:... | I had to give two different client_ids for the two instances of Client and it solved the issue. | 5 | 1 |
68,754,499 | 2021-8-12 | https://stackoverflow.com/questions/68754499/sphinx-meth-role-does-not-create-a-link | In a python module, in the docstring of the module I have the following: :meth:`my_method` and I have the following class in the current module: class GameP: ... def my_method(self): return f"{self._name} {self.selected}" Sphinx does not create a link for that, whilst in the Sphinx documentation we have: Normally, n... | The documentation is not crystal clear IMHO, but it works if you use :meth:`.my_method` (with a dot). The dot makes Sphinx look for a match for my_method anywhere. The dot is not needed if the cross-reference is in the docstring of the GameP class. But in this case the cross-reference is in the module docstring, and o... | 5 | 4 |
68,741,263 | 2021-8-11 | https://stackoverflow.com/questions/68741263/pycharm-like-console-in-visual-code-studio | I wanted to give VSC a try for developing some Python programs, where I only used PyCharm before. One of the most helpful features for me in Pycharm was the PyDev Console, where I can quickly try small snippets of code (think 3-10 lines), and adjust it to work the way I want it to. I see VSC has a console, but it's muc... | Have you tried Jupyter Notebook and Interactive? There are provided by the Jupyter Extension which is bound with Python Extension. Open the Command Palette (Ctrl+Shift+P), with the command of: Jupyter: Create New Blank Notebook Jupyter: Create Interactive Window You can refer to the official docs for more details. | 6 | 9 |
68,750,375 | 2021-8-12 | https://stackoverflow.com/questions/68750375/no-matching-distribution-found-for-pandas-1-3-1 | I currently have Pandas with version 1.1.5 and I am trying to install the newest version of Pandas by using the following command $ pip install pandas==1.3.1 However, I get an error as follows: ERROR: Could not find a version that satisfies the requirement pandas==1.3.1 (from versions: 0.1, 0.2b0, 0.2b1, 0.2, 0.3.0b0,... | Pandas dropped support for Python 3.6 in version 1.2.0 (December, 2020). Either upgrade to Python 3.7+ or make do with Pandas 1.1.5, which is the last version to support Python 3.6. | 6 | 20 |
68,744,441 | 2021-8-11 | https://stackoverflow.com/questions/68744441/why-keyword-match-in-python-3-10-can-be-as-a-variable-or-function-name | I don't fully understand why the keyword match can be used as a variable or function name, unlike other keywords if, while, etc.? >>> match "abc": ... case "abc": ... print('Hello!') ... Hello! >>> from re import match >>> match('A', 'A Something A') <re.Match object; span=(0, 1), match='A'> >>> match = '????' >>> matc... | Per PEP 622, match and case are being added as "soft keywords", so they will remain valid identifiers: This PEP is fully backwards compatible: the match and case keywords are proposed to be (and stay!) soft keywords, so their use as variable, function, class, module or attribute names is not impeded at all. | 6 | 12 |
68,742,663 | 2021-8-11 | https://stackoverflow.com/questions/68742663/how-to-upgrade-tensorflow-in-anaconda-environment | I am having TensorFlow version 2.0.0 in my anaconda environment. I want to upgrade it to an upgraded version. How can I do it? | conda update <package name> or conda install <package name> Note: A second install equals an Override... Specific to your case: conda install -c conda-forge -n <environment> tensorflow==<wanted version> | 6 | 7 |
68,741,944 | 2021-8-11 | https://stackoverflow.com/questions/68741944/using-decorators-of-optional-dependency | Lets say I have the following code: try: import bar except ImportError: bar = None @bar.SomeProvidedDecorator def foo(): pass where bar is an optional dependency. The code above will fail, if bar isn't imported. Is there a recommended way of dealing with this problem? I came up with: try: import bar except ImportError... | Provide an identity decorator in case of bar unavailability: try: import bar except ImportError: class bar: SomeProvidedDecorator = lambda f: f | 5 | 6 |
68,739,824 | 2021-8-11 | https://stackoverflow.com/questions/68739824/use-of-generic-and-typevar | I'm not able to understand the use of Generic and TypeVar, and how they are related. https://docs.python.org/3/library/typing.html#building-generic-types The docs have this example: class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. X = TypeVar('X') Y = TypeVar('Y') def lookup_name(mappi... | Type variables are literally "variables for types". Similar to how regular variables allow code to apply to multiple values, type variables allow code to apply to multiple types. At the same time, just like code is not required to apply to multiple values, it is not required to depend on multiple types. A literal value... | 24 | 40 |
68,739,467 | 2021-8-11 | https://stackoverflow.com/questions/68739467/scalars-returning-first-column-and-leaves-out-all-other-columns | I have the following code that should get the last known action of users and insert it's timestamp in the user object: async def get_last_activity(users, db): user_ids = [user.id for user in users] event_query = select(func.max(EventModel.datetime), EventModel.user_id).\ where(EventModel.user_id.in_(user_ids)).\ group_... | I was under the impression that scalars() was supposed to map the result to an object. Upon reading the docs more closely, it can only do this with one column. This (optional) parameter defaults to 0 (index of column) and hence only the datetime is picked up. I'm not using .scalars() anymore and instead have to do row[... | 5 | 3 |
68,740,412 | 2021-8-11 | https://stackoverflow.com/questions/68740412/type-hinting-a-tuple-without-being-too-verbose | Is there a way to type hint a tuple of elements without having to define each inner element a bunch of times? Example: a = ((1, 2), (2, 3), (3, 4), (4, 5)) a: Tuple[Tuple[int, int], Tuple[int, int], Tuple[int, int], Tuple[int, int]] I am looking for something that may look like this a: Tuple[5*Tuple[int, int]] as oth... | There's a few options here. (All examples here assume a = ((1, 2), (3, 4), (5, 6), (7, 8)), i.e., a tuple consisting of 4 (<int>, <int>) tuples.) You could, as has been suggested in the comments, just use a type alias for the inner type: from typing import Tuple X = Tuple[int, int] a: Tuple[X, X, X, X] You could also ... | 5 | 7 |
68,736,211 | 2021-8-11 | https://stackoverflow.com/questions/68736211/recursionerror-maximum-recursion-depth-exceeded-python-property-getter-setter | I am trying to do getter setter in this simple class, class Person: def __init__(self, n): self.name = n def get_name(self): return self.name def set_name(self, n): self.name = n name = property(get_name, set_name) p = Person('Lewis') p.name = 'Philo' Looks pretty simple and straightforward, but somehow it's not worki... | seems like since name is a property, that you defined with get_name and set_name when you call self.name = n what it does is actually calls the setter of the property, which is set_name. when you initialize the Person object, it calls __init__ which then calls set_name since it has the line self.name = n, and the same ... | 5 | 3 |
68,666,464 | 2021-8-5 | https://stackoverflow.com/questions/68666464/how-to-use-pytest-with-subprocess | The following is a test. How to make this test fail if the subprocess.run results in an error? import pytest import subprocess @pytest.mark.parametrize("input_json", ["input.json"]) def test_main(input_json): subprocess.run(['python', 'main.py', input_json] | subprocess.run returns a CompletedProcess instance, which you can inspect. I'm not sure what exactly you mean by "results in an error"—if it's the return code of the process being non-zero, you can check returncode. If it's a specific error message being output, check stdout or stderr instead. For example: import pytes... | 8 | 9 |
68,684,670 | 2021-8-6 | https://stackoverflow.com/questions/68684670/how-poetry-knows-my-package-is-located-in-the-src-folder | I have a simple question. I used to create a poetry project with my package at root. project.toml mypackage +- __init__.py +- mypackage.py +- test_mypackage.py I recently moved my tests in another directory, so that the folder now looks like. project.toml src +- mypackage +- __init__.py +- mypackage.py tests +- test_m... | Having a folder called src to contain the package code is just a pre-defined standard that poetry recognizes without being told. It works via the packages section in your project file, which by default scans for mypackage and src/mypackage. If you provide your own value, it will stop auto-detecting those two. | 35 | 23 |
68,695,228 | 2021-8-7 | https://stackoverflow.com/questions/68695228/is-there-a-liveness-probe-in-kubernetes-that-can-catch-when-a-python-container-f | I have a python program that runs an infinite loop, however, every once in a while the code freezes. No errors are raised or any other message that would alert me something's wrong. I was wondering if Kubernetes has any liveness probe that could possibly help catch when the code freezes so it can kill and restart that ... | A common approach to liveness probes in Kubernetes is to access an HTTP endpoint (if the application has it). Kubernetes checks whether response status code falls into 200-399 range (=success) or not (=failure). Running a HTTP server is not mandatory as you can run a command or sequence of commands instead. In this cas... | 5 | 3 |
68,668,417 | 2021-8-5 | https://stackoverflow.com/questions/68668417/is-it-possible-to-pass-path-arguments-into-fastapi-dependency-functions | Is there any way for a FastAPI "dependency" to interpret Path parameters? I have a lot of functions of the form: @app.post("/item/{item_id}/process", response_class=ProcessResponse) async def process_item(item_id: UUID, session: UserSession = Depends(security.user_session)) -> ProcessResponse: item = await get_item(cli... | A FastAPI dependency function can take any of the arguments that a normal endpoint function can take. So in a normal endpoint you might define a path parameter like so: from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id): return {"item_id": item_id} Now if you want to ... | 27 | 45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.