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
76,711,533
2023-7-18
https://stackoverflow.com/questions/76711533/how-to-use-the-python-openai-client-with-both-azure-and-openai-at-the-same-time
OpenAI offers a Python client, currently in version 0.27.8, which supports both Azure and OpenAI. Here are examples of how to use it to call the ChatCompletion for each provider: # openai_chatcompletion.py """Test OpenAI's ChatCompletion endpoint""" import os import openai import dotenv dotenv.load_dotenv() openai.api_...
Each API in the library accepts per-method overrides for the configuration options. If you want to access the Azure API for chat completions, you can explicitly pass in your Azure config. For the transcribe endpoint, you can explicitly pass the OpenAI config. For example: import os import openai api_response = openai.C...
3
6
76,715,807
2023-7-18
https://stackoverflow.com/questions/76715807/seeking-optimization-for-computation-heavy-mathematical-function-in-numpy
I've recently been developing a Python script that implements a specific mathematical function, which is shown in the figure below where indexation is periodic and 1 <= j <= n. The function is relatively complex and is inspired by a previous question. The main purpose of the code is to evaluate the mathematical functi...
Convolutions The most important thing to notice, I think, is that this is more-or-less a convolution: exp_1 = np.exp(-np.sum(weights_1[None, :] * x_matrix, axis=1)/v) If you look at the values of x_matrix, they are the x values for x in position -1, 0, 1, ... around each x value. Then it's being multiplied by weights....
2
5
76,704,097
2023-7-17
https://stackoverflow.com/questions/76704097/pytube-exceptions-regexmatcherror-get-transform-object-could-not-find-match-fo
While downloading a video using the PyTube library using this code: yt.streams.get_highest_resolution().download("PATH", f"PATH.mp4") I get an error: raise RegexMatchError(caller="get_transform_object", pattern=pattern) pytube.exceptions.RegexMatchError: get_transform_object: could not find match for var for={(.*?)}; ...
Here is a quick fix in the meantime as the library makes an update. -> In file .venv/lib/python3.10/site-packages/pytube/cipher.py I am using python 3.10 and my virtual environment is called .venv You just have to find the library pytube and go to the file cipher.py and edit its source code for now. -> Find the method ...
5
10
76,678,629
2023-7-13
https://stackoverflow.com/questions/76678629/how-do-i-terminate-the-script-once-q-is-pressed
Below is a complete script I am trying to automate the process of pinging multiple routers and to do that every 2 hrs but I also want the ability to terminate it at any given time. def start(): for file_name in file_list: unrechable = [] rechable = [] print("Processing:"+file_name,end="\n") open_file(file_name, rechabl...
I added a queue to a thread that listens to any keyboard interrupts and once the condition is met adds it to the queue. def qu1(): while(True): if keyboard.is_pressed("q"): qu_main.put("q") print("added q") break else: pass return Next I put my sleep timer in a loop. I wanted my script to execute in 2hr intervals ther...
2
0
76,686,267
2023-7-14
https://stackoverflow.com/questions/76686267/what-is-the-new-way-to-declare-mongo-objectid-with-pydantic-v2-0
This week, I started working with MongoDB and Flask, so I found a helpful article on how to use them together by using PyDantic library to define MongoDB's models. However, the article is somewhat outdated, mostly could be updated to new PyDantic's version, but the problem is that the ObjectId is a third party field an...
Generally best to ask questions like this on pydantic's GitHub discussions. Your solution is pretty close, I think you just have the wrong core schema. I think our documentation on using custom types via Annotated cover this fairly well, but just to help you, here is a working implementation: from typing import Annotat...
17
12
76,701,617
2023-7-17
https://stackoverflow.com/questions/76701617/the-following-arguments-are-not-supported-with-the-native-keras-format-opti
I am building a Keras deep learning Algorithm on dogs vs cats dataset. I am able to run my code in colab. But in Jupyter lab I am getting this error. The following argument(s) are not supported with the native Keras format: ['options'] Below is the code: import os import shutil import pathlib original_dir = pathlib.Pa...
As I mentioned in the comments, there seems to be a weird behaviour related to keras saving and also versioning of TF/Keras. I could replicate your error when running TF/Keras with version 2.13 (newest right now) on colab. Standard install on colab is 2.12, where the error doesn't come up. So one solution would be to d...
9
15
76,717,109
2023-7-18
https://stackoverflow.com/questions/76717109/how-to-optimize-a-for-loop-in-python-that-references-values-in-a-data-frame-that
The code below first updates the signal column with a 1 or -1 if certain conditions are met, otherwise the signal column is set to 0. In the for-loop, the signal column gets updated to the previous signal value if certain conditions are met. I would like to replace the for-loop with a faster solution that is still able...
The fastest way to manipulate data in a dataframe is through vectorization. Let me explain using below code for 1,000,000 records: import pandas as pd import numpy as np from time import time df = pd.DataFrame({ 'ind_1': np.random.randint(-1, 2, size=(1000000, )), 'ind_2': np.random.randint(0, 101, size=(1000000, )) })...
3
1
76,716,898
2023-7-18
https://stackoverflow.com/questions/76716898/is-python-dict-insertion-order-preserved-after-deleting-elements
This StackOverflow answer says python dicts keep insertion order of keys as of python 3.7. The comments to that answer discuss the implementation details of what happens when a key is deleted. I'd like to know: what does the language spec guarantee about key order in the face of deletes (preferably with a link)? Based ...
The language guarantees that undeleted elements will remain in the same order after a key is deleted. The Python language reference states (emphasis mine): Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. Replacing an existing...
4
3
76,713,315
2023-7-18
https://stackoverflow.com/questions/76713315/passing-nested-tuple-to-values-in-psycopg3
I'm trying to updates some psycopg2 code to psycopg3. I'm trying to do a selection based on a set of values passed from Python (joining with an existing table). Without the join, a simplified example is: with connection.cursor() as cur: sql = "WITH sources (a,b,c) AS (VALUES %s) SELECT a,b+c FROM sources;" data = (('hi...
One way to do it: import psycopg con = psycopg.connect("dbname=test host=localhost user=postgres") with con.cursor() as cur: rs = [] sql = "SELECT %s, %s + %s" data = [('hi',2,0), ('ho',5,2)] cur.executemany(sql, data, returning=True ) while True: rs.append(cur.fetchone()) if not cur.nextset(): break print(rs) [('hi', ...
3
2
76,713,531
2023-7-18
https://stackoverflow.com/questions/76713531/create-a-list-in-a-list-from-a-separate-list-which-contains-the-intervals-as-an
As the title suggests, I would like to create a list in a list from a second list. For this I prepared the following example: list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] list2 = [3, 4, 2, 6] solution = [[1, 2, 3], [4, 5, 6, 7], [8, 9], [10, 11, 12, 13, 14, 15]] I have already found a solution, but I find it very cum...
One possible solution is using itertools.islice: from itertools import islice list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] list2 = [3, 4, 2, 6] out = iter(list1) out = [list(islice(out, v)) for v in list2] print(out) Prints: [[1, 2, 3], [4, 5, 6, 7], [8, 9], [10, 11, 12, 13, 14, 15]] Another using := ...
2
6
76,712,042
2023-7-18
https://stackoverflow.com/questions/76712042/how-to-properly-execute-a-convert-command-using-python
I'm new to Python, so, I'm sorry if my question may seems dumb. I'm trying to convert GIF files to APNG using this tool. As it says in the bottom of this page, to convert GIF to APNG you must execute the following command: $ vertopal convert GIF_INPUT_FILE --to apng It works fine when I run the command in the terminal...
Let's talk about your command: "vertopal convert funny cat.gif --to apng" The name "funny cat.gif" has space in it. subprocess calls shlex.split() to split this string into a list of string tokens and the result is: >>> shlex.split("vertopal convert funny cat.gif --to apng") ['vertopal', 'convert', 'funny', 'cat.gif',...
3
3
76,712,736
2023-7-18
https://stackoverflow.com/questions/76712736/why-cant-i-name-a-module-array
Given the following directory structure: app/ └── array/ ├── test/ │ ├── __init__.py │ └── test_array.py ├── __init__.py └── functions.py When I run pytest from the app directory, I get the following error: ERROR collecting array/test/test_array.py _______________________________________ ImportError while importing te...
Because it collides with the stdlib module of the same name.
3
4
76,710,726
2023-7-18
https://stackoverflow.com/questions/76710726/cannot-run-jupyter-notebook-on-ubuntu-22-04
I have Ubuntu 22.04 with python 3.10. When I try to open jupyter notebook from terminal this error occurrs: Traceback (most recent call last): File "/home/anaconda3/lib/python3.10/site-packages/notebook/services/sessions/sessionmanager.py", line 9, in <module> import sqlite3 File "/home/anaconda3/lib/python3.10/sqlite3...
It looks like you performed a manual installation of Jupyter (and required dependencies) directly in your home directory. I'm assuming /home/anaconda3/ is your home directory, and anaconda3 is just a badly chosen name. Rename the lib subdirectory: mv lib lib_aside You might want to do something similar for include/ or...
3
1
76,710,614
2023-7-18
https://stackoverflow.com/questions/76710614/dag-import-error-attributeerror-taskdecorator-object-has-no-attribute-upd
I'm facing an issue which my dag cannot be imported, but cannot figure out why: from airflow.sensors.sql import SqlSensor import pendulum from airflow.decorators import task,dag @dag( dag_id = "database_monitor", schedule_interval = '*/10 * * * *', start_date=pendulum.datetime(2023, 7, 16, 21,0,tz="UTC"), catchup=False...
You need to call the Python task flow operator i.e change check_db_alive >> alert_of_db_inrecovery to check_db_alive >> alert_of_db_inrecovery() check correct code from airflow.sensors.sql import SqlSensor import pendulum from airflow.decorators import task, dag @dag( dag_id="database_monitor", schedule_interval='*/10 ...
6
15
76,700,313
2023-7-16
https://stackoverflow.com/questions/76700313/nicegui-tables-how-to-use-selection-and-click-events
I want to either click or select a single row in a table, retrieve the corresponding row's data, and then process it further with handlers. But the documentation is slim at the moment, and I have never used Quasar or Vue.js before. Here's my attempt: from nicegui import ui columns = [ {'name': 'title', 'label': 'Title'...
Here is a working example table: table = ui.table(title='Example table', columns=columns, rows=rows, row_key='title', pagination=5, selection='single') table.add_slot('body-cell-title', r'<td><a :href="props.row.url">{{ props.row.title }}</a></td>') table.on('rowClick', lambda e: print(e.args)) It looks like your body...
3
3
76,703,878
2023-7-17
https://stackoverflow.com/questions/76703878/swap-columns-from-multidimensional-array
I have this array: my_array = np.arange(1216800).reshape(2, 100, 78, 78) The shape now is: (2, 100, 78, 78) and I want to reorder to : (100, 78, 78, 2). I tried something like: my_array[:, :, 2, :], my_array[:, :, :, 3] = my_array[:, :, :, 3], my_array[:, :, 2, :].copy() to swap first those columns, but I am receivin...
Here is the code that you want: import numpy as np my_array = np.arange(1216800).reshape(2, 100, 78, 78) reordered_array = np.transpose(my_array, (1, 2, 3, 0)) print(reordered_array.shape) # Output: (100, 78, 78, 2)
2
3
76,705,388
2023-7-17
https://stackoverflow.com/questions/76705388/python-telegram-bot-send-message-with-buttons
i'd like to send a message through telegram bot with buttons. Once button is pressed i need to know which button was that and then change the text that came with the button. I've almost found out how to do things separately but i can't unite them. To send a message with buttons i need either to write /start or have to ...
If you want to attach buttons to the message sent in send, you can just use the corresponding parameter of send_message for that. Not that message.reply_text as used in start is just a shortcut for that method. Moreover, you don't need to manually initialize a bot in send and to manually run that method via asyncio.run...
2
5
76,702,175
2023-7-17
https://stackoverflow.com/questions/76702175/using-scipy-interpolate-in-python-i-want-to-erase-certain-values-and-interpolat
In my code, I have certain values like my_list = [725.998474, 0.0, 0.0, 0.0, 0.0, 789.507934, 792.585388, 801.612916, 799.38916, 809.280518, 809.186036, 811.899414, .... , 412.314528] In my code, I want to interpolate the points where the list is 0.0 because they are outliers. But it is not working as interpolation on...
Using the data you provided, we can create a "cleaned" list of the x and y data using numpy. You said that the values equal to 0 are the outliers, but checking equality with floating point numbers can lead to issues, so I used np.isclose. With the outliers removed, you can interpolate the cleaned data. import numpy as ...
2
5
76,705,656
2023-7-17
https://stackoverflow.com/questions/76705656/python-refer-to-parent-class-from-static-class
Is it possible to access the parent class name within a static class? For example, how to I print the parent class name in the bar method below? class Static: def bar(self): parent_name = ??? print(parent_name) class A: object = Static() def foo(self): A.object.bar() class B: object = Static() def foo(self): B.object.b...
You're looking for the __set_name__ method. It is called on every static attribute of a class when the class is finished constructing. One of the parameters is the "owner" class (A or B), so all you need is to store that reference. Note that this requires a separate Static instance for each parent class, but you're doi...
2
3
76,704,752
2023-7-17
https://stackoverflow.com/questions/76704752/merging-records-based-on-consecutive-dates-in-python
I want to merge records of my dataframe if dates are same.Here in the below example I want to merge date (13,14,15), (25,26), (30,31) together as there are continuous dates. I want to break the merging of record if there is any single day break. cust date description CUST123 2020-06-13 observed increased loss rate CUS...
In order to merge records of a dataframe if dates are same, you could do: merged_df = df.groupby(['cust', 'date'])['description'].apply(' '.join).reset_index() which outputs: cust date description 0 CUST123 2020-06-13 observed increased loss rate cut performed job 1 CUST123 2020-06-14 working tight area 2 CUST123 2020...
2
3
76,703,126
2023-7-17
https://stackoverflow.com/questions/76703126/selecting-all-rows-which-contain-values-greater-than-a-percentage-of-average
I have a DataFrame, which have 3 numeric columns A,B,C. I need to extract only those rows where values in all these 3 columns A,B,C is more than 40% of their row average. df = pd.DataFrame([['AA',10,8,12],['BB',10,2,18],['CC',10,6,14]], columns=['ID','A', 'B', 'C']) print(df) ID A B C 0 AA 10 8 12 1 BB 10 2 18 2 CC 10 ...
Another possible solution: a = df[['A', 'B', 'C']].values df[(a > 0.4*(a.mean(1)[:, None])).all(1)] Output: ID A B C 0 AA 10 8 12 2 CC 10 6 14
3
1
76,702,207
2023-7-17
https://stackoverflow.com/questions/76702207/two-level-sorting-in-a-nested-tuple-of-nested-lists-in-python
I have a deeply nested tuple of nested lists as follows: ip = (array([[[ 50, 73]], [[ 50, 107]], [[ 55, 108]], [[ 55, 121]], [[978, 87]], [[977, 86]], [[977, 73]]], dtype=int32), array([[[ 669, 3]], [[ 668, 4]], [[ 667, 4]], [[1033, 71]], [[1035, 69]], [[1035, 4]], [[ 848, 4]], [[ 847, 3]], [[ 813, 3]], [[ 718, 4]], [[...
You can use sorted on your tuple and specify the item using the key parameter First sort ip = sorted(ip, key=lambda x: x[0][0][0]) print(ip) [array([[[ 17, 3]], [[ 16, 4]], [[ 0, 4]], [[ 0, 49]], [[197, 49]], [[197, 8]], [[ 84, 4]], [[ 83, 3]]]), array([[[ 50, 73]], [[ 50, 107]], [[ 55, 108]], [[ 55, 121]], [[978, 87]]...
3
2
76,700,089
2023-7-16
https://stackoverflow.com/questions/76700089/adding-a-column-in-a-dataframe-based-on-thresholds-and-size-of-group
I have a DataFrame with x and y coordinates, where the index represents a timestamp. We may assume it is an object that moves every timestep. The distance between consecutive timestamps is expected to increase. However, if the distance doesn't increase by a certain threshold, I consider it a potential "waiting" positio...
Try: # fill the first NaN df['condition_fulfilled'] = df['condition_fulfilled'].bfill() tmp = (df['condition_fulfilled'] != df['condition_fulfilled'].shift()).cumsum() df['status'] = df.groupby(tmp)['condition_fulfilled'].transform(lambda x: 'waiting' if x.all() and len(x) >= 3 else 'moving') print(df) Prints: x y di...
3
1
76,698,632
2023-7-16
https://stackoverflow.com/questions/76698632/how-to-access-pep-526-local-variable-annotations-in-python
I made a variable annotation of a local variable: def a(): x: int = 1 But the annotations dict is empty: > a.__annotations__ {} Same when I use inspect.get_annotations() or typing.get_type_hints(). How can I access the annotation? Is this feature implemented at all? I'm using Python 3.10.7.
OK, I found a way. As long as a function has a fqdn, its source code can be parsed and local annotations show there. import ast, inspect def a(): k: int = 1 print(ast.dump(ast.parse(inspect.getsource(a)))) gives Module(body=[FunctionDef(name='a', args=arguments(posonlyargs=[], args=[], kwonlyargs=[], kw_defaults=[], ...
2
2
76,697,475
2023-7-16
https://stackoverflow.com/questions/76697475/how-do-i-safely-handle-asyncio-event-loop-handling-with-telethon-and-telegram-bo
I'm creating a simple telegram bot in which I'm making use of the telegram bot and telethon api(as I want to retrieve all members in a chat and with the bot api, i can't do this unless all users are admins). I'm able to currently print out the users in a chat successfully. However when I terminate the script, I keep ge...
telegram package by default is evasive from some aspects, so you need to specify some stuff manually, you have couple issues: main one is run_polling' close_loop not being set to False, it will close the loop on KeyboardInterrupt too and shutdown without giving chance for telethon to disconnect since they share the sa...
2
3
76,692,916
2023-7-15
https://stackoverflow.com/questions/76692916/in-nixos-what-is-the-difference-between-installing-from-pkgs-or-python311packag
I had an issue when I installed Yapf this way: environment.systemPackages = with pkgs; [ (python311.withPackages(ps: with ps; [ toml python-lsp-server pyls-isort flake8 ])) pkgs.yapf ]; This gave me the error: $ yapf autoapp.py yapf: toml package is needed for using pyproject.toml as a configuration file And I solve...
These are the same package - you can see this by checking the source links from the package search page. Adding it to withPackages links the Python package with the interpreter, making it possible to run things like python -m yapf … or import yapf within the Python REPL. If you simply list pkgs.yapf at the top level, t...
3
2
76,693,948
2023-7-15
https://stackoverflow.com/questions/76693948/new-version-selenium-desired-capabilities-deprecate
I want to use ChromeDriver Performance Log to monitor network traffic. I'm looking for some usage like this: capabilities = DesiredCapabilities.CHROME # enable performance log capabilities['loggingPrefs'] = {"performance","all"} self.driver = webdriver.Chrome( desired_capabilities=capabilities ) # get performance log l...
DesiredCapabilities earlier deprecated, is now completely removed in Selenium v4.10. Solution You have to use an instance of ChromeOptions and the set_capability() method as follows: from selenium.webdriver.chrome.options import Options options = Options() options.set_capability('goog:loggingPrefs', {'performance': 'A...
2
3
76,694,215
2023-7-15
https://stackoverflow.com/questions/76694215/python-type-casting-when-preallocating-list
This question might already have an answer, so please guide me to one if you know any. I couldn't find one myself, though this question feels like a common one. So, consider the following pattern: arr = [None] * n for i in range(n): # do some computations # ... # even more computations arr[i] = MyClass(some_computed_va...
You can lie to your type checker when you first initialize arr to "trick" it that arr never contains None entries. For the purposes of static type checking, arr will be a list[MyClass], even though it briefly contains None entries at runtime. You of course assume responsibility for making sure that this assumption play...
2
3
76,693,541
2023-7-15
https://stackoverflow.com/questions/76693541/why-does-numpy-return-a-different-type-for-arrays-and-scalars
I have some whole numbers stored in np.float64 arrays and scalars, which I want to convert to native Python int. This is my attempt: import numpy as np a = np.array([1, 2, 3], dtype=np.float64) b = np.float64(4) def float_to_int(x): x_object = x.astype(object) return np.floor(x_object) # Array inputs are converted to i...
I believe since Numpy and python data types are related but inherently different, you would have to explicitly convert it to python data type. One way to do it would be: a = a.astype(np.int64).tolist() b = int(b) or alternatively a = a.astype(np.int64).astype(object) b = b.astype(np.int64).astype(object) When you con...
2
1
76,690,286
2023-7-14
https://stackoverflow.com/questions/76690286/how-to-convert-frames-from-directory-to-video-without-adding-the-first-frame-eve
I am fairly new to this platform. I will do my best to be clear as possible. My goal is to convert frames from my directory into a video. For some reason, it is including the first frame in every 15 fps. Here is my code below: import cv2 import glob from pathlib import Path def play_frames(frames_dir, fps, output_video...
sorted(), when given a list of strings, sorts them as strings, not as numbers. The following demonstrates why this is a problem: >>> ', '.join(sorted([str(i) for i in range(67)])) '0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 4, 40, ...
3
2
76,684,195
2023-7-14
https://stackoverflow.com/questions/76684195/how-to-best-filter-exceptions-on-their-cause-or-context
Given a base exception type: class MyModuleError(Exception): pass Suppose we have code that explicitly raises it, using exception chaining: def foo(): try: #some code except (ZeroDivisionError, OSError) as e: raise MyModuleError from e Now, in the calling code... try: foo() except MyModuleError as e: # Now what? how...
The re-raising is not recommended. In general, it is not idiomatic to raise something deliberately so that it can be immediately caught1. It's also less performant (exception handling can involve quite a bit of overhead when the exception is actually raised), and creates a reference cycle between the exception object a...
3
3
76,689,402
2023-7-14
https://stackoverflow.com/questions/76689402/use-literal-style-for-just-multiline-strings-in-ruamel-yaml
I would like to have a custom ruamel.yaml dumper that uses Literal style for all multiline strings and the default style otherwise. For example: import sys import ruamel.yaml data = {"a": "hello", "b": "hello\nthere\nworld"} print("Default style") yaml = ruamel.yaml.YAML() yaml.dump(data, sys.stdout) print() print("sty...
There are multiple ways to achieve what you want. If you have control over building up the data structure, it is often easiest to add a LiteralScalarString if appropriate: import sys import ruamel.yaml def lim(s): # literal if multi-line if '\n' in s: return ruamel.yaml.scalarstring.LiteralScalarString(s) return s data...
2
3
76,689,146
2023-7-14
https://stackoverflow.com/questions/76689146/pandas-read-csv-ignore-first-cell
I have .csv file like this: Str; Int; Flt A; 123; 0.1 B; 456; 0.2 C; 789; 0.3 I want to get DataFrame like this Int; Flt A; 123; 0.1 B; 456; 0.2 C; 789; 0.3 I read csv like this df = pd.read_csv('data.csv', index_col=0, sep=";") And the problem is that I can't use df.loc["A", "Int"] to get cell value. If I drop Str...
You have a whitespace issue. import io import pandas as pd fp = io.StringIO(''' Str; Int; Flt A; 123; 0.1 B; 456; 0.2 C; 789; 0.3 '''.strip()) df = pd.read_csv(fp, index_col=0, sep=";") print("Index: ", df.index) print("Columns: ", df.columns) # Now look at the whitespace: print(df.loc[' A',' Int']) Yields: Index: Ind...
2
3
76,686,704
2023-7-14
https://stackoverflow.com/questions/76686704/numpy-array-bool-operation-slow
I started profiling my application and I tested to following code: a = np.random.random((100000,)) def get_first_index(value, arr): firstIndex = np.argmax(arr > value) if firstIndex <= 0: raise Exception('No index found') return firstIndex for i in range(0, 1000): get_first_index(0.5, a) It just returns me the first i...
The reason your approach is slow is that all elements of arr are compared under all circumstances, even if the first element of arr is greater than value. While numpy does not have an API optimized for this kind of processing, Numba can be used instead, which can be easily implemented as follows. import timeit import n...
2
5
76,685,996
2023-7-14
https://stackoverflow.com/questions/76685996/cant-open-lib-odbc-driver-17-for-sql-server-file-not-found-0-sqldriverco
I have searched a lot for the solution but still struggling with this problem. I'm trying to connect to a SQL Server instance running on 127.0.0.1:1433. However, I'm getting a sqlalchemy.exc.DBAPIError with the following error message: sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('01000', "[01000] [unixODBC][Driver Manag...
Solved by these steps: 1- install ODBC driver on local machine using this script for ubuntu official doc: if ! [[ "18.04 20.04 22.04 22.10" == *"$(lsb_release -rs)"* ]]; then echo "Ubuntu $(lsb_release -rs) is not currently supported."; exit; fi sudo su curl https://packages.microsoft.com/keys/microsoft.asc | apt-key a...
10
7
76,683,407
2023-7-13
https://stackoverflow.com/questions/76683407/how-to-pass-multiple-parameters-to-insert-into-values-using-sqlalchemy-conne
The following is valid SQL for PostgreSQL. INSERT INTO schema.table (id, letter) VALUES (1, 'a'), (2, 'b'), ... I would like to execute a similar, parameterized statement using SQLAlchemy. I am using SQLAlchemy 1.4* Connection.execute(), but I do not have access to the table mapper class (ORM model). The following doe...
You can use the following, you were almost there, you just had to change the insert query and make the binding as a list of dicts. As seen in the docs and slightly modified for your use-case. statement: str = "INSERT INTO schema.table (id, letter) VALUES (:id, :letter)" values = ( (1, "a"), (2, "b"), ) values = [{'id':...
2
3
76,680,977
2023-7-13
https://stackoverflow.com/questions/76680977/using-enum-values-as-type-variables-without-using-literal
I'm trying to represent physical dimensions (length, time, temperature, ...), and cannot find a nice way to do so, that is compatible with type hinting and generics. Ideally, I want to be able to define an Enum whose names are types themselves (a metaenum ?): from enum import Enum class Dim(Enum): TIME = "t" MASS = "m"...
Is there a construct as simple as Enum, but to make types instead of values? Yes, the metaclass. A metaclass makes types. It is simple in terms of usage i.e. creation of new types, but you do need to put in some more work to set it up properly. Semantically, you could think of the Dimension is a type and Time, Distan...
4
2
76,679,508
2023-7-13
https://stackoverflow.com/questions/76679508/how-to-set-multiple-values-in-pandas-in-column-of-dtype-np-array
I have a column of Numpy arrays in Pandas, something like: col1 col2 col3 0 1 a None 1 2 b [2, 4] 2 3 c None The [2, 4] is really np.array([2, 4]). Now I need to impute the missing values, and I have a list of arrays for that. For example: vals_to_impute = [np.array([1, 2]), np.array([1, 4])] I tried: mask = col3.is...
I managed to do it using pd.Series instead of list. I also had to input an index to this Series so that the insertion is correct. Maybe it can be done easier. df = pd.DataFrame({ "col1": [1, 2, 3], "col2": ["a", "b", "c"], "col3": [None, np.array([2, 4]), None] }) mask = df["col3"].isna() vals_to_impute = pd.Series( [n...
2
3
76,672,343
2023-7-12
https://stackoverflow.com/questions/76672343/openai-api-chatcompletion-and-completion-give-totally-different-answers-with-sa
I'm exploring the usage of different prompts on gpt3.5-turbo. Investigating over the differences between "ChatCompletion" and "Completion", some references say that they should be more or less the same, for example: https://platform.openai.com/docs/guides/gpt/chat-completions-vs-completions Other sources say, as expect...
I actually found the answer by chance reviewing some old notebooks. It's all on the hidden tags, or as I found out now, the Chat Markup Language (ChatML): https://github.com/openai/openai-python/blob/main/chatml.md This prompt with the Completion api now returns almost the same answer as the ChatCompletion: prompt = ""...
3
6
76,677,507
2023-7-13
https://stackoverflow.com/questions/76677507/f-string-not-formatting-floats-into-an-integer
Usually, I use % string formatting. But, as I discovered f-string is the new way of string formatting and it is faster as well, I want to use it. But, I am facing a problem when formatting a float into an integer using f-string. Following is what I have tried: Using % string formatting '%5d'%1223 # yields --> ' 1223' ...
The reason for this error is that the format specifier d is specifically for formatting integers, not floats.You can use the general format specifier f instead. f'{int(1223.555):5d}'
5
5
76,674,718
2023-7-12
https://stackoverflow.com/questions/76674718/how-to-efficiently-append-same-element-n-times-to-a-non-empty-list
In Python, it's known that the most efficient way to create a list with n repetitions of the same element (let's say the string 's') is by using list multiplication, as shown below: lst = ['s'] * 1000 However, when the list is non-empty initially, what would be the most optimal method to append the same element n time...
I propose: def addition(N): lst = [1, 2, 3] return lst+['s']*N I profiled the approaches: import itertools from performance_measurement import run_performance_comparison def method1(N): lst = [1, 2, 3] for _ in range(N): lst.append("s") return lst def method2(N): lst = [1, 2, 3] lst.extend(["s"] * N) return lst def ge...
4
2
76,673,985
2023-7-12
https://stackoverflow.com/questions/76673985/how-to-remove-a-tuple-in-an-integer-tuple-if-its-last-element-is-0-using-pyt
I have the following code to create a tuple contains multiple tuples with integer pairs: iterable = ( tuple(zip([0, 1, 2], _)) for _ in product(range(9), repeat=3) ) next(iterable) # First element is not needed print(list(iterable)) # This code produces: [((0, 0), (1, 0), (2, 1)), ... , ((0, 8), (1, 8), (2, 8))] But I...
Use filter() to remove the elements ending in 0 from the result of zip(). iterable = ( tuple(filter(lambda x: x[-1] != 0, zip([0, 1, 2], _))) for _ in product(range(9), repeat=3) )
4
5
76,673,056
2023-7-12
https://stackoverflow.com/questions/76673056/differences-in-type-and-naming-conventions-for-uml-class-in-different-programmin
Are UML class representations different for each programming language, or do they adhere to a standard? I have conducted extensive research but remain confused. For instance: In Python: set_name(): None In Java: setName(): void In Kotlin: setName(): Unit
There is not one "standard" for UML naming conventions. I would advise you use names similar to what you would use in the programming language you are using. As long as your intended reader understands the material then it is a good convention. Most important is that whatever you choose remains consistent throughout yo...
4
6
76,670,856
2023-7-12
https://stackoverflow.com/questions/76670856/langchain-conversationalretrieval-with-jsonloader
I modified the data loader of this source code https://github.com/techleadhd/chatgpt-retrieval for ConversationalRetrievalChain to accept data as JSON. I created a dummy JSON file and according to the LangChain documentation, it fits JSON structure as described in the document. { "reviews": [ {"text": "Great hotel, exc...
In ConversationalRetrievalChain , search is setup to default 4, refer top_k_docs_for_context: int = 4 in ../langchain/chains/conversational_retrieval/base.py . That makes sense as you don't want to send all the vectors to LLM model(associated cost too). Based on the usecase, you can change the default to more managea...
4
6
76,670,562
2023-7-12
https://stackoverflow.com/questions/76670562/python-parse-then-put-in-a-dataframe
I have a file with a data like this: ------------------------------ ------------------------------ <TIME:2020-01-01 01:25:10> <TIME:2020-01-01 01:25:10> <TIME:2020-01-01 01:25:10> <TIME:2020-01-01 01:25:10> ------ ++++++ %%RequestHandler DATA1 = 123456 ERROR1 = 500 DATA2 = 56789 ERROR2 = 505 Count = 4 --- I would like...
Another regex approach with pivot: import re # or file.read() out = (pd.DataFrame(re.findall(r'^\s+(\w+)(\d+) = (\d+)', text, flags=re.M)) .pivot(index=1, columns=0, values=2) .rename_axis(index=None, columns=None) ) print(out) Output: DATA ERROR 1 123456 500 2 56789 505 Used input: text = '''-----------------------...
2
2
76,669,711
2023-7-12
https://stackoverflow.com/questions/76669711/how-may-i-instantiate-a-class-of-type-hint-in-python
I am new to python and am coming from C# and java. I want to instantiate a class of the type provided as type hint R as following from typing import (TypeVar, Generic) class BaseParams(object): def __init__(self) -> None: self.name = 'set-in-base-class' class ChildParams(BaseParams): def __init__(self) -> None: super()...
It's still type hints and not type declaration, but I like inspecting weird objects and looking at their insides, so I gave it a go: I tried to inspect Generics in interactive session using dir and also looked for clues in the typing's source. My testing consisted of having one MyGeneric without R specified and one wit...
3
2
76,667,874
2023-7-12
https://stackoverflow.com/questions/76667874/how-can-i-install-python-library-in-chatgpt-code-interpreter
ChatGPT is the newest platform for running Python in a Jupyter-like environment. However the installed libraries are limited. You cannot access the internet too. So, I cannot use pip to install. How can I install a new library?
You can upload a wheel file taken from PyPI, select cp38-manylinux_..._x86_64.whl and upload it. Tell ChatGPT to unzip and move it to /home/sandbox/.local/lib/python3.8/site-packages/ Then you can import and use it normally. Here's an example case where I install DuckDB: https://chat.openai.com/share/fa3df390-8a25-45d3...
6
12
76,664,207
2023-7-11
https://stackoverflow.com/questions/76664207/sending-a-reply-with-gmail-api-python
I created two Gmail accounts and I'm trying to create an e-mail thread between them with the Python Gmail API. I can send e-mails without any issue, but when it comes to replying to each other and creating a thread, it is simply not working : the new message is successfully displaying as the answer of the received emai...
Actually I found why my method did not work ; even if the dict mention a kind of message id : email = {'id': '189462395f418017', 'threadId': '189462395f418017', 'labelIds': ['UNREAD','INBOX'], 'snippet': 'xxx'....} I thought the messageIDcould be taken just by call email['id']. The real messageID is somewhere in the [...
3
5
76,645,870
2023-7-9
https://stackoverflow.com/questions/76645870/importerror-cannot-import-name-gptsimplevectorindex-from-llama-index
I am getting an ImportError while using GPTSimpleVectorIndex from the llama-index library. Have installed the latest version of llama-index library and trying to run it on python 3.9. from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader, LLMPredictor, PromptHelper, ServiceContext ImportError: cannot impo...
Try use GPTVectorStoreIndex instead of GPTSimpleVectorIndex: from llama_index import GPTVectorStoreIndex, ..
6
10
76,624,911
2023-7-6
https://stackoverflow.com/questions/76624911/get-href-link-using-python-playwright
I am trying to extract the link inside a href but all I am finding it is the text inside the element The website code is the following: <div class="item-info-container "> <a href="/imovel/32600863/" role="heading" aria-level="2" class="item-link xh-highlight" title="Apartamento T3 na avenida da Liberdade, São José de S...
Using get_attribute: link = page.locator('.item-info-container ').get_by_role('link').get_attribute('href') More than one locator: link_locators = page.locator('.item-info-container ').get_by_role('link').all() for _ in link_locators: print(_.get_attribute('href'))
8
15
76,643,220
2023-7-8
https://stackoverflow.com/questions/76643220/from-within-a-python-function-how-can-i-tell-if-it-is-being-executed-in-the-gpu
I have a function that sometimes call with Numba as a device function to execute on the GPU and sometimes I call directly from within regular Python on the host: def process(): # perform computation process_cuda = cuda.jit(device=True)(process) sometimes I call process() from directly from Python, and sometimes I invo...
Numba offers a function called cuda.current_context(), if the code is executed from a GPU the function return the current CUDA context otherwise it will return None when run using a CPU So, we can initialize a variable in the process() to check if the code is executed from a CPU or GPU def process(): cuda_context = cud...
4
4
76,666,254
2023-7-11
https://stackoverflow.com/questions/76666254/not-understanding-python-module-in-a-special-case-where-pythonpath-is-set-to-a-s
I encountered an issue I am confused about with Python modules. I have built a minimal working example: $ tree ├── app │ ├── configuration.py │ ├── error_code.py └── test.py app/configuration.py from error_code import ErrorCode class Configuration: def status(self): return self._status def __init__(self): self._status...
It's because the directory that test.py is in is also added to the import path. Which is why this import in test.py worked to begin with: from app.error_code import ErrorCode However, when you do: from error_code import ErrorCode in app/configuration.py it relied on PYTHONPATH=app/. But the original import was cached...
5
2
76,633,836
2023-7-7
https://stackoverflow.com/questions/76633836/what-does-langchain-charactertextsplitters-chunk-size-param-even-do
My default assumption was that the chunk_size parameter would set a ceiling on the size of the chunks/splits that come out of the split_text method, but that's clearly not right: from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter chunk_size = 6 chunk_overlap = 2 c_splitter = Chara...
CharacterTextSplitter will only split on separator (which is '\n\n' by default). chunk_size is the maximum chunk size that will be split if splitting is possible. If a string starts with n characters, has a separator, and has m more characters before the next separator then the first chunk size will be n if chunk_size ...
18
22
76,632,765
2023-7-6
https://stackoverflow.com/questions/76632765/how-to-optimise-an-inequality-join-in-pandas
I have a cross-join-like operation that I have implemented using a for loop. I need to make it fast and preferably elegant. It creates a block entry per day with a date range condition. This works fine for small datasets but completely stalls into a very slow runtime for larger datasets. I know that it can be vectorize...
Looks like some form of inequality join; conditional_join offers an efficient way to handle this. Note that if your dates in block are not overlapping, then pd.IntervalIndex is suitable and performant. # pip install pyjanitor import janitor import pandas as pd # convert date_range to either a named series, or a datafra...
3
2
76,661,046
2023-7-11
https://stackoverflow.com/questions/76661046/can-you-have-a-progress-bar-for-sorting-a-list
I have a list containing ~50k elements of a custom data type (the latter is probably not important for my question) I'm sorting the list using pythons builtin list.sort() method. myList: List[Foo] = ... myList.sort(key=Foo.x) Since the sorting takes a couple of minutes, I would like to have a progress bar for the sort...
Given the interface provided by sort, you don't have too many options for hooking into the actual sorting algoithm. However, if 50K keys is slow, it is most likely that invoking the key function is slow, which is computed prior to the actual sorting. From the docs: The key corresponding to each item in the list is cal...
7
14
76,649,259
2023-7-9
https://stackoverflow.com/questions/76649259/why-is-performing-matrix-multiplication-on-a-pre-transposed-matrix-faster-than-o
Consider the following code in Python, where multiplying a pre-transposed matrix yields faster execution time compared to multiplying a non-transposed matrix: import numpy as np import time # Generate random matrix matrix_size = 1000 matrix = np.random.rand(matrix_size, matrix_size) # Transpose the matrix transposed_ma...
It doesn't seem really obvious on my machine. On 1000 runs. I get these timings (x=non transposed, y=transposed). There are more red dots (under the y=x axis) than blue dots. 685/315 to be more accurate. So, p-value wise, no doubt, that cannot be just random effect. (1000 coins drawn, with 685 heads is a clear anomaly)...
10
12
76,657,664
2023-7-10
https://stackoverflow.com/questions/76657664/pyspark-iterate-rows-and-drop-rows-with-specified-value
I have a dataframe like this Column A Column B Hello [{id: 1000, abbreviatedId: 1, name: “John", planet: “Earth”, solarsystem: “Milky Way”, universe: “this one”, continent: {id: 33, country: “China", Capital: “Bejing”}, otherId: 400, language: “Cantonese”, species: 23409, creature: “Human”}] Bye [{id: 2000, a...
One way is using exists array function. from pyspark.sql.functions import expr from pyspark.sql import Row df = spark.createDataFrame([ [ [ Row(**{"id": 1000, "abbreviatedId": 1, "name": "John", "planet": "Earth", "solarsystem": "Milky Way", "universe": "this one", "continent": Row(**{"id": 33, "country": "China", "Cap...
3
0
76,637,539
2023-7-7
https://stackoverflow.com/questions/76637539/dataprocinstantiateinlineworkflowtemplateoperator-error-in-pysparkjob-template
Hello fellow Stackoverflowers, I have been trying to use the DataprocInstantiateInlineWorkflowTemplateOperator to run a pyspark job. Sadly after following all the documentation I am getting error in Composer ValueError: Protocol message OrderedJob has no "stepID" field. Here is the template that I am using. { "id": "my...
After doing a lot of research and trial and error, I discovered that the keys we provided in the config JSON differ from those described in the Google documentation. While running this from Composer/ Airflow we have to make the keys from camel case to snake case. e.g. stepID --> step_id I am providing the correct JSON ...
4
2
76,651,826
2023-7-10
https://stackoverflow.com/questions/76651826/how-to-chain-multiple-promptnodes-together-in-a-haystack-generativeqapipeline
I'm trying to chain together a simple question answering prompt to an elaboration prompt using Haystack. I had the following code working just fine: import os from haystack.document_stores import InMemoryDocumentStore from haystack.nodes import BM25Retriever from haystack.nodes import PromptNode, PromptTemplate, Answer...
The answer is supposedly to set the "output_variable" parameter of the PromptNode like this: lfqa_node = PromptNode( model_name_or_path="google/flan-t5-large", default_prompt_template=lfqa_prompt, output_variable="my_answer" ) And then you can use the output like: elaboration_prompt = PromptTemplate( prompt=""" ... Pr...
2
1
76,666,045
2023-7-11
https://stackoverflow.com/questions/76666045/unable-to-use-numpy-dot-with-numba
I am getting errors trying to run numpy.dot with numba. It seems to be supported (eg: numpy: Faster np.dot/ multiply(element-wise multiplication) when one array is the same) but eg this code gives me the following error (it runs fine if I remove the njit part) Code: import numpy as np import numba @numba.njit() def tst...
The docs say: Basic linear algebra is supported on 1-D and 2-D contiguous arrays of floating-point and complex numbers: numpy.dot() ... However, your two arrays contain integers. Note indeed, the error message: dot(array(int64, 2d, C), array(int64, 2d, C)) Hence, the trick is to change the dtype: import numpy as n...
5
5
76,663,521
2023-7-11
https://stackoverflow.com/questions/76663521/where-does-py-modules-go-in-pyproject-toml-setuptools
Where does the py_modules parameter (I don't know what it is called) go in a pyproject.toml file? [project] name = "elements" version = "1.0.0" description = "Magic" readme = "README.md" requires-python = ">=3.10" license = {file = "LICENSE"} authors = [ {name = "x"}, {name = "y"} ] maintainers = [ {name = "x"}, {name ...
I was able to find the solution here [tool.setuptools] packages = ["baseclasses", "elements"] py-modules = ["__init__"] # dash, not underscore
5
7
76,653,905
2023-7-10
https://stackoverflow.com/questions/76653905/what-are-the-mechanics-of-python-decorator-for-property-setter-and-deleter
The subject of Python properties is covered extensively here, and the Python documentation provides a pure Python implementation here. However, I am still not fully clear on the mechanics of the decorator functionality itself. More specifically, for identically named getters and setters x, how does the setter function ...
As pointed out by @kindall, the answer seems to lie in the decorator: and the fact that with it, Python does not seem to bind the raw function name to the namespace, but simply creates the raw function object, then calls the decorator function on it, and only binds the final result. This is touched upon in the answer h...
3
2
76,624,569
2023-7-5
https://stackoverflow.com/questions/76624569/assertion-error-custom-exception-not-raised
I am trying to write unittests for a function I wrote that includes a try/except block. I have raised a custom exception if my string contains less than 3 characters. I wanted to test that the error gets raised when inputting a string less than 3 characters long. When running the function, if I input a string less than...
Not raise the Custom Exceptions An other possibility is to remove your custom Exceptions an return directly the error message. So your code becomes: from collections import Counter # create a function that will return the 3 most common letters def three_most_common(string: str): string = string.replace(" ", "") try: if...
4
1
76,644,359
2023-7-8
https://stackoverflow.com/questions/76644359/how-to-type-hint-a-function-which-takes-a-callable-and-its-required-positional-a
Here is my function: def call_func(func, *args): return func(*args) I think I have two options here: Using TypeVarTuple -> in Callable[[*Ts], Any] form. Ts = TypeVarTuple("Ts") T = TypeVar("T") def call_func(func: Callable[[*Ts], T], *args: *Ts) -> T: return func(*args) Currently Mypy has problem with [*Ts] part. it...
The only way to fully type-check something that only accepts positional-only arguments is with PEP 646, which mypy (as of the time of this answer) does not fully implement. However, you can manipulate typing.ParamSpec and typing.Protocol to make positional-only and keyword-only callable types which throw errors at a ca...
4
3
76,655,600
2023-7-10
https://stackoverflow.com/questions/76655600/how-to-use-proxy-in-selenium-4-1
i am trying to make an automation project which will use proxy to register in a site. but i am unable to get it work. I have tried selenium-wire for proxy authentication still it doesn't work from seleniumwire import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.firefox.options import Op...
You can use SeleniumBase to proxy to a site. pip install seleniumbase, then run this with python after filling in the proxy details: from seleniumbase import SB with SB(uc=True, proxy="USER:PASS@IP:PORT") as sb: sb.driver.get("https://whatismyip.com") sb.sleep(5)
3
3
76,624,970
2023-7-6
https://stackoverflow.com/questions/76624970/how-can-i-change-the-parameter-signature-in-the-help-docs-of-a-decorated-functio
I have a class that includes a method that takes two parameters, a and b, like so: class Foo: def method(self, a, b): """Does something""" x, y, z = a.x, a.y, b.z return do(x, y, z) When running help(Foo) in the Python REPL, you would see something like this: class Foo(builtins.object) | Methods defined here: | | meth...
TL;DR Delete the __wrapped__ attribute that is added automatically by functools.wraps before returning the wrapper: def unpack(fn): @wraps(fn) def wrapper(self, a, b): x, y, z = a.x, a.y, b.z return fn(self, x, y, z) del wrapper.__wrapped__ # <-- force inspection to show `wrapper` signature return wrapper Details The...
3
4
76,652,410
2023-7-10
https://stackoverflow.com/questions/76652410/pytest-xdist-teardown-after-all-workers-finish
When I'm running pytest normally it works perfectly fine (before first test it's upgrading migration and after last test it's downgrading migration). Without using xdist I can just set fixture scope='session' and its work that way. But when I run pytest-xdist (tests in parallel) it's upgrading migration before each tes...
The fixture is running as part of a test, even if it's only once in session scope. This means it's running in the process xdist opened. To run this only once you move the code to pytest_sessionstart and pytest_sessionfinish in conftest.py. Those methods will be executed once in "regular" scope before/after xdist kicks ...
3
5
76,649,888
2023-7-9
https://stackoverflow.com/questions/76649888/how-do-i-copy-an-image-from-the-output-in-jupyter-notebook-7
I've been working with Jupyter Notebooks for quite a while. When working with visualisations, I like to copy the output image from a cell by right clicking the image and selecting "Copy Image" from the context menu: I like working with the direct copy from the notebook, especially for answering questions on Stack Over...
Hold down Shift while right-clicking to access the native browser menu, as spelled out here. For context, Version 7 of Jupyter Notebook is built off JupyterLab components (see here and here), and that means that some of the interface and GUI abilities you can learn by seeing how JupyterLab users handle them. Tested by...
11
15
76,649,501
2023-7-9
https://stackoverflow.com/questions/76649501/gitpython-error-module-git-does-not-explicitly-export-attribute-repo-attr
I am using Python 3.10.4, GitPython version 3.1.31, mypy version 1.4.1: $ pip show GitPython Name: GitPython Version: 3.1.31 Location: /home/hakon/.pyenv/versions/3.10.4/lib/python3.10/site-packages Requires: gitdb $ python --version Python 3.10.4 $ mypy --version mypy 1.4.1 (compiled: yes) If run mypy on this minimal...
As documentation suggests this is proper usage https://gitpython.readthedocs.io/en/stable/tutorial.html#meet-the-repo-type from git import Repo ... then I would consider this a minor bug that should be fixed in GitPython. You can work around this bug by importing it from the submodule git.repo.Repo('some_dir') or don...
3
1
76,645,926
2023-7-9
https://stackoverflow.com/questions/76645926/peewee-improperlyconfigured-postgres-driver-not-installed
I have installed peewee and postgres. I am using FastAPI as the backend. When I run the request to create tables, it throws the shown error: INFO: 127.0.0.1:33284 - "GET /setup_db HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): peewee.ImproperlyConfigured: Pos...
install postgresql driver: pip install psycopg2 But, I suggest you to use more robust solution, like: sqlalchemy, asyncpg, alembic :)
3
6
76,630,762
2023-7-6
https://stackoverflow.com/questions/76630762/403-response-while-web-scraping-tried-many-different-solutions-and-implementati
So I've been scraping Glassdoor for company reviews for a while now. In the past, I had scraped the site pretty easily using one line of code: page = http.get(url+ id + ".htm",timeout= 1000000,headers=HEADERS) In fact, I didn't even need the "header" line! This code had worked wonders until I took about a 6-month brea...
I found a solution that can bypass Cloudflare's protections, it is a Python module cloudscraper (which is a fork of cloudflare-scrape). It works on a small scale, but it says in the README that if you get reCAPTCHA challenge, then it won't be able to scrape the page. It is pretty simple to use: import re import cloudsc...
3
0
76,630,196
2023-7-6
https://stackoverflow.com/questions/76630196/how-to-fix-random-seed-in-pytorch-while-keeping-the-dropout-randomness
I am trying to approximate a Bayesian model by keeping the dropout probability during both training and inference (Monte Carlo dropout), in order to obtain the epistemic uncertainty of the model. Is there a way to fix all source of randomness for reproducibility (random seed), but to maintain the randomness of the drop...
I had to remove this line for things to work as expected. model.eval() This line seems to disable the dropout during inference.
3
0
76,639,423
2023-7-7
https://stackoverflow.com/questions/76639423/installing-libmagic-with-pip-fails
After installing in my Jupyter Notebook (as a container of JupyterLab as jovan user without access to root) the libmagic while having cmake 3.26.4 already installed in the conda env. I try to install install libmagic with pip: pip install python-libmagic but I keep getting error: Collecting python-libmagic Using cache...
Correct me, if I'm wrong, but I guess you want to install the python bindings for libmagic. Find them here: https://pypi.org/project/python-magic/ and here https://github.com/ahupp/python-magic pip install python-magic There was an issue request 6 years ago by its maintainer to the person sitting on the abandoned "pyt...
3
4
76,640,329
2023-7-7
https://stackoverflow.com/questions/76640329/rds-mysql-to-kinesis-data-stream-pipeline-using-aws-lambda
I am trying to extract data from RDS MySQL instance and load into kinesis data stream using put_record boto3 API. The connection using pymysql is working and I am able to print the table but, I cannot write the data into kinesis data stream. I get this error "Object of type datetime is not JSON serializable". def lambd...
This error is thrown when an object with a property of type datetime is passed to json.dumps method. There are several ways on how to resolve it but the quickest one is to convert all datetime properties to string by using the keyword argument of json.dumps import json from datetime import datetime # The default keywor...
3
1
76,640,378
2023-7-7
https://stackoverflow.com/questions/76640378/python-zip-magic-for-classes-instead-of-tuples
Python zip function is its own inverse (in a way), thus we can do this: points = [(1,2), (3,4), (5,6), (7,8)] xs, ys = zip(*points) and now xs=[1,3,5,7] and ys=[2,4,6,8]. I wonder if something similar can be done with data class instances instead of tuples: from dataclasses import dataclass @dataclass class XY: "2d po...
With astuple: from dataclasses import dataclass, astuple @dataclass class XY: "2d point" x: float | int y: float | int def __iter__(self): return iter(astuple(self)) points = [XY(1,2), XY(3,4), XY(5,6), XY(7,8)] xs, ys = zip(*points) Or instead map it: xs, ys = zip(*map(astuple, points))
26
19
76,638,630
2023-7-7
https://stackoverflow.com/questions/76638630/how-to-select-last-column-of-polars-dataframe
I have the following polars dataframe and I wanted to select the last column dynamically. >>> import polars as pl >>> >>> df = pl.DataFrame({ ... "col1": [1, 2], ... "col2": ["2", "3"], ... "col3": [3, 4] ... }) >>> >>> df shape: (2, 3) ┌──────┬──────┬──────┐ │ col1 ┆ col2 ┆ col3 │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ i64...
To aid in operatons like these, a polars.selectors module was introduced recently. You can simply use last from this module: df.select(cs.last()) shape: (2, 1) ┌──────┐ │ col3 │ │ --- │ │ i64 │ ╞══════╡ │ 3 │ │ 4 │ └──────┘
3
3
76,635,770
2023-7-7
https://stackoverflow.com/questions/76635770/how-to-test-fastapi-application-without-sharing-the-same-application-between-tes
I'm trying to test my FastAPI code using pytest. some of the tests I'm doing require the application be in an initial state (some configuration to be reset, object data to be cleared and so on). both of the methods I tried put the app in the same state during the test session, I also tried to reload the module in which...
If you convert main.py to use an app factory pattern, and store your state in the app rather than in a global, like this: from fastapi import FastAPI def create_app(): app = FastAPI() app.state.my_state = False @app.get("/my_state/") def return_my_state(): return {"state": app.state.my_state} @app.post("/my_state/") de...
3
6
76,633,711
2023-7-7
https://stackoverflow.com/questions/76633711/langchain-text-splitter-behavior
I don't understand the following behavior of Langchain recursive text splitter. Here is my code and output. from langchain.text_splitter import RecursiveCharacterTextSplitter r_splitter = RecursiveCharacterTextSplitter( chunk_size=10, chunk_overlap=0, # separators=["\n"]#, "\n", " ", ""] ) test = """a\nbcefg\nhij\nk"""...
Accord to the split_text funcion in RecursiveCharacterTextSplitter def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" final_chunks = [] # Get appropriate separator to use separator = self._separators[-1] for _s in self._separators: if _s == "": separator = _s break if _s in text:...
5
2
76,630,471
2023-7-6
https://stackoverflow.com/questions/76630471/coverage-py-returns-error-no-source-for-code-when-running-tensorflow-keras
I have built unittests for my code and everything works fine when running them from vscode. Even running coverage run runs successfully. But when I try to run coverage report I get the following output: No source for code: 'C:\Users\XXX\AppData\Local\Temp\1\__autograph_generated_file4ilniiln.py' I found out that this ...
Tensorflow rewrites your code and runs it from a new location. I need some assistance to get it working properly in coverage.py. See this issue for details: https://github.com/nedbat/coveragepy/issues/856 You can try using the -i flag to coverage report to ignore files it can't find. I don't know if you will still get ...
3
3
76,624,477
2023-7-5
https://stackoverflow.com/questions/76624477/whats-the-raku-equivalent-of-the-super-keyword-as-used-in-javascript-and-python
Whenever you extend a class in JavaScript or Python, the derived class must use the super keyword in order to set attributes and/or invoke methods and constructor in the base class. For example: class Rectangle { constructor(length, width) { this.name = "Rectangle"; this.length = length; this.width = width; } shoutArea...
What's the Raku equivalent of the super keyword as used in JavaScript and Python? One of Raku's re-dispatching functions.¹ Basics of redispatch First some code that does not include a redispatch function: class Rectangle { has ($.length, $.width) } Rectangle.new: length => 6, width => 4; The Rectangle declaration do...
11
11
76,631,028
2023-7-6
https://stackoverflow.com/questions/76631028/how-can-i-create-a-fractionenum-in-python-without-a-metaclass-conflict
I am trying to create a FractionEnum similar to StrEnum or IntEnum. My first attempt resulted in a metaclass conflict: class FractionEnum(fractions.Fraction, Enum): VALUE_1 = 1, 1 VALUE_2 = 8, 9 TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all it...
As @jsbueno said, you have to write your own __new__: from enum import EnumType, Enum from fractions import Fraction import math class FractionEnumMeta(type(Fraction), EnumType): pass class FractionEnum(Fraction, Enum, metaclass=FractionEnumMeta): def __new__(cls, numerator=0, denominator=None): # # this is the only li...
4
3
76,619,522
2023-7-5
https://stackoverflow.com/questions/76619522/jupyter-notebook-slides-in-vscode
In Jupyter Notebook we could create slides, like explained here. Here you can see a reproducible example to create Jupyter notebook slides via Anaconda-navigator: When running this command in the terminal: jupyter nbconvert slides_test.ipynb --to slides --post serve It will outputs this in your browser: And for the ...
Firstly, ensure that you have install Jupyter extension. It will install several extensions required for Jupyter including slides for you. Then, you can add a slide type to the cell you're on by opening the Command Palette (Cmd+Shift+P) and selecting Switch Slide Type according to the document in GitHub. You could m...
4
8
76,624,617
2023-7-5
https://stackoverflow.com/questions/76624617/quickly-mapping-values-from-one-pandas-dataframe-to-another-with-datetime-condit
I have two dataframes df1= ID Value BeginDate EndDate 1 0.5 1/1/12 1/1/13 1 0.6 1/1/13 1/1/14 2 0.4 1/1/12 1/1/13 3 0.7 1/1/12 1/1/13 df2= ID Date 1 6/6/12 1 7/5/12 1 10/5/13 2 8/9/12 3 6/6/12 I want to map the Value column from df1 onto df2 based on the ID column and whether the Date column in df2 fits between BeginD...
If the intervals are non overlapping, the most efficient pandas approach would be to merge_asof on the BeginDate, then to check that the EndDate is valid: df1[['BeginDate', 'EndDate']] = df1[['BeginDate', 'EndDate']].apply(pd.to_datetime, format='%d/%m/%y') df2['Date'] = pd.to_datetime(df2['Date'], format='%d/%m/%y') o...
3
2
76,624,161
2023-7-5
https://stackoverflow.com/questions/76624161/pandas-updating-a-column-with-loc-does-not-work-as-expected
As far as I understood it is preferable to update the column values using .loc method rather than slicing [], because of the potential SettingWithCopy issue. When I use slicing I frequently get these warnings, and I understand that there is a concern when using multindexing. However, when I am using .loc method, my col...
If you use a.loc[:,'A'] the dtype of the Series will not change because you modify only values. You slice your Series (even if you select all rows with :) so the container will remain the same. However, the type of each individual value will change from string to Timestamp. This is the same for any operations where the...
3
2
76,623,651
2023-7-5
https://stackoverflow.com/questions/76623651/storage-of-floating-point-numbers-in-memory-in-python
I know that Python maintains an internal storage of small-ish integers rather than creating them at runtime: id(5) 4304101544 When repeating this code after some time in the same kernel, the id is stable over time: id(5) 4304101544 I thought that this wouldn't work for floating point numbers because it can't possib...
It's not just that the object is garbage collected and and the new object stored in the same location as the previous one after garbage collection. Something different is at work here. We can use the dis module to look at the bytecode generated: import dis def f(): one, two = 4.3333333, 3.3333333 + 1. a, b = id(one), i...
4
1
76,623,398
2023-7-5
https://stackoverflow.com/questions/76623398/how-to-get-entries-of-array-with-separated-by-string-in-one-line
I have this data [[ 2.696000e+00 0.000000e+00 0.000000e+00 0.000000e+00] [ 2.577000e+00 0.000000e+00 0.000000e+00 0.000000e+00] [ 0.000000e+00 -2.560096e+03 0.000000e+00 0.000000e+00] ... and want to print it as such, for each row 2.696000e+00 & 0.000000e+00 & 0.000000e+00 & 0.000000e+00 // 2.577000e+00 & 0.000000e+00...
You can use str.join to join the numbers by & and then print // as last string: data = [ [2.696000e00, 0.000000e00, 0.000000e00, 0.000000e00], [2.577000e00, 0.000000e00, 0.000000e00, 0.000000e00], [0.000000e00, -2.560096e03, 0.000000e00, 0.000000e00], ] for row in data: print(' & '.join(map(str, row)), '//') Prints: 2...
2
5
76,621,598
2023-7-5
https://stackoverflow.com/questions/76621598/how-can-i-reshape-my-dataframe-into-a-3-dimensional-numpy-array
My dataframe contains a multivariate time series per user id. The first column id is the user id (there are N users), the second dt is the date (each user has T days worth of data, i.,e T rows for each user) and the other columns are metrics (basically, each column is a time series per id.) Here's a code to recreate a ...
Group the dataframe by id then for each unique id export the metrics as numpy array inside a list comprehension df = df.set_index(['id', 'dt']).sort_index() np.array([g.values for _, g in df.groupby(level=0)]) array([[[58, 3, 52, 5], [ 6, 34, 28, 88], [27, 98, 74, 81], [96, 13, 7, 52], [80, 69, 22, 12]]])
3
0
76,621,424
2023-7-5
https://stackoverflow.com/questions/76621424/cause-of-pytest-valueerror-fixture-is-being-applied-more-than-once-to-the-same
I have a unit test I'm running with a particular fixture. The fixture is pretty simple and looks like so: @pytest.fixture def patch_s3(): # Create empty bucket bucket = s3_resource().create_bucket(Bucket=BUCKET) bucket.objects.all().delete() yield bucket.objects.all().delete() and the test isn't all that complicated e...
If you scroll up from your definition of patch_s3, you'll probably find another duplicate line like @pytest.fixture, causing the issue. That line can only be used once per fixture method definition. The easiest way to reproduce this issue is with: import pytest @pytest.fixture(scope="session") @pytest.fixture def my_fi...
3
1
76,621,589
2023-7-5
https://stackoverflow.com/questions/76621589/how-to-run-async-methods-in-langchain
I have a basic chain that classifies some text based on the Common European Framework of Reference for Languages. I'm timing the difference between normal chain.apply and chain.aapply but can't get it to work. What am I doing wrong? import os from time import time import openai from dotenv import load_dotenv, find_dote...
Changing res_aa = chain.aapply(texts) to res_aa = await chain.aapply(texts) did the job! Now it works (damn these methods are much faster than doing it sequentially) [{'text': 'Based on the given text "Hallo, ich bin 25 Jahre alt," it can be classified as CEFR level A1.'}, {'text': 'A2'}, {'text': 'A2'}] apply time t...
3
2
76,619,466
2023-7-5
https://stackoverflow.com/questions/76619466/slash-commands-visible-by-role-user-or-permissions
If I have commands for special roles (e.g. /ban, /kick, /mute), every user can see them. It would be possible to display these commands only for those users who can execute them? You could check for permissions, roles, or id, but then people would still see these commands in the list
You can prevent users without the required permissions from seeing a command, by using the default_member_permissions parameter found here, when creating slash commands. @client.slash_command(name="ping", description="Ping the bot", default_member_permissions=(nextcord.Permissions(administrator=True))) async def ping(i...
3
4
76,617,034
2023-7-5
https://stackoverflow.com/questions/76617034/custom-date-format-in-fastapi-model
I have a date type of the format 15-Jul-1996. And I am trying to define a Pydantic model to use for input data validation in a FastAPI application as such: from pydantic import BaseModel from datetime import date class Profile(BaseModel): name: str DOB: date # type of 15-Jul-1996 gender: str Is there a way to constrai...
Try this. You can use @validator from pydantic import BaseModel, validator from datetime import datetime class Profile(BaseModel): name: str DOB: str # change this to str gender: str @validator('DOB') def parse_dob(cls, v): return datetime.strptime(v, '%d-%b-%Y').date() # convert string to date
2
0
76,614,379
2023-7-4
https://stackoverflow.com/questions/76614379/roo-validator-error-when-importing-langchain-text-splitter-python
I have been working through a LangChain tutorial and have hit this problem when trying to import langchain into python in vscode on macos 13.4.1. from dotenv import load_dotenv import os import streamlit as st from PyPDF2 import PdfReader from langchain.text_splitter import CharacterTextSplitter def main(): load_dotenv...
I was using LangChain 0.0.20 and I got the same issue. Upgrading to Python 3.9 and LangChain 0.0.224 fixed this issue for me.
4
0
76,576,620
2023-6-28
https://stackoverflow.com/questions/76576620/optional-caching-in-python-wrapping-a-cachetools-decorator-with-arguments
I'm using the cachetools library and I would like to wrap the decorator form this library and add a class self argument to enable/disable the caching at the class level e.e. MyClass(enable_cache=True) An example usage would be something like: class MyClass(object): def __init__(self, enable_cache=True): self.enable_cac...
When you use cachetools the answer is actually quite simple - you set the cache to None. import cachetools import operator class MyClass(object): def __init__(self, enable_cache=True): self.cache = cachetools.LRUCache(maxsize=10) if enable_cache else None @cachetools.cachedmethod(operator.attrgetter('cache')) def calc(...
5
5
76,596,952
2023-7-1
https://stackoverflow.com/questions/76596952/how-do-i-select-the-top-k-rows-of-a-python-polars-dataframe-for-each-group
The polars dataframe has a top_k method that can be used to select rows which contain the k largest values when sorting on a column. For example, the following code selects the two rows with the largest and second largest entry in the val column: df = pl.DataFrame({'grp':['a','a','a','b','b','b'], 'val':[1,2,3,10,20,30...
The latest release (version 0.20.24) of polars introduced pl.Expr.top_k_by (and also pl.Expr.bottom_k_by) with optimised runtime complexity O(n + k log n - k / 2) for precisely the use-case mentioned in the question. It can be used jointly with pl.Expr.over and mapping_strategy="explode" to obtain the desired result. d...
7
4
76,586,062
2023-6-30
https://stackoverflow.com/questions/76586062/wordcloud-attributeerror-transposedfont-object-has-no-attribute-getbbox
I tried to run the following code to generate a word cloud. text = 'word1 word2 word2 word3 word3 word3' from wordcloud import WordCloud wordcloud = WordCloud(width=480, height=480).generate(text) But I ran into this error: --------------------------------------------------------------------------- AttributeError Trac...
The solution was to upgrade pip and pillow, as based on an issue posted at the word_cloud GitHub repo. See the comments below the post above for how it solved the error featured here.
3
6
76,616,042
2023-7-4
https://stackoverflow.com/questions/76616042/attributeerror-module-pil-image-has-no-attribute-antialias
I am trying to have images in my Tkinter GUI, hence I am using PIL. Image.ANTIALAIS is not working. However, Image.BILINEAR works Here's some sample code: import tkinter as tk from PIL import Image, ImageTk window = tk.Tk() image = Image.open(r"VC.png") image = image.resize((20, 20), Image.ANTIALIAS) tk_image = Image...
The problem is with Pillow 10.0. Trying to uninstall Pillow might give some errors. Just put this in cmd: pip install Pillow==9.5.0
115
23
76,604,686
2023-7-3
https://stackoverflow.com/questions/76604686/pytorch-distributed-run-with-slurm-results-in-adress-family-not-found
When trying to run an example python file via torch.distributed.run on 2 Nodes with 2 GPUs each on a cluster by using a SLURM script I encounter the following error: [W socket.cpp:426] [c10d] The server socket cannot be initialized on [::]:16773 (errno: 97 - Address family not supported by protocol). [W socket.cpp:601]...
Adress Family not Found Errors are related to IPv4 and IPv6 versions. As my service did not provide an ipv6 connection between nodes, these errors occured. But they can be understood as warnings, the connection via IPv4 was still established. I did not find any solution on disabling IPv6 connections, but as they are ju...
4
1
76,571,059
2023-6-28
https://stackoverflow.com/questions/76571059/how-to-freeze-the-backbone-feature-extraction-layers-in-yolo-v8
I want to train the YOLO v8 in transfer learning on my custom dataset. I have different classes than the base training on the COCO dataset. Yet I don't want to learn again the feature extraction. Hence I though following the Ultralytics YOLOv8 Docs - Train. Yet, When I train on my small dataset I want to freeze the bac...
You can do the following def freeze_layer(trainer): model = trainer.model num_freeze = 10 print(f"Freezing {num_freeze} layers") freeze = [f'model.{x}.' for x in range(num_freeze)] # layers to freeze for k, v in model.named_parameters(): v.requires_grad = True # train all layers if any(x in k for x in freeze): print(f'...
3
4
76,576,942
2023-6-28
https://stackoverflow.com/questions/76576942/performance-degradation-with-increasing-threads-in-python-multiprocessing
I have a machine with 24 cores and 2 threads per core. I'm trying to optimize the following code for parallel execution. However, I noticed that the code's performance starts to degrade after a certain number of threads. import argparse import glob import h5py import numpy as np import pandas as pd import xarray as xr ...
TL;DR Replace xarray.open_dataset with xarray.load_dataset to immediately load the data into memory; the former is quite lazy, while the latter is a bit more eager (a.k.a greedy, strict). [if this answer is accepted] Explanation: [At the risk of repeating previous comments/answers,] This appears to be an I/O throughput...
5
0
76,579,007
2023-6-29
https://stackoverflow.com/questions/76579007/is-there-an-interactive-table-widget-for-shiny-for-python-that-calls-back-select
I'm using reactable, Datatable or rhandsontable in R Shiny to display an interactive table and as a user input for selecting rows. Given there are a few packages for doing this in R, I thought there would be even more libraries in python for selecting rows from an interactive table - however I haven't found one yet. Pl...
I also love the way Datatable works for shiny R, and have been searching for an equivalent in shiny Python. The latest release of shiny Python (0.4) has a new feature "data grid / data table" that looks promising ! Here are the links to the release announcement and the API documentation: https://shiny.posit.co/blog/pos...
3
1