content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python: How to replace letters in string using lists?
Basically, I'm creating a really low tier cipher. I've set up a bit of code to randomize each character, but I can't figure out how to replace a string with these. This is the code I attempted
characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",... | Python: How to replace letters in string using lists? | Basically, I'm creating a really low tier cipher. I've set up a bit of code to randomize each character, but I can't figure out how to replace a string with these. This is the code I attempted
characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w"... | [
"Welcome to SO. For these type of problems, it's probably smarter to build a new string and enter in the appropriate character based on its value in the original string. I would also highly consider using a dictionary that maps old_character --> new_character\ncharacter_mapping = {\"a\": \"h\", \"b\": \"i\" , ...} ... | [
1,
0,
0
] | [] | [] | [
"list",
"python",
"replace",
"string"
] | stackoverflow_0074490088_list_python_replace_string.txt |
Q:
pymodbus TcpClient timeout
I have problem with pymodbus TcpClient timeout:
import logging
from pymodbus.client.sync import ModbusTcpClient
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
client = ModbusTcpClient('x.y.z.w', port=yyy)
client.connect()
result = client.read_holding_regis... | pymodbus TcpClient timeout | I have problem with pymodbus TcpClient timeout:
import logging
from pymodbus.client.sync import ModbusTcpClient
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
client = ModbusTcpClient('x.y.z.w', port=yyy)
client.connect()
result = client.read_holding_registers(10, 10)
print(result.regist... | [
"from pymodbus.constants import Defaults\n\nDefaults.Timeout = 10\nclient = ModbusTcpClient('x.y.z.w', port=yyy)\nclient.connect()\n\nModbusTcpClient class doesn't have any argument in it's constructor or specific method to pass the timeout to the class. Instead, one can change the timeout of the class by globally ... | [
4,
2,
0
] | [] | [] | [
"connection_timeout",
"modbus",
"python"
] | stackoverflow_0023887184_connection_timeout_modbus_python.txt |
Q:
Reached error page: The server at x is taking too long to respond
I want to deploy my application on Heroku. My application scrapes data of an apartment website. For one url, I have multiple selectors. The application is ran using APSceduler. Logs are showing the following error:
2020-08-10T11:02:56.259319+00:00 a... | Reached error page: The server at x is taking too long to respond | I want to deploy my application on Heroku. My application scrapes data of an apartment website. For one url, I have multiple selectors. The application is ran using APSceduler. Logs are showing the following error:
2020-08-10T11:02:56.259319+00:00 app[clock.1]: Running main
2020-08-10T11:04:34.374167+00:00 app[clock.1]... | [
"As it turned out, the target website was blocking Heroku. Solution is to use proxy\n",
"I think that you want to wait until the element you are looking for waits:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.co... | [
1,
0,
0
] | [] | [] | [
"heroku",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0063340736_heroku_python_selenium_selenium_webdriver.txt |
Q:
Using pandas TimeStamp with scikit-learn
sklearn classifiers accept pandas' TimeStamp (=datetime64[ns]) as a column in X, as long as all of X columns are of that type. But when there are both TimeStamp and float columns, sklearn refuses to work with TimeStamp.
Is there any workaround besides converting TimeStamp i... | Using pandas TimeStamp with scikit-learn | sklearn classifiers accept pandas' TimeStamp (=datetime64[ns]) as a column in X, as long as all of X columns are of that type. But when there are both TimeStamp and float columns, sklearn refuses to work with TimeStamp.
Is there any workaround besides converting TimeStamp into int using astype(int)? (I still need the o... | [
"You can translate it to a proper integer or float\ntest_df['date'] = test_df['date'].astype(int)\n\n",
"you want to fit on X and y, where X are features (2 or more) and y is a target. use your datetimeindex as a time series, not a feature. In my example, I fit earthquakes with mag > 7 and calculate the elapsed ... | [
1,
0,
0
] | [] | [] | [
"datetime",
"pandas",
"python",
"python_3.x",
"scikit_learn"
] | stackoverflow_0035439723_datetime_pandas_python_python_3.x_scikit_learn.txt |
Q:
Python requests headers not being set properly
I'm having some trouble using Python requests. Here's my code:
fields={
"fields":{
"field1":{"test": "test"},
"field2": "test",
"field3":{"test": "test"}
}
}
try:
results = requests.post(
"http://www.fakenotrealatall.com",
... | Python requests headers not being set properly | I'm having some trouble using Python requests. Here's my code:
fields={
"fields":{
"field1":{"test": "test"},
"field2": "test",
"field3":{"test": "test"}
}
}
try:
results = requests.post(
"http://www.fakenotrealatall.com",
data=json.dumps(fields),
headers={"c... | [
"You got a 415 error because the server at \"http://www.fakenotrealatall.com\" returned a 415 error. According to the HTTP standard, that means \n\n\nThe server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.\n\n\n... | [
3,
0
] | [] | [] | [
"header",
"python",
"python_requests"
] | stackoverflow_0036180901_header_python_python_requests.txt |
Q:
Download files from a site with requests by clicking the button
I'm trying to download download a zip file from this site:
https://resultados.tse.jus.br/oficial/app/index.html#/eleicao/dados-de-urna;e=e545;uf=mg;ufbu=mg;mubu=40037;zn=0001;se=0101/log-da-urna
After clicking the button "download *.zip file" the down... | Download files from a site with requests by clicking the button | I'm trying to download download a zip file from this site:
https://resultados.tse.jus.br/oficial/app/index.html#/eleicao/dados-de-urna;e=e545;uf=mg;ufbu=mg;mubu=40037;zn=0001;se=0101/log-da-urna
After clicking the button "download *.zip file" the download is performed.
I'm trying to do this with the resquest because th... | [
"I'm not sure what you mean by\n\nchange \"zn\" and \"se\" in the url\n\nbut you might want to try this:\nimport os\nimport time\nimport urllib.parse\nfrom pathlib import Path\nfrom shutil import copyfileobj\n\nimport requests\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:10... | [
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests"
] | stackoverflow_0074332212_beautifulsoup_python_python_requests.txt |
Q:
While loop for excel parsing
error message screenshotI'm quite new to Python and I need to create a nested loop for excel parsing. I have a spreadsheet with 4 columns ID, Model, Part Number, Part Description, Year and I need a parser to go through each line and to return in format:
Part Number, Toyota > Model > Ye... | While loop for excel parsing | error message screenshotI'm quite new to Python and I need to create a nested loop for excel parsing. I have a spreadsheet with 4 columns ID, Model, Part Number, Part Description, Year and I need a parser to go through each line and to return in format:
Part Number, Toyota > Model > Year | Toyota > Model > Year etc...
... | [
"Your code gets stuck in an infinite loop, because you do not update the value c as you iterate through the rows. Here's how you could implement this better:\npart_number_group = None\nfor i in range(len(df)): # or `for i, row in df.iterrows():`\n part_number = df.loc[i, \"Part Number\"]\n if part_number != ... | [
1,
0
] | [] | [] | [
"pandas",
"parsing",
"python"
] | stackoverflow_0074489407_pandas_parsing_python.txt |
Q:
Power BI Python visual doesn't plot all available datapoints
I am getting a strange result in Power BI python visual. I am working with the diamonds dataset (sns.load_dataset('diamonds')). I have this code in the python visual editor:
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(dataset['car... | Power BI Python visual doesn't plot all available datapoints | I am getting a strange result in Power BI python visual. I am working with the diamonds dataset (sns.load_dataset('diamonds')). I have this code in the python visual editor:
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(dataset['carat'], bins = 50)
plt.show()
I am however getting this visual (tru... | [
"The Python visual gives you a warning that it will drop duplicates and also supplies the formula it will use for the dataframe you will actually base your plot on:\n\nBy adding an index column in Power Query prior to loading the data, and adding both the (non-summarized) index column and the carat column to the vi... | [
1
] | [] | [] | [
"powerbi",
"python"
] | stackoverflow_0074490261_powerbi_python.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'storid'
I am really new with ontologies especially with owlready2. I loaded an Ontology the basic example Pizza and imported I think successfully on python (I checked whether I can see the classes which I can so..)
Than I used the following code to search one cla... | AttributeError: 'NoneType' object has no attribute 'storid' | I am really new with ontologies especially with owlready2. I loaded an Ontology the basic example Pizza and imported I think successfully on python (I checked whether I can see the classes which I can so..)
Than I used the following code to search one class specifically with the method search():
from owlready2 import *... | [
"Problem solved itself, the example owl File had errors with IRI that caused a Problem with the search\n"
] | [
0
] | [] | [] | [
"owl",
"owlready",
"python"
] | stackoverflow_0074490031_owl_owlready_python.txt |
Q:
RHEL 8 - Unable to complete pyPDF2 offline installation due to typing_extensions
I've been stuck with this problem.
I work on a UNIX RHEL8 server which did not allow to access internet.
All required packages and modules I able to install expect this pyPDF2 module due to typing_extensions
RHEL8 Python 3.6.8
Pip 9.... | RHEL 8 - Unable to complete pyPDF2 offline installation due to typing_extensions | I've been stuck with this problem.
I work on a UNIX RHEL8 server which did not allow to access internet.
All required packages and modules I able to install expect this pyPDF2 module due to typing_extensions
RHEL8 Python 3.6.8
Pip 9.0.3 installed but not able to use due to no internet access
PyPDF2 2.10.0 try to insta... | [
"You need to install the package:\npip install typing-extensions\n\nIn newer Python versions that package is not required.\nYou can also edit the source of PyPDF2 to remove all imports of it and Literal.\n",
"You can download whl file from https://pypi.org/ for the package.\nAnd if pip is installed it can be easi... | [
0,
0
] | [] | [] | [
"offline",
"pypdf2",
"python",
"rhel8",
"unix"
] | stackoverflow_0073325743_offline_pypdf2_python_rhel8_unix.txt |
Q:
How do i recongize artifacts and holes using OpenCV in a image?
I need help with OpenCV
I have a picture with a complex for lying on the ground now i need to extract this form from the picture and cleaned it from noise. But now there is a logo which i need to remove and 4 holes to identify.What i could do Original... | How do i recongize artifacts and holes using OpenCV in a image? | I need help with OpenCV
I have a picture with a complex for lying on the ground now i need to extract this form from the picture and cleaned it from noise. But now there is a logo which i need to remove and 4 holes to identify.What i could do Original image
My code so far:
import cv2
import numpy as np
# Read the ori... | [
"Having a shot at this in ImageJ, extracting the red channel from the raw image gives me this:\n\nWhich is close to a binary image already. Running a small (3pix) median filter and thresholding gives this as a binary:\n\nRunning cv.findContours() on that last one and analysing contour areas should give you the litt... | [
1
] | [] | [] | [
"image",
"image_processing",
"opencv",
"python"
] | stackoverflow_0074489172_image_image_processing_opencv_python.txt |
Q:
Cogs Not Working In Discord.py And commands also not working
I've created a discord bot using python but cogs are not working in my bot Please Tell Me Is There Any Mistake in this code
import discord
from discord.ext import commands
import os
from help_cog import help_cog
from music_cog import music_cog
inten... | Cogs Not Working In Discord.py And commands also not working | I've created a discord bot using python but cogs are not working in my bot Please Tell Me Is There Any Mistake in this code
import discord
from discord.ext import commands
import os
from help_cog import help_cog
from music_cog import music_cog
intents = discord.Intents.default()
intents.message_content = True
bo... | [
"You're never calling that load_extensions function, so you're not loading your cogs. It's good that you made it, but you aren't using it.\nDiscord.py can't smell that it's supposed to call that function, nor that it's supposed to load your cog...\n"
] | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074489122_discord.py_python.txt |
Q:
Combine mutiple variables within netCDF file
Apologies if this is a basic question, I'm new to these tools.
I have a netcdf file with with eight variables containing data from the same source, but in different time periods. There is no overlap between the variables across the time dimension. How do I combine all 8... | Combine mutiple variables within netCDF file | Apologies if this is a basic question, I'm new to these tools.
I have a netcdf file with with eight variables containing data from the same source, but in different time periods. There is no overlap between the variables across the time dimension. How do I combine all 8 variables into one "CHIRPS_p_d" variable that doe... | [
"You can replace NaN values by 0 and then add all CHIRPS_p_d variables. Since there is only one CHIRPS_p_d having a non-NaN value by time step this should do the trick:\nds.fillna(0.0)\nresult = ds[\"CHIRPS_p_d1\"] + ... + ds[\"CHIRPS_p_d8\"]\n\n"
] | [
0
] | [] | [] | [
"netcdf",
"netcdf4",
"python",
"python_xarray"
] | stackoverflow_0074489336_netcdf_netcdf4_python_python_xarray.txt |
Q:
Python printing tabular data
Hell All,
I have been trying to print tabular data from two dimensional list
numerical are right aligned, strings are left aligned and width of a column is dynamically decided based on max string length in each column
Example-A:
table = [['Name', 'Marks', 'Division', 'ID'], ['Raj', 7, ... | Python printing tabular data | Hell All,
I have been trying to print tabular data from two dimensional list
numerical are right aligned, strings are left aligned and width of a column is dynamically decided based on max string length in each column
Example-A:
table = [['Name', 'Marks', 'Division', 'ID'], ['Raj', 7, 'A', 21], ['Shivam', 9, 'A', 52], ... | [
"You could try something like the following:\ncols = []\nfor col in zip(*table):\n just = str.ljust if isinstance(col[1], str) else str.rjust\n strings = [str(item) for item in col]\n width = max(map(len, strings))\n cols.append(\n [strings[0].ljust(width), (len(strings[0]) * \"-\").ljust(width)]... | [
1,
0
] | [] | [] | [
"alignment",
"f_string",
"printing",
"python"
] | stackoverflow_0074489186_alignment_f_string_printing_python.txt |
Q:
How to provide encoded json data to resources in cdktf for grafana
I appear to be an early adopter of cdktf for grafana using python.
The following config is successfully transmitted and accepted by grafana
DataSource(self, "xxx",
uid = "datasource_influxdb",
type = "influxdb",
name = "...",
ur... | How to provide encoded json data to resources in cdktf for grafana | I appear to be an early adopter of cdktf for grafana using python.
The following config is successfully transmitted and accepted by grafana
DataSource(self, "xxx",
uid = "datasource_influxdb",
type = "influxdb",
name = "...",
url = "...",
json_data= [DataSourceJsonData(
default_bucket ... | [
"The solution is simple python json encoding using json.dumps(dict())\n DataSource(self, \"xxx\",\n uid = \"datasource_influxdb\",\n type = \"influxdb\",\n name = \"xxx\",\n url = \"xxx\n json_data_encoded = json.dumps(\n dict(defaultBucket = \"xxx\",\n httpMode = \"POST\",... | [
0
] | [] | [] | [
"grafana",
"python",
"terraform_cdk"
] | stackoverflow_0074490011_grafana_python_terraform_cdk.txt |
Q:
kivymd, creating a splash loading page as animation I couldn't code it instead I use Gif not working why?
Hello Guys i create a page using kivymd using an gif because i couldn't code it so i make a video for it than i convert it to gif.
the point is the code doesn't work and the error wasn't clear any help please
... | kivymd, creating a splash loading page as animation I couldn't code it instead I use Gif not working why? | Hello Guys i create a page using kivymd using an gif because i couldn't code it so i make a video for it than i convert it to gif.
the point is the code doesn't work and the error wasn't clear any help please
this the code of the splashloading.kv
MDFloatLayout:
md_bg_color:1,1,1,1
md_bg_color: (255/255, 250/255... | [
"I am not sure about the gif, but I can give you code for a video player that has worked fairly smoothly in some of my projects.\nNeed to create a Video player class which can then be used in the .kv file\nIn .kv file\n# This is only the code for the widget, the structure around it is not included\nPlayerOpen:\n ... | [
0
] | [] | [] | [
"gif",
"kivy",
"kivy_language",
"kivymd",
"python"
] | stackoverflow_0074490479_gif_kivy_kivy_language_kivymd_python.txt |
Q:
Explode dates and backfill rows in pyspark dataframe
I have this dataframe:
+---+----------+------+
| id| date|amount|
+---+----------+------+
|123|2022-11-11|100.00|
|123|2022-11-12|100.00|
|123|2022-11-13|100.00|
|123|2022-11-14|200.00|
|456|2022-11-14|300.00|
|456|2022-11-15|300.00|
|456|2022-11-16|300.00|... | Explode dates and backfill rows in pyspark dataframe | I have this dataframe:
+---+----------+------+
| id| date|amount|
+---+----------+------+
|123|2022-11-11|100.00|
|123|2022-11-12|100.00|
|123|2022-11-13|100.00|
|123|2022-11-14|200.00|
|456|2022-11-14|300.00|
|456|2022-11-15|300.00|
|456|2022-11-16|300.00|
|789|2022-11-11|400.00|
|789|2022-11-12|500.00|
+---+----... | [
"I managed to find the following solution.\nFor clarification purposes I divided it in three steps; of course you can write fewer lines of code if you make them more compact.\n1) Lookup\nCreate a lookup table with all the necessary dates (both present and not) for each id.\nimport pyspark.sql.functions as F\nfrom p... | [
1
] | [] | [] | [
"apache_spark_sql",
"dataframe",
"pyspark",
"python",
"sequence"
] | stackoverflow_0074489283_apache_spark_sql_dataframe_pyspark_python_sequence.txt |
Q:
How can I find a DIV with a sibling with a specific text and print it Selenium Python?
I want to fetch text from a div, but there are allot of duplicated classes. The only way to filter my search is by checking for a specific text within a sibling. Right now this is what I got:
accountmanager = ()
def send_keys_in... | How can I find a DIV with a sibling with a specific text and print it Selenium Python? | I want to fetch text from a div, but there are allot of duplicated classes. The only way to filter my search is by checking for a specific text within a sibling. Right now this is what I got:
accountmanager = ()
def send_keys_in_loop_dropaccountmanager(locator):
for i in range(5):
try:
global ac... | [
"Try the following xpath -\n//div[text()='Peter Hendrik'][@class='ahoy-value']\n\nEdit: If you want to go through the Accountmanager text, you can use the following xpath -\n//div[text()='Accountmanager'][@class='ahoy-label']/following-sibling::div[@class='ahoy-value']\n\n",
"I figured it out, by removing the loo... | [
1,
1,
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074489979_python_selenium_selenium_webdriver_xpath.txt |
Q:
Python: Remove intersecting line segments from graph until only the shortest of intersecting lines remains (remove dict from list of dicts)
Starting with the graph on the left, I would like to compare all of the lines, and anywhere they intersect (not counting the corners), keep only the shortest of the intersecti... | Python: Remove intersecting line segments from graph until only the shortest of intersecting lines remains (remove dict from list of dicts) |
Starting with the graph on the left, I would like to compare all of the lines, and anywhere they intersect (not counting the corners), keep only the shortest of the intersecting lines. I have the data on the lines stored as a list of dictionaries (in descending order of line length), but I can change the data structur... | [
"\nSort the lines in order of length.\n\nFor each line:\na. Check if the line intersects with any shorter lines (note: it will never\nintersect with any adjacent lines).\nb. If it does, remove it.\n\nRepeat #2 for the next longest line.\n\n\nNote: your intersection algorithm will return that lines intersect if they... | [
0
] | [] | [] | [
"dictionary",
"graph",
"planar_graph",
"python"
] | stackoverflow_0074468476_dictionary_graph_planar_graph_python.txt |
Q:
Panda dataframe percentage clustering
for example I have this data frame
count
A 20
B 20
C 15
D 10
E 10
F 8
G 7
H 5
I 5
and if I want to cut it into several group (biggest 75%, 15%, and last 10%) it would be
count Class
A 20 Top1
B 20 Top1
C 15 Top1
D 10 Top1
E ... | Panda dataframe percentage clustering | for example I have this data frame
count
A 20
B 20
C 15
D 10
E 10
F 8
G 7
H 5
I 5
and if I want to cut it into several group (biggest 75%, 15%, and last 10%) it would be
count Class
A 20 Top1
B 20 Top1
C 15 Top1
D 10 Top1
E 10 Top1
F 8 Top2
G 7... | [
"In theory, you can use qcut:\ndf['Class'] = pd.qcut(df['count'], q=[0, 0.1, 0.15, 1],\n labels=['Top3', 'Top2', 'Top1'])\n\nOutput (note the slightly different example):\n count Class\nA 20 Top1\nB 20 Top1\nC 15 Top1\nD 10 Top1\nE 10 Top1\nF 8 Top1\nG 7 T... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074490435_dataframe_pandas_python.txt |
Q:
Count grid points with same sign across multiple xarray.DataArrays
I have the following three DataArrays each holding the correlation value at grid points across Africa (see ds1, ds2, ds3 below):
<xarray.DataArray (lat: 80, lon: 80)>
array([[ nan, nan, nan, ..., nan, nan,
... | Count grid points with same sign across multiple xarray.DataArrays | I have the following three DataArrays each holding the correlation value at grid points across Africa (see ds1, ds2, ds3 below):
<xarray.DataArray (lat: 80, lon: 80)>
array([[ nan, nan, nan, ..., nan, nan,
nan],
[ nan, nan, nan, ..., nan... | [
"If your DataArrays cover the same grid, you can just combine them to a dataset and compute the occurrences.\nimport xarray as xr\n\n# testdata\nxx = xr.tutorial.load_dataset(\"rasm\").Tair\n\n# list of data arrays with same grid\ndarrs = [xx.to_dataset(name=x) for x in (\"ds1\", \"ds2\", \"ds3\")]\n\nxx_combined ... | [
0
] | [] | [] | [
"netcdf",
"python",
"python_xarray"
] | stackoverflow_0074486411_netcdf_python_python_xarray.txt |
Q:
Aggregate and create a new Pandas DataFrame based on date index
I have a DataFrame that has two columns with index set to date format (yyyy-mm-dd hh:mm:ss). What I want to achieve is to aggregate the original DataFrame into a new one, where the two columns are summed by date.
Example as follows:
Original DataFram... | Aggregate and create a new Pandas DataFrame based on date index | I have a DataFrame that has two columns with index set to date format (yyyy-mm-dd hh:mm:ss). What I want to achieve is to aggregate the original DataFrame into a new one, where the two columns are summed by date.
Example as follows:
Original DataFrame looks like this:
Time Column 1 Column 2 ... | [
"df.set_axis(pd.to_datetime(df.index)).resample(rule='D').sum()\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074490474_dataframe_pandas_python.txt |
Q:
Computing difference between two datefields in Django Model
I have two datefields fields in a Django model, start_date and end_date. I want to calculate and store the total number of days between the two, which will be used alongside a daily fee to return total cost.
models.py
class Booking(models.Model):
"""S... | Computing difference between two datefields in Django Model | I have two datefields fields in a Django model, start_date and end_date. I want to calculate and store the total number of days between the two, which will be used alongside a daily fee to return total cost.
models.py
class Booking(models.Model):
"""Stores the bookings, for example when it was made, the booking dat... | [
"Add a method or property that subtracts the dates of an instance:\n@property\ndef duration(self):\n return (self.end_date - self.start_date).days\n\n"
] | [
2
] | [] | [] | [
"datetime",
"django",
"python",
"python_3.x"
] | stackoverflow_0074490355_datetime_django_python_python_3.x.txt |
Q:
TorchVision using pretrained weights for entire model vs backbone
TorchVision Detection models have a weights and a weights_backbone parameter. Does using pretrained weights imply that the model uses pretrained weights_backbone under the hood? I am training a RetinaNet model and um unsure which of the two options ... | TorchVision using pretrained weights for entire model vs backbone | TorchVision Detection models have a weights and a weights_backbone parameter. Does using pretrained weights imply that the model uses pretrained weights_backbone under the hood? I am training a RetinaNet model and um unsure which of the two options I should use and what the differences are.
| [
"The difference is pretty simple: you can either choose to do transfer learning on the backbone only or on the whole network.\nRetinaNet from Torchvision has a Resnet50 backbone. You should be able to do both of:\n\nretinanet_resnet50_fpn(weights=RetinaNet_ResNet50_FPN_Weights.COCO_V1)\nretinanet_resnet50_fpn(backb... | [
0
] | [] | [] | [
"python",
"pytorch",
"retinanet",
"torchvision"
] | stackoverflow_0074489594_python_pytorch_retinanet_torchvision.txt |
Q:
Replace all subsequent values after the first appearance of a value within a subset Python
I have a pandas dataframe where I've so far created something similar to the below table:
Parent Child Overall Risk Bucket
0 CW12345 CW34565 Low Low to High
1 CW12345 CW28394 Hi... | Replace all subsequent values after the first appearance of a value within a subset Python | I have a pandas dataframe where I've so far created something similar to the below table:
Parent Child Overall Risk Bucket
0 CW12345 CW34565 Low Low to High
1 CW12345 CW28394 High N/A
2 CW12345 CW77646 Moderate Moderate to High
3 CW12345 CW09871 ... | [
"Update: this solution worked for me without creating a new column.\ncols = ['Bucket]\nfor i in cols:\n df[i] = df[i].mask(df.duplicates(['Parent'], i]))\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074407922_pandas_python.txt |
Q:
concatenating character and number as one string
I wanna make strings like A1, A2...
here is my code:
def random_room(self):
return chr(random.randint(65, 90)) + chr(random.randint(1, len(self.rooms)))
but it doesn't work
A:
There are better abstractions available than using chr to manipulate low-level ... | concatenating character and number as one string | I wanna make strings like A1, A2...
here is my code:
def random_room(self):
return chr(random.randint(65, 90)) + chr(random.randint(1, len(self.rooms)))
but it doesn't work
| [
"There are better abstractions available than using chr to manipulate low-level encodings.\nYou want to choose a capital letter\nimport string\nfrom random import choice, randint\n\nletter = choice(string.ascii_uppercase)\n\nand an integer\nnumber = randint(1, len(self.rooms))\n\nthen combine them into a single str... | [
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074490521_python_string.txt |
Q:
Pandas How to Check If a Numpy Float Value is Greater than 0
So I have a DataFrame called df1 with the following setup:
Open Close DiffMa %Percentage Open Close DiffMa2 %Percentage2
2022-11-04 13:30:00-04:00 42.099998 42.224998 -0.135001 0.296912 13.95... | Pandas How to Check If a Numpy Float Value is Greater than 0 | So I have a DataFrame called df1 with the following setup:
Open Close DiffMa %Percentage Open Close DiffMa2 %Percentage2
2022-11-04 13:30:00-04:00 42.099998 42.224998 -0.135001 0.296912 13.9586 14.0150 -0.06584 0.404054
2022-11-04 14:30:00-04:00 42.220... | [
"To count the number of times in which %Percentage and %Percentage2 have the same sign, use:\nimport numpy as np\ncount = np.sign(df1['%Percentage']).eq(np.sign(df1['%Percentage2'])).sum()\n\n"
] | [
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074490769_numpy_pandas_python.txt |
Q:
In a certain range of columns, drop all rows with only NaN values
I have a df like this
x y1 y2 y3 y4
0 -20.0 NaN NaN NaN NaN
1 -19.9 NaN NaN 20 NaN
2 -19.8 NaN NaN NaN NaN
3 -19.7 NaN NaN NaN NaN
4 -19.6 NaN 10 NaN NaN
I want the program to drop all rows with only NaN values in columns y1... | In a certain range of columns, drop all rows with only NaN values | I have a df like this
x y1 y2 y3 y4
0 -20.0 NaN NaN NaN NaN
1 -19.9 NaN NaN 20 NaN
2 -19.8 NaN NaN NaN NaN
3 -19.7 NaN NaN NaN NaN
4 -19.6 NaN 10 NaN NaN
I want the program to drop all rows with only NaN values in columns y1 to y4.
The output would be this:
x y1 y2 y3 y4
1 -19.9 N... | [
"You need to specify your columns as subset:\ndf.dropna(subset=['y1', 'y2', 'y3', 'y4'], how='all', inplace=True)\n\nOutput:\n x y1 y2 y3 y4\n1 -19.9 NaN NaN 20.0 NaN\n4 -19.6 NaN 10.0 NaN NaN\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074490811_dataframe_pandas_python.txt |
Q:
Python: Can dumpdata cannot loaddata back. UnicodeDecodeError
I have been using Python 2.7, Django 1.5 and PostgreSQL 9.2 for two weeks. Never saw it before. Everything is freshly installed on my Windows 7 machine, so it should have default settings. Django beautifully generates tables in my db. Looks like everyth... | Python: Can dumpdata cannot loaddata back. UnicodeDecodeError | I have been using Python 2.7, Django 1.5 and PostgreSQL 9.2 for two weeks. Never saw it before. Everything is freshly installed on my Windows 7 machine, so it should have default settings. Django beautifully generates tables in my db. Looks like everything works fine.
I am able to dump data from my database by running... | [
"What worked for me is following these steps:\n- Open the file in regular notepad\n- Select save as\n- Select encoding \"UTF-8\" (Not \"UTF-8 (With BOM)\")\n- Save the file.\n\nNow you can use loaddata.\nHowever, this only works for files that are small enough for notepad to open.\n",
"0xff in position 0 looks li... | [
25,
6,
1,
1,
1,
1,
1
] | [] | [] | [
"django",
"json",
"postgresql",
"python"
] | stackoverflow_0017843630_django_json_postgresql_python.txt |
Q:
Can't install pycurl with pip
Can't install pycurl with pip, win xp x32, python 2.7.
here is the log
pip install pycurl
Downloading/unpacking pycurl
Downloading pycurl-7.19.3.1.tar.gz (116Kb): 116Kb downloaded
Running setup.py egg_info for package pycurl
Please specify --curl-dir=/path/to/built/libcurl
... | Can't install pycurl with pip | Can't install pycurl with pip, win xp x32, python 2.7.
here is the log
pip install pycurl
Downloading/unpacking pycurl
Downloading pycurl-7.19.3.1.tar.gz (116Kb): 116Kb downloaded
Running setup.py egg_info for package pycurl
Please specify --curl-dir=/path/to/built/libcurl
Complete output from command pytho... | [
"Following the steps one mentioned above, solved my problem.\nsudo apt install libcurl4-gnutls-dev librtmp-dev\n\npip install pycurl\n\n",
"This is a problem indeed. No need to update pip or easy install as it's often advised, well it won't hurt to update but you will still have the problem until you : \n\ninstal... | [
24,
9,
4,
3,
2,
1,
0
] | [
"So has said by Hai Vu you need to install cURL first.\nHere is the dowload page : http://curl.haxx.se/download.html\nI suggest you install it in your C:/ directory, or if you already installed it elsewhere copye the curl.exe file to your c:/\nWhen done, you can try it by going to the cmd prompt :\ncd c:/\ncurl \"y... | [
-3
] | [
"installation",
"pip",
"pycurl",
"python"
] | stackoverflow_0022754649_installation_pip_pycurl_python.txt |
Q:
weird behaviour of terminal in vscode
when i try to execute any command in vscode, for some reason, it opens a particular file. I'm using ubuntu 20.04 with WSL 2
For example, when i do pip freeze it opens a file with the following content:
#!/home/leonardofr/documents/api_flask/flask-project/project/venv/bin/pytho... | weird behaviour of terminal in vscode | when i try to execute any command in vscode, for some reason, it opens a particular file. I'm using ubuntu 20.04 with WSL 2
For example, when i do pip freeze it opens a file with the following content:
#!/home/leonardofr/documents/api_flask/flask-project/project/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import... | [
"I fixed it by adding the WSL extension in vscode.\n"
] | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074490717_python_visual_studio_code.txt |
Q:
Comparing a set and list and adding the duplicates to a new list Python
I'm trying to compare one list and one set using two for loops, what I find weird is that sometimes 'O' is in the output and sometimes 'L' is but never both. Does it have to do with set being unsorted? Also is there a better way of getting the... | Comparing a set and list and adding the duplicates to a new list Python | I'm trying to compare one list and one set using two for loops, what I find weird is that sometimes 'O' is in the output and sometimes 'L' is but never both. Does it have to do with set being unsorted? Also is there a better way of getting the duplicates of a list? Preferably the unique duplicates. Any help is apprecia... | [
"You are removing from charList while you are iterating it, which will mess up your iteration.\nI would use collections.Counter to count your characters, then you can look for any characters that have a count greater than 1, meaning there are duplicates\n>>> from collections import Counter\n>>> s = 'HELOLO'\n>>> c ... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0074490529_python.txt |
Q:
how to paste image on google slides with selenium?
i'm trying to paste a .jpg image from my clipboard to a slide in a google slides presentation, but nothing happens. I'm currently using selenium ActionChains to execute the action. I even tried pasting a text insted of an image... still nothing
code:
ActionChains(... | how to paste image on google slides with selenium? | i'm trying to paste a .jpg image from my clipboard to a slide in a google slides presentation, but nothing happens. I'm currently using selenium ActionChains to execute the action. I even tried pasting a text insted of an image... still nothing
code:
ActionChains(driver).key_down(Keys.DOWN).key_up(Keys.DOWN).perform() ... | [
"If you are able to download the image and add it to your Google Drive, you can try the following code. (the idea is to navigate to the Insert Menu and choose to import the image from Google Drive):\naction.key_down(Keys.ALT).key_down(Keys.SHIFT).key_down('i').key_up(Keys.ALT).key_up(Keys.SHIFT).key_up('i').perform... | [
1
] | [] | [] | [
"copy_paste",
"google_slides",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074482042_copy_paste_google_slides_python_selenium_selenium_webdriver.txt |
Q:
How to set class of OrderingFilter's widget in Django?
I want to set class of OrderingFilter's in Django framework.
I can add class to ModelChoiceFilter like that:
from django_filters import OrderingFilter, ModelChoiceFilter
user_status_filter = ModelChoiceFilter(queryset=UserStatus.objects.all(),
... | How to set class of OrderingFilter's widget in Django? | I want to set class of OrderingFilter's in Django framework.
I can add class to ModelChoiceFilter like that:
from django_filters import OrderingFilter, ModelChoiceFilter
user_status_filter = ModelChoiceFilter(queryset=UserStatus.objects.all(),
label="Status",
... | [
"I tried same thing but didn't found any solution\nYou can try an alternative by using LinkWidget\nfrom django_filters.widgets import LinkWidget\norder_by_filter = OrderingFilter(\n fields=(\n ('score', 'Score'),\n ('money', 'Money'),\n ),\n widget=LinkWidget\n)\n\n",
"Struggled with the sa... | [
0,
0
] | [] | [] | [
"django",
"django_filter",
"python"
] | stackoverflow_0068381768_django_django_filter_python.txt |
Q:
Django how to shuffle a queryset without speed lose
I want to shuffle a list of objects without losing any speed in terms of optimization and performance speed.
let's say I have the following query.
related_products = Announcement.objects.filter(category=category).exclude(id=announcement.id)
pythonically, i would... | Django how to shuffle a queryset without speed lose | I want to shuffle a list of objects without losing any speed in terms of optimization and performance speed.
let's say I have the following query.
related_products = Announcement.objects.filter(category=category).exclude(id=announcement.id)
pythonically, i would import the random module and then random.shuffle(related... | [
"If the list of related_products objects is reasonably short and if you are going to be using them all in any case, It's simplest to just fetch them and then shuffle them.\nimport random\n...\n\nproducts = random.shuffle( list( related_products) )\nfor product in products:\n ...\n\nThis is efficient, in that no ... | [
1
] | [] | [] | [
"django",
"django_queryset",
"postgresql",
"python"
] | stackoverflow_0074490778_django_django_queryset_postgresql_python.txt |
Q:
So, I am trying to restrict a slash command to a certain role. I am using nextcord.H
I am trying to make a slash command (/test) and I am getting a TypeError.
My code:
import nextcord
from nextcord.utils import get
client=nextcord.Client(intents=nextcord.Intents.all())
@client.slash_command(name="test")
async de... | So, I am trying to restrict a slash command to a certain role. I am using nextcord.H | I am trying to make a slash command (/test) and I am getting a TypeError.
My code:
import nextcord
from nextcord.utils import get
client=nextcord.Client(intents=nextcord.Intents.all())
@client.slash_command(name="test")
async def test(interaction:nextcord.Interaction):
if interaction.user in get(interaction.guild.r... | [
"As the error states it is returning a single varible ie Test Role and not a iterable, what you should do is check for the role within the user's roles something like this:\n@client.slash_command(name=\"test\")\nasync def test(interaction:nextcord.Interaction):\n role = nextcord.utils.get(interaction.guild.roles, ... | [
1
] | [] | [] | [
"discord",
"nextcord",
"python"
] | stackoverflow_0074452316_discord_nextcord_python.txt |
Q:
All possible combinations of columns and rows in pandas DataFrame
I have this Dataframe that I want to get all possible combinations of this dataframe across both rows and columns.
A_Points
B_Points
C_Points
0
1
1
3
5
4
9
2
4
For example a combination as follows Points = 0 + 5 + 4, or 9 + 1 + 1.
Is there a bu... | All possible combinations of columns and rows in pandas DataFrame | I have this Dataframe that I want to get all possible combinations of this dataframe across both rows and columns.
A_Points
B_Points
C_Points
0
1
1
3
5
4
9
2
4
For example a combination as follows Points = 0 + 5 + 4, or 9 + 1 + 1.
Is there a builtin tool for such problem?
This is what I tried, but it di... | [
"Use itertools.product and sum:\nfrom itertools import product\n\nout = list(map(sum, product(*df.to_numpy().tolist())))\n\nOutput:\n[12, 5, 7, 14, 7, 9, 13, 6, 8, 13, 6, 8, 15, 8, 10, 14, 7, 9, 13, 6, 8, 15, 8, 10, 14, 7, 9]\n\nIntermediate:\nlist(product(*df.to_numpy().tolist()))\n\nOutput:\n[(0, 3, 9),\n (0, 3, ... | [
0,
0
] | [] | [] | [
"combinations",
"math",
"pandas",
"python"
] | stackoverflow_0074490937_combinations_math_pandas_python.txt |
Q:
Image location data is corrupt when extracted using PIL
I have 2 programs to get the Exif data (specifically geolocation data) from pictures:
Number 1 (removed opening the file, etc to make it more concise):
from PIL import Image
from PIL.ExifTags import TAGS
exif = {}
for tag, value in image._getexif().items():... | Image location data is corrupt when extracted using PIL | I have 2 programs to get the Exif data (specifically geolocation data) from pictures:
Number 1 (removed opening the file, etc to make it more concise):
from PIL import Image
from PIL.ExifTags import TAGS
exif = {}
for tag, value in image._getexif().items():
if tag in TAGS:
exif[TAGS[tag]] = value
print("... | [
"It is a little old, but I have the same problem, I solved using the binary output based in this example\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS, GPSTAGS\n\ndef get_decimal_coordinates(info):\n try:\n #print(info)\n for key in ['Latitude', 'Longitude']:\n print('GPS'+key,'GPS'+key+'Ref')... | [
0
] | [] | [] | [
"exif",
"python",
"python_imaging_library"
] | stackoverflow_0070991066_exif_python_python_imaging_library.txt |
Q:
Generating surfaces in Tensorflow
I have a 2D grid with shape [sampling_size* sampling_size, 2]. I'm using it to generatd 3D surfaces in Tensorflow as follows:
def cube(G):
res = []
for (X, Y) in G:
if X >= -1 and X < 1 and Y >= -1 and Y < 1:
res.append(1.)
else:
r... | Generating surfaces in Tensorflow | I have a 2D grid with shape [sampling_size* sampling_size, 2]. I'm using it to generatd 3D surfaces in Tensorflow as follows:
def cube(G):
res = []
for (X, Y) in G:
if X >= -1 and X < 1 and Y >= -1 and Y < 1:
res.append(1.)
else:
res.append(0.)
return tf.convert_to... | [
"What you're looking for is the multiplexing mode of tf.where. Based on a condition, choose if the element should be taken from Tensor A or Tensor B.\nYou can then rewrite your prism function that way:\ndef tf_prism(G):\n X,Y = tf.unstack(G, axis=-1)\n # Here, the operator '&' replaces 'tf.math.logical_and'\n... | [
1
] | [] | [] | [
"python",
"surface",
"tensorflow"
] | stackoverflow_0074489211_python_surface_tensorflow.txt |
Q:
How can I set and split a dataframe value in Python Pandas?
I have been working on a huge .csv dataset which I have to string split every row of it in order to make some calculations on them later. What I am trying to do basically is I am trying to split the default string which is in another csv dataframe and the... | How can I set and split a dataframe value in Python Pandas? | I have been working on a huge .csv dataset which I have to string split every row of it in order to make some calculations on them later. What I am trying to do basically is I am trying to split the default string which is in another csv dataframe and then export it to another csv file which I will make some similarity... | [
"You can split the columns as a unit.\n df['Product'] = df['Product'].str.split()\n df['Issue'] = df['Issue'].str.split()\n df['Company'] = df['Company'].str.split()\n\nAggregate operations are our friends. :)\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"string"
] | stackoverflow_0074491068_pandas_python_string.txt |
Q:
How to takeout the average colour of a screnshot taken using OpenCV?
I am trying to develop a device that changes the RGB led strips according to the colour of my display. To this, I am planning on screenshotting the screen and normalising/taking the mean of the colours of individual pixels in the display. I am ha... | How to takeout the average colour of a screnshot taken using OpenCV? | I am trying to develop a device that changes the RGB led strips according to the colour of my display. To this, I am planning on screenshotting the screen and normalising/taking the mean of the colours of individual pixels in the display. I am having trouble normalising the image and taking out the average colour of th... | [
"Image processing with lists and for loops is inefficient, slow, and error-prone in Python. try to use Numpy, or a vectorised library such as OpenCV, scikit-image, wand or PIL/Pillow.\nMake a sample gradient image image from lime green to yellow, i.e. with no blue, solid green and a gradient in red which will give ... | [
3,
1,
0
] | [] | [] | [
"image_processing",
"opencv",
"python",
"python_3.x"
] | stackoverflow_0074471621_image_processing_opencv_python_python_3.x.txt |
Q:
Find the elements have the same value in two numpy arrays python
I have two numpy arrays A and B, I want to find in B which rows have the same value (second and third columns) as A. For example, in B I found that 2 & 3 (at the first row) and 8 & 9 (at the 4th row). So I need to print out the row that has the same ... | Find the elements have the same value in two numpy arrays python | I have two numpy arrays A and B, I want to find in B which rows have the same value (second and third columns) as A. For example, in B I found that 2 & 3 (at the first row) and 8 & 9 (at the 4th row). So I need to print out the row that has the same values which is 0 and 3
A = np.array([[1, 2, 3],
... | [
"Try np.equal instread of np.isclose. Isclose is valid in case where two arrays are element-wise equal within a tolerance so this is why it does not work in your case :\nfor k in range(0,A.shape[0]):\n i = np.where(np.all(np.equal(B[:,1:3],A[k,1:3]), axis=1))[0]\n for i in i:\n results.append(i)\... | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074490757_arrays_numpy_python.txt |
Q:
Fetch rows from Pandas dataframe using conditions in Python3
I have a dataframe with following columns.
CUI id term id term_name
C0000729 10000057 MDR LLT Abdominal cramps
C0000729 10000056 MDR LLT Abdominal cramp
C0000729 10011286 MDR LLT Cramp abdominal
C0000729 10000058 ... | Fetch rows from Pandas dataframe using conditions in Python3 | I have a dataframe with following columns.
CUI id term id term_name
C0000729 10000057 MDR LLT Abdominal cramps
C0000729 10000056 MDR LLT Abdominal cramp
C0000729 10011286 MDR LLT Cramp abdominal
C0000729 10000058 MDR LLT Abdominal crampy pains
C0000729 10093764 ICD10 PT... | [
"If I understood right:\nnonMDR = df[df['term id'].str.startswith('ICD')] # creates a new df with ICDs\nterm_ids = nonMDR['CUI'].unique() # create an array of unique CUIs\ndf[df['CUI'].isin(term_ids)] # filter CUIs\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074490903_dataframe_pandas_python.txt |
Q:
Extract words (letters only) and words containing numbers into separate dataframe columns
I'm trying to extract words which contain letter only into a new column, and any word which contains a number into a different column.
Desired Output:
query words_only contains_number
0 Nike Air Max 97 Nik... | Extract words (letters only) and words containing numbers into separate dataframe columns | I'm trying to extract words which contain letter only into a new column, and any word which contains a number into a different column.
Desired Output:
query words_only contains_number
0 Nike Air Max 97 Nike Air Max 97
1 Adidas NMD-R1 Adidas NMD-R1
2 Nike Air Max 270... | [
"You can use a regex with str.extractall to extract the words with and without digits separately, then groupby.agg to join them separately:\ndf[['words_only', 'contains_number']] = (df['query']\n .str.extractall(r'(\\S*\\d\\S*)|([^\\s\\d]+)') # order is important\n .groupby(level=0).agg(lambda s: ' '.join(s.dropna(... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074490892_dataframe_pandas_python.txt |
Q:
You cannot call a method on a null-valued expression
i get this error when im trying to start the docker-compose with the "" command docker-compose -f localdevhelpers/docker-compose.yml -f mediaservice/docker-compose.yml up
% : You cannot call a method on a null-valued expression.
At line:1 char:1
+ % docker-com... | You cannot call a method on a null-valued expression | i get this error when im trying to start the docker-compose with the "" command docker-compose -f localdevhelpers/docker-compose.yml -f mediaservice/docker-compose.yml up
% : You cannot call a method on a null-valued expression.
At line:1 char:1
+ % docker-compose -f localdevhelpers/docker-compose.yml -f mediaservi ... | [
"tl;dr\n\nYour problem boils down to a simple confusion between the &, the call operator and % the built-in alias of the ForEach-Object cmdlet.\n\nHowever, the resulting error message is confusing and therefore worth explaining - see below.\n\nAdditionally, guidance on how to discover the meanings of symbols used i... | [
0
] | [] | [] | [
"docker",
"powershell",
"python",
"terminal"
] | stackoverflow_0074490695_docker_powershell_python_terminal.txt |
Q:
Is there a way to create 10 millions row of random dataset in python?
I would like to create random dataset consists of 10 million rows. Unfortunately, I could not find a way to create date column with specific range (example from 01.01.2021-31.12.2021).
I tried with oracle sql, but could not find a way to do that... | Is there a way to create 10 millions row of random dataset in python? | I would like to create random dataset consists of 10 million rows. Unfortunately, I could not find a way to create date column with specific range (example from 01.01.2021-31.12.2021).
I tried with oracle sql, but could not find a way to do that. There is way that I can do in excel, but excel can not handle 10 millions... | [
"\nI would like to create random dataset consists of 10 million rows. Unfortunately, I could not find a way to create date column with specific range (example from 01.01.2021-31.12.2021).\nI tried with oracle sql, but could not find a way to do that.\n\nYou can use the DBMS_RANDOM package with a hierarchical query:... | [
1,
0,
0
] | [] | [] | [
"dataset",
"numpy",
"oracle",
"pandas",
"python"
] | stackoverflow_0074490801_dataset_numpy_oracle_pandas_python.txt |
Q:
Query result to DataFrame using Pyspark: ValueError: Length of object does not match with length of Field
I was running a query from RDS and converting the query into DataFrame using Pyspark.
Here is my code
query= "Select * from profit"
profit=pd.read_sql(query, con=db_connection)
StructureSechma=StructType([
... | Query result to DataFrame using Pyspark: ValueError: Length of object does not match with length of Field | I was running a query from RDS and converting the query into DataFrame using Pyspark.
Here is my code
query= "Select * from profit"
profit=pd.read_sql(query, con=db_connection)
StructureSechma=StructType([
StructField("id",IntegerType(), True),
StructField("type",StringType(), False),
StructField("userId",Int... | [
"You don't need Pandas.\nUse Spark to directly query RDS using spark.read.jdbc. Then, your schema will be automatically inferred from the database itself.\nhttps://spark.apache.org/docs/latest/sql-data-sources-jdbc.html\nOtherwise, look at the koalas library, which has from_pandas function\nhttps://koalas.readthedo... | [
0
] | [] | [] | [
"amazon_rds",
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0074485418_amazon_rds_apache_spark_pyspark_python.txt |
Q:
Is there a way to map python nose2 to coverage plugin which is installed in custom location?
I have installed nose2 with the following command:
pip3 install nose2
And I have installed the coverage in the custom path with the following command:
pip3 install --target=/tmp/coverage_pkg coverage
I want to execute th... | Is there a way to map python nose2 to coverage plugin which is installed in custom location? | I have installed nose2 with the following command:
pip3 install nose2
And I have installed the coverage in the custom path with the following command:
pip3 install --target=/tmp/coverage_pkg coverage
I want to execute the test cases and generate the coverage report. Is there a way to map my coverage plugin installed ... | [
"I was able to achieve this using the following command:\ncd <custom location where packages are installed>\n\npython3 -m nose2 --with-coverage -s \"path_to_source_dir\" --coverage \"path_to_source_dir\"\n\nYou need to stay in the location where nose2 and coverage in installed(Custom dir/ Eg: /tmp/coverage_pkg).\n... | [
2,
0
] | [] | [] | [
"coverage.py",
"nose2",
"python",
"python_3.x",
"unit_testing"
] | stackoverflow_0074449669_coverage.py_nose2_python_python_3.x_unit_testing.txt |
Q:
How can we assign new variables after each for loop iteration in python?
Although it might be easy but i am not able to get a hang of it..
I want to assign the result to a new variable every time the for loop iteration occurs. I don't wish to do with initializing the list or dict and then adding the result. Becaus... | How can we assign new variables after each for loop iteration in python? | Although it might be easy but i am not able to get a hang of it..
I want to assign the result to a new variable every time the for loop iteration occurs. I don't wish to do with initializing the list or dict and then adding the result. Because that way still it won't assign to a new variable each time.
Basically i want... | [
"You could use exec\n# let's create a list for testing purposes\ndata = list(range(100))\n\n# to assign the 10 first values\nfor i in range(10):\n exec(f'data_Absen_{i+1} = data[{i}]')\n\nThen you can directly access your variables\nprint(data_Absen_6) # returns 5\n\n"
] | [
1
] | [] | [] | [
"data_science_experience",
"python"
] | stackoverflow_0074491145_data_science_experience_python.txt |
Q:
I am getting error while I'm creating game with Ursina(python). How can I fix it?
I'm creating gun game with Ursina Engine (python). but I started to get a errror whenever I tried to play it
I just started coding so I don't know what should I do.
My code was:
from ursina import *
from ursina.prefabs.first_person_c... | I am getting error while I'm creating game with Ursina(python). How can I fix it? | I'm creating gun game with Ursina Engine (python). but I started to get a errror whenever I tried to play it
I just started coding so I don't know what should I do.
My code was:
from ursina import *
from ursina.prefabs.first_person_controller import *
class Player(Entity):
def __init__(self, **kwargs):
self.cont... | [
"You should instantiate Ursina with app = Ursina() before instantiating Entities. You're missing the ().\n"
] | [
0
] | [] | [] | [
"attributeerror",
"game_development",
"game_engine",
"python",
"ursina"
] | stackoverflow_0074489960_attributeerror_game_development_game_engine_python_ursina.txt |
Q:
pandas, how to fill a new column with the highest value of previous rows of an other column
Problem to solve :
When a column_A of a dataframe is filled with values which are not ordered, I would like to create a new column_B filled by the last highest previous value met in column_A. I tried to use the rolling() m... | pandas, how to fill a new column with the highest value of previous rows of an other column | Problem to solve :
When a column_A of a dataframe is filled with values which are not ordered, I would like to create a new column_B filled by the last highest previous value met in column_A. I tried to use the rolling() method, but it delivers wrong numbers compared to what I expected.
Reproductive example
A datafra... | [
"I believe what you are looking for is cummax\ndf['expected_values'] = df['original_values'].cummax()\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074491334_dataframe_pandas_python.txt |
Q:
How to get git diff with full context using gitpython
I want to get the changes to a file in a git repository using the gitpython library.
I'm using
repo.git.diff(commit_a, commit_b, file_path)
for that. But I need to increase the context of the diff similar to the -U argument. How can I do this using the librar... | How to get git diff with full context using gitpython | I want to get the changes to a file in a git repository using the gitpython library.
I'm using
repo.git.diff(commit_a, commit_b, file_path)
for that. But I need to increase the context of the diff similar to the -U argument. How can I do this using the library?
| [
"I solved it using subprocess at the end, like this:\nsubprocess.check_output(['git', 'diff', '-U500', commit_a, commit_b, file_path], cwd=project_dir).\n",
"Like this, repo.git.diff(commit_a, commit_b, file_path, unified=1000)\nSee git-diff Manual\n\n-U\n--unified=<n>\nGenerate diffs with lines of context inste... | [
0,
0
] | [] | [] | [
"git",
"gitpython",
"python"
] | stackoverflow_0043355220_git_gitpython_python.txt |
Q:
Showing objects in web page in Django
I'm trying to show all the data that I have saved in my admin page to users visiting my website.
models.py:
class Movie(models.Model):
name = models.CharField(max_length=255)
genre = models.CharField(max_length=255)
date_of_release=models.CharField(max_length=255)
... | Showing objects in web page in Django | I'm trying to show all the data that I have saved in my admin page to users visiting my website.
models.py:
class Movie(models.Model):
name = models.CharField(max_length=255)
genre = models.CharField(max_length=255)
date_of_release=models.CharField(max_length=255)
IMDb=models.CharField(max_length=250)
... | [
"An example is below.\nurls.py:\nfrom . import views\nurlpatterns=[\n path('movies/', views.movies, name='movies'),\n path('movies/<int:id>/',views.single_movie, name='single_movie')\n]\n\nviews.py:\nfrom django.shortcuts import get_object_or_404\n\ndef movies(request):\n items = Movie.objects.all()\n r... | [
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0074491168_django_django_models_django_templates_django_urls_python.txt |
Q:
Problem In Installing MySql Connector for Python
Hi I have just started learning sql language in MySql and have completed basic level of the language.
Now I want to access mysql databases from python. I got to know that we need to install MYSQL_Connector for Python to achieve this goal.
But, When i tried to instal... | Problem In Installing MySql Connector for Python | Hi I have just started learning sql language in MySql and have completed basic level of the language.
Now I want to access mysql databases from python. I got to know that we need to install MYSQL_Connector for Python to achieve this goal.
But, When i tried to install python-connector for mysql it gives an error that py... | [
"With the error that you've described, it seems that you're using the Windows MSI installer. But there's an issue in the Connector/Python 8.0.31 installer for Python 3.11, that will be fixed in the upcoming release, see https://bugs.mysql.com/bug.php?id=108911\nMeanwhile, the solution is performing the installation... | [
1
] | [] | [] | [
"mysql_connector_python",
"python"
] | stackoverflow_0074490636_mysql_connector_python_python.txt |
Q:
How to set signature if use np.array as an input in numba
I wanna set signature for my numba function to regulate its type. However, after doing so, I find that the function didn't work. How should I set the signature.
mat = np.random.normal(0, 1, size=(1000000, 10))
@nb.jit(nopython=True)
def f(mat):
max_min... | How to set signature if use np.array as an input in numba | I wanna set signature for my numba function to regulate its type. However, after doing so, I find that the function didn't work. How should I set the signature.
mat = np.random.normal(0, 1, size=(1000000, 10))
@nb.jit(nopython=True)
def f(mat):
max_min = 0
for i in range(mat.shape[0]):
max_min += mat[i... | [
"You should do the following:\n@nb.jit(nb.float64(nb.types.Array(nb.float64, 2, \"C\")), nopython=True)\ndef f(mat):\n max_min = 0\n for i in range(mat.shape[0]):\n max_min += mat[i].max() - mat[i].min()\n return max_min / mat.shape[0]\n\nI.e., the nb.types.Array(nb.float64, 2, \"C\") tells it that ... | [
0
] | [] | [] | [
"numba",
"numpy",
"python"
] | stackoverflow_0074491198_numba_numpy_python.txt |
Q:
How to do the pandas.rolling with "stride" in python?
I want to use the rolling window function with "stride".
That means, the step is still 1.
But we can resample the index with a certain interval not only 1.
Do you have any idea of this? Thanks a lot.
For example:
df:
row0: 0
row1: 1
row2: 2
row3... | How to do the pandas.rolling with "stride" in python? | I want to use the rolling window function with "stride".
That means, the step is still 1.
But we can resample the index with a certain interval not only 1.
Do you have any idea of this? Thanks a lot.
For example:
df:
row0: 0
row1: 1
row2: 2
row3: 3
row4: 4
row5: 5
row6: 6
row7: 7
ro... | [
"I guess you wouldn't really use rolling in this case, but rather a shift:\nout = df.shift(2).add(df)\n\noutput:\n col\nrow0 NaN\nrow1 NaN\nrow2 2.0\nrow3 4.0\n\n",
"I figured it out by myself.\nThe solution is:\ndef mean_with_stide(arr, stride): \n return arr.iloc[::stride].mean() \n\ndf.rolling(wi... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074489958_pandas_python.txt |
Q:
How to compare old and new field values in Django serialiazer?
I have a Django model which has a many to many field. When adding or changing a record in this table, I need to perform certain actions. Because the table contains a many to many field, I can't perform model-level validation using the save method.(Corr... | How to compare old and new field values in Django serialiazer? | I have a Django model which has a many to many field. When adding or changing a record in this table, I need to perform certain actions. Because the table contains a many to many field, I can't perform model-level validation using the save method.(Correct me if I am wrong, but when i add or remove many to many field th... | [
"Yes, you can save or delete two objects in a single view. You need to override a method, not on the serializer but on the view.\nLets say you are using ModelViewSet, the Save and deletion hooks: provided by the Mixin classes allows you to override these methods.\n from rest_framework import viewsets\n from .... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0074489716_django_django_rest_framework_django_serializer_python.txt |
Q:
How to modify custom.xml within docx using python
I've been using python-docx to programmatically change parts of a word document (*.docx) that needs to be updated monthly. My problem now lies with editing custom properties in the template, specifically the 'Date Completed' property.
Custom template properties
My ... | How to modify custom.xml within docx using python | I've been using python-docx to programmatically change parts of a word document (*.docx) that needs to be updated monthly. My problem now lies with editing custom properties in the template, specifically the 'Date Completed' property.
Custom template properties
My current simplified python code is as follows:
import py... | [
"This functionality hasn't been implemented yet. There's a feature request open for it and one user has done some work on it you can find linked to from there.\nhttps://github.com/python-openxml/python-docx/issues/91\nI think this would require using his fork, so you might not get all the latest features, depending... | [
0,
0
] | [] | [] | [
"elementtree",
"lxml",
"python",
"python_docx",
"xml"
] | stackoverflow_0039694652_elementtree_lxml_python_python_docx_xml.txt |
Q:
Remove rows with duplicate string values in one column, and append strings from another columns
I am looking to remove duplicate rows based on the values in a column ("Name"), but append the corresponding string values in another column("Occupation").
Duplicate entry is "Jack"
I have a dataframe:
Name
center
Occu... | Remove rows with duplicate string values in one column, and append strings from another columns | I am looking to remove duplicate rows based on the values in a column ("Name"), but append the corresponding string values in another column("Occupation").
Duplicate entry is "Jack"
I have a dataframe:
Name
center
Occupation
Jack
Miami
Clerk
Alice
Tx
Manager
Jack
San Jose
PO
Cathy
Houston
Security
And... | [
"You can do a groupby, and then aggregate the columns as you like. For occupation you already wrote to join, for center I chose first.\nout = df.groupby('Name', as_index=False, sort=False).agg({'center': 'first', 'Occupation': ' '.join})\nprint(out)\n\nOutput:\n Name center Occupation\n0 Jack Miami Cler... | [
1,
0
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074491449_dataframe_group_by_pandas_python.txt |
Q:
I want to convert a binary numpy.ndarray to a list of lists python?
Hi there I need to convert a binary "numpy.ndarray" to a list of lists as the example below :
Matrix:
[[ # 0 1 2 3 4]
[ 0 1 0 1 0 1]
[ 1 0 0 1 1 1]
[ 2 1 0 1 1 0]
[ 3 0 0 1 0 1]
[ 4 1 1 0 0 1]
[ 5 ... | I want to convert a binary numpy.ndarray to a list of lists python? | Hi there I need to convert a binary "numpy.ndarray" to a list of lists as the example below :
Matrix:
[[ # 0 1 2 3 4]
[ 0 1 0 1 0 1]
[ 1 0 0 1 1 1]
[ 2 1 0 1 1 0]
[ 3 0 0 1 0 1]
[ 4 1 1 0 0 1]
[ 5 1 0 1 1 1]
[ 6 0 0 1 0 1]]
List:
[[0,2,4],[2,3,4],[0,2,3],... | [
"This is a small example showing the solution\nimport numpy as np\n\nx = np.array([[ 0 , 1, 0 , 1 , 0 , 1],\n [ 1 , 0 , 0, 1 , 1, 1],\n [ 2 , 1 , 0 ,1 , 1, 0],\n [ 3 , 0 , 0 ,1, 0 , 1],\n [ 4 , 1, 1 , 0 , 0 , 1],\n [ 5 , 1 ,0 , 1, ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074491482_python.txt |
Q:
XGBoost JSON model in android studio using Chaquopy
I am implementing an android app that makes predictions over some sounds using chaquopy. the XGboost was used to make this model which is in json. I'm using chaquopy latest version (10). As chaquopy supports xgboost this module is being installed but when I try t... | XGBoost JSON model in android studio using Chaquopy | I am implementing an android app that makes predictions over some sounds using chaquopy. the XGboost was used to make this model which is in json. I'm using chaquopy latest version (10). As chaquopy supports xgboost this module is being installed but when I try to load the json module it doesn't allow it. I would like ... | [
"You correctly set the filename variable based on __file__, but then you forgot to use that variable when calling load_model.\n",
"I faced the same problem and solved it successfully.\nOne thing\nThe version of xgboost will same while saving the model and loading the model.\nFor me, I used xgboost==1.1.1\nFor the... | [
0,
0
] | [] | [] | [
"android",
"chaquopy",
"json",
"python",
"xgboost"
] | stackoverflow_0070187121_android_chaquopy_json_python_xgboost.txt |
Q:
configparser - create file with key and no value
I have to create an ini file similar to this :
[rke2_servers]
host0
host1
host2
[rke2_agents]
host4
host5
host6
[rke2_cluster:children]
rke2_servers
rke2_agents
I tried to create the file using this code:
import configparser
def initfile(rke2s, rke2a, filepath... | configparser - create file with key and no value | I have to create an ini file similar to this :
[rke2_servers]
host0
host1
host2
[rke2_agents]
host4
host5
host6
[rke2_cluster:children]
rke2_servers
rke2_agents
I tried to create the file using this code:
import configparser
def initfile(rke2s, rke2a, filepath):
config = configparser.ConfigParser(allow_no_val... | [
"Try using None instead of an empty string:\ndef initfile(rke2s, rke2a, filepath):\n config = configparser.ConfigParser(allow_no_value=True)\n config['rke2_servers'] = {rke2s: None}\n config['rke2_agents'] = {rke2a: None}\n config['rke2_cluster:children'] = {'rke2_servers': None, 'rke2_agents': None}\n ... | [
1
] | [] | [] | [
"configparser",
"python",
"python_3.x"
] | stackoverflow_0074451884_configparser_python_python_3.x.txt |
Q:
pandas dataframe to frozenset based on conditions
I have a dataset like:
node community
1 2
2 4
3 5
4 2
5 3
7 1
8 3
10 4
12 5
I want to have the frozenset of node column in a way that their community is the same. Thus, the... | pandas dataframe to frozenset based on conditions | I have a dataset like:
node community
1 2
2 4
3 5
4 2
5 3
7 1
8 3
10 4
12 5
I want to have the frozenset of node column in a way that their community is the same. Thus, the expected result is something like:
[frozenset([1,4]),... | [
"Using GroupBy + apply with frozenset:\nres = df.groupby('community')['node'].apply(frozenset).values.tolist()\n\nprint(res)\n\n[frozenset({7}), frozenset({1, 4}), frozenset({8, 5}),\n frozenset({2, 10}), frozenset({3, 12})]\n\n",
"I would suggest iterating over your GroupBy object and emitting a map instead.\nco... | [
3,
3,
0
] | [] | [] | [
"dataframe",
"frozenset",
"list",
"pandas",
"python"
] | stackoverflow_0053163285_dataframe_frozenset_list_pandas_python.txt |
Q:
How to combine multiple trained models into one and use it to predict?
I have a time series data frame with 100 rows and 1000+ columns. The columns are independent of each other. I am running the ARIMA model on each of these columns. So, it is like running 1000+ ARIMA analysis.
I have written a piece of code that... | How to combine multiple trained models into one and use it to predict? | I have a time series data frame with 100 rows and 1000+ columns. The columns are independent of each other. I am running the ARIMA model on each of these columns. So, it is like running 1000+ ARIMA analysis.
I have written a piece of code that loops through the columns of the training set and fits the ARIMA model on e... | [
"Every time you loop, you are creating a new ARIMA model and you are fitting it on your column. After your last loop, you only have fitted on your last column and then you are predicting on your test column.\nYou have to put your predicting inside your for loop.\nfor col in train.columns:\n model = ARIMA(train[col... | [
0
] | [] | [] | [
"machine_learning",
"model",
"pandas",
"python"
] | stackoverflow_0074491347_machine_learning_model_pandas_python.txt |
Q:
Test Multiprocessing Implementation in python
I was able to test the implementation without multiprocessing using the code below.
import unittest
from unittest.mock import patch
def side_effect_cube(x):
return x**3
@patch("test.data.geocode.test_geo_thread.cube", side_effect=side_effect_cube)
def test_sum(mo... | Test Multiprocessing Implementation in python | I was able to test the implementation without multiprocessing using the code below.
import unittest
from unittest.mock import patch
def side_effect_cube(x):
return x**3
@patch("test.data.geocode.test_geo_thread.cube", side_effect=side_effect_cube)
def test_sum(mock_cube):
assert find_cube(7) == [1, 8, 27, 64,... | [
"This is a unresolved problem.\n\"Because the class for any individual Mock / MagicMock isn't available at the\ntop level of the mock module I don't think this can be fixed (fundamental\npickle limitation).\" #139\nHere some workarounds:\nIf you don't need the magic methods, like assert and return_value you can cre... | [
2
] | [] | [] | [
"multiprocessing",
"pytest",
"python",
"python_3.x"
] | stackoverflow_0061622084_multiprocessing_pytest_python_python_3.x.txt |
Q:
how do I run a correct boolean iteration test on this python code? I wish to iterate through the list checking it x is left< and >right
x = [7,2,9,10,23,5]
left = 3
right = 8
def solution(numbers, left, right):
for i in y:
if y (left < x > right ):
print(bool(x))
else:
... | how do I run a correct boolean iteration test on this python code? I wish to iterate through the list checking it x is left< and >right | x = [7,2,9,10,23,5]
left = 3
right = 8
def solution(numbers, left, right):
for i in y:
if y (left < x > right ):
print(bool(x))
else:
print(bool(x)
I was trying to iterate through the list, and achieve a boolean return for each value in x
| [
"If I understood your requirement, then you need something like this-\nx = [7,2,9,10,23,5]\nleft = 3\nright = 8\n\ndef solution(numbers, left, right):\n result = []\n for i in numbers:\n if left < i > right:\n status = True\n else:\n status = False\n result.append(st... | [
0
] | [] | [] | [
"boolean",
"iteration",
"python"
] | stackoverflow_0074491630_boolean_iteration_python.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'edit'
I made a simple slash command for my discord bot using python, to show bot latency. However, it does not appear to be working. can you help me out? thanks a lot :D.
My code:
import time
import discord
from discord import app_commands
from discord.ext import... | AttributeError: 'NoneType' object has no attribute 'edit' | I made a simple slash command for my discord bot using python, to show bot latency. However, it does not appear to be working. can you help me out? thanks a lot :D.
My code:
import time
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
client = discor... | [
"U cannot store the interaction like message = await Interaction.response.send_message(\"pong\") and update it.\nYou can edit the interaction by using edit_original_message()\n@tree.command(name = \"ping\", description = \"test command\", guild=discord.Object(id=ID)) \nasync def ping(Interaction):\n before = tim... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074489856_discord_discord.py_python.txt |
Q:
Dataset upsampling using pandas and sklearn - Python
I have a dataset with one class being very imbalanced (190 records vs 14810) based on the 'relevance' column. So, I tried to upsample it which worked; but the issue is that I have other category of classes in another column (1000 records per each class) and when... | Dataset upsampling using pandas and sklearn - Python | I have a dataset with one class being very imbalanced (190 records vs 14810) based on the 'relevance' column. So, I tried to upsample it which worked; but the issue is that I have other category of classes in another column (1000 records per each class) and when I simply upsample based on 'relevance' column, these clas... | [
"Here is a way to do it per class. Note that I'm not sure if this will not bias any model after, not enough experience here. First let's create a dummy data that is closer to your real data.\n# dummy data\nnp.random.seed(0)\ndf = pd.DataFrame({\n 'relevance':np.random.choice(a=[0]*14810+[1]*190,size=15000, ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"scikit_learn",
"sklearn_pandas"
] | stackoverflow_0074490565_dataframe_pandas_python_scikit_learn_sklearn_pandas.txt |
Q:
Can't import my own modules in Python
I'm having a hard time understanding how module importing works in Python (I've never done it in any other language before either).
Let's say I have:
myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py
Now I'm trying to get something like ... | Can't import my own modules in Python | I'm having a hard time understanding how module importing works in Python (I've never done it in any other language before either).
Let's say I have:
myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py
Now I'm trying to get something like this:
myapp.py
===================
from mya... | [
"In your particular case it looks like you're trying to import SomeObject from the myapp.py and TestCase.py scripts. From myapp.py, do\nimport SomeObject\n\nsince it is in the same folder. For TestCase.py, do\nfrom ..myapp import SomeObject\n\nHowever, this will work only if you are importing TestCase from the pack... | [
128,
52,
13,
13,
7,
4,
3,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"import",
"module",
"package",
"python"
] | stackoverflow_0009383014_import_module_package_python.txt |
Q:
I am trying to make this game, but the collision blocks are all spawning at the same position
import time import pygame
class Player(pygame.sprite.Sprite):
def \__init_\_(self, player_x, player_y):
super().\__init_\_()
self.image = pygame.image.load("img for sprites\\\\img_9.png")
self... | I am trying to make this game, but the collision blocks are all spawning at the same position | import time import pygame
class Player(pygame.sprite.Sprite):
def \__init_\_(self, player_x, player_y):
super().\__init_\_()
self.image = pygame.image.load("img for sprites\\\\img_9.png")
self.image = pygame.transform.scale(self.image, (40, 55))
self.image.set_colorkey((255, 255, 2... | [
"The position of a block in the window is (x*TILE_SIZE, y*TILE_SIZE) instead of (x, y):\nblock_list.append(pygame.Rect(x, y, TILE_SIZE, TILE_SIZE))\nblock_list.append(pygame.Rect(x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE))\n\n"
] | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074491400_pygame_python.txt |
Q:
TypeError with pandas.read_excel
I can't load the xlsx file
import pandas
y=pandas.read_excel("as.xlsx",sheetname=0)
y
This is the error message
TypeError Traceback (most recent call last)
<ipython-input-5-54208838b8e5> in <module>
1 import pandas
----> 2 y=pandas.read_excel(... | TypeError with pandas.read_excel | I can't load the xlsx file
import pandas
y=pandas.read_excel("as.xlsx",sheetname=0)
y
This is the error message
TypeError Traceback (most recent call last)
<ipython-input-5-54208838b8e5> in <module>
1 import pandas
----> 2 y=pandas.read_excel("as.xlsx",sheetname=0)
3 y
c:\u... | [
"You have a syntax error\nTry\ny=pandas.read_excel(\"as.xlsx\",sheet_name=0)\n\n",
"It seems that this \"sheet_name\" could be language dependent. The argument is also positional, so you can just drop \"sheet_name\" and write:\ny=pandas.read_excel(\"as.xlsx\",0)\n\nI have tried version Pandas 1.0.5 and xlrd 1.2.... | [
29,
4,
0
] | [
"install xlrd from command prompt using below:\n\nconda install xlrd\npip install xlrd\n\nIt is referred to as Sheetname\n"
] | [
-1
] | [
"pandas",
"python"
] | stackoverflow_0057348149_pandas_python.txt |
Q:
Indexing into a list using a sorting function on strings
I have an existing list of strings that I am reading from a CSV which follow a naming convention, for example...
["",
"00000-ABC-XX-00-DR-A-20100",
"00000-ABC-XX-01-DR-A-20101",
"00000-ABC-XX-02-DR-A-20102",
"",
"00000-ABC-XX-ZZ-DR-A-20350",
"00000-ABC-XX-ZZ... | Indexing into a list using a sorting function on strings | I have an existing list of strings that I am reading from a CSV which follow a naming convention, for example...
["",
"00000-ABC-XX-00-DR-A-20100",
"00000-ABC-XX-01-DR-A-20101",
"00000-ABC-XX-02-DR-A-20102",
"",
"00000-ABC-XX-ZZ-DR-A-20350",
"00000-ABC-XX-ZZ-DR-A-20351",
"00000-ABC-XX-ZZ-DR-A-20352",
""]
Given a list ... | [
"Using bisect with a key function will find you the insertion point:\nfrom bisect import bisect\nfrom functools import cmp_to_key\n\ndata = [\n \"\",\n \"00000-ABC-XX-00-DR-A-20100\",\n \"00000-ABC-XX-01-DR-A-20101\",\n \"00000-ABC-XX-02-DR-A-20102\",\n \"\",\n \"00000-ABC-XX-ZZ-DR-A-20350\",\n ... | [
0
] | [] | [] | [
"indexing",
"list",
"python",
"sorting"
] | stackoverflow_0074491718_indexing_list_python_sorting.txt |
Q:
Merge two columns when sign changes pandas
I would like to merge two columns into one but I am not sure how to do this efficiently. My df looks like this:
col1 col2
0.4 -0.9
0.2 -0.5
-0.1 0.2
-0.2 0.4
0.8 -0.6
So if one column is positive, the other one is always negative. But I would like to hav... | Merge two columns when sign changes pandas | I would like to merge two columns into one but I am not sure how to do this efficiently. My df looks like this:
col1 col2
0.4 -0.9
0.2 -0.5
-0.1 0.2
-0.2 0.4
0.8 -0.6
So if one column is positive, the other one is always negative. But I would like to have all negative numbers from column 1 replaced by... | [
"Find the rows where col1 is less than 0 and replace with col2:\ndf.loc[df['col1'] < 0, 'col1'] = df['col2']\n\nresult:\n col1 col2\n0 0.4 -0.9\n1 0.2 -0.5\n2 0.2 0.2\n3 0.4 0.4\n4 0.8 -0.6\n\n",
"You could use a mask for all negative values and fill the missing values with values of col2.\nm ... | [
3,
2,
0
] | [
"You can apply your selection function on the Dataframe and Drop the second column afterwards.\ndf[\"col1\"] = df.apply(lambda row: max(row.col1, row.col2), axis=1)\ndf = df.drop(\"col2\", axis=1)\n\n"
] | [
-1
] | [
"merge",
"pandas",
"python"
] | stackoverflow_0074491748_merge_pandas_python.txt |
Q:
TTK Enty validation issue
I am writing my very first GUI app with Py and Tkinter (Ttkinter). I want to be sure that the user can write only digits, "," and "." in the entries field. So far I did this but I have a couple of issues:
I am not able to make it accept "," and ".";
Using this method I can't use the cle... | TTK Enty validation issue | I am writing my very first GUI app with Py and Tkinter (Ttkinter). I want to be sure that the user can write only digits, "," and "." in the entries field. So far I did this but I have a couple of issues:
I am not able to make it accept "," and ".";
Using this method I can't use the clean functions that I wrote to cl... | [
"You'll need to modify your validator to accept the other characters\ndef dig_check(usr_input):\n # accept digits, '.', ',', or empty values\n char = usr_input[-1] # get the latest character added to the Entry\n if char.isdigit() or char in '.,' or char == '':\n return True\n return False\n\nIt'... | [
1
] | [] | [] | [
"data_entry",
"python",
"tkinter",
"tkinter_entry",
"validation"
] | stackoverflow_0074491887_data_entry_python_tkinter_tkinter_entry_validation.txt |
Q:
How to use pytest to confirm proper exception is raised
I have the following code to create an Object account. I raise an error if the account meets certain conditions, e.g. is too long. I want to use pytest to test that that functionality works.
class Account:
def __init__(self, acct):
self.tagged... | How to use pytest to confirm proper exception is raised | I have the following code to create an Object account. I raise an error if the account meets certain conditions, e.g. is too long. I want to use pytest to test that that functionality works.
class Account:
def __init__(self, acct):
self.tagged = {}
self.untagged = {}
self.acct_stats = {}... | [
"Have you tried with pytest.raises()?\nwith pytest.raises(ValueError, match='invalid'):\n account = Account(account_id)\n\nSource\n"
] | [
2
] | [] | [] | [
"pytest",
"python",
"raise"
] | stackoverflow_0074482742_pytest_python_raise.txt |
Q:
Pandas combine .groubpy().sum() on different index levels in one result-dataframe
Consider the following example dataframe:
df = pd.DataFrame({
"key1":['a','a','a','a','b','b','b','b'],
"key2":[1,1,1,2,3,3,4,4],
"key3":['R','S','T','U','V','W','X','Y'],
"count":[10,20,10,5,12,13,8,22]
})
key1 key2 ... | Pandas combine .groubpy().sum() on different index levels in one result-dataframe | Consider the following example dataframe:
df = pd.DataFrame({
"key1":['a','a','a','a','b','b','b','b'],
"key2":[1,1,1,2,3,3,4,4],
"key3":['R','S','T','U','V','W','X','Y'],
"count":[10,20,10,5,12,13,8,22]
})
key1 key2 key3 count
0 a 1 R 10
1 a 1 S 20
2 a 1 T 10
... | [
"You would need to use a loop and groupby.transform:\nfor key in ['key1', 'key2']:\n df[f'count_{key}'] = df.groupby(key)['count'].transform('sum')\n\nOutput:\n key1 key2 key3 count count_key1 count_key2\n0 a 1 R 10 45 40\n1 a 1 S 20 45 40\n2 ... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074491966_dataframe_pandas_python.txt |
Q:
Am I using LMDB incorrectly? It says environment mapsize limit reached after 0 insertions
I am trying to create an LMDB database for my Caffe machine learning project. But LMDB throws an error ont the first attempt to insert a data point, saying the environment mapsize is full.
Here's the code that attempts to pop... | Am I using LMDB incorrectly? It says environment mapsize limit reached after 0 insertions | I am trying to create an LMDB database for my Caffe machine learning project. But LMDB throws an error ont the first attempt to insert a data point, saying the environment mapsize is full.
Here's the code that attempts to populate the database:
import numpy as np
from PIL import Image
import os
import lmdb
import rando... | [
"map size is the maximum size of the whole DB, including metadata - it appears you used the number of expected records.\nyou increase this number\n",
"Do you have only 10 bytes per image?\nAnd there is other info except of images in the database. So reserve more space for your LMDB database. For example, this com... | [
8,
5,
0
] | [] | [] | [
"database",
"lmdb",
"machine_learning",
"python"
] | stackoverflow_0037642885_database_lmdb_machine_learning_python.txt |
Q:
Python DOcplex how to get end and start value for interval_var
I am trying to model a scheduling task using IBMs DOcplex Python API. The goal is to optimize EV charging schedules and minimize charging costs. However, I am having problems working with the CPO interval variable.
Charging costs are defined by differe... | Python DOcplex how to get end and start value for interval_var | I am trying to model a scheduling task using IBMs DOcplex Python API. The goal is to optimize EV charging schedules and minimize charging costs. However, I am having problems working with the CPO interval variable.
Charging costs are defined by different price windows, e.g., charging between 00:00 - 06:00 costs 0.10$ p... | [
"Have you tried to use overlap_length as can be seen in\nHow to initiate the interval variable bounds in docplex (python)?\n?\nstart_of and end_of do not return values but something that is not set until the model is run.\nWhat you were trying to do is a bit like\nusing CP;\n\ndvar int l;\n\ndvar interval a in 0..1... | [
0
] | [] | [] | [
"cplex",
"docplex",
"python"
] | stackoverflow_0074490804_cplex_docplex_python.txt |
Q:
Can I use .apply() similar to .iterrows()
I like to make a somewhat easy calculation on the rows of my data frame and used to use .iterrows() but the the operation is very slow. Now I wonder if I can use .apply() to achieve the same thing to get it done faster. It could also be that there is a totally differnt opt... | Can I use .apply() similar to .iterrows() | I like to make a somewhat easy calculation on the rows of my data frame and used to use .iterrows() but the the operation is very slow. Now I wonder if I can use .apply() to achieve the same thing to get it done faster. It could also be that there is a totally differnt option, which I'm just not aware of or have not th... | [
"This works:\nd = np.array([ [10,15,12,7],\n [20,10,17,21]])\ndf = pd.DataFrame(d, columns=[\"ID_1\",\"ID_2\",\"ID_3\",\"mean\"])\n\nN = 3\n\ndef my_func(row):\n s = 0\n for i in range(1,N+1):\n if row[f\"ID_{i}\"] > row[\"mean\"]:\n s += row[f\"ID_{i}\"]\n\n return s\n\nd... | [
2,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074491796_dataframe_pandas_python.txt |
Q:
Error uploading PDF-like object to s3 bucket from Streamlit
I have build a streamlit app that takes PDF as an input. After everything is done I want to save/upload the initial pdf file to s3 bucket for check in the future.
st.markdown =('# Imdocker pull mysql/mysql-server:latestport your PDF file')
pdf = st.file_... | Error uploading PDF-like object to s3 bucket from Streamlit | I have build a streamlit app that takes PDF as an input. After everything is done I want to save/upload the initial pdf file to s3 bucket for check in the future.
st.markdown =('# Imdocker pull mysql/mysql-server:latestport your PDF file')
pdf = st.file_uploader(label='Drag the PDF file here. Limit 100MB')
if pdf is n... | [
"Looks like you posted this on the Streamlit forum and it was answered there. Sharing the response below.\n\nIf you use boto3.client instead of resource, and s3.upload_fileobj\ninstead of s3.Bucket.upload_fileobj, it should work.\n\nimport boto3\nimport streamlit as st\n\npdf = st.file_uploader(label=\"Drag the PDF... | [
0
] | [] | [] | [
"amazon_s3",
"pdf",
"python",
"streamlit"
] | stackoverflow_0074444471_amazon_s3_pdf_python_streamlit.txt |
Q:
How to change columns value in reduce function python
'''
dfs = reduce(lambda x,y: pd.merge(x,y, on='just_date', how='outer'), [date_game0, date_game1, date_game2, date_game3,date_game4, date_game5, date_game6, date_game7, date_game8, date_game9, date_game10])
'''
I am merging pandas dataframe by using the above ... | How to change columns value in reduce function python | '''
dfs = reduce(lambda x,y: pd.merge(x,y, on='just_date', how='outer'), [date_game0, date_game1, date_game2, date_game3,date_game4, date_game5, date_game6, date_game7, date_game8, date_game9, date_game10])
'''
I am merging pandas dataframe by using the above code, but the columns names are repeating as shown in pictu... | [
"# define a list with column names that you like\ncols=['id1','date1','id2','date2', 'diff'] #just an example\n\n# assign list to the df\ndf.columns=cols\ndf\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074492026_pandas_python.txt |
Q:
How to print the status of testcases in teardown pytest
I am trying to write a script in pytest where I want to print the status of test result in my fixture teardown:
For example:
there are two test cases
test 1---> fails (print test1 failed in fixture teardown)
test 2---> passes(print test2 failed in fixture tea... | How to print the status of testcases in teardown pytest | I am trying to write a script in pytest where I want to print the status of test result in my fixture teardown:
For example:
there are two test cases
test 1---> fails (print test1 failed in fixture teardown)
test 2---> passes(print test2 failed in fixture teardown)
| [
"Consider using following hook in your conftest.py file:\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\"\n result_setup - setup result\n result_call - test result\n result_teardown - teardown result\n \"\"\"\n outcome = yield\n rep = outco... | [
0
] | [] | [] | [
"pytest",
"python"
] | stackoverflow_0074483863_pytest_python.txt |
Q:
How do I store all the responses of an api in a dataframe?
I am taking a column from a dataframe and I am sending it as a parameter to an api, but I want to put this entire response in a new dataframe. But it is only saving the last response of the api. To which I am trying to put all the answers in an api, but it... | How do I store all the responses of an api in a dataframe? | I am taking a column from a dataframe and I am sending it as a parameter to an api, but I want to put this entire response in a new dataframe. But it is only saving the last response of the api. To which I am trying to put all the answers in an api, but it still does not work for me if you could help me please
`
respon... | [
"You're overwriting the df3 in each iteration of the loop.\nYou can define an empty DataFrame before for loop and then append to it using concat.\n# define empty DF before the for loop\ndf3 = pd.DataFrame()\n\n...\n\ndf3 = pd.concat([df3, pd.DataFrame(response) ) # concat the response to df3\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074492013_dataframe_pandas_python.txt |
Q:
How to write a program in python that keeps asking the user to enter an octal number until user enters an octal number?
I need to write a program that converts an octal number to decimal. However if I enter a non octal number such as 1079, the program shows an error and stops.
I want the program to keep asking the... | How to write a program in python that keeps asking the user to enter an octal number until user enters an octal number? | I need to write a program that converts an octal number to decimal. However if I enter a non octal number such as 1079, the program shows an error and stops.
I want the program to keep asking the user for a valid input until user enters a valid input.
while True:
n= input("Enter an octal value to convert to dec... | [
"it does not seem that you are checking if the number is convertible to octal. you have to divide by the base 8. if there is no remainder then it is an \"octal number\" else it is something else. that's all you need. you can the logic to check for base8 / octal out of this code : https://www.tutorialspoint.com/che... | [
0
] | [
"this is a version:\nwhile True:\n ans = input(\"Number in octal: \")\n try:\n number = int(ans, 8)\n break\n except ValueError:\n print(f\"{ans} can not be interpreted as ocal nubmer\")\n continue\n\n# do stuff with number...\n\ndo not bother to check for 8 or 9 or any other il... | [
-1
] | [
"decimal",
"octal",
"python",
"verification"
] | stackoverflow_0074492092_decimal_octal_python_verification.txt |
Q:
Filter for author exact match regardless of case
I have a linked list for a catalog and book. I am trying to filter by author and return with the books that are of exact match, however, it says that my book type has no such attribute whenever i run it. I also try to upper case the author names so that it is consis... | Filter for author exact match regardless of case | I have a linked list for a catalog and book. I am trying to filter by author and return with the books that are of exact match, however, it says that my book type has no such attribute whenever i run it. I also try to upper case the author names so that it is consistent and match will return even if input are of differ... | [
"You don't need to make a copy of your lst, since your generator below makes a new list anyway. I also don't understand why you are using .capitalize()\nThe problem is that in your list comprehension you go through each book, call the current Book \"author\" and then try to captialize author. author however is a Bo... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074491900_python.txt |
Q:
Pandas Correlation Groupby
Assuming I have a dataframe similar to the below, how would I get the correlation between 2 specific columns and then group by the 'ID' column? I believe the Pandas 'corr' method finds the correlation between all columns. If possible I would also like to know how I could find the 'grou... | Pandas Correlation Groupby | Assuming I have a dataframe similar to the below, how would I get the correlation between 2 specific columns and then group by the 'ID' column? I believe the Pandas 'corr' method finds the correlation between all columns. If possible I would also like to know how I could find the 'groupby' correlation using the .agg ... | [
"You pretty much figured out all the pieces, just need to combine them:\n>>> df.groupby('ID')[['Val1','Val2']].corr()\n\n Val1 Val2\nID \nA Val1 1.000000 0.500000\n Val2 0.500000 1.000000\nB Val1 1.000000 0.385727\n Val2 0.385727 1.000000\n\nIn your case, print... | [
61,
11,
5,
0,
0
] | [] | [] | [
"correlation",
"group_by",
"pandas",
"python"
] | stackoverflow_0028988627_correlation_group_by_pandas_python.txt |
Q:
Airflow: How would I write a Python operator for an extract function from BigQuery to GCS function?
I am writing an Airflow DAG, which will extract a table from BigQuery to a GCS Bucket, but I am unsure what parameters I need to include in my PythonOperator.
So far, I have written the following function to execute... | Airflow: How would I write a Python operator for an extract function from BigQuery to GCS function? | I am writing an Airflow DAG, which will extract a table from BigQuery to a GCS Bucket, but I am unsure what parameters I need to include in my PythonOperator.
So far, I have written the following function to execute the code that will extract the table from BigQuery to a GCS Bucket:
def extract_table(client, to_delete)... | [
"You might consider using the BigQueryToGCSOperator without the need of using a custom function.\nParameters include the dataset/table you want to use as the source data, destination bucket, compression format, export format, delimiter...\nExample of use :\nfrom airflow.providers.google.cloud.transfers.bigquery_to_... | [
0
] | [] | [] | [
"airflow",
"directed_acyclic_graphs",
"google_bigquery",
"google_cloud_platform",
"python"
] | stackoverflow_0074489560_airflow_directed_acyclic_graphs_google_bigquery_google_cloud_platform_python.txt |
Q:
UnicodeDecodeError in client server communication when accessing Desktop
I want to write a reverse shell like netcat. Everything works fine, but after several commands typed in, the client machine throws an error. I managed to identify the problem. When I change to the Desktop directory on the server, for example ... | UnicodeDecodeError in client server communication when accessing Desktop | I want to write a reverse shell like netcat. Everything works fine, but after several commands typed in, the client machine throws an error. I managed to identify the problem. When I change to the Desktop directory on the server, for example C:/Users/Desktop and I type in the command "dir" the error gets thrown on the ... | [
"Before starting Python, set your environment variable PYTHONIOENCODING=utf-8.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"shell",
"sockets",
"subprocess"
] | stackoverflow_0074488610_python_python_3.x_shell_sockets_subprocess.txt |
Q:
What is the solution for 'IndexError: index 0 is out of bounds for dimension 1 with size 0'?
My professor gave me these things and told me to run it. He told me load the data using Custom Data Loader and told me to analyze the result of the dataloader.
import torch
import torch.nn.functional as F
from torch.utils... | What is the solution for 'IndexError: index 0 is out of bounds for dimension 1 with size 0'? | My professor gave me these things and told me to run it. He told me load the data using Custom Data Loader and told me to analyze the result of the dataloader.
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import torch.nn as nn
import pandas... | [
"The problem is in how you extract features vs labels from your data.\nYou do so by:\nself.x_data = np.array(data[:,0:11], dtype=np.float)\n...\nself.y_data = data[:, 11:12]\n\nThis means that your features are the first 11 columns (0 to 10 included) and your labels are in the 12th column.\nYour data though only ha... | [
0
] | [] | [] | [
"deep_learning",
"python"
] | stackoverflow_0074490359_deep_learning_python.txt |
Q:
could anyone identify the days python?
ask the user enter the date in the format YYYY-MM-DD
1.what age of user in days;
2.what day of week (in German language) was the birth.
import datetime
b = int(input('Enter your birthdate: '))
bb = datetime(b, '%Y-%m-%d')
a = datetime.date.today()
c = a-bb
print(c)
from dat... | could anyone identify the days python? | ask the user enter the date in the format YYYY-MM-DD
1.what age of user in days;
2.what day of week (in German language) was the birth.
import datetime
b = int(input('Enter your birthdate: '))
bb = datetime(b, '%Y-%m-%d')
a = datetime.date.today()
c = a-bb
print(c)
from datetime import datetime
d = input("Enter the ... | [
"Your problem is trying to convert an input that's probably in YYYY-MM-DD format, into an int. This will not work in Python. Simply leave as a string and convert to a date.\nUse setlocale to choose German for output.\nfrom datetime import datetime\nfrom datetime import date\n\n# set language output to German\nimpor... | [
0
] | [] | [] | [
"days",
"python"
] | stackoverflow_0074484261_days_python.txt |
Q:
/bin/sh: 1: poetry: not found
i'm trying to build a docker file with docker-compose up but i get error:
/bin/sh: 1: poetry: not found
ERROR: Service 'web' failed to build: The command '/bin/sh -c poetry install && bundler install' returned a non-zero code: 127
here it is my docker file and docker-compose-yml file... | /bin/sh: 1: poetry: not found | i'm trying to build a docker file with docker-compose up but i get error:
/bin/sh: 1: poetry: not found
ERROR: Service 'web' failed to build: The command '/bin/sh -c poetry install && bundler install' returned a non-zero code: 127
here it is my docker file and docker-compose-yml file:
dockerfile:
FROM python:2.7
ENV ... | [
"add this to your Dockerfile:\nFROM python:2.7\n\nENV LIBRARY_PATH=/lib:/usr/lib\n\nRUN curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python\n\nWORKDIR /stream\n\nADD . /stream\n\nENV PATH=\"${PATH}:/root/.poetry/bin\"\n\nRUN poetry install && \\\nbundler install\n\n\nEXPOSE 80... | [
4,
3,
0
] | [] | [] | [
"docker",
"docker_compose",
"python",
"stream_framework"
] | stackoverflow_0057495327_docker_docker_compose_python_stream_framework.txt |
Q:
Python: How to iterate over a list of lists and delete None's?
I want to iterate over a list of lists and delete None's from every list:
List of lists:
my_list = [src_ips, dst_ips, src_fqdns, dst_fqdns, src_groups, dst_groups, services, service_groups]
I tried:
src_ips = [i for i in src_ips if i is not None]
dst_... | Python: How to iterate over a list of lists and delete None's? | I want to iterate over a list of lists and delete None's from every list:
List of lists:
my_list = [src_ips, dst_ips, src_fqdns, dst_fqdns, src_groups, dst_groups, services, service_groups]
I tried:
src_ips = [i for i in src_ips if i is not None]
dst_ips = [i for i in dst_ips if i is not None]
src_fqdns = [i for i in ... | [
"You can do it in for loop like this:\nfor l in [src_ips, dst_ips, src_fqdns, dst_fqdns, src_groups, dst_groups, services, service_groups]:\n l[:] = [element for element in l if element is not None]\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074492242_python.txt |
Q:
How do i precicely add all the packages that are required for the deployment of my py file on Streamlit
I my code is running locally and i need to deploy it on streamlit as a part of my university project. However, how do i know what are the exact dependencies needed to deploy the app? I used PyCharm for the devel... | How do i precicely add all the packages that are required for the deployment of my py file on Streamlit | I my code is running locally and i need to deploy it on streamlit as a part of my university project. However, how do i know what are the exact dependencies needed to deploy the app? I used PyCharm for the development. I pushed the project on Git but i still need a requirements.txt .
What are the steps to generate that... | [
"You can use pip freeze > requirements.txt for this\n"
] | [
0
] | [] | [] | [
"deployment",
"python",
"streamlit"
] | stackoverflow_0074419915_deployment_python_streamlit.txt |
Q:
Modify the volume frame by frame in a wave file
I want to modulate a wave file frame-by-frame using Python. The wave file is composed of brown noise, so pseudo-random noise. The idea would be:
Open the file
Mmodulate it with a 40Hz modulation frequency
Save the new file
I saw that there were some solutions to... | Modify the volume frame by frame in a wave file | I want to modulate a wave file frame-by-frame using Python. The wave file is composed of brown noise, so pseudo-random noise. The idea would be:
Open the file
Mmodulate it with a 40Hz modulation frequency
Save the new file
I saw that there were some solutions to modulate wave volume, however I did not see solution... | [
"I don't fully understand what you are referring to by frame-by-frame. But modulating it by 40 Hz would could possibly refer to either Amplitude or Frequency modulation.\nApplying a simple Amplitude Modulation would look like -\nfrom scipy.io import wavfile\nimport numpy as np\n\n\nF_MOD = 40 # Hz\n\n# 1. Load wav... | [
0
] | [] | [] | [
"acoustics",
"modulation",
"python",
"wave"
] | stackoverflow_0049518329_acoustics_modulation_python_wave.txt |
Q:
Word count in python
I want to calculate the word count of the text taken from the website.
I am trying the following code below:
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
def get_text(url):
page = urlopen(url)
soup = BeautifulSoup(page, "lxml")
text = ' '.join(map(lam... | Word count in python | I want to calculate the word count of the text taken from the website.
I am trying the following code below:
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
def get_text(url):
page = urlopen(url)
soup = BeautifulSoup(page, "lxml")
text = ' '.join(map(lambda p: p.text, soup.find_a... | [
"len(str(text)) will count letters not words, to count total words you will have to split the text len(str(text).split()):\nimport requests\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n\n\ndef get_text(url):\n page = urlopen(url)\n soup = BeautifulSoup(page, \"lxml\")\n text = ' '.jo... | [
1
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python",
"url",
"word_count"
] | stackoverflow_0074492107_beautifulsoup_html_parsing_python_url_word_count.txt |
Q:
Update gdal on ubuntu 22.04
I'm trying to update GDAL on my Ubuntu 22.04 :
python3 -m pip install --upgrade GDAL
This error occurs :
extensions/gdal_array_wrap.cpp:3237:10: fatal error: ogr_recordbatch.h: Aucun fichier ou dossier de ce type
3237 | #include "ogr_recordbatch.h"
| ^~~~~~~~... | Update gdal on ubuntu 22.04 | I'm trying to update GDAL on my Ubuntu 22.04 :
python3 -m pip install --upgrade GDAL
This error occurs :
extensions/gdal_array_wrap.cpp:3237:10: fatal error: ogr_recordbatch.h: Aucun fichier ou dossier de ce type
3237 | #include "ogr_recordbatch.h"
| ^~~~~~~~~~~~~~~~~~~
compilation ter... | [
"ogr_recordbatch.h is one of the new include files in GDAL 3.6.0 - https://github.com/OSGeo/gdal/blob/v3.6.0/NEWS.md\nObviously your system-installed GDAL from Ubuntu is an older version - 3.4.1.\nI don't know what are you trying to do.\nIf you are trying to update only the Python module, it requires having an adeq... | [
0
] | [] | [] | [
"gdal",
"gdal2tiles.py",
"python",
"ubuntu_22.04"
] | stackoverflow_0074473006_gdal_gdal2tiles.py_python_ubuntu_22.04.txt |
Q:
Getting the error message: "r is null" whenever running a Dash application
I couldn't find any similar issue. This error appears ever since I started developing a Dash application.
The error stack is very long and. I'm not sure it's informative, but I'm adding it in case it is.
(This error originated from the buil... | Getting the error message: "r is null" whenever running a Dash application | I couldn't find any similar issue. This error appears ever since I started developing a Dash application.
The error stack is very long and. I'm not sure it's informative, but I'm adding it in case it is.
(This error originated from the built-in JavaScript code that runs Dash apps. Click to see the full stack trace or o... | [
"The first thing to check is that PreventUpdate is being used in callbacks to handle null conditions:\ndef some_callback(some_input):\n if (some_input is None):\n raise PreventUpdate\n\n\nThe r is null also error occurs for me when errors are raised in my server-side code that leave Dash with nothing to d... | [
1,
0,
-2
] | [] | [] | [
"plotly_dash",
"python"
] | stackoverflow_0070145482_plotly_dash_python.txt |
Q:
Is it possible to apply list_filters for parent's object's fields in django?
I want to display the timestamp stored in my parents model to be shown in my model. Also, I want to display it in german format. This is not the problem, but of course I want to be able to sort by this timestamp.
One solution would be to ... | Is it possible to apply list_filters for parent's object's fields in django? | I want to display the timestamp stored in my parents model to be shown in my model. Also, I want to display it in german format. This is not the problem, but of course I want to be able to sort by this timestamp.
One solution would be to create a new DateTimeField in model B, but then I would store redundant informatio... | [
"I cannot post a comment, which is maybe is the case, but:\nHave you tried to set a __str__ method in your A model? Or a german_timestamp method in the A model (if you plan to use other formats for your date) that returns A.timestamp in the format you want.\nThis way you could just set key_to_a in your list_filter ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074490467_django_python.txt |
Q:
How to properly use SQL LIKE statement to query DB from Flask application
I am having a very hard time using a LIKE statement in my Flask application to query my DB. I keep getting a syntax error.
My application is for searching for books and I need to be able to search all columns. I know I need to use LIKE but i... | How to properly use SQL LIKE statement to query DB from Flask application | I am having a very hard time using a LIKE statement in my Flask application to query my DB. I keep getting a syntax error.
My application is for searching for books and I need to be able to search all columns. I know I need to use LIKE but it seems that the single quotes from my variable are getting in the way. However... | [
"For parameterized queries you never need to have quotes inside the statement, they will be added by the db api. This should work:\nsearch = request.values.get('search')\nbooks = db.execute(\"SELECT * FROM books WHERE author LIKE :search\", {\"search\": '%' + search + '%'}).fetchall()\n\nThe % signs need to be part... | [
2,
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"postgresql",
"python"
] | stackoverflow_0062199521_flask_flask_sqlalchemy_postgresql_python.txt |
Q:
Unity Tcpclient connect to python socket server only in local but not in AWS(python server)
i have python server code like below.
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 5000
serverSocket.bind(('aws ec2 private ip', serverPort))
serverSocket.listen(1)
print('server listening')
clientSocket, addr ... | Unity Tcpclient connect to python socket server only in local but not in AWS(python server) | i have python server code like below.
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 5000
serverSocket.bind(('aws ec2 private ip', serverPort))
serverSocket.listen(1)
print('server listening')
clientSocket, addr = serverSocket.accept()
print('Connection from ', addr[0])
...
and i also have c# client code ... | [
"What is it doing with a โaws ec2 public ipโ as a host? That doesnโt look like a domain. It is possible that python works differently and you think that c# tcpclients can figure out what that means, but I donโt think they can. I could be completely wrong, but I would be surprised if you could host a server on a dom... | [
0
] | [] | [] | [
"amazon_ec2",
"c#",
"python",
"sockets",
"unity3d"
] | stackoverflow_0074492392_amazon_ec2_c#_python_sockets_unity3d.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.