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:
Why do pythons tkinter grid buttons stretch when a label in the grid changes size?
I am making a simple application with 1 button and 1 label where pressing the button changes the text on the label. Both label and button and placed using the tkinter's grid system however when I press the button the label's text ch... | Why do pythons tkinter grid buttons stretch when a label in the grid changes size? | I am making a simple application with 1 button and 1 label where pressing the button changes the text on the label. Both label and button and placed using the tkinter's grid system however when I press the button the label's text changes size as expected but the button becomes stretched to the label's length too. Why?
... | [
"Setting sticky=\"news\" for the button, will expand the button to fill the available space in the four directions North, East, West, South. Try changing it to sticky=\"w\" to make it stick to the West. So, the line of code for creating the button will become:\nb1=tk.Button(window,text=\"button1\",font=(\"Segoe UI\... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074665903_python_tkinter.txt |
Q:
How can I specify which Python toolchain to use in Bazel?
How can I configure Bazel to pick one toolchain over the other? I am okay with defining which toolchain to use via command-line argument or specifying which should be used in a specific target.
There are currently two toolchains being defined in my WORKSPAC... | How can I specify which Python toolchain to use in Bazel? | How can I configure Bazel to pick one toolchain over the other? I am okay with defining which toolchain to use via command-line argument or specifying which should be used in a specific target.
There are currently two toolchains being defined in my WORKSPACE file. I have two Python toolchains. One of them builds Python... | [
"Consider upgrading rules_python, as that ruleset includes a hermetic python toolchain since https://github.com/bazelbuild/rules_python/releases/tag/0.7.0.\nIf that is not an option:\nCurrently you are registering two toolchains in your WORKSPACE.bazel file and bazel will use its toolchain resolution to pick one of... | [
0
] | [] | [] | [
"bazel",
"build",
"python"
] | stackoverflow_0074512774_bazel_build_python.txt |
Q:
add a comma after every "%" symbol using regex in a dataframe
if i have a value like this :
C:100% B:90% A:80%
i want to add comma after every % so the output is like this :
C:100%,B:90%,A:80%
i've tried somthing like :
data['Final'] = data['Final'].str.replace(r'(%)\n\b', r'\1,', regex=True)
A:
You can use ... | add a comma after every "%" symbol using regex in a dataframe | if i have a value like this :
C:100% B:90% A:80%
i want to add comma after every % so the output is like this :
C:100%,B:90%,A:80%
i've tried somthing like :
data['Final'] = data['Final'].str.replace(r'(%)\n\b', r'\1,', regex=True)
| [
"You can use the re.sub method from the re module in Python to achieve this.\nimport re\n\n# Your original string\nstring = \"C:100% B:90% A:80%\"\n\n# Use regex to replace all occurrences of '%' with ',%'\nstring = re.sub(\"%\", \",%\", string)\n\n# The resulting string will be: \"C:100%, B:90%, A:80%\"\n\nIf you ... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"python",
"regex",
"string"
] | stackoverflow_0074665703_dataframe_python_regex_string.txt |
Q:
Python Dataframe fillna with value on left column
I have an excel spreadsheet where there are merged cells.
I would like to build a dictionary of Product_ID - Category - Country.
But for that I need to get, I believe, Python to be able to read an excel file with horizontally merged cells.
import pandas as pd
exc... | Python Dataframe fillna with value on left column | I have an excel spreadsheet where there are merged cells.
I would like to build a dictionary of Product_ID - Category - Country.
But for that I need to get, I believe, Python to be able to read an excel file with horizontally merged cells.
import pandas as pd
excel_sheet = pd.read_excel(r'C:\Users\myusername\Document... | [
"This should do:\ndf.iloc[0] = df.iloc[0].ffill() \n\n",
"I understand, that the question is more than 2 yo, and the best answer is coorect, but if you want to fill NaNs of the whole Frame, you can use:\ndf.T.ffill().T\n\n"
] | [
1,
0
] | [] | [] | [
"dataframe",
"fillna",
"pandas",
"python"
] | stackoverflow_0063303810_dataframe_fillna_pandas_python.txt |
Q:
Connect to a remote sqlite3 database with Python
I am able to create a connection to a local sqlite3 database ( Using Mac OS X 10.5 and Python 2.5.1 ) with this:
conn = sqlite3.connect('/db/MyDb')
How can I connect to this database if it is located on a server ( for example on a server running Ubuntu 8.04 with an... | Connect to a remote sqlite3 database with Python | I am able to create a connection to a local sqlite3 database ( Using Mac OS X 10.5 and Python 2.5.1 ) with this:
conn = sqlite3.connect('/db/MyDb')
How can I connect to this database if it is located on a server ( for example on a server running Ubuntu 8.04 with an IP address of 10.7.1.71 ) , and is not stored locally... | [
"SQLite is embedded-only. You'll need to mount the remote filesystem before you can access it. And don't try to have more than one machine accessing the SQLite database at a time; SQLite is not built for that. Use something like PostgreSQL instead if you need that.\n",
"The sqlite FAQ has an answer relevant to yo... | [
12,
2,
0
] | [] | [] | [
"macos",
"python",
"sqlite"
] | stackoverflow_0002318315_macos_python_sqlite.txt |
Q:
Getting position data from UBX protocol
I am working on a project which is use ublox .ubx protocol to getting position information. I'm using serial communication to connect my GPS module and getting position information to python sketch. I used Serial and pyubx2 libraries my sketch as follows,
from serial import ... | Getting position data from UBX protocol | I am working on a project which is use ublox .ubx protocol to getting position information. I'm using serial communication to connect my GPS module and getting position information to python sketch. I used Serial and pyubx2 libraries my sketch as follows,
from serial import Serial
from pyubx2 import UBXReader
stream =... | [
"Try something like this (press CTRL-C to terminate) ...\nfrom serial import Serial\nfrom pyubx2 import UBXReader\n\ntry:\n stream = Serial('COM8', 38400)\n while True:\n ubr = UBXReader(stream)\n (raw_data, parsed_data) = ubr.read()\n # print(parsed_data)\n if parsed_data.identity... | [
0
] | [] | [] | [
"gps",
"location",
"python"
] | stackoverflow_0073864028_gps_location_python.txt |
Q:
How to convert string to number in python?
I have list of numbers as str
li = ['1', '4', '8.6']
if I use int to convert the result is [1, 4, 8].
If I use float to convert the result is [1.0, 4.0, 8.6]
I want to convert them to [1, 4, 8.6]
I've tried this:
li = [1, 4, 8.6]
intli = list(map(lambda x: int(x),li))
fl... | How to convert string to number in python? | I have list of numbers as str
li = ['1', '4', '8.6']
if I use int to convert the result is [1, 4, 8].
If I use float to convert the result is [1.0, 4.0, 8.6]
I want to convert them to [1, 4, 8.6]
I've tried this:
li = [1, 4, 8.6]
intli = list(map(lambda x: int(x),li))
floatli = list(map(lambda x: float(x),li))
print(i... | [
"Convert the items to a integer if isdigit() returns True, else to a float. This can be done by a list generator:\nli = ['1', '4', '8.6']\nlst = [int(x) if x.isdigit() else float(x) for x in li]\nprint(lst)\n\nTo check if it actually worked, you can check for the types using another list generator:\ntypes = [type(i... | [
2,
0,
0,
0,
0,
0
] | [] | [] | [
"converters",
"integer",
"numbers",
"python",
"string"
] | stackoverflow_0074665788_converters_integer_numbers_python_string.txt |
Q:
Pattern finder in python
Let's say I have a list with a bunch of numbers in it, I'm looking to make a function that will list and return the numbers that are being repeated in most of them.
Example code:
—ListOfNumbers = [1234, 9912349, 578]
-print(GetPatern(ListOfNumbers))
1234
A:
Here is an example of a functi... | Pattern finder in python | Let's say I have a list with a bunch of numbers in it, I'm looking to make a function that will list and return the numbers that are being repeated in most of them.
Example code:
—ListOfNumbers = [1234, 9912349, 578]
-print(GetPatern(ListOfNumbers))
1234
| [
"Here is an example of a function that could do this:\ndef get_pattern(numbers):\n # First, we will create a dictionary where the keys are the numbers in our list,\n # and the values are the number of times those numbers appear in the list\n number_count = {}\n for number in numbers:\n if number not in numbe... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074665726_python.txt |
Q:
Will anyone help me with this company specific question :
There are two types of liquid: type 1 and type 2. Initially, we have n ml of each type of liquid. There are four kinds of operations:
Serve 25 ml of liquid 1 and 75 ml of liquid 2.
Serve 75 ml of liquid 1 and 25 ml of liquid 2.
Serve 100 ml of liquid 1 and... | Will anyone help me with this company specific question : | There are two types of liquid: type 1 and type 2. Initially, we have n ml of each type of liquid. There are four kinds of operations:
Serve 25 ml of liquid 1 and 75 ml of liquid 2.
Serve 75 ml of liquid 1 and 25 ml of liquid 2.
Serve 100 ml of liquid 1 and 0 ml of liquid 2, and
Serve 50 ml of liquid 1 and 50 ml of liq... | [] | [] | [
"Here is a possible solution in Python:\ndef probability(n: int) -> float:\n # if there is no liquid, return 0\n if n == 0:\n return 0\n \n # if there is only 1 type of liquid, return 1\n if n == 50:\n return 1\n \n # calculate the probability of each operation\n p1 = 0.25 * pr... | [
-1
] | [
"python"
] | stackoverflow_0074666121_python.txt |
Q:
Chaining Telethon start methods
I have been using telethon for a long time with two clients, one for a bot (with bot token) and another for my user (using phone).
I always thought two separate clients were necessary (are them?) but I recently saw this in the documentation:
https://docs.telethon.dev/en/stable/modu... | Chaining Telethon start methods | I have been using telethon for a long time with two clients, one for a bot (with bot token) and another for my user (using phone).
I always thought two separate clients were necessary (are them?) but I recently saw this in the documentation:
https://docs.telethon.dev/en/stable/modules/client.html#telethon.client.auth.... | [
"The documentation says \"initialization can be chained\". Initialization is this line:\nclient = TelegramClient(...)\n\nand you can chain .start() there:\nclient = await TelegramClient(...).start(...)\n\nbut it doesn't mean you can chain multiple calls to start(). Indeed, if you want to control more than one accou... | [
1
] | [] | [] | [
"python",
"telethon"
] | stackoverflow_0074665837_python_telethon.txt |
Q:
RaggedTensor becomes Tensor in loss function
I have a sequence-to-sequence model in which I am attempting to predict the output sequence following a transformation. In doing so, I need to compute the MSE between elements in a ragged tensor:
def cpu_bce(y_value, y_pred):
with tf.device('/CPU:0'):
y_v = ... | RaggedTensor becomes Tensor in loss function | I have a sequence-to-sequence model in which I am attempting to predict the output sequence following a transformation. In doing so, I need to compute the MSE between elements in a ragged tensor:
def cpu_bce(y_value, y_pred):
with tf.device('/CPU:0'):
y_v = y_value.to_tensor()
y_p = y_pred.to_tensor... | [
"In your loss function, you can re-write it in the following ways to make it work.\ndef cpu_bce(y_value, y_pred):\n with tf.device('/CPU:0'):\n if isinstance(y_value, tf.RaggedTensor):\n y_value = y_value.to_tensor()\n \n if isinstance(y_pred, tf.RaggedTensor): \n ... | [
0
] | [] | [] | [
"keras",
"loss",
"python",
"tensorflow"
] | stackoverflow_0074665549_keras_loss_python_tensorflow.txt |
Q:
Python Pandas - Assign Values to Rows based on Top x% Values found in a Column
Take this mockup dataframe for example:
CustomerID Number of Purchases
ABC 5
DEF 24
GHI 85
JKL 2
MNO 100
Assume this dataframe is first sorted by ... | Python Pandas - Assign Values to Rows based on Top x% Values found in a Column | Take this mockup dataframe for example:
CustomerID Number of Purchases
ABC 5
DEF 24
GHI 85
JKL 2
MNO 100
Assume this dataframe is first sorted by Number of Purchases (descending).
How do I add a new column to it called Score, and ... | [
"import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'CustomerID': ['ABC', 'DEF', 'GHI', 'JKL', 'MNO'],\n 'Number of Purchases': [5, 24, 85, 2, 100]})\n\ndf = df.sort_values(by=['Number of Purchases'], ascending=False)\n\n\nproc = len(df) / 100\naaa = [[0, int(60 * proc), 3], [int(60 * p... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074641326_pandas_python.txt |
Q:
How to handle abbreviation when reading nltk corpus
I am reading nltk corpus using
def read_corpus(package, category):
""" Read files from corpus(package)'s category.
Params:
package (nltk.corpus): corpus
category (string): category name
Return:
list of lists... | How to handle abbreviation when reading nltk corpus | I am reading nltk corpus using
def read_corpus(package, category):
""" Read files from corpus(package)'s category.
Params:
package (nltk.corpus): corpus
category (string): category name
Return:
list of lists, with words from each of the processed files assigned wi... | [
"To treat abbreviations such as \"U.S.\" and contractions such as \"I'm\" as a single token when processing text, you can use the TreebankWordTokenizer from the NLTK library. This tokenizer is designed to tokenize text in a way that is similar to how humans would naturally write and speak, so it will treat abbrevia... | [
0
] | [] | [] | [
"nltk",
"python"
] | stackoverflow_0074666233_nltk_python.txt |
Q:
Can anyone explain why this code on python is not working?
def n(a):
a = str(a)
if "0" in a:
b = str((a).replace("0", ''))
a = b[::-1]
a = a[::-1]
a = int(a)
return a
else:
a = a[::-1]
a = a[::-1]
a = int(a)
return a
N = int(inpu... | Can anyone explain why this code on python is not working? | def n(a):
a = str(a)
if "0" in a:
b = str((a).replace("0", ''))
a = b[::-1]
a = a[::-1]
a = int(a)
return a
else:
a = a[::-1]
a = a[::-1]
a = int(a)
return a
N = int(input())
des = 10**9 + 7
summa = 0
for a in range():
print(n(a... | [
"The input function waits for user input. If none is given, it will return an empty string, i.e., ''. As a result, you are casting '' to an integer. This is not possible and results in the error you mention.\nint('')` # returns `ValueError: invalid literal for int() with base 10: ''\n\nYou can also see this already... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074666238_python.txt |
Q:
jinja2 in python and rendering
I am unable to decipher the error here. Can any one help ?
from jinja2 import Template
prefixes = {
"10.0.0.0/24" : {
"description": "Corporate NAS",
"region": "Europe",
"site": "Telehouse-West"
}
}
template = """
Details for 10.0.0.0/24 prefix:
De... | jinja2 in python and rendering | I am unable to decipher the error here. Can any one help ?
from jinja2 import Template
prefixes = {
"10.0.0.0/24" : {
"description": "Corporate NAS",
"region": "Europe",
"site": "Telehouse-West"
}
}
template = """
Details for 10.0.0.0/24 prefix:
Description: {{ prefixes['10.0.0.0/24'... | [
"render uses keyword arguments. replace print(j2.render(prefixes)) with print(j2.render(prefixes=prefixes)) and it should work.\n",
"If you want to pass prefixes as a positional argument, you should change the prefixes dictionary to be:\nprefixes = {\n \"prefixes\": {\n \"10.0.0.0/24\": {\n \... | [
1,
0,
0
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0074666184_jinja2_python.txt |
Q:
NameError: name 'username_entry' is not defined
So i'm trying to do a login gui using customtkinter
I want to have an window with 2 buttons first : Login and Exit
Then when I press Login to open another py script with the login label
If i execute the second script its all right but if I try from the first one I ge... | NameError: name 'username_entry' is not defined | So i'm trying to do a login gui using customtkinter
I want to have an window with 2 buttons first : Login and Exit
Then when I press Login to open another py script with the login label
If i execute the second script its all right but if I try from the first one I get this error
Exception in Tkinter callback
Tracebac... | [
"Obviously, the username_entry is not defined in the login function body. please add it to the function arguments and then use it properly.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074666259_python.txt |
Q:
Python get key of a value inside a nested dictionary
Let's say I have a dictionary called my_dic:
my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}
Then if I input spam, it should return a, and if I input bar it should return spam. If I input b, it should return N... | Python get key of a value inside a nested dictionary | Let's say I have a dictionary called my_dic:
my_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}
Then if I input spam, it should return a, and if I input bar it should return spam. If I input b, it should return None. Basically getting the parent of the dictionary.
How w... | [
"A simple recursive function, which returns the current key if needle in v is true; needle in v simply testing if the key exists in the associated value:\nmy_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs': None}, 'b': {'ham': None}}\n\ndef get_parent_key(d: dict, needle: str):\n for k, v in... | [
0
] | [
"To check if a key exists in a dictionary and get its corresponding value, you can use the in keyword and the .get() method.\nHere's an example:\nmy_dict = {'a': {'spam': {'foo': None, 'bar': None, 'baz': None},'eggs'}, 'b': {'ham'}}\n\n# Check if 'spam' is a key in my_dict and get its value\nif 'spam' in my_dict:\... | [
-1
] | [
"dictionary",
"nested",
"python"
] | stackoverflow_0074666017_dictionary_nested_python.txt |
Q:
Getting distinct values from from a list comprised of lists containing a comma delimited string
Main list:
data = [
["629-2, text1, 12"],
["629-2, text2, 12"],
["407-3, text9, 6"],
["407-3, text4, 6"],
["000-5, text7, 0"],
["000-5, text6, 0"],
]
I want to get a list comprised of unique lists like so:
data_unique ... | Getting distinct values from from a list comprised of lists containing a comma delimited string | Main list:
data = [
["629-2, text1, 12"],
["629-2, text2, 12"],
["407-3, text9, 6"],
["407-3, text4, 6"],
["000-5, text7, 0"],
["000-5, text6, 0"],
]
I want to get a list comprised of unique lists like so:
data_unique = [
["629-2, text1, 12"],
["407-3, text9, 6"],
["000-5, text6, 0"],
]
I've tried using numpy.unique ... | [
"Code\nfrom itertools import groupby\n\ndef get_unique(data):\n def designated_version(item):\n return item[0].split(',')[0]\n\n return [list(v)[0] \n for _, v in groupby(sorted(data, \n key = designated_version),\n designa... | [
2,
0,
0
] | [] | [] | [
"numpy",
"python",
"python_itertools"
] | stackoverflow_0074666151_numpy_python_python_itertools.txt |
Q:
Python - How to make a circle made of 32 triangles
I would like to ask how you would make a triangle that is purely made of 32 triangles. I'm asking because I'm having trouble writing the code myself, so I thought I'd at least find some help here
I tried to write it but Python doesn't make much sense to me and eve... | Python - How to make a circle made of 32 triangles | I would like to ask how you would make a triangle that is purely made of 32 triangles. I'm asking because I'm having trouble writing the code myself, so I thought I'd at least find some help here
I tried to write it but Python doesn't make much sense to me and every time I get somewhere I find out at the end that it wa... | [] | [] | [
"To draw a circle made of triangles using Python, you can use the turtle module. The turtle module allows you to create simple graphics using a turtle that moves around the screen. You can use the turtle module to draw lines and shapes, and then fill them with color.\n"
] | [
-2
] | [
"python"
] | stackoverflow_0074666273_python.txt |
Q:
Convert RGB array to HSL
A disclaimer first, I'm not very skilled in Python, you guys have my admiration.
My problem:
I need to generate 10k+ images from templates (128px by 128px) with various hues and luminances.
I load the images and turn them into arrays
image = Image.open(dir + "/" + file).convert('RGBA')
arr... | Convert RGB array to HSL | A disclaimer first, I'm not very skilled in Python, you guys have my admiration.
My problem:
I need to generate 10k+ images from templates (128px by 128px) with various hues and luminances.
I load the images and turn them into arrays
image = Image.open(dir + "/" + file).convert('RGBA')
arr=np.array(np.asarray(image).as... | [
"Yes, numpy, namely the vectorised code, can speed-up color conversions.\nThe more, for massive production of 10k+ bitmaps, you may want to re-use a ready made professional conversion, or sub-class it, if it is not exactly matching your preferred Luminance model.\na Computer Vision library OpenCV, currently availab... | [
1,
0,
0
] | [] | [] | [
"hsl",
"numpy",
"python",
"rgb"
] | stackoverflow_0026292114_hsl_numpy_python_rgb.txt |
Q:
How to make early stopping in image classification pytorch
I'm new with Pytorch and machine learning I'm follow this tutorial in this tutorial https://www.learnopencv.com/image-classification-using-transfer-learning-in-pytorch/ and use my custom dataset. Then I have same problem in this tutorial but I dont know ho... | How to make early stopping in image classification pytorch | I'm new with Pytorch and machine learning I'm follow this tutorial in this tutorial https://www.learnopencv.com/image-classification-using-transfer-learning-in-pytorch/ and use my custom dataset. Then I have same problem in this tutorial but I dont know how to make early stopping in pytorch and if do you have better wi... | [
"This is what I did in each epoch\nval_loss += loss\nval_loss = val_loss / len(trainloader)\nif val_loss < min_val_loss:\n #Saving the model\n if min_loss > loss.item():\n min_loss = loss.item()\n best_model = copy.deepcopy(loaded_model.state_dict())\n print('Min loss %0.2f' % min_loss)\n epochs_no_impr... | [
3,
0,
0,
0
] | [] | [] | [
"early_stopping",
"python",
"pytorch"
] | stackoverflow_0060200088_early_stopping_python_pytorch.txt |
Q:
How to change matplotlib marker into a football icon?
I have visualization like this:
I want to change the marker icon into a football icon with the same color as the line
My code looks like this :
fig, ax = plt.subplots(figsize=(12,6))
ax.step(x = a_df['minute'], y = a_df['a_cum'], where = 'post', label= ateam,... | How to change matplotlib marker into a football icon? | I have visualization like this:
I want to change the marker icon into a football icon with the same color as the line
My code looks like this :
fig, ax = plt.subplots(figsize=(12,6))
ax.step(x = a_df['minute'], y = a_df['a_cum'], where = 'post', label= ateam, linewidth=2)
ax.step(x = h_df['minute'], y = h_df['h_cum']... | [
"you can draw your own shapes by creating matplotlib Path objects.\nYou need 2 lists to create it.\n1)shape's vertices(coordinates)\n2)codes:describes the path from a vertice to the next (MOVETO,LINETO,CURVE3,CURVE4,CLOSEPOLY,...)\nfor example\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\n\nve... | [
1,
0
] | [] | [] | [
"google_maps_markers",
"matplotlib",
"python",
"seaborn",
"visualization"
] | stackoverflow_0074664926_google_maps_markers_matplotlib_python_seaborn_visualization.txt |
Q:
Helix Convolution in Pytorch (Machine Learning)
I currently investigate the development of a convolutional neural network involving up to 5 or 6 dimensional arrays efficiently.
I was aware that many of the tools used for convolutional neural networks do not really deal with ND convolutions, so I decided to try and... | Helix Convolution in Pytorch (Machine Learning) | I currently investigate the development of a convolutional neural network involving up to 5 or 6 dimensional arrays efficiently.
I was aware that many of the tools used for convolutional neural networks do not really deal with ND convolutions, so I decided to try and write an implementation of Helix Convolution, whereb... | [
"Sorry, I cannot add a comment due to low rep, so I ask my question as an answer and hopefully can answer your question.\nBy helix convolution, do you mean defining a convolution operation as a single matrix multiplcation? If so, I did try this in the past but it is really memory inefficient for it to be practical.... | [
0,
0
] | [] | [] | [
"conv_neural_network",
"convolution",
"helix",
"python",
"pytorch"
] | stackoverflow_0060103887_conv_neural_network_convolution_helix_python_pytorch.txt |
Q:
Reduce Heroku Slug Size for Machine Learning (Python, PyTorch, Fastai)
I am attempting to deploy a simple maching learning app to heroku but I keep exceeding the slug size requirement of 500MB, it looks like in the end I come up to about 1GB. Most of this appears to come from PyTorch for about 700MB.
Collecting to... | Reduce Heroku Slug Size for Machine Learning (Python, PyTorch, Fastai) | I am attempting to deploy a simple maching learning app to heroku but I keep exceeding the slug size requirement of 500MB, it looks like in the end I come up to about 1GB. Most of this appears to come from PyTorch for about 700MB.
Collecting torch>=1.0.0
Downloading torch-1.6.0-cp36-cp36m-manylinux1_x86_64.whl (748.... | [
"Try adding the following lines to requirements.txt\n-f https://download.pytorch.org/whl/torch_stable.html\ntorch==1.8.1+cpu\ntorchvision==0.9.1+cpu\nfastai\nvoila\nipywidgets\n\n",
"(Aug, 2, 2022) the only solution I found was leaving the requirements.txt like this:\n--find-links https://download.pytorch.org/whl... | [
1,
0,
0
] | [] | [] | [
"heroku",
"pip",
"python"
] | stackoverflow_0063552330_heroku_pip_python.txt |
Q:
I'm not sure how to use RTK without a desktop app
I'm using a ZED-F9P.
Below is the Python script I've made for printing the Latitude and Longitude without correction data, but now I'd like to try and get more accurate with RTK.
I've got familiar with desktop applications for applying RTCM like PyGPSClient and u-c... | I'm not sure how to use RTK without a desktop app | I'm using a ZED-F9P.
Below is the Python script I've made for printing the Latitude and Longitude without correction data, but now I'd like to try and get more accurate with RTK.
I've got familiar with desktop applications for applying RTCM like PyGPSClient and u-center but I'd like to be able to achieve RTK fix within... | [
"Check out the rtk_example.py script here:\nhttps://github.com/semuconsulting/pygnssutils/blob/main/examples/rtk_example.py\n(pygnssutils is the core package used by PyGPSClient)\n"
] | [
0
] | [] | [] | [
"gps",
"ntrip",
"python",
"rtk"
] | stackoverflow_0074470405_gps_ntrip_python_rtk.txt |
Q:
Steps for Machine Learning in Pytorch
When we define our model in PyTorch. We run through different #epochs. I want to know that in the iteration of epochs.
What is the difference between the two following snippets of code in which the order is different? These two snippet versions are:
I found over tutorials
The... | Steps for Machine Learning in Pytorch | When we define our model in PyTorch. We run through different #epochs. I want to know that in the iteration of epochs.
What is the difference between the two following snippets of code in which the order is different? These two snippet versions are:
I found over tutorials
The code provided by my supervisor for the pro... | [
"The only difference is when the gradients are cleared. (when you call optimizer.zero_grad()) the first version zeros out the gradients after updating the weights (optimizer.step()), the second one zeroes out the gradient after updating the weights. both versions should run fine. The only difference would be the fi... | [
1,
0,
0,
0
] | [] | [] | [
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0072262608_machine_learning_python_pytorch.txt |
Q:
Pytorch: How to format data before execution of machine learning
I'm learning how to use pytorch and I was able to get a grasp on the overall process of construction and execution of ML models. However, what I am not able to grasp is how to "format" or "reshape" the data before executing the model. I keep getting ... | Pytorch: How to format data before execution of machine learning | I'm learning how to use pytorch and I was able to get a grasp on the overall process of construction and execution of ML models. However, what I am not able to grasp is how to "format" or "reshape" the data before executing the model. I keep getting errors like:
RuntimeError: size mismatch, m1: [1 x 700], m2: [1 x 1] ... | [
"According to the error, I believe that your data is not correctly formatted. The tensor should be in the form [700, 2] (batch x data) and yours is [1, 700] (data x batch). This makes the model 'think' that you are adding only one entry as training with 700 features instead of 700 entries with only 1 feature. \nRes... | [
0,
0
] | [] | [] | [
"linear_regression",
"machine_learning",
"python",
"pytorch"
] | stackoverflow_0050432506_linear_regression_machine_learning_python_pytorch.txt |
Q:
Screen Recorded Through Python Script is Too fast
I could record the screen, but whenever I play the video it is very fast. How can I solve this issue?
import pyautogui
import cv2
import numpy as np
resolution = (1920, 1080)
codec = cv2.VideoWriter_fourcc(*"XVID")
filename = "Recording.avi"
fps = 60.0
out = cv2.V... | Screen Recorded Through Python Script is Too fast | I could record the screen, but whenever I play the video it is very fast. How can I solve this issue?
import pyautogui
import cv2
import numpy as np
resolution = (1920, 1080)
codec = cv2.VideoWriter_fourcc(*"XVID")
filename = "Recording.avi"
fps = 60.0
out = cv2.VideoWriter(filename, codec, fps, resolution)
cv2.namedW... | [
"There are a few things you can try to make the recorded video play at a normal speed. One possible solution is to reduce the number of frames per second (fps) that are being recorded. In your code, you are setting the fps value to 60.0, which is a very high value and may be causing the recorded video to play back ... | [
0
] | [] | [] | [
"numpy",
"pyautogui",
"python",
"screen_recording"
] | stackoverflow_0074666388_numpy_pyautogui_python_screen_recording.txt |
Q:
Convert long series keys to hex, then Choose desired values from a list of long separated keys
I have code to generate series of keys as in below:
def Keygen (x,r,size):
key=[]
for i in range(size):
x= r*x*(1-x)
key.append(int((x*pow(10,16))%256))
return key
if __name__=="__main__":
key=Keygen(0... | Convert long series keys to hex, then Choose desired values from a list of long separated keys | I have code to generate series of keys as in below:
def Keygen (x,r,size):
key=[]
for i in range(size):
x= r*x*(1-x)
key.append(int((x*pow(10,16))%256))
return key
if __name__=="__main__":
key=Keygen(0.45,0.685,92)#Intial Parameters
print('nx key:', key, "\n")
The output keys are:
nx key: [0,... | [
"In order to get hex values for your list of keys, you have to iterate over the list and turn each element seperately into a hex value:\nK = tuple(hex(x) for x in key)\n\nThen you can select 4 random keys (no repeat) from this list by:\nimport random\nselectedKeys = random.sample(K, 4)\n\n",
"Maybe a better name ... | [
0,
0,
0
] | [] | [] | [
"hex",
"python"
] | stackoverflow_0074666330_hex_python.txt |
Q:
Python read in file: ERROR: line contains NULL byte
I would like to parse an .ubx File(=my input file). This file contains many different NMEA sentences as well as raw receiver data. The output file should just contain informations out of GGA sentences. This works fine as far as the .ubx File does not contain any ... | Python read in file: ERROR: line contains NULL byte | I would like to parse an .ubx File(=my input file). This file contains many different NMEA sentences as well as raw receiver data. The output file should just contain informations out of GGA sentences. This works fine as far as the .ubx File does not contain any raw messages. However if it contains raw data
I get the ... | [
"I am not quite sure but your file looks pretty binary. You should try to open it as such\nwith open(INPUT_FILENAME, 'rb') as input_file:\n\n",
"It seems like you did not open the file with correct coding format.\nSo the raw message cannot be read correctly.\nIf it is encoded as UTF8, you need to open the file wi... | [
1,
0,
0,
0
] | [] | [] | [
"nmea",
"parsing",
"python"
] | stackoverflow_0038179492_nmea_parsing_python.txt |
Q:
Save & load best model in AutoTS python
After fitting AutoTS model over some time series data, how can I save & load the best model trained? Though, the AutoTS object has export_template() & import_template() functions to save best model, but while loading best model from this template, it requires re-fitting. How... | Save & load best model in AutoTS python | After fitting AutoTS model over some time series data, how can I save & load the best model trained? Though, the AutoTS object has export_template() & import_template() functions to save best model, but while loading best model from this template, it requires re-fitting. How can such a solution be used in production? M... | [
"The major issue with your code is that you have named your export_template as 'unique_user_1' without an extension. Try saving it as csv file with 'unique_user_1.csv'\nOnce you feel you are done with training your model. Write the following lines\nmodel.export_template(\n\"unique_user_1.csv\",\nmodels=\"best\",\nm... | [
0
] | [] | [] | [
"data_science",
"forecasting",
"machine_learning",
"python",
"time_series"
] | stackoverflow_0072123229_data_science_forecasting_machine_learning_python_time_series.txt |
Q:
pandas apply subtractions on columns function when indexes are not equal, based on alignment in another columns
I have two dataframes:
df1 =
C0 C1. C2.
4 AB. 1. 2
5 AC. 7 8
6 AD. 9. 9
7 AE. 2. 6
8 AG 8. 9
df2 =
C0 C1. C2
8 AB 0. 1
9 AE. 6. 3
10 AD. 1. 2
I want to apply ... | pandas apply subtractions on columns function when indexes are not equal, based on alignment in another columns | I have two dataframes:
df1 =
C0 C1. C2.
4 AB. 1. 2
5 AC. 7 8
6 AD. 9. 9
7 AE. 2. 6
8 AG 8. 9
df2 =
C0 C1. C2
8 AB 0. 1
9 AE. 6. 3
10 AD. 1. 2
I want to apply a subtraction between these two dataframes, such that when the value of the columns C0 is the same - I will get the s... | [
"A possible solution, based on pandas.DataFrame.merge:\n(df1.merge(df2.iloc[:,:-1], on='C0', suffixes=['', 'y'], how='left')\n .rename({'C1.y': 'diff_C1'}, axis=1)\n .assign(diff_C1 = lambda x: x['C1.'].sub(x['diff_C1']))\n .assign(match = lambda x: x['diff_C1'].notna())\n .fillna(0))\n\nOutput:\n C0 C1. C2. ... | [
1,
0
] | [] | [] | [
"data_munging",
"data_science",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074666280_data_munging_data_science_dataframe_pandas_python.txt |
Q:
ImproperlyConfigured AUTH_USER_MODEL refers to model 'core.User' that has not been installed
I am calling this method in my core app - models.py,
from django.contrib.auth import get_user_model
User = get_user_model()
I am getting error,
Exception has occurred: ImproperlyConfigured (note: full exception trace is s... | ImproperlyConfigured AUTH_USER_MODEL refers to model 'core.User' that has not been installed | I am calling this method in my core app - models.py,
from django.contrib.auth import get_user_model
User = get_user_model()
I am getting error,
Exception has occurred: ImproperlyConfigured (note: full exception trace is shown but execution is paused at: <module>)
AUTH_USER_MODEL refers to model 'core.User' that has no... | [
"I found the problem,\nUser = get_user_model()\n\nI had pasted follwing code inside the core app models.py\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python",
"python_3.x"
] | stackoverflow_0074666310_django_django_models_python_python_3.x.txt |
Q:
Match with Django import_export with multiple fields
I would like to import a CSV in Django. The issue occurs when trying to import based on the attributes. Here is my code:
class Event(models.Model):
id = models.BigAutoField(primary_key=True)
amount = models.ForeignKey(Amount, on_delete=models.CASCADE)
... | Match with Django import_export with multiple fields | I would like to import a CSV in Django. The issue occurs when trying to import based on the attributes. Here is my code:
class Event(models.Model):
id = models.BigAutoField(primary_key=True)
amount = models.ForeignKey(Amount, on_delete=models.CASCADE)
value = models.FloatField()
space = models.ForeignKe... | [
"\nThe main question is: How to search for objects in Space by attributes (space_code,space_type,space_date) and in Time search and create by (time_date,time_type)\n\nIt looks like you are searching for these objects correctly, but it might not be being called. Often with import-export you will save yourself a lot... | [
1,
0
] | [] | [] | [
"django",
"django_import_export",
"python"
] | stackoverflow_0074647054_django_django_import_export_python.txt |
Q:
How to determine the majority of appearances of a list in list of lists. (Python)
I am trying to determine the majority in a list of lists for a project I am working on. My problem is that the code will run in an environment that not allow me to use packages. Can someone refer me to an algorithm that does what I a... | How to determine the majority of appearances of a list in list of lists. (Python) | I am trying to determine the majority in a list of lists for a project I am working on. My problem is that the code will run in an environment that not allow me to use packages. Can someone refer me to an algorithm that does what I am asking or let me know about a way to do it with pre built functions in python that do... | [
"You can actually use a dictionairy to save the lists as keys and use the values as count. Then you can take the maximum count, to get your result.\ndata = [ [\"hello\", 1], [\"hello\", 1], [\"hello\", 1], [\"other\", 32] ]\n\n# Make a dictionary:\ndic = {}\n\n# Loop over every item in the data\nfor item in data:\n... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074665675_python.txt |
Q:
What is meant by ‘define model class’ in pytorch documentation?
On the pytorch documentation page about saving and loading models, it says that when loading a saved model, # Model class must be defined somewhere https://pytorch.org/tutorials/beginner/saving_loading_models.html#:~:text=%23%20Model%20class%20must%20... | What is meant by ‘define model class’ in pytorch documentation? | On the pytorch documentation page about saving and loading models, it says that when loading a saved model, # Model class must be defined somewhere https://pytorch.org/tutorials/beginner/saving_loading_models.html#:~:text=%23%20Model%20class%20must%20be%20defined%20somewhere
Maybe my question is silly, but what does cl... | [
"You need to define the model class as, for example, explained here. Re-using the example from the linked website as a random example, a class for TheModelClass could be defined as follows:\nclass TheModelClass(torch.nn.Module):\n\n def __init__(self):\n super(TheModelClass, self).__init__()\n\n se... | [
0,
0
] | [] | [] | [
"nlp",
"python",
"pytorch"
] | stackoverflow_0073339264_nlp_python_pytorch.txt |
Q:
Concatenate columns of Pandas dataframe into a new column of lists with only non-zero values
I have a Pandas dataframe that looks like:
mwe5a = pd.DataFrame({'a': [0.1, 0.0],
'b': [0.0, 0.2],
'c': [0.3, 0.0]
}
)
mwe5a
a b ... | Concatenate columns of Pandas dataframe into a new column of lists with only non-zero values | I have a Pandas dataframe that looks like:
mwe5a = pd.DataFrame({'a': [0.1, 0.0],
'b': [0.0, 0.2],
'c': [0.3, 0.0]
}
)
mwe5a
a b c
0 0.1 0.0 0.3
1 0.0 0.2 0.0
My desired output is:
mwe5b
output_column
... | [
"A possible solution:\nmwe5b = (mwe5a\n .apply(lambda x: list(x[x.ne(0)].sort_values(ascending=False)), axis=1)\n .to_frame('output_column'))\n\nOutput:\n output_column\n0 [0.3, 0.1]\n1 [0.2]\n\nEDIT\nTo accomplish the goal the OP wants with mwe7a, I offer the following solution:\n(mwe7a... | [
2
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074666489_pandas_python_python_3.x.txt |
Q:
Alphabet Layers In Python
How to multiply layers without ankwardly repeating elif lines? Cannot get += 1 working. Or perhaps different string approach? I'm certainly new in Python.
layer = int(input("Give a number between 2 and 26: "))
table_size = layer + layer - 1
ts = table_size
center = (ts // 2)
for row in r... | Alphabet Layers In Python | How to multiply layers without ankwardly repeating elif lines? Cannot get += 1 working. Or perhaps different string approach? I'm certainly new in Python.
layer = int(input("Give a number between 2 and 26: "))
table_size = layer + layer - 1
ts = table_size
center = (ts // 2)
for row in range(ts):
for col in ra... | [
"You can resort to numpy to prepare the indexation of the alphabet, and then use the prepared indexes to get your final string. This is how:\n# Get your number of layers\nN = int(input(\"Give a number between 2 and 26: \"))\nassert 2<=N<=26, 'Wrong number'\n\n# INDEX PREPARATION WITH NP\nimport numpy as np\nlen_vec... | [
0,
0,
0,
0
] | [] | [] | [
"alphabet",
"design_patterns",
"layer",
"loops",
"python"
] | stackoverflow_0067938383_alphabet_design_patterns_layer_loops_python.txt |
Q:
PyDev and Django: how to restart dev server?
I'm new to Django. I think I'm making a simple mistake.
I launched the dev server with Pydev:
RClick on project >> Django >> Custom
command >> runserver
The server came up, and everything was great. But now I'm trying to stop it, and can't figure out how. I stopped ... | PyDev and Django: how to restart dev server? | I'm new to Django. I think I'm making a simple mistake.
I launched the dev server with Pydev:
RClick on project >> Django >> Custom
command >> runserver
The server came up, and everything was great. But now I'm trying to stop it, and can't figure out how. I stopped the process in the PyDev console, and closed Eclip... | [
"By default, the runserver command runs in autoreload mode, which runs in a separate process. This means that PyDev doesn't know how to stop it, and doesn't display its output in the console window.\nIf you run the command runserver --noreload instead, the auto-reloader will be disabled. Then you can see the consol... | [
14,
5,
4,
3,
2,
1,
0,
0
] | [] | [] | [
"devserver",
"django",
"eclipse",
"pydev",
"python"
] | stackoverflow_0002746512_devserver_django_eclipse_pydev_python.txt |
Q:
Hi I am new to python programming. I have written the following code but I keep getting this error. Can anyone help me at all please?
count = 1
total = 0
average = 0
array = []
while input("Enter q to quit or any other key to continue: ") != "q":
numlist = input('Enter number\n')
array.append(numlist)
... | Hi I am new to python programming. I have written the following code but I keep getting this error. Can anyone help me at all please? | count = 1
total = 0
average = 0
array = []
while input("Enter q to quit or any other key to continue: ") != "q":
numlist = input('Enter number\n')
array.append(numlist)
try:
count = count + 1
total = total + float(numlist)
except:
count = count - 1
print('Enter... | [
"An input function is returning a string even though you actually type a number:\nhttps://docs.python.org/3/library/functions.html#input\nYou need to convert that string to number before appending to array, for instance:\narray.append(float(numlist))\n\nbut it should be in try / except block so your validation chec... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074666567_python.txt |
Q:
Assigned a complex value in cupy RawKernel
I am a beginner learning how to exploit GPU for parallel computation using python and cupy. I would like to implement my code to simulate some problems in physics and require to use complex number, but don't know how to manage it. Although there are examples in Cupy's off... | Assigned a complex value in cupy RawKernel | I am a beginner learning how to exploit GPU for parallel computation using python and cupy. I would like to implement my code to simulate some problems in physics and require to use complex number, but don't know how to manage it. Although there are examples in Cupy's official document, it only mentions about include c... | [
"@plaeonix, thank you very much for your hint. I find out the answer.\nThis line:\ncomplex<float>* value = complex(x[tId_x],y[tId_y])\nshould be replaced to:\ncomplex<float> value = complex<float>(x[tId_x],y[tId_y])\nThen the assignment of a complex number works.\n"
] | [
1
] | [] | [] | [
"cuda",
"cupy",
"python"
] | stackoverflow_0074654285_cuda_cupy_python.txt |
Q:
why i getting IndexError: list index out of range
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:
'abc' => ['ab', 'c_']
'ab... | why i getting IndexError: list index out of range | Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:
'abc' => ['ab', 'c_']
'abcdef' => ['ab', 'cd', 'ef']
https://prnt.sc/E2sdtceLtk... | [
"its fixed by adding another if condition which checking sp is empty or not\ndef solution(s):\n n = 2\n sp = [s[index : index + n] for index in range(0, len(s), n)]\n\n if len(sp) == 0:\n return sp\n\n if len(sp[-1]) == 1:\n sp[-1] = sp[-1] + \"_\"\n return sp\n\n else:\n retu... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074666426_python.txt |
Q:
Can;t install lxml package on windwos 11
"PS D:\Complete-Python-3-Bootcamp-master\12-Advanced Python Modules\puzzle_unzip> pip install lxml
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Installing collected packages: lxml
DEPRECATION: lxml is being installed u... | Can;t install lxml package on windwos 11 | "PS D:\Complete-Python-3-Bootcamp-master\12-Advanced Python Modules\puzzle_unzip> pip install lxml
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Installing collected packages: lxml
DEPRECATION: lxml is being installed using the legacy 'setup.py install' method, bec... | [
"The Python lxml module is a language-binding / wrapper for two C libraries.\nFor Windows they provide binary builds that include these libraries. Otherwise it will be pain and suffering getting it installed and running on Windows. Because it's Windows. \"Developers, developers, developers\".. (As lxml developers p... | [
1
] | [] | [] | [
"lxml",
"pip",
"python",
"python_3.x"
] | stackoverflow_0074666576_lxml_pip_python_python_3.x.txt |
Q:
How to get data from the model
I need to get data from a model in Django. I specify filtering, an error occurs. I'm doing a project with TV series and movies. When clicking on any of the listed categories, I need to take data from this category. That is, which films belong to this category.
enter image description... | How to get data from the model | I need to get data from a model in Django. I specify filtering, an error occurs. I'm doing a project with TV series and movies. When clicking on any of the listed categories, I need to take data from this category. That is, which films belong to this category.
enter image description here
enter image description here
I... | [
"I did not understand your situation well. But that's what I did when I was in that situation.\ndef gallery(request):\n category = request.GET.get('category')\n if category == None:\n photos = Photo.objects.all()\n else:\n photos = Photo.objects.filter(category__name=category)\n \n ... | [
0
] | [] | [] | [
"django",
"model",
"python",
"view"
] | stackoverflow_0074665982_django_model_python_view.txt |
Q:
Why does the function return each element of the list on a new line?
So i have this code right here to separate only ints or floats out of a file and add them to a list, however when it returns the list, it returns each element on a new line and not the entire list on the same line, and I'm wondering why?
the list... | Why does the function return each element of the list on a new line? | So i have this code right here to separate only ints or floats out of a file and add them to a list, however when it returns the list, it returns each element on a new line and not the entire list on the same line, and I'm wondering why?
the list looks kind of like this:
12 w 21 d23g780nb deed e2 21.87
43 91 - . 222 mf... | [
"I created a file like this:\nfile a:\n12 43 12.145 546 23 76 5.54 231.1 32\n\nthen I run your code like this:\nIn [3]: def read_numbers(path: str) -> list:\n ...: with open(path) as f:\n ...: file_elem = f.read().split()\n ...: a = []\n ...: for x in file_elem:\n ...: if x.isn... | [
1
] | [] | [] | [
"append",
"list",
"python"
] | stackoverflow_0074666578_append_list_python.txt |
Q:
Reauthentication failed error while accessing bigquery via python
i am trying to access bigquery using python . even though after executing "gcloud auth login"
getting below error.
google.auth.exceptions.ReauthFailError: Reauthentication failed. Reauthentication challenge could not be answered because you are no... | Reauthentication failed error while accessing bigquery via python | i am trying to access bigquery using python . even though after executing "gcloud auth login"
getting below error.
google.auth.exceptions.ReauthFailError: Reauthentication failed. Reauthentication challenge could not be answered because you are not in an interactive session.
what can be issue here
| [
"You can solve this problem by creating a service account and set up the Cloud SDK to use the service account.\nExample command:\ngcloud auth activate-service-account account-name --key-file=/fullpath/service-account.json\n\nOther way is to set up the environment variables for the Python script to use while accessi... | [
0
] | [] | [] | [
"google_bigquery",
"google_cloud_platform",
"python"
] | stackoverflow_0074475900_google_bigquery_google_cloud_platform_python.txt |
Q:
List comprehension for running total
I want to get a running total from a list of numbers.
For demo purposes, I start with a sequential list of numbers using range
a = range(20)
runningTotal = []
for n in range(len(a)):
new = runningTotal[n-1] + a[n] if n > 0 else a[n]
runningTotal.append(new)
# This one... | List comprehension for running total | I want to get a running total from a list of numbers.
For demo purposes, I start with a sequential list of numbers using range
a = range(20)
runningTotal = []
for n in range(len(a)):
new = runningTotal[n-1] + a[n] if n > 0 else a[n]
runningTotal.append(new)
# This one is a syntax error
# runningTotal = [a[n] ... | [
"A list comprehension has no good (clean, portable) way to refer to the very list it's building. One good and elegant approach might be to do the job in a generator:\ndef running_sum(a):\n tot = 0\n for item in a:\n tot += item\n yield tot\n\nto get this as a list instead, of course, use list(running_sum(a)... | [
30,
28,
12,
10,
9,
7,
3,
3,
2,
2,
1,
0,
0
] | [
"with Python 3.8 and above you can now use walrus operator\nxs = range(20)\ntotal = 0\nrun = [(total := total + d) for d in xs]\n\n"
] | [
-1
] | [
"cumulative_sum",
"list_comprehension",
"python"
] | stackoverflow_0003432830_cumulative_sum_list_comprehension_python.txt |
Q:
Extracting text from an alphanumeric reference
I have a load of bank statement data which includes a payment reference. This is free form so some include invoice numbers, their info or a name and typically it’s 16-256 characters depending on the system they use to make the payment. I’ve put the data in a pandas da... | Extracting text from an alphanumeric reference | I have a load of bank statement data which includes a payment reference. This is free form so some include invoice numbers, their info or a name and typically it’s 16-256 characters depending on the system they use to make the payment. I’ve put the data in a pandas data frame with transaction amount, currency and date ... | [
"If the target text would always be one sequence of contiguous words, you could try using str.extract as follows:\ndf[\"name\"] = df[\"invoice\"].str.extract(r'(\\w+(?: \\w+)*)')\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074666737_dataframe_python.txt |
Q:
how do you Apply math multiply a number to a decimal point python
i want apply lambda to do multiplication which is condition type data float value like this
0.412
0.0036
0.0467
0.000678
0.00000342
expected output
0.41
0.36
0.47
0.68
0.34
A:
You can use replace with astype and round.
Try this :
df["col"] = df["c... | how do you Apply math multiply a number to a decimal point python | i want apply lambda to do multiplication which is condition type data float value like this
0.412
0.0036
0.0467
0.000678
0.00000342
expected output
0.41
0.36
0.47
0.68
0.34
| [
"You can use replace with astype and round.\nTry this :\ndf[\"col\"] = df[\"col\"].replace(\"\\.0*\", \".\", regex=True).astype(float).round(2)\n\n# Output :\nprint(df)\n\n col\n0 0.41\n1 0.36\n2 0.47\n3 0.68\n4 0.34\n\n",
"Try this:\nimport re\nlambda_func = lambda x: re.sub(r'(\\.0*)', r'.', str(x))\n\n"
] | [
1,
0
] | [] | [] | [
"apply",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074665796_apply_dataframe_numpy_pandas_python.txt |
Q:
Python Move/Copy files/Getting names of files from folders without using os.chdir
Without using os.chdir how to move/copy files (specific files using wild card, say ABC in file name) from folder X (drive D) to folder Y (drive E) while the python script is in folder Z (drive F), ? I will run py script from windows ... | Python Move/Copy files/Getting names of files from folders without using os.chdir | Without using os.chdir how to move/copy files (specific files using wild card, say ABC in file name) from folder X (drive D) to folder Y (drive E) while the python script is in folder Z (drive F), ? I will run py script from windows task scheduler.
| [
"How about:\nsubprocess.Popen('copy file.exe C:/path/to/copy/', shell=True)\n\n"
] | [
0
] | [] | [] | [
"python",
"shutil"
] | stackoverflow_0074666753_python_shutil.txt |
Q:
Regex python Match after and before a specific string
Lets say we have this
string:"Code:1,Some text some other text {fdf: more text, attr=important "
I want to catch the pattern using Regex that can findall attr and extract important and 1 and put them in dict.
I tried this one:
(?<=testcaseid_)[^_]+_[^_]+
but s... | Regex python Match after and before a specific string | Lets say we have this
string:"Code:1,Some text some other text {fdf: more text, attr=important "
I want to catch the pattern using Regex that can findall attr and extract important and 1 and put them in dict.
I tried this one:
(?<=testcaseid_)[^_]+_[^_]+
but still capture all the previous
| [
"I'm not sure if I understand well, but if you want to get everything starts from \"1\" to something after attr= you can also use regex like this:\nr\"1.*?attr=\\w+\"\n\n"
] | [
0
] | [] | [] | [
"list",
"python",
"regex",
"split",
"web_scraping"
] | stackoverflow_0074666604_list_python_regex_split_web_scraping.txt |
Q:
I try to iterate over a function and don't know where the error (TypeError: 'tuple' object is not callable) is coming from
def result(player1, player2):
if player1 == 'A' and player2 == 'X' or player1 == 'B' and player2 == 'Y' or player1 == 'C' and player2 == 'Z':
state = 'draw'
return state, V... | I try to iterate over a function and don't know where the error (TypeError: 'tuple' object is not callable) is coming from | def result(player1, player2):
if player1 == 'A' and player2 == 'X' or player1 == 'B' and player2 == 'Y' or player1 == 'C' and player2 == 'Z':
state = 'draw'
return state, VALUE[player2]
if player1 == 'A' and player2 == 'Y' or player1 == 'B' and player2 == 'Z' or player1 == 'C' and player2 == 'X'... | [
"points += 1 + result[1]\n\nI think you should edit the result[1] as results[1]. You are trying to reach the 1st index of the method, not the output.\npoints += 1 + results[1]\n\nAnd in case it does not work, can you please share all error message and your custom input used in the method?\n",
"Now I would like to... | [
0,
0
] | [] | [] | [
"python",
"tuples",
"typeerror"
] | stackoverflow_0074666692_python_tuples_typeerror.txt |
Q:
How to associate repeated strings with values from a dictionary in a dataframe?
I'm trying to associate in a dataframe the values of a list of numbers with the respective strings. Here's the problem:
import pandas as pd
categories = {"key1":["string1", "string2", "string3"], "key2": ["string1", "str1", "str2"]}
st... | How to associate repeated strings with values from a dictionary in a dataframe? | I'm trying to associate in a dataframe the values of a list of numbers with the respective strings. Here's the problem:
import pandas as pd
categories = {"key1":["string1", "string2", "string3"], "key2": ["string1", "str1", "str2"]}
strings= ["string1", "string2", "string3", "string1", "str1", "str2"]
numbers = [1,2,3,... | [
"Do you need a solution with pandas? How about this solution:\nfrom collections import OrderedDict\n\ncategories = OrderedDict([(\"key1\", [\"string1\", \"string2\", \"string3\"]), (\"key2\", [\"string1\", \"str1\", \"str2\"])])\n\ndef category_strings(ordered_dict):\n current_id = 1\n for key, strings in ord... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074666167_dataframe_pandas_python_python_2.7_python_3.x.txt |
Q:
How to print multilevel nested dictonary in python
Here is my code
print(data['a'][0]['aa'])
print(data['a'][0].keys())
This is input->
data={
'a':[{
'aa':{'aax':5,'aay':6,'aaz':7},
'ab':{'abx':8,'aby':9,'abz':10}
},
{
'aaa':{'aaax':... | How to print multilevel nested dictonary in python | Here is my code
print(data['a'][0]['aa'])
print(data['a'][0].keys())
This is input->
data={
'a':[{
'aa':{'aax':5,'aay':6,'aaz':7},
'ab':{'abx':8,'aby':9,'abz':10}
},
{
'aaa':{'aaax':11,'aaay':12,'aaaz':13},
'aab':{'aabx':14,'a... | [
"just use simple for loop\nfor outer_list in data['a']:\n for outer_key, outer_value in outer_list.items():\n for key, value in outer_value.items():\n print(\"Key: {}, Value: {}\".format(key, value))\n\noutput:\nKey: aax, Value: 5\nKey: aay, Value: 6\nKey: aaz, Value: 7\nKey: abx, Value: 8\nKey... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074666762_dictionary_python.txt |
Q:
Any Easy Fix for Module Not Found Error ‘TKinter’?
imported tkinter
jnot able to get the expected output since it gives an error.
imported tkinter
jnot able to get the expected output since it gives an error.
| Any Easy Fix for Module Not Found Error ‘TKinter’? | imported tkinter
jnot able to get the expected output since it gives an error.
imported tkinter
jnot able to get the expected output since it gives an error.
| [] | [] | [
"Firstly, import it like:\nfrom Tkinter import *\n\nif there are still errors, be sure that module installed at your inventory, Open terminal, after reaching the folder you're working, enter pip list.If tkinter is not there, you might be installed it to somewhere else than your environment/folder. In the same termi... | [
-1
] | [
"python"
] | stackoverflow_0074666635_python.txt |
Q:
Flask Sqlalchemy one to many foreignkey error
I made two simple classes as model:
app = Flask(__name__)
app.secret_key = 'winwin'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///abc.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.permanent_session_lifetime = timedelta(minutes=5)
db = SQLAlchemy(ap... | Flask Sqlalchemy one to many foreignkey error | I made two simple classes as model:
app = Flask(__name__)
app.secret_key = 'winwin'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///abc.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.permanent_session_lifetime = timedelta(minutes=5)
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'use... | [
"session.add_all expects a list of model instances as its argument, but you are passing a list containing a string.\nIn instead of\ndb.session.add_all(['aaa,bbb,ccc'])\n\npass the objects that you created, like this:\ndb.session.add_all([aaa, bbb, ccc])\n\n"
] | [
0
] | [] | [] | [
"flask_sqlalchemy",
"foreign_keys",
"python"
] | stackoverflow_0074664654_flask_sqlalchemy_foreign_keys_python.txt |
Q:
Grouping in regular expression with python
I have pandas series which looks like:
m = pd.Series(['expected != is --> found missing lices ## expected: 2.25 || is: 4.5 || expected: 3 || is: 2 ##','expected != is --> found missing lices ## expected: 3.35 || is: 5.5 || expected: 3 || is: 3 ##',
'expected != is --> fou... | Grouping in regular expression with python | I have pandas series which looks like:
m = pd.Series(['expected != is --> found missing lices ## expected: 2.25 || is: 4.5 || expected: 3 || is: 2 ##','expected != is --> found missing lices ## expected: 3.35 || is: 5.5 || expected: 3 || is: 3 ##',
'expected != is --> found missing lices ## expected: 2.25 || is: 4.5 ||... | [
"You can use\nm = m.replace(r'expected != is --> found missing lices ## expected: \\d+(?:\\.\\d+)? \\|\\| is: [0-9]\\d*(\\.\\d+)? \\|\\| expected: \\d+ \\|\\| is: \\d+ ##', 'expected != is --> found missing lices', regex=True)\n\nSee the regex demo\nNote:\n\n{...} is not a grouping construct in regexps, you need (.... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074666518_python_regex.txt |
Q:
overwrite dataframe rows with merge
I am trying to overwrite specific rows and columns from one dataframe with a second dataframe rows and columns. I can't give the actual data but I will use a proxy here.
Here is an example and what I have tried:
df1
UID B C D
0 X14 cat red One
1 X26 ... | overwrite dataframe rows with merge | I am trying to overwrite specific rows and columns from one dataframe with a second dataframe rows and columns. I can't give the actual data but I will use a proxy here.
Here is an example and what I have tried:
df1
UID B C D
0 X14 cat red One
1 X26 cat blue Two
2 X99 cat pink O... | [
"You can approach this by using reindex_like and combine_first.\nTry this :\nout = (\n df2.set_index(\"UID\")\n .reindex_like(df1.set_index(\"UID\"))\n .combine_first(df1.set_index(\"UID\"))\n .reset_index()\n )\n\n# Output :\nprint(out)\n\n UID B C D\n0 X14 ... | [
1,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074666769_dataframe_pandas_python.txt |
Q:
How to add a Zero-or-more-condition (?) to multiple characters via regex without creating a capturing group?
The function rearrange_name should be given a name in the format:
Last Name (Normal or Double-barrelled name) followed by a "," " " and the First Name (either just one first name or together with middle ini... | How to add a Zero-or-more-condition (?) to multiple characters via regex without creating a capturing group? | The function rearrange_name should be given a name in the format:
Last Name (Normal or Double-barrelled name) followed by a "," " " and the First Name (either just one first name or together with middle initial name or full middle name)
Then the name should be rearranged to print it out as first name + last name.
This ... | [
"Try the pattern:\n([A-Z][a-zA-Z]+(?:-[A-Z][a-zA-Z]+)?), ([A-Z][a-zA-Z]+\\s*(?:[A-Z][a-zA-Z]+|[A-Z]\\.)?)\n\nRegex demo.\nimport re\n\n\npat = re.compile(\n r\"([A-Z][a-zA-Z]+(?:-[A-Z][a-zA-Z]+)?), ([A-Z][a-zA-Z]+\\s*(?:[A-Z][a-zA-Z]+|[A-Z]\\.)?)\"\n)\n\n\ndef rearrange_name(name):\n m = pat.match(name)\n ... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074666500_python_regex.txt |
Q:
reversed regex mashine implementation
I'm trying to match a string starting from the last character to fail as soon as possible. This way I can fail a match with a custom string cstr (see specification below) with least amount of operations (4th property).
From a theoritical perspective the regex can be represente... | reversed regex mashine implementation | I'm trying to match a string starting from the last character to fail as soon as possible. This way I can fail a match with a custom string cstr (see specification below) with least amount of operations (4th property).
From a theoritical perspective the regex can be represented as a finite state mashine and the arrows ... | [
"OP here. Here are some thougts:\n\nSince I'm looking for an unoptimized regex mashine, I have to build it myself, which takes time.\n\nAlternatively we can define an upperbound for cstr length and create all strings that matches given regex with length < upperbound. Then we put all solutions to a tire data structu... | [
0
] | [] | [] | [
"implementation",
"javascript",
"python",
"regex"
] | stackoverflow_0074665144_implementation_javascript_python_regex.txt |
Q:
Flask-Caching use UWSGI cache with NGINX
The UWSGI is connected to the flask app per UNIX-Socket:
NGINX (LISTEN TO PORT 80) <-> UWSGI (LISTER PER UNIX-SOCKER) <-> FLASK-APP
I have initalized a uwsgi cache to handle global data.
I want to handle the cache with python package flask-caching.
I am trying to init the C... | Flask-Caching use UWSGI cache with NGINX | The UWSGI is connected to the flask app per UNIX-Socket:
NGINX (LISTEN TO PORT 80) <-> UWSGI (LISTER PER UNIX-SOCKER) <-> FLASK-APP
I have initalized a uwsgi cache to handle global data.
I want to handle the cache with python package flask-caching.
I am trying to init the Cache-instance with the correct cache address. ... | [
"Be aware of using of spawning multiple processes for NGINX. Every process handles its own cache. Without an additional layer, it is not possible to access to a cache from different nginx process.\n\nThis answer was posted as an edit to the question Flask-Caching use UWSGI cache with NGINX by the OP ewro under CC B... | [
0
] | [] | [] | [
"flask_cache",
"flask_caching",
"nginx",
"python",
"uwsgi"
] | stackoverflow_0052096704_flask_cache_flask_caching_nginx_python_uwsgi.txt |
Q:
python beautifulsoup: how to find all before certain stop tag?
I need to find all tags of a certain kind (class "nice") but excluding those after a certain other tag (class "stop").
<div class="nice"></div>
<div class="nice"></div>
<div class="stop">here should be the end of found items</div>
<div class="nice"><... | python beautifulsoup: how to find all before certain stop tag? | I need to find all tags of a certain kind (class "nice") but excluding those after a certain other tag (class "stop").
<div class="nice"></div>
<div class="nice"></div>
<div class="stop">here should be the end of found items</div>
<div class="nice"></div>
<div class="nice"></div>
How do I accomplish this using bs4?
... | [
"You can use for example .find_previous to filter out unwanted tags:\nfrom bs4 import BeautifulSoup\n\n\nhtml_doc = \"\"\"\\\n<div class=\"nice\">want 1</div>\n<div class=\"nice\">want 2</div>\n<div class=\"stop\">here should be the end of found items</div>\n<div class=\"nice\">do not want 1</div>\n<div class=\"nic... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0074666897_beautifulsoup_html_python.txt |
Q:
I'm having trouble adding a scrollbar to my project that I developed with tkinter
`
import tkinter
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from tkinter import *
import pandas as pd
from tkinter import ttk
from datetime import datetime
#tkinter
master = Tk()
master.title("A... | I'm having trouble adding a scrollbar to my project that I developed with tkinter | `
import tkinter
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
from tkinter import *
import pandas as pd
from tkinter import ttk
from datetime import datetime
#tkinter
master = Tk()
master.title("Anket")
master.state('zoomed')
#new mainframe
frame = tkinter.Frame(master)
frame.pack(... | [
"I did not test it. Use tkinter.tix.ScrolledWindow.\nfrom tkinter.tix import *\n:\n:\n:\n#add this between line 16 to 21.\n#new mainframe\nframe = tkinter.Frame(master)\nframe.pack()\n\nswin = ScrolledWindow(frame, width=500, height=500)\nswin.pack()\n\n#label inputs\n\n"
] | [
0
] | [] | [] | [
"python",
"scrollbar",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074665863_python_scrollbar_tkinter_tkinter_canvas.txt |
Q:
tkinter.place() not working and window still blank
I have a problem with tkinter.place, why it is not working?
class KafeDaun(tk.Frame):
def __init__(self, master = None):
super().__init__(master)
self.master.title("Kafe Daun-Daun Pacilkom v2.0 ")
self.master.geometry("500x300")
... | tkinter.place() not working and window still blank | I have a problem with tkinter.place, why it is not working?
class KafeDaun(tk.Frame):
def __init__(self, master = None):
super().__init__(master)
self.master.title("Kafe Daun-Daun Pacilkom v2.0 ")
self.master.geometry("500x300")
self.master.configure(bg="grey")
self.create_wi... | [
"Try this.\nYou have to pack the frame like this self.pack(fill=\"both\", expand=True). Because the place did not change the parent size, that's why it didn't visible\nimport tkinter as tk\nclass KafeDaun(tk.Frame):\n def __init__(self, master = None):\n super().__init__(master)\n self.master.title... | [
1
] | [] | [] | [
"methods",
"python",
"tkinter",
"tkinter_button",
"tkinter_canvas"
] | stackoverflow_0074666863_methods_python_tkinter_tkinter_button_tkinter_canvas.txt |
Q:
Plolty combine timeline on one line into subplots
I try to put a px.timeline into subplot, but my timeline format change.
import pandas as pd
import plotly.express as px
import plotly.subplots as sp
df1 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
dict(unit='MVT',Task="... | Plolty combine timeline on one line into subplots | I try to put a px.timeline into subplot, but my timeline format change.
import pandas as pd
import plotly.express as px
import plotly.subplots as sp
df1 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
dict(unit='MVT',Task="Job B", Start='2009-02-28', Finish='2009-04-15'),
dict(... | [
"I found it, we need to add\nfig_sub.update_layout(barmode=\"overlay\") \n\nby default in sub_plots it is put in barmode=\"group\"\n"
] | [
1
] | [] | [] | [
"plotly",
"python",
"subplot"
] | stackoverflow_0074666793_plotly_python_subplot.txt |
Q:
How to improve the knn model?
I built a knn model for classification. Unfortunately, my model has accuracy > 80%, and I would like to get a better result. Can I ask for some tips? Maybe I used too many predictors?
My data = https://www.openml.org/search?type=data&sort=runs&id=53&status=active
import pandas as pd
f... | How to improve the knn model? | I built a knn model for classification. Unfortunately, my model has accuracy > 80%, and I would like to get a better result. Can I ask for some tips? Maybe I used too many predictors?
My data = https://www.openml.org/search?type=data&sort=runs&id=53&status=active
import pandas as pd
from sklearn.model_selection import ... | [
"There are a few things you can try to improve the accuracy of your KNN model.\nFirst, you can try tuning the hyperparameters of your model, such as the number of nearest neighbors to consider or the distance metric used to measure the similarity between points.\nTo tune the hyperparameters of your KNN model, you c... | [
2,
1
] | [] | [] | [
"knn",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074666866_knn_machine_learning_python_scikit_learn.txt |
Q:
How can I print the number as elements of a list without the quotes and square brackets should be their?
The result should have square brackets enclosing the elements of list which are numbers , these numbers should not be enclosed into quotes.
i tried to do so with split function and for loop but was not able to ... | How can I print the number as elements of a list without the quotes and square brackets should be their? | The result should have square brackets enclosing the elements of list which are numbers , these numbers should not be enclosed into quotes.
i tried to do so with split function and for loop but was not able to get my desired result. i am expecting the answer.
| [
"You can unpack all list elements into the print() function to print all values individually, separated by an empty space per default (that you can override using the sep argument). For example, the expression print(*my_list) prints the elements in my_list, empty space separated, without the enclosing square bracke... | [
0,
0
] | [] | [] | [
"function",
"input",
"list",
"output",
"python"
] | stackoverflow_0074666568_function_input_list_output_python.txt |
Q:
aws glue job: best practice for new data as it comes in?
Im new to AWS and glue.
I have a glue job that uses a python script to convert a data source into a json formatted file. The new data is sent to us on a monthly basis and so my thought was to trigger the glue job to run every time the data was added to our s... | aws glue job: best practice for new data as it comes in? | Im new to AWS and glue.
I have a glue job that uses a python script to convert a data source into a json formatted file. The new data is sent to us on a monthly basis and so my thought was to trigger the glue job to run every time the data was added to our s3 bucket.
I have the job setup to overwrite the file every tim... | [
"What I would suggest to you is to partition the data. Based on what you've said, you get the data on a monthly basis.\nAn S3 key represents the path to the file in an S3 bucket. In your example, outputfile.json is a top-level object in your S3 bucket. Based on your requirements, you could partition the data by yea... | [
0
] | [] | [] | [
"amazon_web_services",
"aws_glue",
"python"
] | stackoverflow_0074650200_amazon_web_services_aws_glue_python.txt |
Q:
Python program unable to access sound (and other files) from subdirectories
I have a few functions in my program to print from text files, and to play sound files using Path. One such function allows me to run the program from ANY directory, and it can still find and play its sound files. It works perfectly, excep... | Python program unable to access sound (and other files) from subdirectories | I have a few functions in my program to print from text files, and to play sound files using Path. One such function allows me to run the program from ANY directory, and it can still find and play its sound files. It works perfectly, except in only plays files located in the program directory:
def sound_player_loop(sou... | [
"To resolve relative to the directory of __file__ you need something like\nsound_folder = Path(__file__).with_name(\"sound\")\n...\np = sound_folder / sound_file\n\n"
] | [
2
] | [] | [] | [
"path",
"python"
] | stackoverflow_0074666976_path_python.txt |
Q:
How do I make a turtle move in OOP?
I'm making a simple pong game and and trying to make it with OOP. I'm trying to get the turtles to move using ycor. It's intended to call the 'objects_up' method to move them up and do then ill do the same for x and y.
I've tried all sorts of indentation, not using a method and ... | How do I make a turtle move in OOP? | I'm making a simple pong game and and trying to make it with OOP. I'm trying to get the turtles to move using ycor. It's intended to call the 'objects_up' method to move them up and do then ill do the same for x and y.
I've tried all sorts of indentation, not using a method and moving wn.listen outside of the class. Wh... | [
"Thanks guys! Solved the problem, was sooo much easier than I thought.\nHere's the new code:\nfrom turtle import Screen,Turtle\n\nwn = Screen()\nwn.title(\"Pong by CGGamer\")\nwn.bgcolor(\"black\")\nwn.setup(width=800, height=600)\nwn.tracer(0)\n\nclass Paddles(Turtle): \n def __init__(self,position,size):\n ... | [
0
] | [] | [] | [
"class",
"python",
"python_turtle"
] | stackoverflow_0074661179_class_python_python_turtle.txt |
Q:
Open and Parse Dynamic XFA (XML Form Architecture) PDF with Python
I would like to parse some text or any data from this pdf with Python. Everything I have tried is not working.
I have a tried a variety of approaches:
# importing required modules
import PyPDF2
# creating a pdf file object
pdfFileObj = open('exa... | Open and Parse Dynamic XFA (XML Form Architecture) PDF with Python | I would like to parse some text or any data from this pdf with Python. Everything I have tried is not working.
I have a tried a variety of approaches:
# importing required modules
import PyPDF2
# creating a pdf file object
pdfFileObj = open('example.pdf', 'rb')
# creating a pdf reader object
pdfReader = PyPDF2.Pd... | [
"Selenium webdriver could be used as an option if browser is capable of showing the PDF. Open PDF with browser and inspect it as an HTML page to figure out XPath of interesting elements.\nThis answer uses a publicly available XFA PDF.\nfrom selenium import webdriver\nimport os\nimport time\nfrom lxml import html\n\... | [
0,
0
] | [] | [] | [
"parsing",
"pdf",
"python",
"xml"
] | stackoverflow_0074647475_parsing_pdf_python_xml.txt |
Q:
programming challenge: how does this algorithm (tied to Number Theory) work?
In order to work on my python skills, I am sometimes doing various challenges on the internet (eg on hackerrank). Googling for something else, I found this problem, and the accompanying solution on the internet, and it caught my attention... | programming challenge: how does this algorithm (tied to Number Theory) work? | In order to work on my python skills, I am sometimes doing various challenges on the internet (eg on hackerrank). Googling for something else, I found this problem, and the accompanying solution on the internet, and it caught my attention:
The Grandest Staircase Of Them All
With her LAMBCHOP doomsday device finished, ... | [
"Regarding the answer function you posted:\nAt the end of each iteration of the outer loop, coefficients[x] is the number of staircases you can make with height at most i, having used a total of x blocks. (including staircases with only one stair or zero stairs).\ncoefficients is initialized to [1,0,0...] before t... | [
5,
2,
0,
0,
0
] | [] | [] | [
"algorithm",
"number_theory",
"python"
] | stackoverflow_0052654530_algorithm_number_theory_python.txt |
Q:
How to count comparisons in binary search
I have a simple program as such whch implements a binary search ussin g recursion
`
def binarySearch(array, p, left, right, count):
if right >= left:
m = left + (right - left)//2
if array[m] == p:
count+=1
return m
elif a... | How to count comparisons in binary search | I have a simple program as such whch implements a binary search ussin g recursion
`
def binarySearch(array, p, left, right, count):
if right >= left:
m = left + (right - left)//2
if array[m] == p:
count+=1
return m
elif array[m] > p:
count+=1
r... | [
"What gog means is:\ndef binarySearch(array, p, left, right, count):\n if right >= left:\n m = left + (right - left)//2\n if array[m] == p:\n count += 1\n return m, count\n elif array[m] > p:\n count += 1\n return binarySearch(array, p, left, m-1, ... | [
0
] | [] | [] | [
"python",
"search"
] | stackoverflow_0074666575_python_search.txt |
Q:
split pandas data frame into multiple of 4 rows
I have a dataset of 100 rows, I want to split them into multiple of 4 and then perform operations on it, i.e., first perform operation on first four rows, then on the next four rows and so on.
Note: Rows are independent of each other.
I don't know how to do it. Can s... | split pandas data frame into multiple of 4 rows | I have a dataset of 100 rows, I want to split them into multiple of 4 and then perform operations on it, i.e., first perform operation on first four rows, then on the next four rows and so on.
Note: Rows are independent of each other.
I don't know how to do it. Can somebody pls help me, I would be extremely thankful to... | [
"i will divide df per 2 row (simple example)\nand make list dfs\nExample\ndf = pd.DataFrame(list('ABCDE'), columns=['value'])\n\ndf\n value\n0 A\n1 B\n2 C\n3 D\n4 E\n\nCode\ngrouper for grouping\ngrouper = pd.Series(range(0, len(df))) // 2\n\ngrouper\n0 0\n1 0\n2 1\n3 1\n4 2\ndtype: int6... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074667114_dataframe_pandas_python.txt |
Q:
cleaning html tags from a variable
I'm trying to clean the html tags from a variable with this value:
<td><a class="css-zwebxb" href="/players/1093743350">Zero Two</a></td>, <td><time datetime="PT2M5.031S" time="1670072352910" title="Saturday, December 3, 2022 12:57 PM">00:02</time></td>, <td class="css-7a8yo0"> <... | cleaning html tags from a variable | I'm trying to clean the html tags from a variable with this value:
<td><a class="css-zwebxb" href="/players/1093743350">Zero Two</a></td>, <td><time datetime="PT2M5.031S" time="1670072352910" title="Saturday, December 3, 2022 12:57 PM">00:02</time></td>, <td class="css-7a8yo0"> <button class="css-sanbnz" type="button">... | [
"If you want only text from the HTML snippet you can use .text or .get_text():\nfrom bs4 import BeautifulSoup\n\nhtml_doc = \"\"\"<td><a class=\"css-zwebxb\" href=\"/players/1093743350\">Zero Two</a></td>, <td><time datetime=\"PT2M5.031S\" time=\"1670072352910\" title=\"Saturday, December 3, 2022 12:57 PM\">00:02</... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074667162_beautifulsoup_python.txt |
Q:
How to use a lambda function to sort a dictionary with a nested list?
I've been trying to sort a dictionary based on largest to lowest values. The dictionary is structured like this:
testing = {"third":[1,89],"first":[5,46],"second":[3,59]}
The issue I'm coming across is that I'm not entirely sure as to how I can... | How to use a lambda function to sort a dictionary with a nested list? | I've been trying to sort a dictionary based on largest to lowest values. The dictionary is structured like this:
testing = {"third":[1,89],"first":[5,46],"second":[3,59]}
The issue I'm coming across is that I'm not entirely sure as to how I can sort this based on the second listed value, so I want to sort it based on ... | [
"sorted(testing.items(), key=lambda x: x[1][1])?\noutput:\n[('first', [5, 46]), ('second', [3, 59]), ('third', [1, 89])]\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"function",
"python",
"sorting"
] | stackoverflow_0074667202_dictionary_function_python_sorting.txt |
Q:
Solving and plotting functions in Python
The proplem
I want to solve the above functions to plot xAxis vs yAxis for x between [0:2]. I started with the first function, "det", and used sympy library and the (solve, nsolve) methods to find the solution "yAxis for every xAxis" but I got an error that says "pop form a... | Solving and plotting functions in Python | The proplem
I want to solve the above functions to plot xAxis vs yAxis for x between [0:2]. I started with the first function, "det", and used sympy library and the (solve, nsolve) methods to find the solution "yAxis for every xAxis" but I got an error that says "pop form an empty set". I am not sure if I am using the ... | [
"This is actually a \"nice\" equation that can be plotted with plot_implicit. \"Nice\" because it is hard to plot, it pushes the algorithms to their limit in terms of capabilities and forces us to analyze what we are doing.\nI'm going to use the SymPy Plotting Backend module because it better deals with implicit pl... | [
0
] | [] | [] | [
"function",
"python",
"sympy"
] | stackoverflow_0074592862_function_python_sympy.txt |
Q:
python program troubleshoot
if the user enters a char it should show the wrong input and continue asking for input until it reaches the range of 10 elements. how to solve this? output
list = []
even = 0
for x in range(10):
number = int(input("Enter a number: "))
list.append(number)
for y in list:
if... | python program troubleshoot | if the user enters a char it should show the wrong input and continue asking for input until it reaches the range of 10 elements. how to solve this? output
list = []
even = 0
for x in range(10):
number = int(input("Enter a number: "))
list.append(number)
for y in list:
if y % 2 == 0:
even +=1
... | [
"myList = []\nwhile len(myList) < 10:\n try:\n number = int(input(\"Enter a number: \"))\n myList.append(number)\n except ValueError:\n print('Wrong value. Please enter a number.')\nprint(myList)\n\n",
"Hope code is self explanatory:\narr = []\neven = 0\nerror_flag = False\n\nfor x in r... | [
0,
0,
0
] | [] | [] | [
"do",
"list",
"python",
"while_loop"
] | stackoverflow_0074666821_do_list_python_while_loop.txt |
Q:
How can I find out which path os.path points to?
i am a web developer (php, js, css and ...).
i order a python script for remove image background. it worked in cmd very well but when running it from php script, it dosnt work.
i look at the script for find problem and i realized that the script stops at this line:
... | How can I find out which path os.path points to? | i am a web developer (php, js, css and ...).
i order a python script for remove image background. it worked in cmd very well but when running it from php script, it dosnt work.
i look at the script for find problem and i realized that the script stops at this line:
net.load_state_dict(self.torch.load(os.path.join("../l... | [
"The problem here is that the php script might be in different directory so while executing the python script via php script, the os.path points to the directory from where it is being executed i.e. the location of php script.\nTLDR; Try using absolute path.\n",
"This should be enough:\nname = 'name'\np = os.path... | [
0,
0
] | [] | [] | [
"os.path",
"python"
] | stackoverflow_0074667211_os.path_python.txt |
Q:
Why my second def inside the first def doesn't function?
I want to make a program that can check whether the entered number is a prime number in Jupyter Notebook. This is the code:
def input_number():
number = input()
if number.isnumeric():
the_number = int(number)
def check_prime():
... | Why my second def inside the first def doesn't function? | I want to make a program that can check whether the entered number is a prime number in Jupyter Notebook. This is the code:
def input_number():
number = input()
if number.isnumeric():
the_number = int(number)
def check_prime():
divisor = 1
divisor += 1
... | [
"You defined that function under input_number()\nYou can only use check_prime() under that function.\ndefine the check_prime() outside of input_number().\ndef input_number(): #input number func\n number = input() #take the number\n return int(number) if number.isnumeric() else print('Input only INT.') #return... | [
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074666624_jupyter_notebook_python.txt |
Q:
input. check if value is float if not go back to input until a float is written. I fail. "Can not convert string to float"
I have a school assignment where im making a budget calcylator. One of the demands are that the program checks if the input is a float, if not go back until a float is written. Im having a sup... | input. check if value is float if not go back to input until a float is written. I fail. "Can not convert string to float" | I have a school assignment where im making a budget calcylator. One of the demands are that the program checks if the input is a float, if not go back until a float is written. Im having a super hard time solving this. Ive been doing python one month so my skills are very limitied. Its hard to google on.
x = float(inpu... | [
"You could do something like this:\nwhile True:\n try:\n x = float(input('Enter a number: '))\n break\n except ValueError:\n print('Invalid input. Please try again.')\n\nThis code uses a while loop to continuously prompt the user for input until a valid float is entered. The try and excep... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074667280_python.txt |
Q:
python convert integer to bytes with bitwise operations
I have 2 inputs: i (the integer), length (how many bytes the integer should be encoded).
how can I convert integer to bytes only with bitwise operations.
def int_to_bytes(i, length):
for _ in range(length):
pass
A:
Without libraries (as specified in t... | python convert integer to bytes with bitwise operations | I have 2 inputs: i (the integer), length (how many bytes the integer should be encoded).
how can I convert integer to bytes only with bitwise operations.
def int_to_bytes(i, length):
for _ in range(length):
pass
| [
"Without libraries (as specified in the original post), use int.to_bytes.\n>>> (1234).to_bytes(16, \"little\")\nb'\\xd2\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n\nIOW, your function would be\ndef int_to_bytes(i, length):\n return i.to_bytes(length, \"little\")\n\n(or big, if y... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0074667168_python.txt |
Q:
How to find the length of the major axis and minor axis of an 2D object with an irregular shape?
I would like to find the length of the major axis and minor axis of a figure with an irregular shape like the figure below.
The way I thought of is to draw a rectangle fit around the object and find the length and wid... | How to find the length of the major axis and minor axis of an 2D object with an irregular shape? | I would like to find the length of the major axis and minor axis of a figure with an irregular shape like the figure below.
The way I thought of is to draw a rectangle fit around the object and find the length and width of the rectangle.
But I don't think this is a good idea.
The center of gravity of an object is give... | [
"One way to find the length of the major and minor axes of an irregularly shaped object is to use its bounding box. A bounding box is the smallest rectangle that encloses the entire object, and it can be found by determining the minimum and maximum values of the object's coordinates along each dimension.\nFor examp... | [
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0074666930_algorithm_python.txt |
Q:
Type hint Pandas DataFrameGroupBy
How should I type hint in Python a pandas DataFrameGroupBy object?
Should I just use pd.DataFrame as for normal pandas dataframes?
I didn't find any other solution atm
A:
DataFrameGroupBy is a proper type in of itself. So if you're writing a function which must specifically take... | Type hint Pandas DataFrameGroupBy | How should I type hint in Python a pandas DataFrameGroupBy object?
Should I just use pd.DataFrame as for normal pandas dataframes?
I didn't find any other solution atm
| [
"DataFrameGroupBy is a proper type in of itself. So if you're writing a function which must specifically take a DataFrameGroupBy instance:\nfrom pandas.core.groupby import DataFrameGroupBy\n\ndef my_function(dfgb: DataFrameGroupBy) -> None:\n \"\"\"Do something with dfgb.\"\"\"\n\nIf you're looking for a more ge... | [
7,
1
] | [] | [] | [
"pandas",
"python",
"type_hinting"
] | stackoverflow_0070501065_pandas_python_type_hinting.txt |
Q:
my .attrs function is not working in beautiful soup
I am a beginner programmer and I was trying to create my hangman game and importing data with Beautiful Soup but when I copied the same exact thing as the youtuber his code worked and mine didn't. I have tested and the problem is the .attrs function.
I have tried... | my .attrs function is not working in beautiful soup | I am a beginner programmer and I was trying to create my hangman game and importing data with Beautiful Soup but when I copied the same exact thing as the youtuber his code worked and mine didn't. I have tested and the problem is the .attrs function.
I have tried looking if I had made a typo but I am pretty sure I didn... | [
"you are getting the error because not all the items in the list soup.find_all('th') have tag a, and if you fix this, not all the items will have title , so try like this:\nsrc = result.content\nsoup = BeautifulSoup(src, 'lxml')\nresults = []\nfor i in soup.find_all('th'):\n if i.find('a'):\n a_tag = i.f... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074666526_beautifulsoup_python.txt |
Q:
formating file with hours and date in the same column
our electricity provider think it could be very fun to make difficult to read csv files they provide.
This is precise electric consumption, every 30 min but in the SAME column you have hours, and date, example :
[EDIT : here the raw version of the csv file, my ... | formating file with hours and date in the same column | our electricity provider think it could be very fun to make difficult to read csv files they provide.
This is precise electric consumption, every 30 min but in the SAME column you have hours, and date, example :
[EDIT : here the raw version of the csv file, my bad]
;
"Récapitulatif de mes puissances atteintes en W";
;
... | [
"Try:\nimport pandas as pd\n\ncurrent_date = None\nall_data = []\nwith open(\"your_file.txt\", \"r\") as f_in:\n # skip first 5 rows (header)\n for _ in range(5):\n next(f_in)\n\n for row in map(str.strip, f_in):\n row = row.replace('\"', \"\")\n if row == \"\":\n continue\n... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"parsing",
"python",
"reindex"
] | stackoverflow_0074667137_dataframe_pandas_parsing_python_reindex.txt |
Q:
How to run python coding in anaconda prompt using vba?
I am attempting to run python coding using vba.
However, when running using vba, it was not successful .
(i discovered that it is not running in anaconda prompt)
the code is attached as follow. appreciate the help.
Sub RunPythonScript()
Dim objShell As Object... | How to run python coding in anaconda prompt using vba? | I am attempting to run python coding using vba.
However, when running using vba, it was not successful .
(i discovered that it is not running in anaconda prompt)
the code is attached as follow. appreciate the help.
Sub RunPythonScript()
Dim objShell As Object
Dim PythonExePath As String, PythonScriptPath As String
Se... | [
"The code you provided looks like it is trying to run a Python script using the Wscript.Shell object in VBA, which is used to run external programs and scripts. However, this will not work for running a Python script in the Anaconda Prompt, as the Anaconda Prompt is a command-line interface (CLI) and not a script.\... | [
0,
0
] | [] | [] | [
"anaconda",
"python",
"vba"
] | stackoverflow_0074662928_anaconda_python_vba.txt |
Q:
Why does my second python async (scraping) function (which uses results from the first async (scraping) function) return no result?
Summary of what the program should do:
Step 1 (sync): Determine exactly how many pages need to be scraped.
Step 2 (sync): create the links to the pages to be scraped in a for-loop.
St... | Why does my second python async (scraping) function (which uses results from the first async (scraping) function) return no result? | Summary of what the program should do:
Step 1 (sync): Determine exactly how many pages need to be scraped.
Step 2 (sync): create the links to the pages to be scraped in a for-loop.
Step 3 (async): Use the link list from step 2 to get the links to the desired detail pages from each of these pages.
Step 4 (async): Use th... | [
"A working solution to the problem:\nadded\npython allow_redirects=True to python async with session_detailinfos.get(detail_link, allow_redirects=True) as res_d:\nadded python return_exceptions=True to python await asyncio.gather(*tasks_detail_infos, return_exceptions=True)\n"
] | [
0
] | [] | [] | [
"aiohttp",
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0074642424_aiohttp_python_python_3.x_python_asyncio.txt |
Q:
dataframe group by for all columns in new dataframe
I want to create a new dataframe with the values grouped by each column header dataset
this is the dataset i'm working with.
I essentially want a new dataframe which sums the occurences of 1 and 0 for each feature (chocolate, fruity etc)
i tried this code with th... | dataframe group by for all columns in new dataframe | I want to create a new dataframe with the values grouped by each column header dataset
this is the dataset i'm working with.
I essentially want a new dataframe which sums the occurences of 1 and 0 for each feature (chocolate, fruity etc)
i tried this code with the groupby and sort function
`
chocolate = data.groupby(["... | [
"You could try the following:\nres = (\n data\n .drop(columns=\"competitorname\")\n .melt().value_counts()\n .unstack()\n .fillna(0).astype(\"int\").T\n)\n\n\nEliminate the columns that aren't relevant (I've only seen competitorname, but there could be more).\n.melt the dataframe. The result has 2 co... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074665750_dataframe_pandas_python.txt |
Q:
What's the optimal implementation of a sliding window over a number's bits?
Given a number i.e (0xD5B8), what is the most efficient way in Python to subset across the bits over a sliding window using only native libraries?
A method might look like the following:
def window_bits(n,w, s):
'''
n: the number
... | What's the optimal implementation of a sliding window over a number's bits? | Given a number i.e (0xD5B8), what is the most efficient way in Python to subset across the bits over a sliding window using only native libraries?
A method might look like the following:
def window_bits(n,w, s):
'''
n: the number
w: the window size
s: step size
'''
# code
window_bits(0xD5B8, 4,... | [
"The \"naive\" option would be to create a bits array - bin(n)[2:] - and then use the answers from How to iterate over a list in chunks.\nBut this is most likely not so efficient assuming we can use bit operations. Another option is to shift-and-mask the input according to the window and step size:\ndef window_bits... | [
1,
0
] | [] | [] | [
"bit",
"bit_shift",
"python"
] | stackoverflow_0074641295_bit_bit_shift_python.txt |
Q:
Returning values from TextInputs in Kivy
does anyone know how to return the string of a textinput in a kivy widget? The textinput is created inside the kv.file.
<OrderScreen>:
BoxLayout:
TextInput:
size_hint: (.2, None)
pos_hint: {"center_y":0.5}
height: 30
width: 100
hi... | Returning values from TextInputs in Kivy | does anyone know how to return the string of a textinput in a kivy widget? The textinput is created inside the kv.file.
<OrderScreen>:
BoxLayout:
TextInput:
size_hint: (.2, None)
pos_hint: {"center_y":0.5}
height: 30
width: 100
hint_text: "Food"
multiline: False
... | [
"Yes, you can return the string of a TextInput widget in Kivy by using the text property of the TextInput widget. For example:\ntextinput = self.ids['my_textinput']\ntextinput_string = textinput.text\n\nHere is an example of a Kivy TextInput widget:\nTextInput:\n id: my_textinput\n multiline: False\n font_... | [
0
] | [] | [] | [
"kivy",
"python",
"textinput"
] | stackoverflow_0074667394_kivy_python_textinput.txt |
Q:
Get the week numbers between two dates with python
I'd like to find the most pythonic way to output a list of the week numbers between two dates.
For example:
input
start = datetime.date(2011, 12, 25)
end = datetime.date(2012, 1, 21)
output
find_weeks(start, end)
>> [201152, 201201, 201202, 201203]
I've been st... | Get the week numbers between two dates with python | I'd like to find the most pythonic way to output a list of the week numbers between two dates.
For example:
input
start = datetime.date(2011, 12, 25)
end = datetime.date(2012, 1, 21)
output
find_weeks(start, end)
>> [201152, 201201, 201202, 201203]
I've been struggling using the datetime library with little success
| [
"Something in the lines of (update: removed less-readable option)\nimport datetime\n\ndef find_weeks(start,end):\n l = []\n for i in range((end-start).days + 1):\n d = (start+datetime.timedelta(days=i)).isocalendar()[:2] # e.g. (2011, 52)\n yearweek = '{}{:02}'.format(*d) # e.g. \"201152\"\n ... | [
6,
3,
3,
0,
0
] | [] | [] | [
"datetime",
"python",
"rrule",
"timedelta"
] | stackoverflow_0048927466_datetime_python_rrule_timedelta.txt |
Q:
How to get n longest entries of DataFrame?
I'm trying to get the n longest entries of a dask DataFrame. I tried calling nlargest on a dask DataFrame with two columns like this:
import dask.dataframe as dd
df = dd.read_csv("opendns-random-domains.txt", header=None, names=['domain_name'])
df['domain_length'] = df.d... | How to get n longest entries of DataFrame? | I'm trying to get the n longest entries of a dask DataFrame. I tried calling nlargest on a dask DataFrame with two columns like this:
import dask.dataframe as dd
df = dd.read_csv("opendns-random-domains.txt", header=None, names=['domain_name'])
df['domain_length'] = df.domain_name.map(len)
print(df.head())
print(df.dt... | [
"I was helped by explicit type conversion:\ndf['column'].astype(str).astype(float).nlargest(5)\n\n",
"I tried to reproduce your problem but things worked fine. Can I recommend that you produce a Minimal Complete Verifiable Example?\nPandas example\nIn [1]: import pandas as pd\n\nIn [2]: df = pd.DataFrame({'x': [... | [
3,
0,
0,
0,
0
] | [] | [] | [
"dask",
"python"
] | stackoverflow_0038978432_dask_python.txt |
Q:
Split torch tensor : max size and end of the sentence
I would like to split a tensor into several tensors with torch on Python.
The tensor is the tokenization of a long text.
First here is what I had done:
tensor = tensor([[ 3746, 3120, 1024, ..., 2655, 24051, 2015]]) #size 14714
result = tensor.split(510)
... | Split torch tensor : max size and end of the sentence | I would like to split a tensor into several tensors with torch on Python.
The tensor is the tokenization of a long text.
First here is what I had done:
tensor = tensor([[ 3746, 3120, 1024, ..., 2655, 24051, 2015]]) #size 14714
result = tensor.split(510)
It works but now I would like to refine this, and make it s... | [
"i tried it out a solution but its not straightforward but does the trick\noo and you might want to install this library more_itertools, used this to do the split\nfrom transformers import BertTokenizerFast\nimport typer\nimport torch\n\nfrom pathlib import Path\nfrom typing import List\nfrom more_itertools import ... | [
0,
0
] | [] | [] | [
"nlp",
"python",
"pytorch",
"tensor",
"torch"
] | stackoverflow_0074488479_nlp_python_pytorch_tensor_torch.txt |
Q:
How to interact with a turtle when it is invisible?
I have been creating a game with turtle and I was going to make a the background change when a certain area is clicked. So I used a turtle and used the onclick() method when I realized that it did not look good with the background so I tried to use the hideturtle... | How to interact with a turtle when it is invisible? | I have been creating a game with turtle and I was going to make a the background change when a certain area is clicked. So I used a turtle and used the onclick() method when I realized that it did not look good with the background so I tried to use the hideturtle() method to hide it. But when I hid the turtle the click... | [
"Passed your question to ChatGpt, that's his answer :) :\n\nIt sounds like you're running into a problem where the turtle becomes\nunresponsive to clicks after you hide it. This is likely because the\nturtle's clickable area is also hidden when you hide the turtle.\nOne solution to this problem would be to create a... | [
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074667472_python_python_turtle_turtle_graphics.txt |
Q:
how to convert 5 digits number to date in python
I would like to convert 44562 int64 data type (5 digits number) to date format like this 1/1/2022.
Out[5]:
0 44562
1 44562
2 44563
3 44563
4 44564
Name: Date, dtype: int64
I try with
df['Date'].apply(lambda x: (datetime.utcfromtimestamp(0) + timedel... | how to convert 5 digits number to date in python | I would like to convert 44562 int64 data type (5 digits number) to date format like this 1/1/2022.
Out[5]:
0 44562
1 44562
2 44563
3 44563
4 44564
Name: Date, dtype: int64
I try with
df['Date'].apply(lambda x: (datetime.utcfromtimestamp(0) + timedelta(int(x))).strftime("%m-%d-%Y"))
but output date is... | [
"You very nearly had it:\ndf['Date'].apply(lambda x: (datetime(1899, 12, 30) + timedelta(days=int(x))).strftime(\"%m/%d/%Y\"))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074667378_python.txt |
Q:
Solving large-scale nonlinear system using exact Newton's method in SciPy
I am trying to solve a large-scale nonlinear system using the exact Newton method in SciPy. In my application, the Jacobian is easy to assemble (and factorize) as a sparse matrix.
It seems that all methods available in scipy.optimize.root ap... | Solving large-scale nonlinear system using exact Newton's method in SciPy | I am trying to solve a large-scale nonlinear system using the exact Newton method in SciPy. In my application, the Jacobian is easy to assemble (and factorize) as a sparse matrix.
It seems that all methods available in scipy.optimize.root approximate the Jacobian in one way or another, and I can't find a way to use New... | [
"It is meant to be used.\nScipy's private functions that are not meant to be used from the outside start with a _.\nThis was confirmed by the scipy's team in an issue I raised recently: cf https://github.com/scipy/scipy/issues/17510\n"
] | [
0
] | [] | [] | [
"optimization",
"python",
"scipy"
] | stackoverflow_0068297903_optimization_python_scipy.txt |
Q:
python issue while importing a module from a file
the below is my main_call.py file
from flask import Flask, jsonify, request
from test_invoke.invoke import end_invoke
from config import config
app = Flask(__name__)
@app.route("/get/posts", methods=["GET"])
def load_data():
res = "True"
... | python issue while importing a module from a file | the below is my main_call.py file
from flask import Flask, jsonify, request
from test_invoke.invoke import end_invoke
from config import config
app = Flask(__name__)
@app.route("/get/posts", methods=["GET"])
def load_data():
res = "True"
# setting a Host url
host_url = config(... | [
"Python looks for packages and modules in its Python path. It searches (in that order):\n\nthe current directory (which may not be the path of the current Python module...)\nthe content of the PYTHONPATH environment variable\nvarious (implementation and system dependant) system paths\n\nAs test_invoke is indeed a p... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074667350_python.txt |
Q:
Fix dates to correct format as days and months interchanged in certain rows
I have a dataset that has a date column and it is interchanging days and months in certain rows after importing the dataset. Can someone pls help me find a fix to this?
Correct data:
First Name
Last Name
... | Fix dates to correct format as days and months interchanged in certain rows | I have a dataset that has a date column and it is interchanging days and months in certain rows after importing the dataset. Can someone pls help me find a fix to this?
Correct data:
First Name
Last Name
Date
Start time
Duration
DetectedArtif... | [
"I assume you're reading data from an excel file, right? And in excel the cells are represented by text, because otherwise it would have been read automatically without a problem. You should have something like this:\nprint(df.Date)\n\nOutput:\n0 02-02-2022\n1 02-09-2022\n2 02-09-2022\n3 03-09-2022\n4 ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074667320_dataframe_pandas_python.txt |
Q:
Don't understand this ConfigParser.InterpolationSyntaxError
So I have tried to write a small config file for my script, which should specify an IP address, a port and a URL which should be created via interpolation using the former two variables. My config.ini looks like this:
[Client]
recv_url : http://%(recv_hos... | Don't understand this ConfigParser.InterpolationSyntaxError | So I have tried to write a small config file for my script, which should specify an IP address, a port and a URL which should be created via interpolation using the former two variables. My config.ini looks like this:
[Client]
recv_url : http://%(recv_host):%(recv_port)/rpm_list/api/
recv_host = 172.28.128.5
recv_port ... | [
"There was indeed a mistake in my config.ini file. I did not regard the s at the end of %(...)s as a necessary syntax element. I suppose it refers to \"string\" but I couldn't really confirm this.\n",
"My .ini file for starting the Python Pyramid server had a similar problem.\nAnd to use the variable from the .en... | [
16,
0
] | [] | [] | [
"configparser",
"python",
"string_interpolation"
] | stackoverflow_0044156665_configparser_python_string_interpolation.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.