content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python range error. Im not sure how to make the program display "out of range if credits" entered are not in the range 0, 20, 40,60, 80, 100 and 120
I'm doing a python sort of grade calculator right now and i need to make the program display ‘Out of range’ if credits entered are not in the range 0, 20, 40,60, 80, ... | Python range error. Im not sure how to make the program display "out of range if credits" entered are not in the range 0, 20, 40,60, 80, 100 and 120 | I'm doing a python sort of grade calculator right now and i need to make the program display ‘Out of range’ if credits entered are not in the range 0, 20, 40,60, 80, 100 and 120.
Where it says incorrect it should say Out of range instead
This is the spec of the grade calc im trying to make
so far everything works apart... | [
"You can validate each credits.\ndef _validate_credits_in_range(credits: int, container: \"Container[int]\" = range(0, 121, 20)) -> bool:\n return credits in container\n\ndef Validation(StudentPassCredits: int, StudentDeferCredits: int, StudentFailCredits: int) -> None:\n if all(_validate_credits_in_range(cre... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074551908_python.txt |
Q:
Elsaticsearch Connection Refused
from elasticsearch import Elasticsearch #elasticsearch==7.17.3 used
esDB = Elasticsearch(
['https://13.XX.242.XX'],
use_ssl = False,
ca_certs=False,
verify_certs=False,
http_auth=('elastic', 'elastic'),
port=5601,
)
Trying to connect to a remote elast... | Elsaticsearch Connection Refused | from elasticsearch import Elasticsearch #elasticsearch==7.17.3 used
esDB = Elasticsearch(
['https://13.XX.242.XX'],
use_ssl = False,
ca_certs=False,
verify_certs=False,
http_auth=('elastic', 'elastic'),
port=5601,
)
Trying to connect to a remote elastic search server but getting t... | [
"Elasticsearch listens on port 9200 for API requests. 5601 is for Kibana. you have the two mixed up in your code, so it should be something like;\nfrom elasticsearch import Elasticsearch #elasticsearch==7.17.3 used\n\n\nesDB = Elasticsearch(\n ['https://13.XX.242.XX'],\n use_ssl = False,\n ca_certs=False,... | [
0
] | [] | [] | [
"elasticsearch",
"python"
] | stackoverflow_0074541730_elasticsearch_python.txt |
Q:
'gbk' codec can't encode character '\u2022' in position 32: illegal multibyte sequence
There is a question about writting file.
when I used data.to_csv('/home/bio_kang/Learning/Python/film_project/top250_film_info.csv', index=None, encoding='gbk'), it given me a error that 'gbk' codec can't encode character '\u202... | 'gbk' codec can't encode character '\u2022' in position 32: illegal multibyte sequence | There is a question about writting file.
when I used data.to_csv('/home/bio_kang/Learning/Python/film_project/top250_film_info.csv', index=None, encoding='gbk'), it given me a error that 'gbk' codec can't encode character '\u2022' in position 32: illegal multibyte sequence.
The data come from a website https://movie.do... | [
"try that:\nopen('...','rb',encoding='utf-8')\n\nor utf-16\n"
] | [
0
] | [] | [] | [
"encoding",
"python",
"python_3.x"
] | stackoverflow_0073540470_encoding_python_python_3.x.txt |
Q:
Moving TKinter Window.destroy to a function from a button, not so simple?
I'm giving myself a crash-course in Python and TKinter, but there is one small detail I can't grasp.
Closing a Toplevel window in a function instead of a button.
My button alone works perfect:
button = Button(UpdateWindow, text="Destroy Wind... | Moving TKinter Window.destroy to a function from a button, not so simple? | I'm giving myself a crash-course in Python and TKinter, but there is one small detail I can't grasp.
Closing a Toplevel window in a function instead of a button.
My button alone works perfect:
button = Button(UpdateWindow, text="Destroy Window", command=UpdateWindow.destroy)
Using a button with a reference to a close ... | [
"command=UpdateWindow.destroy defines a variable. If you want to keep the command variable use command(), while if you want the recommended way use UpdateWindow.destroy()\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074551987_python.txt |
Q:
Python + PyCharm File Structure issue: AttributeError: 'module' object has no attribute 'X'
I'm having the following file structure:
main.py
Crypto
GetGenerators.py
Utils
RecHash.py
ToInteger.py
Utils.py
GetGenerators.py looks like this:
import unittest
import os, sys
import gmpy2
from gmpy2 import mpz
sys.p... | Python + PyCharm File Structure issue: AttributeError: 'module' object has no attribute 'X' | I'm having the following file structure:
main.py
Crypto
GetGenerators.py
Utils
RecHash.py
ToInteger.py
Utils.py
GetGenerators.py looks like this:
import unittest
import os, sys
import gmpy2
from gmpy2 import mpz
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from Utils.Utils ... | [
"I haven't had your exact problem before, but I think I've had one like it. When I use PyCharm, I find that if open and use files that I've created in a project in PyCharm, then everything works fine. I can import them, can run them; no problems. The problems I run into (which are similar to yours) are when I open ... | [
1,
0
] | [] | [] | [
"pycharm",
"python",
"python_3.x"
] | stackoverflow_0044011169_pycharm_python_python_3.x.txt |
Q:
Django Sass Compressor django_libsass.SassCompiler: command not found
I'm using a Django-Compressor Filter as part of Wagtail (Django variant CMS with super cool UI). Environment is Wagtail 0.2 + Python 2.7 + Django 1.6 + Virtualenv + FastCGI + Apache shared hosting.
Issue occurs when trying to access admin/login ... | Django Sass Compressor django_libsass.SassCompiler: command not found | I'm using a Django-Compressor Filter as part of Wagtail (Django variant CMS with super cool UI). Environment is Wagtail 0.2 + Python 2.7 + Django 1.6 + Virtualenv + FastCGI + Apache shared hosting.
Issue occurs when trying to access admin/login page of the CMS. Django shows an Error rendering template
Error during ... | [
"(Reposting my comments as an answer, as requested...)\nThe original error: django_libsass.SassCompiler: command not found\nmeant that it was failing to import the django-libsass library. (django-compressor responded to that failure by trying to treat it as a shell command instead - django_libsass is not a runnable... | [
8,
1,
0,
0
] | [
"pip install django_pyscss will fix your issue.\n"
] | [
-2
] | [
"django",
"django_compressor",
"python",
"python_2.7",
"wagtail"
] | stackoverflow_0022515611_django_django_compressor_python_python_2.7_wagtail.txt |
Q:
What can I do to avoid race conditions for multiple callbacks in plotly?
I have a dashboard very similar to this one-
import datetime
import dash
from dash import dcc, html
import plotly
from dash.dependencies import Input, Output
# pip install pyorbital
from pyorbital.orbital import Orbital
satellite = Orbital('... | What can I do to avoid race conditions for multiple callbacks in plotly? | I have a dashboard very similar to this one-
import datetime
import dash
from dash import dcc, html
import plotly
from dash.dependencies import Input, Output
# pip install pyorbital
from pyorbital.orbital import Orbital
satellite = Orbital('TERRA')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']... | [
"I think this code does what you want. Update data, while keeping layout. You can adapt to exactly what you would like, your example is copied anyhow and not really working (ex: you have a ctx there that is not defined)\nThe idea of the code below is: rather than update the complete object server side (in the callb... | [
1
] | [] | [] | [
"dashboard",
"plotly",
"plotly_dash",
"plotly_python",
"python"
] | stackoverflow_0074442539_dashboard_plotly_plotly_dash_plotly_python_python.txt |
Q:
Comparison between datetime and datetime64[ns] in pandas
I'm writing a program that checks an excel file and if today's date is in the excel file's date column, I parse it
I'm using:
cur_date = datetime.today()
for today's date. I'm checking if today is in the column with:
bool_val = cur_date in df['date'] #evalu... | Comparison between datetime and datetime64[ns] in pandas | I'm writing a program that checks an excel file and if today's date is in the excel file's date column, I parse it
I'm using:
cur_date = datetime.today()
for today's date. I'm checking if today is in the column with:
bool_val = cur_date in df['date'] #evaluates to false
I do know for a fact that today's date is in th... | [
"For anyone who also stumbled across this when comparing a dataframe date to a variable date, and this did not exactly answer your question; you can use the code below.\nInstead of:\nself.df[\"date\"] = pd.to_datetime(self.df[\"date\"])\n\nYou can import datetime and then add .dt.date to the end like:\nself.df[\"da... | [
80,
41,
0
] | [] | [] | [
"datetime",
"datetime64",
"pandas",
"python"
] | stackoverflow_0051827134_datetime_datetime64_pandas_python.txt |
Q:
Get location of pixel upon click in Kivy
I am using Kivy to design an application to draw an n-sided polygon over a live video stream to demarcate regions of interest. The problem I have is that Kivy provides coordinates w.r.t to the whole window and not just the image. What I would like is to have the location of... | Get location of pixel upon click in Kivy | I am using Kivy to design an application to draw an n-sided polygon over a live video stream to demarcate regions of interest. The problem I have is that Kivy provides coordinates w.r.t to the whole window and not just the image. What I would like is to have the location of the pixel (in x and y cords) clicked. I have ... | [
"You can calculate the coordinates of the touch relative to the lower left corner of the actual image that appears in the GUI. Those coordinates can then be scaled to the actual size of the source image to get a reasonable estimate of the actual pixel coordinates within the source. Here is a modified version of you... | [
1
] | [] | [] | [
"kivy",
"python",
"user_interface"
] | stackoverflow_0074543030_kivy_python_user_interface.txt |
Q:
Downloading big file(800MB) from url into GCS bucket using Cloud function
I have written a code which works in my local and then I tried to replicate the same in cloud function. The basic purpose is to download a massive file of around 800 MB to a gcs bucket.
However I am getting the below error:
Function invocati... | Downloading big file(800MB) from url into GCS bucket using Cloud function | I have written a code which works in my local and then I tried to replicate the same in cloud function. The basic purpose is to download a massive file of around 800 MB to a gcs bucket.
However I am getting the below error:
Function invocation was interrupted. Error: function terminated. Recommended action: inspect log... | [
"Cloud Functions stores data in memory when you download it. Even if you use a file system path, it's an in memory file system and will consume memory.\nThe solution is to increase the memory of your cloud function (try with 1 or 2 Gb). Use the second gen Cloud Functions if you want more granularity and more memory... | [
0
] | [] | [] | [
"google_cloud_functions",
"google_cloud_storage",
"pandas",
"python"
] | stackoverflow_0074548275_google_cloud_functions_google_cloud_storage_pandas_python.txt |
Q:
PEP-8 break up for loop
I am trying to figure out a way to break a long for loop to make it PEP-8 valid.
(I'm using flake8 vscode extension).
This is the code:
for result_row in soup.find_all('div', {"class": "b2c-inner-data-wrapper"}):
..............
The error I get is:
line too long (88 > 79 characters)
I'... | PEP-8 break up for loop | I am trying to figure out a way to break a long for loop to make it PEP-8 valid.
(I'm using flake8 vscode extension).
This is the code:
for result_row in soup.find_all('div', {"class": "b2c-inner-data-wrapper"}):
..............
The error I get is:
line too long (88 > 79 characters)
I've tried:
for result_row in s... | [
"result_rows = soup.find_all('div', {\"class\": \"b2c-inner-data-wrapper\"})\nfor result_row in result_rows:\n ..............\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"flake8",
"pep8",
"python"
] | stackoverflow_0074552071_beautifulsoup_flake8_pep8_python.txt |
Q:
"No source for code" message in Coverage.py
I ran a build last night, successfully. I got up this morning and ran another without changing any configuration or modifying any source code. Now my build is failing with the message "No source for code" when running my nosetests with coverage.
NoSource: No source for ... | "No source for code" message in Coverage.py | I ran a build last night, successfully. I got up this morning and ran another without changing any configuration or modifying any source code. Now my build is failing with the message "No source for code" when running my nosetests with coverage.
NoSource: No source for code: '/home/matthew/.hudson/jobs/myproject/works... | [
"I'm not sure why it thinks that file exists, but you can tell coverage.py to ignore these problems with a coverage xml -i switch. \nIf you want to track down the error, drop me a line (ned at ned batchelder com).\n",
"Ensure theres no .pyc file there, that may have existed in the past.\n",
"Summary: Existing ... | [
48,
46,
17,
10,
6,
1,
0,
0,
0,
0
] | [] | [] | [
"code_coverage",
"continuous_integration",
"nosetests",
"python"
] | stackoverflow_0002386975_code_coverage_continuous_integration_nosetests_python.txt |
Q:
DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
Since some columns are strings, I did get numeric to exact those columns only to DF, but I received an error message when I tried to convert the negative numbers to zero
#cleaning negative minimum to equal only 0s
df2 = df._get_numeric_dat... | DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() | Since some columns are strings, I did get numeric to exact those columns only to DF, but I received an error message when I tried to convert the negative numbers to zero
#cleaning negative minimum to equal only 0s
df2 = df._get_numeric_data()
if df2 < 0:
then = 0
/Library/Frameworks/Python.framework/Versions/3.9/l... | [
"this method worked without using an if statment\ndf2 = df._get_numeric_data()\n\ndf2[df2 < 0] = 0\n\n\n"
] | [
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074552136_if_statement_python.txt |
Q:
How to get python logging output in shell script
I would want to get the stdout of the python file into shell script. I initially used print and it worked fine but it is not working for logging.
ab.py
import logging
logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)
logging.info('2222222222222')... | How to get python logging output in shell script | I would want to get the stdout of the python file into shell script. I initially used print and it worked fine but it is not working for logging.
ab.py
import logging
logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)
logging.info('2222222222222')
print("111111111111")
cd.sh
#/bin/bash
set -e
set -x... | [
"logging prints to stderr and not stdout. These are 2 separate streams of data. You can manage these by learning up a bit on Input/Output Redirection. But, it is kind of a big topic to summarize here.\ntl/dr: Make your command be python3 ab.py 2>&1 and you will get the output you want, kinda. You'll see that t... | [
2,
2
] | [] | [] | [
"logging",
"python",
"shell"
] | stackoverflow_0074552292_logging_python_shell.txt |
Q:
Drawing point of view for an object in PyQt6
I'm really new to PyQt6.
I want to draw an object that moves in space and draw around it its point of view site.
This is exactly what I want:
And this is what I get till now.
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import sys
... | Drawing point of view for an object in PyQt6 | I'm really new to PyQt6.
I want to draw an object that moves in space and draw around it its point of view site.
This is exactly what I want:
And this is what I get till now.
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
import sys
class Window(QWidget):
def __init__(self):
... | [
"You're using the wrong angle for QPainterPath, which uses degrees, as opposed to QPainter which uses sixteenths of a degree.\nAlso, you need to use arcMoveTo() (not moveTo) in order to place the path at the correct position when starting a new arc.\nFinally, you have to close the path, using closeSubpath().\n ... | [
1
] | [] | [] | [
"graphics",
"pyqt",
"pyqt6",
"python",
"python_3.x"
] | stackoverflow_0074549261_graphics_pyqt_pyqt6_python_python_3.x.txt |
Q:
How to search a dictionary for a value then delete that value
I have a dictionary where the values are lists. I want to search these for a specific value. right now it returns if the value is in each list individually but i just want overall then it deletes
Here's what it returns right now:
marie true
marie false... | How to search a dictionary for a value then delete that value | I have a dictionary where the values are lists. I want to search these for a specific value. right now it returns if the value is in each list individually but i just want overall then it deletes
Here's what it returns right now:
marie true
marie false
marie false
tom false
tom true
tom false
jane false
jane fal... | [
"You need to wait the iteration on all dict values before being able to yes yes or no\ndictionary = {'nyu': ['marie', 'taylor', 'jim'],\n 'msu': ['tom', 'josh'],\n ' csu': ['tyler', 'mark', 'john']}\n\ndef get_names(names):\n for name in names:\n name_found = False\n for d... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074551969_python.txt |
Q:
how to edit txt file with regular expressions (re) in python
Im having a trouble with editing a txt file on python.
Hi guys,
Im having a trouble with editing a txt file on python.
Here is the first few lines of the txt file
m0 +++$+++ 10 things i hate about you +++$+++ 1999 +++$+++ 6.90 +++$+++ 62847 +++$+++ ['com... | how to edit txt file with regular expressions (re) in python | Im having a trouble with editing a txt file on python.
Hi guys,
Im having a trouble with editing a txt file on python.
Here is the first few lines of the txt file
m0 +++$+++ 10 things i hate about you +++$+++ 1999 +++$+++ 6.90 +++$+++ 62847 +++$+++ ['comedy', 'romance']
m1 +++$+++ 1492: conquest of paradise +++$+++ 199... | [
"Regex is not the correct solution for this. Each of your lists is at the end of each line, so use str.rsplit:\nfrom io import StringIO\nimport ast\n\ncontent = \"\"\"m0 +++$+++ 10 things i hate about you +++$+++ 1999 +++$+++ 6.90 +++$+++ 62847 +++$+++ ['comedy', 'romance']\nm1 +++$+++ 1492: conquest of paradise ++... | [
1,
0
] | [] | [] | [
"python",
"python_re",
"txt"
] | stackoverflow_0074552131_python_python_re_txt.txt |
Q:
How can I solve this double sub-string and astype problem
In this case I have a problem with this:
Im trying to split a column "Ubicación Finalizada" in two, but I have a problem with a "," string, I can't take it out and that make some problems in the after code because I can't convert it to float in the "Latit... | How can I solve this double sub-string and astype problem | In this case I have a problem with this:
Im trying to split a column "Ubicación Finalizada" in two, but I have a problem with a "," string, I can't take it out and that make some problems in the after code because I can't convert it to float in the "Latitud" column with the 'Longitud' I dont have problem.
Code:
df[... | [
"You can use .str.split to split the string column and then convert it:\ndf[[\"lat\", \"lon\"]] = df[\"Ubicación finalizada\"].str.split(\",\", expand=True)\ndf[[\"lat\", \"lon\"]] = df[[\"lat\", \"lon\"]].astype(float)\nprint(df)\n\nPrints:\n Ubicación finalizada lat lon\n0 -34.123,-56.156 -34.1230... | [
1
] | [] | [] | [
"pandas",
"python",
"slice",
"string",
"types"
] | stackoverflow_0074552377_pandas_python_slice_string_types.txt |
Q:
cv2 onMouse() has a missing argument when using importlib to create a class at runtime
I want to load a python file (module) dynamically when the user inputs the filename (here for example: RegionOfInterest.py). In the file will be one class (here: RegionOfInterest). All classes have a method with the same name (h... | cv2 onMouse() has a missing argument when using importlib to create a class at runtime | I want to load a python file (module) dynamically when the user inputs the filename (here for example: RegionOfInterest.py). In the file will be one class (here: RegionOfInterest). All classes have a method with the same name (here: start) which i want to call.
This works fine, but if i call another method from the sta... | [
"I'm not sure what you're trying to achieve with this code:\nmyClass.__init__(myClass, img)\nmyMethod = myClass.__getattribute__(myClass, \"start\")\nmyMethod(myClass)\n\nmyClass is a class, not an instance of that class. So your passing an invalid object as self to the __init__() method.\nThe following seems much ... | [
0
] | [] | [] | [
"python",
"python_importlib",
"self"
] | stackoverflow_0074551092_python_python_importlib_self.txt |
Q:
Why doesn't my function with variables update data?
def overwriteFlat(top, curTable, rawEntrylist, columns):
rawEntrylist = rawEntrylist
entryList = list()
for value in rawEntrylist:
entryList.append(value.get())
conn = sqlite3.connect('data.db')
c = conn.cursor()
for i in range(... | Why doesn't my function with variables update data? | def overwriteFlat(top, curTable, rawEntrylist, columns):
rawEntrylist = rawEntrylist
entryList = list()
for value in rawEntrylist:
entryList.append(value.get())
conn = sqlite3.connect('data.db')
c = conn.cursor()
for i in range(len(columns)):
if entryList[i] != '':
... | [
"Thanks to @JohnGordon i found the solution\nBut just so if someone wants to use Variables in Sqlite i will explain how as this is hardly explained anywhere on the Internet (at least at my Beginner-Programmer-Level)\nUsually Sql commands work like this and are pretty static:\n\"UPDATE Your_Table SET Your_Column = :... | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074552305_python_sqlite.txt |
Q:
Pandas dataframe to SQL table using presto-python-client syntax error: mismatched input ';'
I am connecting to a presto db, trying to write a dataframe into a sql table. I can "CREATE TABLE" but df.to_sql throws a syntax error:
PrestoUserError: PrestoUserError(type=USER_ERROR, name=SYNTAX_ERROR, message="line 1:61... | Pandas dataframe to SQL table using presto-python-client syntax error: mismatched input ';' | I am connecting to a presto db, trying to write a dataframe into a sql table. I can "CREATE TABLE" but df.to_sql throws a syntax error:
PrestoUserError: PrestoUserError(type=USER_ERROR, name=SYNTAX_ERROR, message="line 1:61: mismatched input ';'. Expecting: '%', '*', '+', '-', '.', '/', 'AND', 'AT', 'EXCEPT', 'FETCH', ... | [
"SQLAlchemy have limited dialect options or databases that it can connect to.\nRefer : https://docs.sqlalchemy.org/en/13/dialects/ for the list.\nPresto is not part of it.\n"
] | [
0
] | [] | [] | [
"presto",
"python",
"python_db_api",
"sqlalchemy"
] | stackoverflow_0071942942_presto_python_python_db_api_sqlalchemy.txt |
Q:
How to analyse data collected through a sensor every minute?
I have a dataset from a sensor which collected air quality features like CO2, temperature etc every minute for 30 days.
I have tried pandas and tableu but I don't seem to get anywhere. Any suggestions or solutions?
A:
Usually using sampled data is the ... | How to analyse data collected through a sensor every minute? | I have a dataset from a sensor which collected air quality features like CO2, temperature etc every minute for 30 days.
I have tried pandas and tableu but I don't seem to get anywhere. Any suggestions or solutions?
| [
"Usually using sampled data is the better option for Time-Series data analysis. You can refer this answer to know more about the sampling and how it is useful for time-series data analysis.\n"
] | [
0
] | [] | [] | [
"analysis",
"data_analysis",
"machine_learning",
"pandas",
"python"
] | stackoverflow_0074552496_analysis_data_analysis_machine_learning_pandas_python.txt |
Q:
ArgumentError: Python argument types in rdkit.Chem.rdMolDescriptors.GetMorganFingerprintAsBitVect(NoneType, int) did not match C++ signature
So I'm working with RDKit and Python to convert SMILES strings to ECFP4 fingerprints, and my code is as shown below. I got an error, but I have also checked with this questio... | ArgumentError: Python argument types in rdkit.Chem.rdMolDescriptors.GetMorganFingerprintAsBitVect(NoneType, int) did not match C++ signature | So I'm working with RDKit and Python to convert SMILES strings to ECFP4 fingerprints, and my code is as shown below. I got an error, but I have also checked with this question over here but I seem to have the correct code? But why am I still getting an error?
Is there an alternative way to code this?
bits = 1024
Pandas... | [
"It is likely that your list contains irregular values, such as 'None', nan, or just empty items. In your code the 'x' should correspond to a single string.\n",
"You may have irregular molecules or ions in your data set!\nTo fix this use MolVS (https://molvs.readthedocs.io/en/latest/).\nAn example of use:\nhttps... | [
1,
0
] | [] | [] | [
"python",
"rdkit"
] | stackoverflow_0071776465_python_rdkit.txt |
Q:
Raspi Pico W [Errno 98] EADDRINUSE despite using socket.SO_REUSEADDR
I'm trying to set up a simple server/client connection using the socket module on a Raspberry Pi Pico W running the latest nightly build image rp2-pico-w-20221123-unstable-v1.19.1-713-g7fe7c55bb.uf2 which I've downloaded from https://micropython.... | Raspi Pico W [Errno 98] EADDRINUSE despite using socket.SO_REUSEADDR | I'm trying to set up a simple server/client connection using the socket module on a Raspberry Pi Pico W running the latest nightly build image rp2-pico-w-20221123-unstable-v1.19.1-713-g7fe7c55bb.uf2 which I've downloaded from https://micropython.org/download/rp2-pico-w/
The following code runs fine for the first connec... | [
"While I was able to mitigate the reconnection crash by adding a sock.close() statement after the con.close(), the main issue with my code was the structure itself, as Steffen Ullrich pointed out.\nThe actual fix was to move the operations on the sock object out of the loop.\nimport socket\n\ndef await_connection()... | [
1
] | [] | [] | [
"micropython",
"python",
"raspberry_pi_pico",
"sockets"
] | stackoverflow_0074551529_micropython_python_raspberry_pi_pico_sockets.txt |
Q:
Conditions for statespace statsmodel mlemodel
I'm trying to run a TVP VAR on Statsmodel for a Big Data, but there seems to be a problem when trying to validate the vector matrix and the vector shape. Especially when defining the start and update parameter , mostly on the dimension and the structure of the update p... | Conditions for statespace statsmodel mlemodel | I'm trying to run a TVP VAR on Statsmodel for a Big Data, but there seems to be a problem when trying to validate the vector matrix and the vector shape. Especially when defining the start and update parameter , mostly on the dimension and the structure of the update parameters. My model is a TVP-PVAR in a normal linea... | [
"On this line:\nself['state_cov'] = np.diag([params[2]**2, params[3]**2, params[4]**2])\n\nYou're calling the function np.diag(). According to the documentation, when np.diag() is given a 1-D vector of N elements, it creates an NxN matrix, with the element of the vector along the diagonal. You gave it three element... | [
0
] | [] | [] | [
"bayesian",
"kalman_filter",
"python",
"state_space",
"statsmodels"
] | stackoverflow_0074547854_bayesian_kalman_filter_python_state_space_statsmodels.txt |
Q:
Repack inference model with requirements.txt inside source_dir without installing them during the process in SageMaker
After training a custom model, i need to create an inference model and then deploy the relevant endpoint.
When, in the execution of the pipeline, i have to inject a custom inference script, a mode... | Repack inference model with requirements.txt inside source_dir without installing them during the process in SageMaker | After training a custom model, i need to create an inference model and then deploy the relevant endpoint.
When, in the execution of the pipeline, i have to inject a custom inference script, a model repacking process is triggered. The inference model needs to have the requirements.txt file (the same as the trained model... | [
"The SageMaker SDK will always repackage the tar ball to include the inference.py script and then re-upload the tar ball to S3.\nIn general, SageMaker Framework containers will install the packages specified in the requirements.txt file.\nIf you do not want this to occur you can leave out the requirements.txt file ... | [
1
] | [] | [] | [
"amazon_sagemaker",
"amazon_web_services",
"boto3",
"pipeline",
"python"
] | stackoverflow_0074405489_amazon_sagemaker_amazon_web_services_boto3_pipeline_python.txt |
Q:
Can't recreate Conda environment in docker
I created a conda environment from a fresh installation of miniconda3.
After that I exported it and this is the content of the file (my only extra install was flask):
name: myenv
channels:
- defaults
dependencies:
- ca-certificates=2018.03.07=0
- certifi=2018.11.29... | Can't recreate Conda environment in docker | I created a conda environment from a fresh installation of miniconda3.
After that I exported it and this is the content of the file (my only extra install was flask):
name: myenv
channels:
- defaults
dependencies:
- ca-certificates=2018.03.07=0
- certifi=2018.11.29=py37_0
- click=7.0=py37_0
- flask=1.0.2=py3... | [
"I had a similar problem and I find multiple ways to solve it. The main problem with your approach is conda is not platform independent, so will force the environments to use pip.\n1. Conda Like Solution\nChange your my_env.yml so that all the dependencies apart from pip goes under the pip dependency. Notice that t... | [
3,
0
] | [] | [] | [
"docker",
"dockerfile",
"miniconda",
"python",
"python_3.x"
] | stackoverflow_0053819954_docker_dockerfile_miniconda_python_python_3.x.txt |
Q:
Remove outliers using groupby in data with several categories
I have a time-series with several products. I want to remove outliers using the Tukey Fence method. The idea is to create a column with a flag indicating outlier or not, using groupby. It should be like that (flag column is added by the groupby):
date p... | Remove outliers using groupby in data with several categories | I have a time-series with several products. I want to remove outliers using the Tukey Fence method. The idea is to create a column with a flag indicating outlier or not, using groupby. It should be like that (flag column is added by the groupby):
date prod units flag
1 a 100 0
2 a 90 0
3 a 80 ... | [
"I would compute the quantiles first; then derive IQR from them. Compute the fence bounds and call merge() to map these limits to the original dataframe and call eval() to check if the units are within their respective Tukey fence bounds.\n# compute quantiles\nquantiles = df.groupby('prod')['units'].quantile([0.25,... | [
1
] | [] | [] | [
"group_by",
"pandas",
"python",
"time_series",
"vectorization"
] | stackoverflow_0074551771_group_by_pandas_python_time_series_vectorization.txt |
Q:
Python. Generate imitation of sentence from random letters from large text
I'm a total newbie. I'm writing a code for my python classes and I'm looking for help.
This is supposed to be a code imitating language, in this case latin.
I want to take random letter from long string.
When I have letter1, I'd like to fin... | Python. Generate imitation of sentence from random letters from large text | I'm a total newbie. I'm writing a code for my python classes and I'm looking for help.
This is supposed to be a code imitating language, in this case latin.
I want to take random letter from long string.
When I have letter1, I'd like to find all indexes of the same letter in the text. Then randomly take one index and t... | [
"You are close. You pick a letter randomly from the whole string only the first time, so this should be before the loop. Then you pick one of the succeeding letters. Now reset letter to the picked one and repeat the process:\nimport random\n\ntext = 'Lorem ipsum dolor sit amet. Consectetur adipiscing elit. Fusce ac... | [
0
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0074552623_python_while_loop.txt |
Q:
Mouse not interacting with object correctly using collidepoint function
So I used the collidepoint function to test out whether or not my mouse is interacting or can interact with the images on the surface Surface but the variable mouse_pos does give out a position yet the mouse cannot ever collide with the object... | Mouse not interacting with object correctly using collidepoint function | So I used the collidepoint function to test out whether or not my mouse is interacting or can interact with the images on the surface Surface but the variable mouse_pos does give out a position yet the mouse cannot ever collide with the object (see A is always false rather than true when the mouse hit the object). How ... | [
"You are not drawing the objects on the screen, but on the surface. Therefore the coordinates of player_rect are relative to the surface and you also have to calculate the mouse position relative to the surface. The top left coordinate of the surface is (midalignX_lg, midalignY_lg):\nwhile True:\n # [...]\n \n... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074552642_pygame_python.txt |
Q:
How to handle API response in python
I wonder how I can properly handle this invalid response. How to check if the response has status: 400 or perhaps has a title: Bad Request?
url = f"https://api123.com"
substring = "title: Bad Request"
response = requests.get(url, headers=headers).json()
if substring in respons... | How to handle API response in python | I wonder how I can properly handle this invalid response. How to check if the response has status: 400 or perhaps has a title: Bad Request?
url = f"https://api123.com"
substring = "title: Bad Request"
response = requests.get(url, headers=headers).json()
if substring in response:
print ("Your Data is Invalid")
else... | [
"You have a dictionary right there.\n>>> response = {'type': 'h---s://abc.com/data-errors/bad_request', 'title': 'Bad Request', 'status': 400, 'detail': 'The request you sent was invalid.', 'extras': {'invalid_field': 'account_id', 'reason': 'Account is invalid'}} \n>>> response[\"status\"] == 400 ... | [
1,
1
] | [] | [] | [
"api",
"python",
"request"
] | stackoverflow_0074552447_api_python_request.txt |
Q:
Python - Complementary suppression of 2nd/lowest value row-wise
I'm working on a data suppression script in python where I need to 1) suppress small values (between 1 and 5) and 2) make sure that there are at least 2 values suppressed at the smallest level of aggregation. I've done the first step, replacing small ... | Python - Complementary suppression of 2nd/lowest value row-wise | I'm working on a data suppression script in python where I need to 1) suppress small values (between 1 and 5) and 2) make sure that there are at least 2 values suppressed at the smallest level of aggregation. I've done the first step, replacing small values with -1 (which I'll later recode to "s"). And I created a new ... | [
"I hope I've understood your question right:\ndef fn(x):\n cols = x.filter(regex=r\"^cat\")\n x = cols[cols >= 0].sort_values()[: 2 - x[\"sup_cnt\"]]\n df.loc[x.name, x.index] = -1\n\n\ndf[df.sup_cnt < 2].apply(fn, axis=1)\nprint(df)\n\nPrints:\n Subgroup cat1 cat2 cat3 sup_cnt\n0 Group1 -1 -1... | [
1
] | [] | [] | [
"pandas",
"python",
"replace",
"suppression"
] | stackoverflow_0074552418_pandas_python_replace_suppression.txt |
Q:
Amazon Web Scraping - retrieving price data
I'm currently working on my first project experimenting with web scraping on python. I am attempting to retrieve price data from an amazon url but am having some issues.
url = 'https://www.amazon.ca/Nintendo-SwitchTM-Neon-Blue-Joy-E2-80-91ConTM-dp-B0BFJWCYTL/dp/B0BFJWCYT... | Amazon Web Scraping - retrieving price data | I'm currently working on my first project experimenting with web scraping on python. I am attempting to retrieve price data from an amazon url but am having some issues.
url = 'https://www.amazon.ca/Nintendo-SwitchTM-Neon-Blue-Joy-E2-80-91ConTM-dp-B0BFJWCYTL/dp/B0BFJWCYTL/ref=dp_ob_title_vg'
headers = {"User-Agent": "... | [
"As you can see below, searching for \"corePriceDisplay_desktop_feature_div\" is far to broad. Searching for span element with class=\"a-offscreen\" should fit your needs.\nTry:\nprice = soup.find(\"span\", {\"class\": \"a-offscreen\"})\n\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"jupyter_notebook",
"python",
"web_scraping"
] | stackoverflow_0074551550_beautifulsoup_jupyter_notebook_python_web_scraping.txt |
Q:
how to change the date if it is sunday or saturday in batch file
I have to a run a python script in command line and pass the date as argument and below is my command to run the date
parser = argparse.ArgumentParser()
parser.add_argument('date')
tdate= parser.parse_args().date
i would like to change this to check... | how to change the date if it is sunday or saturday in batch file | I have to a run a python script in command line and pass the date as argument and below is my command to run the date
parser = argparse.ArgumentParser()
parser.add_argument('date')
tdate= parser.parse_args().date
i would like to change this to check if it is sunday or saturday. If it is saturday, tdate should be tdate... | [
"If I'm understanding correctly, you want it so that if the current day is either Saturday or Sunday, then the entered date that is passed as a command line argument should be date - 1 day or date - 2 days.\nSo, if today's date is passed (11/23/2022) on Monday-Friday it'll return the date as is but if the same date... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074551335_pandas_python.txt |
Q:
Is there a fast way to find the first offset at which two large byte sequences differ?
I can use a for loop to loop over two byte sequences and return the index at the first difference of course:
bytes1 = b'12345'
bytes2 = b'1F345'
for index, pair in enumerate(zip(bytes1, bytes2)):
if pair[0] != pair[1]:
... | Is there a fast way to find the first offset at which two large byte sequences differ? | I can use a for loop to loop over two byte sequences and return the index at the first difference of course:
bytes1 = b'12345'
bytes2 = b'1F345'
for index, pair in enumerate(zip(bytes1, bytes2)):
if pair[0] != pair[1]:
print(index)
break
But I don't think that's a smart and fast way to do it. I wou... | [
"a solution with numpy is to convert them to an array of uint8 then xor them and use argmax to get the first non-zero.\nimport numpy as np\nbytes1 = b'12345'\nbytes2 = b'1F345'\nbytes3 = np.frombuffer(bytes1,dtype=np.uint8)\nbytes4 = np.frombuffer(bytes2,dtype=np.uint8)\nmax_loc = np.flatnonzero(bytes3 ^ bytes4)[0]... | [
2,
1
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0074552142_performance_python.txt |
Q:
Reverse a get_dummies encoding in pandas
Column names are: ID,1,2,3,4,5,6,7,8,9.
The col values are either 0 or 1
My dataframe looks like this:
ID 1 2 3 4 5 6 7 8 9
1002 0 1 0 1 0 0 0 0 0
1003 0 0 0 0 0 0 0 0 0
1004 1 1 0 0 ... | Reverse a get_dummies encoding in pandas | Column names are: ID,1,2,3,4,5,6,7,8,9.
The col values are either 0 or 1
My dataframe looks like this:
ID 1 2 3 4 5 6 7 8 9
1002 0 1 0 1 0 0 0 0 0
1003 0 0 0 0 0 0 0 0 0
1004 1 1 0 0 0 0 0 0 0
1005 0 0 0 0 ... | [
"Pretty one-liner :)\nnew_df = df.idxmax(axis=1)\n\n",
"Several great answers for the OP post. However, often get_dummies is used for multiple categorical features. Pandas uses a prefix separator prefix_sep to distinguish different values for a column. \nThe following function collapses a \"dummified\" dataframe ... | [
29,
19,
18,
4,
3,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0050607740_dataframe_pandas_python.txt |
Q:
How to sort MultiIndex using values from a given column
I have a DataFrame with 2-level index and column with the numerical values. I want to sort it by level-0 and level-1 index in such a way that the the order of 0-level index is determined by the sum of values from Value column (descending), and the order of 1-... | How to sort MultiIndex using values from a given column | I have a DataFrame with 2-level index and column with the numerical values. I want to sort it by level-0 and level-1 index in such a way that the the order of 0-level index is determined by the sum of values from Value column (descending), and the order of 1-level index is also determined by the values in Value column.... | [
"You can do this with pandas.DataFrame.sort_values :\nout= (\n df\n .assign(temp_col = df.groupby(level=0).transform(\"sum\"))\n .sort_values(by=[\"temp_col\", \"Value\"], ascending=[False, False])\n .drop(columns=\"temp_col\")\n )\n\n# Output :\nprint(out)\n\n Value... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074552607_dataframe_pandas_python.txt |
Q:
When is the usage of the Python Ellipsis to be preferred over 'pass'?
I was just looking up the way to go for defining an abstract base class in Python, when I found the abc module (https://docs.python.org/3/library/abc.html).
After a bit of reading I saw the following class:
class C(ABC):
@abstractmethod
... | When is the usage of the Python Ellipsis to be preferred over 'pass'? | I was just looking up the way to go for defining an abstract base class in Python, when I found the abc module (https://docs.python.org/3/library/abc.html).
After a bit of reading I saw the following class:
class C(ABC):
@abstractmethod
def my_abstract_method(self, ...):
...
@classmethod
@abstra... | [
"Using the Ellipsis literal as the body of a function does nothing. It's purely a matter of style if you use it instead of pass or some other statement. If you give your function a docstring, you don't even need to put any statement after the line with the docstring.\nIf the official Python documentation is inconsi... | [
37,
17,
13,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0055274977_python.txt |
Q:
AttributeError: 'WebDriver' object has no attribute 'execute_cdp_cmd'
I am trying to set geolocation based on this documentation: https://www.selenium.dev/documentation/en/support_packages/chrome_devtools/
I am using selenium==4.0.0b2
I am running remote webdriver instead of local, and I am getting the following e... | AttributeError: 'WebDriver' object has no attribute 'execute_cdp_cmd' | I am trying to set geolocation based on this documentation: https://www.selenium.dev/documentation/en/support_packages/chrome_devtools/
I am using selenium==4.0.0b2
I am running remote webdriver instead of local, and I am getting the following error:
AttributeError: 'WebDriver' object has no attribute 'execute_cdp_cmd'... | [
"I also have this problem. But I am using is VB.NET at Visual Studio cannot find any Chrome Devtool.\nAnd at the end I found a nuget that is\nhttps://github.com/ToCSharp/AsyncChromeDriver\nYou can try to look at.\n",
"In my case I was following example from Selenium - python. how to capture network traffic's resp... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium4",
"selenium_chromedriver"
] | stackoverflow_0066817547_python_python_3.x_selenium_selenium4_selenium_chromedriver.txt |
Q:
Does tf.histogram_fixed_width() support back propagation?
I want to use the histogram of the output from a CNN to compute the loss. I am wondering whether tf.histogram_fixed_width() supports the gradient to flow back to its former layer. Only it works, I can add a loss layer after calculating the histogram.
A:
t... | Does tf.histogram_fixed_width() support back propagation? | I want to use the histogram of the output from a CNN to compute the loss. I am wondering whether tf.histogram_fixed_width() supports the gradient to flow back to its former layer. Only it works, I can add a loss layer after calculating the histogram.
| [
"tf.histogram_fixed_width() does not support autogradient functionality since histogram is not a continuous differential function. You can look at the following example which returns gradient None.\nimport keras.backend as K\nimport tensorflow as tf\n\nvalue_range = [0.0, 5.0]\na = np.array([-1.0, 0.0, 1.5, 2.0, 5.... | [
2,
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0046394659_python_tensorflow.txt |
Q:
Launch multiple tkinter applications in separate threads
I am trying to launch multiple instances of a tkinter class in separate threads. Everytime the second screen appears, the following error is thrown: "_tkinter.TclError: image "pyimage2" doesn't exist". I expected them to be two separate instances, but accord... | Launch multiple tkinter applications in separate threads | I am trying to launch multiple instances of a tkinter class in separate threads. Everytime the second screen appears, the following error is thrown: "_tkinter.TclError: image "pyimage2" doesn't exist". I expected them to be two separate instances, but according to internet searches this is not the case.
Here's a simpli... | [
"\nEverytime the second screen appears, the following error is thrown: \"_tkinter.TclError: image \"pyimage2\" doesn't exist\". I expected them to be two separate instances, but according to internet searches this is not the case.\n\nThey are separate instances, which is why you're seeing the error. You didn't spec... | [
2
] | [] | [] | [
"python",
"tcl",
"tk_toolkit",
"tkinter"
] | stackoverflow_0074552455_python_tcl_tk_toolkit_tkinter.txt |
Q:
Create empty square Dataframe from single column DataFrame
I have the following single column DataFrame:
df:
data = {'YEAR': [2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030],
}
df = pd.DataFrame(data)
df
How can I create an empty square Dataframe from df like the following DatFrame:
I´m kind... | Create empty square Dataframe from single column DataFrame | I have the following single column DataFrame:
df:
data = {'YEAR': [2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030],
}
df = pd.DataFrame(data)
df
How can I create an empty square Dataframe from df like the following DatFrame:
I´m kinda new to Python. I have tried converting the original Dataframme... | [
"Try provide both index and columns as Year when creating the data frame:\ndf = pd.DataFrame([], index=data['YEAR'], columns=data['YEAR'])\ndf\n 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030\n2020 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n2021 NaN NaN NaN NaN NaN NaN NaN NaN NaN ... | [
1,
1,
1,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074552855_dataframe_numpy_pandas_python.txt |
Q:
Python Z3, rule to make 2 numbers be 2 certain numbers in a 2D array
If i have 2 z3 Ints for examaple x1 and x2, and a 2d array of numbers for example:
list = [[1,2],[12,13],[45,7]]
i need to right a rule so that x1 and x2 are any of the pairs of numbers in the list for example x1 would be 1 and x2 would be 2 or x... | Python Z3, rule to make 2 numbers be 2 certain numbers in a 2D array | If i have 2 z3 Ints for examaple x1 and x2, and a 2d array of numbers for example:
list = [[1,2],[12,13],[45,7]]
i need to right a rule so that x1 and x2 are any of the pairs of numbers in the list for example x1 would be 1 and x2 would be 2 or x1 is 12 and x2 is 13
im guessing it would be something like:
solver = Solv... | [
"You're on the right track. Simply iterate and form the disjunction instead. Something like:\nfrom z3 import *\n\nlist = [[1,2],[12,13],[45,7]]\n\ns = Solver()\nx1, x2 = Ints('x1 x2')\ns.add(Or([And(x1 == p[0], x2 == p[1]) for p in list]))\n\nwhile s.check() == sat:\n m = s.model()\n print(\"x1 = %2d, x2 = %2d\" ... | [
0
] | [] | [] | [
"list",
"list_comprehension",
"python",
"z3",
"z3py"
] | stackoverflow_0074552664_list_list_comprehension_python_z3_z3py.txt |
Q:
Find enums listed in Python DESCRIPTOR for ProtoBuf
I have received a Google ProtoBuf using Python, and am attempting to compare the value for an enum to a string representation of it. Based on this and this I should be able to use something like enum_values_by_name to get the info I need. However, all the enum* r... | Find enums listed in Python DESCRIPTOR for ProtoBuf | I have received a Google ProtoBuf using Python, and am attempting to compare the value for an enum to a string representation of it. Based on this and this I should be able to use something like enum_values_by_name to get the info I need. However, all the enum* related attributes are empty:
>>> type(my_message)
<class ... | [
"I don't know why the DESCRIPTOR for the message includes enum attributes that are not populated. (This seems like a bug to me.) However, there are (at least) two solutions to this:\n1) If you know the name of the file where the enums are defined, you can 'hack' get the enum value by name via:\n# This is the root P... | [
3,
1,
1
] | [] | [] | [
"protocol_buffers",
"python",
"python_3.x"
] | stackoverflow_0040226049_protocol_buffers_python_python_3.x.txt |
Q:
Faster list manipulation
I have a large numpy array whNumPylements I individually want to multiply with other indexes and then sum up. My current code is relatively slow, does anyone have an idea how I could make it faster:
result = 0
n = 1
int_array = np.array((3,16,3,29,36))
for i in int_array:
result += int... | Faster list manipulation | I have a large numpy array whNumPylements I individually want to multiply with other indexes and then sum up. My current code is relatively slow, does anyone have an idea how I could make it faster:
result = 0
n = 1
int_array = np.array((3,16,3,29,36))
for i in int_array:
result += int(i) * n
n *= 10
| [
"In every iteration 10 * prev(10 * ...), So you can use 10 ^ [0, 1, 2, ...] = [1, 10, 100, ...] with numpy.array & numpy.power. Then you need [1*int_arr[0], 10*int_arr[1], ...]. At the end, you need numpy.sum().\nres = (np.power(10, np.arange(int_array.shape[0])) * int_array).sum()\n\nprint(res)\n\nOutput:\n389463\... | [
2
] | [
"I think i have understood that you want to progressively multiply each number of the array by n, and n is going to be multiplied by 10 each loop. Is that is what you want to do, I think there is nothing much to do. The only thing is that you dont need to convert i to an int, as i is already one\n"
] | [
-1
] | [
"numpy",
"python"
] | stackoverflow_0074552950_numpy_python.txt |
Q:
Print specified text from .txt file
im a beginner with python, I wrote a simple webscraper script which returned a html code and printed it into the output2.txt file, and I need to print out thats behind "title=", but I cant seem to do so.
I tried .find method which returned the list of indexes, now I'm stuck at h... | Print specified text from .txt file | im a beginner with python, I wrote a simple webscraper script which returned a html code and printed it into the output2.txt file, and I need to print out thats behind "title=", but I cant seem to do so.
I tried .find method which returned the list of indexes, now I'm stuck at how to print the text starting from the in... | [
"Take a look at this SO answer: Extract title with BeautifulSoup\nCopying from that answer, it looks like you should be doing something like\nfrom bs4 import BeautifulSoup\n\nhtml = \"\"\nwith open('output2.txt', 'r', encoding='utf-8') as f:\n html = f.read()\n\nsoup = BeautifulSoup(html, 'html.parser')\ntitle =... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074552796_python_python_3.x.txt |
Q:
Using the unpacking operator '*' in Python
I have encountered some weird behaviour using the unpacking operator '*' in Python.
L = [1,2,3]
print(*L if len(L)<=2 else f"{L[0]}-{L[-1]}")
Running the above code I was expecting the output "1-3" but instead i get "1 - 3". Am I using the '*'-operator wrong? Or are my... | Using the unpacking operator '*' in Python | I have encountered some weird behaviour using the unpacking operator '*' in Python.
L = [1,2,3]
print(*L if len(L)<=2 else f"{L[0]}-{L[-1]}")
Running the above code I was expecting the output "1-3" but instead i get "1 - 3". Am I using the '*'-operator wrong? Or are my if/else-statements wrong?
I tried changing the ... | [
"This expression is parsed as\nprint(*(L if len(L)<=2 else f\"{L[0]}-{L[-1]}\"))\n\nwhich, for the given L, is equivalent to:\nprint(*'1-3')\n\nwhich is in turn the same as:\nprint('1', '-', '3')\n\nAnd that's where the spaces are coming from.\n"
] | [
3
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074552920_python_python_3.x.txt |
Q:
How to use variable instead of xpath value in Selenium ...find_element(By.XPATH, "xpath")
Is there a way to use variable instead of string value for the xpath?
I am using:
driver.find_element(By.XPATH, "xpath-value-string")
But I need to replace the string (the xpath value) and use variable instead like this:
my_... | How to use variable instead of xpath value in Selenium ...find_element(By.XPATH, "xpath") | Is there a way to use variable instead of string value for the xpath?
I am using:
driver.find_element(By.XPATH, "xpath-value-string")
But I need to replace the string (the xpath value) and use variable instead like this:
my_xpath = "xpath-value-string"
driver.find_element(By.XPATH, my_xpath)
The goal is to pull vario... | [
"Maybe something like this:\nxpaths = ['xpath_example_1', 'xpath_example_2']\nfor xpath in xpaths:\n driver.find_element(By.XPATH, xpath)\n\n"
] | [
1
] | [] | [] | [
"python",
"selenium4",
"variables",
"xpath"
] | stackoverflow_0074552982_python_selenium4_variables_xpath.txt |
Q:
how to exclude words in regex using Negative Lookahead?
I am trying to exclude a word from a sentence, but if the excluded word does not appear, the regex should keep searching for characters until the exclude word is found.
For example, lets suppose I have a list like this:
S.no Vehicle Status
1 car ... | how to exclude words in regex using Negative Lookahead? | I am trying to exclude a word from a sentence, but if the excluded word does not appear, the regex should keep searching for characters until the exclude word is found.
For example, lets suppose I have a list like this:
S.no Vehicle Status
1 car sold
2 car not sold
3 car ... | [
"You can write the pattern like this:\npattern = r\"\\bcar\\b(?!\\s+sold\\b).+\"\n\nExplanation\n\n\\bcar\\b Match the word car\n(?!\\s+sold\\b) Assert not 1+ whitespace chars followed by the word \"sold\" to the right\n.+ Match 1+ chars\n\nSee a regex demo.\nIf there has to be a non whitespace char present after \... | [
1
] | [] | [] | [
"python",
"regex",
"regex_lookarounds",
"web_crawler",
"web_scraping"
] | stackoverflow_0074549686_python_regex_regex_lookarounds_web_crawler_web_scraping.txt |
Q:
How can I get a pandas dataframe into CSV format with different formats per columns?
Issues for pandas' DataFrame text output functions:
to_csv() does not support the 'formatters' parameter of to_string(). I need different formats for each column.
to_string() does not support a separator.
What I do so far:
I gen... | How can I get a pandas dataframe into CSV format with different formats per columns? | Issues for pandas' DataFrame text output functions:
to_csv() does not support the 'formatters' parameter of to_string(). I need different formats for each column.
to_string() does not support a separator.
What I do so far:
I generate a list of formatting strings in the new Python formatting format, so e.g. ['{8.1f}',... | [
"np.savetxt can do it (by supplying fmt argument, which can be a list), but that means the column names has to be written separately (header argument):\nnp.savetxt('temp.csv', df.values, fmt=['%8.1f','%9.3f','%8.1f','%9.3f','%8.1f'], \n delimiter=',', header=' '+' ,'.join(df.columns), comments='')... | [
3,
0
] | [] | [] | [
"csv",
"io",
"pandas",
"python"
] | stackoverflow_0023124128_csv_io_pandas_python.txt |
Q:
Manipulate string data into excel file
I have data in string format like
str1 = "[0,-1.5],[-12.5,1.5],[12.5,1.5],[12.5,-1.5],[-12.5,-1.5])"
I want to put this data into an excel file. means 1st value from the array will go in x Col and 2nd value will go in Y col. this will be repeated until the whole string will ... | Manipulate string data into excel file | I have data in string format like
str1 = "[0,-1.5],[-12.5,1.5],[12.5,1.5],[12.5,-1.5],[-12.5,-1.5])"
I want to put this data into an excel file. means 1st value from the array will go in x Col and 2nd value will go in Y col. this will be repeated until the whole string will be added to the x and y columns. I am attemp... | [
"You can use pandas.Series.str.extractall :\nout = (\n pd.Series([str1])\n .str.extractall(r\"(-?\\d+\\.?\\d*,-?\\d+\\.?\\d*)\")\n .reset_index(drop=True)\n [0].str.split(\",\", expand=True)\n .rename(columns= {0: \"X\", 1: \"Y\"})\n .applymap('=\"{}\"'.... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074552906_dataframe_pandas_python.txt |
Q:
How to read Youtube Videos with OpenCV at specific timestamps and set duration without downloading it?
I have tried using pafy but it plays the video from beginning, I want to run my model on specific parts of the video. If this is possible please guide me how to do it.
Any help is appreciated, thanks in advance :... | How to read Youtube Videos with OpenCV at specific timestamps and set duration without downloading it? | I have tried using pafy but it plays the video from beginning, I want to run my model on specific parts of the video. If this is possible please guide me how to do it.
Any help is appreciated, thanks in advance :)
| [
"It was quite easy actually, I figured it out :)\nHere's the code:\nimport cv2\nimport pafy\n\n#Ask the user for url input\nurl = input(\"Enter Youtube Video URL: \")\n\n#Getting video id from the url string\nurl_data = urlparse.urlparse(url)\nquery = urlparse.parse_qs(url_data.query)\nid = query[\"v\"][0]\nvideo =... | [
1,
1
] | [] | [] | [
"opencv",
"pafy",
"python",
"youtube",
"youtube_dl"
] | stackoverflow_0069400984_opencv_pafy_python_youtube_youtube_dl.txt |
Q:
append values to spinner dynamically
I'm trying to write some basic GUI using Kivy.
My program loads some data from a CSV file that contains an unknown number of rows.
The first column is called sValue which basically tells me the "id" of the spinner and the second column has a Name value.
My goal is to iterate al... | append values to spinner dynamically | I'm trying to write some basic GUI using Kivy.
My program loads some data from a CSV file that contains an unknown number of rows.
The first column is called sValue which basically tells me the "id" of the spinner and the second column has a Name value.
My goal is to iterate all of the rows inside this CSV and to creat... | [
"You can modify your loop to add the values to existing Spinner instances:\n for ind, row in Data.iterrows():\n try:\n spinner = self.spinnerObject[row['sValue']]\n except:\n spinner = Spinner(text='sValue %d' % row['sValue'], values=[])\n self.spinnerObject[row['sV... | [
0
] | [] | [] | [
"kivy",
"python",
"spinner"
] | stackoverflow_0074551260_kivy_python_spinner.txt |
Q:
transfer the value from def() to another def()
How can I transfer the value of the mes variable from one function to another?
def forwardmes2withdelay(message):
print(message.text)
if message.text == 'Главное меню':
button = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
conta... | transfer the value from def() to another def() | How can I transfer the value of the mes variable from one function to another?
def forwardmes2withdelay(message):
print(message.text)
if message.text == 'Главное меню':
button = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
contacts = types.KeyboardButton('Контакты')
post ... | [
"First, you need to have your def functions inside the class.\nSecond. you need to have your variables declared inside that class.\nThis way you can change that variable in one function and then use it in another function. Just like the example below.\nTo access it you need to use \"self.\"\nclass Person():\n de... | [
0
] | [] | [] | [
"function",
"python",
"telebot"
] | stackoverflow_0074553141_function_python_telebot.txt |
Q:
how does indexing work in a for loop when appending a list?
I´m trying write a function that returns a list with the positions for each capital letter it doesn’t work with when the capital letter in the string is repeated.
def capital_indexes(word):
cap = []
for i in word:
if i == i.upper():
... | how does indexing work in a for loop when appending a list? | I´m trying write a function that returns a list with the positions for each capital letter it doesn’t work with when the capital letter in the string is repeated.
def capital_indexes(word):
cap = []
for i in word:
if i == i.upper():
cap.append(word.index(i))
return cap
print(capital_ind... | [
"I think that index method is returning the first occurrence of character.\nMaybe you should control the index of letter by an another var like this:\ndef capital_indexes(word):\n cap = []\n index = 0\n for i in word:\n if i == i.upper():\n cap.append(index)\n index=index+1\n re... | [
0,
0
] | [] | [] | [
"append",
"for_loop",
"indexing",
"python"
] | stackoverflow_0074553126_append_for_loop_indexing_python.txt |
Q:
How to detect #N/A in a data frame (data taken from xlsx file) using pandas?
The blank cells with no data can be checked with:
if pd.isna(dataframe.loc[index_name, column_name] == True)
but if the cell has #N/A, the above command does not work nor
dataframe.loc[index, column_name] == '#N/A'.
On reading that cell,... | How to detect #N/A in a data frame (data taken from xlsx file) using pandas? | The blank cells with no data can be checked with:
if pd.isna(dataframe.loc[index_name, column_name] == True)
but if the cell has #N/A, the above command does not work nor
dataframe.loc[index, column_name] == '#N/A'.
On reading that cell, it shows NaN, but the above codes does not work. My main target is to capture the... | [
"If you're reading your dataframe tft from a spreadsheet (and it seems to be the case here), you can use the parameter na_values of pandas.read_excel to consider some values (e.g #N/A) as NaN values like below :\ntft= pd.read_excel(\"path_to_the_file.xlsx\", na_values=[\"#N/A\"])\n\nOtherwise, if you want to preser... | [
1
] | [] | [] | [
"dataframe",
"nan",
"pandas",
"python",
"syntax_error"
] | stackoverflow_0074553226_dataframe_nan_pandas_python_syntax_error.txt |
Q:
How to pass '\x00' from python to c function?
python:
msg = b'aaa\x01' + b'\x00' + b'\x23\x45cc'
dl = cdll.LoadLibrary
lib = dl("./test.so")
lib.send.argtypes = c_char_p
lib.send(msg)
c (test.so):
void send(char * msg)
{
// printf("%s", msg);
SSL_write(ssl, msg, strlen(msg));
}
how can I p... | How to pass '\x00' from python to c function? | python:
msg = b'aaa\x01' + b'\x00' + b'\x23\x45cc'
dl = cdll.LoadLibrary
lib = dl("./test.so")
lib.send.argtypes = c_char_p
lib.send(msg)
c (test.so):
void send(char * msg)
{
// printf("%s", msg);
SSL_write(ssl, msg, strlen(msg));
}
how can I pass '\x00' and what's behind it in?
Thanks!
| [
"As indicated in comments, printf with %s only prints a char* up to the first null byte found. The C function needs to know the size and some of your bytes are non-printing characters, so printing the bytes in hexadecimal for the specified length is an option:\ntest.c\n#include <stdio.h>\n#include <stdlib.h>\n\n#i... | [
1
] | [] | [] | [
"c",
"ctypes",
"python"
] | stackoverflow_0074549959_c_ctypes_python.txt |
Q:
How to compare two serializer field and show whichever is higher in django rest
I have product serializer which return category_offer_price & product_offer_price,
before getting this response I want to compare both price and only return whichever is highest price.
#Serilaizer.py
class ProductSerializer(ModelSerial... | How to compare two serializer field and show whichever is higher in django rest | I have product serializer which return category_offer_price & product_offer_price,
before getting this response I want to compare both price and only return whichever is highest price.
#Serilaizer.py
class ProductSerializer(ModelSerializer):
category = CategorySerializer()
product_offer_price = SerializerMethod... | [
"You can move into one method, to validate your field. Also, substitute your try:except with get-object-or-404 method and your serializer fields with all value since you are using everything, to have a much cleaner code.\nfrom django.shortcuts import get_object_or_404\n\nclass ProductSerializer(ModelSerializer):\n ... | [
2,
2,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074527264_django_django_rest_framework_python.txt |
Q:
player collision not working properly with jump mechanic
When jumping multiple times, the player can phase through the map. I would assume this is due to the player.y -= yvel line but I cant exactly see a work around.
Here is my code, im not sure why the section that stops collision isn't working, it seems as thou... | player collision not working properly with jump mechanic | When jumping multiple times, the player can phase through the map. I would assume this is due to the player.y -= yvel line but I cant exactly see a work around.
Here is my code, im not sure why the section that stops collision isn't working, it seems as though it should stop all movement that results in collision. Hope... | [
"You must limit the position of the player rectangle depending on the direction of movement with the bottom or top of the tile with which the player collides. e.g.:\nwhile True:\n # [...]\n\n player.y += yvel\n ti = player.collidelist(tile_map)\n if ti >= 0:\n if yvel < 0:\n player.top... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074553124_pygame_python.txt |
Q:
How to replace values in nested dictionaries by new values in a list in python
I am iterating through a list of dictionaries. I need to update the values for one specific key in all the dictionaries and I have the new values stored in a list. The list of new values is ordered so that the 1st new value belongs to a... | How to replace values in nested dictionaries by new values in a list in python | I am iterating through a list of dictionaries. I need to update the values for one specific key in all the dictionaries and I have the new values stored in a list. The list of new values is ordered so that the 1st new value belongs to a key in the 1st dictionary, 2nd new value to a key in the 2nd dictionary, etc.
My da... | [
"If your new_jobs list has the right job for each corresponding entry in the dict list, you could use zip:\ndict_list = [{'person':'Tom', 'job':'student'},\n {'person':'John', 'job':'teacher'},\n {'person':'Mary', 'job':'manager'}]\nnew_jobs = ['lecturer', 'cook', 'driver']\n\nfor d, j in zip(... | [
1,
1,
1
] | [] | [] | [
"dictionary",
"dictionary_comprehension",
"for_loop",
"list",
"python"
] | stackoverflow_0074553173_dictionary_dictionary_comprehension_for_loop_list_python.txt |
Q:
Python class decorator arguments
I'm trying to pass optional arguments to my class decorator in python.
Below the code I currently have:
class Cache(object):
def __init__(self, function, max_hits=10, timeout=5):
self.function = function
self.max_hits = max_hits
self.timeout = timeout
... | Python class decorator arguments | I'm trying to pass optional arguments to my class decorator in python.
Below the code I currently have:
class Cache(object):
def __init__(self, function, max_hits=10, timeout=5):
self.function = function
self.max_hits = max_hits
self.timeout = timeout
self.cache = {}
def __call_... | [
"@Cache(max_hits=100, timeout=50) calls __init__(max_hits=100, timeout=50), so you aren't satisfying the function argument.\nYou could implement your decorator via a wrapper method that detected whether a function was present. If it finds a function, it can return the Cache object. Otherwise, it can return a wrappe... | [
24,
24,
7,
4,
3,
0,
0,
0
] | [] | [] | [
"arguments",
"decorator",
"python"
] | stackoverflow_0007492068_arguments_decorator_python.txt |
Q:
Can I use two Gherkin Annotations on a single step implementation?
Is it possible to use two different Gherkin steps on a step implementation?
@Given('a user signs up for a new "{country}" account')
@Then('Select "{country}" on country selector')
def choose_country(context, country):
match country:
cas... | Can I use two Gherkin Annotations on a single step implementation? | Is it possible to use two different Gherkin steps on a step implementation?
@Given('a user signs up for a new "{country}" account')
@Then('Select "{country}" on country selector')
def choose_country(context, country):
match country:
case "Country A":
context.country_code = "A"
case "Coun... | [
"Short answer, no. It should recognize one step as not being implemented. Perhaps some steps shouldn't exist ? Here's a link to more information about the subject.\n"
] | [
1
] | [] | [] | [
"bdd",
"cucumber",
"gherkin",
"python"
] | stackoverflow_0074553140_bdd_cucumber_gherkin_python.txt |
Q:
clicking a tab on a page to alow selenium to scrape
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time imp... | clicking a tab on a page to alow selenium to scrape | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time import sleep
from datetime import datetime
import pandas as ... | [
"In case you want to click on \"LINE UP\" tab this can be done with the following XPath: \"//div[text()='LINE UP']\". To click on \"STATS\" tab you can use this XPath: \"//div[text()='STATS']\". So, Selenium code line can be as following:\nWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, \"//di... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping",
"xpath"
] | stackoverflow_0074553164_python_selenium_selenium_webdriver_web_scraping_xpath.txt |
Q:
making a request to find members of a group in GCP
this is the request I need to make (trying to get list of members in a google group):
GET https://admin.googleapis.com/admin/directory/v1/groups/{groupKey}/members
https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/list?apix_params=%7B%22... | making a request to find members of a group in GCP | this is the request I need to make (trying to get list of members in a google group):
GET https://admin.googleapis.com/admin/directory/v1/groups/{groupKey}/members
https://developers.google.com/admin-sdk/directory/reference/rest/v1/members/list?apix_params=%7B%22groupKey%22%3A%22devops%40flight-analytics.com%22%2C%22i... | [
"gcloud auth login authorizes the CLI (gcloud). Use gcloud auth application-default login to authorize application credentials.\ngcloud auth application-default login\n"
] | [
2
] | [] | [] | [
"authentication",
"google_cloud_platform",
"google_groups_api",
"python",
"python_requests"
] | stackoverflow_0074551482_authentication_google_cloud_platform_google_groups_api_python_python_requests.txt |
Q:
yarl/_quoting.c:196:12: fatal error: 'longintrepr.h' file not found - 1 error generated
Python version: 3.11
Installing dependencies for an application by pip install -r requirements.txt gives the error below. This error is specific to Python 3.11 version. On Python with 3.10.6 version installation goes fine.
Rela... | yarl/_quoting.c:196:12: fatal error: 'longintrepr.h' file not found - 1 error generated | Python version: 3.11
Installing dependencies for an application by pip install -r requirements.txt gives the error below. This error is specific to Python 3.11 version. On Python with 3.10.6 version installation goes fine.
Related question: ERROR: Could not build wheels for aiohttp, which is required to install pyproje... | [
"Solution for this error: need to update requirements.txt.\nNot working versions of modules with Python 3.11:\nyarl==1.4.2\nfrozenlist==1.3.0\naiohttp==3.8.1\n\nWorking versions:\nyarl==1.8.1\nfrozenlist==1.3.1\naiohttp==3.8.2\n\nLinks to the corresponding issues with fixes:\n\nhttps://github.com/aio-libs/yarl/issu... | [
0
] | [] | [] | [
"linux",
"pip",
"python",
"termux"
] | stackoverflow_0074553366_linux_pip_python_termux.txt |
Q:
AttributeError: module 'collections' has no attribute 'Iterator' python 3.10 django 2.0
Hello its a clone project but when ı try "python manage.py makemigrations" ım getting this error how can ı fix it?
requirements
django==2.0 django-ckeditor==5.4.0
django-cleanup==2.1.0 django-crispy-forms==1.7.2
django-js-as... | AttributeError: module 'collections' has no attribute 'Iterator' python 3.10 django 2.0 | Hello its a clone project but when ı try "python manage.py makemigrations" ım getting this error how can ı fix it?
requirements
django==2.0 django-ckeditor==5.4.0
django-cleanup==2.1.0 django-crispy-forms==1.7.2
django-js-asset==1.0.0
this error
error 2
| [
"You are using a very old version of Django (we are currently in version 4.1.x!) which is incompatible with python3.10.\nIterator was moved from collections to collections.abc (I think in version 3.3).\nIn order to fix this issue you must either downgrade your python version to something before python3.3 (which is ... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0072330021_django_python.txt |
Q:
SageMaker Batch Transform Input filter
I am trying to run inference using SageMaker Batch Transform.
My data input for prediction has two columns:
ID, Text
Basically, doing some prediction based on test data.
However, I do not need ID field going to the prediction.
I tried using input_filter="[1:]", and the job k... | SageMaker Batch Transform Input filter | I am trying to run inference using SageMaker Batch Transform.
My data input for prediction has two columns:
ID, Text
Basically, doing some prediction based on test data.
However, I do not need ID field going to the prediction.
I tried using input_filter="[1:]", and the job keeps failing.
Below is my setup:
transformer... | [
"$[1:]: indicates that we are excluding column 0 (the 'ID') before processing the inferences and keeping everything from column 1 to the last column (all the features)\nKindly see this example that showcases how to make use of input/output/joining filter feature of Batch Transform.\n"
] | [
0
] | [] | [] | [
"amazon_sagemaker",
"python"
] | stackoverflow_0074495545_amazon_sagemaker_python.txt |
Q:
How to get information from excel through an input using pandas python?
How I can get information from specific lines of an excel using a variable entry placed by the user, I managed to find the information, but I can't integrate it.
import pandas as pd
dados = pd.read_excel(r"Dados.xlsx")
CPF = input('Digite o C... | How to get information from excel through an input using pandas python? | How I can get information from specific lines of an excel using a variable entry placed by the user, I managed to find the information, but I can't integrate it.
import pandas as pd
dados = pd.read_excel(r"Dados.xlsx")
CPF = input('Digite o CPF: ')
if CPF in dados:
print(dados.iloc[CPF][['CPF', 'Agencia', 'Conta'... | [
"If I understand well your question use this :\nimport pandas as pd\n\ndados = pd.read_excel(r\"Dados.xlsx\")\n\nCPF = int(input('Digite o CPF: '))\n\nif CPF in dados['CPF'].to_list():\n print(dados.loc[dados['CPF'].eq(CPF), ['CPF', 'Agencia', 'Conta']])\nelse:\n print('Não encontrado')\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074553290_pandas_python.txt |
Q:
Travelling Salesman in scipy
How do I solve a Travelling Salesman problem in python? I did not find any library, there should be a way using scipy functions for optimization or other libraries.
My hacky-extremelly-lazy-pythonic bruteforcing solution is:
tsp_solution = min( (sum( Dist[i] for i in izip(per, per[1:])... | Travelling Salesman in scipy | How do I solve a Travelling Salesman problem in python? I did not find any library, there should be a way using scipy functions for optimization or other libraries.
My hacky-extremelly-lazy-pythonic bruteforcing solution is:
tsp_solution = min( (sum( Dist[i] for i in izip(per, per[1:])), n, per) for n, per in enumerate... | [
"The scipy.optimize functions are not constructed to allow straightforward adaptation to the traveling salesman problem (TSP). For a simple solution, I recommend the 2-opt algorithm, which is a well-accepted algorithm for solving the TSP and relatively straightforward to implement. Here is my implementation of th... | [
25,
0
] | [] | [] | [
"optimization",
"python",
"scipy",
"traveling_salesman"
] | stackoverflow_0025585401_optimization_python_scipy_traveling_salesman.txt |
Q:
How to save all the lines in lists Python
I am trying to get all the lines from my input file and save them in the lists dataset_texts and dataset_labels. But instead I am getting only the last line of my input file.
The variable text_str gets the text sequence in the line and the variable labels_str saves the ve... | How to save all the lines in lists Python | I am trying to get all the lines from my input file and save them in the lists dataset_texts and dataset_labels. But instead I am getting only the last line of my input file.
The variable text_str gets the text sequence in the line and the variable labels_str saves the vector that correspond to the text sequence in th... | [
"I believe the issue is with your regex.\nChange regexp = r'^(.*)\\t(\\d+)$' to regexp = r'^(.*)\\t(\\d+)(\\r\\n|\\r|\\n)$' so that it matches new line characters at the end of each line\nI ran into an error with this label = labels_str.index('1') after fixing the regex. So, you may want to remove that. You will al... | [
0
] | [] | [] | [
"line",
"list",
"python",
"string"
] | stackoverflow_0074547790_line_list_python_string.txt |
Q:
How to create a dictionary using a list?
I have this list(newList) where I´m trying to create a dictionary with the product as a key and the price(identified with a $) as a value, while the output of the key is correct, the only key that has a value is the last one, and I dont know what I´m doing wrong, I would ap... | How to create a dictionary using a list? | I have this list(newList) where I´m trying to create a dictionary with the product as a key and the price(identified with a $) as a value, while the output of the key is correct, the only key that has a value is the last one, and I dont know what I´m doing wrong, I would appreciate some help, thank you.
Here is a resum... | [
"Split the list into two lists, then combine them into a dictionary.\nproducts = [x for x in newList if not x.startswith(\"$\")]\nprices = [x for x in newList if x.startswith(\"$\")]\n\nproduct_prices = dict(zip(products, prices))\n\n"
] | [
3
] | [] | [] | [
"arraylist",
"dictionary",
"python"
] | stackoverflow_0074553432_arraylist_dictionary_python.txt |
Q:
Invalid character in identifier
I am working on the letter distribution problem from HP code wars 2012. I keep getting an error message that says "invalid character in identifier". What does this mean and how can it be fixed?
Here is the page with the information.
import string
def text_analyzer(text):
'''The t... | Invalid character in identifier | I am working on the letter distribution problem from HP code wars 2012. I keep getting an error message that says "invalid character in identifier". What does this mean and how can it be fixed?
Here is the page with the information.
import string
def text_analyzer(text):
'''The text to be parsed and
the number of oc... | [
"The error SyntaxError: invalid character in identifier means you have some character in the middle of a variable name, function, etc. that's not a letter, number, or underscore. The actual error message will look something like this:\n File \"invalchar.py\", line 23\n values = list(analysis.values ())\n ... | [
106,
12,
5,
3,
3,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0014844687_python_python_3.x.txt |
Q:
Convert a lambda function to a regular function
I'm trying to understand how can I convert a lambda function to a normal one. I have this lambda function that it supposed to fill the null values of each column with the mode
def fill_nn(data):
df= data.apply(lambda column: column.fillna(column.mode()[0]))
r... | Convert a lambda function to a regular function | I'm trying to understand how can I convert a lambda function to a normal one. I have this lambda function that it supposed to fill the null values of each column with the mode
def fill_nn(data):
df= data.apply(lambda column: column.fillna(column.mode()[0]))
return df
I tried this:
def fill_nn(df):
for colu... | [
"Hi Hope you are doing well!\nIf I understood your question correctly then the best possible way will be similar to this:\nimport pandas as pd\n\n\ndef fill_missing_values(series: pd.Series) -> pd.Series:\n \"\"\"Fill missing values in series/column.\"\"\"\n\n value_to_use = series.mode()[0]\n return seri... | [
0
] | [] | [] | [
"fillna",
"function",
"lambda",
"python"
] | stackoverflow_0074551640_fillna_function_lambda_python.txt |
Q:
Class attribute named the same as a local variable?
I've got the following Python code:
def GF(p, m=1):
# Yeah, I know this should be a metaclass, but I can't find a good tutorial on them
q = p ** m
class _element:
p = p
m = m
q = q
def __init__(self, value):
... | Class attribute named the same as a local variable? | I've got the following Python code:
def GF(p, m=1):
# Yeah, I know this should be a metaclass, but I can't find a good tutorial on them
q = p ** m
class _element:
p = p
m = m
q = q
def __init__(self, value):
self.value = value
def __repr__(self):
... | [
"Firstly, here's a good tutorial. Secondly, you can use the type function in python to create classes.\ntype(name, bases, attrs)\nSo to answer your question here's some code :\ndef display(self):\n return 'GF(%i, %i)(%i)' % (self.p, self.m, self.value)\n\ndef constructor(self, value):\n self.value = value\n\n... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074553344_python.txt |
Q:
How to write Python code for generating Italian car number plates?
The three-digit number changes first, then the letters from right to left. So, first plate is AA 000 AA, followed by AA 001 AA...AA 999 AA, then AA 000 AB to AA 999 AZ, then AA 000 BA to AA 999 ZZ, then AB 000 AA to AZ 999 ZZ, then BA 000 AA to ZZ ... | How to write Python code for generating Italian car number plates? | The three-digit number changes first, then the letters from right to left. So, first plate is AA 000 AA, followed by AA 001 AA...AA 999 AA, then AA 000 AB to AA 999 AZ, then AA 000 BA to AA 999 ZZ, then AB 000 AA to AZ 999 ZZ, then BA 000 AA to ZZ 999 ZZ.
| [
"Another solution, an alternative to nested loops, also quite readable.\nUse itertools.product() instead of nested loops : \"cartesian product, equivalent to a nested for-loop\".\nUse a generator expression to build the plate string, in order to keep the whole thing \"iterable\".\nfrom string import ascii_uppercase... | [
1,
0,
0
] | [
"Here's a reasonably general approach to this problem:\ndigits = [ \n # value, init, count, suffix, order \n [ 'A', 'A', 26 , '', 6], \n [ 'A', 'A', 26 , ' ', 5], \n [ '0', '0', 10, '', 2 ], \n [ '0', '0', 10, '', 1 ], \n [ '0', '0', 10, ' ', 0 ], \n [ 'A', 'A', 26 , '', 4], \n [ 'A', 'A', 26 , '', 3], \n... | [
-1
] | [
"python"
] | stackoverflow_0074552511_python.txt |
Q:
Pandas. Collapse rows with a certain time difference by summing data in other columns
I have a table with time points (timestamp). If less than a minute has passed between the points, I need to sum the timedelta and update the point's datetime boundaries.
For the rows where 'time_break' is less than 60 I need the ... | Pandas. Collapse rows with a certain time difference by summing data in other columns | I have a table with time points (timestamp). If less than a minute has passed between the points, I need to sum the timedelta and update the point's datetime boundaries.
For the rows where 'time_break' is less than 60 I need the following:
sum 'time_delta' with 'time_delta' from the previous row;
update 'ts_start' wi... | [
"Try:\nx = (\n df.groupby((df[\"time_break\"] >= 60).cumsum())\n .agg(\n {\n \"ts_start\": \"first\",\n \"ts_end\": \"last\",\n \"time_break\": \"first\",\n \"time_delta\": \"sum\",\n }\n )\n .reset_index(drop=True)\n)\n\nprint(x)\n\nPrints:\n ... | [
0
] | [] | [] | [
"dataframe",
"datetime",
"merge",
"pandas",
"python"
] | stackoverflow_0074553438_dataframe_datetime_merge_pandas_python.txt |
Q:
Getting coordinates of surface nodes using pyvista
I'm wondering if anyone could help me figure out how to apply pyvista to extract the surface nodes of a 3D object. For example, suppose I have a collection of points that builds out a sphere, including 'interior' and 'surface' points:
import numpy as np
import ma... | Getting coordinates of surface nodes using pyvista | I'm wondering if anyone could help me figure out how to apply pyvista to extract the surface nodes of a 3D object. For example, suppose I have a collection of points that builds out a sphere, including 'interior' and 'surface' points:
import numpy as np
import matplotlib.pyplot as plt
N = 50
max_rad = 1
thetavec = np... | [
"Since you've confirmed in a comment that you're looking for a convex hull, you can do this using the delaunay_3d() filter. The output of the triangulation is an UnstructuredGrid that contains a grid of tetrahedra that fills the convex hull of you mesh. Calling extract_surface() on this space-filling mesh will give... | [
1
] | [] | [] | [
"python",
"pyvista"
] | stackoverflow_0074535351_python_pyvista.txt |
Q:
Saving OpenCV output in Motion JPEG format. Getting a "'MJPG' is not supported with codec id 7" error
I'd like to save video camera output in motion JPEG (MJPG) format. The below code,
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_... | Saving OpenCV output in Motion JPEG format. Getting a "'MJPG' is not supported with codec id 7" error | I'd like to save video camera output in motion JPEG (MJPG) format. The below code,
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
frame_per_sec = int('10')
out = cv2.VideoWriter('ou... | [
".mjpeg is not a valid suffix for any known container format.\nI'm sure you didn't intend to write a raw MJPG stream without a container. That is very very rarely useful at all and requires expert knowledge.\nYou have two options:\n\nuse MJPG in a .avi container, because that's built into OpenCV and doesn't even re... | [
2
] | [] | [] | [
"ffmpeg",
"mjpeg",
"opencv",
"python",
"video"
] | stackoverflow_0074553092_ffmpeg_mjpeg_opencv_python_video.txt |
Q:
What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?
I'm trying to store 5000 data elements on an array. This 5000 elements are stored on an existinng file (therefore it's not empty).
But I'm getting an error.
IN:
def array():
name = 'puntos.df4'
m = open(name, 'rb')
v = []*5000
... | What causes the error "_pickle.UnpicklingError: invalid load key, ' '."? | I'm trying to store 5000 data elements on an array. This 5000 elements are stored on an existinng file (therefore it's not empty).
But I'm getting an error.
IN:
def array():
name = 'puntos.df4'
m = open(name, 'rb')
v = []*5000
m.seek(-5000, io.SEEK_END)
fp = m.tell()
sz = os.path.getsize(name... | [
"pickling is recursive, not sequential. Thus, to pickle a list, pickle will start to pickle the containing list, then pickle the first element… diving into the first element and pickling dependencies and sub-elements until the first element is serialized. Then moves on to the next element of the list, and so on, u... | [
27,
22,
12,
12,
3,
3,
1,
0,
0
] | [
"\nClose the opened file\nfilepath = 'model_v1.pkl' with open(filepath, 'rb') as f: p = cPickle.Unpickler(f) model = p.load() f.close()\n\nIf step 1 doesn't work; restart the session\n\n\n",
"Pickling error - _pickle.UnpicklingError: invalid load key, '<'. \nThis kind of error comes when Weights are complete or s... | [
-1,
-1
] | [
"pickle",
"python"
] | stackoverflow_0033049688_pickle_python.txt |
Q:
How can I make command line argument values get assigned to selection of 2 variables in python?
I am using the argparse package here.
There are 4 possible command line arguments in this code. I need to choose any combination of only 2 of them, for example "python script.py -arg1 int1 int2 int3 -arg4 int1 int2 int3... | How can I make command line argument values get assigned to selection of 2 variables in python? | I am using the argparse package here.
There are 4 possible command line arguments in this code. I need to choose any combination of only 2 of them, for example "python script.py -arg1 int1 int2 int3 -arg4 int1 int2 int3" and have those int values assigned to variables in for loops(see below).
How can I make it so that ... | [
"First get your two args by iterating over the four possibilities and selecting those that aren't None:\ntwo_args = [a for a in (args.arg1, args.arg2, args.arg3, args.arg4) if a]\nif len(two_args) != 2:\n print(\"Exactly two of arg1, arg2, arg3, and/or arg4 must be provided\")\n exit()\n\nThen you can get you... | [
0
] | [] | [] | [
"argparse",
"command_line_arguments",
"python"
] | stackoverflow_0074553495_argparse_command_line_arguments_python.txt |
Q:
cv2.read or Image from PIL changes PNG image color
Seems like cv2.imread() or Image.fromarray() is changing original image color to a bluish color. What i am trying to accomplish is to crop the original png image and keep the same colors but the color changes. Not sure how to revert to original color. Please help!... | cv2.read or Image from PIL changes PNG image color | Seems like cv2.imread() or Image.fromarray() is changing original image color to a bluish color. What i am trying to accomplish is to crop the original png image and keep the same colors but the color changes. Not sure how to revert to original color. Please help! ty
`
# start cropping logic
... | [
"There is no \"changing\" going on. It's simply a matter of channel order.\n\nOpenCV natively uses BGR order (in numpy arrays)\nPIL natively uses RGB order\nNumpy doesn't care\n\nWhen you call cv.imread(), you're getting BGR data in a numpy array.\nWhen you repackage that into a PIL Image, you are giving it BGR ord... | [
2
] | [] | [] | [
"cv2",
"opencv",
"python",
"python_imaging_library"
] | stackoverflow_0074552758_cv2_opencv_python_python_imaging_library.txt |
Q:
sql select column from nested associated tables
I have 4 tables in PostgreSQL:
Projects
Organizations
Organization_membership
User
CREATE TABLE IF NOT EXISTS organization(
id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (),
CONSTRAINT plan_id_fk FOREIGN KEY (plan_type)
REFERENCES plan(plan_type) MAT... | sql select column from nested associated tables | I have 4 tables in PostgreSQL:
Projects
Organizations
Organization_membership
User
CREATE TABLE IF NOT EXISTS organization(
id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (),
CONSTRAINT plan_id_fk FOREIGN KEY (plan_type)
REFERENCES plan(plan_type) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO AC... | [
"select p.* from users u\njoin organization_membership om on u.id = om.user_id\njoin organization o on om.organization_id = o.id\njoin project p on o.id = p.owner\nwhere u.id = '1';\n\nEdit: Updated as per question\n",
"It depends a lot on how you have your relationship scheme. But what about nesting SQL statemen... | [
0,
0
] | [] | [] | [
"postgresql",
"python",
"sql"
] | stackoverflow_0074553488_postgresql_python_sql.txt |
Q:
Bigquery parquet file treats list as list when empty array is passed
I have a large nested terabyte sized jsonl(s) which I am converting to parquet files and writing to a have partitioned google cloud storage bucket.
The issue is as follows. One of the nested fields is a list of string
ideally the schema for this ... | Bigquery parquet file treats list as list when empty array is passed | I have a large nested terabyte sized jsonl(s) which I am converting to parquet files and writing to a have partitioned google cloud storage bucket.
The issue is as follows. One of the nested fields is a list of string
ideally the schema for this field I expect is billing_code_modifier: list<item: string>, but there is ... | [
"For Pandas you can specify an Arrow schema as a kwarg which should provide the correct schema. See Pyarrow apply schema when using pandas to_parquet() for details.\n"
] | [
1
] | [] | [] | [
"google_bigquery",
"parquet",
"pyarrow",
"python"
] | stackoverflow_0074533897_google_bigquery_parquet_pyarrow_python.txt |
Q:
Can't get my python code to find jpg file even though it is located in the correct folder
Okay, so I cannot understand why this does not work. Every time I run the code it searches for a different picture but it never finds it. When I go to the specified location and search for the image I find it immediately. But... | Can't get my python code to find jpg file even though it is located in the correct folder | Okay, so I cannot understand why this does not work. Every time I run the code it searches for a different picture but it never finds it. When I go to the specified location and search for the image I find it immediately. But i somehow still get the same error message.[enter image description here]
id='../content/drive... | [
"You can follow these steps to get it work:\n\nMount drive and create symbolic link to specific folder you will be using, which is dog-breed-identification in your case\n\n#mount drive\n%cd ..\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n# this creates a symbolic link so that now the path /con... | [
0
] | [] | [] | [
"google_colaboratory",
"python"
] | stackoverflow_0074553331_google_colaboratory_python.txt |
Q:
Reuse colors in plot
I have a project in Jupyter notebooks where I am comparing two dataframes. Both are indexed by year, and both have the same columns representing the proportion of followers of a religion in the population. The two dataframes represent two different populations.
I want to be able to display bot... | Reuse colors in plot | I have a project in Jupyter notebooks where I am comparing two dataframes. Both are indexed by year, and both have the same columns representing the proportion of followers of a religion in the population. The two dataframes represent two different populations.
I want to be able to display both sets of data in the same... | [
"To give each line a particular color, you could capture the output of ax1.plot and iterate through that list of lines. Each line can be given its color. And also a label for the legend. \nThe following code first generates some toy data and then iterates through the lines of both plots. A legend with two columns i... | [
1,
0
] | [] | [] | [
"jupyter_notebook",
"matplotlib",
"python"
] | stackoverflow_0061841011_jupyter_notebook_matplotlib_python.txt |
Q:
How do I set a default value for flag in argparse if the flag is given alone
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-c',
'--cookies',
nargs='?',
default=5,
type=int,
)
args = parser.parse_args()
if a... | How do I set a default value for flag in argparse if the flag is given alone | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-c',
'--cookies',
nargs='?',
default=5,
type=int,
)
args = parser.parse_args()
if args.cookies:
print('cookies flag is set: ' + args.cookies)
else:
print('co... | [
"You're looking for the const parameter, which the docs don't do a very good job of explaining.\ndefault always sets the value, even if the flag is not provided, unless it is overridden by a user input.\nconst only sets the value if the flag is provided and no overriding value is provided.\nThe nargs section has an... | [
0
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0074517842_argparse_python.txt |
Q:
Autosuggestion In Flask Api
I am creating a Flask API, for movie Recommendation i have dataset and i want autosuggestion functionality when i type any letter i will get movie related to that word.
This my app.py file:-
from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
import pa... | Autosuggestion In Flask Api | I am creating a Flask API, for movie Recommendation i have dataset and i want autosuggestion functionality when i type any letter i will get movie related to that word.
This my app.py file:-
from flask import Flask, jsonify, request, render_template
from flask_cors import CORS
import pandas as pd
item_similarity_df = ... | [
"The following example uses AJAX to search for entries in the DataFrame whose title column contains the substring that was sent.\nA GET request is sent to the server for each substring entered. This searches for rows whose title column contains the string, ignoring upper and lower case. Matching rows are then extra... | [
1
] | [] | [] | [
"ajax",
"flash",
"flask",
"pandas",
"python"
] | stackoverflow_0074546737_ajax_flash_flask_pandas_python.txt |
Q:
Create a network graph manually
I am looking to create a program in python that will allow me to draw a graph manually, that is to say, by placing the points (vertex) and clicking on two vertices in order to connect them and thus form an edge and above all I am looking to that this graph is not just a drawing beca... | Create a network graph manually | I am looking to create a program in python that will allow me to draw a graph manually, that is to say, by placing the points (vertex) and clicking on two vertices in order to connect them and thus form an edge and above all I am looking to that this graph is not just a drawing because I have to extract the adjacency a... | [
"If you have a decent GUI framework, then this sort of thing is easily accomplished.\nAs a first step, you need to implement the following\n\nAdd node\n\nmove mouse cursor to location\nclick right mouse button\nselect \"Add Node\" menu item from pop-up\nnode will be displayed at mouse location as a black circle\n\n... | [
1
] | [] | [] | [
"graph",
"python",
"user_interface"
] | stackoverflow_0074548869_graph_python_user_interface.txt |
Q:
How to return binary data from lambda function in AWS in Python?
I cannot get python lambda to return binary data. The node-template for thumbnail images works fine but I cannot get a python lambda to work. Below is the relevant lines from my lambda. The print("image_data " + image_64_encode) line prints a base64 ... | How to return binary data from lambda function in AWS in Python? | I cannot get python lambda to return binary data. The node-template for thumbnail images works fine but I cannot get a python lambda to work. Below is the relevant lines from my lambda. The print("image_data " + image_64_encode) line prints a base64 encoded image to the logs.
def lambda_handler(event, context):
img... | [
"I finally figured this out. Returning binary data from a python lambda is doable.\nFollow the instructions here:\nhttps://aws.amazon.com/blogs/compute/binary-support-for-api-integrations-with-amazon-api-gateway/\nBe sure to check the 'Use Lambda Proxy integration' when creating a new method.\nAlso be sure your Pyt... | [
20,
19,
10,
4,
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"binary",
"image",
"python"
] | stackoverflow_0044860486_amazon_web_services_aws_lambda_binary_image_python.txt |
Q:
How do i get a specfic piece of data from a user input list
I need the code to find the gradient (slope calculation) using the first to inputs but i cant get the code to find the individual inputs
heart_rate = []
max_length = 5
while len(heart_rate) < max_length:
hr = int(input("enter heartrate after exercise: "... | How do i get a specfic piece of data from a user input list | I need the code to find the gradient (slope calculation) using the first to inputs but i cant get the code to find the individual inputs
heart_rate = []
max_length = 5
while len(heart_rate) < max_length:
hr = int(input("enter heartrate after exercise: "))
heart_rate.append(hr)
#Print data set
print(heart_rate)
#Ca... | [
"len is a function, not a list. To get the first 2 inputs of the list you would have to use heart_rate[0] and heart_rate[1] respectively. The code should be like this instead:\ngradient = (time[0]-time[1])/(heart_rate[0]-heart_rate[1])\n\nBut keep in mind that just changing this wont fix your HR_gradient function, ... | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074553487_list_python.txt |
Q:
How do I change abbreviated words in a column in Python, eg NY to New York, US to United States at the same time?
How do I replace all abbreviation in a column to word eg NY to New York, US to United States etal. I could do for just NY with inplace=True, but I need to collectively do for all abbreviations.
I tried... | How do I change abbreviated words in a column in Python, eg NY to New York, US to United States at the same time? | How do I replace all abbreviation in a column to word eg NY to New York, US to United States etal. I could do for just NY with inplace=True, but I need to collectively do for all abbreviations.
I tried df['prod_state'].replace('NY', 'New York', inplace= True), it worked but when I included US, errors started popping
| [
"You can use pandas.Series.replace that accept dictionnaries as an argument of to_replace:\ndico_abbrv= {'NY': 'New York', 'US': 'United States'}\n\ndf['prod_state'].replace(dico_abbrv, inplace= True)\n\nYou can also use pandas.Series.map :\ndf['prod_state']= df['prod_state'].map(dico_abbrv)\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074553662_pandas_python.txt |
Q:
TypeError: 'Artihref' object is not iterable z3-solver
I am trying to create a function called nochange which keeps the variable passed through within the same transition state it was already in.
variables = [('pc_thrd1', 'int'), ('pc_thrd2', 'int'), ('flag1', 'int'), ('flag2', 'int'), ('x', 'int'), ('turn', 'int'... | TypeError: 'Artihref' object is not iterable z3-solver | I am trying to create a function called nochange which keeps the variable passed through within the same transition state it was already in.
variables = [('pc_thrd1', 'int'), ('pc_thrd2', 'int'), ('flag1', 'int'), ('flag2', 'int'), ('x', 'int'), ('turn', 'int'), ('pid', 'int')]
variables_enc_0, variables_enc_1 = bmchec... | [
"You need to post an MRE (minimal-reproducible-example). See here: https://stackoverflow.com/help/minimal-reproducible-example\nWithout a reproducible example, it's impossible to opine on what exactly is going on wrong. However, I see a clear red-flag. You have:\nflag2 == 0\n\nand also:\nnochange(flag2)\n\nThe firs... | [
0
] | [] | [] | [
"python",
"sat",
"smt",
"z3",
"z3py"
] | stackoverflow_0074553489_python_sat_smt_z3_z3py.txt |
Q:
separating 2d numpy array into nxn chunks
How would you separate a 2D numpy array into a nxn chunks?
For example, the following array of shape (4,4):
arr = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
Transformed to this array, of shape (4,2,2), by subsampling with a different (2x2) ar... | separating 2d numpy array into nxn chunks | How would you separate a 2D numpy array into a nxn chunks?
For example, the following array of shape (4,4):
arr = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
Transformed to this array, of shape (4,2,2), by subsampling with a different (2x2) array:
new_arr = [[[1,2],
[5,6]],
... | [
"You can use np.vsplit to split the array into multiple subarrays vertically. Similarly you can use np.hsplit to split the array into multiple subarrays horizontally. To better understand this examine the generalized resample function which makes the use of np.vsplit and np.hsplit methods.\nUse this:\ndef ressample... | [
1,
0,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python",
"slice"
] | stackoverflow_0061094337_arrays_numpy_python_slice.txt |
Q:
Logging from 2 root logger to 1 file
I have a function for quickly setting up the logger:
def init_logger(name: str, log_path: str):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
cli_handler = logging.StreamHandler()
cli_handler.setFormatter(CLILoggerFormatter())
cli_handler.... | Logging from 2 root logger to 1 file | I have a function for quickly setting up the logger:
def init_logger(name: str, log_path: str):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
cli_handler = logging.StreamHandler()
cli_handler.setFormatter(CLILoggerFormatter())
cli_handler.setLevel(logging.INFO)
logger.addHandl... | [
"If anyone has a similar problem, here's a solution that helped me.\nInstead of adding a handler to each logger object, I used logging.config.dictConfig:\nimport logging\nimport logging.config\n\n\nCONFIG = {\n \"version\": 1,\n \"handlers\": {\n \"file_handler\": {\n \"class\": \"logging.ha... | [
0
] | [] | [] | [
"logging",
"python",
"python_3.x"
] | stackoverflow_0074553143_logging_python_python_3.x.txt |
Q:
Retrieve output parameter(s) from a SQL Server stored procedure
Trying to run a MS SQL stored procedure that has an output parameter. I have followed documentation on how to do this, but when I run my code I get this error: SystemError: <class 'pyodbc.Error'> returned a result with an error set. Here is my code:
m... | Retrieve output parameter(s) from a SQL Server stored procedure | Trying to run a MS SQL stored procedure that has an output parameter. I have followed documentation on how to do this, but when I run my code I get this error: SystemError: <class 'pyodbc.Error'> returned a result with an error set. Here is my code:
my_stored_procedure
CREATE PROCEDURE [dbo].[my_stored_procedure]
... | [
".outparam() was added way back in SQLAlchemy 0.4 to address a specific requirement when working with Oracle and is only really used by that dialect. As mentioned in the current SQLAlchemy documentation here, working with stored procedures is one of the more database/dialect-specific tasks because of the significan... | [
0
] | [] | [] | [
"output_parameter",
"python",
"sql_server",
"sqlalchemy",
"stored_procedures"
] | stackoverflow_0074552026_output_parameter_python_sql_server_sqlalchemy_stored_procedures.txt |
Q:
How to find/get class object from a class method, static method or instance method
For example.
class Klass:
def f(sel):
pass
f = Klass().f()
klass = # i want to get Klass object.
I searched a methond in inspect module but I can not find, Actually I find a private function named _findclass but this m... | How to find/get class object from a class method, static method or instance method | For example.
class Klass:
def f(sel):
pass
f = Klass().f()
klass = # i want to get Klass object.
I searched a methond in inspect module but I can not find, Actually I find a private function named _findclass but this method does not run correctly in local class for example
def test():
class K:
... | [
"Once you get the output of a function, you can't get any information about it. In your example, Klass().f() returns None. Once this value is returned, it is indistinguishable from any other None. But if you instead do f = Klass().f, you can get the instance with f.__self__.\nFor example:\nclass Klass:\n def f(s... | [
0
] | [] | [] | [
"inspect",
"python"
] | stackoverflow_0074553431_inspect_python.txt |
Q:
How to take individual words from a list
I am currently running some python code to extract words from a list and create a list of these words.
The list I am using is from a .txt file with some lines from romeo and juliet.
I read in the file, trimmed the whitespace, split each word up, and added these words to a l... | How to take individual words from a list | I am currently running some python code to extract words from a list and create a list of these words.
The list I am using is from a .txt file with some lines from romeo and juliet.
I read in the file, trimmed the whitespace, split each word up, and added these words to a list.
I am now trying to create a list that doe... | [
"A set requires that it has only unique elements. To remove repeated elements from a list, you can convert it into a set and then back again.\nlist_without_duplicates = list(set(lst))\n\nHere's a simple way to do it while preserving the order of the words:\nnew_list = []\nadded_words = {}\nfor word in lst:\n if ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074553807_python.txt |
Q:
Python: Guessing a number is User's mind
I am stuck on a question from my Introduction to Python course. I have to write a code wherein the user keeps an integer in their mind, and the computer guesses. If the user's number is higher than the computer's guess, the user types "+", and the computer guesses higher. I... | Python: Guessing a number is User's mind | I am stuck on a question from my Introduction to Python course. I have to write a code wherein the user keeps an integer in their mind, and the computer guesses. If the user's number is higher than the computer's guess, the user types "+", and the computer guesses higher. If the user's number is lower, the user types "... | [
"I was having the same problem you have and here is my solution for it:\nimport random\n\n\nlow = 1\nhigh = 100\n\nint(input(\"Enter the number for computer to guess: \"))\n\n\nwhile low != high:\n guess = low + (high - low) // 2\n high_low = input(f\"Computer guess is: {guess} \\n \"\n f\"Press (H) for h... | [
0
] | [
"There are several solutions here, and some are more sophisticated than others.\nThe simplest solution in my opinion would simply be something like this (without validations):\nif user_input == \"+\":\n number = number + 1\nelif user_input == \"-\":\n number = number - 1\nelif user_input = \"y\":\n print(\... | [
-1
] | [
"python"
] | stackoverflow_0073859371_python.txt |
Q:
Problem loading parallel datasets even after using SubsetRandomSampler
I have two parallel datasets dataset1 and dataset2 and following is my code to load them in parallel using SubsetRandomSampler where I provide train_indices for dataloading.
P.S. Even after setting num_workers=0 and seeding np as well as torch,... | Problem loading parallel datasets even after using SubsetRandomSampler | I have two parallel datasets dataset1 and dataset2 and following is my code to load them in parallel using SubsetRandomSampler where I provide train_indices for dataloading.
P.S. Even after setting num_workers=0 and seeding np as well as torch, the samples do not get loaded in parallel. Any suggestions are heartily wel... | [
"It looks like you are trying to load the two datasets in parallel, but have them maintain the same shuffled order.\nCurrently, the code is shuffling the indices for dataset1 and then using those same shuffled indices to sample from both dataset1 and dataset2. However, this does not guarantee that the same elements... | [
1,
0
] | [] | [] | [
"python",
"pytorch",
"pytorch_dataloader",
"tensor"
] | stackoverflow_0074537660_python_pytorch_pytorch_dataloader_tensor.txt |
Q:
How to round down a float using import math
I have a variable that is a float, and I can't find out how to round it down.
I did a google search and it said I should use trunc, but trunc didn't work for me.
A:
if you always want to round down and are getting positive floats, just use int() .. otherwise you can us... | How to round down a float using import math | I have a variable that is a float, and I can't find out how to round it down.
I did a google search and it said I should use trunc, but trunc didn't work for me.
| [
"if you always want to round down and are getting positive floats, just use int() .. otherwise you can use math.floor(), which can handle negative floats too\n>>> math.floor(3.99)\n3\n>>> int(-0.1)\n0\n>>> int(-1.2)\n-1\n>>> math.floor(-1.2)\n-2\n\n"
] | [
0
] | [] | [] | [
"python",
"rounding"
] | stackoverflow_0074553939_python_rounding.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.