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:
Get non-float values from specific column in pandas dataframe
I want to get in a new dataframe the rows of an original dataframe where there is a non-real (i.e. string) value in a specific column.
import pandas as pd
import numpy as np
test = {'a':[1,2,3],
'b':[4,5,'x'],
'c':['f','g','h']}
df_test ... | Get non-float values from specific column in pandas dataframe | I want to get in a new dataframe the rows of an original dataframe where there is a non-real (i.e. string) value in a specific column.
import pandas as pd
import numpy as np
test = {'a':[1,2,3],
'b':[4,5,'x'],
'c':['f','g','h']}
df_test = pd.DataFrame(test)
print(df_test)
I want to get the third row wh... | [
"The complication is that Pandas forces column elements to have the same type (object for mixed str and int) so simple selection is not possible. Hence I think it is necessary to iterate over the column of interest to select the row(s) and then extract that/those.\nmask = []\nfor j in df_test['b']:\n if isinstan... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074658386_dataframe_pandas_python.txt |
Q:
Django LoginView can not authenticate the user
I have a LoginView and a registration form. this registration form is working properly, users are flying to the database, but LoginView gives an incorrect login or password when trying to log in, although all the data is correct, why can this be?
CustomUser from model... | Django LoginView can not authenticate the user | I have a LoginView and a registration form. this registration form is working properly, users are flying to the database, but LoginView gives an incorrect login or password when trying to log in, although all the data is correct, why can this be?
CustomUser from models.py
class CustomUser(AbstractUser):
objects = U... | [
"Did you check that password are correctly hashed after the registration?\nIf you are not using the forms in django.contrib.auth you need to manually create and verify password:\nSee\n\nhttps://docs.djangoproject.com/en/4.1/topics/auth/default/\nhttps://docs.djangoproject.com/en/4.1/topics/auth/passwords/#module-dj... | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"python",
"python_3.x"
] | stackoverflow_0074659278_django_django_models_django_rest_framework_python_python_3.x.txt |
Q:
Using ray tune `tune.run` with pytorch returns different optimal hyperparameters combination
I've initialized two identical ANN with PyTorch (both as structure and initial parameters), and I've noticed that the hyperparameters setting with Ray Tune, returns different results for the two ANN, even if I didn't have ... | Using ray tune `tune.run` with pytorch returns different optimal hyperparameters combination | I've initialized two identical ANN with PyTorch (both as structure and initial parameters), and I've noticed that the hyperparameters setting with Ray Tune, returns different results for the two ANN, even if I didn't have any random initialization.
Someone could explain what I'm doing wrong? I'll attach the code:
ANN ... | [
"The issue is the use of torch.random under the hood. Since you are not directly providing a weight matrix for your layers, pytorch initializes it for you. Luckily, you can have a reproducible experiment by setting\ntorch.manual_seed(x) # where x is an integer\n\nOne should use only a few random seeds, otherwise yo... | [
0
] | [] | [] | [
"deep_learning",
"hyperparameters",
"python",
"pytorch",
"ray_tune"
] | stackoverflow_0074656124_deep_learning_hyperparameters_python_pytorch_ray_tune.txt |
Q:
How do I remove an item from an array based on the difference between two items
I'm trying to remove outliers from a dataset, where an outlier is if the difference between one item and the next one is larger than 3 * the uncertainty on the item
def remove_outliers(data):
for i in data:
x = np.where(abs... | How do I remove an item from an array based on the difference between two items | I'm trying to remove outliers from a dataset, where an outlier is if the difference between one item and the next one is larger than 3 * the uncertainty on the item
def remove_outliers(data):
for i in data:
x = np.where(abs(i[1] - (i+1)[1]) > 3( * data[:,2]))
data_outliers_removed = np.delete(data,... | [
"i would maybe do something like this by working with a new empty array.\ndef remove_outliers(dataset):\nfiltered_dataset = []\nfor index, item in enumerate(dataset):\n if index == 0:\n filtered_dataset.append(item)\n else:\n if abs(item[0] - dataset[index - 1][0]) <= 3 * dataset[index - 1][1]:\... | [
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074656777_arrays_numpy_python.txt |
Q:
Why won't my square move right? I'm trying all different methods to move it in turtle module it works for up and down but not left and right?
# Game creation
import turtle
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("Black")
wn.setup(width=800, height=800)
wn.tracer(0)
# paddle a
paddle_a = turtle.Turtle()... | Why won't my square move right? I'm trying all different methods to move it in turtle module it works for up and down but not left and right? | # Game creation
import turtle
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("Black")
wn.setup(width=800, height=800)
wn.tracer(0)
# paddle a
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.penup()
paddle_a.goto(0, 0)
# Functions
def paddle_a_right():
... | [
"There are three major issues with your code. First, you need to call wn.listen() to allow the window to receive keyboard input. Second, you do turtle.forward(100) when you mean paddle_a.forward(100). Finally, since you did tracer(0), you now need to call wn.update() anytime a change is made that you want your u... | [
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074649562_python_python_turtle_turtle_graphics.txt |
Q:
Discord.py Showing User Badges
I am trying to do a command that shows a user's badges. This is my code:
@bot.command(pass_context=True)
async def test(ctx, user: discord.Member):
test = discord.Embed(title=f"{user.name} User's Badges", description=f"{user.public_flags}", color=0xff0000 )
await ctx.... | Discord.py Showing User Badges | I am trying to do a command that shows a user's badges. This is my code:
@bot.command(pass_context=True)
async def test(ctx, user: discord.Member):
test = discord.Embed(title=f"{user.name} User's Badges", description=f"{user.public_flags}", color=0xff0000 )
await ctx.channel.send(embed=test)
And the bo... | [
"You could do str(user.public_flags.all()) to obtain a string value of all the badges an user has. Although this is an improvement, your output will still be something like: [<UserFlags.hypesquad_brilliance: 128>]. But the advantage here is that the words hypesquad and brilliance are clearly indicated in the string... | [
1,
0,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0066951118_discord_discord.py_python.txt |
Q:
Highlighting multiple hex_tiles by hovering in bokeh
I try to visualize my data in a hex map. For this I use python bokeh and the corresponding hex_tile function in the figure class. My data belongs to one of 8 different classes, each having a different color. The image below shows the current visualization:
I wo... | Highlighting multiple hex_tiles by hovering in bokeh | I try to visualize my data in a hex map. For this I use python bokeh and the corresponding hex_tile function in the figure class. My data belongs to one of 8 different classes, each having a different color. The image below shows the current visualization:
I would like to add the possibility to change the color of the... | [
"Following the discussion from previous post here comes the solution targeted for the OP code (Bokeh v1.1.0). What I did is:\n1) Added a HoverTool\n2) Added a JS callback to the HoverTool which:\n\nResets the hex colors to the original ones (colors_array passed in the callback)\nInspects the index of currently hove... | [
7,
2,
0
] | [] | [] | [
"bokeh",
"python"
] | stackoverflow_0055947149_bokeh_python.txt |
Q:
setuptools pyproject.toml equivalent to `python setup.py clean --all`
I'm migrating from setup.py to pyproject.toml. The commands to install my package appear to be the same, but I can't find what the pyproject.toml command for cleaning up build artifacts is. What is the equivalent to python setup.py clean --all?
... | setuptools pyproject.toml equivalent to `python setup.py clean --all` | I'm migrating from setup.py to pyproject.toml. The commands to install my package appear to be the same, but I can't find what the pyproject.toml command for cleaning up build artifacts is. What is the equivalent to python setup.py clean --all?
| [
"The distutils command clean is not needed for a pyproject.toml based build. Modern tools invoking PEP517/PEP518 hooks, such as build, create a temporary directory or a cache directory to store intermediate files while building, rather than littering the project directory with a build subdirectory.\nAnyway, it was ... | [
4,
1
] | [] | [] | [
"pyproject.toml",
"python",
"setuptools"
] | stackoverflow_0072468946_pyproject.toml_python_setuptools.txt |
Q:
imaplib STORE failed - Mailbox has read-only access. Cannot Delete Yahoo Email
trying to delete emails in my yahoo account using imaplib. i'm new to python, figured out most of the code but unable to find anything that works relating to this error.
imap = imaplib.IMAP4_SSL(imap_server)
imap.login(email_address, pa... | imaplib STORE failed - Mailbox has read-only access. Cannot Delete Yahoo Email | trying to delete emails in my yahoo account using imaplib. i'm new to python, figured out most of the code but unable to find anything that works relating to this error.
imap = imaplib.IMAP4_SSL(imap_server)
imap.login(email_address, password)
imap.select("Learn", readonly=False)
con = imaplib.IMAP4_SSL('imap.mail.yah... | [
"imap.select('\"Learn\"', \"(UNSEEN)\")\n\nSelect does not take a search criterion. The second parameter is “readonly”, so this is the same as:\nimap.select('\"Learn\"', readonly=\"(UNSEEN)\")\n\nWhich as a non-empty string is the same as:\nimap.select('\"Learn\"', readonly=True)\n\nWhich is why you can’t make any ... | [
0
] | [] | [] | [
"email",
"imap",
"imaplib",
"python"
] | stackoverflow_0074650452_email_imap_imaplib_python.txt |
Q:
CondaError: Downloaded bytes did not match Content-Length while trying to download cudnn using conda
This is the error I'm having in the anaconda prompt, after executing the command: conda install cudnn==7.6.5
Error:
CondaError: Downloaded bytes did not match Content-Length
url: https://repo.anaconda.com/pkgs/ma... | CondaError: Downloaded bytes did not match Content-Length while trying to download cudnn using conda | This is the error I'm having in the anaconda prompt, after executing the command: conda install cudnn==7.6.5
Error:
CondaError: Downloaded bytes did not match Content-Length
url: https://repo.anaconda.com/pkgs/main/win-64/cudnn-7.6.5-cuda10.1_0.conda
target_path: C:\Users\User\anaconda3\pkgs\cudnn-7.6.5-cuda10.1_0.... | [
"\nusing curl download package\nconda install --offline your_download_package\n\n",
"try go to target_path and uninstall cudnn or just install cudnn in it. It works for me when i install cudatoolkit.\n"
] | [
0,
0
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0065130985_anaconda_python.txt |
Q:
matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y-
When I set up an equal aspect ratio for a 3d graph, the z-axis does not change to 'equal'. So this:
fig = pylab.figure()
mesFig = fig.gca(projection='3d', adjustable='box')
mesFig.axis('equal')
mesFig.plot(xC, yC, zC, 'r.')
... | matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y- | When I set up an equal aspect ratio for a 3d graph, the z-axis does not change to 'equal'. So this:
fig = pylab.figure()
mesFig = fig.gca(projection='3d', adjustable='box')
mesFig.axis('equal')
mesFig.plot(xC, yC, zC, 'r.')
mesFig.plot(xO, yO, zO, 'b.')
pyplot.show()
Gives me the following:
Where obviously the unit l... | [
"I like the above solutions, but they do have the drawback that you need to keep track of the ranges and means over all your data. This could be cumbersome if you have multiple data sets that will be plotted together. To fix this, I made use of the ax.get_[xyz]lim3d() methods and put the whole thing into a standa... | [
85,
79,
58,
57,
25,
23,
7,
2,
1,
0
] | [] | [] | [
"aspect_ratio",
"axis",
"graph",
"matplotlib",
"python"
] | stackoverflow_0013685386_aspect_ratio_axis_graph_matplotlib_python.txt |
Q:
Updated StatsForecast Library shows error 'forecasts' is not defined in Python
I was trying to replicate this code for stat forecasting in python, I came across an odd error "name 'forecasts' is not defined" which is quite strange as I was able to replicate the code without any errors before.
I believe this was re... | Updated StatsForecast Library shows error 'forecasts' is not defined in Python | I was trying to replicate this code for stat forecasting in python, I came across an odd error "name 'forecasts' is not defined" which is quite strange as I was able to replicate the code without any errors before.
I believe this was resolved in the latest update of this library StatsForecast but I still run across to ... | [
"You have to instantiate the models since they are classes.\nThe code would be,\nfrom statsforecast import StatsForecast\n\nfrom statsforecast.models import CrostonClassic, CrostonSBA, CrostonOptimized, ADIDA, IMAPA, TSB\nfrom statsforecast.models import SimpleExponentialSmoothing, SimpleExponentialSmoothingOptimiz... | [
0
] | [] | [] | [
"forecasting",
"python",
"python_3.x",
"time_series"
] | stackoverflow_0074657616_forecasting_python_python_3.x_time_series.txt |
Q:
Python monkeypatch.setattr() with pytest fixture at module scope
First of all, the relevant portion of my project directory looks like:
└── my_package
├── my_subpackage
│ ├── my_module.py
| └── other_module.py
└── tests
└── my_subpackage
└── unit_test.py
I am writing some t... | Python monkeypatch.setattr() with pytest fixture at module scope | First of all, the relevant portion of my project directory looks like:
└── my_package
├── my_subpackage
│ ├── my_module.py
| └── other_module.py
└── tests
└── my_subpackage
└── unit_test.py
I am writing some tests in unit_test.py that require mocking of an external resource at t... | [
"I found this issue which guided the way. I needed to make a few changes to the solution for module level scope. unit_test.py now looks like this:\nimport unittest.mock as mock\n\nimport pytest\n\nfrom my_package.my_subpackage.my_module import MyClass\n\n\n@pytest.fixture(scope='module')\ndef monkeymodule():\n f... | [
17,
0
] | [] | [] | [
"fixtures",
"pytest",
"python",
"scope"
] | stackoverflow_0053963822_fixtures_pytest_python_scope.txt |
Q:
How do I implement recursion to this python program
def recurse( aList ):
matches = [ match for match in action if "A" in match ]
uses = " ".join(matches)
return f"Answer: { aList.index( uses )"
This is the non recursive method. I just couldn't figure out how to implement recursion in regards of lists... | How do I implement recursion to this python program | def recurse( aList ):
matches = [ match for match in action if "A" in match ]
uses = " ".join(matches)
return f"Answer: { aList.index( uses )"
This is the non recursive method. I just couldn't figure out how to implement recursion in regards of lists.
Output should be Answer: n uses.
Can anybody help.
| [
"Recursion is a bad fit for this problem in Python, because lists aren' really recursive data structures. But you could write the following:\ndef recurse(aList):\n if not aList:\n return 0\n return (\"A\" in aList[0]) + recurse(aList[1:])\n\nNothing in an empty list, by definition, contains \"A\". Otherwi... | [
1
] | [] | [] | [
"list",
"python",
"python_3.x",
"recursion"
] | stackoverflow_0074659546_list_python_python_3.x_recursion.txt |
Q:
Cant properly orginize self method in a class TypeError:create_bool(): incompatible function arguments. The following argument types are supported:
Return Error when Im tried to make a class.
When I tried as here https://github.com/google/mediapipe/blob/master/docs/solutions/face_mesh.md#python-solution-api. evere... | Cant properly orginize self method in a class TypeError:create_bool(): incompatible function arguments. The following argument types are supported: | Return Error when Im tried to make a class.
When I tried as here https://github.com/google/mediapipe/blob/master/docs/solutions/face_mesh.md#python-solution-api. everething is perfect
There are some problem with self. method. But I could not undestand where exactly
import cv2
import mediapipe as mp
import time
class F... | [
"You have a parameter in the wrong place.\nUse named parameters or add a value for \"refine_landmarks\".\nSee signature of FaceMesh:\ndef __init__(self,\n static_image_mode=False,\n max_num_faces=1,\n refine_landmarks=False,\n min_detection_confidence=0.5,\n ... | [
0,
0
] | [] | [] | [
"mediapipe",
"python",
"self"
] | stackoverflow_0074658820_mediapipe_python_self.txt |
Q:
ImportError with tkinter
So I found tutorial about work with GUI in python tkinter
then I try to learn it from w3school, I copied the sample code:
from tkinter import *
from tkinter .ttk import *
root = Tk()
label = Label(root, text="Hello world Tkinket GUI Example ")
label.pack()
root.mainloop() ... | ImportError with tkinter | So I found tutorial about work with GUI in python tkinter
then I try to learn it from w3school, I copied the sample code:
from tkinter import *
from tkinter .ttk import *
root = Tk()
label = Label(root, text="Hello world Tkinket GUI Example ")
label.pack()
root.mainloop()
So, I google how to install ... | [
"Generally what you want is\nimport tkinter as tk # 'as tk' isn't required, but it's common practice\nfrom tkinter import ttk # though you aren't using any ttk widgets at the moment...\n\nI know star imports have a certain appeal, but they can lead to namespace pollution which is a huge headache!\nFor example let... | [
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074659714_python_python_3.x_tkinter.txt |
Q:
Index Enumeration doesn't seem to be operating properly. Where am I messing up?
I'm trying to figure out how to enumerate an index properly into specified cells on an Excel spreadsheet using Python. Following a tutorial video, I thought I had it figured out, but it doesn't seem to be pulling each index value and p... | Index Enumeration doesn't seem to be operating properly. Where am I messing up? | I'm trying to figure out how to enumerate an index properly into specified cells on an Excel spreadsheet using Python. Following a tutorial video, I thought I had it figured out, but it doesn't seem to be pulling each index value and parsing it to each individual cell as intended. Instead, it's taking only the first en... | [
"Unfortunately, this manner of accessing a range of cells is always a bit clumsy. If you look at what accessing the range returns:\n>>> ws['A2':'A4']\n((<Cell 'Systems'.A2>,), (<Cell 'Systems'.A3>,), (<Cell 'Systems'.A4>,))\n\nit's a tuple of tuples, where each inner tuple is a single cell. So, in your for loop, wh... | [
0
] | [] | [] | [
"enumeration",
"excel",
"indexing",
"openpyxl",
"python"
] | stackoverflow_0074659526_enumeration_excel_indexing_openpyxl_python.txt |
Q:
How to save XGBoost/LightGBM model to PostgreSQL database in Python for subsequent inference in Java?
I'm restricted to a PostgreSQL as 'model storage' for the models itself or respective components (coefficients, ..). Obviously, PostgreSQL is far from being a fully-fledged model storage, so I can't rule out that ... | How to save XGBoost/LightGBM model to PostgreSQL database in Python for subsequent inference in Java? | I'm restricted to a PostgreSQL as 'model storage' for the models itself or respective components (coefficients, ..). Obviously, PostgreSQL is far from being a fully-fledged model storage, so I can't rule out that I have to implement the whole model training process in Java [...].
I couldn't find a solution that involve... | [
"Using PostgreSQL as dummy model storage:\n\nTrain a model in Python.\nEstablish PostgreSQL connection, dump your model in Pickle data format to the \"models\" table. Obviously, the data type of the main column should be BLOB.\nAnytime you want to use the model for some application, unpickle it from the \"models\" ... | [
0
] | [] | [] | [
"java",
"lightgbm",
"machine_learning",
"python",
"xgboost"
] | stackoverflow_0074656521_java_lightgbm_machine_learning_python_xgboost.txt |
Q:
Solve a math operation in a string without using the eval function(python)
Solve a math operation in a string based on operation priority without using the eval function
for example (3*(72/2)+2-1(32%2))
should solve this without using eval
I couldn't make the parenthetical operation priority
A:
No need to rei... | Solve a math operation in a string without using the eval function(python) | Solve a math operation in a string based on operation priority without using the eval function
for example (3*(72/2)+2-1(32%2))
should solve this without using eval
I couldn't make the parenthetical operation priority
| [
"No need to reinvent the wheel, there is a very straightforward way to do this by using the PCPP package, which is a C/C++ preprocessor for Python:\nfrom pcpp import Evaluator\n\neval = Evaluator()\nresult = eval(\"(3*(72/2)+2-(32%2))\")\nprint(result.value())\n\nNote that for this case I had to manually remove the... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074659443_python.txt |
Q:
How to convert numpy.ndarray image to discord.File?
I found similar question but about PIL: How can I upload a PIL Image object to a Discord chat without saving the image?, and using it results in
AttributeError: 'numpy.ndarray' object has no attribute 'save'
which is surely because I use OpenCV and not PIL.
The q... | How to convert numpy.ndarray image to discord.File? | I found similar question but about PIL: How can I upload a PIL Image object to a Discord chat without saving the image?, and using it results in
AttributeError: 'numpy.ndarray' object has no attribute 'save'
which is surely because I use OpenCV and not PIL.
The question is how to convert this numpy.ndarray to discord.F... | [
"In case anybody also get this problem here is function that takes cv2 image(which is basically numpy.ndarray) and returns discord.File:\ndef cv2discordfile(img):\n img_encode = cv2.imencode('.png', img)[1]\n data_encode = np.array(img_encode)\n byte_encode = data_encode.tobytes()\n byteImage = BytesIO(... | [
0
] | [] | [] | [
"discord.py",
"numpy_ndarray",
"python"
] | stackoverflow_0074657948_discord.py_numpy_ndarray_python.txt |
Q:
How to optimize hyper-parameters of a PPO for a gym environment training
I would like to use an optimization algorithm (hyperOptSearch) using ray.tune .
On the official documentation, they use this syntax :
tuner = tune.Tuner(
objective,
tune_config=tune.TuneConfig(
metric="mean_loss",
mode... | How to optimize hyper-parameters of a PPO for a gym environment training | I would like to use an optimization algorithm (hyperOptSearch) using ray.tune .
On the official documentation, they use this syntax :
tuner = tune.Tuner(
objective,
tune_config=tune.TuneConfig(
metric="mean_loss",
mode="min",
search_alg=algo,
num_samples=num_samples,
),
p... | [
"You need to modify your config to make use of Tune search space distributions (https://docs.ray.io/en/latest/tune/tutorials/tune-search-spaces.html), which will let you specify lower and upper bounds for possible values in your search space. Without them (as it is in your case), you will only have constant values ... | [
0
] | [] | [] | [
"hyperparameters",
"openai_gym",
"python",
"ray",
"reinforcement_learning"
] | stackoverflow_0074635036_hyperparameters_openai_gym_python_ray_reinforcement_learning.txt |
Q:
(Stochastic) Gradient Descent implementation in Python
I am trying to do (preferably Stochastic) Gradient Descent to minimize a custom loss function. I tried using scikit learn SGDRegressor class. However, SGDRegressor doesn't seem to allow me to minimize a custom loss function without data, and if I can use custo... | (Stochastic) Gradient Descent implementation in Python | I am trying to do (preferably Stochastic) Gradient Descent to minimize a custom loss function. I tried using scikit learn SGDRegressor class. However, SGDRegressor doesn't seem to allow me to minimize a custom loss function without data, and if I can use custom loss function, I can only use it as regression to fit data... | [
"Implementation of Basic Gradient Descent\nNow that you know how the basic gradient descent works, you can implement it in Python. You’ll use only plain Python and NumPy, which enables you to write concise code when working with arrays (or vectors) and gain a performance boost.\nThis is a basic implementation of th... | [
1,
0
] | [] | [] | [
"gradient_descent",
"keras",
"python",
"scikit_learn",
"tensorflow"
] | stackoverflow_0074631492_gradient_descent_keras_python_scikit_learn_tensorflow.txt |
Q:
function that takes two parameters of string type which are fractions with the same denominator and returns a sum expression and the sum result
For example:
>>> a_b = '1/3'
>>> c_b = '5/3'
>>> get_fractions(a_b, c_b)
'1/3 + 5/3 = 6/3'`
I'm trying to solve this but it won't work:
def get_fractions(a_b: str, c_b: s... | function that takes two parameters of string type which are fractions with the same denominator and returns a sum expression and the sum result | For example:
>>> a_b = '1/3'
>>> c_b = '5/3'
>>> get_fractions(a_b, c_b)
'1/3 + 5/3 = 6/3'`
I'm trying to solve this but it won't work:
def get_fractions(a_b: str, c_b: str) -> str:
calculate = int(a_b) + int(c_b)
return calculate
| [
"First you will have to get the nominator and denominator for each argument. After that you convert the nominator of each argument from string to integer and add them. Then lastly convert the sum of nominators to str and concatenate it with '/' and any of the argument denominator.\ndef get_fractions(a_b: str, c_b: ... | [
1,
0
] | [] | [] | [
"fractions",
"integer",
"python",
"python_3.x",
"string"
] | stackoverflow_0074235217_fractions_integer_python_python_3.x_string.txt |
Q:
Create multiple objects in one form Django
I am trying to create a form in Django that can create one Student object with two Contact objects in the same form. The second Contact object must be optional to fill in (not required).
Schematic view of the objects created in the single form:
Contact 1
Student... | Create multiple objects in one form Django | I am trying to create a form in Django that can create one Student object with two Contact objects in the same form. The second Contact object must be optional to fill in (not required).
Schematic view of the objects created in the single form:
Contact 1
Student <
Contact 2 (not required)
I have th... | [
"What I'd try:\nI don't understand your StudentSignUpForm magic. However, if it's effectively the same as a ModelForm:\nclass StudentSignUpForm(forms.Modelform):\n class Meta:\n model = Student\n fields = ('first_name', 'last_name', ...)\n\nthen just add non-model fields\n contact1_first_name ... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"formset",
"python"
] | stackoverflow_0074655177_django_django_forms_django_models_formset_python.txt |
Q:
__init__.py issue in django test
I have an issue with running a test in my Django project, using the command python manage.py test. It shows:
user:~/workspace/connector$ docker-compose run --rm app sh -c "python manage.py test"
Creating connector_app_run ... done
Found 0 test(s).
System check identified no issues ... | __init__.py issue in django test | I have an issue with running a test in my Django project, using the command python manage.py test. It shows:
user:~/workspace/connector$ docker-compose run --rm app sh -c "python manage.py test"
Creating connector_app_run ... done
Found 0 test(s).
System check identified no issues (0 silenced).
-----------------------... | [
"So as per your project file structure, I changed from app.app import secrets to from app import secrets and then found test cases are also failing, so I fixed them also, you can review the changes here:\nhttps://github.com/MrHarvvey/connector/pull/1\nPlease let me know you if you wanted something else.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074658535_django_python.txt |
Q:
Select dropdown option with Selenium (Python)
I'm kinda new at Selenium, so a proposed myself a project. I'm trying to get as much information as I can from this URL https://statusinvest.com.br/acoes/proventos/ibovespa
Until that time I was able to do everything, EXCEPT change the default option at the "Filtro por... | Select dropdown option with Selenium (Python) | I'm kinda new at Selenium, so a proposed myself a project. I'm trying to get as much information as I can from this URL https://statusinvest.com.br/acoes/proventos/ibovespa
Until that time I was able to do everything, EXCEPT change the default option at the "Filtro por Índice". I would like to change it from "Ibovespa"... | [
"So a very simple way to change the input option would be to do:\nfrom selenium.webdriver.common.by import By\n\nselect_obj = driver.find_element(By.CLASS_NAME, 'select-wrapper') # object that contains all of the elements for first input selector\nselect_obj.find_element(By.TAG_NAME, 'input').click() # click the in... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074659548_python_selenium.txt |
Q:
How to convert python list to JSON array?
If I have python list like
pyList=[‘x@x.x’,’y@y.y’]
And I want it to convert it to json array and add {} around every object, it should be like that :
arrayJson=[{“email”:”x@x.x”},{“ email”:”y@y.y”}]
any idea how to do that ?
A:
You can achieve this by using built-in j... | How to convert python list to JSON array? | If I have python list like
pyList=[‘x@x.x’,’y@y.y’]
And I want it to convert it to json array and add {} around every object, it should be like that :
arrayJson=[{“email”:”x@x.x”},{“ email”:”y@y.y”}]
any idea how to do that ?
| [
"You can achieve this by using built-in json module\nimport json\n\narrayJson = json.dumps([{\"email\": item} for item in pyList])\n\n",
"Try to Google this kind of stuff first. :)\nimport json\n\narray = [1, 2, 3]\njsonArray = json.dumps(array)\n\nBy the way, the result you asked for can not be achieved with the... | [
2,
0,
0
] | [] | [] | [
"arraylist",
"arrays",
"django",
"json",
"python"
] | stackoverflow_0071979765_arraylist_arrays_django_json_python.txt |
Q:
Create a DataFrame with data from a class
I want to create a DataFrame to which I want to import data from a class. I mean, I type t1 = Transaction("20221128", "C1", 14) and I want a DataFrame to show data like:
Column 1: Date
Column 2: Concept
Column 3: Amount
The code where I want to implement this is:
class T... | Create a DataFrame with data from a class | I want to create a DataFrame to which I want to import data from a class. I mean, I type t1 = Transaction("20221128", "C1", 14) and I want a DataFrame to show data like:
Column 1: Date
Column 2: Concept
Column 3: Amount
The code where I want to implement this is:
class Transactions:
num_of_transactions = 0
a... | [
"In order to create a new data frame, you have to provide the rows and the columns name.\nYou have to change the code as the following:\ndef DataFrame(self):\n df = pd.DataFrame(data=[[self.date, self.concept, self.amount]], columns=['Date','Concept','Amount'])\n\n",
"You can create a DataFrame from a list of ... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074659144_dataframe_pandas_python_python_3.x.txt |
Q:
how to connect an s3 bucket w/ airflow
I have an airflow task where I try and load a file into an s3 bucket. I have airflow running on a Ec2 instance. Im running AF version 2.4.3 I have done
pip install 'apache-airflow[amazon]'
I start up my AF server, log in and go to the Admin section to add a connection. I open... | how to connect an s3 bucket w/ airflow | I have an airflow task where I try and load a file into an s3 bucket. I have airflow running on a Ec2 instance. Im running AF version 2.4.3 I have done
pip install 'apache-airflow[amazon]'
I start up my AF server, log in and go to the Admin section to add a connection. I open a new connection and I dont have an option ... | [
"You need to define aws connection under \"Amazon Web Services Connection\"\nfor more details see here\n",
"You should define the connection within your DAG.\nYou should also use a secure settings.ini file to save your secrets, and then call those variables from your DAG.\nSee this answer for a complete guide: Ai... | [
1,
0
] | [] | [] | [
"airflow",
"amazon_s3",
"amazon_web_services",
"python"
] | stackoverflow_0074631434_airflow_amazon_s3_amazon_web_services_python.txt |
Q:
How can I define some initial values that are variable in formula
How can I define some initial values (that are variable)in formulas
I should write code to predict and also optimize prediction of data series
But it has many formulas as a gray box and in these formulas, I should define some initial values(as varia... | How can I define some initial values that are variable in formula | How can I define some initial values (that are variable)in formulas
I should write code to predict and also optimize prediction of data series
But it has many formulas as a gray box and in these formulas, I should define some initial values(as variables)
| [
"Default Arguments:\ndef student(firstname, lastname ='Mark', standard ='Fifth'):\n\n print(firstname, lastname, 'studies in', standard, 'Standard')\n\nWe need to keep the following points in mind while calling functions:\nIn the case of passing the keyword arguments, the order of arguments is important.\nThere ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074659988_python.txt |
Q:
Ignore first element with XPATH
I need to get only text from the following structure, however, ignoring the first element, which would be the <span>SIGNIFICADO: </span> tag
<p class="p1">
<span>SIGNIFICADO: </span>
<strong>
<a href="www.site.com">Text Link</a>
</strong>
Some text Some text Some text
</p>
... | Ignore first element with XPATH | I need to get only text from the following structure, however, ignoring the first element, which would be the <span>SIGNIFICADO: </span> tag
<p class="p1">
<span>SIGNIFICADO: </span>
<strong>
<a href="www.site.com">Text Link</a>
</strong>
Some text Some text Some text
</p>
Currently I do it like this: p1=driv... | [
"To omit text of and before the first element, you can use\n//p[@class=\"p1\"]//text()[preceding::*]\n\nThis selects all text nodes that have at least one preceding element(here: <span>. Disadvantage is that this also discards text between the <p> element and the <span> element.\n"
] | [
0
] | [] | [] | [
"python",
"xpath"
] | stackoverflow_0074656703_python_xpath.txt |
Q:
Convert a dictionary into a list by enumerating?
I have a list created from a csv file that is a dictionary within a list. I need to officially convert the list to a dictionary. I have a working solution below but what's wrong with it is that it labels each dictionary row sequentially sub[i], for example name[0] a... | Convert a dictionary into a list by enumerating? | I have a list created from a csv file that is a dictionary within a list. I need to officially convert the list to a dictionary. I have a working solution below but what's wrong with it is that it labels each dictionary row sequentially sub[i], for example name[0] and name[1]. I have searched around online and it seems... | [
"To convert a dictionary into a list by enumerating in Python, you can use the items() method to get a list of the key-value pairs in the dictionary, and then use a for loop to enumerate over the pairs and create a new list.\nHere is an example:\n# Define a dictionary\nmy_dict = {'apple': 1, 'banana': 2, 'cherry': ... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074659808_python_python_3.x.txt |
Q:
How do I crop a python array to maximum size with only non-zero values (largest non-zero rectangle)
I have a numpy array of pixel data, something like
0 0 0 0 0 0 0
0 1 3 4 6 1 0
0 2 3 5 2 1 0
0 1 0 0 1 0 0
0 0 0 0 0 0 0
I would like to get a new array which excludes any outer rows/columns with zeroes, so I just ... | How do I crop a python array to maximum size with only non-zero values (largest non-zero rectangle) | I have a numpy array of pixel data, something like
0 0 0 0 0 0 0
0 1 3 4 6 1 0
0 2 3 5 2 1 0
0 1 0 0 1 0 0
0 0 0 0 0 0 0
I would like to get a new array which excludes any outer rows/columns with zeroes, so I just end up with only the non-zero values (that works for any given array) i.e.
1 3 4 6 1
2 3 5 2 1
So far al... | [
"Welcome to StackOverflow!\nInput:\n[[ 0 0 0 ... 0 0 0]\n [ 0 0 0 ... 0 0 0]\n [ 0 0 1872 ... 1765 0 0]\n ...\n [ 0 0 1850 ... 1800 0 0]\n [ 0 0 0 ... 0 0 0]\n [ 0 0 0 ... 0 0 0]]\n\nInput array.npy\n0 0 0 0 0 0 0 0 0 0 0 0 0 ... | [
0
] | [
"If we go by your assumption that there likely won't be any zeros in the middle of the array, we can figure out if a row contains any zeros using any(axis=1) (or axis=0 for columns), and if a row contains all zeros using all\ndata = np.array([[0, 0, 0, 0, 0, 0, 0],\n [0, 1, 3, 4, 6, 1, 0],\n ... | [
-1
] | [
"numpy",
"numpy_ndarray",
"python",
"python_3.x"
] | stackoverflow_0074655756_numpy_numpy_ndarray_python_python_3.x.txt |
Q:
how to print month on calendar with list comprehension in python
basically need to print a calendar for a month using list comprehension.
cant figure out how to make this work, if anyone can help itd be greatly appreciated
not great with list comprehension so not sure where to even start with this
A:
You can use... | how to print month on calendar with list comprehension in python | basically need to print a calendar for a month using list comprehension.
cant figure out how to make this work, if anyone can help itd be greatly appreciated
not great with list comprehension so not sure where to even start with this
| [
"You can use the calendar library to display a calendar in a variety of formats\n>>> calendar.monthcalendar(2022, 12)\n[[0, 0, 0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9, 10, 11],\n [12, 13, 14, 15, 16, 17, 18],\n [19, 20, 21, 22, 23, 24, 25],\n [26, 27, 28, 29, 30, 31, 0]]\n\n>>> calendar.TextCalendar().prmonth(2022, 12)\n ... | [
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0074659961_list_comprehension_python.txt |
Q:
How to change the font of Axis label in Pyqtgraph
I have a custom font, I am able to set this font in title of the graph, I need help in setting the axis label font.(left, bottom axis labels)
I am able to set the font to the title of the graph like this
graphWidget = pyqtgraph.PlotWidget()
graph = graphWid... | How to change the font of Axis label in Pyqtgraph | I have a custom font, I am able to set this font in title of the graph, I need help in setting the axis label font.(left, bottom axis labels)
I am able to set the font to the title of the graph like this
graphWidget = pyqtgraph.PlotWidget()
graph = graphWidget.getPlotItem()
graph.titleLabel.item.setFont(fon... | [
"To set custom QFont to axis label, you have to setFont for label of each axis.\nHere is a short example, which changes font family to Times for title, bottom and left axis.\nimport sys\n\nimport pyqtgraph\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtWidgets import QApplication\n\napp = QApplication(sys.argv)\n\n# ... | [
0
] | [] | [] | [
"pyqt",
"pyqt5",
"pyqtgraph",
"pyside2",
"python"
] | stackoverflow_0074628737_pyqt_pyqt5_pyqtgraph_pyside2_python.txt |
Q:
Unable to list files in google drive using python
Not sure if this has to do with my code or something on the Google side, however I'm able to push files to drive, but for some reason I cannot list the file/folder metadata inside a folder. Here is the code I'm using:
SCOPES = ['https://www.googleapis.com/auth/dri... | Unable to list files in google drive using python | Not sure if this has to do with my code or something on the Google side, however I'm able to push files to drive, but for some reason I cannot list the file/folder metadata inside a folder. Here is the code I'm using:
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'creds.json'
credentials = ... | [
"I think you forgot .execute()\ntry:\n service = build('drive', 'v3', credentials=creds)\n\n # Call the Drive v3 API\n results = service.files().list(q=\"'\" + topFolderId + \"' in parents\",\n pageSize=10, fields=\"nextPageToken, files(id, name)\").execute()\n items = results.get('files', [])\n\... | [
1
] | [] | [] | [
"google_api",
"google_api_python_client",
"google_drive_api",
"python",
"python_3.x"
] | stackoverflow_0074659022_google_api_google_api_python_client_google_drive_api_python_python_3.x.txt |
Q:
How could I find specific texts in one column of another dataset? Python
I have 2 datasets. One contains a column of companies name, and another contains a column of headlines of news. So the aim I want to achieve is to find all the news whose headline contains one company in the other datasets.Basically the two ... | How could I find specific texts in one column of another dataset? Python | I have 2 datasets. One contains a column of companies name, and another contains a column of headlines of news. So the aim I want to achieve is to find all the news whose headline contains one company in the other datasets.Basically the two datasets are like this, and I wanna select the news with specific company name... | [
"If I understand correctly you should have 2 data sets with different columns, first, you need to loop through the dataset that contains the company name to search in the headline, then you could use obj. find(“search”) to find matches in both datasets.\nAlso if every query is stored in a CSV format you could use t... | [
0,
0
] | [] | [] | [
"dataset",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074659809_dataset_pandas_python_python_3.x.txt |
Q:
How to define custom check according to my rules and how to implement Django
I using Python 3.10, Django 4.1.2, djangorestframework==3.14.0 (front separately)
In an order, the products received field is empty by default. As we receive the order, we must remove these elements from the ordered field and transfer the... | How to define custom check according to my rules and how to implement Django | I using Python 3.10, Django 4.1.2, djangorestframework==3.14.0 (front separately)
In an order, the products received field is empty by default. As we receive the order, we must remove these elements from the ordered field and transfer them to the received ones.
received products must contain only products from request... | [
"I will not write the complete code, but you can try this logic -\nDefine a Create method for the viewset or views (whatever you use)\ndef create(self, request, format=None):\n request.data is the data that you receive\n all_product_recieved = all products that you have received\n recived_products = all_pr... | [
1
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"python"
] | stackoverflow_0074657076_django_django_models_django_rest_framework_python.txt |
Q:
Terminal can't find version of python despite it being installed
I'm trying to install packages on multiple versions of Python. I'm currently running 3.8.8, and 3.11.0.
Following this post Install a module using pip for specific python version
called
python3.11 -m pip install pandas
which results in
File "<stdin>"... | Terminal can't find version of python despite it being installed | I'm trying to install packages on multiple versions of Python. I'm currently running 3.8.8, and 3.11.0.
Following this post Install a module using pip for specific python version
called
python3.11 -m pip install pandas
which results in
File "<stdin>", line 1 python3.11 -m pip install pandas SyntaxError: invalid syntax ... | [
"If you’re using Linux try just\npython3 —-version\n\nIn Windows you may need to add path to folder with installed Python to PATH variable.\n"
] | [
0
] | [
"Check your environment variables, you could try removing the variables pointing to the 3.8 version until you get the packages you want installed.\nYou could also try navigating to that python 3.11 installation directly, and executing the python shell from there, then run the command.\n"
] | [
-1
] | [
"module",
"python",
"version"
] | stackoverflow_0074660181_module_python_version.txt |
Q:
Use of int function in Python
This code is working fine but I am confused why I only have to change age into an integer and not months, weeks or days. If I simply add age = 25, then it does not give any error.
age = input("What is your current age? ")
Years_remaining = Years_remaining = (90 - int(age))
months = Y... | Use of int function in Python | This code is working fine but I am confused why I only have to change age into an integer and not months, weeks or days. If I simply add age = 25, then it does not give any error.
age = input("What is your current age? ")
Years_remaining = Years_remaining = (90 - int(age))
months = Years_remaining * 12
weeks = Years_... | [
"This is why:\nage is str as this is what the input method returns, therefore, you have to cast to int to subtract it to 90 and store it in Years_remaining.\nAt this point, Years_remaining is an int, so months does not need any cast as both of its operands are now int (Years_remaining and 12).\nIf for example, you ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074660044_python_python_3.x.txt |
Q:
How to get the ID of an element with class name with BS4
I have a site where there are multiple li elements whos ID I need but I only have the class name. I also need the IDs to be put into a list
The html:
<ul class="price-list">
<li class="price-box" id="200"></li>
<li class="price-box" id="300"></li>
<... | How to get the ID of an element with class name with BS4 | I have a site where there are multiple li elements whos ID I need but I only have the class name. I also need the IDs to be put into a list
The html:
<ul class="price-list">
<li class="price-box" id="200"></li>
<li class="price-box" id="300"></li>
<li class="price-box" id="400"></li>
</ul>
I have tried the f... | [] | [] | [
"import requests\nimport bs4\n\nresult = requests.get(\"url\")\nsoup = bs4.BeautifulSoup(result.text,\"html.parser\")\nclass_name = \"the class name\"\ndivs = soup.find_all(\"div\", {'class':class_name})\n# this will give you a list of divs with the class name\n# if you want to find the first div the soup find or y... | [
-1
] | [
"beautifulsoup",
"python",
"python_requests"
] | stackoverflow_0074660222_beautifulsoup_python_python_requests.txt |
Q:
How to create widgets based on lists in kivy?
does anyone knwo whether it is possible in kivy to create buttons based on list items.
I have a list of category names within a list, the amount of items can change based on the users previous input. So does anyone know whether, and how, it is possible to create button... | How to create widgets based on lists in kivy? | does anyone knwo whether it is possible in kivy to create buttons based on list items.
I have a list of category names within a list, the amount of items can change based on the users previous input. So does anyone know whether, and how, it is possible to create buttons dynamically, and maybe also link these buttons to... | [
"that is an very general question. here is an idea to get you started. A widget is needed that can hold the buttons and you also can bind each button in advance to a specific function using partial\nfrom functools import partial\ndef switch_page(self, _this_button, course: str = \"\") -> None:\n print(f\"Set {... | [
0
] | [] | [] | [
"button",
"kivy",
"list",
"python"
] | stackoverflow_0074657481_button_kivy_list_python.txt |
Q:
Python. View the "import" name of a library
Some Python libraries are listed under one name in pip, but imported under a different name in the interpreter.
pycroptodome is a good example. In pip list, you see "pycryptodome". In a Python program, you have to call "import Crypto". "import pycryptodome" gives an erro... | Python. View the "import" name of a library | Some Python libraries are listed under one name in pip, but imported under a different name in the interpreter.
pycroptodome is a good example. In pip list, you see "pycryptodome". In a Python program, you have to call "import Crypto". "import pycryptodome" gives an error that the module doesn't exist.
Some libraries I... | [
"Usually in /lib/site-packages in your Python folder. (At least, on Windows.) You can use sys. path to find out what directories are searched for modules.\nIn the standard Python interpreter, you can type \" help('modules') \". At the command-line, you can use pydoc modules . In a script, call pkgutil. iter_modules... | [
0,
0
] | [
"go https://pypi.org/project/pycryptodome\ndownload the tar file version you downloaded using pip and see the top-level view to see import names\n"
] | [
-1
] | [
"pip",
"python"
] | stackoverflow_0074659686_pip_python.txt |
Q:
I want to filter a dataframe that contains all the days of year 2021 and 2022 such that I only have the data that belongs to 2021?
enter image description here
I only want to print only the data for 2021
A:
can you try this:
df['time'] = pd.to_datetime(df['time'])
df = df[df['time'].dt.year == 2021]
| I want to filter a dataframe that contains all the days of year 2021 and 2022 such that I only have the data that belongs to 2021? | enter image description here
I only want to print only the data for 2021
| [
"can you try this:\ndf['time'] = pd.to_datetime(df['time'])\ndf = df[df['time'].dt.year == 2021]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074660177_dataframe_pandas_python.txt |
Q:
Why is my api response not inserted into postgres
dictionary = testEns(idSession)
columns = dictionary.keys()
for i in dictionary.values():
sql2='''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i)
cursor.execute(sql2)
The function testEns(idSession) contains th... | Why is my api response not inserted into postgres | dictionary = testEns(idSession)
columns = dictionary.keys()
for i in dictionary.values():
sql2='''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i)
cursor.execute(sql2)
The function testEns(idSession) contains the result of an api call that returns an xml response th... | [
"Your SQL statement looks off, I think you want something like:\nsql2='''insert into PERSONS (person_id , person_name) VALUES (%s, %s);'''\ncursor.execute(sql2, (i.person_id, i.person_name))\n\nAssuming the property names in i here.\n"
] | [
0
] | [
"Your line\nsql2 = '''insert into PERSONS(person_id , person_name) VALUES{};'''.format(i)\n\nShould be fixed\nsql2 = '''INSERT INTO PERSONS (person_id, person_name) VALUES (value1, value2, ...)'''.format(i)\n\n"
] | [
-1
] | [
"postgresql",
"python"
] | stackoverflow_0074660328_postgresql_python.txt |
Q:
Unable to install the jupyter module with pip
I would like to be able to install the python module jupyter with pip but I get an error in my terminal when I try 'pip install jupyter' which returns this:
`
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ e... | Unable to install the jupyter module with pip | I would like to be able to install the python module jupyter with pip but I get an error in my terminal when I try 'pip install jupyter' which returns this:
`
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [9 lines of output]
C:\User... | [
"Try pip install jupyterlab.\nRefer for more info: https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html\nI also see that you are having an error: Microsoft Visual C++ 14.0 or greater is required\nYou can also try installing/upgrading Microsoft Visual C++\n",
"I still have the same error w... | [
0,
0
] | [] | [] | [
"jupyter",
"pip",
"python"
] | stackoverflow_0074659543_jupyter_pip_python.txt |
Q:
Receiving OSError: [Errno 8] Exec format error in app running in Docker Container
I have a React/Flask app running within a Docker container. There is no issue with me building the project using docker-compose, and running the app itself in the container. Where I am running into issues is a particular API route th... | Receiving OSError: [Errno 8] Exec format error in app running in Docker Container | I have a React/Flask app running within a Docker container. There is no issue with me building the project using docker-compose, and running the app itself in the container. Where I am running into issues is a particular API route that is supposed to fetch user profiles from the DB, encrypt the values in a text file, a... | [
"So thanks to David Maze's comment on this, I followed the lead that maybe the executable I wanted to run needed to be built within the Dockerfile. I destroyed my original container, added in a step to run the Makefile that generates the executable, and finally ran the program through the app running in the Docker ... | [
0
] | [] | [] | [
"docker",
"python"
] | stackoverflow_0074605372_docker_python.txt |
Q:
How we handle input validation on python
I am new to python. I am wondering how we handle input validation using try catch. I have the code below, would you provide some suggestion?
try:
validate_input(date, value, region)
raise IllegalArgumentError("Invalid input")
except IllegalArgumentError as err... | How we handle input validation on python | I am new to python. I am wondering how we handle input validation using try catch. I have the code below, would you provide some suggestion?
try:
validate_input(date, value, region)
raise IllegalArgumentError("Invalid input")
except IllegalArgumentError as error:
print("Invalid input occur:", err... | [
"Suggestions\n\nFirst of all, you cannot call a function before it being actually created.\nAlso, except is used to provide a set of code if the execution flow of code is interrupted with an error, so the raising of another error inside the except is illogical\nYou need to use a base exception to create a custom ex... | [
0
] | [] | [] | [
"python",
"try_catch",
"validation"
] | stackoverflow_0074659981_python_try_catch_validation.txt |
Q:
Is there a matplotlib function in Python for forcing all subplots inside different figures to have the same x and y axis length?
I'm testing out different way of displaying figures. I have one figure which is made up of 12 subplots split into two columns. Something like...
fig, ax = plt.subplots(6, 2, figsize= (20... | Is there a matplotlib function in Python for forcing all subplots inside different figures to have the same x and y axis length? | I'm testing out different way of displaying figures. I have one figure which is made up of 12 subplots split into two columns. Something like...
fig, ax = plt.subplots(6, 2, figsize= (20,26))
I have another code which splits the 12 subplots into 3 different figures based on categorical data. Something like
figA, ax = ... | [
"Answer turns out to be simple. Use a variable that can be scaled by the number of plots in the figure. So, a figure with more plots will have a higher figsize yet equal plot sizes. Something like...\nps = 5 #indicates plot size\nfigA, ax = plt.subplots(5, 1, figsize= (10, 5*ps))\nfigB, ax = plt.subplots(3, 1, figs... | [
0,
0
] | [] | [] | [
"figure",
"matplotlib",
"plot",
"python",
"subplot"
] | stackoverflow_0074382240_figure_matplotlib_plot_python_subplot.txt |
Q:
Lookoing to create a graph based off the average of two columns in my dataset
Ulitmately I am very new with Data Analysis and am in the middle of a project that is due very soon.
Of the data here:
enter image description here
I would like to have the Station areas grouped up, and the Time_Diff averaged out for eac... | Lookoing to create a graph based off the average of two columns in my dataset | Ulitmately I am very new with Data Analysis and am in the middle of a project that is due very soon.
Of the data here:
enter image description here
I would like to have the Station areas grouped up, and the Time_Diff averaged out for each area.
There are 35000+ entries in this dataset, hence why I want to group it up i... | [
"subset.groupby('Station Area')['Time_Diff'].mean()\n"
] | [
0
] | [] | [] | [
"data_analysis",
"dataset",
"graph",
"jupyter_notebook",
"python"
] | stackoverflow_0074659331_data_analysis_dataset_graph_jupyter_notebook_python.txt |
Q:
How do I replace every NaN value in every column by minimum value of that column in pandas?
I have a dataframe and I want to replace every NaN value in every column by min() of the column, how do I do that?
A:
To replace all NaN values in a dataframe with the minimum value of the respective column, you can use t... | How do I replace every NaN value in every column by minimum value of that column in pandas? | I have a dataframe and I want to replace every NaN value in every column by min() of the column, how do I do that?
| [
"To replace all NaN values in a dataframe with the minimum value of the respective column, you can use the pandas DataFrame.fillna() method in combination with the DataFrame.min() method.\nFor example, suppose you have a dataframe df with the following values:\n col1 col2\n0 NaN 1\n1 NaN 3\n2 ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074660412_dataframe_pandas_python.txt |
Q:
How to concatenate a series to a pandas dataframe in python?
I would like to iterate through a dataframe rows and concatenate that row to a different dataframe basically building up a different dataframe with some rows.
For example:
`IPCSection and IPCClass Dataframes
allcolumns = np.concatenate((IPCSection.colum... | How to concatenate a series to a pandas dataframe in python? | I would like to iterate through a dataframe rows and concatenate that row to a different dataframe basically building up a different dataframe with some rows.
For example:
`IPCSection and IPCClass Dataframes
allcolumns = np.concatenate((IPCSection.columns, IPCClass.columns), axis = 0)
finalpatentclasses = pd.DataFrame... | [
"The problem with the current implementation is that pd.concat is being called with axis=0 and ignore_index=True, resulting in the values from secrow and clrow being concatenated vertically and the original indices being ignored. This causes the values to be misaligned with the columns of the final dataframe, as sh... | [
0,
0
] | [] | [] | [
"dataframe",
"loops",
"python"
] | stackoverflow_0074659968_dataframe_loops_python.txt |
Q:
Error: type(Nonetype) has no len() attribute
I was trying to solve a problem on leetcode but I keep incurring in an error that I don’t understand
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
char = set()
longest ... | Error: type(Nonetype) has no len() attribute | I was trying to solve a problem on leetcode but I keep incurring in an error that I don’t understand
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
char = set()
longest = []
curr = []
for i in range(len(... | [
"As already mentioned in the comment problem When you set longest = max... it ceases to be a list by @mark-ransom already. I will purpose different way of solving this\n# lengthOfLongestSubstring\n# can be optimized to O(n) using sliding window technique\nclass Solution2(object):\n def lengthOfLongestSubstring(s... | [
0
] | [] | [] | [
"algorithm",
"python",
"python_3.x"
] | stackoverflow_0074660122_algorithm_python_python_3.x.txt |
Q:
How to set input time limit for user in game?
I was wondering how I can make a program with input of MAXIMUM 5 seconds(e.g he can send input after 2 seconds) in python I decided to do a SIMPLE game where you basically have to rewrite a word below 5 seconds. I know how to create input and make it wait EXACTLY 5 SEC... | How to set input time limit for user in game? | I was wondering how I can make a program with input of MAXIMUM 5 seconds(e.g he can send input after 2 seconds) in python I decided to do a SIMPLE game where you basically have to rewrite a word below 5 seconds. I know how to create input and make it wait EXACTLY 5 SECONDS, but what I want to achieve is to set maximum ... | [] | [] | [
"=======\nTo create a program with a maximum input time of 5 seconds in Python, you can use the time and select modules to implement a timeout for the input operation. The time module provides functions for working with time, such as measuring elapsed time, and the select module provides functions for waiting for i... | [
-1,
-1
] | [
"python",
"python_3.x"
] | stackoverflow_0074660327_python_python_3.x.txt |
Q:
Plotting GIF on Folium Map
I have a GIF of 24 seconds showing the temperature of -119.564209,38.503915,-114.060059,41.211203 region in the square (heat map) for 24 hrs. Is there a way I can plot this GIF on the Folium map (or any other interactive map in python) by giving the mentioned coordinates?
A:
Here's how... | Plotting GIF on Folium Map | I have a GIF of 24 seconds showing the temperature of -119.564209,38.503915,-114.060059,41.211203 region in the square (heat map) for 24 hrs. Is there a way I can plot this GIF on the Folium map (or any other interactive map in python) by giving the mentioned coordinates?
| [
"Here's how I solved it using folium.\nfrom folium import raster_layers\nm = folium.Map(location=[100, 100], zoom_start=2, tiles='OpenStreetMap')\n\nraster_layers.ImageOverlay('temp.gif',\n [[-119.564209,38.503915],[-114.060059,41.211203]],\n opacity=0.8,\n ).... | [
0
] | [] | [] | [
"folium",
"gis",
"python"
] | stackoverflow_0074657170_folium_gis_python.txt |
Q:
How to explicitly add role to a user in discord bot
I'm relatively new to programming and am trying to code a bot for a server I'm in. I'd ideally like to assign a user to a specific role based on them sending a message containing 'gm' or 'good morning'. Right now, the bot can read the message and send a reply. Bu... | How to explicitly add role to a user in discord bot | I'm relatively new to programming and am trying to code a bot for a server I'm in. I'd ideally like to assign a user to a specific role based on them sending a message containing 'gm' or 'good morning'. Right now, the bot can read the message and send a reply. But I'm a bit lost trying to figure out how to actually add... | [
"You need a role object, and to do that, you need a guild object, which you can get with message.author.guild.\nFrom this, you can get the Role object:\nrole = await message.author.guild.get_role(ROLE_ID)\n\nNote that you need to get the role ID yourself. The easiest method to do so is to go into Discord and enable... | [
0
] | [] | [] | [
"bots",
"discord",
"python"
] | stackoverflow_0074660454_bots_discord_python.txt |
Q:
pip install . creates only the dist-info not the package
I am trying to make a python package which I want to install using pip install . locally. The package name is listed in pip freeze but import <package> results in an error No module named <package>. Also the site-packages folder does only contain a dist-info... | pip install . creates only the dist-info not the package | I am trying to make a python package which I want to install using pip install . locally. The package name is listed in pip freeze but import <package> results in an error No module named <package>. Also the site-packages folder does only contain a dist-info folder. find_packages() is able to find packages. What am I m... | [
"Since the question has become quite popular, here are the diagnosis steps to go through when you're missing files after installation. Imagine having an example project with the following structure:\nroot\n├── spam\n│ ├── __init__.py\n│ ├── data.txt\n│ ├── eggs.py\n│ └── fizz\n│ ├── __init__.py\n│ ... | [
127,
1,
0,
0,
0
] | [] | [] | [
"package",
"pip",
"python",
"setup.py",
"setuptools"
] | stackoverflow_0050585246_package_pip_python_setup.py_setuptools.txt |
Q:
Update treemodel in real time PySide
How can I make it so when I click the Randomize button, for the selected treeview items, the treeview updates to show the changes to data, while maintaining the expanding items states and the users selection? Is this accomplished by subclasses the StandardItemModel or ProxyMode... | Update treemodel in real time PySide | How can I make it so when I click the Randomize button, for the selected treeview items, the treeview updates to show the changes to data, while maintaining the expanding items states and the users selection? Is this accomplished by subclasses the StandardItemModel or ProxyModel class? Help is much appreciated as I'm n... | [
"Your Team class should be a subclass of QStandardItem, which will be the top-level parent in the model. This class should create its own child items (as you are currently doing in the for-loop of populateModel), and its randomize method should directly reset the item-data of those children. This will ensure the ch... | [
0
] | [] | [] | [
"pyside",
"python",
"qstandarditemmodel"
] | stackoverflow_0074646878_pyside_python_qstandarditemmodel.txt |
Q:
Python: What does this error message mean and why are we getting it?
We are trying to create a new Excel file with nested data using Python code. Here is the code for reference:
`import glob
import pandas as pd
import re
import openpyxl
dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name ="Sheet1")
line_... | Python: What does this error message mean and why are we getting it? | We are trying to create a new Excel file with nested data using Python code. Here is the code for reference:
`import glob
import pandas as pd
import re
import openpyxl
dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name ="Sheet1")
line_numbers = [4, 7]
print("Heey, we read")
dp_max = dp.groupby(['Subject', '... | [
"The error message indicates that an exception occurred while trying to read an Excel file using the pd.read_excel function. The most likely cause of the error is that the file \"UnpredictableDataMerge.xlsx\" was not found in the current working directory.\nYou can check the current working directory by running the... | [
0,
0
] | [] | [] | [
"data_analysis",
"database",
"excel",
"output",
"python"
] | stackoverflow_0074659693_data_analysis_database_excel_output_python.txt |
Q:
TypeError: 'NoneType' object is not iterable in Python
What does TypeError: 'NoneType' object is not iterable mean? Example:
for row in data: # Gives TypeError!
print(row)
A:
It means the value of data is None.
A:
Explanation of error: 'NoneType' object is not iterable
In python2, NoneType is the type of ... | TypeError: 'NoneType' object is not iterable in Python | What does TypeError: 'NoneType' object is not iterable mean? Example:
for row in data: # Gives TypeError!
print(row)
| [
"It means the value of data is None.\n",
"Explanation of error: 'NoneType' object is not iterable\nIn python2, NoneType is the type of None. In Python3 NoneType is the class of None, for example:\n>>> print(type(None)) #Python2\n<type 'NoneType'> #In Python2 the type of None is the 'NoneType' type.\n... | [
261,
114,
63,
20,
8,
7,
2,
1,
0,
0,
0,
0
] | [
"Just continue the loop when you get None Exception,\nexample:\n a = None\n if a is None:\n continue\n else:\n print(\"do something\")\n\nThis can be any iterable coming from DB or an excel file.\n"
] | [
-3
] | [
"nonetype",
"python"
] | stackoverflow_0003887381_nonetype_python.txt |
Q:
how to remove buttons off of a message discord
@client.command()
async def test(ctx):
message = await ctx.send("**TEST**\n**IS THIS WORKING?**")
await asyncio.sleep(3)
button = Button(style = discord.ButtonStyle.green, emoji = "◀", custom_id = "button")
view = View()
view.add_item(button)
async def button_callbac... | how to remove buttons off of a message discord | @client.command()
async def test(ctx):
message = await ctx.send("**TEST**\n**IS THIS WORKING?**")
await asyncio.sleep(3)
button = Button(style = discord.ButtonStyle.green, emoji = "◀", custom_id = "button")
view = View()
view.add_item(button)
async def button_callback(interaction):
await message.edit(content="**ed... | [
"Make sure you set view=None when you edit your message (or if you only want a few buttons removed, create a new view without those buttons and set view to that).\n"
] | [
0
] | [] | [] | [
"discord",
"pycord",
"python"
] | stackoverflow_0074612394_discord_pycord_python.txt |
Q:
In Python why is my "for entry in csv_compare:" loop iterating only once and getting stuck on the last input
I'm trying to compare 2 csv files and then put the common entries in a 3rd csv to write to file. For some reason it iterates the whole loop for row in csv_input but the entry in csv_compare loop iterates on... | In Python why is my "for entry in csv_compare:" loop iterating only once and getting stuck on the last input | I'm trying to compare 2 csv files and then put the common entries in a 3rd csv to write to file. For some reason it iterates the whole loop for row in csv_input but the entry in csv_compare loop iterates only once and stops on the last entry. I want to compare every row entry with every entry entry.
import csv
finalCSV... | [
"When you break the inner loop and start the next iteration of the outer loop, csv_compare doesn't reset to the beginning. It picks up where you left off. Once you have exhausted the iterator, that's it.\nYou would need to reset the iterator at the top of each iteration of the outer loop, which is most easily done ... | [
1,
0,
0
] | [] | [] | [
"csv",
"for_loop",
"python"
] | stackoverflow_0074660417_csv_for_loop_python.txt |
Q:
How can I return a list
I wanted to do a discord command scraper in python for the raffles available on https://releases.footshop.com/ and I almost finished it but when I wan to return a list of size (and stock also) it's return an error "IndexError: list index out of range" and I can't find what to do :/
thank fo... | How can I return a list | I wanted to do a discord command scraper in python for the raffles available on https://releases.footshop.com/ and I almost finished it but when I wan to return a list of size (and stock also) it's return an error "IndexError: list index out of range" and I can't find what to do :/
thank for your help guys !
I try this... | [
"len(size1) returns the length of the list, not the index of the last item. To loop through a list using len and index access, you need to compare it to len(size1) - 1 or just use count < len(size1).\n"
] | [
0
] | [] | [] | [
"discord",
"list",
"python"
] | stackoverflow_0074605388_discord_list_python.txt |
Q:
How to use `ListCtrl` on wxpython
How can I append row and it's corresponding data into ListCtrl.
I've just finished how to use TreeCtrl(Relatively easier than ListCtrl), it shows me a clear usage of matching single GUI object and data. But ListCtrl dose not.
How can I append or insert single row with it's corres... | How to use `ListCtrl` on wxpython | How can I append row and it's corresponding data into ListCtrl.
I've just finished how to use TreeCtrl(Relatively easier than ListCtrl), it shows me a clear usage of matching single GUI object and data. But ListCtrl dose not.
How can I append or insert single row with it's corresponding data.
How can I access row and ... | [
"I know that wxPython docs are retarded and gives no much help, here is some quick tips below,\ni added explanations in comments:\n# create new list control\nlistctrl = wx.dataview.DataViewListCtrl( my_panel, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.dataview.DV_SINGLE )\n\n# setup listctrl columns\nlistctr... | [
1,
0
] | [] | [] | [
"listctrl",
"python",
"wxpython"
] | stackoverflow_0055789154_listctrl_python_wxpython.txt |
Q:
assistance needed please, float is not iterable issues
`
life_max = -5
life_min = 999
country_max = ""
country_min = ""
answer = int(input("Which year would you like to enter? "))
with open ("life.csv") as f:
next(f)
for line in f:
parts = line.split(",")
life = float(parts[3])
... | assistance needed please, float is not iterable issues | `
life_max = -5
life_min = 999
country_max = ""
country_min = ""
answer = int(input("Which year would you like to enter? "))
with open ("life.csv") as f:
next(f)
for line in f:
parts = line.split(",")
life = float(parts[3])
year = int(parts[2])
country = parts[0].strip(... | [] | [] | [
"sum needs a list of values to add to each other ;)\n",
"A bit confusing answering this without your input and what line throws the error, but I'm guessing it's due to the 'sum(life)' - life seems to be a float while sum expects an iterable\n"
] | [
-2,
-2
] | [
"python",
"python_3.x"
] | stackoverflow_0074660613_python_python_3.x.txt |
Q:
Python, replace a word in a string from a list and iterate over it
I have a simple string and a list:
string = "the secret key is A"
list = ["123","234","345"]
I need to replace one item ("A") combining that item with another item from the list ("A123") as many times as the number of items in the list. Basically ... | Python, replace a word in a string from a list and iterate over it | I have a simple string and a list:
string = "the secret key is A"
list = ["123","234","345"]
I need to replace one item ("A") combining that item with another item from the list ("A123") as many times as the number of items in the list. Basically the result I would like to achieve is:
"the secret key is A123"
"the sec... | [
"Please don't clobber reserved keywords.\ns = \"the secret key is A\"\nlst = [\"123\",\"234\",\"345\"]\n\nitem = 'A'\nnewlst = [s.replace(item, f'{item}{tok}') for tok in lst]\n\n>>> newlst\n['the secret key is A123', 'the secret key is A234', 'the secret key is A345']\n\nEdit\nAs rightly noted by @JohnnyMopp, the ... | [
1,
0,
0
] | [] | [] | [
"list",
"python",
"replace"
] | stackoverflow_0074660234_list_python_replace.txt |
Q:
Buttons don't do their intended command at click
Im making a turtle race game, its a game where there are a few turtles who are assigned random speeds and then one turtle wins. However, just for fun im trying to add a few things to the game. For example, a button to exit the game and a button to restart the race. ... | Buttons don't do their intended command at click | Im making a turtle race game, its a game where there are a few turtles who are assigned random speeds and then one turtle wins. However, just for fun im trying to add a few things to the game. For example, a button to exit the game and a button to restart the race. I have made only the exit button for now, and gave the... | [
"What's happing is that your application is getting \"hung up\" on the long-running movement loop. Tkinter is registering your button press, but it can't do anything about it until it's done with the for loop. A quick solution to this is to define a function that handles the movements, and uses tkinter.after() to c... | [
1,
0
] | [] | [] | [
"python",
"python_turtle",
"tkinter"
] | stackoverflow_0074646592_python_python_turtle_tkinter.txt |
Q:
How to put a dictionary in a JSON?
I'm working with a REST API, and I need to return a JSON with my values to it. However, I need the items of the payload variable to show all the items inside the cart_item.
I have this:
payload = {
"items": [],
}
I tried this, but I don't know how I would put this inside t... | How to put a dictionary in a JSON? | I'm working with a REST API, and I need to return a JSON with my values to it. However, I need the items of the payload variable to show all the items inside the cart_item.
I have this:
payload = {
"items": [],
}
I tried this, but I don't know how I would put this inside the items of the payload:
for cart_item i... | [
"Instead of trying to create one item at a time, just populate payload['items'] directly, using a comprehension:\npayload['items'] = [\n {\n 'reference_id': cart_item.sku,\n 'name': cart_item.product.name,\n 'quantity': cart_item.quantity,\n 'unit_amount': cart_item.product.price \n ... | [
1,
0
] | [] | [] | [
"django_rest_framework",
"json",
"python",
"python_requests",
"rest"
] | stackoverflow_0074660579_django_rest_framework_json_python_python_requests_rest.txt |
Q:
Change dates to quarters in JSON file Python
I'm trying to convert the dates inside a JSON file to their respective quarter and year. My JSON file is formatted below:
{
"lastDate": {
"0": "11/22/2022",
"1": "10/28/2022",
"2": "10/17/2022",
"7": "07/03/2022",
"8": "07/03/... | Change dates to quarters in JSON file Python | I'm trying to convert the dates inside a JSON file to their respective quarter and year. My JSON file is formatted below:
{
"lastDate": {
"0": "11/22/2022",
"1": "10/28/2022",
"2": "10/17/2022",
"7": "07/03/2022",
"8": "07/03/2022",
"9": "06/03/2022",
"18": "0... | [
"You can use this bit of code instead:\nimport json\nimport pandas as pd\n\ndata = json.load(open(\"date_to_quarters.json\"))\n\n# convert json to df\ndf = pd.DataFrame.from_dict(data, orient=\"columns\")\n\n# convert last date to quarter\ndf['lastDate'] = pd.to_datetime(df['lastDate'])\ndf['lastDate'] = df['lastDa... | [
1,
1
] | [] | [] | [
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074660556_dataframe_json_pandas_python.txt |
Q:
How to use Gradio interface to auto submit the audio when recording is done?
I am using the following Gradio sample code to transcribe my audio:
from transformers import pipeline
p = pipeline("automatic-speech-recognition")
import gradio as gr
def transcribe(audio):
text = p(audio)["text"]
return text
g... | How to use Gradio interface to auto submit the audio when recording is done? | I am using the following Gradio sample code to transcribe my audio:
from transformers import pipeline
p = pipeline("automatic-speech-recognition")
import gradio as gr
def transcribe(audio):
text = p(audio)["text"]
return text
gr.Interface(
fn=transcribe,
inputs=gr.Audio(source="microphone", type="fi... | [
"You can use auto-submit something like this should work\n#auto submit after 5 seconds\ngr.Interface(\n fn=transcribe,\n inputs=gr.Audio(source=\"microphone\", type=\"filepath\"),\n outputs=\"text\",\n auto_submit=True,\n auto_submit_duration=5).launch()\n\n",
"I found the solution. I am putting it... | [
0,
0
] | [] | [] | [
"gradio",
"python"
] | stackoverflow_0074660611_gradio_python.txt |
Q:
Find if words from one sentence are found in corresponding row of another column also containing sentences (Pandas)
I have dataframe that looks like this:
email account_name
0 NaN weichert, realtors mnsota
1 jhawkins sterling group com ... | Find if words from one sentence are found in corresponding row of another column also containing sentences (Pandas) | I have dataframe that looks like this:
email account_name
0 NaN weichert, realtors mnsota
1 jhawkins sterling group com sterling group
2 lbaltz baltzchevy com baltz chevrolet
and I have this code that works as a sol... | [
"This solves your query.\nimport pandas as pd\n\ndf = pd.DataFrame({'email': ['', 'jhawkins sterling group com', 'lbaltz baltzchevy com'], 'name': ['John', 'sterling group', 'Linda']})\n\nfor index, row in df.iterrows():\n matches = sum([1 for x in row['email'].split() if x in row['name'].split()])\n df.loc[i... | [
2,
2
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074660484_group_by_pandas_python.txt |
Q:
How can I compare one column of a dataframe to multiple other columns using SequenceMatcher?
I have a dataframe with 6 columns, the first two are an id and a name column, the remaining 4 are potential matches for the name column.
id name match1 match2 match3 match4
id name... | How can I compare one column of a dataframe to multiple other columns using SequenceMatcher? | I have a dataframe with 6 columns, the first two are an id and a name column, the remaining 4 are potential matches for the name column.
id name match1 match2 match3 match4
id name match1 match2 ... | [
"I ended up solving this using the second idea of reformatting the table. Using the melt function I was able to get a two column table of the name field with each possible match. From there I used the original lambda function to compare the two columns and output a ratio. From there it was relatively easy to go thr... | [
0
] | [] | [] | [
"pandas",
"python",
"sequencematcher"
] | stackoverflow_0074637083_pandas_python_sequencematcher.txt |
Q:
Determine if Two Strings Are Close
i am trying to make a program that compares word1 strings with word2 string to occur only once
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
word1 = [x.strip() for x in word1]
word2 = [x.strip() for x in word2]
update = False
... | Determine if Two Strings Are Close | i am trying to make a program that compares word1 strings with word2 string to occur only once
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
word1 = [x.strip() for x in word1]
word2 = [x.strip() for x in word2]
update = False
for x in word1:
if(x... | [
"\nprint(Solution.closeStrings(Solution,word1='a',word2='aa'))\nYou create a class in order to be able to create an instance of it. That way you don't need to pass Solution as the self parameter.\n\nword1 = [x.strip() for x in word1]\nIt looks like you expect to remove spaces. But you'll get a list of strings with ... | [
1,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074660641_list_python_python_3.x.txt |
Q:
Error while working on the site in Django
This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up:
C:\Program Files\Python36\lib\site-packag... | Error while working on the site in Django | This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up:
C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning... | [
"The error lies in your urls file\napp_name is passed as an arg instead of a kwarg\n url(r'^blog/', include('blog.urls',\n namespace='blog',\n app_name='blog')), \n\nThis should fix the issue\n url(r'^blog/', include('blog.urls', \"blog\", namespace='blog... | [
1,
0
] | [] | [] | [
"django",
"django_templates",
"python",
"python_3.x",
"web"
] | stackoverflow_0074645823_django_django_templates_python_python_3.x_web.txt |
Q:
Neo4j Python Driver Using Unwind with a list of dictionaries
I'm trying to batch merge to create multiple nodes. Using the below code,
def test_batches(tx,user_batch):
result= tx.run(f"Unwind {user_batch} as user\
MERGE (n:User {{id: user.id, name: user.name, username: user.u... | Neo4j Python Driver Using Unwind with a list of dictionaries | I'm trying to batch merge to create multiple nodes. Using the below code,
def test_batches(tx,user_batch):
result= tx.run(f"Unwind {user_batch} as user\
MERGE (n:User {{id: user.id, name: user.name, username: user.username }})")
However I am getting this error.
Note I'm passing i... | [
"Below is a working code on using UNWIND for a list of dictionaries. Please note that is it recommended to pass the value as a parameter rather than working on the value string in query.\nfrom neo4j import GraphDatabase\n\nuri = \"neo4j://localhost:7687\"\ndriver = GraphDatabase.driver(uri, auth=(\"neo4j\", \"awes... | [
1,
0
] | [] | [] | [
"neo4j",
"neo4j_python_driver",
"python"
] | stackoverflow_0074659436_neo4j_neo4j_python_driver_python.txt |
Q:
How to get reference table fields with django model query
When I am trying to fetch foreign key table using django model I am only unable to get the referenced table details.
I have two models TblVersion and TblProject defined below
class TblVersion(models.Model):
version_id = models.AutoField(primary_key=True... | How to get reference table fields with django model query | When I am trying to fetch foreign key table using django model I am only unable to get the referenced table details.
I have two models TblVersion and TblProject defined below
class TblVersion(models.Model):
version_id = models.AutoField(primary_key=True)
project = models.ForeignKey(TblProject, models.DO_NOTHING... | [
"select_related method accepts an arg of fields that relates to an other model\nresult= TblVersion.objects.all().select_related(\"product\")\nUpdate\nTo add those related field to be serializable u can list the values as\nresult = TblVersion.objects.all().select_related(\"product\").values(\"id\", \"version_id\", .... | [
0
] | [] | [] | [
"django",
"django_models",
"django_orm",
"django_views",
"python"
] | stackoverflow_0074660813_django_django_models_django_orm_django_views_python.txt |
Q:
Mock class in Python with decorator patch
I would like to patch a class in Python in unit testing. The main code is this (mymath.py):
class MyMath:
def my_add(self, a, b):
return a + b
def add_three_and_two():
my_math = MyMath()
return my_math.my_add(3, 2)
The test class is this:
import unitt... | Mock class in Python with decorator patch | I would like to patch a class in Python in unit testing. The main code is this (mymath.py):
class MyMath:
def my_add(self, a, b):
return a + b
def add_three_and_two():
my_math = MyMath()
return my_math.my_add(3, 2)
The test class is this:
import unittest
from unittest.mock import patch
import mym... | [
"Your code is almost there, some small changes and you'll be okay:\n\nmy_add should be a class method since self does not really play a role here.\nIf my_add is an instance method, then it will be harder to trace the calls, since your test will track the instance signature, not the class sig\nSince you are are patc... | [
2,
0
] | [] | [] | [
"python",
"python_unittest",
"python_unittest.mock"
] | stackoverflow_0074525368_python_python_unittest_python_unittest.mock.txt |
Q:
How to use AWS Sagemaker with newer version of Huggingface Estimator?
When trying to use Huggingface estimator on sagemaker, Run training on Amazon SageMaker e.g.
# create the Estimator
huggingface_estimator = HuggingFace(
entry_point='train.py',
source_dir='./scripts',
instance_type='ml.p3... | How to use AWS Sagemaker with newer version of Huggingface Estimator? | When trying to use Huggingface estimator on sagemaker, Run training on Amazon SageMaker e.g.
# create the Estimator
huggingface_estimator = HuggingFace(
entry_point='train.py',
source_dir='./scripts',
instance_type='ml.p3.2xlarge',
instance_count=1,
role=role,
transformer... | [
"You can use the Pytorch estimator and in your source directory place a requirements.txt with Transformers added to it. This will ensure 2 things\n\nYou can use higher version of pytorch 1.12 (current) compared to 1.10.2 in the huggingface estimator.\nInstall new version of HuggingFace Transformers library.\n\nTo a... | [
2,
2,
0,
0
] | [] | [] | [
"amazon_sagemaker",
"docker",
"huggingface",
"python",
"pytorch"
] | stackoverflow_0074548143_amazon_sagemaker_docker_huggingface_python_pytorch.txt |
Q:
Input from user to print out a certain instance variable in python
I have created a class with programs:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewer... | Input from user to print out a certain instance variable in python | I have created a class with programs:
class Program:
def __init__(self,channel,start, end, name, viewers, percentage):
self.channel = channel
self.start = start
self.end = end
self.name = name
self.viewers = viewers
Channel 1, start:16.00 end:17.45 viewers: 100 name: Matine... | [
"\nI wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)\n\nWell if all your programs have a unique name then the easiest approach would probably be to store them in a dictionary instead of a... | [
1
] | [] | [] | [
"class",
"input",
"list",
"python",
"try_except"
] | stackoverflow_0074660715_class_input_list_python_try_except.txt |
Q:
I'm looking forward to install the hunspell package using pip, but it throws the following error:
Collecting hunspell
Using cached hunspell-0.5.5.tar.gz (34 kB)
Building wheels for collected packages: hunspell
Building wheel for hunspell (setup.py) ... error
ERROR: Command errored out with exit status 1:
command: ... | I'm looking forward to install the hunspell package using pip, but it throws the following error: | Collecting hunspell
Using cached hunspell-0.5.5.tar.gz (34 kB)
Building wheels for collected packages: hunspell
Building wheel for hunspell (setup.py) ... error
ERROR: Command errored out with exit status 1:
command: 'C:\Users\shikhar\AppData\Local\Programs\Python\Python310\python.exe' -u -c 'import io, os, sys, setupt... | [
"I tried an older version and successfully installed.\npip install hunspell==0.3.4\n\n",
"Collecting cyhunspell\nUsing cached CyHunspell-1.3.4.tar.gz (2.7 MB)\nPreparing metadata (setup.py) ... done\nRequirement already satisfied: cacheman>=2.0.6 in c:\\users\\abdul rehman\\appdata\\local\\programs\\python\\pytho... | [
0,
0
] | [] | [] | [
"hunspell",
"python"
] | stackoverflow_0071396413_hunspell_python.txt |
Q:
How to convert this pseudocode to code in python
I am new to coding and i can't figure out a way to convert this pseudocode to actual code in python especially the total number of dice part.
I want to calculate total number of green dice in a dice stack of different colours.
Y4 G6
R3 G2
W2 W1
where,
Y4 = yellow... | How to convert this pseudocode to code in python | I am new to coding and i can't figure out a way to convert this pseudocode to actual code in python especially the total number of dice part.
I want to calculate total number of green dice in a dice stack of different colours.
Y4 G6
R3 G2
W2 W1
where,
Y4 = yellow dice with face value 4
R3 = red dice with face value ... | [
"Welcome to the community. I will help get you started and provide some references. To be honest however, when you post on here, you typically want to be as descriptive as possible. Don't be afraid to list the guidelines for your assignment or go into more exact detail on what problems you are having. I know it is ... | [
0
] | [
"I think you should not be asking someone to do your code.\nI will try to help Python version if you mean this\nclass Dice(object):\n\n def __init__(self, dice_list):\n self.dice_list = dice_list\n\n def score(self):\n total_number_of_dice = 0\n for dice in self.dice_list:\n to... | [
-2
] | [
"algorithm",
"dice",
"pseudocode",
"python",
"python_3.x"
] | stackoverflow_0074660492_algorithm_dice_pseudocode_python_python_3.x.txt |
Q:
How to create two columns of a dataframe from separate lines in a text file
I have a text file where every other row either begins with "A" or "B" like this
A810 WE WILDWOOD DR
B20220901BROOKE
A6223 AMHERST BAY
B20221001SARAI
How can I read the text file and create a two column pandas dataframe where the line be... | How to create two columns of a dataframe from separate lines in a text file | I have a text file where every other row either begins with "A" or "B" like this
A810 WE WILDWOOD DR
B20220901BROOKE
A6223 AMHERST BAY
B20221001SARAI
How can I read the text file and create a two column pandas dataframe where the line beginning with "A" is a column and likewise for the "B", on a single row. Like thi... | [
"You can approach this by using pandas.DataFrame.shift and pandas.DataFrame.join :\nfrom io import StringIO \nimport pandas as pd\n\ns = \"\"\"A810 WE WILDWOOD DR\nB20220901BROOKE\nA6223 AMHERST BAY\nB20221001SARAI\n\"\"\"\n\ndf = pd.read_csv(StringIO(s), header=None, names=[\"A\"])\n#in your case, df = pd.read_... | [
2,
1,
1
] | [] | [] | [
"pandas",
"python",
"text_files"
] | stackoverflow_0074660644_pandas_python_text_files.txt |
Q:
Pip subprocess error: No matching distribution found for matlabengineforpython==R2020b
So, I'm trying to import an environment.yml file from one windows laptop to a windows pc. I enter the following command (conda env create -f environment.yml), and get the following error (at the end of the code). The imports fai... | Pip subprocess error: No matching distribution found for matlabengineforpython==R2020b | So, I'm trying to import an environment.yml file from one windows laptop to a windows pc. I enter the following command (conda env create -f environment.yml), and get the following error (at the end of the code). The imports fail when they reach the matlabengine package. Not sure why this is. Any thoughts? Thanks.
C:\S... | [
"Have you looked at condaENVexception.\nTry updating conda and pip versions to latest.\n"
] | [
0
] | [] | [] | [
"anaconda",
"matlab",
"pip",
"python"
] | stackoverflow_0074660932_anaconda_matlab_pip_python.txt |
Q:
h2o frame from pandas casting
I am using h2o to perform predictive modeling from python.
I have loaded some data from a csv using pandas, specifying some column types:
dtype_dict = {'SIT_SSICCOMP':'object',
'SIT_CAPACC':'object',
'PTT_SSIRMPOL':'object',
'PTT_SPTCLVEI':'ob... | h2o frame from pandas casting | I am using h2o to perform predictive modeling from python.
I have loaded some data from a csv using pandas, specifying some column types:
dtype_dict = {'SIT_SSICCOMP':'object',
'SIT_CAPACC':'object',
'PTT_SSIRMPOL':'object',
'PTT_SPTCLVEI':'object',
'cap_pad':'obj... | [
"Yes, there is. See the H2OFrame doc here: http://docs.h2o.ai/h2o/latest-stable/h2o-py/docs/frame.html#h2oframe\nYou just need to use the column_types argument when you cast.\nHere's a short example:\n# imports\nimport h2o\nimport numpy as np\nimport pandas as pd\n\n# create small random pandas df\ndf = pd.DataFram... | [
3,
0
] | [] | [] | [
"casting",
"h2o",
"pandas",
"python"
] | stackoverflow_0049823178_casting_h2o_pandas_python.txt |
Q:
How do I write the __init__ to assign 1 to the __value data attibute for the dice game?
Write a class named Die that simulates rolling dice. The Die class
should have one private data attribute named __value. It should
also have the following methods:
__init__ : The __init__ method should assign 1 to the __valu... | How do I write the __init__ to assign 1 to the __value data attibute for the dice game? |
Write a class named Die that simulates rolling dice. The Die class
should have one private data attribute named __value. It should
also have the following methods:
__init__ : The __init__ method should assign 1 to the __value
data attribute.
roll: The roll method should set the __value
data attribute to a random nu... | [] | [] | [
"As you created number variable using self.number,you can create value with self.__value.\nLike this: self.__value = randint(1,6).\nBe aware that you can create it outside of the __init__ method. But if you do that, the variable will be linked to the class instead of instances (so multiple call to new dice will hav... | [
-1,
-1
] | [
"class",
"dice",
"python"
] | stackoverflow_0074660989_class_dice_python.txt |
Q:
How to generate a random group of result from a list
So, In a exercice of my school, 'cell' is a point that have his own coordinates x and y, in a previous question i had to generate a list of his neighbours and now I have to generate randomly his one of these neighbours and the result have to be in the form of (x... | How to generate a random group of result from a list | So, In a exercice of my school, 'cell' is a point that have his own coordinates x and y, in a previous question i had to generate a list of his neighbours and now I have to generate randomly his one of these neighbours and the result have to be in the form of (x,y) and only a single value.
import random
#Qst1
cell=(2,... | [
"Like @JohnnyMopp said, the function already returns a list of neighbors, so you can use random.choice() to select a random element of the list, like so:\ndef voisine_PI_alea(cell):\n return random.choice(voisines_PI(cell))\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074660869_python.txt |
Q:
GUIZERO: I want to use a pushbutton to save what's in a textbox to file. How do I do that?
I'm a super beginner with Python, so please be kind.
I am creating an app that should take in user input from text boxes, and then when the user presses the submit button this is saved in a text file.
I think the issue is th... | GUIZERO: I want to use a pushbutton to save what's in a textbox to file. How do I do that? | I'm a super beginner with Python, so please be kind.
I am creating an app that should take in user input from text boxes, and then when the user presses the submit button this is saved in a text file.
I think the issue is that I'm not quite sure how to create the right function for the pushbutton command.
I would reall... | [
"I figured it out. Thanks :)\n from guizero import *\nimport os\ncwd = os.getcwd()\n\n\n# function for writing files\ndef save_file():\n with open(cwd+'/Desktop/File handling/newfile.txt','a') as f:\n f.write(\"First name:\"+\" \"+first_name.value+\"\\n\")\n\n#the app\napp = App(\"testing\")\n\n\n#text... | [
0
] | [] | [] | [
"guizero",
"python",
"textbox"
] | stackoverflow_0074648037_guizero_python_textbox.txt |
Q:
Failed to install wsgiref on Python 3
I have a problem installing wsgiref:
$ python --version
Python 3.6.0 :: Anaconda 4.3.1 (x86_64)
$ pip --version
pip 9.0.1 from /anaconda/lib/python3.6/site-packages (python 3.6)
My requirement.txt file are shown as below.
numpy==1.8.1
scipy==0.14.0
pyzmq==14.3.1
pandas==0.14.... | Failed to install wsgiref on Python 3 | I have a problem installing wsgiref:
$ python --version
Python 3.6.0 :: Anaconda 4.3.1 (x86_64)
$ pip --version
pip 9.0.1 from /anaconda/lib/python3.6/site-packages (python 3.6)
My requirement.txt file are shown as below.
numpy==1.8.1
scipy==0.14.0
pyzmq==14.3.1
pandas==0.14.0
Jinja2==2.7.3
MarkupSafe==0.23
backports.... | [
"wsgiref is already been included as a standard library in Python 3...\nSo in case if you are trying with Python 3 just go ahead and import wsgiref thats it.\n",
"According to this line SyntaxError: Missing parentheses in call to 'print', I think it needs Python 2.x to run the setup.py. Whether to use parentheses... | [
30,
4,
0
] | [] | [] | [
"pip",
"python",
"python_3.x",
"wsgiref"
] | stackoverflow_0043026999_pip_python_python_3.x_wsgiref.txt |
Q:
Paraphrase generation
Can u please give some hint how can we create utterances for example
I have input say -
"I want my account details"
The output should be like
Can I get my account details
Please provide me my account details
Can I get my account information
A:
The problem you are describing here is cal... | Paraphrase generation | Can u please give some hint how can we create utterances for example
I have input say -
"I want my account details"
The output should be like
Can I get my account details
Please provide me my account details
Can I get my account information
| [
"The problem you are describing here is called paraphrasing: taking an input phrase and producing an output phrase with the same meaning. \nTo get the taste of it, you can try an online paraphraser, like https://quillbot.com/. \nAnd one way to create your own paraphraser (if you really really want it) is to get a p... | [
0,
0
] | [] | [] | [
"keras",
"machine_learning",
"nlp",
"nltk",
"python"
] | stackoverflow_0060712874_keras_machine_learning_nlp_nltk_python.txt |
Q:
How to Create a Pandas DataFrame from multiple list of dictionaries
I want to create a pandas dataframe using the two list of dictionaries below:
country_codes = [
{
"id": 92,
"name": "93",
"position": 1,
"description": "Afghanistan"
},
{
"id": 93,
"name"... | How to Create a Pandas DataFrame from multiple list of dictionaries | I want to create a pandas dataframe using the two list of dictionaries below:
country_codes = [
{
"id": 92,
"name": "93",
"position": 1,
"description": "Afghanistan"
},
{
"id": 93,
"name": "355",
"position": 2,
"description": "Albania"
},
... | [
"Use:\ndf = pd.DataFrame({'gender': pd.DataFrame(gender)['name'],\n 'country': pd.DataFrame(country_codes)['description']})\n\nOutput:\n gender country\n0 Female Afghanistan\n1 Male Albania\n2 NaN Algeria\n3 NaN American Samoa\n\n"
] | [
1
] | [] | [] | [
"django",
"pandas",
"python",
"xlsxwriter"
] | stackoverflow_0074660948_django_pandas_python_xlsxwriter.txt |
Q:
How to propagate the effect of model bias via MEAS update correctly to other variables in GEKKO
EDIT: I am just checking if the issue not on the condensate side.
I have a material balance optimisation problem that I have configured in GEKKO. I have reproduced my challenge on a smaller problem that I can share her... | How to propagate the effect of model bias via MEAS update correctly to other variables in GEKKO | EDIT: I am just checking if the issue not on the condensate side.
I have a material balance optimisation problem that I have configured in GEKKO. I have reproduced my challenge on a smaller problem that I can share here.
It pertains to the initial values for CV's that I have left undefined (defaulting to zero) during ... | [
"Gekko uses the unbiased model values to solve the equations. The BIAS is only applied to that specific CV as an output correction. A state estimation algorithm such as a Kalman filter or Moving Horizon Estimator (MHE) is required to adjust parameters or initial conditions to correct for the difference between meas... | [
0
] | [] | [] | [
"gekko",
"python"
] | stackoverflow_0074640886_gekko_python.txt |
Q:
drop table timing out using psycopg2 (on postgres)
I can't drop a table that has dependencies using psycopg2 in python because it times out. (updating to remove irrelevant info, thank you to @Adrian Klaver for the assistance so far).
I have two docker images, one running a postgres database, the other a python fla... | drop table timing out using psycopg2 (on postgres) | I can't drop a table that has dependencies using psycopg2 in python because it times out. (updating to remove irrelevant info, thank you to @Adrian Klaver for the assistance so far).
I have two docker images, one running a postgres database, the other a python flask application making use of multiple psycopg2 calls to ... | [
"The issue was with only including the psycopg2-binary==2.9.5 module in my requirements file... I needed to also include psycopg2==2.9.5\nI don't completely understand why, but this was the solution to the problem (I found this when deploying my docker image to AWS-ECS and seeing that my uwsgi process was crashing... | [
0
] | [] | [] | [
"flask",
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0074323783_flask_postgresql_psycopg2_python.txt |
Q:
Cloud Run with Gunicorn Best-Practise
I am currently working on a service that is supposed to provide an HTTP endpoint in Cloud Run and I don't have much experience. I am currently using flask + gunicorn and can also call the service. My main problem now is optimising for multiple simultaneous requests. Currently,... | Cloud Run with Gunicorn Best-Practise | I am currently working on a service that is supposed to provide an HTTP endpoint in Cloud Run and I don't have much experience. I am currently using flask + gunicorn and can also call the service. My main problem now is optimising for multiple simultaneous requests. Currently, the service in Cloud Run has 4GB of memory... | [
"One of the best practice is to let Cloud Run scale automatically instead of trying to optimize each instance. Using 1 worker is a good idea to limit the memory footprint and reduce the cold start.\nI recommend to play with the threads, typically to put it to 8 or 16 to leverage the concurrency parameter.\nIf you p... | [
0,
0
] | [] | [] | [
"google_cloud_run",
"gunicorn",
"python"
] | stackoverflow_0071378905_google_cloud_run_gunicorn_python.txt |
Q:
The video writer is not writing any video just an empty .mp4 file. Rest is working fine. What's the problem?
import cv2
import os
cam = cv2.VideoCapture(r"C:/Users/User/Desktop/aayfryxljh.mp4")
detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
result = cv2.VideoWriter('C:/Users/User/Desktop/... | The video writer is not writing any video just an empty .mp4 file. Rest is working fine. What's the problem? |
import cv2
import os
cam = cv2.VideoCapture(r"C:/Users/User/Desktop/aayfryxljh.mp4")
detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
result = cv2.VideoWriter('C:/Users/User/Desktop/new.mp4',cv2.VideoWriter_fourcc(*'mp4v'),30,(112,112))
while (True):
# reading from frame
ret, frame =... | [
"As I mentioned in the comments the while loop never finishes and so result.release() never gets called. It looks like the code needs a way to end the while loop. Perhaps:\nwhile (True):\n\n # reading from frame\n ret, frame = cam.read()\n\n ### ADDED CODE:\n if ret == False:\n break\n\n gray ... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074626256_opencv_python.txt |
Q:
Why does my file keep closing after the first loop in python
I'm trying to read through a large file in which I have marked the start and end lines of each segment. I'm extracting a component of each segment using regex.
What I don't understand is that after the first inner loop, my code seems to have closed the f... | Why does my file keep closing after the first loop in python | I'm trying to read through a large file in which I have marked the start and end lines of each segment. I'm extracting a component of each segment using regex.
What I don't understand is that after the first inner loop, my code seems to have closed the file and I don't get the desired output.
Simplified code below
with... | [
"Assuming your indentation is wrong in the description and not actually in your original code, readlines() moves the file pointer to the end so you can't read any more lines.\nYou need to either reopen the file or .seek(0).\nSee this for more info: Does fp.readlines() close a file?\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074661143_python.txt |
Q:
How to run Docker with python and Java?
I need both java and python in my docker container to run some code.
This is my dockerfile:
It works perpectly if I don't add the FROM openjdk:slim
#get python
FROM python:3.6-slim
RUN pip install --trusted-host pypi.python.org flask
#get openjdk
FROM openjdk:slim
COPY ... | How to run Docker with python and Java? | I need both java and python in my docker container to run some code.
This is my dockerfile:
It works perpectly if I don't add the FROM openjdk:slim
#get python
FROM python:3.6-slim
RUN pip install --trusted-host pypi.python.org flask
#get openjdk
FROM openjdk:slim
COPY . /targetdir
WORKDIR /targetdir
# Make port... | [
"An easier solution to the above issue is to use multi-stage docker containers where you can copy the content from one to another. In the above case you can have openjdk:slim as the base container and then use content from a python container to be copied over into this base container as follows:\nFROM openjdk:slim\... | [
34,
30,
6,
2,
2,
1,
1,
0,
0,
0
] | [
"Instead of using FROM openjdk:slim you can separately install Java, please refer below example:\n# Install OpenJDK-8\nRUN apt-get update && \\\napt-get install -y openjdk-8-jdk && \\\napt-get install -y ant && \\\napt-get clean;\n\n# Fix certificate issues\nRUN apt-get update && \\\napt-get install ca-certificates... | [
-1
] | [
"docker",
"java",
"python",
"python_3.x"
] | stackoverflow_0051121875_docker_java_python_python_3.x.txt |
Q:
How to connect to remote and run Python from local like in SQL DB Management tools
So if we want to run SQL in a remote server we can connect to it using JDBC connection strings. Is there something similar but for Python? I want to develop using my, already tuned, IDE instead of the clunky IDEs there are like Zepp... | How to connect to remote and run Python from local like in SQL DB Management tools | So if we want to run SQL in a remote server we can connect to it using JDBC connection strings. Is there something similar but for Python? I want to develop using my, already tuned, IDE instead of the clunky IDEs there are like Zeppelin for remote servers.
Do you know a secure way to achieve this? I know it's possible ... | [] | [] | [
"I'm not aware of a way to execute python on a remote instance without establishing an ssh (linux) or winrm/prsp (windows) session first. I do know of a powerful IDE that can accomplish this pretty smoothly though.\nPycharm Professional has the ability to establish an ssh session out to a target environment, allows... | [
-1
] | [
"pycharm",
"python",
"remote_server",
"visual_studio_code"
] | stackoverflow_0074660678_pycharm_python_remote_server_visual_studio_code.txt |
Q:
Quit function in python programming
I have tried to use the 'quit()' function in python and the spyder's compiler keep says me "quit" is not defined
print("Welcome to my computer quiz")
playing = input("Do you want to play? ")
if (playing != "yes" ):
quit()
print("Okay! Let's play :)")
the output keep ... | Quit function in python programming | I have tried to use the 'quit()' function in python and the spyder's compiler keep says me "quit" is not defined
print("Welcome to my computer quiz")
playing = input("Do you want to play? ")
if (playing != "yes" ):
quit()
print("Okay! Let's play :)")
the output keep says me "name 'quit' is not defined", how... | [
"There is no such thing as quit() in python. Python rather has exit(). Simply replace your quit() to exit().\nprint(\"Welcome to my computer quiz\")\n\nplaying = input(\"Do you want to play? \")\n\nif (playing != \"yes\" ):\n exit()\n \nprint(\"Okay! Let's play :)\")\n\n",
"Invert the logic and play if the ... | [
2,
0
] | [] | [] | [
"python",
"runtime_error"
] | stackoverflow_0074661123_python_runtime_error.txt |
Q:
Python write serial data to the second column of my .csv file
Im reading from my serialport data, I can store this data to .csv file. But the problem is that I want to write my data to a second or third column.
With code the data is stored in the first column:
file = open('test.csv', 'w', encoding="utf",newline=""... | Python write serial data to the second column of my .csv file | Im reading from my serialport data, I can store this data to .csv file. But the problem is that I want to write my data to a second or third column.
With code the data is stored in the first column:
file = open('test.csv', 'w', encoding="utf",newline="")
writer = csv.writer(file)
while True:
if serialInst.in_wait... | [
"I've not use the csv.writer before, but a quick read of the docs, seems to indicate that you can only write one row at a time, but you are getting data one cell/value at a time.\nIn your code example, you already have a file handle. Instead of writing one row at a time, you want to write one cell at a time. You'll... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074657545_python.txt |
Q:
Pandas JSON Normalize multiple columns in a dataframe
So I have the following dataframe:
The JSON blobs all look something like this:
{"id":"dddd1", "random_number":"77777"}
What I want my dataframe to look like is something like this:
Basically what I need is to get a way to iterate and normalize all the JSON ... | Pandas JSON Normalize multiple columns in a dataframe | So I have the following dataframe:
The JSON blobs all look something like this:
{"id":"dddd1", "random_number":"77777"}
What I want my dataframe to look like is something like this:
Basically what I need is to get a way to iterate and normalize all the JSON blob columns and put them back in the dataframe in the prop... | [
"Can you try this:\nnormalized = pd.concat([df[i].apply(pd.Series) for i in df.iloc[:,2:]],axis=1) #2 is the position number of JSON_0.\nfinal = pd.concat([df[['Root_id_PK','random_number']],normalized],axis=1)\n\nif you want the column names as in the question:\nnormalized = pd.concat([df[i].apply(pd.Series).renam... | [
1
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074660865_json_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.