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
74,199,437
2022-10-25
https://stackoverflow.com/questions/74199437/why-is-jaxs-split-so-slow-at-first-call
jax.numpy.split can be used to segment an array into equal-length segments with a remainder in the last element. e.g. splitting an array of 5000 elements into segments of 10: array = jnp.ones(5000) segment_size = 10 split_indices = jnp.arange(segment_size, array.shape[0], segment_size) segments = jnp.split(array, split...
This is slow because there are tradeoffs in the implementation of split(), and your function happens to be on the wrong side of the tradeoff. There are several ways to compute slices in XLA, including XLA:Slice (i.e. lax.slice), XLA:DynamicSlice (i.e. lax.dynamic_slice), and XLA:Gather (i.e. lax.gather). The main diffe...
3
5
74,199,117
2022-10-25
https://stackoverflow.com/questions/74199117/trying-to-web-scrape-text-from-a-table-on-a-website
I am a novice at this, but I've been trying to scrape data on a website (https://awards.decanter.com/DWWA/2022/search/wines?competitionType=DWWA) but I keep coming up empty. I've tried BeautifulSoup and Scrapy but I can't get the text out. Eventually I want to get the row of each individual wine in the table into a dat...
Try: import pandas as pd url = "https://decanterresultsapi.decanter.com/api/DWWA/2022/wines/search?competitionType=DWWA" df = pd.read_json(url) # print last items in df: print(df.tail().to_markdown()) Prints: producer name id competition award score country region subRegion vintage color style priceBandLetter com...
3
1
74,194,721
2022-10-25
https://stackoverflow.com/questions/74194721/how-to-create-incrementing-group-column-counter
Consider the following data set: How can I generate the expected value, ExpectedGroup such that the same value exists when True, but changes and increments by 1, when we run into a False statement in case_id. df = pd.DataFrame([ ['A', 'P', 'O', 2, np.nan], ['A', 'O', 'O', 5, 1], ['A', 'O', 'O', 10, 1], ['A', 'O', 'P', ...
You can use diff to select only the first item of each stretch of True: df['ExpectedGroup'] = (df['case_id'].diff() &df['case_id'] ).cumsum().where(df['case_id']) If you don't want the intermediate column: s = (df.FromState == 'O') & (df.ToState == 'O') # or # s = df[['FromState', 'ToState']].eq('O').all(axis=1) df['E...
3
2
74,190,736
2022-10-25
https://stackoverflow.com/questions/74190736/how-to-refer-to-hierachical-column-in-a-pandas-query
# hierarchical indices and columns index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]], names=['year', 'visit']) columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']], names=['subject', 'type']) # mock some data data = np.round(np.random.randn(4, 6), 1) data[:, ::2] *= 10 data += 37 # cre...
You can't use MultiIndexes with query. (Well, you can to some limit use health_data.query('@health_data.Bob.HR > 35'), but this has many flaws, and you won't be able to do this with a sublevel only). You can use xs instead to select your levels: # is Bod/HR > 35? m1 = health_data[('Bob', 'HR')].gt(35) # is any HR > 35?...
3
4
74,190,554
2022-10-25
https://stackoverflow.com/questions/74190554/what-does-show-caches-and-adaptive-arguments-do-in-dis-dis-function
Python 3.11 introduces new two parameters to the dis.dis function, show_caches and adaptive. >>> import dis >>> >>> help(dis.dis) Help on function dis in module dis: dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False) Disassemble classes, methods, functions, and other compiled objects. With no arg...
The show_caches argument is described at the very top of dis documentation since it is possible to pass it to many of the module's functions: Changed in version 3.11: Some instructions are accompanied by one or more inline cache entries, which take the form of CACHE instructions. These instructions are hidden by defau...
8
4
74,189,407
2022-10-25
https://stackoverflow.com/questions/74189407/pandas-numpy-multiple-if-statement-with-and-or-operators
I have quite a complex If statement that I would like to add as a column in my pandas dataframe. In the past I've always used numpy.select for this type of problem, however I wouldn't know how to achieve that with a multi-line if statement. I was able to get this in Excel: =IF(sum1=3,IF(AND(col1=col2,col2=col3),0,1),IF...
Use numpy.where with chain mask with | for bitwise OR - if no match any conditions is created 1: m1 = (df['sum1'] == 3) m2 = (df['col1'] == df['col2']) & (df['col2'] == df['col3']) m3 = (df['sum1'] == 2) m4 = (df['col1'] == df['col2']) | (df['col2'] == df['col3']) | (df['col1'] == df['col3']) m5 = df['sum1'] == 1 df['v...
4
4
74,186,833
2022-10-24
https://stackoverflow.com/questions/74186833/how-to-get-the-schema-from-parquet-in-python-apache-beam
I currently have an apache-beam pipeline in Python in which I'm reading parquet, converting it to a dataframe to do some pandas cleaning, and then converting back to parquet where I'd like to then write the file. It looks like this: with beam.Pipeline(options=pipeline_options) as p: dataframes = p \ | 'Read' >> beam.i...
Your codetable.to_parquet() returns serialized bytes of all of the records in Parquet format. Currently, WriteToParquet() need a manually given fixed schema. So, you have to implement your own pipeline(PTransform) if you want to generate a schema automatically. If you don't need a parallelism(such as sharding), you can...
3
3
74,188,468
2022-10-25
https://stackoverflow.com/questions/74188468/python-how-to-resize-an-array-and-duplicate-the-elements
I've got an array with data like this a = [[1,2,3],[4,5,6],[7,8,9]] and I want to change it to b = [[1,1,2,2,3,3],[1,1,2,2,3,3],[4,4,5,5,6,6],[4,4,5,5,6,6],[7,7,8,8,9,9],[7,7,8,8,9,9]] I've tried to use numpy.resize() function but after resizing, it gives [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]. I can use a for loo...
My initial though was that np.tile would work but in fact what you are looking for is np.repeat twice on two different axes. Try this runnable example! #!/usr/bin/env python import numpy as np a = [[1,2,3],[4,5,6],[7,8,9]] b = np.repeat(np.repeat(a, 2, axis=1), 2, axis=0) b <script src="https://modularizer.github.io/...
3
5
74,188,287
2022-10-25
https://stackoverflow.com/questions/74188287/python-from-dataframes-a-and-b-use-datetime-of-a-to-find-a-value-in-b-based
Have two dataframes, and I am attempting to 'merge' with conditions. The idea being if df_B's DateTime is greater than ST's DateTime by less than 5 mins, then add the value of df_B 'MC' into a new column in df_A. If not, its a blank. df_A = {'SS': ['2022/10/23 9:58:08', '2022/10/23 9:58:08', '2022/10/23 23:07:17', '20...
I get that the rows of df_A and df_B are aligned and both dataframes have equal number of rows. In this case: Putting the 'on' columns into indexes is not necessary to merge dataframes. Instead you can use 'left_on' and 'right_on'. Use 'tolerance' along with the 'forward' direction for the required condition. Reset in...
4
1
74,175,111
2022-10-23
https://stackoverflow.com/questions/74175111/how-to-import-a-pydantic-model-into-sqlmodel
I generated a Pydantic model and would like to import it into SQLModel. Since said model does not inherit from the SQLModel class, it is not registered in the metadata which is why SQLModel.metadata.create_all(engine) just ignores it. In this discussion I found a way to manually add models: SQLModel.metadata.tables["h...
As far as I know, it is not possible to simply convert an existing Pydantic model to an SQLModel at runtime. (At least as of now.) There are a lot of things that happen during model definition. There is a custom meta class involved, so there is no way that you can simply substitute a regular Pydantic model class for a ...
3
3
74,126,228
2022-10-19
https://stackoverflow.com/questions/74126228/how-can-i-develop-with-python-libraries-in-editable-mode-on-databricks
On Databricks, it is possible to install Python packages directly from a git repo, or from the dbfs: %pip install git+https://github/myrepo %pip install /dbfs/my-library-0.0.0-py3-none-any.whl Is there a way to enable a live package development mode, similar to the usage of pip install -e, such that the databricks not...
I would recommend to adopt the Databricks Repos functionality that allows to import Python code into a notebook as a normal package, including the automatic reload of the code when Python package code changes. You need to add the following two lines to your notebook that uses the Python package that you're developing: ...
3
6
74,182,245
2022-10-24
https://stackoverflow.com/questions/74182245/why-prevent-initial-call-does-not-stop-the-initial-call
I have the written code below. I have two dropdown menus that work based on chained callbacks. the first dropdown menu gets the datasets and reads the columns' names and updates the options in the second dropdown menu. Then, the parameters can be plotted on the chart. my dataframes look like this: df={'col1':[12,15,25,...
You can fix it by modifying your code to the following: @app.callback( Output({'type': 'dynamic-graph', 'index': MATCH}, 'figure'), [Input({'type': 'dataset-choice', 'index': MATCH}, 'value'), Input({'type': 'feature-choice', 'index': MATCH}, 'value')], prevent_initial_call=True ) def update_graph(chosen_dataset1, chos...
5
8
74,182,208
2022-10-24
https://stackoverflow.com/questions/74182208/i-am-getting-valueerror-a-document-must-have-an-even-number-of-path-elements
I am trying to read data from excel and store the text data in firestore. When I try to add it one by one without for loop it is working but if I try to automate the process it is not working. Working Code: import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credenti...
As mentioned in the documentation, document IDs cannot contain a slash but in the provided screenshot there are 3. The value of cert is PSDC/2022/TCS/01 so the final path becomes certs/PSDC/2022/TCS/01 that has 5 segments i.e. a sub-collection. You can either replace the / with some other character like _: db.collectio...
3
4
74,180,341
2022-10-24
https://stackoverflow.com/questions/74180341/pythonic-way-to-vectorize-ifelse-over-list
What is the most pythonic way to reverse the elements of one list based on another equally-sized list? lista = [1,2,4] listb = ['yes', 'no', 'yep'] # expecting [-1, 2,-4] [[-x if y in ['yes','yep'] else x for x in lista] for y in listb] # yields [[-1, -2, -4], [1, 2, 4], [-1, -2, -4]] if listb[i] is yes or yep, result...
using zip? >>> [-a if b in ('yes','yep') else a for a,b in zip(lista, listb)] [-1, 2, -4]
3
3
74,175,424
2022-10-23
https://stackoverflow.com/questions/74175424/is-spacy-lemmatization-not-working-properly-or-does-it-not-lemmatize-all-words-e
When I run the spacy lemmatizer, it does not lemmatize the word "consulting" and therefore I suspect it is failing. Here is my code: nlp = spacy.load('en_core_web_trf', disable=['parser', 'ner']) lemmatizer = nlp.get_pipe('lemmatizer') doc = nlp('consulting') print([token.lemma_ for token in doc]) And my output: ['con...
The spaCy lemmatizer is not failing, it's performing as expected. Lemmatization depends heavily on the Part of Speech (PoS) tag assigned to the token, and PoS tagger models are trained on sentences/documents, not single tokens (words). For example, parts-of-speech.info which is based on the Stanford PoS tagger, does no...
4
4
74,174,413
2022-10-23
https://stackoverflow.com/questions/74174413/add-last-value-from-list-in-column-a-into-list-in-column-b
I have the following data frame: df_test = pd.DataFrame({"f":['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], "d":['x', 'x', 'y', 'y', 'x', 'x', 'y', 'y'], "low": [0,5,2,4,5,10,4,8], "up": [5,10,4,6,10,15,8,12], "z": [1,3,6,2,3,7,5,10]}) and what I first have to do is to convert the columns 'low', 'up' and 'z' to list for e...
Another possible solution: dff['new'] = dff['low'] + pd.Series([[x[1]] for x in dff['up']]) Output: f d low up z new 0 a x [0, 5] [5, 10] [1, 3] [0, 5, 10] 1 a y [2, 4] [4, 6] [6, 2] [2, 4, 6] 2 b x [5, 10] [10, 15] [3, 7] [5, 10, 15] 3 b y [4, 8] [8, 12] [5, 10] [4, 8, 12]
3
1
74,168,458
2022-10-23
https://stackoverflow.com/questions/74168458/achieving-interface-without-inheritance-in-python
I have a sorted linked list class SortedLinkedList: # ... def insert(self, value: int): # ... if node.value > value: self.add_before(node, value) # ... I would like to generalize the type of values that a Node can hold from only ints to any object that overloads the > operator by implementing the __gt__() magic method...
What you're looking for is typing.Protocol. class Sortable(Protocol): def __gt__(self, other) -> bool: ... With this, any class that defines __gt__ will be detected as an implicit subtype of Sortable. Note that in Pythons >= 3.8, you may need to to make other positional: class Sortable(Protocol): def __gt__(self, othe...
6
8
74,172,806
2022-10-23
https://stackoverflow.com/questions/74172806/how-to-generate-random-numbers-in-pre-defined-range-which-sums-up-to-a-fixed-num
I have a simple data generation question. I would request for any kind of help with the code in R or Python. I am pasting the table first. Total Num1_betw_1_to_4 Num2_betw_1_to_3 Num3_betw_1_to_3 9 3 3 3 7 1 3 3 9 4 3 2 9 3 3 3 5 2 2 1 7 3 2 2 9 3 3 3 7 2 3 2 5 6 2 4 9 ...
This is straightforward in R. First make a data frame of all possible allowed values of each column: df <- expand.grid(Num1_1_to_4 = 1:4, Num2_1_to_3 = 1:3, Num3_1_to_3 = 1:3) Now throw away any rows that don't sum to 7: df <- df[rowSums(df) == 7,] Finally, sample this data frame: df[sample(nrow(df), 1),] #> Num1_1_t...
3
2
74,169,861
2022-10-23
https://stackoverflow.com/questions/74169861/attrs-convert-liststr-to-listfloat
Given the following scenario: import attrs @attrs.define(kw_only=True) class A: values: list[float] = attrs.field(converter=float) A(values=["1.1", "2.2", "3.3"]) which results in *** TypeError: float() argument must be a string or a real number, not 'list' Obviously it's due to providing the whole list to float, but...
As far as I know, attrs doesn't have a built-in option to switch conversion or validation to "element-wise", the way Pydantic's validators have the each_item parameter. I know you specifically did not ask for a converter function, but I don't really see much of an issue in defining one that you can reuse as often as yo...
4
3
74,171,123
2022-10-23
https://stackoverflow.com/questions/74171123/python-replacing-multiple-list-items-by-one
I want to write a calculator program. My goal is to replace multiple list items(with datatype str) by one(int). I've tried the .insert() method, but it creates a new inner list and places it at the end of the main list. Something like this: input_list = ['4','5','6','+','8','7','4'] #expected result output_list = [456,...
You can use itertools.groupby and pass str.isdigit to its key. It will group the numbers together. from itertools import groupby input_list = ["4", "5", "6", "+", "8", "7", "4"] result = [] for k, g in groupby(input_list, key=str.isdigit): string = "".join(g) # It's True for numbers, False for operators. if k: number =...
3
6
74,170,810
2022-10-23
https://stackoverflow.com/questions/74170810/pandas-how-to-sort-rows-based-on-particular-suffix-values
My Pandas data frame contains the following data reading from a csv file: id,values 1001-MAC, 10 1034-WIN, 20 2001-WIN, 15 3001-MAC, 45 4001-LINUX, 12 4001-MAC, 67 df = pd.read_csv('example.csv') df.set_index('id', inplace=True) I have to sort this data frame based on the id column order by given suffix list = ["WIN",...
Here is one way to do that: import pandas as pd df = pd.read_csv('example.csv') idx = df.id.str.split('-').str[1].sort_values(ascending=False).index df = df.loc[idx] df.set_index('id', inplace=True) print(df)
3
4
74,129,732
2022-10-19
https://stackoverflow.com/questions/74129732/proper-way-to-document-keys-in-typeddict
What is the proper way to document keys inside a TypedDict? I don't see much information inside PEP 589 – TypedDict. I can think of a few solutions: Document keys inside a docstring (is there a standard field to use here?): class Foo(TypedDict): """ I am a documented schema. Keys: key: This key has some implications n...
If we look at the class typing.TypedDict(dict) signature in the documentation we see it's a class, as the official docs start by saying: TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys So documenting the TypedDict is straightforward because it also uses Class Defin...
5
2
74,167,295
2022-10-22
https://stackoverflow.com/questions/74167295/add-the-missing-numbers-in-the-table-in-order
I need modify a csv file with pandas. I have the following table: Interface Description 1 Used 2 Used 3 Used 4 Used 6 Used 8 Used 12 Used 17 Used I need to match the "Interface" column with a range of 1, 20, complete the table with the missing numbers and place the word "free" in the "Description" column and order it ...
Use merge in combination with fillna df = pd.DataFrame({ 'Interface': [1, 2, 3, 4, 6, 8, 12, 17], 'Description': 'Used'}) df2 = pd.DataFrame({'Interface': range(1, 21)}).merge(df, how="left").fillna("free")
4
4
74,152,013
2022-10-21
https://stackoverflow.com/questions/74152013/importing-parquet-file-in-chunks-and-insert-in-duckdb
I am trying to load the parquet file with row size group = 10 into duckdb table in chunks. I am not finding any documents to support this. This is my work so on: see code import duckdb import pandas as pd import gc import numpy as np # connect to an in-memory database con = duckdb.connect(database='database.duckdb', re...
df1 = pd.read_parquet("file1.parquet") This statement will read the entire parquet file into memory. Instead, I assume you want to read in chunks (i.e one row group after another or in batches) and then write the data frame into DuckDB. This is not possible as of now using pandas. You can use something like pyarrow (o...
4
5
74,162,027
2022-10-22
https://stackoverflow.com/questions/74162027/plotnine-secondary-y-axis-dual-axes
I am using python's wonderful plotnine package. I would like to make a plot with dual y-axis, let's say Celsius on the left axis and Fahrenheit on the right. I have installed the latest version of plotnine, v0.10.1. This says the feature was added in v0.10.0. I tried to follow the syntax on how one might do this in R's...
This github issue thread that was mentioned in the question does not say in any way that the secondary axis feature has been implemented. It was added to v0.10.0 milestones list before it was released. Here, milestones list means a todo list of what was planned to be implemented before the version releases. However, up...
3
3
74,159,352
2022-10-21
https://stackoverflow.com/questions/74159352/how-do-i-subtract-from-every-secondi1-element-in-a-2d-array
Here is my 2d array: [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]] I have created a loop to attach each appropriate label to its corresponding value within this 2d array. At the end of the loop I would like to subtract every value by a different number. For example: if I wanted t...
This is a simple job for a list comprehension: >>> L = [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]] >>> [[s, n - 5] for s, n in L] [['P1', 22], ['P2', 39], ['P3', 60], ['P4', 46], ['P5', 26], ['P6', 13], ['P7', 28]] Note that using a comprehension creates a new list and the orig...
4
5
74,157,935
2022-10-21
https://stackoverflow.com/questions/74157935/getting-the-file-name-of-downloaded-video-using-yt-dlp
I'm intending to use yt-dlp to download a video and then cut the video down afterward using ffmpeg. But to be able to use ffmpeg I am going to have to know the name of the file that yt-dlp produces. I have read through their documentation but I can't seem to find a way of getting the file name back into my program.
here are the doc examples the numbers you mentioned (like .f399) I believe are temp only and are eventually removed when the final file is merged. if you want to get the filename: import subprocess someFilename = subprocess.getoutput('yt-dlp --print filename https://www.youtube.com/something') # then pass someFilename ...
13
8
74,143,732
2022-10-20
https://stackoverflow.com/questions/74143732/customize-legend-labels-in-geopandas
I would like to customize the labels on the geopandas plot legend. fig, ax = plt.subplots(figsize = (8,5)) gdf.plot(column = "WF_CEREAL", ax = ax, legend=True, categorical=True, cmap='YlOrBr',legend_kwds = {"loc":"lower right"}, figsize =(10,6)) Adding "labels" in legend_kwds does not help. I tried to add labels with...
Since the question does not have reproducible code and data to work on. I will use the best possible approach to give a demo code that the general readers can follow and some of it may answer the question. The code I provide below can run without the need of external data. Comments are inserted in various places to exp...
4
6
74,151,654
2022-10-21
https://stackoverflow.com/questions/74151654/error-cannot-install-miniconda-with-rstudio
I have written a R script where I use some python lines through the reticulate package. I need to share it with some colleagues who don't know about programming and I've created a batch file so I can run it without them even opening R. However, I tried using the install_miniconda() function to silently install python t...
Try installing rminiconda from the github like this: remotes::install_github("hafen/rminiconda") rminiconda::install_miniconda(name='your_name') After that you can specify the installation using reticulate like this: py <- rminiconda::find_miniconda_python("your_name") reticulate::use_python(py, required = TRUE)
3
4
74,146,246
2022-10-20
https://stackoverflow.com/questions/74146246/counting-number-of-permutations-in-permutation
A permutation of size n is a sequence of n integers in which each of the values ​​from 1 to n occurs exactly once. For example, the sequences [3, 1, 2], [1], and [1, 2, 3, 4] are permutations, while [2], [4, 1, 2], [3, 1] are not. So i recieve 2 inputs: 1 - number of numbers in permutation,2 - the permutation by itself...
l = [6, 3, 4, 1, 2, 7, 5] left_bound = right_bound = l.index(1) permutations = [] for i in range(1,len(l)+1): new_index = l.index(i) # special case if i == 1 if new_index == left_bound == right_bound: pass # if new index if further to the left, update the left index elif new_index < left_bound: left_bound = new_index #...
4
0
74,145,111
2022-10-20
https://stackoverflow.com/questions/74145111/pylance-requiring-explicit-type-on-conformant-list-variables
I define a type as a Union of Literal strings Color = Literal[ "red", "green", "blue", "yellow", "orange", "purple" ] I have a function that expects a list of strings conforming to the type. def f(colors: List[Color]): ... I instantiate a list of conformant strings and pass it to the function colors = ['blue', 'green...
Python literals, like 'blue' or 7, have a natural type. 'blue' is a str, and 7 is an int, according to their runtime types. Type Literals can throw a little confusion into this, because while they take specific objects and give them additional semantic meaning (like 'blue' being a Color or 7 being parameter for f()), t...
3
3
74,134,089
2022-10-20
https://stackoverflow.com/questions/74134089/keyerror-weakref-at-0x7fc9e8267ad0-to-flask-at-0x7fc9e9ec5750
I've been having a hard time handling sessions in flask. Since when I manage the application in the local environment everything works perfectly, including flask sessions. But when i already host it in Render i always get this error in every route. [55] [ERROR] Error handling request /valle-de-guadalupe Traceback (most...
It's usually best to remove as many extra components and identify a minimal example that produces the error, otherwise it's often hard to help. That said, I think that error suggests that db (SQLAlachemy() from flask-sqlalchemy) is not being inited with app. I'm not sure what the db is that is being imported from app_f...
3
6
74,144,861
2022-10-20
https://stackoverflow.com/questions/74144861/runtimeerror-runtimeerror-either-sqlalchemy-database-uri-or-sqlalchemy-bind
I am learning basic flask but cannot import db(database) from freecodecamp I cannot find the solution plz answer this query as soon as possible There are 4 files : when I write from app import db the pythonshell shows error app.py from flask import Flask,render_template, url_for from flask_sqlalchemy import SQLAlchemy ...
You need to initialize db as well, db = SQLAlchemy() # db intitialized here app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://test.db" db.init_app(app) It's SQLALCHEMY_DATABASE_URI not SQLALCHEMY_DATABASE_URL
6
9
74,144,613
2022-10-20
https://stackoverflow.com/questions/74144613/flask-sqlalchemy-raises-typeerror-query-paginate-takes-1-positional-argument
I call Flask-SQLAlchemy's query.paginate method with arguments. Recently this stopped working and instead raised a TypeError. How do I pass page and other arguments to query.paginate? Ticker.query.paginate(page, app.config["TICKERS_PER_PAGE"], False) TypeError: Query.paginate() takes 1 positional argument but 4 were g...
As of Flask-SQLAlchemy 3.0, all arguments to paginate are keyword-only. Ticker.query.paginate(page=page, per_page=app.config["TICKERS_PER_PAGE"], error_out=False)
9
20
74,144,004
2022-10-20
https://stackoverflow.com/questions/74144004/for-loop-that-takes-turns-between-printing-one-thing-or-the-other-python
Not sure how else to word the title, but this is what I need: Print either the number zero, the number one or a phrase in no consecutive order twenty times. This is what I have: n = 0 x = “hello” for i in range(20): print(n, end= ‘’) or print(n+1, end= ‘’) or print(x) The only problem is that it prints them out in or...
import random choices = [1, 0, "hello"] for i in range(20): print(random.choice(choices))
4
8
74,140,606
2022-10-20
https://stackoverflow.com/questions/74140606/pandas-get-all-positive-delta-values-efficiently
I am looking for an efficient way to turn this pandas dataframe: A B C 0 0 1 0 1 0 1 1 2 1 1 1 3 1 1 0 4 0 0 1 into A B C 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 0 4 0 0 1 I only want "1" in a cell, if in the original dataframe the value jumps from "0" to "1". If it's the first row, I want a "1", if "1" is the start value. I...
You can use: df.diff().clip(0).fillna(df) output: A B C 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 0 4 0 0 1
3
2
74,137,116
2022-10-20
https://stackoverflow.com/questions/74137116/how-to-hide-a-pydantic-discriminator-field-from-fastapi-docs
We have a discriminator field type which we want to hide from the Swagger UI docs: class Foo(BDCBaseModel): type: Literal["Foo"] = Field("Foo", exclude=True) Name: str class Bar(BDCBaseModel): type: Literal["Bar"] = Field("Bar", exclude=True) Name: str class Demo(BDCBaseModel): example: Union[Foo, Bar] = Field(discrimi...
This is a very common situation and the solution is farily simple. Factor out that type field into its own separate model. The typical way to go about this is to create one FooBase with all the fields, validators etc. that all child models will share (in this example only name) and then subclass it as needed. In this e...
6
1
74,133,458
2022-10-20
https://stackoverflow.com/questions/74133458/python-annotate-return-types-for-different-input-cases
I have a function that can return different types given a boolean input argument. Currently, I just annotate it using union: def fn(x: int, ret_str: bool) -> Union[int, str]: if ret_str: return str(x) else: return x However, if I annotate like this, the output of this function will be typed as a union type as well. ou...
Yes, this is possible using the typing module and overload/Literal. It isn't the most elegant solution since it is so verbose (in comparison to most typed languages), but will cause the type checker to associate a return type depending on arguments passed. I would probably avoid doing this in most circumstances outside...
5
4
74,124,896
2022-10-19
https://stackoverflow.com/questions/74124896/fastapi-is-returning-attributeerror-dict-object-has-no-attribute-encode
I am having a very simple FastAPI service, when I try to hit the /spell_checking endpoint, I get this error `AttributeError: 'dict' object has no attribute 'encode'. I am hitting the endpoint using postman, with Post request, and this is the url: http://127.0.0.1:8080/spell_checking, the payload is JSON with value: {"w...
The problem happens when you try to create the Response object. This object expects a string as input (infact it tries to call .encode() on it). There is no need to explicitly create one, you can just return the data and fastapi will do the rest. from typing import Dict import uvicorn from fastapi import FastAPI app = ...
3
5
74,123,745
2022-10-19
https://stackoverflow.com/questions/74123745/how-to-capture-the-data-of-the-drawn-shapes-by-the-mouse-in-dash
So I have this simple python dash application in which I've laid out a graph and a button. My goal is this: when I press the button, I want to retrieve the shapes that have been drawn. import plotly.graph_objects as go import dash from dash import html, dcc, Input, Output, State app = dash.Dash(__name__) fig = go.Figur...
You should use relayout_data to detect all the drawn shapes on the graph, and then you can parse the desired data as you would: import dash import json import plotly.graph_objects as go from dash import html, dcc, Input, Output, State app = dash.Dash(__name__) fig = go.Figure() app.layout = html.Div([ dcc.Graph(id = "g...
4
3
74,103,649
2022-10-17
https://stackoverflow.com/questions/74103649/is-there-a-way-to-use-endswith-startswith-in-match-case-statements
Is there a way to use match case to select string endings/beginnings like below? match text_string: case 'bla-bla': return 'bla' case .endswith('endofstring'): return 'ends' case .startswith('somestart'): return 'start'
You were close. You wanted a conditional guard on a pattern. In the following case, one that simply matches the value. match text_string: case 'bla-bla': return 'bla' case s if s.endswith('endofstring'): return 'ends' case s if s.startswith('somestart'): return 'start' This doesn't gain much over the following. if tex...
10
19
74,058,262
2022-10-13
https://stackoverflow.com/questions/74058262/icu-sort-strings-based-on-2-different-locales
As you probably know, the order of alphabet in some (maybe most) languages is different than their order in Unicode. That's why we may want to use icu.Collator to sort, like this Python example: from icu import Collator, Locale collator = Collator.createInstance(Locale("fa_IR.UTF-8")) mylist.sort(key=collator.getSortKe...
A bit late to answer the question, but here it is for future reference. ICU collation uses the CLDR Collation Algorithm, which is a tailoring of the Unicode Collation Algorithm. The default collation is referred to as the root collation. Don't think in terms of Locales having a set of collation rules, think more in ter...
7
4
74,039,971
2022-10-12
https://stackoverflow.com/questions/74039971/importerror-cannot-import-name-timedjsonwebsignatureserializer-from-itsdange
I'm running a flask app using itsdangerous python package in AWS EC2 instance. Traceback (most recent call last): File "run.py", line 4, in <module> app = create_app() File "/home/ubuntu/RHS_US/application/portal/__init__.py", line 29, in create_app from portal.users.routes import users File "/home/ubuntu/RHS_US/applic...
First make sure to re-install and update itsdangerous. pip install -U itsdangerous Then what you want to do is from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer This works well.
7
15
74,098,560
2022-10-17
https://stackoverflow.com/questions/74098560/python-bad-file-descriptor-when-reading-from-pipe
I'm trying to start a subprocess and pass a pipe file descriptor to it to read from. However when I try to read from the pipe in the child process I get "Bad file descriptor", even though I can read from the pipe in the parent process just fine. Here's the parent process: import subprocess import sys import os r, w = o...
From the official Python docs: Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds parameter is False.
3
4
74,046,983
2022-10-12
https://stackoverflow.com/questions/74046983/plotly-no-renderer-could-be-found-for-mimetype-application-vnd-plotly-v1json
Environment: Visual Code Jupyter extension (v2022.9.1202862440) Kernel: Python 3.10.1 64-bit Pyplot version: 5.10.0 Nbformat version: 5.7.0 What happened? I am trying to use simple boxplot with plotly.express via this code: #Basic vizualization fig = px.box(dataset, y='Rh2') fig.update_layout( height=1000 ) First er...
Try to install Jupyter Notebook Renderers extension on vscode.
9
10
74,070,505
2022-10-14
https://stackoverflow.com/questions/74070505/how-to-run-fastapi-application-inside-jupyter
I am learning FastAPI and I have this example. from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} I saved the script as main.ipynb The tutorial says to run this line of code in the command line: uvicorn main:app --reload I am getting this error: (venv) PS C:\U...
If you attempted to start the server as usual inside Jupyter, for example: import uvicorn if __name__ == "__main__": uvicorn.run(app) you would get the following error: RuntimeError: asyncio.run() cannot be called from a running event loop This is due to Jupyter already running an event loop, and once Uvicorn calls a...
8
15
74,056,594
2022-10-13
https://stackoverflow.com/questions/74056594/python-discord-bot-works-in-dm-but-not-in-server
I am trying to set up a simple Discord bot for a server, but it only appears to be responding in DMs to commands and not in any server channels. The bot has admin permissions in the server I am trying to get it to respond in. After doing some looking around I have found no fixes. Here's the code: import discord token_f...
Two things must be done before you can respond to messages within channels: Configuration the intent of the bot within discord developer portal Specify the intent within the bot itself. Step 1: Configuring the intent of the bot in developer portal: Within the developer portal, find your bot under applications. Select...
3
3
74,086,844
2022-10-16
https://stackoverflow.com/questions/74086844/how-to-type-hint-pandas-na-as-a-possible-output
I have Pandas lambda function which I use with .apply. This function will output a dictionary with string keys and values that are either strings or pd.NA. When I try to type hint the function I get an error: def _the_function(x: str) -> dict[str, str | pd.NA]: ... ERROR: Expected class type but received "NAType" How...
Your problem comes from the fact that pandas.NA is not a type. It is an instance (a singleton in fact) of the NAType class in Pandas. You need to use classes in type annotations.* More precisely, annotations must be made with instances of type (typically called classes) or special typing constructs like Union or generi...
5
10
74,074,580
2022-10-14
https://stackoverflow.com/questions/74074580/how-to-avoid-losing-type-hinting-of-decorated-function
I noticed that when wrapping a function or method that have some type hinting then the wrapped method loses the type hinting informations when I am coding using Visual studio code. For example with this code: from typing import Callable import functools def decorate(function: Callable): @functools.wraps(function) def w...
The best you can do with Python 3.8 (and 3.9) is the following: from __future__ import annotations from functools import wraps from typing import Any, Callable, TypeVar T = TypeVar("T") def decorate(function: Callable[..., T]) -> Callable[..., T]: @wraps(function) def wrapper(obj: A, *args: Any, **kwargs: Any) -> T: re...
7
11
74,099,657
2022-10-17
https://stackoverflow.com/questions/74099657/how-to-print-a-fraction-in-latex-form
I have a fraction and I want to print the latex form of it. The fraction is like this for n == 3: How can I print the latex for this fraction using divide and conquer: 1+\frac{2+\frac{4}{5}}{3+\frac{6}{7}} And for n == 4 the fraction is: And the result is: 1+\frac{2+\frac{4+\frac{8}{9}}{5+\frac{10}{11}}}{3+\frac{6+\f...
I found the solution myself. I've tried to solve the problem by using divide and conquer. My solution has two parameters, start and step. Start is the value that is printed at the first step. and step is the value that shows the number of fractions. If step = 1, then I print just the value of start. Otherwise for each ...
3
11
74,058,780
2022-10-13
https://stackoverflow.com/questions/74058780/validation-of-field-assignment-inside-validator-of-pydantic-model
I've following pydantic model defined. When I run p = IntOrStr(value=True), I expect failure as True is boolean and it should fail the assignments to __int and __str class IntOrStr(BaseModel): __int: Optional[conint(strict=True, le=100, ge=10)] = None __str: Optional[constr(strict=True, max_length=64, min_length=10)] =...
There are a quite a few problems here. Namespace This is unrelated to Pydantic; this is just a misunderstanding of how Python namespaces work: In the namespace of the method, __int and __str are just local variables. What you are doing is simply creating these variables and assigning values to them, then discarding the...
3
5
74,106,823
2022-10-18
https://stackoverflow.com/questions/74106823/working-poetry-project-with-private-dependencies-inside-docker
I have a Python library hosted in Google Cloud Platform Artifact Registry. Besides, I have a Python project, using Poetry, that depends on the library. This is my project file pyproject.toml: [tool.poetry] name = "Test" version = "0.0.1" description = "Test project." authors = [ "Me <me@mycompany.com>" ] [tool.poetry.d...
Finally, I found a solution that worked in my use case. There are two main parts: Installing keyrings.google-artifactregistry-auth as a Poetry plugin, using this command: poetry self add keyrings.google-artifactregistry-auth Authenticating inside the container using a service account key file: gcloud auth activate...
12
5
74,045,802
2022-10-12
https://stackoverflow.com/questions/74045802/0-invalid-argument-unknown-image-file-format-one-of-jpeg-png-gif-bmp-requ
I have seen Tensorflow Keras error: Unknown image file format. One of JPEG, PNG, GIF, BMP required and Unknown image file format. One of JPEG, PNG, GIF, BMP required these answers. It did not help me completely I am building a simple CNN in google colab Epoch 1/5 --------------------------------------------------------...
Please just because an image has a .jpeg or .png extension doesn't mean it is good. Some images can have a correct extension and still be bad. Apart from extensions, the image may still have bad binaries which is what makes an image corrupt. You need a code base to properly fish out corrupt images from your directory d...
3
2
74,105,403
2022-10-18
https://stackoverflow.com/questions/74105403/determine-if-code-is-running-on-databricks-or-ide-pycharm
I am in the process of building a Python package that can be used by Data Scientists to manage their MLOps lifecycle. Now, this package can be used either locally (usually on PyCharm) or on Databricks. I want a certain functionality of the package to be dependent on where it is running, i.e. I want it to do something d...
The workaround I've found to work is to check for databricks specific environment variables. import os def is_running_in_databricks() -> bool: return "DATABRICKS_RUNTIME_VERSION" in os.environ
6
8
74,114,745
2022-10-18
https://stackoverflow.com/questions/74114745/how-to-fix-deprecationwarning-dataframes-with-non-bool-types-result-in-worse-c
I have been trying to implement the Apriori Algorithm in python. There are several examples online, they all use similar methods and mostly the same example dataset. The reference link: https://www.kaggle.com/code/rockystats/apriori-algorithm-or-market-basket-analysis/notebook (starting from the line [26]) I have a dif...
I ran into the same issue even after converting my dataframe fields to 0 and 1. The fix was just making sure the apriori module knows the dataframe is of boolean type, so in your case you should run this : frequent_itemsets = apriori(basket_sets.astype('bool'), min_support=0.07, use_colnames=True) In addition, in th...
5
7
74,073,543
2022-10-14
https://stackoverflow.com/questions/74073543/remove-features-of-json-if-lat-lon-keys-not-within-other-json-boundaries
I'm trying to create a weather contour for the United States from an existing data frame and add it to a Dash Mapbox map, but the json file I am creating "fills in" areas where data does not exist in an attempt to fill out the entire array. The unwanted data can be seen shaded in the image below. I'd like to remove da...
Think of each weather contour as a polygon and the outline of the US as another polygon. What you need is the overlap of the US polygon with each contour polygon. import pandas as pd from datetime import datetime import plotly.express as px import plotly.graph_objects as go import numpy as np import pandas as pd import...
3
3
74,111,323
2022-10-18
https://stackoverflow.com/questions/74111323/python-memory-limit-exceeded-during-google-app-engine-deployment
I am creating a Python project and deploying it to Google App Engine. When I use the deployed link in another project, I get the following error message in Google Cloud Logging: Exceeded hard memory limit of 256 MB with 667 MB after servicing 0 requests total. Consider setting a larger instance class in app.yaml. So, ...
First, I store larger files from local to cloud. Then I successfully deployed the code to Google App Engine without any errors.
5
1
74,057,367
2022-10-13
https://stackoverflow.com/questions/74057367/how-to-get-rid-of-the-in-place-futurewarning-when-setting-an-entire-column-from
In pandas v.1.5.0 a new warning has been added, which is shown, when a column is set from an array of different dtype. The FutureWarning informs about a planned semantic change, when using iloc: the change will be done in-place in future versions. The changelog instructs what to do to get the old behavior, but there is...
I haven't found any better way than suppressing the warning using the warnings module: import numpy as np import pandas as pd import warnings df = pd.DataFrame({"price": [11.1, 12.2]}, index=["book1", "book2"]) original_prices = df["price"] new_prices = np.array([98, 99]) with warnings.catch_warnings(): # Setting value...
24
8
74,075,122
2022-10-14
https://stackoverflow.com/questions/74075122/the-most-efficient-way-rather-than-using-np-setdiff1d-and-np-in1d-to-remove-com
I need a much faster code to remove values of an 1D array (array length ~ 10-15) that are common with another 1D array (array length ~ 1e5-5e5 --> rarely up to 7e5), which are index arrays contain integers. There is no duplicate in the arrays, and they are not sorted and the order of the values must be kept in the main...
Understanding the hash-based solution At first, IDU what does mul_xor_hash exactly do, and if init and k are arbitrary selected or not mul_xor_hash is a custom hash function. Functions mixing xor and multiply (possibly with shifts) are known to be relatively fast to compute the hash of a raw data buffer. The multipli...
3
10
74,044,291
2022-10-12
https://stackoverflow.com/questions/74044291/pyenv-poetry-itself-running-on-older-python-version-what-to-do
Update: Which Python should I use to install poetry? System Python: That is an excellent idea. Once, however, poetry self update was trying to update a system package without the necessary permissions. Pyenv: A good solution. Nonetheless, if Python is updated and the old installation is deleted, poetry will stop worki...
The decision is to use Pyenv to install Poetry. If the older python version should be deleted: Uninstall Poetry. Delete old Python version. Install Poetry.
3
1
74,058,894
2022-10-13
https://stackoverflow.com/questions/74058894/event-loop-is-closed-in-a-celery-worker
I am facing multiple issues using an async ODM inside my celery worker First i wasn't able to init my database models using celery worker signal i am using beanie for the db connection. First Implementation from asyncer import syncify from asgiref.sync import async_to_sync client = AsyncIOMotorClient( DATABASE_URL, uui...
After many investigation using flower for monitoring workers and logging the workers Id ( processes ids) it turns out that Celery worker itself does not process any tasks, it spawns other child processes ( this is my case because i am using the default executor pool which is prefork), while the signal ( worker_ready.co...
8
2
74,089,170
2022-10-16
https://stackoverflow.com/questions/74089170/suppress-rasterio-warning-warning-1-tiffreaddirectory
I've been having problems with the error message Warning 1: TIFFReadDirectory:Sum of Photometric type-related color channels and ExtraSamples doesn't match SamplesPerPixel. Defining non-color channels as ExtraSamples. This error message occurs when I open a .tiff file with wrong tiff tags, in my case the tags: PHOTOME...
Updated Answer After a lot of hunting around, and trying to use TIFFSetWarningHandler() as described here, it transpires that rasterio uses its own, built-in, stripped-down version of gdal - unless you build from source. That gives rise to the following. Method 1 Tell rasterio's GDAL to quiet warnings: #!/usr/bin/env p...
3
4
74,117,873
2022-10-18
https://stackoverflow.com/questions/74117873/data-classes-vs-dictionaries
I've been learning about dataclasses, and was reworking an old project trying to integrate a dataclass into the program in place of a dictionary system I was using. The code blocks below are essentially the respective new and old methods being used to build a dataframe of several thousand items. My problem is I don't u...
As discussed in the comments, there is a lot of discussion (and opinions) regarding this particular comparison. After doing several hours of research, there are a few main points I'd like to lay out for anyone else who may have this question in the future. 1. In regard to efficiency Dictionaries are simpler data contai...
10
12
74,085,655
2022-10-16
https://stackoverflow.com/questions/74085655/pandas-appending-excelxlsx-file-gives-attribute-error
Getting trouble with either of errors ; writer.book=book AttributeError: can't set attribute 'book' or BadZipFile for code not giving badzipfile error I put code line which writes excel file first, dataOutput=pd.DataFrame(dictDataOutput,index=[0]) but, even though I cannot get rid of writer.book = book AttributeError: ...
There are a few things that are unclear about your question, but I'll do my best to try and answer what I think you're trying to do. First off, things that won't work: From the to_excel docs, "If you wish to write to more than one sheet in the workbook, it is necessary to specify an ExcelWriter object", so when you ru...
3
7
74,116,435
2022-10-18
https://stackoverflow.com/questions/74116435/fastapi-is-not-quitting-when-pressing-ctrc
I am finding a difficulty with quitting FastAPI. Ctr+c does not work. Here is my pyproject.toml [tool.pyright] exclude = ["app/worker"] ignore = ["app/worker"] [tool.poetry] name = "api" version = "0.1.0" description = "" authors = ["SamiAlsubhi <sami@alsubhi.me>"] [tool.poetry.dependencies] python = ">=3.8,<3.9" fasta...
It looks like there was a compatibility issue between unvicorn, starlette and FastAPI around those versions. I updated them to the latest versions and that solved the issue.
5
2
74,110,362
2022-10-18
https://stackoverflow.com/questions/74110362/is-there-a-way-in-vscode-to-automatically-switch-python-interpreter-depending-on
I'm using a monorepo with multiple packages in separate directories. Poetry is in charge of package management including creating the virtual environment. I wish VS Code would use the right Python interpreter for each package individually. Is that possible? My workaround is to open a separate window with the directory ...
You can open multiple folders in vscode and select the interpreter for each folder individually. Select Add Folder to Workspace in the menu. As a simple example I have added three folders Then click on the python interpreter version in the lower right corner (or Ctrl+Shift+P --> Python:Select Interpreter) Choose ...
14
9
74,112,099
2022-10-18
https://stackoverflow.com/questions/74112099/importing-matplotlib-causes-int-argument-must-be-a-string-error
I'm new to Python. A few days ago I installed Anaconda and PyCharm (on D disk), and I am trying to use the matplotlib package to plot one picture. When I click "run", I get the following error: Traceback (most recent call last): File "G:\onedrive\OneDrive - mail.dlut.edu.cn\PyCharm\shock wave\P6.py", line 7, in <module...
It looks like this is a bug in pyside6 v6.3.0, one of the libraries matplotlib depends on for rendering plots; here's the bug report. It's a new bug, and it's already been fixed, so it's really bad luck that it got you! Solution: the issue seems to be fixed in pyside version 6.4.0 (released 13 October), so one solution...
4
11
74,108,243
2022-10-18
https://stackoverflow.com/questions/74108243/pyvis-is-there-a-way-to-disable-physics-without-losing-graphs-layout
I am trying to vizualize a large network with pyvis and facing two problems: super long rendering network instability, i.e. nodes move too fast and it is hard to interact with such a network. Disabling physics with toggle_physics(False) helps to speed up rendering and makes the network static, but eliminates the layo...
It is possible to pass x and y coordinates to your pyvis nodes (see doc here). You can then create a graph layout with networkx and pass the resulting positions to your pyvis graph. See example below with nx.circular_layout() applied to the karate club network: import networkx as nx from pyvis.network import Network G ...
6
6
74,110,251
2022-10-18
https://stackoverflow.com/questions/74110251/python-class-generated-by-protoc-cannot-be-imported-in-the-code-because-of-unres
I tried to use protocol buffers on my project and the problem I have is that when I use protoc to generate the python class. The file that's generated looks nothing like in the example provided by Google and cannot be imported in any file because there are some unresolved references. So I followed the example from this...
Turned out the example code works well and the problem was elsewhere in my code. A few confusing things that made me question the code were: The example on the official page is outdated. Google has changed the way the protobuffs are generated and there are no metaclasses anymore. There are dynamic imports so an IDE wi...
5
4
74,111,063
2022-10-18
https://stackoverflow.com/questions/74111063/at-sign-in-pylance-pyright-inlay-hints-error-messages
The July 2022 release of the Python extension for Visual Studio Code introduced "Inlay Type Hints", which automatically suggests return types of functions that don't have an explicit annotation. To enable it, you can set "python.analysis.inlayHints.functionReturnTypes": true to your IDE user settings (Preferences: Open...
That @ indicates that Self is a TypeVar, and Self@HereIsMyClassName refers to the Self in the context of the class HereIsMyClassName (it could also be a function). This is not valid Python. (Technically, it is valid, as the @ operator is matrix multiplication, so you are matrix-multiplying Self and HereIsMyClassName. H...
9
8
74,108,540
2022-10-18
https://stackoverflow.com/questions/74108540/python-error-boolean-series-key-will-be-reindexed-to-match-dataframe-index
I am working on a project in Python, and while my below code works I am getting this hideous error: UserWarning: Boolean Series key will be reindexed to match DataFrame index. dummy_types = pd.get_dummies(df_pokemon_co, columns=['Type 1', 'Type 2']) df_pokemon_co['Rock'] = dummy_types['Type 1_Rock'] + dummy_types['Ty...
If need count matched values by 2 conditions chain them by & for bitwise AND and use sum for Trues values: print('Total rock:', ((df_pokemon_co['Sum']==2) & (df_pokemon_co['Rock']==1)).sum()) For median use DataFrame.loc for select by condition and column name: med = (df_pokemon_co.loc[(df_pokemon_co['Rock']==1) & (df...
3
4
74,103,528
2022-10-17
https://stackoverflow.com/questions/74103528/type-hinting-an-instance-of-a-nested-class
I have a class structure that looks something like this: class Base: class Nested: pass def __init__(self): self.nestedInstance = self.Nested() where subclasses of Base each have their own Nested class extending the original, like this: class Sub(Base): class Nested(Base.Nested): pass This works perfectly, and instan...
I don't agree with the statement that you were trying to violate the Liskov substitution principle. You were merely looking for a way to let a static type checker infer the type of nested_instance for classes inheriting from Base to be their respective Nested class. Obviously this wasn't possible with the code you had;...
3
3
74,091,600
2022-10-17
https://stackoverflow.com/questions/74091600/asgi-application-not-working-with-django-channels
I followed the tutorial in the channels documentation but when I start the server python3 manage.py runserver it gives me this : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 17, 2022 - 00:13:21 Django version 4.1.2, using settings 'confi...
This could be due to the fact that the Django and channels versions you have used are not compatible Try : channels==3.0.4 and django==4.0.0
20
30
74,097,495
2022-10-17
https://stackoverflow.com/questions/74097495/aligning-text-according-to-user-input-in-python
aStr = input("Enter a string message: ") fW = eval(input("Enter a positive integer: ")) print(f"Right aligned is <{aStr:>fW}>") so, this is my code, I would like to align the spaces according to the user input. Whenever I try to use eval or int in fW, it shows this error. Traceback (most recent call last): File "C:\Us...
You were close. To implement a "parameterized" format-string, you need to wrap the parameter fW into additional curly braces: aStr = input("Enter a string message: ") fW = int(input("Enter a positive integer: ")) print(f"Right aligned is <{aStr:>{fW}}>") # {fW} instead of fW See PEP 498 -> format specifiers for furthe...
3
3
74,105,434
2022-10-18
https://stackoverflow.com/questions/74105434/how-to-use-text-languages-in-python
I'm trying to create a text-to-speech Python program. I already have it working in English, though, I need other languages too. How can I use the same methods for other languages like Chinese? coding: from gtts import gTTS import os myText = "hello" language = 'en' output = gTTS(text=myText, lang = language, slow = Fal...
To get all the languages supported by the library you are using use the following: import gtts.lang print(gtts.lang.tts_langs()) In this output, the keys are what you would use and the values just explain what language it is. And to answer your question 'zh-CN': 'Chinese', 'zh-TW': 'Chinese (Mandarin/Taiwan)', 'zh': '...
4
6
74,100,867
2022-10-17
https://stackoverflow.com/questions/74100867/run-github-workflow-with-python
I have a python workflow in github here. I can run that workflow from the web interface. But problem is everytime I have to visit github and click on run workflow. Again I have to login in github from an unknown device to run that workflow. Is there any github module in python that can run a workflow using a personal a...
Thanks to @C.Nivs & @larsks for helping me to find the right documentation. After experimenting with github api, finally I found my answer. Here is the code I used: branch, owner, repo, workflow_name, ghp_token="main", "dev-zarir", "Python-Workflow", "python.yml", "ghp_..." import requests def run_workflow(branch, owne...
3
4
74,105,187
2022-10-18
https://stackoverflow.com/questions/74105187/vscode-auto-suggest-latest-versions-pip-requirements-txt
Identify an unkown feature On a previous VSCode installation (OSX Vscode 1.7.x), a feature was enabled that auto suggested the 3rd party dependencies in the pip requirements.txt file. I am on a fresh install of VSCode(1.71.2 linux) and have both Microsoft Python(v2022.16.1) Pylance(v2022.10.20) extensions installed, ...
It was called PyPi Assistant. I found that by searching in VSCode with @popular pip
3
3
74,103,366
2022-10-17
https://stackoverflow.com/questions/74103366/importerror-cannot-import-name-rfc-1738-quote-from-sqlalchemy-engine-url
I am using a python snowflake connector from the following package: snowflake-sqlalchemy from sqlalchemy import create_engine engine = create_engine(...) It used to be working but it's now failing with this weird error. I tried to switch to older version of the package, but can't get rid of this error. Here is the ful...
Looks like this is a known issue will get resolved in v1.4.3, per the release notes: https://github.com/snowflakedb/snowflake-sqlalchemy/blob/main/DESCRIPTION.md
6
7
74,080,017
2022-10-15
https://stackoverflow.com/questions/74080017/typing-a-dynamically-assigned-attribute
I am writing a "plugin" for an existing python package and wondering how I would properly type-hint something like this. Scenario A python object from a framework I am working with has a plugins attribute that is designed to be extended by user-created plugins. For instance: (very simplified) # External module that I h...
I am afraid you are out of luck, if you are looking for some magical elegant annotation. Dynamic attribute assignment The problem lies in the way that the the package you are using (the one defining BaseClass) is designed. Adding a new attribute to an object using setattr means you are dynamically altering the interfac...
3
4
74,100,294
2022-10-17
https://stackoverflow.com/questions/74100294/how-do-i-multiply-a-pandas-dataframe-by-a-multiplier-from-a-dict
Starting from a dataframe like the below (simplified example of my real case): import pandas as pd df = pd.DataFrame({ 'a': [1.0, 1.1, 1.0, 4.2, 5.1], 'b': [5.0, 4.2, 3.1, 3.2, 4.1], 'c': [3.9, 2.0, 4.2, 3.8, 6.7], 'd': [3.1, 2.1, 1.2, 1.0, 1.0] }) And then taking a dictionary containing some multipliers I want to mul...
Try: df[list(dct)] *= dct.values() print(df) Prints: a b c d 0 1.0 0.050 3.9 0.0031 1 1.1 0.042 2.0 0.0021 2 1.0 0.031 4.2 0.0012 3 4.2 0.032 3.8 0.0010 4 5.1 0.041 6.7 0.0010 If in dct are keys not in dataframe: tmp = {k: dct[k] for k in dct.keys() & df.columns} df[list(tmp)] *= tmp.values()
3
5
74,097,901
2022-10-17
https://stackoverflow.com/questions/74097901/meaning-of-all-inside-python-class
I am aware of the use of __all__ at module scope. However I came across the usage of __all__ inside classes. This is done e.g. in the Python standardlib: class re(metaclass=_DeprecatedType): """Wrapper namespace for re type aliases.""" __all__ = ['Pattern', 'Match'] Pattern = Pattern Match = Match What does __all__ ac...
The typing module does some unorthodox things to patch existing modules (like re). Basically, the built-in module re is being replaced with this class re defined using a custom metaclass that intercepts attribute lookups on the underlying object. __all__ doesn't really have any special meaning to the class (it's just a...
18
12
74,095,402
2022-10-17
https://stackoverflow.com/questions/74095402/flake8s-noqa-interferes-with-markdown-using-mkdocstrings
I am using mkdocstrings in order automatically generate an API documentation from my Python functions. At the same time I am using flake8 to keep my code in good shape. If you want to ignore some flake8 warnings on an in-line basis, you could insert "# noqa" whereby the following lines of code will be ignored by flake8...
put the noqa comment on the end of the docstring -- it will apply to any line within the docstring without changing the string's contents (note: you need a sufficiently new flake8, this change is relatively recent (probably >=4.x)) def f(): """some docstring here something which causes a warning """ # noqa: ABC123 di...
3
5
74,094,919
2022-10-17
https://stackoverflow.com/questions/74094919/how-to-measure-ram-usage-of-each-part-of-code-in-python
I want to measure the RAM usage of each for loop in my code. I searched internet and find process = psutil.Process(os.getpid()) and print(process.memory_info().rss) for measuring RAM. But this code gets the pid of the whole process and not a specific part. Is there any way to measure RAM usage of each part of the code?...
You can read memory usage just before loop and then read it again inside loop. Then you can calculate loop memory usage as a difference between these two values. If it exceeds some threshold, break the loop. Here is sample code: import numpy as np import psutil import os process = psutil.Process(os.getpid()) a = [] thr...
3
3
74,091,764
2022-10-17
https://stackoverflow.com/questions/74091764/string-literal-matching-between-words-in-two-different-dataframe-dfs-and-gener
I have two dataframes df1 and df2 df1 = University School Student first name last name nick name AAA Law John Mckenzie Stevie BBB Business Steve Savannah JO CCC Engineering Mark Justice Fre DDD Arts Stuart Little Rah EEE Life science Adam Johnson meh 120 rows X 5 columns df2 = Statement Stua...
You can melt and merge: import re df1_melt = df1.melt(['University', 'School'], value_name='Match') regex = '|'.join(map(re.escape, df1_melt['Match'])) out = df2.join( df1_melt[['Match', 'University', 'School']] .merge(df2['Statement'] .str.extract(f'({regex})', expand=False) .rename('Match'), how='right', on='Match' )...
3
2
74,092,203
2022-10-17
https://stackoverflow.com/questions/74092203/merge-two-dataframes-with-common-keys-and-adding-unique-columns
I have read through the pandas guide, especially merge and join sections, but still can not figure it out. Basically, this is what I want to do: Let's say we have two data frames: left = pd.DataFrame( { "key": ["K0", "K1", "K2", "K3"], "A": ["A0", "A1", "A2", "A3"], "C": ["B0", "B1", np.nan, np.nan]}) right = pd.DataFr...
You can use combine_first with set_index to accomplish your goal here. right.set_index('key').combine_first(left.set_index('key')).reset_index() Output: key A C D 0 K0 A0 B0 NaN 1 K1 A1 B1 NaN 2 K2 A8 NaN D3 3 K3 A3 NaN NaN
3
5
74,082,173
2022-10-15
https://stackoverflow.com/questions/74082173/python-how-to-merge-column-values-from-one-df-to-match-rows-in-another-df
Can someone please show me how to merge df2 to df1 for just the matching cities, then use the df2's average monthly temperature columns to match to each city's date range (according to the month) into a new column called 'Temp' in df1? These are sample data of much larger files for state and cities in Brazil. df1 Stat...
You can use a merge after reshaping df2 to long form with melt and extracting the month abbreviation with to_datetime and strftime: (df1.assign(month=pd.to_datetime(df1['Dates']).dt.strftime('%b').str.upper()) .merge(df2.melt(['State', 'City'], var_name='month', value_name='Temp'), on=['State', 'City', 'month']) #.drop...
3
1
74,058,548
2022-10-13
https://stackoverflow.com/questions/74058548/why-the-listview-not-showing-data-in-the-template
I'm working on my first Django project (the final project for codecademy's Django class) and I'm making webpages to show the inventory and menu that a restaurant has. I made the model, view, template, etc. for inventory and it displays the ListView perfectly. I did the same thing for my menu and it doesn't work. The pa...
I could see one problem, you have one extra <tr> tag open in both the templates just below the loop. Also think some problem with available method you manually defined in MenuItem model, so I removed it, try without it. Also I'd recommend you to use context_object_name which is by default object_list so: views.py class...
3
1
74,079,204
2022-10-15
https://stackoverflow.com/questions/74079204/spllit-string-and-assign-to-two-columns-using-pandas-assign-method
If using the following DataFrame I can split the "ccy" string and create two new columns: df_so = pd.DataFrame.from_dict({0: 'gbp_usd', 1: 'eur_usd', 2: 'usd_cad', 3: 'usd_jpy', 4: 'eur_usd', 5: 'eur_usd'},orient='index',columns=["ccy"]) df_so[['base_ccy', 'quote_ccy']] = df_so['ccy'].str.split('_', 1, expand=True) gi...
I actually think the first version you suggested is the best. df_so[['base_ccy', 'quote_ccy']] = df_so['ccy'].str.split('_', 1, expand=True) If you want to do it using assign, you can do it like this utilising the rename function. df_so.assign(**df_so['ccy'].str.split('_', n=1, expand=True) .rename(columns={0: "base_c...
3
1
74,076,140
2022-10-15
https://stackoverflow.com/questions/74076140/sdk-is-not-defined-for-run-configuration
When I'm trying to run my project in PyCharm I'm getting an error: SDK is not defined for Run Configuration. I tried to set a new interpreter and tried everything. What does "SDK" mean and where can I configure it?
I just had this same issue (see my comment above). What worked for me was to go into "Edit Configurations", delete the configuration that was copied over from the original PC, and create my own configuration (basically with the same inputs as before).
17
19
74,080,581
2022-10-15
https://stackoverflow.com/questions/74080581/building-dictionary-of-unique-ids-for-pairs-of-matching-strings
I have a dataframe like this #Test dataframe import pandas as pd import numpy as np #Build df titles = {'Title': ['title1', 'cat', 'dog']} references = {'References': [['donkey','chicken'],['title1','dog'],['bird','snake']]} df = pd.DataFrame({'Title': ['title1', 'cat', 'dog'], 'References': [['donkey','chicken'],['tit...
# Explode to one reference per row references = df["References"].explode() # Combine existing titles with new title from References titles = pd.concat([df["Title"], references]).unique() # Assign each title an index number mappings = {t: i + 1 for i, t in enumerate(titles)} # Map the reference to the index number and c...
4
2
74,079,778
2022-10-15
https://stackoverflow.com/questions/74079778/bin-sh-1-crond-not-found-when-cron-already-installed
I have a dockerfile FROM python:3.9.12-bullseye COPY . . RUN apt-get update -y RUN apt-get install cron -y RUN crontab crontab CMD python task.py && crond -f And a crontab * * * * * python /task.py I keep running into the error /bin/sh: 1: crond: not found when I run the docker file. Docker build is fine. Anyone know...
If you have a look for debian series cron.service, you could see next: [Unit] Description=Regular background program processing daemon Documentation=man:cron(8) After=remote-fs.target nss-user-lookup.target [Service] EnvironmentFile=-/etc/default/cron ExecStart=/usr/sbin/cron -f $EXTRA_OPTS IgnoreSIGPIPE=false KillMode...
3
6
74,074,484
2022-10-14
https://stackoverflow.com/questions/74074484/pandas-read-json-skip-first-lines-of-the-file
Say I have a json file with lines of data like this : file.json : {'ID':'098656', 'query':'query_file.txt'} {'A':1, 'B':2} {'A':3, 'B':6} {'A':0, 'B':4} ... where the first line is just explanations about the given file and how it was created. I would like to open it with something like : import pandas as pd df = pd.r...
We can pass into pandas.read_json a file handler as well. If before that we read part of the data, then only the rest will be converted to DataFrame. def read_json(file, skiprows=None): with open(file) as f: if skiprows: f.readlines(skiprows) df = pd.read_json(f, lines=True) return df
3
3
74,056,454
2022-10-13
https://stackoverflow.com/questions/74056454/defining-a-quadratic-function-with-numpy-meshgrid
Let's consider a function of two variables f(x1, x2) , where x1 spans over a vector v1 and x2 spans over a vector v2. If f(x1, x2) = np.exp(x1 + x2), we can represent this function in Python as a matrix by means of the command numpy.meshgrid like this: xx, yy = numpy.meshgrid(v1, v2) M = numpy.exp(xx + yy) This way, M...
def quad(x, y, q): """Return an array A of a shape (len(x), len(y)) with values A[i,j] = [x[i],y[j]] @ q @ [x[i],y[j]] x, y: 1d arrays, q: an array of shape (2,2)""" from numpy import array, meshgrid, einsum a = array(meshgrid(x, y)).transpose() return einsum('ijk,kn,ijn->ij', a, q, a) Notes meshgrid produces 2 arrays...
3
3
74,069,659
2022-10-14
https://stackoverflow.com/questions/74069659/conditional-types-with-mypy
I have the following code snippet: from typing import TypedDict class Super(TypedDict): foo: int class SubA(Super): bar: int class SubB(Super): zap: int def print_props(inp: Super, key: str): print(inp[key]) When I call the method print_props with either an instance of SubA or SubB it would be valid as they are sub ty...
Overloads with Literal could well do it, though I do wonder if a different design would be better. I'm a bit concerned about the increasingly frequent usage of overload and Literal in SO answers. They both suggest a design smell to me @overload def printMyProps(input: SubA, key: Literal["foo", "bar"]) -> None: ... @ove...
4
5
74,067,547
2022-10-14
https://stackoverflow.com/questions/74067547/could-not-find-poetry-1-2-2-linux-sha256sum-file
I am trying to update my version of Poetry to 1.2.*, but when running poetry self update I get the error Could not find poetry-1.2.2-linux.sha256sum file... I can't figure out how to try and update Poetry to an earlier version for which hopefully the checksum exists.
You are trying to update a Poetry that was installed with the get-poetry.py installer. This installer is deprecated for more than a year now. Updating via poetry self update is not possible for these installation. Uninstall Poetry and reinstall with the recommended installer. More information are available at https://p...
14
18
74,060,371
2022-10-13
https://stackoverflow.com/questions/74060371/gym-super-mario-bros-7-3-0-valueerror-not-enough-values-to-unpack-expected
I'm running Python3 (3.8.10) and am attempting a tutorial with the gym_super_mario_bros (7.3.0) and nes_py libraries. I followed various tutorials code and tried on multiple computers but get an error. I have tried to adjust some of the parameters like adding a 'truncated' variable to the list of values to return. As t...
Move to "...../python3.8/site-packages/gym/wrappers/time_limit.py".And delete all "truncated"
4
5
74,062,326
2022-10-13
https://stackoverflow.com/questions/74062326/should-an-application-check-for-uuid-v4-duplicated
I work in my app with a database. This database stores data with a randomly generated ID of the type UUID v4. Now I'm wondering, how common is it for a big (let's be optimistic :D ) app with many users to have a duplicate ID? The ID is the primary key in the SQL database so it could only crash one API call. Is it a cle...
This shouldn't be a problem in practice due to the very low probability of collisions. See the Wikipedia article on UUID4 collision For example, the number of random version-4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion This number is equivalent to ...
3
3
74,054,138
2022-10-13
https://stackoverflow.com/questions/74054138/fastest-way-to-expand-the-values-of-a-numpy-matrix-in-diagonal-blocks
I'm searching for a fast way for resize the matrix in a special way, without using for-loops: I have a squared Matrix: matrix = [[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]] and my purpose is to resize it 3 (or n) times, where the values are diagonal blocks in the matrix an...
IMO, it is inappropriate to reject the for loop blindly. Here I provide a solution without the for loop. When n is small, its performance is better than that of @MichaelSzczesny and @SalvatoreDanieleBianco solutions: def mechanic(mat, n): ar = np.zeros((*mat.shape, n * n), mat.dtype) ar[..., ::n + 1] = mat[..., None] r...
4
4
74,054,217
2022-10-13
https://stackoverflow.com/questions/74054217/how-do-you-put-the-x-axis-labels-on-the-top-of-the-heatmap-created-with-seaborn
I have created a heatmap using the seaborn and matplotlib package in python, and while it is perfectly suited for my current needs, I really would prefer to have the labels on the x-axis of the heatmap to be placed at the top of the plot, rather than at the bottom (which seems to be its default). So an abridged form of...
Ok, so I did a bit more research, and it turns out you can add the follow code with the seaborn approach: plt.tick_params(axis='both', which='major', labelsize=10, labelbottom = False, bottom=False, top = False, labeltop=True)
3
6
74,052,308
2022-10-13
https://stackoverflow.com/questions/74052308/how-to-replace-certain-keys-and-values-of-a-json-with-list-in-python
{'Functions': {0: {'Function-1': {0: {'Function': 'dd', 'Function2': 'd3'}}}}} From the above json i would like to remove the {0: } item and add a list in that place so that the value is enclosed in a list like shown in Desired Output. Please note the above json is an put of a jsondiff. Desired output {"Functions":[{"...
Code: from ndicts.ndicts import NestedDict STEP 1// Convert nested dict to flat dict fd = list(pd.json_normalize(Mydict).T.to_dict().values())[0] #Output {'Functions.0.Function-1.0.Function': 'dd', 'Functions.0.Function-1.0.Function2': 'd3'} STEP 2// Convert flat dictionary to nested by split/removing the 0 nd = Nest...
3
2