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:
How to add an anchor to navigate within same page in ploty dash
How to add an anchor to navigate within the same page in ploty dash?
A:
It's possible to place an anchor using href to where you want to navigate. You can use html.A to add an invisible anchor.
Note that there's no '#' in html.A id.
Ex:
html.A(id="P... | How to add an anchor to navigate within same page in ploty dash | How to add an anchor to navigate within the same page in ploty dash?
| [
"It's possible to place an anchor using href to where you want to navigate. You can use html.A to add an invisible anchor.\nNote that there's no '#' in html.A id.\nEx:\nhtml.A(id=\"PageSection1\"),\n\nThen just place navigate button where you need it. Clicking the button will take you to the anchor position.\nhtml.... | [
0
] | [] | [] | [
"plotly_dash",
"python"
] | stackoverflow_0074615880_plotly_dash_python.txt |
Q:
How to pass -Xfrozen_modules=off to python to disable frozen modules?
Running a python script on VS outputs this error. How to pass -Xfrozen_modules=off to python to disable frozen modules?
I was trying to update the python version from 3.6 to 3.11 and then started seeing this message.
A:
In Python version 3.11... | How to pass -Xfrozen_modules=off to python to disable frozen modules? | Running a python script on VS outputs this error. How to pass -Xfrozen_modules=off to python to disable frozen modules?
I was trying to update the python version from 3.6 to 3.11 and then started seeing this message.
| [
"In Python version 3.11 I got also the error.\nPython version 3.11 https://i.stack.imgur.com/EI0Co.png\nPython version 3.10 works fine.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074364918_python_python_3.x.txt |
Q:
How can I take the Fourier Transform using np.fft.fft function?
I want to generate two sinusoidal signals where =5 Hz and f2=3 Hz, the time duration of the signal is =1.
x1(t)=sin(2)
X2(t)=sin(2(1+f2))
X()=1()+2()
So, I will try to analyze the frequency domain respresentation of this signal.
How can I take the ... | How can I take the Fourier Transform using np.fft.fft function? | I want to generate two sinusoidal signals where =5 Hz and f2=3 Hz, the time duration of the signal is =1.
x1(t)=sin(2)
X2(t)=sin(2(1+f2))
X()=1()+2()
So, I will try to analyze the frequency domain respresentation of this signal.
How can I take the Fourier Transform using np.fft.fft function by using DFT size =64 , ... | [
"It is not entirely clear what the final signal is you want to do a Fourier Transform on, but I made the following assumptions:\n\nyour time domain signal x(t)=sin(21)+sin(22). From what your wrote it wasn't entirely clear\nyou want to have the FFT of above x(t)\nyour total time T=1s (you wrote T=1, units are impor... | [
0
] | [] | [] | [
"fft",
"python",
"signal_processing"
] | stackoverflow_0074614941_fft_python_signal_processing.txt |
Q:
Is there a python binding to the Berkeley DB XML database?
I'm trying to migrate some perl code to python and it uses Sleeypcat::DbXml 'simple' to get read access to a .dbxml file, creates a XmlManager, calls createQueryContext, openContainer and query to get an XmlValue. I have found https://pypi.org/project/ber... | Is there a python binding to the Berkeley DB XML database? | I'm trying to migrate some perl code to python and it uses Sleeypcat::DbXml 'simple' to get read access to a .dbxml file, creates a XmlManager, calls createQueryContext, openContainer and query to get an XmlValue. I have found https://pypi.org/project/berkeleydb/ to support the Berkeley DB in general, but it has no me... | [
"Berkeley DB and Berkeley DB XML are two different products. My python bindings (legacy \"bsddb3\" and current \"berkeleydb\") only interface with Berkeley DB.\nI am not aware of any Python bindings for Berkeley DB XML.\nI am a freelance with commercial contracts, if that option would be useful to you.\n"
] | [
1
] | [] | [] | [
"api",
"berkeley_db",
"berkeley_db_xml",
"python",
"python_3.x"
] | stackoverflow_0074579981_api_berkeley_db_berkeley_db_xml_python_python_3.x.txt |
Q:
How to get the file-magic module working on Alpine Linux?
I'm trying to use file-magic on Alpine Linux and it keeps blowing up with AttributeError: Symbol not found: magic_open whenever I import the magic module.
I noted that there's two Python modules out there with the same magic namespace, but as most Linux dis... | How to get the file-magic module working on Alpine Linux? | I'm trying to use file-magic on Alpine Linux and it keeps blowing up with AttributeError: Symbol not found: magic_open whenever I import the magic module.
I noted that there's two Python modules out there with the same magic namespace, but as most Linux distros appear to be using file-magic and not python-magic, I deci... | [
"Python-Magic has a hard-coded fallback for Alpine Linux so you might be in for a hard time with file-magic, which just uses ctypes.util.find_library('magic') and apparently can't find your library.\nThe exact behavior of ctypes.util.find_library is pretty complicated but if you trace through the code and see which... | [
4,
0
] | [] | [] | [
"alpine_linux",
"libmagic",
"python"
] | stackoverflow_0053936467_alpine_linux_libmagic_python.txt |
Q:
Scrapy - How does a request sent using requests library to an API differs from the request that is sent using Scrapy.Request?
I am a beginner at using Scrapy and I was trying to scrape this website https://directory.ntschools.net/#/schools which is using javascript to load the contents. So I checked the networks t... | Scrapy - How does a request sent using requests library to an API differs from the request that is sent using Scrapy.Request? | I am a beginner at using Scrapy and I was trying to scrape this website https://directory.ntschools.net/#/schools which is using javascript to load the contents. So I checked the networks tab and there's an API address available https://directory.ntschools.net/api/System/GetAllSchools If you open this address, the data... | [
"It's because Scrapy sets the Accept header to 'text/html,application/xhtml+xml,application/xml ...'. You can see that from this.\nI experimented and found that server sends a JSON response if the request has no Accept header.\n"
] | [
1
] | [] | [] | [
"api",
"python",
"python_requests",
"scrapy",
"web_scraping"
] | stackoverflow_0074612450_api_python_python_requests_scrapy_web_scraping.txt |
Q:
How can I get all values above a certain percentile in a data frame using pandas?
I can get the value of 75% using the quantile function in pandas, but how can I get all the values from 75% to 100% of each column in a data frame?
I tried this at the beginning to get the 75 percentile and the mean of that
n = df.qu... | How can I get all values above a certain percentile in a data frame using pandas? | I can get the value of 75% using the quantile function in pandas, but how can I get all the values from 75% to 100% of each column in a data frame?
I tried this at the beginning to get the 75 percentile and the mean of that
n = df.quantile(0.75)
x = df.mean(n)
Then I tried a for loop but did not quite work because I c... | [
"The expected output is unclear, but assuming you want a list/Series of those values.\nLet's start with a dummy example:\nnp.random.seed(0)\ndf = pd.DataFrame(np.random.randint(0, 100, size=(20, 10)))\n\nAnd get the quantile(0.75) per column:\ndf.quantile(0.75)\n\n0 75.50\n1 67.50\n2 72.75\n3 78.25\n4 ... | [
0
] | [] | [] | [
"dataframe",
"loops",
"pandas",
"percentile",
"python"
] | stackoverflow_0074615879_dataframe_loops_pandas_percentile_python.txt |
Q:
web scrape specific sets of data from table using API with python
I am looking to web scrape the large table showing the name, date, bought/ sold, amount of shares, etc from the following website:
https://www.nasdaq.com/market-activity/stocks/aapl/insider-activity
Preferably I need someone to show how to use the N... | web scrape specific sets of data from table using API with python | I am looking to web scrape the large table showing the name, date, bought/ sold, amount of shares, etc from the following website:
https://www.nasdaq.com/market-activity/stocks/aapl/insider-activity
Preferably I need someone to show how to use the Nasdaq api if possible. I believe the way I'd normally webscrape (using ... | [
"All you have to do is:\nimport requests\nimport json \nimport pandas as pd\n\nurl = 'https://api.nasdaq.com/api/company/AAPL/insider-trades?limit=25&offset=0&type=ALL&sortColumn=lastDate&sortOrder=DESC'\n\nheaders = {\n 'accept': 'application/json, text/plain, */*',\n 'accept-encoding': 'gzip, deflate, br',\... | [
1
] | [] | [] | [
"api",
"json",
"python"
] | stackoverflow_0074614995_api_json_python.txt |
Q:
How do I fit my X - Axis labels on my plot
I cant seem to find a way to fit my x labels in the right way on my plot.
Can someone help ?
here is the code and the output is in the picture
Code:
sns.lineplot(x="ds", y="y", data=df_new, hue="Type", marker="o")
A:
You should be able to rotate your xlabels, which make... | How do I fit my X - Axis labels on my plot | I cant seem to find a way to fit my x labels in the right way on my plot.
Can someone help ?
here is the code and the output is in the picture
Code:
sns.lineplot(x="ds", y="y", data=df_new, hue="Type", marker="o")
| [
"You should be able to rotate your xlabels, which makes your plot more readable. Try:\nax = sns.lineplot(x=\"ds\", y=\"y\", data=df_new, hue=\"Type\", marker=\"o\")\nax.tick_params(axis='x', labelrotation=45)\n\nAnd then plotting your data.\n"
] | [
0
] | [] | [] | [
"forecast",
"pandas",
"plot",
"python"
] | stackoverflow_0074615821_forecast_pandas_plot_python.txt |
Q:
Value count of columns in a pandas DataFrame where where string is 'nan'
Let's say I have the following pd.DataFrame
>>> df = pd.DataFrame({
'col_1': ['Elon', 'Jeff', 'Warren', 'Mark'],
'col_2': ['nan', 'Bezos', 'Buffet', 'nan'],
'col_3': ['nan', 'Amazon', 'Berkshire', 'Meta'],
})
which gets me
co... | Value count of columns in a pandas DataFrame where where string is 'nan' | Let's say I have the following pd.DataFrame
>>> df = pd.DataFrame({
'col_1': ['Elon', 'Jeff', 'Warren', 'Mark'],
'col_2': ['nan', 'Bezos', 'Buffet', 'nan'],
'col_3': ['nan', 'Amazon', 'Berkshire', 'Meta'],
})
which gets me
col_1 col_2 col_3
0 Elon nan nan
1 Jeff Bezos Amazon
2 War... | [
"you have nan as string , you can do :\ndf.eq(\"nan\").sum()\n\noutput :\ncol_1 0\ncol_2 2\ncol_3 1\ndtype: int64\n\n",
"It took me a while to see that you changed your initial code for the dataset. However, if you would like to extract all of the rows where you have the 'nan' string, I would use a mask.... | [
2,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074615797_dataframe_pandas_python.txt |
Q:
TensorRT - TensorFlow deserialization fails with Serialization Error in verifyHeader
I'm running the nvcr.io/nvidia/tensorflow:19.12-tf2-py3 docker image with the following runtime information:
Tensorflow 2.0.0 (tf.__version__)
Python 3.6 (!python --version)
TensorRT 6.0.1 (!dpkg -l | grep nvinfer)
cuda 10.2
I... | TensorRT - TensorFlow deserialization fails with Serialization Error in verifyHeader | I'm running the nvcr.io/nvidia/tensorflow:19.12-tf2-py3 docker image with the following runtime information:
Tensorflow 2.0.0 (tf.__version__)
Python 3.6 (!python --version)
TensorRT 6.0.1 (!dpkg -l | grep nvinfer)
cuda 10.2
I have built a model in TensorFlow 2.0 and converted+saved it to a dir:
1/
├── assets/
| ... | [
"If the engine was created and ran on different versions, this may happen. TensorRT engines are not compatible across different TensorRT versions. Go to this reference for more info.\n",
"For future readers, if you get this error building and running on the same machine or even the same container, your tensorrt p... | [
2,
0
] | [] | [] | [
"nvidia_docker",
"python",
"tensorflow",
"tensorrt"
] | stackoverflow_0059934105_nvidia_docker_python_tensorflow_tensorrt.txt |
Q:
I am trying to replace the values in a dictionary with an updated one and i am not getting the exact result
So i updated the values of a dictionary into percentage by multiplying by 100. Now i want to replace the initial decimal with the updated results, but instead, i am getting each value replaced by the whole ... | I am trying to replace the values in a dictionary with an updated one and i am not getting the exact result | So i updated the values of a dictionary into percentage by multiplying by 100. Now i want to replace the initial decimal with the updated results, but instead, i am getting each value replaced by the whole new values.
job_role_overtime_att_rate = {'Healthcare Representative Overtime Rate' : 2/37, ' Human Resources Ove... | [
"You can loop through the dict.items() function to loop through the key and the value.\njob_role_overtime_att_rate = {\n 'Healthcare Representative Overtime Rate': 0.05405405405405406,\n 'Human Resources Overtime Rate': 0.38461538461538464,\n 'Laboratory Technician Total': 0.5,\n 'Manager Total': 0.148148148148... | [
2,
0
] | [] | [] | [
"dictionary",
"nested_for_loop",
"python"
] | stackoverflow_0074615696_dictionary_nested_for_loop_python.txt |
Q:
Trouble reading some pdfs with PyPDF2
I'm having trouble reading a standard PDF with PyPDF2. The PdfReader class will read the document and give me the correct metadata properties for my document, but examining any other content gives me the filler text that a browser would if I do not have the adobe extension ins... | Trouble reading some pdfs with PyPDF2 | I'm having trouble reading a standard PDF with PyPDF2. The PdfReader class will read the document and give me the correct metadata properties for my document, but examining any other content gives me the filler text that a browser would if I do not have the adobe extension installed:
The document you are trying to loa... | [
"Your document is a dynamic XFA form. These dynamic forms are defined entirely in XML and the PDF file serves as a container. The PDF file has a single page with the message you extracted, this is for the PDF processors that do not support dynamic XFA forms.\nOpen the file with Adobe Reader and you will see a full... | [
0
] | [] | [] | [
"adobe",
"pdf",
"pypdf2",
"python"
] | stackoverflow_0074613023_adobe_pdf_pypdf2_python.txt |
Q:
Python comprehension with multiple prints
I want to put this for loop into a comprehension. Is this even possible?
for i in range(1, 11):
result = len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})
print(f'There are {result} different unique walks with length {i}')
I tried stuff like
print... | Python comprehension with multiple prints | I want to put this for loop into a comprehension. Is this even possible?
for i in range(1, 11):
result = len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})
print(f'There are {result} different unique walks with length {i}')
I tried stuff like
print({tuple(walk) for i in range(1, 11) for (walk,... | [
"You were pretty close actually:\n[print(f'There are {len({tuple(walk) for (walk, distance) in dic[i] if distance == 0})} different unique walks with length {i}') for i in range(1,11)]\n\nBut it's a long and ugly oneliner, in a regular for it looks way better.\n",
"Technically yes, but I'd not recommend doing tha... | [
2,
1
] | [] | [] | [
"list_comprehension",
"printing",
"python",
"set_comprehension"
] | stackoverflow_0074615760_list_comprehension_printing_python_set_comprehension.txt |
Q:
Send VISCA commands to IPcamera using python-onvif-zeep or valkka and sendreceiveserialcommand service from DeviceIO
The problem
I have recently acquired an Active Silicon IP-camera and I have been trying to control it using python-onvif-zeep or valkka. The camera implements the ONVIF Profile S standard. I would l... | Send VISCA commands to IPcamera using python-onvif-zeep or valkka and sendreceiveserialcommand service from DeviceIO | The problem
I have recently acquired an Active Silicon IP-camera and I have been trying to control it using python-onvif-zeep or valkka. The camera implements the ONVIF Profile S standard. I would like to send zoom in / our, focus and other basic VISCA commands to the camera using the SendReceiveSerialData service as d... | [
"I managed to get your example to work using the following code. The data was not passed in the correct format to the function, so the SOAP message was incomplete.\nCheck the zeep documentation for details about passing SOAP datastructures.\ndeviceio_type_factory = deviceIO_service.zeep_client.type_factory(\"http:/... | [
2
] | [] | [] | [
"ip_camera",
"onvif",
"python",
"python_onvif",
"zeep"
] | stackoverflow_0074504555_ip_camera_onvif_python_python_onvif_zeep.txt |
Q:
Subtracting times in a csv for a row by row basis in Python
I have a CSV that's few thousand rows long. It contains data sent from various devices. They should transmit frequently (every 10 minutes) however sometimes there is a lag. I'm trying to write a program that will highlight all instances where the delay be... | Subtracting times in a csv for a row by row basis in Python | I have a CSV that's few thousand rows long. It contains data sent from various devices. They should transmit frequently (every 10 minutes) however sometimes there is a lag. I'm trying to write a program that will highlight all instances where the delay between two readings is greater than 15 minutes
I've made a functio... | [
"threshold is datetime and you compare it to timedelta object (difference). Did you mean:\nfrom datetime import timedelta\n...\nthreshold = datetime.timedelta(minutes=15)\n\n",
"Given this dataframe:\n actual_ts id\n0 05:00:00 SPAM\n1 5:15:00 SPAM\n2 5:33:00 SPAM <-- Should highlight\n3 5:45:00 SPA... | [
0,
0
] | [] | [] | [
"csv",
"datetime",
"pandas",
"python"
] | stackoverflow_0074615585_csv_datetime_pandas_python.txt |
Q:
How to add rows as sums of other rows in DataFrame?
I'm not sure I titled this post correctly but I have a unique situation where I want to append a new set of rows to an existing DataFrame as a sum of rows from existing sets and I'm not sure where to start.
For example, I have the following DataFrame:
import pand... | How to add rows as sums of other rows in DataFrame? | I'm not sure I titled this post correctly but I have a unique situation where I want to append a new set of rows to an existing DataFrame as a sum of rows from existing sets and I'm not sure where to start.
For example, I have the following DataFrame:
import pandas as pd
data = {'Team': ['Atlanta', 'Atlanta', 'Clevela... | [
"We can use groupby agg to create the summary rows then append to the DataFrame:\ndf = df.append(df.groupby('Team', as_index=False).agg({\n 'Position': ' + '.join, # Concat Strings together\n 'Points': 'sum' # Total Points\n}), ignore_index=True)\n\ndf:\n Team Position Points\n0 Atlanta ... | [
1,
0
] | [] | [] | [
"aggregate",
"append",
"dataframe",
"pandas",
"python"
] | stackoverflow_0068773113_aggregate_append_dataframe_pandas_python.txt |
Q:
What's the equivalent of the php Laravel's "Http::fake()" in Python/ Django / DRF / Pytest?
Laravel's Http:fake() method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made. How can I achieve the same using Django Rest Framework APIClient in tests?
I tried requests_moc... | What's the equivalent of the php Laravel's "Http::fake()" in Python/ Django / DRF / Pytest? | Laravel's Http:fake() method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made. How can I achieve the same using Django Rest Framework APIClient in tests?
I tried requests_mock but it didn't yield the result I was expecting. It only mocks requests made within test functio... | [
"When you use pytest-django you can use import the fixture admin_client and then do requests like this:\ndef test_get_project_list(admin_client):\n resp = admin_client.get(\"/projects/\")\n assert resp.status_code == 200\n resp_json = resp.json()\n assert resp_json == {\"some\": \"thing\"}\n\n"
] | [
0
] | [] | [] | [
"django_rest_framework",
"django_testing",
"django_tests",
"http_mock",
"python"
] | stackoverflow_0074614274_django_rest_framework_django_testing_django_tests_http_mock_python.txt |
Q:
Python multiprocessing queue using a lot of resources with opencv
I am using multiprocessing to get frames of a video using Opencv in python.
My class looks like this :-
import cv2
from multiprocessing import Process, Queue
class StreamVideos:
def __init__(self):
self.image_data = Queue()
def sta... | Python multiprocessing queue using a lot of resources with opencv | I am using multiprocessing to get frames of a video using Opencv in python.
My class looks like this :-
import cv2
from multiprocessing import Process, Queue
class StreamVideos:
def __init__(self):
self.image_data = Queue()
def start_proces(self):
p = Process(target=self.echo)
p.start... | [
"The following is a general purpose single producer/multiple consumer implementation. The producer (class StreamVideos) creates a shared memory array whose size is the number of bytes in the video frame. One or more consumers (you specify the number of consumers to StreamVideos) can then call StreamVideos.get_next_... | [
0
] | [] | [] | [
"multiprocessing",
"opencv",
"python",
"queue"
] | stackoverflow_0074600004_multiprocessing_opencv_python_queue.txt |
Q:
Call function without optional arguments if they are None
There's a function which takes optional arguments.
def alpha(p1="foo", p2="bar"):
print('{0},{1}'.format(p1, p2))
Let me iterate over what happens when we use that function in different ways:
>>> alpha()
foo,bar
>>> alpha("FOO")
FOO,bar
>>> alpha(p2="... | Call function without optional arguments if they are None | There's a function which takes optional arguments.
def alpha(p1="foo", p2="bar"):
print('{0},{1}'.format(p1, p2))
Let me iterate over what happens when we use that function in different ways:
>>> alpha()
foo,bar
>>> alpha("FOO")
FOO,bar
>>> alpha(p2="BAR")
foo,BAR
>>> alpha(p1="FOO", p2=None)
FOO,None
Now consid... | [
"Pass the arguments as kwargs from a dictionary, from which you filter out the None values:\nkwargs = dict(p1='FOO', p2=None)\n\nalpha(**{k: v for k, v in kwargs.items() if v is not None})\n\n",
"\nBut assume that alpha is used in other places where it is actually supposed to handle None as it does.\n\nTo respond... | [
66,
14,
12,
5,
3,
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0052494128_python_python_3.x.txt |
Q:
Python matplotlib adjust colormap
This is what I want to create.
This is what I get.
This is the code I have written.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
x = np.linspace(-90, 90, 181)
y = np.linspace(-90, 90, 181)
x_grid, y_grid = np.meshgrid(x, y)
z = np.e**x_grid
fig ... | Python matplotlib adjust colormap | This is what I want to create.
This is what I get.
This is the code I have written.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
x = np.linspace(-90, 90, 181)
y = np.linspace(-90, 90, 181)
x_grid, y_grid = np.meshgrid(x, y)
z = np.e**x_grid
fig = plt.figure()
ax = fig.add_subplot(1, ... | [
"Welcome to Stackoverflow!!\nYour problem is related to the fact that you are working with exponential numbers, but you're using a linear colormap. For x=90 you have z=1.2e+39, reaaaally large.\nYou were very close with your second attempt! I just changed 1 line in there, instead of\nnorm = mpl.colors.Normalize(vmi... | [
1
] | [] | [] | [
"colormap",
"matplotlib",
"python"
] | stackoverflow_0074615755_colormap_matplotlib_python.txt |
Q:
Why values of my specific key and value in a dictionary don't change in Python?
I am trying to handle a dictionary that has a list as a value for a key named 'notes' , so I am trying to find the maximum element from that list and reassign the value with that maximum element from the list and also change the key va... | Why values of my specific key and value in a dictionary don't change in Python? | I am trying to handle a dictionary that has a list as a value for a key named 'notes' , so I am trying to find the maximum element from that list and reassign the value with that maximum element from the list and also change the key value to 'top_notes' as follows.
Input = top_note({ "name": "John", "notes": [3, 5, 4] ... | [
"Iterating over dict using .items()will yield you a pair of (key, value)\nMaking a list of a single value...gives list with a single value, max of it returns that single item.\nYour whole function body could be:\nclass Solution:\n def top_notes(self, di: dict)->dict:\n di[\"top_note\"] = max(di[\"notes\"]... | [
1,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074615463_dictionary_list_python.txt |
Q:
How to avoid selecting parents 'twice' using Roulette Wheel Selection?
I am working on a genetic algorithm in Python, where I want to use the roulette wheel selection for selecting parents. However, I came to the conclusion that with my current code, it is possible that certain parents are selected multiple times,... | How to avoid selecting parents 'twice' using Roulette Wheel Selection? | I am working on a genetic algorithm in Python, where I want to use the roulette wheel selection for selecting parents. However, I came to the conclusion that with my current code, it is possible that certain parents are selected multiple times, however I want to avoid this.
Here is the first part of my code: The part w... | [
"Just keep track which individuals were already selected by putting their indices into a set (already_selected). Then select only when cum_prob[i]>=r and i not in already_selected.\nparent_number = population_size\nchosen = []\nalready_selected = set()\nfor n in range(parent_number):\n r=random.random()\n for... | [
0
] | [] | [] | [
"genetic_algorithm",
"python",
"roulette_wheel_selection"
] | stackoverflow_0074616090_genetic_algorithm_python_roulette_wheel_selection.txt |
Q:
CadQuery: Selecting an edge by index (Filleting specific edges)
I come from the engineering CAD world and I'm creating some designs in CadQuery. What I want to do is this (pseudocode):
edges = part.edges()
edges[n].fillet(r)
Or ideally have the ability to do something like this (though I can't find any methods fo... | CadQuery: Selecting an edge by index (Filleting specific edges) | I come from the engineering CAD world and I'm creating some designs in CadQuery. What I want to do is this (pseudocode):
edges = part.edges()
edges[n].fillet(r)
Or ideally have the ability to do something like this (though I can't find any methods for edge properties). Pseudocode:
edges = part.edges()
for edge in edge... | [
"Take a look at this code, i hope this will be helpful.\nimport cadquery as cq\n\nplane1 = cq.Workplane()\n\nblock = plane1.rect(10,12).extrude(10)\n\nedges = block.edges(\"|Z\")\n\nfilleted_block = edges.all()[0].fillet(0.5)\n\nshow(filleted_block)\n\n",
"For the posterity. To select multiple edges eg. for chamf... | [
1,
0
] | [] | [] | [
"cad",
"cadquery",
"python"
] | stackoverflow_0072142702_cad_cadquery_python.txt |
Q:
Pythonic Way to create a Error Class from Exception
I am working on a Project where I want to raise a error and I have been creating class each time I need a new Exception. I am staying away from generic / builtin errors as they are less descriptive for the purpose I need them for.
I came up with a solution but I ... | Pythonic Way to create a Error Class from Exception | I am working on a Project where I want to raise a error and I have been creating class each time I need a new Exception. I am staying away from generic / builtin errors as they are less descriptive for the purpose I need them for.
I came up with a solution but I am not sure if it is a pythonic way to create an instance... | [
"I wouldn't say it's a pythonic way to be honest. Python has initializers, not \"constructors\", the constructor would be the magic method __new__ if you really needed that (which is rare).\nFor customizable initializers the decorator @classmethod (multiple factory methods) is the way to go.\nAlso __str__ and __rep... | [
3
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0074615061_error_handling_python.txt |
Q:
Bad Request 400 when uploading file to Flask
I have a Flask server that looks like this:
import flask, os, werkzeug.utils
UPLOAD_FOLDER = "files/"
ALLOWED_EXTENSIONS = {"txt"}
def isFileAllowed(file):
return str("." in file and file.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS)
app = flask.Flask(__name__... | Bad Request 400 when uploading file to Flask | I have a Flask server that looks like this:
import flask, os, werkzeug.utils
UPLOAD_FOLDER = "files/"
ALLOWED_EXTENSIONS = {"txt"}
def isFileAllowed(file):
return str("." in file and file.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS)
app = flask.Flask(__name__)
app.config["UPLOAD_DIR"] = UPLOAD_FOLDER
@app.r... | [
"See again the flask documentation for request.files\n\nEach value in files is a Werkzeug FileStorage object\n\nIt is not just the filename but much more than that. The error message is telling you something: That secure_filename() expects a string, but you are passing it something that isn't a string.\nHave a loo... | [
0
] | [] | [] | [
"file",
"flask",
"python"
] | stackoverflow_0074616137_file_flask_python.txt |
Q:
How to merge two data frames on the basis of values present in multiple columns in pandas?
I have the following two data frames.
Column A
Column B
id1
name1
id2
name2
id3
name3
Column X1
Column X2
Column Y
name1
name4
company1
name6
name2
company2
name3
name8
company3
I want to merge the above two on the ... | How to merge two data frames on the basis of values present in multiple columns in pandas? | I have the following two data frames.
Column A
Column B
id1
name1
id2
name2
id3
name3
Column X1
Column X2
Column Y
name1
name4
company1
name6
name2
company2
name3
name8
company3
I want to merge the above two on the basis of names to get the final data frame like given below:
Column A
... | [
"join each time with one column and then union all the results together:\nout1 = df1.merge(df2, left_on=['Column B'], right_on=['Column X1'])\nout2 = df1.merge(df2, left_on=['Column B'], right_on=['Column X2'])\nout = pd.concat([out1, out2], ignore_index=True)\n\nout['Column X1'].loc[out['Column B'] == out['Column ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074616120_dataframe_pandas_python.txt |
Q:
How to add a seconds to a timestamp value which is in your another variable/dataframe
lv_seconds_back = mv_time_horizon.select(col("max(time_horizon)") * 60).show()
mv_now =spark.sql("select from_unixtime(unix_timestamp()) as mv_now")
local_date_time =mv_now.select(date_format('mv_now', 'HH:mm:ss').alia... | How to add a seconds to a timestamp value which is in your another variable/dataframe | lv_seconds_back = mv_time_horizon.select(col("max(time_horizon)") * 60).show()
mv_now =spark.sql("select from_unixtime(unix_timestamp()) as mv_now")
local_date_time =mv_now.select(date_format('mv_now', 'HH:mm:ss').alias("local_date_time"))
lv_start =local_date_time.select(col("local_date_time") - exp... | [
"Maybe you should remove .show() so that your column is captured in lv_seconds_back variable.\n",
"Your first line has two issues. The first one: col(\"max(time_horizon)\") cannot work because the col function expects a column name. Either do expr(\"max(time_horizon)\") or max(col(\"time_horizon\")). Then, the sh... | [
0,
0
] | [] | [] | [
"apache_spark",
"dataframe",
"pyspark",
"python",
"sql"
] | stackoverflow_0074613675_apache_spark_dataframe_pyspark_python_sql.txt |
Q:
Turning a vector of length n squared into a matrix of size n times n python
In python I have a numpy vector array v of length n squared. I want to make it into a matrix M of size n times n, by laying the elements of n into n rows, so the first n elements of v comprise the first row of M, similarly the i-th n eleme... | Turning a vector of length n squared into a matrix of size n times n python | In python I have a numpy vector array v of length n squared. I want to make it into a matrix M of size n times n, by laying the elements of n into n rows, so the first n elements of v comprise the first row of M, similarly the i-th n elements of v comprise the i-th row of M.
I tired using numpy reshape, but as I am com... | [
"You're definitely on the right track, you want to use np.reshape() here by doing\nM = M.reshape(n,n)\n\nor\nM = np.reshape(M, (n,n))\n\nNote the extra parentheses in the second case, they are important for it to work right because you are passing the tuple (n,n) as an argument.\n"
] | [
0
] | [] | [] | [
"arrays",
"numpy",
"python",
"reshape",
"vector"
] | stackoverflow_0074615993_arrays_numpy_python_reshape_vector.txt |
Q:
Why wont my display update with my background? The window just opens black. Pygame
I'm trying to learn OOP but my pygame window wont update with the background I'm trying to put in. The gameObject class is in another file. Filling it with white color also isn't working and I don't know why. I was able to display a... | Why wont my display update with my background? The window just opens black. Pygame | I'm trying to learn OOP but my pygame window wont update with the background I'm trying to put in. The gameObject class is in another file. Filling it with white color also isn't working and I don't know why. I was able to display a background on another project I did but I cant now and I have no idea what's different.... | [
"It is a matter of indentation. self.draw_objects() must be called in the application loop not after the application loop:\nclass Game:\n # [...]\n\n def run_game_loop(self):\n\n gameRunning = True\n while gameRunning:\n for event in pygame.event.get():\n if event.type ... | [
1,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074615885_pygame_python.txt |
Q:
Dataframe group by only groups with 2 or more rows
Is there a way to groupby only groups with 2 or more rows?
Or can I delete groups from a grouped dataframe that contains only 1 row?
Thank you very much for your help!
A:
Yes there is a way. Here is an example below
df = pd.DataFrame(
np.array([['A','A','B',... | Dataframe group by only groups with 2 or more rows | Is there a way to groupby only groups with 2 or more rows?
Or can I delete groups from a grouped dataframe that contains only 1 row?
Thank you very much for your help!
| [
"Yes there is a way. Here is an example below\ndf = pd.DataFrame(\n np.array([['A','A','B','C','C'],[1,2,1,1,2]]).T\n , columns= ['type','value']\n )\ngroups = df.groupby('type')\ngroups_without_single_row_df = [g for g in groups if len(g[1]) > 1]\n\ngroupby return a list of tuples.\nHere, 'type' (A, b or ... | [
0
] | [] | [] | [
"dataframe",
"group_by",
"python"
] | stackoverflow_0074577647_dataframe_group_by_python.txt |
Q:
Scan paired cells of two columns for the same pattern using Python
I'm a Python beginner and would like to learn how to use it for operations on text files. I have an input txt file of 4 columns separated by TAB, and I want to search whether, row by row, the cell pairs in columns 1 and 4 simultaneously contain the... | Scan paired cells of two columns for the same pattern using Python | I'm a Python beginner and would like to learn how to use it for operations on text files. I have an input txt file of 4 columns separated by TAB, and I want to search whether, row by row, the cell pairs in columns 1 and 4 simultaneously contain the pattern "BBB" or "CCC". If true, send the whole line to output1. If fal... | [
"You get duplicated lines in output2 because you ask it to do so. Your condition is: If item exists in both columns, write the line to output1, else write it to output2. Then you proceed to do this for each item in list. Since there are two items in list, and (e.g. in line 1) the first item doesn't exist in both co... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074615905_python.txt |
Q:
Is it possible to pass command line arguments to a decorator in Django?
I have a decorator that is supposed to use a parameter that's passed in from the commandline e.g
@deco(name)
def handle(self, *_args, **options):
name = options["name"]
def deco(name):
// The name should come from commandline
pass... | Is it possible to pass command line arguments to a decorator in Django? | I have a decorator that is supposed to use a parameter that's passed in from the commandline e.g
@deco(name)
def handle(self, *_args, **options):
name = options["name"]
def deco(name):
// The name should come from commandline
pass
class Command(BaseCommand):
def add_arguments(self, parser):
pa... | [
"You don't have access to the command-line value when the @deco decorator is applied, no. But you can delay applying that decorator until you do have access.\nDo so by creating your own decorator. A decorator is simply a function that applied when Python parses the @decorator and def functionname lines, right after... | [
3,
2,
2
] | [] | [] | [
"argparse",
"django",
"python"
] | stackoverflow_0074616062_argparse_django_python.txt |
Q:
Extracting parameters from strings - SQL Server
I have a table with strings in one column, which are actually storing other SQL Queries written before and stored to be ran at later times. They contain parameters such as '@organisationId' or '@enterDateHere'. I want to be able to extract these.
Example:
ID
Query
... | Extracting parameters from strings - SQL Server | I have a table with strings in one column, which are actually storing other SQL Queries written before and stored to be ran at later times. They contain parameters such as '@organisationId' or '@enterDateHere'. I want to be able to extract these.
Example:
ID
Query
1
SELECT * FROM table WHERE id = @organisationI... | [
"It is very simple to implement by using tokenization via XML and XQuery.\nNotable points:\n\n1st CROSS APPLY is tokenazing Query column as XML.\n2nd CROSS APPLY is filtering out tokens that don't have \"@\" symbol.\n\nSQL #1\n-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY... | [
2,
2,
0,
0
] | [] | [] | [
"c#",
"excel",
"python",
"sql",
"sql_server"
] | stackoverflow_0074615546_c#_excel_python_sql_sql_server.txt |
Q:
Forcing numpy.linspace to have specific entry
I am using numpy.linspace to let other functions sweep over some parameters, for example:
def fun(array):
newarray= []
for i in array:
newarray.append(i**2)
return newarray
Now I want to pass this function numpy.linspace(0,20,30) which h... | Forcing numpy.linspace to have specific entry | I am using numpy.linspace to let other functions sweep over some parameters, for example:
def fun(array):
newarray= []
for i in array:
newarray.append(i**2)
return newarray
Now I want to pass this function numpy.linspace(0,20,30) which has to contain the number 2.
Is there some way to fo... | [
"If I understand your question correctly you want a numpy array that consists of 30 values that are equally spaced between 0 and 20, containing 0 and 20, but also to contain the value of 2.0 exactly? That is not possible, since the steps will not be equally spaced anymore.\nYou either have to adjust the boundaries,... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074616441_numpy_python.txt |
Q:
Pyspark dataframe sum variable up to the current row's month
I have a pyspark dataframe that looks as follows:
date, loan
1.1.2020, 0
1.2.2020, 0
1.3.2020, 0
1.4.2020, 10000
1.5.2020, 200
1.6.2020, 0
I would like to have the fact that they took out a loan in month 4 to reflect on the other later months as well. S... | Pyspark dataframe sum variable up to the current row's month | I have a pyspark dataframe that looks as follows:
date, loan
1.1.2020, 0
1.2.2020, 0
1.3.2020, 0
1.4.2020, 10000
1.5.2020, 200
1.6.2020, 0
I would like to have the fact that they took out a loan in month 4 to reflect on the other later months as well. So the resulting dataframe would be:
date, loan
1.1.2020, 0
1.2.202... | [
"@Ehrendil - do you want to calculate running total ..\nselect date,loan,\nsum(loan) over(order by date row between unbounded preceding and current row) as running_total from table\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pyspark",
"python",
"sql"
] | stackoverflow_0074616093_dataframe_pyspark_python_sql.txt |
Q:
how a toplevel class can inherite from the main class tkinter opp inorder to access main class's attr
hi i want to access the mainwindow attributes and change some of its labels and button's states in my toplevel class however it can not find them. so im not sure how to use opp approach in tkinter and i tried usin... | how a toplevel class can inherite from the main class tkinter opp inorder to access main class's attr | hi i want to access the mainwindow attributes and change some of its labels and button's states in my toplevel class however it can not find them. so im not sure how to use opp approach in tkinter and i tried using super__init__ and textvariable but i failed. the main problem is inheritance in tkinter frame work and i ... | [
"Alright so, in order for you to inherit from the main class, you have to make your __init__() method's signature the same + whatever you might need for the top level class.\nExample:\nclass Parent:\n def __init__(self, attr1):\n self.attr1 = attr1\n\nclass Child(Parent):\n def __init__(self, attr1, at... | [
0,
0
] | [] | [] | [
"inheritance",
"python",
"subclass",
"tkinter",
"toplevel"
] | stackoverflow_0074613705_inheritance_python_subclass_tkinter_toplevel.txt |
Q:
Exclude Xpath from other Xpath
If you have two Xpaths you can join them with the | operator to return both their results in one result set. This essentially gives back the union of the two sets of elements. The example below gives back all divs and all spans on a website:
//div | //span
What I need is the differe... | Exclude Xpath from other Xpath | If you have two Xpaths you can join them with the | operator to return both their results in one result set. This essentially gives back the union of the two sets of elements. The example below gives back all divs and all spans on a website:
//div | //span
What I need is the difference (subsection). I need all element... | [
"An approach realizing this is using the self:: axis and the not() operator in a predicate:\nFor example, with an XML like this\n<root>\n <tr>\n <td>1</td>\n <td>2</td>\n <td>3</td>\n <td>4</td>\n <td>5</td>\n </tr> \n <dr>\n <td>1</td>\n <td>4</td>\n ... | [
1,
0,
0
] | [] | [] | [
"html",
"python",
"web_scraping",
"xpath",
"xpath_1.0"
] | stackoverflow_0074614843_html_python_web_scraping_xpath_xpath_1.0.txt |
Q:
Type conversion of custom class to float
I have a class customInt, which looks something like this:
class customInt:
def __init__(self, value):
self.value=int(value)
def __add__(self, other):
return foo(self.value+other.value)
# do some other stuff
obj=foo(1.23)
Is it possible to create a... | Type conversion of custom class to float | I have a class customInt, which looks something like this:
class customInt:
def __init__(self, value):
self.value=int(value)
def __add__(self, other):
return foo(self.value+other.value)
# do some other stuff
obj=foo(1.23)
Is it possible to create an operator/attribute/property/... to cast the ... | [
"You can define a def __float__(self): function in your class, and it will be called when you use float(obj). You can also add __int__, __str__ and __complex__ in the same way.\n"
] | [
2
] | [] | [] | [
"casting",
"python",
"type_conversion"
] | stackoverflow_0074616570_casting_python_type_conversion.txt |
Q:
Historgrams for lists inside a list
I have a list containing 8 lists. Each sub list has length of 100 and I want to plot histograms, 4 rows 2 columns.
I want to set the title, and x and y labels. In addition to a big title to all histograms.
I tired this:
mytitles = ['Label 30 sub 0', 'Label 30 sub 1',
'la... | Historgrams for lists inside a list | I have a list containing 8 lists. Each sub list has length of 100 and I want to plot histograms, 4 rows 2 columns.
I want to set the title, and x and y labels. In addition to a big title to all histograms.
I tired this:
mytitles = ['Label 30 sub 0', 'Label 30 sub 1',
'label 50 sub 0', 'label 50 sub 3',
... | [
"You need to iterate over the axes. Otherwise it will just use the last subplot.\nfor i, ax, title in zip(sub_list, axes.flat, mytitles):\n ax.hist(i, bins = 20)\n ax.set_title(title)\nplt.show()\n\n"
] | [
1
] | [] | [] | [
"histogram",
"list",
"python"
] | stackoverflow_0074616545_histogram_list_python.txt |
Q:
Coloring data sets with two colors in Spyder(Python 3.9)
I have a dataset with 569 data points, each associated with two features and labelled either as 0 0r 1. Based on the label, I want to make a scatterplot graph such that data point associated with label 0 gets a green dot while the other with label 1 gets red... | Coloring data sets with two colors in Spyder(Python 3.9) | I have a dataset with 569 data points, each associated with two features and labelled either as 0 0r 1. Based on the label, I want to make a scatterplot graph such that data point associated with label 0 gets a green dot while the other with label 1 gets red dot on the scatterplot.I am using spyder(python 3.9).
Here is... | [
"Change the last part to:\nfor target,color in zip(targets,colors):\n indicesToKeep=breast_dataset['label']==target\n plt.scatter(principal_breast_Df[breast_dataset['label']==target]['Principal component 1'], principal_breast_Df[breast_dataset['label']==target]['Principal component 2'],c=color,s=50)\n plt.... | [
0
] | [] | [] | [
"colors",
"graph",
"python",
"spyder"
] | stackoverflow_0074616534_colors_graph_python_spyder.txt |
Q:
Saving files inside a subfolder using Pathlib
I am using Pathlib to store my output images from a script.
My working tree looks like this : root> time.strftime("%H%M%S") > Scans.
I want to save the images using cv2.imwrite to the subfolder Scans. Using np.tofile to any other format is also fine.
But the problem is... | Saving files inside a subfolder using Pathlib | I am using Pathlib to store my output images from a script.
My working tree looks like this : root> time.strftime("%H%M%S") > Scans.
I want to save the images using cv2.imwrite to the subfolder Scans. Using np.tofile to any other format is also fine.
But the problem is I am not able to save the images to the folder "Sc... | [
"The problem is that you are not adding the / when you pass the output path to imwrite. This way, it reads the filename as for example Scans164617.png.\nI guess what you are looking for is:\ncv2.imwrite(str(scan_dir / \"image_name.png\"), data)\n\n"
] | [
0
] | [] | [] | [
"pathlib",
"python"
] | stackoverflow_0074616401_pathlib_python.txt |
Q:
GSPREAD: How do I fetch the last added worksheet from a spreadsheet having many worksheets?
Using gspread, I know how to access a sheet by name, id or index, like:
import gspread
gc = gspread.authorize(credentials)
worksheet = sh.worksheet("January")
or
worksheet = sh.sheet1
But I was wondering if it is possibl... | GSPREAD: How do I fetch the last added worksheet from a spreadsheet having many worksheets? | Using gspread, I know how to access a sheet by name, id or index, like:
import gspread
gc = gspread.authorize(credentials)
worksheet = sh.worksheet("January")
or
worksheet = sh.sheet1
But I was wondering if it is possible to open a last added or last updated sheet?
| [
"It's not possible to get the last modification of each spreadsheet sheet because this modification is fetched through Google Drive.\nIt's possible to obtain the last modification of the entire worksheet using the lastUpdateTime:\nimport gspread\nsa = gspread.service_account('authentication')\nsa.open(\"worksheet n... | [
0
] | [] | [] | [
"google_sheets",
"google_sheets_api",
"gspread",
"python"
] | stackoverflow_0054902092_google_sheets_google_sheets_api_gspread_python.txt |
Q:
Removing pip cache after installing dependencies in Docker image
I noticed that docker images may be large because of keeping pip cache in /root/.cache/pip. I know I can remove this directory after all my dependencies are installed in my docker image. What I'm not sure is how this relates to docker's BuildKit whic... | Removing pip cache after installing dependencies in Docker image | I noticed that docker images may be large because of keeping pip cache in /root/.cache/pip. I know I can remove this directory after all my dependencies are installed in my docker image. What I'm not sure is how this relates to docker's BuildKit which allows quicker installation by using cache. Are these two somehow re... | [
"The better solution here is to not cache the packages in the first place (you're not going to need them anyway; the image build process won't benefit from them unless you're doing something terrible).\nThe simplest solution is to just pass --no-cache-dir to your pip invocations, and it won't cache the packages to ... | [
1
] | [] | [] | [
"docker",
"linux",
"pip",
"python"
] | stackoverflow_0074616667_docker_linux_pip_python.txt |
Q:
AES-GCM 256-bit VS. SSL/TLS for socket security
Is there a difference between using AES-GCM 256-bit encryption, or using SSL/TLS to pass data over a socket.
I am currently passing data back and forth from client to server, using asymmetric AES-GCM 256-bit encryption. Is there an advantage to using SSL/TLS as oppos... | AES-GCM 256-bit VS. SSL/TLS for socket security | Is there a difference between using AES-GCM 256-bit encryption, or using SSL/TLS to pass data over a socket.
I am currently passing data back and forth from client to server, using asymmetric AES-GCM 256-bit encryption. Is there an advantage to using SSL/TLS as opposed to my current security method?
| [
"\ndifference between using AES-GCM 256-bit encryption, or using SSL/TLS\n\nThese cannot be directly compared.\n\nAES-GCM is encryption with integrity protection - nothing more. It needs an encryption key which somehow needs to be exchanged between the sender and recipient - how this is done is out of scope of AES... | [
2
] | [] | [] | [
"aes",
"encryption",
"python",
"security",
"ssl"
] | stackoverflow_0074616446_aes_encryption_python_security_ssl.txt |
Q:
pandas: merge strings when other columns satisfy a condition
I have a table:
genome start end strand etc
GUT_GENOME270877.fasta 98 396 +
GUT_GENOME270877.fasta 384 574 -
GUT_GENOME270877.fasta 593 984 +
GUT_GENOME270877.fasta 991 999 -
I'd like to make a new table with column coordinates, which jo... | pandas: merge strings when other columns satisfy a condition | I have a table:
genome start end strand etc
GUT_GENOME270877.fasta 98 396 +
GUT_GENOME270877.fasta 384 574 -
GUT_GENOME270877.fasta 593 984 +
GUT_GENOME270877.fasta 991 999 -
I'd like to make a new table with column coordinates, which joins start and end columns and looking like this:
genome start e... | [
"You can use numpy.where:\nm = df['strand'].eq('-')\n\ndf['coordinates'] = (np.where(m, 'complement(', '')\n +df['start'].astype(str)+'..'+df['end'].astype(str)\n +np.where(m, ')', '')\n )\n\nOr boolean indexing:\nm = df['strand'].eq('-')\n\ndf['coordinates']... | [
1
] | [] | [] | [
"conditional_statements",
"if_statement",
"pandas",
"python"
] | stackoverflow_0074616690_conditional_statements_if_statement_pandas_python.txt |
Q:
Error in pytube
Code:
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/playlist?list=PLWPirh4EWFpEpO6NjjWLbKSCb-wx3hMql')
for video in playlist.videos:
print("Video: ",video)
video.streams.get_highest_resolution().download()
Error I am getting:
<urlopen error [SSL: CERTIFICATE_V... | Error in pytube | Code:
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/playlist?list=PLWPirh4EWFpEpO6NjjWLbKSCb-wx3hMql')
for video in playlist.videos:
print("Video: ",video)
video.streams.get_highest_resolution().download()
Error I am getting:
<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certific... | [
"Go to /Applications/Python3.x and run 'Install Certificates.command'\n",
"(for OSX users)\nIn another words...\n\nGo to your applications folder and look for Python folder. Mine says \"Python 3.11\"\nOpen that directory, there is a file called \"Install Certificates.command\".\nOpen that file and it will run the... | [
0,
0,
0
] | [] | [] | [
"python",
"pytube",
"ssl",
"youtube"
] | stackoverflow_0072306952_python_pytube_ssl_youtube.txt |
Q:
Vscode black formatter is not working in poetry project
I have these settings in vscode for the black extension in a poetry project, which uses system cache and poetry venv.
"editor.formatOnSave": true,
"python.formatting.provider": "black",
"python.formatting.blackPath": "path-to-/bin/black",
"pyt... | Vscode black formatter is not working in poetry project | I have these settings in vscode for the black extension in a poetry project, which uses system cache and poetry venv.
"editor.formatOnSave": true,
"python.formatting.provider": "black",
"python.formatting.blackPath": "path-to-/bin/black",
"python.pythonPath": "path-to-/python",
"python.linting.mypyE... | [
"Make sure black is installed in current used environment.\nOpen a integrated Terminal and activate the venv, run pip show black to see if it's installed in current environment. If not,\n1.Comment these two settings;\n\n\"python.formatting.provider\": \"black\",\n\"python.formatting.blackPath\":\"path-to-/bin/black... | [
2,
1,
0
] | [] | [] | [
"django",
"python",
"visual_studio_code"
] | stackoverflow_0067287004_django_python_visual_studio_code.txt |
Q:
how to check if a dynamodb attribute is a reserved keyword (in Python)
I need to update a dynamodb table using the update_item method.
I get a dynamic list of attribute to update, so some of them can be reserved words.
Is there a way to check (in Python) if an attribute is a reserved word?
There is a list of all ~... | how to check if a dynamodb attribute is a reserved keyword (in Python) | I need to update a dynamodb table using the update_item method.
I get a dynamic list of attribute to update, so some of them can be reserved words.
Is there a way to check (in Python) if an attribute is a reserved word?
There is a list of all ~570 words here. So in theory I can create a static list and check it, but I ... | [
"Always use expressionAttributeValues/Names so that you do not have to check if the word is reserved or not. That is not a static list of reserved words and can be changed at anytime. There is no API to check for reserved key words.\n"
] | [
1
] | [] | [] | [
"amazon_dynamodb",
"boto3",
"python"
] | stackoverflow_0074615649_amazon_dynamodb_boto3_python.txt |
Q:
Why does not pandas datetime work when trying to change dateformat?
I have the following code
temp1 = df.iloc[1:,0]
print(type(temp1))
temp2 = pd.to_datetime(temp1, format='%Y/%m/%d')
where df is a dataframe whose first column (i.e. column 0) contains dates with format "YYYY-MM-DD-hh-mm-ss". Now I'm trying to con... | Why does not pandas datetime work when trying to change dateformat? | I have the following code
temp1 = df.iloc[1:,0]
print(type(temp1))
temp2 = pd.to_datetime(temp1, format='%Y/%m/%d')
where df is a dataframe whose first column (i.e. column 0) contains dates with format "YYYY-MM-DD-hh-mm-ss". Now I'm trying to convert that into the format "YYYY-MM-DD" with line 2 and 3 but it does not ... | [
"The format is to tell pandas how to parse the datetime string, not how to output the result. From the docs:\nThe strftime to parse time, e.g. \"%d/%m/%Y\"\n\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html\nYou can use something like this to format the datetime:\nimport pandas as... | [
2
] | [] | [] | [
"pandas",
"python",
"python_3.x",
"python_datetime"
] | stackoverflow_0074616802_pandas_python_python_3.x_python_datetime.txt |
Q:
Issues while Generating TFrecords
I am Trying to generate tfrecord file with tensorflow 2.0, at the first I have generated correctly the files, but when I am trying generate them again, python console show an error below:
Traceback (most recent call last):
File "generate_tfrecordv2.py", line 106, in <module>
... | Issues while Generating TFrecords | I am Trying to generate tfrecord file with tensorflow 2.0, at the first I have generated correctly the files, but when I am trying generate them again, python console show an error below:
Traceback (most recent call last):
File "generate_tfrecordv2.py", line 106, in <module>
tf.compat.v1.app.run()
File "C:\User... | [
"I had the same error because I used RectLabel and I exported the CSV file directly from there.\nThe CSV must have this line first:\nfilename,width,height,class,xmin,ymin,xmax,ymax\nExample annotations.csv:\nfilename,width,height,class,xmin,ymin,xmax,ymax\n8.jpg,1280,720,label1,427,82,848,578\n9.jpg,1280,720,label1... | [
0
] | [
"@Louis and @jedesha if you check my name, you see it's kw while I specified on my label that it's a capital letter K and not a small letter k or Kw. what you need to do is ensure your filename is correctly written without any underscore in the filename as 1_245 to 1245\n`<object>\n <name>Kw</name> (wrong name)\n ... | [
-1
] | [
"pandas_groupby",
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0058753666_pandas_groupby_python_python_3.x_tensorflow.txt |
Q:
ERROR: Could not install packages due to an OSError: [13] Permission denied: '/nix/store/8d3695w7vasap3kkcn3yk731v4iw2kcv-python3.8-pip-21.1.3/bin/pip
I've been working on one error for about an hour. I've been development an app in Nix on REPLIT. But no matter what I do this error comes while installing packages ... | ERROR: Could not install packages due to an OSError: [13] Permission denied: '/nix/store/8d3695w7vasap3kkcn3yk731v4iw2kcv-python3.8-pip-21.1.3/bin/pip | I've been working on one error for about an hour. I've been development an app in Nix on REPLIT. But no matter what I do this error comes while installing packages with with Python Pip:
Firstly, this came up whilst installing any packages... But I realized it also comes up in attempt to update Pip.
ERROR: Could not ins... | [
"You could try using the --user option installs the package in the user's home directory.\nEg.\npip install octosuite --user\n\n"
] | [
0
] | [] | [] | [
"nix",
"pip",
"python",
"replit"
] | stackoverflow_0072117127_nix_pip_python_replit.txt |
Q:
Unable to download a file from Azure Repos using azure devops api python
I am trying to write a script to download a single file from azure repos using python.
I am using the official Microsoft library https://github.com/microsoft/azure-devops-python-api
from azure.devops.connection import Connection
from msrest.a... | Unable to download a file from Azure Repos using azure devops api python | I am trying to write a script to download a single file from azure repos using python.
I am using the official Microsoft library https://github.com/microsoft/azure-devops-python-api
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
personal_access_token = "MY_PAT"
org... | [
"It cannot be saved directly. it is generator object. You can use my reference below to save it into file.\nfile_content = git_client.get_item_content(repo_id,path=file_path,download=True,include_content=True)\nwith open('output.txt', 'wb') as f:\n for x in file_content:\n f.write(x)\n\n"
] | [
0
] | [] | [] | [
"azure_devops",
"azure_devops_rest_api",
"azure_repos",
"python"
] | stackoverflow_0072989160_azure_devops_azure_devops_rest_api_azure_repos_python.txt |
Q:
How to upload file to Sharepoint folder
I want to upload a file from my local machine to SharePoint using the Office365-REST-Python-Client library. The issue I'm having to uploading the file to a specific folder in SharePoint. Documentation seems to be all over the place. The Github repo provides the following sol... | How to upload file to Sharepoint folder | I want to upload a file from my local machine to SharePoint using the Office365-REST-Python-Client library. The issue I'm having to uploading the file to a specific folder in SharePoint. Documentation seems to be all over the place. The Github repo provides the following solution to upload a file to the main "Documents... | [
"I found your question while I was looking for the exact same answer and having come to the same conclusions about the documentation needing to be a little more helpful.\nI'm using an Azure Service Principal (Registered App) not username/password, that's the primary difference.\nI store creds securely in Windows Cr... | [
0
] | [] | [] | [
"python",
"sharepoint"
] | stackoverflow_0072628931_python_sharepoint.txt |
Q:
Inline buttons doesnt work in Aiogram Telegram Bot
Im trying to get a random number while clicking inline buttons. Im getting a message with buttons, but when i click on them nothing happends — i just see a small clock in the button. Here are my handlers:
from loader import dp
from random import randint
from aiog... | Inline buttons doesnt work in Aiogram Telegram Bot | Im trying to get a random number while clicking inline buttons. Im getting a message with buttons, but when i click on them nothing happends — i just see a small clock in the button. Here are my handlers:
from loader import dp
from random import randint
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardBut... | [
"You need to add\nstate=\"*\"\n\ninto\n@dp.callback_query_handler(text=[\"random1-10\", \"random1-100\"])\n\n"
] | [
0
] | [] | [] | [
"aiogram",
"python",
"telegram_api",
"telegram_bot"
] | stackoverflow_0074616302_aiogram_python_telegram_api_telegram_bot.txt |
Q:
How to end the loop when I type n?
import random
#yes or no
yrn = input("R u going to play black jack? (Y/N): ").upper()
if yrn == "Y":
player1 = random.randint(1,19)
player2 = random.randint(1,19)
print(player1,player2)
while True:
player1_yrn = input("Player 1, Do you want more numbers?... | How to end the loop when I type n? | import random
#yes or no
yrn = input("R u going to play black jack? (Y/N): ").upper()
if yrn == "Y":
player1 = random.randint(1,19)
player2 = random.randint(1,19)
print(player1,player2)
while True:
player1_yrn = input("Player 1, Do you want more numbers? (Y/N): ").upper()
if player1_yr... | [
"You need some state to allow you to remember when a player says \"no more cards\". A boolean flag per player would be one way to do it:\nplayer1_keep_dealing = True\nplayer2_keep_dealing = True\nwhile player1_keep_dealing and player2_keep_dealing:\n if player1_keep_dealing:\n player1_yrn = input(\"Player... | [
0,
0,
0
] | [] | [] | [
"input",
"python"
] | stackoverflow_0074616599_input_python.txt |
Q:
how to fix error UNIQUE constraint failed: auth_user.username
i was trying to use sending email modual from django in order to send sign up email for each user when sign up im facing this error :UNIQUE constraint failed: auth_user.username
` i was trying to use sending email modual from django in order to send si... | how to fix error UNIQUE constraint failed: auth_user.username | i was trying to use sending email modual from django in order to send sign up email for each user when sign up im facing this error :UNIQUE constraint failed: auth_user.username
` i was trying to use sending email modual from django in order to send sign up email for each user when sign up im facing this error :UNIQUE... | [
"Someone is signing up with a username that already exists. The username field in the auth_user table has a uniqueness constraint that prevents you from inserting a row that has a username that already exists in the table.\n",
"thanks @Eshter the solution was as mention above :create an \"application password\" f... | [
2,
0
] | [] | [] | [
"django",
"email",
"oauth_2.0",
"python"
] | stackoverflow_0074605979_django_email_oauth_2.0_python.txt |
Q:
Why does defining new class sometimes call the __init__() function of objects that the class inherits from?
I'm trying to understand what actually happens when you declare a new class which inherits from a parent class in python.
Here's a very simple code snippet:
# inheritance.py
class Foo():
def __init__(sel... | Why does defining new class sometimes call the __init__() function of objects that the class inherits from? | I'm trying to understand what actually happens when you declare a new class which inherits from a parent class in python.
Here's a very simple code snippet:
# inheritance.py
class Foo():
def __init__(self, *args, **kwargs):
print("Inside foo.__init__")
print(args)
print(kwargs)
class Bar(F... | [
"Python is using foo to determine the metaclass to use for Bar. No explicit metaclass is given, so the \"most derived metaclass\" must be determined. The metaclass of a base class is its type; usually, that's type itself. But in this case, the type of the only base \"class\", foo, is Foo, so that becomes the most d... | [
6
] | [] | [] | [
"inheritance",
"metaclass",
"python",
"python_3.x"
] | stackoverflow_0074616757_inheritance_metaclass_python_python_3.x.txt |
Q:
Converting Matlab function to Python
I have a Matlab file that I'm looking to convert into Python. Part of it is functions and I'm a bit confused by it. In the Matlab code, there is a function that looks like this:
function [u, v, speed, dir] = NewCalculations(data)
Would the Python equivalent of this be?:
def Ne... | Converting Matlab function to Python | I have a Matlab file that I'm looking to convert into Python. Part of it is functions and I'm a bit confused by it. In the Matlab code, there is a function that looks like this:
function [u, v, speed, dir] = NewCalculations(data)
Would the Python equivalent of this be?:
def NewCalculations(data):
u = data.u
v ... | [
"It would be like this:\ndef NewCalculations(data):\n# some calculations\n return u, v, speed, dir\n\nThe matlab syntax is\nfunction outvars = functionname(inputvars)\n\n"
] | [
1
] | [] | [] | [
"function",
"matlab",
"python"
] | stackoverflow_0074616904_function_matlab_python.txt |
Q:
Read a CSV file and connec to database based on columns
I have a file.csv that contains columns databasename and tablename. Using Python I have to perform an action in such a way if column1 is pointing to a database a then connect to server a and perform action on that table. Otherwise, connect to server b and per... | Read a CSV file and connec to database based on columns | I have a file.csv that contains columns databasename and tablename. Using Python I have to perform an action in such a way if column1 is pointing to a database a then connect to server a and perform action on that table. Otherwise, connect to server b and perform action on tables in server b.
Example file.csv:
database... | [
"A simple example using psycopg2 as the Python driver to a Postgres\ndatabase:\ncat file.csv \ndatabase,tablename\ndb1,tbl1\ndb2,tbl2 \ndb2,tbl3\ndb1,tbl4\n\ni... | [
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python",
"split"
] | stackoverflow_0074609706_csv_dataframe_pandas_python_split.txt |
Q:
Peak Detection of Partial Discharges with CNN
This is one of my first posts here so if I make any mistakes or don't follow some guidelines please be considerate.
For my bachelors thesis im trying to create a CNN with tensorflow which has the ability to do basic peak detection like scipy.find_peaks for example. My ... | Peak Detection of Partial Discharges with CNN | This is one of my first posts here so if I make any mistakes or don't follow some guidelines please be considerate.
For my bachelors thesis im trying to create a CNN with tensorflow which has the ability to do basic peak detection like scipy.find_peaks for example. My input data consists of 2 numpy arrays with timeseri... | [
"Since your output is of the same shape as your input, and you want to classify each point, maybe you should try a unet, similar to this one:\n Something like the following (added normalization, and some noise and dropout to prevent overfitting):\nskip_connections = []\nkernel_size = 7\npool_size = 10\ndeepth = 3\n... | [
0
] | [] | [] | [
"autoencoder",
"conv_neural_network",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0074600357_autoencoder_conv_neural_network_machine_learning_python_tensorflow.txt |
Q:
how to use if statement with return to check if the function returns value when calling stored proc using python
i need to check the value with return if getting some value when calling procedure in python
` i need to check the value with return if getting some value when calling procedure in python`
def get_ord... | how to use if statement with return to check if the function returns value when calling stored proc using python | i need to check the value with return if getting some value when calling procedure in python
` i need to check the value with return if getting some value when calling procedure in python`
def get_order_count(salesman_id, year):
try:
# create a connection to the Oracle Database
with cx_Oracle.conn... | [
" so inside a procedder there was if stament to check if run right then will return 1 if not 0 so we assing that to int value and then use it when calling procedure\nif order_count ==1:\nprint ('succesesfull' )\nelif: order_count ==0:\nprint('faild')\nelse:\npass ```\n\n"
] | [
0
] | [] | [] | [
"cx_oracle",
"oracle",
"python",
"sql"
] | stackoverflow_0074379044_cx_oracle_oracle_python_sql.txt |
Q:
Group separate strings of an OCR-Result based on coordinates in the image
I use easyocr to read the key figures from an image (display output of measuring instrument).
Because of different proportions of characters on the picture, some characters/strings, that are meant to be one unit, like value and unit (e.g "23... | Group separate strings of an OCR-Result based on coordinates in the image | I use easyocr to read the key figures from an image (display output of measuring instrument).
Because of different proportions of characters on the picture, some characters/strings, that are meant to be one unit, like value and unit (e.g "230 Volt"), are recognised as separate strings ("230", "Volt"). Another example a... | [
"Every time you will similar pattern text like in above case you get 230 volts...Like in another example you will get 320 volts? ...So which will be formatted as x volts?\nIf so\nimport pandas as pd\nc1_str = ' '.join(df[\"Text\"])\n\nc1_str = c1_str.replace('linebreaks', 'linebreaks|')\nc1_str = c1_str.replace('... | [
0
] | [] | [] | [
"easyocr",
"numpy",
"pandas",
"python"
] | stackoverflow_0074616726_easyocr_numpy_pandas_python.txt |
Q:
How to export YahooQuery Dict type modules to CSV from AttributeError: 'dict' object has no attribute 'to_csv'?
AttributeError: 'dict' object has no attribute 'to_csv' occurs with the following:
import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT']
faang = Ticker(symbols)
faang.asset_... | How to export YahooQuery Dict type modules to CSV from AttributeError: 'dict' object has no attribute 'to_csv'? | AttributeError: 'dict' object has no attribute 'to_csv' occurs with the following:
import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT']
faang = Ticker(symbols)
faang.asset_profile
df = (faang.asset_profile)
df.to_csv('output.csv', mode='a', index=True, header=True)
It happens with a lot ... | [
"This seems to be working:\nimport pandas as pd\nfrom yahooquery import Ticker\nsymbols = ['AAPL','GOOG','MSFT'] \nfaang = Ticker(symbols)\nfaang.asset_profile\ndf = pd.DataFrame(faang.asset_profile).T\ndf.to_csv('output.csv', mode='a', index=True, header=True)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python",
"yfinance"
] | stackoverflow_0074616735_dataframe_dictionary_pandas_python_yfinance.txt |
Q:
OSError: [WinError 193] %1 is not a valid Win32 application - nltk
So, I keep getting this error:
OSError: [WinError 193] %1 is not a valid Win32 application
I believed it to be because of my environment variables. So, I fixed that, but still keep getting the error. I'm at a loss currently. Here's the complete er... | OSError: [WinError 193] %1 is not a valid Win32 application - nltk | So, I keep getting this error:
OSError: [WinError 193] %1 is not a valid Win32 application
I believed it to be because of my environment variables. So, I fixed that, but still keep getting the error. I'm at a loss currently. Here's the complete error output:
Traceback (most recent call last):
File "c:\Users\angel\De... | [
"OSError: [WinError 193] %1 is not a valid Win32 application\n\nMaybe your computer's OS is not window_32, But your python version is 32-bit. So check your OS, I guess your OS is window_64, And install right python version.\nHere is python installer for window_64.\npython installer for win_64\n",
"I ran into the ... | [
0,
0,
0
] | [] | [] | [
"corpus",
"nltk",
"python",
"python_3.x"
] | stackoverflow_0062337501_corpus_nltk_python_python_3.x.txt |
Q:
trying to make snakecase program
so i have to make an snakecase program
camelcase = input("camelCase: ")
snakecase = camelcase.lower()
for c in camelcase:
if c.isupper():
snakecase += "_"
snakecase += c.lower()
print(snakecase)
with the for im going through each letter, the if is for... | trying to make snakecase program | so i have to make an snakecase program
camelcase = input("camelCase: ")
snakecase = camelcase.lower()
for c in camelcase:
if c.isupper():
snakecase += "_"
snakecase += c.lower()
print(snakecase)
with the for im going through each letter, the if is for finding the uppercase right? but im ... | [
"Use list comprehension: it is more Pythonic and concise:\ncamelcase = input(\"camelCase: \")\nsnakecase = ''.join(c if c.lower() == c else '_' + c.lower() for c in camelcase)\nprint(snakecase)\n\n",
"With += you are adding the _ to the end of the snakecase variable. This you do for every uppercase character and ... | [
2,
1
] | [
"Your function would work if snakecase was empty, but it is not.\nYou should initialize it to snakecase = str()\n"
] | [
-1
] | [
"python",
"snakecase"
] | stackoverflow_0074616852_python_snakecase.txt |
Q:
Use TensorFlow model to guess / predict values between 2 points
My question is something that I didn't encounter anywhere, I've been wondering if it was possible for a TF Model to determinate values between 2 dates that have real / validated values assigned to them.
I have an example :
Let's take the price of Nick... | Use TensorFlow model to guess / predict values between 2 points | My question is something that I didn't encounter anywhere, I've been wondering if it was possible for a TF Model to determinate values between 2 dates that have real / validated values assigned to them.
I have an example :
Let's take the price of Nickel, here's it's chart the last week :
There is no data for the two f... | [
"It would be possible to create a machine learning model to predict the prices given a dataset of previous prices. Take a look at this post for instance. You would have to modify it slightly such that it predicts the prices in the gaps given previous and upcoming prices.\nBut for the example you gave assuming the d... | [
1
] | [] | [] | [
"keras",
"python",
"tensorflow",
"tf.keras"
] | stackoverflow_0074616938_keras_python_tensorflow_tf.keras.txt |
Q:
How to use numpy.arange with two other arrays as the start and stop parameter?
I want to build a 2D-array where the first dimension has the same length as two other arrays and the second dimension is an array created by numpy.arange and based on every element of the other two arrays, where one array defines the st... | How to use numpy.arange with two other arrays as the start and stop parameter? | I want to build a 2D-array where the first dimension has the same length as two other arrays and the second dimension is an array created by numpy.arange and based on every element of the other two arrays, where one array defines the start parameter and the second array defines the stop parameter-1.
Let me give an exam... | [
"You can do this by using zip and list comprehension\nres_arr = [np.arange(start, stop + 1) for start, stop in zip(arr_1, arr_2)]\n\n"
] | [
2
] | [] | [] | [
"arrays",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0074616862_arrays_multidimensional_array_numpy_python.txt |
Q:
Convert Unicode char code to char on Python
I have a list of Unicode character codes I need to convert into chars on python 2.7.
U+0021
U+0022
U+0023
.......
U+0024
How to do that?
A:
This regular expression will replace all U+nnnn sequences with the corresponding Unicode character:
import re
s = u'''\
U+0021
... | Convert Unicode char code to char on Python | I have a list of Unicode character codes I need to convert into chars on python 2.7.
U+0021
U+0022
U+0023
.......
U+0024
How to do that?
| [
"This regular expression will replace all U+nnnn sequences with the corresponding Unicode character:\nimport re\n\ns = u'''\\\nU+0021\nU+0022\nU+0023\n.......\nU+0024\n'''\n\ns = re.sub(ur'U\\+([0-9A-F]{4})',lambda m: unichr(int(m.group(1),16)),s)\n\nprint(s)\n\nOutput:\n!\n\"\n#\n.......\n$\n\nExplanation:\n\nunic... | [
2,
1,
0
] | [
"a = 'U+aaa'\na.encode('ascii','ignore')\n'aaa'\n\nThis will convert for unicode to Ascii which i think is what you want.\n"
] | [
-2
] | [
"python",
"python_2.7",
"unicode"
] | stackoverflow_0050283553_python_python_2.7_unicode.txt |
Q:
PyCharm does not highlight errors
I have a problem with PyCharm v2.7.
it does not show me errors.
I have configured it to show them as here
but nothing.
here a screenshot of what I see (no error displayed)
if I run code analysis it shows the errors marked as INVALID in the window but it does not highlight the cod... | PyCharm does not highlight errors | I have a problem with PyCharm v2.7.
it does not show me errors.
I have configured it to show them as here
but nothing.
here a screenshot of what I see (no error displayed)
if I run code analysis it shows the errors marked as INVALID in the window but it does not highlight the code.
any idea?
| [
"I had this issue recently on PyCharm 2020.3.3 Community Edition.\nWhat I've found is in the top right corner of the editor there is a Reader Mode button.\nIf you click it you turn the Reader Mode off and then you can see your errors.\n\nYou can re-enable it by clicking the book icon\n\n",
"I found. i've enabled ... | [
57,
6,
3,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0020663545_pycharm_python.txt |
Q:
Constraining select coefficients to be the same across equations in a SUR system
I want to estimate Labor Force Participation Rates for different age groups in a system of seemingly unrelated regressions (SUR), regressing them on some age group specific variables and shared birth-cohort dummies. This is the typica... | Constraining select coefficients to be the same across equations in a SUR system | I want to estimate Labor Force Participation Rates for different age groups in a system of seemingly unrelated regressions (SUR), regressing them on some age group specific variables and shared birth-cohort dummies. This is the typical cohort-based approach (see for example Grigoli et al (2018).
I manage to estimate th... | [
"Answering my own question after I got inspired by a friend. This is easily formulated in a linear constraint. The coefficient of benefits_male minus earnings_male needs to equal 0:\nconstraints_matrix=pd.DataFrame([0,1,0,-1]).transpose()\nconstraints_values=pd.Series([0])\nmod.add_constraints(constraints_matrix,co... | [
0
] | [] | [] | [
"linearmodels",
"python",
"seemingly_unrelated_regression"
] | stackoverflow_0074606527_linearmodels_python_seemingly_unrelated_regression.txt |
Q:
Python f-string with variable width alignment
I want to print below code.
!!!!**
!!!****
!!******
!********
So I use while loop with i, j. But, in some parts, the output of ! becomes weird.
I tried some case, there is no problem if the i and j are in ascending order, but there is a problem if they are in descendin... | Python f-string with variable width alignment | I want to print below code.
!!!!**
!!!****
!!******
!********
So I use while loop with i, j. But, in some parts, the output of ! becomes weird.
I tried some case, there is no problem if the i and j are in ascending order, but there is a problem if they are in descending order. Below my code, print(i, j) means there was... | [
"Aren't you over-complicating things a bit here?\nIf it's the pattern you are looking for here:\ndef print_pattern(bangs: int, stars: int)->None:\n output = f\"{'!'*bangs}{'*'*stars}\"\n print(output)\n\nCare to provide some more explanations about what do you expect actually?\nIs the total number of chars f... | [
0,
0,
0
] | [
"I found wrong thing.\ns1 = f\"{s1:!<{j}}\" in this part, value(j) is max value.\nSo, s1 already full.\nAt the end of the loop, s1 must be initialized.\nI should add s1 = \"\"\n"
] | [
-1
] | [
"alignment",
"f_string",
"python",
"while_loop",
"width"
] | stackoverflow_0074616829_alignment_f_string_python_while_loop_width.txt |
Q:
How to check if the first line has changed in a text file using python
I'm trying to write a script that will check if the first line of a text file has changed and print the value once. It needs to be an infinite loop so It will always keep checking for a change. The problem I'm having is when the value is change... | How to check if the first line has changed in a text file using python | I'm trying to write a script that will check if the first line of a text file has changed and print the value once. It needs to be an infinite loop so It will always keep checking for a change. The problem I'm having is when the value is changed it will keep constantly printing and it does not detect the new change.
Wh... | [
"If the initial line has changed, set initial to current.\nIn the function checkvar()\ndef checkvar():\n initial = getvar()\n print(\"Initial var: {}\".format(initial))\n while True:\n current = getvar()\n if initial == current:\n pass \n el... | [
2,
2
] | [] | [] | [
"if_statement",
"python",
"while_loop"
] | stackoverflow_0074617156_if_statement_python_while_loop.txt |
Q:
Unzigzag an array into a matrix
I have a 1D array which is in fact a 2D matrix sampled this way:
↓-------<------S <- start
>------->------↓
↓-------<------<
>------->------E <- end
For example
B = 1 2 3 4
5 6 7 8
9 10 11 12
is coded as A = [4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9].
The numbe... | Unzigzag an array into a matrix | I have a 1D array which is in fact a 2D matrix sampled this way:
↓-------<------S <- start
>------->------↓
↓-------<------<
>------->------E <- end
For example
B = 1 2 3 4
5 6 7 8
9 10 11 12
is coded as A = [4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9].
The number of rows can be odd or even.
The fol... | [
"I would reshape, then updated every other row with the horizontally flipped version of that row.\nimport numpy as np\n\na = np.array([4, 3, 2, 1, 5, 6, 7, 8, 12, 11, 10, 9])\nnumcols = 4\n\na = a.reshape(-1,numcols)\na[::2] = np.flip(a, axis=1)[::2]\n\nprint(a)\n\nOutput\n[[ 1 2 3 4]\n [ 5 6 7 8]\n [ 9 10 11... | [
4,
1
] | [] | [] | [
"matrix",
"numpy",
"numpy_ndarray",
"performance",
"python"
] | stackoverflow_0074615495_matrix_numpy_numpy_ndarray_performance_python.txt |
Q:
Take only one side of a list of lists and add to a new list
Say I have multiple lists of lists. Something like this:
list1 = [[1,2],[56,32],[34,244]]
list2 = [[43,21],[30,1],[19,3]]
list3 = [[1,3],[8,21],[9,57]]
I want to create two new lists:
right_side = [2,32,244,21,1,3,3,21,57]
left_side = [1,56,34,43,30,19,1... | Take only one side of a list of lists and add to a new list | Say I have multiple lists of lists. Something like this:
list1 = [[1,2],[56,32],[34,244]]
list2 = [[43,21],[30,1],[19,3]]
list3 = [[1,3],[8,21],[9,57]]
I want to create two new lists:
right_side = [2,32,244,21,1,3,3,21,57]
left_side = [1,56,34,43,30,19,1,8,9]
All sub-lists have only two values. And all big lists (lis... | [
"By using zip built-in function you get tuples:\nleft_side, right_side = zip(*list1, *list2, *list3)\n\nAnd if you really need lists:\nleft_side, right_side = map(list, zip(*list1, *list2, *list3))\n\n",
"The below seems to work.\nlist1 = [[1, 2], [56, 32], [34, 244]]\nlist2 = [[43, 21], [30, 1], [19, 3]]\nlist3 ... | [
2,
2,
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074617210_list_python.txt |
Q:
Write multiple rows to a CSV
I have a small GUI which should write the values into a CSV file. However, the header is always written instead of just the new entries.
this is how it looks in the csv:
Amount, Time
1000,12:13:40
Amount, Time
2000,12:14:30
What I want:
Amount, Time
1000,12:13:40
2000,12:14:30
def ... | Write multiple rows to a CSV | I have a small GUI which should write the values into a CSV file. However, the header is always written instead of just the new entries.
this is how it looks in the csv:
Amount, Time
1000,12:13:40
Amount, Time
2000,12:14:30
What I want:
Amount, Time
1000,12:13:40
2000,12:14:30
def submit():
import csv
imp... | [
"You unconditionally write the header again each time you call submit. Either:\n\nRemove that header write, and have, somewhere outside submit (early in your program, run exactly once), the code that initializes (opens in \"w\" mode so the file is cleared) the file with just the header, so each submit doesn't add a... | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074617295_csv_python.txt |
Q:
get data sent from flask to html
I am doing a flask application and I have a issue related to data sent from render_template() in flask to html web page.
This is my flask code ( I want to pass a number)
screenx = ((int(width[0][0]) - 0))
return render_template('/barchart.html', screen = screenx)
while this is... | get data sent from flask to html | I am doing a flask application and I have a issue related to data sent from render_template() in flask to html web page.
This is my flask code ( I want to pass a number)
screenx = ((int(width[0][0]) - 0))
return render_template('/barchart.html', screen = screenx)
while this is my html code.
<canvas id="myCanvas" ... | [
"Flask\nscreenx = ((int(width[0][0]) - 0)) \nreturn render_template('/barchart.html', data=screenx)\n\nHTML\nscreenx1={{data}}\n\nUse data instead of screen?\n"
] | [
0
] | [] | [] | [
"canvas",
"flask",
"html",
"python"
] | stackoverflow_0074616644_canvas_flask_html_python.txt |
Q:
Code returning :.2f as invalid for a str, not sure where I'm missing the Float conversion
Working on a code for Python, where essentially I am taking a csv file and depending on user input, I can print/return the connected information within the csv file. Essentially I'm slowly but surely de-bugging it but I'm stu... | Code returning :.2f as invalid for a str, not sure where I'm missing the Float conversion | Working on a code for Python, where essentially I am taking a csv file and depending on user input, I can print/return the connected information within the csv file. Essentially I'm slowly but surely de-bugging it but I'm stuck most likely due to frustration and would love some help catching what's wrong. So been tryin... | [
"Both calc_minimums and calc_maximums are copying string data directly from the provided filtered_data argument without performing any type conversions. It's string data because the filter_data function is not performing any type conversions itself, and since you're not reading from the file with the csv.QUOTE_NONN... | [
1
] | [] | [] | [
"csv",
"python",
"string"
] | stackoverflow_0074617352_csv_python_string.txt |
Q:
Writing into a specific location in a text file
How do I add a string/integer into an existing text file at a specific location?
My sample text looks like below:
No, Color, Height, age
1, blue,70,
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,
My text file has 4 columns, three columns have text, how do I wri... | Writing into a specific location in a text file | How do I add a string/integer into an existing text file at a specific location?
My sample text looks like below:
No, Color, Height, age
1, blue,70,
2, white,65,
3, brown,49,
4, purple,71,
5, grey,60,
My text file has 4 columns, three columns have text, how do I write to any row in the fourth column?
If I want to writ... | [
"Alternate way is read that text file to a list & append based on index as follows.\nwith open('sample.txt') as file:\n lines = [line.rstrip() for line in file]\n\nline1 = lines[1]\nnew_line1 = line1 + str(12)\nlines[1] = new_line1\n\nwith open('sample.txt', mode='wt', encoding='utf-8') as f:\n f.write('\\n'.... | [
0,
0
] | [] | [] | [
"file_writing",
"overwrite",
"python",
"text"
] | stackoverflow_0074616016_file_writing_overwrite_python_text.txt |
Q:
Selenium : Add multiple path with send_keys
When I try to add multiple path to an input type=file, one per one, it adds the file 1 then the file 1 and 2 etc...
new_images = modify_images(ad['images_url'])
time.sleep(4)
add_images = driver.find_element(By.XPATH, image_add_xpath)
time.sleep(2)
for i in range(len(new... | Selenium : Add multiple path with send_keys | When I try to add multiple path to an input type=file, one per one, it adds the file 1 then the file 1 and 2 etc...
new_images = modify_images(ad['images_url'])
time.sleep(4)
add_images = driver.find_element(By.XPATH, image_add_xpath)
time.sleep(2)
for i in range(len(new_images)):
print("image " + str(index) + " " ... | [
"From your code trials shown here looks like you didn't add the new line correctly.\nTo upload multiple files you can construct a string adding all the absolute paths of the uploaded files separated by \\n , as following:\nall_path_images = \"\"\nfor i in range(len(new_images)):\n all_path_images + = r\"C:\\\\Us... | [
1
] | [] | [] | [
"file_upload",
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074616739_file_upload_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
slope varying on straight, parallel linestrings (shapely)
I have 2 parallel lines (line1 = [(1,3),(4,3)] and line2 = [(1,2),(4,2)]):
Both have the same slope if I calculate it manually with m = (y-y1)/(x-x1):
line1: m1 = (3-3)/(1-4) = 0
line2: m2 = (2-2)/(1-4) = 0
m1 = m2 and therefore the lines are parallel, lik... | slope varying on straight, parallel linestrings (shapely) | I have 2 parallel lines (line1 = [(1,3),(4,3)] and line2 = [(1,2),(4,2)]):
Both have the same slope if I calculate it manually with m = (y-y1)/(x-x1):
line1: m1 = (3-3)/(1-4) = 0
line2: m2 = (2-2)/(1-4) = 0
m1 = m2 and therefore the lines are parallel, like shown in the picture.
But if I create shapely linestrings fro... | [
"line1.cord[0] returns x1,y1 not x1,x2\nimport matplotlib.pyplot as plt\nfrom shapely.geometry import LineString\n\nline1 = LineString([(1,3),(4,3)])\nline2 = LineString([(1,2),(4,2)])\n\nfig, ax = plt.subplots()\nax.plot(*line1.xy)\nax.plot(*line2.xy)\n\nxs1, ys1 = line1.coords[0]\nxe1, ye1 = line1.coords[1]\n\nm1... | [
2
] | [] | [] | [
"line",
"math",
"python",
"shapely"
] | stackoverflow_0074617327_line_math_python_shapely.txt |
Q:
Returning people born before certain year from tuple?
I need to write a function named older_people(people: list, year: int), which selects all those people on the list who were born before the year given as an argument. The function should return the names of these people in a new list.
An example of its use:
p1 ... | Returning people born before certain year from tuple? | I need to write a function named older_people(people: list, year: int), which selects all those people on the list who were born before the year given as an argument. The function should return the names of these people in a new list.
An example of its use:
p1 = ("Adam", 1977)
p2 = ("Ellen", 1985)
p3 = ("Mary", 1953)
p... | [
"First you should use the argument of the function in the body of older_people instead of the global variable plist. people should be used instead of plist.\nThen, your return statement is inside the for loop, this means that it will leave the function at the first time the if condition is true, hence printing only... | [
2,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0074616213_python_tuples.txt |
Q:
New Conda environment with latest Python Version for Jupyter Notebook
Since Python version changes are far and few between, I always forget how I have created a new Conda environment with the latest Python for Jupyter Notebook, so I thought I'd list it down for next time. From StackOverflow, there are some answer... | New Conda environment with latest Python Version for Jupyter Notebook | Since Python version changes are far and few between, I always forget how I have created a new Conda environment with the latest Python for Jupyter Notebook, so I thought I'd list it down for next time. From StackOverflow, there are some answers that no longer worked, and below is a compilation of commands I found on ... | [
"\nThe steps in the main question above is the nb_conda_kernels way. With nb_conda_kernels installed in the base environment, any notebook running from the base environment will automatically show the kernel from any other environment which has ipykernel installed. We only need one jupyter notebook, ideally inst... | [
0
] | [] | [] | [
"conda",
"jupyter_notebook",
"python"
] | stackoverflow_0074611535_conda_jupyter_notebook_python.txt |
Q:
Change a url parameter
How change a parameter's value of url? Without regexps.
Now I try this, but it's long:
from urllib.parse import parse_qs, urlencode, urlsplit
url = 'http://example.com/?page=1&text=test#section'
param, newvalue = 'page', '2'
url, sharp, frag = url.partition('#')
base, q, query = url.parti... | Change a url parameter | How change a parameter's value of url? Without regexps.
Now I try this, but it's long:
from urllib.parse import parse_qs, urlencode, urlsplit
url = 'http://example.com/?page=1&text=test#section'
param, newvalue = 'page', '2'
url, sharp, frag = url.partition('#')
base, q, query = url.partition('?')
query_dict = parse... | [
"Tuples are immutable.So you have to replace it .Here _ is meant to avoid conflict with fieldnames ._replace\nfrom urllib.parse import parse_qs, urlencode, urlsplit\nurl = 'http://example.com/?page=1&text=test#section'\nparam, newvalue = 'page', '2'\nparsed = urlsplit(url)\nquery_dict = parse_qs(parsed.query)\nque... | [
9,
6,
0
] | [] | [] | [
"python",
"url",
"urllib"
] | stackoverflow_0050893347_python_url_urllib.txt |
Q:
pandas vs. datetime: calculating time deltas between timezone-aware datetimes
On the one hand, for performance requirements, I'm using pandas to compute time difference between 2 timezone-aware datetimes, that is to say between 2 timezone-aware pandas.Timestamp objects.
On the other hand, for testing purposes (mai... | pandas vs. datetime: calculating time deltas between timezone-aware datetimes | On the one hand, for performance requirements, I'm using pandas to compute time difference between 2 timezone-aware datetimes, that is to say between 2 timezone-aware pandas.Timestamp objects.
On the other hand, for testing purposes (mainly), I'm using exclusively the Python datetime module. The idea was to achieve the... | [
"# you can try some thing like \ndate=datetime.datetime(2023, 3, 1, 0, 0,)\ntimestamp = pd.Timestamp(date, tz='Europe/Paris') #Convert timezone of timestamp.\nprint(timestamp)\n\nafter looking into p1 and p2 and trying to find the difference i found out this :\nprint(p1,p2)\nprint(d1,d2)\nprint(p2.astimezone(utc))\... | [
0
] | [] | [] | [
"datetime",
"pandas",
"python",
"python_datetime",
"timezone"
] | stackoverflow_0074617029_datetime_pandas_python_python_datetime_timezone.txt |
Q:
Clear slash command in discord.py
At the beginning I would like to point out that I do not use the py-cord module only and only discord.py. I wanted to create a / clear command.The problem is when the application that has to return the feedback that successfully deleted n messages from the user xyz.
There is an er... | Clear slash command in discord.py | At the beginning I would like to point out that I do not use the py-cord module only and only discord.py. I wanted to create a / clear command.The problem is when the application that has to return the feedback that successfully deleted n messages from the user xyz.
There is an error mentioning
"await interaction.resp... | [
"Use this. I hope that I can help you with it.\nclient = MyClient(intents=intents)\nt = app_commands.CommandTree(client)\n\n@t.command(name=\"clear\", description=\"Clear n messages specific user\", guild=discord.Object(id=867851000286806016))\nasync def self(ctx, interaction: discord.Interaction, amount: int, memb... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0073629825_discord.py_python.txt |
Q:
how to submit button click by text link
I am trying submit form using selenium, but submit button isn't working , How can I submit button through driver.find_element_by_xpath('//button\[@type="submit"\]').click() this isn't working for me.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdr... | how to submit button click by text link | I am trying submit form using selenium, but submit button isn't working , How can I submit button through driver.find_element_by_xpath('//button\[@type="submit"\]').click() this isn't working for me.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdri... | [
"\nI guess you are using Selenium 4. If so find_element_by_* are no more supported there. You need to use the modern syntax of driver.find_element(By. as folllowing.\nYou need to introduce WebDriverWait expected_conditions to wait for element to become clickable.\n\nThe following code works\nfrom selenium import we... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium4",
"webdriverwait"
] | stackoverflow_0074617483_python_selenium_selenium4_webdriverwait.txt |
Q:
How to print my class and not get memory reference
I have a class called Pension, with attributes like a person's name, age, savings and a growth rate.
I have a class method which calculates the person's total savings at retirement year.
Under my main function, I want to print the class to see if my code is workin... | How to print my class and not get memory reference | I have a class called Pension, with attributes like a person's name, age, savings and a growth rate.
I have a class method which calculates the person's total savings at retirement year.
Under my main function, I want to print the class to see if my code is working as intended, but I don't know how to do as I only get ... | [
"From the Pension class object's perspective it doesn't actually matter how is the growth provided. Also in this case maybe it's worth to make the result a property, then there's no need to call it as a function (just access like any other property, but the values will be calculated \"dynamically\").\nYou can custo... | [
0
] | [] | [] | [
"class",
"methods",
"printing",
"python"
] | stackoverflow_0074617432_class_methods_printing_python.txt |
Q:
Fastest possible optimisation of an area difference with a constrained sum
I have four arrays, a1,a2,a3,a4, each of length 500. I have a target array at, also of length 500. These arrays each represent the y coordinates of unevenly spaced points on a graph. I have the x coordinates in a separate array.
I want to o... | Fastest possible optimisation of an area difference with a constrained sum | I have four arrays, a1,a2,a3,a4, each of length 500. I have a target array at, also of length 500. These arrays each represent the y coordinates of unevenly spaced points on a graph. I have the x coordinates in a separate array.
I want to optimise the coefficients c1,c2,c3,c4 such that the area difference between c1x1 ... | [
"This isn't a full solution, more like some thoughts that may lead to one. Also, someone please double-check my math.\nVariables and test data\nFirst, let's begin by defining some test data. While doing so, I transpose the a1a2a3a4 matrix because it will prove more conventient. Plus, I'm renaming it to a14 because ... | [
2
] | [] | [] | [
"optimization",
"performance",
"python",
"scipy",
"scipy_optimize"
] | stackoverflow_0074613758_optimization_performance_python_scipy_scipy_optimize.txt |
Q:
Find closest point in Pandas DataFrames
I am quite new to Python. I have the following table in Postgres. These are Polygon values with four coordinates with same Id with ZONE name I have stored this data in Python dataframe called df1
Id Order Lat Lon Zone
00001 1 50.6373473 3.0750... | Find closest point in Pandas DataFrames | I am quite new to Python. I have the following table in Postgres. These are Polygon values with four coordinates with same Id with ZONE name I have stored this data in Python dataframe called df1
Id Order Lat Lon Zone
00001 1 50.6373473 3.075029928 A
00001 2 50.63740441 3.07... | [
"This sounds like a good use case for scipy cdist, also discussed here.\nimport pandas as pd\nfrom scipy.spatial.distance import cdist\n\n\ndata1 = {'Lat': pd.Series([50.6373473,50.63740441,50.63744285,50.63737839,50.6376054,50.6375896,50.6374239,50.6374404]),\n 'Lon': pd.Series([3.075029928,3.075068636,3.0... | [
14,
0
] | [] | [] | [
"pandas",
"postgresql",
"python"
] | stackoverflow_0038965720_pandas_postgresql_python.txt |
Q:
how to save a pandas DataFrame to an excel file?
I am trying to load data from the web source and save it as a Excel file but not sure how to do it. What should I do?
import requests
import pandas as pd
import xmltodict
url = "https://www.kstan.ua/sitemap.xml"
res = requests.get(url)
raw = xmltodict.parse(res.tex... | how to save a pandas DataFrame to an excel file? | I am trying to load data from the web source and save it as a Excel file but not sure how to do it. What should I do?
import requests
import pandas as pd
import xmltodict
url = "https://www.kstan.ua/sitemap.xml"
res = requests.get(url)
raw = xmltodict.parse(res.text)
data = [[r["loc"], r["lastmod"]] for r in raw["ur... | [
"df.to_csv(\"output.csv\", index=False)\n\nOR\ndf.to_excel(\"output.xlsx\")\n\n",
"You can write the dataframe to excel using the pandas ExcelWriter, such as this:\nimport pandas as pd\nwith pd.ExcelWriter('path_to_file.xlsx') as writer:\n dataframe.to_excel(writer)\n\n",
"If you want to create multiple shee... | [
21,
3,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0055170300_pandas_python.txt |
Q:
error:'_UserObject' object has no attribute 'predict'
I am building an ANN model for machine learning against a data train. when I call the model to validate the test data, an error occurs
model = Sequential()
model.add(Dense(8,activation='tanh',input_dim = 10))
model.add(Dense(6,activation='tanh'))
model.add(De... | error:'_UserObject' object has no attribute 'predict' | I am building an ANN model for machine learning against a data train. when I call the model to validate the test data, an error occurs
model = Sequential()
model.add(Dense(8,activation='tanh',input_dim = 10))
model.add(Dense(6,activation='tanh'))
model.add(Dense(4,activation='softmax'))
model.summary()
from tensorf... | [
"I solved this issue by using the older keras h5 format:\nh5-format\nSimply load and save the model with the .h5 extension:\nmodel.save('model_name.h5')\nloaded_model = keras.model.load_model('model_name.h5')\n\n",
"For me this happened when I trained a network on computer1 and tried to predict using it on comput... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0068173923_python.txt |
Q:
Pandas lambda function syntax error (with dictionary)
I use lambda functions in Python a lot. All of a sudden, I cannot figure out why is there a syntax error message for this:
table['sp1 name'] = table['sp1'].apply(lambda x: sp1_new_dict[x] if x in sp1_new_dict.keys())
Any ideas?
Thanks!
A:
You need an else. B... | Pandas lambda function syntax error (with dictionary) | I use lambda functions in Python a lot. All of a sudden, I cannot figure out why is there a syntax error message for this:
table['sp1 name'] = table['sp1'].apply(lambda x: sp1_new_dict[x] if x in sp1_new_dict.keys())
Any ideas?
Thanks!
| [
"You need an else. Boiling down your error:\nx = 1 if True\n\n File \"<stdin>\", line 1\n x = 1 if True\n ^\nSyntaxError: invalid syntax\n\n\n# No error here\nx = 1 if True else 2\n\nSince you are using a dictionary, maybe use dict.get:\ntable['sp1 name'] = table['sp1'].apply(lambda x: sp1_new_d... | [
2
] | [] | [] | [
"dictionary",
"lambda",
"pandas",
"python"
] | stackoverflow_0074617658_dictionary_lambda_pandas_python.txt |
Q:
How do add an assembled field to a Pydantic model
Say I have model
class UserDB(BaseModel):
first_name: Optional[str] = None
last_name: Optional[str] = None
How do I make another model that is constructed from this one and has a field that changes based on the fields in this model?
For instance, something... | How do add an assembled field to a Pydantic model | Say I have model
class UserDB(BaseModel):
first_name: Optional[str] = None
last_name: Optional[str] = None
How do I make another model that is constructed from this one and has a field that changes based on the fields in this model?
For instance, something like this
class User(BaseModel):
full_name: str = ... | [
"If you do not want to keep first_name and last_name in User then you can\n\ncustomize __init__.\nuse validator for setting full_name.\n\nBoth methods do what you want:\nfrom typing import Optional\nfrom pydantic import BaseModel, validator\n\n\nclass UserDB(BaseModel):\n first_name: Optional[str] = None\n la... | [
16,
0
] | [] | [] | [
"fastapi",
"pydantic",
"python"
] | stackoverflow_0063492123_fastapi_pydantic_python.txt |
Q:
Changing the format of a column of data in a Pandas Series
I would like to change the format of the returned dates from this:
listOfDates = df2['TradeDate'].drop_duplicates().reset_index(drop=True)
print(listOfDates)
0 2022-02-02
1 2022-02-08
2 2022-05-01
3 2022-05-06
4 2022-06-05
5 2022-06-17
6 202... | Changing the format of a column of data in a Pandas Series | I would like to change the format of the returned dates from this:
listOfDates = df2['TradeDate'].drop_duplicates().reset_index(drop=True)
print(listOfDates)
0 2022-02-02
1 2022-02-08
2 2022-05-01
3 2022-05-06
4 2022-06-05
5 2022-06-17
6 2022-07-30
7 2022-08-03
8 2022-10-10
9 2022-11-18
Name: Trade... | [
"You need to use the datetime accessor dt like this:\nlistOfDates = df2['TradeDate'].drop_duplicates().reset_index(drop=True).dt.strftime(\"%Y%m%d\")\n\nDocumented here\n"
] | [
1
] | [] | [] | [
"pandas",
"python",
"series"
] | stackoverflow_0074617681_pandas_python_series.txt |
Q:
Create a custom column in a dict format
I currently have a dataframe like this
Person
Analysis
Dexterity
Skills
174
3.76
4.12
1.20
239
4.10
3.78
3.77
557
5.00
2.00
4.40
674
2.23
2.40
2.80
122
3.33
4.80
4.10
I want to add an column to compile all this information like below
Person
Analysis
Dexterity
Skills
... | Create a custom column in a dict format | I currently have a dataframe like this
Person
Analysis
Dexterity
Skills
174
3.76
4.12
1.20
239
4.10
3.78
3.77
557
5.00
2.00
4.40
674
2.23
2.40
2.80
122
3.33
4.80
4.10
I want to add an column to compile all this information like below
Person
Analysis
Dexterity
Skills
new_column
174
3.76
4.12
... | [
"You can use to to_dict method like so:\nimport pandas as pd\n\nrows = [\n {'a': 1, 'b': 2},\n {'a': 3, 'b': 4},\n]\n\ndf = pd.DataFrame(rows)\n\n# define new column as the json format of another\n# also convert to str as that is what you have in your output\ndf['c'] = df[['a', 'b']].astype(str).to_dict(orien... | [
4
] | [] | [] | [
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074617602_data_science_dataframe_pandas_python.txt |
Q:
How do you shuffle functions using python to then call the shuffled result?
I am trying to make functions which would print separate questions. I then want the functions to be put into a list and shuffled with the shuffled functions being called in their shuffled order.
I tried to change the functions into variabl... | How do you shuffle functions using python to then call the shuffled result? | I am trying to make functions which would print separate questions. I then want the functions to be put into a list and shuffled with the shuffled functions being called in their shuffled order.
I tried to change the functions into variables and then put the variables in a list. I then tried to use random.shuffle()
to ... | [
"You have to actually call the functions. Further, you don't want to return until you actually call all three. You also don't need any additional variables; Question1 is already a variable that refers to the function originally bound to it.\ndef questionfunction():\n questionlist = [Question1, Question2, Questio... | [
0
] | [] | [] | [
"python",
"python_3.x",
"random"
] | stackoverflow_0074617688_python_python_3.x_random.txt |
Q:
Removing charaters from string in a list of list
I have a list, lst =[['ABC, CN', 'X'], ['DCS, BA', 'X'], ['SCS, TW', 'X'], ['SFA, GW', 'X']]. Want to remove the last 4 charaters in the in the first part of ever string? Is this possible?
Wanted outcome would be:
newlist = [['ABC', 'X'], ['DCS', 'X'], ['SCS', 'X']... | Removing charaters from string in a list of list | I have a list, lst =[['ABC, CN', 'X'], ['DCS, BA', 'X'], ['SCS, TW', 'X'], ['SFA, GW', 'X']]. Want to remove the last 4 charaters in the in the first part of ever string? Is this possible?
Wanted outcome would be:
newlist = [['ABC', 'X'], ['DCS', 'X'], ['SCS', 'X'], ['SFA', 'X']]
I've tried:
newlist= [sub[:][: -1] for... | [
"You can use unpacking when iterate over elements of the list.\n>>> [[a[:-4], b] for (a, b) in lst]\n[['ABC', 'X'], ['DCS', 'X'], ['SCS', 'X'], ['SFA', 'X']]\n\n"
] | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074617685_list_python.txt |
Q:
How to write uwsgi ini file equivalent to a uwsgi command
I am testing an application in uWsgi server using the command,
uwsgi --http :9090 --wsgi-file myapp.py --callable app --processes 4 --threads 2 --stats 127.0.0.1:9191
That starts the application on 9090 port. I want to write a .ini file for this. But I am ... | How to write uwsgi ini file equivalent to a uwsgi command | I am testing an application in uWsgi server using the command,
uwsgi --http :9090 --wsgi-file myapp.py --callable app --processes 4 --threads 2 --stats 127.0.0.1:9191
That starts the application on 9090 port. I want to write a .ini file for this. But I am stuck with --http :9090 part. How it will be written in the ini... | [
"Configuration directives and command line options are managed by the same parser: https://uwsgi-docs.readthedocs.org/en/latest/Configuration.html\nIn the case of the ini format you only need to remove the double dashes before the option.\n",
"uwisgi.ini \nstats = :1717 --stats-http\n\nDocumentation: http://uwsgi... | [
4,
4,
0
] | [] | [] | [
"ini",
"python",
"uwsgi"
] | stackoverflow_0026302562_ini_python_uwsgi.txt |
Q:
How to remove the UnboundLocalError in Python while calculating profit from the values given in a dictionary?
I have a dictionary dt which consists of cost price, selling price and the inventory. The purpose of the code is to calculate the Profit. Profit and can be calculated by
Profit = Total selling price - Tota... | How to remove the UnboundLocalError in Python while calculating profit from the values given in a dictionary? | I have a dictionary dt which consists of cost price, selling price and the inventory. The purpose of the code is to calculate the Profit. Profit and can be calculated by
Profit = Total selling price - Total Cost price. For example following is the input
profit({
"cost_price": 32.67,
"sell_price": 45.00,
"inventory": 12... | [
"When extracting values from the dictionary you need to validate their existence. You may even want to check the data type(s).\nThere is no need for global variables in this case.\nThe main method might as well be static as it does not depend upon any other attributes of the Solution class.\nSomething like this wil... | [
0,
0
] | [] | [] | [
"dictionary",
"global_variables",
"python"
] | stackoverflow_0074617610_dictionary_global_variables_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.