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:
Using SimpleImputer to impute values by class
I'm trying to build a custom transformer wrapped around SimpleImputer. My idea is to apply the SimpleImputer transformer, but grouping for a categorical column of choice. And I want it to be a sklearn transformer so it can be applied to a pipeline.
Letter
Value
A
10
... | Using SimpleImputer to impute values by class | I'm trying to build a custom transformer wrapped around SimpleImputer. My idea is to apply the SimpleImputer transformer, but grouping for a categorical column of choice. And I want it to be a sklearn transformer so it can be applied to a pipeline.
Letter
Value
A
10
A
20
B
np.nan
B
1
A
np.nan
B
2
... | [
"One possible solution to the problem might be the following:\nimport numpy as np\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\ndf = pd.DataFrame({'Letter': ['A', 'A', 'B', 'B', 'A', 'B'], \n 'Value': [10, 20, np.nan, 1, np.nan, 2]}\n)\n\nclass CustomImputer(BaseEstimator, Tra... | [
1
] | [] | [] | [
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074348670_pandas_python_scikit_learn.txt |
Q:
Built-in binary search algorithm in numpy that is like np.searchsorted?
I have a main numpy array a and I have another numpy array b. What I want to do is go through each element of b and check if that element exists in a. Keep in mind that both a and b are pretty massive, so I would like to avoid O(N) search time... | Built-in binary search algorithm in numpy that is like np.searchsorted? | I have a main numpy array a and I have another numpy array b. What I want to do is go through each element of b and check if that element exists in a. Keep in mind that both a and b are pretty massive, so I would like to avoid O(N) search times.
I know np.searchsorted(a,b) exists, but this provides an index at which I ... | [
"Once you have completed the sorted search you can check if the elements at those indices are equal to the elements in b:\na = numpy.array([1,2,3,4,7])\nb = numpy.array([1,4,5,7])\nx = numpy.searchsorted(a,b)\nboolean_array = a[x] == b\n\nsearchsorted indicates that with the default side = 'left' it ensures : a[i-1... | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074416885_numpy_python.txt |
Q:
Correct way to check against type given by string in Python
In short, if I have:
str_type = "int"
to_check = 1
what is the best way to implement the following check?
if isinstance(to_check, str_type):
...
More detailed:
I want to use type information given by one JSON file to check the values of another JSON fil... | Correct way to check against type given by string in Python | In short, if I have:
str_type = "int"
to_check = 1
what is the best way to implement the following check?
if isinstance(to_check, str_type):
...
More detailed:
I want to use type information given by one JSON file to check the values of another JSON file.
So if I have template.json:
{
"param1": "int",
"param2": ... | [
"I think the best solution is to build a dictionary with string value corresponding to type. Then we can use build a simple function to check it\ndef check_types(value, expected_type: str):\n types = {\n \"int\": int,\n \"str\": str,\n \"float\": float\n }\n return isinstance(value, ty... | [
1
] | [] | [] | [
"json",
"python",
"types",
"validation"
] | stackoverflow_0074416986_json_python_types_validation.txt |
Q:
Function to find the index of the beginning and end of the longest run in a list
I'm trying to write code that finds the longest run in a list of Boolean values and return the index of the first and last value of that run. For example, if L is [False, False, True, False, False, False, False, True, True, False, Fa... | Function to find the index of the beginning and end of the longest run in a list | I'm trying to write code that finds the longest run in a list of Boolean values and return the index of the first and last value of that run. For example, if L is [False, False, True, False, False, False, False, True, True, False, False]. then the function would return (3, 6), since the longest run of False is from 3 ... | [
"You can keep track of the starting index and the length of the longest run so far, as well as the starting index of the current run, and if the current index minus the starting index of the current run is greater than the length of the longest run so far, make the current starting index and the said length the new... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0058862837_python.txt |
Q:
Using flatten in pytorch v1.0 Sequential module
Due to my CUDA version being 8, I am using torch 1.0.0
I need to use the Flatten layer for Sequential model. Here's my code :
import torch
import torch.nn as nn
import torch.nn.functional as F
print(torch.__version__)
# 1.0.0
from collections import OrderedDict
lay... | Using flatten in pytorch v1.0 Sequential module | Due to my CUDA version being 8, I am using torch 1.0.0
I need to use the Flatten layer for Sequential model. Here's my code :
import torch
import torch.nn as nn
import torch.nn.functional as F
print(torch.__version__)
# 1.0.0
from collections import OrderedDict
layers = OrderedDict()
layers['conv1'] = nn.Conv2d(1, 5,... | [
"Just make a new Flatten layer.\nfrom collections import OrderedDict\n\nclass Flatten(nn.Module):\n def forward(self, input):\n return input.view(input.size(0), -1)\n\nlayers = OrderedDict()\nlayers['conv1'] = nn.Conv2d(1, 5, 3)\nlayers['relu1'] = nn.ReLU()\nlayers['conv2'] = nn.Conv2d(5, 1, 3)\nlayers['r... | [
6,
0
] | [] | [] | [
"conv_neural_network",
"python",
"pytorch"
] | stackoverflow_0061039700_conv_neural_network_python_pytorch.txt |
Q:
Concatenate along last dimension with custom layer with Tensorflow
I'm trying to concatenate a number to the last dimension of a (None, 10, 3) tensor to make it a (None, 10, 4) tensor using a custom layer. It seems impossible, because to concatenate, all the dimensions except for the one being merged on must be eq... | Concatenate along last dimension with custom layer with Tensorflow | I'm trying to concatenate a number to the last dimension of a (None, 10, 3) tensor to make it a (None, 10, 4) tensor using a custom layer. It seems impossible, because to concatenate, all the dimensions except for the one being merged on must be equal and we can't initialize a tensor with 'None' as the first dimension.... | [
"You will have to make sure you respect the batch dimension. Maybe something like this:\noutp = tf.concat([inputs, tf.cast(tf.repeat(self.positional_embeddings_array[None, ...], repeats=tf.shape(inputs)[0], axis=0), dtype=tf.float32)], axis = 2)\n\nAlso, tf.shape gives you the dynamic shape of a tensor.\n",
"your... | [
1,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074411652_keras_python_tensorflow.txt |
Q:
using xpath with lxml isn't returning a value
I'm trying to get the header of this website (https://en.wikipedia.org/wiki/Wikipedia:About) by using beautiful soup and lxml's xpath.
This is the code that I'm using
from bs4 import BeautifulSoup
from lxml import etree
import requests
xpath_url = "https://en.wikipedi... | using xpath with lxml isn't returning a value | I'm trying to get the header of this website (https://en.wikipedia.org/wiki/Wikipedia:About) by using beautiful soup and lxml's xpath.
This is the code that I'm using
from bs4 import BeautifulSoup
from lxml import etree
import requests
xpath_url = "https://en.wikipedia.org/wiki/Wikipedia:About"
xpath_headers = ({'User... | [
"Try something like\nfrom lxml import html as lh\n\ndom = xpath_wpage.fromstring(req.text,'lxml')\nprint(\" \".join(doc.xpath('//h1[@id=\"firstHeading\"]//text()'))\n\nOutput:\n'Wikipedia : About'\n\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"lxml",
"python",
"web_scraping"
] | stackoverflow_0074416837_beautifulsoup_lxml_python_web_scraping.txt |
Q:
Change Palette color index in Python
I got this image.
The image is PNG, in mode P, palette is mode RGB.
I need to stay with 16 colors, as I want the image as 4bpp.
And I need to change his palette, making the color pink (255, 192, 203) its first index.
The image palette is:
{(255, 255, 232): 0, (255, 192, 203): 1... | Change Palette color index in Python | I got this image.
The image is PNG, in mode P, palette is mode RGB.
I need to stay with 16 colors, as I want the image as 4bpp.
And I need to change his palette, making the color pink (255, 192, 203) its first index.
The image palette is:
{(255, 255, 232): 0, (255, 192, 203): 1, (210, 204, 147): 2, (62, 214, 108): 3, (... | [
"If I understand correctly, you want to keep the image unchanged, and replace the index of the pink color to be 0.\nWhen we modify the palette, we are switching between the two colors:\nAll the pixels with color (255, 255, 232) are switched to pink color (255, 192, 203), and all the pixels with pink color (255, 192... | [
3
] | [] | [] | [
"color_palette",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0074414820_color_palette_image_processing_python_python_imaging_library.txt |
Q:
Check if score is equal to the last score checked, and if it is, put both of them in the same rank from a dict
I need to check if the score is equal to the previous one, if it is, change both to the same one.
But I can't figure out how. I have included the file and the json file
I have also removed a few functions... | Check if score is equal to the last score checked, and if it is, put both of them in the same rank from a dict | I need to check if the score is equal to the previous one, if it is, change both to the same one.
But I can't figure out how. I have included the file and the json file
I have also removed a few functions that i think are unnecessary, but if you want to see it it is
https://github.com/IdkDwij/PLTW-CSP-1.2.2/tree/main
i... | [
"Well, it's really quite simple:\ndef checkTie():\n leaderboard = getLeaderBoard()\n lastScore = -1\n rank = 0\n for x in enumerate(leaderboard[\"score\"]):\n if lastScore != leaderboard[\"score\"][x]:\n rank += 1\n leaderboard[\"rank\"][x] = rank\n lastScore = leaderboard[\"score\"]\n return lea... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074417010_python.txt |
Q:
Pygame player spawn
I'm making a game and the player spawn is off I've tried tutorials and I haven't found anything here is my code and a photo I've tried playing with the code But I can't seem to find how to change my player spawn please can help I'm stuck
from pickle import FALSE
import pygame
from pygame.loc... | Pygame player spawn | I'm making a game and the player spawn is off I've tried tutorials and I haven't found anything here is my code and a photo I've tried playing with the code But I can't seem to find how to change my player spawn please can help I'm stuck
from pickle import FALSE
import pygame
from pygame.locals import *
pygame.ini... | [
"In your code, specify the top left position of the rectangle:\n\nself.rect = self.image.get_rect()\nself.rect.x = x\nself.rect.y = y\n\n\nA pygame.Rect object has a lot of virtual attributes:\n\nx,y\ntop, left, bottom, right\ntopleft, bottomleft, topright, bottomright\nmidtop, midleft, midbottom, midright\ncenter,... | [
0,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074379484_pygame_python.txt |
Q:
Pycaret - Stuck on Setup()
I'm using Pycaret classification to do some machine learning with my >1 million of data (this includes 18 categorical and 1 numerical features). Pandas Dataframe is storing the data pulled from Oracle database. These steps take about 2-3 minutes. When my data is being preprocessed, it's ... | Pycaret - Stuck on Setup() | I'm using Pycaret classification to do some machine learning with my >1 million of data (this includes 18 categorical and 1 numerical features). Pandas Dataframe is storing the data pulled from Oracle database. These steps take about 2-3 minutes. When my data is being preprocessed, it's taking >7 hours. Is there a way ... | [
"In pycaret, you can use use_gpu=True and Turbo=True\n",
"What shape is the data after setup()?\nWith that many categorical features there's a chance your features multiplied by orders of magnitude due to default one hot enconding pycaret setup() uses.\nIf that is the case, you should use high_cardinality_feature... | [
0,
0
] | [] | [] | [
"pycaret",
"python"
] | stackoverflow_0067000519_pycaret_python.txt |
Q:
Read json from file.json.bz2 quickly
I'm trying to open a bz2 file and read the json file contained inside. My current implementation looks like
with bz2.open(bz2_file_path, 'rb') as f:
json_content = f.read()
json_df = pd.read_json(json_content.decode('utf-8'), lines = True)
I need to repeat this process man... | Read json from file.json.bz2 quickly | I'm trying to open a bz2 file and read the json file contained inside. My current implementation looks like
with bz2.open(bz2_file_path, 'rb') as f:
json_content = f.read()
json_df = pd.read_json(json_content.decode('utf-8'), lines = True)
I need to repeat this process many times, and the the with block is taking ... | [
"The following variation of your code won't necessarily read all the code into memory at once. Passing encoding to bz2.open() allows the decoding to be done on the fly, and panads.read_json() can accept a file-like object to read incrementally.\nwith bz2.open(bz2_file_path, 'rt', encoding='utf-8') as f:\n json_df ... | [
2
] | [] | [] | [
"bz2",
"json",
"pandas",
"python"
] | stackoverflow_0074417046_bz2_json_pandas_python.txt |
Q:
How to click on a button with only classname? Selenium Python
Im having trouble to let Selenium click on a button for me.The button is:
<button data-v-4c4862d1="" data-v-149d3c0b="" class="btn btn-success">
Activate
</button>
I tried the following things :
driver.find_element(By.CLASS_NAME, 'btn... | How to click on a button with only classname? Selenium Python | Im having trouble to let Selenium click on a button for me.The button is:
<button data-v-4c4862d1="" data-v-149d3c0b="" class="btn btn-success">
Activate
</button>
I tried the following things :
driver.find_element(By.CLASS_NAME, 'btn btn-success').click()
as well as ;
activate_button = driver.find... | [
"The line driver.find_element(By.CLASS_NAME, 'btn btn-success') only finds the element but does not \"click\".\nTry this:\nelement_to_click = driver.find_element(By.CLASS_NAME, 'btn btn-success')\nelement_to_click.click()\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074417099_python_selenium.txt |
Q:
how do I use Python requests to api.trafikinfo.trafikverket.se/API?
I am trying to use an API from trafikverket.se to get current air temperatures in Python. I've registered an account and got a key to use for my request. But even though I am trying their example code I can not get it to work.
API request document... | how do I use Python requests to api.trafikinfo.trafikverket.se/API? | I am trying to use an API from trafikverket.se to get current air temperatures in Python. I've registered an account and got a key to use for my request. But even though I am trying their example code I can not get it to work.
API request documentation trafikverket.se
my python code:
import requests
data = """
<REQUES... | [
"From the documentation you linked to, it looks like they require a Content-Type header (translated to English):\n\nContent-Type\nAs of version 2, the POST call must have one of the following values in the Content-Type header:\napplication/xml\ntext/xml\ntext/plain (triggers no CORS preflight, more info here .)\n... | [
1
] | [] | [] | [
"api",
"json",
"python",
"python_requests"
] | stackoverflow_0074404517_api_json_python_python_requests.txt |
Q:
Pandas reverse of diff()
I have calculated the differences between consecutive values in a series, but I cannot reverse / undifference them using diffinv():
ds_sqrt = np.sqrt(ds)
ds_sqrt = pd.DataFrame(ds_sqrt)
ds_diff = ds_sqrt.diff().values
How can I undifference this?
A:
You can do this via numpy. Algorit... | Pandas reverse of diff() | I have calculated the differences between consecutive values in a series, but I cannot reverse / undifference them using diffinv():
ds_sqrt = np.sqrt(ds)
ds_sqrt = pd.DataFrame(ds_sqrt)
ds_diff = ds_sqrt.diff().values
How can I undifference this?
| [
"You can do this via numpy. Algorithm courtesy of @Divakar.\nOf course, you need to know the first item in your series for this to work.\ndf = pd.DataFrame({'A': np.random.randint(0, 10, 10)})\ndf['B'] = df['A'].diff()\n\nx, x_diff = df['A'].iloc[0], df['B'].iloc[1:]\ndf['C'] = np.r_[x, x_diff].cumsum().astype(int)... | [
14,
6,
4,
1,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0049903037_arrays_numpy_pandas_python_python_3.x.txt |
Q:
How to join multiple dataframe columns based on row index to specified column?
PROBLEM STATEMENT:
I'm trying to join multiple pandas data frame columns, based on row index, to a single column already in the data frame. Issues seem to happen when the data in a column is read in as np.nan.
EXAMPLE:
Original Data fra... | How to join multiple dataframe columns based on row index to specified column? | PROBLEM STATEMENT:
I'm trying to join multiple pandas data frame columns, based on row index, to a single column already in the data frame. Issues seem to happen when the data in a column is read in as np.nan.
EXAMPLE:
Original Data frame
time
msg
d0
d1
d2
0
msg0
a
b
c
1
msg1
x
x
x
2
msg0
a
b
c
3
msg2
1
2... | [
"You can use:\ncols = ['d0', 'd1', 'd2']\n\n# get the rows matching the msg condition\nm = df['msg'].isin(['msg0', 'msg2'])\n\n# get relevant columns\n# concatenate the non-NaN value\n# update as DataFrame to assign NaN is the non-first columns\ndf.loc[m, cols] = (df\n .loc[m, cols]\n .agg(lambda r: ''.join(r.d... | [
1,
1
] | [] | [] | [
"data_cleaning",
"pandas",
"python"
] | stackoverflow_0074416925_data_cleaning_pandas_python.txt |
Q:
Create separate pandas dataframes based on a column and operate on them
I have the following code, which works, but surely there has to be a more efficient way to loop through these steps.
First, here's the data frame. You will see we have some tweets about some cereals, nothing fancy.
import pandas as pd
df = pd.... | Create separate pandas dataframes based on a column and operate on them | I have the following code, which works, but surely there has to be a more efficient way to loop through these steps.
First, here's the data frame. You will see we have some tweets about some cereals, nothing fancy.
import pandas as pd
df = pd.DataFrame([['Cheerios', 'I love Cheerios they are the best'], ['FrostedFlakes... | [
"Looking at your examples you probably want to look at .pivot_table or pd.crosstab:\ndf = df.assign(Tweet=df[\"Tweet\"].str.split()).explode(\"Tweet\")\nprint(pd.crosstab(df[\"Tweet\"], df[\"Label\"]))\n\nPrints:\nLabel Cheerios FrostedFlakes FruityPebbles\nTweet \n... | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"pandas",
"python"
] | stackoverflow_0074417127_dataframe_for_loop_pandas_python.txt |
Q:
Can't install packages in virtual environment created with venv
I am developing in the following environment:
Windows11 21H2.
Ubuntu-20.04
Visual Studio Code 2022
Remote-WSL extension in VSCode
Python3.8.10 64-bit
I formatted a USB drive in NTFS format and installed Django in the virtual environment with the fol... | Can't install packages in virtual environment created with venv | I am developing in the following environment:
Windows11 21H2.
Ubuntu-20.04
Visual Studio Code 2022
Remote-WSL extension in VSCode
Python3.8.10 64-bit
I formatted a USB drive in NTFS format and installed Django in the virtual environment with the following procedure:
sudo python3 -m venv .venv
sudo source .venv/bin/ac... | [
"As mentioned in the comments, sudo is problematic here. There are a few problems with using sudo with a venv in this case:\n\nTypically, sudo python3 -m venv .venv would create the venv as root, but you mention that you are doing this on an NTFS-formatted USB drive. Because of the way that WSL accesses NTFS driv... | [
0
] | [] | [] | [
"python",
"python_venv",
"ubuntu",
"windows_subsystem_for_linux"
] | stackoverflow_0074413864_python_python_venv_ubuntu_windows_subsystem_for_linux.txt |
Q:
Discord bot only working in pm, how can i fix this?
This is the code, it only answers me in private messages but not in any group chat.
import discord
import random
import time
import asyncio
token = "number that im not gonna show"
client = discord.Client(intents=discord.Intents.default())
@client.event
async d... | Discord bot only working in pm, how can i fix this? | This is the code, it only answers me in private messages but not in any group chat.
import discord
import random
import time
import asyncio
token = "number that im not gonna show"
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_ready():
print(f"Bot logged on as {client.user... | [
"You don't have the message_content intent, so you can't read messages except\n\nDM's\nMessages your bot is @mentioned in\n\nIf you'd like to read messages, enable this intent both in code and on the developer portal.\nDocs: https://discordpy.readthedocs.io/en/stable/intents.html\nPS. instead of manually trying to ... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074417159_discord.py_python.txt |
Q:
Write a program that changes to letters given in an array to '* "in a given string
Write a function that changes letters given in an array to '*' in a given string.
'Irisk' ['i','k'] -> *r * s *
I have tried using:
def filter(word, lett):
new_word = ''
for c in word:
if c == lett:
new_w... | Write a program that changes to letters given in an array to '* "in a given string | Write a function that changes letters given in an array to '*' in a given string.
'Irisk' ['i','k'] -> *r * s *
I have tried using:
def filter(word, lett):
new_word = ''
for c in word:
if c == lett:
new_word += '*'
else:
new_word += c
return new_word
| [
"You can use a loop to go with \"*\" or the original letter if the letter is in a list.\nThen combine the characters using ''.join().\nLike this:\nmy_string = 'Irisk'\nmy_list = ['i', 'k']\nnew_string = ''.join(\"*\" if (c.lower() in my_list) else c for c in my_string)\n\nResult:\n'*r*s*'\n\n",
"use 'in' instead ... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074417135_python.txt |
Q:
I get an EOF error when running my code, what can i do?
Basically i have a programm in which you must set the teachers patience and then count "one", "two", "three", "four", "one" and etc and when you fail it write "the streak was ... , but you failed" and after the patience reaches 0 the teacher says "enough for ... | I get an EOF error when running my code, what can i do? | Basically i have a programm in which you must set the teachers patience and then count "one", "two", "three", "four", "one" and etc and when you fail it write "the streak was ... , but you failed" and after the patience reaches 0 the teacher says "enough for today" and ignores all inputs afterwards, but when i get an o... | [
"Reason\nLets look at the while loop, when you first guess it right, the variable mistake is set to false. so if you guess wrong on the second time around the mistake is set to true. On the third time around if you guess wrong again nothing will happen. cause nextNum is not equal to variable a, and mistake was set ... | [
0
] | [] | [] | [
"eof",
"python"
] | stackoverflow_0074302522_eof_python.txt |
Q:
I need to add threads to this code how to do it?
I need to add threads to this code but it doesn't work. The teacher gave advice to create a list that stores the parameters to use, but I can't figure out how to do it
a = 1
b = 3
E = 0.07
def f(x):
return x**4
def quad(left, right, fleft, fright, lr_area):
... | I need to add threads to this code how to do it? | I need to add threads to this code but it doesn't work. The teacher gave advice to create a list that stores the parameters to use, but I can't figure out how to do it
a = 1
b = 3
E = 0.07
def f(x):
return x**4
def quad(left, right, fleft, fright, lr_area):
mid = (left + right)/2
fmid = f(mid)
l_area ... | [
"here is my code if anyone is interested\nimport threading\n\na = 1\nb = 3\nE = 0.07\nst = int(input(\"Write number: \"))\n\n\ndef f(x):\n return x**st\n\nlparametrs_list = [a, b, f(a), f(b), (f(a) + f(b))*(b-a)/2]\n\nrparametrs_list = [a, b, f(a), f(b), (f(a) + f(b))*(b-a)/2]\n\n\ndef llist_updater(l_list):\n ... | [
0
] | [] | [] | [
"multithreading",
"python",
"python_3.x"
] | stackoverflow_0074413463_multithreading_python_python_3.x.txt |
Q:
Extract all possible combinations of unique elements in dict of lists
I have this input:
d = {'a': ['A', 'B', 'C'], 'b': ['A', 'B', 'C'], 'c': ['D', 'E'], 'd': ['E', 'F', 'G']}
How can I extract all the possible unique samplings per list?
One of the possible output is for example:
d = {'a': 'A', 'b': 'B', 'c': 'D... | Extract all possible combinations of unique elements in dict of lists | I have this input:
d = {'a': ['A', 'B', 'C'], 'b': ['A', 'B', 'C'], 'c': ['D', 'E'], 'd': ['E', 'F', 'G']}
How can I extract all the possible unique samplings per list?
One of the possible output is for example:
d = {'a': 'A', 'b': 'B', 'c': 'D', 'd': 'E'}
or
d = {'a': 'B', 'b': 'A', 'c': 'E', 'd': 'F'}
and so on..
... | [
"This is what you are looking for\nimport itertools\nkeys, values = zip(*d.items())\npermutations_dicts = [dict(zip(keys, v)) for v in itertools.product(*values)]\n\n"
] | [
1
] | [] | [] | [
"list",
"python",
"sampling"
] | stackoverflow_0074417180_list_python_sampling.txt |
Q:
Create button to update in django posts with javascript fetch
I have an html that displays user's posts. At the same time, the post model is accessible via fetch (javascript). I want to create a button to update the content of the posts that django shows but with the fetch. The problem is that when the button is c... | Create button to update in django posts with javascript fetch | I have an html that displays user's posts. At the same time, the post model is accessible via fetch (javascript). I want to create a button to update the content of the posts that django shows but with the fetch. The problem is that when the button is created in my code, instead of creating a button for each post, it c... | [
"I have solved the problem in this way. So far (before testing it much) it has worked. The difference is the querySelectorAll the variable i and the i++\ndata.forEach(post => {\n console.log(post.usuario);\n \n post_div = document.querySelectorAll('.post-div-class')[i]; \n ... | [
0
] | [] | [] | [
"django",
"fetch",
"javascript",
"posts",
"python"
] | stackoverflow_0074403118_django_fetch_javascript_posts_python.txt |
Q:
Can i have some python code in second file and when i run the first file its like the code is inside the first file?
I have 2 python files and i want to run the second file in the first one like the code in the second file was inside the first file. Is this possible and if so how?
I dont know what to try please he... | Can i have some python code in second file and when i run the first file its like the code is inside the first file? | I have 2 python files and i want to run the second file in the first one like the code in the second file was inside the first file. Is this possible and if so how?
I dont know what to try please help. Thanks!
| [
"Just like how you can use import to import other python libraries (built-in or third-party), you can also import your own libraries/modules/files. if the two files are in the same directory, you can do import file2 at the top of file one and run any of the functions or modules within it.\nex:\n# this is file_2\n\n... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074417238_python_python_3.x.txt |
Q:
Using function variables in another function
I'm struggling a bit as a new python learner, I have a "code" function that returns a concatenated code entered. I'm trying to create another function that takes that same code and prints the variables separately.
for exemple: n1 = 30, gender = m, n2 = 22
the code funct... | Using function variables in another function | I'm struggling a bit as a new python learner, I have a "code" function that returns a concatenated code entered. I'm trying to create another function that takes that same code and prints the variables separately.
for exemple: n1 = 30, gender = m, n2 = 22
the code function returns : 30m22
and code_details function shou... | [
"Love your name, and are you still playing basketball?\nTry the code below,\ndef code():\n n1 = input(\"enter number 1 :\")\n gender = input(\"enter male or female :\")\n n2= input(\"enter number 2 :\")\n result = \"{n1}{gender}{n2}\".format(n1=n1, gender=gender, n2=n2)\n return result, n1, gender, n... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074417230_python.txt |
Q:
Why duplicates aren't being removed in Pandas
Very new to Python and Pandas...but the issue is that my final output file isn't excluding any duplicates on the 'Customer Number'. Any suggestions on why this would be happening would be appreciated!
import pandas as pd
import numpy as np #numpy is the module which c... | Why duplicates aren't being removed in Pandas | Very new to Python and Pandas...but the issue is that my final output file isn't excluding any duplicates on the 'Customer Number'. Any suggestions on why this would be happening would be appreciated!
import pandas as pd
import numpy as np #numpy is the module which can replace errors from huge datasets
from openpyxl... | [
"You should assign the return value of df_all.drop_duplicates to a variable or set inplace=True to have the DataFrame contents overwritten. This is to prevent undesired changes to the original data.\nTry:\ndf_all = df_all.drop_duplicates(subset='Customer Number', keep=False)\n\nOr the equivalent:\ndf_all.drop_dupli... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074417286_numpy_pandas_python.txt |
Q:
subclassing Q_ in pint - why does the super call not take arguments?
(Python 3.7)
pint / Q_ behavior
I want to subclass pint's quantity class and override __init__. The standard syntax fails because apparently the arguments bubble up to the object init method (which takes no argument):
# file: test.py
from pint im... | subclassing Q_ in pint - why does the super call not take arguments? | (Python 3.7)
pint / Q_ behavior
I want to subclass pint's quantity class and override __init__. The standard syntax fails because apparently the arguments bubble up to the object init method (which takes no argument):
# file: test.py
from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity
class Q_Child... | [
"This is an old question, but I had the same issue right now. As pointed out in the comments to the question, the Quantity class utilizes the __new__ operator (here is a nice description how it works).\nLeporello's example without calling __init__ works for instantiation with value and unit, but not when asking to ... | [
0
] | [] | [] | [
"pint",
"python",
"python_3.x",
"super"
] | stackoverflow_0057429429_pint_python_python_3.x_super.txt |
Q:
Cloud Flight Coding Contest - Mars Rover
Doing the Mars Rover coding problem and am stuck at level 2. Trying to debug but I just can't see it and it wont let me progress until current level is finished.
Problem Description as follows:
Calculate the position and the direction of the rover after driving a certain di... | Cloud Flight Coding Contest - Mars Rover | Doing the Mars Rover coding problem and am stuck at level 2. Trying to debug but I just can't see it and it wont let me progress until current level is finished.
Problem Description as follows:
Calculate the position and the direction of the rover after driving a certain distance with a certain steering angle.
Input: W... | [
"I'm also stuck, but what I have so far works for the first 2 inputs:\nimport math\n\nWheelBase, Distance, SteeringAngle = 1, 1, 30.00\nWheelBase, Distance, SteeringAngle = 2.13, 4.30, 23.00\n\nWheelBase = float(WheelBase)\nDistance = float(Distance)\nSteeringAngle = float(SteeringAngle)\n\nTurnRadius = abs(WheelBa... | [
0,
0
] | [] | [] | [
"python",
"trigonometry"
] | stackoverflow_0071934454_python_trigonometry.txt |
Q:
Type of a returned class
Update: as chepner points out in the comments, creating the class in the function is a bad idea, it performs ten to eighty times slower than other solutions. See the performance comparison in my self-answer, which also shows how to do the typing.
I do this:
def get_an_x():
class X:
... | Type of a returned class | Update: as chepner points out in the comments, creating the class in the function is a bad idea, it performs ten to eighty times slower than other solutions. See the performance comparison in my self-answer, which also shows how to do the typing.
I do this:
def get_an_x():
class X:
foo = 1
bar = 'H... | [
"The issue is, every time you call foo, it returns a different class. If it had a base class, you could annotate it with typing.Type[Base], to at least show the base's attributes. But in your situation I'd suggest you to either let your IDE figure it out without annotations, or to annotate it as typing.Type.\nOne m... | [
1,
1
] | [] | [] | [
"python",
"python_typing"
] | stackoverflow_0074416272_python_python_typing.txt |
Q:
Scrape webpage element with text or href criteria simultaneously
In the code below I can either write a function to pass to soup.find_all to search for regular expressions in the text or search with href keyword inside the reference.
from bs4 import BeautifulSoup
import re
# s is an example string. Scraping a web... | Scrape webpage element with text or href criteria simultaneously | In the code below I can either write a function to pass to soup.find_all to search for regular expressions in the text or search with href keyword inside the reference.
from bs4 import BeautifulSoup
import re
# s is an example string. Scraping a webpage in reality.
s = """<tr>
<td><a href="/-/media/market... | [
"In this particular case, if you have html5lib parser, you can use CSS selectors\nauction_results = soup.select('tr:-soup-contains(\"3rd Incremental Auction\"), tr:has(*[href*=\"base-residual\"])')\n\nor, if you want to parametrize it a bit\ninText, inAttr = \"3rd Incremental Auction\", \"base-residual\"\ntag, attr... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074410699_beautifulsoup_python_web_scraping.txt |
Q:
'Prophet' object has no attribute 'stan_backend'
I'm trying to use Facebook prophet for a project. The problem is that when I try to use it I have an error :
'Prophet' object has no attribute 'stan_backend'
when I initialize the prophet
from prophet import Prophet
m = Prophet()
I have installed prophet and pystan... | 'Prophet' object has no attribute 'stan_backend' | I'm trying to use Facebook prophet for a project. The problem is that when I try to use it I have an error :
'Prophet' object has no attribute 'stan_backend'
when I initialize the prophet
from prophet import Prophet
m = Prophet()
I have installed prophet and pystan 1.19.1.1 using a pipenv. Here is my Pipfile
numpy = "... | [
"This method works for me :\nCreating new environment and use conda install -c conda-forge prophet in cmd\n",
"I faced this issue on my windows machine while working with Prophet.\nSetting the environment variable pointing to 'CMDSTAN' directory fixed it.\nimport os\nos.environ['CMDSTAN'] = \"C:/Anaconda/Anaconda... | [
1,
1
] | [] | [] | [
"facebook_prophet",
"intellij_idea",
"pip",
"pipenv",
"python"
] | stackoverflow_0070169628_facebook_prophet_intellij_idea_pip_pipenv_python.txt |
Q:
Guess the word with definitions? (nested tuples)
I am trying to create a function that prints a random word, and then its definition only using nested tuples (stated clearly in my assignment that i cannot use anything else…). The problem is that i then need to import this function into another program that makes t... | Guess the word with definitions? (nested tuples) | I am trying to create a function that prints a random word, and then its definition only using nested tuples (stated clearly in my assignment that i cannot use anything else…). The problem is that i then need to import this function into another program that makes the user guess the word, and, at the end, print out the... | [
"Consider a simpler approach that involves splitting your tasks. Below gives a random word from list and its meaning on each function call in import.\nimport random\n\ndef random_word_meaning():\n word_list = (('string','Collection of alphabets, words or other characters.'), \n ('int','Converts any s... | [
1
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0074416846_python_tuples.txt |
Q:
os.system() keeps giving me import errors
I am using os.system("python game2.py") to run different parts of my code.
Every time I try this it gives me an import error for example "no module named pygame" even though when I game2 itself, it works fine.
What can I do?
A:
Well, first of all, you shouldn't even do t... | os.system() keeps giving me import errors | I am using os.system("python game2.py") to run different parts of my code.
Every time I try this it gives me an import error for example "no module named pygame" even though when I game2 itself, it works fine.
What can I do?
| [
"Well, first of all, you shouldn't even do that for code in different files, you can just do import game2 and then run the functions inside of it. As an example, game2.RunGame(), If you have a function called that, of course this is just an example\n",
"Like said in other answers there is no need to run os.system... | [
0,
0
] | [] | [] | [
"operating_system",
"python"
] | stackoverflow_0074417408_operating_system_python.txt |
Q:
Most efficient way to calculate mean of a large array?
I have some large .csv files of experimental data. Their sizes are in the range 30MB-3GB. I have successfully read them in using pandas and have performed some other calculations on the data. As it stands I have an extremely long 1D array which I need to take ... | Most efficient way to calculate mean of a large array? | I have some large .csv files of experimental data. Their sizes are in the range 30MB-3GB. I have successfully read them in using pandas and have performed some other calculations on the data. As it stands I have an extremely long 1D array which I need to take the mean of.
By default I used statistics.mean(array) but th... | [
"It Depends on the size of the array you could just loop over it and divide by the size of the array at the end:\ndef GetMean(ionVelocityArray):\n total = 0\n for _ in ionVelocityArray:\n total += 1\n\n return total / len(ionVelocityArray)\n\nBut if it over 20k elements i would sort the array and do ... | [
0,
0
] | [] | [] | [
"mean",
"python",
"statistics"
] | stackoverflow_0074405944_mean_python_statistics.txt |
Q:
IndexError: tuple index out of range in LabelEncoder Sklearn
I would like to train a DecisionTree using sklearn Pipeline. My goal is to predict the 'language' column, using the 'tweet' as ngram transformed features. However I am not able to make the LabelEncoder transformation works for the 'language' column insid... | IndexError: tuple index out of range in LabelEncoder Sklearn | I would like to train a DecisionTree using sklearn Pipeline. My goal is to predict the 'language' column, using the 'tweet' as ngram transformed features. However I am not able to make the LabelEncoder transformation works for the 'language' column inside a pipeline. I saw that there is a common error, but also if I tr... | [
"Imo there are a couple of main issues linked to the way you're dealing with your CountVectorizer instance.\nFirst off, CountVectorizer requires 1D input, in which case (I mean with such transformers) ColumnTransformer requires parameter column to be passed as a scalar string or int; you might find a detailed expla... | [
1
] | [] | [] | [
"decision_tree",
"python",
"scikit_learn",
"sklearn_pandas",
"tuples"
] | stackoverflow_0074411976_decision_tree_python_scikit_learn_sklearn_pandas_tuples.txt |
Q:
Keyboard input with timeout?
How would you prompt the user for some input but timing out after N seconds?
Google is pointing to a mail thread about it at http://mail.python.org/pipermail/python-list/2006-January/533215.html but it seems not to work. The statement in which the timeout happens, no matter whether it ... | Keyboard input with timeout? | How would you prompt the user for some input but timing out after N seconds?
Google is pointing to a mail thread about it at http://mail.python.org/pipermail/python-list/2006-January/533215.html but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.s... | [
"Using a select call is shorter, and should be much more portable\nimport sys, select\n\nprint \"You have ten seconds to answer!\"\n\ni, o, e = select.select( [sys.stdin], [], [], 10 )\n\nif (i):\n print \"You said\", sys.stdin.readline().strip()\nelse:\n print \"You said nothing!\"\n\n",
"The example you have ... | [
114,
45,
16,
15,
13,
10,
5,
5,
4,
3,
3,
3,
3,
2,
2,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"A late answer :)\nI would do something like this:\nfrom time import sleep\n\nprint('Please provide input in 20 seconds! (Hit Ctrl-C to start)')\ntry:\n for i in range(0,20):\n sleep(1) # could use a backward counter to be preeety :)\n print('No input is given.')\nexcept KeyboardInterrupt:\n raw_inp... | [
-4
] | [
"keyboard_input",
"python",
"timeout"
] | stackoverflow_0001335507_keyboard_input_python_timeout.txt |
Q:
How to choose random values in an range?
for i in range(0,500,10):
xsnake=random(i)
for b in range(0,500,10):
ysnake=random(b)
Hello, I wanted to know how I can choose randomly in the i of range in the variable below.
Thanks.
A:
You can try random.randrange
import random
print(random.ran... | How to choose random values in an range? | for i in range(0,500,10):
xsnake=random(i)
for b in range(0,500,10):
ysnake=random(b)
Hello, I wanted to know how I can choose randomly in the i of range in the variable below.
Thanks.
| [
"You can try random.randrange\n import random\n print(random.randrange(0,500,10) \n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074417527_python.txt |
Q:
first argument must be an iterable of pandas objects, you passed an object of type "DataFrame" - not sure why
I have the following code below. I am trying to concatenate columns together and fill an empty dataframe 'emptyframe'.
The idea is that I start with 3 columns, then add on another 3 columns, then another 3... | first argument must be an iterable of pandas objects, you passed an object of type "DataFrame" - not sure why | I have the following code below. I am trying to concatenate columns together and fill an empty dataframe 'emptyframe'.
The idea is that I start with 3 columns, then add on another 3 columns, then another 3 colums etc...
emptyframe = pd.DataFrame()
for j in range(0,len(df.columns)):
newdata = pd.concat((newdf.loc[:... | [
"I used the 'append' function to solve this issue:\nemptyframe = pd.DataFrame()\n\nfor j in range(0,len(df.columns)):\n newdata = pd.concat((newdf.iloc[:,j],happydf.iloc[:,j],motivedf.iloc[:,j]),axis=1)\n emptyframe = emptyframe.append(newdata) \n\nprint(emptyframe)\n\n:)\n"
] | [
0
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074417453_dataframe_jupyter_notebook_pandas_python.txt |
Q:
Python is crashing at random points. Any suggestions? Could it be a memory problem?
I am writing a Python genetic algorithm optimization library, and am finding my kernel is dying at random points for one of the problems I'm working on. The crashes have me pretty stumped, and any advice would be welcome.
Backgroun... | Python is crashing at random points. Any suggestions? Could it be a memory problem? | I am writing a Python genetic algorithm optimization library, and am finding my kernel is dying at random points for one of the problems I'm working on. The crashes have me pretty stumped, and any advice would be welcome.
Background:
I'm using Python 3.8.8.
Among lots of other code, my library has the following objects... | [
"For anyone who encounters similar issues, this was a memory problem for me. Large amounts of data was being recorded in memory and eventually crashed the script. The solution I employed was just to store less data in memory.\n"
] | [
0
] | [] | [] | [
"memory",
"python"
] | stackoverflow_0067137237_memory_python.txt |
Q:
Installing venv for python3 in WSL (Ubuntu)
I am trying to configure venv on Windows Subsystem for Linux with Ubuntu.
What I have tried:
1) Installing venv through pip (pip3, to be exact)
pip3 install venv
I get the following error
ERROR: Could not find a version that satisfies the requirement venv (from versions... | Installing venv for python3 in WSL (Ubuntu) | I am trying to configure venv on Windows Subsystem for Linux with Ubuntu.
What I have tried:
1) Installing venv through pip (pip3, to be exact)
pip3 install venv
I get the following error
ERROR: Could not find a version that satisfies the requirement venv (from versions: none)
ERROR: No matching distribution found for... | [
"Nothing here worked for me, but this did in WSL2:\nsudo apt-get update\nsudo apt-get install libpython3-dev\nsudo apt-get install python3-venv\npython3.8 -m venv whatever\n\nGood luck!\n",
"Give this approach a shot:\nInstall the pip:\nsudo apt-get install python-pip\n\nInstall the virtual environment:\nsudo pip... | [
48,
36,
12,
5,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"python_venv",
"ubuntu",
"windows_subsystem_for_linux"
] | stackoverflow_0061528500_python_python_3.x_python_venv_ubuntu_windows_subsystem_for_linux.txt |
Q:
List not defined in a function in Python
I am working on one of my first codes (Tic Tac Toe), and I cannot figure out why I'm getting a name error.
First I have a list (board).
Then I have a function (possible_victory_for() ) that I define. It is supposed to to something with a list (temp_board) that will be defin... | List not defined in a function in Python | I am working on one of my first codes (Tic Tac Toe), and I cannot figure out why I'm getting a name error.
First I have a list (board).
Then I have a function (possible_victory_for() ) that I define. It is supposed to to something with a list (temp_board) that will be defined later, within the next function.
The next f... | [
"temp_board is local to computer_move, but you're treating it as if it were a global. You should make it a parameter to possible_victory_for:\ndef possible_victory_for(sign, temp_board):\n # if (temp_board[0] ...\n\nand then pass it from computer_move as an argument:\n if possible_victory_for(\"X\", temp_boa... | [
2
] | [] | [] | [
"function",
"list",
"nameerror",
"python",
"tic_tac_toe"
] | stackoverflow_0074417568_function_list_nameerror_python_tic_tac_toe.txt |
Q:
Python requests wait for redirect
I'm trying to access a website that verifies I'm not a bot by redirecting after a few seconds. How do I have the requests module wait for a redirect?
Edit: It seems I didn't entirely understand the problem. I liked Kirk Strauser's response, but couldn't find a location header.
I f... | Python requests wait for redirect | I'm trying to access a website that verifies I'm not a bot by redirecting after a few seconds. How do I have the requests module wait for a redirect?
Edit: It seems I didn't entirely understand the problem. I liked Kirk Strauser's response, but couldn't find a location header.
I found out that the site was managed with... | [
"The requests module has a parameter for configuring allow_redirects if you need to follow the redirected 300-series response.\nhttps://docs.python-requests.org/en/master/user/quickstart/#redirection-and-history\n>>> r = requests.get('http://github.com/', allow_redirects=False)\n\n>>> r.status_code\n301\n\n>>> r.hi... | [
0,
0,
0
] | [] | [] | [
"bots",
"python",
"python_requests"
] | stackoverflow_0068309784_bots_python_python_requests.txt |
Q:
Bring to the front the MainWindow in Pyqt5
I am dealing with the following problem, while I am having multiple windows open, i would like to build a function linked to a button to bring to the front the Main window.
Thank you in advance.
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication,... | Bring to the front the MainWindow in Pyqt5 | I am dealing with the following problem, while I am having multiple windows open, i would like to build a function linked to a button to bring to the front the Main window.
Thank you in advance.
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
... | [
"You could emit a signal from your second window that your fist window listens for, and calls .raise_() when triggered.\nUpdate: Added a call to activateWindow in the first windows callback. thanks @musicmante\nFor example:\nimport sys\nfrom PyQt5 import QtGui\nfrom PyQt5.QtCore import pyqtSignal # import signal\... | [
0
] | [] | [] | [
"pyqt5",
"python",
"qmainwindow",
"user_interface"
] | stackoverflow_0074417470_pyqt5_python_qmainwindow_user_interface.txt |
Q:
How can I use tuples in recursive functions?
I have to make a function where the input is a tuple consisting of 3 elements: elements 1 and 3 are numbers or other tuples with the same structure, and the second element is a string indicating an operation. An example would be (10, '-', (5, '*', 3)) and should return ... | How can I use tuples in recursive functions? | I have to make a function where the input is a tuple consisting of 3 elements: elements 1 and 3 are numbers or other tuples with the same structure, and the second element is a string indicating an operation. An example would be (10, '-', (5, '*', 3)) and should return -5.
The problem is that the function must be recur... | [
"Evaluate the left and right sides of the tuple before performing the operation.\ndef evaluate(equation):\n left, operation, right = equation\n if type(left) == tuple:\n left = evaluate(left)\n if type(right) == tuple:\n right = evaluate(right)\n if operation == \"+\":\n return left... | [
1
] | [] | [] | [
"python",
"recursion",
"tuples"
] | stackoverflow_0074417666_python_recursion_tuples.txt |
Q:
python : disable download popup when using firefox with selenium
I have script that using selenium and firefox to automating download action.
The problem is whenever I run script I always get pop up from firefox keep asking what kinds of action I would like to do, even though I set download path in firefox prefer... | python : disable download popup when using firefox with selenium | I have script that using selenium and firefox to automating download action.
The problem is whenever I run script I always get pop up from firefox keep asking what kinds of action I would like to do, even though I set download path in firefox preference. I checked files and folders to create master mimeTypes.rdf for a... | [
"I doubt you need to define both. Remove the below line from your code\nprofile.set_preference(\"browser.helperApps.neverAsk.openFile\", 'application/zip')\n\nAlso sometime the MIME type of zip file can be different based on the server. It could be any of below\n\napplication/octet-stream \nmultipart/x-zip \napplic... | [
2,
2,
0
] | [] | [] | [
"firefox",
"javascript",
"python",
"selenium"
] | stackoverflow_0045645648_firefox_javascript_python_selenium.txt |
Q:
append rows from dataframe to google sheets
I'm using google colab and I have a dataframe that I would like to append into a google spreadsheets. At the end of my code, I am using this:
from google.colab import auth
auth.authenticate_user()
import gspread
from google.auth import default
creds, _ = default()
gc =... | append rows from dataframe to google sheets | I'm using google colab and I have a dataframe that I would like to append into a google spreadsheets. At the end of my code, I am using this:
from google.colab import auth
auth.authenticate_user()
import gspread
from google.auth import default
creds, _ = default()
gc = gspread.authorize(creds)
wb = gc.open_by_key('1... | [
"df.columns.values.to_list()\n\nProbably it will work.\n"
] | [
1
] | [] | [] | [
"google_colaboratory",
"pandas",
"python"
] | stackoverflow_0074417601_google_colaboratory_pandas_python.txt |
Q:
How to create a custom decorator in Django?
I'm trying to create a custom decorator in Django but I couldn't find any ways to do it.
# "views.py"
@custom_decorator
def my_view(request):
# .......
So, how can I create it in Django? and where should I put it so that I can use it anywhere in my Django project?... | How to create a custom decorator in Django? | I'm trying to create a custom decorator in Django but I couldn't find any ways to do it.
# "views.py"
@custom_decorator
def my_view(request):
# .......
So, how can I create it in Django? and where should I put it so that I can use it anywhere in my Django project?
| [
"Played around with the various links above and couldn't get them working and then came across this really simple one which I adapted. http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/\nfrom functools import wraps\nfrom django.http import HttpResponseRedirect\n\ndef authors_only(fun... | [
81,
62,
6,
2,
1,
1,
1,
0
] | [] | [] | [
"decorator",
"django",
"python",
"python_decorators"
] | stackoverflow_0005469159_decorator_django_python_python_decorators.txt |
Q:
Label not updating from button
I'm trying to make a basic interest income calculator using GUI tkinker in Python. However, after entering all the values, the label at the end doesn't update.
Please note that calculations is just printing the variables for now
import tkinter as tk
frame = tk.Tk()
frame.title("Inter... | Label not updating from button | I'm trying to make a basic interest income calculator using GUI tkinker in Python. However, after entering all the values, the label at the end doesn't update.
Please note that calculations is just printing the variables for now
import tkinter as tk
frame = tk.Tk()
frame.title("Interest Income Calculator")
frame.geomet... | [
"To understand why it doesn't work when we use command = func() we have to understand how passing function as an argument works\nWhen we pass function with parentheses as an argument, we are first calling the function and then giving the returned value as an argument for the method or function we are using. For exa... | [
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074417493_python_tkinter.txt |
Q:
How to convert binary columns with multiple occurrences into categorical data in Pandas
I have the following example data set
A
B
C
D
foo
0
1
1
bar
0
0
1
baz
1
1
0
How could extract the column names of each 1 occurrence in a row and put that into another column E so that I get the following table:
A
B
C
D
E
... | How to convert binary columns with multiple occurrences into categorical data in Pandas | I have the following example data set
A
B
C
D
foo
0
1
1
bar
0
0
1
baz
1
1
0
How could extract the column names of each 1 occurrence in a row and put that into another column E so that I get the following table:
A
B
C
D
E
foo
0
1
1
C, D
bar
0
0
1
D
baz
1
1
0
B, C
Note that there can be mo... | [
"You can use DataFrame.dot.\ndf['E'] = df[['B', 'C', 'D']].dot(df.columns[1:] + ', ').str.rstrip(', ')\ndf\n\n A B C D E\n0 foo 0 1 1 C, D\n1 bar 0 0 1 D\n2 baz 1 1 0 B, C\n\nInspired by jezrael's answer in this post.\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074417556_dataframe_pandas_python.txt |
Q:
I have a problem with 'Int' Object is not iterable
I have a problem with integer object
I tried:
for i in range(0,10):
pyautogui.write(i)
pyautogui.press('enter')
time.sleep(1)
i expected it to say:
1
2
3
4
5
6
7
8
9
A:
The write function expects a string:
The primary keyboard function is write(). ... | I have a problem with 'Int' Object is not iterable | I have a problem with integer object
I tried:
for i in range(0,10):
pyautogui.write(i)
pyautogui.press('enter')
time.sleep(1)
i expected it to say:
1
2
3
4
5
6
7
8
9
| [
"The write function expects a string:\n\nThe primary keyboard function is write(). This function will type the characters in the string that is passed\n\nTurn i into a string first:\npyautogui.write(str(i))\n\n"
] | [
1
] | [] | [] | [
"integer",
"iterable",
"object",
"pyautogui",
"python"
] | stackoverflow_0074417714_integer_iterable_object_pyautogui_python.txt |
Q:
Pyautogui error: The Pillow package is required to use this function
My pyautogui program gives me the following error when I do:
position = pyautogui.locateCenterOnScreen(image, confidence=.7)
Error message:
File "C:\Users\ashis\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line... | Pyautogui error: The Pillow package is required to use this function | My pyautogui program gives me the following error when I do:
position = pyautogui.locateCenterOnScreen(image, confidence=.7)
Error message:
File "C:\Users\ashis\AppData\Local\Programs\Python\Python39\lib\site-packages\pyscreeze\__init__.py", line 144, in wrapper
raise PyScreezeException('The Pillow package is requi... | [
"That's a small problem, just update your Pillow package.\npip install Pillow --upgrade\n\nPillow-4.2.1 was on my system, it upgraded to Pillow-5.1.0 and now everything works just fine.\n",
"pip install pyautogui --upgrade\n\n"
] | [
4,
0
] | [] | [] | [
"pyautogui",
"python",
"python_imaging_library"
] | stackoverflow_0071213028_pyautogui_python_python_imaging_library.txt |
Q:
Type one of several classes
Let's say I have the following two classes:
class Literal:
pass
class Expr:
pass
class MyClass:
def __init__(self, Type:OneOf(Literal, Expr)):
pass
How would I make the type one of the Expr or Literal class? The full example of what I'm trying to do is as follows:... | Type one of several classes | Let's say I have the following two classes:
class Literal:
pass
class Expr:
pass
class MyClass:
def __init__(self, Type:OneOf(Literal, Expr)):
pass
How would I make the type one of the Expr or Literal class? The full example of what I'm trying to do is as follows:
from enum import Enum
PrimitiveT... | [
"You can refer post:\nHow to express multiple types for a single parameter or a return value in docstrings that are processed by Sphinx?\nfrom typing import Union\n\nand\ndef __init__(self, Type:Union[Array,Struct,PrimitiveType])\n\n",
"You want a Union type:\nfrom typing import Union\n\ndef __init__(self, Key: s... | [
2,
1
] | [] | [] | [
"python",
"python_3.x",
"typing"
] | stackoverflow_0074417729_python_python_3.x_typing.txt |
Q:
How to find collar number in python
Take the first four characters of your surname - this is your dog name. Now, using the mapping suggested in Lecture 8 (slides 18 and 19), work out your collar number.
For example
"My dog name is LEVI and my collar number is 214873"
I want to know the method how it find.
A:
The... | How to find collar number in python | Take the first four characters of your surname - this is your dog name. Now, using the mapping suggested in Lecture 8 (slides 18 and 19), work out your collar number.
For example
"My dog name is LEVI and my collar number is 214873"
I want to know the method how it find.
| [
"There is not enough information to answer this. What is \"Lecture 8 slide 18 and 19\"? If you ask a question at least provide the full context. As is, nobody will be able to answer this for you.\n"
] | [
0
] | [] | [] | [
"azure_pipeline_python_script_task",
"python"
] | stackoverflow_0074417677_azure_pipeline_python_script_task_python.txt |
Q:
Does anyone have a simple code I can reference for serial communication from Pi to Arduino?
If I make a loop on my Raspberry Pi from 1 to 10 and assigned to a variable x for a small example, how do I take it and transfer it to an Arduino via Serial to be able to be used for an angle for my stepper motor or to simp... | Does anyone have a simple code I can reference for serial communication from Pi to Arduino? | If I make a loop on my Raspberry Pi from 1 to 10 and assigned to a variable x for a small example, how do I take it and transfer it to an Arduino via Serial to be able to be used for an angle for my stepper motor or to simply make it usable as a variable in a loop?
Is there a small code from a Pi and Arduino each that ... | [
"Are you talking about general serial communication? I have something that will work on both ends. It is not simple\nHere is what you should run on the Pi.\nChange Baud rate to proper rate for your device\nChange \"Possible_Parameters\" to a list of possible angles to run\nimport time\nimport serial\nimport numpy a... | [
0
] | [] | [] | [
"arduino",
"python",
"raspberry_pi",
"serial_communication",
"serial_port"
] | stackoverflow_0074417577_arduino_python_raspberry_pi_serial_communication_serial_port.txt |
Q:
Expanding a non-singleton dimension in PyTorch, but without copying data in memory?
Say that we have a tensor s of size [a,b,c] that is not necessarily contiguous, and b>>1.
I want to expand (but not copy) it in the second dimension for n times to get a tensor of size [a,nb,c].
The issue is that I cannot find a wa... | Expanding a non-singleton dimension in PyTorch, but without copying data in memory? | Say that we have a tensor s of size [a,b,c] that is not necessarily contiguous, and b>>1.
I want to expand (but not copy) it in the second dimension for n times to get a tensor of size [a,nb,c].
The issue is that I cannot find a way to do this without explicitly copying data in memory.
The ways I know to do the operati... | [
"I don't think this is possible, and here is a minimal example to illustrate my point.\nConsider a torch.Tensor [1, 2, 3], which has size (3,). If we want to expand it without performing a copy, we would create a new view of the tensor. Imagine for example that we want to create a view that contains twice the value... | [
1
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074355156_python_pytorch.txt |
Q:
datetime.strptime is not support to convert future date?
I had the following error in Nov 13th 2022
end = datetime.strptime("2022-11-16", "%Y-%d-%m")
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/_strptime.py", l... | datetime.strptime is not support to convert future date? | I had the following error in Nov 13th 2022
end = datetime.strptime("2022-11-16", "%Y-%d-%m")
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fracti... | [
"Future dates are supported by datetime.strptime. Here, you're trying to convert a date with 16 months which is leading to the error. I'm guessing you're looking for\ndatetime.strptime(\"2022-11-16\", \"%Y-%m-%d\")\n\n",
"datetime.strptime(\"2022-11-16\", \"%Y-%d-%m\")\n\nThat format string is year-day-month, but... | [
1,
0,
0
] | [] | [] | [
"datetime",
"python",
"strptime"
] | stackoverflow_0074417757_datetime_python_strptime.txt |
Q:
Replacing BCP utility with microservice
My team want to implement a ASP.NET CORE Web API based micro service with a plan to replace bulk copy program utility. Currently we are using BCP utility to return 200,000 rows with 30 columns. The data is returned in csv format.
We created a restful endpoint and using ADO.N... | Replacing BCP utility with microservice | My team want to implement a ASP.NET CORE Web API based micro service with a plan to replace bulk copy program utility. Currently we are using BCP utility to return 200,000 rows with 30 columns. The data is returned in csv format.
We created a restful endpoint and using ADO.NET we are connecting to SQL server to extract... | [
"The following code streams the data directly from the database, so it should be quite memory efficient and performant. It is using the Sylvan Csv library functionality to create csv records directly from the SqlDataReader.\n using Microsoft.AspNetCore.Mvc;\n using Microsoft.AspNetCore.Mvc.Infrastructure;\n ... | [
0
] | [] | [] | [
"c#",
"flask_restful",
"java",
"python",
"webapi"
] | stackoverflow_0074409114_c#_flask_restful_java_python_webapi.txt |
Q:
python: get value from dataframe if it exists, else skip
I am trying to get a value from a dataframe using q = bins._get_value(gene, 'quantile') however sometimes my value for gene does not exists in the index of bins and I get a key error. In the case that gene does not exist I would essentially like to do nothin... | python: get value from dataframe if it exists, else skip | I am trying to get a value from a dataframe using q = bins._get_value(gene, 'quantile') however sometimes my value for gene does not exists in the index of bins and I get a key error. In the case that gene does not exist I would essentially like to do nothing. If gene does exist then I would like to do the following:
d... | [
"You can use wrap the body of get_bins() in a try/except to catch the KeyError and return None when a KeyError occurs. Then in the loop, check whether the result is None and append to the list if it isn't None (which means the gene was found in the dataframe).\nBy the way, the first line of a function must have a c... | [
0
] | [] | [] | [
"dataframe",
"keyerror",
"list",
"python"
] | stackoverflow_0074417825_dataframe_keyerror_list_python.txt |
Q:
How can I reiterate a sum of values without getting my variable reassigned in a oop
def orders():
orders= {
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad":... | How can I reiterate a sum of values without getting my variable reassigned in a oop | def orders():
orders= {
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00
}
while True:
try:
key = input("Item: ").title().lstrip... | [
"The value of total keeps getting reassigned in the while loop because that's what you told it to do:\ntotal = orders[key]\n\nThis reassigns total to a new value, and forgets whatever value it had before.\nIf you want to actually add up all the numbers, use += instead of =.\ntotal = 0\nwhile True:\n key = input(... | [
0
] | [] | [] | [
"python",
"variables",
"while_loop"
] | stackoverflow_0074417853_python_variables_while_loop.txt |
Q:
how to convert X to Y and Y to X at the same time in a string in python
Assume that we have a string like:XYYX. I want to get YXXY.How do I do that in python?
couldnt think of anything
A:
You could just iterate through the string and swap them.
def invert(str):
newstr = ""
for i from 0 to len(str):
if st... | how to convert X to Y and Y to X at the same time in a string in python | Assume that we have a string like:XYYX. I want to get YXXY.How do I do that in python?
couldnt think of anything
| [
"You could just iterate through the string and swap them.\ndef invert(str):\n newstr = \"\"\n for i from 0 to len(str):\n if str[i] == 'X':\n newstr += 'Y'\n else:\n newstr += 'X'\n return newstr\n\nCould also just modify the original string.\nEdit: I'm assuming this is some kind of from-scratch ... | [
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074417779_python_string.txt |
Q:
Is there a fast way to shuffle numpy image in segments?
I want to write a function that can take small images and return a permutation of them, block-wise.
Basically I want to turn this:
Into this:
There was an excellent answer in Is there a function in Python that shuffle data by data blocks? that helped me wri... | Is there a fast way to shuffle numpy image in segments? | I want to write a function that can take small images and return a permutation of them, block-wise.
Basically I want to turn this:
Into this:
There was an excellent answer in Is there a function in Python that shuffle data by data blocks? that helped me write a solution. However for ~50,000 28x28 images this takes a... | [
"Here's one approach based on this post -\ndef randomize_tiles_3D(x1, H, W):\n # W,H are width and height of blocks\n m,n,p = x1.shape\n l1,l2 = n//H,p//W\n combs = np.random.rand(m,l1*l2).argsort(axis=1)\n r,c = np.unravel_index(combs,(l1,l2))\n x1cr = x1.reshape(-1,l1,H,l2,W)\n out = x1cr[np... | [
2,
0,
0,
0
] | [] | [] | [
"image",
"numpy",
"python"
] | stackoverflow_0058074732_image_numpy_python.txt |
Q:
Import Random throwing a multiple statements error
I just started learning python and have immediately run into a road block while trying to build the Guess a Number game from one of Al Sweigart's books.
The code starts with this:
import random
guessesTaken = 0
Every time I run just that block of code in IDLE co... | Import Random throwing a multiple statements error | I just started learning python and have immediately run into a road block while trying to build the Guess a Number game from one of Al Sweigart's books.
The code starts with this:
import random
guessesTaken = 0
Every time I run just that block of code in IDLE copy and pasted from the file editor, I get an error that ... | [
"In IDLE you need to execute code line by line. Or just save your code in .py file and run it by python <filename>.py in console.\n"
] | [
0
] | [] | [] | [
"importerror",
"python",
"python_idle"
] | stackoverflow_0074417891_importerror_python_python_idle.txt |
Q:
How to create a python function that runs as soon as its file is imported?
I am trying to make a module for personal uses, but I want to make it so as soon as I import it, it will run a function. Is there any way to do this. (preferably use the threading module as I already am using it)
A:
Within the module, cal... | How to create a python function that runs as soon as its file is imported? | I am trying to make a module for personal uses, but I want to make it so as soon as I import it, it will run a function. Is there any way to do this. (preferably use the threading module as I already am using it)
| [
"Within the module, call the function\ndef run_this_first():\n # write your code here\n pass\n\nrun_this_first()\n\nEvery time the module is imported, it will run run_this_first()\n",
"That is exactly what should happen if you call the function needed inside the file you are importing without using\nif __name... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074417940_python.txt |
Q:
Scrapy error when executing fetch(url) command
I have this error when executing the fetch(url) command using Scrapy. I'm using Scrapy 2.7.1, Python 3.10.6 with miniconda on Ubuntu 22.04
Here are the steps that I have done:
scrapy startproject worldometers
cd worldometers
scrap shell
fetch("https://www.worldomet... | Scrapy error when executing fetch(url) command | I have this error when executing the fetch(url) command using Scrapy. I'm using Scrapy 2.7.1, Python 3.10.6 with miniconda on Ubuntu 22.04
Here are the steps that I have done:
scrapy startproject worldometers
cd worldometers
scrap shell
fetch("https://www.worldometers.info/world-population/population-by-country/")
... | [
"solved it by commenting this line of code in file settings.py of the project:\n# Set settings whose default value is deprecated to a future-proof value\nREQUEST_FINGERPRINTER_IMPLEMENTATION = '2.7'\n#TWISTED_REACTOR = 'twisted.internet.asyncioreactor.AsyncioSelectorReactor'\n\n"
] | [
1
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0074413711_python_scrapy.txt |
Q:
Alternate method of getting 'There is no solution' to print
I had this problem for class, Given integer coefficients of two linear equations with variables x and y, use brute force to find an integer solution for x and y in the range -10 to 10. My question is, is there an alternate method to get 'There is no solut... | Alternate method of getting 'There is no solution' to print | I had this problem for class, Given integer coefficients of two linear equations with variables x and y, use brute force to find an integer solution for x and y in the range -10 to 10. My question is, is there an alternate method to get 'There is no solution.' to print just once?
I've tried making a count and adding +1... | [
"As a curiosity, you could use for else syntax too:\nimport itertools\n\nfor i, o in itertools.product(range(-10,11), range(-10,11)):\n if a*i + b*o == c and d*i + e*o == f: \n print('x =', i,',', 'y =', o)\n break\nelse:\n print('There is no solution')\n\n",
"Just use a boolean variable an... | [
2,
1
] | [] | [] | [
"brute_force",
"count",
"if_statement",
"python"
] | stackoverflow_0074417895_brute_force_count_if_statement_python.txt |
Q:
Problem in inserting data into database using Flask and MySQL
I had used the flask and MySQL in my project, after inserting the users data into database it shows only the empty rows but the rows are counted but the rows are showed as empty row. I did tried many ways to solve this but i didn't solve. There is no so... | Problem in inserting data into database using Flask and MySQL | I had used the flask and MySQL in my project, after inserting the users data into database it shows only the empty rows but the rows are counted but the rows are showed as empty row. I did tried many ways to solve this but i didn't solve. There is no solution over the internet.is there any one to help me to build my pr... | [
"Check your insert statement, a proper way to do it could by\ncursor.execute(\n \"\"\" \n INSERT INTO accounts(username,email,password)\n VALUES (%s, %s, %s) \n \"\"\", \n (username,email,password)\n)\n\nmysql.connection.commit()\n\n"
] | [
0
] | [] | [] | [
"database",
"flask",
"html",
"mysql_python",
"python"
] | stackoverflow_0074414061_database_flask_html_mysql_python_python.txt |
Q:
pd.read_excel(C:\Users\yaswa\Downloads\"Dataset-DV.xlsx",sheet_name="ListOfOrders")while reading file it shows invalid syntax
pd.read_excel(C:\Users\yaswa\Downloads\"Dataset-DV.xlsx",sheet_name="ListOfOrders")
while reading file it shows invalid syntax
to read my data set without error
A:
Try:
pd.read_excel("C:... | pd.read_excel(C:\Users\yaswa\Downloads\"Dataset-DV.xlsx",sheet_name="ListOfOrders")while reading file it shows invalid syntax | pd.read_excel(C:\Users\yaswa\Downloads\"Dataset-DV.xlsx",sheet_name="ListOfOrders")
while reading file it shows invalid syntax
to read my data set without error
| [
"Try:\npd.read_excel(\"C:\\Users\\yaswa\\Downloads\\Dataset-DV.xlsx\",sheet_name=\"ListOfOrders\")\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074417976_python.txt |
Q:
Why bit_count() equal bin(self).count("1") , also it means not count 0 in bit count?
Python 3.11.0 . I read document at https://docs.python.org/3/library/stdtypes.html#comparisons
int.bit_count() Return the number of ones in the binary representation
of the absolute value of the integer. This is also known as the... | Why bit_count() equal bin(self).count("1") , also it means not count 0 in bit count? | Python 3.11.0 . I read document at https://docs.python.org/3/library/stdtypes.html#comparisons
int.bit_count() Return the number of ones in the binary representation
of the absolute value of the integer. This is also known as the
population count. Example:
n = 19
bin(n)
n.bit_count()
(-n).bit_count()
def bit_count... | [
"counting of zeros in positive number does not make much sense (the same goes for counting ones in negative 2complement numbers)\nonly ones are really significant, what to do with non significant zeroes on left?\n\nif you count non significant zeroes from left - number of zeroes depends on size of variable, how man... | [
0
] | [
"Counting 1-bits is a somewhat common need. For example when you use an integer to represent a set, where 1-bits mark the elements in the set, and you want to know the size of the set.\nAs its documentation says, it was added in Python 3.10. So you visit the What’s New In Python 3.10 page and search for it. You see... | [
-1
] | [
"python"
] | stackoverflow_0074417841_python.txt |
Q:
Ternary As A Function Parameter?
I have a function where I'm searching for regex patterns in sentences and file paths. To do this, I need to chunk the text so that it evaluates full words, not individual characters.
def print_word_and_match_fragment(text):
word_list = text.split('\\') if '\\' in text else tex... | Ternary As A Function Parameter? | I have a function where I'm searching for regex patterns in sentences and file paths. To do this, I need to chunk the text so that it evaluates full words, not individual characters.
def print_word_and_match_fragment(text):
word_list = text.split('\\') if '\\' in text else text.split()
patterns = re.compile(r... | [
"This will work for the default argument, but it will only be evaluated once when the function definition is read\nalso see \"Least Astonishment\" and the Mutable Default Argument\nInstead, you may be able to use re.findall() or re.finditer() to optionally include // and \\b as a word boundary\n"
] | [
0
] | [] | [] | [
"python",
"ternary"
] | stackoverflow_0074417993_python_ternary.txt |
Q:
Making a functional contact form using django
I'm created a website for a friend. I have created a contact form which he would like people to use and the messages will directly be sent to his own personal email address. I can't seem to get it working. I'm currently testing using my own outlook account and eventual... | Making a functional contact form using django | I'm created a website for a friend. I have created a contact form which he would like people to use and the messages will directly be sent to his own personal email address. I can't seem to get it working. I'm currently testing using my own outlook account and eventually would like to be using his Gmail account. please... | [
"Here how i did it\nin settings.py +=\nEMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST='smtp.gmail.com'\nEMAIL_PORT=587\nEMAIL_HOST_USER=''\nEMAIL_HOST_PASSWORD=''\nEMAIL_USE_TLS= True\nEMAIL_HOST_USER='yourmail@gmail.com'\nEMAIL_HOST_PASSWORD='passwordgeneratedforthisappingoogleaccounts'\n\... | [
0
] | [] | [] | [
"contact_form",
"django",
"html",
"python",
"smtp"
] | stackoverflow_0074417399_contact_form_django_html_python_smtp.txt |
Q:
How to make a OptionMenu maintain the same width?
I have a snippet which creates an OptionMenu widget.
...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row... | How to make a OptionMenu maintain the same width? | I have a snippet which creates an OptionMenu widget.
...
options = ('White', 'Grey', 'Black', 'Red', 'Orange',
'Yellow', 'Green', 'Blue', 'Cyan', 'Purple')
var = StringVar()
optionmenu = OptionMenu(par, var, *options)
optionmenu.grid(column=column, row=row)
...
One problem I've encountered is every time a... | [
"To the best of my knowledge, you can use optionmenu.config(width=<YOUR_WIDTH>) as follows:\n...\noptionmenu = OptionMenu(par, var, *options)\noptionmenu.config(width=<YOUR_WIDTH>)\noptionmenu.grid(column=column, row=row)\n...\n\n",
"When you use the grid command to place the widget in its parent, have the widget... | [
33,
16,
1,
0
] | [] | [] | [
"optionmenu",
"python",
"tkinter"
] | stackoverflow_0005629745_optionmenu_python_tkinter.txt |
Q:
C-like forward declaration in python class
How would I properly do the following in python?
class AnyType:
def __init__(self, Type:Union[PrimitiveType, ComplexType]):
self.Type = Type
class PrimitiveType(AnyType):
def __init__(self, Type):
super().__init__(Type)
class NestedType(AnyType):... | C-like forward declaration in python class | How would I properly do the following in python?
class AnyType:
def __init__(self, Type:Union[PrimitiveType, ComplexType]):
self.Type = Type
class PrimitiveType(AnyType):
def __init__(self, Type):
super().__init__(Type)
class NestedType(AnyType):
def __init__(self, Type):
super()._... | [
"There is a PEP describing such feature. If you use python3.7+ you can add from __future__ import annotations at the beginning and it should work. In other case, using string fixes the problem\nclass AnyType:\n def __init__(self, Type:Union[\"PrimitiveType\", \"ComplexType\"]):\n self.Type = Type\n\n"
] | [
1
] | [] | [] | [
"inheritance",
"python",
"python_3.x"
] | stackoverflow_0074417820_inheritance_python_python_3.x.txt |
Q:
Merging Two Tables with pretty table
After scrapping with beautiful soup,
I have 2 tables :
x = PrettyTable()
x.field_names = ['Titre', 'Price']
y = PrettyTable()
y.field_names = ['Description']
OUTPUT:
x =
+-----------------+
| Titre | Price |
+-----------------+
| a | abc |
| b | xyz ... | Merging Two Tables with pretty table | After scrapping with beautiful soup,
I have 2 tables :
x = PrettyTable()
x.field_names = ['Titre', 'Price']
y = PrettyTable()
y.field_names = ['Description']
OUTPUT:
x =
+-----------------+
| Titre | Price |
+-----------------+
| a | abc |
| b | xyz |
+-----------------
y =
+-----------... | [
"Possible solution in case of number of rows in \"y\" should be less or equal to number of rows in \"x\".\nOr you can just switch the \"x\" \"y\".\nz = PrettyTable()\nz_rows = []\ncounter = 0\nfor i in x.rows:\n i.extend(y.rows[counter])\n counter += 1\n z_rows.append(i)\n\nfield = []\nfield.extend(x.field... | [
1
] | [] | [] | [
"beautifulsoup",
"prettytable",
"python"
] | stackoverflow_0074417688_beautifulsoup_prettytable_python.txt |
Q:
Query to a list of dictionaries (python)
I have a list of dictionaries:
friends = [
{'name': 'Sam', 'gender': 'male', 'sport': 'Basketball'},
{'name': 'Emily', 'gender': 'female', 'sport': 'volleyball'},
]
I need to create functions query, select, and field_filter to work with similar lists. These functions have ... | Query to a list of dictionaries (python) | I have a list of dictionaries:
friends = [
{'name': 'Sam', 'gender': 'male', 'sport': 'Basketball'},
{'name': 'Emily', 'gender': 'female', 'sport': 'volleyball'},
]
I need to create functions query, select, and field_filter to work with similar lists. These functions have to provide a possibility to select necessary c... | [
"Although the question implies that select and field_filter might want to be classes, I don't think that's necessary here; I'd just make them return regular old tuples:\nselect = field_filter = lambda *args: args\n\nand then query is just a list and dict comprehension where you iterate over the list of dicts and re... | [
1
] | [] | [] | [
"arguments",
"dictionary",
"filtering",
"nested_function",
"python"
] | stackoverflow_0074418076_arguments_dictionary_filtering_nested_function_python.txt |
Q:
polar pcolormesh plot projected onto cartopy map
To simplify, as much as possible, a question I already asked, how would you OVERLAY or PROJECT a polar plot onto a cartopy map.
phis = np.linspace(1e-5,10,10) # SV half cone ang, measured up from nadir
thetas = np.linspace(0,2*np.pi,361)# SV azimuth, 0 coincides wit... | polar pcolormesh plot projected onto cartopy map | To simplify, as much as possible, a question I already asked, how would you OVERLAY or PROJECT a polar plot onto a cartopy map.
phis = np.linspace(1e-5,10,10) # SV half cone ang, measured up from nadir
thetas = np.linspace(0,2*np.pi,361)# SV azimuth, 0 coincides with the vel vector
X,Y = np.meshgrid(thetas,phis)
Z =... | [
"Firstly, the data must be prepared/transformed into certain projection coordinates for use as input. And the instruction/option of the data's CRS must be specified correctly when used in the plot statement.\nIn your specific case, you need to transform your data into (long,lat) values.\nXX = X/np.pi*180 # wrap ar... | [
1,
0
] | [] | [] | [
"cartopy",
"matplotlib",
"python"
] | stackoverflow_0074414297_cartopy_matplotlib_python.txt |
Q:
How to get the x and y coordinate from an (x,y) point in Python?
I have a string variable which is a point, such as m="(2, 5)" or m="(-6, 7)". I want to extract the x coordinate and y coordinate and store them in different variables. Could someone provide some code in Python for how I could do this? Thanks!
A:
m... | How to get the x and y coordinate from an (x,y) point in Python? | I have a string variable which is a point, such as m="(2, 5)" or m="(-6, 7)". I want to extract the x coordinate and y coordinate and store them in different variables. Could someone provide some code in Python for how I could do this? Thanks!
| [
"maybe that help you\nm = \"(7, 5)\"\nx, y = m.strip('()').split(',')\nprint(x) # 7\nprint(y) # 5\n\nwith variables :\nm = \"(7, 5)\"\nx, y = m.strip('()').split(',')\n\nvar1 = x\nvar2 = y\n\nprint(var1)\nprint(var2)\n\n",
"You can use the ast library. As explained in this answer for example https://stackoverflow... | [
0,
0,
0
] | [
"Weird, but ok.\ndef coords(m):\n for i in range(2, len(m) - 2):\n if m[i] == ',':\n return m[1:i],m[(i+1),(len(m)-1)]\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0074417800_python.txt |
Q:
Minimal PySide6 code to get screen resolution
I'm fairly new to Qt for Python, and tried to get screen resolution like this:
screen = QtGui.QScreen()
print(f'screen geometry: {screen.geometry()}')
The numbers it gave were crazy, and were different every time I ran the script.
What's the right way to do it?
A:
S... | Minimal PySide6 code to get screen resolution | I'm fairly new to Qt for Python, and tried to get screen resolution like this:
screen = QtGui.QScreen()
print(f'screen geometry: {screen.geometry()}')
The numbers it gave were crazy, and were different every time I ran the script.
What's the right way to do it?
| [
"Searching the web gave me surprisingly little info about this.\nThis answer provided the clues that I needed.\nSeems like you have to get to a screen through QApplication.screens(), which returns a list of QScreen objects.\nI wanted to know the minimal PySide6 code to get the resolution of a single screen ...\nEDI... | [
0
] | [] | [] | [
"pyside6",
"python",
"qt"
] | stackoverflow_0074418142_pyside6_python_qt.txt |
Q:
Specify a default rendering method for a certain type in Jinja2
In Jinja2, how would you specify a default rendering method for a certain type?
In particular, datetime?
I found it quite annoying when rendering datetime values from Django. They look like 2022-11-04T00:00:00.987654+00:00. What was that T for, and wh... | Specify a default rendering method for a certain type in Jinja2 | In Jinja2, how would you specify a default rendering method for a certain type?
In particular, datetime?
I found it quite annoying when rendering datetime values from Django. They look like 2022-11-04T00:00:00.987654+00:00. What was that T for, and why there was a plus + followed by 00:00. My users who lived on small i... | [
"You can use dateparse:\nfrom django.utils import dateparse\n\nThen when before you pass the time to the template you can use the following to convert it to something more understandable to your fellow islanders:\nreadable_time = dateparse.parse_datetime(CONFUSING_TIME_STRING)\n\n"
] | [
0
] | [] | [] | [
"django",
"jinja2",
"python"
] | stackoverflow_0074311156_django_jinja2_python.txt |
Q:
How do I copy png/mp4 files from another directory to a folder of my choice?
I want to get the address of a file with filedialog.askopenfilenames() of tkinter lib and copy that file to the file I want.
As explained above, I got the address using filedialog.askopenfilenames() and using that address, I use shutil li... | How do I copy png/mp4 files from another directory to a folder of my choice? | I want to get the address of a file with filedialog.askopenfilenames() of tkinter lib and copy that file to the file I want.
As explained above, I got the address using filedialog.askopenfilenames() and using that address, I use shutil lib to
list_file = []
files = filedialog.askopenfilenames(initialdir="/", \
... | [
"the problem with your code is that you are checking \"list_file\" which is empty, what you should try is this instead:\nfor i in files:\n shutil.copy(i, \"image_file\")\n\nhttps://i.stack.imgur.com/u8STd.png\nalthough, if you try to copy to the same folder it will crash, what you could do is:\nfor i in files:\n... | [
1
] | [] | [] | [
"python",
"shutil",
"tkinter"
] | stackoverflow_0074417987_python_shutil_tkinter.txt |
Q:
Flask: AttributeError: 'NoneType' object has no attribute 'split'
Im new to Python/Flask and wanted to set Cookies for my Website. When i open the Website i get this error.
The functions that are causing Problems:
def numberinstring(nr: int, cookie: str):
visited = cookie.split(":")
fo... | Flask: AttributeError: 'NoneType' object has no attribute 'split' | Im new to Python/Flask and wanted to set Cookies for my Website. When i open the Website i get this error.
The functions that are causing Problems:
def numberinstring(nr: int, cookie: str):
visited = cookie.split(":")
for door in visited:
if nr == int(door):
... | [
"request.cookies.get(\"Besucht\") will return None if there's no KEY with name \"Besucht\" so check if cookie has value before calling the split method.\ndef numberinstring(nr: int, cookie: str):\n visited = \"\"\n if cookie:\n visited = cookie.split(\":\")\n\n for door in visited:\n ... | [
1
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074418182_flask_python.txt |
Q:
How to transform pandas columns into a column and formatted as json accepted
I need help on how to properly transform my df from this:
df_installation = pd.DataFrame({'InstallationID': ["Item 1", "Item 2", "Item 3","Item 1", "Item 2", "Item 3"],
'Type': ["Metric", "Metric","Me... | How to transform pandas columns into a column and formatted as json accepted | I need help on how to properly transform my df from this:
df_installation = pd.DataFrame({'InstallationID': ["Item 1", "Item 2", "Item 3","Item 1", "Item 2", "Item 3"],
'Type': ["Metric", "Metric","Metric", "Imperial","Imperial","Imperial"],
'Measur... | [
"Given your input dataframe:\ndf = pd.DataFrame({'InstallationID': [\"Item 1\", \"Item 2\", \"Item 3\",\"Item 1\", \"Item 2\", \"Item 3\"],\n 'Type': [\"Metric\", \"Metric\",\"Metric\", \"Imperial\",\"Imperial\",\"Imperial\"],\n 'Measure 1': [1199... | [
1
] | [] | [] | [
"arrays",
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074418071_arrays_dataframe_json_pandas_python.txt |
Q:
Django model conditionally based on two abstract classes
I have more of a conceptual question, but with practical implications.
In a Django 4.1.x app, I have one owner class which can be either a person or an organization, but never both together.
These two classes doesn't need to be registered in the database, on... | Django model conditionally based on two abstract classes | I have more of a conceptual question, but with practical implications.
In a Django 4.1.x app, I have one owner class which can be either a person or an organization, but never both together.
These two classes doesn't need to be registered in the database, only the owner has to:
from django.db import models
class Perso... | [
"There are a couple of possible approaches, but they have tradeoffs. A lot will depend on how important it is for your classes to all use the same table. As a rule of thumb, if a non-abstract model needs new fields, it needs a new table.\nAbstract classes:\nThese are useful as archetypes, but you can't combine them... | [
1
] | [] | [] | [
"django",
"django_models",
"inheritance",
"multiple_inheritance",
"python"
] | stackoverflow_0074396041_django_django_models_inheritance_multiple_inheritance_python.txt |
Q:
Retrieve data colors bootstrap theme plotly-dash
I am building an application using the Plotly-Dash library in Python. I am using bootstrap components with the Lumen theme to make everything look nice (For the DCC components, I'm also using this stylesheet, but I don't think it is relevant). Thanks to these styles... | Retrieve data colors bootstrap theme plotly-dash | I am building an application using the Plotly-Dash library in Python. I am using bootstrap components with the Lumen theme to make everything look nice (For the DCC components, I'm also using this stylesheet, but I don't think it is relevant). Thanks to these stylesheets, my plotly graphs look according to the theme, i... | [
"Two possible solutions:\nGuess from the CSS file\nDownload the Lumen package using the link you provided, unzip it, then open the lumen/theme/boostrap.css file. Some styles are pretty self-explanatory, for example\n .btn-warning {\n color: #ffffff;\n background-color: #ff851b;\n border-color: #ff... | [
0
] | [] | [] | [
"plotly_dash",
"python"
] | stackoverflow_0074360281_plotly_dash_python.txt |
Q:
Finding all integers under v which are the sum of two abundant numbers
Write a function that returns a list of all the positive integers under v that can be expressed as the sum of two abundant numbers.
I'm very new to coding so it's quite messy and I don't even understand how half of it works. I tried multiple th... | Finding all integers under v which are the sum of two abundant numbers | Write a function that returns a list of all the positive integers under v that can be expressed as the sum of two abundant numbers.
I'm very new to coding so it's quite messy and I don't even understand how half of it works. I tried multiple things, all on the premise of, I will add the 0th element with the 0th, then t... | [
"Here's a sequence of functions that'll give you what you're after:\ndef divisors(a: int) -> list:\n \"\"\"\n Returns a list of all the proper divisors of \"a\". \n \"\"\"\n b=[]\n for i in range(1,a):\n \n if a%i==0:\n b.append(i)\n return b\n\ndef is_abundant(n: int) -> bool... | [
-1
] | [] | [] | [
"python"
] | stackoverflow_0074418150_python.txt |
Q:
How to add user input to a list to view later?
I am new to python and I have to code a ticket system. The user needs to answer a few questions and a ticket is create. The user should then later be able to view all tickets created or search the ticket by number. I can not figure out how to do this. Any one else hav... | How to add user input to a list to view later? | I am new to python and I have to code a ticket system. The user needs to answer a few questions and a ticket is create. The user should then later be able to view all tickets created or search the ticket by number. I can not figure out how to do this. Any one else have a few ideas?
Below is my current code:
class MenuL... | [
"what you could do is create a while True or while 1 loop, the infinite loop will keep the program runing and you can use a bunch of if: statements inside, when you want to close the program just use break:\nwhile 1:\n #print the options of valid inputs\n \n text = input()\n\n if text == \"exit\":\n ... | [
0
] | [] | [] | [
"list",
"python",
"python_3.x",
"ticket_system"
] | stackoverflow_0074418133_list_python_python_3.x_ticket_system.txt |
Q:
Python - pandas remove duplicate rows based on condition
I have a csv which has data that looks like this
id | code | date
-------------+-----------------------------
| 1 | 2 | 2022-10-05 07:22:39+00::00 |
| 1 | 0 | 2022-11-05 02:22:35+00::00 |
| 2 | 3 | 2021-01-05 10:10:15+00::00 |
| 2 | ... | Python - pandas remove duplicate rows based on condition | I have a csv which has data that looks like this
id | code | date
-------------+-----------------------------
| 1 | 2 | 2022-10-05 07:22:39+00::00 |
| 1 | 0 | 2022-11-05 02:22:35+00::00 |
| 2 | 3 | 2021-01-05 10:10:15+00::00 |
| 2 | 0 | 2019-01-11 10:05:21+00::00 |
| 2 | 1 | 2022-01-1... | [
"There is probably a sleeker solution but something along the following lines should work.\ndf = pd.read_csv('file.csv')\nlastcode = df[df.code!=0].groupby('id').apply(lambda block: block[block['date'] == block['date'].max()]['code'])\nprev_codes = df.groupby('id').agg(code=('code', lambda x: [val for val in x if v... | [
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074417294_dataframe_numpy_pandas_python_python_3.x.txt |
Q:
File not found when executing a .exe from PyInstaller
I have a script which contains several libraries, one of which is iapws.
When I create an executable using
pyinstaller --onefile myScript.spec
I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Miguel\AppData\Local\Tem... | File not found when executing a .exe from PyInstaller | I have a script which contains several libraries, one of which is iapws.
When I create an executable using
pyinstaller --onefile myScript.spec
I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Miguel\AppData\Local\Temp\_MEI147002\iapws\VERSION
I tried upgrading all my librar... | [
"You need to force pyinstaller to include iapws files, as it seems to have issues generating the appropriate hooks. This worked for me:\npyinstaller \"your_script.py\" --collect-all iapws\n\nI reviewed command options here which helped:\nhttps://pyinstaller.org/en/stable/usage.html\n"
] | [
0
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0072578026_pyinstaller_python.txt |
Q:
Why is pandas adding new columns to my new excel file
I am trying to concatenate two excel files with the same column names together, but there seems to be a problem as there are new empty columns/spaces being added to my new excel file, and i don't know why.
I used pd.concat() function which was supposed to conca... | Why is pandas adding new columns to my new excel file | I am trying to concatenate two excel files with the same column names together, but there seems to be a problem as there are new empty columns/spaces being added to my new excel file, and i don't know why.
I used pd.concat() function which was supposed to concat the two files into one single sheet and make a new file, ... | [
"Concat respects the column names, so is not like a plain vector concatenate, try to check if the column names are the same among all your source files. If no, you can normalize them, rename them or move to a vector base format like numpy arrays.\n"
] | [
0
] | [] | [] | [
"concatenation",
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074418153_concatenation_dataframe_excel_pandas_python.txt |
Q:
I am trying to match names from Two Dataframes and adding a running score for each person matched
I have two data frames, df1 containing Actor Names & A weighted Score, and df2 containing a list of movies with the cast-members.
I want to loop through the df2 movie cast column to see if they are matching with the d... | I am trying to match names from Two Dataframes and adding a running score for each person matched | I have two data frames, df1 containing Actor Names & A weighted Score, and df2 containing a list of movies with the cast-members.
I want to loop through the df2 movie cast column to see if they are matching with the df1 Actor Names column. Then add their cumulative weighted score from df1 as a NEW column for df2.
| [
"Here is the dummy dataframe I created.\ndf1\nHere is the second dataframe.\ndf2\nNow here is the code to loop through every cast member and add their cumulative score.\nscores_list=[]\nfor cast in df2[\"credits\"]:\n score=0\n for actor in cast:\n score+=df[df[\"Actor\"]==actor][\"Actor Score\"].value... | [
0
] | [] | [] | [
"dataframe",
"loops",
"matching",
"pandas",
"python"
] | stackoverflow_0074418082_dataframe_loops_matching_pandas_python.txt |
Q:
How to let pyInstaller find datafiles when your package is imported by others
As a user of the iapws package, I got hit by a general issue that I don't manage to solve.
The package is small, and a good candidate look at.
A simples script is the following (I called it main.py):
from iapws import IAPWS97
def main()... | How to let pyInstaller find datafiles when your package is imported by others | As a user of the iapws package, I got hit by a general issue that I don't manage to solve.
The package is small, and a good candidate look at.
A simples script is the following (I called it main.py):
from iapws import IAPWS97
def main():
h = IAPWS97(P=1, x=1).h
print(f"h = {h:.5g} kJ/kg")
if __name__ == "__ma... | [
"For this purpose, pyInstaller allows hooks to be applied. In this case, create a hook called hook-iapws.py with the content\nfrom PyInstaller.utils.hooks import collect_data_files\ndatas = collect_data_files('iapws')\n\nAs a user of the package, the hook is found by pointing on the containing directory in the pyin... | [
0,
0
] | [] | [] | [
"pyinstaller",
"python",
"setuptools"
] | stackoverflow_0066010802_pyinstaller_python_setuptools.txt |
Q:
How to programmatically sync anki flashcard database with local file?
I would like to have a script ran by cron or an anki background job that will automatically read in a file (e.g. csv, tsv) containing all my flashcards and update the flashcard database in anki automatically so that i don't have to manually impo... | How to programmatically sync anki flashcard database with local file? | I would like to have a script ran by cron or an anki background job that will automatically read in a file (e.g. csv, tsv) containing all my flashcards and update the flashcard database in anki automatically so that i don't have to manually import my flashcards 1000 times a week.
any have any ideas how this can be achi... | [
"The most robust approach there is so far is to have your collection under git, and use Ki to make Anki behave like a remote repository, so it's very easy to synchronise. The only constraint is the format of your collection. Each card is kept as a single file, and there is no real way around this.\n",
"I'm the ma... | [
2,
0
] | [] | [] | [
"anki",
"cron",
"python",
"synchronization"
] | stackoverflow_0072759169_anki_cron_python_synchronization.txt |
Q:
Matching corresponding items in two lists for a menu
What this will print is:
Enter an action: 2
1. Bacon - 10
2. Cheese - 10
How do I get 12$ matched to the bacon, while 10 matched up with the cheese?
print('\nWelcome to the Shopping List App!\n')
item_list= []
item_price_list = []
while True:
menu_select... | Matching corresponding items in two lists for a menu | What this will print is:
Enter an action: 2
1. Bacon - 10
2. Cheese - 10
How do I get 12$ matched to the bacon, while 10 matched up with the cheese?
print('\nWelcome to the Shopping List App!\n')
item_list= []
item_price_list = []
while True:
menu_selection = input(
'''Please select one of the following:
... | [
"Use a dictionary to hold data values.\nitem_dict = {}\nwhile True:\n\n #...\n\n if menu_selection == '1':\n item = input('Add item: ').capitalize()\n item_price = input(f'What is the price of {item}? $')\n item_dict[item] = item_price\n print(f'\\n{item} has been added to you cart... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074417693_python.txt |
Q:
Django rest_framework : count objects and return value to serializer
i need to count all supporters in model and return value to serializer
models.py
class Supporters(models.Model):
name = models.CharField(max_length=255)
img = models.ImageField(upload_to="Supporters", blank=True, null=True)
serializers.p... | Django rest_framework : count objects and return value to serializer | i need to count all supporters in model and return value to serializer
models.py
class Supporters(models.Model):
name = models.CharField(max_length=255)
img = models.ImageField(upload_to="Supporters", blank=True, null=True)
serializers.py
class SupportersSerializer(serializers.ModelSerializer):
id = serial... | [
"About your serializer file, beware of indentation, here is an example. As for counting objects, i believe you are looking for something like this:\nclass SupportersSerializer(serializers.ModelSerializer):\n id = serializers.ReadOnlyField()\n supporters_count = serializers.SerializerMethodField()\n\n class... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074417849_django_django_rest_framework_python.txt |
Q:
Convert instructions to op code bytes in python script for IDA Pro
I need to convert into op code bytes the instructions that I have disassembled but I can't find a function that lets me do it, I've tried idc.get_bytes but it doesn't seem to work.
This is my python script:
import sys
import idc
import idautils
f ... | Convert instructions to op code bytes in python script for IDA Pro | I need to convert into op code bytes the instructions that I have disassembled but I can't find a function that lets me do it, I've tried idc.get_bytes but it doesn't seem to work.
This is my python script:
import sys
import idc
import idautils
f = open(idc.ARGV[1], 'w') if len(idc.ARGV) > 1 else sys.stdout
log = f.wr... | [
"So, something like this?\ndef GetFuncHeads(funcea=None):\n \"\"\"\n Get all heads in a function\n\n @param funcea: any address in the function\n \"\"\"\n func = ida_funcs.get_func(funcea)\n if not func:\n return []\n else:\n funcea = func.start_ea\n\n ea = funcea\n\n heads ... | [
1
] | [] | [] | [
"ida",
"python",
"reverse_engineering"
] | stackoverflow_0074363980_ida_python_reverse_engineering.txt |
Q:
How can I add to a dataframe count values of another?
I have a problem that I would like to solve with a dataframe. The index of this table represents a cluster. I have a dataframe called "representative points" that has this structure:
lon lat
0 76 3
1 45 1
2 32 4
On the other hand I have... | How can I add to a dataframe count values of another? | I have a problem that I would like to solve with a dataframe. The index of this table represents a cluster. I have a dataframe called "representative points" that has this structure:
lon lat
0 76 3
1 45 1
2 32 4
On the other hand I have a dataset containing a point with the cluster it belongs... | [
"I think that you may need something like\nimport pandas as pd\n\na = pd.DataFrame({\"lat\": [76, 45, 32], \"lon\": [12, 34, 56]})\nb = pd.DataFrame({\"lat\": [32, 45, 13], \"lon\": [13, 13, 13], \"cluster\": [1, 2, 3]})\n\na[\"cluster\"] = a.index\ngrouped = b.groupby(\"cluster\").size().reset_index(name='counts')... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074417860_python.txt |
Q:
Numba cuda dynamic shared memory: more than one type?
I am aware that I can create a dynamic shared memory array for a numba-compiled CUDA kernel by passing the size in as the forth argument to the kernel call:
...
foo_kernel[grid, block, stream, shared_bytes](...)
...
@cuda.jit
def foo_kernel(...) ->... | Numba cuda dynamic shared memory: more than one type? | I am aware that I can create a dynamic shared memory array for a numba-compiled CUDA kernel by passing the size in as the forth argument to the kernel call:
...
foo_kernel[grid, block, stream, shared_bytes](...)
...
@cuda.jit
def foo_kernel(...) -> None:
a = cuda.shared.array(0, nb.int32)
From here, I... | [
"Aha -- some googling finds: https://curiouscoding.nl/posts/numba-cuda-speedup/#v15-dynamic-shared-memory\nWhich confirms that different dtypes are indeed supported, using the trick I guessed (as pictured above).\n"
] | [
0
] | [] | [] | [
"cuda",
"numba",
"python"
] | stackoverflow_0074418324_cuda_numba_python.txt |
Q:
python for .net Module not found Error no module named Numpy
I am trying to call Python functions from C# with Python.Runtime.
I have used this example from the internet.
When I try to run it , it says. no module named Numpy.
Numpy is working very well under Python.
Where am I going wrong?
class Program
{
... | python for .net Module not found Error no module named Numpy | I am trying to call Python functions from C# with Python.Runtime.
I have used this example from the internet.
When I try to run it , it says. no module named Numpy.
Numpy is working very well under Python.
Where am I going wrong?
class Program
{
static void Main(string[] args)
{
using ... | [
"I had the same issue and resolved it.\nFirst try installing numpy using\n$ pip install numpy\n\nYou probably have done this step, but still got the same error.\nThis is due to your pip and packages belonging to a different python installation than the one Python.Net is seeing. For example, on my Windows 10, I foun... | [
0
] | [] | [] | [
".net",
"python"
] | stackoverflow_0048974470_.net_python.txt |
Q:
Multiple Page App Side Bar Icon and Background in Streamlit
Is there any way to use the icons which ı select for the sidebar in multiple page app. I want to make a sidebar like the below image:
Is there any way to change the background image of sidebar?
A:
You should rename the pages starting with a number, the... | Multiple Page App Side Bar Icon and Background in Streamlit |
Is there any way to use the icons which ı select for the sidebar in multiple page app. I want to make a sidebar like the below image:
Is there any way to change the background image of sidebar?
| [
"You should rename the pages starting with a number, the icon and then the page name. Streamlit will automatically take care of the numbers and the _ by removing them leaving only the icon and the page name. Pages are sorted based on the numbers.\nYour page should return only>>> Mapping Demo\n# How to name page:\n... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"streamlit"
] | stackoverflow_0073677916_python_python_3.x_streamlit.txt |
Q:
TypeError when using random.sample() in python
I'm making a password generator and getting a strange error when I try to run the code.
I created a list with characters and I want the code to sort all the elements in that list and print them with a defined range.
But when I try to run that code I get a TypeError sa... | TypeError when using random.sample() in python | I'm making a password generator and getting a strange error when I try to run the code.
I created a list with characters and I want the code to sort all the elements in that list and print them with a defined range.
But when I try to run that code I get a TypeError saying " '<=' not supported between instances of 'int'... | [
"Please replace range argument in the random.sample function with user_input. Also modified the while condition to check the user_input in a simpler way.\nimport random\n\ncharaters = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"0\", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', ... | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074418343_list_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.