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:
python3 torch waning removal
I have a python script the uses torch and easyocr.
When I run it I get in the terminal my output but also I see two warnings:
CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.
[W NNPACK.cpp:79] Could not initialize NNPACK! Reason: Unsupported hardware... | python3 torch waning removal | I have a python script the uses torch and easyocr.
When I run it I get in the terminal my output but also I see two warnings:
CUDA not available - defaulting to CPU. Note: This module is much faster with a GPU.
[W NNPACK.cpp:79] Could not initialize NNPACK! Reason: Unsupported hardware.
Is there a way to add something... | [
"I had run my program all day the next day it said:\n[W NNPACK.cpp:79] Could not initialize NNPACK! Reason: Unsupported hardware.\nwhen I added:\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\"\nit started working again\n",
"Just use these 2 lines of code\nimport warnings\nwarnings.filterwarnings('ignore')\n\n"
] | [
0,
0
] | [] | [] | [
"python",
"pytorch",
"torch"
] | stackoverflow_0070038557_python_pytorch_torch.txt |
Q:
Convert C# post request to Python
var client = new RestClient(Url.Combine(sharepointSiteUrl, "_api"));
client.CookieContainer = new CookieContainer();
client.CookieContainer.SetCookies(siteUri, cred.GetAuthenticationCookie(siteUri));
var digestReq = new RestRequest("contextinfo", Method.POST);
digestReq.AddHeader... | Convert C# post request to Python | var client = new RestClient(Url.Combine(sharepointSiteUrl, "_api"));
client.CookieContainer = new CookieContainer();
client.CookieContainer.SetCookies(siteUri, cred.GetAuthenticationCookie(siteUri));
var digestReq = new RestRequest("contextinfo", Method.POST);
digestReq.AddHeader("Accept", "application/json");
var dig... | [
"Use the following lines of code to send a post request to a server resource\nimport requests # you need to install requests library (pip install requests)\nmy_cookie = {'some_key': 'value}\nresp = requests.post('the url', cookies=cookies) # request.get\nprint(resp.status_code) # print the http response code (20... | [
0
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0074427334_c#_python.txt |
Q:
AttributeError: 'Model' object has no attribute '_output_tensor_cache'
import keras
from keras.layers import Input, Dense
from keras.models import Model
from keras_adamw import AdamW
mlp = Model([
Dense(10, activation='relu', input_shape=trainX_scaled.shape), #input shape
Dense(10, activation='re... | AttributeError: 'Model' object has no attribute '_output_tensor_cache' | import keras
from keras.layers import Input, Dense
from keras.models import Model
from keras_adamw import AdamW
mlp = Model([
Dense(10, activation='relu', input_shape=trainX_scaled.shape), #input shape
Dense(10, activation='relu'), #Hiddin layer
Dense(10, activation='relu') #output layer
])
... | [
"Which tensorflow version have you installed in your system? Please import the keras libraries from tensorflow.keras and re-execute the above code.\nfrom tensorflow.keras.layers import Input, Dense\nfrom tensorflow.keras.models import Model\n\nAdamW api is part of Tensorflow Addons package. To import AdamW optimize... | [
0
] | [] | [] | [
"keras",
"machine_learning",
"mlp",
"python"
] | stackoverflow_0073193789_keras_machine_learning_mlp_python.txt |
Q:
Find sum of values between two dates of a single date column in Pandas dataframe
The dataframe contains date column, revenue column(for specific date) and the name of the day.
This is the code for creating the df:
pd.DataFrame({'Date':['2015-01-08','2015-01-09','2015-01-10','2015-02-10','2015-08-09','2015-08-13',... | Find sum of values between two dates of a single date column in Pandas dataframe | The dataframe contains date column, revenue column(for specific date) and the name of the day.
This is the code for creating the df:
pd.DataFrame({'Date':['2015-01-08','2015-01-09','2015-01-10','2015-02-10','2015-08-09','2015-08-13','2015-11-09','2015-11-15'],
'Revenue':[15,4,15,13,16,20,12,9],
... | [
"First idea is used Weekday for groups by compare by Monday with cumulative sum and aggregate per groups:\ndf1 = (df.groupby(df['Weekday'].eq('Monday').cumsum())\n .agg({'Date':'first','Revenue':'sum', 'Weekday':'first'}))\nprint (df1)\n Date Revenue Weekday\nWeekday ... | [
0,
0
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074427437_dataframe_datetime_pandas_python.txt |
Q:
Selenium: How to get find_element through a function
i am trying to automatize login to a few webpages (Firefox) through python and selenium.
When i try my code outside of a function it works fine but if i call it in a function it says
RemoteError@chrome://remote/content/shared/RemoteError.jsm:12:1
WebDriverError... | Selenium: How to get find_element through a function | i am trying to automatize login to a few webpages (Firefox) through python and selenium.
When i try my code outside of a function it works fine but if i call it in a function it says
RemoteError@chrome://remote/content/shared/RemoteError.jsm:12:1
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:192:5... | [
"You need to pass the driver into each function:\nfrom selenium import webdriver\nfrom time import sleep\nfrom getpass import getpass\nfrom subprocess import Popen, PIPE\nfrom selenium.webdriver.common.by import By\n\nwebpages = dict(zip(['name', 'name2', 'name3'], ['webpage', 'weboage2', 'werbpage3']))\nusr = 'use... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074424688_python_selenium_selenium_webdriver.txt |
Q:
Python - How to check if my string contain any element in an array and get the repeated value?
for line in lines
if any(word in line for word in Array):
print(word)
I am using something similar to this, but I am not able to print it out.
For example:
String1 = " I am a newbie".
String2 = " Hello There".
Array... | Python - How to check if my string contain any element in an array and get the repeated value? | for line in lines
if any(word in line for word in Array):
print(word)
I am using something similar to this, but I am not able to print it out.
For example:
String1 = " I am a newbie".
String2 = " Hello There".
Array = [newbie, hello, world]
I want to get the repeated word when I loop through each line.
Thanks!!
S... | [
"I think there maybe a more efficient way but I managed to do it this way:\n(I assumed that hello word starts with small letter h so that the output is as you wrote\nString1 = \" I am a newbie\"\nString2 = \" hello There\"\nArray = [\"newbie\", \"hello\", \"world\"]\n\nfor word in String1.split(\" \"):\n for wo... | [
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074427317_loops_python.txt |
Q:
How can I check is each keys in this dict exist and that they all have a non empty value?
I have a toml file that looks like
[default]
conf_path = "d"
prefix = "p"
suffix = "s"
I am turning this into a dict that looks like,
{default: {'conf_path': 'd', 'prefix': 'p', 'suffix': 's'}}
They key is default and the v... | How can I check is each keys in this dict exist and that they all have a non empty value? | I have a toml file that looks like
[default]
conf_path = "d"
prefix = "p"
suffix = "s"
I am turning this into a dict that looks like,
{default: {'conf_path': 'd', 'prefix': 'p', 'suffix': 's'}}
They key is default and the value is a dictionary. I want to check if default exists and for the dict in the value -- I want... | [
"if 'default' in conf and all(key in conf['default'] and conf['default'][key] for key in ('conf_path', 'prefix', 'suffix')):\n\nThis makes sure that the default element exists, and that each of the keys you're interested in has a Truthy value (I.E. not None or '').\n"
] | [
1
] | [] | [] | [
"dictionary",
"operating_system",
"pathlib",
"python",
"tomlkit"
] | stackoverflow_0074427500_dictionary_operating_system_pathlib_python_tomlkit.txt |
Q:
Use selenium for find element
I would like to take the word "buy"
browser.find_element_by_xpath("//*[@id='js-commentaire']")
print(commentaire)
and i also did
browser.find_element_by_id("js-commentaire")
print(commentaire)
This the source code
"div class="col-6 form-control form-control-sm overflow-auto" id="j... | Use selenium for find element | I would like to take the word "buy"
browser.find_element_by_xpath("//*[@id='js-commentaire']")
print(commentaire)
and i also did
browser.find_element_by_id("js-commentaire")
print(commentaire)
This the source code
"div class="col-6 form-control form-control-sm overflow-auto" id="js-commentaire"> buy</div"
| [
"You will need following libs:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nAnd then try this:\nmy_element = WebDriverWait(driver, 20).until(EC.presence_of_el... | [
0,
0
] | [] | [] | [
"get",
"python",
"selenium"
] | stackoverflow_0074423270_get_python_selenium.txt |
Q:
Google Compute Engine VM - set up SSH tunnel through Python using google cloud API?
I'm able to use the following command to create a temporary SSH tunnel to my GCE VM through the terminal:
gcloud compute ssh tunnel --zone=us-central1-a -- -NL 5000:localhost:5000
What I'm trying to determine is whether this is al... | Google Compute Engine VM - set up SSH tunnel through Python using google cloud API? | I'm able to use the following command to create a temporary SSH tunnel to my GCE VM through the terminal:
gcloud compute ssh tunnel --zone=us-central1-a -- -NL 5000:localhost:5000
What I'm trying to determine is whether this is also possible through the Google Cloud Python API using the google.cloud.compute_v1.VpnTunn... | [
"As clarified by John in the comments; the API is not meant for this task. Instead, I was able to use the sshtunnel library to simply replicate the behavior of the gcloud command:\nfrom sshtunnel import SSHTunnelForwarder\n\nserver = SSHTunnelForwarder(\n \"<server_ip>\",\n ssh_username=\"<username>\",\n l... | [
1
] | [] | [] | [
"google_compute_engine",
"python",
"ssh_tunnel"
] | stackoverflow_0074426172_google_compute_engine_python_ssh_tunnel.txt |
Q:
How to transform and get coordinates/shapes from results of MMDetection?
Official demo shows we could use show_result(img, result, out_file='result.jpg') api to draw results on a picture.
model = init_detector('configs/any-config.py', 'checkpoints/any-checkpoints.pth', device='cpu')
results = inference_detector(mo... | How to transform and get coordinates/shapes from results of MMDetection? | Official demo shows we could use show_result(img, result, out_file='result.jpg') api to draw results on a picture.
model = init_detector('configs/any-config.py', 'checkpoints/any-checkpoints.pth', device='cpu')
results = inference_detector(model, 'some_pic.png')
model.show_result('some_pic.png', results, 'some_pic_resu... | [
"Okay that, I combined several methods and got a usable method. \nIf you guys have a better way please let me know.\nconvert_polygon:\n# this method combined:\n# mmdetection.mmdet.models.detectors.base.BaseDetector.show_result\n# open-mmlab\\Lib\\site-packages\\mmdet\\core\\visualization\\image.py imshow_det_bboxes... | [
0
] | [] | [] | [
"artificial_intelligence",
"computer_vision",
"python"
] | stackoverflow_0074341574_artificial_intelligence_computer_vision_python.txt |
Q:
Calculate conditional probabilities in pandas
I'm trying to calculate a conditional response probabilities when aggregating my dataset. Take the following toy example:
import pandas as pd
gender = [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]
is_family = [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1]
treatment = [0,1,0,1,0,1,0,1,0,1,0,1,... | Calculate conditional probabilities in pandas | I'm trying to calculate a conditional response probabilities when aggregating my dataset. Take the following toy example:
import pandas as pd
gender = [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1]
is_family = [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1]
treatment = [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]
response = [1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,... | [
"IIUC, use a double groupby:\n(df.groupby(by=['gender', 'treatment', 'response'],\n as_index=False)\n ['num_rows'].sum()\n .assign(resp_prob=lambda d: d['num_rows'].div(\n d.groupby(['gender', 'treatment'])\n ['num_rows'].transform('sum'))... | [
3,
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0073501348_pandas_python.txt |
Q:
python: What does nan_policy=omit do for scipy.stat.spearmanr
scipy.stats.spearmanr([1,2,3,4,1],[1,2,2,1,np.nan],nan_policy='omit')
it will give a spearman correlation of 0.349999
My understanding is that nan_policy ='omit' will discard all the pairs which have nan. If that's the case, the results should be the s... | python: What does nan_policy=omit do for scipy.stat.spearmanr | scipy.stats.spearmanr([1,2,3,4,1],[1,2,2,1,np.nan],nan_policy='omit')
it will give a spearman correlation of 0.349999
My understanding is that nan_policy ='omit' will discard all the pairs which have nan. If that's the case, the results should be the same as scipy.stats.spearmanr([1,2,3,4],[1,2,2,1])
However, it gives... | [
"I tried to run your code, it gives me cero correlation (R=0.0).\nI use this function and you are understanding well nan_policy ='omit'.\nIf you don't need the p-value of the correlation I would sugest using .corr(method = 'spearman') from pandas library. By default it excludes NA/null values. \nOfficial Documentat... | [
0,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0051479809_python_scipy.txt |
Q:
Find minimum of the entire dataframe?
I have a dataFrame like:
a b
0 4 7
1 3 2
2 1 9
3 3 4
4 2 Nan
I need to calculate min, mean, std, sum, for all dataFrame as a single list of numbers. (e.g minimum here is 1)
EDIT: The data may have Nans or different size columns.
df.to_numpy().mean()
Produ... | Find minimum of the entire dataframe? | I have a dataFrame like:
a b
0 4 7
1 3 2
2 1 9
3 3 4
4 2 Nan
I need to calculate min, mean, std, sum, for all dataFrame as a single list of numbers. (e.g minimum here is 1)
EDIT: The data may have Nans or different size columns.
df.to_numpy().mean()
Produce Nan, because there are nans in the array... | [
"Pandas solution is with reshape by DataFrame.stack and Series.agg:\ndef std_ddof0(x):\n return x.std(ddof=0)\n\nout = df.stack().agg(['mean','sum',std_ddof0, 'min'])\nprint (out)\nmean 3.888889\nsum 35.000000\nstd_ddof0 2.424158\nmin 1.000000\ndtype: float64\n\nNumpy solution wit... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074425021_pandas_python.txt |
Q:
Plot multiple dataframe in a plot with facet_wrap
I have a dataset df that looks like this:
ID Week VarA VarB VarC VarD
s001 w1 2 5 4 7
s001 w2 4 5 2 3
s001 w3 7 2 0 1
s002 w1 4 0 9 8
s002 w2... | Plot multiple dataframe in a plot with facet_wrap | I have a dataset df that looks like this:
ID Week VarA VarB VarC VarD
s001 w1 2 5 4 7
s001 w2 4 5 2 3
s001 w3 7 2 0 1
s002 w1 4 0 9 8
s002 w2 1 5 2 5
s002 w3 7 ... | [
"The issue with the question is a bug that would be reproduced by the following code. The bug has been fixed and the next version of plotnine will have the fix.\nimport pandas as pd\nfrom plotnine import *\n\ndf1 = pd.DataFrame({\n 'x': list(\"abc\"),\n 'y': [1, 2, 3],\n 'g': list(\"AAA\")\n\n})\n\ndf2 = p... | [
2,
0
] | [] | [] | [
"plotnine",
"python",
"python_ggplot"
] | stackoverflow_0074369454_plotnine_python_python_ggplot.txt |
Q:
Discord.py, if statement not passing despite being true
When I attempt to compare the current users game to a predetermined string, it fails to pass even if they are the same thing.
@client.event
async def on_presence_update(prev,cur):
print(cur.activity)
if cur.activity=='RimWorld':
print('Playing RW')
... | Discord.py, if statement not passing despite being true | When I attempt to compare the current users game to a predetermined string, it fails to pass even if they are the same thing.
@client.event
async def on_presence_update(prev,cur):
print(cur.activity)
if cur.activity=='RimWorld':
print('Playing RW')
await message.send(f'{cur.mention} is playing RimWorld, a c... | [
"You are comparing a discord.Activity instance, that isn‘t a string. To compare it, you have to use the name attribute of the Activity instance\n"
] | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074427460_discord.py_python.txt |
Q:
RuntimeError: CUDA error: no kernel image is available for execution on the device after model.cuda()
I am working on this model:
class Model(torch.nn.Module):
def __init__(self, sizes, config):
super(Model, self).__init__()
self.lstm = []
for i in range(len(sizes) - 2):
se... | RuntimeError: CUDA error: no kernel image is available for execution on the device after model.cuda() | I am working on this model:
class Model(torch.nn.Module):
def __init__(self, sizes, config):
super(Model, self).__init__()
self.lstm = []
for i in range(len(sizes) - 2):
self.lstm.append(LSTM(sizes[i], sizes[i+1], num_layers=8))
self.lstm.append(torch.nn.Linear(sizes[-2]... | [
"I checked the latest torch and torchvision version with cuda from the given link. Stable versions list: https://download.pytorch.org/whl/cu113/torch_stable.html\nBelow versions solved the error,\npip install torch==1.11.0+cu113 torchvision==0.12.0+cu113 -f https://download.pytorch.org/whl/torch_stable.html\nRefere... | [
5,
3,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0069968477_python_pytorch.txt |
Q:
ValueError: Unable to create dataset (name already exists) when using ModelCheckpoint to save my model
I am trying to run the Keras Offical Code Example "Image classification with Swin Transformers". The code works fine at first, but after I added a ModelCheckpoint to save the hdf5 model in the callbacks argueme... | ValueError: Unable to create dataset (name already exists) when using ModelCheckpoint to save my model | I am trying to run the Keras Offical Code Example "Image classification with Swin Transformers". The code works fine at first, but after I added a ModelCheckpoint to save the hdf5 model in the callbacks arguement of the model.fit method{i.e. model.fit(..., callbacks=[ModelCheckpoint(...)], ..., )}, I received the fol... | [] | [] | [
"If you using TensorFlow version 2.0 or above, you can try to change the \".hdf5\" files to \".tf\". Having met the same problem, I changed file extensions as follows:\nsave_dir = os.path.join(os.getcwd(), \"save_models\")\nfilepath = \"cnn_cnn_weights.{epoch:02d}-{val_loss:.4f}--0fold.tf\"\ncheckpoint = ModelChe... | [
-1
] | [
"keras",
"python",
"tensorflow",
"transformer_model"
] | stackoverflow_0072776335_keras_python_tensorflow_transformer_model.txt |
Q:
AttributeError: 'Button' object has no attribute 'response'
class MyView(View):
@discord.ui.button(label = 'Ping',style=discord.ButtonStyle.red)
async def ping_button_callback(self, button, interaction):
await interaction.response.send_message(embed = pingembed)
It was working fine, until today ... | AttributeError: 'Button' object has no attribute 'response' | class MyView(View):
@discord.ui.button(label = 'Ping',style=discord.ButtonStyle.red)
async def ping_button_callback(self, button, interaction):
await interaction.response.send_message(embed = pingembed)
It was working fine, until today when I tryed to execute the command and it gave me that error
Att... | [
"You swapped the arguments. The first argument (in this case button) is the Interaction instance. The second one (in this case interaction) is the Button instance\n"
] | [
3
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074426018_discord.py_python.txt |
Q:
Discord Bot Post requests to Browser
I would like to create a bot that sends a request (post) via a command /refresh with certain information so where I say /refresh test and it then sends a POST with certain information that is given for the time being.
Like this
client_id=CLIENT_ID_HERE&client_secret=CLIENT_SECR... | Discord Bot Post requests to Browser | I would like to create a bot that sends a request (post) via a command /refresh with certain information so where I say /refresh test and it then sends a POST with certain information that is given for the time being.
Like this
client_id=CLIENT_ID_HERE&client_secret=CLIENT_SECRET_HERE&refresh_token=REFRESH_TOKEN_HERE&g... | [
"So I reread this now many times. If I understood it right now, you just want to post something to, for example https://example.com/post\nIf so, then use aiohttp and create a client session and post it.\nimport aiohttp\n\n#this in your command\nasync with aiohttp.ClientSession() as session:\n await session.post(... | [
2
] | [] | [] | [
"discord.py",
"minecraft",
"python"
] | stackoverflow_0074425861_discord.py_minecraft_python.txt |
Q:
How do I serially rename multiple files at once in shell scripting (or python)?
I have this dir with multiple *.mp4 files. I would like to add serial no. in order as a prefix, still keeping the original name unchanged. I'm quite new to shell scripting, (also couldnt find a proper answer on google) so It would be n... | How do I serially rename multiple files at once in shell scripting (or python)? | I have this dir with multiple *.mp4 files. I would like to add serial no. in order as a prefix, still keeping the original name unchanged. I'm quite new to shell scripting, (also couldnt find a proper answer on google) so It would be nice if someone explains it to me. If it can be done with python, It would be even bet... | [
"In Python, several ways to do this, for example:\nimport os\n\nos.chdir(path) # Enter your desired path like r\"D:\\My Articles\\Phd\\ACCRUFER\"\nallFiles = os.listdir()\n\nmp4Files = [file for file in allfiles if file.endswith('.mp4')]\nfor i, file in enumerate(files, 1):\n index = str(i).zfill(2) # to mak... | [
0
] | [] | [] | [
"batch_rename",
"file_rename",
"python",
"sh",
"shell"
] | stackoverflow_0074427622_batch_rename_file_rename_python_sh_shell.txt |
Q:
I am trying this below code to find the 'Images' button and click on that using python in Pycharm. But its showing some errors
C:\Users\PWTTS\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\PWTTS\PycharmProjects\pythonProject\main.py
C:\Users\PWTTS\PycharmProjects\pythonProject\main.py:11: Deprecat... | I am trying this below code to find the 'Images' button and click on that using python in Pycharm. But its showing some errors | C:\Users\PWTTS\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\PWTTS\PycharmProjects\pythonProject\main.py
C:\Users\PWTTS\PycharmProjects\pythonProject\main.py:11: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome(r"D:\driver\chromedrive... | [
"The error is in the stack trace:\nMessage: no such element: Unable to locate element: {\"method\":\"css selector\",\"selector\":\"[name=\"Images\"]\"}\n\nFirst of all, which element are you trying to select? I don't see an element called \"images\" on Google. That would explain the error.\nIf such an element does... | [
0
] | [] | [] | [
"findelement",
"pycharm",
"python",
"selenium"
] | stackoverflow_0074427886_findelement_pycharm_python_selenium.txt |
Q:
Opencv draws numpy.zeros as a gray image
I'm struggling with understanding how opencv interprets numpy arrays.
import cv2
import numpy as np
if __name__ == '__main__':
size = (w, h, channels) = (100, 100, 1)
img = np.zeros(size, np.int8)
cv2.imshow('result', img), cv2.waitKey(0)
cv2.destroyAllWind... | Opencv draws numpy.zeros as a gray image | I'm struggling with understanding how opencv interprets numpy arrays.
import cv2
import numpy as np
if __name__ == '__main__':
size = (w, h, channels) = (100, 100, 1)
img = np.zeros(size, np.int8)
cv2.imshow('result', img), cv2.waitKey(0)
cv2.destroyAllWindows()
Grayscale black 100x100 image, right?
N... | [
"Ok, the crucial part is dtype. I've chosen np.int8. When I use np.uint8, it is black.\nSuprisingly, when dtype=np.int8, zeros are interpreted as 127(or 128)!\nI expected that zero is still zero, no matter if it is signed or unsigned.\n",
"For a BGR image,\nimg = np.zeros([height, width, 3], dtype=np.uint8)\n\n",... | [
13,
3,
0
] | [] | [] | [
"numpy",
"opencv",
"python"
] | stackoverflow_0018945785_numpy_opencv_python.txt |
Q:
Change the file name by using python
I would like to change the file name in the folder, there are jpg file but corrupted with product id number. I tried to rename it and delete the string after ".jpg" by using python, here is the code, but there is no any change.
Do you guys have any suggestion?
import os
path=i... | Change the file name by using python | I would like to change the file name in the folder, there are jpg file but corrupted with product id number. I tried to rename it and delete the string after ".jpg" by using python, here is the code, but there is no any change.
Do you guys have any suggestion?
import os
path=input('C:\\Users\\pengoul\\Downloads\\Files... | [
"if you input path from user, python automatically use \\ instead of \\ so you shouldn't use \\ while input. So I suggest one of these two ways:\npath = input('C:\\Users\\pengoul\\Downloads\\Files\\PIC')\n\nor\npath = 'C:\\\\Users\\\\pengoul\\\\Downloads\\\\Files\\\\PIC'\n\nor\npath = r'C:\\Users\\pengoul\\Download... | [
0
] | [] | [] | [
"batch_rename",
"file_rename",
"image",
"jpeg",
"python"
] | stackoverflow_0074426919_batch_rename_file_rename_image_jpeg_python.txt |
Q:
Trying to print the position of the element on the linked list, it seems to just print PS
trying to print the position of an element on the linked list via using a counter variable hop and returning it on success.
class Node_or_Element:
def __init__(self,data): # Function to initialize the element's or the no... | Trying to print the position of the element on the linked list, it seems to just print PS | trying to print the position of an element on the linked list via using a counter variable hop and returning it on success.
class Node_or_Element:
def __init__(self,data): # Function to initialize the element's or the nodes
self.data=data
self.next=None
class Linked_list:
def __init__(self):
... | [
"Yours pos function is the problem. You see, there is while(curr==None) but that never happens since curr=self.head...\nI would advice you something like this:\ndef pos(self, l_data):\n curr = self.head\n index = 0\n\n while(True):\n if curr.data == l_data:\n return index\n elif curr.next !=... | [
1
] | [] | [] | [
"data_structures",
"linked_list",
"python"
] | stackoverflow_0074427985_data_structures_linked_list_python.txt |
Q:
Index out of range when printing adjacent letter
I have string which is as follows below
stg = 'AVBFGHJ'
I want the adjacent letter to be printed as expected below
AV
VB
BF
FG
GH
HJ
J None
I tried below code but throws me error like Index out of Range
My code :
for i in range(len(stg)):
print(stg[i],st... | Index out of range when printing adjacent letter | I have string which is as follows below
stg = 'AVBFGHJ'
I want the adjacent letter to be printed as expected below
AV
VB
BF
FG
GH
HJ
J None
I tried below code but throws me error like Index out of Range
My code :
for i in range(len(stg)):
print(stg[i],stg[i+1])
| [
"This is meant to happen. You are accessing an index that is out of the range of the string.\nIf you really want to do it this way however, you can do something like this\nstg = 'AVBFGHJ'\nfor i in range(len(stg)):\n if (i + 1) < len(stg):\n print(stg[i],stg[i+1])\n else:\n print(stg[i], None)\n... | [
1,
1
] | [] | [] | [
"for_loop",
"indexoutofrangeexception",
"list",
"python",
"python_3.x"
] | stackoverflow_0074427904_for_loop_indexoutofrangeexception_list_python_python_3.x.txt |
Q:
count function only outputing 1 python
Using return only gives me the number 1, even though its found 796 times using a print statement, just wondering what I'm doing wrong whether its indentation errors or something like that.
def findSubstringInTweets(userName, tweetFile, substring):
import csv
# op... | count function only outputing 1 python | Using return only gives me the number 1, even though its found 796 times using a print statement, just wondering what I'm doing wrong whether its indentation errors or something like that.
def findSubstringInTweets(userName, tweetFile, substring):
import csv
# open file
myFile = open(tweetFile,"r")
... | [
"As some of the comments have noted, the return statement causes your loops to exit once that condition is met.\nYou can move the return statement outside your loops like below, to return the target output once all your loops have completed:\nimport csv\n# open file\nmyFile = open(tweetFile,\"r\")\n# create csv rea... | [
0
] | [] | [] | [
"printing",
"python",
"return"
] | stackoverflow_0074427165_printing_python_return.txt |
Q:
How to compute MD5 hash for a file on the remote server using paramiko
I have achieved how to download a file using SFTP and generate an MD5 hash of the downloaded file locally.
I am trying to upload a file to an SFTP Server and generate its MD5 hash when it's on the server and then download the file and its MD5 h... | How to compute MD5 hash for a file on the remote server using paramiko | I have achieved how to download a file using SFTP and generate an MD5 hash of the downloaded file locally.
I am trying to upload a file to an SFTP Server and generate its MD5 hash when it's on the server and then download the file and its MD5 hash from the remote server.
How can I computer the MD5 hash on the remote SF... | [
"Very few FTP/SFTP servers support calculation of remote file checksum.\nYou can try first (my) WinSCP GUI SFTP/FTP client to see if your FTP/SFTP server does. WinSCP supports many standard and non-standard APIs for checksum calculation. So if your server does support such API, WinSCP should be able to make use of ... | [
0
] | [] | [] | [
"ftp",
"pysftp",
"python",
"sftp"
] | stackoverflow_0074425783_ftp_pysftp_python_sftp.txt |
Q:
Python - Defining variables with dictionaries
So I'm trying to store a couple of conditional dictionaries in a couple of variables.
to_dict = ['a', 'b', 'c']
vars = ['x', 'y', 'z']
for i, j in zip(enumerate(to_dict, start=1), enumerate(vars, start=1)):
j[1]=dict(some_calculation of i[1])
The above says, 'tup... | Python - Defining variables with dictionaries | So I'm trying to store a couple of conditional dictionaries in a couple of variables.
to_dict = ['a', 'b', 'c']
vars = ['x', 'y', 'z']
for i, j in zip(enumerate(to_dict, start=1), enumerate(vars, start=1)):
j[1]=dict(some_calculation of i[1])
The above says, 'tuple object doesn't support item assignment.'
Also tr... | [
"You shouldn't try to assign variables dynamically, this is an anti-pattern.\nUse your dictionary:\nout = {k: some_calculation(x) for k, x in zip(vars_, to_dict)}\n\nOutput (here leaving the values unchanged):\n{'x': 'a', 'y': 'b', 'z': 'c'}\n\nThen use out['x'] to access the output of your function on 'x'.\nSide n... | [
1
] | [] | [] | [
"analysis",
"jupyter_notebook",
"python"
] | stackoverflow_0074428186_analysis_jupyter_notebook_python.txt |
Q:
Weird 1d shape result on pytorch 3d ResNet
I have a 3dResNet model from PyTorch. I also commented out the flatten line in the resnet.py source code so my output shouldn't be 1D.
Here is the code I have:
class VideoModel(nn.Module):
def __init__(self,num_channels=3):
super(VideoModel, self).__init__()
... | Weird 1d shape result on pytorch 3d ResNet | I have a 3dResNet model from PyTorch. I also commented out the flatten line in the resnet.py source code so my output shouldn't be 1D.
Here is the code I have:
class VideoModel(nn.Module):
def __init__(self,num_channels=3):
super(VideoModel, self).__init__()
self.r2plus1d = models.video.r2plus1d_18(... | [
"The cause is the AdaptiveAvgPool3d layer right before the flatten step. It is called with the argument output_size=(1,1,1), and so pools the last three dimensions to (1,1,1) regardless of their original dimensions.\nIn your case, the output after the average pool has the shape (1,512,1,1,1), after flatten has the ... | [
1
] | [] | [] | [
"deep_learning",
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0074427579_deep_learning_machine_learning_python_pytorch.txt |
Q:
I want to send posts with captcha validation in flask, but when sending, the captcha is reloaded and does not match the one entered in the form
To put it simply: I have code that sends and saves posts using flask and I have code that generates a captcha. Both work separately, I don't know how to make them work tog... | I want to send posts with captcha validation in flask, but when sending, the captcha is reloaded and does not match the one entered in the form | To put it simply: I have code that sends and saves posts using flask and I have code that generates a captcha. Both work separately, I don't know how to make them work together.
Code from flask tutorial:
@bp.route("/create", methods=("GET", "POST"))
@auth.login_required
def create():
"""Create a new post for the cu... | [
"https://pypi.org/project/flask-session-captcha/\ni had also same problem then i use this option its better for captcha validation actually\nfirst install the package and then import to your code\nthis codes you need to add it in your app.py file\n# import the package\nfrom flask_session_captcha import FlaskSession... | [
0
] | [] | [] | [
"captcha",
"flask",
"jinja2",
"python",
"python_3.x"
] | stackoverflow_0072182749_captcha_flask_jinja2_python_python_3.x.txt |
Q:
How to read only the number from json file with python - discord.py?
I have a file with the following content:
{
"Youtube tutorial bot test": {
"ivan4o assistant": 0,
"kurwa qvor": 1
}
}
And I want it to read only the number.
I've tried with this code:
def warns_check(member: discord.Membe... | How to read only the number from json file with python - discord.py? | I have a file with the following content:
{
"Youtube tutorial bot test": {
"ivan4o assistant": 0,
"kurwa qvor": 1
}
}
And I want it to read only the number.
I've tried with this code:
def warns_check(member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
... | [
"\nI want it to read only the number.\n\nIn order to fetch the number you would need to access it using\nwarns[\"Youtube tutorial bot test\"][member.name]\n\n\nAnd it reads the whole file. How to fix this?\n\nYou are reading essentially a text file so you always need to load the whole file. I would suggest using a ... | [
1,
1,
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074422749_discord.py_python.txt |
Q:
Creating day after long weekend flag in pandas
I want to create a new column in pandas data frame 'day_after_long_weekend' based on the conditions shown in the image.
Sat and Sun are default holidays
condition 1 - if Fri is a holiday (national/provincial) then Monday is the day after long weekend.
condition 2 - i... | Creating day after long weekend flag in pandas | I want to create a new column in pandas data frame 'day_after_long_weekend' based on the conditions shown in the image.
Sat and Sun are default holidays
condition 1 - if Fri is a holiday (national/provincial) then Monday is the day after long weekend.
condition 2 - if Fri and following Monday is a holiday then Tuesday... | [
"Use masks and a rolling sum:\n# is a weekend?\nm1 = df['day_of week'].isin(['Sat', 'Sun'])\n# is a holiday?\nm2 = df[['national_holiday', 'provincial_holiday']].eq(1).any(axis=1)\n\n# weekend or holiday\nm = (m1|m2)\n\n# is there 3 weekend days or holidays in the last 3 days\n# and today is a working day?\ndf['day... | [
3,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074115409_pandas_python.txt |
Q:
Standardize large Pyspark dataframe using scipy Z-score
I have a py-spark code running in Azure databricks. I have a spark dataframe with 20 numerical columns, named column1, column2, ...column20.
I have to calculate the Zscore(from scipy.stats import zscore) of these 20 columns, for that I am reading these 20 col... | Standardize large Pyspark dataframe using scipy Z-score | I have a py-spark code running in Azure databricks. I have a spark dataframe with 20 numerical columns, named column1, column2, ...column20.
I have to calculate the Zscore(from scipy.stats import zscore) of these 20 columns, for that I am reading these 20 columns as numpy array.
But this collect is causing the spark cl... | [
"To keep all your results in Spark and avoid the collect step, you should use a for-loop and aggregate functions over the entire dataframe:\nimport pyspark.sql.functions as F\nfrom pyspark.sql.window import Window\n\nw = Window.partitionBy()\n\nfor c in df_spark.columns:\n df_spark = df_spark.withColumn(c, (F.col(... | [
1,
0
] | [] | [] | [
"apache_spark",
"databricks",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074421484_apache_spark_databricks_dataframe_pyspark_python.txt |
Q:
How to fix 'Command errored out with exit status 1' with pip install
I'm experiencing some trouble installing pytype with pip install as shown here:
OS: CentOS 7
Python: Python 3.6
Pip: 20.0.2
$ pip3 install pytype
Collecting pytype
Using cached pytype-2020.2.20.tar.gz (1.1 MB)
Installing build dependencies: s... | How to fix 'Command errored out with exit status 1' with pip install | I'm experiencing some trouble installing pytype with pip install as shown here:
OS: CentOS 7
Python: Python 3.6
Pip: 20.0.2
$ pip3 install pytype
Collecting pytype
Using cached pytype-2020.2.20.tar.gz (1.1 MB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Gett... | [
"That package directory find: comes from setup.cfg; it's actually not a package directory but an instruction for setuptools to find a list of subdirectories to install.\nI successfully installed the package for Python 2.7 and 3.5. So my advice is to upgrade pip and setuptools\npip install -U pip setuptools\n\nand ... | [
12,
0
] | [
"When I updated Python to version 3.9 then I was unable to install Pandas and NumPy in PyCharm which was giving me an error, 'Command errored out with exit status 1'.\nThe solution is to install an old version of Python 3.8.5 and use that as the interpreter.\n"
] | [
-1
] | [
"centos7",
"pip",
"python",
"pytype"
] | stackoverflow_0060709574_centos7_pip_python_pytype.txt |
Q:
Returning list as integer gives TypeError: 'type' object is not iterable
sum = []
def s(d):
d = list[int]
sum = []
for i in d:
sum += i
return(sum)
s([1, 2, 3])
Python gives me the following message:
TypeError: 'type' object is not iterable.
How can I make the code work?
A:
As first ... | Returning list as integer gives TypeError: 'type' object is not iterable | sum = []
def s(d):
d = list[int]
sum = []
for i in d:
sum += i
return(sum)
s([1, 2, 3])
Python gives me the following message:
TypeError: 'type' object is not iterable.
How can I make the code work?
| [
"\nAs first commentator said, you are iterating a list composed of one element: a type int (which is not iterable, as the error message states). If you trying to specify a type of argument d in your function, you should use code like that:\n\ndef s(d: list[int]):\n ...\n\n\nAlso if you trying to find a sum of ele... | [
1,
0
] | [] | [] | [
"error_handling",
"git_checkout",
"python",
"solver"
] | stackoverflow_0074205398_error_handling_git_checkout_python_solver.txt |
Q:
python/pandas: convert month int to month name
Most of the info I found was not in python>pandas>dataframe hence the question.
I want to transform an integer between 1 and 12 into an abbrieviated month name.
I have a df which looks like:
client Month
1 sss 02
2 yyy 12
3 www 06
I want the df to look... | python/pandas: convert month int to month name | Most of the info I found was not in python>pandas>dataframe hence the question.
I want to transform an integer between 1 and 12 into an abbrieviated month name.
I have a df which looks like:
client Month
1 sss 02
2 yyy 12
3 www 06
I want the df to look like this:
client Month
1 sss Feb
2 yyy ... | [
"You can do this efficiently with combining calendar.month_abbr and df[col].apply()\nimport calendar\ndf['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])\n\n",
"Since the abbreviated month names is the first three letters of their full names, we could first convert the Month column to datetime and t... | [
57,
24,
10,
9,
6,
6,
5,
5,
4,
2,
2,
1,
0
] | [] | [] | [
"dataframe",
"date",
"monthcalendar",
"pandas",
"python"
] | stackoverflow_0037625334_dataframe_date_monthcalendar_pandas_python.txt |
Q:
x,y parameters in plot() to be treated as RGB or 2D scalar in imshow()
in the description of matplotlib.axes.Axes.plot it can be found that to plot data according to the parameters provided in terms of x, y, z; Depending on the dataset type we want to plot. The goal of this program is to plot data using matplotli... | x,y parameters in plot() to be treated as RGB or 2D scalar in imshow() | in the description of matplotlib.axes.Axes.plot it can be found that to plot data according to the parameters provided in terms of x, y, z; Depending on the dataset type we want to plot. The goal of this program is to plot data using matplotlib.Axes.axes.imshow to get images.
How could I do it taking into account that... | [
"You cold use pcolormesh for the plotting.\nDoes something like this work?\nimport numpy as np \nimport matplotlib.pyplot as plt \n\nfig, ax = plt.subplots(constrained_layout=True)\n\nnum_series = 1000\nnum_points = 100\n\nx = np.linspace(0, 4 * np.pi, num_points) \ny = np.arange(num_series)\nZ = np.cumsum(np.rando... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074428263_matplotlib_python.txt |
Q:
Handle a gunicorn worker termination from the FastAPI
A FastAPI application restarts after gunicorn worker timeout. Is it possible to handle such a signal from the FastAPI application (shutdown signal doesn't help) before the application restart?
The problem is that some function exceeds the default time limit (30... | Handle a gunicorn worker termination from the FastAPI | A FastAPI application restarts after gunicorn worker timeout. Is it possible to handle such a signal from the FastAPI application (shutdown signal doesn't help) before the application restart?
The problem is that some function exceeds the default time limit (30 seconds), which is ok, and we want to handle the situation... | [
"Gunicorn sends a SIGABRT, signal 6, to a worker process when timed out.\nThus a process, FastAPI in this case, needs to catch the signal, but on_event cannot because FastAPI(Starlette) event doesn't mean signals.\nBut there is a simple solution, Gunicorn server hooks.\ndef worker_abort(worker):\n ...\n\n\nCalled... | [
0
] | [] | [] | [
"fastapi",
"python",
"shutdown",
"signals",
"uvicorn"
] | stackoverflow_0074209575_fastapi_python_shutdown_signals_uvicorn.txt |
Q:
loading and saving a JPEG image results in different file content
Here's a script that reads a JPG image and then writes 2 JPG images:
import cv2
# https://github.com/opencv/opencv/blob/master/samples/data/baboon.jpg
input_path = './baboon.jpg'
# Read image
im = cv2.imread(input_path)
# Write image using defau... | loading and saving a JPEG image results in different file content | Here's a script that reads a JPG image and then writes 2 JPG images:
import cv2
# https://github.com/opencv/opencv/blob/master/samples/data/baboon.jpg
input_path = './baboon.jpg'
# Read image
im = cv2.imread(input_path)
# Write image using default quality (95)
cv2.imwrite('./baboon_out.jpg', im)
# Write image usin... | [
"It's a simplification, but the image will probably always change the checksum if you're reading a JPEG image because it's a lossy format being re-encoded and read by an avalanching hash and definitely will if you do any meaningful work on it, even if (especially if) you directly manipulated the bits of the file ra... | [
2,
1
] | [] | [] | [
"binary",
"image_compression",
"python",
"python_imaging_library"
] | stackoverflow_0074427088_binary_image_compression_python_python_imaging_library.txt |
Q:
pandas how to get sorted value in groupby object
I have a dataframe
df =
Col Val
a. 8
a. 9
c. 4
c. 0
d. 3
d. 9
I want to sort by Val of the smallest value within group and then foreach row get the index of the groupby Col
So the new df will df
df_new =
Col Val Idx
c. 4. 0
c. 0. 0
d. 3. 1
d... | pandas how to get sorted value in groupby object | I have a dataframe
df =
Col Val
a. 8
a. 9
c. 4
c. 0
d. 3
d. 9
I want to sort by Val of the smallest value within group and then foreach row get the index of the groupby Col
So the new df will df
df_new =
Col Val Idx
c. 4. 0
c. 0. 0
d. 3. 1
d. 9. 1
a. 8. 2
a. 9. 2
What is the best way t... | [
"Use GroupBy.transform with min to new column, then for starting by 1 with range use Series.rank and then sorting by 2 columns - if same minimal value per multiple groups get same groups by Col together:\ndf['Idx'] = (df.groupby('Col')['Val'].transform('min')\n .rank(method='dense').astype(int).sub(1)... | [
1
] | [] | [] | [
"data_munging",
"data_science",
"group_by",
"pandas",
"python"
] | stackoverflow_0074428514_data_munging_data_science_group_by_pandas_python.txt |
Q:
Looping option selection in python
I bought a TI-84 Plus CE with python support and thought I'd have a play at trying to learn python to make cheat sheets etc.
Any way I have this code so far, what I'm struggling to understand is how to loop it so I can keep entering a selection instead of it just running and exit... | Looping option selection in python | I bought a TI-84 Plus CE with python support and thought I'd have a play at trying to learn python to make cheat sheets etc.
Any way I have this code so far, what I'm struggling to understand is how to loop it so I can keep entering a selection instead of it just running and exiting.
Would appreciate any advice etc
I h... | [
"If I understood your question correctly, you want to have an infinite loop. It can be achieved by while True:\nwhile(True):\n choice = input(\"Please select: \")\n \n val = options.get(choice)\n if val is not None:\n action = val[1]\n else:\n action = invalid_opt\n\n action()\n\nal... | [
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074428259_loops_python.txt |
Q:
pytest fixture runs for class instead of each tests separately
Could you explain to me please why fixture with scope function(which is supposed to run anew for each test) runs for the whole test class?
@pytest.fixture(scope="function")
def application_with_assigned_task_id(api, db, application_with_tasks_id, set_u... | pytest fixture runs for class instead of each tests separately | Could you explain to me please why fixture with scope function(which is supposed to run anew for each test) runs for the whole test class?
@pytest.fixture(scope="function")
def application_with_assigned_task_id(api, db, application_with_tasks_id, set_user_with_st_types):
with allure.step("ищу задание по по id заявк... | [
"This simple example shows clearly that the tests are executed for each function and that's all (the output file will contain two lines). If it is not the case for you, please follow hoefling's comment and create a reproducible example (your code is both not complete and contains too many irrelevant things).\nimpor... | [
0
] | [] | [] | [
"fixtures",
"pytest",
"python",
"scope",
"testing"
] | stackoverflow_0074359428_fixtures_pytest_python_scope_testing.txt |
Q:
"SyntaxError: cannot assign to expression" and "SyntaxError: invalid decimal literal" for class name with spaces and numbers inside a div
I'm trying to make a web scraper for a website to let me know when an new item is available, but I encountered this problem in my code when trying to ask it to print me the URL:... | "SyntaxError: cannot assign to expression" and "SyntaxError: invalid decimal literal" for class name with spaces and numbers inside a div | I'm trying to make a web scraper for a website to let me know when an new item is available, but I encountered this problem in my code when trying to ask it to print me the URL:
import requests
from bs4 import BeautifulSoup
import webbrowser
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 13_0_1)... | [
"This is one way of obtaining the data - as a dataframe - and then you can scrape that endpoint at regular intervals, like every 3 hours - and compare the results with something like first_df.compare(second_df):\nimport requests\nimport pandas as pd\nheaders = {\n 'accept': 'application/json, text/plain, */*',\n... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x",
"python_requests",
"web_scraping"
] | stackoverflow_0074427749_beautifulsoup_python_python_3.x_python_requests_web_scraping.txt |
Q:
How to update all but one python packages?
I've multiple python packages installed on my system. My update script calls pip-review --local --auto to update all the python packages. However, I don't want to update all packages. What I want is pip-review to update all packages except scons, since one of my programs ... | How to update all but one python packages? | I've multiple python packages installed on my system. My update script calls pip-review --local --auto to update all the python packages. However, I don't want to update all packages. What I want is pip-review to update all packages except scons, since one of my programs needs an older version of scons. Currently to do... | [
"Based on the comments and answers posted by other users, I've decided to go for the following piece of command to update all packages except scons:\npip-review --local --auto && python3 -m pip install -U scons==3.1.2\nThanks a lot to everyone for helping me out with this.\n"
] | [
0
] | [
"pip install -r $(grep -v '^ *#\\|^pkg1\\|^pkg2' requirements.txt | grep .)\n\nThis is a shell hack to exclude pkg1, pkg2, etc. from a pip install using requirements.txt, but you may want to modify it and see if it suits your purpose. But like the other guy said, use a virtualenv going forward.\n"
] | [
-1
] | [
"pip",
"python",
"python_3.8"
] | stackoverflow_0074274724_pip_python_python_3.8.txt |
Q:
PyQt5 QWebEngineView causes the whole window to go white/blank
I have this weird problem on Windows 10 with PyQt5 QWebEngineView.
When I delete self.webView = QtWebEngineWidgets.QWebEngineView(self.groupBox_4) from window_ui.py which is generated with pyuic5 app starts fine. When I add it back, whole window is ju... | PyQt5 QWebEngineView causes the whole window to go white/blank | I have this weird problem on Windows 10 with PyQt5 QWebEngineView.
When I delete self.webView = QtWebEngineWidgets.QWebEngineView(self.groupBox_4) from window_ui.py which is generated with pyuic5 app starts fine. When I add it back, whole window is just white.
However, my Windows 10 in VirtualBox works just fine. Also... | [
"export QTWEBENGINE_CHROMIUM_FLAGS=\"--no-sandbox\"\n"
] | [
0
] | [] | [] | [
"pyqt5",
"python",
"qtwebengine"
] | stackoverflow_0073808010_pyqt5_python_qtwebengine.txt |
Q:
Use managers in Factory-Boy for models
Use Factory-boy for retrieve operation without use the DB for testing case.
I have this simple model:
class Student(models.Model):
name = models.CharField(max_length=20) `
To get all: Student.objects.all()
With Factory-boy:
class StudentFactory(factory.django.DjangoModel... | Use managers in Factory-Boy for models | Use Factory-boy for retrieve operation without use the DB for testing case.
I have this simple model:
class Student(models.Model):
name = models.CharField(max_length=20) `
To get all: Student.objects.all()
With Factory-boy:
class StudentFactory(factory.django.DjangoModelFactory):
class Meta:
model = St... | [
"You may be looking for the methods create_batch and build_batch, depending on whether you want to save the newly generated instances in the test database or not.\nHere's an example which I copy-pasted and adapted from factory-boy documentation:\n# --- models.py\n\nclass StudentFactory(factory.django.DjangoModelFac... | [
1
] | [] | [] | [
"django",
"factory_boy",
"python",
"testing"
] | stackoverflow_0074337547_django_factory_boy_python_testing.txt |
Q:
Sqlalchemy query on multiple relationship between two tables
I am having trouble with the following setup of a sqlalchemy ORM connected to a postgresql db.
class Map(Base):
__tablename__ = "map"
id = Column(BigInteger, Sequence(name="myseq"), primary_key=True)
cmp_1_id = Column(BigInteger, ForeignKey(... | Sqlalchemy query on multiple relationship between two tables | I am having trouble with the following setup of a sqlalchemy ORM connected to a postgresql db.
class Map(Base):
__tablename__ = "map"
id = Column(BigInteger, Sequence(name="myseq"), primary_key=True)
cmp_1_id = Column(BigInteger, ForeignKey("component.id"))
cmp_2_id = Column(BigInteger, ForeignKey("com... | [
"After some thorough consulting of the extensive sqlalchemy docs I found some answers:\n\nTo my first question and the related query: in my ORM classes I did not specify the loading type of the data, leaving it at the default type \"lazy\". Therefore the other_attribute attribute's value is not loaded with the firs... | [
0
] | [] | [] | [
"orm",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074403833_orm_postgresql_python_sqlalchemy.txt |
Q:
Convert a text file with a particular format into dataframe
I am new to Pandas and thus I wanted to know if I can convert my text file with a particular format into a Pandas data frame. Below is my text file format
"FACT"|"FSYM"|"POSITION"|"INDIRECT_OPTIONS"|"REPORT"|"SOURCE"|"COMMENTS"|
"ABCX"|"VVG1"|2800000|7600... | Convert a text file with a particular format into dataframe | I am new to Pandas and thus I wanted to know if I can convert my text file with a particular format into a Pandas data frame. Below is my text file format
"FACT"|"FSYM"|"POSITION"|"INDIRECT_OPTIONS"|"REPORT"|"SOURCE"|"COMMENTS"|
"ABCX"|"VVG1"|2800000|760000|2022-11-03|"A"|"INCLUDES CAR"|0
I wanted to convert this form... | [
"df.to_csv(file_name, sep='\\t')\n\nTo use a specific encoding (e.g. 'utf-8') use the encoding argument:\ndf.to_csv(file_name, sep='\\t', encoding='utf-8')\n\n",
"I think you have a typo and should call\ndata = pd.read_csv(\n \"{}/output/Float_Ingestion_files/{}/{}.txt\".format(\n str(parentDir), test_c... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074428716_pandas_python.txt |
Q:
How to load an excel file in IronPython?
I am trying to load an excel file within an IronPython script, which is embedded within a software.
I tried to do this with the following code:
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel
excel = Excel.Applica... | How to load an excel file in IronPython? | I am trying to load an excel file within an IronPython script, which is embedded within a software.
I tried to do this with the following code:
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel
excel = Excel.ApplicationClass()
excel.Visible = True
workbook = ex... | [
"if it's just a path error, try to escape your \\.\n\\ is a character used to escape some other characters (such as quotes, new lines, etc)\nSo when python is reading your code and interpreting it, it is trying to understand the characters you escaped such as \\U, \\a ...\nTo avoid this problem you can try this :\n... | [
0
] | [] | [] | [
"clr",
"excel",
"ironpython",
"loading",
"python"
] | stackoverflow_0074428706_clr_excel_ironpython_loading_python.txt |
Q:
pandas group data at 3 month intervals and aggregate list of functions
I have a dataframe like as shown below
df = pd.DataFrame({'subject_id':[1,1,1,1,1,1,1,2,2,2,2,2],
'invoice_id':[1,2,3,4,5,6,7,8,9,10,11,12],
'purchase_date' :['2017-04-03 12:35:00','2017-04-03 12:50:00','20... | pandas group data at 3 month intervals and aggregate list of functions | I have a dataframe like as shown below
df = pd.DataFrame({'subject_id':[1,1,1,1,1,1,1,2,2,2,2,2],
'invoice_id':[1,2,3,4,5,6,7,8,9,10,11,12],
'purchase_date' :['2017-04-03 12:35:00','2017-04-03 12:50:00','2018-04-05 12:59:00','2018-05-04 13:14:00','2017-05-05 13:37:00','2018-07-06 1... | [
"Use:\n#sorting per subject_id, purchase_date\ndf = df.sort_values(['subject_id','purchase_date'])\n\n#create month groups by convert to month periods with subtract min values\nper = df['purchase_date'].dt.to_period('m').astype('int')\ndf['date_group'] = (per.sub(per.min()) // 3 + 1)\n\n#custom function\ndef f(x):\... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python",
"time_series"
] | stackoverflow_0074428395_dataframe_group_by_pandas_python_time_series.txt |
Q:
Telegram API "parseMode:MarkdownV2" doesn't change text style
so I try to use Telegram's API to send messages to a group. Sending messages is working, but when I try to send messages with a certain style,
for example bold, it just doesn't work.
My example message is: "* hello send help *".
It should look something... | Telegram API "parseMode:MarkdownV2" doesn't change text style | so I try to use Telegram's API to send messages to a group. Sending messages is working, but when I try to send messages with a certain style,
for example bold, it just doesn't work.
My example message is: "* hello send help *".
It should look something like this: hello send help, but it just sends the literal (i.e the... | [
"The parameter of sendMessage is specified as parse_mode, not parseMode. Try that.\n"
] | [
0
] | [] | [] | [
"python",
"telegram"
] | stackoverflow_0074427418_python_telegram.txt |
Q:
Python: how to identify common elements in lists from two dataframes' series
Using Pandas, I have two data sets stored in two separate dataframes. Each dataframe is composed of two series.
The first dataframe has a series called 'name', the second series is a list of strings. It looks something like this:
... | Python: how to identify common elements in lists from two dataframes' series | Using Pandas, I have two data sets stored in two separate dataframes. Each dataframe is composed of two series.
The first dataframe has a series called 'name', the second series is a list of strings. It looks something like this:
name attributes
0 John [ABC, ... | [
"You could try a method like below:\n# Import pandas library\nimport pandas as pd\n\n# Create our data frames\ndata1 = [['John', ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU']], ['Mike', ['EUD', 'DBS', 'QMD', 'ABC', 'GHI']],\n['Jane', ['JKL', 'EJD', 'MDE', 'MNO', 'DEF', 'ABC']], ['Kevin', ['FHE', 'EUD', 'GHI', '... | [
0
] | [] | [] | [
"compare",
"list",
"pandas",
"python",
"series"
] | stackoverflow_0074396438_compare_list_pandas_python_series.txt |
Q:
Simple Stopwatch in python using time.sleep
Im trying to create a simple stopwatch using counter logic and sleep function in python. It seems to increment fine and be pretty accurate with the one issue of my if statement.
self.sec = 0
self.min = 0
time.sleep(1)
self.sec = self.sec + 1
if (self.sec == 59):
sel... | Simple Stopwatch in python using time.sleep | Im trying to create a simple stopwatch using counter logic and sleep function in python. It seems to increment fine and be pretty accurate with the one issue of my if statement.
self.sec = 0
self.min = 0
time.sleep(1)
self.sec = self.sec + 1
if (self.sec == 59):
self.sec = 0
self.min = self.min + 1
I'd like... | [
"First thing: Weird, that your minute would only have 59 seconds instead of 60. Your example would result in the exact behavior described in your problem. Try changing to if (self.sec == 60): ... and check the results.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074428797_python.txt |
Q:
clarifai- ValueError: too many values to unpack (expected 2)
I am trying to upload an food image and trying to detect the picture using clarifai food detection model which is in JSON format and display results in my html page I am taking sample code from here
from flask import Flask,render_template,request,redirec... | clarifai- ValueError: too many values to unpack (expected 2) | I am trying to upload an food image and trying to detect the picture using clarifai food detection model which is in JSON format and display results in my html page I am taking sample code from here
from flask import Flask,render_template,request,redirect,url_for ,session
from PIL import Image
import pandas as pandas
f... | [
"According to this API doc example, metadata should be as follows:\nmetadata = (('authorization', 'Key ' + PAT),)\n\nYou should remove the {} in your string.\n"
] | [
0
] | [] | [] | [
"clarifai",
"python"
] | stackoverflow_0074428109_clarifai_python.txt |
Q:
Creating large image from csv data
I'm trying to create a very large image from CSV file data. The image will be used as a material texture in rendering software, so there is some motivation to avoid splitting the image up.
The image can be monochromatic - just a series of filled circles on a background (doesn't m... | Creating large image from csv data | I'm trying to create a very large image from CSV file data. The image will be used as a material texture in rendering software, so there is some motivation to avoid splitting the image up.
The image can be monochromatic - just a series of filled circles on a background (doesn't matter whether is black on white or vice ... | [
"You can speed up execution by not saving the picture in every iteration, like you do so far.\nSaving the picture takes time. If it's a large image, it takes more time.\nJust save it once, when you're done.\n\nMonochrome:\n\nchange the shape of the numpy array (2-dimensional, no third dimension)\ndraw circles havin... | [
1
] | [] | [] | [
"csv",
"opencv",
"python"
] | stackoverflow_0074427991_csv_opencv_python.txt |
Q:
Hide input json files during the conversion of python scripts into exe
I am making a console app to download gcp objects using service account GOOGLE_CREDENTIALS, which is stored in json file. When i buddle my project using auto-py-to-exe to make it as an exe file. The json file comes into this folder. I want to h... | Hide input json files during the conversion of python scripts into exe | I am making a console app to download gcp objects using service account GOOGLE_CREDENTIALS, which is stored in json file. When i buddle my project using auto-py-to-exe to make it as an exe file. The json file comes into this folder. I want to hide this file from user. Is there any way to do so??
| [
"You can use os.chmod at the end of your setup script to make any file of the build directory read-only. For example:\nimport os\nimport stat\nos.chmod(path_to_file, stat.S_IREAD)\n\nAnd also to hide use below :\nstat.FILE_ATTRIBUTE_HIDDEN this indicates The file or directory is hidden. It is not included in an ... | [
0
] | [] | [] | [
"auto_py_to_exe",
"exe",
"google_cloud_platform",
"json",
"python"
] | stackoverflow_0074427795_auto_py_to_exe_exe_google_cloud_platform_json_python.txt |
Q:
The dataframe index column not getting dropped
I am trying to convert a CSV into a dataframe and also updating column values in the CSV. But the issue I am facing is I am not getting rid of the index column as a result I am getting an extra index column without name in the console as follows.
fsym_id factset_e... | The dataframe index column not getting dropped | I am trying to convert a CSV into a dataframe and also updating column values in the CSV. But the issue I am facing is I am not getting rid of the index column as a result I am getting an extra index column without name in the console as follows.
fsym_id factset_entity_id ... is_substituted is_current
0 VVG1JM-S ... | [
"As far as I know, you cannot get rid of index in the pandas dataframe.\n(Index is not considered as column)\nHowever, when you convert dataframe into csv, you can skip indicies like below.\ndf.to_csv(path, index = False)\n\n",
"You can try this because while you read the csv column unnamed 0 contains your previo... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074427747_pandas_python.txt |
Q:
Remove duplicate lines with a specific string from a file
I have a file in which i have to remove the duplicate lines with same string at the last three positions
file.txt contains
['aabbccj', 'biukghk', 'hgkfhff', 'hsgfccj', ' jflgsfs', 'fskfyhd', 'bfsbkhd', 'fjlfghk']
i want the output as
['aabbccj', 'biuk... | Remove duplicate lines with a specific string from a file | I have a file in which i have to remove the duplicate lines with same string at the last three positions
file.txt contains
['aabbccj', 'biukghk', 'hgkfhff', 'hsgfccj', ' jflgsfs', 'fskfyhd', 'bfsbkhd', 'fjlfghk']
i want the output as
['aabbccj', 'biukghk', 'hgkfhff', ' jflgsfs', 'fskfyhd', 'bfsbkhd']
| [
"Simply create a list of your endings. In your loop through the list, store them in a separate list and check for any new iteration:\nlist = ['aabbccj', 'biukghk', 'hgkfhff', 'hsgfccj', ' jflgsfs', 'fskfyhd', 'bfsbkhd', 'fjlfghk']\nendings = []\nresults = []\nfor entry in list:\n if entry[-3:] in endings:\n ... | [
0,
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074428865_list_pandas_python.txt |
Q:
Calculate the sum of column values per row but not include every value
So I have this dataset which looks like this.
id
something
number1
number2
number3
number4
number5
number6
sum_columns
1
105
1
NaN
NaN
2
3
4
4
2
300
2
1
1
33
6
2
6
3
20
1
NaN
NaN
NaN
5
3
3
Now I need to calculate the sum of columns values ... | Calculate the sum of column values per row but not include every value | So I have this dataset which looks like this.
id
something
number1
number2
number3
number4
number5
number6
sum_columns
1
105
1
NaN
NaN
2
3
4
4
2
300
2
1
1
33
6
2
6
3
20
1
NaN
NaN
NaN
5
3
3
Now I need to calculate the sum of columns values starting with 'number' but only include the values that are in r... | [
"Use DataFrame.where for filter values less like 6 and replace not matched to 0:\ndf1 = df.filter(like='number')\ndf['values_sum'] = df1.where(df1.lt(6),0).sum(axis=1)\n\n#if need values only range(1,6)\n#df['values_sum'] = df1.where(df1.isin(range(1, 6)),0).sum(axis=1)\nprint (df)\n id something number1 numbe... | [
1
] | [] | [] | [
"dataframe",
"filter",
"pandas",
"python",
"sum"
] | stackoverflow_0074428950_dataframe_filter_pandas_python_sum.txt |
Q:
How to call a function in a function in maya 2022?
I'm creating a GUI in Maya that will either make a procedural material or a material with user input texture files. There are a lot of place holders in my code but right now I am trying to get my Create button to print different statements depending on which radio... | How to call a function in a function in maya 2022? | I'm creating a GUI in Maya that will either make a procedural material or a material with user input texture files. There are a lot of place holders in my code but right now I am trying to get my Create button to print different statements depending on which radio button is clicked. I know how to do this with PyQt5 but... | [
"Your button command has the wrong signature: You write\ndef do_butt(test, self, *args):\n\nWhat is not correct for a class method, it has to be\ndef do_butt(self, test, *args):\n\nAnd your line:\nself.radio_butts = cmds.radioButtonGrp(test, q=1, select=1)\n\ndoes not make sense because test is False and you assign... | [
1
] | [] | [] | [
"maya",
"python"
] | stackoverflow_0074424477_maya_python.txt |
Q:
Installing private pip package inside docker container
I am trying to create docker container for a fastapi application.
This application is going to use a private pip package hosted on github.
During local development, I used the following command to install the dependency:
pip install git+https://<ACCESS_TOKEN>:... | Installing private pip package inside docker container | I am trying to create docker container for a fastapi application.
This application is going to use a private pip package hosted on github.
During local development, I used the following command to install the dependency:
pip install git+https://<ACCESS_TOKEN>:x-oauth-basic@github.com/username/projectname
I tried the s... | [
"if I am not mistaken, you could run your pip command without echo:\nRUN pip install git+https://${ACCESS_TOKEN}:x-oauth-basic@github.com/username/projectname\n\n"
] | [
0
] | [] | [] | [
"docker",
"github",
"pip",
"python"
] | stackoverflow_0074428652_docker_github_pip_python.txt |
Q:
'WebDriver' object has no attribute 'find_elements_by_xpath File "C:\Users\luigi\Downloads\script_sbs.py", line 20
import re
import time
from datetime import datetime
from operator import itemgetter
import openpyxl
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdrive... | 'WebDriver' object has no attribute 'find_elements_by_xpath File "C:\Users\luigi\Downloads\script_sbs.py", line 20 | import re
import time
from datetime import datetime
from operator import itemgetter
import openpyxl
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
driver.minimize_window()
url = 'https://www.sbostats.com/partite'
tgame = []
driver.get(url)
tab = driver... | [
"All the methods like find_element_by_name, find_element_by_xpath, find_element_by_id etc. are deprecated now.\nYou should use find_element(By. instead.\nSo, instead of\ntab = driver.find_element_by_xpath(\"/html/body/div[2]/div[3]/div/div/div[2]/app-root/div/app-matches/section\")\n\nit should be now\ntab = driver... | [
0
] | [] | [] | [
"python",
"selenium4",
"selenium_webdriver",
"web_scraping",
"xpath"
] | stackoverflow_0074429037_python_selenium4_selenium_webdriver_web_scraping_xpath.txt |
Q:
Tried getting the Name from anothter python file but error index out of range
Tried Importing Name from File1 to File 2 so it can be used in Char1 creation but error as it state index out of range
Any ideas how can i get the name and roles from file 1 and input it in file 2 ?
Tested with File 1 that the name i inp... | Tried getting the Name from anothter python file but error index out of range | Tried Importing Name from File1 to File 2 so it can be used in Char1 creation but error as it state index out of range
Any ideas how can i get the name and roles from file 1 and input it in file 2 ?
Tested with File 1 that the name i input will get saved in the Name List when i tried printing it out but when i shift it... | [
"Problem\nThe problem occurs because you use the if __name__ guard that prevents the running of an entire script when it is imported. Running the PlayerCreate script on its own will run all the code, but only the unguarded parts of the script get executed when it is imported. Running the second script only will res... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074428572_python.txt |
Q:
Why is my scipy.optimize.curve_fit p0 not taking a list as a single parameter?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import scipy.io as spio
from scipy.optimize import curve_fit
Im trying to create a line of fit with curve_fit, using a gauss function.
def gauss (x, peaks) : #... | Why is my scipy.optimize.curve_fit p0 not taking a list as a single parameter? | import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import scipy.io as spio
from scipy.optimize import curve_fit
Im trying to create a line of fit with curve_fit, using a gauss function.
def gauss (x, peaks) : #peaks is parameters of gaussian fitting function
result = peaks[0] + peaks[1]*x ... | [
"The function to fit is expected to have the signature def f(xdata, *params), i.e. the function f has an arbitrary number of params. Inside the function params is just a tuple that contains all the arguments.\nIn code:\nfrom scipy.optimize import curve_fit\n\ndef gauss(x, *peaks):\n result = peaks[0] + peaks[1]*... | [
0
] | [] | [] | [
"curve_fitting",
"python",
"scipy"
] | stackoverflow_0074425960_curve_fitting_python_scipy.txt |
Q:
jupyter notebook showing this message, ImportError: cannot import name 'encodestring' from 'base64'
I am new to python and jupyter notebook and I am using windows. Recently I installed Anaconda Navigator 2.3.1 and the python verson 3.9.13 on my computer. After entering the command jupyter notebook on the command-l... | jupyter notebook showing this message, ImportError: cannot import name 'encodestring' from 'base64' | I am new to python and jupyter notebook and I am using windows. Recently I installed Anaconda Navigator 2.3.1 and the python verson 3.9.13 on my computer. After entering the command jupyter notebook on the command-line, my browser doesn't open jupyter notebook, instead that showing me this error message:
(base) C:\User... | [
"base64.encodestring was deprecated since python 3.1 and finally removed in 3.9\nYou can compare the official documentation for the base64 library for version 3.8 and 3.9\nhttps://docs.python.org/3.8/library/base64.html\nhttps://docs.python.org/3.9/library/base64.html\nI'm not sure exactly how you installed anacond... | [
2,
0
] | [] | [] | [
"anaconda",
"data_science",
"jupyter_notebook",
"python",
"windows"
] | stackoverflow_0074375400_anaconda_data_science_jupyter_notebook_python_windows.txt |
Q:
How to make cmds.duplicate() execute immediately when called in maya
How to make cmds.duplicate execute immediately when called in maya? Instead of waiting for the entire script to run and then executing it in batches. For example, for this script below, all execution results will appear immediately after the enti... | How to make cmds.duplicate() execute immediately when called in maya | How to make cmds.duplicate execute immediately when called in maya? Instead of waiting for the entire script to run and then executing it in batches. For example, for this script below, all execution results will appear immediately after the entire script is executed
import time
for i in range(1, 6):
pm.select("pSph... | [
"Your assumptions are not correct. Maya does not need to display anything to complete a tool. If you want to see the results inbetween you can try to use:\npm.refresh()\n\nbut this will not change the behaviour in general. I suppose your memory problems have a different source. You could check if it helps to turn o... | [
2,
0
] | [] | [] | [
"maya",
"maya_api",
"pymel",
"python"
] | stackoverflow_0074427404_maya_maya_api_pymel_python.txt |
Q:
How to convert each value of a series to a list, then combine them to a list?
for example, I have a df like this:
A
0 I like this
1 I like that
which was created by:
df = DataFrame({'A':['I like this','I like that']})
Now for df['A'], I want to convert this series to a list of lists, like this:
[['I l... | How to convert each value of a series to a list, then combine them to a list? | for example, I have a df like this:
A
0 I like this
1 I like that
which was created by:
df = DataFrame({'A':['I like this','I like that']})
Now for df['A'], I want to convert this series to a list of lists, like this:
[['I like this'],['I like that']]
I searched about this but I only got suggestions like ... | [
"You need to apply the list operation on each row individually as well.\ndf.apply(list, axis=1).tolist()\n\nIf you just want this apply on a few columns in your DF, simply slice into the DF using:\ndf[['A']].apply(list, axis=1).tolist()\n\nOutput\n[['I like this'], ['I like that']]\n\n",
"You can try list compreh... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"gensim",
"list",
"python",
"series"
] | stackoverflow_0074429126_dataframe_gensim_list_python_series.txt |
Q:
Specifying Windows to use Anaconda Python interpreter
I have Python 2.7 installed and I have Anaconda (using Python 3.6) installed on Windows. Whenever I try to run my .py scripts from Windows outside of the Anaconda environment Windows defaults to using the Python 2.7 interpreter. My Scripts fail to import module... | Specifying Windows to use Anaconda Python interpreter | I have Python 2.7 installed and I have Anaconda (using Python 3.6) installed on Windows. Whenever I try to run my .py scripts from Windows outside of the Anaconda environment Windows defaults to using the Python 2.7 interpreter. My Scripts fail to import modules (i'm assuming this is using the wrong interpreter).
I ha... | [
"Another solution which worked for me.\n\nOpen Command Prompt and type where python.\nFor me:\n\nC:\\Users\\user\\anaconda3\\python.exe\nC:\\Users\\user\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe\n\nI am going to use the first path to the python interpreter because it relates to Anaconda.\n\nFollowing this... | [
0,
0
] | [] | [] | [
"anaconda",
"python",
"version",
"windows"
] | stackoverflow_0053988558_anaconda_python_version_windows.txt |
Q:
I want line break after slicing by \t pandas
I want to do line break after slicing by \t. Could you possibly know about this?
columns
A00\t콜레라\tCholera
=>
columns
A00
콜레라
Cholera
A:
You can first split your column then explode:
df['column'] = df['column'].str.split("\t")
df.explode("column")
A:
Can you ... | I want line break after slicing by \t pandas | I want to do line break after slicing by \t. Could you possibly know about this?
columns
A00\t콜레라\tCholera
=>
columns
A00
콜레라
Cholera
| [
"You can first split your column then explode:\ndf['column'] = df['column'].str.split(\"\\t\")\ndf.explode(\"column\")\n\n",
"Can you check if this works?\nimport pandas as pd\ndf = pd.DataFrame({'columns':['A00\\t콜레라\\tCholera']})\nnew_df = pd.DataFrame(df['columns'].str.split('\\t').tolist()).stack()\nnew_df\n\... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074429190_dataframe_pandas_python.txt |
Q:
KeyError thrown even if hashes are the same
I'm trying to get a value from the dictionary using a key - a hashable object. Unfortunately I get a KeyError even if the key with the same hash exists in the dictionary:
#structures.py
class TransactionDesignation:
def __init__(self, gd, id, child_of):
self.... | KeyError thrown even if hashes are the same | I'm trying to get a value from the dictionary using a key - a hashable object. Unfortunately I get a KeyError even if the key with the same hash exists in the dictionary:
#structures.py
class TransactionDesignation:
def __init__(self, gd, id, child_of):
self.id = id
self.child_of = child_of
... | [
"I made a mistake during implementation of this mechanism. @Jasonharper, I was wrong saying no more code is needed. The problem is here:\ntransaction_designation = TransactionDesignation('test1', '3917', None)\nlogs[TRANSACTIONS][transaction_designation] = transaction\n#...\ntransaction_designation.child_of = '3318... | [
0
] | [] | [] | [
"dictionary",
"keyerror",
"python"
] | stackoverflow_0074417803_dictionary_keyerror_python.txt |
Q:
Create Dataframe from list of strings of delimited column names and values
I have a list of strings:
data = ['col1:abc col2:def col3:ghi',
'col4:123 col2:qwe col10:xyz',
'col3:asd']
I would like to convert this to a dataframe, where each string in the list is a row in the dataframe, like so:
desir... | Create Dataframe from list of strings of delimited column names and values | I have a list of strings:
data = ['col1:abc col2:def col3:ghi',
'col4:123 col2:qwe col10:xyz',
'col3:asd']
I would like to convert this to a dataframe, where each string in the list is a row in the dataframe, like so:
desired_out = pd.DataFrame({'col1': ['abc', np.nan, np.nan],
... | [
"Use nested list comprehension with convert splitted values to dictionaries:\ndf = pd.DataFrame([dict([y.split(':') for y in x.split()]) for x in data])\nprint (df)\n col1 col2 col3 col4 col10\n0 abc def ghi NaN NaN\n1 NaN qwe NaN 123 xyz\n2 NaN NaN asd NaN NaN\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"list",
"pandas",
"parsing",
"python"
] | stackoverflow_0074429273_dataframe_list_pandas_parsing_python.txt |
Q:
Different time points for deep learning model inputs
I want to ask if it is possible to create a model where I have 2 inputs, which are Temperature and Status, but the inputs start at different times? For example, the temperature starts at t=0 and the status starts at t=1. The output for this model will only be th... | Different time points for deep learning model inputs | I want to ask if it is possible to create a model where I have 2 inputs, which are Temperature and Status, but the inputs start at different times? For example, the temperature starts at t=0 and the status starts at t=1. The output for this model will only be the temperature at t=15. I'm really new to deep learning and... | [
"I think to solve this issue we have to change the df in a way 'Z1_S1(degC)' starts at t=0 and 'Status' starts at t=1, so we will define a new df as follows:\nnew_df=pd.DataFrame({'Z1_S1(degC)': [df['Z1_S1(degC)'][i] for i in range(len(df)-1)], #last value not included\n 'Status': [df['Status'... | [
0
] | [] | [] | [
"deep_learning",
"forecasting",
"jupyter_notebook",
"lstm",
"python"
] | stackoverflow_0074429022_deep_learning_forecasting_jupyter_notebook_lstm_python.txt |
Q:
Finding substring without exact match inside full String (non English)
I want to find a substring like (میں چند ممالک ایک ایسے گیا) from a paragraph
but the paragraph line is not exactly same to the substring line so if more than two words are match from the line of the paragraph give that line as match line
ful... | Finding substring without exact match inside full String (non English) | I want to find a substring like (میں چند ممالک ایک ایسے گیا) from a paragraph
but the paragraph line is not exactly same to the substring line so if more than two words are match from the line of the paragraph give that line as match line
fullstringlist =(" ادھر کی رات صرف چار گھنٹے کی ہے- جہاں دن کا دورانیہ بیس گھن... | [
"You can achieve that using Threshold variable that indicates half number of words plus one in each substring.\nExample:\nادھر رات صرف چار گھنٹے کی ہے contains 7 words so its threshold about 5 words, if we find 5 matches words or more we will consider it a match substring\nfullstringlist = \" ادھر کی رات صرف چار گ... | [
1
] | [] | [] | [
"list",
"python",
"search",
"string",
"urdu"
] | stackoverflow_0074427252_list_python_search_string_urdu.txt |
Q:
Python List Statistics not correct
I try to calculate some stats for a list. But somehow these are not correct:
Code:
import pandas as pd
import statistics
list_runs_stats=[4.149432, 3.133142, 3.182976, 2.620959, 3.200038, 2.66668, 2.604444, 2.683382, 3.249564, 3.149947]
list_stats=pd.Series(list_runs_stats).des... | Python List Statistics not correct | I try to calculate some stats for a list. But somehow these are not correct:
Code:
import pandas as pd
import statistics
list_runs_stats=[4.149432, 3.133142, 3.182976, 2.620959, 3.200038, 2.66668, 2.604444, 2.683382, 3.249564, 3.149947]
list_stats=pd.Series(list_runs_stats).describe()
print (list_stats.mean())
prin... | [
"By assigning the output of describe() to list_stats, you are calculating the min and max of the output of describe function\nCan you try this this instead?\nimport pandas as pd\nlist_runs_stats=[4.149432, 3.133142, 3.182976, 2.620959, 3.200038, 2.66668, 2.604444, 2.683382, 3.249564, 3.149947]\ndf = pd.Series(list_... | [
2,
1
] | [] | [] | [
"pandas",
"python",
"statistics"
] | stackoverflow_0074429325_pandas_python_statistics.txt |
Q:
different outlook email grouped by unique email with a email body
How can I paste the email body grouped by unique values of column = country and send to the respective email ID and CC list provided?
enter image description here
A:
You can automate Excel and Outlook to get the job done, it seems you need to iter... | different outlook email grouped by unique email with a email body | How can I paste the email body grouped by unique values of column = country and send to the respective email ID and CC list provided?
enter image description here
| [
"You can automate Excel and Outlook to get the job done, it seems you need to iterate over all cells in the range of countries, for example:\nFor Each myCell In Rng\n\nWhere you can create a new mail item for an individual country and fill it with a data from the corresponding row.\nTo automate Outlook and create a... | [
0
] | [] | [] | [
"email",
"html",
"outlook",
"pandas",
"python"
] | stackoverflow_0074427584_email_html_outlook_pandas_python.txt |
Q:
Can't click on a specific element using selenium/python (tried iframe and all the methods that I know or found here)
I am trying to reach a website using Selenium and Python.
Once the website is loaded, there is like an iframe/pop-up above the website and I need to click on "Alles akzeptieren" but I can't target t... | Can't click on a specific element using selenium/python (tried iframe and all the methods that I know or found here) | I am trying to reach a website using Selenium and Python.
Once the website is loaded, there is like an iframe/pop-up above the website and I need to click on "Alles akzeptieren" but I can't target the element no matter what method I try.
I left all the methods that I used commented out, but neither one worked.
import r... | [
"Try using https://pypi.org/project/pyshadow/ in order to select your element.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"shadow_dom",
"web_scraping"
] | stackoverflow_0074156691_python_python_3.x_selenium_shadow_dom_web_scraping.txt |
Q:
How to install and use Kmeans in Chaquopy in android studio?
I am trying to get the RGB values from images using K-means clustering. The value of k is decided based on the Adaptive K value method.
A:
Find a package that implements this algorithm, such as scikit-learn, and then install it in your build.gradle fil... | How to install and use Kmeans in Chaquopy in android studio? | I am trying to get the RGB values from images using K-means clustering. The value of k is decided based on the Adaptive K value method.
| [
"Find a package that implements this algorithm, such as scikit-learn, and then install it in your build.gradle file.\n"
] | [
0
] | [] | [] | [
"android",
"android_studio",
"chaquopy",
"k_means",
"python"
] | stackoverflow_0074429214_android_android_studio_chaquopy_k_means_python.txt |
Q:
CDKTF not recognizing libraries outside of python standard library
I am unable to run cdktf because cdktf won't work with packages installed from PyPI. I need cdktf to be able to install / access packages installed from PyPI.
$ cdktf diff
⠏ Synthesizing
[2022-11-11T14:03:01.343] [ERROR] default - Traceback (most... | CDKTF not recognizing libraries outside of python standard library | I am unable to run cdktf because cdktf won't work with packages installed from PyPI. I need cdktf to be able to install / access packages installed from PyPI.
$ cdktf diff
⠏ Synthesizing
[2022-11-11T14:03:01.343] [ERROR] default - Traceback (most recent call last):
File "/Users/jcbcodes/workspace/project/main.py", ... | [
"As you have a Pipfile I'd expect your app command in your cdktf.json looks something like this: pipenv run python main.py. As you can see python is executed through Pipenv. You can use pipenv install to install the dependencies and then use it as you normally would in your python program.\n"
] | [
0
] | [] | [] | [
"aws_cdk",
"pipfile",
"python",
"terraform",
"terraform_cdk"
] | stackoverflow_0074408689_aws_cdk_pipfile_python_terraform_terraform_cdk.txt |
Q:
How to stop the sound in pgzrun (Pygame Zero) when my game ends?
the sound plays right now for eternity and I only want it to play once when the game ends. I've looked it up everywhere but I really cannot find any good and helpful solution to this problem.
I use pygame zero.
Here is my code for my game:
import pgz... | How to stop the sound in pgzrun (Pygame Zero) when my game ends? | the sound plays right now for eternity and I only want it to play once when the game ends. I've looked it up everywhere but I really cannot find any good and helpful solution to this problem.
I use pygame zero.
Here is my code for my game:
import pgzrun
from random import randint
'''
music
music = pygame.mixer.music.l... | [
"instead of music.play(\"music\") use music.play_once(\"music\")\nmusic.play(): Play a music track from the given file. The track will loop indefinitely.\nmusic.play_once: Similar to play(), but the music will stop after playing through once.\ntry: music.stop() to stop the music\nyou can read more about there here:... | [
0,
0
] | [] | [] | [
"pgzero",
"python"
] | stackoverflow_0070406320_pgzero_python.txt |
Q:
Python - How to use os.getenv with Path().resolve()
I have the following code. D_CONFIG_PATH IS ~/winnie/poohbear.toml
def get_config_path():
default_path = os.path.expanduser(const.D_CONFIG_PATH)
final_path = os.getenv('CONFIG_PATH', default_path)
if not final_path.is_file():
raise FileNotFoun... | Python - How to use os.getenv with Path().resolve() | I have the following code. D_CONFIG_PATH IS ~/winnie/poohbear.toml
def get_config_path():
default_path = os.path.expanduser(const.D_CONFIG_PATH)
final_path = os.getenv('CONFIG_PATH', default_path)
if not final_path.is_file():
raise FileNotFoundError(f'File {final_path} does not exist')
return fi... | [
"Apparently, you can do both at once.\nfinal_path = Path(os.getenv('CONFIG_PATH', const.CONFIG_PATH)).expanduser().resolve()\n\n"
] | [
0
] | [] | [] | [
"getenv",
"pathlib",
"python"
] | stackoverflow_0074429253_getenv_pathlib_python.txt |
Q:
exe file made with pyinstaller being reported as a virus threat by windows defender
I'm trying to create an exe using pyinstaller for a school project but, windows defender seems to report a virus threat and blocks the file. I want to send this exe to some other people but i wouldn't be able to do that unless I fi... | exe file made with pyinstaller being reported as a virus threat by windows defender | I'm trying to create an exe using pyinstaller for a school project but, windows defender seems to report a virus threat and blocks the file. I want to send this exe to some other people but i wouldn't be able to do that unless I fix this. So these are my queries- Why does the exe file get reported as a virus? A quick s... | [
"METHOD 1\nA possible solution for this would be to encrypt your code. There are several ways of encrypting your code. But the easiest one is to use base64 or basically converting text-to-binary encoding. and you need to make sure that there is no special character because base64 only have this charachter set.\nYou... | [
14,
3,
2,
1,
1,
0
] | [] | [] | [
"exe",
"pyinstaller",
"python",
"python_3.x",
"windows"
] | stackoverflow_0064788656_exe_pyinstaller_python_python_3.x_windows.txt |
Q:
Python - Web Scraping - Selenium - AttributeError: 'WebDriver' object has no attribute 'find_elements_by_xpath
I wrote a code in Python for Web Scraping and fetching HTML table but its throwing an Attribute Error : 'WebDriver' object has no attribute 'find_elements_by_xpath'
FULL ERROR
DeprecationWarning: executab... | Python - Web Scraping - Selenium - AttributeError: 'WebDriver' object has no attribute 'find_elements_by_xpath | I wrote a code in Python for Web Scraping and fetching HTML table but its throwing an Attribute Error : 'WebDriver' object has no attribute 'find_elements_by_xpath'
FULL ERROR
DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome('C:\webdrivers\chromedriver.e... | [
"Updated\nThe same issue can be seen here TypeError: 'module' object is not callable ( when importing selenium ).\nThe line,\ndriver = webdriver.chrome('C:\\webdrivers\\chromedriver.exe')\n\nshould be,\ndriver = webdriver.Chrome('C:\\webdrivers\\chromedriver.exe')\n\nnotice the capital 'C' in Chrome.\nAdditionally ... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"web_scraping"
] | stackoverflow_0074429516_python_selenium_selenium_chromedriver_web_scraping.txt |
Q:
How to check if a number (or str) from a list is in another column? - Python
I have a problem cross-checking numbers between a list and a column.
I have a list called "allowed_numbers" with 40 different phone numbers and a column imported from an excel sheet with 8000 calls called df['B-NUMBER']. I believe around ... | How to check if a number (or str) from a list is in another column? - Python | I have a problem cross-checking numbers between a list and a column.
I have a list called "allowed_numbers" with 40 different phone numbers and a column imported from an excel sheet with 8000 calls called df['B-NUMBER']. I believe around 90% of these 8000 calls are in the allowed_number list but I need to cross-check t... | [
"Just to summarize the discussion in the comments.\nUsing\ndf['B-NUMBER'].isin(allowed_number)\n\nworks once the content of allowed_number is turned into integers via\nallowed_number = [int(x) for x in allowed_number]\n\nSo to get the fraudulent numbers something like this works\nallowed_number=re.sub(\",\",\"\", a... | [
0
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074428618_list_pandas_python.txt |
Q:
Python how to select specific cells on excel with pandas
I have an excel here as shown in this picture:
I am using pandas to read my excel file and it is working fine, this code below can print all the data in my excel:
import pandas as pd
df = pd.read_csv('alpha.csv')
print(df)
I want to get the values from C... | Python how to select specific cells on excel with pandas | I have an excel here as shown in this picture:
I am using pandas to read my excel file and it is working fine, this code below can print all the data in my excel:
import pandas as pd
df = pd.read_csv('alpha.csv')
print(df)
I want to get the values from C2 cell to H9 cell which month is October and day is Monday onl... | [
"You should consider slicing your dataframe and then using .values to story them. If you want them as a list, then you can use to_list():\nFirst transform the Date column to a datetime:\ndf['Date'] = pd.to_datetime(df['Date'],dayfirst=True,infer_datetime_format=True)\n\nThen, slice and return the values for the Col... | [
0,
0
] | [] | [] | [
"csv",
"excel",
"pandas",
"python"
] | stackoverflow_0074429513_csv_excel_pandas_python.txt |
Q:
Unable to import from root directory to subdirectory without modifying sys.path (Python 3.8)
What I have tried
First let me say, I have read maybe 5 or 6 other stackoverflow questions related to this and many things have been said about this. Here's what I found and what I tried:
"Do sys.path.append(<root dir>) b... | Unable to import from root directory to subdirectory without modifying sys.path (Python 3.8) | What I have tried
First let me say, I have read maybe 5 or 6 other stackoverflow questions related to this and many things have been said about this. Here's what I found and what I tried:
"Do sys.path.append(<root dir>) before other imports."
Issue: This works, but it's against PEP standard practice so I'd rather find... | [
"Probably the easiest way to solve your problem is to restructure your project:\nProject\n ├── script.py\n └── module\n ├── __init__.py\n └── module.py\n\n",
"I solved my issue by setting PYTHONPATH. In my case, it works with this.\nPYTHONPATH=<root dir> python3 subdir/script.py\n\n"
] | [
0,
0
] | [] | [] | [
"modulenotfounderror",
"python",
"python_import"
] | stackoverflow_0071621273_modulenotfounderror_python_python_import.txt |
Q:
PermissionError: [Errno 13] Permission denied: '/manage.py'
I am trying to run the following command in docker-composer, to start project with django-admin:
docker-compose run app sh -c "django-admin startproject app ."
This produces the error:
Traceback (most recent call last):
File "/usr/local/bin/django-... | PermissionError: [Errno 13] Permission denied: '/manage.py' | I am trying to run the following command in docker-composer, to start project with django-admin:
docker-compose run app sh -c "django-admin startproject app ."
This produces the error:
Traceback (most recent call last):
File "/usr/local/bin/django-admin", line 10, in <module>
sys.exit(execute_from_command_li... | [
"ubuntu 21.04\nI got here searching for PermissionError: [Errno 13] Permission denied: so i'll just leave this here.\nnote: the below answer doesn't work for multi user systems ... see this answer instead for another possible solution\n\nIf you want to set it and forget it for 1 user, your own user ... here's what ... | [
60,
16,
9,
5,
4,
1,
0,
0,
0
] | [] | [] | [
"django",
"django_admin",
"docker",
"docker_compose",
"python"
] | stackoverflow_0056784492_django_django_admin_docker_docker_compose_python.txt |
Q:
Why is the sorted insert not working properly?
Here is the code for a linked list. When applying the following commands, it doesn't work properly.
The output is inconsistent.
The class is defined below.
class Node:
def __init__(self,data) -> None:
self.data=data
self.next=None
class linke... | Why is the sorted insert not working properly? | Here is the code for a linked list. When applying the following commands, it doesn't work properly.
The output is inconsistent.
The class is defined below.
class Node:
def __init__(self,data) -> None:
self.data=data
self.next=None
class linkedList:
def __init__(self) -> None:
self... | [
"The problem is you are going to far in your while loop:\nwhile data>cur.data and cur.next!=None:\n\nYou leave this loop when your cur is smaller, so you want to put new element between cur and the previous one. But you use his next. Change it to:\nwhile cur.next!=None and cur.next.data < data:\n\n"
] | [
1
] | [] | [] | [
"class",
"linked_list",
"python"
] | stackoverflow_0074429673_class_linked_list_python.txt |
Q:
How to use a Python Dataclass in another class
I'm trying to get to grips with Python and seem to be hitting a wall when trying to use Dataclasses. But when I run the test I have for it I get assertion error as it doesn't seem to see the dataclass right.
I have the following code:
file: music_library.py
from datac... | How to use a Python Dataclass in another class | I'm trying to get to grips with Python and seem to be hitting a wall when trying to use Dataclasses. But when I run the test I have for it I get assertion error as it doesn't seem to see the dataclass right.
I have the following code:
file: music_library.py
from dataclasses import dataclass
@dataclass
class Track:
... | [
"Update music_library.py like this:\nfrom dataclasses import dataclass\n\n@dataclass\nclass Track:\n title: str\n artist: str\n file: str\n\n\nclass MusicLibrary:\n def __init__(self):\n self.track = None\n\n def all(self):\n return self.track\n\n def add(self, title, artist, file):\... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_dataclasses",
"unit_testing"
] | stackoverflow_0074429602_python_python_3.x_python_dataclasses_unit_testing.txt |
Q:
Column comparison in Django queries
I have a following model:
class Car(models.Model):
make = models.CharField(max_length=40)
mileage_limit = models.IntegerField()
mileage = models.IntegerField()
I want to select all cars where mileage is less than mileage_limit, so in SQL it would be something like:
... | Column comparison in Django queries | I have a following model:
class Car(models.Model):
make = models.CharField(max_length=40)
mileage_limit = models.IntegerField()
mileage = models.IntegerField()
I want to select all cars where mileage is less than mileage_limit, so in SQL it would be something like:
select * from car where mileage < mileage... | [
"You can't do this right now without custom SQL. The django devs are working on an F() function that would make it possible: #7210 - F() syntax, design feedback required.\n",
"Since I had to look this up based on the accepted answer, I wanted to quickly mention that the F() expression has indeed been released an... | [
9,
0
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0000433294_django_orm_python.txt |
Q:
How to disable error syntax highlight Sublime Text 3
I am using a language I made with a similar syntax to python, and I wanted to use python syntax highlighting for my language as well.
The only problem is that my language uses curly brackets rather then : and indents.
So some times when I type return for example... | How to disable error syntax highlight Sublime Text 3 | I am using a language I made with a similar syntax to python, and I wanted to use python syntax highlighting for my language as well.
The only problem is that my language uses curly brackets rather then : and indents.
So some times when I type return for example it highlights the return in red.
Is there any way I can d... | [
"The decision about what code is valid and what code is invalid is something that's happening inside of the syntax definition (in this case, Python.sublime-syntax in the Python package). Any code that it deems is incorrect is scoped as invalid to convey that, and your color scheme knows to display code that's inval... | [
0,
0
] | [] | [] | [
"python",
"sublimetext3",
"syntax"
] | stackoverflow_0052608420_python_sublimetext3_syntax.txt |
Q:
Group column names and their values in two separate columns
I have the following dataframe:
averageNumberOfOperationsPerPath api_spec_id get post put delete
0 1.285714 84 12.0 4.0 1.0 1.0
1 1.266667 84 13.0 4.0 ... | Group column names and their values in two separate columns | I have the following dataframe:
averageNumberOfOperationsPerPath api_spec_id get post put delete
0 1.285714 84 12.0 4.0 1.0 1.0
1 1.266667 84 13.0 4.0 1.0 1.0
2 1.266667 ... | [
"I think you can use stack method:\ndf= (df\n .set_index(['averageNumberOfOperationsPerPath','api_spec_id'])\n .stack()\n .reset_index()\n .rename(columns={'level_2': 'methods', 0:'values'}))\n\nprint(df)\n\n averageNumberOfOperationsPerPath api_spec_id methods values\n0 ... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074429778_pandas_python.txt |
Q:
Generate matrix and save it in list
I want to create a list like the following, based on a starting point (x, y):
[[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]
My actual starting point is (71, 180) and
x_distance = 105
y_distance = 111
My expected output is (6x5) format:
[[71,180], [176,18... | Generate matrix and save it in list | I want to create a list like the following, based on a starting point (x, y):
[[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]]
My actual starting point is (71, 180) and
x_distance = 105
y_distance = 111
My expected output is (6x5) format:
[[71,180], [176,180], [281,180], [386,180], [491,180], [596... | [
"You could use the full range of range options:\nstart_x, start_y = 71, 180\ndist_x, dist_y = 105, 111\nres = [\n [x, y]\n for y in range(start_y, start_y + 5 * dist_y, dist_y)\n for x in range(start_x, start_x + 6 * dist_x, dist_x)\n]\n\nResult:\n[[71, 180], [176, 180], [281, 180], [386, 180], [491, 180],... | [
2,
1
] | [] | [] | [
"for_loop",
"python",
"python_3.x",
"while_loop"
] | stackoverflow_0074426642_for_loop_python_python_3.x_while_loop.txt |
Q:
Faster way to implement this formula in python
n and F are 3d matrices of dimensions m * l * l, where m=5 and l=174. n is given by gamma multiplied by the square of norm 2 of Fi-Fj. Formula here
My current brute force implementation is
for k in range(0,m):
for i in range(0,l):
for j in range(0,l):
dis... | Faster way to implement this formula in python | n and F are 3d matrices of dimensions m * l * l, where m=5 and l=174. n is given by gamma multiplied by the square of norm 2 of Fi-Fj. Formula here
My current brute force implementation is
for k in range(0,m):
for i in range(0,l):
for j in range(0,l):
dist = gamma*(np.linalg.norm(F[0][i] - F[0][j]))
... | [
"Right now your operation is done using 3 nested slow Python-style loops. Use the power of Numpy, broadcasting along the last-but-one axis and vectorizing the operations:\nn = gamma * np.sum((F[:,np.newaxis,:,:] - F[:,:,np.newaxis,:])**2, axis=-1)\n\n"
] | [
1
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0074429622_optimization_python.txt |
Q:
Pandas.dataframe.query() - fetch not null rows (Pandas equivalent to SQL: "IS NOT NULL")
I am fetching the rows with some values from a pandas dataframe with the following code. I need to convert this code to pandas.query().
results = rs_gp[rs_gp['Col1'].notnull()]
When I convert to:
results = rs_gp.query('Col1!=... | Pandas.dataframe.query() - fetch not null rows (Pandas equivalent to SQL: "IS NOT NULL") | I am fetching the rows with some values from a pandas dataframe with the following code. I need to convert this code to pandas.query().
results = rs_gp[rs_gp['Col1'].notnull()]
When I convert to:
results = rs_gp.query('Col1!=None')
It gives me the error
None is not defined
| [
"We can use the fact that NaN != NaN:\nIn [1]: np.nan == np.nan\nOut[1]: False\n\nSo comparing column to itself will return us only non-NaN values:\nrs_gp.query('Col1 == Col1')\n\nDemo:\nIn [42]: df = pd.DataFrame({'Col1':['aaa', np.nan, 'bbb', None, '', 'ccc']})\n\nIn [43]: df\nOut[43]:\n Col1\n0 aaa\n1 NaN\... | [
33,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0037863660_dataframe_pandas_python.txt |
Q:
Python Google authentication for a program used for web scraping
Never done this but, I'm trying to build a program, that would scrape a google classroom site specific to the user that's logged in. Even when logged in the main browser google denies the request and instead gives me authentication error (I need to l... | Python Google authentication for a program used for web scraping | Never done this but, I'm trying to build a program, that would scrape a google classroom site specific to the user that's logged in. Even when logged in the main browser google denies the request and instead gives me authentication error (I need to login in other words) how can I be logged in, in the program so that go... | [
"It would be expensive to try and implement a log-in mechanism, especially with all the 2FA requirements of Google solutions today.\nWhat would be quicker and usually works in software automation today is to have a manually logged in session and then start the browser with the user data directory pointed to it. Thi... | [
0
] | [] | [] | [
"authentication",
"python"
] | stackoverflow_0074429698_authentication_python.txt |
Q:
playwright headless chromium can't find selector, but finds it in UI mode
What I'm trying to do
I am doing some e2e testing with playwright on a webapp
The problem
I am running into problems whenever I want to save resources with headless mode.
My playwright script is working perfectly in chromium UI mode. When en... | playwright headless chromium can't find selector, but finds it in UI mode | What I'm trying to do
I am doing some e2e testing with playwright on a webapp
The problem
I am running into problems whenever I want to save resources with headless mode.
My playwright script is working perfectly in chromium UI mode. When encountering the first from (login), this happens:
[2022-03-31 07:57:38,079] [roo... | [
"I ran into this problem as well where my test would run in headed mode but not headless mode. I had a window of Chromium open when trying to run my test and it will fail. Once I closed all Chromium windows it worked in headless mode.\n",
"What I ran into when I saw this behavior is that when running in headless ... | [
1,
0,
0
] | [] | [] | [
"chromium",
"e2e_testing",
"playwright",
"playwright_python",
"python"
] | stackoverflow_0071687642_chromium_e2e_testing_playwright_playwright_python_python.txt |
Q:
Creating Kivy customized ToggleButtons
I am trying to create customized ToggleButtons in Kivy.
For the most part I have succeeded except when I pair them into group.
When one of the buttons is pressed down and I press onto another, the color of the formerly pressed button won't return to normal, unless I hover ove... | Creating Kivy customized ToggleButtons | I am trying to create customized ToggleButtons in Kivy.
For the most part I have succeeded except when I pair them into group.
When one of the buttons is pressed down and I press onto another, the color of the formerly pressed button won't return to normal, unless I hover over it. Is there a way to make it return to it... | [
"In the \"on_state\" method of your toggle button replace self.hover_anim.start(self) with self.down_anim.start(self) in the \"else\" branch and you should get the correct behavior.\n"
] | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"python",
"togglebutton"
] | stackoverflow_0074420635_kivy_kivy_language_python_togglebutton.txt |
Q:
How to add a column data from one table to another table column field in postgresql using python
I am new to django and postgresql. I have two tables in postgresql. in one table i have two fields ID and Value. i want to add the datas in the ID column to another table column field named value_id. In postgres the t... | How to add a column data from one table to another table column field in postgresql using python | I am new to django and postgresql. I have two tables in postgresql. in one table i have two fields ID and Value. i want to add the datas in the ID column to another table column field named value_id. In postgres the tables are from the same schema. I want to do this via python. Is there any way. please help.
cur =... | [
"you can do that with migration file\nclass Migration(migrations.Migration):\n\n dependencies = [\n ( .....),\n ]\n operations = [\n migrations.AddField(\n model_name=\"Model1\",\n name=\"field1\",\n ),\n migrations.RunPython(forwards_migrate_data_from_fiel... | [
1
] | [] | [] | [
"database",
"django",
"postgresql",
"python"
] | stackoverflow_0074429874_database_django_postgresql_python.txt |
Q:
Raster and Shapefiles not lining up using Geopandas, Rasterio, and Contextily
I am trying to get a DEM raster to line up with a shapefile in Python, but it will not show up no matter what I do. This is for lab exercise, the entire rest of the exercise relies on these lining up, as I will be extracting data from th... | Raster and Shapefiles not lining up using Geopandas, Rasterio, and Contextily | I am trying to get a DEM raster to line up with a shapefile in Python, but it will not show up no matter what I do. This is for lab exercise, the entire rest of the exercise relies on these lining up, as I will be extracting data from the raster and polygon layers to a point layer.
I know how to do all this "by hand" i... | [
"You could give EOmaps a try... it uses matplotlib/cartopy for plotting and handles re-projecting the data and shapes to the plot-crs\nfrom pathlib import Path\nfrom eomaps import Maps\nimport geopandas as gpd\n\np = Path(r\"path to the data folder\")\n# read shapefile\nabisveg = gpd.read_file(p / 'abisveg_polygon.... | [
0
] | [] | [] | [
"epsg",
"geopandas",
"matplotlib",
"python",
"rasterio"
] | stackoverflow_0074350387_epsg_geopandas_matplotlib_python_rasterio.txt |
Q:
Employee Leave types conditions in DJango rest framework
I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand... | Employee Leave types conditions in DJango rest framework | I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand how to make the logic for it and and don't know where to writ... | [
"Make a separate app for leaves, linked as foreign key field to the main employee.\nThen declare leave models, and go with the conditions in the serializer, to allow or not allow employee to apply for leave.\nWith permissions, you can control the read only or the read/write part of the view.\nFor sending email, tak... | [
1,
1
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0074426902_django_django_models_django_rest_framework_django_views_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.